title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
How to Use axis=0 and axis=1 in Pandas?
19 Dec, 2021 In this article, we will discuss how to use axis=0 and axis=1 in pandas using Python. Sometimes we need to do operations only on rows, and sometimes only on columns, in such situations, we specify the axis parameter. In this article, let’s see a few examples to know when and how to use the axis parameter. In pandas axis = 0 refers to horizontal axis or rows and axis = 1 refers to vertical axis or columns. When the axis is set to zero while performing a specific action, the action is performed on rows that satisfy the condition. Dataset Used: Example: Using axis=0 Python3 # importing packagesimport pandas as pd # importing our datasetdf = pd.read_csv('hiring.csv') # dropping the column named 'experience'df = df.drop([0, 3], axis=0) # 'viewing the dataframedf.head() Output: Example: Using axis=0 Python3 # importing packagesimport pandas as pd # creating a datasetdf = pd.DataFrame([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]], columns=['a', 'b', 'c']) # viewing the dataFrameprint(df) # finding mean by rowsdf.mean(axis='rows') Output: When the axis is set to one while performing a specific action, the action is performed on column(s) that satisfy the condition. Example: Using axis=1 Python3 # importing packagesimport pandas as pd # importing our datasetdf = pd.read_csv('hiring.csv') # dropping the column named 'experience'df = df.drop(['experience'], axis=1) # 'viewing the dataframedf.head() Output: Example: Using axis=1 Python3 # importing packagesimport pandas as pd # creating a datasetdf = pd.DataFrame([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]], columns=['a', 'b', 'c']) # viewing the dataFrameprint(df) # finding mean by columnsdf.mean(axis='columns') Output: Picked Python pandas-dataFrame Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON Python | os.path.join() method How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Get unique values from a list Python | datetime.timedelta() function
[ { "code": null, "e": 52, "s": 24, "text": "\n19 Dec, 2021" }, { "code": null, "e": 138, "s": 52, "text": "In this article, we will discuss how to use axis=0 and axis=1 in pandas using Python." }, { "code": null, "e": 462, "s": 138, "text": "Sometimes we need to do operations only on rows, and sometimes only on columns, in such situations, we specify the axis parameter. In this article, let’s see a few examples to know when and how to use the axis parameter. In pandas axis = 0 refers to horizontal axis or rows and axis = 1 refers to vertical axis or columns. " }, { "code": null, "e": 587, "s": 462, "text": "When the axis is set to zero while performing a specific action, the action is performed on rows that satisfy the condition." }, { "code": null, "e": 601, "s": 587, "text": "Dataset Used:" }, { "code": null, "e": 623, "s": 601, "text": "Example: Using axis=0" }, { "code": null, "e": 631, "s": 623, "text": "Python3" }, { "code": "# importing packagesimport pandas as pd # importing our datasetdf = pd.read_csv('hiring.csv') # dropping the column named 'experience'df = df.drop([0, 3], axis=0) # 'viewing the dataframedf.head()", "e": 831, "s": 631, "text": null }, { "code": null, "e": 839, "s": 831, "text": "Output:" }, { "code": null, "e": 861, "s": 839, "text": "Example: Using axis=0" }, { "code": null, "e": 869, "s": 861, "text": "Python3" }, { "code": "# importing packagesimport pandas as pd # creating a datasetdf = pd.DataFrame([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]], columns=['a', 'b', 'c']) # viewing the dataFrameprint(df) # finding mean by rowsdf.mean(axis='rows')", "e": 1135, "s": 869, "text": null }, { "code": null, "e": 1143, "s": 1135, "text": "Output:" }, { "code": null, "e": 1272, "s": 1143, "text": "When the axis is set to one while performing a specific action, the action is performed on column(s) that satisfy the condition." }, { "code": null, "e": 1294, "s": 1272, "text": "Example: Using axis=1" }, { "code": null, "e": 1302, "s": 1294, "text": "Python3" }, { "code": "# importing packagesimport pandas as pd # importing our datasetdf = pd.read_csv('hiring.csv') # dropping the column named 'experience'df = df.drop(['experience'], axis=1) # 'viewing the dataframedf.head()", "e": 1510, "s": 1302, "text": null }, { "code": null, "e": 1518, "s": 1510, "text": "Output:" }, { "code": null, "e": 1540, "s": 1518, "text": "Example: Using axis=1" }, { "code": null, "e": 1548, "s": 1540, "text": "Python3" }, { "code": "# importing packagesimport pandas as pd # creating a datasetdf = pd.DataFrame([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]], columns=['a', 'b', 'c']) # viewing the dataFrameprint(df) # finding mean by columnsdf.mean(axis='columns')", "e": 1821, "s": 1548, "text": null }, { "code": null, "e": 1829, "s": 1821, "text": "Output:" }, { "code": null, "e": 1836, "s": 1829, "text": "Picked" }, { "code": null, "e": 1860, "s": 1836, "text": "Python pandas-dataFrame" }, { "code": null, "e": 1874, "s": 1860, "text": "Python-pandas" }, { "code": null, "e": 1881, "s": 1874, "text": "Python" }, { "code": null, "e": 1979, "s": 1881, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2011, "s": 1979, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2038, "s": 2011, "text": "Python Classes and Objects" }, { "code": null, "e": 2059, "s": 2038, "text": "Python OOPs Concepts" }, { "code": null, "e": 2082, "s": 2059, "text": "Introduction To PYTHON" }, { "code": null, "e": 2113, "s": 2082, "text": "Python | os.path.join() method" }, { "code": null, "e": 2169, "s": 2113, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 2211, "s": 2169, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 2253, "s": 2211, "text": "Check if element exists in list in Python" }, { "code": null, "e": 2292, "s": 2253, "text": "Python | Get unique values from a list" } ]
Merge k sorted arrays | Set 2 (Different Sized Arrays)
21 Jun, 2022 Given k sorted arrays of possibly different sizes, merge them and print the sorted output.Examples: Input: k = 3 arr[][] = { {1, 3}, {2, 4, 6}, {0, 9, 10, 11}} ; Output: 0 1 2 3 4 6 9 10 11 Input: k = 2 arr[][] = { {1, 3, 20}, {2, 4, 6}} ; Output: 1 2 3 4 6 20 We have discussed a solution that works for all arrays of the same size in Merge k sorted arrays | Set 1.A simple solution is to create an output array and one by one copy all k arrays to it. Finally, sort the output array. This approach takes O(N Log N) time where N is the count of all elements.An efficient solution is to use a heap data structure. The time complexity of the heap-based solution is O(N Log k).1. Create an output array. 2. Create a min-heap of size k and insert 1st element in all the arrays into the heap 3. Repeat the following steps while the priority queue is not empty. .....a) Remove the minimum element from the heap (minimum is always at the root) and store it in the output array. .....b) Insert the next element from the array from which the element is extracted. If the array doesn’t have any more elements, then do nothing. Below is the implementation of the above approach: C++ Java Python3 C# // C++ program to merge k sorted arrays// of size n each.#include <bits/stdc++.h>using namespace std; // A pair of pairs, first element is going to// store value, second element index of array// and third element index in the array.typedef pair<int, pair<int, int> > ppi; // This function takes an array of arrays as an// argument and all arrays are assumed to be// sorted. It merges them together and prints// the final sorted output.vector<int> mergeKArrays(vector<vector<int> > arr){ vector<int> output; // Create a min heap with k heap nodes. Every // heap node has first element of an array priority_queue<ppi, vector<ppi>, greater<ppi> > pq; for (int i = 0; i < arr.size(); i++) pq.push({ arr[i][0], { i, 0 } }); // Now one by one get the minimum element // from min heap and replace it with next // element of its array while (pq.empty() == false) { ppi curr = pq.top(); pq.pop(); // i ==> Array Number // j ==> Index in the array number int i = curr.second.first; int j = curr.second.second; output.push_back(curr.first); // The next element belongs to same array as // current. if (j + 1 < arr[i].size()) pq.push({ arr[i][j + 1], { i, j + 1 } }); } return output;} // Driver program to test above functionsint main(){ // Change n at the top to change number // of elements in an array vector<vector<int> > arr{ { 2, 6, 12 }, { 1, 9 }, { 23, 34, 90, 2000 } }; vector<int> output = mergeKArrays(arr); cout << "Merged array is " << endl; for (auto x : output) cout << x << " "; return 0;} /*package whatever //do not write package name here */ import java.util.ArrayList;import java.util.PriorityQueue; public class MergeKSortedArrays { private static class HeapNode implements Comparable<HeapNode> { int x; int y; int value; HeapNode(int x, int y, int value) { this.x = x; this.y = y; this.value = value; } @Override public int compareTo(HeapNode hn) { if (this.value <= hn.value) { return -1; } else { return 1; } } } // Function to merge k sorted arrays. public static ArrayList<Integer> mergeKArrays(int[][] arr, int K) { ArrayList<Integer> result = new ArrayList<Integer>(); PriorityQueue<HeapNode> heap = new PriorityQueue<HeapNode>(); // Initially add only first column of elements. First // element of every array for (int i = 0; i < arr.length; i++) { heap.add(new HeapNode(i, 0, arr[i][0])); } HeapNode curr = null; while (!heap.isEmpty()) { curr = heap.poll(); result.add(curr.value); // Check if next element of curr min exists, // then add that to heap. if (curr.y < (arr[curr.x].length - 1)) { heap.add( new HeapNode(curr.x, curr.y + 1, arr[curr.x][curr.y + 1])); } } return result; } public static void main(String[] args) { int[][] arr = { { 2, 6, 12 }, { 1, 9 }, { 23, 34, 90, 2000 } }; System.out.println( MergeKSortedArrays.mergeKArrays(arr, arr.length) .toString()); }}// This code has been contributed by Manjunatha KB # merge function merge two arrays# of different or same length# if n = max(n1, n2)# time complexity of merge is (o(n log(n))) from heapq import merge # function for meging k arraysdef mergeK(arr, k): l = arr[0] for i in range(k-1): # when k = 0 it merge arr[1] # with arr[0] here in l arr[0] # is stored l = list(merge(l, arr[i + 1])) return l # for printing arraydef printArray(arr): print(*arr) # driver codearr =[[2, 6, 12 ], [ 1, 9 ], [23, 34, 90, 2000 ]]k = 3 l = mergeK(arr, k) printArray(l) // C# program to merge k sorted arrays// of size n each.using System;using System.Collections.Generic;class GFG{ // This function takes an array of arrays as an // argument and all arrays are assumed to be // sorted. It merges them together and prints // the final sorted output. static List<int> mergeKArrays(List<List<int>> arr) { List<int> output = new List<int>(); // Create a min heap with k heap nodes. Every // heap node has first element of an array List<Tuple<int,Tuple<int,int>>> pq = new List<Tuple<int,Tuple<int,int>>>(); for (int i = 0; i < arr.Count; i++) pq.Add(new Tuple<int, Tuple<int,int>>(arr[i][0], new Tuple<int,int>(i, 0))); pq.Sort(); // Now one by one get the minimum element // from min heap and replace it with next // element of its array while (pq.Count > 0) { Tuple<int,Tuple<int,int>> curr = pq[0]; pq.RemoveAt(0); // i ==> Array Number // j ==> Index in the array number int i = curr.Item2.Item1; int j = curr.Item2.Item2; output.Add(curr.Item1); // The next element belongs to same array as // current. if (j + 1 < arr[i].Count) { pq.Add(new Tuple<int,Tuple<int,int>>(arr[i][j + 1], new Tuple<int,int>(i, j + 1))); pq.Sort(); } } return output; } // Driver codestatic void Main(){ // Change n at the top to change number // of elements in an array List<List<int>> arr = new List<List<int>>(); arr.Add(new List<int>(new int[]{2, 6, 12})); arr.Add(new List<int>(new int[]{1, 9})); arr.Add(new List<int>(new int[]{23, 34, 90, 2000})); List<int> output = mergeKArrays(arr); Console.WriteLine("Merged array is "); foreach(int x in output) Console.Write(x + " ");}} // This code is contributed by divyeshrabadiya07. Merged array is 1 2 6 9 12 23 34 90 2000 Time Complexity: O(N Log k)Auxiliary Space: O(N) rajutkarshai divyeshrabadiya07 rajatkumargla19 manjunatha_kb Code_r array-merge cpp-pair cpp-priority-queue cpp-vector priority-queue Arrays Heap Arrays Heap priority-queue Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n21 Jun, 2022" }, { "code": null, "e": 155, "s": 54, "text": "Given k sorted arrays of possibly different sizes, merge them and print the sorted output.Examples: " }, { "code": null, "e": 386, "s": 155, "text": "Input: k = 3 \n arr[][] = { {1, 3},\n {2, 4, 6},\n {0, 9, 10, 11}} ;\nOutput: 0 1 2 3 4 6 9 10 11 \n\nInput: k = 2\n arr[][] = { {1, 3, 20},\n {2, 4, 6}} ;\nOutput: 1 2 3 4 6 20 " }, { "code": null, "e": 1242, "s": 386, "text": "We have discussed a solution that works for all arrays of the same size in Merge k sorted arrays | Set 1.A simple solution is to create an output array and one by one copy all k arrays to it. Finally, sort the output array. This approach takes O(N Log N) time where N is the count of all elements.An efficient solution is to use a heap data structure. The time complexity of the heap-based solution is O(N Log k).1. Create an output array. 2. Create a min-heap of size k and insert 1st element in all the arrays into the heap 3. Repeat the following steps while the priority queue is not empty. .....a) Remove the minimum element from the heap (minimum is always at the root) and store it in the output array. .....b) Insert the next element from the array from which the element is extracted. If the array doesn’t have any more elements, then do nothing." }, { "code": null, "e": 1293, "s": 1242, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 1297, "s": 1293, "text": "C++" }, { "code": null, "e": 1302, "s": 1297, "text": "Java" }, { "code": null, "e": 1310, "s": 1302, "text": "Python3" }, { "code": null, "e": 1313, "s": 1310, "text": "C#" }, { "code": "// C++ program to merge k sorted arrays// of size n each.#include <bits/stdc++.h>using namespace std; // A pair of pairs, first element is going to// store value, second element index of array// and third element index in the array.typedef pair<int, pair<int, int> > ppi; // This function takes an array of arrays as an// argument and all arrays are assumed to be// sorted. It merges them together and prints// the final sorted output.vector<int> mergeKArrays(vector<vector<int> > arr){ vector<int> output; // Create a min heap with k heap nodes. Every // heap node has first element of an array priority_queue<ppi, vector<ppi>, greater<ppi> > pq; for (int i = 0; i < arr.size(); i++) pq.push({ arr[i][0], { i, 0 } }); // Now one by one get the minimum element // from min heap and replace it with next // element of its array while (pq.empty() == false) { ppi curr = pq.top(); pq.pop(); // i ==> Array Number // j ==> Index in the array number int i = curr.second.first; int j = curr.second.second; output.push_back(curr.first); // The next element belongs to same array as // current. if (j + 1 < arr[i].size()) pq.push({ arr[i][j + 1], { i, j + 1 } }); } return output;} // Driver program to test above functionsint main(){ // Change n at the top to change number // of elements in an array vector<vector<int> > arr{ { 2, 6, 12 }, { 1, 9 }, { 23, 34, 90, 2000 } }; vector<int> output = mergeKArrays(arr); cout << \"Merged array is \" << endl; for (auto x : output) cout << x << \" \"; return 0;}", "e": 3021, "s": 1313, "text": null }, { "code": "/*package whatever //do not write package name here */ import java.util.ArrayList;import java.util.PriorityQueue; public class MergeKSortedArrays { private static class HeapNode implements Comparable<HeapNode> { int x; int y; int value; HeapNode(int x, int y, int value) { this.x = x; this.y = y; this.value = value; } @Override public int compareTo(HeapNode hn) { if (this.value <= hn.value) { return -1; } else { return 1; } } } // Function to merge k sorted arrays. public static ArrayList<Integer> mergeKArrays(int[][] arr, int K) { ArrayList<Integer> result = new ArrayList<Integer>(); PriorityQueue<HeapNode> heap = new PriorityQueue<HeapNode>(); // Initially add only first column of elements. First // element of every array for (int i = 0; i < arr.length; i++) { heap.add(new HeapNode(i, 0, arr[i][0])); } HeapNode curr = null; while (!heap.isEmpty()) { curr = heap.poll(); result.add(curr.value); // Check if next element of curr min exists, // then add that to heap. if (curr.y < (arr[curr.x].length - 1)) { heap.add( new HeapNode(curr.x, curr.y + 1, arr[curr.x][curr.y + 1])); } } return result; } public static void main(String[] args) { int[][] arr = { { 2, 6, 12 }, { 1, 9 }, { 23, 34, 90, 2000 } }; System.out.println( MergeKSortedArrays.mergeKArrays(arr, arr.length) .toString()); }}// This code has been contributed by Manjunatha KB", "e": 4917, "s": 3021, "text": null }, { "code": "# merge function merge two arrays# of different or same length# if n = max(n1, n2)# time complexity of merge is (o(n log(n))) from heapq import merge # function for meging k arraysdef mergeK(arr, k): l = arr[0] for i in range(k-1): # when k = 0 it merge arr[1] # with arr[0] here in l arr[0] # is stored l = list(merge(l, arr[i + 1])) return l # for printing arraydef printArray(arr): print(*arr) # driver codearr =[[2, 6, 12 ], [ 1, 9 ], [23, 34, 90, 2000 ]]k = 3 l = mergeK(arr, k) printArray(l)", "e": 5476, "s": 4917, "text": null }, { "code": "// C# program to merge k sorted arrays// of size n each.using System;using System.Collections.Generic;class GFG{ // This function takes an array of arrays as an // argument and all arrays are assumed to be // sorted. It merges them together and prints // the final sorted output. static List<int> mergeKArrays(List<List<int>> arr) { List<int> output = new List<int>(); // Create a min heap with k heap nodes. Every // heap node has first element of an array List<Tuple<int,Tuple<int,int>>> pq = new List<Tuple<int,Tuple<int,int>>>(); for (int i = 0; i < arr.Count; i++) pq.Add(new Tuple<int, Tuple<int,int>>(arr[i][0], new Tuple<int,int>(i, 0))); pq.Sort(); // Now one by one get the minimum element // from min heap and replace it with next // element of its array while (pq.Count > 0) { Tuple<int,Tuple<int,int>> curr = pq[0]; pq.RemoveAt(0); // i ==> Array Number // j ==> Index in the array number int i = curr.Item2.Item1; int j = curr.Item2.Item2; output.Add(curr.Item1); // The next element belongs to same array as // current. if (j + 1 < arr[i].Count) { pq.Add(new Tuple<int,Tuple<int,int>>(arr[i][j + 1], new Tuple<int,int>(i, j + 1))); pq.Sort(); } } return output; } // Driver codestatic void Main(){ // Change n at the top to change number // of elements in an array List<List<int>> arr = new List<List<int>>(); arr.Add(new List<int>(new int[]{2, 6, 12})); arr.Add(new List<int>(new int[]{1, 9})); arr.Add(new List<int>(new int[]{23, 34, 90, 2000})); List<int> output = mergeKArrays(arr); Console.WriteLine(\"Merged array is \"); foreach(int x in output) Console.Write(x + \" \");}} // This code is contributed by divyeshrabadiya07.", "e": 7589, "s": 5476, "text": null }, { "code": null, "e": 7632, "s": 7589, "text": "Merged array is \n1 2 6 9 12 23 34 90 2000 " }, { "code": null, "e": 7681, "s": 7632, "text": "Time Complexity: O(N Log k)Auxiliary Space: O(N)" }, { "code": null, "e": 7694, "s": 7681, "text": "rajutkarshai" }, { "code": null, "e": 7712, "s": 7694, "text": "divyeshrabadiya07" }, { "code": null, "e": 7728, "s": 7712, "text": "rajatkumargla19" }, { "code": null, "e": 7742, "s": 7728, "text": "manjunatha_kb" }, { "code": null, "e": 7749, "s": 7742, "text": "Code_r" }, { "code": null, "e": 7761, "s": 7749, "text": "array-merge" }, { "code": null, "e": 7770, "s": 7761, "text": "cpp-pair" }, { "code": null, "e": 7789, "s": 7770, "text": "cpp-priority-queue" }, { "code": null, "e": 7800, "s": 7789, "text": "cpp-vector" }, { "code": null, "e": 7815, "s": 7800, "text": "priority-queue" }, { "code": null, "e": 7822, "s": 7815, "text": "Arrays" }, { "code": null, "e": 7827, "s": 7822, "text": "Heap" }, { "code": null, "e": 7834, "s": 7827, "text": "Arrays" }, { "code": null, "e": 7839, "s": 7834, "text": "Heap" }, { "code": null, "e": 7854, "s": 7839, "text": "priority-queue" } ]
Python MySQL – Create Database
04 Jul, 2021 Python Database API ( Application Program Interface ) is the Database interface for the standard Python. This standard is adhered to by most Python Database interfaces. There are various Database servers supported by Python Database such as MySQL, GadFly, mSQL, PostgreSQL, Microsoft SQL Server 2000, Informix, Interbase, Oracle, Sybase etc. To connect with MySQL database server from Python, we need to import the mysql.connector interface.Syntax: CREATE DATABASE DATABASE_NAME Example: Python # importing required librariesimport mysql.connector dataBase = mysql.connector.connect( host ="localhost", user ="user", passwd ="gfg") # preparing a cursor objectcursorObject = dataBase.cursor() # creating databasecursorObject.execute("CREATE DATABASE geeks4geeks") Output: The above program illustrates the creation of MySQL database geeks4geeks in which host-name is localhost, the username is user and password is gfg.Let’s suppose we want to create a table in the database, then we need to connect to a database. Below is a program to create a table in the geeks4geeks database which was created in the above program. Python # importing required libraryimport mysql.connector # connecting to the databasedataBase = mysql.connector.connect( host = "localhost", user = "user", passwd = "gfg", database = "geeks4geeks" ) # preparing a cursor objectcursorObject = dataBase.cursor() # creating table studentRecord = """CREATE TABLE STUDENT ( NAME VARCHAR(20) NOT NULL, BRANCH VARCHAR(50), ROLL INT NOT NULL, SECTION VARCHAR(5), AGE INT )""" # table createdcursorObject.execute(studentRecord) # disconnecting from serverdataBase.close() Output: abhaderiya46 gabaa406 Python-mySQL Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? Iterate over a list in Python
[ { "code": null, "e": 54, "s": 26, "text": "\n04 Jul, 2021" }, { "code": null, "e": 505, "s": 54, "text": "Python Database API ( Application Program Interface ) is the Database interface for the standard Python. This standard is adhered to by most Python Database interfaces. There are various Database servers supported by Python Database such as MySQL, GadFly, mSQL, PostgreSQL, Microsoft SQL Server 2000, Informix, Interbase, Oracle, Sybase etc. To connect with MySQL database server from Python, we need to import the mysql.connector interface.Syntax: " }, { "code": null, "e": 535, "s": 505, "text": "CREATE DATABASE DATABASE_NAME" }, { "code": null, "e": 545, "s": 535, "text": "Example: " }, { "code": null, "e": 552, "s": 545, "text": "Python" }, { "code": "# importing required librariesimport mysql.connector dataBase = mysql.connector.connect( host =\"localhost\", user =\"user\", passwd =\"gfg\") # preparing a cursor objectcursorObject = dataBase.cursor() # creating databasecursorObject.execute(\"CREATE DATABASE geeks4geeks\")", "e": 823, "s": 552, "text": null }, { "code": null, "e": 832, "s": 823, "text": "Output: " }, { "code": null, "e": 1181, "s": 832, "text": "The above program illustrates the creation of MySQL database geeks4geeks in which host-name is localhost, the username is user and password is gfg.Let’s suppose we want to create a table in the database, then we need to connect to a database. Below is a program to create a table in the geeks4geeks database which was created in the above program. " }, { "code": null, "e": 1188, "s": 1181, "text": "Python" }, { "code": "# importing required libraryimport mysql.connector # connecting to the databasedataBase = mysql.connector.connect( host = \"localhost\", user = \"user\", passwd = \"gfg\", database = \"geeks4geeks\" ) # preparing a cursor objectcursorObject = dataBase.cursor() # creating table studentRecord = \"\"\"CREATE TABLE STUDENT ( NAME VARCHAR(20) NOT NULL, BRANCH VARCHAR(50), ROLL INT NOT NULL, SECTION VARCHAR(5), AGE INT )\"\"\" # table createdcursorObject.execute(studentRecord) # disconnecting from serverdataBase.close()", "e": 1885, "s": 1188, "text": null }, { "code": null, "e": 1894, "s": 1885, "text": "Output: " }, { "code": null, "e": 1909, "s": 1896, "text": "abhaderiya46" }, { "code": null, "e": 1918, "s": 1909, "text": "gabaa406" }, { "code": null, "e": 1931, "s": 1918, "text": "Python-mySQL" }, { "code": null, "e": 1938, "s": 1931, "text": "Python" }, { "code": null, "e": 2036, "s": 1938, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2064, "s": 2036, "text": "Read JSON file using Python" }, { "code": null, "e": 2114, "s": 2064, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 2136, "s": 2114, "text": "Python map() function" }, { "code": null, "e": 2180, "s": 2136, "text": "How to get column names in Pandas dataframe" }, { "code": null, "e": 2222, "s": 2180, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2244, "s": 2222, "text": "Enumerate() in Python" }, { "code": null, "e": 2279, "s": 2244, "text": "Read a file line by line in Python" }, { "code": null, "e": 2305, "s": 2279, "text": "Python String | replace()" }, { "code": null, "e": 2337, "s": 2305, "text": "How to Install PIP on Windows ?" } ]
How to check whether a checkbox is checked in jQuery?
03 Aug, 2021 prop() and is() method are the two way by which we can check whether a checkbox is checked in jQuery or not. prop(): This method provides an simple way to track down the status of checkboxes. It works well in every condition because every checkbox has checked property which specifies its checked or unchecked status. is(): This method is also very simple and easy to use. By using this we can easily find whether a checked box is checked or not. Using the jQuery prop() Method:Syntax: $(selector).prop(parameter) Parameter: Here parameter is the present status of the Checkbox. Example-1: <!DOCTYPE html><html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script></head> <body> <div style="width: 80px; height: 80px; padding: 10px; border: 2px solid green;"> <input type="checkbox" name="radio1" checked /> <script> $(document).ready(function() { $("#but").click(function() { if ($("input[type=checkbox]").prop( ":checked")) { alert("Check box in Checked"); } else { alert("Check box is Unchecked"); } }); }); </script> <br> <button style="margin-top:10px" id="but" type="submit"> Submit </button> </div></body> </html> Output:Before click on button checkbox is unclicked: After click on the button: Using the jQuery is() Method :Syntax : $(selector).is(parameter) Parameter: Here parameter is the present status of the Checkbox. Example-2: <!DOCTYPE html><html> <head> <style> div { width: 80px; height: 80px; padding: 10px; border: 2px solid green; } button { margin-top: 10px; } </style> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> </head> <body> <div> <input type="checkbox" name="radio1" checked /> <script> $(document).ready(function() { $("#but").click(function() { if ($("input[type=checkbox]").is( ":checked")) { alert("Check box in Checked"); } else { alert("Check box is Unchecked"); } }); }); </script> <br> <button id="but" type="submit"> Submit </button> </div></body> </html> Output:Before click on button checkbox is clicked: After click on the button: jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous with it’s philosophy of “Write less, do more”.You can learn jQuery from the ground up by following this jQuery Tutorial and jQuery Examples. Picked JQuery Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. JQuery | Set the value of an input text field Form validation using jQuery How to change selected value of a drop-down list using jQuery? How to add options to a select element using jQuery? Scroll to the top of the page using JavaScript/jQuery Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 28, "s": 0, "text": "\n03 Aug, 2021" }, { "code": null, "e": 137, "s": 28, "text": "prop() and is() method are the two way by which we can check whether a checkbox is checked in jQuery or not." }, { "code": null, "e": 346, "s": 137, "text": "prop(): This method provides an simple way to track down the status of checkboxes. It works well in every condition because every checkbox has checked property which specifies its checked or unchecked status." }, { "code": null, "e": 475, "s": 346, "text": "is(): This method is also very simple and easy to use. By using this we can easily find whether a checked box is checked or not." }, { "code": null, "e": 514, "s": 475, "text": "Using the jQuery prop() Method:Syntax:" }, { "code": null, "e": 544, "s": 514, "text": "$(selector).prop(parameter) \n" }, { "code": null, "e": 609, "s": 544, "text": "Parameter: Here parameter is the present status of the Checkbox." }, { "code": null, "e": 620, "s": 609, "text": "Example-1:" }, { "code": "<!DOCTYPE html><html> <head> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script></head> <body> <div style=\"width: 80px; height: 80px; padding: 10px; border: 2px solid green;\"> <input type=\"checkbox\" name=\"radio1\" checked /> <script> $(document).ready(function() { $(\"#but\").click(function() { if ($(\"input[type=checkbox]\").prop( \":checked\")) { alert(\"Check box in Checked\"); } else { alert(\"Check box is Unchecked\"); } }); }); </script> <br> <button style=\"margin-top:10px\" id=\"but\" type=\"submit\"> Submit </button> </div></body> </html>", "e": 1538, "s": 620, "text": null }, { "code": null, "e": 1591, "s": 1538, "text": "Output:Before click on button checkbox is unclicked:" }, { "code": null, "e": 1618, "s": 1591, "text": "After click on the button:" }, { "code": null, "e": 1657, "s": 1618, "text": "Using the jQuery is() Method :Syntax :" }, { "code": null, "e": 1685, "s": 1657, "text": "$(selector).is(parameter) \n" }, { "code": null, "e": 1750, "s": 1685, "text": "Parameter: Here parameter is the present status of the Checkbox." }, { "code": null, "e": 1761, "s": 1750, "text": "Example-2:" }, { "code": "<!DOCTYPE html><html> <head> <style> div { width: 80px; height: 80px; padding: 10px; border: 2px solid green; } button { margin-top: 10px; } </style> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> </head> <body> <div> <input type=\"checkbox\" name=\"radio1\" checked /> <script> $(document).ready(function() { $(\"#but\").click(function() { if ($(\"input[type=checkbox]\").is( \":checked\")) { alert(\"Check box in Checked\"); } else { alert(\"Check box is Unchecked\"); } }); }); </script> <br> <button id=\"but\" type=\"submit\"> Submit </button> </div></body> </html>", "e": 2745, "s": 1761, "text": null }, { "code": null, "e": 2796, "s": 2745, "text": "Output:Before click on button checkbox is clicked:" }, { "code": null, "e": 2823, "s": 2796, "text": "After click on the button:" }, { "code": null, "e": 3091, "s": 2823, "text": "jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous with it’s philosophy of “Write less, do more”.You can learn jQuery from the ground up by following this jQuery Tutorial and jQuery Examples." }, { "code": null, "e": 3098, "s": 3091, "text": "Picked" }, { "code": null, "e": 3105, "s": 3098, "text": "JQuery" }, { "code": null, "e": 3122, "s": 3105, "text": "Web Technologies" }, { "code": null, "e": 3220, "s": 3122, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3266, "s": 3220, "text": "JQuery | Set the value of an input text field" }, { "code": null, "e": 3295, "s": 3266, "text": "Form validation using jQuery" }, { "code": null, "e": 3358, "s": 3295, "text": "How to change selected value of a drop-down list using jQuery?" }, { "code": null, "e": 3411, "s": 3358, "text": "How to add options to a select element using jQuery?" }, { "code": null, "e": 3465, "s": 3411, "text": "Scroll to the top of the page using JavaScript/jQuery" }, { "code": null, "e": 3498, "s": 3465, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 3560, "s": 3498, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 3621, "s": 3560, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 3671, "s": 3621, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
PostgreSQL – BETWEEN operator
28 Aug, 2020 PostgreSQL BETWEEN operator is used to match a value against a range of values. Syntax: value BETWEEN low AND high; Or, Syntax: value >= low and value; The BETWEEN operator is used generally with WHERE clause with association with SELECT, INSERT, UPDATE or DELETE statement.For the sake of this article we will be using the sample DVD rental database, which is explained here and can be downloaded by clicking on this link in our examples.Example 1:Here we will query for the payment whose amount is between 3 USD and 5 USD, using the BETWEEN operator in the “Payment” table of our sample database. SELECT customer_id, payment_id, amount FROM payment WHERE amount BETWEEN 3 AND 5; Output: Example 2:Here we will query for getting the payment whose payment date is between 2007-02-07 and 2007-02-15 using the BETWEEN operator in the “Payment” table of our sample database. SELECT customer_id, payment_id, amount, payment_date FROM payment WHERE payment_date BETWEEN '2007-02-07' AND '2007-02-15'; Output: Note: While making date queries the literal date in ISO 8601 format i.e., YYYY-MM-DD should be used in PostgreSQL. postgreSQL-operators PostgreSQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. PostgreSQL - Psql commands PostgreSQL - Change Column Type PostgreSQL - For Loops PostgreSQL - LIMIT with OFFSET clause PostgreSQL - Function Returning A Table PostgreSQL - ARRAY_AGG() Function PostgreSQL - Create Auto-increment Column using SERIAL PostgreSQL - DROP INDEX PostgreSQL - Copy Table PostgreSQL - ROW_NUMBER Function
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Aug, 2020" }, { "code": null, "e": 108, "s": 28, "text": "PostgreSQL BETWEEN operator is used to match a value against a range of values." }, { "code": null, "e": 182, "s": 108, "text": "Syntax: value BETWEEN low AND high;\n\nOr,\n\nSyntax: value >= low and value;" }, { "code": null, "e": 629, "s": 182, "text": "The BETWEEN operator is used generally with WHERE clause with association with SELECT, INSERT, UPDATE or DELETE statement.For the sake of this article we will be using the sample DVD rental database, which is explained here and can be downloaded by clicking on this link in our examples.Example 1:Here we will query for the payment whose amount is between 3 USD and 5 USD, using the BETWEEN operator in the “Payment” table of our sample database." }, { "code": null, "e": 731, "s": 629, "text": "SELECT\n customer_id,\n payment_id,\n amount\nFROM\n payment\nWHERE\n amount BETWEEN 3\nAND 5;" }, { "code": null, "e": 739, "s": 731, "text": "Output:" }, { "code": null, "e": 922, "s": 739, "text": "Example 2:Here we will query for getting the payment whose payment date is between 2007-02-07 and 2007-02-15 using the BETWEEN operator in the “Payment” table of our sample database." }, { "code": null, "e": 1067, "s": 922, "text": "SELECT\n customer_id,\n payment_id,\n amount,\n payment_date\nFROM\n payment\nWHERE\n payment_date BETWEEN '2007-02-07'\nAND '2007-02-15';" }, { "code": null, "e": 1075, "s": 1067, "text": "Output:" }, { "code": null, "e": 1190, "s": 1075, "text": "Note: While making date queries the literal date in ISO 8601 format i.e., YYYY-MM-DD should be used in PostgreSQL." }, { "code": null, "e": 1211, "s": 1190, "text": "postgreSQL-operators" }, { "code": null, "e": 1222, "s": 1211, "text": "PostgreSQL" }, { "code": null, "e": 1320, "s": 1222, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1347, "s": 1320, "text": "PostgreSQL - Psql commands" }, { "code": null, "e": 1379, "s": 1347, "text": "PostgreSQL - Change Column Type" }, { "code": null, "e": 1402, "s": 1379, "text": "PostgreSQL - For Loops" }, { "code": null, "e": 1440, "s": 1402, "text": "PostgreSQL - LIMIT with OFFSET clause" }, { "code": null, "e": 1480, "s": 1440, "text": "PostgreSQL - Function Returning A Table" }, { "code": null, "e": 1514, "s": 1480, "text": "PostgreSQL - ARRAY_AGG() Function" }, { "code": null, "e": 1569, "s": 1514, "text": "PostgreSQL - Create Auto-increment Column using SERIAL" }, { "code": null, "e": 1593, "s": 1569, "text": "PostgreSQL - DROP INDEX" }, { "code": null, "e": 1617, "s": 1593, "text": "PostgreSQL - Copy Table" } ]
LL(1) Parsing Algorithm
29 Apr, 2021 Prerequisite — construction of LL(1) parsing table.LL(1) parsing is a top-down parsing method in the syntax analysis phase of compiler design. Required components for LL(1) parsing are input string, a stack, parsing table for given grammar, and parser. Here, we discuss a parser that determines that given string can be generated from a given grammar(or parsing table) or not. Let given grammar is G = (V, T, S, P)where V-variable symbol set, T-terminal symbol set, S- start symbol, P- production set. LL(1) Parser algorithm:Input- 1. stack = S //stack initially contains only S. 2. input string = w$ where S is the start symbol of grammar, w is given string, and $ is used for the end of string. 3. PT is a parsing table of given grammar in the form of a matrix or 2D array. Output- determines that given string can be produced by given grammar(parsing table) or not, if not then it produces an error. Steps: 1. while(stack is not empty) { // initially it is S 2. A = top symbol of stack; //initially it is first symbol in string, it can be $ also 3. r = next input symbol of given string; 4. if (A∈T or A==$) { 5. if(A==r){ 6. pop A from stack; 7. remove r from input; 8. } 9. else 10. ERROR(); 11. } 12. else if (A∈V) { 13. if(PT[A,r]= A⇢B1B2....Bk) { 14. pop A from stack; // B1 on top of stack at final of this step 15. push Bk,Bk-1......B1 on stack 16. } 17. else if (PT[A,r] = error()) 18. error(); 19. } 20. } // if parser terminate without error() // then given string can generated by given parsing table. Time complexityAs we know that size of a grammar for a language is finite. Like, a finite number of variables, terminals, and productions. If grammar is finite then its LL(1) parsing table is also finite of size O(V*T). Let p is the maximum of lengths of strings in RHS of all productions and l is the length of given string and l is very larger than p. if block at line 4 of algorithm always runs for O(1) time. else if block at line 12 in algorithm takes O(|P|*p) as upper bound for a single next input symbol. And while loop can run for more than l times, but we have considered the repeated while loop for a single next input symbol in O(|P|*p). So, the total time complexity is T(l) = O(l)*O(|P|*p) = O(l*|P|*p) = O(l) { as l >>>|P|*p } The time complexity of this algorithm is the order of length of the input string. Comparison with Context-free language (CFL) :Languages in LL(1) grammar is a proper subset of CFL. Using the CYK algorithm we can find membership of a string for a given Context-free grammar(CFG). CYK takes O(l3) time for the membership test for CFG. But for LL(1) grammar we can do a membership test in O(l) time which is linear using the above algorithm. If we know that given CFG is LL(1) grammar then use LL(1) parser for parsing rather than CYK algorithm. Example –Let the grammar G = (V, T, S’, P) is S' → S$ S → xYzS | a Y → xYz | y Parsing table(PT) for this grammar Let string1 = xxyzza, We have to add $ with this string, We will use the above parsing algorithm, diagram for the process : For string1 we got an empty stack, and while loop or algorithm terminated without error. So, string1 belongs to language for given grammar G. Let string2 = xxyzzz, Same way as above we will use the algorithm to parse the string2, here is the diagram For string2, at the last stage as in the above diagram when the top of the stack is S and the next input symbol of the string is z, but in PT[S,z] = error. The algorithm terminated with an error. So, string2 is not in the language of grammar G. Compiler Design GATE CS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Directed Acyclic graph in Compiler Design (with examples) Type Checking in Compiler Design Data flow analysis in Compiler S - attributed and L - attributed SDTs in Syntax directed translation Runtime Environments in Compiler Design Layers of OSI Model ACID Properties in DBMS TCP/IP Model Types of Operating Systems Normal Forms in DBMS
[ { "code": null, "e": 54, "s": 26, "text": "\n29 Apr, 2021" }, { "code": null, "e": 558, "s": 54, "text": "Prerequisite — construction of LL(1) parsing table.LL(1) parsing is a top-down parsing method in the syntax analysis phase of compiler design. Required components for LL(1) parsing are input string, a stack, parsing table for given grammar, and parser. Here, we discuss a parser that determines that given string can be generated from a given grammar(or parsing table) or not. Let given grammar is G = (V, T, S, P)where V-variable symbol set, T-terminal symbol set, S- start symbol, P- production set. " }, { "code": null, "e": 870, "s": 558, "text": "LL(1) Parser algorithm:Input- 1. stack = S //stack initially contains only S. 2. input string = w$ where S is the start symbol of grammar, w is given string, and $ is used for the end of string. 3. PT is a parsing table of given grammar in the form of a matrix or 2D array." }, { "code": null, "e": 997, "s": 870, "text": "Output- determines that given string can be produced by given grammar(parsing table) or not, if not then it produces an error." }, { "code": null, "e": 1004, "s": 997, "text": "Steps:" }, { "code": null, "e": 1807, "s": 1004, "text": "1. while(stack is not empty) {\n\n // initially it is S\n2. A = top symbol of stack; \n\n //initially it is first symbol in string, it can be $ also\n3. r = next input symbol of given string; \n4. if (A∈T or A==$) {\n5. if(A==r){\n6. pop A from stack;\n7. remove r from input;\n8. }\n9. else\n10. ERROR();\n11. }\n12. else if (A∈V) {\n13. if(PT[A,r]= A⇢B1B2....Bk) {\n14. pop A from stack;\n \n // B1 on top of stack at final of this step\n15. push Bk,Bk-1......B1 on stack \n16. }\n17. else if (PT[A,r] = error())\n18. error();\n19. }\n20. } \n// if parser terminate without error() \n// then given string can generated by given parsing table." }, { "code": null, "e": 2032, "s": 1807, "text": "Time complexityAs we know that size of a grammar for a language is finite. Like, a finite number of variables, terminals, and productions. If grammar is finite then its LL(1) parsing table is also finite of size O(V*T). Let" }, { "code": null, "e": 2101, "s": 2032, "text": "p is the maximum of lengths of strings in RHS of all productions and" }, { "code": null, "e": 2138, "s": 2101, "text": "l is the length of given string and" }, { "code": null, "e": 2492, "s": 2138, "text": "l is very larger than p. if block at line 4 of algorithm always runs for O(1) time. else if block at line 12 in algorithm takes O(|P|*p) as upper bound for a single next input symbol. And while loop can run for more than l times, but we have considered the repeated while loop for a single next input symbol in O(|P|*p). So, the total time complexity is" }, { "code": null, "e": 2597, "s": 2492, "text": " T(l) = O(l)*O(|P|*p)\n = O(l*|P|*p)\n = O(l) { as l >>>|P|*p }" }, { "code": null, "e": 2679, "s": 2597, "text": "The time complexity of this algorithm is the order of length of the input string." }, { "code": null, "e": 3140, "s": 2679, "text": "Comparison with Context-free language (CFL) :Languages in LL(1) grammar is a proper subset of CFL. Using the CYK algorithm we can find membership of a string for a given Context-free grammar(CFG). CYK takes O(l3) time for the membership test for CFG. But for LL(1) grammar we can do a membership test in O(l) time which is linear using the above algorithm. If we know that given CFG is LL(1) grammar then use LL(1) parser for parsing rather than CYK algorithm." }, { "code": null, "e": 3187, "s": 3140, "text": "Example –Let the grammar G = (V, T, S’, P) is " }, { "code": null, "e": 3220, "s": 3187, "text": "S' → S$\nS → xYzS | a\nY → xYz | y" }, { "code": null, "e": 3255, "s": 3220, "text": "Parsing table(PT) for this grammar" }, { "code": null, "e": 3277, "s": 3255, "text": "Let string1 = xxyzza," }, { "code": null, "e": 3379, "s": 3277, "text": "We have to add $ with this string, We will use the above parsing algorithm, diagram for the process :" }, { "code": null, "e": 3521, "s": 3379, "text": "For string1 we got an empty stack, and while loop or algorithm terminated without error. So, string1 belongs to language for given grammar G." }, { "code": null, "e": 3543, "s": 3521, "text": "Let string2 = xxyzzz," }, { "code": null, "e": 3629, "s": 3543, "text": "Same way as above we will use the algorithm to parse the string2, here is the diagram" }, { "code": null, "e": 3875, "s": 3629, "text": "For string2, at the last stage as in the above diagram when the top of the stack is S and the next input symbol of the string is z, but in PT[S,z] = error. The algorithm terminated with an error. So, string2 is not in the language of grammar G. " }, { "code": null, "e": 3891, "s": 3875, "text": "Compiler Design" }, { "code": null, "e": 3899, "s": 3891, "text": "GATE CS" }, { "code": null, "e": 3997, "s": 3899, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4055, "s": 3997, "text": "Directed Acyclic graph in Compiler Design (with examples)" }, { "code": null, "e": 4088, "s": 4055, "text": "Type Checking in Compiler Design" }, { "code": null, "e": 4119, "s": 4088, "text": "Data flow analysis in Compiler" }, { "code": null, "e": 4189, "s": 4119, "text": "S - attributed and L - attributed SDTs in Syntax directed translation" }, { "code": null, "e": 4229, "s": 4189, "text": "Runtime Environments in Compiler Design" }, { "code": null, "e": 4249, "s": 4229, "text": "Layers of OSI Model" }, { "code": null, "e": 4273, "s": 4249, "text": "ACID Properties in DBMS" }, { "code": null, "e": 4286, "s": 4273, "text": "TCP/IP Model" }, { "code": null, "e": 4313, "s": 4286, "text": "Types of Operating Systems" } ]
Matcher groupCount() method in Java with Examples
26 Nov, 2018 The groupCount() method of Matcher Class is used to get the number of capturing groups in this matcher’s pattern. Syntax: public int groupCount() Parameters: This method do not takes any parameter. Return Value: This method returns the number of capturing groups in this matcher’s pattern. Below examples illustrate the Matcher.groupCount() method: Example 1: // Java code to illustrate groupCount() method import java.util.regex.*; public class GFG { public static void main(String[] args) { // Get the regex to be checked String regex = "Geeks"; // Create a pattern from regex Pattern pattern = Pattern.compile(regex); // Get the String to be matched String stringToBeMatched = "GeeksForGeeks"; // Create a matcher for the input String Matcher matcher = pattern .matcher(stringToBeMatched); // Get the number of capturing groups // using groupCount() method System.out.println(matcher.groupCount()); }} 0 Example 2: // Java code to illustrate groupCount() method import java.util.regex.*; public class GFG { public static void main(String[] args) { // Get the regex to be checked String regex = "GFG"; // Create a pattern from regex Pattern pattern = Pattern.compile(regex); // Get the String to be matched String stringToBeMatched = "GFGFGFGFGFGFGFGFGFG"; // Create a matcher for the input String Matcher matcher = pattern .matcher(stringToBeMatched); // Get the number of capturing groups // using groupCount() method System.out.println(matcher.groupCount()); }} 0 Reference: Oracle Doc Java - util package Java-Functions Java-Matcher Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n26 Nov, 2018" }, { "code": null, "e": 142, "s": 28, "text": "The groupCount() method of Matcher Class is used to get the number of capturing groups in this matcher’s pattern." }, { "code": null, "e": 150, "s": 142, "text": "Syntax:" }, { "code": null, "e": 175, "s": 150, "text": "public int groupCount()\n" }, { "code": null, "e": 227, "s": 175, "text": "Parameters: This method do not takes any parameter." }, { "code": null, "e": 319, "s": 227, "text": "Return Value: This method returns the number of capturing groups in this matcher’s pattern." }, { "code": null, "e": 378, "s": 319, "text": "Below examples illustrate the Matcher.groupCount() method:" }, { "code": null, "e": 389, "s": 378, "text": "Example 1:" }, { "code": "// Java code to illustrate groupCount() method import java.util.regex.*; public class GFG { public static void main(String[] args) { // Get the regex to be checked String regex = \"Geeks\"; // Create a pattern from regex Pattern pattern = Pattern.compile(regex); // Get the String to be matched String stringToBeMatched = \"GeeksForGeeks\"; // Create a matcher for the input String Matcher matcher = pattern .matcher(stringToBeMatched); // Get the number of capturing groups // using groupCount() method System.out.println(matcher.groupCount()); }}", "e": 1082, "s": 389, "text": null }, { "code": null, "e": 1085, "s": 1082, "text": "0\n" }, { "code": null, "e": 1096, "s": 1085, "text": "Example 2:" }, { "code": "// Java code to illustrate groupCount() method import java.util.regex.*; public class GFG { public static void main(String[] args) { // Get the regex to be checked String regex = \"GFG\"; // Create a pattern from regex Pattern pattern = Pattern.compile(regex); // Get the String to be matched String stringToBeMatched = \"GFGFGFGFGFGFGFGFGFG\"; // Create a matcher for the input String Matcher matcher = pattern .matcher(stringToBeMatched); // Get the number of capturing groups // using groupCount() method System.out.println(matcher.groupCount()); }}", "e": 1793, "s": 1096, "text": null }, { "code": null, "e": 1796, "s": 1793, "text": "0\n" }, { "code": null, "e": 1818, "s": 1796, "text": "Reference: Oracle Doc" }, { "code": null, "e": 1838, "s": 1818, "text": "Java - util package" }, { "code": null, "e": 1853, "s": 1838, "text": "Java-Functions" }, { "code": null, "e": 1866, "s": 1853, "text": "Java-Matcher" }, { "code": null, "e": 1871, "s": 1866, "text": "Java" }, { "code": null, "e": 1876, "s": 1871, "text": "Java" } ]
ImageView in Android using Jetpack Compose
25 Feb, 2021 Images, Graphics, and vectors attract so many users as they tell so much information in a very informative way. ImageView in Android is used to display different types of images from drawable or in the form of Bitmaps. In this article, we will take a look at the implementation of an ImageView in Android using Jetpack Compose. Attributes Description Step 1: Create a New Project To create a new project in the Android Studio Canary Version please refer to How to Create a new Project in Android Studio Canary Version with Jetpack Compose. Step 2: Add an Image to the drawable folder After creating a new project we have to add an image inside our drawable folder for displaying that image inside our ImageView. Copy your image from your folder’s location and go inside our project. Inside our project Navigate to the app > res > drawable > Right-click on the drawable folder and paste your image there. Step 3: Working with the MainActivity.kt file After adding this image navigates to the app > java > MainActivity.kt and add the below code to it. Comments are added inside the code for a detailed explanation. Kotlin package com.example.edittext import android.os.Bundleimport androidx.appcompat.app.AppCompatActivityimport androidx.compose.foundation.Imageimport androidx.compose.foundation.layout.*import androidx.compose.material.MaterialThemeimport androidx.compose.material.Surfaceimport androidx.compose.runtime.Composableimport androidx.compose.ui.Alignmentimport androidx.compose.ui.layout.ContentScaleimport androidx.compose.ui.platform.setContentimport androidx.compose.ui.res.imageResourceimport androidx.compose.ui.tooling.preview.Previewimport androidx.compose.ui.Modifierimport androidx.compose.ui.unit.Dp import com.example.edittext.ui.EditTextTheme class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { EditTextTheme { // A surface container using the // 'background' color from the theme Surface( // to add background color for our screen. color = MaterialTheme.colors.background, ) { // at below line we are calling // our function for image view. Img(); } } } }} @Composablefun Img() { Column( // we are using column to align our // imageview to center of the screen. modifier = Modifier.fillMaxWidth().fillMaxHeight(), // below line is used for specifying // vertical arrangement. verticalArrangement = Arrangement.Center, // below line is used for specifying // horizontal arrangement. horizontalAlignment = Alignment.CenterHorizontally, ) { // below line is used for creating a variable // for our image resource file. val img = imageResource(id = R.drawable.gfgimage) // below line is used for creating a modifier for our image // which includes image width and image height val modifier = Modifier.preferredHeight(height = Dp(200F)).preferredWidth(width = Dp(200F)) // below is the widget for image. Image( // first parameter of our Image widget // is our image path which we have created // above and name it as img. img, // below line is used to give // alignment to our image view. alignment = Alignment.Center, // below line is used to scale our image // we are using center crop for it. contentScale = ContentScale.Crop, // below line is used to add modifier // to our image. we are adding modifier // which we have created above and name // it as modifier. modifier = modifier ) }} // @Preview function is use to see preview// for our composable function in preview section.@Preview@Composablefun DefaultPreview() { MaterialTheme { // we are passing our composable // function to display its preview. Img() }} Android-Jetpack Technical Scripter 2020 Android Technical Scripter Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Android SDK and it's Components How to Add Views Dynamically and Store Data in Arraylist in Android? Flutter - Custom Bottom Navigation Bar Retrofit with Kotlin Coroutine in Android How to Post Data to API using Retrofit in Android? Flutter - Stack Widget How to Communicate Between Fragments in Android? Activity Lifecycle in Android with Demo App Introduction to Android Development Animation in Android with Example
[ { "code": null, "e": 28, "s": 0, "text": "\n25 Feb, 2021" }, { "code": null, "e": 357, "s": 28, "text": "Images, Graphics, and vectors attract so many users as they tell so much information in a very informative way. ImageView in Android is used to display different types of images from drawable or in the form of Bitmaps. In this article, we will take a look at the implementation of an ImageView in Android using Jetpack Compose. " }, { "code": null, "e": 368, "s": 357, "text": "Attributes" }, { "code": null, "e": 380, "s": 368, "text": "Description" }, { "code": null, "e": 409, "s": 380, "text": "Step 1: Create a New Project" }, { "code": null, "e": 569, "s": 409, "text": "To create a new project in the Android Studio Canary Version please refer to How to Create a new Project in Android Studio Canary Version with Jetpack Compose." }, { "code": null, "e": 613, "s": 569, "text": "Step 2: Add an Image to the drawable folder" }, { "code": null, "e": 934, "s": 613, "text": "After creating a new project we have to add an image inside our drawable folder for displaying that image inside our ImageView. Copy your image from your folder’s location and go inside our project. Inside our project Navigate to the app > res > drawable > Right-click on the drawable folder and paste your image there. " }, { "code": null, "e": 980, "s": 934, "text": "Step 3: Working with the MainActivity.kt file" }, { "code": null, "e": 1144, "s": 980, "text": "After adding this image navigates to the app > java > MainActivity.kt and add the below code to it. Comments are added inside the code for a detailed explanation. " }, { "code": null, "e": 1151, "s": 1144, "text": "Kotlin" }, { "code": "package com.example.edittext import android.os.Bundleimport androidx.appcompat.app.AppCompatActivityimport androidx.compose.foundation.Imageimport androidx.compose.foundation.layout.*import androidx.compose.material.MaterialThemeimport androidx.compose.material.Surfaceimport androidx.compose.runtime.Composableimport androidx.compose.ui.Alignmentimport androidx.compose.ui.layout.ContentScaleimport androidx.compose.ui.platform.setContentimport androidx.compose.ui.res.imageResourceimport androidx.compose.ui.tooling.preview.Previewimport androidx.compose.ui.Modifierimport androidx.compose.ui.unit.Dp import com.example.edittext.ui.EditTextTheme class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { EditTextTheme { // A surface container using the // 'background' color from the theme Surface( // to add background color for our screen. color = MaterialTheme.colors.background, ) { // at below line we are calling // our function for image view. Img(); } } } }} @Composablefun Img() { Column( // we are using column to align our // imageview to center of the screen. modifier = Modifier.fillMaxWidth().fillMaxHeight(), // below line is used for specifying // vertical arrangement. verticalArrangement = Arrangement.Center, // below line is used for specifying // horizontal arrangement. horizontalAlignment = Alignment.CenterHorizontally, ) { // below line is used for creating a variable // for our image resource file. val img = imageResource(id = R.drawable.gfgimage) // below line is used for creating a modifier for our image // which includes image width and image height val modifier = Modifier.preferredHeight(height = Dp(200F)).preferredWidth(width = Dp(200F)) // below is the widget for image. Image( // first parameter of our Image widget // is our image path which we have created // above and name it as img. img, // below line is used to give // alignment to our image view. alignment = Alignment.Center, // below line is used to scale our image // we are using center crop for it. contentScale = ContentScale.Crop, // below line is used to add modifier // to our image. we are adding modifier // which we have created above and name // it as modifier. modifier = modifier ) }} // @Preview function is use to see preview// for our composable function in preview section.@Preview@Composablefun DefaultPreview() { MaterialTheme { // we are passing our composable // function to display its preview. Img() }}", "e": 4337, "s": 1151, "text": null }, { "code": null, "e": 4353, "s": 4337, "text": "Android-Jetpack" }, { "code": null, "e": 4377, "s": 4353, "text": "Technical Scripter 2020" }, { "code": null, "e": 4385, "s": 4377, "text": "Android" }, { "code": null, "e": 4404, "s": 4385, "text": "Technical Scripter" }, { "code": null, "e": 4412, "s": 4404, "text": "Android" }, { "code": null, "e": 4510, "s": 4412, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4542, "s": 4510, "text": "Android SDK and it's Components" }, { "code": null, "e": 4611, "s": 4542, "text": "How to Add Views Dynamically and Store Data in Arraylist in Android?" }, { "code": null, "e": 4650, "s": 4611, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 4692, "s": 4650, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 4743, "s": 4692, "text": "How to Post Data to API using Retrofit in Android?" }, { "code": null, "e": 4766, "s": 4743, "text": "Flutter - Stack Widget" }, { "code": null, "e": 4815, "s": 4766, "text": "How to Communicate Between Fragments in Android?" }, { "code": null, "e": 4859, "s": 4815, "text": "Activity Lifecycle in Android with Demo App" }, { "code": null, "e": 4895, "s": 4859, "text": "Introduction to Android Development" } ]
Insert N elements in a Linked List one after other at middle position
09 Jun, 2022 Given an array of N elements. The task is to insert the given elements at the middle position in the linked list one after another. Each insert operation should take O(1) time complexity.Examples: Input: arr[] = {1, 2, 3, 4, 5} Output: 1 -> 3 -> 5 -> 4 -> 2 -> NULL 1 -> NULL 1 -> 2 -> NULL 1 -> 3 -> 2 -> NULL 1 -> 3 -> 4 -> 2 -> NULL 1 -> 3 -> 5 -> 4 -> 2 -> NULLInput: arr[] = {5, 4, 1, 2} Output: 5 -> 1 -> 2 -> 4 -> NULL Approach: There are two cases: Number of elements present in the list are less than 2.Number of elements present in the list are more than 2. The number of elements already present are even say N then the new element is inserted in the middle position that is (N / 2) + 1.The number of elements already present are odd then the new element is inserted next to the current middle element that is (N / 2) + 2. Number of elements present in the list are less than 2. Number of elements present in the list are more than 2. The number of elements already present are even say N then the new element is inserted in the middle position that is (N / 2) + 1.The number of elements already present are odd then the new element is inserted next to the current middle element that is (N / 2) + 2. The number of elements already present are even say N then the new element is inserted in the middle position that is (N / 2) + 1. The number of elements already present are odd then the new element is inserted next to the current middle element that is (N / 2) + 2. We take one additional pointer ‘middle’ which stores the address of current middle element and a counter which counts the total number of elements. If the elements already present in the linked list are less than 2 then middle will always point to the first position and we insert the new node after the current middle. If the elements already present in the linked list are more than 2 then we insert the new node next to the current middle and increment the counter. If there are an odd number of elements after insertion then the middle points to the newly inserted node else there is no change in the middle pointer.Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation of the approach#include <iostream>using namespace std; // Node structurestruct Node { int value; struct Node* next;}; // Class to represent a node// of the linked listclass LinkedList { private: struct Node *head, *mid; int count; public: LinkedList(); void insertAtMiddle(int); void show();}; LinkedList::LinkedList(){ head = NULL; mid = NULL; count = 0;} // Function to insert a node in// the middle of the linked listvoid LinkedList::insertAtMiddle(int n){ struct Node* temp = new struct Node(); struct Node* temp1; temp->next = NULL; temp->value = n; // If the number of elements // already present are less than 2 if (count < 2) { if (head == NULL) { head = temp; } else { temp1 = head; temp1->next = temp; } count++; // mid points to first element mid = head; } // If the number of elements already present // are greater than 2 else { temp->next = mid->next; mid->next = temp; count++; // If number of elements after insertion // are odd if (count % 2 != 0) { // mid points to the newly // inserted node mid = mid->next; } }} // Function to print the nodes// of the linked listvoid LinkedList::show(){ struct Node* temp; temp = head; // Initializing temp to head // Iterating and printing till // The end of linked list // That is, till temp is null while (temp != NULL) { cout << temp->value << " -> "; temp = temp->next; } cout << "NULL"; cout << endl;} // Driver codeint main(){ // Elements to be inserted one after another int arr[] = { 1, 2, 3, 4, 5 }; int n = sizeof(arr) / sizeof(arr[0]); LinkedList L1; // Insert the elements for (int i = 0; i < n; i++) L1.insertAtMiddle(arr[i]); // Print the nodes of the linked list L1.show(); return 0;} // Java implementation of the approachclass GFG{ // Node urestatic class Node{ int value; Node next;}; // Class to represent a node// of the linked liststatic class LinkedList{ Node head, mid; int count; LinkedList(){ head = null; mid = null; count = 0;} // Function to insert a node in// the middle of the linked listvoid insertAtMiddle(int n){ Node temp = new Node(); Node temp1; temp.next = null; temp.value = n; // If the number of elements // already present are less than 2 if (count < 2) { if (head == null) { head = temp; } else { temp1 = head; temp1.next = temp; } count++; // mid points to first element mid = head; } // If the number of elements already present // are greater than 2 else { temp.next = mid.next; mid.next = temp; count++; // If number of elements after insertion // are odd if (count % 2 != 0) { // mid points to the newly // inserted node mid = mid.next; } }} // Function to print the nodes// of the linked listvoid show(){ Node temp; temp = head; // Initializing temp to head // Iterating and printing till // The end of linked list // That is, till temp is null while (temp != null) { System.out.print( temp.value + " -> "); temp = temp.next; } System.out.print( "null"); System.out.println();} } // Driver codepublic static void main(String args[]){ // Elements to be inserted one after another int arr[] = { 1, 2, 3, 4, 5 }; int n = arr.length; LinkedList L1=new LinkedList(); // Insert the elements for (int i = 0; i < n; i++) L1.insertAtMiddle(arr[i]); // Print the nodes of the linked list L1.show();}} // This code is contributed by Arnab Kundu # Python3 implementation of the approach # Node ureclass Node: def __init__(self): self.value = 0 self.next = None # Class to represent a node# of the linked listclass LinkedList: def __init__(self) : self.head = None self.mid = None self.count = 0 # Function to insert a node in # the middle of the linked list def insertAtMiddle(self , n): temp = Node() temp1 = None temp.next = None temp.value = n # If the number of elements # already present are less than 2 if (self.count < 2): if (self.head == None) : self.head = temp else: temp1 = self.head temp1.next = temp self.count = self.count + 1 # mid points to first element self.mid = self.head # If the number of elements already present # are greater than 2 else: temp.next = self.mid.next self.mid.next = temp self.count = self.count + 1 # If number of elements after insertion # are odd if (self.count % 2 != 0): # mid points to the newly # inserted node self.mid = self.mid.next # Function to print the nodes # of the linked list def show(self): temp = None temp = self.head # Initializing temp to self.head # Iterating and printing till # The end of linked list # That is, till temp is None while (temp != None) : print( temp.value, end = " -> ") temp = temp.next print( "None") # Driver code # Elements to be inserted one after anotherarr = [ 1, 2, 3, 4, 5]n = len(arr) L1 = LinkedList() # Insert the elementsfor i in range(n): L1.insertAtMiddle(arr[i]) # Print the nodes of the linked listL1.show() # This code is contributed by Arnab Kundu // C# implementation of the approachusing System; class GFG{ // Node urepublic class Node{ public int value; public Node next;}; // Class to represent a node// of the linked listpublic class LinkedList{ public Node head, mid; public int count; public LinkedList(){ head = null; mid = null; count = 0;} // Function to insert a node in// the middle of the linked listpublic void insertAtMiddle(int n){ Node temp = new Node(); Node temp1; temp.next = null; temp.value = n; // If the number of elements // already present are less than 2 if (count < 2) { if (head == null) { head = temp; } else { temp1 = head; temp1.next = temp; } count++; // mid points to first element mid = head; } // If the number of elements already present // are greater than 2 else { temp.next = mid.next; mid.next = temp; count++; // If number of elements after insertion // are odd if (count % 2 != 0) { // mid points to the newly // inserted node mid = mid.next; } }} // Function to print the nodes// of the linked listpublic void show(){ Node temp; temp = head; // Initializing temp to head // Iterating and printing till // The end of linked list // That is, till temp is null while (temp != null) { Console.Write( temp.value + " -> "); temp = temp.next; } Console.Write( "null"); Console.WriteLine();} } // Driver codepublic static void Main(String []args){ // Elements to be inserted one after another int []arr = { 1, 2, 3, 4, 5 }; int n = arr.Length; LinkedList L1=new LinkedList(); // Insert the elements for (int i = 0; i < n; i++) L1.insertAtMiddle(arr[i]); // Print the nodes of the linked list L1.show();}} // This code contributed by Rajput-Ji <script> // JavaScript implementation of the approach // Node ure class Node { constructor() { this.value = 0; this.next = null; } } // Class to represent a node // of the linked list class LinkedList { constructor() { this.head = null; this.mid = null; this.count = 0; } // Function to insert a node in // the middle of the linked list insertAtMiddle(n) { var temp = new Node(); var temp1; temp.next = null; temp.value = n; // If the number of elements // already present are less than 2 if (this.count < 2) { if (this.head == null) { this.head = temp; } else { temp1 = this.head; temp1.next = temp; } this.count++; // mid points to first element this.mid = this.head; } // If the number of elements already present // are greater than 2 else { temp.next = this.mid.next; this.mid.next = temp; this.count++; // If number of elements after insertion // are odd if (this.count % 2 != 0) { // mid points to the newly // inserted node this.mid = this.mid.next; } } } // Function to print the nodes // of the linked list show() { var temp; temp = this.head; // Initializing temp to head // Iterating and printing till // The end of linked list // That is, till temp is null while (temp != null) { document.write(temp.value + " -> "); temp = temp.next; } document.write("null"); document.write("<br>"); } } // Driver code // Elements to be inserted one after another var arr = [1, 2, 3, 4, 5]; var n = arr.length; var L1 = new LinkedList(); // Insert the elements for (var i = 0; i < n; i++) L1.insertAtMiddle(arr[i]); // Print the nodes of the linked list L1.show(); </script> 1 -> 3 -> 5 -> 4 -> 2 -> NULL Time Complexity : O(N)Auxiliary Space: O(1), since no extra space has been taken. andrew1234 Rajput-Ji rdtank pankajsharmagfg rishav1329 Data Structures Linked List Mathematical Data Structures Linked List Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. DSA Sheet by Love Babbar SDE SHEET - A Complete Guide for SDE Preparation Introduction to Data Structures What is Hashing | A Complete Tutorial Introduction to Tree Data Structure Reverse a linked list Stack Data Structure (Introduction and Program) LinkedList in Java Introduction to Data Structures Merge two sorted linked lists
[ { "code": null, "e": 53, "s": 25, "text": "\n09 Jun, 2022" }, { "code": null, "e": 252, "s": 53, "text": "Given an array of N elements. The task is to insert the given elements at the middle position in the linked list one after another. Each insert operation should take O(1) time complexity.Examples: " }, { "code": null, "e": 483, "s": 252, "text": "Input: arr[] = {1, 2, 3, 4, 5} Output: 1 -> 3 -> 5 -> 4 -> 2 -> NULL 1 -> NULL 1 -> 2 -> NULL 1 -> 3 -> 2 -> NULL 1 -> 3 -> 4 -> 2 -> NULL 1 -> 3 -> 5 -> 4 -> 2 -> NULLInput: arr[] = {5, 4, 1, 2} Output: 5 -> 1 -> 2 -> 4 -> NULL " }, { "code": null, "e": 518, "s": 485, "text": "Approach: There are two cases: " }, { "code": null, "e": 895, "s": 518, "text": "Number of elements present in the list are less than 2.Number of elements present in the list are more than 2. The number of elements already present are even say N then the new element is inserted in the middle position that is (N / 2) + 1.The number of elements already present are odd then the new element is inserted next to the current middle element that is (N / 2) + 2." }, { "code": null, "e": 951, "s": 895, "text": "Number of elements present in the list are less than 2." }, { "code": null, "e": 1273, "s": 951, "text": "Number of elements present in the list are more than 2. The number of elements already present are even say N then the new element is inserted in the middle position that is (N / 2) + 1.The number of elements already present are odd then the new element is inserted next to the current middle element that is (N / 2) + 2." }, { "code": null, "e": 1404, "s": 1273, "text": "The number of elements already present are even say N then the new element is inserted in the middle position that is (N / 2) + 1." }, { "code": null, "e": 1540, "s": 1404, "text": "The number of elements already present are odd then the new element is inserted next to the current middle element that is (N / 2) + 2." }, { "code": null, "e": 2213, "s": 1540, "text": "We take one additional pointer ‘middle’ which stores the address of current middle element and a counter which counts the total number of elements. If the elements already present in the linked list are less than 2 then middle will always point to the first position and we insert the new node after the current middle. If the elements already present in the linked list are more than 2 then we insert the new node next to the current middle and increment the counter. If there are an odd number of elements after insertion then the middle points to the newly inserted node else there is no change in the middle pointer.Below is the implementation of the above approach: " }, { "code": null, "e": 2217, "s": 2213, "text": "C++" }, { "code": null, "e": 2222, "s": 2217, "text": "Java" }, { "code": null, "e": 2230, "s": 2222, "text": "Python3" }, { "code": null, "e": 2233, "s": 2230, "text": "C#" }, { "code": null, "e": 2244, "s": 2233, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <iostream>using namespace std; // Node structurestruct Node { int value; struct Node* next;}; // Class to represent a node// of the linked listclass LinkedList { private: struct Node *head, *mid; int count; public: LinkedList(); void insertAtMiddle(int); void show();}; LinkedList::LinkedList(){ head = NULL; mid = NULL; count = 0;} // Function to insert a node in// the middle of the linked listvoid LinkedList::insertAtMiddle(int n){ struct Node* temp = new struct Node(); struct Node* temp1; temp->next = NULL; temp->value = n; // If the number of elements // already present are less than 2 if (count < 2) { if (head == NULL) { head = temp; } else { temp1 = head; temp1->next = temp; } count++; // mid points to first element mid = head; } // If the number of elements already present // are greater than 2 else { temp->next = mid->next; mid->next = temp; count++; // If number of elements after insertion // are odd if (count % 2 != 0) { // mid points to the newly // inserted node mid = mid->next; } }} // Function to print the nodes// of the linked listvoid LinkedList::show(){ struct Node* temp; temp = head; // Initializing temp to head // Iterating and printing till // The end of linked list // That is, till temp is null while (temp != NULL) { cout << temp->value << \" -> \"; temp = temp->next; } cout << \"NULL\"; cout << endl;} // Driver codeint main(){ // Elements to be inserted one after another int arr[] = { 1, 2, 3, 4, 5 }; int n = sizeof(arr) / sizeof(arr[0]); LinkedList L1; // Insert the elements for (int i = 0; i < n; i++) L1.insertAtMiddle(arr[i]); // Print the nodes of the linked list L1.show(); return 0;}", "e": 4247, "s": 2244, "text": null }, { "code": "// Java implementation of the approachclass GFG{ // Node urestatic class Node{ int value; Node next;}; // Class to represent a node// of the linked liststatic class LinkedList{ Node head, mid; int count; LinkedList(){ head = null; mid = null; count = 0;} // Function to insert a node in// the middle of the linked listvoid insertAtMiddle(int n){ Node temp = new Node(); Node temp1; temp.next = null; temp.value = n; // If the number of elements // already present are less than 2 if (count < 2) { if (head == null) { head = temp; } else { temp1 = head; temp1.next = temp; } count++; // mid points to first element mid = head; } // If the number of elements already present // are greater than 2 else { temp.next = mid.next; mid.next = temp; count++; // If number of elements after insertion // are odd if (count % 2 != 0) { // mid points to the newly // inserted node mid = mid.next; } }} // Function to print the nodes// of the linked listvoid show(){ Node temp; temp = head; // Initializing temp to head // Iterating and printing till // The end of linked list // That is, till temp is null while (temp != null) { System.out.print( temp.value + \" -> \"); temp = temp.next; } System.out.print( \"null\"); System.out.println();} } // Driver codepublic static void main(String args[]){ // Elements to be inserted one after another int arr[] = { 1, 2, 3, 4, 5 }; int n = arr.length; LinkedList L1=new LinkedList(); // Insert the elements for (int i = 0; i < n; i++) L1.insertAtMiddle(arr[i]); // Print the nodes of the linked list L1.show();}} // This code is contributed by Arnab Kundu", "e": 6172, "s": 4247, "text": null }, { "code": "# Python3 implementation of the approach # Node ureclass Node: def __init__(self): self.value = 0 self.next = None # Class to represent a node# of the linked listclass LinkedList: def __init__(self) : self.head = None self.mid = None self.count = 0 # Function to insert a node in # the middle of the linked list def insertAtMiddle(self , n): temp = Node() temp1 = None temp.next = None temp.value = n # If the number of elements # already present are less than 2 if (self.count < 2): if (self.head == None) : self.head = temp else: temp1 = self.head temp1.next = temp self.count = self.count + 1 # mid points to first element self.mid = self.head # If the number of elements already present # are greater than 2 else: temp.next = self.mid.next self.mid.next = temp self.count = self.count + 1 # If number of elements after insertion # are odd if (self.count % 2 != 0): # mid points to the newly # inserted node self.mid = self.mid.next # Function to print the nodes # of the linked list def show(self): temp = None temp = self.head # Initializing temp to self.head # Iterating and printing till # The end of linked list # That is, till temp is None while (temp != None) : print( temp.value, end = \" -> \") temp = temp.next print( \"None\") # Driver code # Elements to be inserted one after anotherarr = [ 1, 2, 3, 4, 5]n = len(arr) L1 = LinkedList() # Insert the elementsfor i in range(n): L1.insertAtMiddle(arr[i]) # Print the nodes of the linked listL1.show() # This code is contributed by Arnab Kundu", "e": 8182, "s": 6172, "text": null }, { "code": "// C# implementation of the approachusing System; class GFG{ // Node urepublic class Node{ public int value; public Node next;}; // Class to represent a node// of the linked listpublic class LinkedList{ public Node head, mid; public int count; public LinkedList(){ head = null; mid = null; count = 0;} // Function to insert a node in// the middle of the linked listpublic void insertAtMiddle(int n){ Node temp = new Node(); Node temp1; temp.next = null; temp.value = n; // If the number of elements // already present are less than 2 if (count < 2) { if (head == null) { head = temp; } else { temp1 = head; temp1.next = temp; } count++; // mid points to first element mid = head; } // If the number of elements already present // are greater than 2 else { temp.next = mid.next; mid.next = temp; count++; // If number of elements after insertion // are odd if (count % 2 != 0) { // mid points to the newly // inserted node mid = mid.next; } }} // Function to print the nodes// of the linked listpublic void show(){ Node temp; temp = head; // Initializing temp to head // Iterating and printing till // The end of linked list // That is, till temp is null while (temp != null) { Console.Write( temp.value + \" -> \"); temp = temp.next; } Console.Write( \"null\"); Console.WriteLine();} } // Driver codepublic static void Main(String []args){ // Elements to be inserted one after another int []arr = { 1, 2, 3, 4, 5 }; int n = arr.Length; LinkedList L1=new LinkedList(); // Insert the elements for (int i = 0; i < n; i++) L1.insertAtMiddle(arr[i]); // Print the nodes of the linked list L1.show();}} // This code contributed by Rajput-Ji", "e": 10156, "s": 8182, "text": null }, { "code": "<script> // JavaScript implementation of the approach // Node ure class Node { constructor() { this.value = 0; this.next = null; } } // Class to represent a node // of the linked list class LinkedList { constructor() { this.head = null; this.mid = null; this.count = 0; } // Function to insert a node in // the middle of the linked list insertAtMiddle(n) { var temp = new Node(); var temp1; temp.next = null; temp.value = n; // If the number of elements // already present are less than 2 if (this.count < 2) { if (this.head == null) { this.head = temp; } else { temp1 = this.head; temp1.next = temp; } this.count++; // mid points to first element this.mid = this.head; } // If the number of elements already present // are greater than 2 else { temp.next = this.mid.next; this.mid.next = temp; this.count++; // If number of elements after insertion // are odd if (this.count % 2 != 0) { // mid points to the newly // inserted node this.mid = this.mid.next; } } } // Function to print the nodes // of the linked list show() { var temp; temp = this.head; // Initializing temp to head // Iterating and printing till // The end of linked list // That is, till temp is null while (temp != null) { document.write(temp.value + \" -> \"); temp = temp.next; } document.write(\"null\"); document.write(\"<br>\"); } } // Driver code // Elements to be inserted one after another var arr = [1, 2, 3, 4, 5]; var n = arr.length; var L1 = new LinkedList(); // Insert the elements for (var i = 0; i < n; i++) L1.insertAtMiddle(arr[i]); // Print the nodes of the linked list L1.show(); </script>", "e": 12405, "s": 10156, "text": null }, { "code": null, "e": 12435, "s": 12405, "text": "1 -> 3 -> 5 -> 4 -> 2 -> NULL" }, { "code": null, "e": 12519, "s": 12437, "text": "Time Complexity : O(N)Auxiliary Space: O(1), since no extra space has been taken." }, { "code": null, "e": 12530, "s": 12519, "text": "andrew1234" }, { "code": null, "e": 12540, "s": 12530, "text": "Rajput-Ji" }, { "code": null, "e": 12547, "s": 12540, "text": "rdtank" }, { "code": null, "e": 12563, "s": 12547, "text": "pankajsharmagfg" }, { "code": null, "e": 12574, "s": 12563, "text": "rishav1329" }, { "code": null, "e": 12590, "s": 12574, "text": "Data Structures" }, { "code": null, "e": 12602, "s": 12590, "text": "Linked List" }, { "code": null, "e": 12615, "s": 12602, "text": "Mathematical" }, { "code": null, "e": 12631, "s": 12615, "text": "Data Structures" }, { "code": null, "e": 12643, "s": 12631, "text": "Linked List" }, { "code": null, "e": 12656, "s": 12643, "text": "Mathematical" }, { "code": null, "e": 12754, "s": 12656, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 12779, "s": 12754, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 12828, "s": 12779, "text": "SDE SHEET - A Complete Guide for SDE Preparation" }, { "code": null, "e": 12860, "s": 12828, "text": "Introduction to Data Structures" }, { "code": null, "e": 12898, "s": 12860, "text": "What is Hashing | A Complete Tutorial" }, { "code": null, "e": 12934, "s": 12898, "text": "Introduction to Tree Data Structure" }, { "code": null, "e": 12956, "s": 12934, "text": "Reverse a linked list" }, { "code": null, "e": 13004, "s": 12956, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 13023, "s": 13004, "text": "LinkedList in Java" }, { "code": null, "e": 13055, "s": 13023, "text": "Introduction to Data Structures" } ]
How to create reflection effect using HTML and CSS ?
10 Jul, 2020 The reflection effect is one of the coolest effects that one can use in his/her website. It is a type of informal effect so it is highly recommended not to use it any professional project. You can use it in your personal projects and maybe your portfolio to show your creativity. In this effect, we try to imitate a realistic reflection effect like it is being reflected from water. Approach: The approach is to create a rotated string at the bottom of the original string and then changing its opacity and background to make it look like the reflection of the original string. Let us look at the implementation of the above approach. HTML Code: In this section, “h2” tag is created with the text wrapped in it. <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content= "width=device-width, initial-scale=1.0" /> <title> Text Reflection using HTML and CSS </title></head> <body> <h2 data-text="GeeksforGeeks"> GeeksforGeeks </h2></body> </html> CSS Code: Step 1: Apply a radial background which is lighter at the center and darker at the corners. Step 2: Apply some basic styling like size, color, etc to the heading. Step 3: Now use the after selector and rotate the original text on X-axis keeping the origin as bottom. Step 4: Apply “webkit” property to cut the rotated text into cuts. It will make the upperportion of the text visible , as shown in the output image. Step 5: Now apply the transparent color and decrease the opacity of the rotated text. Note: Make sure to decrease the opacity according to your background. If you are using a darkerbackground, decrease the opacity by 0.1-0.2 and if you are using a lighter background then decrease it by 0.6-0.8. <style> body { /* Radiel gradient defined by its center*/ background-image: radial-gradient(#013220,#008000); height: 100vh; } h2 { position: absolute; top: 30%; left: 30%; text-transform: capitalize; color: white; font-size: 50px; } h2::after { content: attr(data-text); position: absolute; top: 0; left: 0; /* Change the position of transformed element */ transform-origin: bottom; /* Rotates around x-axis */ transform: rotateX(180deg); line-height: 0.85em; /* linear-gradient defined by up,down,left ,right ,diagonal */ background-image: linear-gradient(0deg, #ffffff 0, transparent 95%); -webkit-background-clip: text; color: transparent; opacity: 0.7; } </style> Complete Code: It is the combination of the above two sections of code. <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Text Reflection using HTML and CSS</title> <style> body { /* Radiel gradient defined by its center*/ background-image: radial-gradient(#013220,#008000); height: 100vh; } h2 { position: absolute; top: 30%; left: 30%; text-transform: capitalize; color: white; font-size: 50px; } h2::after { content: attr(data-text); position: absolute; top: 0; left: 0; /* Change the position of transformed element */ transform-origin: bottom; /* Rotates around x-axis */ transform: rotateX(180deg); line-height: 0.85em; /* linear-gradient defined by up,down,left ,right ,diagonal */ background-image: linear-gradient(0deg, #ffffff 0, transparent 95%); -webkit-background-clip: text; color: transparent; opacity: 0.7; } </style> </head> <body> <h2 data-text="GeeksforGeeks">GeeksforGeeks</h2> </body></html> Output: CSS-Selectors CSS HTML HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to set space between the flexbox ? Design a Tribute Page using HTML & CSS Build a Survey Form using HTML and CSS Form validation using jQuery Design a web page using HTML and CSS REST API (Introduction) Hide or show elements in HTML using display property How to set the default value for an HTML <select> element ? How to set input type date in dd-mm-yyyy format using HTML ? HTTP headers | Content-Type
[ { "code": null, "e": 28, "s": 0, "text": "\n10 Jul, 2020" }, { "code": null, "e": 411, "s": 28, "text": "The reflection effect is one of the coolest effects that one can use in his/her website. It is a type of informal effect so it is highly recommended not to use it any professional project. You can use it in your personal projects and maybe your portfolio to show your creativity. In this effect, we try to imitate a realistic reflection effect like it is being reflected from water." }, { "code": null, "e": 663, "s": 411, "text": "Approach: The approach is to create a rotated string at the bottom of the original string and then changing its opacity and background to make it look like the reflection of the original string. Let us look at the implementation of the above approach." }, { "code": null, "e": 740, "s": 663, "text": "HTML Code: In this section, “h2” tag is created with the text wrapped in it." }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\" /> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\" /> <title> Text Reflection using HTML and CSS </title></head> <body> <h2 data-text=\"GeeksforGeeks\"> GeeksforGeeks </h2></body> </html>", "e": 1070, "s": 740, "text": null }, { "code": null, "e": 1080, "s": 1070, "text": "CSS Code:" }, { "code": null, "e": 1172, "s": 1080, "text": "Step 1: Apply a radial background which is lighter at the center and darker at the corners." }, { "code": null, "e": 1243, "s": 1172, "text": "Step 2: Apply some basic styling like size, color, etc to the heading." }, { "code": null, "e": 1347, "s": 1243, "text": "Step 3: Now use the after selector and rotate the original text on X-axis keeping the origin as bottom." }, { "code": null, "e": 1496, "s": 1347, "text": "Step 4: Apply “webkit” property to cut the rotated text into cuts. It will make the upperportion of the text visible , as shown in the output image." }, { "code": null, "e": 1582, "s": 1496, "text": "Step 5: Now apply the transparent color and decrease the opacity of the rotated text." }, { "code": null, "e": 1792, "s": 1582, "text": "Note: Make sure to decrease the opacity according to your background. If you are using a darkerbackground, decrease the opacity by 0.1-0.2 and if you are using a lighter background then decrease it by 0.6-0.8." }, { "code": "<style> body { /* Radiel gradient defined by its center*/ background-image: radial-gradient(#013220,#008000); height: 100vh; } h2 { position: absolute; top: 30%; left: 30%; text-transform: capitalize; color: white; font-size: 50px; } h2::after { content: attr(data-text); position: absolute; top: 0; left: 0; /* Change the position of transformed element */ transform-origin: bottom; /* Rotates around x-axis */ transform: rotateX(180deg); line-height: 0.85em; /* linear-gradient defined by up,down,left ,right ,diagonal */ background-image: linear-gradient(0deg, #ffffff 0, transparent 95%); -webkit-background-clip: text; color: transparent; opacity: 0.7; } </style>", "e": 2653, "s": 1792, "text": null }, { "code": null, "e": 2725, "s": 2653, "text": "Complete Code: It is the combination of the above two sections of code." }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\" /> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" /> <title>Text Reflection using HTML and CSS</title> <style> body { /* Radiel gradient defined by its center*/ background-image: radial-gradient(#013220,#008000); height: 100vh; } h2 { position: absolute; top: 30%; left: 30%; text-transform: capitalize; color: white; font-size: 50px; } h2::after { content: attr(data-text); position: absolute; top: 0; left: 0; /* Change the position of transformed element */ transform-origin: bottom; /* Rotates around x-axis */ transform: rotateX(180deg); line-height: 0.85em; /* linear-gradient defined by up,down,left ,right ,diagonal */ background-image: linear-gradient(0deg, #ffffff 0, transparent 95%); -webkit-background-clip: text; color: transparent; opacity: 0.7; } </style> </head> <body> <h2 data-text=\"GeeksforGeeks\">GeeksforGeeks</h2> </body></html>", "e": 3878, "s": 2725, "text": null }, { "code": null, "e": 3886, "s": 3878, "text": "Output:" }, { "code": null, "e": 3900, "s": 3886, "text": "CSS-Selectors" }, { "code": null, "e": 3904, "s": 3900, "text": "CSS" }, { "code": null, "e": 3909, "s": 3904, "text": "HTML" }, { "code": null, "e": 3914, "s": 3909, "text": "HTML" }, { "code": null, "e": 4012, "s": 3914, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4051, "s": 4012, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 4090, "s": 4051, "text": "Design a Tribute Page using HTML & CSS" }, { "code": null, "e": 4129, "s": 4090, "text": "Build a Survey Form using HTML and CSS" }, { "code": null, "e": 4158, "s": 4129, "text": "Form validation using jQuery" }, { "code": null, "e": 4195, "s": 4158, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 4219, "s": 4195, "text": "REST API (Introduction)" }, { "code": null, "e": 4272, "s": 4219, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 4332, "s": 4272, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 4393, "s": 4332, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" } ]
turtle.backward() method in Python
16 Jul, 2020 The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses Tkinter for the underlying graphics, it needs a version of Python installed with Tk support. The turtle.backward() method is used to move the turtle backward by the value of the argument that it takes. It gives a line on moving to another position or direction with backward motion. Syntax: turtle.backward(distance) The argument it takes is distance { a number (integer or float) }. So, it moves the turtle backward by the specified distance, in the opposite direction the turtle is headed. Below is the implementation of the above method with some examples : Example 1: Python3 # importing packagesimport turtle # move turtle backward with # distance = 100turtle.backward(100) Output : Example 2: Python3 # importing packageimport turtle # move the turtle backward by 50turtle.backward(50) # change the directionturtle.right(90) # move the turtle backward by 50 againturtle.backward(50) Output : Python-turtle Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n16 Jul, 2020" }, { "code": null, "e": 245, "s": 28, "text": "The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses Tkinter for the underlying graphics, it needs a version of Python installed with Tk support." }, { "code": null, "e": 435, "s": 245, "text": "The turtle.backward() method is used to move the turtle backward by the value of the argument that it takes. It gives a line on moving to another position or direction with backward motion." }, { "code": null, "e": 443, "s": 435, "text": "Syntax:" }, { "code": null, "e": 470, "s": 443, "text": "turtle.backward(distance)\n" }, { "code": null, "e": 714, "s": 470, "text": "The argument it takes is distance { a number (integer or float) }. So, it moves the turtle backward by the specified distance, in the opposite direction the turtle is headed. Below is the implementation of the above method with some examples :" }, { "code": null, "e": 725, "s": 714, "text": "Example 1:" }, { "code": null, "e": 733, "s": 725, "text": "Python3" }, { "code": "# importing packagesimport turtle # move turtle backward with # distance = 100turtle.backward(100)", "e": 835, "s": 733, "text": null }, { "code": null, "e": 844, "s": 835, "text": "Output :" }, { "code": null, "e": 855, "s": 844, "text": "Example 2:" }, { "code": null, "e": 863, "s": 855, "text": "Python3" }, { "code": "# importing packageimport turtle # move the turtle backward by 50turtle.backward(50) # change the directionturtle.right(90) # move the turtle backward by 50 againturtle.backward(50)", "e": 1050, "s": 863, "text": null }, { "code": null, "e": 1059, "s": 1050, "text": "Output :" }, { "code": null, "e": 1073, "s": 1059, "text": "Python-turtle" }, { "code": null, "e": 1080, "s": 1073, "text": "Python" } ]
Overview of Data Science
26 Apr, 2022 Data science is the study of data. Like biological sciences is a study of biology, physical sciences, it’s the study of physical reactions. Data is real, data has real properties, and we need to study them if we’re going to work on them. Data Science involves data and some signs. It is a process, not an event. It is the process of using data to understand too many different things, to understand the world. Let Suppose when you have a model or proposed explanation of a problem, and you try to validate that proposed explanation or model with your data. It is the skill of unfolding the insights and trends that are hiding (or abstract) behind data. It’s when you translate data into a story. So use storytelling to generate insight. And with these insights, you can make strategic choices for a company or an institution. We can also define data science as a field that is about processes and systems to extract data of various forms and from various resources whether the data is unstructured or structured. The definition and the name came up in the 1980s and 1990s when some professors, IT Professionals, scientists were looking into the statistics curriculum, and they thought it would be better to call it data science and then later on data analytics derived. But the biggest question and confusion in the world is what is Data Science? we’d see data science as one and from one to many attempts to work with data, to find answers to questions that they are exploring. On summarizing all, we can say that it’s much more about data than about science. If you have proper or improper data, and you have curiosity for working with data, and you’re manipulating it according to your needs, you’re exploring it according to your needs, the very exercise of going through analyzing data, trying to get some answers or fulfill the society need from your explored, manipulated and exercised Data – it is Data Science. Data Science is relevant today because we have millions of data available on single data or for single data. We didn’t use to worry about the lack of data. Now we have tons of data. In the past, we didn’t have defined algorithms, now we have algorithms. In the past, the software was not affordable by everyone because it was too expensive, so only industries with big-bucks can use it but now it is open source and freely available. In the past, we didn’t even think about storing a large amount of data, because the storage facilities are also very costly and now it is available for a fraction of a cost, we can have gazillions of data sets for a very low cost. Also, internet connectivity was not common and too costly. So, the tools to work with data, the variability of data, the ability to store, analyze data and last and most important Connectivity, it’s all cheap, it’s all available, it’s all ubiquitous, it’s here. There’s never been a better time to be a data scientist than now. Following are some of the applications that makes use of Data Science for it’s services: Internet Search Results (Google) Recommendation Engine (Spotify) Intelligent Digital Assistants (Google Assistant) Autonomous Driving Vehicle (Waymo) Spam Filter (Gmail) Abusive Content and Hate Speech Filter (Facebook) Robotics (Boston Dynamics) Automatic Piracy Detection (YouTube) Is he/she someone struggling with data all day and night or experimenting in his/her laboratory with complex mathematics? After all, ‘Who is a Data Scientist’? There are many definitions available in the market for Data Scientists. In simple words, a Data Scientist is one who knows and practices the art of Data Science. The super-popular term ‘Data Scientist’ was coined by DJ Patil and Jeff Hammerbacher. Data Scientists are those scientists who crack complex data problems with their strong expertise in certain scientific disciplines. They work with many elements related to mathematics, statistics, probability, Quantitative and Qualitative forecasting, computer science, etc. (though they may not be an expert in all these fields). We can say that Data Scientists are Business Analysts and Data Analysts, with a difference!. Though the initial training or basic requirements are similar for all these disciplines, Data Scientists require: Strong Business Acumen Strong Communication Skills Exploring Big Data Just like an agricultural scientist wants to know the percentage increase in the yield of wheat this year as compared to last year’s (also the reasons associated with it) or if a financial company wants to classify its customers based on their creditworthiness (before granting loans) or whether a retail organization wants to reward extra points to its loyal customers, all need data scientists to process a large volume of both structured and unstructured data in order to make crucial business decisions. In today’s dynamic and vast world, the main challenge that today’s Data Scientists face is to find solutions to the existing business problems and above it, to identify the problems that are most relevant and crucial to the organization and its success. The term “Data Scientist” has been in existence after considering the fact that a Data Scientist collects a huge amount of information from the scientific fields and applications whether the information is statistical, mathematical, or computer science. They make use of the latest technologies and tools in finding the solutions and reaching the conclusions that are important for an organization’s growth and development. Data Scientists present the data in a much more useful form as compared to the raw data available to them from structured as well as unstructured forms. Just like any other scientific piece of training, data scientists always need to ask and find answers of What, How Who, and Why that data is available to them. They are required to make a clearly defined plan and work towards achieving the results within a limited time, effort and money. naveenkumarkharwal data-science Machine Learning Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n26 Apr, 2022" }, { "code": null, "e": 336, "s": 54, "text": "Data science is the study of data. Like biological sciences is a study of biology, physical sciences, it’s the study of physical reactions. Data is real, data has real properties, and we need to study them if we’re going to work on them. Data Science involves data and some signs. " }, { "code": null, "e": 613, "s": 336, "text": "It is a process, not an event. It is the process of using data to understand too many different things, to understand the world. Let Suppose when you have a model or proposed explanation of a problem, and you try to validate that proposed explanation or model with your data. " }, { "code": null, "e": 883, "s": 613, "text": "It is the skill of unfolding the insights and trends that are hiding (or abstract) behind data. It’s when you translate data into a story. So use storytelling to generate insight. And with these insights, you can make strategic choices for a company or an institution. " }, { "code": null, "e": 1328, "s": 883, "text": "We can also define data science as a field that is about processes and systems to extract data of various forms and from various resources whether the data is unstructured or structured. The definition and the name came up in the 1980s and 1990s when some professors, IT Professionals, scientists were looking into the statistics curriculum, and they thought it would be better to call it data science and then later on data analytics derived. " }, { "code": null, "e": 1979, "s": 1328, "text": "But the biggest question and confusion in the world is what is Data Science? we’d see data science as one and from one to many attempts to work with data, to find answers to questions that they are exploring. On summarizing all, we can say that it’s much more about data than about science. If you have proper or improper data, and you have curiosity for working with data, and you’re manipulating it according to your needs, you’re exploring it according to your needs, the very exercise of going through analyzing data, trying to get some answers or fulfill the society need from your explored, manipulated and exercised Data – it is Data Science. " }, { "code": null, "e": 2973, "s": 1979, "text": "Data Science is relevant today because we have millions of data available on single data or for single data. We didn’t use to worry about the lack of data. Now we have tons of data. In the past, we didn’t have defined algorithms, now we have algorithms. In the past, the software was not affordable by everyone because it was too expensive, so only industries with big-bucks can use it but now it is open source and freely available. In the past, we didn’t even think about storing a large amount of data, because the storage facilities are also very costly and now it is available for a fraction of a cost, we can have gazillions of data sets for a very low cost. Also, internet connectivity was not common and too costly. So, the tools to work with data, the variability of data, the ability to store, analyze data and last and most important Connectivity, it’s all cheap, it’s all available, it’s all ubiquitous, it’s here. There’s never been a better time to be a data scientist than now. " }, { "code": null, "e": 3062, "s": 2973, "text": "Following are some of the applications that makes use of Data Science for it’s services:" }, { "code": null, "e": 3095, "s": 3062, "text": "Internet Search Results (Google)" }, { "code": null, "e": 3127, "s": 3095, "text": "Recommendation Engine (Spotify)" }, { "code": null, "e": 3177, "s": 3127, "text": "Intelligent Digital Assistants (Google Assistant)" }, { "code": null, "e": 3212, "s": 3177, "text": "Autonomous Driving Vehicle (Waymo)" }, { "code": null, "e": 3232, "s": 3212, "text": "Spam Filter (Gmail)" }, { "code": null, "e": 3282, "s": 3232, "text": "Abusive Content and Hate Speech Filter (Facebook)" }, { "code": null, "e": 3309, "s": 3282, "text": "Robotics (Boston Dynamics)" }, { "code": null, "e": 3346, "s": 3309, "text": "Automatic Piracy Detection (YouTube)" }, { "code": null, "e": 3507, "s": 3346, "text": "Is he/she someone struggling with data all day and night or experimenting in his/her laboratory with complex mathematics? After all, ‘Who is a Data Scientist’? " }, { "code": null, "e": 4087, "s": 3507, "text": "There are many definitions available in the market for Data Scientists. In simple words, a Data Scientist is one who knows and practices the art of Data Science. The super-popular term ‘Data Scientist’ was coined by DJ Patil and Jeff Hammerbacher. Data Scientists are those scientists who crack complex data problems with their strong expertise in certain scientific disciplines. They work with many elements related to mathematics, statistics, probability, Quantitative and Qualitative forecasting, computer science, etc. (though they may not be an expert in all these fields). " }, { "code": null, "e": 4297, "s": 4089, "text": "We can say that Data Scientists are Business Analysts and Data Analysts, with a difference!. Though the initial training or basic requirements are similar for all these disciplines, Data Scientists require: " }, { "code": null, "e": 4320, "s": 4297, "text": "Strong Business Acumen" }, { "code": null, "e": 4348, "s": 4320, "text": "Strong Communication Skills" }, { "code": null, "e": 4367, "s": 4348, "text": "Exploring Big Data" }, { "code": null, "e": 4876, "s": 4367, "text": "Just like an agricultural scientist wants to know the percentage increase in the yield of wheat this year as compared to last year’s (also the reasons associated with it) or if a financial company wants to classify its customers based on their creditworthiness (before granting loans) or whether a retail organization wants to reward extra points to its loyal customers, all need data scientists to process a large volume of both structured and unstructured data in order to make crucial business decisions. " }, { "code": null, "e": 5131, "s": 4876, "text": "In today’s dynamic and vast world, the main challenge that today’s Data Scientists face is to find solutions to the existing business problems and above it, to identify the problems that are most relevant and crucial to the organization and its success. " }, { "code": null, "e": 5709, "s": 5131, "text": "The term “Data Scientist” has been in existence after considering the fact that a Data Scientist collects a huge amount of information from the scientific fields and applications whether the information is statistical, mathematical, or computer science. They make use of the latest technologies and tools in finding the solutions and reaching the conclusions that are important for an organization’s growth and development. Data Scientists present the data in a much more useful form as compared to the raw data available to them from structured as well as unstructured forms. " }, { "code": null, "e": 5999, "s": 5709, "text": "Just like any other scientific piece of training, data scientists always need to ask and find answers of What, How Who, and Why that data is available to them. They are required to make a clearly defined plan and work towards achieving the results within a limited time, effort and money. " }, { "code": null, "e": 6018, "s": 5999, "text": "naveenkumarkharwal" }, { "code": null, "e": 6031, "s": 6018, "text": "data-science" }, { "code": null, "e": 6048, "s": 6031, "text": "Machine Learning" }, { "code": null, "e": 6065, "s": 6048, "text": "Machine Learning" } ]
Unused variable in for loop in Python
01 Oct, 2020 Prerequisite: Python For loops The for loop has a loop variable that controls the iteration. Not all the loops utilize the loop variable inside the process carried out in the loop. Example: Python3 # i,j - loop variable # loop-1print("Using the loop variable inside :") # used loop variablefor i in range(0, 5): x = (i+1)*2 print(x, end=" ") # loop-2print("\nUsing the loop variable only for iteration :") # unsused loop variablefor j in range(0, 5): print('*', end=" ") Using the loop variable inside : 2 4 6 8 10 Using the loop variable only for iteration : * * * * * In the code snippet above, in loop-1, the loop control variable ‘i‘ is used inside the loop for computation. But in loop-2, the loop control variable ‘j‘ is concerned only with keeping tracking of the iteration number. Thus, ‘j’ is an unused variable in for loop. It is good practice to avoid declaring variables that are of no use. Some IDEs like Pycharm, PyDev, VSCode produce warning messages for such unused variables in the looping structure. The warning may look like something given below: To avoid such warnings, the convention of naming the unused variable with an underscore(‘_’) alone can be used. This avoids the problem of unused variables in for loops. Consider the following script with an unused loop variable tested with the Vulture module in Python. Once the vulture module is installed using the pip command, it can be used for testing .py scripts in the anaconda prompt. Example: trial1.py Python3 # unused functiondef my_func(): # unused local variable a = 5 b = 2 c = b+2 print(b, c) # unused loop variable 'i'for i in range(0, 5): print("*", end=" ") * * * * * To avoid this unused variable ‘i’ warning, the loop variable can simply be replaced by an underscore (‘_’). Look at the code snippet below Python3 # unused functiondef my_func(): b = 2 c = b+2 print(b, c) # unused loop variable 'i'for _ in range(0, 5): print("*", end=" ") Some use pylint, a tool to keep track of code styles and dead code in Python. Such a tool can raise a warning when the variable in for loop is not used. To suppress that, it is better to use the underscore naming conventions for the unused variables. python-basics Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Python | os.path.join() method Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python | Get unique values from a list Create a directory in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n01 Oct, 2020" }, { "code": null, "e": 59, "s": 28, "text": "Prerequisite: Python For loops" }, { "code": null, "e": 211, "s": 59, "text": "The for loop has a loop variable that controls the iteration. Not all the loops utilize the loop variable inside the process carried out in the loop. " }, { "code": null, "e": 220, "s": 211, "text": "Example:" }, { "code": null, "e": 228, "s": 220, "text": "Python3" }, { "code": "# i,j - loop variable # loop-1print(\"Using the loop variable inside :\") # used loop variablefor i in range(0, 5): x = (i+1)*2 print(x, end=\" \") # loop-2print(\"\\nUsing the loop variable only for iteration :\") # unsused loop variablefor j in range(0, 5): print('*', end=\" \")", "e": 518, "s": 228, "text": null }, { "code": null, "e": 619, "s": 518, "text": "Using the loop variable inside :\n2 4 6 8 10 \nUsing the loop variable only for iteration :\n* * * * * " }, { "code": null, "e": 1117, "s": 619, "text": "In the code snippet above, in loop-1, the loop control variable ‘i‘ is used inside the loop for computation. But in loop-2, the loop control variable ‘j‘ is concerned only with keeping tracking of the iteration number. Thus, ‘j’ is an unused variable in for loop. It is good practice to avoid declaring variables that are of no use. Some IDEs like Pycharm, PyDev, VSCode produce warning messages for such unused variables in the looping structure. The warning may look like something given below:" }, { "code": null, "e": 1512, "s": 1117, "text": "To avoid such warnings, the convention of naming the unused variable with an underscore(‘_’) alone can be used. This avoids the problem of unused variables in for loops. Consider the following script with an unused loop variable tested with the Vulture module in Python. Once the vulture module is installed using the pip command, it can be used for testing .py scripts in the anaconda prompt. " }, { "code": null, "e": 1531, "s": 1512, "text": "Example: trial1.py" }, { "code": null, "e": 1539, "s": 1531, "text": "Python3" }, { "code": "# unused functiondef my_func(): # unused local variable a = 5 b = 2 c = b+2 print(b, c) # unused loop variable 'i'for i in range(0, 5): print(\"*\", end=\" \")", "e": 1718, "s": 1539, "text": null }, { "code": null, "e": 1729, "s": 1718, "text": "* * * * * " }, { "code": null, "e": 1868, "s": 1729, "text": "To avoid this unused variable ‘i’ warning, the loop variable can simply be replaced by an underscore (‘_’). Look at the code snippet below" }, { "code": null, "e": 1876, "s": 1868, "text": "Python3" }, { "code": "# unused functiondef my_func(): b = 2 c = b+2 print(b, c) # unused loop variable 'i'for _ in range(0, 5): print(\"*\", end=\" \")", "e": 2017, "s": 1876, "text": null }, { "code": null, "e": 2268, "s": 2017, "text": "Some use pylint, a tool to keep track of code styles and dead code in Python. Such a tool can raise a warning when the variable in for loop is not used. To suppress that, it is better to use the underscore naming conventions for the unused variables." }, { "code": null, "e": 2282, "s": 2268, "text": "python-basics" }, { "code": null, "e": 2289, "s": 2282, "text": "Python" }, { "code": null, "e": 2387, "s": 2289, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2419, "s": 2387, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2446, "s": 2419, "text": "Python Classes and Objects" }, { "code": null, "e": 2467, "s": 2446, "text": "Python OOPs Concepts" }, { "code": null, "e": 2490, "s": 2467, "text": "Introduction To PYTHON" }, { "code": null, "e": 2546, "s": 2490, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 2577, "s": 2546, "text": "Python | os.path.join() method" }, { "code": null, "e": 2619, "s": 2577, "text": "Check if element exists in list in Python" }, { "code": null, "e": 2661, "s": 2619, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 2700, "s": 2661, "text": "Python | Get unique values from a list" } ]
IntStream mapToObj() in Java
06 Dec, 2018 IntStream mapToObj() returns an object-valued Stream consisting of the results of applying the given function. Note : IntStream mapToObj() is a intermediate operation. These operations are always lazy. Intermediate operations are invoked on a Stream instance and after they finish their processing, they give a Stream instance as output.Syntax : <U> Stream<U> mapToObj(IntFunction<? extends U> mapper) Parameters : U : The element type of the new stream.Stream : A sequence of elements supporting sequential and parallel aggregate operations.IntFunction : Represents a function that accepts an int-valued argument and produces a result.mapper : A stateless function to apply to each element. U : The element type of the new stream. Stream : A sequence of elements supporting sequential and parallel aggregate operations. IntFunction : Represents a function that accepts an int-valued argument and produces a result. mapper : A stateless function to apply to each element. Return Value : The function returns an object-valued Stream consisting of the results of applying the given function. Example 1 : // Java code for IntStream mapToObj// (IntFunction mapper)import java.util.*;import java.util.stream.Stream;import java.util.stream.IntStream; class GFG { // Driver code public static void main(String[] args) { // Creating an IntStream IntStream stream = IntStream.range(3, 8); // Creating a Stream of Strings // Using IntStream mapToObj(IntFunction mapper) // to store binary representation of // elements in IntStream Stream<String> stream1 = stream.mapToObj(num -> Integer.toBinaryString(num)); // Displaying an object-valued Stream // consisting of the results of // applying the given function. stream1.forEach(System.out::println); }} Output : 11 100 101 110 111 Example 2 : // Java code for IntStream mapToObj// (IntFunction mapper)import java.util.*; import java.math.BigInteger;import java.util.stream.Stream;import java.util.stream.IntStream; class GFG { // Driver code public static void main(String[] args) { // Creating an IntStream IntStream stream = IntStream.of(3, 5, 7, 9, 11); // Creating a Stream // Using IntStream mapToObj(IntFunction mapper) Stream<BigInteger> stream1 = stream .mapToObj(BigInteger::valueOf); // Displaying an object-valued Stream // consisting of the results of // applying the given function. stream1.forEach(num -> System.out.println(num.add(BigInteger.TEN))); }} Output : 13 15 17 19 21 Java - util package Java-Functions java-intstream java-stream Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java How to iterate any Map in Java Interfaces in Java HashMap in Java with Examples ArrayList in Java Collections in Java Multidimensional Arrays in Java Singleton Class in Java Stack Class in Java Set in Java
[ { "code": null, "e": 52, "s": 24, "text": "\n06 Dec, 2018" }, { "code": null, "e": 163, "s": 52, "text": "IntStream mapToObj() returns an object-valued Stream consisting of the results of applying the given function." }, { "code": null, "e": 398, "s": 163, "text": "Note : IntStream mapToObj() is a intermediate operation. These operations are always lazy. Intermediate operations are invoked on a Stream instance and after they finish their processing, they give a Stream instance as output.Syntax :" }, { "code": null, "e": 455, "s": 398, "text": "<U> Stream<U> mapToObj(IntFunction<? extends U> mapper)\n" }, { "code": null, "e": 468, "s": 455, "text": "Parameters :" }, { "code": null, "e": 745, "s": 468, "text": "U : The element type of the new stream.Stream : A sequence of elements supporting sequential and parallel aggregate operations.IntFunction : Represents a function that accepts an int-valued argument and produces a result.mapper : A stateless function to apply to each element." }, { "code": null, "e": 785, "s": 745, "text": "U : The element type of the new stream." }, { "code": null, "e": 874, "s": 785, "text": "Stream : A sequence of elements supporting sequential and parallel aggregate operations." }, { "code": null, "e": 969, "s": 874, "text": "IntFunction : Represents a function that accepts an int-valued argument and produces a result." }, { "code": null, "e": 1025, "s": 969, "text": "mapper : A stateless function to apply to each element." }, { "code": null, "e": 1143, "s": 1025, "text": "Return Value : The function returns an object-valued Stream consisting of the results of applying the given function." }, { "code": null, "e": 1155, "s": 1143, "text": "Example 1 :" }, { "code": "// Java code for IntStream mapToObj// (IntFunction mapper)import java.util.*;import java.util.stream.Stream;import java.util.stream.IntStream; class GFG { // Driver code public static void main(String[] args) { // Creating an IntStream IntStream stream = IntStream.range(3, 8); // Creating a Stream of Strings // Using IntStream mapToObj(IntFunction mapper) // to store binary representation of // elements in IntStream Stream<String> stream1 = stream.mapToObj(num -> Integer.toBinaryString(num)); // Displaying an object-valued Stream // consisting of the results of // applying the given function. stream1.forEach(System.out::println); }}", "e": 1940, "s": 1155, "text": null }, { "code": null, "e": 1949, "s": 1940, "text": "Output :" }, { "code": null, "e": 1969, "s": 1949, "text": "11\n100\n101\n110\n111\n" }, { "code": null, "e": 1981, "s": 1969, "text": "Example 2 :" }, { "code": "// Java code for IntStream mapToObj// (IntFunction mapper)import java.util.*; import java.math.BigInteger;import java.util.stream.Stream;import java.util.stream.IntStream; class GFG { // Driver code public static void main(String[] args) { // Creating an IntStream IntStream stream = IntStream.of(3, 5, 7, 9, 11); // Creating a Stream // Using IntStream mapToObj(IntFunction mapper) Stream<BigInteger> stream1 = stream .mapToObj(BigInteger::valueOf); // Displaying an object-valued Stream // consisting of the results of // applying the given function. stream1.forEach(num -> System.out.println(num.add(BigInteger.TEN))); }}", "e": 2729, "s": 1981, "text": null }, { "code": null, "e": 2738, "s": 2729, "text": "Output :" }, { "code": null, "e": 2754, "s": 2738, "text": "13\n15\n17\n19\n21\n" }, { "code": null, "e": 2774, "s": 2754, "text": "Java - util package" }, { "code": null, "e": 2789, "s": 2774, "text": "Java-Functions" }, { "code": null, "e": 2804, "s": 2789, "text": "java-intstream" }, { "code": null, "e": 2816, "s": 2804, "text": "java-stream" }, { "code": null, "e": 2821, "s": 2816, "text": "Java" }, { "code": null, "e": 2826, "s": 2821, "text": "Java" }, { "code": null, "e": 2924, "s": 2826, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2975, "s": 2924, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 3006, "s": 2975, "text": "How to iterate any Map in Java" }, { "code": null, "e": 3025, "s": 3006, "text": "Interfaces in Java" }, { "code": null, "e": 3055, "s": 3025, "text": "HashMap in Java with Examples" }, { "code": null, "e": 3073, "s": 3055, "text": "ArrayList in Java" }, { "code": null, "e": 3093, "s": 3073, "text": "Collections in Java" }, { "code": null, "e": 3125, "s": 3093, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 3149, "s": 3125, "text": "Singleton Class in Java" }, { "code": null, "e": 3169, "s": 3149, "text": "Stack Class in Java" } ]
Pyspark – Converting JSON to DataFrame
29 Jun, 2021 In this article, we are going to convert JSON String to DataFrame in Pyspark. Method 1: Using read_json() We can read JSON files using pandas.read_json. This method is basically used to read JSON files through pandas. Syntax: pandas.read_json(“file_name.json”) Here we are going to use this JSON file for demonstration: Code: Python3 # import pandas to read json fileimport pandas as pd # importing moduleimport pyspark # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # creating a dataframe from the json file named studentdataframe = spark.createDataFrame(pd.read_json('student.json')) # display the dataframe (Pyspark dataframe)dataframe.show() Output: Method 2: Using spark.read.json() This is used to read a json data from a file and display the data in the form of a dataframe Syntax: spark.read.json(‘file_name.json’) JSON file for demonstration: Code: Python3 # importing moduleimport pyspark # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # read json filedata = spark.read.json('college.json') # display json datadata.show() Output: Picked Python-Pyspark Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON Python | os.path.join() method How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Get unique values from a list Python | datetime.timedelta() function
[ { "code": null, "e": 28, "s": 0, "text": "\n29 Jun, 2021" }, { "code": null, "e": 106, "s": 28, "text": "In this article, we are going to convert JSON String to DataFrame in Pyspark." }, { "code": null, "e": 134, "s": 106, "text": "Method 1: Using read_json()" }, { "code": null, "e": 246, "s": 134, "text": "We can read JSON files using pandas.read_json. This method is basically used to read JSON files through pandas." }, { "code": null, "e": 289, "s": 246, "text": "Syntax: pandas.read_json(“file_name.json”)" }, { "code": null, "e": 348, "s": 289, "text": "Here we are going to use this JSON file for demonstration:" }, { "code": null, "e": 354, "s": 348, "text": "Code:" }, { "code": null, "e": 362, "s": 354, "text": "Python3" }, { "code": "# import pandas to read json fileimport pandas as pd # importing moduleimport pyspark # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # creating a dataframe from the json file named studentdataframe = spark.createDataFrame(pd.read_json('student.json')) # display the dataframe (Pyspark dataframe)dataframe.show()", "e": 827, "s": 362, "text": null }, { "code": null, "e": 835, "s": 827, "text": "Output:" }, { "code": null, "e": 869, "s": 835, "text": "Method 2: Using spark.read.json()" }, { "code": null, "e": 962, "s": 869, "text": "This is used to read a json data from a file and display the data in the form of a dataframe" }, { "code": null, "e": 1004, "s": 962, "text": "Syntax: spark.read.json(‘file_name.json’)" }, { "code": null, "e": 1033, "s": 1004, "text": "JSON file for demonstration:" }, { "code": null, "e": 1039, "s": 1033, "text": "Code:" }, { "code": null, "e": 1047, "s": 1039, "text": "Python3" }, { "code": "# importing moduleimport pyspark # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # read json filedata = spark.read.json('college.json') # display json datadata.show()", "e": 1363, "s": 1047, "text": null }, { "code": null, "e": 1371, "s": 1363, "text": "Output:" }, { "code": null, "e": 1378, "s": 1371, "text": "Picked" }, { "code": null, "e": 1393, "s": 1378, "text": "Python-Pyspark" }, { "code": null, "e": 1400, "s": 1393, "text": "Python" }, { "code": null, "e": 1498, "s": 1400, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1530, "s": 1498, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1557, "s": 1530, "text": "Python Classes and Objects" }, { "code": null, "e": 1578, "s": 1557, "text": "Python OOPs Concepts" }, { "code": null, "e": 1601, "s": 1578, "text": "Introduction To PYTHON" }, { "code": null, "e": 1632, "s": 1601, "text": "Python | os.path.join() method" }, { "code": null, "e": 1688, "s": 1632, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 1730, "s": 1688, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 1772, "s": 1730, "text": "Check if element exists in list in Python" }, { "code": null, "e": 1811, "s": 1772, "text": "Python | Get unique values from a list" } ]
Matplotlib.colors.to_hex() in Python
21 Apr, 2020 Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack. The matplotlib.colors.to_hex() function is used to convert numbers between 0 to 1 into hex color code. It uses the #rrggbb format if keep_alpha is set to False(its also the default) else it uses #rrggbbaa. Syntax: matplotlib.colors.to_hex(c, keep_alpha=False) Parameters: c: This represents an array of color sequence between 0 to 1.keep_alpha: If set True uses #rrggbbaa format else uses #rrggbb format and it only accepts boolean values. c: This represents an array of color sequence between 0 to 1. keep_alpha: If set True uses #rrggbbaa format else uses #rrggbb format and it only accepts boolean values. Example 1: import matplotlib.pyplot as pltfrom matplotlib import colorsimport numpy as np # dummy data to build the griddata = np.random.rand(10, 10) * 20 # converting into hex color codehex_color=matplotlib.colors.to_hex([ 0.47, 0.0, 1.0 ]) # create discrete colormapcmap = colors.ListedColormap([hex_color, 'green']) bounds = [0,10,20]norm = colors.BoundaryNorm(bounds, cmap.N) fig, ax = plt.subplots()ax.imshow(data, cmap=cmap, norm=norm) # draw gridlinesax.grid(which='major', axis='both', linestyle='-', color='k', linewidth=2) ax.set_xticks(np.arange(-.5, 10, 1));ax.set_yticks(np.arange(-.5, 10, 1)); plt.show() Output: Example 2: import matplotlib.pyplot as pltfrom matplotlib import colorsimport numpy as np # dummy data to build the griddata = np.random.rand(10, 10) * 20 # converting into hex color# code with alpha set to Truehex_color = matplotlib.colors.to_hex([ 0.47, 0.0, 1.0, 0.5 ], keep_alpha = True) # create discrete colormapcmap = colors.ListedColormap([hex_color, 'red']) bounds = [0, 10, 20]norm = colors.BoundaryNorm(bounds, cmap.N) fig, ax = plt.subplots()ax.imshow(data, cmap = cmap, norm = norm) # draw gridlinesax.grid(which ='major', axis ='both', linestyle ='-', color ='k', linewidth = 2) ax.set_xticks(np.arange(-.5, 10, 1));ax.set_yticks(np.arange(-.5, 10, 1)); plt.show() Output: Python-matplotlib Python Write From Home Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() Convert integer to string in Python Convert string to integer in Python How to set input type date in dd-mm-yyyy format using HTML ? Python infinity Similarities and Difference between Java and C++
[ { "code": null, "e": 28, "s": 0, "text": "\n21 Apr, 2020" }, { "code": null, "e": 240, "s": 28, "text": "Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack." }, { "code": null, "e": 446, "s": 240, "text": "The matplotlib.colors.to_hex() function is used to convert numbers between 0 to 1 into hex color code. It uses the #rrggbb format if keep_alpha is set to False(its also the default) else it uses #rrggbbaa." }, { "code": null, "e": 500, "s": 446, "text": "Syntax: matplotlib.colors.to_hex(c, keep_alpha=False)" }, { "code": null, "e": 512, "s": 500, "text": "Parameters:" }, { "code": null, "e": 680, "s": 512, "text": "c: This represents an array of color sequence between 0 to 1.keep_alpha: If set True uses #rrggbbaa format else uses #rrggbb format and it only accepts boolean values." }, { "code": null, "e": 742, "s": 680, "text": "c: This represents an array of color sequence between 0 to 1." }, { "code": null, "e": 849, "s": 742, "text": "keep_alpha: If set True uses #rrggbbaa format else uses #rrggbb format and it only accepts boolean values." }, { "code": null, "e": 860, "s": 849, "text": "Example 1:" }, { "code": "import matplotlib.pyplot as pltfrom matplotlib import colorsimport numpy as np # dummy data to build the griddata = np.random.rand(10, 10) * 20 # converting into hex color codehex_color=matplotlib.colors.to_hex([ 0.47, 0.0, 1.0 ]) # create discrete colormapcmap = colors.ListedColormap([hex_color, 'green']) bounds = [0,10,20]norm = colors.BoundaryNorm(bounds, cmap.N) fig, ax = plt.subplots()ax.imshow(data, cmap=cmap, norm=norm) # draw gridlinesax.grid(which='major', axis='both', linestyle='-', color='k', linewidth=2) ax.set_xticks(np.arange(-.5, 10, 1));ax.set_yticks(np.arange(-.5, 10, 1)); plt.show()", "e": 1593, "s": 860, "text": null }, { "code": null, "e": 1601, "s": 1593, "text": "Output:" }, { "code": null, "e": 1612, "s": 1601, "text": "Example 2:" }, { "code": "import matplotlib.pyplot as pltfrom matplotlib import colorsimport numpy as np # dummy data to build the griddata = np.random.rand(10, 10) * 20 # converting into hex color# code with alpha set to Truehex_color = matplotlib.colors.to_hex([ 0.47, 0.0, 1.0, 0.5 ], keep_alpha = True) # create discrete colormapcmap = colors.ListedColormap([hex_color, 'red']) bounds = [0, 10, 20]norm = colors.BoundaryNorm(bounds, cmap.N) fig, ax = plt.subplots()ax.imshow(data, cmap = cmap, norm = norm) # draw gridlinesax.grid(which ='major', axis ='both', linestyle ='-', color ='k', linewidth = 2) ax.set_xticks(np.arange(-.5, 10, 1));ax.set_yticks(np.arange(-.5, 10, 1)); plt.show()", "e": 2483, "s": 1612, "text": null }, { "code": null, "e": 2491, "s": 2483, "text": "Output:" }, { "code": null, "e": 2509, "s": 2491, "text": "Python-matplotlib" }, { "code": null, "e": 2516, "s": 2509, "text": "Python" }, { "code": null, "e": 2532, "s": 2516, "text": "Write From Home" }, { "code": null, "e": 2630, "s": 2532, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2648, "s": 2630, "text": "Python Dictionary" }, { "code": null, "e": 2690, "s": 2648, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2712, "s": 2690, "text": "Enumerate() in Python" }, { "code": null, "e": 2747, "s": 2712, "text": "Read a file line by line in Python" }, { "code": null, "e": 2773, "s": 2747, "text": "Python String | replace()" }, { "code": null, "e": 2809, "s": 2773, "text": "Convert integer to string in Python" }, { "code": null, "e": 2845, "s": 2809, "text": "Convert string to integer in Python" }, { "code": null, "e": 2906, "s": 2845, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 2922, "s": 2906, "text": "Python infinity" } ]
Role of Pressure Groups and its Influence on Politics
05 Jul, 2022 David Truman defined pressure groups as “that on the basis of one or more shared attitudes, makes certain claims upon other groups in the society for the establishment, maintenance, enhancement of forms of behavior that are implied by shared attitude.” Pressure groups and movements are the very essences of modern democracy; they are capable of influencing government decisions through their powerful representation. They can range from very small groups to a nexus of a million people. The pressure groups are not political by nature and they do not contest for political power. Individuals with shared interests come together to change the government’s outlook and alter government decisions. Sectional: This type of pressure group includes self-interest organisations such as trade unions, business and farming groups.Promotional: The promotional interest groups focus on a particular cause and direct their activities towards fulfilling that cause, for instance, women’s rights, moral rights. Sectional: This type of pressure group includes self-interest organisations such as trade unions, business and farming groups. Promotional: The promotional interest groups focus on a particular cause and direct their activities towards fulfilling that cause, for instance, women’s rights, moral rights. Representation in the pressure groups is at times from the influential section of the population, which may include doctors, lawyers, and prominent businessmen; as a result, the government has to take into consideration the views of this section of the population, whose support they cannot afford to lose. For instance, in the U.K. the ban imposed on smoking in public places in July 2007 was partially the result of lobbying by the British Medical Association. Sometimes pressure groups also consist of the outsider groups who mostly do not have any links with the ministers; as a result, the bigger interest groups with insider links are probable to be more successful in influencing the decisions of the government than the smaller ones. In India, the popular pressure groups are Business groups like the Federation of Indian Chamber of Commerce and Industry (FICCI), Trade Unions like the All-India Trade Union Congress (AITUC), Professional Groups like the Indian Medical Association (IMA), Agrarian Groups like the All India Kisan Sabha, and Student Organisations like the Akhil Bharatiya Vidyarthi Parishad (ABVP). The pressure groups perform a major role in modifying the community as a whole by generating political awareness and making the electorate politically aware. They act as a bridge between the electorate and the government by making the government aware of the needs of the governed. The pressure groups give representation to the minority and make their voices heard. They even act as an advisor to the government as and when needed. The presence of the pressure groups makes a democracy rich and viable. Besides, enhancing the quality of democracy, pressure groups at times are autocratic in nature; they represent the powerful minority who are financially affluent, thereby overshadowing the needs of the vast majority. The methods of resistance used by these groups (strikes, demonstrations, rallies) hinder the movement of the community as a whole. They also pressurize the government at times to implement policies benefitting their own interest, disregarding the interests of the vast majority, this is most commonly observed with regard to the trade unions and the business groups. Some techniques generally used by the pressure groups to influence the government’s decisions: Electioneering: In this method, they place representatives favoring their issues in prominent public offices.Lobbying: This method employs convincing public officers to adopt and implement policies that will benefit their Interests.Propagandizing: This involves influencing public opinion in their favour and pressurising the government to accept their interests, as, in a democracy, public opinion is regarded as the sovereign.Resorting to legal actions by making appeals to the judiciary.Campaigning in favour of a particular candidate or opposing any candidate.Organising protests: The interest groups also organise protests, rallies, campaigns that indirectly exercise pressure on the government and oblige them to consider the demands of the people.Demonstrating generally occurs outside government offices, Parliament House, Jantar-Mantar, etc. or marching on the streets.Mass media: In recent years, pressure groups have also taken the help of mass media to present their case before the people and gather public opinion in their favour as public opinion is always an asset in a democracy. Electioneering: In this method, they place representatives favoring their issues in prominent public offices. Lobbying: This method employs convincing public officers to adopt and implement policies that will benefit their Interests. Propagandizing: This involves influencing public opinion in their favour and pressurising the government to accept their interests, as, in a democracy, public opinion is regarded as the sovereign. Resorting to legal actions by making appeals to the judiciary. Campaigning in favour of a particular candidate or opposing any candidate. Organising protests: The interest groups also organise protests, rallies, campaigns that indirectly exercise pressure on the government and oblige them to consider the demands of the people. Demonstrating generally occurs outside government offices, Parliament House, Jantar-Mantar, etc. or marching on the streets. Mass media: In recent years, pressure groups have also taken the help of mass media to present their case before the people and gather public opinion in their favour as public opinion is always an asset in a democracy. All these methods are employed by protesters to influence the decision of the government in their favor. For instance, in 2011 social activist Anna Hazare sat on a 12-day hunger strike and he wanted a joint committee composed of members of the government and of civil society to make a draft tougher anti-corruption legislation. He was supported by retired IPS officer Kiran Bedi and social reformist Swami Agnivesh. The then Congress government, however, post the strike passed the Lokpal Bill, and in January 2014, the then President Pranab Mukherjee granted assent to the law. In the year 2019, a mass protest was observed by the doctors in West Bengal over violence meted out towards the doctors. The doctors refused to attend to patients and boycotted their duties. The Indian Medical Association had also held a country-wide protest on June 18th, 2019. The movement received the support of doctors from all over the world. The protests were finally called off when the security of the doctors was guaranteed by Mamata Banerjee, the Chief Minister of West Bengal, who asked the police to appoint nodal officers at all the government hospitals in the state for the security of the doctors. All their demands were agreed to in the presence of the media. She agreed on punishing the assaulters and also decided on the formation of a grievance redressal unit in all the state-run hospitals. The state government had also taken adequate measures and arrested the assailants. In a recent instance, we have been witness to the ongoing farmer’s protests against the Farm Bills passed by the legislature which is regarded as the Kala Kanoon (Black Law) by the farmers. This protest has received widespread support from prominent agrarian pressure groups. Besides that, the movement has also been backed by the political power of the Shiv Sena and the Congress party. The movement has also been widely acclaimed by the student organizations of prominent Indian Universities who have resorted to demonstrations and rallies, thereby pressurizing the government to withdraw the law passed. The pressure groups and the movements are essential tools in preserving public opinion in a democracy by ensuring adequate public representation, by acting as an effective check against the arbitrary decision-making of the government. pradeepkumar2xpw Political Science UPSC Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Role and Functions of NGOs Financial Emergency and its Consequences Caste System is Assuming New Identities and Associational Forms Freedom of Religion Guaranteed Under Indian Constitution The Inter-State Council Role of Service Sector in Modern Economic Development of India Role of Several Foreigners in Indian Freedom Struggle Strategies to Improve Health Facility in India Future Perspective For Non-Conventional Sources of Energy In India Role of Mahatma Gandhi in National Movement
[ { "code": null, "e": 28, "s": 0, "text": "\n05 Jul, 2022" }, { "code": null, "e": 724, "s": 28, "text": "David Truman defined pressure groups as “that on the basis of one or more shared attitudes, makes certain claims upon other groups in the society for the establishment, maintenance, enhancement of forms of behavior that are implied by shared attitude.” Pressure groups and movements are the very essences of modern democracy; they are capable of influencing government decisions through their powerful representation. They can range from very small groups to a nexus of a million people. The pressure groups are not political by nature and they do not contest for political power. Individuals with shared interests come together to change the government’s outlook and alter government decisions." }, { "code": null, "e": 1026, "s": 724, "text": "Sectional: This type of pressure group includes self-interest organisations such as trade unions, business and farming groups.Promotional: The promotional interest groups focus on a particular cause and direct their activities towards fulfilling that cause, for instance, women’s rights, moral rights." }, { "code": null, "e": 1153, "s": 1026, "text": "Sectional: This type of pressure group includes self-interest organisations such as trade unions, business and farming groups." }, { "code": null, "e": 1329, "s": 1153, "text": "Promotional: The promotional interest groups focus on a particular cause and direct their activities towards fulfilling that cause, for instance, women’s rights, moral rights." }, { "code": null, "e": 2454, "s": 1329, "text": "Representation in the pressure groups is at times from the influential section of the population, which may include doctors, lawyers, and prominent businessmen; as a result, the government has to take into consideration the views of this section of the population, whose support they cannot afford to lose. For instance, in the U.K. the ban imposed on smoking in public places in July 2007 was partially the result of lobbying by the British Medical Association. Sometimes pressure groups also consist of the outsider groups who mostly do not have any links with the ministers; as a result, the bigger interest groups with insider links are probable to be more successful in influencing the decisions of the government than the smaller ones. In India, the popular pressure groups are Business groups like the Federation of Indian Chamber of Commerce and Industry (FICCI), Trade Unions like the All-India Trade Union Congress (AITUC), Professional Groups like the Indian Medical Association (IMA), Agrarian Groups like the All India Kisan Sabha, and Student Organisations like the Akhil Bharatiya Vidyarthi Parishad (ABVP). " }, { "code": null, "e": 2958, "s": 2454, "text": "The pressure groups perform a major role in modifying the community as a whole by generating political awareness and making the electorate politically aware. They act as a bridge between the electorate and the government by making the government aware of the needs of the governed. The pressure groups give representation to the minority and make their voices heard. They even act as an advisor to the government as and when needed. The presence of the pressure groups makes a democracy rich and viable." }, { "code": null, "e": 3542, "s": 2958, "text": "Besides, enhancing the quality of democracy, pressure groups at times are autocratic in nature; they represent the powerful minority who are financially affluent, thereby overshadowing the needs of the vast majority. The methods of resistance used by these groups (strikes, demonstrations, rallies) hinder the movement of the community as a whole. They also pressurize the government at times to implement policies benefitting their own interest, disregarding the interests of the vast majority, this is most commonly observed with regard to the trade unions and the business groups." }, { "code": null, "e": 3637, "s": 3542, "text": "Some techniques generally used by the pressure groups to influence the government’s decisions:" }, { "code": null, "e": 4734, "s": 3637, "text": "Electioneering: In this method, they place representatives favoring their issues in prominent public offices.Lobbying: This method employs convincing public officers to adopt and implement policies that will benefit their Interests.Propagandizing: This involves influencing public opinion in their favour and pressurising the government to accept their interests, as, in a democracy, public opinion is regarded as the sovereign.Resorting to legal actions by making appeals to the judiciary.Campaigning in favour of a particular candidate or opposing any candidate.Organising protests: The interest groups also organise protests, rallies, campaigns that indirectly exercise pressure on the government and oblige them to consider the demands of the people.Demonstrating generally occurs outside government offices, Parliament House, Jantar-Mantar, etc. or marching on the streets.Mass media: In recent years, pressure groups have also taken the help of mass media to present their case before the people and gather public opinion in their favour as public opinion is always an asset in a democracy." }, { "code": null, "e": 4844, "s": 4734, "text": "Electioneering: In this method, they place representatives favoring their issues in prominent public offices." }, { "code": null, "e": 4968, "s": 4844, "text": "Lobbying: This method employs convincing public officers to adopt and implement policies that will benefit their Interests." }, { "code": null, "e": 5165, "s": 4968, "text": "Propagandizing: This involves influencing public opinion in their favour and pressurising the government to accept their interests, as, in a democracy, public opinion is regarded as the sovereign." }, { "code": null, "e": 5228, "s": 5165, "text": "Resorting to legal actions by making appeals to the judiciary." }, { "code": null, "e": 5303, "s": 5228, "text": "Campaigning in favour of a particular candidate or opposing any candidate." }, { "code": null, "e": 5494, "s": 5303, "text": "Organising protests: The interest groups also organise protests, rallies, campaigns that indirectly exercise pressure on the government and oblige them to consider the demands of the people." }, { "code": null, "e": 5619, "s": 5494, "text": "Demonstrating generally occurs outside government offices, Parliament House, Jantar-Mantar, etc. or marching on the streets." }, { "code": null, "e": 5838, "s": 5619, "text": "Mass media: In recent years, pressure groups have also taken the help of mass media to present their case before the people and gather public opinion in their favour as public opinion is always an asset in a democracy." }, { "code": null, "e": 6418, "s": 5838, "text": "All these methods are employed by protesters to influence the decision of the government in their favor. For instance, in 2011 social activist Anna Hazare sat on a 12-day hunger strike and he wanted a joint committee composed of members of the government and of civil society to make a draft tougher anti-corruption legislation. He was supported by retired IPS officer Kiran Bedi and social reformist Swami Agnivesh. The then Congress government, however, post the strike passed the Lokpal Bill, and in January 2014, the then President Pranab Mukherjee granted assent to the law." }, { "code": null, "e": 7313, "s": 6418, "text": "In the year 2019, a mass protest was observed by the doctors in West Bengal over violence meted out towards the doctors. The doctors refused to attend to patients and boycotted their duties. The Indian Medical Association had also held a country-wide protest on June 18th, 2019. The movement received the support of doctors from all over the world. The protests were finally called off when the security of the doctors was guaranteed by Mamata Banerjee, the Chief Minister of West Bengal, who asked the police to appoint nodal officers at all the government hospitals in the state for the security of the doctors. All their demands were agreed to in the presence of the media. She agreed on punishing the assaulters and also decided on the formation of a grievance redressal unit in all the state-run hospitals. The state government had also taken adequate measures and arrested the assailants." }, { "code": null, "e": 7920, "s": 7313, "text": "In a recent instance, we have been witness to the ongoing farmer’s protests against the Farm Bills passed by the legislature which is regarded as the Kala Kanoon (Black Law) by the farmers. This protest has received widespread support from prominent agrarian pressure groups. Besides that, the movement has also been backed by the political power of the Shiv Sena and the Congress party. The movement has also been widely acclaimed by the student organizations of prominent Indian Universities who have resorted to demonstrations and rallies, thereby pressurizing the government to withdraw the law passed." }, { "code": null, "e": 8155, "s": 7920, "text": "The pressure groups and the movements are essential tools in preserving public opinion in a democracy by ensuring adequate public representation, by acting as an effective check against the arbitrary decision-making of the government." }, { "code": null, "e": 8172, "s": 8155, "text": "pradeepkumar2xpw" }, { "code": null, "e": 8190, "s": 8172, "text": "Political Science" }, { "code": null, "e": 8195, "s": 8190, "text": "UPSC" }, { "code": null, "e": 8293, "s": 8195, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 8320, "s": 8293, "text": "Role and Functions of NGOs" }, { "code": null, "e": 8361, "s": 8320, "text": "Financial Emergency and its Consequences" }, { "code": null, "e": 8425, "s": 8361, "text": "Caste System is Assuming New Identities and Associational Forms" }, { "code": null, "e": 8482, "s": 8425, "text": "Freedom of Religion Guaranteed Under Indian Constitution" }, { "code": null, "e": 8506, "s": 8482, "text": "The Inter-State Council" }, { "code": null, "e": 8569, "s": 8506, "text": "Role of Service Sector in Modern Economic Development of India" }, { "code": null, "e": 8623, "s": 8569, "text": "Role of Several Foreigners in Indian Freedom Struggle" }, { "code": null, "e": 8670, "s": 8623, "text": "Strategies to Improve Health Facility in India" }, { "code": null, "e": 8737, "s": 8670, "text": "Future Perspective For Non-Conventional Sources of Energy In India" } ]
list size() function in C++ STL
14 Jun, 2022 The list::size() is a built-in function in C++ STL which is used to find the number of elements present in a list container. That is, it is used to find the size of the list container. Syntax: list_name.size(); Time Complexity – Linear O(N) Parameters: This function does not accept any parameter. Return Value: This function returns the number of elements present in the list container list_name. Below program illustrate the list::size() function in C++ STL: CPP // CPP program to illustrate the// list::size() function#include <bits/stdc++.h>using namespace std; int main(){ // Creating a list list<int> demoList; // Add elements to the List demoList.push_back(10); demoList.push_back(20); demoList.push_back(30); demoList.push_back(40); // getting size of the list int size = demoList.size(); cout << "The list contains " << size << " elements"; return 0;} utkarshgupta110092 CPP-Functions cpp-list STL C++ STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n14 Jun, 2022" }, { "code": null, "e": 221, "s": 28, "text": "The list::size() is a built-in function in C++ STL which is used to find the number of elements present in a list container. That is, it is used to find the size of the list container. Syntax:" }, { "code": null, "e": 239, "s": 221, "text": "list_name.size();" }, { "code": null, "e": 269, "s": 239, "text": "Time Complexity – Linear O(N)" }, { "code": null, "e": 490, "s": 269, "text": "Parameters: This function does not accept any parameter. Return Value: This function returns the number of elements present in the list container list_name. Below program illustrate the list::size() function in C++ STL: " }, { "code": null, "e": 494, "s": 490, "text": "CPP" }, { "code": "// CPP program to illustrate the// list::size() function#include <bits/stdc++.h>using namespace std; int main(){ // Creating a list list<int> demoList; // Add elements to the List demoList.push_back(10); demoList.push_back(20); demoList.push_back(30); demoList.push_back(40); // getting size of the list int size = demoList.size(); cout << \"The list contains \" << size << \" elements\"; return 0;}", "e": 927, "s": 494, "text": null }, { "code": null, "e": 946, "s": 927, "text": "utkarshgupta110092" }, { "code": null, "e": 960, "s": 946, "text": "CPP-Functions" }, { "code": null, "e": 969, "s": 960, "text": "cpp-list" }, { "code": null, "e": 973, "s": 969, "text": "STL" }, { "code": null, "e": 977, "s": 973, "text": "C++" }, { "code": null, "e": 981, "s": 977, "text": "STL" }, { "code": null, "e": 985, "s": 981, "text": "CPP" } ]
Missing data imputation with fancyimpute
01 Aug, 2020 In a real world dataset, there will always be some data missing. This mainly associates with how the data was collected. Missing data plays an important role creating a predictive model, because there are algorithms which does not perform very well with missing dataset. fancyimpute is a library for missing data imputation algorithms. Fancyimpute use machine learning algorithm to impute missing values. Fancyimpute uses all the column to impute the missing values. There are two ways missing data can be imputed using Fancyimpute KNN or K-Nearest NeighborMICE or Multiple Imputation by Chained Equation KNN or K-Nearest Neighbor MICE or Multiple Imputation by Chained Equation To fill out the missing values KNN finds out the similar data points among all the features. Then it took the average of all the points to fill in the missing values. Python3 import pandas as pdimport numpy as np# importing the KNN from fancyimpute libraryfrom fancyimpute import KNN df = pd.DataFrame([[np.nan, 2, np.nan, 0], [3, 4, np.nan, 1], [np.nan, np.nan, np.nan, 5], [np.nan, 3, np.nan, 4], [5, 7, 8, 2], [2, 5, 7, 9]], columns = list('ABCD')) # printing the dataframeprint(df) # calling the KNN classknn_imputer = KNN()# imputing the missing value with knn imputerdf = knn_imputer.fit_transform(df) # printing dataframeprint(df) A B C D 0 NaN 2.0 NaN 0 1 3.0 4.0 NaN 1 2 NaN NaN NaN 5 3 NaN 3.0 NaN 4 4 5.0 7.0 8.0 2 5 2.0 5.0 7.0 9 Imputing row 1/6 with 2 missing, elapsed time: 0.001 [[3.23556938 2. 7.75630267 0.] [3. 4. 7.825 1.] [3.67647071 3.46386587 7.64000033 5.] [3.35514006 3. 7.59183674 4.] [5. 7. 8. 2.] [2. 5. 7. 9.]] MICE uses multiple imputation instead of single imputation which results in statistical uncertainty. MICE perform multiple regression over the sample data and take averages of them Python3 import pandas as pdimport numpy as np# importing the MICE from fancyimpute libraryfrom fancyimpute import IterativeImputer df = pd.DataFrame([[np.nan, 2, np.nan, 0], [3, 4, np.nan, 1], [np.nan, np.nan, np.nan, 5], [np.nan, 3, np.nan, 4], [5, 7, 8, 2], [2, 5, 7, 9]], columns = list('ABCD')) # printing the dataframeprint(df) # calling the MICE classmice_imputer = IterativeImputer()# imputing the missing value with mice imputerdf = mice_imputer.fit_transform(df) # printing dataframeprint(df) A B C D 0 NaN 2.0 NaN 0 1 3.0 4.0 NaN 1 2 NaN NaN NaN 5 3 NaN 3.0 NaN 4 4 5.0 7.0 8.0 2 5 2.0 5.0 7.0 9 [[3.27262261 2. 7.9809332 0 ] [3. 4. 7.9193547 1.] [2.91717117 4.35730239 7.47523962 5.] [2.77722048 3. 7.53760743 4.] [5. 7. 8. 2.] [2. 5. 7. 9.]] Machine Learning Python Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n01 Aug, 2020" }, { "code": null, "e": 299, "s": 28, "text": "In a real world dataset, there will always be some data missing. This mainly associates with how the data was collected. Missing data plays an important role creating a predictive model, because there are algorithms which does not perform very well with missing dataset." }, { "code": null, "e": 560, "s": 299, "text": "fancyimpute is a library for missing data imputation algorithms. Fancyimpute use machine learning algorithm to impute missing values. Fancyimpute uses all the column to impute the missing values. There are two ways missing data can be imputed using Fancyimpute" }, { "code": null, "e": 633, "s": 560, "text": "KNN or K-Nearest NeighborMICE or Multiple Imputation by Chained Equation" }, { "code": null, "e": 659, "s": 633, "text": "KNN or K-Nearest Neighbor" }, { "code": null, "e": 707, "s": 659, "text": "MICE or Multiple Imputation by Chained Equation" }, { "code": null, "e": 874, "s": 707, "text": "To fill out the missing values KNN finds out the similar data points among all the features. Then it took the average of all the points to fill in the missing values." }, { "code": null, "e": 882, "s": 874, "text": "Python3" }, { "code": "import pandas as pdimport numpy as np# importing the KNN from fancyimpute libraryfrom fancyimpute import KNN df = pd.DataFrame([[np.nan, 2, np.nan, 0], [3, 4, np.nan, 1], [np.nan, np.nan, np.nan, 5], [np.nan, 3, np.nan, 4], [5, 7, 8, 2], [2, 5, 7, 9]], columns = list('ABCD')) # printing the dataframeprint(df) # calling the KNN classknn_imputer = KNN()# imputing the missing value with knn imputerdf = knn_imputer.fit_transform(df) # printing dataframeprint(df)", "e": 1476, "s": 882, "text": null }, { "code": null, "e": 1904, "s": 1476, "text": " A B C D\n0 NaN 2.0 NaN 0\n1 3.0 4.0 NaN 1\n2 NaN NaN NaN 5\n3 NaN 3.0 NaN 4\n4 5.0 7.0 8.0 2\n5 2.0 5.0 7.0 9\nImputing row 1/6 with 2 missing, elapsed time: 0.001\n[[3.23556938 2. 7.75630267 0.]\n [3. 4. 7.825 1.]\n [3.67647071 3.46386587 7.64000033 5.]\n [3.35514006 3. 7.59183674 4.]\n [5. 7. 8. 2.]\n [2. 5. 7. 9.]]\n" }, { "code": null, "e": 2085, "s": 1904, "text": "MICE uses multiple imputation instead of single imputation which results in statistical uncertainty. MICE perform multiple regression over the sample data and take averages of them" }, { "code": null, "e": 2093, "s": 2085, "text": "Python3" }, { "code": "import pandas as pdimport numpy as np# importing the MICE from fancyimpute libraryfrom fancyimpute import IterativeImputer df = pd.DataFrame([[np.nan, 2, np.nan, 0], [3, 4, np.nan, 1], [np.nan, np.nan, np.nan, 5], [np.nan, 3, np.nan, 4], [5, 7, 8, 2], [2, 5, 7, 9]], columns = list('ABCD')) # printing the dataframeprint(df) # calling the MICE classmice_imputer = IterativeImputer()# imputing the missing value with mice imputerdf = mice_imputer.fit_transform(df) # printing dataframeprint(df)", "e": 2719, "s": 2093, "text": null }, { "code": null, "e": 3095, "s": 2719, "text": " A B C D\n0 NaN 2.0 NaN 0\n1 3.0 4.0 NaN 1\n2 NaN NaN NaN 5\n3 NaN 3.0 NaN 4\n4 5.0 7.0 8.0 2\n5 2.0 5.0 7.0 9\n[[3.27262261 2. 7.9809332 0 ]\n [3. 4. 7.9193547 1.]\n [2.91717117 4.35730239 7.47523962 5.]\n [2.77722048 3. 7.53760743 4.]\n [5. 7. 8. 2.]\n [2. 5. 7. 9.]]\n" }, { "code": null, "e": 3112, "s": 3095, "text": "Machine Learning" }, { "code": null, "e": 3119, "s": 3112, "text": "Python" }, { "code": null, "e": 3136, "s": 3119, "text": "Machine Learning" } ]
Mongoose count() Function
10 Sep, 2020 The Query.prototype.count() function is used to count the number of documents in a collection. This functions basically specifies this query as a count query. Syntax: Query.prototype.count() Parameters: This function accepts one array parameter i.e. callback function. Return Value: This function returns Query Object. Installation of mongoose module: You can visit the link to Install mongoose module. You can install this package by using this command. npm install mongoose After installing the mongoose module, you can check your mongoose version in command prompt using the command. npm version mongoose After that, you can just create a folder and add a file for example, index.js as shown below. Database: The sample database used here is shown below: Example 1: Filename: index.js javascript const mongoose = require('mongoose'); // Database connectionmongoose.connect('mongodb://127.0.0.1:27017/geeksforgeeks', { useNewUrlParser: true, useCreateIndex: true, useUnifiedTopology: true}); // User modelconst User = mongoose.model('User', { name: { type: String }, age: { type: Number }}); var query = User.find();query.count(function (err, count) { if (err) console.log(err) else console.log("Count is", count)}); Steps to run the program: The project structure will look like this: Run index.js file using below command: node index.js Output: Count is 4 Example 2: Filename: index.js javascript const express = require('express');const mongoose = require('mongoose');const app = express() // Database connectionmongoose.connect('mongodb://127.0.0.1:27017/geeksforgeeks', { useNewUrlParser: true, useCreateIndex: true, useUnifiedTopology: true}); // User modelconst User = mongoose.model('User', { name: { type: String }, age: { type: Number }}); var query = User.find();query.count(function (err, count) { if (err) console.log(err) else console.log("Count:", count)}); app.listen(3000, function(error ) { if(error) console.log(error) console.log("Server listening on PORT 3000")}); Steps to run the program: The project structure will look like this: Run index.js file using below command: node index.js Output: Server listening on PORT 3000 Count: 4 Reference: https://mongoosejs.com/docs/api/query.html#query_Query-count Mongoose Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. JWT Authentication with Node.js Installation of Node.js on Windows Difference between dependencies, devDependencies and peerDependencies Mongoose Populate() Method Mongoose find() Function 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": "\n10 Sep, 2020" }, { "code": null, "e": 187, "s": 28, "text": "The Query.prototype.count() function is used to count the number of documents in a collection. This functions basically specifies this query as a count query." }, { "code": null, "e": 196, "s": 187, "text": "Syntax: " }, { "code": null, "e": 221, "s": 196, "text": "Query.prototype.count()\n" }, { "code": null, "e": 300, "s": 221, "text": "Parameters: This function accepts one array parameter i.e. callback function. " }, { "code": null, "e": 351, "s": 300, "text": "Return Value: This function returns Query Object. " }, { "code": null, "e": 385, "s": 351, "text": "Installation of mongoose module: " }, { "code": null, "e": 489, "s": 385, "text": "You can visit the link to Install mongoose module. You can install this package by using this command. " }, { "code": null, "e": 511, "s": 489, "text": "npm install mongoose\n" }, { "code": null, "e": 623, "s": 511, "text": "After installing the mongoose module, you can check your mongoose version in command prompt using the command. " }, { "code": null, "e": 645, "s": 623, "text": "npm version mongoose\n" }, { "code": null, "e": 739, "s": 645, "text": "After that, you can just create a folder and add a file for example, index.js as shown below." }, { "code": null, "e": 797, "s": 739, "text": "Database: The sample database used here is shown below: " }, { "code": null, "e": 829, "s": 797, "text": "Example 1: Filename: index.js " }, { "code": null, "e": 840, "s": 829, "text": "javascript" }, { "code": "const mongoose = require('mongoose'); // Database connectionmongoose.connect('mongodb://127.0.0.1:27017/geeksforgeeks', { useNewUrlParser: true, useCreateIndex: true, useUnifiedTopology: true}); // User modelconst User = mongoose.model('User', { name: { type: String }, age: { type: Number }}); var query = User.find();query.count(function (err, count) { if (err) console.log(err) else console.log(\"Count is\", count)});", "e": 1285, "s": 840, "text": null }, { "code": null, "e": 1312, "s": 1285, "text": "Steps to run the program: " }, { "code": null, "e": 1356, "s": 1312, "text": "The project structure will look like this: " }, { "code": null, "e": 1396, "s": 1356, "text": "Run index.js file using below command: " }, { "code": null, "e": 1411, "s": 1396, "text": "node index.js\n" }, { "code": null, "e": 1420, "s": 1411, "text": "Output: " }, { "code": null, "e": 1432, "s": 1420, "text": "Count is 4\n" }, { "code": null, "e": 1464, "s": 1432, "text": "Example 2: Filename: index.js " }, { "code": null, "e": 1475, "s": 1464, "text": "javascript" }, { "code": "const express = require('express');const mongoose = require('mongoose');const app = express() // Database connectionmongoose.connect('mongodb://127.0.0.1:27017/geeksforgeeks', { useNewUrlParser: true, useCreateIndex: true, useUnifiedTopology: true}); // User modelconst User = mongoose.model('User', { name: { type: String }, age: { type: Number }}); var query = User.find();query.count(function (err, count) { if (err) console.log(err) else console.log(\"Count:\", count)}); app.listen(3000, function(error ) { if(error) console.log(error) console.log(\"Server listening on PORT 3000\")});", "e": 2094, "s": 1475, "text": null }, { "code": null, "e": 2121, "s": 2094, "text": "Steps to run the program: " }, { "code": null, "e": 2165, "s": 2121, "text": "The project structure will look like this: " }, { "code": null, "e": 2205, "s": 2165, "text": "Run index.js file using below command: " }, { "code": null, "e": 2220, "s": 2205, "text": "node index.js\n" }, { "code": null, "e": 2229, "s": 2220, "text": "Output: " }, { "code": null, "e": 2269, "s": 2229, "text": "Server listening on PORT 3000\nCount: 4\n" }, { "code": null, "e": 2341, "s": 2269, "text": "Reference: https://mongoosejs.com/docs/api/query.html#query_Query-count" }, { "code": null, "e": 2350, "s": 2341, "text": "Mongoose" }, { "code": null, "e": 2358, "s": 2350, "text": "Node.js" }, { "code": null, "e": 2375, "s": 2358, "text": "Web Technologies" }, { "code": null, "e": 2473, "s": 2375, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2505, "s": 2473, "text": "JWT Authentication with Node.js" }, { "code": null, "e": 2540, "s": 2505, "text": "Installation of Node.js on Windows" }, { "code": null, "e": 2610, "s": 2540, "text": "Difference between dependencies, devDependencies and peerDependencies" }, { "code": null, "e": 2637, "s": 2610, "text": "Mongoose Populate() Method" }, { "code": null, "e": 2662, "s": 2637, "text": "Mongoose find() Function" }, { "code": null, "e": 2724, "s": 2662, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 2785, "s": 2724, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2835, "s": 2785, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 2878, "s": 2835, "text": "How to fetch data from an API in ReactJS ?" } ]
JavaScript | Adding hours to the Date object
18 May, 2019 Given a date, the task is to add hours to it. To add hours to date in javascript, we’re going to discuss a few techniques. First few methods to know. JavaScript getHours() MethodThis method returns the hour (from 0 to 23) of the provided date and time.Syntax:Date.getHours() Return value:It returns a number, from 0 to 23, representing the hour. Date.getHours() Return value:It returns a number, from 0 to 23, representing the hour. JavaScript setHours() MethodThis method sets the hour of a date object.We can also set the minutes, seconds and milliseconds.Syntax:Date.setHours(hour, min, sec, millisec) Parameters:hour: This parameter is required. It specifies the integer representing the hour. Values expected are 0-23, but other values are allowed.min: This parameter is optional. It specifies the integer representing the minutes. Values expected are 0-59, but other values are allowed.sec: This parameter is optional. It specifies the integer representing the seconds. Values expected are 0-59, but other values are allowed.millisec: This parameter is optional. It specifies the integer representing the milliseconds. Values expected are 0-999, but other values are allowed.Note:All the previous 4 parameters accept values apart from their range and these values adjust like.hour = -1, means the last hour of the previous day and same for the other parameters.if min passed is 60, means the first minute of the next hour and same for the other parameters.Return value:It returns a number, denoting the number of milliseconds between the date object and midnight January 1, 1970. JavaScript setHours() MethodThis method sets the hour of a date object.We can also set the minutes, seconds and milliseconds.Syntax: Date.setHours(hour, min, sec, millisec) Parameters: hour: This parameter is required. It specifies the integer representing the hour. Values expected are 0-23, but other values are allowed. min: This parameter is optional. It specifies the integer representing the minutes. Values expected are 0-59, but other values are allowed. sec: This parameter is optional. It specifies the integer representing the seconds. Values expected are 0-59, but other values are allowed. millisec: This parameter is optional. It specifies the integer representing the milliseconds. Values expected are 0-999, but other values are allowed. Note:All the previous 4 parameters accept values apart from their range and these values adjust like. hour = -1, means the last hour of the previous day and same for the other parameters. if min passed is 60, means the first minute of the next hour and same for the other parameters. Return value:It returns a number, denoting the number of milliseconds between the date object and midnight January 1, 1970. JavaScript getTime() methodThis method returns the number of milliseconds between midnight of January 1, 1970, and the specified date.Syntax:Date.getTime() Return value:It returns a number, representing the number of milliseconds since midnight January 1, 1970. Date.getTime() Return value:It returns a number, representing the number of milliseconds since midnight January 1, 1970. JavaScript setTime() methodThis method set the date and time by adding/subtracting a defines number of milliseconds to/from midnight January 1, 1970.Syntax:Date.setTime(millisec) Parameters:millisec: This parameter is required. It specifies the number of milliseconds to be added/subtracted, midnight January 1, 1970Return value:It returns, representing the number of milliseconds between the date object and midnight January 1 1970. JavaScript setTime() methodThis method set the date and time by adding/subtracting a defines number of milliseconds to/from midnight January 1, 1970.Syntax: Date.setTime(millisec) Parameters: millisec: This parameter is required. It specifies the number of milliseconds to be added/subtracted, midnight January 1, 1970 Return value:It returns, representing the number of milliseconds between the date object and midnight January 1 1970. Example 1: This example adds 4 hours to the 16th may by using setTime() and getTime() method. <!DOCTYPE HTML><html> <head> <title> JavaScript | Adding hours to Date object. </title></head> <body style="text-align:center;" id="body"> <h1 style="color:green;"> GeeksForGeeks </h1> <p id="GFG_UP" style="font-size: 15px; font-weight: bold;"> </p> <button onclick="gfg_Run()"> addHours </button> <p id="GFG_DOWN" style="color:green; font-size: 20px; font-weight: bold;"> </p> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); var today = new Date(); el_up.innerHTML = "Today's date = " + today; Date.prototype.addHours = function(h) { this.setTime(this.getTime() + (h * 60 * 60 * 1000)); return this; } function gfg_Run() { var a = new Date(); a.addHours(4); el_down.innerHTML = a; } </script></body> </html> Output: Before clicking on the button: After clicking on the button: Example 2: This example adds 6 hours to the 16th may by using setHours() and getHours() method. <!DOCTYPE HTML><html> <head> <title> JavaScript | Adding hours to Date object. </title></head> <body style="text-align:center;" id="body"> <h1 style="color:green;"> GeeksForGeeks </h1> <p id="GFG_UP" style="font-size: 15px; font-weight: bold;"> </p> <button onclick="gfg_Run()"> addHours </button> <p id="GFG_DOWN" style="color:green; font-size: 20px; font-weight: bold;"> </p> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); var today = new Date(); el_up.innerHTML = "Today's date = " + today; Date.prototype.addHours = function(h) { this.setHours(this.getHours() + h); return this; } function gfg_Run() { var a = new Date(); a.addHours(6); el_down.innerHTML = a; } </script></body> </html> Output: Before clicking on the button: After clicking on the button: javascript-date 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 How to append HTML code to a div using JavaScript ? Difference Between PUT and PATCH Request 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": "\n18 May, 2019" }, { "code": null, "e": 178, "s": 28, "text": "Given a date, the task is to add hours to it. To add hours to date in javascript, we’re going to discuss a few techniques. First few methods to know." }, { "code": null, "e": 374, "s": 178, "text": "JavaScript getHours() MethodThis method returns the hour (from 0 to 23) of the provided date and time.Syntax:Date.getHours()\nReturn value:It returns a number, from 0 to 23, representing the hour." }, { "code": null, "e": 391, "s": 374, "text": "Date.getHours()\n" }, { "code": null, "e": 462, "s": 391, "text": "Return value:It returns a number, from 0 to 23, representing the hour." }, { "code": null, "e": 1615, "s": 462, "text": "JavaScript setHours() MethodThis method sets the hour of a date object.We can also set the minutes, seconds and milliseconds.Syntax:Date.setHours(hour, min, sec, millisec)\nParameters:hour: This parameter is required. It specifies the integer representing the hour. Values expected are 0-23, but other values are allowed.min: This parameter is optional. It specifies the integer representing the minutes. Values expected are 0-59, but other values are allowed.sec: This parameter is optional. It specifies the integer representing the seconds. Values expected are 0-59, but other values are allowed.millisec: This parameter is optional. It specifies the integer representing the milliseconds. Values expected are 0-999, but other values are allowed.Note:All the previous 4 parameters accept values apart from their range and these values adjust like.hour = -1, means the last hour of the previous day and same for the other parameters.if min passed is 60, means the first minute of the next hour and same for the other parameters.Return value:It returns a number, denoting the number of milliseconds between the date object and midnight January 1, 1970." }, { "code": null, "e": 1748, "s": 1615, "text": "JavaScript setHours() MethodThis method sets the hour of a date object.We can also set the minutes, seconds and milliseconds.Syntax:" }, { "code": null, "e": 1789, "s": 1748, "text": "Date.setHours(hour, min, sec, millisec)\n" }, { "code": null, "e": 1801, "s": 1789, "text": "Parameters:" }, { "code": null, "e": 1939, "s": 1801, "text": "hour: This parameter is required. It specifies the integer representing the hour. Values expected are 0-23, but other values are allowed." }, { "code": null, "e": 2079, "s": 1939, "text": "min: This parameter is optional. It specifies the integer representing the minutes. Values expected are 0-59, but other values are allowed." }, { "code": null, "e": 2219, "s": 2079, "text": "sec: This parameter is optional. It specifies the integer representing the seconds. Values expected are 0-59, but other values are allowed." }, { "code": null, "e": 2370, "s": 2219, "text": "millisec: This parameter is optional. It specifies the integer representing the milliseconds. Values expected are 0-999, but other values are allowed." }, { "code": null, "e": 2472, "s": 2370, "text": "Note:All the previous 4 parameters accept values apart from their range and these values adjust like." }, { "code": null, "e": 2558, "s": 2472, "text": "hour = -1, means the last hour of the previous day and same for the other parameters." }, { "code": null, "e": 2654, "s": 2558, "text": "if min passed is 60, means the first minute of the next hour and same for the other parameters." }, { "code": null, "e": 2778, "s": 2654, "text": "Return value:It returns a number, denoting the number of milliseconds between the date object and midnight January 1, 1970." }, { "code": null, "e": 3040, "s": 2778, "text": "JavaScript getTime() methodThis method returns the number of milliseconds between midnight of January 1, 1970, and the specified date.Syntax:Date.getTime()\nReturn value:It returns a number, representing the number of milliseconds since midnight January 1, 1970." }, { "code": null, "e": 3056, "s": 3040, "text": "Date.getTime()\n" }, { "code": null, "e": 3162, "s": 3056, "text": "Return value:It returns a number, representing the number of milliseconds since midnight January 1, 1970." }, { "code": null, "e": 3596, "s": 3162, "text": "JavaScript setTime() methodThis method set the date and time by adding/subtracting a defines number of milliseconds to/from midnight January 1, 1970.Syntax:Date.setTime(millisec)\nParameters:millisec: This parameter is required. It specifies the number of milliseconds to be added/subtracted, midnight January 1, 1970Return value:It returns, representing the number of milliseconds between the date object and midnight January 1 1970." }, { "code": null, "e": 3753, "s": 3596, "text": "JavaScript setTime() methodThis method set the date and time by adding/subtracting a defines number of milliseconds to/from midnight January 1, 1970.Syntax:" }, { "code": null, "e": 3777, "s": 3753, "text": "Date.setTime(millisec)\n" }, { "code": null, "e": 3789, "s": 3777, "text": "Parameters:" }, { "code": null, "e": 3916, "s": 3789, "text": "millisec: This parameter is required. It specifies the number of milliseconds to be added/subtracted, midnight January 1, 1970" }, { "code": null, "e": 4034, "s": 3916, "text": "Return value:It returns, representing the number of milliseconds between the date object and midnight January 1 1970." }, { "code": null, "e": 4128, "s": 4034, "text": "Example 1: This example adds 4 hours to the 16th may by using setTime() and getTime() method." }, { "code": "<!DOCTYPE HTML><html> <head> <title> JavaScript | Adding hours to Date object. </title></head> <body style=\"text-align:center;\" id=\"body\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p id=\"GFG_UP\" style=\"font-size: 15px; font-weight: bold;\"> </p> <button onclick=\"gfg_Run()\"> addHours </button> <p id=\"GFG_DOWN\" style=\"color:green; font-size: 20px; font-weight: bold;\"> </p> <script> var el_up = document.getElementById(\"GFG_UP\"); var el_down = document.getElementById(\"GFG_DOWN\"); var today = new Date(); el_up.innerHTML = \"Today's date = \" + today; Date.prototype.addHours = function(h) { this.setTime(this.getTime() + (h * 60 * 60 * 1000)); return this; } function gfg_Run() { var a = new Date(); a.addHours(4); el_down.innerHTML = a; } </script></body> </html>", "e": 5204, "s": 4128, "text": null }, { "code": null, "e": 5212, "s": 5204, "text": "Output:" }, { "code": null, "e": 5243, "s": 5212, "text": "Before clicking on the button:" }, { "code": null, "e": 5273, "s": 5243, "text": "After clicking on the button:" }, { "code": null, "e": 5369, "s": 5273, "text": "Example 2: This example adds 6 hours to the 16th may by using setHours() and getHours() method." }, { "code": "<!DOCTYPE HTML><html> <head> <title> JavaScript | Adding hours to Date object. </title></head> <body style=\"text-align:center;\" id=\"body\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p id=\"GFG_UP\" style=\"font-size: 15px; font-weight: bold;\"> </p> <button onclick=\"gfg_Run()\"> addHours </button> <p id=\"GFG_DOWN\" style=\"color:green; font-size: 20px; font-weight: bold;\"> </p> <script> var el_up = document.getElementById(\"GFG_UP\"); var el_down = document.getElementById(\"GFG_DOWN\"); var today = new Date(); el_up.innerHTML = \"Today's date = \" + today; Date.prototype.addHours = function(h) { this.setHours(this.getHours() + h); return this; } function gfg_Run() { var a = new Date(); a.addHours(6); el_down.innerHTML = a; } </script></body> </html>", "e": 6396, "s": 5369, "text": null }, { "code": null, "e": 6404, "s": 6396, "text": "Output:" }, { "code": null, "e": 6435, "s": 6404, "text": "Before clicking on the button:" }, { "code": null, "e": 6465, "s": 6435, "text": "After clicking on the button:" }, { "code": null, "e": 6481, "s": 6465, "text": "javascript-date" }, { "code": null, "e": 6492, "s": 6481, "text": "JavaScript" }, { "code": null, "e": 6509, "s": 6492, "text": "Web Technologies" }, { "code": null, "e": 6607, "s": 6509, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6668, "s": 6607, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 6740, "s": 6668, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 6780, "s": 6740, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 6832, "s": 6780, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 6873, "s": 6832, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 6935, "s": 6873, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 6968, "s": 6935, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 7029, "s": 6968, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 7079, "s": 7029, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
GATE | GATE-CS-2002 | Question 35
28 Jun, 2021 Consider the following algorithm for searching for a given number x in an unsorted array A[1.....n] having n distinct values: 1. Choose an i uniformaly at random from 1..... n; 2. If A[i] = x then Stop else Goto 1; Assuming that x is present in A, what is the expected number of comparisons made by the algorithm before it terminates ?(A) n(B) n – 1(C) 2n(D) n/2Answer: (A)Explanation: If you remember the coin and dice questions, you can just guess the answer for the above. Below is proof for the answer. Let expected number of comparisons be E. Value of E is sum of following expression for all the possible cases. number_of_comparisons_for_a_case * probability_for_the_case Case 1 If A[i] is found in the first attempt number of comparisons = 1 probability of the case = 1/n Case 2 If A[i] is found in the second attempt number of comparisons = 2 probability of the case = (n-1)/n*1/n Case 3 If A[i] is found in the third attempt number of comparisons = 2 probability of the case = (n-1)/n*(n-1)/n*1/n There are actually infinite such cases. So, we have following infinite series for E. E = 1/n + [(n-1)/n]*[1/n]*2 + [(n-1)/n]*[(n-1)/n]*[1/n]*3 + .... (1) After multiplying equation (1) with (n-1)/n, we get E (n-1)/n = [(n-1)/n]*[1/n] + [(n-1)/n]*[(n-1)/n]*[1/n]*2 + [(n-1)/n]*[(n-1)/n]*[(n-1)/n]*[1/n]*3 ..........(2) Subtracting (2) from (1), we get E/n = 1/n + (n-1)/n*1/n + (n-1)/n*(n-1)/n*1/n + ............ The expression on right side is a GP with infinite elements. Let us apply the sum formula (a/(1-r)) E/n = [1/n]/[1-(n-1)/n] = 1 E = n Quiz of this Question GATE-CS-2002 GATE-GATE-CS-2002 GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. GATE | GATE-CS-2014-(Set-2) | Question 65 GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33 GATE | GATE-CS-2014-(Set-3) | Question 65 GATE | GATE-CS-2015 (Set 3) | Question 65 GATE | GATE CS 2008 | Question 46 GATE | GATE CS 2011 | Question 49 GATE | GATE CS 1996 | Question 38 GATE | GATE-CS-2004 | Question 31 GATE | GATE IT 2006 | Question 20 GATE | GATE-CS-2016 (Set 1) | Question 45
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Jun, 2021" }, { "code": null, "e": 154, "s": 28, "text": "Consider the following algorithm for searching for a given number x in an unsorted array A[1.....n] having n distinct values:" }, { "code": null, "e": 250, "s": 154, "text": " 1. Choose an i uniformaly at random from 1..... n;\n 2. If A[i] = x then Stop else Goto 1; " }, { "code": null, "e": 421, "s": 250, "text": "Assuming that x is present in A, what is the expected number of comparisons made by the algorithm before it terminates ?(A) n(B) n – 1(C) 2n(D) n/2Answer: (A)Explanation:" }, { "code": null, "e": 511, "s": 421, "text": "If you remember the coin and dice questions, you can just guess the answer for the above." }, { "code": null, "e": 542, "s": 511, "text": "Below is proof for the answer." }, { "code": null, "e": 653, "s": 542, "text": "Let expected number of comparisons be E. Value of E is sum of following expression for all the possible cases." }, { "code": null, "e": 715, "s": 653, "text": "number_of_comparisons_for_a_case * probability_for_the_case \n" }, { "code": null, "e": 722, "s": 715, "text": "Case 1" }, { "code": null, "e": 825, "s": 722, "text": " If A[i] is found in the first attempt \n number of comparisons = 1\n probability of the case = 1/n\n" }, { "code": null, "e": 832, "s": 825, "text": "Case 2" }, { "code": null, "e": 944, "s": 832, "text": " If A[i] is found in the second attempt \n number of comparisons = 2\n probability of the case = (n-1)/n*1/n\n" }, { "code": null, "e": 951, "s": 944, "text": "Case 3" }, { "code": null, "e": 1070, "s": 951, "text": " If A[i] is found in the third attempt \n number of comparisons = 2\n probability of the case = (n-1)/n*(n-1)/n*1/n\n" }, { "code": null, "e": 1155, "s": 1070, "text": "There are actually infinite such cases. So, we have following infinite series for E." }, { "code": null, "e": 1227, "s": 1155, "text": "E = 1/n + [(n-1)/n]*[1/n]*2 + [(n-1)/n]*[(n-1)/n]*[1/n]*3 + .... (1)\n" }, { "code": null, "e": 1279, "s": 1227, "text": "After multiplying equation (1) with (n-1)/n, we get" }, { "code": null, "e": 1426, "s": 1279, "text": "E (n-1)/n = [(n-1)/n]*[1/n] + [(n-1)/n]*[(n-1)/n]*[1/n]*2 + \n [(n-1)/n]*[(n-1)/n]*[(n-1)/n]*[1/n]*3 ..........(2)\n" }, { "code": null, "e": 1459, "s": 1426, "text": "Subtracting (2) from (1), we get" }, { "code": null, "e": 1521, "s": 1459, "text": "E/n = 1/n + (n-1)/n*1/n + (n-1)/n*(n-1)/n*1/n + ............\n" }, { "code": null, "e": 1621, "s": 1521, "text": "The expression on right side is a GP with infinite elements. Let us apply the sum formula (a/(1-r))" }, { "code": null, "e": 1661, "s": 1621, "text": " E/n = [1/n]/[1-(n-1)/n] = 1\n E = n\n" }, { "code": null, "e": 1683, "s": 1661, "text": "Quiz of this Question" }, { "code": null, "e": 1696, "s": 1683, "text": "GATE-CS-2002" }, { "code": null, "e": 1714, "s": 1696, "text": "GATE-GATE-CS-2002" }, { "code": null, "e": 1719, "s": 1714, "text": "GATE" }, { "code": null, "e": 1817, "s": 1719, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1859, "s": 1817, "text": "GATE | GATE-CS-2014-(Set-2) | Question 65" }, { "code": null, "e": 1921, "s": 1859, "text": "GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33" }, { "code": null, "e": 1963, "s": 1921, "text": "GATE | GATE-CS-2014-(Set-3) | Question 65" }, { "code": null, "e": 2005, "s": 1963, "text": "GATE | GATE-CS-2015 (Set 3) | Question 65" }, { "code": null, "e": 2039, "s": 2005, "text": "GATE | GATE CS 2008 | Question 46" }, { "code": null, "e": 2073, "s": 2039, "text": "GATE | GATE CS 2011 | Question 49" }, { "code": null, "e": 2107, "s": 2073, "text": "GATE | GATE CS 1996 | Question 38" }, { "code": null, "e": 2141, "s": 2107, "text": "GATE | GATE-CS-2004 | Question 31" }, { "code": null, "e": 2175, "s": 2141, "text": "GATE | GATE IT 2006 | Question 20" } ]
Given a sequence of words, print all anagrams together | Set 2
07 Jun, 2022 Given an array of words, print all anagrams together. For example, if the given array is {“cat”, “dog”, “tac”, “god”, “act”}, then output may be “cat tac act dog god”. We have discussed two different methods in the previous post. In this post, a more efficient solution is discussed.Trie data structure can be used for a more efficient solution. Insert the sorted order of each word in the trie. Since all the anagrams will end at the same leaf node. We can start a linked list at the leaf nodes where each node represents the index of the original array of words. Finally, traverse the Trie. While traversing the Trie, traverse each linked list one line at a time. Following are the detailed steps.1) Create an empty Trie 2) One by one take all words of input sequence. Do following for each word ...a) Copy the word to a buffer. ...b) Sort the buffer ...c) Insert the sorted buffer and index of this word to Trie. Each leaf node of Trie is head of a Index list. The Index list stores index of words in original sequence. If sorted buffer is already present, we insert index of this word to the index list. 3) Traverse Trie. While traversing, if you reach a leaf node, traverse the index list. And print all words using the index obtained from Index list. Below is the implementation of the above approach: C++ Java C# Javascript // An efficient program to print all anagrams together#include <stdio.h>#include <stdlib.h>#include <string.h>#include <ctype.h> #define NO_OF_CHARS 26 // Structure to represent list node for indexes of words in// the given sequence. The list nodes are used to connect// anagrams at leaf nodes of Triestruct IndexNode{ int index; struct IndexNode* next;}; // Structure to represent a Trie Nodestruct TrieNode{ bool isEnd; // indicates end of word struct TrieNode* child[NO_OF_CHARS]; // 26 slots each for 'a' to 'z' struct IndexNode* head; // head of the index list}; // A utility function to create a new Trie nodestruct TrieNode* newTrieNode(){ struct TrieNode* temp = new TrieNode; temp->isEnd = 0; temp->head = NULL; for (int i = 0; i < NO_OF_CHARS; ++i) temp->child[i] = NULL; return temp;} /* Following function is needed for library function qsort(). Refer http://www.cplusplus.com/reference/clibrary/cstdlib/qsort/ */int compare(const void* a, const void* b){ return *(char*)a - *(char*)b; } /* A utility function to create a new linked list node */struct IndexNode* newIndexNode(int index){ struct IndexNode* temp = new IndexNode; temp->index = index; temp->next = NULL; return temp;} // A utility function to insert a word to Trievoid insert(struct TrieNode** root, char* word, int index){ // Base case if (*root == NULL) *root = newTrieNode(); if (*word != '\0') insert( &( (*root)->child[tolower(*word) - 'a'] ), word+1, index ); else // If end of the word reached { // Insert index of this word to end of index linked list if ((*root)->isEnd) { IndexNode* pCrawl = (*root)->head; while( pCrawl->next ) pCrawl = pCrawl->next; pCrawl->next = newIndexNode(index); } else // If Index list is empty { (*root)->isEnd = 1; (*root)->head = newIndexNode(index); } }} // This function traverses the built trie. When a leaf node is reached,// all words connected at that leaf node are anagrams. So it traverses// the list at leaf node and uses stored index to print original wordsvoid printAnagramsUtil(struct TrieNode* root, char *wordArr[]){ if (root == NULL) return; // If a lead node is reached, print all anagrams using the indexes // stored in index linked list if (root->isEnd) { // traverse the list IndexNode* pCrawl = root->head; while (pCrawl != NULL) { printf( "%s ", wordArr[ pCrawl->index ] ); pCrawl = pCrawl->next; } } for (int i = 0; i < NO_OF_CHARS; ++i) printAnagramsUtil(root->child[i], wordArr);} // The main function that prints all anagrams together. wordArr[] is input// sequence of words.void printAnagramsTogether(char* wordArr[], int size){ // Create an empty Trie struct TrieNode* root = NULL; // Iterate through all input words for (int i = 0; i < size; ++i) { // Create a buffer for this word and copy the word to buffer int len = strlen(wordArr[i]); char *buffer = new char[len+1]; strcpy(buffer, wordArr[i]); // Sort the buffer qsort( (void*)buffer, strlen(buffer), sizeof(char), compare ); // Insert the sorted buffer and its original index to Trie insert(&root, buffer, i); } // Traverse the built Trie and print all anagrams together printAnagramsUtil(root, wordArr);} // Driver program to test above functionsint main(){ char* wordArr[] = {"cat", "dog", "tac", "god", "act", "gdo"}; int size = sizeof(wordArr) / sizeof(wordArr[0]); printAnagramsTogether(wordArr, size); return 0;} // An efficient program to print all// anagrams together import java.util.Arrays;import java.util.LinkedList; public class GFG{ static final int NO_OF_CHARS = 26; // Class to represent a Trie Node static class TrieNode { boolean isEnd; // indicates end of word // 26 slots each for 'a' to 'z' TrieNode[] child = new TrieNode[NO_OF_CHARS]; // head of the index list LinkedList<Integer> head; // constructor public TrieNode() { isEnd = false; head = new LinkedList<>(); for (int i = 0; i < NO_OF_CHARS; ++i) child[i] = null; } } // A utility function to insert a word to Trie static TrieNode insert(TrieNode root,String word, int index, int i) { // Base case if (root == null) { root = new TrieNode(); } if (i < word.length() ) { int index1 = word.charAt(i) - 'a'; root.child[index1] = insert(root.child[index1], word, index, i+1 ); } else // If end of the word reached { // Insert index of this word to end of // index linked list if (root.isEnd == true) { root.head.add(index); } else // If Index list is empty { root.isEnd = true; root.head.add(index); } } return root; } // This function traverses the built trie. When a leaf // node is reached, all words connected at that leaf // node are anagrams. So it traverses the list at leaf // node and uses stored index to print original words static void printAnagramsUtil(TrieNode root, String wordArr[]) { if (root == null) return; // If a lead node is reached, print all anagrams // using the indexes stored in index linked list if (root.isEnd) { // traverse the list for(Integer pCrawl: root.head) System.out.println(wordArr[pCrawl]); } for (int i = 0; i < NO_OF_CHARS; ++i) printAnagramsUtil(root.child[i], wordArr); } // The main function that prints all anagrams together. // wordArr[] is input sequence of words. static void printAnagramsTogether(String wordArr[], int size) { // Create an empty Trie TrieNode root = null; // Iterate through all input words for (int i = 0; i < size; ++i) { // Create a buffer for this word and copy the // word to buffer char[] buffer = wordArr[i].toCharArray(); // Sort the buffer Arrays.sort(buffer); // Insert the sorted buffer and its original // index to Trie root = insert(root, new String(buffer), i, 0); } // Traverse the built Trie and print all anagrams // together printAnagramsUtil(root, wordArr); } // Driver program to test above functions public static void main(String args[]) { String wordArr[] = {"cat", "dog", "tac", "god", "act", "gdo"}; int size = wordArr.length; printAnagramsTogether(wordArr, size); }}// This code is contributed by Sumit Ghosh // An efficient C# program to print all// anagrams togetherusing System;using System.Collections.Generic; class GFG{ static readonly int NO_OF_CHARS = 26; // Class to represent a Trie Node public class TrieNode { // indicates end of word public bool isEnd; // 26 slots each for 'a' to 'z' public TrieNode[] child = new TrieNode[NO_OF_CHARS]; // head of the index list public List<int> head; // constructor public TrieNode() { isEnd = false; head = new List<int>(); for (int i = 0; i < NO_OF_CHARS; ++i) child[i] = null; } } // A utility function to insert a word to Trie static TrieNode insert(TrieNode root,String word, int index, int i) { // Base case if (root == null) { root = new TrieNode(); } if (i < word.Length ) { int index1 = word[i] - 'a'; root.child[index1] = insert(root.child[index1], word, index, i + 1 ); } // If end of the word reached else { // Insert index of this word to end of // index linked list if (root.isEnd == true) { root.head.Add(index); } // If Index list is empty else { root.isEnd = true; root.head.Add(index); } } return root; } // This function traverses the built trie. // When a leaf node is reached, all words // connected at that leaf node are anagrams. // So it traverses the list at leaf node // and uses stored index to print original words static void printAnagramsUtil(TrieNode root, String []wordArr) { if (root == null) return; // If a lead node is reached, // print all anagrams using the // indexes stored in index linked list if (root.isEnd) { // traverse the list foreach(int pCrawl in root.head) Console.WriteLine(wordArr[pCrawl]); } for (int i = 0; i < NO_OF_CHARS; ++i) printAnagramsUtil(root.child[i], wordArr); } // The main function that prints // all anagrams together. wordArr[] // is input sequence of words. static void printAnagramsTogether(String []wordArr, int size) { // Create an empty Trie TrieNode root = null; // Iterate through all input words for (int i = 0; i < size; ++i) { // Create a buffer for this word // and copy the word to buffer char[] buffer = wordArr[i].ToCharArray(); // Sort the buffer Array.Sort(buffer); // Insert the sorted buffer and // its original index to Trie root = insert(root, new String(buffer), i, 0); } // Traverse the built Trie and // print all anagrams together printAnagramsUtil(root, wordArr); } // Driver code public static void Main(String []args) { String []wordArr = {"cat", "dog", "tac", "god", "act", "gdo"}; int size = wordArr.Length; printAnagramsTogether(wordArr, size); }} // This code is contributed by 29AjayKumar <script>// An efficient program to print all// anagrams together let NO_OF_CHARS = 26; // Class to represent a Trie Nodeclass TrieNode{ constructor() { this.isEnd = false; // indicates end of word // 26 slots each for 'a' to 'z' this.child = new Array(NO_OF_CHARS); for (let i = 0; i < NO_OF_CHARS; ++i) this.child[i] = null; // head of the index list this.head=[]; }} // A utility function to insert a word to Triefunction insert(root,word,index,i){ // Base case if (root == null) { root = new TrieNode(); } if (i < word.length ) { let index1 = word[i].charCodeAt(0) - 'a'.charCodeAt(0); root.child[index1] = insert(root.child[index1], word, index, i+1 ); } else // If end of the word reached { // Insert index of this word to end of // index linked list if (root.isEnd == true) { root.head.push(index); } else // If Index list is empty { root.isEnd = true; root.head.push(index); } } return root;} // This function traverses the built trie. When a leaf // node is reached, all words connected at that leaf // node are anagrams. So it traverses the list at leaf // node and uses stored index to print original wordsfunction printAnagramsUtil(root,wordArr){ if (root == null) return; // If a lead node is reached, print all anagrams // using the indexes stored in index linked list if (root.isEnd) { // traverse the list for(let pCrawl=0;pCrawl<root.head.length;pCrawl++) document.write(wordArr[root.head[pCrawl]]+"<br>"); } for (let i = 0; i < NO_OF_CHARS; ++i) printAnagramsUtil(root.child[i], wordArr);} // The main function that prints all anagrams together. // wordArr[] is input sequence of words.function printAnagramsTogether(wordArr,size){ // Create an empty Trie let root = null; // Iterate through all input words for (let i = 0; i < size; ++i) { // Create a buffer for this word and copy the // word to buffer let buffer = wordArr[i].split(""); // Sort the buffer (buffer).sort(); // Insert the sorted buffer and its original // index to Trie root = insert(root, (buffer).join(""), i, 0); } // Traverse the built Trie and print all anagrams // together printAnagramsUtil(root, wordArr);} // Driver program to test above functionslet wordArr=["cat", "dog", "tac", "god", "act", "gdo"]; let size = wordArr.length;printAnagramsTogether(wordArr, size); // This code is contributed by rag2127</script> Output: cat tac act dog god gdo Time Complexity : O(MN+N*MlogM) time where- N = Number of stringsM = Length of the largest string Inserting all the words in the trie takes O(MN) time and sorting the buffer takes O(N*MlogM) timeAuxiliary Space : To store all the strings we need to allocate O(26*M*N) ~ O(MN) space for the Trie.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. reyaz_ahmed 29AjayKumar rag2127 surindertarika1234 pall58183 hasani Amazon anagram Snapdeal Advanced Data Structure Hash Strings Amazon Snapdeal Hash Strings anagram 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) Binary Indexed Tree or Fenwick Tree AVL Tree | Set 2 (Deletion) 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) Count pairs with given sum Longest Consecutive Subsequence
[ { "code": null, "e": 52, "s": 24, "text": "\n07 Jun, 2022" }, { "code": null, "e": 220, "s": 52, "text": "Given an array of words, print all anagrams together. For example, if the given array is {“cat”, “dog”, “tac”, “god”, “act”}, then output may be “cat tac act dog god”." }, { "code": null, "e": 1310, "s": 220, "text": "We have discussed two different methods in the previous post. In this post, a more efficient solution is discussed.Trie data structure can be used for a more efficient solution. Insert the sorted order of each word in the trie. Since all the anagrams will end at the same leaf node. We can start a linked list at the leaf nodes where each node represents the index of the original array of words. Finally, traverse the Trie. While traversing the Trie, traverse each linked list one line at a time. Following are the detailed steps.1) Create an empty Trie 2) One by one take all words of input sequence. Do following for each word ...a) Copy the word to a buffer. ...b) Sort the buffer ...c) Insert the sorted buffer and index of this word to Trie. Each leaf node of Trie is head of a Index list. The Index list stores index of words in original sequence. If sorted buffer is already present, we insert index of this word to the index list. 3) Traverse Trie. While traversing, if you reach a leaf node, traverse the index list. And print all words using the index obtained from Index list. " }, { "code": null, "e": 1361, "s": 1310, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 1365, "s": 1361, "text": "C++" }, { "code": null, "e": 1370, "s": 1365, "text": "Java" }, { "code": null, "e": 1373, "s": 1370, "text": "C#" }, { "code": null, "e": 1384, "s": 1373, "text": "Javascript" }, { "code": "// An efficient program to print all anagrams together#include <stdio.h>#include <stdlib.h>#include <string.h>#include <ctype.h> #define NO_OF_CHARS 26 // Structure to represent list node for indexes of words in// the given sequence. The list nodes are used to connect// anagrams at leaf nodes of Triestruct IndexNode{ int index; struct IndexNode* next;}; // Structure to represent a Trie Nodestruct TrieNode{ bool isEnd; // indicates end of word struct TrieNode* child[NO_OF_CHARS]; // 26 slots each for 'a' to 'z' struct IndexNode* head; // head of the index list}; // A utility function to create a new Trie nodestruct TrieNode* newTrieNode(){ struct TrieNode* temp = new TrieNode; temp->isEnd = 0; temp->head = NULL; for (int i = 0; i < NO_OF_CHARS; ++i) temp->child[i] = NULL; return temp;} /* Following function is needed for library function qsort(). Refer http://www.cplusplus.com/reference/clibrary/cstdlib/qsort/ */int compare(const void* a, const void* b){ return *(char*)a - *(char*)b; } /* A utility function to create a new linked list node */struct IndexNode* newIndexNode(int index){ struct IndexNode* temp = new IndexNode; temp->index = index; temp->next = NULL; return temp;} // A utility function to insert a word to Trievoid insert(struct TrieNode** root, char* word, int index){ // Base case if (*root == NULL) *root = newTrieNode(); if (*word != '\\0') insert( &( (*root)->child[tolower(*word) - 'a'] ), word+1, index ); else // If end of the word reached { // Insert index of this word to end of index linked list if ((*root)->isEnd) { IndexNode* pCrawl = (*root)->head; while( pCrawl->next ) pCrawl = pCrawl->next; pCrawl->next = newIndexNode(index); } else // If Index list is empty { (*root)->isEnd = 1; (*root)->head = newIndexNode(index); } }} // This function traverses the built trie. When a leaf node is reached,// all words connected at that leaf node are anagrams. So it traverses// the list at leaf node and uses stored index to print original wordsvoid printAnagramsUtil(struct TrieNode* root, char *wordArr[]){ if (root == NULL) return; // If a lead node is reached, print all anagrams using the indexes // stored in index linked list if (root->isEnd) { // traverse the list IndexNode* pCrawl = root->head; while (pCrawl != NULL) { printf( \"%s \", wordArr[ pCrawl->index ] ); pCrawl = pCrawl->next; } } for (int i = 0; i < NO_OF_CHARS; ++i) printAnagramsUtil(root->child[i], wordArr);} // The main function that prints all anagrams together. wordArr[] is input// sequence of words.void printAnagramsTogether(char* wordArr[], int size){ // Create an empty Trie struct TrieNode* root = NULL; // Iterate through all input words for (int i = 0; i < size; ++i) { // Create a buffer for this word and copy the word to buffer int len = strlen(wordArr[i]); char *buffer = new char[len+1]; strcpy(buffer, wordArr[i]); // Sort the buffer qsort( (void*)buffer, strlen(buffer), sizeof(char), compare ); // Insert the sorted buffer and its original index to Trie insert(&root, buffer, i); } // Traverse the built Trie and print all anagrams together printAnagramsUtil(root, wordArr);} // Driver program to test above functionsint main(){ char* wordArr[] = {\"cat\", \"dog\", \"tac\", \"god\", \"act\", \"gdo\"}; int size = sizeof(wordArr) / sizeof(wordArr[0]); printAnagramsTogether(wordArr, size); return 0;}", "e": 5103, "s": 1384, "text": null }, { "code": "// An efficient program to print all// anagrams together import java.util.Arrays;import java.util.LinkedList; public class GFG{ static final int NO_OF_CHARS = 26; // Class to represent a Trie Node static class TrieNode { boolean isEnd; // indicates end of word // 26 slots each for 'a' to 'z' TrieNode[] child = new TrieNode[NO_OF_CHARS]; // head of the index list LinkedList<Integer> head; // constructor public TrieNode() { isEnd = false; head = new LinkedList<>(); for (int i = 0; i < NO_OF_CHARS; ++i) child[i] = null; } } // A utility function to insert a word to Trie static TrieNode insert(TrieNode root,String word, int index, int i) { // Base case if (root == null) { root = new TrieNode(); } if (i < word.length() ) { int index1 = word.charAt(i) - 'a'; root.child[index1] = insert(root.child[index1], word, index, i+1 ); } else // If end of the word reached { // Insert index of this word to end of // index linked list if (root.isEnd == true) { root.head.add(index); } else // If Index list is empty { root.isEnd = true; root.head.add(index); } } return root; } // This function traverses the built trie. When a leaf // node is reached, all words connected at that leaf // node are anagrams. So it traverses the list at leaf // node and uses stored index to print original words static void printAnagramsUtil(TrieNode root, String wordArr[]) { if (root == null) return; // If a lead node is reached, print all anagrams // using the indexes stored in index linked list if (root.isEnd) { // traverse the list for(Integer pCrawl: root.head) System.out.println(wordArr[pCrawl]); } for (int i = 0; i < NO_OF_CHARS; ++i) printAnagramsUtil(root.child[i], wordArr); } // The main function that prints all anagrams together. // wordArr[] is input sequence of words. static void printAnagramsTogether(String wordArr[], int size) { // Create an empty Trie TrieNode root = null; // Iterate through all input words for (int i = 0; i < size; ++i) { // Create a buffer for this word and copy the // word to buffer char[] buffer = wordArr[i].toCharArray(); // Sort the buffer Arrays.sort(buffer); // Insert the sorted buffer and its original // index to Trie root = insert(root, new String(buffer), i, 0); } // Traverse the built Trie and print all anagrams // together printAnagramsUtil(root, wordArr); } // Driver program to test above functions public static void main(String args[]) { String wordArr[] = {\"cat\", \"dog\", \"tac\", \"god\", \"act\", \"gdo\"}; int size = wordArr.length; printAnagramsTogether(wordArr, size); }}// This code is contributed by Sumit Ghosh", "e": 8683, "s": 5103, "text": null }, { "code": "// An efficient C# program to print all// anagrams togetherusing System;using System.Collections.Generic; class GFG{ static readonly int NO_OF_CHARS = 26; // Class to represent a Trie Node public class TrieNode { // indicates end of word public bool isEnd; // 26 slots each for 'a' to 'z' public TrieNode[] child = new TrieNode[NO_OF_CHARS]; // head of the index list public List<int> head; // constructor public TrieNode() { isEnd = false; head = new List<int>(); for (int i = 0; i < NO_OF_CHARS; ++i) child[i] = null; } } // A utility function to insert a word to Trie static TrieNode insert(TrieNode root,String word, int index, int i) { // Base case if (root == null) { root = new TrieNode(); } if (i < word.Length ) { int index1 = word[i] - 'a'; root.child[index1] = insert(root.child[index1], word, index, i + 1 ); } // If end of the word reached else { // Insert index of this word to end of // index linked list if (root.isEnd == true) { root.head.Add(index); } // If Index list is empty else { root.isEnd = true; root.head.Add(index); } } return root; } // This function traverses the built trie. // When a leaf node is reached, all words // connected at that leaf node are anagrams. // So it traverses the list at leaf node // and uses stored index to print original words static void printAnagramsUtil(TrieNode root, String []wordArr) { if (root == null) return; // If a lead node is reached, // print all anagrams using the // indexes stored in index linked list if (root.isEnd) { // traverse the list foreach(int pCrawl in root.head) Console.WriteLine(wordArr[pCrawl]); } for (int i = 0; i < NO_OF_CHARS; ++i) printAnagramsUtil(root.child[i], wordArr); } // The main function that prints // all anagrams together. wordArr[] // is input sequence of words. static void printAnagramsTogether(String []wordArr, int size) { // Create an empty Trie TrieNode root = null; // Iterate through all input words for (int i = 0; i < size; ++i) { // Create a buffer for this word // and copy the word to buffer char[] buffer = wordArr[i].ToCharArray(); // Sort the buffer Array.Sort(buffer); // Insert the sorted buffer and // its original index to Trie root = insert(root, new String(buffer), i, 0); } // Traverse the built Trie and // print all anagrams together printAnagramsUtil(root, wordArr); } // Driver code public static void Main(String []args) { String []wordArr = {\"cat\", \"dog\", \"tac\", \"god\", \"act\", \"gdo\"}; int size = wordArr.Length; printAnagramsTogether(wordArr, size); }} // This code is contributed by 29AjayKumar", "e": 12280, "s": 8683, "text": null }, { "code": "<script>// An efficient program to print all// anagrams together let NO_OF_CHARS = 26; // Class to represent a Trie Nodeclass TrieNode{ constructor() { this.isEnd = false; // indicates end of word // 26 slots each for 'a' to 'z' this.child = new Array(NO_OF_CHARS); for (let i = 0; i < NO_OF_CHARS; ++i) this.child[i] = null; // head of the index list this.head=[]; }} // A utility function to insert a word to Triefunction insert(root,word,index,i){ // Base case if (root == null) { root = new TrieNode(); } if (i < word.length ) { let index1 = word[i].charCodeAt(0) - 'a'.charCodeAt(0); root.child[index1] = insert(root.child[index1], word, index, i+1 ); } else // If end of the word reached { // Insert index of this word to end of // index linked list if (root.isEnd == true) { root.head.push(index); } else // If Index list is empty { root.isEnd = true; root.head.push(index); } } return root;} // This function traverses the built trie. When a leaf // node is reached, all words connected at that leaf // node are anagrams. So it traverses the list at leaf // node and uses stored index to print original wordsfunction printAnagramsUtil(root,wordArr){ if (root == null) return; // If a lead node is reached, print all anagrams // using the indexes stored in index linked list if (root.isEnd) { // traverse the list for(let pCrawl=0;pCrawl<root.head.length;pCrawl++) document.write(wordArr[root.head[pCrawl]]+\"<br>\"); } for (let i = 0; i < NO_OF_CHARS; ++i) printAnagramsUtil(root.child[i], wordArr);} // The main function that prints all anagrams together. // wordArr[] is input sequence of words.function printAnagramsTogether(wordArr,size){ // Create an empty Trie let root = null; // Iterate through all input words for (let i = 0; i < size; ++i) { // Create a buffer for this word and copy the // word to buffer let buffer = wordArr[i].split(\"\"); // Sort the buffer (buffer).sort(); // Insert the sorted buffer and its original // index to Trie root = insert(root, (buffer).join(\"\"), i, 0); } // Traverse the built Trie and print all anagrams // together printAnagramsUtil(root, wordArr);} // Driver program to test above functionslet wordArr=[\"cat\", \"dog\", \"tac\", \"god\", \"act\", \"gdo\"]; let size = wordArr.length;printAnagramsTogether(wordArr, size); // This code is contributed by rag2127</script>", "e": 15396, "s": 12280, "text": null }, { "code": null, "e": 15405, "s": 15396, "text": "Output: " }, { "code": null, "e": 15429, "s": 15405, "text": "cat\ntac\nact\ndog\ngod\ngdo" }, { "code": null, "e": 15473, "s": 15429, "text": "Time Complexity : O(MN+N*MlogM) time where-" }, { "code": null, "e": 15527, "s": 15473, "text": "N = Number of stringsM = Length of the largest string" }, { "code": null, "e": 15850, "s": 15527, "text": "Inserting all the words in the trie takes O(MN) time and sorting the buffer takes O(N*MlogM) timeAuxiliary Space : To store all the strings we need to allocate O(26*M*N) ~ O(MN) space for the Trie.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 15862, "s": 15850, "text": "reyaz_ahmed" }, { "code": null, "e": 15874, "s": 15862, "text": "29AjayKumar" }, { "code": null, "e": 15882, "s": 15874, "text": "rag2127" }, { "code": null, "e": 15901, "s": 15882, "text": "surindertarika1234" }, { "code": null, "e": 15911, "s": 15901, "text": "pall58183" }, { "code": null, "e": 15918, "s": 15911, "text": "hasani" }, { "code": null, "e": 15925, "s": 15918, "text": "Amazon" }, { "code": null, "e": 15933, "s": 15925, "text": "anagram" }, { "code": null, "e": 15942, "s": 15933, "text": "Snapdeal" }, { "code": null, "e": 15966, "s": 15942, "text": "Advanced Data Structure" }, { "code": null, "e": 15971, "s": 15966, "text": "Hash" }, { "code": null, "e": 15979, "s": 15971, "text": "Strings" }, { "code": null, "e": 15986, "s": 15979, "text": "Amazon" }, { "code": null, "e": 15995, "s": 15986, "text": "Snapdeal" }, { "code": null, "e": 16000, "s": 15995, "text": "Hash" }, { "code": null, "e": 16008, "s": 16000, "text": "Strings" }, { "code": null, "e": 16016, "s": 16008, "text": "anagram" }, { "code": null, "e": 16114, "s": 16016, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 16148, "s": 16114, "text": "Agents in Artificial Intelligence" }, { "code": null, "e": 16188, "s": 16148, "text": "Decision Tree Introduction with example" }, { "code": null, "e": 16230, "s": 16188, "text": "Segment Tree | Set 1 (Sum of given range)" }, { "code": null, "e": 16266, "s": 16230, "text": "Binary Indexed Tree or Fenwick Tree" }, { "code": null, "e": 16294, "s": 16266, "text": "AVL Tree | Set 2 (Deletion)" }, { "code": null, "e": 16379, "s": 16294, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 16417, "s": 16379, "text": "What is Hashing | A Complete Tutorial" }, { "code": null, "e": 16448, "s": 16417, "text": "Hashing | Set 1 (Introduction)" }, { "code": null, "e": 16475, "s": 16448, "text": "Count pairs with given sum" } ]
SQL Query to Add a New Column After an Existing Column in SQL
29 Sep, 2021 Structured Query Language or SQL is a standard Database language that is used to create, maintain and retrieve the data from relational databases like MySQL, Oracle, SQL Server, Postgres, etc. In Microsoft SQL Server, we can change the order of the columns and can add a new column by using ALTER command. ALTER TABLE is used to add, delete/drop or modify columns in the existing table. It is also used to add and drop various constraints on the existing table. Step 1: Create a database Let’s create a database employee. Query: CREATE DATABASE employee; Step 2: Create a table Now create a table employee_info. Query: CREATE TABLE employee_info ( Employee_id INT, First_Name VARCHAR(25), Last_Name VARCHAR(25), Salary INT, City VARCHAR(20)); INSERT INTO employee_info VALUES (1,'Monika','Singh',800000,'Nashik'), (2,'Rahul','Kumar',450000,'Mumbai'), (3,'Sushant','Kumar',500000,'Pune'), (4,'Ajay','Mehta',600000,'Mumbai'); Step 3: To view a database schema we use the following query. Query: EXEC sp_help 'dbo.employee_info'; Output: Now, let’s add a new column Gender in the table. Then we use ALTER table command. Step 4: Alter table. ALTER TABLE employee_info ADD Gender CHAR(1) CHECK (Gender IN ('M','F')); Output: Now, the new column gets added after City i.e. at the last successfully. Take another case using a query, If we want the Gender column after Last_Name, then we can write the query as shown below. Query: SELECT Employee_Id,First_Name,Last_Name,Gender,Salary,City FROM employee_info; Output: Blogathon-2021 Picked SQL-Query SQL-Server Blogathon SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Connect Python with SQL Database? How to Import JSON Data into SQL Server? Data Mining - Cluster Analysis Explain the purpose of render() in ReactJS How to build a basic CRUD app with Node.js and ReactJS ? SQL | DDL, DQL, DML, DCL and TCL Commands SQL | Join (Inner, Left, Right and Full Joins) SQL | WITH clause How to find Nth highest salary from a table CTE in SQL
[ { "code": null, "e": 28, "s": 0, "text": "\n29 Sep, 2021" }, { "code": null, "e": 490, "s": 28, "text": "Structured Query Language or SQL is a standard Database language that is used to create, maintain and retrieve the data from relational databases like MySQL, Oracle, SQL Server, Postgres, etc. In Microsoft SQL Server, we can change the order of the columns and can add a new column by using ALTER command. ALTER TABLE is used to add, delete/drop or modify columns in the existing table. It is also used to add and drop various constraints on the existing table." }, { "code": null, "e": 516, "s": 490, "text": "Step 1: Create a database" }, { "code": null, "e": 550, "s": 516, "text": "Let’s create a database employee." }, { "code": null, "e": 557, "s": 550, "text": "Query:" }, { "code": null, "e": 583, "s": 557, "text": "CREATE DATABASE employee;" }, { "code": null, "e": 606, "s": 583, "text": "Step 2: Create a table" }, { "code": null, "e": 640, "s": 606, "text": "Now create a table employee_info." }, { "code": null, "e": 647, "s": 640, "text": "Query:" }, { "code": null, "e": 954, "s": 647, "text": "CREATE TABLE employee_info\n( Employee_id INT,\nFirst_Name VARCHAR(25),\nLast_Name VARCHAR(25),\nSalary INT,\nCity VARCHAR(20)); \n\nINSERT INTO employee_info\nVALUES (1,'Monika','Singh',800000,'Nashik'),\n(2,'Rahul','Kumar',450000,'Mumbai'),\n(3,'Sushant','Kumar',500000,'Pune'),\n(4,'Ajay','Mehta',600000,'Mumbai');" }, { "code": null, "e": 1016, "s": 954, "text": "Step 3: To view a database schema we use the following query." }, { "code": null, "e": 1023, "s": 1016, "text": "Query:" }, { "code": null, "e": 1057, "s": 1023, "text": "EXEC sp_help 'dbo.employee_info';" }, { "code": null, "e": 1065, "s": 1057, "text": "Output:" }, { "code": null, "e": 1148, "s": 1065, "text": "Now, let’s add a new column Gender in the table. Then we use ALTER table command. " }, { "code": null, "e": 1169, "s": 1148, "text": "Step 4: Alter table." }, { "code": null, "e": 1243, "s": 1169, "text": "ALTER TABLE employee_info ADD Gender CHAR(1) CHECK (Gender IN ('M','F'));" }, { "code": null, "e": 1251, "s": 1243, "text": "Output:" }, { "code": null, "e": 1324, "s": 1251, "text": "Now, the new column gets added after City i.e. at the last successfully." }, { "code": null, "e": 1447, "s": 1324, "text": "Take another case using a query, If we want the Gender column after Last_Name, then we can write the query as shown below." }, { "code": null, "e": 1454, "s": 1447, "text": "Query:" }, { "code": null, "e": 1533, "s": 1454, "text": "SELECT Employee_Id,First_Name,Last_Name,Gender,Salary,City FROM employee_info;" }, { "code": null, "e": 1541, "s": 1533, "text": "Output:" }, { "code": null, "e": 1556, "s": 1541, "text": "Blogathon-2021" }, { "code": null, "e": 1563, "s": 1556, "text": "Picked" }, { "code": null, "e": 1573, "s": 1563, "text": "SQL-Query" }, { "code": null, "e": 1584, "s": 1573, "text": "SQL-Server" }, { "code": null, "e": 1594, "s": 1584, "text": "Blogathon" }, { "code": null, "e": 1598, "s": 1594, "text": "SQL" }, { "code": null, "e": 1602, "s": 1598, "text": "SQL" }, { "code": null, "e": 1700, "s": 1602, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1741, "s": 1700, "text": "How to Connect Python with SQL Database?" }, { "code": null, "e": 1782, "s": 1741, "text": "How to Import JSON Data into SQL Server?" }, { "code": null, "e": 1813, "s": 1782, "text": "Data Mining - Cluster Analysis" }, { "code": null, "e": 1856, "s": 1813, "text": "Explain the purpose of render() in ReactJS" }, { "code": null, "e": 1913, "s": 1856, "text": "How to build a basic CRUD app with Node.js and ReactJS ?" }, { "code": null, "e": 1955, "s": 1913, "text": "SQL | DDL, DQL, DML, DCL and TCL Commands" }, { "code": null, "e": 2002, "s": 1955, "text": "SQL | Join (Inner, Left, Right and Full Joins)" }, { "code": null, "e": 2020, "s": 2002, "text": "SQL | WITH clause" }, { "code": null, "e": 2064, "s": 2020, "text": "How to find Nth highest salary from a table" } ]
How to convert string to binary in Python?
To convert a string to binary, you need to iterate over each character and convert it to binary. Then join these characters together in a single string. You can use format(ord(x), 'b') to format the character x as binary. For example: >>>st = "hello world" >>>' '.join(format(ord(x), 'b') for x in st) '11010001100101 1101100 1101100 1101111 100000 1110111 1101111 1110010 1101100 1100100' You can alsomap all characters to bin(number) using bytearray to get the array of allcharacters in binary. For example: >>>st = "hello world" >>>map(bin,bytearray(st)) ['0b1101000','0b1100101', '0b1101100', '0b1101100', '0b1101111', '0b100000', '0b1110111','0b1101111', '0b1110010', '0b1101100', '0b1100100']
[ { "code": null, "e": 1297, "s": 1062, "text": "To convert a string to binary, you need to iterate over each character and convert it to binary. Then join these characters together in a single string. You can use format(ord(x), 'b') to format the character x as binary. For example:" }, { "code": null, "e": 1452, "s": 1297, "text": ">>>st = \"hello world\"\n>>>' '.join(format(ord(x), 'b') for x in st)\n'11010001100101 1101100 1101100 1101111 100000 1110111 1101111 1110010 1101100 1100100'" }, { "code": null, "e": 1573, "s": 1452, "text": " You can alsomap all characters to bin(number) using bytearray to get the array of allcharacters in binary. For example:" }, { "code": null, "e": 1762, "s": 1573, "text": ">>>st = \"hello world\"\n>>>map(bin,bytearray(st))\n['0b1101000','0b1100101', '0b1101100', '0b1101100', '0b1101111', '0b100000', '0b1110111','0b1101111', '0b1110010', '0b1101100', '0b1100100']" } ]
C++ Pointer to Pointer (Multiple Indirection)
A pointer to a pointer is a form of multiple indirection or a chain of pointers. Normally, a pointer contains the address of a variable. When we define a pointer to a pointer, the first pointer contains the address of the second pointer, which points to the location that contains the actual value as shown below. A variable that is a pointer to a pointer must be declared as such. This is done by placing an additional asterisk in front of its name. For example, following is the declaration to declare a pointer to a pointer of type int − int **var; When a target value is indirectly pointed to by a pointer to a pointer, accessing that value requires that the asterisk operator be applied twice, as is shown below in the example − #include <iostream> using namespace std; int main () { int var; int *ptr; int **pptr; var = 3000; // take the address of var ptr = &var; // take the address of ptr using address of operator & pptr = &ptr; // take the value using pptr cout << "Value of var :" << var << endl; cout << "Value available at *ptr :" << *ptr << endl; cout << "Value available at **pptr :" << **pptr << endl; return 0; } When the above code is compiled and executed, it produces the following result − Value of var :3000 Value available at *ptr :3000 Value available at **pptr :3000 154 Lectures 11.5 hours Arnab Chakraborty 14 Lectures 57 mins Kaushik Roy Chowdhury 30 Lectures 12.5 hours Frahaan Hussain 54 Lectures 3.5 hours Frahaan Hussain 77 Lectures 5.5 hours Frahaan Hussain 12 Lectures 3.5 hours Frahaan Hussain Print Add Notes Bookmark this page
[ { "code": null, "e": 2632, "s": 2318, "text": "A pointer to a pointer is a form of multiple indirection or a chain of pointers. Normally, a pointer contains the address of a variable. When we define a pointer to a pointer, the first pointer contains the address of the second pointer, which points to the location that contains the actual value as shown below." }, { "code": null, "e": 2860, "s": 2632, "text": "A variable that is a pointer to a pointer must be declared as such. This is done by placing an additional asterisk in front of its name. For example, following is the declaration to declare a pointer to a pointer of type int −" }, { "code": null, "e": 2872, "s": 2860, "text": "int **var;\n" }, { "code": null, "e": 3054, "s": 2872, "text": "When a target value is indirectly pointed to by a pointer to a pointer, accessing that value requires that the asterisk operator be applied twice, as is shown below in the example −" }, { "code": null, "e": 3502, "s": 3054, "text": "#include <iostream>\n \nusing namespace std;\n \nint main () {\n int var;\n int *ptr;\n int **pptr;\n\n var = 3000;\n\n // take the address of var\n ptr = &var;\n\n // take the address of ptr using address of operator &\n pptr = &ptr;\n\n // take the value using pptr\n cout << \"Value of var :\" << var << endl;\n cout << \"Value available at *ptr :\" << *ptr << endl;\n cout << \"Value available at **pptr :\" << **pptr << endl;\n\n return 0;\n}" }, { "code": null, "e": 3583, "s": 3502, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 3665, "s": 3583, "text": "Value of var :3000\nValue available at *ptr :3000\nValue available at **pptr :3000\n" }, { "code": null, "e": 3702, "s": 3665, "text": "\n 154 Lectures \n 11.5 hours \n" }, { "code": null, "e": 3721, "s": 3702, "text": " Arnab Chakraborty" }, { "code": null, "e": 3753, "s": 3721, "text": "\n 14 Lectures \n 57 mins\n" }, { "code": null, "e": 3776, "s": 3753, "text": " Kaushik Roy Chowdhury" }, { "code": null, "e": 3812, "s": 3776, "text": "\n 30 Lectures \n 12.5 hours \n" }, { "code": null, "e": 3829, "s": 3812, "text": " Frahaan Hussain" }, { "code": null, "e": 3864, "s": 3829, "text": "\n 54 Lectures \n 3.5 hours \n" }, { "code": null, "e": 3881, "s": 3864, "text": " Frahaan Hussain" }, { "code": null, "e": 3916, "s": 3881, "text": "\n 77 Lectures \n 5.5 hours \n" }, { "code": null, "e": 3933, "s": 3916, "text": " Frahaan Hussain" }, { "code": null, "e": 3968, "s": 3933, "text": "\n 12 Lectures \n 3.5 hours \n" }, { "code": null, "e": 3985, "s": 3968, "text": " Frahaan Hussain" }, { "code": null, "e": 3992, "s": 3985, "text": " Print" }, { "code": null, "e": 4003, "s": 3992, "text": " Add Notes" } ]
Enumerator (Enum) in MySQL - GeeksforGeeks
20 Sep, 2021 An ENUM is a string object whose value is decided from a set of permitted literals(Values) that are explicitly defined at the time of column creation. Benefits of Enum data type – Succinct data storage required to store data in limited size columns. The strings that you pass to the enum data types implicitly get the numerical numbering. It also provides readable queries and output easily because the numbers can be translated back to the result of the corresponding string. Enum syntax for columns : CREATE TABLE table_name ( col... col ENUM ('value_1','value_2','value_3', ....), col... ); MySQL allows us to define the ENUM data type with the following three attributes – NOT NULL – If we don’t want NULL values, it is required to use the NOT NULL property in the ENUM column. NULL – It is a synonym for DEFAULT NULL, and its index value is always NULL. DEFAULT – By default, the ENUM data type is NULL, if the user doesn’t want to pass any value to it. Example :Suppose, we want to store the student data in the table Student_grade in order to store the grades of students in the corresponding columns (High, Medium, Low). We use the priority statement to assign the priority to the Enum column. CREATE TABLE Student_grade( id INT PRIMARY KEY AUTO_INCREMENT, Grade VARCHAR(250) NOT NULL, priority ENUM('Low', 'Medium', 'High') NOT NULL ); The prioritized column will accept only three columns. Here, the order of numbering Low->1, Medium->2, High->3. Insert data into the table – Insert a new row into the table named Student_grade, the statement is as follows – INSERT INTO Student_grade(Grade, priority) VALUES('Good grades', 'High'); Instead of using the enumeration values, you can also use the numerical indexes too, in order to insert the values into the Enum column of the table – INSERT INTO Student_grade(Grade, priority) VALUES('Poor grades', 1); // Here we use 1 instead of using 'Low' enumeration value, since 1 is mapped to 'Low' implicitly. Let’s add more rows into the table Student_grade – INSERT INTO Student_grade(Grade, priority) VALUES('Mediocre grade', 'Medium'); INSERT INTO Student_grade(Grade) VALUES('Poor grades',1); INSERT INTO Student_grade(Grade) VALUES('Good grades','High'); Note : ENUM column can also store NULL values if it is defined as a null-able column. Output : The following statement brought all the high grades student results – SELECT * FROM Student_grade WHERE priority = 'High'; The same result you can get through this My SQL query – SELECT * FROM Student_grade WHERE priority = 3; The query below selects the Student_grade and sorts them by the priority from High to Low – SELECT Grade, priority FROM Student_grade ORDER BY priority DESC; Sort_data MySQL ENUM Disadvantages : If you are thinking of modifying enumeration members then you need to rebuild the entire table using the ALTER TABLE command, which has quite overhead in terms of used resources and time. It is very complex to get the complete enumeration list because in that case, you need to access the inform_schema database – SELECT colmn_type FROM inform_schema WHERE TABLE_NAME = 'Student_grade' AND COLUMN_NAME = 'priority'; Porting it to other RDBMS could be a hard task because ENUM is not an SQL’s standard datatype and not many database systems provide support to it. It isn’t possible to insert more values to the enumerated column. Suppose, you are interested to insert a service-based agreement for every priority e.x., High (48hrs), Medium (4-3 days), Low (1 week), but it is not as easy as it looks and pragmatic with ENUM data type. Enumerated list is not reusable. Because if, you want to create a new table named “Emp-List” and interested to reuse its priority list, so it is not possible. gulshankumarar231 DBMS-SQL mysql SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Update Multiple Columns in Single Update Statement in SQL? What is Temporary Table in SQL? SQL Query for Matching Multiple Values in the Same Column SQL using Python SQL Query to Insert Multiple Rows SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter SQL | Subquery SQL | SEQUENCES SQL | DROP, TRUNCATE SQL Query to Convert VARCHAR to INT
[ { "code": null, "e": 24212, "s": 24184, "text": "\n20 Sep, 2021" }, { "code": null, "e": 24363, "s": 24212, "text": "An ENUM is a string object whose value is decided from a set of permitted literals(Values) that are explicitly defined at the time of column creation." }, { "code": null, "e": 24392, "s": 24363, "text": "Benefits of Enum data type –" }, { "code": null, "e": 24552, "s": 24392, "text": "Succinct data storage required to store data in limited size columns. The strings that you pass to the enum data types implicitly get the numerical numbering. " }, { "code": null, "e": 24691, "s": 24552, "text": "It also provides readable queries and output easily because the numbers can be translated back to the result of the corresponding string. " }, { "code": null, "e": 24717, "s": 24691, "text": "Enum syntax for columns :" }, { "code": null, "e": 24814, "s": 24717, "text": "CREATE TABLE table_name (\n col...\n col ENUM ('value_1','value_2','value_3', ....),\n col...\n);" }, { "code": null, "e": 24898, "s": 24814, "text": "MySQL allows us to define the ENUM data type with the following three attributes –" }, { "code": null, "e": 25003, "s": 24898, "text": "NOT NULL – If we don’t want NULL values, it is required to use the NOT NULL property in the ENUM column." }, { "code": null, "e": 25080, "s": 25003, "text": "NULL – It is a synonym for DEFAULT NULL, and its index value is always NULL." }, { "code": null, "e": 25181, "s": 25080, "text": "DEFAULT – By default, the ENUM data type is NULL, if the user doesn’t want to pass any value to it. " }, { "code": null, "e": 25424, "s": 25181, "text": "Example :Suppose, we want to store the student data in the table Student_grade in order to store the grades of students in the corresponding columns (High, Medium, Low). We use the priority statement to assign the priority to the Enum column." }, { "code": null, "e": 25567, "s": 25424, "text": "CREATE TABLE Student_grade(\nid INT PRIMARY KEY AUTO_INCREMENT, Grade VARCHAR(250) NOT NULL,\npriority ENUM('Low', 'Medium', 'High') NOT NULL\n);" }, { "code": null, "e": 25679, "s": 25567, "text": "The prioritized column will accept only three columns. Here, the order of numbering Low->1, Medium->2, High->3." }, { "code": null, "e": 25708, "s": 25679, "text": "Insert data into the table –" }, { "code": null, "e": 25791, "s": 25708, "text": "Insert a new row into the table named Student_grade, the statement is as follows –" }, { "code": null, "e": 25865, "s": 25791, "text": "INSERT INTO Student_grade(Grade, priority)\nVALUES('Good grades', 'High');" }, { "code": null, "e": 26016, "s": 25865, "text": "Instead of using the enumeration values, you can also use the numerical indexes too, in order to insert the values into the Enum column of the table –" }, { "code": null, "e": 26184, "s": 26016, "text": "INSERT INTO Student_grade(Grade, priority)\nVALUES('Poor grades', 1);\n// Here we use 1 instead of using 'Low' enumeration value, \nsince 1 is mapped to 'Low' implicitly." }, { "code": null, "e": 26235, "s": 26184, "text": "Let’s add more rows into the table Student_grade –" }, { "code": null, "e": 26437, "s": 26235, "text": "INSERT INTO Student_grade(Grade, priority)\nVALUES('Mediocre grade', 'Medium');\n\nINSERT INTO Student_grade(Grade)\nVALUES('Poor grades',1);\n\nINSERT INTO Student_grade(Grade)\nVALUES('Good grades','High');" }, { "code": null, "e": 26523, "s": 26437, "text": "Note : ENUM column can also store NULL values if it is defined as a null-able column." }, { "code": null, "e": 26532, "s": 26523, "text": "Output :" }, { "code": null, "e": 26602, "s": 26532, "text": "The following statement brought all the high grades student results –" }, { "code": null, "e": 26655, "s": 26602, "text": "SELECT * FROM Student_grade\nWHERE priority = 'High';" }, { "code": null, "e": 26711, "s": 26655, "text": "The same result you can get through this My SQL query –" }, { "code": null, "e": 26759, "s": 26711, "text": "SELECT * FROM Student_grade\nWHERE priority = 3;" }, { "code": null, "e": 26851, "s": 26759, "text": "The query below selects the Student_grade and sorts them by the priority from High to Low –" }, { "code": null, "e": 26917, "s": 26851, "text": "SELECT Grade, priority FROM Student_grade\nORDER BY priority DESC;" }, { "code": null, "e": 26927, "s": 26917, "text": "Sort_data" }, { "code": null, "e": 26955, "s": 26927, "text": "MySQL ENUM Disadvantages : " }, { "code": null, "e": 27144, "s": 26955, "text": "If you are thinking of modifying enumeration members then you need to rebuild the entire table using the ALTER TABLE command, which has quite overhead in terms of used resources and time. " }, { "code": null, "e": 27270, "s": 27144, "text": "It is very complex to get the complete enumeration list because in that case, you need to access the inform_schema database –" }, { "code": null, "e": 27373, "s": 27270, "text": "SELECT colmn_type FROM inform_schema \nWHERE TABLE_NAME = 'Student_grade' AND COLUMN_NAME = 'priority';" }, { "code": null, "e": 27521, "s": 27373, "text": "Porting it to other RDBMS could be a hard task because ENUM is not an SQL’s standard datatype and not many database systems provide support to it. " }, { "code": null, "e": 27793, "s": 27521, "text": "It isn’t possible to insert more values to the enumerated column. Suppose, you are interested to insert a service-based agreement for every priority e.x., High (48hrs), Medium (4-3 days), Low (1 week), but it is not as easy as it looks and pragmatic with ENUM data type. " }, { "code": null, "e": 27953, "s": 27793, "text": "Enumerated list is not reusable. Because if, you want to create a new table named “Emp-List” and interested to reuse its priority list, so it is not possible. " }, { "code": null, "e": 27973, "s": 27955, "text": "gulshankumarar231" }, { "code": null, "e": 27982, "s": 27973, "text": "DBMS-SQL" }, { "code": null, "e": 27988, "s": 27982, "text": "mysql" }, { "code": null, "e": 27992, "s": 27988, "text": "SQL" }, { "code": null, "e": 27996, "s": 27992, "text": "SQL" }, { "code": null, "e": 28094, "s": 27996, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28103, "s": 28094, "text": "Comments" }, { "code": null, "e": 28116, "s": 28103, "text": "Old Comments" }, { "code": null, "e": 28182, "s": 28116, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 28214, "s": 28182, "text": "What is Temporary Table in SQL?" }, { "code": null, "e": 28272, "s": 28214, "text": "SQL Query for Matching Multiple Values in the Same Column" }, { "code": null, "e": 28289, "s": 28272, "text": "SQL using Python" }, { "code": null, "e": 28323, "s": 28289, "text": "SQL Query to Insert Multiple Rows" }, { "code": null, "e": 28401, "s": 28323, "text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter" }, { "code": null, "e": 28416, "s": 28401, "text": "SQL | Subquery" }, { "code": null, "e": 28432, "s": 28416, "text": "SQL | SEQUENCES" }, { "code": null, "e": 28453, "s": 28432, "text": "SQL | DROP, TRUNCATE" } ]
A practical example of Training a Neural Network in the AWS cloud with Docker | by Jens Laufer | Towards Data Science
My last article Example Use Cases of Docker in the Data Science Process was about Docker in Data Science in general. This time I want to get my hands dirty with a practical example. In this case study, I want to show you how to train a shallow neural network on top of a deep InceptionV3 model on CIFAR-10 images within a Docker container on AWS. I am using a standard technology stack for this project with Python, Tensorflow and Keras. The source code for this project is available on Github. What you will learn in this case study: Setup of GPU empowered cloud instance on AWS from your command line with docker-machine Usage of a tensorflow docker image in your Dockerfile Setup of a multi-container Docker application for training a neural network with docker-compose Setup of a MongoDB as Persistence container for training meta-data and file storage for models Simple data inserting and querying with MongoDB Some simple docker, docker-compose and docker-machine commands Transfer learning of a convolutional neural network (CNN) Let’s define the requirements for this little project: Training must be done in the cloud on a GPU empowered instance in AWS Flexibility to port the whole training pipeline also to Google Cloud or Microsoft Azure Usage of nvidia-docker to activate the full GPU-power on the cloud instance Persistence of models metadata on MongoDB for model reproducibility. Usage of docker-compose for the multi-container application (training container + MongoDB) Usage of docker-machine to manage the cloud instance and start the training from the local command line with docker-compose Let’s dive deeper. Installation of Docker along with Docker Machine and Docker Compose (The tools are installed with the standard docker installation on Mac and Windows)Creation of an Account on AWSInstallation and Setup of the AWS Command Line Client Installation of Docker along with Docker Machine and Docker Compose (The tools are installed with the standard docker installation on Mac and Windows) Creation of an Account on AWS Installation and Setup of the AWS Command Line Client To train the neural network on AWS you first need to set up an instance there. You can do this from the AWS Web Console or from the command line with the AWS Command Line Client. I show you a convenient third way with the docker-machine command. The command wraps the drivers for different cloud and local providers. You get a unique interface for the Google Compute Cloud, Microsoft Azure and Amazon AWS this way, which makes it easy to setup instances on the platforms. Keep in mind that once you have set up the instance, you can reuse for other purposes. I am creating an AWS instance with Ubuntu 18.04 Linux (ami-0891f5dcc59fc5285) which has CUDA 10.1 and nvidia-docker already installed. The components are needed to enable the GPU for the training. The basis for the AMI is a standard AWS Ubuntu 18.04 Linux instance (ami-0a313d6098716f372), which I extended with these components. I shared the image to the public to make life easier. I am using the p2.xlarge instance type, which is cheapest GPU instance on AWS. The p2.xlarge instance type equips you with the GPU power of a Tesla K80. docker-machine create --driver amazonec2\ --amazonec2-instance-type p2.xlarge\ --amazonec2-ami ami-0891f5dcc59fc5285\ --amazonec2-vpc-id <YOUR VPC-ID>\ cifar10-deep-learning You need a VPC-ID for the setup. You can use the AWS command to get it: You can get the VPC-ID as well from the AWS Web Console For more information check the Docker Machine with AWS Documentation. WARNING: The p2.xlarge costs $0.90 per HOUR. Please don’t forget to stop the instance after completing your training sessions You want to train the neural network with different training parameters to find the best set up. After the training, you test the model quality on the test set. It’s a classification problem; I suggest to use the accuracy metric for simplicity. In the end, you persist the training log, model weights and architecture for further usage. Everything is reproducible and traceable this way. You can do transfer learning by replacing the top layers of the base model with your shallow network, then you freeze the weights of the base model and perform the training on the whole network. I am doing it differently in this case study. I am removing the top layers of the base model, then I feed the images into the base model and persist the resulting features in the MongoDB. Predictions need less computing power than training, and I can reuse the bottleneck features once they are extracted. You train the shallow network on the bottleneck features. The input and output requirements for the training script: Input The Docker container is parameterised from a MongoDB collection with all parameters for a training session. loss function optimiser batch size number of epochs subset percentage of all samples used for training (used for testing the pipeline with fewer images) Output Model architecture file Model weights file Training Session Log Model accuracy on the test set I put the whole training pipeline into one script src/cnn/cifar10.py It consists of one class for the whole training pipeline: Downloading of the CIFAR-10 images to the container file system.Loading of the base model (InceptionV3) with imagenet weights and removal of the top layerExtracting of bottleneck features for training and test images; persisting of the features in MongoDB for further usage.Creation and Compilation of the shallow neural network; persisting the model architecture in MongoDBTraining of the shallow model; persisting of model weights and training log in MongoDBModel testing on test set; persisting the accuracy metric in MongoDB Downloading of the CIFAR-10 images to the container file system. Loading of the base model (InceptionV3) with imagenet weights and removal of the top layer Extracting of bottleneck features for training and test images; persisting of the features in MongoDB for further usage. Creation and Compilation of the shallow neural network; persisting the model architecture in MongoDB Training of the shallow model; persisting of model weights and training log in MongoDB Model testing on test set; persisting the accuracy metric in MongoDB Everything you need to train the neural network I put into the Dockerfile, which defines the runtime environment for the training. Line 1: Definition of the base image. The setup and configuration are inherited from this image. An official tensorflow image with python3 and GPU support is used. Line 3: Everything in the local directory src, like the training script and entry point, is copied into the Docker image. Line 5: Container is started in src directory Line 7: Installation of python requirements Line 9: src directory is added to PYTHONPATH to tell python to look for modules in this directory Line 11: Definition of the entry point for the image. This entry point script is executed when the container is started. This script starts our python training script. The entry point shell script is pretty self-explaining: It starts the python module with no parameters. The module fetches then the training parameter from the MongoDB on startup. First, I need to build a Docker image. You can skip this step as I shared the ready-built Docker image on Docker Hub. The image is automatically downloaded when it is referenced the first time. I have two docker containers in my setup: The Docker container for training and a MongoDB for persisting meta-data and as a file server. You use docker-compose for this scenario. You define the containers that make your application in a docker-compose.yml Line 4–5: Definition of the training container which uses the jenslaufer/neural-network-training-with-docker image with tag 0.1.0-GPU. This image is automatically downloaded from the public Docker Hub repository Line 7: The runtime environment for tensorflow Line 9: The training container needs the trainingdb container for execution. In the code, you use mongodb://trainingdb as Mongo URI Line 11–12: Definition of the MongoDB database. An official mongo image from Docker Hub is used with version 3.6.12 Line 14–15: The internal port 27017 is available at port 27018 from outsite Line 16: Mongo daemon is started You can see that it’s straightforward to set up a multi-application with docker compose — you just set up a database with a few lines of code without complicated installation routines. You need to execute this command to ensure that the docker commands are going against our AWS instance: docker-machine env cifar10-deep-learning Afterwards, you can list your machines NAME ACTIVE DRIVER STATE cifar10-deep-learning * amazonec2 Running Ensure that you see the star for the active environment. It’s the environment against all docker commands are executed. Keep in mind that you execute the commands in your local shell. It’s very convenient. You can now start the containers the first time. Docker downloads all images to the AWS instance. The MongoDB started and keep running until you stop the containers. The neural-network-training-with-docker executes the training module. The module fetches the training sessions from the MongoDB, which is empty on the first start. The container stops after finishing the training sessions. Let’s add training session parameters. You log into the MongoDB container for this (everything from your local shell): You open the mongo client. Then you are selecting the DB ‘trainings’ with the use command. You can add then a training session with only 5% of the images, a rmsprop optimizer with a batch size of 50 and 20 epochs. It’s a quick test if everything works smoothly. You leave the MongoDB and restart the containers: The problem is now that you don’t see what’s going. You can get the logs of a docker container with the docker log command. docker logs -f neural-network-training-with-docker You can now follow the training session on the remote docker container on your local machine this way. You can compare the results from the different training sessions quickly with the MongoDB, as I persisted all parameters and the accuracy metric on the test set. The advantage of a database is that you can execute queries against it, which is much better than saving results in CSV or JSON. Let’s list the three model with the highest accuracy. You can also query the database for the model files for a specific training session. You can see that you have hdf5 files for the model architecture and weights. There is also a JSON file with the training history you can use to analyse the training itself. It can be used to visualise the training process. You can load the best model automatically from the MongoDB and ship it in Flask, Spring Boot or Tensorflow Application. You can download the files to the local filesystem with the mongofiles command: You set up in this case study a GPU-empowered cloud instance on AWS from the command line with docker-machine. The goal was to train a neural network faster with additional computing power. The instance is reusable for other training containers. In the next step, you implemented a script with all steps needed to train a shallow fully connected neural network on top of InceptionV3 model with transfer learning. The script uses a MongoDB instance as a persistence layer to store training metadata and model files. You created a Dockerfile with the infrastructure needed to train the network with Tensorflow on a GPU cloud instance. You defined then a multi-container setup with training container and MongoDB container in a docker-compose file. You trained the neural network on the AWS cloud within Docker. You started the training from the local command line. You logged from the local command line into the MongoDB to add training sessions and to get insights on the training sessions afterwards. Next steps to improve the process: The architecture of the shallow neural network is hard coded. It would be better to load it from the persistence layer as well. Generic way to use as well other base models than the InceptionV3 You used the accuracy metric to test the quality of the model. It would be better to find a more generic way to persist more metrics. You used the optimisers with default parameters. An improvement would be to load optimiser specific parameters generically. A goal could be to remove the Python script from the container and load it as a python module from a repository in the entry point script with the help of environment variables in the docker-compose file. Do you need advice with your Data Science setup? Please let me know. Send me a mail Originally published at https://jenslaufer.com on April 23, 2019.
[ { "code": null, "e": 354, "s": 172, "text": "My last article Example Use Cases of Docker in the Data Science Process was about Docker in Data Science in general. This time I want to get my hands dirty with a practical example." }, { "code": null, "e": 667, "s": 354, "text": "In this case study, I want to show you how to train a shallow neural network on top of a deep InceptionV3 model on CIFAR-10 images within a Docker container on AWS. I am using a standard technology stack for this project with Python, Tensorflow and Keras. The source code for this project is available on Github." }, { "code": null, "e": 707, "s": 667, "text": "What you will learn in this case study:" }, { "code": null, "e": 795, "s": 707, "text": "Setup of GPU empowered cloud instance on AWS from your command line with docker-machine" }, { "code": null, "e": 849, "s": 795, "text": "Usage of a tensorflow docker image in your Dockerfile" }, { "code": null, "e": 945, "s": 849, "text": "Setup of a multi-container Docker application for training a neural network with docker-compose" }, { "code": null, "e": 1040, "s": 945, "text": "Setup of a MongoDB as Persistence container for training meta-data and file storage for models" }, { "code": null, "e": 1088, "s": 1040, "text": "Simple data inserting and querying with MongoDB" }, { "code": null, "e": 1151, "s": 1088, "text": "Some simple docker, docker-compose and docker-machine commands" }, { "code": null, "e": 1209, "s": 1151, "text": "Transfer learning of a convolutional neural network (CNN)" }, { "code": null, "e": 1264, "s": 1209, "text": "Let’s define the requirements for this little project:" }, { "code": null, "e": 1334, "s": 1264, "text": "Training must be done in the cloud on a GPU empowered instance in AWS" }, { "code": null, "e": 1422, "s": 1334, "text": "Flexibility to port the whole training pipeline also to Google Cloud or Microsoft Azure" }, { "code": null, "e": 1498, "s": 1422, "text": "Usage of nvidia-docker to activate the full GPU-power on the cloud instance" }, { "code": null, "e": 1567, "s": 1498, "text": "Persistence of models metadata on MongoDB for model reproducibility." }, { "code": null, "e": 1658, "s": 1567, "text": "Usage of docker-compose for the multi-container application (training container + MongoDB)" }, { "code": null, "e": 1782, "s": 1658, "text": "Usage of docker-machine to manage the cloud instance and start the training from the local command line with docker-compose" }, { "code": null, "e": 1801, "s": 1782, "text": "Let’s dive deeper." }, { "code": null, "e": 2034, "s": 1801, "text": "Installation of Docker along with Docker Machine and Docker Compose (The tools are installed with the standard docker installation on Mac and Windows)Creation of an Account on AWSInstallation and Setup of the AWS Command Line Client" }, { "code": null, "e": 2185, "s": 2034, "text": "Installation of Docker along with Docker Machine and Docker Compose (The tools are installed with the standard docker installation on Mac and Windows)" }, { "code": null, "e": 2215, "s": 2185, "text": "Creation of an Account on AWS" }, { "code": null, "e": 2269, "s": 2215, "text": "Installation and Setup of the AWS Command Line Client" }, { "code": null, "e": 2448, "s": 2269, "text": "To train the neural network on AWS you first need to set up an instance there. You can do this from the AWS Web Console or from the command line with the AWS Command Line Client." }, { "code": null, "e": 2828, "s": 2448, "text": "I show you a convenient third way with the docker-machine command. The command wraps the drivers for different cloud and local providers. You get a unique interface for the Google Compute Cloud, Microsoft Azure and Amazon AWS this way, which makes it easy to setup instances on the platforms. Keep in mind that once you have set up the instance, you can reuse for other purposes." }, { "code": null, "e": 3212, "s": 2828, "text": "I am creating an AWS instance with Ubuntu 18.04 Linux (ami-0891f5dcc59fc5285) which has CUDA 10.1 and nvidia-docker already installed. The components are needed to enable the GPU for the training. The basis for the AMI is a standard AWS Ubuntu 18.04 Linux instance (ami-0a313d6098716f372), which I extended with these components. I shared the image to the public to make life easier." }, { "code": null, "e": 3365, "s": 3212, "text": "I am using the p2.xlarge instance type, which is cheapest GPU instance on AWS. The p2.xlarge instance type equips you with the GPU power of a Tesla K80." }, { "code": null, "e": 3541, "s": 3365, "text": "docker-machine create --driver amazonec2\\ --amazonec2-instance-type p2.xlarge\\ --amazonec2-ami ami-0891f5dcc59fc5285\\ --amazonec2-vpc-id <YOUR VPC-ID>\\ cifar10-deep-learning" }, { "code": null, "e": 3613, "s": 3541, "text": "You need a VPC-ID for the setup. You can use the AWS command to get it:" }, { "code": null, "e": 3669, "s": 3613, "text": "You can get the VPC-ID as well from the AWS Web Console" }, { "code": null, "e": 3739, "s": 3669, "text": "For more information check the Docker Machine with AWS Documentation." }, { "code": null, "e": 3865, "s": 3739, "text": "WARNING: The p2.xlarge costs $0.90 per HOUR. Please don’t forget to stop the instance after completing your training sessions" }, { "code": null, "e": 4253, "s": 3865, "text": "You want to train the neural network with different training parameters to find the best set up. After the training, you test the model quality on the test set. It’s a classification problem; I suggest to use the accuracy metric for simplicity. In the end, you persist the training log, model weights and architecture for further usage. Everything is reproducible and traceable this way." }, { "code": null, "e": 4448, "s": 4253, "text": "You can do transfer learning by replacing the top layers of the base model with your shallow network, then you freeze the weights of the base model and perform the training on the whole network." }, { "code": null, "e": 4812, "s": 4448, "text": "I am doing it differently in this case study. I am removing the top layers of the base model, then I feed the images into the base model and persist the resulting features in the MongoDB. Predictions need less computing power than training, and I can reuse the bottleneck features once they are extracted. You train the shallow network on the bottleneck features." }, { "code": null, "e": 4871, "s": 4812, "text": "The input and output requirements for the training script:" }, { "code": null, "e": 4877, "s": 4871, "text": "Input" }, { "code": null, "e": 4985, "s": 4877, "text": "The Docker container is parameterised from a MongoDB collection with all parameters for a training session." }, { "code": null, "e": 4999, "s": 4985, "text": "loss function" }, { "code": null, "e": 5009, "s": 4999, "text": "optimiser" }, { "code": null, "e": 5020, "s": 5009, "text": "batch size" }, { "code": null, "e": 5037, "s": 5020, "text": "number of epochs" }, { "code": null, "e": 5138, "s": 5037, "text": "subset percentage of all samples used for training (used for testing the pipeline with fewer images)" }, { "code": null, "e": 5145, "s": 5138, "text": "Output" }, { "code": null, "e": 5169, "s": 5145, "text": "Model architecture file" }, { "code": null, "e": 5188, "s": 5169, "text": "Model weights file" }, { "code": null, "e": 5209, "s": 5188, "text": "Training Session Log" }, { "code": null, "e": 5240, "s": 5209, "text": "Model accuracy on the test set" }, { "code": null, "e": 5367, "s": 5240, "text": "I put the whole training pipeline into one script src/cnn/cifar10.py It consists of one class for the whole training pipeline:" }, { "code": null, "e": 5896, "s": 5367, "text": "Downloading of the CIFAR-10 images to the container file system.Loading of the base model (InceptionV3) with imagenet weights and removal of the top layerExtracting of bottleneck features for training and test images; persisting of the features in MongoDB for further usage.Creation and Compilation of the shallow neural network; persisting the model architecture in MongoDBTraining of the shallow model; persisting of model weights and training log in MongoDBModel testing on test set; persisting the accuracy metric in MongoDB" }, { "code": null, "e": 5961, "s": 5896, "text": "Downloading of the CIFAR-10 images to the container file system." }, { "code": null, "e": 6052, "s": 5961, "text": "Loading of the base model (InceptionV3) with imagenet weights and removal of the top layer" }, { "code": null, "e": 6173, "s": 6052, "text": "Extracting of bottleneck features for training and test images; persisting of the features in MongoDB for further usage." }, { "code": null, "e": 6274, "s": 6173, "text": "Creation and Compilation of the shallow neural network; persisting the model architecture in MongoDB" }, { "code": null, "e": 6361, "s": 6274, "text": "Training of the shallow model; persisting of model weights and training log in MongoDB" }, { "code": null, "e": 6430, "s": 6361, "text": "Model testing on test set; persisting the accuracy metric in MongoDB" }, { "code": null, "e": 6561, "s": 6430, "text": "Everything you need to train the neural network I put into the Dockerfile, which defines the runtime environment for the training." }, { "code": null, "e": 6725, "s": 6561, "text": "Line 1: Definition of the base image. The setup and configuration are inherited from this image. An official tensorflow image with python3 and GPU support is used." }, { "code": null, "e": 6847, "s": 6725, "text": "Line 3: Everything in the local directory src, like the training script and entry point, is copied into the Docker image." }, { "code": null, "e": 6893, "s": 6847, "text": "Line 5: Container is started in src directory" }, { "code": null, "e": 6937, "s": 6893, "text": "Line 7: Installation of python requirements" }, { "code": null, "e": 7035, "s": 6937, "text": "Line 9: src directory is added to PYTHONPATH to tell python to look for modules in this directory" }, { "code": null, "e": 7203, "s": 7035, "text": "Line 11: Definition of the entry point for the image. This entry point script is executed when the container is started. This script starts our python training script." }, { "code": null, "e": 7383, "s": 7203, "text": "The entry point shell script is pretty self-explaining: It starts the python module with no parameters. The module fetches then the training parameter from the MongoDB on startup." }, { "code": null, "e": 7577, "s": 7383, "text": "First, I need to build a Docker image. You can skip this step as I shared the ready-built Docker image on Docker Hub. The image is automatically downloaded when it is referenced the first time." }, { "code": null, "e": 7714, "s": 7577, "text": "I have two docker containers in my setup: The Docker container for training and a MongoDB for persisting meta-data and as a file server." }, { "code": null, "e": 7833, "s": 7714, "text": "You use docker-compose for this scenario. You define the containers that make your application in a docker-compose.yml" }, { "code": null, "e": 8045, "s": 7833, "text": "Line 4–5: Definition of the training container which uses the jenslaufer/neural-network-training-with-docker image with tag 0.1.0-GPU. This image is automatically downloaded from the public Docker Hub repository" }, { "code": null, "e": 8092, "s": 8045, "text": "Line 7: The runtime environment for tensorflow" }, { "code": null, "e": 8224, "s": 8092, "text": "Line 9: The training container needs the trainingdb container for execution. In the code, you use mongodb://trainingdb as Mongo URI" }, { "code": null, "e": 8340, "s": 8224, "text": "Line 11–12: Definition of the MongoDB database. An official mongo image from Docker Hub is used with version 3.6.12" }, { "code": null, "e": 8416, "s": 8340, "text": "Line 14–15: The internal port 27017 is available at port 27018 from outsite" }, { "code": null, "e": 8449, "s": 8416, "text": "Line 16: Mongo daemon is started" }, { "code": null, "e": 8634, "s": 8449, "text": "You can see that it’s straightforward to set up a multi-application with docker compose — you just set up a database with a few lines of code without complicated installation routines." }, { "code": null, "e": 8738, "s": 8634, "text": "You need to execute this command to ensure that the docker commands are going against our AWS instance:" }, { "code": null, "e": 8779, "s": 8738, "text": "docker-machine env cifar10-deep-learning" }, { "code": null, "e": 8818, "s": 8779, "text": "Afterwards, you can list your machines" }, { "code": null, "e": 8912, "s": 8818, "text": "NAME ACTIVE DRIVER STATE cifar10-deep-learning * amazonec2 Running" }, { "code": null, "e": 9118, "s": 8912, "text": "Ensure that you see the star for the active environment. It’s the environment against all docker commands are executed. Keep in mind that you execute the commands in your local shell. It’s very convenient." }, { "code": null, "e": 9167, "s": 9118, "text": "You can now start the containers the first time." }, { "code": null, "e": 9507, "s": 9167, "text": "Docker downloads all images to the AWS instance. The MongoDB started and keep running until you stop the containers. The neural-network-training-with-docker executes the training module. The module fetches the training sessions from the MongoDB, which is empty on the first start. The container stops after finishing the training sessions." }, { "code": null, "e": 9546, "s": 9507, "text": "Let’s add training session parameters." }, { "code": null, "e": 9626, "s": 9546, "text": "You log into the MongoDB container for this (everything from your local shell):" }, { "code": null, "e": 9888, "s": 9626, "text": "You open the mongo client. Then you are selecting the DB ‘trainings’ with the use command. You can add then a training session with only 5% of the images, a rmsprop optimizer with a batch size of 50 and 20 epochs. It’s a quick test if everything works smoothly." }, { "code": null, "e": 9938, "s": 9888, "text": "You leave the MongoDB and restart the containers:" }, { "code": null, "e": 10062, "s": 9938, "text": "The problem is now that you don’t see what’s going. You can get the logs of a docker container with the docker log command." }, { "code": null, "e": 10113, "s": 10062, "text": "docker logs -f neural-network-training-with-docker" }, { "code": null, "e": 10216, "s": 10113, "text": "You can now follow the training session on the remote docker container on your local machine this way." }, { "code": null, "e": 10507, "s": 10216, "text": "You can compare the results from the different training sessions quickly with the MongoDB, as I persisted all parameters and the accuracy metric on the test set. The advantage of a database is that you can execute queries against it, which is much better than saving results in CSV or JSON." }, { "code": null, "e": 10561, "s": 10507, "text": "Let’s list the three model with the highest accuracy." }, { "code": null, "e": 10869, "s": 10561, "text": "You can also query the database for the model files for a specific training session. You can see that you have hdf5 files for the model architecture and weights. There is also a JSON file with the training history you can use to analyse the training itself. It can be used to visualise the training process." }, { "code": null, "e": 10989, "s": 10869, "text": "You can load the best model automatically from the MongoDB and ship it in Flask, Spring Boot or Tensorflow Application." }, { "code": null, "e": 11069, "s": 10989, "text": "You can download the files to the local filesystem with the mongofiles command:" }, { "code": null, "e": 11315, "s": 11069, "text": "You set up in this case study a GPU-empowered cloud instance on AWS from the command line with docker-machine. The goal was to train a neural network faster with additional computing power. The instance is reusable for other training containers." }, { "code": null, "e": 11815, "s": 11315, "text": "In the next step, you implemented a script with all steps needed to train a shallow fully connected neural network on top of InceptionV3 model with transfer learning. The script uses a MongoDB instance as a persistence layer to store training metadata and model files. You created a Dockerfile with the infrastructure needed to train the network with Tensorflow on a GPU cloud instance. You defined then a multi-container setup with training container and MongoDB container in a docker-compose file." }, { "code": null, "e": 12070, "s": 11815, "text": "You trained the neural network on the AWS cloud within Docker. You started the training from the local command line. You logged from the local command line into the MongoDB to add training sessions and to get insights on the training sessions afterwards." }, { "code": null, "e": 12105, "s": 12070, "text": "Next steps to improve the process:" }, { "code": null, "e": 12233, "s": 12105, "text": "The architecture of the shallow neural network is hard coded. It would be better to load it from the persistence layer as well." }, { "code": null, "e": 12299, "s": 12233, "text": "Generic way to use as well other base models than the InceptionV3" }, { "code": null, "e": 12433, "s": 12299, "text": "You used the accuracy metric to test the quality of the model. It would be better to find a more generic way to persist more metrics." }, { "code": null, "e": 12557, "s": 12433, "text": "You used the optimisers with default parameters. An improvement would be to load optimiser specific parameters generically." }, { "code": null, "e": 12762, "s": 12557, "text": "A goal could be to remove the Python script from the container and load it as a python module from a repository in the entry point script with the help of environment variables in the docker-compose file." }, { "code": null, "e": 12811, "s": 12762, "text": "Do you need advice with your Data Science setup?" }, { "code": null, "e": 12846, "s": 12811, "text": "Please let me know. Send me a mail" } ]
How to Build a Chatbot — A Lesson in NLP | by Rishi Sidhu | Towards Data Science
A ‘chatbot’ as the name suggests is a machine that chats with you. The trick though is to make it as human-like as possible. From ‘American Express customer support’ to Google Pixel’s call screening software chatbots can be found in various flavours. The earlier versions of chatbots used a machine learning technique called pattern matching. This was much simpler as compared to the advanced NLP techniques being used today. To understand this just imagine what you would ask a book seller for example — “What is the price of __ book?” or “Which books of __ author do you have?” Each of these italicised questions is an example of a pattern that can be matched when similar questions appear in the future. Pattern matching requires a lot of pre generated patterns. Based on these pre-generated patterns the chatbot can easily pick the pattern which best matches the customer query and provide an answer for it. How do you think the following chat could be created Put simply, the question May I know the price for is converted into a template The price of <star/>. This template is like a key against which all future answers will be stored. So we can have the following The price of iPhone X — $1500 The price of Kindle Paperwhite — $100 The code for this in AIML (Artificial Intelligence Modelling Language) will look like #PATTERN MATCHING<category> <pattern>MAY I KNOW THE PRICE FOR *</pattern> <template> <srai>THE PRICE OF <star/></srai> </template> </category>------------------------------------------------#PRE_STORED PATTERNS<category> <pattern>THE PRICE OF iPhone X?</pattern> <template>iPhone X Costs $1500.</template></category><category> <pattern>THE PRICE OF Kindle Paperwhite?</pattern> <template>The all-new kindle paperwhite costs $100. Yay!! You have got an offer!! You can get it for $85 if you apply the coupon MyGoodBot </template></category> Pattern matching is simple and quick to implement but it can only go so far. It needs a lot of pre-generated templates and is useful only for applications which expect a limited number of questions. Enter NLP! NLP is a collection of slightly advanced techniques which can understand a broad range of questions. NLP process for creating a chatbot can be broken down into 5 major steps 1) Tokenize — Tokenization is the technique for chopping text up into pieces, called tokens, and at the same time throwing away certain characters, such as punctuation. These tokens are linguistically representative of the text. 2) Normalisation — Normalisation processes the text to find out the common spelling mistakes that might alter the intended meaning of the user’s request. A very good research paper that performs normalisation on tweets explains this concept very well 3) Recognising Entities — This step helps chatbot identify which thing is being talked about e.g. is it an object or a country or a number or the user’s address. Observe in the below example how Google, IBM and Microsoft are all clubbed as organizations. This step is also known as named entity recognition. 4) Dependency Parsing — In this step we split the sentence into its constiuent nouns, verbs, objects, common phrases and punctuations. This technique helps the machine to identify phrases and that in turn tells it about what users want to convey. 5) Generation — Finally, the step where a response is generated. All the above steps fall under NLU (Natural Language Understanding). These steps help the bot to understand the meaning of the sentence being written. This step however falls under NLG (Natural Language Generation). This step receives the output of the previous NLU steps and generates a number of sentences with the same meaning. The generated sentences are generally similar in terms of the following Word order — “the kitchen light” is similar to “the light in the kitchen” Singular/plural — “the kitchen light” is similar to “the kitchen lights” Questions — “close the door” is similar to “do you mind closing the door?” Negation — “turn on the tv at 19:00” is similar to “don’t turn on the tv at 19:00” Politeness — “turn on the tv” is similar to “could you please be so kind as to turn on the tv?” Based on the context of user’s question the bot can reply with one of the above options and the user would return satisfied. In a lot of cases users are unable to differentiate between a bot and human. Chatbots are growingly steadily and have come a long way since AIML was invented in 1995. Even in 2016 an average user was spending more than 20 minutes interacting over messaging apps, with Kakao, Whatsapp and Line being the top favorites. Businesses around the world are looking to cut costs on customer care and provide round the clock customer service through the use of these bots. www.businessinsider.com The technology behind chatbots is fairly standard. NLP has a long way to go but even in its current state it holds a lot of promise for the field of chatbots.
[ { "code": null, "e": 423, "s": 172, "text": "A ‘chatbot’ as the name suggests is a machine that chats with you. The trick though is to make it as human-like as possible. From ‘American Express customer support’ to Google Pixel’s call screening software chatbots can be found in various flavours." }, { "code": null, "e": 598, "s": 423, "text": "The earlier versions of chatbots used a machine learning technique called pattern matching. This was much simpler as compared to the advanced NLP techniques being used today." }, { "code": null, "e": 879, "s": 598, "text": "To understand this just imagine what you would ask a book seller for example — “What is the price of __ book?” or “Which books of __ author do you have?” Each of these italicised questions is an example of a pattern that can be matched when similar questions appear in the future." }, { "code": null, "e": 1084, "s": 879, "text": "Pattern matching requires a lot of pre generated patterns. Based on these pre-generated patterns the chatbot can easily pick the pattern which best matches the customer query and provide an answer for it." }, { "code": null, "e": 1137, "s": 1084, "text": "How do you think the following chat could be created" }, { "code": null, "e": 1344, "s": 1137, "text": "Put simply, the question May I know the price for is converted into a template The price of <star/>. This template is like a key against which all future answers will be stored. So we can have the following" }, { "code": null, "e": 1374, "s": 1344, "text": "The price of iPhone X — $1500" }, { "code": null, "e": 1412, "s": 1374, "text": "The price of Kindle Paperwhite — $100" }, { "code": null, "e": 1498, "s": 1412, "text": "The code for this in AIML (Artificial Intelligence Modelling Language) will look like" }, { "code": null, "e": 2093, "s": 1498, "text": "#PATTERN MATCHING<category> <pattern>MAY I KNOW THE PRICE FOR *</pattern> <template> <srai>THE PRICE OF <star/></srai> </template> </category>------------------------------------------------#PRE_STORED PATTERNS<category> <pattern>THE PRICE OF iPhone X?</pattern> <template>iPhone X Costs $1500.</template></category><category> <pattern>THE PRICE OF Kindle Paperwhite?</pattern> <template>The all-new kindle paperwhite costs $100. Yay!! You have got an offer!! You can get it for $85 if you apply the coupon MyGoodBot </template></category>" }, { "code": null, "e": 2292, "s": 2093, "text": "Pattern matching is simple and quick to implement but it can only go so far. It needs a lot of pre-generated templates and is useful only for applications which expect a limited number of questions." }, { "code": null, "e": 2477, "s": 2292, "text": "Enter NLP! NLP is a collection of slightly advanced techniques which can understand a broad range of questions. NLP process for creating a chatbot can be broken down into 5 major steps" }, { "code": null, "e": 2706, "s": 2477, "text": "1) Tokenize — Tokenization is the technique for chopping text up into pieces, called tokens, and at the same time throwing away certain characters, such as punctuation. These tokens are linguistically representative of the text." }, { "code": null, "e": 2957, "s": 2706, "text": "2) Normalisation — Normalisation processes the text to find out the common spelling mistakes that might alter the intended meaning of the user’s request. A very good research paper that performs normalisation on tweets explains this concept very well" }, { "code": null, "e": 3119, "s": 2957, "text": "3) Recognising Entities — This step helps chatbot identify which thing is being talked about e.g. is it an object or a country or a number or the user’s address." }, { "code": null, "e": 3265, "s": 3119, "text": "Observe in the below example how Google, IBM and Microsoft are all clubbed as organizations. This step is also known as named entity recognition." }, { "code": null, "e": 3512, "s": 3265, "text": "4) Dependency Parsing — In this step we split the sentence into its constiuent nouns, verbs, objects, common phrases and punctuations. This technique helps the machine to identify phrases and that in turn tells it about what users want to convey." }, { "code": null, "e": 3980, "s": 3512, "text": "5) Generation — Finally, the step where a response is generated. All the above steps fall under NLU (Natural Language Understanding). These steps help the bot to understand the meaning of the sentence being written. This step however falls under NLG (Natural Language Generation). This step receives the output of the previous NLU steps and generates a number of sentences with the same meaning. The generated sentences are generally similar in terms of the following" }, { "code": null, "e": 4054, "s": 3980, "text": "Word order — “the kitchen light” is similar to “the light in the kitchen”" }, { "code": null, "e": 4127, "s": 4054, "text": "Singular/plural — “the kitchen light” is similar to “the kitchen lights”" }, { "code": null, "e": 4202, "s": 4127, "text": "Questions — “close the door” is similar to “do you mind closing the door?”" }, { "code": null, "e": 4285, "s": 4202, "text": "Negation — “turn on the tv at 19:00” is similar to “don’t turn on the tv at 19:00”" }, { "code": null, "e": 4381, "s": 4285, "text": "Politeness — “turn on the tv” is similar to “could you please be so kind as to turn on the tv?”" }, { "code": null, "e": 4583, "s": 4381, "text": "Based on the context of user’s question the bot can reply with one of the above options and the user would return satisfied. In a lot of cases users are unable to differentiate between a bot and human." }, { "code": null, "e": 4824, "s": 4583, "text": "Chatbots are growingly steadily and have come a long way since AIML was invented in 1995. Even in 2016 an average user was spending more than 20 minutes interacting over messaging apps, with Kakao, Whatsapp and Line being the top favorites." }, { "code": null, "e": 4970, "s": 4824, "text": "Businesses around the world are looking to cut costs on customer care and provide round the clock customer service through the use of these bots." }, { "code": null, "e": 4994, "s": 4970, "text": "www.businessinsider.com" } ]
Default Arguments and Virtual Function in C++ - GeeksforGeeks
08 Dec, 2021 Let’s first understand what Default arguments and Virtual functions mean. Default Arguments: These are the values provided during function declaration, such that values can be automatically assigned if no argument is passed to them. In case any value is passed the default value is overridden. Virtual Function: A virtual function is a member function that is declared within a base class and is redefined(Overridden) by a derived class. When you refer to a derived class object using a pointer or a reference to the base class, you can call a virtual function for that object and execute the derived class’s version of the function. To see the combined application of default arguments with virtual functions lets first see the following C++ program, CPP // CPP program to demonstrate how default arguments and// virtual function are used together#include <iostream>using namespace std; class Base {public: virtual void fun(int x = 0) { cout << "Base::fun(), x = " << x << endl; }}; class Derived : public Base {public: virtual void fun(int x) { cout << "Derived::fun(), x = " << x << endl; }}; // Driver Codeint main(){ Derived d1; Base* bp = &d1; bp->fun(); return 0;} Derived::fun(), x = 0 If we take a closer look at the output, we observe that fun() of the derived class is called and the default value of base class fun() is used. Default arguments do not participate in the signature of functions. So signatures of fun() in the base class and derived class are considered the same, hence the fun() of the base class is overridden. Also, the default value is used at compile time. When the compiler sees that an argument is missing in a function call, it substitutes the default value given. Therefore, in the above program, the value of x is substituted at compile-time, and at run time derived class’s fun() is called. Now predict the output of the following program, CPP // CPP program to demonstrate how default arguments and// virtual function are used together#include <iostream>using namespace std; class Base {public: virtual void fun(int x = 0) { cout << "Base::fun(), x = " << x << endl; }}; class Derived : public Base {public: virtual void fun(int x = 10) // NOTE THIS CHANGE { cout << "Derived::fun(), x = " << x << endl; }}; int main(){ Derived d1; Base* bp = &d1; bp->fun(); return 0;} Derived::fun(), x = 0 The output of this program is the same as the previous program. The reason is the same, the default value is substituted at compile time. The fun() is called on ‘bp’ which is a pointer of Base type. So compiler substitutes 0 (not 10). anshikajain26 CPP-Functions C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Operator Overloading in C++ Sorting a vector in C++ Friend class and function in C++ Polymorphism in C++ List in C++ Standard Template Library (STL) Pair in C++ Standard Template Library (STL) Convert string to char array in C++ new and delete operators in C++ for dynamic memory Destructors in C++ Queue in C++ Standard Template Library (STL)
[ { "code": null, "e": 23733, "s": 23705, "text": "\n08 Dec, 2021" }, { "code": null, "e": 23807, "s": 23733, "text": "Let’s first understand what Default arguments and Virtual functions mean." }, { "code": null, "e": 24027, "s": 23807, "text": "Default Arguments: These are the values provided during function declaration, such that values can be automatically assigned if no argument is passed to them. In case any value is passed the default value is overridden." }, { "code": null, "e": 24368, "s": 24027, "text": "Virtual Function: A virtual function is a member function that is declared within a base class and is redefined(Overridden) by a derived class. When you refer to a derived class object using a pointer or a reference to the base class, you can call a virtual function for that object and execute the derived class’s version of the function. " }, { "code": null, "e": 24486, "s": 24368, "text": "To see the combined application of default arguments with virtual functions lets first see the following C++ program," }, { "code": null, "e": 24490, "s": 24486, "text": "CPP" }, { "code": "// CPP program to demonstrate how default arguments and// virtual function are used together#include <iostream>using namespace std; class Base {public: virtual void fun(int x = 0) { cout << \"Base::fun(), x = \" << x << endl; }}; class Derived : public Base {public: virtual void fun(int x) { cout << \"Derived::fun(), x = \" << x << endl; }}; // Driver Codeint main(){ Derived d1; Base* bp = &d1; bp->fun(); return 0;}", "e": 24953, "s": 24490, "text": null }, { "code": null, "e": 24975, "s": 24953, "text": "Derived::fun(), x = 0" }, { "code": null, "e": 25610, "s": 24975, "text": "If we take a closer look at the output, we observe that fun() of the derived class is called and the default value of base class fun() is used. Default arguments do not participate in the signature of functions. So signatures of fun() in the base class and derived class are considered the same, hence the fun() of the base class is overridden. Also, the default value is used at compile time. When the compiler sees that an argument is missing in a function call, it substitutes the default value given. Therefore, in the above program, the value of x is substituted at compile-time, and at run time derived class’s fun() is called. " }, { "code": null, "e": 25659, "s": 25610, "text": "Now predict the output of the following program," }, { "code": null, "e": 25663, "s": 25659, "text": "CPP" }, { "code": "// CPP program to demonstrate how default arguments and// virtual function are used together#include <iostream>using namespace std; class Base {public: virtual void fun(int x = 0) { cout << \"Base::fun(), x = \" << x << endl; }}; class Derived : public Base {public: virtual void fun(int x = 10) // NOTE THIS CHANGE { cout << \"Derived::fun(), x = \" << x << endl; }}; int main(){ Derived d1; Base* bp = &d1; bp->fun(); return 0;}", "e": 26137, "s": 25663, "text": null }, { "code": null, "e": 26159, "s": 26137, "text": "Derived::fun(), x = 0" }, { "code": null, "e": 26394, "s": 26159, "text": "The output of this program is the same as the previous program. The reason is the same, the default value is substituted at compile time. The fun() is called on ‘bp’ which is a pointer of Base type. So compiler substitutes 0 (not 10)." }, { "code": null, "e": 26408, "s": 26394, "text": "anshikajain26" }, { "code": null, "e": 26422, "s": 26408, "text": "CPP-Functions" }, { "code": null, "e": 26426, "s": 26422, "text": "C++" }, { "code": null, "e": 26430, "s": 26426, "text": "CPP" }, { "code": null, "e": 26528, "s": 26430, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26537, "s": 26528, "text": "Comments" }, { "code": null, "e": 26550, "s": 26537, "text": "Old Comments" }, { "code": null, "e": 26578, "s": 26550, "text": "Operator Overloading in C++" }, { "code": null, "e": 26602, "s": 26578, "text": "Sorting a vector in C++" }, { "code": null, "e": 26635, "s": 26602, "text": "Friend class and function in C++" }, { "code": null, "e": 26655, "s": 26635, "text": "Polymorphism in C++" }, { "code": null, "e": 26699, "s": 26655, "text": "List in C++ Standard Template Library (STL)" }, { "code": null, "e": 26743, "s": 26699, "text": "Pair in C++ Standard Template Library (STL)" }, { "code": null, "e": 26779, "s": 26743, "text": "Convert string to char array in C++" }, { "code": null, "e": 26830, "s": 26779, "text": "new and delete operators in C++ for dynamic memory" }, { "code": null, "e": 26849, "s": 26830, "text": "Destructors in C++" } ]
Exploring Univariate Data in Python | Towards Data Science
Wikipedia states that “univariate analysis is perhaps the simplest form of statistical analysis. . . The key fact is that only one variable is involved.” Because univariate analysis is so simple, it’s a good place to start in an exploratory analysis. Some questions to consider when getting started can include: How many variables do I have? Do I have missing data? What types of variables do I have? We will explore the Super Heroes Dataset from Kaggle to begin answering these questions. The data includes two csv files. The first which we’ll use here, contains characteristics of each Super Hero. The second lists what superpowers each hero has. The full notebook can be found here. I like to get started by viewing the first few rows of the dataframe and printing out the shape: print(info_df.shape)info_df.head() Right away we can see we have the column ‘Unnamed: 0’ that we can most likely safely drop. That leaves us with 10 total variables. We can also see in the Skin Color column that we are missing some values, bringing us to our next question. We already saw we have some missing data, but let’s check for the sum of null values for each variable. #check for null valuesinfo_df.isnull().sum()name 0Gender 0Eye color 0Race 0Hair color 0Height 0Publisher 15Skin color 0Alignment 0Weight 2dtype: int64 While this shows there is missing data, it may be somewhat misleading. Above we saw the skin color column contains dash values, which Python technically does not interpret as null values. This shows that visual inspection of the data is important. We can clean up the dashes and replace with NaN: info_df['Skin color'].replace('-', np.nan, inplace=True) After cleaning up our data we can move on to the next question. Variables can be one of two types: categorical or numerical. Categorical data classify items into groups. This type of data can be further broken down into nominal, ordinal, and binary values. Ordinal values have a set order. An example here could be a ranking of low to high. Nominal values have no set order. Examples include the Super Hero’s gender and alignment. Binary data has only two values. This could be represented as True/False or 1/0. A common way to summarize categorical variables is with a frequency table. To visualize we will use a bar chart. sns.countplot(x='Publisher', data='info_df')plt.title('Number of Superheros by Publisher')plt.ylabel('Number of Superheros')plt.xlabel('Publisher')plt.xticks(rotation = 90)plt.show(); Here we can see that Marvel Comics has the greatest number of Super Heroes followed by DC Comics. Numerical data are values that we can perform mathematical operations on. They are further broken down into continuous and discrete data types. Discreet variables have to be an integer. An example is number of Super Heroes. Continuous can be any value. Examples here include height and weight. Numerical data can be visualized with a histogram. Histograms are a great first analysis of continuous data. Four main aspects to consider here are shape, center, spread, and outliers. Shape is the overall appearance of the histogram. It can be symmetric, skewed, uniform, or have multiple peaks. Center refers to the mean or median. Spread refers to the range or how far the data reaches. Outliers are data points that fall far from the bulk of the data. sns.distplot(info_2.Weight, kde=False)plt.title('Histogram of Superhero Weight')plt.show(); From the histogram we can see that most Super Heroes have a weight between about 50 and 150 pounds. We have one peak at about 100 pounds and outliers with weights above 800. We can confirm this by printing a numerical summary with the describe function: info_2.Weight.describe()count 490.000000mean 112.179592std 104.422653min 4.00000025% 61.00000050% 81.00000075% 106.000000max 900.000000Name: Weight, dtype: float64 Describe shows us key statistics including mean, standard deviation, and max value. Using summary statistics in addition to our histogram above can begin to give us a good idea of what our data looks like. The dataset contains 10 variables and some missing data. We saw that DC Comics has the most Super Heroes and that the weight variable has some outliers. This is by no means a complete exploratory analysis. We can continue to explore the remaining variables and move on to bivariate analysis. Something interesting to explore further could be to compare Marvel and DC Comics. Can we use data science to determine the superior universe?
[ { "code": null, "e": 326, "s": 172, "text": "Wikipedia states that “univariate analysis is perhaps the simplest form of statistical analysis. . . The key fact is that only one variable is involved.”" }, { "code": null, "e": 423, "s": 326, "text": "Because univariate analysis is so simple, it’s a good place to start in an exploratory analysis." }, { "code": null, "e": 484, "s": 423, "text": "Some questions to consider when getting started can include:" }, { "code": null, "e": 514, "s": 484, "text": "How many variables do I have?" }, { "code": null, "e": 538, "s": 514, "text": "Do I have missing data?" }, { "code": null, "e": 573, "s": 538, "text": "What types of variables do I have?" }, { "code": null, "e": 858, "s": 573, "text": "We will explore the Super Heroes Dataset from Kaggle to begin answering these questions. The data includes two csv files. The first which we’ll use here, contains characteristics of each Super Hero. The second lists what superpowers each hero has. The full notebook can be found here." }, { "code": null, "e": 955, "s": 858, "text": "I like to get started by viewing the first few rows of the dataframe and printing out the shape:" }, { "code": null, "e": 990, "s": 955, "text": "print(info_df.shape)info_df.head()" }, { "code": null, "e": 1121, "s": 990, "text": "Right away we can see we have the column ‘Unnamed: 0’ that we can most likely safely drop. That leaves us with 10 total variables." }, { "code": null, "e": 1229, "s": 1121, "text": "We can also see in the Skin Color column that we are missing some values, bringing us to our next question." }, { "code": null, "e": 1333, "s": 1229, "text": "We already saw we have some missing data, but let’s check for the sum of null values for each variable." }, { "code": null, "e": 1550, "s": 1333, "text": "#check for null valuesinfo_df.isnull().sum()name 0Gender 0Eye color 0Race 0Hair color 0Height 0Publisher 15Skin color 0Alignment 0Weight 2dtype: int64" }, { "code": null, "e": 1621, "s": 1550, "text": "While this shows there is missing data, it may be somewhat misleading." }, { "code": null, "e": 1847, "s": 1621, "text": "Above we saw the skin color column contains dash values, which Python technically does not interpret as null values. This shows that visual inspection of the data is important. We can clean up the dashes and replace with NaN:" }, { "code": null, "e": 1904, "s": 1847, "text": "info_df['Skin color'].replace('-', np.nan, inplace=True)" }, { "code": null, "e": 1968, "s": 1904, "text": "After cleaning up our data we can move on to the next question." }, { "code": null, "e": 2029, "s": 1968, "text": "Variables can be one of two types: categorical or numerical." }, { "code": null, "e": 2161, "s": 2029, "text": "Categorical data classify items into groups. This type of data can be further broken down into nominal, ordinal, and binary values." }, { "code": null, "e": 2245, "s": 2161, "text": "Ordinal values have a set order. An example here could be a ranking of low to high." }, { "code": null, "e": 2335, "s": 2245, "text": "Nominal values have no set order. Examples include the Super Hero’s gender and alignment." }, { "code": null, "e": 2416, "s": 2335, "text": "Binary data has only two values. This could be represented as True/False or 1/0." }, { "code": null, "e": 2529, "s": 2416, "text": "A common way to summarize categorical variables is with a frequency table. To visualize we will use a bar chart." }, { "code": null, "e": 2713, "s": 2529, "text": "sns.countplot(x='Publisher', data='info_df')plt.title('Number of Superheros by Publisher')plt.ylabel('Number of Superheros')plt.xlabel('Publisher')plt.xticks(rotation = 90)plt.show();" }, { "code": null, "e": 2811, "s": 2713, "text": "Here we can see that Marvel Comics has the greatest number of Super Heroes followed by DC Comics." }, { "code": null, "e": 2955, "s": 2811, "text": "Numerical data are values that we can perform mathematical operations on. They are further broken down into continuous and discrete data types." }, { "code": null, "e": 3035, "s": 2955, "text": "Discreet variables have to be an integer. An example is number of Super Heroes." }, { "code": null, "e": 3105, "s": 3035, "text": "Continuous can be any value. Examples here include height and weight." }, { "code": null, "e": 3290, "s": 3105, "text": "Numerical data can be visualized with a histogram. Histograms are a great first analysis of continuous data. Four main aspects to consider here are shape, center, spread, and outliers." }, { "code": null, "e": 3402, "s": 3290, "text": "Shape is the overall appearance of the histogram. It can be symmetric, skewed, uniform, or have multiple peaks." }, { "code": null, "e": 3439, "s": 3402, "text": "Center refers to the mean or median." }, { "code": null, "e": 3495, "s": 3439, "text": "Spread refers to the range or how far the data reaches." }, { "code": null, "e": 3561, "s": 3495, "text": "Outliers are data points that fall far from the bulk of the data." }, { "code": null, "e": 3653, "s": 3561, "text": "sns.distplot(info_2.Weight, kde=False)plt.title('Histogram of Superhero Weight')plt.show();" }, { "code": null, "e": 3907, "s": 3653, "text": "From the histogram we can see that most Super Heroes have a weight between about 50 and 150 pounds. We have one peak at about 100 pounds and outliers with weights above 800. We can confirm this by printing a numerical summary with the describe function:" }, { "code": null, "e": 4112, "s": 3907, "text": "info_2.Weight.describe()count 490.000000mean 112.179592std 104.422653min 4.00000025% 61.00000050% 81.00000075% 106.000000max 900.000000Name: Weight, dtype: float64" }, { "code": null, "e": 4318, "s": 4112, "text": "Describe shows us key statistics including mean, standard deviation, and max value. Using summary statistics in addition to our histogram above can begin to give us a good idea of what our data looks like." }, { "code": null, "e": 4471, "s": 4318, "text": "The dataset contains 10 variables and some missing data. We saw that DC Comics has the most Super Heroes and that the weight variable has some outliers." }, { "code": null, "e": 4610, "s": 4471, "text": "This is by no means a complete exploratory analysis. We can continue to explore the remaining variables and move on to bivariate analysis." } ]
Stack.Clear Method in C# - GeeksforGeeks
04 Feb, 2019 This method(comes under System.Collections namespace) is used to remove all the objects from the Stack. This method will set the Count of Stack to zero, and references to other objects from elements of the collection are also removed. This method is an O(n) operation, where n is Count. Syntax: public virtual void Clear (); Below programs illustrate the use of above-discussed method: Example 1: // C# code to illustrate the// Stack.Clear Methodusing System;using System.Collections; class GFG { // Driver code public static void Main() { // Creating a Stack Stack myStack = new Stack(); // Inserting the elements into the Stack myStack.Push("1st Element"); myStack.Push("2nd Element"); myStack.Push("3rd Element"); myStack.Push("4th Element"); myStack.Push("5th Element"); myStack.Push("6th Element"); // Displaying the count of elements // contained in the Stack before // removing all the elements Console.Write("Total number of elements"+ " in the Stack are : "); Console.WriteLine(myStack.Count); // Removing all elements from Stack myStack.Clear(); // Displaying the count of elements // contained in the Stack after // removing all the elements Console.Write("Total number of elements"+ " in the Stack are : "); Console.WriteLine(myStack.Count); }} Total number of elements in the Stack are : 6 Total number of elements in the Stack are : 0 Example 2: // C# code to illustrate the// Stack.Clear Methodusing System;using System.Collections; class GFG { // Driver code public static void Main() { // Creating a Stack Stack myStack = new Stack(); // Inserting the elements into the Stack myStack.Push(3); myStack.Push(5); myStack.Push(7); myStack.Push(9); myStack.Push(11); // Displaying the count of elements // contained in the Stack before // removing all the elements Console.Write("Total number of elements "+ "in the Stack are : "); Console.WriteLine(myStack.Count); // Removing all elements from Stack myStack.Clear(); // Displaying the count of elements // contained in the Stack after // removing all the elements Console.Write("Total number of elements"+ " in the Stack are : "); Console.WriteLine(myStack.Count); }} Total number of elements in the Stack are : 5 Total number of elements in the Stack are : 0 Reference: https://docs.microsoft.com/en-us/dotnet/api/system.collections.stack.clear?view=netframework-4.7.2 CSharp-Collections-Namespace CSharp-Collections-Stack CSharp-method C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between Abstract Class and Interface in C# String.Split() Method in C# with Examples C# | How to check whether a List contains a specified element C# | IsNullOrEmpty() Method C# Dictionary with examples C# | Delegates C# | Arrays of Strings C# | Method Overriding C# | Abstract Classes Difference between Ref and Out keywords in C#
[ { "code": null, "e": 24533, "s": 24505, "text": "\n04 Feb, 2019" }, { "code": null, "e": 24820, "s": 24533, "text": "This method(comes under System.Collections namespace) is used to remove all the objects from the Stack. This method will set the Count of Stack to zero, and references to other objects from elements of the collection are also removed. This method is an O(n) operation, where n is Count." }, { "code": null, "e": 24828, "s": 24820, "text": "Syntax:" }, { "code": null, "e": 24858, "s": 24828, "text": "public virtual void Clear ();" }, { "code": null, "e": 24919, "s": 24858, "text": "Below programs illustrate the use of above-discussed method:" }, { "code": null, "e": 24930, "s": 24919, "text": "Example 1:" }, { "code": "// C# code to illustrate the// Stack.Clear Methodusing System;using System.Collections; class GFG { // Driver code public static void Main() { // Creating a Stack Stack myStack = new Stack(); // Inserting the elements into the Stack myStack.Push(\"1st Element\"); myStack.Push(\"2nd Element\"); myStack.Push(\"3rd Element\"); myStack.Push(\"4th Element\"); myStack.Push(\"5th Element\"); myStack.Push(\"6th Element\"); // Displaying the count of elements // contained in the Stack before // removing all the elements Console.Write(\"Total number of elements\"+ \" in the Stack are : \"); Console.WriteLine(myStack.Count); // Removing all elements from Stack myStack.Clear(); // Displaying the count of elements // contained in the Stack after // removing all the elements Console.Write(\"Total number of elements\"+ \" in the Stack are : \"); Console.WriteLine(myStack.Count); }}", "e": 26014, "s": 24930, "text": null }, { "code": null, "e": 26107, "s": 26014, "text": "Total number of elements in the Stack are : 6\nTotal number of elements in the Stack are : 0\n" }, { "code": null, "e": 26118, "s": 26107, "text": "Example 2:" }, { "code": "// C# code to illustrate the// Stack.Clear Methodusing System;using System.Collections; class GFG { // Driver code public static void Main() { // Creating a Stack Stack myStack = new Stack(); // Inserting the elements into the Stack myStack.Push(3); myStack.Push(5); myStack.Push(7); myStack.Push(9); myStack.Push(11); // Displaying the count of elements // contained in the Stack before // removing all the elements Console.Write(\"Total number of elements \"+ \"in the Stack are : \"); Console.WriteLine(myStack.Count); // Removing all elements from Stack myStack.Clear(); // Displaying the count of elements // contained in the Stack after // removing all the elements Console.Write(\"Total number of elements\"+ \" in the Stack are : \"); Console.WriteLine(myStack.Count); }}", "e": 27109, "s": 26118, "text": null }, { "code": null, "e": 27202, "s": 27109, "text": "Total number of elements in the Stack are : 5\nTotal number of elements in the Stack are : 0\n" }, { "code": null, "e": 27213, "s": 27202, "text": "Reference:" }, { "code": null, "e": 27312, "s": 27213, "text": "https://docs.microsoft.com/en-us/dotnet/api/system.collections.stack.clear?view=netframework-4.7.2" }, { "code": null, "e": 27341, "s": 27312, "text": "CSharp-Collections-Namespace" }, { "code": null, "e": 27366, "s": 27341, "text": "CSharp-Collections-Stack" }, { "code": null, "e": 27380, "s": 27366, "text": "CSharp-method" }, { "code": null, "e": 27383, "s": 27380, "text": "C#" }, { "code": null, "e": 27481, "s": 27383, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27535, "s": 27481, "text": "Difference between Abstract Class and Interface in C#" }, { "code": null, "e": 27577, "s": 27535, "text": "String.Split() Method in C# with Examples" }, { "code": null, "e": 27639, "s": 27577, "text": "C# | How to check whether a List contains a specified element" }, { "code": null, "e": 27667, "s": 27639, "text": "C# | IsNullOrEmpty() Method" }, { "code": null, "e": 27695, "s": 27667, "text": "C# Dictionary with examples" }, { "code": null, "e": 27710, "s": 27695, "text": "C# | Delegates" }, { "code": null, "e": 27733, "s": 27710, "text": "C# | Arrays of Strings" }, { "code": null, "e": 27756, "s": 27733, "text": "C# | Method Overriding" }, { "code": null, "e": 27778, "s": 27756, "text": "C# | Abstract Classes" } ]
numpy.random.triangular() in Python - GeeksforGeeks
18 Aug, 2020 With the help of numpy.random.triangular() method, we can get the random samples from triangular distribution from interval [left, right] and return the random samples by using this method. Syntax : numpy.random.triangular(left, mode, right, size=None) Parameters : 1) left – lower limit of the triangle. 2) mode – peak value of the distribution. 3) right – upper limit of the triangle. 4) size – total number of samples required. Return : Return the random samples as numpy array. Example #1 : In this example we can see that by using numpy.random.triangular() method, we are able to get the random samples of triangular distribution and return the numpy array. Python3 # import numpyimport numpy as npimport matplotlib.pyplot as plt # Using triangular() methodgfg = np.random.triangular(-5, 0, 5, 5000) plt.hist(gfg, bins = 50, density = True)plt.show() Output : Example #2 : Python3 # import numpyimport numpy as npimport matplotlib.pyplot as plt # Using triangular() methodgfg = np.random.triangular(-10, 8, 10, 15000) plt.hist(gfg, bins = 100, density = True)plt.show() Output : Python numpy-Random Python-numpy 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": "\n18 Aug, 2020" }, { "code": null, "e": 25727, "s": 25537, "text": "With the help of numpy.random.triangular() method, we can get the random samples from triangular distribution from interval [left, right] and return the random samples by using this method." }, { "code": null, "e": 25790, "s": 25727, "text": "Syntax : numpy.random.triangular(left, mode, right, size=None)" }, { "code": null, "e": 25803, "s": 25790, "text": "Parameters :" }, { "code": null, "e": 25842, "s": 25803, "text": "1) left – lower limit of the triangle." }, { "code": null, "e": 25884, "s": 25842, "text": "2) mode – peak value of the distribution." }, { "code": null, "e": 25924, "s": 25884, "text": "3) right – upper limit of the triangle." }, { "code": null, "e": 25968, "s": 25924, "text": "4) size – total number of samples required." }, { "code": null, "e": 26019, "s": 25968, "text": "Return : Return the random samples as numpy array." }, { "code": null, "e": 26032, "s": 26019, "text": "Example #1 :" }, { "code": null, "e": 26200, "s": 26032, "text": "In this example we can see that by using numpy.random.triangular() method, we are able to get the random samples of triangular distribution and return the numpy array." }, { "code": null, "e": 26208, "s": 26200, "text": "Python3" }, { "code": "# import numpyimport numpy as npimport matplotlib.pyplot as plt # Using triangular() methodgfg = np.random.triangular(-5, 0, 5, 5000) plt.hist(gfg, bins = 50, density = True)plt.show()", "e": 26395, "s": 26208, "text": null }, { "code": null, "e": 26404, "s": 26395, "text": "Output :" }, { "code": null, "e": 26417, "s": 26404, "text": "Example #2 :" }, { "code": null, "e": 26425, "s": 26417, "text": "Python3" }, { "code": "# import numpyimport numpy as npimport matplotlib.pyplot as plt # Using triangular() methodgfg = np.random.triangular(-10, 8, 10, 15000) plt.hist(gfg, bins = 100, density = True)plt.show()", "e": 26616, "s": 26425, "text": null }, { "code": null, "e": 26625, "s": 26616, "text": "Output :" }, { "code": null, "e": 26645, "s": 26625, "text": "Python numpy-Random" }, { "code": null, "e": 26658, "s": 26645, "text": "Python-numpy" }, { "code": null, "e": 26665, "s": 26658, "text": "Python" }, { "code": null, "e": 26763, "s": 26665, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26795, "s": 26763, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26837, "s": 26795, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26879, "s": 26837, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 26906, "s": 26879, "text": "Python Classes and Objects" }, { "code": null, "e": 26962, "s": 26906, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26984, "s": 26962, "text": "Defaultdict in Python" }, { "code": null, "e": 27023, "s": 26984, "text": "Python | Get unique values from a list" }, { "code": null, "e": 27054, "s": 27023, "text": "Python | os.path.join() method" }, { "code": null, "e": 27083, "s": 27054, "text": "Create a directory in Python" } ]
CSS | DropDowns - GeeksforGeeks
03 Dec, 2018 Dropdowns are one of the most important parts of an interactive website. CSS is used to design the drop-down menus. A drop-down is a bunch of lists under an unordered list i.e. <ul> as it is popularly known in HTML world. Nested list (<li>) tags under the <ul> tag used to create drop-down structure. To bring out the effects use CSS for the components present in the structure. The CSS is very straightforward property used to create the drop-down menu. <!DOCTYPE html><html> <head> <title>Dropdown property</title> </head> <body> <nav> <ul> <li class="Lev-1"> <a href="">Level-1</a> <ul> <li><a href="">Link 1</a></li> <li><a href="">Link 2</a></li> <li><a href="">Link 3</a></li> <li><a href="">Link 4</a></li> </ul> </li> </ul> </nav> </body></html> Output: Example: Adding CSS property in HTML structure to create interactive drop-down structure. <!DOCTYPE html><html> <head> <title>Navigation property</title> <style> a { color: white; background-color:#990; text-decoration: none; } nav{ background: #333; } nav >ul{ margin: 0 auto; width: 80px; } nav ul li{ display: block; float: left; margin-left:-40px; position: relative; } nav ul a{ display: block; float: left; width: 150px; padding: 10px 20px; } nav ul a:hover{ background: #090; } nav ul li ul li{ float: none; } nav ul li ul{ display: none; position: absolute; background: #333; top: 42px; } nav ul li:hover>ul{ display: block; } nav ul li a{ display: block; } .gfg { font-size:40px; font-weight:bold; color:#009900; Text-align:center; } p { font-size:20px; font-weight:bold; text-align:center; } </style> </head> <body> <div class="gfg">GeeksforGeeks</div> <p>Dropdown Navigation property</p> <nav> <ul> <li class="Lev-1"> <a href="">Level-1</a> <ul> <li><a href="">Link 1</a></li> <li><a href="">Link 2</a></li> <li><a href="">Link 3</a></li> <li><a href="">Link 4</a></li> </ul> </li> </ul> </nav> </body></html> Output: The above-written code producing a proper output on the basis of a drop-down structure. Important parts of HTML code are discussed below: nav is the outermost container nav ul li ul li – float is set to none so that it remains intact when we hover over it. Use relative position so that li moves or changes its position relative to its component. Use ‘>’ after hover to see the effect of hover on the immediate next ul of the li. Right-aligned Dropdown: Right aligned dropdown is a dropdown that float value is right to display drop-down content on the right screen. Add float right to the div which holds the content. <!DOCTYPE html><html> <head> <title>right-aligned dropdown content property</title> <style> #drop { background-color: teal; color: white; padding: 10px; font-size: 16px; width: : 200px; height: : 60px; border-radius: 5px; font-size: 20px; } #drop-down { position: relative; display: inline-block; } #dropdown-menu { display: none; position: absolute; background-color: #666; width: 160px; margin-left:-45px; border-radius: 5px; z-index: 1; } #dropdown-menu a { color: black; padding: 12px 16px; text-decoration: none; display: block; } .gfg { font-size:40px; font-weight:bold; color:#009900; Text-align:center; } p { font-size:20px; font-weight:bold; text-align:center; } #dropdown-menu a:hover {background-color: #ddd;} #drop-down:hover #dropdown-menu {display: block;} </style> </head> <body> <div class="gfg">GeeksforGeeks</div> <p>Right-aligned Dropdown content property</p> <div id="drop-down" style=" float: right; margin-right: 70px;"> <button id="drop">DropDown</button> <div id="dropdown-menu"> <a href="">Item 1</a> <a href="">Item 2</a> <a href="">Item 3</a> <a href="">Item 4</a> </div> </div> </body></html> Output: Image Dropdown: It is not a dropdown but enlarges the image on which you hover. Needs basic CSS and an image to make it work. Example: <!DOCTYPE html><html> <head> <title>Image Dropdown</title> <style> .dropmenu { position: relative; display: inline-block; margin-left:150px; } .sub-dropmenu { display: none; position: absolute; } .dropmenu:hover .sub-dropmenu { display: block; } .enlarge { padding: 15px; text-align: center; } .gfg { margin-left:40px; font-size:30px; font-weight:bold; } </style> </head> <body> <div class = "gfg">Image Dropdown property</div> <div class="dropmenu"> <img src="https://media.geeksforgeeks.org/wp-content/uploads/temp1.png" width="150" height="50" align="middle"> <div class="sub-dropmenu"> <img src="https://media.geeksforgeeks.org/wp-content/uploads/temp1.png" width="600" height="200"> </div> </div> </body></html> Output: Clicked Drop-downs: This requires basic understanding of JavaScript as it is used to run some functions to make the clicked drop-down work.Example: <!DOCTYPE html><html> <head> <title>clicked dropdown</title> <style type="text/css"> button { background: #009900; width: 200px; height: 60px; color: white; border: 1px solid #fff; font-size: 20px; border-radius: 5px; } ul li { list-style: none; } ul li a { display: block; background: #c99; width: 200px; height: 50px; text-decoration: none; text-align: center; padding: 10px; border-radius: 5px; text-align: center; color: white; font-size: 25px; } ul li a { text-decoration: none; } ul li a:hover { background: #009900; } .open {display: none;} .gfg { font-size:40px; font-weight:bold; color:#009900; Text-align:center; } p { font-size:20px; font-weight:bold; text-align:center; } </style> <script type="text/javascript"> function open_menu(){ var clicked= document.getElementById('drop-menu'); if(clicked.style.display=='block') { clicked.style.display='none'; } else{ clicked.style.display='block'; } } </script> </head> <body> <div class="gfg">GeeksforGeeks</div> <p>Clicked Dropdown content property</p> <div id="dropdown"> <button onclick="open_menu()">Click Me!</button> <div class="open" id="drop-menu"> <ul> <li><a href="">Item-1</a></li> <li><a href="">Item-2</a></li> <li><a href="">Item-3</a></li> <li><a href="">Item-4</a></li> </ul> </div> </div> </body> </html> Output: Note: Some important highlights of the code: The javascript function will expand and collapse the menu when the button “Click Me” is clicked. We use onclick to call the javascript function in the button tag. Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. CSS-Basics Picked CSS HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to insert spaces/tabs in text using HTML/CSS? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to update Node.js and NPM to next version ? How to create footer to stay at the bottom of a Web page? How to apply style to parent if it has child with CSS? How to insert spaces/tabs in text using HTML/CSS? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to update Node.js and NPM to next version ? How to set the default value for an HTML <select> element ? Hide or show elements in HTML using display property
[ { "code": null, "e": 29317, "s": 29289, "text": "\n03 Dec, 2018" }, { "code": null, "e": 29772, "s": 29317, "text": "Dropdowns are one of the most important parts of an interactive website. CSS is used to design the drop-down menus. A drop-down is a bunch of lists under an unordered list i.e. <ul> as it is popularly known in HTML world. Nested list (<li>) tags under the <ul> tag used to create drop-down structure. To bring out the effects use CSS for the components present in the structure. The CSS is very straightforward property used to create the drop-down menu." }, { "code": "<!DOCTYPE html><html> <head> <title>Dropdown property</title> </head> <body> <nav> <ul> <li class=\"Lev-1\"> <a href=\"\">Level-1</a> <ul> <li><a href=\"\">Link 1</a></li> <li><a href=\"\">Link 2</a></li> <li><a href=\"\">Link 3</a></li> <li><a href=\"\">Link 4</a></li> </ul> </li> </ul> </nav> </body></html>", "e": 30277, "s": 29772, "text": null }, { "code": null, "e": 30285, "s": 30277, "text": "Output:" }, { "code": null, "e": 30375, "s": 30285, "text": "Example: Adding CSS property in HTML structure to create interactive drop-down structure." }, { "code": "<!DOCTYPE html><html> <head> <title>Navigation property</title> <style> a { color: white; background-color:#990; text-decoration: none; } nav{ background: #333; } nav >ul{ margin: 0 auto; width: 80px; } nav ul li{ display: block; float: left; margin-left:-40px; position: relative; } nav ul a{ display: block; float: left; width: 150px; padding: 10px 20px; } nav ul a:hover{ background: #090; } nav ul li ul li{ float: none; } nav ul li ul{ display: none; position: absolute; background: #333; top: 42px; } nav ul li:hover>ul{ display: block; } nav ul li a{ display: block; } .gfg { font-size:40px; font-weight:bold; color:#009900; Text-align:center; } p { font-size:20px; font-weight:bold; text-align:center; } </style> </head> <body> <div class=\"gfg\">GeeksforGeeks</div> <p>Dropdown Navigation property</p> <nav> <ul> <li class=\"Lev-1\"> <a href=\"\">Level-1</a> <ul> <li><a href=\"\">Link 1</a></li> <li><a href=\"\">Link 2</a></li> <li><a href=\"\">Link 3</a></li> <li><a href=\"\">Link 4</a></li> </ul> </li> </ul> </nav> </body></html> ", "e": 32318, "s": 30375, "text": null }, { "code": null, "e": 32326, "s": 32318, "text": "Output:" }, { "code": null, "e": 32464, "s": 32326, "text": "The above-written code producing a proper output on the basis of a drop-down structure. Important parts of HTML code are discussed below:" }, { "code": null, "e": 32495, "s": 32464, "text": "nav is the outermost container" }, { "code": null, "e": 32583, "s": 32495, "text": "nav ul li ul li – float is set to none so that it remains intact when we hover over it." }, { "code": null, "e": 32673, "s": 32583, "text": "Use relative position so that li moves or changes its position relative to its component." }, { "code": null, "e": 32756, "s": 32673, "text": "Use ‘>’ after hover to see the effect of hover on the immediate next ul of the li." }, { "code": null, "e": 32945, "s": 32756, "text": "Right-aligned Dropdown: Right aligned dropdown is a dropdown that float value is right to display drop-down content on the right screen. Add float right to the div which holds the content." }, { "code": "<!DOCTYPE html><html> <head> <title>right-aligned dropdown content property</title> <style> #drop { background-color: teal; color: white; padding: 10px; font-size: 16px; width: : 200px; height: : 60px; border-radius: 5px; font-size: 20px; } #drop-down { position: relative; display: inline-block; } #dropdown-menu { display: none; position: absolute; background-color: #666; width: 160px; margin-left:-45px; border-radius: 5px; z-index: 1; } #dropdown-menu a { color: black; padding: 12px 16px; text-decoration: none; display: block; } .gfg { font-size:40px; font-weight:bold; color:#009900; Text-align:center; } p { font-size:20px; font-weight:bold; text-align:center; } #dropdown-menu a:hover {background-color: #ddd;} #drop-down:hover #dropdown-menu {display: block;} </style> </head> <body> <div class=\"gfg\">GeeksforGeeks</div> <p>Right-aligned Dropdown content property</p> <div id=\"drop-down\" style=\" float: right; margin-right: 70px;\"> <button id=\"drop\">DropDown</button> <div id=\"dropdown-menu\"> <a href=\"\">Item 1</a> <a href=\"\">Item 2</a> <a href=\"\">Item 3</a> <a href=\"\">Item 4</a> </div> </div> </body></html> ", "e": 34814, "s": 32945, "text": null }, { "code": null, "e": 34822, "s": 34814, "text": "Output:" }, { "code": null, "e": 34948, "s": 34822, "text": "Image Dropdown: It is not a dropdown but enlarges the image on which you hover. Needs basic CSS and an image to make it work." }, { "code": null, "e": 34957, "s": 34948, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <title>Image Dropdown</title> <style> .dropmenu { position: relative; display: inline-block; margin-left:150px; } .sub-dropmenu { display: none; position: absolute; } .dropmenu:hover .sub-dropmenu { display: block; } .enlarge { padding: 15px; text-align: center; } .gfg { margin-left:40px; font-size:30px; font-weight:bold; } </style> </head> <body> <div class = \"gfg\">Image Dropdown property</div> <div class=\"dropmenu\"> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/temp1.png\" width=\"150\" height=\"50\" align=\"middle\"> <div class=\"sub-dropmenu\"> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/temp1.png\" width=\"600\" height=\"200\"> </div> </div> </body></html> ", "e": 36104, "s": 34957, "text": null }, { "code": null, "e": 36112, "s": 36104, "text": "Output:" }, { "code": null, "e": 36260, "s": 36112, "text": "Clicked Drop-downs: This requires basic understanding of JavaScript as it is used to run some functions to make the clicked drop-down work.Example:" }, { "code": "<!DOCTYPE html><html> <head> <title>clicked dropdown</title> <style type=\"text/css\"> button { background: #009900; width: 200px; height: 60px; color: white; border: 1px solid #fff; font-size: 20px; border-radius: 5px; } ul li { list-style: none; } ul li a { display: block; background: #c99; width: 200px; height: 50px; text-decoration: none; text-align: center; padding: 10px; border-radius: 5px; text-align: center; color: white; font-size: 25px; } ul li a { text-decoration: none; } ul li a:hover { background: #009900; } .open {display: none;} .gfg { font-size:40px; font-weight:bold; color:#009900; Text-align:center; } p { font-size:20px; font-weight:bold; text-align:center; } </style> <script type=\"text/javascript\"> function open_menu(){ var clicked= document.getElementById('drop-menu'); if(clicked.style.display=='block') { clicked.style.display='none'; } else{ clicked.style.display='block'; } } </script> </head> <body> <div class=\"gfg\">GeeksforGeeks</div> <p>Clicked Dropdown content property</p> <div id=\"dropdown\"> <button onclick=\"open_menu()\">Click Me!</button> <div class=\"open\" id=\"drop-menu\"> <ul> <li><a href=\"\">Item-1</a></li> <li><a href=\"\">Item-2</a></li> <li><a href=\"\">Item-3</a></li> <li><a href=\"\">Item-4</a></li> </ul> </div> </div> </body> </html> ", "e": 38501, "s": 36260, "text": null }, { "code": null, "e": 38509, "s": 38501, "text": "Output:" }, { "code": null, "e": 38554, "s": 38509, "text": "Note: Some important highlights of the code:" }, { "code": null, "e": 38651, "s": 38554, "text": "The javascript function will expand and collapse the menu when the button “Click Me” is clicked." }, { "code": null, "e": 38717, "s": 38651, "text": "We use onclick to call the javascript function in the button tag." }, { "code": null, "e": 38854, "s": 38717, "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": 38865, "s": 38854, "text": "CSS-Basics" }, { "code": null, "e": 38872, "s": 38865, "text": "Picked" }, { "code": null, "e": 38876, "s": 38872, "text": "CSS" }, { "code": null, "e": 38881, "s": 38876, "text": "HTML" }, { "code": null, "e": 38898, "s": 38881, "text": "Web Technologies" }, { "code": null, "e": 38903, "s": 38898, "text": "HTML" }, { "code": null, "e": 39001, "s": 38903, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 39051, "s": 39001, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 39113, "s": 39051, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 39161, "s": 39113, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 39219, "s": 39161, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 39274, "s": 39219, "text": "How to apply style to parent if it has child with CSS?" }, { "code": null, "e": 39324, "s": 39274, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 39386, "s": 39324, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 39434, "s": 39386, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 39494, "s": 39434, "text": "How to set the default value for an HTML <select> element ?" } ]
Count number of Faces using Python - OpenCV - GeeksforGeeks
06 Jun, 2021 Prerequisites: Face detection using dlib and openCV In this article, we will use image processing to detect and count the number of faces. We are not supposed to get all the features of the face. Instead, the objective is to obtain the bounding box through some methods i.e. coordinates of the face in the image, depending on different areas covered by the number of the coordinates, number faces that will be computed. OpenCV library in python is a computer vision library, mostly used for image processing, video processing, and analysis, facial recognition and detection, etc. Dlib library in python contains the pre-trained facial landmark detector, that is used to detect the (x, y) coordinates that map to facial structures on the face. Numpy is a general-purpose array-processing package. It provides a high-performance multidimensional array object and tools for working with these arrays. Below is the step-wise approach to Count the Number of faces: Step 1: Import required libraries. Python3 # Import librariesimport cv2import numpy as npimport dlib Step 2: Open the default camera to capture faces and use the dlib library to get coordinates. Python3 # (0) in VideoCapture is used to# connect to your computer's default cameracap = cv2.VideoCapture(0)# Get the coordinatesdetector = dlib.get_frontal_face_detector() Step 3: Count the number of faces. Capture the frames continuously. Convert the frames to grayscale(not necessary). Take an iterator i and initialize it to zero. Each time you get the coordinates to the face structure in the frame, increment the iterator by 1. Plot the box around each detected face along with its face count. Python3 while True: # Capture frame-by-frame ret, frame = cap.read() frame = cv2.flip(frame, 1) # Our operations on the frame come here gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) faces = detector(gray) # Counter to count number of faces i = 0 for face in faces: x, y = face.left(), face.top() x1, y1 = face.right(), face.bottom() cv2.rectangle(frame, (x, y), (x1, y1), (0, 255, 0), 2) # Increment the iterartor each time you get the coordinates i = i+1 # Adding face number to the box detecting faces cv2.putText(frame, 'face num'+str(i), (x-10, y-10), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2) print(face, i) # Display the resulting frame cv2.imshow('frame', frame) Step 4: Terminate the loop. Python3 # Enter key 'q' to break the loopif cv2.waitKey(1) & 0xFF == ord('q'): break Step 5: Clear windows. Python3 # When everything done, release# the capture and destroy the windowscap.release()cv2.destroyAllWindows() Below is the complete program of the above approach: Python3 # Import required librariesimport cv2import numpy as npimport dlib # Connects to your computer's default cameracap = cv2.VideoCapture(0) # Detect the coordinatesdetector = dlib.get_frontal_face_detector() # Capture frames continuouslywhile True: # Capture frame-by-frame ret, frame = cap.read() frame = cv2.flip(frame, 1) # RGB to grayscale gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) faces = detector(gray) # Iterator to count faces i = 0 for face in faces: # Get the coordinates of faces x, y = face.left(), face.top() x1, y1 = face.right(), face.bottom() cv2.rectangle(frame, (x, y), (x1, y1), (0, 255, 0), 2) # Increment iterator for each face in faces i = i+1 # Display the box and faces cv2.putText(frame, 'face num'+str(i), (x-10, y-10), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2) print(face, i) # Display the resulting frame cv2.imshow('frame', frame) # This command let's us quit with the "q" button on a keyboard. if cv2.waitKey(1) & 0xFF == ord('q'): break # Release the capture and destroy the windowscap.release()cv2.destroyAllWindows() Output: sooda367 Python-OpenCV 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": 25861, "s": 25833, "text": "\n06 Jun, 2021" }, { "code": null, "e": 25913, "s": 25861, "text": "Prerequisites: Face detection using dlib and openCV" }, { "code": null, "e": 26281, "s": 25913, "text": "In this article, we will use image processing to detect and count the number of faces. We are not supposed to get all the features of the face. Instead, the objective is to obtain the bounding box through some methods i.e. coordinates of the face in the image, depending on different areas covered by the number of the coordinates, number faces that will be computed." }, { "code": null, "e": 26441, "s": 26281, "text": "OpenCV library in python is a computer vision library, mostly used for image processing, video processing, and analysis, facial recognition and detection, etc." }, { "code": null, "e": 26604, "s": 26441, "text": "Dlib library in python contains the pre-trained facial landmark detector, that is used to detect the (x, y) coordinates that map to facial structures on the face." }, { "code": null, "e": 26759, "s": 26604, "text": "Numpy is a general-purpose array-processing package. It provides a high-performance multidimensional array object and tools for working with these arrays." }, { "code": null, "e": 26821, "s": 26759, "text": "Below is the step-wise approach to Count the Number of faces:" }, { "code": null, "e": 26857, "s": 26821, "text": "Step 1: Import required libraries. " }, { "code": null, "e": 26865, "s": 26857, "text": "Python3" }, { "code": "# Import librariesimport cv2import numpy as npimport dlib", "e": 26923, "s": 26865, "text": null }, { "code": null, "e": 27017, "s": 26923, "text": "Step 2: Open the default camera to capture faces and use the dlib library to get coordinates." }, { "code": null, "e": 27025, "s": 27017, "text": "Python3" }, { "code": "# (0) in VideoCapture is used to# connect to your computer's default cameracap = cv2.VideoCapture(0)# Get the coordinatesdetector = dlib.get_frontal_face_detector()", "e": 27190, "s": 27025, "text": null }, { "code": null, "e": 27225, "s": 27190, "text": "Step 3: Count the number of faces." }, { "code": null, "e": 27258, "s": 27225, "text": "Capture the frames continuously." }, { "code": null, "e": 27306, "s": 27258, "text": "Convert the frames to grayscale(not necessary)." }, { "code": null, "e": 27352, "s": 27306, "text": "Take an iterator i and initialize it to zero." }, { "code": null, "e": 27451, "s": 27352, "text": "Each time you get the coordinates to the face structure in the frame, increment the iterator by 1." }, { "code": null, "e": 27517, "s": 27451, "text": "Plot the box around each detected face along with its face count." }, { "code": null, "e": 27525, "s": 27517, "text": "Python3" }, { "code": "while True: # Capture frame-by-frame ret, frame = cap.read() frame = cv2.flip(frame, 1) # Our operations on the frame come here gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) faces = detector(gray) # Counter to count number of faces i = 0 for face in faces: x, y = face.left(), face.top() x1, y1 = face.right(), face.bottom() cv2.rectangle(frame, (x, y), (x1, y1), (0, 255, 0), 2) # Increment the iterartor each time you get the coordinates i = i+1 # Adding face number to the box detecting faces cv2.putText(frame, 'face num'+str(i), (x-10, y-10), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2) print(face, i) # Display the resulting frame cv2.imshow('frame', frame)", "e": 28307, "s": 27525, "text": null }, { "code": null, "e": 28335, "s": 28307, "text": "Step 4: Terminate the loop." }, { "code": null, "e": 28343, "s": 28335, "text": "Python3" }, { "code": "# Enter key 'q' to break the loopif cv2.waitKey(1) & 0xFF == ord('q'): break", "e": 28423, "s": 28343, "text": null }, { "code": null, "e": 28446, "s": 28423, "text": "Step 5: Clear windows." }, { "code": null, "e": 28454, "s": 28446, "text": "Python3" }, { "code": "# When everything done, release# the capture and destroy the windowscap.release()cv2.destroyAllWindows()", "e": 28559, "s": 28454, "text": null }, { "code": null, "e": 28612, "s": 28559, "text": "Below is the complete program of the above approach:" }, { "code": null, "e": 28620, "s": 28612, "text": "Python3" }, { "code": "# Import required librariesimport cv2import numpy as npimport dlib # Connects to your computer's default cameracap = cv2.VideoCapture(0) # Detect the coordinatesdetector = dlib.get_frontal_face_detector() # Capture frames continuouslywhile True: # Capture frame-by-frame ret, frame = cap.read() frame = cv2.flip(frame, 1) # RGB to grayscale gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) faces = detector(gray) # Iterator to count faces i = 0 for face in faces: # Get the coordinates of faces x, y = face.left(), face.top() x1, y1 = face.right(), face.bottom() cv2.rectangle(frame, (x, y), (x1, y1), (0, 255, 0), 2) # Increment iterator for each face in faces i = i+1 # Display the box and faces cv2.putText(frame, 'face num'+str(i), (x-10, y-10), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2) print(face, i) # Display the resulting frame cv2.imshow('frame', frame) # This command let's us quit with the \"q\" button on a keyboard. if cv2.waitKey(1) & 0xFF == ord('q'): break # Release the capture and destroy the windowscap.release()cv2.destroyAllWindows()", "e": 29817, "s": 28620, "text": null }, { "code": null, "e": 29825, "s": 29817, "text": "Output:" }, { "code": null, "e": 29834, "s": 29825, "text": "sooda367" }, { "code": null, "e": 29848, "s": 29834, "text": "Python-OpenCV" }, { "code": null, "e": 29855, "s": 29848, "text": "Python" }, { "code": null, "e": 29953, "s": 29855, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29971, "s": 29953, "text": "Python Dictionary" }, { "code": null, "e": 30006, "s": 29971, "text": "Read a file line by line in Python" }, { "code": null, "e": 30038, "s": 30006, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 30060, "s": 30038, "text": "Enumerate() in Python" }, { "code": null, "e": 30102, "s": 30060, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 30132, "s": 30102, "text": "Iterate over a list in Python" }, { "code": null, "e": 30158, "s": 30132, "text": "Python String | replace()" }, { "code": null, "e": 30187, "s": 30158, "text": "*args and **kwargs in Python" }, { "code": null, "e": 30231, "s": 30187, "text": "Reading and Writing to text files in Python" } ]
Transmitting data over WiFi using HTTPS
We looked at transmitting data over HTTP using ESP32 in the previous chapter. In this one, we will transmit data over HTTPS. The S in HTTPS stands for 'Secure'. Basically, whatever data you transmit is encrypted using Transport Layer Security (TLS). This means that if someone is eavesdropping on your communication, they won't understand what you've transmitted. Instead, what they'll get is some gibberish. Covering how HTTPS works is beyond the scope of this chapter. But a simple Google search will provide several useful resources for you to get started. In this chapter, we will see how to implement HTTPS on ESP32. In general, if you have a code written for sending an HTTP request to the server, you can convert it to HTTPS following these simple steps − Change the library from WiFiClient to WiFiClientSecure (you need to include WiFiClientSecure.h) Change the library from WiFiClient to WiFiClientSecure (you need to include WiFiClientSecure.h) Change the port from 80 to 443 Change the port from 80 to 443 There is an optional fourth step: Add CA Certificate for the server. This step is optional because it doesn't affect the security of the communication. It just assures you that you are communicating with the correct server. If you don't provide the CA Certificate, your communication will still be secure. The code you see below is very similar to the one used for the HTTP communication. You are strongly advised to revisit that chapter. In this walkthrough, we will simply highlight the parts that are different from the HTTP code. The code can be found on GitHub We begin with the inclusion of the WiFi library. We also need to include the WiFiClientSecure library here. #include <WiFi.h> #include <WiFiClientSecure.h> Next, we will define the constants. Note that the port is now 443 instead of 80. const char* ssid = "YOUR_SSID"; const char* password = "YOUR_PASSWORD"; const char* server = "httpbin.org"; const int port = 443; Next, instead of the WiFiClient object, we create the WiFiClientSecure object. WiFiClientSecure client; Next, we define the CA certificate for our server (httpbin.org). Now, you may be wondering how to get the CA certificate for our server. Detailed steps are given here to get the CA certificate of any server using Google Chrome. In that same post, a note on the validity of CA certificates has been provided, and it is recommended to use the certificate of the Certification Authority, instead of the certificate of the server, especially for applications where you just program the device once and send it out in the field for years. The Certification Authority's certificate has a much longer validity (15+ years), compared to the server's certificate validity (1−2 years). Therefore, we are using the certificate of the Starfield Class 2 Certification Authority (valid till 2034), instead of the certificate of httpbin.org (valid till Feb 2021). const char* ca_cert = \ "-----BEGIN CERTIFICATE-----\n" \ "MIIEDzCCAvegAwIBAgIBADANBgkqhkiG9w0BAQUFADBoMQswCQYDVQQGEwJVUzEl\n"\ "MCMGA1UEChMcU3RhcmZpZWxkIFRlY2hub2xvZ2llcywgSW5jLjEyMDAGA1UECxMp\n"\ "U3RhcmZpZWxkIENsYXNzIDIgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNMDQw\n"\ "NjI5MTczOTE2WhcNMzQwNjI5MTczOTE2WjBoMQswCQYDVQQGEwJVUzElMCMGA1UE\n"\ "ChMcU3RhcmZpZWxkIFRlY2hub2xvZ2llcywgSW5jLjEyMDAGA1UECxMpU3RhcmZp\n"\ "ZWxkIENsYXNzIDIgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwggEgMA0GCSqGSIb3\n"\ "DQEBAQUAA4IBDQAwggEIAoIBAQC3Msj+6XGmBIWtDBFk385N78gDGIc/oav7PKaf\n"\ "8MOh2tTYbitTkPskpD6E8J7oX+zlJ0T1KKY/e97gKvDIr1MvnsoFAZMej2YcOadN\n"\ "+lq2cwQlZut3f+dZxkqZJRRU6ybH838Z1TBwj6+wRir/resp7defqgSHo9T5iaU0\n"\ "X9tDkYI22WY8sbi5gv2cOj4QyDvvBmVmepsZGD3/cVE8MC5fvj13c7JdBmzDI1aa\n"\ "K4UmkhynArPkPw2vCHmCuDY96pzTNbO8acr1zJ3o/WSNF4Azbl5KXZnJHoe0nRrA\n"\ "1W4TNSNe35tfPe/W93bC6j67eA0cQmdrBNj41tpvi/JEoAGrAgEDo4HFMIHCMB0G\n"\ "A1UdDgQWBBS/X7fRzt0fhvRbVazc1xDCDqmI5zCBkgYDVR0jBIGKMIGHgBS/X7fR\n"\ "zt0fhvRbVazc1xDCDqmI56FspGowaDELMAkGA1UEBhMCVVMxJTAjBgNVBAoTHFN0\n"\ "YXJmaWVsZCBUZWNobm9sb2dpZXMsIEluYy4xMjAwBgNVBAsTKVN0YXJmaWVsZCBD\n"\ "bGFzcyAyIENlcnRpZmljYXRpb24gQXV0aG9yaXR5ggEAMAwGA1UdEwQFMAMBAf8w\n"\ "DQYJKoZIhvcNAQEFBQADggEBAAWdP4id0ckaVaGsafPzWdqbAYcaT1epoXkJKtv3\n"\ "L7IezMdeatiDh6GX70k1PncGQVhiv45YuApnP+yz3SFmH8lU+nLMPUxA2IGvd56D\n"\ "eruix/U0F47ZEUD0/CwqTRV/p2JdLiXTAAsgGh1o+Re49L2L7ShZ3U0WixeDyLJl\n"\ "xy16paq8U4Zt3VekyvggQQto8PT7dL5WXXp59fkdheMtlb71cZBDzI0fmgAKhynp\n"\ "VSJYACPq4xJDKVtHCN2MQWplBqjlIapBtJUhlbl90TSrE9atvNziPTnNvT51cKEY\n"\ "WQPJIrSPnNVeKtelttQKbfi3QBFGmh95DmK/D5fs4C8fF5Q=\n"\ "-----END CERTIFICATE-----\n"; In the setup, we connect to the WiFi in the station mode using the credentials provided, like before. Here, we have the additional step of setting the CA Certificate for our WiFiSecureClient. By doing this, we are telling the client that only communicate with the server if its CA certificate matches the one provided. void setup() { Serial.begin(115200); WiFi.mode(WIFI_STA); //The WiFi is in station mode. The other is the softAP mode WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println(""); Serial.print("WiFi connected to: "); Serial.println(ssid); Serial.println("IP address: "); Serial.println(WiFi.localIP()); client.setCACert(ca_cert); //Only communicate with the server if the CA certificates match delay(2000); } The loop is exactly the same as the one used in the HTTP example. void loop() { int conn; int chip_id = ESP.getEfuseMac();; Serial.printf(" Flash Chip id = %08X\t", chip_id); Serial.println(); Serial.println(); String body = "ChipId=" + String(chip_id) + "&SentBy=" + "your_name"; int body_len = body.length(); Serial.println("....."); Serial.println(); Serial.print("For sending parameters, connecting to "); Serial.println(server); conn = client.connect(server, port); if (conn == 1) { Serial.println(); Serial.print("Sending Parameters..."); //Request client.println("POST /post HTTP/1.1"); //Headers client.print("Host: "); client.println(server); client.println("Content-Type: application/x−www−form−urlencoded"); client.print("Content-Length: "); client.println(body_len); client.println("Connection: Close"); client.println(); //Body client.println(body); client.println(); //Wait for server response while (client.available() == 0); //Print Server Response while (client.available()) { char c = client.read(); Serial.write(c); } } else { client.stop(); Serial.println("Connection Failed"); } delay(5000); } The response to be expected from the server is also similar to the HTTP example. The only difference is that the response received will also be secure. But we won't have to worry about decrypting the encrypted message. ESP32 does that for us. Notice the URL field in the server response. It contains https instead of http, confirming that our transmission was secure. In fact, if you edit the CA certificate slightly, say you just delete one character, and then try to run the sketch, you will see the connection getting failed. However, if you remove the client.setCACert() line from the setup, the connection will get established again securely, even with the faulty CA Certificate. This proves that setting the CA Certificate doesn't affect the security of our communication. It just helps us verify that we are communicating with the right server. If we do set the certificate, then the ESP32 won't communicate with the server unless the provided CA Certificate matches the server's CA Certificate. If we don't set the certificate, the ESP32 will still communicate with the server securely. Congratulations!! You've successfully sent your HTTPS requests using ESP32. Note − The hardware accelerator on ESP32 that performs the encryption of messages for HTTPS, can support a maximum of 16384 bytes (16 KB) of data. Therefore, if your message size exceeds 16 KB, you may need to break it down into chunks. Getting CA Certificate for any server using Google Chrome Getting CA Certificate for any server using Google Chrome 54 Lectures 4.5 hours Frahaan Hussain 20 Lectures 5 hours Azaz Patel 20 Lectures 4 hours Azaz Patel 0 Lectures 0 mins Eduonix Learning Solutions 169 Lectures 12.5 hours Kalob Taulien 29 Lectures 2 hours Zenva Print Add Notes Bookmark this page
[ { "code": null, "e": 2805, "s": 2183, "text": "We looked at transmitting data over HTTP using ESP32 in the previous chapter. In this one, we will transmit data over HTTPS. The S in HTTPS stands for 'Secure'. Basically, whatever data you transmit is encrypted using Transport Layer Security (TLS). This means that if someone is eavesdropping on your communication, they won't understand what you've transmitted. Instead, what they'll get is some gibberish. Covering how HTTPS works is beyond the scope of this chapter. But a simple Google search will provide several useful resources for you to get started. In this chapter, we will see how to implement HTTPS on ESP32." }, { "code": null, "e": 2946, "s": 2805, "text": "In general, if you have a code written for sending an HTTP request to the server, you can convert it to HTTPS following these simple steps −" }, { "code": null, "e": 3042, "s": 2946, "text": "Change the library from WiFiClient to WiFiClientSecure (you need to include WiFiClientSecure.h)" }, { "code": null, "e": 3138, "s": 3042, "text": "Change the library from WiFiClient to WiFiClientSecure (you need to include WiFiClientSecure.h)" }, { "code": null, "e": 3169, "s": 3138, "text": "Change the port from 80 to 443" }, { "code": null, "e": 3200, "s": 3169, "text": "Change the port from 80 to 443" }, { "code": null, "e": 3506, "s": 3200, "text": "There is an optional fourth step: Add CA Certificate for the server. This step is optional because it doesn't affect the security of the communication. It just assures you that you are communicating with the correct server. If you don't provide the CA Certificate, your communication will still be secure." }, { "code": null, "e": 3734, "s": 3506, "text": "The code you see below is very similar to the one used for the HTTP communication. You are strongly advised to revisit that chapter. In this walkthrough, we will simply highlight the parts that are different from the HTTP code." }, { "code": null, "e": 3766, "s": 3734, "text": "The code can be found on GitHub" }, { "code": null, "e": 3874, "s": 3766, "text": "We begin with the inclusion of the WiFi library. We also need to include the WiFiClientSecure library here." }, { "code": null, "e": 3922, "s": 3874, "text": "#include <WiFi.h>\n#include <WiFiClientSecure.h>" }, { "code": null, "e": 4004, "s": 3922, "text": "Next, we will define the constants. Note that the port is now 443 instead of 80. " }, { "code": null, "e": 4136, "s": 4004, "text": "const char* ssid = \"YOUR_SSID\";\nconst char* password = \"YOUR_PASSWORD\";\n\nconst char* server = \"httpbin.org\";\nconst int port = 443;\n" }, { "code": null, "e": 4215, "s": 4136, "text": "Next, instead of the WiFiClient object, we create the WiFiClientSecure object." }, { "code": null, "e": 4241, "s": 4215, "text": "WiFiClientSecure client;\n" }, { "code": null, "e": 5089, "s": 4241, "text": "Next, we define the CA certificate for our server (httpbin.org). Now, you may be wondering how to get the CA certificate for our server. Detailed steps are given here to get the CA certificate of any server using Google Chrome. In that same post, a note on the validity of CA certificates has been provided, and it is recommended to use the certificate of the Certification Authority, instead of the certificate of the server, especially for applications where you just program the device once and send it out in the field for years. The Certification Authority's certificate has a much longer validity (15+ years), compared to the server's certificate validity (1−2 years). Therefore, we are using the certificate of the Starfield Class 2 Certification Authority (valid till 2034), instead of the certificate of httpbin.org (valid till Feb 2021)." }, { "code": null, "e": 6704, "s": 5089, "text": "const char* ca_cert = \\ \n\"-----BEGIN CERTIFICATE-----\\n\" \\\n\"MIIEDzCCAvegAwIBAgIBADANBgkqhkiG9w0BAQUFADBoMQswCQYDVQQGEwJVUzEl\\n\"\\\n\"MCMGA1UEChMcU3RhcmZpZWxkIFRlY2hub2xvZ2llcywgSW5jLjEyMDAGA1UECxMp\\n\"\\\n\"U3RhcmZpZWxkIENsYXNzIDIgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNMDQw\\n\"\\\n\"NjI5MTczOTE2WhcNMzQwNjI5MTczOTE2WjBoMQswCQYDVQQGEwJVUzElMCMGA1UE\\n\"\\\n\"ChMcU3RhcmZpZWxkIFRlY2hub2xvZ2llcywgSW5jLjEyMDAGA1UECxMpU3RhcmZp\\n\"\\\n\"ZWxkIENsYXNzIDIgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwggEgMA0GCSqGSIb3\\n\"\\\n\"DQEBAQUAA4IBDQAwggEIAoIBAQC3Msj+6XGmBIWtDBFk385N78gDGIc/oav7PKaf\\n\"\\\n\"8MOh2tTYbitTkPskpD6E8J7oX+zlJ0T1KKY/e97gKvDIr1MvnsoFAZMej2YcOadN\\n\"\\\n\"+lq2cwQlZut3f+dZxkqZJRRU6ybH838Z1TBwj6+wRir/resp7defqgSHo9T5iaU0\\n\"\\\n\"X9tDkYI22WY8sbi5gv2cOj4QyDvvBmVmepsZGD3/cVE8MC5fvj13c7JdBmzDI1aa\\n\"\\\n\"K4UmkhynArPkPw2vCHmCuDY96pzTNbO8acr1zJ3o/WSNF4Azbl5KXZnJHoe0nRrA\\n\"\\\n\"1W4TNSNe35tfPe/W93bC6j67eA0cQmdrBNj41tpvi/JEoAGrAgEDo4HFMIHCMB0G\\n\"\\\n\"A1UdDgQWBBS/X7fRzt0fhvRbVazc1xDCDqmI5zCBkgYDVR0jBIGKMIGHgBS/X7fR\\n\"\\\n\"zt0fhvRbVazc1xDCDqmI56FspGowaDELMAkGA1UEBhMCVVMxJTAjBgNVBAoTHFN0\\n\"\\\n\"YXJmaWVsZCBUZWNobm9sb2dpZXMsIEluYy4xMjAwBgNVBAsTKVN0YXJmaWVsZCBD\\n\"\\\n\"bGFzcyAyIENlcnRpZmljYXRpb24gQXV0aG9yaXR5ggEAMAwGA1UdEwQFMAMBAf8w\\n\"\\\n\"DQYJKoZIhvcNAQEFBQADggEBAAWdP4id0ckaVaGsafPzWdqbAYcaT1epoXkJKtv3\\n\"\\\n\"L7IezMdeatiDh6GX70k1PncGQVhiv45YuApnP+yz3SFmH8lU+nLMPUxA2IGvd56D\\n\"\\\n\"eruix/U0F47ZEUD0/CwqTRV/p2JdLiXTAAsgGh1o+Re49L2L7ShZ3U0WixeDyLJl\\n\"\\\n\"xy16paq8U4Zt3VekyvggQQto8PT7dL5WXXp59fkdheMtlb71cZBDzI0fmgAKhynp\\n\"\\\n\"VSJYACPq4xJDKVtHCN2MQWplBqjlIapBtJUhlbl90TSrE9atvNziPTnNvT51cKEY\\n\"\\\n\"WQPJIrSPnNVeKtelttQKbfi3QBFGmh95DmK/D5fs4C8fF5Q=\\n\"\\\n\"-----END CERTIFICATE-----\\n\";\n" }, { "code": null, "e": 7023, "s": 6704, "text": "In the setup, we connect to the WiFi in the station mode using the credentials provided, like before. Here, we have the additional step of setting the CA Certificate for our WiFiSecureClient. By doing this, we are telling the client that only communicate with the server if its CA certificate matches the one provided." }, { "code": null, "e": 7563, "s": 7023, "text": "void setup() {\n Serial.begin(115200);\n WiFi.mode(WIFI_STA); //The WiFi is in station mode. The other is the softAP mode\n WiFi.begin(ssid, password);\n while (WiFi.status() != WL_CONNECTED) {\n delay(500);\n Serial.print(\".\");\n }\n Serial.println(\"\"); Serial.print(\"WiFi connected to: \"); Serial.println(ssid); Serial.println(\"IP address: \"); Serial.println(WiFi.localIP());\n client.setCACert(ca_cert); //Only communicate with the server if the CA certificates match\n delay(2000);\n}" }, { "code": null, "e": 7629, "s": 7563, "text": "The loop is exactly the same as the one used in the HTTP example." }, { "code": null, "e": 8858, "s": 7629, "text": "void loop() {\n int conn;\n int chip_id = ESP.getEfuseMac();;\n Serial.printf(\" Flash Chip id = %08X\\t\", chip_id);\n Serial.println();\n Serial.println();\n String body = \"ChipId=\" + String(chip_id) + \"&SentBy=\" + \"your_name\";\n int body_len = body.length();\n\n Serial.println(\".....\");\n Serial.println(); Serial.print(\"For sending parameters, connecting to \"); Serial.println(server);\n conn = client.connect(server, port);\n\n if (conn == 1) {\n Serial.println(); Serial.print(\"Sending Parameters...\");\n //Request\n client.println(\"POST /post HTTP/1.1\");\n //Headers\n client.print(\"Host: \"); client.println(server);\n client.println(\"Content-Type: application/x−www−form−urlencoded\");\n client.print(\"Content-Length: \"); client.println(body_len);\n client.println(\"Connection: Close\");\n client.println();\n //Body\n client.println(body);\n client.println();\n\n //Wait for server response\n while (client.available() == 0);\n\n //Print Server Response\n while (client.available()) {\n char c = client.read();\n Serial.write(c);\n }\n } else {\n client.stop();\n Serial.println(\"Connection Failed\");\n }\n delay(5000);\n}" }, { "code": null, "e": 9101, "s": 8858, "text": "The response to be expected from the server is also similar to the HTTP example. The only difference is that the response received will also be secure. But we won't have to worry about decrypting the encrypted message. ESP32 does that for us." }, { "code": null, "e": 9388, "s": 9101, "text": "Notice the URL field in the server response. It contains https instead of http, confirming that our transmission was secure. In fact, if you edit the CA certificate slightly, say you just delete one character, and then try to run the sketch, you will see the connection getting failed. " }, { "code": null, "e": 9955, "s": 9388, "text": "However, if you remove the client.setCACert() line from the setup, the connection will get established again securely, even with the faulty CA Certificate. This proves that setting the CA Certificate doesn't affect the security of our communication. It just helps us verify that we are communicating with the right server. If we do set the certificate, then the ESP32 won't communicate with the server unless the provided CA Certificate matches the server's CA Certificate. If we don't set the certificate, the ESP32 will still communicate with the server securely. " }, { "code": null, "e": 10031, "s": 9955, "text": "Congratulations!! You've successfully sent your HTTPS requests using ESP32." }, { "code": null, "e": 10270, "s": 10031, "text": "Note − The hardware accelerator on ESP32 that performs the encryption of messages for HTTPS, can \nsupport a maximum of 16384 bytes (16 KB) of data. Therefore, if your message size exceeds\n16 KB, you may need to break it down into chunks. " }, { "code": null, "e": 10328, "s": 10270, "text": "Getting CA Certificate for any server using Google Chrome" }, { "code": null, "e": 10386, "s": 10328, "text": "Getting CA Certificate for any server using Google Chrome" }, { "code": null, "e": 10421, "s": 10386, "text": "\n 54 Lectures \n 4.5 hours \n" }, { "code": null, "e": 10438, "s": 10421, "text": " Frahaan Hussain" }, { "code": null, "e": 10471, "s": 10438, "text": "\n 20 Lectures \n 5 hours \n" }, { "code": null, "e": 10483, "s": 10471, "text": " Azaz Patel" }, { "code": null, "e": 10516, "s": 10483, "text": "\n 20 Lectures \n 4 hours \n" }, { "code": null, "e": 10528, "s": 10516, "text": " Azaz Patel" }, { "code": null, "e": 10558, "s": 10528, "text": "\n 0 Lectures \n 0 mins\n" }, { "code": null, "e": 10586, "s": 10558, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 10623, "s": 10586, "text": "\n 169 Lectures \n 12.5 hours \n" }, { "code": null, "e": 10638, "s": 10623, "text": " Kalob Taulien" }, { "code": null, "e": 10671, "s": 10638, "text": "\n 29 Lectures \n 2 hours \n" }, { "code": null, "e": 10678, "s": 10671, "text": " Zenva" }, { "code": null, "e": 10685, "s": 10678, "text": " Print" }, { "code": null, "e": 10696, "s": 10685, "text": " Add Notes" } ]
Angular Material - Divider
The md-divider, an Angular Directive, is a rule element and is used to display a thin lightweight rule to group and divide contents within lists and page layouts. The following table lists out the parameters and description of the different attributes of md-divider. md-inset Add this attribute to activate the inset divider style. The following example showcases the use of md-divider directive to showcase uses of dividers. am_dividers.htm <html lang = "en"> <head> <link rel = "stylesheet" href = "https://ajax.googleapis.com/ajax/libs/angular_material/1.0.0/angular-material.min.css"> <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script> <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-animate.min.js"></script> <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-aria.min.js"></script> <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-messages.min.js"></script> <script src = "https://ajax.googleapis.com/ajax/libs/angular_material/1.0.0/angular-material.min.js"></script> <script language = "javascript"> angular .module('firstApplication', ['ngMaterial']) .controller('dividerController', dividerController); function dividerController ($scope) { var self = this; self.allContacts = loadContacts(); self.contacts = [self.allContacts[0]]; function loadContacts() { var contacts = [ 'Roberto Karlos', 'Bob Crestor', 'Nigel Rick', 'Narayana Garner' ]; return contacts.map(function (c, index) { var cParts = c.split(' '); var contact = { name: c, email: cParts[0][0].toLowerCase() + '.' + cParts[1].toLowerCase() + '@example.com', image: 'http://lorempixel.com/50/50/people?' + index }; contact._lowername = contact.name.toLowerCase(); return contact; }); } } </script> </head> <body ng-app = "firstApplication"> <div id = "dividerContainer" ng-controller = "dividerController as ctrl" layout = "column" ng-cloak> <md-content> <md-list> <md-subheader class = "md-no-sticky">Contacts</md-subheader> <md-list-item class = "md-2-line contact-item" ng-repeat = "(index, contact) in ctrl.allContacts" ng-if = "ctrl.contacts.indexOf(contact) < 0"> <img ng-src = "{{contact.image}}" class = "md-avatar" alt = "{{contact.name}}" /> <div class = "md-list-item-text compact"> <h3>{{contact.name}}</h3> <p>{{contact.email}}</p> </div> <md-divider ng-if = "!$last"></md-divider> </md-list-item> </md-list> <md-list> <md-subheader class = "md-no-sticky">Contacts (With Insets)</md-subheader> <md-list-item class = "md-2-line contact-item" ng-repeat = "(index, contact) in ctrl.allContacts" ng-if = "ctrl.contacts.indexOf(contact) < 0"> <img ng-src = "{{contact.image}}" class = "md-avatar" alt = "{{contact.name}}" /> <div class = "md-list-item-text compact"> <h3>{{contact.name}}</h3> <p>{{contact.email}}</p> </div> <md-divider md-inset ng-if = "!$last"></md-divider> </md-list-item> </md-list> </md-content> </div> </body> </html> Verify the result. {{contact.email}} {{contact.email}} 16 Lectures 1.5 hours Anadi Sharma 28 Lectures 2.5 hours Anadi Sharma 11 Lectures 7.5 hours SHIVPRASAD KOIRALA 16 Lectures 2.5 hours Frahaan Hussain 69 Lectures 5 hours Senol Atac 53 Lectures 3.5 hours Senol Atac Print Add Notes Bookmark this page
[ { "code": null, "e": 2353, "s": 2190, "text": "The md-divider, an Angular Directive, is a rule element and is used to display a thin lightweight rule to group and divide contents within lists and page layouts." }, { "code": null, "e": 2457, "s": 2353, "text": "The following table lists out the parameters and description of the different attributes of md-divider." }, { "code": null, "e": 2466, "s": 2457, "text": "md-inset" }, { "code": null, "e": 2522, "s": 2466, "text": "Add this attribute to activate the inset divider style." }, { "code": null, "e": 2616, "s": 2522, "text": "The following example showcases the use of md-divider directive to showcase uses of dividers." }, { "code": null, "e": 2632, "s": 2616, "text": "am_dividers.htm" }, { "code": null, "e": 6354, "s": 2632, "text": "<html lang = \"en\">\n <head>\n <link rel = \"stylesheet\"\n href = \"https://ajax.googleapis.com/ajax/libs/angular_material/1.0.0/angular-material.min.css\">\n <script src = \"https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js\"></script>\n <script src = \"https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-animate.min.js\"></script>\n <script src = \"https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-aria.min.js\"></script>\n <script src = \"https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-messages.min.js\"></script>\n <script src = \"https://ajax.googleapis.com/ajax/libs/angular_material/1.0.0/angular-material.min.js\"></script>\n <script language = \"javascript\">\n angular\n .module('firstApplication', ['ngMaterial'])\n .controller('dividerController', dividerController);\n\n function dividerController ($scope) {\n var self = this; \n self.allContacts = loadContacts();\n self.contacts = [self.allContacts[0]];\n \n function loadContacts() {\n var contacts = [\n 'Roberto Karlos',\n 'Bob Crestor',\n 'Nigel Rick',\n 'Narayana Garner' \n ];\n \n return contacts.map(function (c, index) {\n var cParts = c.split(' ');\n var contact = {\n name: c,\n email: cParts[0][0].toLowerCase() + '.' + cParts[1].toLowerCase() \n + '@example.com',\n image: 'http://lorempixel.com/50/50/people?' + index\n };\n contact._lowername = contact.name.toLowerCase();\n return contact;\n });\n }\n } \n </script> \n </head>\n \n <body ng-app = \"firstApplication\"> \n <div id = \"dividerContainer\" ng-controller = \"dividerController as ctrl\"\n layout = \"column\" ng-cloak>\n <md-content>\n <md-list>\n <md-subheader class = \"md-no-sticky\">Contacts</md-subheader>\n <md-list-item class = \"md-2-line contact-item\"\n ng-repeat = \"(index, contact) in ctrl.allContacts\"\n ng-if = \"ctrl.contacts.indexOf(contact) < 0\">\n <img ng-src = \"{{contact.image}}\" class = \"md-avatar\"\n alt = \"{{contact.name}}\" />\n \n <div class = \"md-list-item-text compact\">\n <h3>{{contact.name}}</h3>\n <p>{{contact.email}}</p>\n </div>\n \n <md-divider ng-if = \"!$last\"></md-divider>\n </md-list-item>\n </md-list>\n \n <md-list>\n <md-subheader class = \"md-no-sticky\">Contacts (With Insets)</md-subheader>\n <md-list-item class = \"md-2-line contact-item\"\n ng-repeat = \"(index, contact) in ctrl.allContacts\"\n ng-if = \"ctrl.contacts.indexOf(contact) < 0\">\n <img ng-src = \"{{contact.image}}\" class = \"md-avatar\"\n alt = \"{{contact.name}}\" />\n \n <div class = \"md-list-item-text compact\">\n <h3>{{contact.name}}</h3>\n <p>{{contact.email}}</p>\n </div>\n \n <md-divider md-inset ng-if = \"!$last\"></md-divider>\n </md-list-item>\n </md-list>\n \n </md-content>\t \n </div>\n </body>\n</html>" }, { "code": null, "e": 6373, "s": 6354, "text": "Verify the result." }, { "code": null, "e": 6391, "s": 6373, "text": "{{contact.email}}" }, { "code": null, "e": 6409, "s": 6391, "text": "{{contact.email}}" }, { "code": null, "e": 6444, "s": 6409, "text": "\n 16 Lectures \n 1.5 hours \n" }, { "code": null, "e": 6458, "s": 6444, "text": " Anadi Sharma" }, { "code": null, "e": 6493, "s": 6458, "text": "\n 28 Lectures \n 2.5 hours \n" }, { "code": null, "e": 6507, "s": 6493, "text": " Anadi Sharma" }, { "code": null, "e": 6542, "s": 6507, "text": "\n 11 Lectures \n 7.5 hours \n" }, { "code": null, "e": 6562, "s": 6542, "text": " SHIVPRASAD KOIRALA" }, { "code": null, "e": 6597, "s": 6562, "text": "\n 16 Lectures \n 2.5 hours \n" }, { "code": null, "e": 6614, "s": 6597, "text": " Frahaan Hussain" }, { "code": null, "e": 6647, "s": 6614, "text": "\n 69 Lectures \n 5 hours \n" }, { "code": null, "e": 6659, "s": 6647, "text": " Senol Atac" }, { "code": null, "e": 6694, "s": 6659, "text": "\n 53 Lectures \n 3.5 hours \n" }, { "code": null, "e": 6706, "s": 6694, "text": " Senol Atac" }, { "code": null, "e": 6713, "s": 6706, "text": " Print" }, { "code": null, "e": 6724, "s": 6713, "text": " Add Notes" } ]
WebGL - Drawing a Triangle
In the previous chapter (Chapter 11), we discussed how to draw three points using WebGL. In Chapter 5, we took sample application to demonstrate how to draw a triangle. In both the examples, we have drawn the primitives using only vertices. To draw more complex shapes/meshes, we pass the indices of a geometry too, along with the vertices, to the shaders. In this chapter, we will see how to draw a triangle using indices. The following steps are required to create a WebGL application to draw a triangle. Step 1 − Prepare the Canvas and Get WebGL Rendering Context In this step, we obtain the WebGL Rendering context object using getContext(). Step 2 − Define the Geometry and Store it in Buffer Objects Since we are drawing a triangle using indices, we have to pass the three vertices of the triangle, including the indices, and store them in the buffers. var vertices = [ -0.5,0.5,0.0, -0.5,-0.5,0.0, 0.5,-0.5,0.0, ]; indices = [0,1,2]; Step 3 − Create and Compile the Shader Programs In this step, you need to write vertex shader and fragment shader programs, compile them, and create a combined program by linking these two programs. Vertex Shader − In the vertex shader of the program, we define the vector attribute to store 3D coordinates and assign it to gl_position. Vertex Shader − In the vertex shader of the program, we define the vector attribute to store 3D coordinates and assign it to gl_position. var vertCode = 'attribute vec3 coordinates;' + 'void main(void) {' + ' gl_Position = vec4(coordinates, 1.0);' + '}'; Fragment Shader − In the fragment shader, we simply assign the fragment color to the gl_FragColor variable. Fragment Shader − In the fragment shader, we simply assign the fragment color to the gl_FragColor variable. var fragCode = 'void main(void) {' + ' gl_FragColor = vec4(1, 0.5, 0.0, 1);' + '}'; Step 4 − Associate the Shader Programs to the Buffer Objects In this step, we associate the buffer objects and the shader program. Step 5 − Drawing the Required Object Since we are drawing a triangle using indices, we will use drawElements(). To this method, we have to pass the number of indices. The value of the indices.length signifies the number of indices. gl.drawElements(gl.TRIANGLES, indices.length, gl.UNSIGNED_SHORT,0); The following program code shows how to draw a triangle in WebGL using indices − <!doctype html> <html> <body> <canvas width = "570" height = "570" id = "my_Canvas"></canvas> <script> /*============== Creating a canvas ====================*/ var canvas = document.getElementById('my_Canvas'); gl = canvas.getContext('experimental-webgl'); /*======== Defining and storing the geometry ===========*/ var vertices = [ -0.5,0.5,0.0, -0.5,-0.5,0.0, 0.5,-0.5,0.0, ]; indices = [0,1,2]; // Create an empty buffer object to store vertex buffer var vertex_buffer = gl.createBuffer(); // Bind appropriate array buffer to it gl.bindBuffer(gl.ARRAY_BUFFER, vertex_buffer); // Pass the vertex data to the buffer gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW); // Unbind the buffer gl.bindBuffer(gl.ARRAY_BUFFER, null); // Create an empty buffer object to store Index buffer var Index_Buffer = gl.createBuffer(); // Bind appropriate array buffer to it gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, Index_Buffer); // Pass the vertex data to the buffer gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(indices), gl.STATIC_DRAW); // Unbind the buffer gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, null); /*================ Shaders ====================*/ // Vertex shader source code var vertCode = 'attribute vec3 coordinates;' + 'void main(void) {' + ' gl_Position = vec4(coordinates, 1.0);' + '}'; // Create a vertex shader object var vertShader = gl.createShader(gl.VERTEX_SHADER); // Attach vertex shader source code gl.shaderSource(vertShader, vertCode); // Compile the vertex shader gl.compileShader(vertShader); //fragment shader source code var fragCode = 'void main(void) {' + ' gl_FragColor = vec4(0.0, 0.0, 0.0, 0.1);' + '}'; // Create fragment shader object var fragShader = gl.createShader(gl.FRAGMENT_SHADER); // Attach fragment shader source code gl.shaderSource(fragShader, fragCode); // Compile the fragmentt shader gl.compileShader(fragShader); // Create a shader program object to store // the combined shader program var shaderProgram = gl.createProgram(); // Attach a vertex shader gl.attachShader(shaderProgram, vertShader); // Attach a fragment shader gl.attachShader(shaderProgram, fragShader); // Link both the programs gl.linkProgram(shaderProgram); // Use the combined shader program object gl.useProgram(shaderProgram); /*======= Associating shaders to buffer objects =======*/ // Bind vertex buffer object gl.bindBuffer(gl.ARRAY_BUFFER, vertex_buffer); // Bind index buffer object gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, Index_Buffer); // Get the attribute location var coord = gl.getAttribLocation(shaderProgram, "coordinates"); // Point an attribute to the currently bound VBO gl.vertexAttribPointer(coord, 3, gl.FLOAT, false, 0, 0); // Enable the attribute gl.enableVertexAttribArray(coord); /*=========Drawing the triangle===========*/ // Clear the canvas gl.clearColor(0.5, 0.5, 0.5, 0.9); // Enable the depth test gl.enable(gl.DEPTH_TEST); // Clear the color buffer bit gl.clear(gl.COLOR_BUFFER_BIT); // Set the view port gl.viewport(0,0,canvas.width,canvas.height); // Draw the triangle gl.drawElements(gl.TRIANGLES, indices.length, gl.UNSIGNED_SHORT,0); </script> </body> </html> If you run this example, it will produce the following output − 10 Lectures 1 hours Frahaan Hussain 28 Lectures 4 hours Frahaan Hussain Print Add Notes Bookmark this page
[ { "code": null, "e": 2288, "s": 2047, "text": "In the previous chapter (Chapter 11), we discussed how to draw three points using WebGL. In Chapter 5, we took sample application to demonstrate how to draw a triangle. In both the examples, we have drawn the primitives using only vertices." }, { "code": null, "e": 2471, "s": 2288, "text": "To draw more complex shapes/meshes, we pass the indices of a geometry too, along with the vertices, to the shaders. In this chapter, we will see how to draw a triangle using indices." }, { "code": null, "e": 2554, "s": 2471, "text": "The following steps are required to create a WebGL application to draw a triangle." }, { "code": null, "e": 2614, "s": 2554, "text": "Step 1 − Prepare the Canvas and Get WebGL Rendering Context" }, { "code": null, "e": 2693, "s": 2614, "text": "In this step, we obtain the WebGL Rendering context object using getContext()." }, { "code": null, "e": 2753, "s": 2693, "text": "Step 2 − Define the Geometry and Store it in Buffer Objects" }, { "code": null, "e": 2906, "s": 2753, "text": "Since we are drawing a triangle using indices, we have to pass the three vertices of the triangle, including the indices, and store them in the buffers." }, { "code": null, "e": 3002, "s": 2906, "text": "var vertices = [\n -0.5,0.5,0.0,\n -0.5,-0.5,0.0,\n 0.5,-0.5,0.0, \n];\n\t\nindices = [0,1,2]; \n" }, { "code": null, "e": 3050, "s": 3002, "text": "Step 3 − Create and Compile the Shader Programs" }, { "code": null, "e": 3201, "s": 3050, "text": "In this step, you need to write vertex shader and fragment shader programs, compile them, and create a combined program by linking these two programs." }, { "code": null, "e": 3339, "s": 3201, "text": "Vertex Shader − In the vertex shader of the program, we define the vector attribute to store 3D coordinates and assign it to gl_position." }, { "code": null, "e": 3477, "s": 3339, "text": "Vertex Shader − In the vertex shader of the program, we define the vector attribute to store 3D coordinates and assign it to gl_position." }, { "code": null, "e": 3612, "s": 3477, "text": "var vertCode =\n 'attribute vec3 coordinates;' +\n\t\n 'void main(void) {' +\n ' gl_Position = vec4(coordinates, 1.0);' +\n '}';\n" }, { "code": null, "e": 3720, "s": 3612, "text": "Fragment Shader − In the fragment shader, we simply assign the fragment color to the gl_FragColor variable." }, { "code": null, "e": 3828, "s": 3720, "text": "Fragment Shader − In the fragment shader, we simply assign the fragment color to the gl_FragColor variable." }, { "code": null, "e": 3916, "s": 3828, "text": "var fragCode = 'void main(void) {' +\n ' gl_FragColor = vec4(1, 0.5, 0.0, 1);' +\n'}';\n" }, { "code": null, "e": 3977, "s": 3916, "text": "Step 4 − Associate the Shader Programs to the Buffer Objects" }, { "code": null, "e": 4047, "s": 3977, "text": "In this step, we associate the buffer objects and the shader program." }, { "code": null, "e": 4084, "s": 4047, "text": "Step 5 − Drawing the Required Object" }, { "code": null, "e": 4279, "s": 4084, "text": "Since we are drawing a triangle using indices, we will use drawElements(). To this method, we have to pass the number of indices. The value of the indices.length signifies the number of indices." }, { "code": null, "e": 4348, "s": 4279, "text": "gl.drawElements(gl.TRIANGLES, indices.length, gl.UNSIGNED_SHORT,0);\n" }, { "code": null, "e": 4429, "s": 4348, "text": "The following program code shows how to draw a triangle in WebGL using indices −" }, { "code": null, "e": 8523, "s": 4429, "text": "<!doctype html>\n<html>\n <body>\n <canvas width = \"570\" height = \"570\" id = \"my_Canvas\"></canvas>\n\n <script>\n /*============== Creating a canvas ====================*/\n var canvas = document.getElementById('my_Canvas');\n gl = canvas.getContext('experimental-webgl');\n \n /*======== Defining and storing the geometry ===========*/\n\n var vertices = [\n -0.5,0.5,0.0,\n -0.5,-0.5,0.0,\n 0.5,-0.5,0.0, \n ];\n \n indices = [0,1,2];\n \n // Create an empty buffer object to store vertex buffer\n var vertex_buffer = gl.createBuffer();\n\n // Bind appropriate array buffer to it\n gl.bindBuffer(gl.ARRAY_BUFFER, vertex_buffer);\n \n // Pass the vertex data to the buffer\n gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);\n\n // Unbind the buffer\n gl.bindBuffer(gl.ARRAY_BUFFER, null);\n\n // Create an empty buffer object to store Index buffer\n var Index_Buffer = gl.createBuffer();\n\n // Bind appropriate array buffer to it\n gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, Index_Buffer);\n\n // Pass the vertex data to the buffer\n gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(indices), gl.STATIC_DRAW);\n \n // Unbind the buffer\n gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, null);\n\n /*================ Shaders ====================*/\n \n // Vertex shader source code\n var vertCode =\n 'attribute vec3 coordinates;' +\n\t\t\t\t\n 'void main(void) {' +\n ' gl_Position = vec4(coordinates, 1.0);' +\n '}';\n \n // Create a vertex shader object\n var vertShader = gl.createShader(gl.VERTEX_SHADER);\n\n // Attach vertex shader source code\n gl.shaderSource(vertShader, vertCode);\n\n // Compile the vertex shader\n gl.compileShader(vertShader);\n\n //fragment shader source code\n var fragCode =\n 'void main(void) {' +\n ' gl_FragColor = vec4(0.0, 0.0, 0.0, 0.1);' +\n '}';\n \n // Create fragment shader object\n var fragShader = gl.createShader(gl.FRAGMENT_SHADER);\n\n // Attach fragment shader source code\n gl.shaderSource(fragShader, fragCode); \n \n // Compile the fragmentt shader\n gl.compileShader(fragShader);\n\n // Create a shader program object to store\n // the combined shader program\n var shaderProgram = gl.createProgram();\n\n // Attach a vertex shader\n gl.attachShader(shaderProgram, vertShader);\n\n // Attach a fragment shader\n gl.attachShader(shaderProgram, fragShader);\n\n // Link both the programs\n gl.linkProgram(shaderProgram);\n\n // Use the combined shader program object\n gl.useProgram(shaderProgram);\n\n /*======= Associating shaders to buffer objects =======*/\n\n // Bind vertex buffer object\n gl.bindBuffer(gl.ARRAY_BUFFER, vertex_buffer);\n\n // Bind index buffer object\n gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, Index_Buffer);\n \n // Get the attribute location\n var coord = gl.getAttribLocation(shaderProgram, \"coordinates\");\n\n // Point an attribute to the currently bound VBO\n gl.vertexAttribPointer(coord, 3, gl.FLOAT, false, 0, 0); \n \n // Enable the attribute\n gl.enableVertexAttribArray(coord);\n\n /*=========Drawing the triangle===========*/\n\n // Clear the canvas\n gl.clearColor(0.5, 0.5, 0.5, 0.9);\n\n // Enable the depth test\n gl.enable(gl.DEPTH_TEST);\n\n // Clear the color buffer bit\n gl.clear(gl.COLOR_BUFFER_BIT);\n\n // Set the view port\n gl.viewport(0,0,canvas.width,canvas.height);\n\n // Draw the triangle\n gl.drawElements(gl.TRIANGLES, indices.length, gl.UNSIGNED_SHORT,0);\n </script>\n </body>\n</html>" }, { "code": null, "e": 8587, "s": 8523, "text": "If you run this example, it will produce the following output −" }, { "code": null, "e": 8620, "s": 8587, "text": "\n 10 Lectures \n 1 hours \n" }, { "code": null, "e": 8637, "s": 8620, "text": " Frahaan Hussain" }, { "code": null, "e": 8670, "s": 8637, "text": "\n 28 Lectures \n 4 hours \n" }, { "code": null, "e": 8687, "s": 8670, "text": " Frahaan Hussain" }, { "code": null, "e": 8694, "s": 8687, "text": " Print" }, { "code": null, "e": 8705, "s": 8694, "text": " Add Notes" } ]
Java Program to Get System IP Address in Windows and Linux Machine - GeeksforGeeks
19 Aug, 2021 IP Address: An Internet Protocol address is a numerical label assigned to each device connected to a computer network that uses the Internet Protocol for communication. Packages used: io (input-output): This package provides for system input and output through data streams, serialization, and the file system.net (network): This package provides the classes for implementing networking applications.util (utility): It contains the collection framework, legacy collection classes, event model, date and time facilities, internationalization, and miscellaneous utility classes io (input-output): This package provides for system input and output through data streams, serialization, and the file system. net (network): This package provides the classes for implementing networking applications. util (utility): It contains the collection framework, legacy collection classes, event model, date and time facilities, internationalization, and miscellaneous utility classes Methods Used: 1. getInetAddresses() Syntax: public Enumeration getInetAddresses() Return Type: It returns an Enumeration of InetAddress. 2. getInterfaceAddresses() Syntax: public List getInterfaceAddresses() Return Type: It returns a list of java.net.InterfaceAddress instances. Below is the implementation of the problem statement: Java // Java Program to Get System IP Address// in Windows and Linux Machineimport static java.lang.System.out; import java.io.*;import java.net.*;import java.util.*; public class gfg { public static void main(String args[]) // main method throws SocketException { // fetching network interface Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces(); for (NetworkInterface netint : Collections.list(nets)) displayInterfaceInformation(netint); } // Display Internet Information method static void displayInterfaceInformation(NetworkInterface netint) throws SocketException { out.printf("Display name: %s\n", netint.getDisplayName()); out.printf("Name: %s\n", netint.getName()); Enumeration<InetAddress> inetAddresses = netint.getInetAddresses(); // Output System IP for (InetAddress inetAddress : Collections.list(inetAddresses)) { out.printf("System IP: %s\n", inetAddress); } out.printf("\n"); }} Display name: eth0 Name: eth0 Display name: lo Name: lo System IP: /127.0.0.1 Output in Windows: Output in Linux: rajeev0719singh Picked Technical Scripter 2020 Java Java Programs Technical Scripter Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. 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 Convert a String to Character array in Java Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class How to Iterate HashMap in Java?
[ { "code": null, "e": 23583, "s": 23555, "text": "\n19 Aug, 2021" }, { "code": null, "e": 23753, "s": 23583, "text": "IP Address: An Internet Protocol address is a numerical label assigned to each device connected to a computer network that uses the Internet Protocol for communication. " }, { "code": null, "e": 23768, "s": 23753, "text": "Packages used:" }, { "code": null, "e": 24160, "s": 23768, "text": "io (input-output): This package provides for system input and output through data streams, serialization, and the file system.net (network): This package provides the classes for implementing networking applications.util (utility): It contains the collection framework, legacy collection classes, event model, date and time facilities, internationalization, and miscellaneous utility classes" }, { "code": null, "e": 24287, "s": 24160, "text": "io (input-output): This package provides for system input and output through data streams, serialization, and the file system." }, { "code": null, "e": 24378, "s": 24287, "text": "net (network): This package provides the classes for implementing networking applications." }, { "code": null, "e": 24554, "s": 24378, "text": "util (utility): It contains the collection framework, legacy collection classes, event model, date and time facilities, internationalization, and miscellaneous utility classes" }, { "code": null, "e": 24568, "s": 24554, "text": "Methods Used:" }, { "code": null, "e": 24590, "s": 24568, "text": "1. getInetAddresses()" }, { "code": null, "e": 24598, "s": 24590, "text": "Syntax:" }, { "code": null, "e": 24636, "s": 24598, "text": "public Enumeration getInetAddresses()" }, { "code": null, "e": 24691, "s": 24636, "text": "Return Type: It returns an Enumeration of InetAddress." }, { "code": null, "e": 24718, "s": 24691, "text": "2. getInterfaceAddresses()" }, { "code": null, "e": 24726, "s": 24718, "text": "Syntax:" }, { "code": null, "e": 24762, "s": 24726, "text": "public List getInterfaceAddresses()" }, { "code": null, "e": 24833, "s": 24762, "text": "Return Type: It returns a list of java.net.InterfaceAddress instances." }, { "code": null, "e": 24887, "s": 24833, "text": "Below is the implementation of the problem statement:" }, { "code": null, "e": 24892, "s": 24887, "text": "Java" }, { "code": "// Java Program to Get System IP Address// in Windows and Linux Machineimport static java.lang.System.out; import java.io.*;import java.net.*;import java.util.*; public class gfg { public static void main(String args[]) // main method throws SocketException { // fetching network interface Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces(); for (NetworkInterface netint : Collections.list(nets)) displayInterfaceInformation(netint); } // Display Internet Information method static void displayInterfaceInformation(NetworkInterface netint) throws SocketException { out.printf(\"Display name: %s\\n\", netint.getDisplayName()); out.printf(\"Name: %s\\n\", netint.getName()); Enumeration<InetAddress> inetAddresses = netint.getInetAddresses(); // Output System IP for (InetAddress inetAddress : Collections.list(inetAddresses)) { out.printf(\"System IP: %s\\n\", inetAddress); } out.printf(\"\\n\"); }}", "e": 26003, "s": 24892, "text": null }, { "code": null, "e": 26082, "s": 26003, "text": "Display name: eth0\nName: eth0\n\nDisplay name: lo\nName: lo\nSystem IP: /127.0.0.1" }, { "code": null, "e": 26102, "s": 26082, "text": "Output in Windows: " }, { "code": null, "e": 26120, "s": 26102, "text": "Output in Linux: " }, { "code": null, "e": 26138, "s": 26122, "text": "rajeev0719singh" }, { "code": null, "e": 26145, "s": 26138, "text": "Picked" }, { "code": null, "e": 26169, "s": 26145, "text": "Technical Scripter 2020" }, { "code": null, "e": 26174, "s": 26169, "text": "Java" }, { "code": null, "e": 26188, "s": 26174, "text": "Java Programs" }, { "code": null, "e": 26207, "s": 26188, "text": "Technical Scripter" }, { "code": null, "e": 26212, "s": 26207, "text": "Java" }, { "code": null, "e": 26310, "s": 26212, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26319, "s": 26310, "text": "Comments" }, { "code": null, "e": 26332, "s": 26319, "text": "Old Comments" }, { "code": null, "e": 26362, "s": 26332, "text": "Functional Interfaces in Java" }, { "code": null, "e": 26377, "s": 26362, "text": "Stream In Java" }, { "code": null, "e": 26398, "s": 26377, "text": "Constructors in Java" }, { "code": null, "e": 26444, "s": 26398, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 26463, "s": 26444, "text": "Exceptions in Java" }, { "code": null, "e": 26507, "s": 26463, "text": "Convert a String to Character array in Java" }, { "code": null, "e": 26533, "s": 26507, "text": "Java Programming Examples" }, { "code": null, "e": 26567, "s": 26533, "text": "Convert Double to Integer in Java" }, { "code": null, "e": 26614, "s": 26567, "text": "Implementing a Linked List in Java using Class" } ]
Simplest way to detect keypresses in JavaScript?
The easiest way to detect keypresses in JavaScript, use the onKeyPress event handler − document.onkeypress The key press is matched with the keyCode property, which returns the Unicode character code of the key that triggered the onkeypress event. Live Demo <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initialscale= 1.0"> <title>Document</title> </head> <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> <body> <script> document.onkeypress = function (eventKeyName) { eventKeyName = eventKeyName || window.event; if(eventKeyName.keyCode==13){ console.log('You have pressed enter key'); } else { alert(String.fromCharCode(eventKeyName.keyCode)) } }; </script> </body> </html> To run the above program, save the file name “anyName.html(index.html)” and right click on the file. Select the option “Open with Live Server” in VS Code editor. This will produce the following output − Case 1 − On pressing ENTER key, you will get the following output on console. Case 2 − When you press any other key except ENTER, example letter g, then the same would be visible on console −
[ { "code": null, "e": 1149, "s": 1062, "text": "The easiest way to detect keypresses in JavaScript, use the onKeyPress event handler −" }, { "code": null, "e": 1169, "s": 1149, "text": "document.onkeypress" }, { "code": null, "e": 1310, "s": 1169, "text": "The key press is matched with the keyCode property, which returns the Unicode character code\nof the key that triggered the onkeypress event." }, { "code": null, "e": 1321, "s": 1310, "text": " Live Demo" }, { "code": null, "e": 2021, "s": 1321, "text": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\">\n<meta name=\"viewport\" content=\"width=device-width, initialscale=\n1.0\">\n<title>Document</title>\n</head>\n<link rel=\"stylesheet\"\nhref=\"//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css\">\n<script src=\"https://code.jquery.com/jquery-1.12.4.js\"></script>\n<script src=\"https://code.jquery.com/ui/1.12.1/jquery-ui.js\"></script>\n<body>\n<script>\n document.onkeypress = function (eventKeyName) {\n eventKeyName = eventKeyName || window.event;\n if(eventKeyName.keyCode==13){\n console.log('You have pressed enter key');\n } else {\n alert(String.fromCharCode(eventKeyName.keyCode))\n }\n};\n</script>\n</body>\n</html>" }, { "code": null, "e": 2183, "s": 2021, "text": "To run the above program, save the file name “anyName.html(index.html)” and right click on the\nfile. Select the option “Open with Live Server” in VS Code editor." }, { "code": null, "e": 2224, "s": 2183, "text": "This will produce the following output −" }, { "code": null, "e": 2302, "s": 2224, "text": "Case 1 − On pressing ENTER key, you will get the following output on console." }, { "code": null, "e": 2416, "s": 2302, "text": "Case 2 − When you press any other key except ENTER, example letter g, then the same would be visible on console −" } ]
Vertically stack pills with Bootstrap
Use the .nav-stacked class in Bootstrap to vertically stack pills: You can try to run the following code to implement the .nav-stacked class − Live Demo <!DOCTYPE html> <html> <head> <title>Bootstrap Example</title> <link rel = "stylesheet" href = "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src = "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> </head> <body> <div class = "container"> <h2>Database</h2> <p>The following are the database technologies:</p> <ul class = "nav nav-pills nav-stacked" role = "tablist"> <li class = "active"><a href = "#">DB2</a></li> <li><a href = "#">MySQL</a></li> <li><a href = "#">SQL</a></li> <li><a href = "#">CouchDB</a></li> </ul> </div> </body> </html>
[ { "code": null, "e": 1129, "s": 1062, "text": "Use the .nav-stacked class in Bootstrap to vertically stack pills:" }, { "code": null, "e": 1205, "s": 1129, "text": "You can try to run the following code to implement the .nav-stacked class −" }, { "code": null, "e": 1215, "s": 1205, "text": "Live Demo" }, { "code": null, "e": 2045, "s": 1215, "text": "<!DOCTYPE html>\n<html>\n <head>\n <title>Bootstrap Example</title>\n <link rel = \"stylesheet\" href = \"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css\">\n <script src = \"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n <script src = \"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js\"></script>\n </head>\n <body>\n <div class = \"container\">\n <h2>Database</h2>\n <p>The following are the database technologies:</p>\n <ul class = \"nav nav-pills nav-stacked\" role = \"tablist\">\n <li class = \"active\"><a href = \"#\">DB2</a></li>\n <li><a href = \"#\">MySQL</a></li>\n <li><a href = \"#\">SQL</a></li>\n <li><a href = \"#\">CouchDB</a></li>\n </ul>\n </div>\n </body>\n</html>" } ]
Clustering Algorithms - K-means Algorithm
K-means clustering algorithm computes the centroids and iterates until we it finds optimal centroid. It assumes that the number of clusters are already known. It is also called flat clustering algorithm. The number of clusters identified from data by algorithm is represented by ‘K’ in K-means. In this algorithm, the data points are assigned to a cluster in such a manner that the sum of the squared distance between the data points and centroid would be minimum. It is to be understood that less variation within the clusters will lead to more similar data points within same cluster. We can understand the working of K-Means clustering algorithm with the help of following steps − Step 1 − First, we need to specify the number of clusters, K, need to be generated by this algorithm. Step 1 − First, we need to specify the number of clusters, K, need to be generated by this algorithm. Step 2 − Next, randomly select K data points and assign each data point to a cluster. In simple words, classify the data based on the number of data points. Step 2 − Next, randomly select K data points and assign each data point to a cluster. In simple words, classify the data based on the number of data points. Step 3 − Now it will compute the cluster centroids. Step 3 − Now it will compute the cluster centroids. Step 4 − Next, keep iterating the following until we find optimal centroid which is the assignment of data points to the clusters that are not changing any more − Step 4 − Next, keep iterating the following until we find optimal centroid which is the assignment of data points to the clusters that are not changing any more − 4.1 − First, the sum of squared distance between data points and centroids would be computed. 4.2 − Now, we have to assign each data point to the cluster that is closer than other cluster (centroid). 4.3 − At last compute the centroids for the clusters by taking the average of all data points of that cluster. K-means follows Expectation-Maximization approach to solve the problem. The Expectation-step is used for assigning the data points to the closest cluster and the Maximization-step is used for computing the centroid of each cluster. While working with K-means algorithm we need to take care of the following things − While working with clustering algorithms including K-Means, it is recommended to standardize the data because such algorithms use distance-based measurement to determine the similarity between data points. While working with clustering algorithms including K-Means, it is recommended to standardize the data because such algorithms use distance-based measurement to determine the similarity between data points. Due to the iterative nature of K-Means and random initialization of centroids, K-Means may stick in a local optimum and may not converge to global optimum. That is why it is recommended to use different initializations of centroids. Due to the iterative nature of K-Means and random initialization of centroids, K-Means may stick in a local optimum and may not converge to global optimum. That is why it is recommended to use different initializations of centroids. The following two examples of implementing K-Means clustering algorithm will help us in its better understanding − It is a simple example to understand how k-means works. In this example, we are going to first generate 2D dataset containing 4 different blobs and after that will apply k-means algorithm to see the result. First, we will start by importing the necessary packages − %matplotlib inline import matplotlib.pyplot as plt import seaborn as sns; sns.set() import numpy as np from sklearn.cluster import KMeans The following code will generate the 2D, containing four blobs − from sklearn.datasets.samples_generator import make_blobs X, y_true = make_blobs(n_samples=400, centers=4, cluster_std=0.60, random_state=0) Next, the following code will help us to visualize the dataset − plt.scatter(X[:, 0], X[:, 1], s=20); plt.show() Next, make an object of KMeans along with providing number of clusters, train the model and do the prediction as follows − kmeans = KMeans(n_clusters=4) kmeans.fit(X) y_kmeans = kmeans.predict(X) Now, with the help of following code we can plot and visualize the cluster’s centers picked by k-means Python estimator − plt.scatter(X[:, 0], X[:, 1], c=y_kmeans, s=20, cmap='summer') centers = kmeans.cluster_centers_ plt.scatter(centers[:, 0], centers[:, 1], c='blue', s=100, alpha=0.9); plt.show() Let us move to another example in which we are going to apply K-means clustering on simple digits dataset. K-means will try to identify similar digits without using the original label information. First, we will start by importing the necessary packages − %matplotlib inline import matplotlib.pyplot as plt import seaborn as sns; sns.set() import numpy as np from sklearn.cluster import KMeans Next, load the digit dataset from sklearn and make an object of it. We can also find number of rows and columns in this dataset as follows − from sklearn.datasets import load_digits digits = load_digits() digits.data.shape (1797, 64) The above output shows that this dataset is having 1797 samples with 64 features. We can perform the clustering as we did in Example 1 above − kmeans = KMeans(n_clusters=10, random_state=0) clusters = kmeans.fit_predict(digits.data) kmeans.cluster_centers_.shape (10, 64) The above output shows that K-means created 10 clusters with 64 features. fig, ax = plt.subplots(2, 5, figsize=(8, 3)) centers = kmeans.cluster_centers_.reshape(10, 8, 8) for axi, center in zip(ax.flat, centers): axi.set(xticks=[], yticks=[]) axi.imshow(center, interpolation='nearest', cmap=plt.cm.binary) As output, we will get following image showing clusters centers learned by k-means. The following lines of code will match the learned cluster labels with the true labels found in them − from scipy.stats import mode labels = np.zeros_like(clusters) for i in range(10): mask = (clusters == i) labels[mask] = mode(digits.target[mask])[0] Next, we can check the accuracy as follows − from sklearn.metrics import accuracy_score accuracy_score(digits.target, labels) 0.7935447968836951 The above output shows that the accuracy is around 80%. The following are some advantages of K-Means clustering algorithms − It is very easy to understand and implement. It is very easy to understand and implement. If we have large number of variables then, K-means would be faster than Hierarchical clustering. If we have large number of variables then, K-means would be faster than Hierarchical clustering. On re-computation of centroids, an instance can change the cluster. On re-computation of centroids, an instance can change the cluster. Tighter clusters are formed with K-means as compared to Hierarchical clustering. Tighter clusters are formed with K-means as compared to Hierarchical clustering. The following are some disadvantages of K-Means clustering algorithms − It is a bit difficult to predict the number of clusters i.e. the value of k. It is a bit difficult to predict the number of clusters i.e. the value of k. Output is strongly impacted by initial inputs like number of clusters (value of k). Output is strongly impacted by initial inputs like number of clusters (value of k). Order of data will have strong impact on the final output. Order of data will have strong impact on the final output. It is very sensitive to rescaling. If we will rescale our data by means of normalization or standardization, then the output will completely change.final output. It is very sensitive to rescaling. If we will rescale our data by means of normalization or standardization, then the output will completely change.final output. It is not good in doing clustering job if the clusters have a complicated geometric shape. It is not good in doing clustering job if the clusters have a complicated geometric shape. The main goals of cluster analysis are − To get a meaningful intuition from the data we are working with. To get a meaningful intuition from the data we are working with. Cluster-then-predict where different models will be built for different subgroups. Cluster-then-predict where different models will be built for different subgroups. To fulfill the above-mentioned goals, K-means clustering is performing well enough. It can be used in following applications − Market segmentation Market segmentation Document Clustering Document Clustering Image segmentation Image segmentation Image compression Image compression Customer segmentation Customer segmentation Analyzing the trend on dynamic data Analyzing the trend on dynamic data 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": 2599, "s": 2304, "text": "K-means clustering algorithm computes the centroids and iterates until we it finds optimal centroid. It assumes that the number of clusters are already known. It is also called flat clustering algorithm. The number of clusters identified from data by algorithm is represented by ‘K’ in K-means." }, { "code": null, "e": 2891, "s": 2599, "text": "In this algorithm, the data points are assigned to a cluster in such a manner that the sum of the squared distance between the data points and centroid would be minimum. It is to be understood that less variation within the clusters will lead to more similar data points within same cluster." }, { "code": null, "e": 2988, "s": 2891, "text": "We can understand the working of K-Means clustering algorithm with the help of following steps −" }, { "code": null, "e": 3090, "s": 2988, "text": "Step 1 − First, we need to specify the number of clusters, K, need to be generated by this algorithm." }, { "code": null, "e": 3192, "s": 3090, "text": "Step 1 − First, we need to specify the number of clusters, K, need to be generated by this algorithm." }, { "code": null, "e": 3349, "s": 3192, "text": "Step 2 − Next, randomly select K data points and assign each data point to a cluster. In simple words, classify the data based on the number of data points." }, { "code": null, "e": 3506, "s": 3349, "text": "Step 2 − Next, randomly select K data points and assign each data point to a cluster. In simple words, classify the data based on the number of data points." }, { "code": null, "e": 3558, "s": 3506, "text": "Step 3 − Now it will compute the cluster centroids." }, { "code": null, "e": 3610, "s": 3558, "text": "Step 3 − Now it will compute the cluster centroids." }, { "code": null, "e": 3773, "s": 3610, "text": "Step 4 − Next, keep iterating the following until we find optimal centroid which is the assignment of data points to the clusters that are not changing any more −" }, { "code": null, "e": 3936, "s": 3773, "text": "Step 4 − Next, keep iterating the following until we find optimal centroid which is the assignment of data points to the clusters that are not changing any more −" }, { "code": null, "e": 4030, "s": 3936, "text": "4.1 − First, the sum of squared distance between data points and centroids would be computed." }, { "code": null, "e": 4136, "s": 4030, "text": "4.2 − Now, we have to assign each data point to the cluster that is closer than other cluster (centroid)." }, { "code": null, "e": 4247, "s": 4136, "text": "4.3 − At last compute the centroids for the clusters by taking the average of all data points of that cluster." }, { "code": null, "e": 4479, "s": 4247, "text": "K-means follows Expectation-Maximization approach to solve the problem. The Expectation-step is used for assigning the data points to the closest cluster and the Maximization-step is used for computing the centroid of each cluster." }, { "code": null, "e": 4563, "s": 4479, "text": "While working with K-means algorithm we need to take care of the following things −" }, { "code": null, "e": 4769, "s": 4563, "text": "While working with clustering algorithms including K-Means, it is recommended to standardize the data because such algorithms use distance-based measurement to determine the similarity between data points." }, { "code": null, "e": 4975, "s": 4769, "text": "While working with clustering algorithms including K-Means, it is recommended to standardize the data because such algorithms use distance-based measurement to determine the similarity between data points." }, { "code": null, "e": 5208, "s": 4975, "text": "Due to the iterative nature of K-Means and random initialization of centroids, K-Means may stick in a local optimum and may not converge to global optimum. That is why it is recommended to use different initializations of centroids." }, { "code": null, "e": 5441, "s": 5208, "text": "Due to the iterative nature of K-Means and random initialization of centroids, K-Means may stick in a local optimum and may not converge to global optimum. That is why it is recommended to use different initializations of centroids." }, { "code": null, "e": 5556, "s": 5441, "text": "The following two examples of implementing K-Means clustering algorithm will help us in its better understanding −" }, { "code": null, "e": 5763, "s": 5556, "text": "It is a simple example to understand how k-means works. In this example, we are going to first generate 2D dataset containing 4 different blobs and after that will apply k-means algorithm to see the result." }, { "code": null, "e": 5822, "s": 5763, "text": "First, we will start by importing the necessary packages −" }, { "code": null, "e": 5961, "s": 5822, "text": "%matplotlib inline\nimport matplotlib.pyplot as plt\nimport seaborn as sns; sns.set()\nimport numpy as np\nfrom sklearn.cluster import KMeans\n" }, { "code": null, "e": 6026, "s": 5961, "text": "The following code will generate the 2D, containing four blobs −" }, { "code": null, "e": 6168, "s": 6026, "text": "from sklearn.datasets.samples_generator import make_blobs\nX, y_true = make_blobs(n_samples=400, centers=4, cluster_std=0.60, random_state=0)\n" }, { "code": null, "e": 6233, "s": 6168, "text": "Next, the following code will help us to visualize the dataset −" }, { "code": null, "e": 6282, "s": 6233, "text": "plt.scatter(X[:, 0], X[:, 1], s=20);\nplt.show()\n" }, { "code": null, "e": 6405, "s": 6282, "text": "Next, make an object of KMeans along with providing number of clusters, train the model and do the prediction as follows −" }, { "code": null, "e": 6479, "s": 6405, "text": "kmeans = KMeans(n_clusters=4)\nkmeans.fit(X)\ny_kmeans = kmeans.predict(X)\n" }, { "code": null, "e": 6601, "s": 6479, "text": "Now, with the help of following code we can plot and visualize the cluster’s centers picked by k-means Python estimator −" }, { "code": null, "e": 6780, "s": 6601, "text": "plt.scatter(X[:, 0], X[:, 1], c=y_kmeans, s=20, cmap='summer')\ncenters = kmeans.cluster_centers_\nplt.scatter(centers[:, 0], centers[:, 1], c='blue', s=100, alpha=0.9);\nplt.show()" }, { "code": null, "e": 6977, "s": 6780, "text": "Let us move to another example in which we are going to apply K-means clustering on simple digits dataset. K-means will try to identify similar digits without using the original label information." }, { "code": null, "e": 7036, "s": 6977, "text": "First, we will start by importing the necessary packages −" }, { "code": null, "e": 7175, "s": 7036, "text": "%matplotlib inline\nimport matplotlib.pyplot as plt\nimport seaborn as sns; sns.set()\nimport numpy as np\nfrom sklearn.cluster import KMeans\n" }, { "code": null, "e": 7316, "s": 7175, "text": "Next, load the digit dataset from sklearn and make an object of it. We can also find number of rows and columns in this dataset as follows −" }, { "code": null, "e": 7399, "s": 7316, "text": "from sklearn.datasets import load_digits\ndigits = load_digits()\ndigits.data.shape\n" }, { "code": null, "e": 7411, "s": 7399, "text": "(1797, 64)\n" }, { "code": null, "e": 7493, "s": 7411, "text": "The above output shows that this dataset is having 1797 samples with 64 features." }, { "code": null, "e": 7554, "s": 7493, "text": "We can perform the clustering as we did in Example 1 above −" }, { "code": null, "e": 7675, "s": 7554, "text": "kmeans = KMeans(n_clusters=10, random_state=0)\nclusters = kmeans.fit_predict(digits.data)\nkmeans.cluster_centers_.shape\n" }, { "code": null, "e": 7685, "s": 7675, "text": "(10, 64)\n" }, { "code": null, "e": 7759, "s": 7685, "text": "The above output shows that K-means created 10 clusters with 64 features." }, { "code": null, "e": 7999, "s": 7759, "text": "fig, ax = plt.subplots(2, 5, figsize=(8, 3))\ncenters = kmeans.cluster_centers_.reshape(10, 8, 8)\nfor axi, center in zip(ax.flat, centers):\n axi.set(xticks=[], yticks=[])\n axi.imshow(center, interpolation='nearest', cmap=plt.cm.binary)\n" }, { "code": null, "e": 8083, "s": 7999, "text": "As output, we will get following image showing clusters centers learned by k-means." }, { "code": null, "e": 8186, "s": 8083, "text": "The following lines of code will match the learned cluster labels with the true labels found in them −" }, { "code": null, "e": 8342, "s": 8186, "text": "from scipy.stats import mode\nlabels = np.zeros_like(clusters)\nfor i in range(10):\n mask = (clusters == i)\n labels[mask] = mode(digits.target[mask])[0]\n" }, { "code": null, "e": 8387, "s": 8342, "text": "Next, we can check the accuracy as follows −" }, { "code": null, "e": 8469, "s": 8387, "text": "from sklearn.metrics import accuracy_score\naccuracy_score(digits.target, labels)\n" }, { "code": null, "e": 8489, "s": 8469, "text": "0.7935447968836951\n" }, { "code": null, "e": 8545, "s": 8489, "text": "The above output shows that the accuracy is around 80%." }, { "code": null, "e": 8614, "s": 8545, "text": "The following are some advantages of K-Means clustering algorithms −" }, { "code": null, "e": 8659, "s": 8614, "text": "It is very easy to understand and implement." }, { "code": null, "e": 8704, "s": 8659, "text": "It is very easy to understand and implement." }, { "code": null, "e": 8801, "s": 8704, "text": "If we have large number of variables then, K-means would be faster than Hierarchical clustering." }, { "code": null, "e": 8898, "s": 8801, "text": "If we have large number of variables then, K-means would be faster than Hierarchical clustering." }, { "code": null, "e": 8966, "s": 8898, "text": "On re-computation of centroids, an instance can change the cluster." }, { "code": null, "e": 9034, "s": 8966, "text": "On re-computation of centroids, an instance can change the cluster." }, { "code": null, "e": 9115, "s": 9034, "text": "Tighter clusters are formed with K-means as compared to Hierarchical clustering." }, { "code": null, "e": 9196, "s": 9115, "text": "Tighter clusters are formed with K-means as compared to Hierarchical clustering." }, { "code": null, "e": 9268, "s": 9196, "text": "The following are some disadvantages of K-Means clustering algorithms −" }, { "code": null, "e": 9345, "s": 9268, "text": "It is a bit difficult to predict the number of clusters i.e. the value of k." }, { "code": null, "e": 9422, "s": 9345, "text": "It is a bit difficult to predict the number of clusters i.e. the value of k." }, { "code": null, "e": 9506, "s": 9422, "text": "Output is strongly impacted by initial inputs like number of clusters (value of k)." }, { "code": null, "e": 9590, "s": 9506, "text": "Output is strongly impacted by initial inputs like number of clusters (value of k)." }, { "code": null, "e": 9649, "s": 9590, "text": "Order of data will have strong impact on the final output." }, { "code": null, "e": 9708, "s": 9649, "text": "Order of data will have strong impact on the final output." }, { "code": null, "e": 9870, "s": 9708, "text": "It is very sensitive to rescaling. If we will rescale our data by means of normalization or standardization, then the output will completely change.final output." }, { "code": null, "e": 10032, "s": 9870, "text": "It is very sensitive to rescaling. If we will rescale our data by means of normalization or standardization, then the output will completely change.final output." }, { "code": null, "e": 10123, "s": 10032, "text": "It is not good in doing clustering job if the clusters have a complicated geometric shape." }, { "code": null, "e": 10214, "s": 10123, "text": "It is not good in doing clustering job if the clusters have a complicated geometric shape." }, { "code": null, "e": 10255, "s": 10214, "text": "The main goals of cluster analysis are −" }, { "code": null, "e": 10320, "s": 10255, "text": "To get a meaningful intuition from the data we are working with." }, { "code": null, "e": 10385, "s": 10320, "text": "To get a meaningful intuition from the data we are working with." }, { "code": null, "e": 10468, "s": 10385, "text": "Cluster-then-predict where different models will be built for different subgroups." }, { "code": null, "e": 10551, "s": 10468, "text": "Cluster-then-predict where different models will be built for different subgroups." }, { "code": null, "e": 10678, "s": 10551, "text": "To fulfill the above-mentioned goals, K-means clustering is performing well enough. It can be used in following applications −" }, { "code": null, "e": 10698, "s": 10678, "text": "Market segmentation" }, { "code": null, "e": 10718, "s": 10698, "text": "Market segmentation" }, { "code": null, "e": 10738, "s": 10718, "text": "Document Clustering" }, { "code": null, "e": 10758, "s": 10738, "text": "Document Clustering" }, { "code": null, "e": 10777, "s": 10758, "text": "Image segmentation" }, { "code": null, "e": 10796, "s": 10777, "text": "Image segmentation" }, { "code": null, "e": 10814, "s": 10796, "text": "Image compression" }, { "code": null, "e": 10832, "s": 10814, "text": "Image compression" }, { "code": null, "e": 10854, "s": 10832, "text": "Customer segmentation" }, { "code": null, "e": 10876, "s": 10854, "text": "Customer segmentation" }, { "code": null, "e": 10912, "s": 10876, "text": "Analyzing the trend on dynamic data" }, { "code": null, "e": 10948, "s": 10912, "text": "Analyzing the trend on dynamic data" }, { "code": null, "e": 10985, "s": 10948, "text": "\n 168 Lectures \n 13.5 hours \n" }, { "code": null, "e": 11008, "s": 10985, "text": " Er. Himanshu Vasishta" }, { "code": null, "e": 11044, "s": 11008, "text": "\n 64 Lectures \n 10.5 hours \n" }, { "code": null, "e": 11072, "s": 11044, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 11106, "s": 11072, "text": "\n 91 Lectures \n 10 hours \n" }, { "code": null, "e": 11123, "s": 11106, "text": " Abhilash Nelson" }, { "code": null, "e": 11156, "s": 11123, "text": "\n 54 Lectures \n 6 hours \n" }, { "code": null, "e": 11178, "s": 11156, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 11211, "s": 11178, "text": "\n 49 Lectures \n 5 hours \n" }, { "code": null, "e": 11233, "s": 11211, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 11266, "s": 11233, "text": "\n 35 Lectures \n 4 hours \n" }, { "code": null, "e": 11288, "s": 11266, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 11295, "s": 11288, "text": " Print" }, { "code": null, "e": 11306, "s": 11295, "text": " Add Notes" } ]
Difference between 1NF and 3NF in DBMS - GeeksforGeeks
19 Oct, 2020 1. First Normal Form (1NF) :An entity that does not have any repeating columns or data groups can be termed as the First Norm. 1NF is the First normal form, which provides the minimum set of requirements for normalizing a relational database. A table that complies with 1NF assures that it actually represents a relation (i.e. it does not contain any records that are repeating), but there is no universally accepted definition for 1NF. One important property is that a table that comply with 1NF could not contain any attributes that are relational valued i.e. all the attributes should have atomic values. Some rules to be followed are : There should be a unique name to be specified for each attribute within the table. It should not contain any composite attributes. Example : As this relation does not contain any composite or multi-valued attributes then this relation is in 1NF. 2. Third Normal Form (3NF) :It mean a table is considered in third normal if the table/entity is already in the second normal form and the columns of the table/entity are non-transitively dependent on the primary key. If a transitive dependency exists, we remove the transitively dependent attribute(s) from the relation by placing the attribute(s) in a new relation along with a copy of the determinant Most of the 3NF tables are free of insertion, update, and deletion anomalies. 3NF is used to reduce data duplication and to attain data integrity. Example : Consider relation R (E, F, G, H, I) E -> FG, GH -> I, F -> H, I -> E All possible candidate keys in above relation are {E, I, GH, FG} All attribute are on right sides of all functional dependencies are prime. Difference between 1NF and 3NF : DBMS GATE CS DBMS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Types of Functional dependencies in DBMS Introduction of Relational Algebra in DBMS What is Temporary Table in SQL? Two Phase Locking Protocol KDD Process in Data Mining Layers of OSI Model TCP/IP Model Page Replacement Algorithms in Operating Systems Types of Operating Systems Differences between TCP and UDP
[ { "code": null, "e": 24330, "s": 24302, "text": "\n19 Oct, 2020" }, { "code": null, "e": 24938, "s": 24330, "text": "1. First Normal Form (1NF) :An entity that does not have any repeating columns or data groups can be termed as the First Norm. 1NF is the First normal form, which provides the minimum set of requirements for normalizing a relational database. A table that complies with 1NF assures that it actually represents a relation (i.e. it does not contain any records that are repeating), but there is no universally accepted definition for 1NF. One important property is that a table that comply with 1NF could not contain any attributes that are relational valued i.e. all the attributes should have atomic values." }, { "code": null, "e": 24970, "s": 24938, "text": "Some rules to be followed are :" }, { "code": null, "e": 25053, "s": 24970, "text": "There should be a unique name to be specified for each attribute within the table." }, { "code": null, "e": 25101, "s": 25053, "text": "It should not contain any composite attributes." }, { "code": null, "e": 25111, "s": 25101, "text": "Example :" }, { "code": null, "e": 25216, "s": 25111, "text": "As this relation does not contain any composite or multi-valued attributes then this relation is in 1NF." }, { "code": null, "e": 25434, "s": 25216, "text": "2. Third Normal Form (3NF) :It mean a table is considered in third normal if the table/entity is already in the second normal form and the columns of the table/entity are non-transitively dependent on the primary key." }, { "code": null, "e": 25767, "s": 25434, "text": "If a transitive dependency exists, we remove the transitively dependent attribute(s) from the relation by placing the attribute(s) in a new relation along with a copy of the determinant Most of the 3NF tables are free of insertion, update, and deletion anomalies. 3NF is used to reduce data duplication and to attain data integrity." }, { "code": null, "e": 25813, "s": 25767, "text": "Example : Consider relation R (E, F, G, H, I)" }, { "code": null, "e": 25851, "s": 25813, "text": "E -> FG, \nGH -> I, \nF -> H, \nI -> E \n" }, { "code": null, "e": 25991, "s": 25851, "text": "All possible candidate keys in above relation are {E, I, GH, FG} All attribute are on right sides of all functional dependencies are prime." }, { "code": null, "e": 26024, "s": 25991, "text": "Difference between 1NF and 3NF :" }, { "code": null, "e": 26029, "s": 26024, "text": "DBMS" }, { "code": null, "e": 26037, "s": 26029, "text": "GATE CS" }, { "code": null, "e": 26042, "s": 26037, "text": "DBMS" }, { "code": null, "e": 26140, "s": 26042, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26181, "s": 26140, "text": "Types of Functional dependencies in DBMS" }, { "code": null, "e": 26224, "s": 26181, "text": "Introduction of Relational Algebra in DBMS" }, { "code": null, "e": 26256, "s": 26224, "text": "What is Temporary Table in SQL?" }, { "code": null, "e": 26283, "s": 26256, "text": "Two Phase Locking Protocol" }, { "code": null, "e": 26310, "s": 26283, "text": "KDD Process in Data Mining" }, { "code": null, "e": 26330, "s": 26310, "text": "Layers of OSI Model" }, { "code": null, "e": 26343, "s": 26330, "text": "TCP/IP Model" }, { "code": null, "e": 26392, "s": 26343, "text": "Page Replacement Algorithms in Operating Systems" }, { "code": null, "e": 26419, "s": 26392, "text": "Types of Operating Systems" } ]
C Program for Iterative Quick Sort - GeeksforGeeks
04 Dec, 2018 // An iterative implementation of quick sort#include <stdio.h> // A utility function to swap two elementsvoid swap(int* a, int* b){ int t = *a; *a = *b; *b = t;} /* This function is same in both iterative and recursive*/int partition(int arr[], int l, int h){ int x = arr[h]; int i = (l - 1); for (int j = l; j <= h - 1; j++) { if (arr[j] <= x) { i++; swap(&arr[i], &arr[j]); } } swap(&arr[i + 1], &arr[h]); return (i + 1);} /* A[] --> Array to be sorted, l --> Starting index, h --> Ending index */void quickSortIterative(int arr[], int l, int h){ // Create an auxiliary stack int stack[h - l + 1]; // initialize top of stack int top = -1; // push initial values of l and h to stack stack[++top] = l; stack[++top] = h; // Keep popping from stack while is not empty while (top >= 0) { // Pop h and l h = stack[top--]; l = stack[top--]; // Set pivot element at its correct position // in sorted array int p = partition(arr, l, h); // If there are elements on left side of pivot, // then push left side to stack if (p - 1 > l) { stack[++top] = l; stack[++top] = p - 1; } // If there are elements on right side of pivot, // then push right side to stack if (p + 1 < h) { stack[++top] = p + 1; stack[++top] = h; } }} // A utility function to print contents of arrvoid printArr(int arr[], int n){ int i; for (i = 0; i < n; ++i) printf("%d ", arr[i]);} // Driver program to test above functionsint main(){ int arr[] = { 4, 3, 5, 2, 1, 3, 2, 3 }; int n = sizeof(arr) / sizeof(*arr); quickSortIterative(arr, 0, n - 1); printArr(arr, n); return 0;} 1 2 2 3 3 3 4 5 The above mentioned optimizations for recursive quick sort can also be applied to iterative version. 1) Partition process is same in both recursive and iterative. The same techniques to choose optimal pivot can also be applied to iterative version. 2) To reduce the stack size, first push the indexes of smaller half. 3) Use insertion sort when the size reduces below a experimentally calculated threshold. Please refer complete article on Iterative Quick Sort for more details! C Programs Sorting Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C Program to read contents of Whole File Producer Consumer Problem in C C program to find the length of a string Exit codes in C/C++ with Examples Regular expressions in C
[ { "code": null, "e": 25008, "s": 24980, "text": "\n04 Dec, 2018" }, { "code": "// An iterative implementation of quick sort#include <stdio.h> // A utility function to swap two elementsvoid swap(int* a, int* b){ int t = *a; *a = *b; *b = t;} /* This function is same in both iterative and recursive*/int partition(int arr[], int l, int h){ int x = arr[h]; int i = (l - 1); for (int j = l; j <= h - 1; j++) { if (arr[j] <= x) { i++; swap(&arr[i], &arr[j]); } } swap(&arr[i + 1], &arr[h]); return (i + 1);} /* A[] --> Array to be sorted, l --> Starting index, h --> Ending index */void quickSortIterative(int arr[], int l, int h){ // Create an auxiliary stack int stack[h - l + 1]; // initialize top of stack int top = -1; // push initial values of l and h to stack stack[++top] = l; stack[++top] = h; // Keep popping from stack while is not empty while (top >= 0) { // Pop h and l h = stack[top--]; l = stack[top--]; // Set pivot element at its correct position // in sorted array int p = partition(arr, l, h); // If there are elements on left side of pivot, // then push left side to stack if (p - 1 > l) { stack[++top] = l; stack[++top] = p - 1; } // If there are elements on right side of pivot, // then push right side to stack if (p + 1 < h) { stack[++top] = p + 1; stack[++top] = h; } }} // A utility function to print contents of arrvoid printArr(int arr[], int n){ int i; for (i = 0; i < n; ++i) printf(\"%d \", arr[i]);} // Driver program to test above functionsint main(){ int arr[] = { 4, 3, 5, 2, 1, 3, 2, 3 }; int n = sizeof(arr) / sizeof(*arr); quickSortIterative(arr, 0, n - 1); printArr(arr, n); return 0;}", "e": 26838, "s": 25008, "text": null }, { "code": null, "e": 26855, "s": 26838, "text": "1 2 2 3 3 3 4 5\n" }, { "code": null, "e": 26956, "s": 26855, "text": "The above mentioned optimizations for recursive quick sort can also be applied to iterative version." }, { "code": null, "e": 27104, "s": 26956, "text": "1) Partition process is same in both recursive and iterative. The same techniques to choose optimal pivot can also be applied to iterative version." }, { "code": null, "e": 27173, "s": 27104, "text": "2) To reduce the stack size, first push the indexes of smaller half." }, { "code": null, "e": 27262, "s": 27173, "text": "3) Use insertion sort when the size reduces below a experimentally calculated threshold." }, { "code": null, "e": 27334, "s": 27262, "text": "Please refer complete article on Iterative Quick Sort for more details!" }, { "code": null, "e": 27345, "s": 27334, "text": "C Programs" }, { "code": null, "e": 27353, "s": 27345, "text": "Sorting" }, { "code": null, "e": 27361, "s": 27353, "text": "Sorting" }, { "code": null, "e": 27459, "s": 27361, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27500, "s": 27459, "text": "C Program to read contents of Whole File" }, { "code": null, "e": 27531, "s": 27500, "text": "Producer Consumer Problem in C" }, { "code": null, "e": 27572, "s": 27531, "text": "C program to find the length of a string" }, { "code": null, "e": 27606, "s": 27572, "text": "Exit codes in C/C++ with Examples" } ]
Angular 8 - Pipes
Pipes are referred as filters. It helps to transform data and manage data within interpolation, denoted by {{ | }}. It accepts data, arrays, integers and strings as inputs which are separated by ‘|’ symbol. This chapter explains about pipes in detail. Create a date method in your test.component.ts file. export class TestComponent { presentDate = new Date(); } Now, add the below code in your test.component.html file. <div> Today's date :- {{presentDate}} </div> Now, run the application, it will show the following output − Today's date :- Mon Jun 15 2020 10:25:05 GMT+0530 (IST) Here, Date object is converted into easily readable format. Let’s add date pipe in the above html file. <div> Today's date :- {{presentDate | date }} </div> You could see the below output − Today's date :- Jun 15, 2020 We can add parameter in pipe using : character. We can show short, full or formatted dates using this parameter. Add the below code in test.component.html file. <div> short date :- {{presentDate | date:'shortDate' }} <br/> Full date :- {{presentDate | date:'fullDate' }} <br/> Formatted date:- {{presentDate | date:'M/dd/yyyy'}} <br/> Hours and minutes:- {{presentDate | date:'h:mm'}} </div> You could see the below response on your screen − short date :- 6/15/20 Full date :- Monday, June 15, 2020 Formatted date:- 6/15/2020 Hours and minutes:- 12:00 We can combine multiple pipes together. This will be useful when a scenario associates with more than one pipe that has to be applied for data transformation. In the above example, if you want to show the date with uppercase letters, then we can apply both Date and Uppercase pipes together. <div> Date with uppercase :- {{presentDate | date:'fullDate' | uppercase}} <br/> Date with lowercase :- {{presentDate | date:'medium' | lowercase}} <br/> </div> You could see the below response on your screen − Date with uppercase :- MONDAY, JUNE 15, 2020 Date with lowercase :- jun 15, 2020, 12:00:00 am Here, Date, Uppercase and Lowercase are pre-defined pipes. Let’s understand other types of built-in pipes in next section. Angular 8 supports the following built-in pipes. We will discuss one by one in brief. If data comes in the form of observables, then Async pipe subscribes to an observable and returns the transmitted values. import { Observable, Observer } from 'rxjs'; export class TestComponent implements OnInit { timeChange = new Observable<string>((observer: Observer>string>) => { setInterval(() => observer.next(new Date().toString()), 1000); }); } Here, The Async pipe performs subscription for time changing in every one seconds and returns the result whenever gets passed to it. Main advantage is that, we don’t need to call subscribe on our timeChange and don’t worry about unsubscribe, if the component is removed. Add the below code inside your test.component.html. <div> Seconds changing in Time: {{ timeChange | async }} </div> Now, run the application, you could see the seconds changing on your screen. It is used to convert the given number into various countries currency format. Consider the below code in test.component.ts file. import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-test', template: ` <div style="text-align:center"> <h3> Currency Pipe</h3> <p>{{ price | currency:'EUR':true}}</p> <p>{{ price | currency:'INR' }}</p> </div> `, styleUrls: ['./test.component.scss'] }) export class TestComponent implements OnInit { price : number = 20000; ngOnInit() { } } You could see the following output on your screen − Currency Pipe €20,000.00 ₹20,000.00 Slice pipe is used to return a slice of an array. It takes index as an argument. If you assign only start index, means it will print till the end of values. If you want to print specific range of values, then we can assign start and end index. We can also use negative index to access elements. Simple example is shown below − test.component.ts import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-test', template: ` <div> <h3>Start index:- {{Fruits | slice:2}}</h3> <h4>Start and end index:- {{Fruits | slice:1:4}}</h4> <h5>Negative index:- {{Fruits | slice:-2}}</h5> <h6>Negative start and end index:- {{Fruits | slice:-4:-2}}</h6> </div> `, styleUrls: ['./test.component.scss'] }) export class TestComponent implements OnInit { Fruits = ["Apple","Orange","Grapes","Mango","Kiwi","Pomegranate"]; ngOnInit() { } } Now run your application and you could see the below output on your screen − Start index:- Grapes,Mango,Kiwi,Pomegranate Start and end index:- Orange,Grapes,Mango Negative index:- Kiwi,Pomegranate Negative start and end index:- Grapes,Mango Here, {{Fruits | slice:2}} means it starts from second index value Grapes to till the end of value. {{Fruits | slice:2}} means it starts from second index value Grapes to till the end of value. {{Fruits | slice:1:4}} means starts from 1 to end-1 so the result is one to third index values. {{Fruits | slice:1:4}} means starts from 1 to end-1 so the result is one to third index values. {{Fruits | slice:-2}} means starts from -2 to till end because no end value is specified. Hence the result is Kiwi, Pomegranate. {{Fruits | slice:-2}} means starts from -2 to till end because no end value is specified. Hence the result is Kiwi, Pomegranate. {{Fruits | slice:-4:-2}} means starts from negative index -4 is Grapes to end-1 which is -3 so the result of index[-4,-3] is Grapes, Mango. {{Fruits | slice:-4:-2}} means starts from negative index -4 is Grapes to end-1 which is -3 so the result of index[-4,-3] is Grapes, Mango. It is used to format decimal values. It is also considered as CommonModule. Let’s understand a simple code in test.component.ts file, import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-test', template: ` <div style="text-align:center"> <h3>Decimal Pipe</h3> <p> {{decimalNum1 | number}} </p> <p> {{decimalNum2 | number}} </p> </div> `, styleUrls: ['./test.component.scss'] }) export class TestComponent implements OnInit { decimalNum1: number = 8.7589623; decimalNum2: number = 5.43; ngOnInit() { } } You could see the below output on your screen − Decimal Pipe 8.759 5.43 We can apply string format inside number pattern. It is based on the below format − number:"{minimumIntegerDigits}.{minimumFractionDigits} - {maximumFractionDigits}" Let’s apply the above format in our code, @Component({ template: ` <div style="text-align:center"> <p> Apply formatting:- {{decimalNum1 | number:'3.1'}} </p> <p> Apply formatting:- {{decimalNum1 | number:'2.1-4'}} </p> </div> `, }) Here, {{decimalNum1 | number:’3.1’}} means three decimal place and minimum of one fraction but no constraint about maximum fraction limit. It returns the following output − Apply formatting:- 008.759 {{decimalNum1 | number:’2.1-4’}} means two decimal places and minimum one and maximum of four fractions allowed so it returns the below output − Apply formatting:- 08.759 It is used to format number as percent. Formatting strings are same as DecimalPipe concept. Simple example is shown below − import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-test', template: ` <div style="text-align:center"> <h3>Decimal Pipe</h3> <p> {{decimalNum1 | percent:'2.2'}} </p> </div> `, styleUrls: ['./test.component.scss'] }) export class TestComponent { decimalNum1: number = 0.8178; } You could see the below output on your screen − Decimal Pipe 81.78% It is used to transform a JavaScript object into a JSON string. Add the below code in test.component.ts file as follows − import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-test', template: ` <div style="text-align:center"> <p ngNonBindable>{{ jsonData }}</p> (1) <p>{{ jsonData }}</p> <p ngNonBindable>{{ jsonData | json }}</p> <p>{{ jsonData | json }}</p> </div> `, styleUrls: ['./test.component.scss'] }) export class TestComponent { jsonData = { id: 'one', name: { username: 'user1' }} } Now, run the application, you could see the below output on your screen − {{ jsonData }} (1) [object Object] {{ jsonData | json }} { "id": "one", "name": { "username": "user1" } } As we have seen already, there is a number of pre-defined Pipes available in Angular 8 but sometimes, we may want to transform values in custom formats. This section explains about creating custom Pipes. Create a custom Pipe using the below command − ng g pipe digitcount After executing the above command, you could see the response − CREATE src/app/digitcount.pipe.spec.ts (203 bytes) CREATE src/app/digitcount.pipe.ts (213 bytes) UPDATE src/app/app.module.ts (744 bytes) Let’s create a logic for counting digits in a number using Pipe. Open digitcount.pipe.ts file and add the below code − import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'digitcount' }) export class DigitcountPipe implements PipeTransform { transform(val : number) : number { return val.toString().length; } } Now, we have added logic for count number of digits in a number. Let’s add the final code in test.component.ts file as follows − import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-test', template: ` <div> <p> DigitCount Pipe </p> <h1>{{ digits | digitcount }}</h1> </div> `, styleUrls: ['./test.component.scss'] }) export class TestComponent implements OnInit { digits : number = 100; ngOnInit() { } } Now, run the application, you could see the below response − DigitCount Pipe 3 Let us use the pipe in the our ExpenseManager application. Open command prompt and go to project root folder. cd /go/to/expense-manager Start the application. ng serve Open ExpenseEntryListComponent’s template, src/app/expense-entry-list/expense-entry-list.component.html and include pipe in entry.spendOn as mentioned below − <td>{{ entry.spendOn | date: 'short' }}</td> Here, we have used the date pipe to show the spend on date in the short format. Finally, the output of the application is as shown below − 16 Lectures 1.5 hours Anadi Sharma 28 Lectures 2.5 hours Anadi Sharma 11 Lectures 7.5 hours SHIVPRASAD KOIRALA 16 Lectures 2.5 hours Frahaan Hussain 69 Lectures 5 hours Senol Atac 53 Lectures 3.5 hours Senol Atac Print Add Notes Bookmark this page
[ { "code": null, "e": 2640, "s": 2388, "text": "Pipes are referred as filters. It helps to transform data and manage data within interpolation, denoted by {{ | }}. It accepts data, arrays, integers and strings as inputs which are separated by ‘|’ symbol. This chapter explains about pipes in detail." }, { "code": null, "e": 2693, "s": 2640, "text": "Create a date method in your test.component.ts file." }, { "code": null, "e": 2756, "s": 2693, "text": "export class TestComponent { \n presentDate = new Date(); \n}\n" }, { "code": null, "e": 2814, "s": 2756, "text": "Now, add the below code in your test.component.html file." }, { "code": null, "e": 2865, "s": 2814, "text": "<div> \n Today's date :- {{presentDate}} \n</div>\n" }, { "code": null, "e": 2927, "s": 2865, "text": "Now, run the application, it will show the following output −" }, { "code": null, "e": 2984, "s": 2927, "text": "Today's date :- Mon Jun 15 2020 10:25:05 GMT+0530 (IST)\n" }, { "code": null, "e": 2990, "s": 2984, "text": "Here," }, { "code": null, "e": 3044, "s": 2990, "text": "Date object is converted into easily readable format." }, { "code": null, "e": 3088, "s": 3044, "text": "Let’s add date pipe in the above html file." }, { "code": null, "e": 3146, "s": 3088, "text": "<div> \n Today's date :- {{presentDate | date }}\n</div>\n" }, { "code": null, "e": 3179, "s": 3146, "text": "You could see the below output −" }, { "code": null, "e": 3209, "s": 3179, "text": "Today's date :- Jun 15, 2020\n" }, { "code": null, "e": 3370, "s": 3209, "text": "We can add parameter in pipe using : character. We can show short, full or formatted dates using this parameter. Add the below code in test.component.html file." }, { "code": null, "e": 3618, "s": 3370, "text": "<div> \n short date :- {{presentDate | date:'shortDate' }} <br/>\n Full date :- {{presentDate | date:'fullDate' }} <br/> \n Formatted date:- {{presentDate | date:'M/dd/yyyy'}} <br/> \n Hours and minutes:- {{presentDate | date:'h:mm'}} \n</div>\n" }, { "code": null, "e": 3668, "s": 3618, "text": "You could see the below response on your screen −" }, { "code": null, "e": 3782, "s": 3668, "text": "short date :- 6/15/20 \nFull date :- Monday, June 15, 2020 \nFormatted date:- 6/15/2020 \nHours and minutes:- 12:00\n" }, { "code": null, "e": 3941, "s": 3782, "text": "We can combine multiple pipes together. This will be useful when a scenario associates with more than one pipe that has to be applied for data transformation." }, { "code": null, "e": 4074, "s": 3941, "text": "In the above example, if you want to show the date with uppercase letters, then we can apply both Date and Uppercase pipes together." }, { "code": null, "e": 4245, "s": 4074, "text": "<div> \n Date with uppercase :- {{presentDate | date:'fullDate' | uppercase}} <br/>\n Date with lowercase :- {{presentDate | date:'medium' | lowercase}} <br/> \n</div>\n" }, { "code": null, "e": 4295, "s": 4245, "text": "You could see the below response on your screen −" }, { "code": null, "e": 4390, "s": 4295, "text": "Date with uppercase :- MONDAY, JUNE 15, 2020 Date with lowercase :- jun 15, 2020, 12:00:00 am\n" }, { "code": null, "e": 4396, "s": 4390, "text": "Here," }, { "code": null, "e": 4513, "s": 4396, "text": "Date, Uppercase and Lowercase are pre-defined pipes. Let’s understand other types of built-in pipes in next section." }, { "code": null, "e": 4599, "s": 4513, "text": "Angular 8 supports the following built-in pipes. We will discuss one by one in brief." }, { "code": null, "e": 4721, "s": 4599, "text": "If data comes in the form of observables, then Async pipe subscribes to an observable and returns the transmitted values." }, { "code": null, "e": 4973, "s": 4721, "text": "import { Observable, Observer } from 'rxjs';\nexport class TestComponent implements OnInit {\n timeChange = new Observable<string>((observer: Observer>string>) => {\n setInterval(() => observer.next(new \n Date().toString()), 1000); \n }); \n}" }, { "code": null, "e": 4979, "s": 4973, "text": "Here," }, { "code": null, "e": 5244, "s": 4979, "text": "The Async pipe performs subscription for time changing in every one seconds and returns the result whenever gets passed to it. Main advantage is that, we don’t need to call subscribe on our timeChange and don’t worry about unsubscribe, if the component is removed." }, { "code": null, "e": 5296, "s": 5244, "text": "Add the below code inside your test.component.html." }, { "code": null, "e": 5365, "s": 5296, "text": "<div> \n Seconds changing in Time: {{ timeChange | async }}\n</div>\n" }, { "code": null, "e": 5442, "s": 5365, "text": "Now, run the application, you could see the seconds changing on your screen." }, { "code": null, "e": 5572, "s": 5442, "text": "It is used to convert the given number into various countries currency format. Consider the below code in test.component.ts file." }, { "code": null, "e": 5996, "s": 5572, "text": "import { Component, OnInit } from '@angular/core'; @Component({ \n selector: 'app-test', \n template: ` \n <div style=\"text-align:center\"> \n <h3> Currency Pipe</h3> \n <p>{{ price | currency:'EUR':true}}</p> \n <p>{{ price | currency:'INR' }}</p> \n </div> \n `, \n styleUrls: ['./test.component.scss'] \n}) \nexport class TestComponent implements OnInit { \n price : number = 20000; ngOnInit() {\n\n } \n}" }, { "code": null, "e": 6048, "s": 5996, "text": "You could see the following output on your screen −" }, { "code": null, "e": 6087, "s": 6048, "text": "Currency Pipe\n\n€20,000.00 \n₹20,000.00\n" }, { "code": null, "e": 6331, "s": 6087, "text": "Slice pipe is used to return a slice of an array. It takes index as an argument. If you assign only start index, means it will print till the end of values. If you want to print specific range of values, then we can assign start and end index." }, { "code": null, "e": 6414, "s": 6331, "text": "We can also use negative index to access elements. Simple example is shown below −" }, { "code": null, "e": 6432, "s": 6414, "text": "test.component.ts" }, { "code": null, "e": 6994, "s": 6432, "text": "import { Component, OnInit } from '@angular/core'; @Component({ \n selector: 'app-test', \n template: ` \n <div> \n <h3>Start index:- {{Fruits | slice:2}}</h3> \n <h4>Start and end index:- {{Fruits | slice:1:4}}</h4> \n <h5>Negative index:- {{Fruits | slice:-2}}</h5> \n <h6>Negative start and end index:- {{Fruits | slice:-4:-2}}</h6> \n </div>\n `, \n styleUrls: ['./test.component.scss'] \n}) \nexport class TestComponent implements OnInit { \n Fruits = [\"Apple\",\"Orange\",\"Grapes\",\"Mango\",\"Kiwi\",\"Pomegranate\"]; \n ngOnInit() {\n\n } \n}" }, { "code": null, "e": 7071, "s": 6994, "text": "Now run your application and you could see the below output on your screen −" }, { "code": null, "e": 7238, "s": 7071, "text": "Start index:- Grapes,Mango,Kiwi,Pomegranate\nStart and end index:- Orange,Grapes,Mango \nNegative index:- Kiwi,Pomegranate \nNegative start and end index:- Grapes,Mango\n" }, { "code": null, "e": 7244, "s": 7238, "text": "Here," }, { "code": null, "e": 7338, "s": 7244, "text": "{{Fruits | slice:2}} means it starts from second index value Grapes to till the end of value." }, { "code": null, "e": 7432, "s": 7338, "text": "{{Fruits | slice:2}} means it starts from second index value Grapes to till the end of value." }, { "code": null, "e": 7528, "s": 7432, "text": "{{Fruits | slice:1:4}} means starts from 1 to end-1 so the result is one to third index values." }, { "code": null, "e": 7624, "s": 7528, "text": "{{Fruits | slice:1:4}} means starts from 1 to end-1 so the result is one to third index values." }, { "code": null, "e": 7753, "s": 7624, "text": "{{Fruits | slice:-2}} means starts from -2 to till end because no end value is specified. Hence the result is Kiwi, Pomegranate." }, { "code": null, "e": 7882, "s": 7753, "text": "{{Fruits | slice:-2}} means starts from -2 to till end because no end value is specified. Hence the result is Kiwi, Pomegranate." }, { "code": null, "e": 8022, "s": 7882, "text": "{{Fruits | slice:-4:-2}} means starts from negative index -4 is Grapes to end-1 which is -3 so the result of index[-4,-3] is Grapes, Mango." }, { "code": null, "e": 8162, "s": 8022, "text": "{{Fruits | slice:-4:-2}} means starts from negative index -4 is Grapes to end-1 which is -3 so the result of index[-4,-3] is Grapes, Mango." }, { "code": null, "e": 8296, "s": 8162, "text": "It is used to format decimal values. It is also considered as CommonModule. Let’s understand a simple code in test.component.ts file," }, { "code": null, "e": 8755, "s": 8296, "text": "import { Component, OnInit } from '@angular/core'; @Component({ \n selector: 'app-test', \n template: ` \n <div style=\"text-align:center\"> \n <h3>Decimal Pipe</h3> \n <p> {{decimalNum1 | number}} </p> \n <p> {{decimalNum2 | number}} </p> \n </div> \n `, \n styleUrls: ['./test.component.scss'] \n}) \nexport class TestComponent implements OnInit { \n decimalNum1: number = 8.7589623; \n decimalNum2: number = 5.43; \n ngOnInit() {\n\n } \n}" }, { "code": null, "e": 8803, "s": 8755, "text": "You could see the below output on your screen −" }, { "code": null, "e": 8830, "s": 8803, "text": "Decimal Pipe \n8.759 \n5.43\n" }, { "code": null, "e": 8914, "s": 8830, "text": "We can apply string format inside number pattern. It is based on the below format −" }, { "code": null, "e": 8997, "s": 8914, "text": "number:\"{minimumIntegerDigits}.{minimumFractionDigits} - {maximumFractionDigits}\"\n" }, { "code": null, "e": 9039, "s": 8997, "text": "Let’s apply the above format in our code," }, { "code": null, "e": 9261, "s": 9039, "text": "@Component({ \n template: ` \n <div style=\"text-align:center\"> \n <p> Apply formatting:- {{decimalNum1 | number:'3.1'}} </p> \n <p> Apply formatting:- {{decimalNum1 | number:'2.1-4'}} </p> \n </div> \n `, \n})\n" }, { "code": null, "e": 9267, "s": 9261, "text": "Here," }, { "code": null, "e": 9434, "s": 9267, "text": "{{decimalNum1 | number:’3.1’}} means three decimal place and minimum of one fraction but no constraint about maximum fraction limit. It returns the following output −" }, { "code": null, "e": 9462, "s": 9434, "text": "Apply formatting:- 008.759\n" }, { "code": null, "e": 9607, "s": 9462, "text": "{{decimalNum1 | number:’2.1-4’}} means two decimal places and minimum one and maximum of four fractions allowed so it returns the below output −" }, { "code": null, "e": 9634, "s": 9607, "text": "Apply formatting:- 08.759\n" }, { "code": null, "e": 9758, "s": 9634, "text": "It is used to format number as percent. Formatting strings are same as DecimalPipe concept. Simple example is shown below −" }, { "code": null, "e": 10108, "s": 9758, "text": "import { Component, OnInit } from '@angular/core'; \n@Component({ \n selector: 'app-test', \n template: ` \n <div style=\"text-align:center\"> \n <h3>Decimal Pipe</h3> \n <p> {{decimalNum1 | percent:'2.2'}} </p> \n </div> \n `, \n styleUrls: ['./test.component.scss'] \n}) \nexport class TestComponent { \n decimalNum1: number = 0.8178; \n}" }, { "code": null, "e": 10156, "s": 10108, "text": "You could see the below output on your screen −" }, { "code": null, "e": 10178, "s": 10156, "text": "Decimal Pipe \n81.78%\n" }, { "code": null, "e": 10300, "s": 10178, "text": "It is used to transform a JavaScript object into a JSON string. Add the below code in test.component.ts file as follows −" }, { "code": null, "e": 10758, "s": 10300, "text": "import { Component, OnInit } from '@angular/core'; \n@Component({ \n selector: 'app-test', \n template: ` \n <div style=\"text-align:center\"> \n <p ngNonBindable>{{ jsonData }}</p> (1) \n <p>{{ jsonData }}</p> \n <p ngNonBindable>{{ jsonData | json }}</p> \n <p>{{ jsonData | json }}</p> \n </div> \n `, \n styleUrls: ['./test.component.scss'] \n}) \nexport class TestComponent { \n jsonData = { id: 'one', name: { username: 'user1' }} \n}" }, { "code": null, "e": 10832, "s": 10758, "text": "Now, run the application, you could see the below output on your screen −" }, { "code": null, "e": 10943, "s": 10832, "text": "{{ jsonData }} \n(1) \n[object Object] \n{{ jsonData | json }} \n{ \"id\": \"one\", \"name\": { \"username\": \"user1\" } }\n" }, { "code": null, "e": 11147, "s": 10943, "text": "As we have seen already, there is a number of pre-defined Pipes available in Angular 8 but sometimes, we may want to transform values in custom formats. This section explains about creating custom Pipes." }, { "code": null, "e": 11194, "s": 11147, "text": "Create a custom Pipe using the below command −" }, { "code": null, "e": 11216, "s": 11194, "text": "ng g pipe digitcount\n" }, { "code": null, "e": 11280, "s": 11216, "text": "After executing the above command, you could see the response −" }, { "code": null, "e": 11420, "s": 11280, "text": "CREATE src/app/digitcount.pipe.spec.ts (203 bytes) CREATE src/app/digitcount.pipe.ts (213 bytes) \nUPDATE src/app/app.module.ts (744 bytes)\n" }, { "code": null, "e": 11539, "s": 11420, "text": "Let’s create a logic for counting digits in a number using Pipe. Open digitcount.pipe.ts file and add the below code −" }, { "code": null, "e": 11769, "s": 11539, "text": "import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ \n name: 'digitcount' \n}) \nexport class DigitcountPipe implements PipeTransform { \n transform(val : number) : number { \n return val.toString().length; \n } \n}\n" }, { "code": null, "e": 11898, "s": 11769, "text": "Now, we have added logic for count number of digits in a number. Let’s add the final code in test.component.ts file as follows −" }, { "code": null, "e": 12252, "s": 11898, "text": "import { Component, OnInit } from '@angular/core'; @Component({ \n selector: 'app-test', \n template: ` \n <div> \n <p> DigitCount Pipe </p> \n <h1>{{ digits | digitcount }}</h1> \n </div> \n `, \n styleUrls: ['./test.component.scss'] \n}) \nexport class TestComponent implements OnInit { \n digits : number = 100; \n ngOnInit() { \n } \n}" }, { "code": null, "e": 12313, "s": 12252, "text": "Now, run the application, you could see the below response −" }, { "code": null, "e": 12333, "s": 12313, "text": "DigitCount Pipe \n3\n" }, { "code": null, "e": 12392, "s": 12333, "text": "Let us use the pipe in the our ExpenseManager application." }, { "code": null, "e": 12443, "s": 12392, "text": "Open command prompt and go to project root folder." }, { "code": null, "e": 12470, "s": 12443, "text": "cd /go/to/expense-manager\n" }, { "code": null, "e": 12493, "s": 12470, "text": "Start the application." }, { "code": null, "e": 12503, "s": 12493, "text": "ng serve\n" }, { "code": null, "e": 12662, "s": 12503, "text": "Open ExpenseEntryListComponent’s template, src/app/expense-entry-list/expense-entry-list.component.html and include pipe in entry.spendOn as mentioned below −" }, { "code": null, "e": 12708, "s": 12662, "text": "<td>{{ entry.spendOn | date: 'short' }}</td>\n" }, { "code": null, "e": 12788, "s": 12708, "text": "Here, we have used the date pipe to show the spend on date in the short format." }, { "code": null, "e": 12847, "s": 12788, "text": "Finally, the output of the application is as shown below −" }, { "code": null, "e": 12882, "s": 12847, "text": "\n 16 Lectures \n 1.5 hours \n" }, { "code": null, "e": 12896, "s": 12882, "text": " Anadi Sharma" }, { "code": null, "e": 12931, "s": 12896, "text": "\n 28 Lectures \n 2.5 hours \n" }, { "code": null, "e": 12945, "s": 12931, "text": " Anadi Sharma" }, { "code": null, "e": 12980, "s": 12945, "text": "\n 11 Lectures \n 7.5 hours \n" }, { "code": null, "e": 13000, "s": 12980, "text": " SHIVPRASAD KOIRALA" }, { "code": null, "e": 13035, "s": 13000, "text": "\n 16 Lectures \n 2.5 hours \n" }, { "code": null, "e": 13052, "s": 13035, "text": " Frahaan Hussain" }, { "code": null, "e": 13085, "s": 13052, "text": "\n 69 Lectures \n 5 hours \n" }, { "code": null, "e": 13097, "s": 13085, "text": " Senol Atac" }, { "code": null, "e": 13132, "s": 13097, "text": "\n 53 Lectures \n 3.5 hours \n" }, { "code": null, "e": 13144, "s": 13132, "text": " Senol Atac" }, { "code": null, "e": 13151, "s": 13144, "text": " Print" }, { "code": null, "e": 13162, "s": 13151, "text": " Add Notes" } ]
Character.digit() in Java with examples - GeeksforGeeks
06 Dec, 2018 The java.lang.Character.digit() is an inbuilt method in java which returns the numeric value of the character ch in the specified radix. It returns -1 if the radix is not in the range MIN_RADIX <= radix <= MAX_RADIX or if the value of ch is not a valid digit in the specified radix. A character is a valid digit if at least one of the following is true: The method isDigit is true of the character and the Unicode decimal digit value of the character (or its single-character decomposition) is less than the specified radix. In this case the decimal digit value is returned. The character is one of the uppercase Latin letters ‘A’ through ‘Z’ and its code is less than radix + ‘A’ – 10. In this case, ch – ‘A’ + 10 is returned. The character is one of the lowercase Latin letters ‘a’ through ‘z’ and its code is less than radix + ‘a’ – 10. In this case, ch – ‘a’ + 10 is returned. The character is one of the fullwidth uppercase Latin letters A (‘\uFF21’) through Z (‘\uFF3A’) and its code is less than radix + ‘\uFF21’ – 10. In this case, ch – ‘\uFF21’ + 10 is returned. The character is one of the fullwidth lowercase Latin letters a (‘\uFF41’) through z (‘\uFF5A’) and its code is less than radix + ‘\uFF41’ – 10. In this case, ch – ‘\uFF41’ + 10 is returned. Syntax: public static int digit(char ch, int radix) Parameters:The function accepts two parameters which are described below: ch- This is a mandatory parameter which specifies the character to be converted. radix- This is a mandatory parameter which specifies radix. Return value: This method returns the numeric value represented by the character in the specified radix. Below programs demonstrates the above method: Program 1: // Java program to illustrate the// Character.digit() method import java.lang.*; public class gfg { public static void main(String[] args) { // create and assign value // to 2 character objects char c1 = '3', c2 = '6'; // assign the numeric value of c1 to in1 using radix int in1 = Character.digit(c1, 5); System.out.println("Numeric value of " + c1 + " in radix 5 is " + in1); // assign the numeric value of c2 to in2 using radix int in2 = Character.digit(c2, 15); System.out.println("Numeric value of " + c2 + " in radix 15 is " + in2); }} Numeric value of 3 in radix 5 is 3 Numeric value of 6 in radix 15 is 6 Program 2: // Java program to illustrate the// Character.digit() method// when -1 is returnedimport java.lang.*; public class gfg { public static void main(String[] args) { // create and assign value // to 2 character objects char c1 = 'a', c2 = 'z'; // assign the numeric value of c1 to in1 using radix int in1 = Character.digit(c1, 5); System.out.println("Numeric value of " + c1 + " in radix 5 is " + in1); // assign the numeric value of c2 to in2 using radix int in2 = Character.digit(c2, 15); System.out.println("Numeric value of " + c2 + " in radix 15 is " + in2); }} Numeric value of a in radix 5 is -1 Numeric value of z in radix 15 is -1 Reference: https://docs.oracle.com/javase/7/docs/api/java/lang/Character.html#digit(char,%20int) Java-Character Java-Functions Java-lang package Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Different ways of Reading a text file in Java Constructors in Java Exceptions in Java Functional Interfaces in Java Generics in Java Comparator Interface in Java with Examples HashMap get() Method in Java Introduction to Java Difference between Abstract Class and Interface in Java
[ { "code": null, "e": 23972, "s": 23944, "text": "\n06 Dec, 2018" }, { "code": null, "e": 24326, "s": 23972, "text": "The java.lang.Character.digit() is an inbuilt method in java which returns the numeric value of the character ch in the specified radix. It returns -1 if the radix is not in the range MIN_RADIX <= radix <= MAX_RADIX or if the value of ch is not a valid digit in the specified radix. A character is a valid digit if at least one of the following is true:" }, { "code": null, "e": 24547, "s": 24326, "text": "The method isDigit is true of the character and the Unicode decimal digit value of the character (or its single-character decomposition) is less than the specified radix. In this case the decimal digit value is returned." }, { "code": null, "e": 24700, "s": 24547, "text": "The character is one of the uppercase Latin letters ‘A’ through ‘Z’ and its code is less than radix + ‘A’ – 10. In this case, ch – ‘A’ + 10 is returned." }, { "code": null, "e": 24853, "s": 24700, "text": "The character is one of the lowercase Latin letters ‘a’ through ‘z’ and its code is less than radix + ‘a’ – 10. In this case, ch – ‘a’ + 10 is returned." }, { "code": null, "e": 25044, "s": 24853, "text": "The character is one of the fullwidth uppercase Latin letters A (‘\\uFF21’) through Z (‘\\uFF3A’) and its code is less than radix + ‘\\uFF21’ – 10. In this case, ch – ‘\\uFF21’ + 10 is returned." }, { "code": null, "e": 25235, "s": 25044, "text": "The character is one of the fullwidth lowercase Latin letters a (‘\\uFF41’) through z (‘\\uFF5A’) and its code is less than radix + ‘\\uFF41’ – 10. In this case, ch – ‘\\uFF41’ + 10 is returned." }, { "code": null, "e": 25243, "s": 25235, "text": "Syntax:" }, { "code": null, "e": 25288, "s": 25243, "text": "public static int digit(char ch, int radix)\n" }, { "code": null, "e": 25362, "s": 25288, "text": "Parameters:The function accepts two parameters which are described below:" }, { "code": null, "e": 25443, "s": 25362, "text": "ch- This is a mandatory parameter which specifies the character to be converted." }, { "code": null, "e": 25503, "s": 25443, "text": "radix- This is a mandatory parameter which specifies radix." }, { "code": null, "e": 25608, "s": 25503, "text": "Return value: This method returns the numeric value represented by the character in the specified radix." }, { "code": null, "e": 25654, "s": 25608, "text": "Below programs demonstrates the above method:" }, { "code": null, "e": 25665, "s": 25654, "text": "Program 1:" }, { "code": "// Java program to illustrate the// Character.digit() method import java.lang.*; public class gfg { public static void main(String[] args) { // create and assign value // to 2 character objects char c1 = '3', c2 = '6'; // assign the numeric value of c1 to in1 using radix int in1 = Character.digit(c1, 5); System.out.println(\"Numeric value of \" + c1 + \" in radix 5 is \" + in1); // assign the numeric value of c2 to in2 using radix int in2 = Character.digit(c2, 15); System.out.println(\"Numeric value of \" + c2 + \" in radix 15 is \" + in2); }}", "e": 26287, "s": 25665, "text": null }, { "code": null, "e": 26359, "s": 26287, "text": "Numeric value of 3 in radix 5 is 3\nNumeric value of 6 in radix 15 is 6\n" }, { "code": null, "e": 26370, "s": 26359, "text": "Program 2:" }, { "code": "// Java program to illustrate the// Character.digit() method// when -1 is returnedimport java.lang.*; public class gfg { public static void main(String[] args) { // create and assign value // to 2 character objects char c1 = 'a', c2 = 'z'; // assign the numeric value of c1 to in1 using radix int in1 = Character.digit(c1, 5); System.out.println(\"Numeric value of \" + c1 + \" in radix 5 is \" + in1); // assign the numeric value of c2 to in2 using radix int in2 = Character.digit(c2, 15); System.out.println(\"Numeric value of \" + c2 + \" in radix 15 is \" + in2); }}", "e": 27014, "s": 26370, "text": null }, { "code": null, "e": 27088, "s": 27014, "text": "Numeric value of a in radix 5 is -1\nNumeric value of z in radix 15 is -1\n" }, { "code": null, "e": 27185, "s": 27088, "text": "Reference: https://docs.oracle.com/javase/7/docs/api/java/lang/Character.html#digit(char,%20int)" }, { "code": null, "e": 27200, "s": 27185, "text": "Java-Character" }, { "code": null, "e": 27215, "s": 27200, "text": "Java-Functions" }, { "code": null, "e": 27233, "s": 27215, "text": "Java-lang package" }, { "code": null, "e": 27238, "s": 27233, "text": "Java" }, { "code": null, "e": 27243, "s": 27238, "text": "Java" }, { "code": null, "e": 27341, "s": 27243, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27356, "s": 27341, "text": "Stream In Java" }, { "code": null, "e": 27402, "s": 27356, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 27423, "s": 27402, "text": "Constructors in Java" }, { "code": null, "e": 27442, "s": 27423, "text": "Exceptions in Java" }, { "code": null, "e": 27472, "s": 27442, "text": "Functional Interfaces in Java" }, { "code": null, "e": 27489, "s": 27472, "text": "Generics in Java" }, { "code": null, "e": 27532, "s": 27489, "text": "Comparator Interface in Java with Examples" }, { "code": null, "e": 27561, "s": 27532, "text": "HashMap get() Method in Java" }, { "code": null, "e": 27582, "s": 27561, "text": "Introduction to Java" } ]
Perl glob Function
This function returns a list of files matching EXPR as they would be expanded by the standard Bourne shell. If the EXPR does not specify a path, uses the current directory. If EXPR is omitted, the value of $_ is used. From Perl 5.6 on, expansion is done internally, rather than using an external script. Expansion follows the csh (and any derivatives, including tcsh and bash) style of expansion, which translates as the following − Files beginning with a single period are ignored unless EXPR explicitly matches. Files beginning with a single period are ignored unless EXPR explicitly matches. The * character matches zero or more characters of any type. The * character matches zero or more characters of any type. The ? character matches one character of any type. The ? character matches one character of any type. The [..] construct matches the characters listed, including ranges, as per regular expressions. The [..] construct matches the characters listed, including ranges, as per regular expressions. The ~ characters matches the home directory; ~name matches the home directory for the user name. The ~ characters matches the home directory; ~name matches the home directory for the user name. The {..} construct matches against any of the comma-separated words enclosed in the braces. The {..} construct matches against any of the comma-separated words enclosed in the braces. Following is the simple syntax for this function − glob EXPR glob This function returns undef on error otherwise First file in the list of expanded names in scalar context and Empty list on error otherwise List of expanded file names in list context. Following is the example code showing its basic usage − #!/usr/bin/perl (@file_list) = glob "perl_g*"; print "Returned list of file @file_list\n"; When above code is executed, it produces the following result − Returned list of file 46 Lectures 4.5 hours Devi Killada 11 Lectures 1.5 hours Harshit Srivastava 30 Lectures 6 hours TELCOMA Global 24 Lectures 2 hours Mohammad Nauman 68 Lectures 7 hours Stone River ELearning 58 Lectures 6.5 hours Stone River ELearning Print Add Notes Bookmark this page
[ { "code": null, "e": 2438, "s": 2220, "text": "This function returns a list of files matching EXPR as they would be expanded by the standard Bourne shell. If the EXPR does not specify a path, uses the current directory. If EXPR is omitted, the value of $_ is used." }, { "code": null, "e": 2653, "s": 2438, "text": "From Perl 5.6 on, expansion is done internally, rather than using an external script. Expansion follows the csh (and any derivatives, including tcsh and bash) style of expansion, which translates as the following −" }, { "code": null, "e": 2734, "s": 2653, "text": "Files beginning with a single period are ignored unless EXPR explicitly matches." }, { "code": null, "e": 2815, "s": 2734, "text": "Files beginning with a single period are ignored unless EXPR explicitly matches." }, { "code": null, "e": 2876, "s": 2815, "text": "The * character matches zero or more characters of any type." }, { "code": null, "e": 2937, "s": 2876, "text": "The * character matches zero or more characters of any type." }, { "code": null, "e": 2988, "s": 2937, "text": "The ? character matches one character of any type." }, { "code": null, "e": 3039, "s": 2988, "text": "The ? character matches one character of any type." }, { "code": null, "e": 3135, "s": 3039, "text": "The [..] construct matches the characters listed, including ranges, as per regular expressions." }, { "code": null, "e": 3231, "s": 3135, "text": "The [..] construct matches the characters listed, including ranges, as per regular expressions." }, { "code": null, "e": 3328, "s": 3231, "text": "The ~ characters matches the home directory; ~name matches the home directory for the user name." }, { "code": null, "e": 3425, "s": 3328, "text": "The ~ characters matches the home directory; ~name matches the home directory for the user name." }, { "code": null, "e": 3517, "s": 3425, "text": "The {..} construct matches against any of the comma-separated words enclosed in the braces." }, { "code": null, "e": 3609, "s": 3517, "text": "The {..} construct matches against any of the comma-separated words enclosed in the braces." }, { "code": null, "e": 3660, "s": 3609, "text": "Following is the simple syntax for this function −" }, { "code": null, "e": 3677, "s": 3660, "text": "glob EXPR\n\nglob\n" }, { "code": null, "e": 3862, "s": 3677, "text": "This function returns undef on error otherwise First file in the list of expanded names in scalar context and Empty list on error otherwise List of expanded file names in list context." }, { "code": null, "e": 3918, "s": 3862, "text": "Following is the example code showing its basic usage −" }, { "code": null, "e": 4011, "s": 3918, "text": "#!/usr/bin/perl\n\n(@file_list) = glob \"perl_g*\";\n\nprint \"Returned list of file @file_list\\n\";" }, { "code": null, "e": 4075, "s": 4011, "text": "When above code is executed, it produces the following result −" }, { "code": null, "e": 4098, "s": 4075, "text": "Returned list of file\n" }, { "code": null, "e": 4133, "s": 4098, "text": "\n 46 Lectures \n 4.5 hours \n" }, { "code": null, "e": 4147, "s": 4133, "text": " Devi Killada" }, { "code": null, "e": 4182, "s": 4147, "text": "\n 11 Lectures \n 1.5 hours \n" }, { "code": null, "e": 4202, "s": 4182, "text": " Harshit Srivastava" }, { "code": null, "e": 4235, "s": 4202, "text": "\n 30 Lectures \n 6 hours \n" }, { "code": null, "e": 4251, "s": 4235, "text": " TELCOMA Global" }, { "code": null, "e": 4284, "s": 4251, "text": "\n 24 Lectures \n 2 hours \n" }, { "code": null, "e": 4301, "s": 4284, "text": " Mohammad Nauman" }, { "code": null, "e": 4334, "s": 4301, "text": "\n 68 Lectures \n 7 hours \n" }, { "code": null, "e": 4357, "s": 4334, "text": " Stone River ELearning" }, { "code": null, "e": 4392, "s": 4357, "text": "\n 58 Lectures \n 6.5 hours \n" }, { "code": null, "e": 4415, "s": 4392, "text": " Stone River ELearning" }, { "code": null, "e": 4422, "s": 4415, "text": " Print" }, { "code": null, "e": 4433, "s": 4422, "text": " Add Notes" } ]
Perl hex Function
This function interprets EXPR as a hexadecimal string and returns the value, or converts $_ if EXPR is omitted. Following is the simple syntax for this function − hex EXPR hex This function returns numeric value equivalent to hexa in scalar context. Following is the example code showing its basic usage − #!/usr/bin/perl print hex '0xAf'; # prints '175' print "\n"; print hex 'aF'; # same When above code is executed, it produces the following result − 175 175 46 Lectures 4.5 hours Devi Killada 11 Lectures 1.5 hours Harshit Srivastava 30 Lectures 6 hours TELCOMA Global 24 Lectures 2 hours Mohammad Nauman 68 Lectures 7 hours Stone River ELearning 58 Lectures 6.5 hours Stone River ELearning Print Add Notes Bookmark this page
[ { "code": null, "e": 2332, "s": 2220, "text": "This function interprets EXPR as a hexadecimal string and returns the value, or converts $_ if EXPR is omitted." }, { "code": null, "e": 2383, "s": 2332, "text": "Following is the simple syntax for this function −" }, { "code": null, "e": 2398, "s": 2383, "text": "hex EXPR\n\nhex\n" }, { "code": null, "e": 2472, "s": 2398, "text": "This function returns numeric value equivalent to hexa in scalar context." }, { "code": null, "e": 2528, "s": 2472, "text": "Following is the example code showing its basic usage −" }, { "code": null, "e": 2615, "s": 2528, "text": "#!/usr/bin/perl\n\nprint hex '0xAf'; # prints '175'\nprint \"\\n\";\nprint hex 'aF'; # same" }, { "code": null, "e": 2679, "s": 2615, "text": "When above code is executed, it produces the following result −" }, { "code": null, "e": 2688, "s": 2679, "text": "175\n175\n" }, { "code": null, "e": 2723, "s": 2688, "text": "\n 46 Lectures \n 4.5 hours \n" }, { "code": null, "e": 2737, "s": 2723, "text": " Devi Killada" }, { "code": null, "e": 2772, "s": 2737, "text": "\n 11 Lectures \n 1.5 hours \n" }, { "code": null, "e": 2792, "s": 2772, "text": " Harshit Srivastava" }, { "code": null, "e": 2825, "s": 2792, "text": "\n 30 Lectures \n 6 hours \n" }, { "code": null, "e": 2841, "s": 2825, "text": " TELCOMA Global" }, { "code": null, "e": 2874, "s": 2841, "text": "\n 24 Lectures \n 2 hours \n" }, { "code": null, "e": 2891, "s": 2874, "text": " Mohammad Nauman" }, { "code": null, "e": 2924, "s": 2891, "text": "\n 68 Lectures \n 7 hours \n" }, { "code": null, "e": 2947, "s": 2924, "text": " Stone River ELearning" }, { "code": null, "e": 2982, "s": 2947, "text": "\n 58 Lectures \n 6.5 hours \n" }, { "code": null, "e": 3005, "s": 2982, "text": " Stone River ELearning" }, { "code": null, "e": 3012, "s": 3005, "text": " Print" }, { "code": null, "e": 3023, "s": 3012, "text": " Add Notes" } ]
Date and Time Functions in DBMS
The date and time functions in DBMS are quite useful to manipulate and store values related to date and time. The different date and time functions are as follows − The numbers of days in integer form (DAYS) is added to the specified date. This is the value returned by the function. For example − sql> SELECT ADDDATE('2018-08-01', 31); +---------------------------------------------------------+ | DATE_ADD('2018-08-01', INTERVAL 31 DAY) | +---------------------------------------------------------+ | 2018-09-01 | +---------------------------------------------------------+ 1 row in set (0.00 sec) This function adds 31 days to the given date i.e. ‘2018-08-01’ and returns the resultant date i.e. ‘2018-09-01’. This function adds the two expressions exp1 and exp2 and displays the result. In this case, exp1 can be a datetime or time expression and exp2 is a time expression. For example: sql> SELECT ADDTIME('2018-08-01 23:59:59.999999','1 1:1:1.000002'); +---------------------------------------------------------+ |ADDTIME('2018-08-01 23:59:59.999999','1 1:1:1.000002') | +---------------------------------------------------------+ | 2018-08-02 01:01:01.000001 | +---------------------------------------------------------+ 1 row in set (0.00 sec) The time '1 1:1:1.000002' is added to the datetime function '2018-08-01 23:59:59.999999' to give the resultant value ‘2018-08-02 01:01:01.000001’ This returns the current date of the system in the YYYY-MM-DD format. For example − sql> SELECT CURDATE(); +---------------------------------------------------------+ | CURDATE() | +---------------------------------------------------------+ | 2018-08-01 | +---------------------------------------------------------+ 1 row in set (0.00 sec) This function returns the current date i.e. ‘2018-08-01’ This returns the current time of the system from the current time zone in the format HH:MM:SS. For example − sql> SELECT CURTIME(); +---------------------------------------------------------+ | CURTIME() | +---------------------------------------------------------+ | 10:56:35 | +---------------------------------------------------------+ 1 row in set (0.00 sec) This function returns the current time i.e ‘10:56:35’ For the given date, this function returns the corresponding day of the week. For example − sql> SELECT DAYNAME('2018-08-01'); +---------------------------------------------------------+ | DAYNAME('2018-08-01') | +---------------------------------------------------------+ | Wednesday | +---------------------------------------------------------+ 1 row in set (0.00 sec) For the date '2018-08-01’, this function returns the day of the week i.e. Wednesday. For the given date, it returns the day of the month the date is on. The value of day of the month ranges from 1 to 31. For example − sql> SELECT DAYOFMONTH('2018-02-15'); +---------------------------------------------------------+ | DAYOFMONTH('2018-02-15') | +---------------------------------------------------------+ | 15 | +---------------------------------------------------------+ 1 row in set (0.00 sec) This returns the day of the month '2018-02-15' falls on i.e 15. For the given date, it returns the day of the week the date is on. The value of day of the week ranges from 1 to 7 (Sunday is 1 and Saturday is 7). For example − sql> SELECT DAYOFWEEK('2018-02-15'); +---------------------------------------------------------+ |DAYOFWEEK('2018-02-15') | +---------------------------------------------------------+ | 5 | +---------------------------------------------------------+ 1 row in set (0.00 sec) This returns the day of the week '2018-02-15' falls on i.e 5. For the given date, it returns the day of the year the date is on. The value of day of the year ranges from 1 to 366. For example − sql> SELECT DAYOFYEAR('2018-02-15'); +---------------------------------------------------------+ | DAYOFYEAR('2018-02-15') | +---------------------------------------------------------+ | 46 | +---------------------------------------------------------+ 1 row in set (0.00 sec) This returns the day of the year '2018-02-15' falls on i.e 46. It returns the month value for the corresponding date. The range of the month is from 1 to 12. For example − sql> SELECT MONTH('2018-08-01'); +---------------------------------------------------------+ | MONTH('2018-08-01') | +---------------------------------------------------------+ | 8 | +---------------------------------------------------------+ 1 row in set (0.00 sec) This returns the month number for '2018-08-01' which is 8. This function displays the time part of a time or date time expression in the form of a string. For example − sql> SELECT TIME('2018-08-01 11:33:25'); +---------------------------------------------------------+ | TIME('2018-08-01 11:33:25') | +---------------------------------------------------------+ | 11:33:25 | +---------------------------------------------------------+ 1 row in set (0.00 sec) This displays the time part of '2018-08-01 11:33:25' in the form of a string.
[ { "code": null, "e": 1172, "s": 1062, "text": "The date and time functions in DBMS are quite useful to manipulate and store values related to date and time." }, { "code": null, "e": 1227, "s": 1172, "text": "The different date and time functions are as follows −" }, { "code": null, "e": 1360, "s": 1227, "text": "The numbers of days in integer form (DAYS) is added to the specified date. This is the value returned by the function. For example −" }, { "code": null, "e": 1722, "s": 1360, "text": "sql> SELECT ADDDATE('2018-08-01', 31);\n+---------------------------------------------------------+\n| DATE_ADD('2018-08-01', INTERVAL 31 DAY) |\n+---------------------------------------------------------+\n| 2018-09-01 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 1835, "s": 1722, "text": "This function adds 31 days to the given date i.e. ‘2018-08-01’ and returns the resultant date i.e. ‘2018-09-01’." }, { "code": null, "e": 2013, "s": 1835, "text": "This function adds the two expressions exp1 and exp2 and displays the result. In this case, exp1 can be a datetime or time expression and exp2 is a time expression. For example:" }, { "code": null, "e": 2374, "s": 2013, "text": "sql> SELECT ADDTIME('2018-08-01 23:59:59.999999','1 1:1:1.000002');\n+---------------------------------------------------------+\n|ADDTIME('2018-08-01 23:59:59.999999','1 1:1:1.000002') |\n+---------------------------------------------------------+\n| 2018-08-02 01:01:01.000001 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 2520, "s": 2374, "text": "The time '1 1:1:1.000002' is added to the datetime function '2018-08-01 23:59:59.999999' to give the resultant value ‘2018-08-02 01:01:01.000001’" }, { "code": null, "e": 2604, "s": 2520, "text": "This returns the current date of the system in the YYYY-MM-DD format. For example −" }, { "code": null, "e": 2949, "s": 2604, "text": "sql> SELECT CURDATE();\n+---------------------------------------------------------+\n| CURDATE() |\n+---------------------------------------------------------+\n| 2018-08-01 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 3006, "s": 2949, "text": "This function returns the current date i.e. ‘2018-08-01’" }, { "code": null, "e": 3115, "s": 3006, "text": "This returns the current time of the system from the current time zone in the format HH:MM:SS. For example −" }, { "code": null, "e": 3461, "s": 3115, "text": "sql> SELECT CURTIME();\n+---------------------------------------------------------+\n| CURTIME() |\n+---------------------------------------------------------+\n| 10:56:35 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 3515, "s": 3461, "text": "This function returns the current time i.e ‘10:56:35’" }, { "code": null, "e": 3606, "s": 3515, "text": "For the given date, this function returns the corresponding day of the week. For example −" }, { "code": null, "e": 3965, "s": 3606, "text": "sql> SELECT DAYNAME('2018-08-01');\n+---------------------------------------------------------+\n| DAYNAME('2018-08-01') |\n+---------------------------------------------------------+\n| Wednesday |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 4050, "s": 3965, "text": "For the date '2018-08-01’, this function returns the day of the week i.e. Wednesday." }, { "code": null, "e": 4183, "s": 4050, "text": "For the given date, it returns the day of the month the date is on. The value of day of the month ranges from 1 to 31. For example −" }, { "code": null, "e": 4544, "s": 4183, "text": "sql> SELECT DAYOFMONTH('2018-02-15');\n+---------------------------------------------------------+\n| DAYOFMONTH('2018-02-15') |\n+---------------------------------------------------------+\n| 15 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 4608, "s": 4544, "text": "This returns the day of the month '2018-02-15' falls on i.e 15." }, { "code": null, "e": 4770, "s": 4608, "text": "For the given date, it returns the day of the week the date is on. The value of day of the week ranges from 1 to 7 (Sunday is 1 and Saturday is 7). For example −" }, { "code": null, "e": 5044, "s": 4770, "text": "sql> SELECT DAYOFWEEK('2018-02-15');\n+---------------------------------------------------------+\n|DAYOFWEEK('2018-02-15') |\n+---------------------------------------------------------+\n| 5 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 5106, "s": 5044, "text": "This returns the day of the week '2018-02-15' falls on i.e 5." }, { "code": null, "e": 5238, "s": 5106, "text": "For the given date, it returns the day of the year the date is on. The value of day of the year ranges from 1 to 366. For example −" }, { "code": null, "e": 5598, "s": 5238, "text": "sql> SELECT DAYOFYEAR('2018-02-15');\n+---------------------------------------------------------+\n| DAYOFYEAR('2018-02-15') |\n+---------------------------------------------------------+\n| 46 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 5661, "s": 5598, "text": "This returns the day of the year '2018-02-15' falls on i.e 46." }, { "code": null, "e": 5770, "s": 5661, "text": "It returns the month value for the corresponding date. The range of the month is from 1 to 12. For example −" }, { "code": null, "e": 6037, "s": 5770, "text": "sql> SELECT MONTH('2018-08-01');\n+---------------------------------------------------------+\n| MONTH('2018-08-01') |\n+---------------------------------------------------------+\n| 8 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 6096, "s": 6037, "text": "This returns the month number for '2018-08-01' which is 8." }, { "code": null, "e": 6206, "s": 6096, "text": "This function displays the time part of a time or date time expression in the form of a string. For example −" }, { "code": null, "e": 6571, "s": 6206, "text": "sql> SELECT TIME('2018-08-01 11:33:25');\n+---------------------------------------------------------+\n| TIME('2018-08-01 11:33:25') |\n+---------------------------------------------------------+\n| 11:33:25 |\n+---------------------------------------------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 6649, "s": 6571, "text": "This displays the time part of '2018-08-01 11:33:25' in the form of a string." } ]
Python Program to Find All Connected Components using DFS in an Undirected Graph
When it is required to find all the connected components using depth first search in an undirected graph, a class is defined that contains methods to initialize values, perform depth first search traversal, find the connected components, add nodes to the graph and so on. The instance of the class can be created and the methods can be accessed and operations and be performed on it. Below is a demonstration of the same − Live Demo class Graph_struct: def __init__(self, V): self.V = V self.adj = [[] for i in range(V)] def DFS_Utililty(self, temp, v, visited): visited[v] = True temp.append(v) for i in self.adj[v]: if visited[i] == False: temp = self.DFS_Utililty(temp, i, visited) return temp def add_edge(self, v, w): self.adj[v].append(w) self.adj[w].append(v) def connected_components(self): visited = [] conn_compnent = [] for i in range(self.V): visited.append(False) for v in range(self.V): if visited[v] == False: temp = [] conn_compnent.append(self.DFS_Utililty(temp, v, visited)) return conn_compnent my_instance = Graph_struct(5) my_instance.add_edge(1, 0) my_instance.add_edge(2, 3) my_instance.add_edge(3, 0) print("1-->0") print("2-->3") print("3-->0") conn_comp = my_instance.connected_components() print("The connected components are :") print(conn_comp) 1-->0 2-->3 3-->0 The connected components are : [[0, 1, 3, 2], [4]] A class named ‘Graph_struct’ is defined. A class named ‘Graph_struct’ is defined. A method named ‘add_edge’ is defined that helps add elements to the tree. A method named ‘add_edge’ is defined that helps add elements to the tree. The ‘DFS_Utility’ method is defined that helps traverse the tree using depth first search approach. The ‘DFS_Utility’ method is defined that helps traverse the tree using depth first search approach. A method named ‘connected_components’ is defined, that helps determine the nodes that are connected to each other. A method named ‘connected_components’ is defined, that helps determine the nodes that are connected to each other. An instance of the class is created, and the methods are called on it. An instance of the class is created, and the methods are called on it. The node are displayed on the console. The node are displayed on the console. The connected components are displayed as output on the console. The connected components are displayed as output on the console.
[ { "code": null, "e": 1446, "s": 1062, "text": "When it is required to find all the connected components using depth first search in an undirected graph, a class is defined that contains methods to initialize values, perform depth first search traversal, find the connected components, add nodes to the graph and so on. The instance of the class can be created and the methods can be accessed and operations and be performed on it." }, { "code": null, "e": 1485, "s": 1446, "text": "Below is a demonstration of the same −" }, { "code": null, "e": 1496, "s": 1485, "text": " Live Demo" }, { "code": null, "e": 2497, "s": 1496, "text": "class Graph_struct:\n def __init__(self, V):\n self.V = V\n self.adj = [[] for i in range(V)]\n\n def DFS_Utililty(self, temp, v, visited):\n\n visited[v] = True\n\n temp.append(v)\n\n for i in self.adj[v]:\n if visited[i] == False:\n temp = self.DFS_Utililty(temp, i, visited)\n return temp\n\n def add_edge(self, v, w):\n self.adj[v].append(w)\n self.adj[w].append(v)\n\n def connected_components(self):\n visited = []\n conn_compnent = []\n for i in range(self.V):\n visited.append(False)\n for v in range(self.V):\n if visited[v] == False:\n temp = []\n conn_compnent.append(self.DFS_Utililty(temp, v, visited))\n return conn_compnent\n\nmy_instance = Graph_struct(5)\nmy_instance.add_edge(1, 0)\nmy_instance.add_edge(2, 3)\nmy_instance.add_edge(3, 0)\nprint(\"1-->0\")\nprint(\"2-->3\")\nprint(\"3-->0\")\nconn_comp = my_instance.connected_components()\nprint(\"The connected components are :\")\nprint(conn_comp)" }, { "code": null, "e": 2566, "s": 2497, "text": "1-->0\n2-->3\n3-->0\nThe connected components are :\n[[0, 1, 3, 2], [4]]" }, { "code": null, "e": 2607, "s": 2566, "text": "A class named ‘Graph_struct’ is defined." }, { "code": null, "e": 2648, "s": 2607, "text": "A class named ‘Graph_struct’ is defined." }, { "code": null, "e": 2722, "s": 2648, "text": "A method named ‘add_edge’ is defined that helps add elements to the tree." }, { "code": null, "e": 2796, "s": 2722, "text": "A method named ‘add_edge’ is defined that helps add elements to the tree." }, { "code": null, "e": 2896, "s": 2796, "text": "The ‘DFS_Utility’ method is defined that helps traverse the tree using depth first search approach." }, { "code": null, "e": 2996, "s": 2896, "text": "The ‘DFS_Utility’ method is defined that helps traverse the tree using depth first search approach." }, { "code": null, "e": 3111, "s": 2996, "text": "A method named ‘connected_components’ is defined, that helps determine the nodes that are connected to each other." }, { "code": null, "e": 3226, "s": 3111, "text": "A method named ‘connected_components’ is defined, that helps determine the nodes that are connected to each other." }, { "code": null, "e": 3297, "s": 3226, "text": "An instance of the class is created, and the methods are called on it." }, { "code": null, "e": 3368, "s": 3297, "text": "An instance of the class is created, and the methods are called on it." }, { "code": null, "e": 3407, "s": 3368, "text": "The node are displayed on the console." }, { "code": null, "e": 3446, "s": 3407, "text": "The node are displayed on the console." }, { "code": null, "e": 3511, "s": 3446, "text": "The connected components are displayed as output on the console." }, { "code": null, "e": 3576, "s": 3511, "text": "The connected components are displayed as output on the console." } ]
Handling a thread's exception in the caller thread in Python - GeeksforGeeks
22 Nov, 2021 Multithreading in Python can be achieved by using the threading library. For invoking a thread, the caller thread creates a thread object and calls the start method on it. Once the join method is called, that initiates its execution and executes the run method of the class object. For Exception handling, try-except blocks are used that catch the exceptions raised across the try block and are handled accordingly in the except block Example: Python3 # Importing the modulesimport threadingimport sys # Custom Thread Classclass MyThread(threading.Thread): def someFunction(self): print("Hello World") def run(self): self.someFunction() def join(self): threading.Thread.join(self) # Driver functiondef main(): t = MyThread() t.start() t.join() # Driver codeif __name__ == '__main__': main() Output: Hello World For catching and handling a thread’s exception in the caller thread we use a variable that stores the raised exception (if any) in the called thread, and when the called thread is joined, the join function checks whether the value of exc is None, if it is then no exception is generated, otherwise, the generated exception that is stored in exc is raised again. This happens in the caller thread and hence can be handled in the caller thread itself. Example: The example creates a thread t of type MyThread, the run() method for the thread calls the someFunction() method, that raises the MyException, thus whenever the thread is run, it will raise an exception. To catch the exception in the caller thread we maintain a separate variable exc, which is set to the exception raised when the called thread raises an exception. This exc is finally checked in the join() method and if is not None, then join simply raises the same exception. Thus, the caught exception is raised in the caller thread, as join returns in the caller thread (Here The Main Thread) and is thus handled correspondingly. Python3 # Importing the modulesimport threadingimport sys # Custom Exception Classclass MyException(Exception): pass # Custom Thread Classclass MyThread(threading.Thread): # Function that raises the custom exception def someFunction(self): name = threading.current_thread().name raise MyException("An error in thread "+ name) def run(self): # Variable that stores the exception, if raised by someFunction self.exc = None try: self.someFunction() except BaseException as e: self.exc = e def join(self): threading.Thread.join(self) # Since join() returns in caller thread # we re-raise the caught exception # if any was caught if self.exc: raise self.exc # Driver functiondef main(): # Create a new Thread t # Here Main is the caller thread t = MyThread() t.start() # Exception handled in Caller thread try: t.join() except Exception as e: print("Exception Handled in Main, Details of the Exception:", e) # Driver codeif __name__ == '__main__': main() Output: Exception Handled in Main, Details of the Exception: An error in thread Thread-1 anikaseth98 Python-threading Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install PIP on Windows ? Selecting rows in pandas DataFrame based on conditions How to drop one or multiple columns in Pandas Dataframe Python | Get unique values from a list How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | os.path.join() method Defaultdict in Python Create a directory in Python Python Classes and Objects
[ { "code": null, "e": 24238, "s": 24210, "text": "\n22 Nov, 2021" }, { "code": null, "e": 24521, "s": 24238, "text": "Multithreading in Python can be achieved by using the threading library. For invoking a thread, the caller thread creates a thread object and calls the start method on it. Once the join method is called, that initiates its execution and executes the run method of the class object. " }, { "code": null, "e": 24674, "s": 24521, "text": "For Exception handling, try-except blocks are used that catch the exceptions raised across the try block and are handled accordingly in the except block" }, { "code": null, "e": 24683, "s": 24674, "text": "Example:" }, { "code": null, "e": 24691, "s": 24683, "text": "Python3" }, { "code": "# Importing the modulesimport threadingimport sys # Custom Thread Classclass MyThread(threading.Thread): def someFunction(self): print(\"Hello World\") def run(self): self.someFunction() def join(self): threading.Thread.join(self) # Driver functiondef main(): t = MyThread() t.start() t.join() # Driver codeif __name__ == '__main__': main()", "e": 25074, "s": 24691, "text": null }, { "code": null, "e": 25082, "s": 25074, "text": "Output:" }, { "code": null, "e": 25094, "s": 25082, "text": "Hello World" }, { "code": null, "e": 25544, "s": 25094, "text": "For catching and handling a thread’s exception in the caller thread we use a variable that stores the raised exception (if any) in the called thread, and when the called thread is joined, the join function checks whether the value of exc is None, if it is then no exception is generated, otherwise, the generated exception that is stored in exc is raised again. This happens in the caller thread and hence can be handled in the caller thread itself." }, { "code": null, "e": 26188, "s": 25544, "text": "Example: The example creates a thread t of type MyThread, the run() method for the thread calls the someFunction() method, that raises the MyException, thus whenever the thread is run, it will raise an exception. To catch the exception in the caller thread we maintain a separate variable exc, which is set to the exception raised when the called thread raises an exception. This exc is finally checked in the join() method and if is not None, then join simply raises the same exception. Thus, the caught exception is raised in the caller thread, as join returns in the caller thread (Here The Main Thread) and is thus handled correspondingly." }, { "code": null, "e": 26196, "s": 26188, "text": "Python3" }, { "code": "# Importing the modulesimport threadingimport sys # Custom Exception Classclass MyException(Exception): pass # Custom Thread Classclass MyThread(threading.Thread): # Function that raises the custom exception def someFunction(self): name = threading.current_thread().name raise MyException(\"An error in thread \"+ name) def run(self): # Variable that stores the exception, if raised by someFunction self.exc = None try: self.someFunction() except BaseException as e: self.exc = e def join(self): threading.Thread.join(self) # Since join() returns in caller thread # we re-raise the caught exception # if any was caught if self.exc: raise self.exc # Driver functiondef main(): # Create a new Thread t # Here Main is the caller thread t = MyThread() t.start() # Exception handled in Caller thread try: t.join() except Exception as e: print(\"Exception Handled in Main, Details of the Exception:\", e) # Driver codeif __name__ == '__main__': main()", "e": 27338, "s": 26196, "text": null }, { "code": null, "e": 27346, "s": 27338, "text": "Output:" }, { "code": null, "e": 27429, "s": 27346, "text": "Exception Handled in Main, Details of the Exception: An error in thread Thread-1 " }, { "code": null, "e": 27441, "s": 27429, "text": "anikaseth98" }, { "code": null, "e": 27458, "s": 27441, "text": "Python-threading" }, { "code": null, "e": 27465, "s": 27458, "text": "Python" }, { "code": null, "e": 27563, "s": 27465, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27572, "s": 27563, "text": "Comments" }, { "code": null, "e": 27585, "s": 27572, "text": "Old Comments" }, { "code": null, "e": 27617, "s": 27585, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27672, "s": 27617, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 27728, "s": 27672, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27767, "s": 27728, "text": "Python | Get unique values from a list" }, { "code": null, "e": 27809, "s": 27767, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27851, "s": 27809, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27882, "s": 27851, "text": "Python | os.path.join() method" }, { "code": null, "e": 27904, "s": 27882, "text": "Defaultdict in Python" }, { "code": null, "e": 27933, "s": 27904, "text": "Create a directory in Python" } ]
Standard I/O in Rust - GeeksforGeeks
17 Mar, 2021 In this article, we will explore the standard input and standard output in the Rust programming language. Generally, the standard input is provided through the keyboard and the standard output displays values in the console. There are two core traits in Rust, around which the Rust’s standard Input and Output are featured. They provide an interface for feeding in input and displaying output. These two traits are listed below: Read Traits Write Traits Let’s explore them in detail. Reading input from an input device in the form of Bytes is done by Rust components called Readers. The read_line() function is used to read data, one line at a time from an input stream or file. Take a look at the below example: Example: Rust use std::io; fn main() { println!("Enter a name:"); let mut guess = String::new(); io::stdin().read_line(&mut guess).expect("failed to readline"); print!("You entered {}", guess);} Output: Same as in other programming languages, we use std::io(standard input/output) library to get input using the read_line function similar to scanf() in C language. The let and mut are keywords to create a mutable variable that can hold the given string. The Writers in Rust are programs that can write data to a file or an output stream in bytes. The write() method is used for this purpose. Take a look at the below example. Example: Rust use std::io::Write;fn main() { let var1 = std::io::stdout().write("Geeksforgeeks ".as_bytes()).unwrap(); let var2 = std::io::stdout().write( String::from("is the best.").as_bytes()).unwrap(); std::io::stdout().write(format!( "\n{} bytes of data has been written!",(var1+var2)).as_bytes()).unwrap();} Output: Geeksforgeeks is the best. 26 bytes of data has been written! In the above example, the write() function is applied to the standard output stream returned by the stdout() standard library function. An enum is returned by the write() method which is further extracted by the unwrap() function to display the result. The print function is one of the most important and most used to print any output in almost all major programming languages. Rust has and print!() and println!() function similar to printf in C language. We will see how we can print output in Rust. The main difference between Rust’s print! & println! is that the print! outputs in the same line whereas println! give output in a new line. The print macro function of the program is almost similar to cout in C++ without endl (or) \n. An example of print is given below Example: Rust fn main() { // printed in new line print!("Hello, Geeks"); print!(" Welcome to GeeksForGeeks");} Output: Hello, Geeks Welcome to GeeksForGeeks The println is the macro prints to the standard output, with a newline. We can use println! only for the primary output of your program. Example: Rust fn main() { // printed in new line println!("Hello, Geeks"); println!("Welcome to GeeksForGeeks");} Output: Hello, Geeks Welcome to GeeksForGeeks Same as in other programming languages, we use std::io(standard input/output) library to get input using the read_line function similar to scanf() in C language. The let and mut are keywords to create a mutable variable that can hold the given string. Rust use std::io; fn main() { println!("Enter a name:"); let mut guess = String::new(); io::stdin().read_line(&mut guess).expect("failed to readline"); print!("You entered {}", guess);} Output: Enter a name: geeksforgeeks You entered geeksforgeeks Command-line arguments are the values passed through the console to the program for processing. It’s similar to how you pass the parameter values to the main() function. The std::env::args() is used to return the command line arguments. Take a look at the below example. Example: In this example, we will be using command-line arguments to pass values to the main function of the program. Rust use std:: env; fn main() { let args: Vec<String> = env::args().collect(); for argument in args.iter() { println!("{}", argument); }} Let’s check what we did in the above example. First, we need to use the environment module using std:: env. Then we create a new vector of strings. Now, this vector just reads each of our arguments. Meaning we can just say the type of the vector is a string that equals a variable and args.collect() function is used to collect the argument from the command line. Here we made a new vector that holds strings this is equal to all the command-line arguments that are collected. Now use the below command in your shell to activate Rust script: cargo run Then pass in the argument as follows: cargo run YOUR_ARGUMENT Here we will pass the string “dom” for the sake of example. Output: kushwanthreddy Rust-basics Rust Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Rust - Creating a Library Rust - Casting Rust - Concept of Structures Rust - Comments Rust - For and Range Rust - Box Smart Pointer Rust - Recoverable Errors Rust - Concept of Smart Pointers Rust - Concept of Ownership Scalar Datatypes in Rust
[ { "code": null, "e": 23550, "s": 23522, "text": "\n17 Mar, 2021" }, { "code": null, "e": 23776, "s": 23550, "text": "In this article, we will explore the standard input and standard output in the Rust programming language. Generally, the standard input is provided through the keyboard and the standard output displays values in the console. " }, { "code": null, "e": 23980, "s": 23776, "text": "There are two core traits in Rust, around which the Rust’s standard Input and Output are featured. They provide an interface for feeding in input and displaying output. These two traits are listed below:" }, { "code": null, "e": 23992, "s": 23980, "text": "Read Traits" }, { "code": null, "e": 24005, "s": 23992, "text": "Write Traits" }, { "code": null, "e": 24035, "s": 24005, "text": "Let’s explore them in detail." }, { "code": null, "e": 24264, "s": 24035, "text": "Reading input from an input device in the form of Bytes is done by Rust components called Readers. The read_line() function is used to read data, one line at a time from an input stream or file. Take a look at the below example:" }, { "code": null, "e": 24273, "s": 24264, "text": "Example:" }, { "code": null, "e": 24278, "s": 24273, "text": "Rust" }, { "code": "use std::io; fn main() { println!(\"Enter a name:\"); let mut guess = String::new(); io::stdin().read_line(&mut guess).expect(\"failed to readline\"); print!(\"You entered {}\", guess);}", "e": 24473, "s": 24278, "text": null }, { "code": null, "e": 24481, "s": 24473, "text": "Output:" }, { "code": null, "e": 24733, "s": 24481, "text": "Same as in other programming languages, we use std::io(standard input/output) library to get input using the read_line function similar to scanf() in C language. The let and mut are keywords to create a mutable variable that can hold the given string." }, { "code": null, "e": 24905, "s": 24733, "text": "The Writers in Rust are programs that can write data to a file or an output stream in bytes. The write() method is used for this purpose. Take a look at the below example." }, { "code": null, "e": 24914, "s": 24905, "text": "Example:" }, { "code": null, "e": 24919, "s": 24914, "text": "Rust" }, { "code": "use std::io::Write;fn main() { let var1 = std::io::stdout().write(\"Geeksforgeeks \".as_bytes()).unwrap(); let var2 = std::io::stdout().write( String::from(\"is the best.\").as_bytes()).unwrap(); std::io::stdout().write(format!( \"\\n{} bytes of data has been written!\",(var1+var2)).as_bytes()).unwrap();}", "e": 25233, "s": 24919, "text": null }, { "code": null, "e": 25241, "s": 25233, "text": "Output:" }, { "code": null, "e": 25303, "s": 25241, "text": "Geeksforgeeks is the best.\n26 bytes of data has been written!" }, { "code": null, "e": 25556, "s": 25303, "text": "In the above example, the write() function is applied to the standard output stream returned by the stdout() standard library function. An enum is returned by the write() method which is further extracted by the unwrap() function to display the result." }, { "code": null, "e": 25946, "s": 25556, "text": "The print function is one of the most important and most used to print any output in almost all major programming languages. Rust has and print!() and println!() function similar to printf in C language. We will see how we can print output in Rust. The main difference between Rust’s print! & println! is that the print! outputs in the same line whereas println! give output in a new line." }, { "code": null, "e": 26076, "s": 25946, "text": "The print macro function of the program is almost similar to cout in C++ without endl (or) \\n. An example of print is given below" }, { "code": null, "e": 26085, "s": 26076, "text": "Example:" }, { "code": null, "e": 26090, "s": 26085, "text": "Rust" }, { "code": "fn main() { // printed in new line print!(\"Hello, Geeks\"); print!(\" Welcome to GeeksForGeeks\");}", "e": 26192, "s": 26090, "text": null }, { "code": null, "e": 26200, "s": 26192, "text": "Output:" }, { "code": null, "e": 26238, "s": 26200, "text": "Hello, Geeks Welcome to GeeksForGeeks" }, { "code": null, "e": 26375, "s": 26238, "text": "The println is the macro prints to the standard output, with a newline. We can use println! only for the primary output of your program." }, { "code": null, "e": 26384, "s": 26375, "text": "Example:" }, { "code": null, "e": 26389, "s": 26384, "text": "Rust" }, { "code": "fn main() { // printed in new line println!(\"Hello, Geeks\"); println!(\"Welcome to GeeksForGeeks\");}", "e": 26492, "s": 26389, "text": null }, { "code": null, "e": 26500, "s": 26492, "text": "Output:" }, { "code": null, "e": 26538, "s": 26500, "text": "Hello, Geeks\nWelcome to GeeksForGeeks" }, { "code": null, "e": 26790, "s": 26538, "text": "Same as in other programming languages, we use std::io(standard input/output) library to get input using the read_line function similar to scanf() in C language. The let and mut are keywords to create a mutable variable that can hold the given string." }, { "code": null, "e": 26795, "s": 26790, "text": "Rust" }, { "code": "use std::io; fn main() { println!(\"Enter a name:\"); let mut guess = String::new(); io::stdin().read_line(&mut guess).expect(\"failed to readline\"); print!(\"You entered {}\", guess);}", "e": 26984, "s": 26795, "text": null }, { "code": null, "e": 26992, "s": 26984, "text": "Output:" }, { "code": null, "e": 27046, "s": 26992, "text": "Enter a name: geeksforgeeks\nYou entered geeksforgeeks" }, { "code": null, "e": 27317, "s": 27046, "text": "Command-line arguments are the values passed through the console to the program for processing. It’s similar to how you pass the parameter values to the main() function. The std::env::args() is used to return the command line arguments. Take a look at the below example." }, { "code": null, "e": 27328, "s": 27319, "text": "Example:" }, { "code": null, "e": 27437, "s": 27328, "text": "In this example, we will be using command-line arguments to pass values to the main function of the program." }, { "code": null, "e": 27442, "s": 27437, "text": "Rust" }, { "code": "use std:: env; fn main() { let args: Vec<String> = env::args().collect(); for argument in args.iter() { println!(\"{}\", argument); }}", "e": 27587, "s": 27442, "text": null }, { "code": null, "e": 28065, "s": 27587, "text": "Let’s check what we did in the above example. First, we need to use the environment module using std:: env. Then we create a new vector of strings. Now, this vector just reads each of our arguments. Meaning we can just say the type of the vector is a string that equals a variable and args.collect() function is used to collect the argument from the command line. Here we made a new vector that holds strings this is equal to all the command-line arguments that are collected. " }, { "code": null, "e": 28130, "s": 28065, "text": "Now use the below command in your shell to activate Rust script:" }, { "code": null, "e": 28140, "s": 28130, "text": "cargo run" }, { "code": null, "e": 28178, "s": 28140, "text": "Then pass in the argument as follows:" }, { "code": null, "e": 28202, "s": 28178, "text": "cargo run YOUR_ARGUMENT" }, { "code": null, "e": 28262, "s": 28202, "text": "Here we will pass the string “dom” for the sake of example." }, { "code": null, "e": 28270, "s": 28262, "text": "Output:" }, { "code": null, "e": 28285, "s": 28270, "text": "kushwanthreddy" }, { "code": null, "e": 28297, "s": 28285, "text": "Rust-basics" }, { "code": null, "e": 28302, "s": 28297, "text": "Rust" }, { "code": null, "e": 28400, "s": 28302, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28409, "s": 28400, "text": "Comments" }, { "code": null, "e": 28422, "s": 28409, "text": "Old Comments" }, { "code": null, "e": 28448, "s": 28422, "text": "Rust - Creating a Library" }, { "code": null, "e": 28463, "s": 28448, "text": "Rust - Casting" }, { "code": null, "e": 28492, "s": 28463, "text": "Rust - Concept of Structures" }, { "code": null, "e": 28508, "s": 28492, "text": "Rust - Comments" }, { "code": null, "e": 28529, "s": 28508, "text": "Rust - For and Range" }, { "code": null, "e": 28554, "s": 28529, "text": "Rust - Box Smart Pointer" }, { "code": null, "e": 28580, "s": 28554, "text": "Rust - Recoverable Errors" }, { "code": null, "e": 28613, "s": 28580, "text": "Rust - Concept of Smart Pointers" }, { "code": null, "e": 28641, "s": 28613, "text": "Rust - Concept of Ownership" } ]
How to count SQL table columns using Python?
It may be required to count the number of columns present in a SQL table. This is done using count(*) function with information_schema.columns and the WHERE clause. The WHERE clause is used to specify the name of the table whose columns are to be counted. SELECT COUNT(*) FROM information_schema.columns WHERE table_name= ‘your_table_name’ import MySQL connector import MySQL connector establish connection with the connector using connect() establish connection with the connector using connect() create the cursor object using cursor() method create the cursor object using cursor() method create a query using the appropriate mysql statements create a query using the appropriate mysql statements execute the SQL query using execute() method execute the SQL query using execute() method close the connection close the connection Suppose we have a table named “Students” as below − +----------+---------+-----------+------------+ | Name | Class | City | Marks | +----------+---------+-----------+------------+ | Karan | 4 | Amritsar | 95 | | Sahil | 6 | Amritsar | 93 | | Kriti | 3 | Batala | 88 | | Khushi | 9 | Delhi | 90 | | Kirat | 5 | Delhi | 85 | +----------+---------+-----------+------------+ We want to count the number of columns in the above table. import mysql.connector db=mysql.connector.connect(host="your host", user="your username", password="your password",database="database_name") cursor=db.cursor() query="SELECT COUNT(*) FROM information_schema.columns WHERE table_name= "Students" " cursor.execute(query) col=cursor.fetchall() for x in col: print(x) db.close() The above returns the number of columns present in the table named “Students”. 4
[ { "code": null, "e": 1136, "s": 1062, "text": "It may be required to count the number of columns present in a SQL table." }, { "code": null, "e": 1318, "s": 1136, "text": "This is done using count(*) function with information_schema.columns and the WHERE clause. The WHERE clause is used to specify the name of the table whose columns are to be counted." }, { "code": null, "e": 1402, "s": 1318, "text": "SELECT COUNT(*) FROM information_schema.columns WHERE table_name= ‘your_table_name’" }, { "code": null, "e": 1425, "s": 1402, "text": "import MySQL connector" }, { "code": null, "e": 1448, "s": 1425, "text": "import MySQL connector" }, { "code": null, "e": 1504, "s": 1448, "text": "establish connection with the connector using connect()" }, { "code": null, "e": 1560, "s": 1504, "text": "establish connection with the connector using connect()" }, { "code": null, "e": 1607, "s": 1560, "text": "create the cursor object using cursor() method" }, { "code": null, "e": 1654, "s": 1607, "text": "create the cursor object using cursor() method" }, { "code": null, "e": 1708, "s": 1654, "text": "create a query using the appropriate mysql statements" }, { "code": null, "e": 1762, "s": 1708, "text": "create a query using the appropriate mysql statements" }, { "code": null, "e": 1807, "s": 1762, "text": "execute the SQL query using execute() method" }, { "code": null, "e": 1852, "s": 1807, "text": "execute the SQL query using execute() method" }, { "code": null, "e": 1873, "s": 1852, "text": "close the connection" }, { "code": null, "e": 1894, "s": 1873, "text": "close the connection" }, { "code": null, "e": 1946, "s": 1894, "text": "Suppose we have a table named “Students” as below −" }, { "code": null, "e": 2378, "s": 1946, "text": "+----------+---------+-----------+------------+\n| Name | Class | City | Marks |\n+----------+---------+-----------+------------+\n| Karan | 4 | Amritsar | 95 |\n| Sahil | 6 | Amritsar | 93 |\n| Kriti | 3 | Batala | 88 |\n| Khushi | 9 | Delhi | 90 |\n| Kirat | 5 | Delhi | 85 |\n+----------+---------+-----------+------------+" }, { "code": null, "e": 2437, "s": 2378, "text": "We want to count the number of columns in the above table." }, { "code": null, "e": 2770, "s": 2437, "text": "import mysql.connector\n\ndb=mysql.connector.connect(host=\"your host\", user=\"your username\", password=\"your\npassword\",database=\"database_name\")\n\ncursor=db.cursor()\n\nquery=\"SELECT COUNT(*) FROM information_schema.columns WHERE table_name= \"Students\" \"\ncursor.execute(query)\n\ncol=cursor.fetchall()\n\nfor x in col:\n print(x)\n\ndb.close()" }, { "code": null, "e": 2849, "s": 2770, "text": "The above returns the number of columns present in the table named “Students”." }, { "code": null, "e": 2851, "s": 2849, "text": "4" } ]
Unity - Saving and Loading Scenes
At the end of the day, when you are done with a fair amount of work, you want to save your progress. In Unity, hitting Ctrl + S will not directly save your project. Everything in Unity happens in scenes. So does saving and loading; you must save your current work as a scene (.unity extension) in your assets. Let us try it out. If we hit Ctrl + S and give our scene a name, we will be presented with a new asset in our Assets region. This is the scene file. Now, let us try and create a new scene. To do so, right click in the Assets and go Create → Scene. Give your new scene a name and hit enter. In the Editor mode (when the game is not playing), scenes can be loaded into the editor by double-clicking them. Loading a scene with unsaved changes on your current one will prompt you to save or discard your changes. Importing images and having them stay still in your game is not really going to get you anywhere. It would make a nice picture frame, perhaps, but not a game. Scripting is imperative to making games in Unity. Scripting is the process of writing blocks of code that are attached like components to GameObjects in the scene. Scripting is one of the most powerful tools at your disposal, and it can make or break a good game. Scripting in Unity is done through either C# or Unity’s implementation of JavaScript, known as UnityScript (however, with the 2018 cycle, UnityScript is now beginning it’s deprecation phase, so it’s advised not to use it). For the purpose of this series, we will use C#. To create a new script, right-click in your Assets and go to Create → C# Script. You can also use the Assets tab in the top bar of the engine. When you create a new script, a new asset should show up. For the time being, leave the name as it is, and double-click it. Your default IDE should open up along with the script. Let us have a look at what it actually is. using System.Collections; using System.Collections.Generic; using UnityEngine; public class NewBehaviourScript : MonoBehaviour { // Use this for initialization void Start() { } // Update is called once per frame void Update() { } } You will see your script name as a class deriving from MonoBehaviour. What is MonoBehaviour? It is a vast library of classes and methods. It helps all the scripts in Unity derive from one way or the other. The more you write scripts in Unity the more you will realize how useful MonoBehaviour actually is. As we proceed, we have two private scripts that do not have any return types, namely the Start and Update methods. The Start method runs once for the first frame that the gameObject this is used on is active in the scene. The Update method runs every frame of the game after the Start method. Normally, games in Unity run at 60 FPS or frames per second, which means that the Update method is called 60 times per second while the object is active. Unity scripting allows you to take advantage of the entirety of the MonoBehaviour class, as well as core C# features such as generic collections, lambda expressions and XML parsing, to name a few. In the next lesson, we will write our first code! 119 Lectures 23.5 hours Raja Biswas 58 Lectures 10 hours Three Millennials 16 Lectures 1 hours Peter Jepson 23 Lectures 2.5 hours Zenva 21 Lectures 2 hours Zenva 43 Lectures 9.5 hours Raja Biswas Print Add Notes Bookmark this page
[ { "code": null, "e": 2380, "s": 2215, "text": "At the end of the day, when you are done with a fair amount of work, you want to save your progress. In Unity, hitting Ctrl + S will not directly save your project." }, { "code": null, "e": 2525, "s": 2380, "text": "Everything in Unity happens in scenes. So does saving and loading; you must save your current work as a scene (.unity extension) in your assets." }, { "code": null, "e": 2674, "s": 2525, "text": "Let us try it out. If we hit Ctrl + S and give our scene a name, we will be presented with a new asset in our Assets region. This is the scene file." }, { "code": null, "e": 2815, "s": 2674, "text": "Now, let us try and create a new scene. To do so, right click in the Assets and go Create → Scene. Give your new scene a name and hit enter." }, { "code": null, "e": 3034, "s": 2815, "text": "In the Editor mode (when the game is not playing), scenes can be loaded into the editor by double-clicking them. Loading a scene with unsaved changes on your current one will prompt you to save or discard your changes." }, { "code": null, "e": 3193, "s": 3034, "text": "Importing images and having them stay still in your game is not really going to get you anywhere. It would make a nice picture frame, perhaps, but not a game." }, { "code": null, "e": 3457, "s": 3193, "text": "Scripting is imperative to making games in Unity. Scripting is the process of writing blocks of code that are attached like components to GameObjects in the scene. Scripting is one of the most powerful tools at your disposal, and it can make or break a good game." }, { "code": null, "e": 3728, "s": 3457, "text": "Scripting in Unity is done through either C# or Unity’s implementation of JavaScript, known as UnityScript (however, with the 2018 cycle, UnityScript is now beginning it’s deprecation phase, so it’s advised not to use it). For the purpose of this series, we will use C#." }, { "code": null, "e": 3871, "s": 3728, "text": "To create a new script, right-click in your Assets and go to Create → C# Script. You can also use the Assets tab in the top bar of the engine." }, { "code": null, "e": 4093, "s": 3871, "text": "When you create a new script, a new asset should show up. For the time being, leave the name as it is, and double-click it. Your default IDE should open up along with the script. Let us have a look at what it actually is." }, { "code": null, "e": 4345, "s": 4093, "text": "using System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\npublic class NewBehaviourScript : MonoBehaviour {\n // Use this for initialization\n void Start() { \n }\n // Update is called once per frame\n void Update() {\n\n }\n}" }, { "code": null, "e": 4651, "s": 4345, "text": "You will see your script name as a class deriving from MonoBehaviour. What is MonoBehaviour? It is a vast library of classes and methods. It helps all the scripts in Unity derive from one way or the other. The more you write scripts in Unity the more you will realize how useful MonoBehaviour actually is." }, { "code": null, "e": 4873, "s": 4651, "text": "As we proceed, we have two private scripts that do not have any return types, namely the Start and Update methods. The Start method runs once for the first frame that the gameObject this is used on is active in the scene." }, { "code": null, "e": 5098, "s": 4873, "text": "The Update method runs every frame of the game after the Start method. Normally, games in Unity run at 60 FPS or frames per second, which means that the Update method is called 60 times per second while the object is active." }, { "code": null, "e": 5345, "s": 5098, "text": "Unity scripting allows you to take advantage of the entirety of the MonoBehaviour class, as well as core C# features such as generic collections, lambda expressions and XML parsing, to name a few. In the next lesson, we will write our first code!" }, { "code": null, "e": 5382, "s": 5345, "text": "\n 119 Lectures \n 23.5 hours \n" }, { "code": null, "e": 5395, "s": 5382, "text": " Raja Biswas" }, { "code": null, "e": 5429, "s": 5395, "text": "\n 58 Lectures \n 10 hours \n" }, { "code": null, "e": 5448, "s": 5429, "text": " Three Millennials" }, { "code": null, "e": 5481, "s": 5448, "text": "\n 16 Lectures \n 1 hours \n" }, { "code": null, "e": 5495, "s": 5481, "text": " Peter Jepson" }, { "code": null, "e": 5530, "s": 5495, "text": "\n 23 Lectures \n 2.5 hours \n" }, { "code": null, "e": 5537, "s": 5530, "text": " Zenva" }, { "code": null, "e": 5570, "s": 5537, "text": "\n 21 Lectures \n 2 hours \n" }, { "code": null, "e": 5577, "s": 5570, "text": " Zenva" }, { "code": null, "e": 5612, "s": 5577, "text": "\n 43 Lectures \n 9.5 hours \n" }, { "code": null, "e": 5625, "s": 5612, "text": " Raja Biswas" }, { "code": null, "e": 5632, "s": 5625, "text": " Print" }, { "code": null, "e": 5643, "s": 5632, "text": " Add Notes" } ]
Materialize - Grids
Materialize provides a 12 column fluid responsive grid. It uses the row and column style classes to define rows and columns respectively. Specifies a padding-less container to be used for responsive columns. This class is mandatory for responsive classes to be fully responsive. Specifies a column with sub-classes. col has several sub-classes meant for different types of screens. Following is a list of column-level styles for small screen devices, typically smartphones. s1 Defines 1 of 12 columns with width as 08.33% s2 Defines 2 of 12 columns with width as 16.66%. s3 Defines 3 of 12 columns with width as 25.00%. s4 Defines 4 of 12 columns with width as 33.33%. s12 Defines 12 of 12 columns with width as 100%. Default class for small screen phones. Following is a list of column-level styles for medium screen devices, typically tablets. m1 Defines 1 of 12 columns with width as 08.33% m2 Defines 2 of 12 columns with width as 16.66%. m3 Defines 3 of 12 columns with width as 25.00%. m4 Defines 4 of 12 columns with width as 33.33%. m12 Defines 12 of 12 columns with width as 100%. Default class for medium screen phones. Following is a list of column-level styles for large screen devices, typically laptops. l1 Defines 1 of 12 columns with width as 08.33% l2 Defines 2 of 12 columns with width as 16.66%. l3 Defines 3 of 12 columns with width as 25.00%. l4 Defines 4 of 12 columns with width as 33.33%. l12 Defines 12 of 12 columns with width as 100%. Default class for large screen devices. Each subclass determines the number of columns of the grid to be used based on the type of a device. Consider the following HTML snippet. <div class="row"> <div class="col s2 m4 l3"> <p>This text will use 2 columns on a small screen, 4 on a medium screen, and 3 on a large screen.</p> </div> </div> Default columns to be used are 12 on a device, if a sub-class is not mentioned in the class attribute of an HTML element. <!DOCTYPE html> <html> <head> <title>The Materialize Grids Example</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/css/materialize.min.css"> <script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/js/materialize.min.js"></script> </head> <body> <div class="teal"> <h2>Mobile First Design Demo</h2> <p>Resize the window to see the effect!</p> </div> <hr/> <div class="row"> <div class="col m1 grey center">1</div> <div class="col m1 center">2</div> <div class="col m1 grey center">3</div> <div class="col m1 center">4</div> <div class="col m1 grey center">5</div> <div class="col m1 center">6</div> <div class="col m1 center grey">7</div> <div class="col m1 center">8</div> <div class="col m1 center grey">9</div> <div class="col m1 center">10</div> <div class="col m1 center grey">11</div> <div class="col m1 center">12</div> </div> <div class="row"> <div class="col m4 l3 yellow"> <p>This text will use 12 columns on a small screen, 4 on a medium screen (m4), and 3 on a large screen (l3).</p> </div> <div class="col s4 m8 l9 grey"> <p>This text will use 4 columns on a small screen (s4), 8 on a medium screen (m8), and 9 on a large screen (l9).</p> </div> </div> </body> </html> Verify the output. Print Add Notes Bookmark this page
[ { "code": null, "e": 2243, "s": 2187, "text": "Materialize provides a 12 column fluid responsive grid." }, { "code": null, "e": 2325, "s": 2243, "text": "It uses the row and column style classes to define rows and columns respectively." }, { "code": null, "e": 2466, "s": 2325, "text": "Specifies a padding-less container to be used for responsive columns. This class is mandatory for responsive classes to be fully responsive." }, { "code": null, "e": 2503, "s": 2466, "text": "Specifies a column with sub-classes." }, { "code": null, "e": 2569, "s": 2503, "text": "col has several sub-classes meant for different types of screens." }, { "code": null, "e": 2661, "s": 2569, "text": "Following is a list of column-level styles for small screen devices, typically smartphones." }, { "code": null, "e": 2664, "s": 2661, "text": "s1" }, { "code": null, "e": 2709, "s": 2664, "text": "Defines 1 of 12 columns with width as 08.33%" }, { "code": null, "e": 2712, "s": 2709, "text": "s2" }, { "code": null, "e": 2758, "s": 2712, "text": "Defines 2 of 12 columns with width as 16.66%." }, { "code": null, "e": 2761, "s": 2758, "text": "s3" }, { "code": null, "e": 2807, "s": 2761, "text": "Defines 3 of 12 columns with width as 25.00%." }, { "code": null, "e": 2810, "s": 2807, "text": "s4" }, { "code": null, "e": 2856, "s": 2810, "text": "Defines 4 of 12 columns with width as 33.33%." }, { "code": null, "e": 2860, "s": 2856, "text": "s12" }, { "code": null, "e": 2944, "s": 2860, "text": "Defines 12 of 12 columns with width as 100%. Default class for small screen phones." }, { "code": null, "e": 3033, "s": 2944, "text": "Following is a list of column-level styles for medium screen devices, typically tablets." }, { "code": null, "e": 3036, "s": 3033, "text": "m1" }, { "code": null, "e": 3081, "s": 3036, "text": "Defines 1 of 12 columns with width as 08.33%" }, { "code": null, "e": 3084, "s": 3081, "text": "m2" }, { "code": null, "e": 3130, "s": 3084, "text": "Defines 2 of 12 columns with width as 16.66%." }, { "code": null, "e": 3133, "s": 3130, "text": "m3" }, { "code": null, "e": 3179, "s": 3133, "text": "Defines 3 of 12 columns with width as 25.00%." }, { "code": null, "e": 3182, "s": 3179, "text": "m4" }, { "code": null, "e": 3228, "s": 3182, "text": "Defines 4 of 12 columns with width as 33.33%." }, { "code": null, "e": 3232, "s": 3228, "text": "m12" }, { "code": null, "e": 3317, "s": 3232, "text": "Defines 12 of 12 columns with width as 100%. Default class for medium screen phones." }, { "code": null, "e": 3405, "s": 3317, "text": "Following is a list of column-level styles for large screen devices, typically laptops." }, { "code": null, "e": 3408, "s": 3405, "text": "l1" }, { "code": null, "e": 3453, "s": 3408, "text": "Defines 1 of 12 columns with width as 08.33%" }, { "code": null, "e": 3456, "s": 3453, "text": "l2" }, { "code": null, "e": 3502, "s": 3456, "text": "Defines 2 of 12 columns with width as 16.66%." }, { "code": null, "e": 3505, "s": 3502, "text": "l3" }, { "code": null, "e": 3551, "s": 3505, "text": "Defines 3 of 12 columns with width as 25.00%." }, { "code": null, "e": 3554, "s": 3551, "text": "l4" }, { "code": null, "e": 3600, "s": 3554, "text": "Defines 4 of 12 columns with width as 33.33%." }, { "code": null, "e": 3604, "s": 3600, "text": "l12" }, { "code": null, "e": 3689, "s": 3604, "text": "Defines 12 of 12 columns with width as 100%. Default class for large screen devices." }, { "code": null, "e": 3827, "s": 3689, "text": "Each subclass determines the number of columns of the grid to be used based on the type of a device. Consider the following HTML snippet." }, { "code": null, "e": 4000, "s": 3827, "text": "<div class=\"row\">\n <div class=\"col s2 m4 l3\">\n <p>This text will use 2 columns on a small screen, 4 on a medium screen, and 3 on a large screen.</p>\n </div>\n</div>" }, { "code": null, "e": 4122, "s": 4000, "text": "Default columns to be used are 12 on a device, if a sub-class is not mentioned in the class attribute of an HTML element." }, { "code": null, "e": 5923, "s": 4122, "text": "<!DOCTYPE html>\n<html>\n <head>\n <title>The Materialize Grids Example</title>\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n <link rel=\"stylesheet\" href=\"https://fonts.googleapis.com/icon?family=Material+Icons\">\n <link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/css/materialize.min.css\">\n <script type=\"text/javascript\" src=\"https://code.jquery.com/jquery-2.1.1.min.js\"></script>\n <script src=\"https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/js/materialize.min.js\"></script>\n </head>\n <body>\n <div class=\"teal\">\n <h2>Mobile First Design Demo</h2>\n <p>Resize the window to see the effect!</p>\n </div>\n <hr/>\n <div class=\"row\">\n <div class=\"col m1 grey center\">1</div>\n <div class=\"col m1 center\">2</div>\n <div class=\"col m1 grey center\">3</div>\n <div class=\"col m1 center\">4</div>\n <div class=\"col m1 grey center\">5</div>\n <div class=\"col m1 center\">6</div>\n <div class=\"col m1 center grey\">7</div>\n <div class=\"col m1 center\">8</div>\n <div class=\"col m1 center grey\">9</div>\n <div class=\"col m1 center\">10</div>\n <div class=\"col m1 center grey\">11</div>\n <div class=\"col m1 center\">12</div>\n </div>\n <div class=\"row\">\n <div class=\"col m4 l3 yellow\">\n <p>This text will use 12 columns on a small screen, 4 on a medium screen (m4), and 3 on a large screen (l3).</p>\n </div>\n <div class=\"col s4 m8 l9 grey\">\n <p>This text will use 4 columns on a small screen (s4), 8 on a medium screen (m8), and 9 on a large screen (l9).</p>\n </div>\n </div>\n </body>\n</html>" }, { "code": null, "e": 5942, "s": 5923, "text": "Verify the output." }, { "code": null, "e": 5949, "s": 5942, "text": " Print" }, { "code": null, "e": 5960, "s": 5949, "text": " Add Notes" } ]
Reduce string to shortest length by deleting a pair of same adjacent characters
05 May, 2021 Given a string str of lowercase characters. The task is to count the number of deletions required to reduce the string to its shortest length. In each delete operation, you can select a pair of adjacent lowercase letters that match, and then delete them. The task is to print the count of deletions done. Examples: Input: str = "aaabccddd" Output: 3 Following are sequence of operations: aaabccddd -> abccddd -> abddd -> abd Input: str = "aa" Output: 1 Approach: Initialize count = 1 initially.Iterate for every character, increase count if s[i]==s[i-1].If s[i]!=s[i-1], add count/2 to the number of steps, and re-initialize count to 1. Initialize count = 1 initially. Iterate for every character, increase count if s[i]==s[i-1]. If s[i]!=s[i-1], add count/2 to the number of steps, and re-initialize count to 1. If s[i]!=s[i-1], then the number of deletions is increased by count/2. If the count is even, number of pairs will be count/2. If count is odd, then the number of deletions will be (count-1)/2 which is the same as (int)count/2. Below is the implementation of the above approach: C++ Java Python3 C# PHP Javascript // C++ program to count deletions// to reduce the string to its shortest// length by deleting a pair of// same adjacent characters#include <bits/stdc++.h>using namespace std; // Function count the operationsint reduceString(string s, int l){ int count = 1, steps = 0; // traverse in the string for (int i = 1; i < l; i++) { // if adjacent characters are same if (s[i] == s[i - 1]) count += 1; else { // if same adjacent pairs are more than 1 steps += (count / 2); count = 1; } } steps += count / 2; return steps;} // Driver Codeint main(){ string s = "geeksforgeeks"; int l = s.length(); cout << reduceString(s, l) << endl; return 0;} // Java program to count deletions// to reduce the string to its// shortest length by deleting a// pair of same adjacent charactersimport java.io.*;import java.util.*;import java.lang.*; class GFG{ // Function count// the operationsstatic int reduceString(String s, int l){ int count = 1, steps = 0; // traverse in the string for (int i = 1; i < l; i++) { // if adjacent characters // are same if (s.charAt(i) == s.charAt(i - 1)) count += 1; else { // if same adjacent pairs // are more than 1 steps += (count / 2); count = 1; } } steps += count / 2; return steps;} // Driver Codepublic static void main(String[] args){ String s = "geeksforgeeks"; int l = s.length(); System.out.print(reduceString(s, l) + "\n");}} # Python3 program to count# deletions to reduce# the string to its# shortest length by# deleting a pair of# same adjacent characters # Function count# the operationsdef reduceString(s, l): count = 1; steps = 0; # traverse in # the string for i in range(1,l): # if adjacent # characters are same if (s[i] is s[i - 1]): count += 1; else: # if same adjacent pairs # are more than 1 steps +=(int)(count / 2); count = 1; steps +=(int)(count / 2); return steps; # Driver Codes = "geeksforgeeks"; l = len(s);print(reduceString(s, l)); # This code contributed by Rajput-Ji // C# program to count deletions// to reduce the string to its// shortest length by deleting a// pair of same adjacent charactersusing System; class GFG{ // Function count// the operationsstatic int reduce(string s, int l){ int count = 1, step = 0; // traverse in // the string for (int i = 1; i < l; i++) { // if adjacent characters // are same if (s[i] == s[i - 1]) count += 1; else { // if same adjacent pairs // are more than 1 step += (count / 2); count = 1; } } step += count / 2; return step;} // Driver Codepublic static void Main(){ string s = "geeksforgeeks"; int l = s.Length; Console.WriteLine(reduce(s, l));}} // This code is contributed by// Akanksha Rai(Abby_akku) <?php// PHP program to count// deletions to reduce// the string to its// shortest length by// deleting a pair of// same adjacent characters // Function count// the operationsfunction reduceString($s, $l){ $count = 1; $steps = 0; // traverse in // the string for ($i = 1; $i < $l; $i++) { // if adjacent // characters are same if ($s[$i] == $s[$i - 1]) $count += 1; else { // if same adjacent pairs // are more than 1 $steps +=(int)($count / 2); $count = 1; } } $steps +=(int)($count / 2); return $steps;} // Driver Code$s = "geeksforgeeks"; $l = strlen($s);echo reduceString($s, $l); // This code is contributed by ajit?> <script> // Javascript program to count deletions// to reduce the string to its// shortest length by deleting a// pair of same adjacent characters // Function count// the operationsfunction reduce(s, l){ let count = 1, step = 0; // Traverse in the string for(let i = 1; i < l; i++) { // If adjacent characters // are same if (s[i] == s[i - 1]) count += 1; else { // If same adjacent pairs // are more than 1 step += parseInt(count / 2, 10); count = 1; } } step += parseInt(count / 2, 10); return step;} // Driver codelet s = "geeksforgeeks";let l = s.length; document.write(reduce(s, l)); // This code is contributed by mukesh07 </script> 2 jit_t Akanksha_Rai Rajput-Ji mukesh07 C-String-Question School Programming Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Constructors in Java Exceptions in Java Python Exception Handling Python Try Except Ternary Operator in Python How JVM Works - JVM Architecture? Python program to add two numbers Variables in Java Data types in Java Difference between Abstract Class and Interface in Java
[ { "code": null, "e": 52, "s": 24, "text": "\n05 May, 2021" }, { "code": null, "e": 358, "s": 52, "text": "Given a string str of lowercase characters. The task is to count the number of deletions required to reduce the string to its shortest length. In each delete operation, you can select a pair of adjacent lowercase letters that match, and then delete them. The task is to print the count of deletions done. " }, { "code": null, "e": 369, "s": 358, "text": "Examples: " }, { "code": null, "e": 508, "s": 369, "text": "Input: str = \"aaabccddd\"\nOutput: 3\nFollowing are sequence of operations:\naaabccddd -> abccddd -> abddd -> abd\n\nInput: str = \"aa\"\nOutput: 1" }, { "code": null, "e": 520, "s": 508, "text": "Approach: " }, { "code": null, "e": 694, "s": 520, "text": "Initialize count = 1 initially.Iterate for every character, increase count if s[i]==s[i-1].If s[i]!=s[i-1], add count/2 to the number of steps, and re-initialize count to 1." }, { "code": null, "e": 726, "s": 694, "text": "Initialize count = 1 initially." }, { "code": null, "e": 787, "s": 726, "text": "Iterate for every character, increase count if s[i]==s[i-1]." }, { "code": null, "e": 870, "s": 787, "text": "If s[i]!=s[i-1], add count/2 to the number of steps, and re-initialize count to 1." }, { "code": null, "e": 1098, "s": 870, "text": "If s[i]!=s[i-1], then the number of deletions is increased by count/2. If the count is even, number of pairs will be count/2. If count is odd, then the number of deletions will be (count-1)/2 which is the same as (int)count/2. " }, { "code": null, "e": 1151, "s": 1098, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 1155, "s": 1151, "text": "C++" }, { "code": null, "e": 1160, "s": 1155, "text": "Java" }, { "code": null, "e": 1168, "s": 1160, "text": "Python3" }, { "code": null, "e": 1171, "s": 1168, "text": "C#" }, { "code": null, "e": 1175, "s": 1171, "text": "PHP" }, { "code": null, "e": 1186, "s": 1175, "text": "Javascript" }, { "code": "// C++ program to count deletions// to reduce the string to its shortest// length by deleting a pair of// same adjacent characters#include <bits/stdc++.h>using namespace std; // Function count the operationsint reduceString(string s, int l){ int count = 1, steps = 0; // traverse in the string for (int i = 1; i < l; i++) { // if adjacent characters are same if (s[i] == s[i - 1]) count += 1; else { // if same adjacent pairs are more than 1 steps += (count / 2); count = 1; } } steps += count / 2; return steps;} // Driver Codeint main(){ string s = \"geeksforgeeks\"; int l = s.length(); cout << reduceString(s, l) << endl; return 0;}", "e": 1956, "s": 1186, "text": null }, { "code": "// Java program to count deletions// to reduce the string to its// shortest length by deleting a// pair of same adjacent charactersimport java.io.*;import java.util.*;import java.lang.*; class GFG{ // Function count// the operationsstatic int reduceString(String s, int l){ int count = 1, steps = 0; // traverse in the string for (int i = 1; i < l; i++) { // if adjacent characters // are same if (s.charAt(i) == s.charAt(i - 1)) count += 1; else { // if same adjacent pairs // are more than 1 steps += (count / 2); count = 1; } } steps += count / 2; return steps;} // Driver Codepublic static void main(String[] args){ String s = \"geeksforgeeks\"; int l = s.length(); System.out.print(reduceString(s, l) + \"\\n\");}}", "e": 2838, "s": 1956, "text": null }, { "code": "# Python3 program to count# deletions to reduce# the string to its# shortest length by# deleting a pair of# same adjacent characters # Function count# the operationsdef reduceString(s, l): count = 1; steps = 0; # traverse in # the string for i in range(1,l): # if adjacent # characters are same if (s[i] is s[i - 1]): count += 1; else: # if same adjacent pairs # are more than 1 steps +=(int)(count / 2); count = 1; steps +=(int)(count / 2); return steps; # Driver Codes = \"geeksforgeeks\"; l = len(s);print(reduceString(s, l)); # This code contributed by Rajput-Ji", "e": 3522, "s": 2838, "text": null }, { "code": "// C# program to count deletions// to reduce the string to its// shortest length by deleting a// pair of same adjacent charactersusing System; class GFG{ // Function count// the operationsstatic int reduce(string s, int l){ int count = 1, step = 0; // traverse in // the string for (int i = 1; i < l; i++) { // if adjacent characters // are same if (s[i] == s[i - 1]) count += 1; else { // if same adjacent pairs // are more than 1 step += (count / 2); count = 1; } } step += count / 2; return step;} // Driver Codepublic static void Main(){ string s = \"geeksforgeeks\"; int l = s.Length; Console.WriteLine(reduce(s, l));}} // This code is contributed by// Akanksha Rai(Abby_akku)", "e": 4365, "s": 3522, "text": null }, { "code": "<?php// PHP program to count// deletions to reduce// the string to its// shortest length by// deleting a pair of// same adjacent characters // Function count// the operationsfunction reduceString($s, $l){ $count = 1; $steps = 0; // traverse in // the string for ($i = 1; $i < $l; $i++) { // if adjacent // characters are same if ($s[$i] == $s[$i - 1]) $count += 1; else { // if same adjacent pairs // are more than 1 $steps +=(int)($count / 2); $count = 1; } } $steps +=(int)($count / 2); return $steps;} // Driver Code$s = \"geeksforgeeks\"; $l = strlen($s);echo reduceString($s, $l); // This code is contributed by ajit?>", "e": 5122, "s": 4365, "text": null }, { "code": "<script> // Javascript program to count deletions// to reduce the string to its// shortest length by deleting a// pair of same adjacent characters // Function count// the operationsfunction reduce(s, l){ let count = 1, step = 0; // Traverse in the string for(let i = 1; i < l; i++) { // If adjacent characters // are same if (s[i] == s[i - 1]) count += 1; else { // If same adjacent pairs // are more than 1 step += parseInt(count / 2, 10); count = 1; } } step += parseInt(count / 2, 10); return step;} // Driver codelet s = \"geeksforgeeks\";let l = s.length; document.write(reduce(s, l)); // This code is contributed by mukesh07 </script>", "e": 5904, "s": 5122, "text": null }, { "code": null, "e": 5906, "s": 5904, "text": "2" }, { "code": null, "e": 5914, "s": 5908, "text": "jit_t" }, { "code": null, "e": 5927, "s": 5914, "text": "Akanksha_Rai" }, { "code": null, "e": 5937, "s": 5927, "text": "Rajput-Ji" }, { "code": null, "e": 5946, "s": 5937, "text": "mukesh07" }, { "code": null, "e": 5964, "s": 5946, "text": "C-String-Question" }, { "code": null, "e": 5983, "s": 5964, "text": "School Programming" }, { "code": null, "e": 6081, "s": 5983, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6102, "s": 6081, "text": "Constructors in Java" }, { "code": null, "e": 6121, "s": 6102, "text": "Exceptions in Java" }, { "code": null, "e": 6147, "s": 6121, "text": "Python Exception Handling" }, { "code": null, "e": 6165, "s": 6147, "text": "Python Try Except" }, { "code": null, "e": 6192, "s": 6165, "text": "Ternary Operator in Python" }, { "code": null, "e": 6226, "s": 6192, "text": "How JVM Works - JVM Architecture?" }, { "code": null, "e": 6260, "s": 6226, "text": "Python program to add two numbers" }, { "code": null, "e": 6278, "s": 6260, "text": "Variables in Java" }, { "code": null, "e": 6297, "s": 6278, "text": "Data types in Java" } ]
SQL Query to Compare Two Strings
14 Sep, 2021 SQL stands for Structured Query Language. It is used to communicate with the database. There are some standard SQL commands like ‘select’, ‘delete’, ‘alter’ etc. To compare two strings in SQL Server, there is no direct way. In this article, we will learn how to compare two strings in an MS SQL server and we will provide some examples. A string function is a function that takes a string value as an input regardless of the data type of the returned value. In SQL Server, there are many built-in string functions that can be used by developers. We can compare strings by using the IF-ELSE statement. Syntax: IF Boolean_expression { sql_statement | statement_block } [ ELSE { sql_statement | statement_block } ] We can declare variables easily by using the keyword DECLARE before the variable name. By default, the local variable starts with @. Syntax: DECLARE @variable_name datatype; We can assign value to the variables using the SET keyword. Syntax: SET @variable_name; Example 1: Query: DECLARE @Name1 VARCHAR(30), @Name2 VARCHAR(20); Set @Name1='geeks'; Set @Name2='geeks'; If @Name1=@Name2 Select 'match' else Select 'not match'; Output: The above example shows the string comparison and returns the result as a ‘match’ because both strings are the same. Example 2: Query: DECLARE @Name1 VARCHAR(30), @Name2 VARCHAR(20); Set @Name1='geeks'; Set @Name2='geeksforgeeks'; If @Name1=@Name2 Select 'match' else Select 'not match'; Output: The above example shows the string comparison and returns the result as a ‘not match’ because both strings are not the same. Blogathon-2021 Picked SQL-Query Blogathon SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n14 Sep, 2021" }, { "code": null, "e": 365, "s": 28, "text": "SQL stands for Structured Query Language. It is used to communicate with the database. There are some standard SQL commands like ‘select’, ‘delete’, ‘alter’ etc. To compare two strings in SQL Server, there is no direct way. In this article, we will learn how to compare two strings in an MS SQL server and we will provide some examples." }, { "code": null, "e": 574, "s": 365, "text": "A string function is a function that takes a string value as an input regardless of the data type of the returned value. In SQL Server, there are many built-in string functions that can be used by developers." }, { "code": null, "e": 629, "s": 574, "text": "We can compare strings by using the IF-ELSE statement." }, { "code": null, "e": 637, "s": 629, "text": "Syntax:" }, { "code": null, "e": 664, "s": 637, "text": " IF Boolean_expression " }, { "code": null, "e": 708, "s": 664, "text": " { sql_statement | statement_block } " }, { "code": null, "e": 719, "s": 708, "text": "[ ELSE " }, { "code": null, "e": 763, "s": 719, "text": " { sql_statement | statement_block } ] " }, { "code": null, "e": 896, "s": 763, "text": "We can declare variables easily by using the keyword DECLARE before the variable name. By default, the local variable starts with @." }, { "code": null, "e": 904, "s": 896, "text": "Syntax:" }, { "code": null, "e": 938, "s": 904, "text": " DECLARE @variable_name datatype;" }, { "code": null, "e": 998, "s": 938, "text": "We can assign value to the variables using the SET keyword." }, { "code": null, "e": 1007, "s": 998, "text": "Syntax: " }, { "code": null, "e": 1027, "s": 1007, "text": "SET @variable_name;" }, { "code": null, "e": 1038, "s": 1027, "text": "Example 1:" }, { "code": null, "e": 1045, "s": 1038, "text": "Query:" }, { "code": null, "e": 1190, "s": 1045, "text": "DECLARE @Name1 VARCHAR(30), @Name2 VARCHAR(20);\nSet @Name1='geeks';\nSet @Name2='geeks';\nIf @Name1=@Name2 Select 'match' else Select 'not match';" }, { "code": null, "e": 1198, "s": 1190, "text": "Output:" }, { "code": null, "e": 1315, "s": 1198, "text": "The above example shows the string comparison and returns the result as a ‘match’ because both strings are the same." }, { "code": null, "e": 1326, "s": 1315, "text": "Example 2:" }, { "code": null, "e": 1333, "s": 1326, "text": "Query:" }, { "code": null, "e": 1486, "s": 1333, "text": "DECLARE @Name1 VARCHAR(30), @Name2 VARCHAR(20);\nSet @Name1='geeks';\nSet @Name2='geeksforgeeks';\nIf @Name1=@Name2 Select 'match' else Select 'not match';" }, { "code": null, "e": 1494, "s": 1486, "text": "Output:" }, { "code": null, "e": 1619, "s": 1494, "text": "The above example shows the string comparison and returns the result as a ‘not match’ because both strings are not the same." }, { "code": null, "e": 1634, "s": 1619, "text": "Blogathon-2021" }, { "code": null, "e": 1641, "s": 1634, "text": "Picked" }, { "code": null, "e": 1651, "s": 1641, "text": "SQL-Query" }, { "code": null, "e": 1661, "s": 1651, "text": "Blogathon" }, { "code": null, "e": 1665, "s": 1661, "text": "SQL" }, { "code": null, "e": 1669, "s": 1665, "text": "SQL" } ]
HTML | Color Styles and HSL
14 Jun, 2022 Colors are used to make the page more attractive. Here are the different styles which can be used to create new colors by combination of different colors. Hexadecimal Style : In this style, we define the color in 6 digit hexadecimal number (from 0 to F). It is denoted by ‘#’. The first two digits indicate red color, next two green color and the last two blue color.Examples : If we want all ‘h1’ tags of purple color. h1{ color:#00FF00; } RGB Style [Red Green Blue] : In this we need to give 3 numbers indicating the amount of red, green and blue colors respectively required in the mixed color. The range of each color is from 0 to 255. Example: If we want all ‘h1’ tags of green color. h1{ color:rgb(0, 255, 0); } Note: rgba(0, 0, 0) is Black color and rgb(255, 255, 255) is White color. RGBA Style [Red Green Blue Alpha] : This style allows us to make the color transparent according to our will. Alpha indicates the degree of transparency. The range of green, blue and red is from 0 to 255 and that of alpha is from 0 to 1.Example: If we want all ‘h1’ tags of green color. h1{ color:rgba(11, 99, 150, 1); } HSL colors : Here ‘H’ stands for hue, ‘S’ for Saturation and ‘L’ for Lightness. HSL color values are specified as: Syntax: hsl(hue, saturation, lightness) HSL colors value: Hue is the color of the image itself. It’s range is from 0 to 360. 0 is for red, 120 is for green and 240 is for blue.Saturation is the intensity/purity of the hue. 0% is for a shade of gray, and 100% is the full color. When color is fully saturated, the color is considered in purest/truest version.Lightness is the color space’s brightness. 0% is for black, 100% is for white. Hue is the color of the image itself. It’s range is from 0 to 360. 0 is for red, 120 is for green and 240 is for blue. Saturation is the intensity/purity of the hue. 0% is for a shade of gray, and 100% is the full color. When color is fully saturated, the color is considered in purest/truest version. Lightness is the color space’s brightness. 0% is for black, 100% is for white. html <!-- Write HTML code here --><head> <title>GeeksforGeeks</title> <style type="text/css"> h1{ color:#0FFFF0; background-color: hsl(200, 50%, 20%); color: hsl(200, 20%, 90%); } h4{ color:rgb(0, 255, 0); background-color: hsl(150, 20%, 40%); color: hsl(360, 30%, 90%); } li{ color:rgba(11, 99, 150, 1); background-color: hsl(250, 45%, 60%); color: hsl(175, 35%, 87%); } </style></head><body> <h1>GeeksforGeeks</h1> <h4>Programming Languages</h4> <ul> <li>Java</li> <li>C++</li> <li>C</li> </ul></body></html> Supported Browser: Google Chrome Microsoft Edge Firefox Opera Safari ysachin2314 sanayush1357 HTML-Basics HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to update Node.js and NPM to next version ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? REST API (Introduction) Hide or show elements in HTML using display property Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 52, "s": 24, "text": "\n14 Jun, 2022" }, { "code": null, "e": 209, "s": 52, "text": "Colors are used to make the page more attractive. Here are the different styles which can be used to create new colors by combination of different colors. " }, { "code": null, "e": 476, "s": 209, "text": "Hexadecimal Style : In this style, we define the color in 6 digit hexadecimal number (from 0 to F). It is denoted by ‘#’. The first two digits indicate red color, next two green color and the last two blue color.Examples : If we want all ‘h1’ tags of purple color. " }, { "code": null, "e": 500, "s": 476, "text": "h1{\n color:#00FF00;\n}\n " }, { "code": null, "e": 751, "s": 500, "text": "RGB Style [Red Green Blue] : In this we need to give 3 numbers indicating the amount of red, green and blue colors respectively required in the mixed color. The range of each color is from 0 to 255. Example: If we want all ‘h1’ tags of green color. " }, { "code": null, "e": 787, "s": 751, "text": "h1{\n color:rgb(0, 255, 0);\n}\n " }, { "code": null, "e": 875, "s": 787, "text": " Note: rgba(0, 0, 0) is Black color and rgb(255, 255, 255) is White color. " }, { "code": null, "e": 1164, "s": 875, "text": "RGBA Style [Red Green Blue Alpha] : This style allows us to make the color transparent according to our will. Alpha indicates the degree of transparency. The range of green, blue and red is from 0 to 255 and that of alpha is from 0 to 1.Example: If we want all ‘h1’ tags of green color. " }, { "code": null, "e": 1203, "s": 1164, "text": "h1{\n color:rgba(11, 99, 150, 1);\n }\n " }, { "code": null, "e": 1328, "s": 1203, "text": "HSL colors : Here ‘H’ stands for hue, ‘S’ for Saturation and ‘L’ for Lightness. HSL color values are specified as: Syntax: " }, { "code": null, "e": 1361, "s": 1328, "text": " hsl(hue, saturation, lightness)" }, { "code": null, "e": 1386, "s": 1361, "text": " HSL colors value:" }, { "code": null, "e": 1765, "s": 1386, "text": "Hue is the color of the image itself. It’s range is from 0 to 360. 0 is for red, 120 is for green and 240 is for blue.Saturation is the intensity/purity of the hue. 0% is for a shade of gray, and 100% is the full color. When color is fully saturated, the color is considered in purest/truest version.Lightness is the color space’s brightness. 0% is for black, 100% is for white." }, { "code": null, "e": 1884, "s": 1765, "text": "Hue is the color of the image itself. It’s range is from 0 to 360. 0 is for red, 120 is for green and 240 is for blue." }, { "code": null, "e": 2067, "s": 1884, "text": "Saturation is the intensity/purity of the hue. 0% is for a shade of gray, and 100% is the full color. When color is fully saturated, the color is considered in purest/truest version." }, { "code": null, "e": 2146, "s": 2067, "text": "Lightness is the color space’s brightness. 0% is for black, 100% is for white." }, { "code": null, "e": 2153, "s": 2148, "text": "html" }, { "code": "<!-- Write HTML code here --><head> <title>GeeksforGeeks</title> <style type=\"text/css\"> h1{ color:#0FFFF0; background-color: hsl(200, 50%, 20%); color: hsl(200, 20%, 90%); } h4{ color:rgb(0, 255, 0); background-color: hsl(150, 20%, 40%); color: hsl(360, 30%, 90%); } li{ color:rgba(11, 99, 150, 1); background-color: hsl(250, 45%, 60%); color: hsl(175, 35%, 87%); } </style></head><body> <h1>GeeksforGeeks</h1> <h4>Programming Languages</h4> <ul> <li>Java</li> <li>C++</li> <li>C</li> </ul></body></html>", "e": 2843, "s": 2153, "text": null }, { "code": null, "e": 2862, "s": 2843, "text": "Supported Browser:" }, { "code": null, "e": 2876, "s": 2862, "text": "Google Chrome" }, { "code": null, "e": 2891, "s": 2876, "text": "Microsoft Edge" }, { "code": null, "e": 2899, "s": 2891, "text": "Firefox" }, { "code": null, "e": 2905, "s": 2899, "text": "Opera" }, { "code": null, "e": 2912, "s": 2905, "text": "Safari" }, { "code": null, "e": 2924, "s": 2912, "text": "ysachin2314" }, { "code": null, "e": 2937, "s": 2924, "text": "sanayush1357" }, { "code": null, "e": 2949, "s": 2937, "text": "HTML-Basics" }, { "code": null, "e": 2954, "s": 2949, "text": "HTML" }, { "code": null, "e": 2971, "s": 2954, "text": "Web Technologies" }, { "code": null, "e": 2976, "s": 2971, "text": "HTML" }, { "code": null, "e": 3074, "s": 2976, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3122, "s": 3074, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 3184, "s": 3122, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 3234, "s": 3184, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 3258, "s": 3234, "text": "REST API (Introduction)" }, { "code": null, "e": 3311, "s": 3258, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 3344, "s": 3311, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 3406, "s": 3344, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 3467, "s": 3406, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 3517, "s": 3467, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
R - Next Statement
The next statement in R programming language is useful when we want to skip the current iteration of a loop without terminating it. On encountering next, the R parser skips further evaluation and starts next iteration of the loop. The basic syntax for creating a next statement in R is − next v <- LETTERS[1:6] for ( i in v) { if (i == "D") { next } print(i) } When the above code is compiled and executed, it produces the following result −
[ { "code": null, "e": 2767, "s": 2536, "text": "The next statement in R programming language is useful when we want to skip the current iteration of a loop without terminating it. On encountering next, the R parser skips further evaluation and starts next iteration of the loop." }, { "code": null, "e": 2824, "s": 2767, "text": "The basic syntax for creating a next statement in R is −" }, { "code": null, "e": 2830, "s": 2824, "text": "next\n" }, { "code": null, "e": 2917, "s": 2830, "text": "v <- LETTERS[1:6]\nfor ( i in v) {\n \n if (i == \"D\") {\n next\n }\n print(i)\n}" } ]
Python | Numpy matrix.copy()
12 Apr, 2019 With the help of Numpy matrix.copy() method, we can make a copy of all the data elements that is present in matrix. If we change any data element in the copy, it will not affect the original matrix. Syntax : matrix.copy() Return : Return copy of matrix Example #1 :In this example we can see that with the help of matrix.copy() method we are making the copy of an elements in different matrix. # import the important module in pythonimport numpy as np # make matrix with numpygfg = np.matrix('[1, 2, 3]') # applying matrix.copy() methodgeeks = gfg.copy() print(geeks) [[1 2 3]] Example #2 : # import the important module in pythonimport numpy as np # make a matrix with numpygfg = np.matrix('[1, 2, 3; 4, 5, 6]') # applying matrix.copy() methodgeeks = gfg.copy() print(geeks) [[1 2 3] [4 5 6]] Python numpy-Matrix Function Python-numpy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to iterate through Excel rows in Python? Rotate axis tick labels in Seaborn and Matplotlib Deque in Python Queue in Python Defaultdict in Python Check if element exists in list in Python Python Classes and Objects Bar Plot in Matplotlib reduce() in Python Python | Get unique values from a list
[ { "code": null, "e": 28, "s": 0, "text": "\n12 Apr, 2019" }, { "code": null, "e": 227, "s": 28, "text": "With the help of Numpy matrix.copy() method, we can make a copy of all the data elements that is present in matrix. If we change any data element in the copy, it will not affect the original matrix." }, { "code": null, "e": 250, "s": 227, "text": "Syntax : matrix.copy()" }, { "code": null, "e": 281, "s": 250, "text": "Return : Return copy of matrix" }, { "code": null, "e": 422, "s": 281, "text": "Example #1 :In this example we can see that with the help of matrix.copy() method we are making the copy of an elements in different matrix." }, { "code": "# import the important module in pythonimport numpy as np # make matrix with numpygfg = np.matrix('[1, 2, 3]') # applying matrix.copy() methodgeeks = gfg.copy() print(geeks)", "e": 614, "s": 422, "text": null }, { "code": null, "e": 625, "s": 614, "text": "[[1 2 3]]\n" }, { "code": null, "e": 638, "s": 625, "text": "Example #2 :" }, { "code": "# import the important module in pythonimport numpy as np # make a matrix with numpygfg = np.matrix('[1, 2, 3; 4, 5, 6]') # applying matrix.copy() methodgeeks = gfg.copy() print(geeks)", "e": 841, "s": 638, "text": null }, { "code": null, "e": 861, "s": 841, "text": "[[1 2 3]\n [4 5 6]]\n" }, { "code": null, "e": 890, "s": 861, "text": "Python numpy-Matrix Function" }, { "code": null, "e": 903, "s": 890, "text": "Python-numpy" }, { "code": null, "e": 910, "s": 903, "text": "Python" }, { "code": null, "e": 1008, "s": 910, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1053, "s": 1008, "text": "How to iterate through Excel rows in Python?" }, { "code": null, "e": 1103, "s": 1053, "text": "Rotate axis tick labels in Seaborn and Matplotlib" }, { "code": null, "e": 1119, "s": 1103, "text": "Deque in Python" }, { "code": null, "e": 1135, "s": 1119, "text": "Queue in Python" }, { "code": null, "e": 1157, "s": 1135, "text": "Defaultdict in Python" }, { "code": null, "e": 1199, "s": 1157, "text": "Check if element exists in list in Python" }, { "code": null, "e": 1226, "s": 1199, "text": "Python Classes and Objects" }, { "code": null, "e": 1249, "s": 1226, "text": "Bar Plot in Matplotlib" }, { "code": null, "e": 1268, "s": 1249, "text": "reduce() in Python" } ]
Python program to convert time from 12 hour to 24 hour format
02 May, 2018 Given a time in 12-hour AM/PM format, convert it to military (24-hour) time. Note : Midnight is 12:00:00 AM on a 12-hour clock and 00:00:00 on a 24-hour clock. Noon is 12:00:00 PM on 12-hour clock and 12:00:00 on 24-hour clock. Examples : Input : 11:21:30 PM Output : 23:21:30 Input : 12:12:20 AM Output : 00:12:20 Approach : Whether the time format is 12 hours or not, can be found out by using list slicing. Check if last two elements are PM, then simply add 12 to them. If AM, then don’t add. Remove AM/PM from the updated time. Below is the implementation : # Python program to convert time# from 12 hour to 24 hour format # Function to convert the date formatdef convert24(str1): # Checking if last two elements of time # is AM and first two elements are 12 if str1[-2:] == "AM" and str1[:2] == "12": return "00" + str1[2:-2] # remove the AM elif str1[-2:] == "AM": return str1[:-2] # Checking if last two elements of time # is PM and first two elements are 12 elif str1[-2:] == "PM" and str1[:2] == "12": return str1[:-2] else: # add 12 to hours and remove PM return str(int(str1[:2]) + 12) + str1[2:8] # Driver Code print(convert24("08:05:45 PM")) Output : 20:05:45 date-time-program Python Python Programs School Programming Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() Python program to convert a list to string Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python Program for Fibonacci numbers
[ { "code": null, "e": 52, "s": 24, "text": "\n02 May, 2018" }, { "code": null, "e": 129, "s": 52, "text": "Given a time in 12-hour AM/PM format, convert it to military (24-hour) time." }, { "code": null, "e": 280, "s": 129, "text": "Note : Midnight is 12:00:00 AM on a 12-hour clock and 00:00:00 on a 24-hour clock. Noon is 12:00:00 PM on 12-hour clock and 12:00:00 on 24-hour clock." }, { "code": null, "e": 291, "s": 280, "text": "Examples :" }, { "code": null, "e": 369, "s": 291, "text": "Input : 11:21:30 PM\nOutput : 23:21:30\n\nInput : 12:12:20 AM\nOutput : 00:12:20\n" }, { "code": null, "e": 586, "s": 369, "text": "Approach : Whether the time format is 12 hours or not, can be found out by using list slicing. Check if last two elements are PM, then simply add 12 to them. If AM, then don’t add. Remove AM/PM from the updated time." }, { "code": null, "e": 617, "s": 586, "text": " Below is the implementation :" }, { "code": "# Python program to convert time# from 12 hour to 24 hour format # Function to convert the date formatdef convert24(str1): # Checking if last two elements of time # is AM and first two elements are 12 if str1[-2:] == \"AM\" and str1[:2] == \"12\": return \"00\" + str1[2:-2] # remove the AM elif str1[-2:] == \"AM\": return str1[:-2] # Checking if last two elements of time # is PM and first two elements are 12 elif str1[-2:] == \"PM\" and str1[:2] == \"12\": return str1[:-2] else: # add 12 to hours and remove PM return str(int(str1[:2]) + 12) + str1[2:8] # Driver Code print(convert24(\"08:05:45 PM\"))", "e": 1330, "s": 617, "text": null }, { "code": null, "e": 1339, "s": 1330, "text": "Output :" }, { "code": null, "e": 1348, "s": 1339, "text": "20:05:45" }, { "code": null, "e": 1366, "s": 1348, "text": "date-time-program" }, { "code": null, "e": 1373, "s": 1366, "text": "Python" }, { "code": null, "e": 1389, "s": 1373, "text": "Python Programs" }, { "code": null, "e": 1408, "s": 1389, "text": "School Programming" }, { "code": null, "e": 1427, "s": 1408, "text": "Technical Scripter" }, { "code": null, "e": 1525, "s": 1427, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1543, "s": 1525, "text": "Python Dictionary" }, { "code": null, "e": 1585, "s": 1543, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 1607, "s": 1585, "text": "Enumerate() in Python" }, { "code": null, "e": 1642, "s": 1607, "text": "Read a file line by line in Python" }, { "code": null, "e": 1668, "s": 1642, "text": "Python String | replace()" }, { "code": null, "e": 1711, "s": 1668, "text": "Python program to convert a list to string" }, { "code": null, "e": 1733, "s": 1711, "text": "Defaultdict in Python" }, { "code": null, "e": 1772, "s": 1733, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 1810, "s": 1772, "text": "Python | Convert a list to dictionary" } ]
jQuery - Widget Tab
The Widget Tab function can be used with widgets in JqueryUI.tab is used to swap between content that is broken into logical sections. Here is the simple syntax to use tab − $( "#tabs" ).tabs(); Following is a simple example showing the usage of Tab − <!doctype html> <html lang = "en"> <head> <meta charset = "utf-8"> <title>jQuery UI Tabs - Default functionality</title> <link rel = "stylesheet" href = "//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css"> <script type = "text/javascript" src = "https://www.tutorialspoint.com/jquery/jquery-3.6.0.js"></script> <script type = "text/javascript" src = "https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.3/jquery-ui.min.js"> </script> <script> $(function() { $( "#tabs" ).tabs(); }); </script> </head> <body> <div id = "tabs"> <ul> <li><a href = "#tabs-1">Android</a></li> <li><a href = "#tabs-2">CSS</a></li> <li><a href = "#tabs-3">AngularJS</a></li> </ul> <div id = "tabs-1"> <p>Android is an open source and Linux-based operating system for mobile devices such as smartphones and tablet computers. Android was developed by the Open Handset Alliance, led by Google, and other companies.</p> </div> <div id = "tabs-2"> <p>CSS is the acronym for "Cascading Style Sheet". This tutorial covers both the versions CSS1,CSS2 and CSS3, and gives a complete understanding of CSS,starting from its basics to advanced concepts.</p> </div> <div id = "tabs-3"> <p>AngularJS is a very powerful JavaScript library. It is used in Single Page Application (SPA) projects. It extends HTML DOM with additional attributes and makes it more responsive to user actions. AngularJS is open source,completely free, and used by thousands of developers around the world. It is licensed under the Apache license version 2.0.</p> </div> </div> </body> </html> This will produce following result − Android CSS AngularJS Android is an open source and Linux-based operating system for mobile devices such as smartphones and tablet computers. Android was developed by the Open Handset Alliance, led by Google, and other companies. CSS is the acronym for "Cascading Style Sheet". This tutorial covers both the versions CSS1,CSS2 and CSS3, and gives a complete understanding of CSS, starting from its basics to advanced concepts. AngularJS is a very powerful JavaScript library. It is used in Single Page Application (SPA) projects. It extends HTML DOM with additional attributes and makes it more responsive to user actions. AngularJS is open source, completely free, and used by thousands of developers around the world. It is licensed under the Apache license version 2.0.
[ { "code": null, "e": 2924, "s": 2789, "text": "The Widget Tab function can be used with widgets in JqueryUI.tab is used to swap between content that is broken into logical sections." }, { "code": null, "e": 2963, "s": 2924, "text": "Here is the simple syntax to use tab −" }, { "code": null, "e": 2985, "s": 2963, "text": "$( \"#tabs\" ).tabs();\n" }, { "code": null, "e": 3042, "s": 2985, "text": "Following is a simple example showing the usage of Tab −" }, { "code": null, "e": 5058, "s": 3042, "text": "<!doctype html>\n<html lang = \"en\">\n <head>\n <meta charset = \"utf-8\">\n <title>jQuery UI Tabs - Default functionality</title>\n\t\t\n <link rel = \"stylesheet\" \n href = \"//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css\">\n\t\t\t\n <script type = \"text/javascript\" \n src = \"https://www.tutorialspoint.com/jquery/jquery-3.6.0.js\"></script>\n\t\t\n <script type = \"text/javascript\" \n src = \"https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.3/jquery-ui.min.js\">\n </script>\n \n <script>\n $(function() {\n $( \"#tabs\" ).tabs();\n });\n </script>\n </head>\n\t\n <body>\n <div id = \"tabs\">\n <ul>\n <li><a href = \"#tabs-1\">Android</a></li>\n <li><a href = \"#tabs-2\">CSS</a></li>\n <li><a href = \"#tabs-3\">AngularJS</a></li>\n </ul>\n\t\t\t\n <div id = \"tabs-1\">\n <p>Android is an open source and Linux-based operating system \n for mobile devices such as smartphones and tablet computers. \n Android was developed by the Open Handset Alliance, led by Google, \n and other companies.</p>\n </div>\n\t\t\t\n <div id = \"tabs-2\">\n <p>CSS is the acronym for \"Cascading Style Sheet\". This\n tutorial covers both the versions CSS1,CSS2 and CSS3, and gives a\n complete understanding of CSS,starting from its basics to advanced \n concepts.</p>\n </div>\n\t\t\t\n <div id = \"tabs-3\">\n <p>AngularJS is a very powerful JavaScript library. It is used\n in Single Page Application (SPA) projects. It extends HTML DOM \n with additional attributes and makes it more responsive to user \n actions. AngularJS is open source,completely free, and used by\n thousands of developers around the world. It is licensed under \n the Apache license version 2.0.</p>\n </div>\n </div>\n </body>\n</html>" }, { "code": null, "e": 5095, "s": 5058, "text": "This will produce following result −" }, { "code": null, "e": 5103, "s": 5095, "text": "Android" }, { "code": null, "e": 5107, "s": 5103, "text": "CSS" }, { "code": null, "e": 5117, "s": 5107, "text": "AngularJS" }, { "code": null, "e": 5325, "s": 5117, "text": "Android is an open source and Linux-based operating system for mobile devices such as smartphones and tablet computers. Android was developed by the Open Handset Alliance, led by Google, and other companies." }, { "code": null, "e": 5522, "s": 5325, "text": "CSS is the acronym for \"Cascading Style Sheet\". This tutorial covers both the versions CSS1,CSS2 and CSS3, and gives a complete understanding of CSS, starting from its basics to advanced concepts." } ]
How to Correctly Access Elements in a 3D Pytorch Tensor?
23 Aug, 2021 In this article, we will discuss how to access elements in a 3D Tensor in Pytorch. PyTorch is an optimized tensor library majorly used for Deep Learning applications using GPUs and CPUs. It is one of the widely used Machine learning libraries, others being TensorFlow and Keras. The python supports the torch module, so to work with this first we import the module to the workspace. Syntax: import torch We can create a vector by using the torch.tensor() function Syntax: torch.tensor([value1,value2,.value n]) Example 1: Python code to create an 3 D Tensor and display Python3 # import torch moduleimport torch # create an 3 D tensor with 8 elements eacha = torch.tensor([[[1, 2, 3, 4, 5, 6, 7, 8], [10, 11, 12, 13, 14, 15, 16, 17]], [[71, 72, 73, 74, 75, 76, 77, 78], [81, 82, 83, 84, 85, 86, 87, 88]]]) # display actual tensorprint(a) Output: tensor([[[ 1, 2, 3, 4, 5, 6, 7, 8], [10, 11, 12, 13, 14, 15, 16, 17]], [[71, 72, 73, 74, 75, 76, 77, 78], [81, 82, 83, 84, 85, 86, 87, 88]]]) To access elements from a 3-D tensor Slicing can be used. Slicing means selecting the elements present in the tensor by using “:” slice operator. We can slice the elements by using the index of that particular element. Note: Indexing starts with 0 Syntax: tensor[tensor_position_start:tensor_position_end, tensor_dimension_start:tensor_dimension_end , tensor_value_start:tensor_value_end] where, tensor_position_start – Specifies the Tensor to start iterating tensor_position_end – Specifies the Tensor to stop iterating tensor_dimension_start – Specifies the Tensor to start the iteration of tensor in given positions tensor_dimension_stop– Specifies the Tensor to stop the iteration of tensor in given positions tensor_value_start – Specifies the start position of the tensor to iterate the elements given in dimensions tensor_value_stop – Specifies the end position of the tensor to iterate the elements given in dimensions Given below are the various examples for the same. Example 2: Python code to access all the tensors of 1 dimension and get only 7 values in that dimension Python3 # import torch moduleimport torch # create an 3 D tensor with 8 elements eacha = torch.tensor([[[1, 2, 3, 4, 5, 6, 7, 8], [10, 11, 12, 13, 14, 15, 16, 17]], [[71, 72, 73, 74, 75, 76, 77, 78], [81, 82, 83, 84, 85, 86, 87, 88]]]) # display actual tensorprint(a) # access all the tensors of 1 dimension # and get only 7 values in that dimensionprint(a[0:1, 0:1, :7]) Output: tensor([[[ 1, 2, 3, 4, 5, 6, 7, 8], [10, 11, 12, 13, 14, 15, 16, 17]], [[71, 72, 73, 74, 75, 76, 77, 78], [81, 82, 83, 84, 85, 86, 87, 88]]]) tensor([[[1, 2, 3, 4, 5, 6, 7]]]) Example 3: Python code to access all the tensors of all dimensions and get only 3 values in each dimension Python3 # import torch moduleimport torch # create an 3 D tensor with 8 elements eacha = torch.tensor([[[1, 2, 3, 4, 5, 6, 7, 8], [10, 11, 12, 13, 14, 15, 16, 17]], [[71, 72, 73, 74, 75, 76, 77, 78], [81, 82, 83, 84, 85, 86, 87, 88]]]) # display actual tensorprint(a) # access all the tensors of all dimensions# and get only 3 values in each dimensionprint(a[0:1, 0:2, :3]) Output: tensor([[[ 1, 2, 3, 4, 5, 6, 7, 8], [10, 11, 12, 13, 14, 15, 16, 17]], [[71, 72, 73, 74, 75, 76, 77, 78], [81, 82, 83, 84, 85, 86, 87, 88]]]) tensor([[[ 1, 2, 3], [10, 11, 12]]]) Example 4: access 8 elements in 1 dimension on all tensors Python3 # import torch moduleimport torch # create an 3 D tensor with 8 elements eacha = torch.tensor([[[1, 2, 3, 4, 5, 6, 7, 8], [10, 11, 12, 13, 14, 15, 16, 17]], [[71, 72, 73, 74, 75, 76, 77, 78], [81, 82, 83, 84, 85, 86, 87, 88]]]) # display actual tensorprint(a) # access 8 elements in 1 dimension on all tensorsprint(a[0:2, 1, 0:8]) Output: tensor([[[ 1, 2, 3, 4, 5, 6, 7, 8], [10, 11, 12, 13, 14, 15, 16, 17]], [[71, 72, 73, 74, 75, 76, 77, 78], [81, 82, 83, 84, 85, 86, 87, 88]]]) tensor([[10, 11, 12, 13, 14, 15, 16, 17], [81, 82, 83, 84, 85, 86, 87, 88]]) 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 ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Python | os.path.join() method How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | datetime.timedelta() function Python | Get unique values from a list
[ { "code": null, "e": 28, "s": 0, "text": "\n23 Aug, 2021" }, { "code": null, "e": 411, "s": 28, "text": "In this article, we will discuss how to access elements in a 3D Tensor in Pytorch. PyTorch is an optimized tensor library majorly used for Deep Learning applications using GPUs and CPUs. It is one of the widely used Machine learning libraries, others being TensorFlow and Keras. The python supports the torch module, so to work with this first we import the module to the workspace." }, { "code": null, "e": 419, "s": 411, "text": "Syntax:" }, { "code": null, "e": 432, "s": 419, "text": "import torch" }, { "code": null, "e": 492, "s": 432, "text": "We can create a vector by using the torch.tensor() function" }, { "code": null, "e": 500, "s": 492, "text": "Syntax:" }, { "code": null, "e": 539, "s": 500, "text": "torch.tensor([value1,value2,.value n])" }, { "code": null, "e": 598, "s": 539, "text": "Example 1: Python code to create an 3 D Tensor and display" }, { "code": null, "e": 606, "s": 598, "text": "Python3" }, { "code": "# import torch moduleimport torch # create an 3 D tensor with 8 elements eacha = torch.tensor([[[1, 2, 3, 4, 5, 6, 7, 8], [10, 11, 12, 13, 14, 15, 16, 17]], [[71, 72, 73, 74, 75, 76, 77, 78], [81, 82, 83, 84, 85, 86, 87, 88]]]) # display actual tensorprint(a)", "e": 922, "s": 606, "text": null }, { "code": null, "e": 930, "s": 922, "text": "Output:" }, { "code": null, "e": 1102, "s": 930, "text": "tensor([[[ 1, 2, 3, 4, 5, 6, 7, 8],\n [10, 11, 12, 13, 14, 15, 16, 17]],\n [[71, 72, 73, 74, 75, 76, 77, 78],\n [81, 82, 83, 84, 85, 86, 87, 88]]])" }, { "code": null, "e": 1321, "s": 1102, "text": "To access elements from a 3-D tensor Slicing can be used. Slicing means selecting the elements present in the tensor by using “:” slice operator. We can slice the elements by using the index of that particular element." }, { "code": null, "e": 1350, "s": 1321, "text": "Note: Indexing starts with 0" }, { "code": null, "e": 1358, "s": 1350, "text": "Syntax:" }, { "code": null, "e": 1491, "s": 1358, "text": "tensor[tensor_position_start:tensor_position_end, tensor_dimension_start:tensor_dimension_end , tensor_value_start:tensor_value_end]" }, { "code": null, "e": 1498, "s": 1491, "text": "where," }, { "code": null, "e": 1562, "s": 1498, "text": "tensor_position_start – Specifies the Tensor to start iterating" }, { "code": null, "e": 1623, "s": 1562, "text": "tensor_position_end – Specifies the Tensor to stop iterating" }, { "code": null, "e": 1721, "s": 1623, "text": "tensor_dimension_start – Specifies the Tensor to start the iteration of tensor in given positions" }, { "code": null, "e": 1816, "s": 1721, "text": "tensor_dimension_stop– Specifies the Tensor to stop the iteration of tensor in given positions" }, { "code": null, "e": 1925, "s": 1816, "text": "tensor_value_start – Specifies the start position of the tensor to iterate the elements given in dimensions" }, { "code": null, "e": 2030, "s": 1925, "text": "tensor_value_stop – Specifies the end position of the tensor to iterate the elements given in dimensions" }, { "code": null, "e": 2081, "s": 2030, "text": "Given below are the various examples for the same." }, { "code": null, "e": 2187, "s": 2081, "text": "Example 2: Python code to access all the tensors of 1 dimension and get only 7 values in that dimension" }, { "code": null, "e": 2195, "s": 2187, "text": "Python3" }, { "code": "# import torch moduleimport torch # create an 3 D tensor with 8 elements eacha = torch.tensor([[[1, 2, 3, 4, 5, 6, 7, 8], [10, 11, 12, 13, 14, 15, 16, 17]], [[71, 72, 73, 74, 75, 76, 77, 78], [81, 82, 83, 84, 85, 86, 87, 88]]]) # display actual tensorprint(a) # access all the tensors of 1 dimension # and get only 7 values in that dimensionprint(a[0:1, 0:1, :7])", "e": 2621, "s": 2195, "text": null }, { "code": null, "e": 2629, "s": 2621, "text": "Output:" }, { "code": null, "e": 2835, "s": 2629, "text": "tensor([[[ 1, 2, 3, 4, 5, 6, 7, 8],\n [10, 11, 12, 13, 14, 15, 16, 17]],\n [[71, 72, 73, 74, 75, 76, 77, 78],\n [81, 82, 83, 84, 85, 86, 87, 88]]])\ntensor([[[1, 2, 3, 4, 5, 6, 7]]])" }, { "code": null, "e": 2943, "s": 2835, "text": "Example 3: Python code to access all the tensors of all dimensions and get only 3 values in each dimension" }, { "code": null, "e": 2951, "s": 2943, "text": "Python3" }, { "code": "# import torch moduleimport torch # create an 3 D tensor with 8 elements eacha = torch.tensor([[[1, 2, 3, 4, 5, 6, 7, 8], [10, 11, 12, 13, 14, 15, 16, 17]], [[71, 72, 73, 74, 75, 76, 77, 78], [81, 82, 83, 84, 85, 86, 87, 88]]]) # display actual tensorprint(a) # access all the tensors of all dimensions# and get only 3 values in each dimensionprint(a[0:1, 0:2, :3])", "e": 3377, "s": 2951, "text": null }, { "code": null, "e": 3385, "s": 3377, "text": "Output:" }, { "code": null, "e": 3604, "s": 3385, "text": "tensor([[[ 1, 2, 3, 4, 5, 6, 7, 8],\n [10, 11, 12, 13, 14, 15, 16, 17]],\n [[71, 72, 73, 74, 75, 76, 77, 78],\n [81, 82, 83, 84, 85, 86, 87, 88]]])\ntensor([[[ 1, 2, 3],\n [10, 11, 12]]])" }, { "code": null, "e": 3663, "s": 3604, "text": "Example 4: access 8 elements in 1 dimension on all tensors" }, { "code": null, "e": 3671, "s": 3663, "text": "Python3" }, { "code": "# import torch moduleimport torch # create an 3 D tensor with 8 elements eacha = torch.tensor([[[1, 2, 3, 4, 5, 6, 7, 8], [10, 11, 12, 13, 14, 15, 16, 17]], [[71, 72, 73, 74, 75, 76, 77, 78], [81, 82, 83, 84, 85, 86, 87, 88]]]) # display actual tensorprint(a) # access 8 elements in 1 dimension on all tensorsprint(a[0:2, 1, 0:8])", "e": 4062, "s": 3671, "text": null }, { "code": null, "e": 4070, "s": 4062, "text": "Output:" }, { "code": null, "e": 4326, "s": 4070, "text": "tensor([[[ 1, 2, 3, 4, 5, 6, 7, 8],\n [10, 11, 12, 13, 14, 15, 16, 17]],\n [[71, 72, 73, 74, 75, 76, 77, 78],\n [81, 82, 83, 84, 85, 86, 87, 88]]])\ntensor([[10, 11, 12, 13, 14, 15, 16, 17],\n [81, 82, 83, 84, 85, 86, 87, 88]])" }, { "code": null, "e": 4333, "s": 4326, "text": "Picked" }, { "code": null, "e": 4348, "s": 4333, "text": "Python-PyTorch" }, { "code": null, "e": 4355, "s": 4348, "text": "Python" }, { "code": null, "e": 4453, "s": 4355, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4485, "s": 4453, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 4512, "s": 4485, "text": "Python Classes and Objects" }, { "code": null, "e": 4533, "s": 4512, "text": "Python OOPs Concepts" }, { "code": null, "e": 4556, "s": 4533, "text": "Introduction To PYTHON" }, { "code": null, "e": 4612, "s": 4556, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 4643, "s": 4612, "text": "Python | os.path.join() method" }, { "code": null, "e": 4685, "s": 4643, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 4727, "s": 4685, "text": "Check if element exists in list in Python" }, { "code": null, "e": 4766, "s": 4727, "text": "Python | datetime.timedelta() function" } ]
Longest Subarray consisting of unique elements from an Array
09 Jun, 2022 Given an array arr[] consisting of N integers, the task is to find the largest subarray consisting of unique elements only. Examples: Input: arr[] = {1, 2, 3, 4, 5, 1, 2, 3} Output: 5 Explanation: One possible subarray is {1, 2, 3, 4, 5}. Input: arr[]={1, 2, 4, 4, 5, 6, 7, 8, 3, 4, 5, 3, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4} Output: 8 Explanation: Only possible subarray is {3, 4, 5, 6, 7, 8, 1, 2}. Naive Approach: The simplest approach to solve the problem is to generate all subarrays from the given array and check if it contains any duplicates or not to use HashSet. Find the longest subarray satisfying the condition. Time Complexity: O(N3logN) Auxiliary Space: O(N) Efficient Approach: The above approach can be optimized by HashMap. Follow the steps below to solve the problem: Initialize a variable j, to store the maximum value of the index such that there are no repeated elements between index i and jTraverse the array and keep updating j based on the previous occurrence of a[i] stored in the HashMap.After updating j, update ans accordingly to store the maximum length of the desired subarray.Print ans, after traversal, is completed. Initialize a variable j, to store the maximum value of the index such that there are no repeated elements between index i and j Traverse the array and keep updating j based on the previous occurrence of a[i] stored in the HashMap. After updating j, update ans accordingly to store the maximum length of the desired subarray. Print ans, after traversal, is completed. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program to implement// the above approach#include <bits/stdc++.h>using namespace std; // Function to find largest// subarray with no duplicatesint largest_subarray(int a[], int n){ // Stores index of array elements unordered_map<int, int> index; int ans = 0; for (int i = 0, j = 0; i < n; i++) { // Update j based on previous // occurrence of a[i] j = max(index[a[i]], j); // Update ans to store maximum // length of subarray ans = max(ans, i - j + 1); // Store the index of current // occurrence of a[i] index[a[i]] = i + 1; } // Return final ans return ans;} // Driver Codeint32_t main(){ int arr[] = { 1, 2, 3, 4, 5, 1, 2, 3 }; int n = sizeof(arr) / sizeof(arr[0]); cout << largest_subarray(arr, n);} // Java program to implement// the above approachimport java.util.*;class GFG{ // Function to find largest// subarray with no duplicatesstatic int largest_subarray(int a[], int n){ // Stores index of array elements HashMap<Integer, Integer> index = new HashMap<Integer, Integer>(); int ans = 0; for(int i = 0, j = 0; i < n; i++) { // Update j based on previous // occurrence of a[i] j = Math.max(index.containsKey(a[i]) ? index.get(a[i]) : 0, j); // Update ans to store maximum // length of subarray ans = Math.max(ans, i - j + 1); // Store the index of current // occurrence of a[i] index.put(a[i], i + 1); } // Return final ans return ans;} // Driver Codepublic static void main(String[] args){ int arr[] = { 1, 2, 3, 4, 5, 1, 2, 3 }; int n = arr.length; System.out.print(largest_subarray(arr, n));}} // This code is contributed by Rajput-Ji # Python3 program to implement# the above approachfrom collections import defaultdict # Function to find largest# subarray with no duplicatesdef largest_subarray(a, n): # Stores index of array elements index = defaultdict(lambda : 0) ans = 0 j = 0 for i in range(n): # Update j based on previous # occurrence of a[i] j = max(index[a[i]], j) # Update ans to store maximum # length of subarray ans = max(ans, i - j + 1) # Store the index of current # occurrence of a[i] index[a[i]] = i + 1 i += 1 # Return final ans return ans # Driver Codearr = [ 1, 2, 3, 4, 5, 1, 2, 3 ]n = len(arr) # Function callprint(largest_subarray(arr, n)) # This code is contributed by Shivam Singh // C# program to implement// the above approachusing System;using System.Collections.Generic; class GFG{ // Function to find largest// subarray with no duplicatesstatic int largest_subarray(int []a, int n){ // Stores index of array elements Dictionary<int, int> index = new Dictionary<int, int>(); int ans = 0; for(int i = 0, j = 0; i < n; i++) { // Update j based on previous // occurrence of a[i] j = Math.Max(index.ContainsKey(a[i]) ? index[a[i]] : 0, j); // Update ans to store maximum // length of subarray ans = Math.Max(ans, i - j + 1); // Store the index of current // occurrence of a[i] if(index.ContainsKey(a[i])) index[a[i]] = i + 1; else index.Add(a[i], i + 1); } // Return readonly ans return ans;} // Driver Codepublic static void Main(String[] args){ int []arr = { 1, 2, 3, 4, 5, 1, 2, 3 }; int n = arr.Length; Console.Write(largest_subarray(arr, n));}} // This code is contributed by Amit Katiyar <script> // Javascript program to implement// the above approach // Function to find largest// subarray with no duplicatesfunction largest_subarray(a, n){ // Stores index of array elements let index = new Map(); let ans = 0; for(let i = 0, j = 0; i < n; i++) { // Update j based on previous // occurrence of a[i] j = Math.max(index.has(a[i]) ? index.get(a[i]) : 0, j); // Update ans to store maximum // length of subarray ans = Math.max(ans, i - j + 1); // Store the index of current // occurrence of a[i] index.set(a[i], i + 1); } // Return final ans return ans;} // Driver code let arr = [ 1, 2, 3, 4, 5, 1, 2, 3 ]; let n = arr.length; document.write(largest_subarray(arr, n)); </script> 5 Time Complexity: O(N) in best case and O(n^2) in worst case. NOTE: We can make Time complexity equal to O(n * logn) by using balanced binary tree structures (`std::map` in c++ and `TreeMap` in Java.) instead of Hash structures.Auxiliary Space: O(N) SHIVAMSINGH67 Rajput-Ji amit143katiyar Vishalmast souravghosh0416 surindertarika1234 anikaseth98 ishwarendra27 frequency-counting Java-HashMap subarray Arrays Greedy Hash Searching Arrays Searching Hash Greedy Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Maximum and minimum of an array using minimum number of comparisons Top 50 Array Coding Problems for Interviews Multidimensional Arrays in Java Stack Data Structure (Introduction and Program) Linear Search Dijkstra's shortest path algorithm | Greedy Algo-7 Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5 Write a program to print all permutations of a given string Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2 Huffman Coding | Greedy Algo-3
[ { "code": null, "e": 54, "s": 26, "text": "\n09 Jun, 2022" }, { "code": null, "e": 178, "s": 54, "text": "Given an array arr[] consisting of N integers, the task is to find the largest subarray consisting of unique elements only." }, { "code": null, "e": 188, "s": 178, "text": "Examples:" }, { "code": null, "e": 293, "s": 188, "text": "Input: arr[] = {1, 2, 3, 4, 5, 1, 2, 3} Output: 5 Explanation: One possible subarray is {1, 2, 3, 4, 5}." }, { "code": null, "e": 448, "s": 293, "text": "Input: arr[]={1, 2, 4, 4, 5, 6, 7, 8, 3, 4, 5, 3, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4} Output: 8 Explanation: Only possible subarray is {3, 4, 5, 6, 7, 8, 1, 2}." }, { "code": null, "e": 721, "s": 448, "text": "Naive Approach: The simplest approach to solve the problem is to generate all subarrays from the given array and check if it contains any duplicates or not to use HashSet. Find the longest subarray satisfying the condition. Time Complexity: O(N3logN) Auxiliary Space: O(N)" }, { "code": null, "e": 834, "s": 721, "text": "Efficient Approach: The above approach can be optimized by HashMap. Follow the steps below to solve the problem:" }, { "code": null, "e": 1198, "s": 834, "text": "Initialize a variable j, to store the maximum value of the index such that there are no repeated elements between index i and jTraverse the array and keep updating j based on the previous occurrence of a[i] stored in the HashMap.After updating j, update ans accordingly to store the maximum length of the desired subarray.Print ans, after traversal, is completed." }, { "code": null, "e": 1326, "s": 1198, "text": "Initialize a variable j, to store the maximum value of the index such that there are no repeated elements between index i and j" }, { "code": null, "e": 1429, "s": 1326, "text": "Traverse the array and keep updating j based on the previous occurrence of a[i] stored in the HashMap." }, { "code": null, "e": 1523, "s": 1429, "text": "After updating j, update ans accordingly to store the maximum length of the desired subarray." }, { "code": null, "e": 1565, "s": 1523, "text": "Print ans, after traversal, is completed." }, { "code": null, "e": 1616, "s": 1565, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 1620, "s": 1616, "text": "C++" }, { "code": null, "e": 1625, "s": 1620, "text": "Java" }, { "code": null, "e": 1633, "s": 1625, "text": "Python3" }, { "code": null, "e": 1636, "s": 1633, "text": "C#" }, { "code": null, "e": 1647, "s": 1636, "text": "Javascript" }, { "code": "// C++ program to implement// the above approach#include <bits/stdc++.h>using namespace std; // Function to find largest// subarray with no duplicatesint largest_subarray(int a[], int n){ // Stores index of array elements unordered_map<int, int> index; int ans = 0; for (int i = 0, j = 0; i < n; i++) { // Update j based on previous // occurrence of a[i] j = max(index[a[i]], j); // Update ans to store maximum // length of subarray ans = max(ans, i - j + 1); // Store the index of current // occurrence of a[i] index[a[i]] = i + 1; } // Return final ans return ans;} // Driver Codeint32_t main(){ int arr[] = { 1, 2, 3, 4, 5, 1, 2, 3 }; int n = sizeof(arr) / sizeof(arr[0]); cout << largest_subarray(arr, n);}", "e": 2455, "s": 1647, "text": null }, { "code": "// Java program to implement// the above approachimport java.util.*;class GFG{ // Function to find largest// subarray with no duplicatesstatic int largest_subarray(int a[], int n){ // Stores index of array elements HashMap<Integer, Integer> index = new HashMap<Integer, Integer>(); int ans = 0; for(int i = 0, j = 0; i < n; i++) { // Update j based on previous // occurrence of a[i] j = Math.max(index.containsKey(a[i]) ? index.get(a[i]) : 0, j); // Update ans to store maximum // length of subarray ans = Math.max(ans, i - j + 1); // Store the index of current // occurrence of a[i] index.put(a[i], i + 1); } // Return final ans return ans;} // Driver Codepublic static void main(String[] args){ int arr[] = { 1, 2, 3, 4, 5, 1, 2, 3 }; int n = arr.length; System.out.print(largest_subarray(arr, n));}} // This code is contributed by Rajput-Ji", "e": 3478, "s": 2455, "text": null }, { "code": "# Python3 program to implement# the above approachfrom collections import defaultdict # Function to find largest# subarray with no duplicatesdef largest_subarray(a, n): # Stores index of array elements index = defaultdict(lambda : 0) ans = 0 j = 0 for i in range(n): # Update j based on previous # occurrence of a[i] j = max(index[a[i]], j) # Update ans to store maximum # length of subarray ans = max(ans, i - j + 1) # Store the index of current # occurrence of a[i] index[a[i]] = i + 1 i += 1 # Return final ans return ans # Driver Codearr = [ 1, 2, 3, 4, 5, 1, 2, 3 ]n = len(arr) # Function callprint(largest_subarray(arr, n)) # This code is contributed by Shivam Singh", "e": 4254, "s": 3478, "text": null }, { "code": "// C# program to implement// the above approachusing System;using System.Collections.Generic; class GFG{ // Function to find largest// subarray with no duplicatesstatic int largest_subarray(int []a, int n){ // Stores index of array elements Dictionary<int, int> index = new Dictionary<int, int>(); int ans = 0; for(int i = 0, j = 0; i < n; i++) { // Update j based on previous // occurrence of a[i] j = Math.Max(index.ContainsKey(a[i]) ? index[a[i]] : 0, j); // Update ans to store maximum // length of subarray ans = Math.Max(ans, i - j + 1); // Store the index of current // occurrence of a[i] if(index.ContainsKey(a[i])) index[a[i]] = i + 1; else index.Add(a[i], i + 1); } // Return readonly ans return ans;} // Driver Codepublic static void Main(String[] args){ int []arr = { 1, 2, 3, 4, 5, 1, 2, 3 }; int n = arr.Length; Console.Write(largest_subarray(arr, n));}} // This code is contributed by Amit Katiyar", "e": 5394, "s": 4254, "text": null }, { "code": "<script> // Javascript program to implement// the above approach // Function to find largest// subarray with no duplicatesfunction largest_subarray(a, n){ // Stores index of array elements let index = new Map(); let ans = 0; for(let i = 0, j = 0; i < n; i++) { // Update j based on previous // occurrence of a[i] j = Math.max(index.has(a[i]) ? index.get(a[i]) : 0, j); // Update ans to store maximum // length of subarray ans = Math.max(ans, i - j + 1); // Store the index of current // occurrence of a[i] index.set(a[i], i + 1); } // Return final ans return ans;} // Driver code let arr = [ 1, 2, 3, 4, 5, 1, 2, 3 ]; let n = arr.length; document.write(largest_subarray(arr, n)); </script>", "e": 6217, "s": 5394, "text": null }, { "code": null, "e": 6219, "s": 6217, "text": "5" }, { "code": null, "e": 6282, "s": 6221, "text": "Time Complexity: O(N) in best case and O(n^2) in worst case." }, { "code": null, "e": 6470, "s": 6282, "text": "NOTE: We can make Time complexity equal to O(n * logn) by using balanced binary tree structures (`std::map` in c++ and `TreeMap` in Java.) instead of Hash structures.Auxiliary Space: O(N)" }, { "code": null, "e": 6484, "s": 6470, "text": "SHIVAMSINGH67" }, { "code": null, "e": 6494, "s": 6484, "text": "Rajput-Ji" }, { "code": null, "e": 6509, "s": 6494, "text": "amit143katiyar" }, { "code": null, "e": 6520, "s": 6509, "text": "Vishalmast" }, { "code": null, "e": 6536, "s": 6520, "text": "souravghosh0416" }, { "code": null, "e": 6555, "s": 6536, "text": "surindertarika1234" }, { "code": null, "e": 6567, "s": 6555, "text": "anikaseth98" }, { "code": null, "e": 6581, "s": 6567, "text": "ishwarendra27" }, { "code": null, "e": 6600, "s": 6581, "text": "frequency-counting" }, { "code": null, "e": 6613, "s": 6600, "text": "Java-HashMap" }, { "code": null, "e": 6622, "s": 6613, "text": "subarray" }, { "code": null, "e": 6629, "s": 6622, "text": "Arrays" }, { "code": null, "e": 6636, "s": 6629, "text": "Greedy" }, { "code": null, "e": 6641, "s": 6636, "text": "Hash" }, { "code": null, "e": 6651, "s": 6641, "text": "Searching" }, { "code": null, "e": 6658, "s": 6651, "text": "Arrays" }, { "code": null, "e": 6668, "s": 6658, "text": "Searching" }, { "code": null, "e": 6673, "s": 6668, "text": "Hash" }, { "code": null, "e": 6680, "s": 6673, "text": "Greedy" }, { "code": null, "e": 6778, "s": 6680, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6846, "s": 6778, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 6890, "s": 6846, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 6922, "s": 6890, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 6970, "s": 6922, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 6984, "s": 6970, "text": "Linear Search" }, { "code": null, "e": 7035, "s": 6984, "text": "Dijkstra's shortest path algorithm | Greedy Algo-7" }, { "code": null, "e": 7086, "s": 7035, "text": "Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5" }, { "code": null, "e": 7146, "s": 7086, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 7204, "s": 7146, "text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2" } ]
JavaFX | ChoiceBox
13 Jun, 2022 ChoiceBox is a part of the JavaFX package. ChoiceBox shows a set of items and allows the user to select a single choice and it will show the currently selected item on the top. ChoiceBox by default has no selected item unless otherwise selected. One may either specify the items and then the selected item, or you may specify the selected item and then the items. Constructor of the ChoiceBox class are: ChoiceBox(): Creates a new empty ChoiceBox.ChoiceBox(ObservableList items): Creates a new ChoiceBox with the given set of items. ChoiceBox(): Creates a new empty ChoiceBox. ChoiceBox(ObservableList items): Creates a new ChoiceBox with the given set of items. Commonly used methods: Below program illustrate the use of ChoiceBox: Program to create a ChoiceBox and add items to it: This program creates a ChoiceBox named c and add a list of string to it using(ChoiceBox(FXCollections.observableArrayList(string_array))). We would add the choice and a label to the tilepane(getChildren().add() function). Then we will create a stage (container) and add the tilepane to the scene and add the scene to the stage. Then display the stage using show() function. Program to create a ChoiceBox and add items to it: This program creates a ChoiceBox named c and add a list of string to it using(ChoiceBox(FXCollections.observableArrayList(string_array))). We would add the choice and a label to the tilepane(getChildren().add() function). Then we will create a stage (container) and add the tilepane to the scene and add the scene to the stage. Then display the stage using show() function. Java // Java Program to create a ChoiceBox and add items to it.import javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.collections.*;import javafx.stage.Stage;public class Choice_1 extends Application { // launch the application public void start(Stage s) { // set title for the stage s.setTitle("creating ChoiceBox"); // create a button Button b = new Button("show"); // create a tile pane TilePane r = new TilePane(); // create a label Label l = new Label("This is a choice box"); // string array String st[] = { "Arnab", "Andrew", "Ankit", "None" }; // create a choiceBox ChoiceBox c = new ChoiceBox(FXCollections.observableArrayList(st)); // add ChoiceBox r.getChildren().add(l); r.getChildren().add(c); // create a scene Scene sc = new Scene(r, 200, 200); // set the scene s.setScene(sc); s.show(); } public static void main(String args[]) { // launch the application launch(args); }} Output: Program to create a ChoiceBox and add listener to it: This program creates a ChoiceBox named c and add a list of string to it using(ChoiceBox(FXCollections.observableArrayList(string_array))). We would add a change listener to detect when the user selects an item of the choice (we will add the listener using addListener() function ). The change listener has a function(public void changed(ObservableValue ov, Number value, Number new_value)) which is invoked when the selection of choice is changed. We would add the choice and a label to the tilepane(getChildren().add() function). Then we will create a stage (container) and add the tilepane to the scene and add the scene to the stage. Finally, display the stage using show() function. Output: Program to create a ChoiceBox and add listener to it: This program creates a ChoiceBox named c and add a list of string to it using(ChoiceBox(FXCollections.observableArrayList(string_array))). We would add a change listener to detect when the user selects an item of the choice (we will add the listener using addListener() function ). The change listener has a function(public void changed(ObservableValue ov, Number value, Number new_value)) which is invoked when the selection of choice is changed. We would add the choice and a label to the tilepane(getChildren().add() function). Then we will create a stage (container) and add the tilepane to the scene and add the scene to the stage. Finally, display the stage using show() function. Java // Java Program to create a ChoiceBox and add listener to it.import javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.collections.*;import javafx.beans.value.*;import javafx.stage.Stage;public class Choice_2 extends Application { // launch the application public void start(Stage s) { // set title for the stage s.setTitle("creating ChoiceBox"); // create a button Button b = new Button("show"); // create a tile pane TilePane r = new TilePane(); // create a label Label l = new Label("This is a choice box"); Label l1 = new Label("nothing selected"); // string array String st[] = { "Arnab", "Andrew", "Ankit", "None" }; // create a choiceBox ChoiceBox c = new ChoiceBox(FXCollections.observableArrayList(st)); // add a listener c.getSelectionModel().selectedIndexProperty().addListener(new ChangeListener<Number>() { // if the item of the list is changed public void changed(ObservableValue ov, Number value, Number new_value) { // set the text for the label to the selected item l1.setText(st[new_value.intValue()] + " selected"); } }); // add ChoiceBox r.getChildren().add(l); r.getChildren().add(c); r.getChildren().add(l1); // create a scene Scene sc = new Scene(r, 200, 200); // set the scene s.setScene(sc); s.show(); } public static void main(String args[]) { // launch the application launch(args); }} Output: Output: Note: The above programs might not run in an online IDE please use an offline compiler. Reference: https://docs.oracle.com/javase/8/javafx/api/javafx/scene/control/ChoiceBox.html ManasChhabra2 vinayedula JavaFX Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n13 Jun, 2022" }, { "code": null, "e": 432, "s": 28, "text": "ChoiceBox is a part of the JavaFX package. ChoiceBox shows a set of items and allows the user to select a single choice and it will show the currently selected item on the top. ChoiceBox by default has no selected item unless otherwise selected. One may either specify the items and then the selected item, or you may specify the selected item and then the items. Constructor of the ChoiceBox class are:" }, { "code": null, "e": 561, "s": 432, "text": "ChoiceBox(): Creates a new empty ChoiceBox.ChoiceBox(ObservableList items): Creates a new ChoiceBox with the given set of items." }, { "code": null, "e": 605, "s": 561, "text": "ChoiceBox(): Creates a new empty ChoiceBox." }, { "code": null, "e": 691, "s": 605, "text": "ChoiceBox(ObservableList items): Creates a new ChoiceBox with the given set of items." }, { "code": null, "e": 714, "s": 691, "text": "Commonly used methods:" }, { "code": null, "e": 761, "s": 714, "text": "Below program illustrate the use of ChoiceBox:" }, { "code": null, "e": 1187, "s": 761, "text": "Program to create a ChoiceBox and add items to it: This program creates a ChoiceBox named c and add a list of string to it using(ChoiceBox(FXCollections.observableArrayList(string_array))). We would add the choice and a label to the tilepane(getChildren().add() function). Then we will create a stage (container) and add the tilepane to the scene and add the scene to the stage. Then display the stage using show() function. " }, { "code": null, "e": 1613, "s": 1187, "text": "Program to create a ChoiceBox and add items to it: This program creates a ChoiceBox named c and add a list of string to it using(ChoiceBox(FXCollections.observableArrayList(string_array))). We would add the choice and a label to the tilepane(getChildren().add() function). Then we will create a stage (container) and add the tilepane to the scene and add the scene to the stage. Then display the stage using show() function. " }, { "code": null, "e": 1618, "s": 1613, "text": "Java" }, { "code": "// Java Program to create a ChoiceBox and add items to it.import javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.collections.*;import javafx.stage.Stage;public class Choice_1 extends Application { // launch the application public void start(Stage s) { // set title for the stage s.setTitle(\"creating ChoiceBox\"); // create a button Button b = new Button(\"show\"); // create a tile pane TilePane r = new TilePane(); // create a label Label l = new Label(\"This is a choice box\"); // string array String st[] = { \"Arnab\", \"Andrew\", \"Ankit\", \"None\" }; // create a choiceBox ChoiceBox c = new ChoiceBox(FXCollections.observableArrayList(st)); // add ChoiceBox r.getChildren().add(l); r.getChildren().add(c); // create a scene Scene sc = new Scene(r, 200, 200); // set the scene s.setScene(sc); s.show(); } public static void main(String args[]) { // launch the application launch(args); }}", "e": 2836, "s": 1618, "text": null }, { "code": null, "e": 3586, "s": 2836, "text": "Output: Program to create a ChoiceBox and add listener to it: This program creates a ChoiceBox named c and add a list of string to it using(ChoiceBox(FXCollections.observableArrayList(string_array))). We would add a change listener to detect when the user selects an item of the choice (we will add the listener using addListener() function ). The change listener has a function(public void changed(ObservableValue ov, Number value, Number new_value)) which is invoked when the selection of choice is changed. We would add the choice and a label to the tilepane(getChildren().add() function). Then we will create a stage (container) and add the tilepane to the scene and add the scene to the stage. Finally, display the stage using show() function. " }, { "code": null, "e": 3595, "s": 3586, "text": "Output: " }, { "code": null, "e": 4337, "s": 3595, "text": "Program to create a ChoiceBox and add listener to it: This program creates a ChoiceBox named c and add a list of string to it using(ChoiceBox(FXCollections.observableArrayList(string_array))). We would add a change listener to detect when the user selects an item of the choice (we will add the listener using addListener() function ). The change listener has a function(public void changed(ObservableValue ov, Number value, Number new_value)) which is invoked when the selection of choice is changed. We would add the choice and a label to the tilepane(getChildren().add() function). Then we will create a stage (container) and add the tilepane to the scene and add the scene to the stage. Finally, display the stage using show() function. " }, { "code": null, "e": 4342, "s": 4337, "text": "Java" }, { "code": "// Java Program to create a ChoiceBox and add listener to it.import javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.collections.*;import javafx.beans.value.*;import javafx.stage.Stage;public class Choice_2 extends Application { // launch the application public void start(Stage s) { // set title for the stage s.setTitle(\"creating ChoiceBox\"); // create a button Button b = new Button(\"show\"); // create a tile pane TilePane r = new TilePane(); // create a label Label l = new Label(\"This is a choice box\"); Label l1 = new Label(\"nothing selected\"); // string array String st[] = { \"Arnab\", \"Andrew\", \"Ankit\", \"None\" }; // create a choiceBox ChoiceBox c = new ChoiceBox(FXCollections.observableArrayList(st)); // add a listener c.getSelectionModel().selectedIndexProperty().addListener(new ChangeListener<Number>() { // if the item of the list is changed public void changed(ObservableValue ov, Number value, Number new_value) { // set the text for the label to the selected item l1.setText(st[new_value.intValue()] + \" selected\"); } }); // add ChoiceBox r.getChildren().add(l); r.getChildren().add(c); r.getChildren().add(l1); // create a scene Scene sc = new Scene(r, 200, 200); // set the scene s.setScene(sc); s.show(); } public static void main(String args[]) { // launch the application launch(args); }}", "e": 6098, "s": 4342, "text": null }, { "code": null, "e": 6107, "s": 6098, "text": "Output: " }, { "code": null, "e": 6116, "s": 6107, "text": "Output: " }, { "code": null, "e": 6295, "s": 6116, "text": "Note: The above programs might not run in an online IDE please use an offline compiler. Reference: https://docs.oracle.com/javase/8/javafx/api/javafx/scene/control/ChoiceBox.html" }, { "code": null, "e": 6309, "s": 6295, "text": "ManasChhabra2" }, { "code": null, "e": 6320, "s": 6309, "text": "vinayedula" }, { "code": null, "e": 6327, "s": 6320, "text": "JavaFX" }, { "code": null, "e": 6332, "s": 6327, "text": "Java" }, { "code": null, "e": 6337, "s": 6332, "text": "Java" } ]
Loops (For and While) and Control Statements in Octave
01 Aug, 2020 Control statements are expressions used to control the execution and flow of the program based on the conditions provided in the statements. These structures are used to make a decision after assessing the variable. In this article, we’ll discuss control statements like the if statement, for and while loops with examples. This control structure checks the expression provided in parenthesis is true or not. If true, the execution of the statements continues.Syntax : if (condition) statements ... ... end (endif can also be used) Example : % initializing variables variable1 and variable2 variable1 = 20;variable2 = 20; % check the if conditionif variable1 == variable2, % if the condition is true this statement will executedisp('The variables are Equal'); % end the if statementendif; Output: The variables are Equal It is similar to if condition but when the test expression in if condition fails, then statements in else condition are executed.Syntax : if (condition) statements ... ... else statements ... ... end (endif can also be used) Example : % initializing variables variable1 and variable2 variable1 = 20;variable2 = 40; % check the if conditionif variable1 == variable2, % if the condition is true this statement will executedisp('The variables are Equal'); % if the condition is false else statement will executeelsedisp('The variables are Not Equal'); %end the if-else statementend; Output: The variables are Not Equal When the first if condition fails, we can use elseif to supply another if condition.Syntax : if (condition) statements ... ... elseif (condition) statements ... ... else statements ... ... end (endif can also be used) Example : % initializing the variable varvar = 50; % check the if conditionif var < 50,disp('The variable is less than 50'); % check the elseif conditionelseif var > 50,disp('The variable is greater than 50'); % if both the above condition is false else% statement will executeelsedisp('The variable is 50'); % end the if..elseif.. statementsend; Output: The variable is 50 It is a type of loop or sequence of statements executed repeatedly until exit condition is reached.Syntax : for var = expression body end (endfor can also be used) Example 1 : Printing numbers from 1 to 5 : % the value of i will move from 1 to 5% with an increment of 1for i = 1:5, % displays value of idisp(i); % end the for loopend; Output : 1 2 3 4 5 Example 2 : for loop with vectors : % making a column vector from 1 to 10v = [1; 2; 3; 4; 5; 6; 7; 8; 9; 10]; % the value of i will move from 1 to 10 % with an increment of 1for i = 1:10, % modifying the value of ith element % in the column vector as v(i) * 10 v(i) = v(i) * 10; % end the for loopend; % displays the v vector with modified valuesdisp(v) Output : 10 20 30 40 50 60 70 80 90 100 Example 4 : Program to print the Fibonacci series up to 10 elements using for loop : % create a row vector of 10 elements all as '1' fibonacci = ones(1, 10); % the value of i will move from 3 to 10 over the % increment of 1for i = 3:10 % the ith term of fibonacci will computed % as the sum of its previous 2 terms fibonacci(i) = fibonacci(i - 1) + fibonacci(i - 2); % end the for loopendfor % print the fibonacci seriesdisp(fibonacci) Output : 1 1 2 3 5 8 13 21 34 55 The while loop is another kind of loop iterated until a condition is satisfied. The testing expression is checked first before executing the body of the loop. Syntax : while (condition) body end (endwhile can also be used) Example : Display numbers from 1 to 10 : % initializing the variable i with 1i = 1; % while conditionwhile i <= 10 % displaying the value of idisp(i); % make an increment of 1 in the value of ii = i + 1; % end the while loopendwhile Output : 1 2 3 4 5 6 7 8 9 10 It is used to exit from a loop. Example 1 : We will be making a row vector and will only modify the first 6 values using the break statement. % making a row vector of 1x10, starting from 1 % and the next value is +10 of it's previous valuev = [1:10:100]; % the value of i will move from 1 to 10 % with an increment of 1for i = 1:10, % making the ith element in vector to 0v(i) = 0; % if the condition is true the break statement % will execute and the loop will terminateif i == 6,break; % end the if conditionend; % end the for loopend; % displays the modified vector vdisp(v) Output : 0 0 0 0 0 0 61 71 81 91 Example 2 : break statement with while loop : % initializing the variable i with 1i = 1; % the while condition is always truewhile true % display the value of idisp(i); % display the below contentdisp(" is less then 5"); % make an increment of 1 in value of ii = i + 1; % if the if condition is true loop will break if i == 5,break; % end the if statementend; % end the whileend; Output : 1 is less then 5 2 is less then 5 3 is less then 5 4 is less then 5 Octave-GNU Programming Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Decorators with parameters in Python C# | Data Types Shallow Copy and Deep Copy in C++ Difference between Shallow and Deep copy of a class Kotlin Array Top 10 Programming Languages to Learn in 2022 Advantages and Disadvantages of OOP Top 10 Fastest Programming Languages Difference between while and do-while loop in C, C++, Java Introduction of Object Oriented Programming
[ { "code": null, "e": 28, "s": 0, "text": "\n01 Aug, 2020" }, { "code": null, "e": 352, "s": 28, "text": "Control statements are expressions used to control the execution and flow of the program based on the conditions provided in the statements. These structures are used to make a decision after assessing the variable. In this article, we’ll discuss control statements like the if statement, for and while loops with examples." }, { "code": null, "e": 497, "s": 352, "text": "This control structure checks the expression provided in parenthesis is true or not. If true, the execution of the statements continues.Syntax :" }, { "code": null, "e": 574, "s": 497, "text": "if (condition)\n statements\n ...\n ...\nend \n(endif can also be used)\n" }, { "code": null, "e": 584, "s": 574, "text": "Example :" }, { "code": "% initializing variables variable1 and variable2 variable1 = 20;variable2 = 20; % check the if conditionif variable1 == variable2, % if the condition is true this statement will executedisp('The variables are Equal'); % end the if statementendif;", "e": 837, "s": 584, "text": null }, { "code": null, "e": 845, "s": 837, "text": "Output:" }, { "code": null, "e": 870, "s": 845, "text": "The variables are Equal\n" }, { "code": null, "e": 1008, "s": 870, "text": "It is similar to if condition but when the test expression in if condition fails, then statements in else condition are executed.Syntax :" }, { "code": null, "e": 1121, "s": 1008, "text": "if (condition)\n statements\n ...\n ...\nelse\n statements\n ...\n ...\nend \n(endif can also be used)\n" }, { "code": null, "e": 1131, "s": 1121, "text": "Example :" }, { "code": "% initializing variables variable1 and variable2 variable1 = 20;variable2 = 40; % check the if conditionif variable1 == variable2, % if the condition is true this statement will executedisp('The variables are Equal'); % if the condition is false else statement will executeelsedisp('The variables are Not Equal'); %end the if-else statementend; ", "e": 1483, "s": 1131, "text": null }, { "code": null, "e": 1491, "s": 1483, "text": "Output:" }, { "code": null, "e": 1520, "s": 1491, "text": "The variables are Not Equal\n" }, { "code": null, "e": 1613, "s": 1520, "text": "When the first if condition fails, we can use elseif to supply another if condition.Syntax :" }, { "code": null, "e": 1775, "s": 1613, "text": "if (condition)\n statements\n ...\n ...\nelseif (condition)\n statements\n ...\n ...\nelse\n statements\n ...\n ...\nend\n(endif can also be used)\n" }, { "code": null, "e": 1785, "s": 1775, "text": "Example :" }, { "code": "% initializing the variable varvar = 50; % check the if conditionif var < 50,disp('The variable is less than 50'); % check the elseif conditionelseif var > 50,disp('The variable is greater than 50'); % if both the above condition is false else% statement will executeelsedisp('The variable is 50'); % end the if..elseif.. statementsend;", "e": 2126, "s": 1785, "text": null }, { "code": null, "e": 2134, "s": 2126, "text": "Output:" }, { "code": null, "e": 2154, "s": 2134, "text": "The variable is 50\n" }, { "code": null, "e": 2262, "s": 2154, "text": "It is a type of loop or sequence of statements executed repeatedly until exit condition is reached.Syntax :" }, { "code": null, "e": 2323, "s": 2262, "text": "for var = expression\n body\nend\n(endfor can also be used)\n" }, { "code": null, "e": 2366, "s": 2323, "text": "Example 1 : Printing numbers from 1 to 5 :" }, { "code": "% the value of i will move from 1 to 5% with an increment of 1for i = 1:5, % displays value of idisp(i); % end the for loopend;", "e": 2496, "s": 2366, "text": null }, { "code": null, "e": 2505, "s": 2496, "text": "Output :" }, { "code": null, "e": 2521, "s": 2505, "text": " 1\n 2\n 3\n 4\n 5\n" }, { "code": null, "e": 2557, "s": 2521, "text": "Example 2 : for loop with vectors :" }, { "code": "% making a column vector from 1 to 10v = [1; 2; 3; 4; 5; 6; 7; 8; 9; 10]; % the value of i will move from 1 to 10 % with an increment of 1for i = 1:10, % modifying the value of ith element % in the column vector as v(i) * 10 v(i) = v(i) * 10; % end the for loopend; % displays the v vector with modified valuesdisp(v)", "e": 2883, "s": 2557, "text": null }, { "code": null, "e": 2892, "s": 2883, "text": "Output :" }, { "code": null, "e": 2963, "s": 2892, "text": " 10\n 20\n 30\n 40\n 50\n 60\n 70\n 80\n 90\n 100\n" }, { "code": null, "e": 3048, "s": 2963, "text": "Example 4 : Program to print the Fibonacci series up to 10 elements using for loop :" }, { "code": "% create a row vector of 10 elements all as '1' fibonacci = ones(1, 10); % the value of i will move from 3 to 10 over the % increment of 1for i = 3:10 % the ith term of fibonacci will computed % as the sum of its previous 2 terms fibonacci(i) = fibonacci(i - 1) + fibonacci(i - 2); % end the for loopendfor % print the fibonacci seriesdisp(fibonacci)", "e": 3406, "s": 3048, "text": null }, { "code": null, "e": 3415, "s": 3406, "text": "Output :" }, { "code": null, "e": 3467, "s": 3415, "text": " 1 1 2 3 5 8 13 21 34 55\n" }, { "code": null, "e": 3626, "s": 3467, "text": "The while loop is another kind of loop iterated until a condition is satisfied. The testing expression is checked first before executing the body of the loop." }, { "code": null, "e": 3635, "s": 3626, "text": "Syntax :" }, { "code": null, "e": 3695, "s": 3635, "text": "while (condition)\n body\nend\n(endwhile can also be used)\n" }, { "code": null, "e": 3736, "s": 3695, "text": "Example : Display numbers from 1 to 10 :" }, { "code": "% initializing the variable i with 1i = 1; % while conditionwhile i <= 10 % displaying the value of idisp(i); % make an increment of 1 in the value of ii = i + 1; % end the while loopendwhile", "e": 3932, "s": 3736, "text": null }, { "code": null, "e": 3941, "s": 3932, "text": "Output :" }, { "code": null, "e": 3973, "s": 3941, "text": " 1\n 2\n 3\n 4\n 5\n 6\n 7\n 8\n 9\n 10\n" }, { "code": null, "e": 4005, "s": 3973, "text": "It is used to exit from a loop." }, { "code": null, "e": 4115, "s": 4005, "text": "Example 1 : We will be making a row vector and will only modify the first 6 values using the break statement." }, { "code": "% making a row vector of 1x10, starting from 1 % and the next value is +10 of it's previous valuev = [1:10:100]; % the value of i will move from 1 to 10 % with an increment of 1for i = 1:10, % making the ith element in vector to 0v(i) = 0; % if the condition is true the break statement % will execute and the loop will terminateif i == 6,break; % end the if conditionend; % end the for loopend; % displays the modified vector vdisp(v)", "e": 4557, "s": 4115, "text": null }, { "code": null, "e": 4566, "s": 4557, "text": "Output :" }, { "code": null, "e": 4618, "s": 4566, "text": " 0 0 0 0 0 0 61 71 81 91\n" }, { "code": null, "e": 4664, "s": 4618, "text": "Example 2 : break statement with while loop :" }, { "code": "% initializing the variable i with 1i = 1; % the while condition is always truewhile true % display the value of idisp(i); % display the below contentdisp(\" is less then 5\"); % make an increment of 1 in value of ii = i + 1; % if the if condition is true loop will break if i == 5,break; % end the if statementend; % end the whileend;", "e": 5005, "s": 4664, "text": null }, { "code": null, "e": 5014, "s": 5005, "text": "Output :" }, { "code": null, "e": 5091, "s": 5014, "text": " 1\n is less then 5\n 2\n is less then 5\n 3\n is less then 5\n 4\n is less then 5\n" }, { "code": null, "e": 5102, "s": 5091, "text": "Octave-GNU" }, { "code": null, "e": 5123, "s": 5102, "text": "Programming Language" }, { "code": null, "e": 5221, "s": 5123, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5258, "s": 5221, "text": "Decorators with parameters in Python" }, { "code": null, "e": 5274, "s": 5258, "text": "C# | Data Types" }, { "code": null, "e": 5308, "s": 5274, "text": "Shallow Copy and Deep Copy in C++" }, { "code": null, "e": 5360, "s": 5308, "text": "Difference between Shallow and Deep copy of a class" }, { "code": null, "e": 5373, "s": 5360, "text": "Kotlin Array" }, { "code": null, "e": 5419, "s": 5373, "text": "Top 10 Programming Languages to Learn in 2022" }, { "code": null, "e": 5455, "s": 5419, "text": "Advantages and Disadvantages of OOP" }, { "code": null, "e": 5492, "s": 5455, "text": "Top 10 Fastest Programming Languages" }, { "code": null, "e": 5551, "s": 5492, "text": "Difference between while and do-while loop in C, C++, Java" } ]
How to get HTML code of a WebElement in Selenium?
We can get the html code of a webelement with the help of Selenium webdriver. We can obtain the innerHTML attribute to get the HTML content of the web element. The innerHTML is an attribute of a webelement which is equal to the content that is present between the starting and ending tag. The getAttribute method is used for this and innerHTML is passed as an argument to the method. String s = element.getAttribute('innerHTML'); Let us see the below html code of an element. The innerHTML of the element shall be < You are browsing the best resource for <b>Online Education</b>. Code Implementation import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.By; import java.util.concurrent.TimeUnit; import org.openqa.selenium.WebElement; public class HtmlCodeElement{ public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe"); WebDriver driver = new ChromeDriver(); driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); driver.get("https://www.tutorialspoint.com/index.htm"); // identify element WebElement l=driver.findElement(By.cssSelector("h4")); // obtain the innerHTML with getAttribute method String s = l.getAttribute("innerHTML"); System.out.println("HTML code of element: " +s); driver.close(); } }
[ { "code": null, "e": 1347, "s": 1187, "text": "We can get the html code of a webelement with the help of Selenium webdriver. We can obtain the innerHTML attribute to get the HTML content of the web element." }, { "code": null, "e": 1571, "s": 1347, "text": "The innerHTML is an attribute of a webelement which is equal to the content that is present between the starting and ending tag. The getAttribute method is used for this and innerHTML is passed as an argument to the method." }, { "code": null, "e": 1617, "s": 1571, "text": "String s = element.getAttribute('innerHTML');" }, { "code": null, "e": 1767, "s": 1617, "text": "Let us see the below html code of an element. The innerHTML of the element shall be < You are browsing the best resource for <b>Online Education</b>." }, { "code": null, "e": 1787, "s": 1767, "text": "Code Implementation" }, { "code": null, "e": 2612, "s": 1787, "text": "import org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.chrome.ChromeDriver;\nimport org.openqa.selenium.By;\nimport java.util.concurrent.TimeUnit;\nimport org.openqa.selenium.WebElement;\npublic class HtmlCodeElement{\n public static void main(String[] args) {\n System.setProperty(\"webdriver.chrome.driver\", \"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java\\\\chromedriver.exe\");\n WebDriver driver = new ChromeDriver();\n driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);\n driver.get(\"https://www.tutorialspoint.com/index.htm\");\n // identify element\n WebElement l=driver.findElement(By.cssSelector(\"h4\"));\n // obtain the innerHTML with getAttribute method\n String s = l.getAttribute(\"innerHTML\");\n System.out.println(\"HTML code of element: \" +s);\n driver.close();\n }\n}" } ]
CHARINDEX() function SQL Server
22 Dec, 2020 CHARINDEX() :This function in SQL Server helps to return the position of a substring within a given string. The searching performed in this function is NOT case-sensitive. Syntax : CHARINDEX(substring, string, [starting_position] Parameters :This function accepts 3 parameters. substring –The substring that we are searching for. It has a limit of 8, 000 characters.string –The string in which searching takes place.starting_position –The position from where searching will take place. It’s an optional parameter. substring –The substring that we are searching for. It has a limit of 8, 000 characters. string –The string in which searching takes place. starting_position –The position from where searching will take place. It’s an optional parameter. Returns : The function will return the position of a substring within a given string. If the substring is not found in the string, then the function will return 0. Applicable to the following versions : SQL Server 2017 SQL Server 2016 SQL Server 2014 SQL Server 2012 SQL Server 2008 R2 SQL Server 2008 SQL Server 2005 Example-1 :Searching a character using the CHARINDEX() function. SELECT CHARINDEX('k', 'GeeksforGeeks') As Found ; Output : Example-2 :Searching a substring using the CHARINDEX() function. SELECT CHARINDEX('fully', 'Life is a journey so live it fully') As Found ; Output : Example-3 :If the substring doesn’t match with the given string. SELECT CHARINDEX ('python', 'Geeks for geeks is a well known computer science website') As Found ; Output : Example-4 :Use of “starting_position” parameter in CHARINDEX() function. SELECT CHARINDEX ('for', 'Love for all, Hate for none', 10) As Found ; Output : Example-5 :Showing that CHARINDEX() function is case-insensitive. SELECT CHARINDEX('Bear', 'Bob likes Bear, beer likes bob') As Found1, CHARINDEX('bear', 'Bob likes Bear, beer likes bob') As Found2 ; Output : Example-6 :Making the function case-sensitive using the COLLATE clause. SELECT CHARINDEX ('A', 'There is always a need to Develop' COLLATE Latin1_General_CS_AS) As Found; Output :The function is now following a case-sensitive search, and since it doesn’t contain “A”, so the function will return 0. DBMS-SQL SQL-Server Technical Scripter 2020 SQL Technical Scripter 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 | Sub queries in From Clause Window functions in SQL What is Temporary Table in SQL? SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter SQL using Python SQL Query to Convert VARCHAR to INT RANK() Function in SQL Server How to Import JSON Data into SQL Server? SQL Query to Compare Two Dates
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Dec, 2020" }, { "code": null, "e": 200, "s": 28, "text": "CHARINDEX() :This function in SQL Server helps to return the position of a substring within a given string. The searching performed in this function is NOT case-sensitive." }, { "code": null, "e": 209, "s": 200, "text": "Syntax :" }, { "code": null, "e": 258, "s": 209, "text": "CHARINDEX(substring, string, [starting_position]" }, { "code": null, "e": 306, "s": 258, "text": "Parameters :This function accepts 3 parameters." }, { "code": null, "e": 542, "s": 306, "text": "substring –The substring that we are searching for. It has a limit of 8, 000 characters.string –The string in which searching takes place.starting_position –The position from where searching will take place. It’s an optional parameter." }, { "code": null, "e": 631, "s": 542, "text": "substring –The substring that we are searching for. It has a limit of 8, 000 characters." }, { "code": null, "e": 682, "s": 631, "text": "string –The string in which searching takes place." }, { "code": null, "e": 780, "s": 682, "text": "starting_position –The position from where searching will take place. It’s an optional parameter." }, { "code": null, "e": 790, "s": 780, "text": "Returns :" }, { "code": null, "e": 866, "s": 790, "text": "The function will return the position of a substring within a given string." }, { "code": null, "e": 944, "s": 866, "text": "If the substring is not found in the string, then the function will return 0." }, { "code": null, "e": 983, "s": 944, "text": "Applicable to the following versions :" }, { "code": null, "e": 999, "s": 983, "text": "SQL Server 2017" }, { "code": null, "e": 1015, "s": 999, "text": "SQL Server 2016" }, { "code": null, "e": 1031, "s": 1015, "text": "SQL Server 2014" }, { "code": null, "e": 1047, "s": 1031, "text": "SQL Server 2012" }, { "code": null, "e": 1066, "s": 1047, "text": "SQL Server 2008 R2" }, { "code": null, "e": 1082, "s": 1066, "text": "SQL Server 2008" }, { "code": null, "e": 1098, "s": 1082, "text": "SQL Server 2005" }, { "code": null, "e": 1163, "s": 1098, "text": "Example-1 :Searching a character using the CHARINDEX() function." }, { "code": null, "e": 1214, "s": 1163, "text": "SELECT CHARINDEX('k', 'GeeksforGeeks') \nAs Found ;" }, { "code": null, "e": 1223, "s": 1214, "text": "Output :" }, { "code": null, "e": 1288, "s": 1223, "text": "Example-2 :Searching a substring using the CHARINDEX() function." }, { "code": null, "e": 1364, "s": 1288, "text": "SELECT CHARINDEX('fully', 'Life is a journey so live it fully') \nAs Found ;" }, { "code": null, "e": 1373, "s": 1364, "text": "Output :" }, { "code": null, "e": 1438, "s": 1373, "text": "Example-3 :If the substring doesn’t match with the given string." }, { "code": null, "e": 1538, "s": 1438, "text": "SELECT CHARINDEX\n('python', 'Geeks for geeks is a well known computer science website') \nAs Found ;" }, { "code": null, "e": 1547, "s": 1538, "text": "Output :" }, { "code": null, "e": 1620, "s": 1547, "text": "Example-4 :Use of “starting_position” parameter in CHARINDEX() function." }, { "code": null, "e": 1692, "s": 1620, "text": "SELECT CHARINDEX\n('for', 'Love for all, Hate for none', 10) \nAs Found ;" }, { "code": null, "e": 1701, "s": 1692, "text": "Output :" }, { "code": null, "e": 1767, "s": 1701, "text": "Example-5 :Showing that CHARINDEX() function is case-insensitive." }, { "code": null, "e": 1905, "s": 1767, "text": "SELECT \nCHARINDEX('Bear', 'Bob likes Bear, beer likes bob') \nAs Found1,\nCHARINDEX('bear', 'Bob likes Bear, beer likes bob') \nAs Found2 ;" }, { "code": null, "e": 1914, "s": 1905, "text": "Output :" }, { "code": null, "e": 1986, "s": 1914, "text": "Example-6 :Making the function case-sensitive using the COLLATE clause." }, { "code": null, "e": 2086, "s": 1986, "text": "SELECT CHARINDEX\n('A', 'There is always a need to Develop' COLLATE Latin1_General_CS_AS) \nAs Found;" }, { "code": null, "e": 2214, "s": 2086, "text": "Output :The function is now following a case-sensitive search, and since it doesn’t contain “A”, so the function will return 0." }, { "code": null, "e": 2223, "s": 2214, "text": "DBMS-SQL" }, { "code": null, "e": 2234, "s": 2223, "text": "SQL-Server" }, { "code": null, "e": 2258, "s": 2234, "text": "Technical Scripter 2020" }, { "code": null, "e": 2262, "s": 2258, "text": "SQL" }, { "code": null, "e": 2281, "s": 2262, "text": "Technical Scripter" }, { "code": null, "e": 2285, "s": 2281, "text": "SQL" }, { "code": null, "e": 2383, "s": 2285, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2449, "s": 2383, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 2482, "s": 2449, "text": "SQL | Sub queries in From Clause" }, { "code": null, "e": 2506, "s": 2482, "text": "Window functions in SQL" }, { "code": null, "e": 2538, "s": 2506, "text": "What is Temporary Table in SQL?" }, { "code": null, "e": 2616, "s": 2538, "text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter" }, { "code": null, "e": 2633, "s": 2616, "text": "SQL using Python" }, { "code": null, "e": 2669, "s": 2633, "text": "SQL Query to Convert VARCHAR to INT" }, { "code": null, "e": 2699, "s": 2669, "text": "RANK() Function in SQL Server" }, { "code": null, "e": 2740, "s": 2699, "text": "How to Import JSON Data into SQL Server?" } ]
How to create static classes in PHP ?
22 Jul, 2021 A class is a user-defined data type that holds its own data members and member functions that can be accessed and used by creating one or more instances of that class. Every time a class is instantiated, the values that it holds are different and unique to the particular instance or object and not to that class. Static Classes brings forth a property wherein a class itself holds values that remain the same and aren’t unique. Another property of Static Classes is that we can do the aforementioned without having to create an instance of the class. How to create a static class? It’s fairly simple. The variables and methods that are declared and defined within a class are to be declared as static with the use of static keyword, so that they can be used without instantiating the class first. An important point to note here is that, since this means a class variable can be accessed without a specific instance, it also means that there will only be one version of this variable. Another consequence is that a static method cannot access non-static variables and methods since these require an instance of the class. To access the static class and it’s method use the following syntax: ClassName::MethodName(); Example 1: The following code returns the current date without instantiating the class Date. In this case, the format of the date and not the actual date remains the same. PHP <?php class Date { public static $date_format1 = 'F jS, Y'; public static $date_format2 = 'Y/m/d H:i:s'; public static function format_date($unix_timestamp) { echo date(self::$date_format1, $unix_timestamp), "\n"; echo date(self::$date_format2, $unix_timestamp); }} echo Date::format_date(time());?> Output: April 30th, 2020 2020/04/30 10:48:36 Example 2: The following code checks whether the string is valid or not. It is valid if it’s length is equal to 13. PHP <?php class geeks { public static $x = 13; public static function isValid($s) { if(strlen($s) == self::$x ) return true; else return false; }} $s1 = "geeksforgeeks";if(geeks::isValid($s1)) echo "String is valid! \n";else echo "String is NOT valid! \n"; $s2 = "geekforgeek"; if(geeks::isValid($s2)) echo "String is valid!\n ";else echo "String is NOT valid! \n";?> Output: String is valid! String is NOT valid! sumitgumber28 PHP-Misc Picked PHP PHP Programs Web Technologies Web technologies Questions Write From Home PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to convert array to string in PHP ? PHP | Converting string to Date and DateTime Comparing two dates in PHP How to get parameters from a URL string in PHP? Split a comma delimited string into an array in PHP How to convert array to string in PHP ? How to call PHP function on the click of a Button ? Comparing two dates in PHP How to get parameters from a URL string in PHP? Split a comma delimited string into an array in PHP
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Jul, 2021" }, { "code": null, "e": 580, "s": 28, "text": "A class is a user-defined data type that holds its own data members and member functions that can be accessed and used by creating one or more instances of that class. Every time a class is instantiated, the values that it holds are different and unique to the particular instance or object and not to that class. Static Classes brings forth a property wherein a class itself holds values that remain the same and aren’t unique. Another property of Static Classes is that we can do the aforementioned without having to create an instance of the class." }, { "code": null, "e": 1151, "s": 580, "text": "How to create a static class? It’s fairly simple. The variables and methods that are declared and defined within a class are to be declared as static with the use of static keyword, so that they can be used without instantiating the class first. An important point to note here is that, since this means a class variable can be accessed without a specific instance, it also means that there will only be one version of this variable. Another consequence is that a static method cannot access non-static variables and methods since these require an instance of the class." }, { "code": null, "e": 1222, "s": 1151, "text": "To access the static class and it’s method use the following syntax: " }, { "code": null, "e": 1248, "s": 1222, "text": " ClassName::MethodName();" }, { "code": null, "e": 1420, "s": 1248, "text": "Example 1: The following code returns the current date without instantiating the class Date. In this case, the format of the date and not the actual date remains the same." }, { "code": null, "e": 1424, "s": 1420, "text": "PHP" }, { "code": "<?php class Date { public static $date_format1 = 'F jS, Y'; public static $date_format2 = 'Y/m/d H:i:s'; public static function format_date($unix_timestamp) { echo date(self::$date_format1, $unix_timestamp), \"\\n\"; echo date(self::$date_format2, $unix_timestamp); }} echo Date::format_date(time());?>", "e": 1751, "s": 1424, "text": null }, { "code": null, "e": 1796, "s": 1751, "text": "Output:\nApril 30th, 2020\n2020/04/30 10:48:36" }, { "code": null, "e": 1913, "s": 1796, "text": "Example 2: The following code checks whether the string is valid or not. It is valid if it’s length is equal to 13. " }, { "code": null, "e": 1917, "s": 1913, "text": "PHP" }, { "code": "<?php class geeks { public static $x = 13; public static function isValid($s) { if(strlen($s) == self::$x ) return true; else return false; }} $s1 = \"geeksforgeeks\";if(geeks::isValid($s1)) echo \"String is valid! \\n\";else echo \"String is NOT valid! \\n\"; $s2 = \"geekforgeek\"; if(geeks::isValid($s2)) echo \"String is valid!\\n \";else echo \"String is NOT valid! \\n\";?>", "e": 2340, "s": 1917, "text": null }, { "code": null, "e": 2349, "s": 2340, "text": "Output: " }, { "code": null, "e": 2387, "s": 2349, "text": "String is valid!\nString is NOT valid!" }, { "code": null, "e": 2403, "s": 2389, "text": "sumitgumber28" }, { "code": null, "e": 2412, "s": 2403, "text": "PHP-Misc" }, { "code": null, "e": 2419, "s": 2412, "text": "Picked" }, { "code": null, "e": 2423, "s": 2419, "text": "PHP" }, { "code": null, "e": 2436, "s": 2423, "text": "PHP Programs" }, { "code": null, "e": 2453, "s": 2436, "text": "Web Technologies" }, { "code": null, "e": 2480, "s": 2453, "text": "Web technologies Questions" }, { "code": null, "e": 2496, "s": 2480, "text": "Write From Home" }, { "code": null, "e": 2500, "s": 2496, "text": "PHP" }, { "code": null, "e": 2598, "s": 2500, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2638, "s": 2598, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 2683, "s": 2638, "text": "PHP | Converting string to Date and DateTime" }, { "code": null, "e": 2710, "s": 2683, "text": "Comparing two dates in PHP" }, { "code": null, "e": 2758, "s": 2710, "text": "How to get parameters from a URL string in PHP?" }, { "code": null, "e": 2810, "s": 2758, "text": "Split a comma delimited string into an array in PHP" }, { "code": null, "e": 2850, "s": 2810, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 2902, "s": 2850, "text": "How to call PHP function on the click of a Button ?" }, { "code": null, "e": 2929, "s": 2902, "text": "Comparing two dates in PHP" }, { "code": null, "e": 2977, "s": 2929, "text": "How to get parameters from a URL string in PHP?" } ]
NavigableMap Interface in Java with Example
21 Nov, 2021 The NavigableMap interface is a member of the Java Collection Framework. It belongs to java.util package and It is an extension of SortedMap which provides convenient navigation methods like lowerKey, floorKey, ceilingKey and higherKey, and along with this popular navigation method. It also provide ways to create a Sub Map from existing Map in Java e.g. headMap whose keys are less than the specified key, tailMap whose keys are greater than the specified key, and a subMap which strictly contains keys which fall between toKey and fromKey. An example class that implements NavigableMap is TreeMap. Declaration: public interface NavigableMap<K,V> extends SortedMap<K,V> Here, K is the key Object type and V is the value Object type. Hierarchy of NavigableMap It implements Map<K,V>, SortedMap<K,V> interfaces. ConcurrentNavigableMap<K,V> extends NavigableMap. ConcurrentSkipListMap and TreeMap implements NavigableMap. Example: Java // Java program to demonstrate// the NavigableMap interfaceimport java.util.NavigableMap;import java.util.TreeMap; public class NavigableMapExample { public static void main(String[] args) { // Instantiate an object // Since NavigableMap // is an interface so we // use TreeMap NavigableMap<String, Integer> nm = new TreeMap<String, Integer>(); // Add elements using put() method nm.put("C", 888); nm.put("Y", 999); nm.put("A", 444); nm.put("T", 555); nm.put("B", 666); nm.put("A", 555); // Print the contents on the console System.out.println("Mappings of NavigableMap : " + nm); System.out.printf("Descending Set : %s%n", nm.descendingKeySet()); System.out.printf("Floor Entry : %s%n", nm.floorEntry("L")); System.out.printf("First Entry : %s%n", nm.firstEntry()); System.out.printf("Last Key : %s%n", nm.lastKey()); System.out.printf("First Key : %s%n", nm.firstKey()); System.out.printf("Original Map : %s%n", nm); System.out.printf("Reverse Map : %s%n", nm.descendingMap()); }} Output: Mappings of NavigableMap : {A=555, B=666, C=888, T=555, Y=999} Descending Set : [Y, T, C, B, A] Floor Entry : C=888 First Entry : A=555 Last Key : Y First Key : A Original Map : {A=555, B=666, C=888, T=555, Y=999} Reverse Map : {Y=999, T=555, C=888, B=666, A=555} The NavigableMap has two implementing classes which are ConcurrentSkipListMap and TreeMap. TreeMap is a Red-Black tree based NavigableMap implementation and it is sorted according to the natural ordering of its keys, or by a Comparator provided at map creation time, depending on which constructor is used. The TreeMap has the expected time cost of log(n) for insertion, deletion, and access operations. TreeMap is not synchronized and it has to be done externally. Syntax: NavigableMap<K, V> objectName = new TreeMap<K, V>(); 1. Adding Elements To add elements to a NavigableMap we can use any methods of the Map interface. The code below shows how to use them. You can observe in the code that the insertion order is not retained. When no Comparator is provided at the time of construction, the natural order is followed. Java // Java program for adding elements// to a NavigableMapimport java.util.*; class AddingElementsExample { public static void main(String args[]) { // Instantiate an object // Since NavigableMap is an interface // We use TreeMap NavigableMap<Integer, String> nmap = new TreeMap<Integer, String>(); // Add elements using put() nmap.put(3, "Geeks"); nmap.put(2, "For"); nmap.put(1, "Geeks"); // Print the contents on the console System.out.println("Mappings of NavigableMap : " + nmap); }} Output: Mappings of NavigableMap : {1=Geeks, 2=For, 3=Geeks} 2. Removing Elements To remove elements as well we use methods of the Map interface, as NavigableMap is a descendant of Map. We can use the remove() method that takes the key value and removes the mapping for the key from this treemap if it is present on the map. We can use clear() to remove all the elements of the map. Java // Java Program for deleting// elements from NavigableMapimport java.util.*; class RemovingElementsExample { public static void main(String args[]) { // Instantiate an object // Since NavigableMap // is an interface // We use TreeMap NavigableMap<Integer, String> nmap = new TreeMap<Integer, String>(); // Add elements using put() nmap.put(3, "Geeks"); nmap.put(2, "Geeks"); nmap.put(1, "Geeks"); nmap.put(4, "For"); // Print the contents on the console System.out.println("Mappings of NavigableMap : " + nmap); // Remove elements using remove() nmap.remove(4); // Print the contents on the console System.out.println( "\nNavigableMap, after remove operation : " + nmap); // Clear the entire map using clear() nmap.clear(); System.out.println( "\nNavigableMap, after clear operation : " + nmap); }} Output: Mappings of NavigableMap : {1=Geeks, 2=Geeks, 3=Geeks, 4=For} NavigableMap, after remove operation : {1=Geeks, 2=Geeks, 3=Geeks} NavigableMap, after clear operation : {} 3. Accessing the Elements We can access the elements of a NavigableMap using get() method, the example of this is given below. Java // Java Program for accessing// elements in a NavigableMap import java.util.*; public class AccessingElementsExample { public static void main(String[] args) { // Instantiate an object // Since NavigableMap is an interface // We use TreeMap NavigableMap<Integer, String> nmap = new TreeMap<Integer, String>(); // Add elements using put() nmap.put(8, "Third"); nmap.put(6, "Second"); nmap.put(3, "First"); nmap.put(11, "Fourth"); // Accessing the elements using get() // with key as a parameter System.out.println(nmap.get(3)); System.out.println(nmap.get(6)); System.out.println(nmap.get(8)); System.out.println(nmap.get(11)); // Display the set of keys using keySet() System.out.println("\nThe NavigableMap key set: " + nmap.keySet()); }} Output: First Second Third Fourth The NavigableMap key set: [3, 6, 8, 11] 4. Traversing We can use the Iterator interface to traverse over any structure of the Collection Framework. Since Iterators work with one type of data we use Entry< ? , ? > to resolve the two separate types into a compatible format. Then using the next() method we print the elements of the NavigableMap. Another famous way is to use a for-each loop and get the keys. The value of the key is found by using the getValue() method. Java // Java Program for traversing// a NavigableMapimport java.util.*; class TraversalExample { public static void main(String args[]) { // Instantiate an object // Since NavigableMap is an interface // We use TreeMap NavigableMap<Integer, String> nmap = new TreeMap<Integer, String>(); // Add elements using put() nmap.put(3, "Geeks"); nmap.put(2, "For"); nmap.put(1, "Geeks"); // Create an Iterator over the // NavigableMap Iterator<NavigableMap.Entry<Integer, String> > itr = nmap.entrySet().iterator(); System.out.println("Traversing using Iterator: "); // The hasNext() method is used to check if there is // a next element The next() method is used to // retrieve the next element while (itr.hasNext()) { NavigableMap.Entry<Integer, String> entry = itr.next(); System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue()); } System.out.println("Traversing using for-each: "); // Iterate using for-each loop for (Map.Entry mapElement : nmap.entrySet()) { // get the key using getKey() int key = (int)mapElement.getKey(); // Finding the value String value = (String)mapElement.getValue(); System.out.println("Key = " + key + ", Value = " + value); } }} Output: Traversing using Iterator: Key = 1, Value = Geeks Key = 2, Value = For Key = 3, Value = Geeks Traversing using for-each: Key = 1, Value = Geeks Key = 2, Value = For Key = 3, Value = Geeks Note: Every time that we say ‘elements of NavigableMap’, it has to be noted that the elements are actually stored in the object of an implementing class of NavigableMap in this case TreeMap. NavigableMap inherits methods from the Map interface, SortedMap interface. The basic methods for adding elements, removing elements, and traversal are given by the parent interfaces. The methods of the NavigableMap are given in the following table. Here, K – The type of the keys in the map. V – The type of values mapped in the map. METHOD DESCRIPTION subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) METHOD DESCRIPTION METHOD DESCRIPTION compute(K key, BiFunction<? super K,? super V,? extends V> remappingFunction) computeIfAbsent(K key, Function<? super K,? extends V> mappingFunction) Reference: https://docs.oracle.com/javase/8/docs/api/java/util/NavigableMap.html This article is contributed by Pratik Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Ganeshchowdharysadanala kapoorsagar226 Java-Collections Java Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Interfaces in Java ArrayList in Java Stream In Java Collections in Java Multidimensional Arrays in Java Singleton Class in Java Stack Class in Java Initialize an ArrayList in Java Initializing a List in Java Introduction to Java
[ { "code": null, "e": 52, "s": 24, "text": "\n21 Nov, 2021" }, { "code": null, "e": 653, "s": 52, "text": "The NavigableMap interface is a member of the Java Collection Framework. It belongs to java.util package and It is an extension of SortedMap which provides convenient navigation methods like lowerKey, floorKey, ceilingKey and higherKey, and along with this popular navigation method. It also provide ways to create a Sub Map from existing Map in Java e.g. headMap whose keys are less than the specified key, tailMap whose keys are greater than the specified key, and a subMap which strictly contains keys which fall between toKey and fromKey. An example class that implements NavigableMap is TreeMap." }, { "code": null, "e": 666, "s": 653, "text": "Declaration:" }, { "code": null, "e": 724, "s": 666, "text": "public interface NavigableMap<K,V> extends SortedMap<K,V>" }, { "code": null, "e": 787, "s": 724, "text": "Here, K is the key Object type and V is the value Object type." }, { "code": null, "e": 813, "s": 787, "text": "Hierarchy of NavigableMap" }, { "code": null, "e": 973, "s": 813, "text": "It implements Map<K,V>, SortedMap<K,V> interfaces. ConcurrentNavigableMap<K,V> extends NavigableMap. ConcurrentSkipListMap and TreeMap implements NavigableMap." }, { "code": null, "e": 982, "s": 973, "text": "Example:" }, { "code": null, "e": 987, "s": 982, "text": "Java" }, { "code": "// Java program to demonstrate// the NavigableMap interfaceimport java.util.NavigableMap;import java.util.TreeMap; public class NavigableMapExample { public static void main(String[] args) { // Instantiate an object // Since NavigableMap // is an interface so we // use TreeMap NavigableMap<String, Integer> nm = new TreeMap<String, Integer>(); // Add elements using put() method nm.put(\"C\", 888); nm.put(\"Y\", 999); nm.put(\"A\", 444); nm.put(\"T\", 555); nm.put(\"B\", 666); nm.put(\"A\", 555); // Print the contents on the console System.out.println(\"Mappings of NavigableMap : \" + nm); System.out.printf(\"Descending Set : %s%n\", nm.descendingKeySet()); System.out.printf(\"Floor Entry : %s%n\", nm.floorEntry(\"L\")); System.out.printf(\"First Entry : %s%n\", nm.firstEntry()); System.out.printf(\"Last Key : %s%n\", nm.lastKey()); System.out.printf(\"First Key : %s%n\", nm.firstKey()); System.out.printf(\"Original Map : %s%n\", nm); System.out.printf(\"Reverse Map : %s%n\", nm.descendingMap()); }}", "e": 2295, "s": 987, "text": null }, { "code": null, "e": 2304, "s": 2295, "text": " Output:" }, { "code": null, "e": 2571, "s": 2304, "text": "Mappings of NavigableMap : {A=555, B=666, C=888, T=555, Y=999}\nDescending Set : [Y, T, C, B, A]\nFloor Entry : C=888\nFirst Entry : A=555\nLast Key : Y\nFirst Key : A\nOriginal Map : {A=555, B=666, C=888, T=555, Y=999}\nReverse Map : {Y=999, T=555, C=888, B=666, A=555}" }, { "code": null, "e": 3038, "s": 2571, "text": "The NavigableMap has two implementing classes which are ConcurrentSkipListMap and TreeMap. TreeMap is a Red-Black tree based NavigableMap implementation and it is sorted according to the natural ordering of its keys, or by a Comparator provided at map creation time, depending on which constructor is used. The TreeMap has the expected time cost of log(n) for insertion, deletion, and access operations. TreeMap is not synchronized and it has to be done externally." }, { "code": null, "e": 3046, "s": 3038, "text": "Syntax:" }, { "code": null, "e": 3099, "s": 3046, "text": "NavigableMap<K, V> objectName = new TreeMap<K, V>();" }, { "code": null, "e": 3118, "s": 3099, "text": "1. Adding Elements" }, { "code": null, "e": 3397, "s": 3118, "text": "To add elements to a NavigableMap we can use any methods of the Map interface. The code below shows how to use them. You can observe in the code that the insertion order is not retained. When no Comparator is provided at the time of construction, the natural order is followed. " }, { "code": null, "e": 3402, "s": 3397, "text": "Java" }, { "code": "// Java program for adding elements// to a NavigableMapimport java.util.*; class AddingElementsExample { public static void main(String args[]) { // Instantiate an object // Since NavigableMap is an interface // We use TreeMap NavigableMap<Integer, String> nmap = new TreeMap<Integer, String>(); // Add elements using put() nmap.put(3, \"Geeks\"); nmap.put(2, \"For\"); nmap.put(1, \"Geeks\"); // Print the contents on the console System.out.println(\"Mappings of NavigableMap : \" + nmap); }}", "e": 4007, "s": 3402, "text": null }, { "code": null, "e": 4016, "s": 4007, "text": " Output:" }, { "code": null, "e": 4069, "s": 4016, "text": "Mappings of NavigableMap : {1=Geeks, 2=For, 3=Geeks}" }, { "code": null, "e": 4090, "s": 4069, "text": "2. Removing Elements" }, { "code": null, "e": 4392, "s": 4090, "text": "To remove elements as well we use methods of the Map interface, as NavigableMap is a descendant of Map. We can use the remove() method that takes the key value and removes the mapping for the key from this treemap if it is present on the map. We can use clear() to remove all the elements of the map. " }, { "code": null, "e": 4397, "s": 4392, "text": "Java" }, { "code": "// Java Program for deleting// elements from NavigableMapimport java.util.*; class RemovingElementsExample { public static void main(String args[]) { // Instantiate an object // Since NavigableMap // is an interface // We use TreeMap NavigableMap<Integer, String> nmap = new TreeMap<Integer, String>(); // Add elements using put() nmap.put(3, \"Geeks\"); nmap.put(2, \"Geeks\"); nmap.put(1, \"Geeks\"); nmap.put(4, \"For\"); // Print the contents on the console System.out.println(\"Mappings of NavigableMap : \" + nmap); // Remove elements using remove() nmap.remove(4); // Print the contents on the console System.out.println( \"\\nNavigableMap, after remove operation : \" + nmap); // Clear the entire map using clear() nmap.clear(); System.out.println( \"\\nNavigableMap, after clear operation : \" + nmap); }}", "e": 5427, "s": 4397, "text": null }, { "code": null, "e": 5436, "s": 5427, "text": " Output:" }, { "code": null, "e": 5608, "s": 5436, "text": "Mappings of NavigableMap : {1=Geeks, 2=Geeks, 3=Geeks, 4=For}\n\nNavigableMap, after remove operation : {1=Geeks, 2=Geeks, 3=Geeks}\n\nNavigableMap, after clear operation : {}" }, { "code": null, "e": 5634, "s": 5608, "text": "3. Accessing the Elements" }, { "code": null, "e": 5735, "s": 5634, "text": "We can access the elements of a NavigableMap using get() method, the example of this is given below." }, { "code": null, "e": 5740, "s": 5735, "text": "Java" }, { "code": "// Java Program for accessing// elements in a NavigableMap import java.util.*; public class AccessingElementsExample { public static void main(String[] args) { // Instantiate an object // Since NavigableMap is an interface // We use TreeMap NavigableMap<Integer, String> nmap = new TreeMap<Integer, String>(); // Add elements using put() nmap.put(8, \"Third\"); nmap.put(6, \"Second\"); nmap.put(3, \"First\"); nmap.put(11, \"Fourth\"); // Accessing the elements using get() // with key as a parameter System.out.println(nmap.get(3)); System.out.println(nmap.get(6)); System.out.println(nmap.get(8)); System.out.println(nmap.get(11)); // Display the set of keys using keySet() System.out.println(\"\\nThe NavigableMap key set: \" + nmap.keySet()); }}", "e": 6649, "s": 5740, "text": null }, { "code": null, "e": 6658, "s": 6649, "text": " Output:" }, { "code": null, "e": 6725, "s": 6658, "text": "First\nSecond\nThird\nFourth\n\nThe NavigableMap key set: [3, 6, 8, 11]" }, { "code": null, "e": 6739, "s": 6725, "text": "4. Traversing" }, { "code": null, "e": 7155, "s": 6739, "text": "We can use the Iterator interface to traverse over any structure of the Collection Framework. Since Iterators work with one type of data we use Entry< ? , ? > to resolve the two separate types into a compatible format. Then using the next() method we print the elements of the NavigableMap. Another famous way is to use a for-each loop and get the keys. The value of the key is found by using the getValue() method." }, { "code": null, "e": 7160, "s": 7155, "text": "Java" }, { "code": "// Java Program for traversing// a NavigableMapimport java.util.*; class TraversalExample { public static void main(String args[]) { // Instantiate an object // Since NavigableMap is an interface // We use TreeMap NavigableMap<Integer, String> nmap = new TreeMap<Integer, String>(); // Add elements using put() nmap.put(3, \"Geeks\"); nmap.put(2, \"For\"); nmap.put(1, \"Geeks\"); // Create an Iterator over the // NavigableMap Iterator<NavigableMap.Entry<Integer, String> > itr = nmap.entrySet().iterator(); System.out.println(\"Traversing using Iterator: \"); // The hasNext() method is used to check if there is // a next element The next() method is used to // retrieve the next element while (itr.hasNext()) { NavigableMap.Entry<Integer, String> entry = itr.next(); System.out.println(\"Key = \" + entry.getKey() + \", Value = \" + entry.getValue()); } System.out.println(\"Traversing using for-each: \"); // Iterate using for-each loop for (Map.Entry mapElement : nmap.entrySet()) { // get the key using getKey() int key = (int)mapElement.getKey(); // Finding the value String value = (String)mapElement.getValue(); System.out.println(\"Key = \" + key + \", Value = \" + value); } }}", "e": 8701, "s": 7160, "text": null }, { "code": null, "e": 8710, "s": 8701, "text": " Output:" }, { "code": null, "e": 8902, "s": 8710, "text": "Traversing using Iterator: \nKey = 1, Value = Geeks\nKey = 2, Value = For\nKey = 3, Value = Geeks\nTraversing using for-each: \nKey = 1, Value = Geeks\nKey = 2, Value = For\nKey = 3, Value = Geeks" }, { "code": null, "e": 9093, "s": 8902, "text": "Note: Every time that we say ‘elements of NavigableMap’, it has to be noted that the elements are actually stored in the object of an implementing class of NavigableMap in this case TreeMap." }, { "code": null, "e": 9348, "s": 9093, "text": "NavigableMap inherits methods from the Map interface, SortedMap interface. The basic methods for adding elements, removing elements, and traversal are given by the parent interfaces. The methods of the NavigableMap are given in the following table. Here," }, { "code": null, "e": 9385, "s": 9348, "text": "K – The type of the keys in the map." }, { "code": null, "e": 9427, "s": 9385, "text": "V – The type of values mapped in the map." }, { "code": null, "e": 9434, "s": 9427, "text": "METHOD" }, { "code": null, "e": 9446, "s": 9434, "text": "DESCRIPTION" }, { "code": null, "e": 9473, "s": 9446, "text": "subMap(K fromKey, boolean " }, { "code": null, "e": 9518, "s": 9473, "text": "fromInclusive, K toKey, boolean toInclusive)" }, { "code": null, "e": 9525, "s": 9518, "text": "METHOD" }, { "code": null, "e": 9537, "s": 9525, "text": "DESCRIPTION" }, { "code": null, "e": 9544, "s": 9537, "text": "METHOD" }, { "code": null, "e": 9556, "s": 9544, "text": "DESCRIPTION" }, { "code": null, "e": 9601, "s": 9556, "text": "compute(K key, BiFunction<? super K,? super " }, { "code": null, "e": 9635, "s": 9601, "text": "V,? extends V> remappingFunction)" }, { "code": null, "e": 9680, "s": 9635, "text": "computeIfAbsent(K key, Function<? super K,? " }, { "code": null, "e": 9708, "s": 9680, "text": "extends V> mappingFunction)" }, { "code": null, "e": 10211, "s": 9708, "text": "Reference: https://docs.oracle.com/javase/8/docs/api/java/util/NavigableMap.html This article is contributed by Pratik Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 10235, "s": 10211, "text": "Ganeshchowdharysadanala" }, { "code": null, "e": 10250, "s": 10235, "text": "kapoorsagar226" }, { "code": null, "e": 10267, "s": 10250, "text": "Java-Collections" }, { "code": null, "e": 10272, "s": 10267, "text": "Java" }, { "code": null, "e": 10277, "s": 10272, "text": "Java" }, { "code": null, "e": 10294, "s": 10277, "text": "Java-Collections" }, { "code": null, "e": 10392, "s": 10294, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 10411, "s": 10392, "text": "Interfaces in Java" }, { "code": null, "e": 10429, "s": 10411, "text": "ArrayList in Java" }, { "code": null, "e": 10444, "s": 10429, "text": "Stream In Java" }, { "code": null, "e": 10464, "s": 10444, "text": "Collections in Java" }, { "code": null, "e": 10496, "s": 10464, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 10520, "s": 10496, "text": "Singleton Class in Java" }, { "code": null, "e": 10540, "s": 10520, "text": "Stack Class in Java" }, { "code": null, "e": 10572, "s": 10540, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 10600, "s": 10572, "text": "Initializing a List in Java" } ]
Launching AWS EC2 Instance using Python
26 Aug, 2020 In this article, we will learn how python can be used for creating and managing Amazon Web Services (AWS) such as Elastic Compute Cloud (EC2), Simple Storage Service (S3), Relational Database Service (RDS). For this purpose, we will use boto3 library of python, Boto is a Python package that provides interfaces to Amazon Web Services (AWS). AWS account with privileges Basics of EC2 For installing boto3 in python : default version : pip install boto3 specific version : python3 -m pip install boto3 (as python3 in this case) For accessing the AWS services from python code we first need to create a user and give him programmatic access using Amazon console. Launch IAM console Add user Then provide a username and give programmatic access to it and then click Next. Now provide the necessary permission related to the user, this user might belong to a group and their policies can be directly attached to the user, or we can copy the policies of an existing user, or we can directly attach an existing policy as we are going to provide here. Tag is optional we can skip it, review the permissions, and create the user finally. Download the CSV as this is the last time it is available for download, this file contains the access key ID and the secret key which will be used next in code. Now we are all set to launch our EC2 instance using python code. For making a connection with EC2 instance we use boto3’s client API. The client API takes in following arguments to make a connection with AWS the service. Service Name: The service to which connection has to be established. Region: Amazon EC2 is hosted in multiple locations worldwide. Based on our need we can choose our region, we have taken Asia-pacific as our region( ‘ap-south-1’ ). aws_access_key_id: AWS Security Credentials. Paste the downloaded ID in the blank space. aws_secret_access_key: AWS Security Credentials. Paste the downloaded secret key in the blank space. Python3 #Python Program for creating a connectionimport boto3 ec2 = boto3.client('ec2', 'ap-south-1', aws_access_key_id='', aws_secret_access_key='') #This function will describe all the instances#with their current state response = ec2.describe_instances()print(response) OUTPUT The ec2.run_instances launches the specified number of instances using an AMI for which you have permissions. It provides a variety of launch configurations, but we can launch instances with few of the following arguments. InstanceType: The instance type that you specify determines the hardware of the host computer used for your instance. Each instance type offers different compute, memory, and storage capabilities and are grouped in instance families based on these capabilities. However, AWS provides “t2.micro” as free in the Free Tier limit. MaxCount: The maximum number of instances to launch. If MaxCount > available instances in target Availability Zone, then it launches the maximum number of Instances greater than MinCount. MinCount: The minimum number of instances to launch. If available instances in target Availability Zone < MinCount, then no instances are launched. ImageId: The ID of the AMI used to launch the instance. For our case we have chosen Ubuntu Server 18.04 LTS (HVM), SSD Volume Type (ami-02d55cb47e83a99a0). Python3 #Python Program for creating a connectionimport boto3 #Function for connecting to EC2 ec2 = boto3.client('ec2', 'ap-south-1', aws_access_key_id='', aws_secret_access_key='') #Function for running instancesconn = ec2.run_instances(InstanceType="t2.micro", MaxCount=1, MinCount=1, ImageId="ami-02d55cb47e83a99a0")print(conn) OUTPUT AWS Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Iterate over a list in Python Python OOPs Concepts
[ { "code": null, "e": 54, "s": 26, "text": "\n26 Aug, 2020" }, { "code": null, "e": 397, "s": 54, "text": "In this article, we will learn how python can be used for creating and managing Amazon Web Services (AWS) such as Elastic Compute Cloud (EC2), Simple Storage Service (S3), Relational Database Service (RDS). For this purpose, we will use boto3 library of python, Boto is a Python package that provides interfaces to Amazon Web Services (AWS). " }, { "code": null, "e": 425, "s": 397, "text": "AWS account with privileges" }, { "code": null, "e": 439, "s": 425, "text": "Basics of EC2" }, { "code": null, "e": 472, "s": 439, "text": "For installing boto3 in python :" }, { "code": null, "e": 583, "s": 472, "text": "default version : pip install boto3\nspecific version : python3 -m pip install boto3 (as python3 in this case)\n" }, { "code": null, "e": 717, "s": 583, "text": "For accessing the AWS services from python code we first need to create a user and give him programmatic access using Amazon console." }, { "code": null, "e": 736, "s": 717, "text": "Launch IAM console" }, { "code": null, "e": 745, "s": 736, "text": "Add user" }, { "code": null, "e": 825, "s": 745, "text": "Then provide a username and give programmatic access to it and then click Next." }, { "code": null, "e": 1102, "s": 825, "text": "Now provide the necessary permission related to the user, this user might belong to a group and their policies can be directly attached to the user, or we can copy the policies of an existing user, or we can directly attach an existing policy as we are going to provide here." }, { "code": null, "e": 1348, "s": 1102, "text": "Tag is optional we can skip it, review the permissions, and create the user finally. Download the CSV as this is the last time it is available for download, this file contains the access key ID and the secret key which will be used next in code." }, { "code": null, "e": 1569, "s": 1348, "text": "Now we are all set to launch our EC2 instance using python code. For making a connection with EC2 instance we use boto3’s client API. The client API takes in following arguments to make a connection with AWS the service." }, { "code": null, "e": 1638, "s": 1569, "text": "Service Name: The service to which connection has to be established." }, { "code": null, "e": 1802, "s": 1638, "text": "Region: Amazon EC2 is hosted in multiple locations worldwide. Based on our need we can choose our region, we have taken Asia-pacific as our region( ‘ap-south-1’ )." }, { "code": null, "e": 1891, "s": 1802, "text": "aws_access_key_id: AWS Security Credentials. Paste the downloaded ID in the blank space." }, { "code": null, "e": 1992, "s": 1891, "text": "aws_secret_access_key: AWS Security Credentials. Paste the downloaded secret key in the blank space." }, { "code": null, "e": 2000, "s": 1992, "text": "Python3" }, { "code": "#Python Program for creating a connectionimport boto3 ec2 = boto3.client('ec2', 'ap-south-1', aws_access_key_id='', aws_secret_access_key='') #This function will describe all the instances#with their current state response = ec2.describe_instances()print(response)", "e": 2321, "s": 2000, "text": null }, { "code": null, "e": 2328, "s": 2321, "text": "OUTPUT" }, { "code": null, "e": 2551, "s": 2328, "text": "The ec2.run_instances launches the specified number of instances using an AMI for which you have permissions. It provides a variety of launch configurations, but we can launch instances with few of the following arguments." }, { "code": null, "e": 2878, "s": 2551, "text": "InstanceType: The instance type that you specify determines the hardware of the host computer used for your instance. Each instance type offers different compute, memory, and storage capabilities and are grouped in instance families based on these capabilities. However, AWS provides “t2.micro” as free in the Free Tier limit." }, { "code": null, "e": 3066, "s": 2878, "text": "MaxCount: The maximum number of instances to launch. If MaxCount > available instances in target Availability Zone, then it launches the maximum number of Instances greater than MinCount." }, { "code": null, "e": 3215, "s": 3066, "text": "MinCount: The minimum number of instances to launch. If available instances in target Availability Zone < MinCount, then no instances are launched." }, { "code": null, "e": 3371, "s": 3215, "text": "ImageId: The ID of the AMI used to launch the instance. For our case we have chosen Ubuntu Server 18.04 LTS (HVM), SSD Volume Type (ami-02d55cb47e83a99a0)." }, { "code": null, "e": 3379, "s": 3371, "text": "Python3" }, { "code": "#Python Program for creating a connectionimport boto3 #Function for connecting to EC2 ec2 = boto3.client('ec2', 'ap-south-1', aws_access_key_id='', aws_secret_access_key='') #Function for running instancesconn = ec2.run_instances(InstanceType=\"t2.micro\", MaxCount=1, MinCount=1, ImageId=\"ami-02d55cb47e83a99a0\")print(conn)", "e": 3830, "s": 3379, "text": null }, { "code": null, "e": 3837, "s": 3830, "text": "OUTPUT" }, { "code": null, "e": 3841, "s": 3837, "text": "AWS" }, { "code": null, "e": 3848, "s": 3841, "text": "Python" }, { "code": null, "e": 3946, "s": 3848, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3964, "s": 3946, "text": "Python Dictionary" }, { "code": null, "e": 4006, "s": 3964, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 4028, "s": 4006, "text": "Enumerate() in Python" }, { "code": null, "e": 4063, "s": 4028, "text": "Read a file line by line in Python" }, { "code": null, "e": 4089, "s": 4063, "text": "Python String | replace()" }, { "code": null, "e": 4121, "s": 4089, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 4150, "s": 4121, "text": "*args and **kwargs in Python" }, { "code": null, "e": 4177, "s": 4150, "text": "Python Classes and Objects" }, { "code": null, "e": 4207, "s": 4177, "text": "Iterate over a list in Python" } ]
Function overloading and const keyword
17 Jun, 2022 Function overloading is a feature of object-oriented programming where two or more functions can have the same name but different parameters. When a function name is overloaded with different jobs it is called Function Overloading. In Function Overloading “Function” name should be the same and the arguments should be different. Function overloading can be considered as an example of a polymorphism feature in C++. The parameters should follow any one or more than one of the following conditions for Function overloading: Parameters should have a different type add(int a, int b)add(double a, double b) Below is the implementation of the above discussion: C++ #include <iostream>using namespace std; void add(int a, int b){ cout << "sum = " << (a + b);} void add(double a, double b){ cout << endl << "sum = " << (a + b);} // Driver codeint main(){ add(10, 2); add(5.3, 6.2); return 0;} sum = 12 sum = 11.5 Parameters should have a different number add(int a, int b)add(int a, int b, int c) Below is the implementation of the above discussion: C++ #include <iostream>using namespace std; void add(int a, int b){ cout << "sum = " << (a + b);} void add(int a, int b, int c){ cout << endl << "sum = " << (a + b + c);} // Driver codeint main(){ add(10, 2); add(5, 6, 4); return 0;} sum = 12 sum = 15 Parameters should have a different sequence of parameters. add(int a, double b)add(double a, int b) Below is the implementation of the above discussion: C++ #include<iostream>using namespace std; void add(int a, double b){ cout<<"sum = "<<(a+b);} void add(double a, int b){ cout<<endl<<"sum = "<<(a+b);} // Driver codeint main(){ add(10,2.5); add(5.5,6); return 0;} sum = 12.5 sum = 11.5 Predict the output of the following C++ program. CPP #include <iostream>using namespace std; class Test {protected: int x; public: Test(int i) : x(i) { } void fun() const { cout << "fun() const called " << endl; } void fun() { cout << "fun() called " << endl; }}; int main(){ Test t1(10); const Test t2(20); t1.fun(); t2.fun(); return 0;} fun() called fun() const called The two methods ‘void fun() const’ and ‘void fun()’ have the same signature except that one is const and the other is not. Also, if we take a closer look at the output, we observe that ‘const void fun()’ is called on the const object, and ‘void fun()’ is called on the non-const object. C++ allows member methods to be overloaded on the basis of const type. Overloading on the basis of const type can be useful when a function returns a reference or pointer. We can make one function const, that returns a const reference or const pointer, and another non-const function, that returns a non-const reference or pointer. See this for more details. What about parameters? Rules related to const parameters are interesting. Let us first take a look at the following two examples. Program 1 fails in compilation, but program 2 compiles and runs fine. CPP // PROGRAM 1 (Fails in compilation)#include<iostream>using namespace std; void fun(const int i){ cout << "fun(const int) called ";}void fun(int i){ cout << "fun(int ) called " ;}int main(){ const int i = 10; fun(i); return 0;} Output: Compiler Error: redefinition of 'void fun(int)' CPP // PROGRAM 2 (Compiles and runs fine)#include<iostream>using namespace std; void fun(char *a){cout << "non-const fun() " << a;} void fun(const char *a){cout << "const fun() " << a;} int main(){const char *ptr = "GeeksforGeeks";fun(ptr);return 0;} const fun() GeeksforGeeks C++ allows functions to be overloaded on the basis of the const-ness of parameters only if the const parameter is a reference or a pointer. That is why program 1 failed in compilation, but program 2 worked fine. This rule actually makes sense. In program 1, the parameter ‘i’ is passed by value, so ‘i’ in fun() is a copy of ‘i’ in main(). Hence fun() cannot modify ‘i’ of main(). Therefore, it doesn’t matter whether ‘i’ is received as a const parameter or a normal parameter. When we pass by reference or pointer, we can modify the value referred or pointed, so we can have two versions of a function, one which can modify the referred or pointed value, other which can not. As an exercise, predict the output of the following program. CPP #include<iostream>using namespace std; void fun(const int &i){ cout << "fun(const int &) called ";}void fun(int &i){ cout << "fun(int &) called " ;}int main(){ const int i = 10; fun(i); return 0;} fun(const int &) called Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above. aditiyadav20102001 CPP-Functions cpp-overloading C Language C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Substring in C++ Function Pointer in C Different Methods to Reverse a String in C++ std::string class in C++ Unordered Sets in C++ Standard Template Library Vector in C++ STL Map in C++ Standard Template Library (STL) Initialize a vector in C++ (7 different ways) Set in C++ Standard Template Library (STL) vector erase() and clear() in C++
[ { "code": null, "e": 54, "s": 26, "text": "\n17 Jun, 2022" }, { "code": null, "e": 471, "s": 54, "text": "Function overloading is a feature of object-oriented programming where two or more functions can have the same name but different parameters. When a function name is overloaded with different jobs it is called Function Overloading. In Function Overloading “Function” name should be the same and the arguments should be different. Function overloading can be considered as an example of a polymorphism feature in C++." }, { "code": null, "e": 579, "s": 471, "text": "The parameters should follow any one or more than one of the following conditions for Function overloading:" }, { "code": null, "e": 619, "s": 579, "text": "Parameters should have a different type" }, { "code": null, "e": 660, "s": 619, "text": "add(int a, int b)add(double a, double b)" }, { "code": null, "e": 713, "s": 660, "text": "Below is the implementation of the above discussion:" }, { "code": null, "e": 717, "s": 713, "text": "C++" }, { "code": "#include <iostream>using namespace std; void add(int a, int b){ cout << \"sum = \" << (a + b);} void add(double a, double b){ cout << endl << \"sum = \" << (a + b);} // Driver codeint main(){ add(10, 2); add(5.3, 6.2); return 0;}", "e": 958, "s": 717, "text": null }, { "code": null, "e": 978, "s": 958, "text": "sum = 12\nsum = 11.5" }, { "code": null, "e": 1021, "s": 978, "text": "Parameters should have a different number " }, { "code": null, "e": 1063, "s": 1021, "text": "add(int a, int b)add(int a, int b, int c)" }, { "code": null, "e": 1116, "s": 1063, "text": "Below is the implementation of the above discussion:" }, { "code": null, "e": 1120, "s": 1116, "text": "C++" }, { "code": "#include <iostream>using namespace std; void add(int a, int b){ cout << \"sum = \" << (a + b);} void add(int a, int b, int c){ cout << endl << \"sum = \" << (a + b + c);} // Driver codeint main(){ add(10, 2); add(5, 6, 4); return 0;}", "e": 1364, "s": 1120, "text": null }, { "code": null, "e": 1382, "s": 1364, "text": "sum = 12\nsum = 15" }, { "code": null, "e": 1441, "s": 1382, "text": "Parameters should have a different sequence of parameters." }, { "code": null, "e": 1482, "s": 1441, "text": "add(int a, double b)add(double a, int b)" }, { "code": null, "e": 1535, "s": 1482, "text": "Below is the implementation of the above discussion:" }, { "code": null, "e": 1539, "s": 1535, "text": "C++" }, { "code": "#include<iostream>using namespace std; void add(int a, double b){ cout<<\"sum = \"<<(a+b);} void add(double a, int b){ cout<<endl<<\"sum = \"<<(a+b);} // Driver codeint main(){ add(10,2.5); add(5.5,6); return 0;}", "e": 1769, "s": 1539, "text": null }, { "code": null, "e": 1791, "s": 1769, "text": "sum = 12.5\nsum = 11.5" }, { "code": null, "e": 1841, "s": 1791, "text": "Predict the output of the following C++ program. " }, { "code": null, "e": 1845, "s": 1841, "text": "CPP" }, { "code": "#include <iostream>using namespace std; class Test {protected: int x; public: Test(int i) : x(i) { } void fun() const { cout << \"fun() const called \" << endl; } void fun() { cout << \"fun() called \" << endl; }}; int main(){ Test t1(10); const Test t2(20); t1.fun(); t2.fun(); return 0;}", "e": 2184, "s": 1845, "text": null }, { "code": null, "e": 2219, "s": 2184, "text": "fun() called \nfun() const called \n" }, { "code": null, "e": 3066, "s": 2219, "text": "The two methods ‘void fun() const’ and ‘void fun()’ have the same signature except that one is const and the other is not. Also, if we take a closer look at the output, we observe that ‘const void fun()’ is called on the const object, and ‘void fun()’ is called on the non-const object. C++ allows member methods to be overloaded on the basis of const type. Overloading on the basis of const type can be useful when a function returns a reference or pointer. We can make one function const, that returns a const reference or const pointer, and another non-const function, that returns a non-const reference or pointer. See this for more details. What about parameters? Rules related to const parameters are interesting. Let us first take a look at the following two examples. Program 1 fails in compilation, but program 2 compiles and runs fine. " }, { "code": null, "e": 3070, "s": 3066, "text": "CPP" }, { "code": "// PROGRAM 1 (Fails in compilation)#include<iostream>using namespace std; void fun(const int i){ cout << \"fun(const int) called \";}void fun(int i){ cout << \"fun(int ) called \" ;}int main(){ const int i = 10; fun(i); return 0;}", "e": 3312, "s": 3070, "text": null }, { "code": null, "e": 3320, "s": 3312, "text": "Output:" }, { "code": null, "e": 3368, "s": 3320, "text": "Compiler Error: redefinition of 'void fun(int)'" }, { "code": null, "e": 3372, "s": 3368, "text": "CPP" }, { "code": "// PROGRAM 2 (Compiles and runs fine)#include<iostream>using namespace std; void fun(char *a){cout << \"non-const fun() \" << a;} void fun(const char *a){cout << \"const fun() \" << a;} int main(){const char *ptr = \"GeeksforGeeks\";fun(ptr);return 0;}", "e": 3619, "s": 3372, "text": null }, { "code": null, "e": 3645, "s": 3619, "text": "const fun() GeeksforGeeks" }, { "code": null, "e": 4322, "s": 3645, "text": "C++ allows functions to be overloaded on the basis of the const-ness of parameters only if the const parameter is a reference or a pointer. That is why program 1 failed in compilation, but program 2 worked fine. This rule actually makes sense. In program 1, the parameter ‘i’ is passed by value, so ‘i’ in fun() is a copy of ‘i’ in main(). Hence fun() cannot modify ‘i’ of main(). Therefore, it doesn’t matter whether ‘i’ is received as a const parameter or a normal parameter. When we pass by reference or pointer, we can modify the value referred or pointed, so we can have two versions of a function, one which can modify the referred or pointed value, other which can not." }, { "code": null, "e": 4384, "s": 4322, "text": "As an exercise, predict the output of the following program. " }, { "code": null, "e": 4388, "s": 4384, "text": "CPP" }, { "code": "#include<iostream>using namespace std; void fun(const int &i){ cout << \"fun(const int &) called \";}void fun(int &i){ cout << \"fun(int &) called \" ;}int main(){ const int i = 10; fun(i); return 0;}", "e": 4600, "s": 4388, "text": null }, { "code": null, "e": 4625, "s": 4600, "text": "fun(const int &) called " }, { "code": null, "e": 4753, "s": 4625, "text": "Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above." }, { "code": null, "e": 4772, "s": 4753, "text": "aditiyadav20102001" }, { "code": null, "e": 4786, "s": 4772, "text": "CPP-Functions" }, { "code": null, "e": 4802, "s": 4786, "text": "cpp-overloading" }, { "code": null, "e": 4813, "s": 4802, "text": "C Language" }, { "code": null, "e": 4817, "s": 4813, "text": "C++" }, { "code": null, "e": 4821, "s": 4817, "text": "CPP" }, { "code": null, "e": 4919, "s": 4821, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4936, "s": 4919, "text": "Substring in C++" }, { "code": null, "e": 4958, "s": 4936, "text": "Function Pointer in C" }, { "code": null, "e": 5003, "s": 4958, "text": "Different Methods to Reverse a String in C++" }, { "code": null, "e": 5028, "s": 5003, "text": "std::string class in C++" }, { "code": null, "e": 5076, "s": 5028, "text": "Unordered Sets in C++ Standard Template Library" }, { "code": null, "e": 5094, "s": 5076, "text": "Vector in C++ STL" }, { "code": null, "e": 5137, "s": 5094, "text": "Map in C++ Standard Template Library (STL)" }, { "code": null, "e": 5183, "s": 5137, "text": "Initialize a vector in C++ (7 different ways)" }, { "code": null, "e": 5226, "s": 5183, "text": "Set in C++ Standard Template Library (STL)" } ]
Python – seaborn.jointplot() method
01 Aug, 2020 Seaborn is a Python data visualization library based on matplotlib. It provides a high-level interface for drawing attractive and informative statistical graphics. Seaborn helps resolve the two major problems faced by Matplotlib; the problems are ? Default Matplotlib parameters Working with data frames As Seaborn compliments and extends Matplotlib, the learning curve is quite gradual. If you know Matplotlib, you are already half-way through Seaborn. Draw a plot of two variables with bivariate and univariate graphs. This function provides a convenient interface to the ‘JointGrid’ class, with several canned plot kinds. This is intended to be a fairly lightweight wrapper; if you need more flexibility, you should use :class:’JointGrid’ directly. Syntax: seaborn.jointplot(x, y, data=None, kind=’scatter’, stat_func=None, color=None, height=6, ratio=5, space=0.2, dropna=True, xlim=None, ylim=None, joint_kws=None, marginal_kws=None, annot_kws=None, **kwargs) Parameters: The description of some main parameters are given below: x, y: These parameters take Data or names of variables in “data”. data: (optional) This parameter take DataFrame when “x” and “y” are variable names. kind: (optional) This parameter take Kind of plot to draw. color: (optional) This parameter take Color used for the plot elements. dropna: (optional) This parameter take boolean value, If True, remove observations that are missing from “x” and “y”. Return: jointgrid object with the plot on it. Below is the implementation of above method: Example 1: Python3 # importing required packagesimport seaborn as snsimport matplotlib.pyplot as plt # loading datasetdata = sns.load_dataset("attention") # draw jointplot with# hex kindsns.jointplot(x = "solutions", y = "score", kind = "hex", data = data)# show the plotplt.show() # This code is contributed # by Deepanshu Rustagi. Output: Example 2: Python3 # importing required packagesimport seaborn as snsimport matplotlib.pyplot as plt # loading datasetdata = sns.load_dataset("mpg") # draw jointplot with# scatter kindsns.jointplot(x = "mpg", y = "acceleration", kind = "scatter", data = data)# show the plotplt.show() # This code is contributed# by Deepanshu Rustagi. Output: Example 3: Python3 # importing required packagesimport seaborn as snsimport matplotlib.pyplot as plt # loading datasetdata = sns.load_dataset("exercise") # draw jointplot with# kde kindsns.jointplot(x = "id", y = "pulse", kind = "kde", data = data)# Show the plotplt.show() # This code is contributed# by Deepanshu Rustagi. Output: Example 4: Python3 # importing required packagesimport seaborn as snsimport matplotlib.pyplot as plt # loading datasetdata = sns.load_dataset("titanic") # draw jointplot with# reg kindsns.jointplot(x = "age", y = "fare", kind = "reg", data = data, dropna = True) # show the plotplt.show() # This code is contributed # by Deepanshu Rustagi. Output: Python-Seaborn Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Convert integer to string in Python Python | os.path.join() method Python OOPs Concepts
[ { "code": null, "e": 28, "s": 0, "text": "\n01 Aug, 2020" }, { "code": null, "e": 277, "s": 28, "text": "Seaborn is a Python data visualization library based on matplotlib. It provides a high-level interface for drawing attractive and informative statistical graphics. Seaborn helps resolve the two major problems faced by Matplotlib; the problems are ?" }, { "code": null, "e": 307, "s": 277, "text": "Default Matplotlib parameters" }, { "code": null, "e": 332, "s": 307, "text": "Working with data frames" }, { "code": null, "e": 482, "s": 332, "text": "As Seaborn compliments and extends Matplotlib, the learning curve is quite gradual. If you know Matplotlib, you are already half-way through Seaborn." }, { "code": null, "e": 780, "s": 482, "text": "Draw a plot of two variables with bivariate and univariate graphs. This function provides a convenient interface to the ‘JointGrid’ class, with several canned plot kinds. This is intended to be a fairly lightweight wrapper; if you need more flexibility, you should use :class:’JointGrid’ directly." }, { "code": null, "e": 996, "s": 780, "text": "Syntax: seaborn.jointplot(x, y, data=None, kind=’scatter’, stat_func=None, color=None, height=6, ratio=5, space=0.2, dropna=True, xlim=None, ylim=None, joint_kws=None, marginal_kws=None, annot_kws=None, **kwargs)" }, { "code": null, "e": 1065, "s": 996, "text": "Parameters: The description of some main parameters are given below:" }, { "code": null, "e": 1131, "s": 1065, "text": "x, y: These parameters take Data or names of variables in “data”." }, { "code": null, "e": 1215, "s": 1131, "text": "data: (optional) This parameter take DataFrame when “x” and “y” are variable names." }, { "code": null, "e": 1274, "s": 1215, "text": "kind: (optional) This parameter take Kind of plot to draw." }, { "code": null, "e": 1347, "s": 1274, "text": "color: (optional) This parameter take Color used for the plot elements." }, { "code": null, "e": 1465, "s": 1347, "text": "dropna: (optional) This parameter take boolean value, If True, remove observations that are missing from “x” and “y”." }, { "code": null, "e": 1511, "s": 1465, "text": "Return: jointgrid object with the plot on it." }, { "code": null, "e": 1556, "s": 1511, "text": "Below is the implementation of above method:" }, { "code": null, "e": 1567, "s": 1556, "text": "Example 1:" }, { "code": null, "e": 1575, "s": 1567, "text": "Python3" }, { "code": "# importing required packagesimport seaborn as snsimport matplotlib.pyplot as plt # loading datasetdata = sns.load_dataset(\"attention\") # draw jointplot with# hex kindsns.jointplot(x = \"solutions\", y = \"score\", kind = \"hex\", data = data)# show the plotplt.show() # This code is contributed # by Deepanshu Rustagi.", "e": 1905, "s": 1575, "text": null }, { "code": null, "e": 1913, "s": 1905, "text": "Output:" }, { "code": null, "e": 1924, "s": 1913, "text": "Example 2:" }, { "code": null, "e": 1932, "s": 1924, "text": "Python3" }, { "code": "# importing required packagesimport seaborn as snsimport matplotlib.pyplot as plt # loading datasetdata = sns.load_dataset(\"mpg\") # draw jointplot with# scatter kindsns.jointplot(x = \"mpg\", y = \"acceleration\", kind = \"scatter\", data = data)# show the plotplt.show() # This code is contributed# by Deepanshu Rustagi.", "e": 2264, "s": 1932, "text": null }, { "code": null, "e": 2272, "s": 2264, "text": "Output:" }, { "code": null, "e": 2283, "s": 2272, "text": "Example 3:" }, { "code": null, "e": 2291, "s": 2283, "text": "Python3" }, { "code": "# importing required packagesimport seaborn as snsimport matplotlib.pyplot as plt # loading datasetdata = sns.load_dataset(\"exercise\") # draw jointplot with# kde kindsns.jointplot(x = \"id\", y = \"pulse\", kind = \"kde\", data = data)# Show the plotplt.show() # This code is contributed# by Deepanshu Rustagi.", "e": 2612, "s": 2291, "text": null }, { "code": null, "e": 2620, "s": 2612, "text": "Output:" }, { "code": null, "e": 2631, "s": 2620, "text": "Example 4:" }, { "code": null, "e": 2639, "s": 2631, "text": "Python3" }, { "code": "# importing required packagesimport seaborn as snsimport matplotlib.pyplot as plt # loading datasetdata = sns.load_dataset(\"titanic\") # draw jointplot with# reg kindsns.jointplot(x = \"age\", y = \"fare\", kind = \"reg\", data = data, dropna = True) # show the plotplt.show() # This code is contributed # by Deepanshu Rustagi.", "e": 2990, "s": 2639, "text": null }, { "code": null, "e": 2998, "s": 2990, "text": "Output:" }, { "code": null, "e": 3013, "s": 2998, "text": "Python-Seaborn" }, { "code": null, "e": 3020, "s": 3013, "text": "Python" }, { "code": null, "e": 3118, "s": 3020, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3136, "s": 3118, "text": "Python Dictionary" }, { "code": null, "e": 3178, "s": 3136, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 3200, "s": 3178, "text": "Enumerate() in Python" }, { "code": null, "e": 3226, "s": 3200, "text": "Python String | replace()" }, { "code": null, "e": 3258, "s": 3226, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 3287, "s": 3258, "text": "*args and **kwargs in Python" }, { "code": null, "e": 3314, "s": 3287, "text": "Python Classes and Objects" }, { "code": null, "e": 3350, "s": 3314, "text": "Convert integer to string in Python" }, { "code": null, "e": 3381, "s": 3350, "text": "Python | os.path.join() method" } ]
Program to find last two digits of 2^n
24 Nov, 2021 Given a number n, we need to find the last two digits of 2n. Examples: Input : n = 7 Output : 28 Input : n = 72 Output : 96 2^72 = 4722366482869645213696 A Naive Approach is to find the value of 2^n iteratively or using pow function. Once the value of 2^n is calculated, find the last two digits and print it. Note: This approach will only work for 2n within a certain range, as overflow occurs. Below is the implementation of the above approach. C++ Java Python3 C# PHP Javascript // C++ code to find last 2 digits of 2^n#include <bits/stdc++.h>using namespace std; // Find the first digitint LastTwoDigit(long long int num){ // Get the last digit from the number int one = num % 10; // Remove last digit from number num /= 10; // Get the last digit from // the number(last second of num) int tens = num % 10; // Take last digit to ten's position // i.e. last second digit tens *= 10; // Add the value of ones and tens to // make it complete 2 digit number num = tens + one; // return the first digit return num;} // Driver programint main(){ int n = 10; long long int num = 1; // pow function used num = pow(2, n); cout << "Last " << 2; cout << " digits of " << 2; cout << "^" << n << " = "; cout << LastTwoDigit(num) << endl; return 0;} // Java code to find last 2 digits of 2^n class Geeks { // Find the first digitstatic long LastTwoDigit(long num){ // Get the last digit from the number long one = num % 10; // Remove last digit from number num /= 10; // Get the last digit from // the number(last second of num) long tens = num % 10; // Take last digit to ten's position // i.e. last second digit tens *= 10; // Add the value of ones and tens to // make it complete 2 digit number num = tens + one; // return the first digit return num;} // Driver code public static void main(String args[]) { int n = 10; long num = 1; // pow function used num = (long)Math.pow(2, n); System.out.println("Last 2 digits of 2^10 = " +LastTwoDigit(num)); }} // This code is contributed by ankita_saini # Python 3 code to find# last 2 digits of 2^n # Find the first digitdef LastTwoDigit(num): # Get the last digit from the number one = num % 10 # Remove last digit from number num //= 10 # Get the last digit from # the number(last second of num) tens = num % 10 # Take last digit to ten's position # i.e. last second digit tens *= 10 # Add the value of ones and tens to # make it complete 2 digit number num = tens + one # return the first digit return num # Driver Codeif __name__ == "__main__": n = 10 num = 1 # pow function used num = pow(2, n); print("Last " + str(2) + " digits of " + str(2) + "^" + str(n) + " = ", end = "") print(LastTwoDigit(num)) # This code is contributed# by ChitraNayal // C# code to find last// 2 digits of 2^nusing System; class GFG{ // Find the first digitstatic long LastTwoDigit(long num){ // Get the last digit // from the number long one = num % 10; // Remove last digit // from number num /= 10; // Get the last digit // from the number(last // second of num) long tens = num % 10; // Take last digit to // ten's position i.e. // last second digit tens *= 10; // Add the value of ones // and tens to make it // complete 2 digit number num = tens + one; // return the first digit return num;} // Driver code public static void Main(String []args) { int n = 10; long num = 1; // pow function used num = (long)Math.Pow(2, n); Console.WriteLine("Last 2 digits of 2^10 = " + LastTwoDigit(num)); }} // This code is contributed// by Ankita_Saini <?php// PHP code to find last// 2 digits of 2^n // Find the first digitfunction LastTwoDigit($num){ // Get the last digit // from the number $one = $num % 10; // Remove last digit // from number $num /= 10; // Get the last digit // from the number(last // second of num) $tens = $num % 10; // Take last digit to // ten's position i.e. // last second digit $tens *= 10; // Add the value of ones // and tens to make it // complete 2 digit number $num = $tens + $one; // return the first digit return $num;} // Driver Code$n = 10;$num = 1; // pow function used$num = pow(2, $n); echo ("Last " . 2); echo (" digits of " . 2); echo("^" . $n . " = "); echo( LastTwoDigit($num)) ; // This code is contributed// by Shivi_Aggarwal?> <script> // Javascript code to find last 2 digits of 2^n // Find the first digitfunction LastTwoDigit(num){ // Get the last digit from the number let one = num % 10; // Remove last digit from number num = Math.floor(num/10); // Get the last digit from // the number(last second of num) let tens = num % 10; // Take last digit to ten's position // i.e. last second digit tens *= 10; // Add the value of ones and tens to // make it complete 2 digit number num = tens + one; // return the first digit return num;} // Driver program let n = 10; let num = 1; // pow function used num = Math.pow(2, n); document.write("Last " + 2); document.write(" digits of " + 2); document.write("^" + n + " = "); document.write(LastTwoDigit(num) + "<br>"); // This code is contributed by Mayank Tyagi </script> Last 2 digits of 2^10 = 24 Efficient approach: The efficient way is to keep only 2 digits after every multiplication. This idea is very similar to the one discussed in Modular exponentiation where a general way is discussed to find (a^b)%c, here in this case c is 10^2 as the last two digits are only needed. Below is the implementation of the above approach. C++ Java Python3 C# PHP Javascript // C++ code to find last 2 digits of 2^n#include <iostream>using namespace std; /* Iterative Function to calculate (x^y)%p in O(log y) */int power(long long int x, long long int y, long long int p){ long long int res = 1; // Initialize result x = x % p; // Update x if it is more than or // equal to p while (y > 0) { // If y is odd, multiply x with result if (y & 1) res = (res * x) % p; // y must be even now y = y >> 1; // y = y/2 x = (x * x) % p; } return res;} // C++ function to calculate// number of digits in xint numberOfDigits(int x){ int i = 0; while (x) { x /= 10; i++; } return i;} // C++ function to print last 2 digits of 2^nvoid LastTwoDigit(int n){ cout << "Last " << 2; cout << " digits of " << 2; cout << "^" << n << " = "; // Generating 10^2 int temp = 1; for (int i = 1; i <= 2; i++) temp *= 10; // Calling modular exponentiation temp = power(2, n, temp); // Printing leftmost zeros. Since (2^n)%2 // can have digits less then 2. In that // case we need to print zeros for (int i = 0; i < 2 - numberOfDigits(temp); i++) cout << 0; // If temp is not zero then print temp // If temp is zero then already printed if (temp) cout << temp;} // Driver program to test above functionsint main(){ int n = 72; LastTwoDigit(n); return 0;} // Java code to find last// 2 digits of 2^nclass GFG{ /* Iterative Function tocalculate (x^y)%p in O(log y) */static int power(long x, long y, long p){int res = 1; // Initialize result x = x % p; // Update x if it is more // than or equal to p while (y > 0){ // If y is odd, multiply // x with result long r = y & 1; if (r == 1) res = (res * (int)x) % (int)p; // y must be even now y = y >> 1; // y = y/2 x = (x * x) % p;}return res;} // Java function to calculate// number of digits in xstatic int numberOfDigits(int x){int i = 0;while (x != 0){ x /= 10; i++;}return i;} // Java function to print// last 2 digits of 2^nstatic void LastTwoDigit(int n){System.out.print("Last " + 2 + " digits of " + 2 + "^");System.out.print(n +" = "); // Generating 10^2int temp = 1;for (int i = 1; i <= 2; i++) temp *= 10; // Calling modular exponentiationtemp = power(2, n, temp); // Printing leftmost zeros.// Since (2^n)%2 can have digits// less then 2. In that case// we need to print zerosfor (int i = 0; i < ( 2 - numberOfDigits(temp)); i++) System.out.print(0 + " "); // If temp is not zero then// print temp. If temp is zero// then already printedif (temp != 0) System.out.println(temp);} // Driver Codepublic static void main(String[] args){ int n = 72; LastTwoDigit(n);}} // This code is contributed// by ChitraNayal # Python 3 code to find# last 2 digits of 2^n # Iterative Function to# calculate (x^y)%p in O(log y)def power(x, y, p): res = 1 # Initialize result x = x % p # Update x if it is more # than or equal to p while (y > 0): # If y is odd, multiply # x with result if (y & 1): res = (res * x) % p # y must be even now y = y >> 1 # y = y/2 x = (x * x) % p return res # function to calculate# number of digits in xdef numberOfDigits(x): i = 0 while (x): x //= 10 i += 1 return i # function to print# last 2 digits of 2^ndef LastTwoDigit(n): print("Last " + str(2) + " digits of " + str(2), end = "") print("^" + str(n) + " = ", end = "") # Generating 10^2 temp = 1 for i in range(1, 3): temp *= 10 # Calling modular exponentiation temp = power(2, n, temp) # Printing leftmost zeros. # Since (2^n)%2 can have digits # less then 2. In that case we # need to print zeros for i in range(2 - numberOfDigits(temp)): print(0, end = "") # If temp is not zero then print temp # If temp is zero then already printed if temp: print(temp) # Driver Codeif __name__ == "__main__": n = 72 LastTwoDigit(n) # This code is contributed# by ChitraNayal // C# code to find last// 2 digits of 2^nusing System; class GFG{ /* Iterative Function to calculate (x^y)%p in O(log y) */static int power(long x, long y, long p){int res = 1; // Initialize result x = x % p; // Update x if it is more // than or equal to p while (y > 0){ // If y is odd, multiply // x with result long r = y & 1; if (r == 1) res = (res * (int)x) % (int)p; // y must be even now y = y >> 1; // y = y/2 x = (x * x) % p;}return res;} // C# function to calculate// number of digits in xstatic int numberOfDigits(int x){ int i = 0; while (x != 0) { x /= 10; i++; } return i;} // C# function to print// last 2 digits of 2^nstatic void LastTwoDigit(int n){Console.Write("Last " + 2 + " digits of " + 2 + "^");Console.Write(n + " = "); // Generating 10^2int temp = 1;for (int i = 1; i <= 2; i++) temp *= 10; // Calling modular exponentiationtemp = power(2, n, temp); // Printing leftmost zeros. Since// (2^n)%2 can have digits less// then 2. In that case we need// to print zerosfor (int i = 0; i < ( 2 - numberOfDigits(temp)); i++) Console.Write(0 + " "); // If temp is not zero then print temp// If temp is zero then already printedif (temp != 0) Console.Write(temp);} // Driver Codepublic static void Main(){ int n = 72; LastTwoDigit(n);}} // This code is contributed// by ChitraNayal <?php// PHP code to find last// 2 digits of 2^n /* Iterative Function tocalculate (x^y)%p in O(log y) */function power($x, $y, $p){ $res = 1; // Initialize result $x = $x % $p; // Update x if it // is more than or // equal to p while ($y > 0) { // If y is odd, multiply // x with result if ($y & 1) $res = ($res * $x) % $p; // y must be even now $y = $y >> 1; // y = y/2 $x = ($x * $x) % $p; } return $res;} // PHP function to calculate// number of digits in xfunction numberOfDigits($x){ $i = 0; while ($x) { $x /= 10; $i++; } return $i;} // PHP function to print// last 2 digits of 2^nfunction LastTwoDigit($n){ echo("Last " . 2); echo(" digits of " . 2); echo("^" . $n ." = "); // Generating 10^2 $temp = 1; for ($i = 1; $i <= 2; $i++) $temp *= 10; // Calling modular // exponentiation $temp = power(2, $n, $temp); // Printing leftmost zeros. // Since (2^n)%2 can have // digits less then 2. In // that case we need to // print zeros for ($i = 0; $i < 2 - numberOfDigits($temp); $i++) echo (0); // If temp is not zero then // print temp. If temp is zero // then already printed if ($temp) echo ($temp);} // Driver Code$n = 72;LastTwoDigit($n); // This code is contributed// by Shivi_Aggarwal?> <script> // Javascript code to find last// 2 digits of 2^n /* Iterative Function tocalculate (x^y)%p in O(log y) */function power(x, y, p){let res = 1; // Initialize result x = x % p; // Update x if it is more // than or equal to p while (y > 0){ // If y is odd, multiply // x with result let r = y & 1; if (r == 1) res = (res * x) % p; // y must be even now y = y >> 1; // y = y/2 x = (x * x) % p;}return res;} // JavaScript function to calculate// number of digits in xfunction numberOfDigits(x){let i = 0;while (x != 0){ x /= 10; i++;}return i;} // JavaScript function to print// last 2 digits of 2^nfunction LastTwoDigit(n){document.write("Last " + 2 + " digits of " + 2 + "^");document.write(n +" = "); // Generating 10^2let temp = 1;for (let i = 1; i <= 2; i++) temp *= 10; // Calling modular exponentiationtemp = power(2, n, temp); // Printing leftmost zeros.// Since (2^n)%2 can have digits// less then 2. In that case// we need to print zerosfor (let i = 0; i < ( 2 - numberOfDigits(temp)); i++) document.write(0 + " "); // If temp is not zero then// print temp. If temp is zero// then already printedif (temp != 0) document.write(temp);} // driver program let n = 72; LastTwoDigit(n); </script> Last 2 digits of 2^72 = 96 Time Complexity: O(log n) ankita_saini Shivi_Aggarwal ukasp mayanktyagi1709 susmitakundugoaldanga surindertarika1234 Kirti_Mangal simranarora5sos math Modular Arithmetic Competitive Programming Mathematical Mathematical Modular Arithmetic Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n24 Nov, 2021" }, { "code": null, "e": 115, "s": 54, "text": "Given a number n, we need to find the last two digits of 2n." }, { "code": null, "e": 126, "s": 115, "text": "Examples: " }, { "code": null, "e": 210, "s": 126, "text": "Input : n = 7\nOutput : 28\n\nInput : n = 72\nOutput : 96\n2^72 = 4722366482869645213696" }, { "code": null, "e": 367, "s": 210, "text": "A Naive Approach is to find the value of 2^n iteratively or using pow function. Once the value of 2^n is calculated, find the last two digits and print it. " }, { "code": null, "e": 454, "s": 367, "text": "Note: This approach will only work for 2n within a certain range, as overflow occurs. " }, { "code": null, "e": 507, "s": 454, "text": "Below is the implementation of the above approach. " }, { "code": null, "e": 511, "s": 507, "text": "C++" }, { "code": null, "e": 516, "s": 511, "text": "Java" }, { "code": null, "e": 524, "s": 516, "text": "Python3" }, { "code": null, "e": 527, "s": 524, "text": "C#" }, { "code": null, "e": 531, "s": 527, "text": "PHP" }, { "code": null, "e": 542, "s": 531, "text": "Javascript" }, { "code": "// C++ code to find last 2 digits of 2^n#include <bits/stdc++.h>using namespace std; // Find the first digitint LastTwoDigit(long long int num){ // Get the last digit from the number int one = num % 10; // Remove last digit from number num /= 10; // Get the last digit from // the number(last second of num) int tens = num % 10; // Take last digit to ten's position // i.e. last second digit tens *= 10; // Add the value of ones and tens to // make it complete 2 digit number num = tens + one; // return the first digit return num;} // Driver programint main(){ int n = 10; long long int num = 1; // pow function used num = pow(2, n); cout << \"Last \" << 2; cout << \" digits of \" << 2; cout << \"^\" << n << \" = \"; cout << LastTwoDigit(num) << endl; return 0;}", "e": 1382, "s": 542, "text": null }, { "code": "// Java code to find last 2 digits of 2^n class Geeks { // Find the first digitstatic long LastTwoDigit(long num){ // Get the last digit from the number long one = num % 10; // Remove last digit from number num /= 10; // Get the last digit from // the number(last second of num) long tens = num % 10; // Take last digit to ten's position // i.e. last second digit tens *= 10; // Add the value of ones and tens to // make it complete 2 digit number num = tens + one; // return the first digit return num;} // Driver code public static void main(String args[]) { int n = 10; long num = 1; // pow function used num = (long)Math.pow(2, n); System.out.println(\"Last 2 digits of 2^10 = \" +LastTwoDigit(num)); }} // This code is contributed by ankita_saini", "e": 2286, "s": 1382, "text": null }, { "code": "# Python 3 code to find# last 2 digits of 2^n # Find the first digitdef LastTwoDigit(num): # Get the last digit from the number one = num % 10 # Remove last digit from number num //= 10 # Get the last digit from # the number(last second of num) tens = num % 10 # Take last digit to ten's position # i.e. last second digit tens *= 10 # Add the value of ones and tens to # make it complete 2 digit number num = tens + one # return the first digit return num # Driver Codeif __name__ == \"__main__\": n = 10 num = 1 # pow function used num = pow(2, n); print(\"Last \" + str(2) + \" digits of \" + str(2) + \"^\" + str(n) + \" = \", end = \"\") print(LastTwoDigit(num)) # This code is contributed# by ChitraNayal", "e": 3105, "s": 2286, "text": null }, { "code": "// C# code to find last// 2 digits of 2^nusing System; class GFG{ // Find the first digitstatic long LastTwoDigit(long num){ // Get the last digit // from the number long one = num % 10; // Remove last digit // from number num /= 10; // Get the last digit // from the number(last // second of num) long tens = num % 10; // Take last digit to // ten's position i.e. // last second digit tens *= 10; // Add the value of ones // and tens to make it // complete 2 digit number num = tens + one; // return the first digit return num;} // Driver code public static void Main(String []args) { int n = 10; long num = 1; // pow function used num = (long)Math.Pow(2, n); Console.WriteLine(\"Last 2 digits of 2^10 = \" + LastTwoDigit(num)); }} // This code is contributed// by Ankita_Saini", "e": 4048, "s": 3105, "text": null }, { "code": "<?php// PHP code to find last// 2 digits of 2^n // Find the first digitfunction LastTwoDigit($num){ // Get the last digit // from the number $one = $num % 10; // Remove last digit // from number $num /= 10; // Get the last digit // from the number(last // second of num) $tens = $num % 10; // Take last digit to // ten's position i.e. // last second digit $tens *= 10; // Add the value of ones // and tens to make it // complete 2 digit number $num = $tens + $one; // return the first digit return $num;} // Driver Code$n = 10;$num = 1; // pow function used$num = pow(2, $n); echo (\"Last \" . 2); echo (\" digits of \" . 2); echo(\"^\" . $n . \" = \"); echo( LastTwoDigit($num)) ; // This code is contributed// by Shivi_Aggarwal?>", "e": 4837, "s": 4048, "text": null }, { "code": "<script> // Javascript code to find last 2 digits of 2^n // Find the first digitfunction LastTwoDigit(num){ // Get the last digit from the number let one = num % 10; // Remove last digit from number num = Math.floor(num/10); // Get the last digit from // the number(last second of num) let tens = num % 10; // Take last digit to ten's position // i.e. last second digit tens *= 10; // Add the value of ones and tens to // make it complete 2 digit number num = tens + one; // return the first digit return num;} // Driver program let n = 10; let num = 1; // pow function used num = Math.pow(2, n); document.write(\"Last \" + 2); document.write(\" digits of \" + 2); document.write(\"^\" + n + \" = \"); document.write(LastTwoDigit(num) + \"<br>\"); // This code is contributed by Mayank Tyagi </script>", "e": 5709, "s": 4837, "text": null }, { "code": null, "e": 5736, "s": 5709, "text": "Last 2 digits of 2^10 = 24" }, { "code": null, "e": 6020, "s": 5738, "text": "Efficient approach: The efficient way is to keep only 2 digits after every multiplication. This idea is very similar to the one discussed in Modular exponentiation where a general way is discussed to find (a^b)%c, here in this case c is 10^2 as the last two digits are only needed." }, { "code": null, "e": 6073, "s": 6020, "text": "Below is the implementation of the above approach. " }, { "code": null, "e": 6077, "s": 6073, "text": "C++" }, { "code": null, "e": 6082, "s": 6077, "text": "Java" }, { "code": null, "e": 6090, "s": 6082, "text": "Python3" }, { "code": null, "e": 6093, "s": 6090, "text": "C#" }, { "code": null, "e": 6097, "s": 6093, "text": "PHP" }, { "code": null, "e": 6108, "s": 6097, "text": "Javascript" }, { "code": "// C++ code to find last 2 digits of 2^n#include <iostream>using namespace std; /* Iterative Function to calculate (x^y)%p in O(log y) */int power(long long int x, long long int y, long long int p){ long long int res = 1; // Initialize result x = x % p; // Update x if it is more than or // equal to p while (y > 0) { // If y is odd, multiply x with result if (y & 1) res = (res * x) % p; // y must be even now y = y >> 1; // y = y/2 x = (x * x) % p; } return res;} // C++ function to calculate// number of digits in xint numberOfDigits(int x){ int i = 0; while (x) { x /= 10; i++; } return i;} // C++ function to print last 2 digits of 2^nvoid LastTwoDigit(int n){ cout << \"Last \" << 2; cout << \" digits of \" << 2; cout << \"^\" << n << \" = \"; // Generating 10^2 int temp = 1; for (int i = 1; i <= 2; i++) temp *= 10; // Calling modular exponentiation temp = power(2, n, temp); // Printing leftmost zeros. Since (2^n)%2 // can have digits less then 2. In that // case we need to print zeros for (int i = 0; i < 2 - numberOfDigits(temp); i++) cout << 0; // If temp is not zero then print temp // If temp is zero then already printed if (temp) cout << temp;} // Driver program to test above functionsint main(){ int n = 72; LastTwoDigit(n); return 0;}", "e": 7530, "s": 6108, "text": null }, { "code": "// Java code to find last// 2 digits of 2^nclass GFG{ /* Iterative Function tocalculate (x^y)%p in O(log y) */static int power(long x, long y, long p){int res = 1; // Initialize result x = x % p; // Update x if it is more // than or equal to p while (y > 0){ // If y is odd, multiply // x with result long r = y & 1; if (r == 1) res = (res * (int)x) % (int)p; // y must be even now y = y >> 1; // y = y/2 x = (x * x) % p;}return res;} // Java function to calculate// number of digits in xstatic int numberOfDigits(int x){int i = 0;while (x != 0){ x /= 10; i++;}return i;} // Java function to print// last 2 digits of 2^nstatic void LastTwoDigit(int n){System.out.print(\"Last \" + 2 + \" digits of \" + 2 + \"^\");System.out.print(n +\" = \"); // Generating 10^2int temp = 1;for (int i = 1; i <= 2; i++) temp *= 10; // Calling modular exponentiationtemp = power(2, n, temp); // Printing leftmost zeros.// Since (2^n)%2 can have digits// less then 2. In that case// we need to print zerosfor (int i = 0; i < ( 2 - numberOfDigits(temp)); i++) System.out.print(0 + \" \"); // If temp is not zero then// print temp. If temp is zero// then already printedif (temp != 0) System.out.println(temp);} // Driver Codepublic static void main(String[] args){ int n = 72; LastTwoDigit(n);}} // This code is contributed// by ChitraNayal", "e": 8952, "s": 7530, "text": null }, { "code": "# Python 3 code to find# last 2 digits of 2^n # Iterative Function to# calculate (x^y)%p in O(log y)def power(x, y, p): res = 1 # Initialize result x = x % p # Update x if it is more # than or equal to p while (y > 0): # If y is odd, multiply # x with result if (y & 1): res = (res * x) % p # y must be even now y = y >> 1 # y = y/2 x = (x * x) % p return res # function to calculate# number of digits in xdef numberOfDigits(x): i = 0 while (x): x //= 10 i += 1 return i # function to print# last 2 digits of 2^ndef LastTwoDigit(n): print(\"Last \" + str(2) + \" digits of \" + str(2), end = \"\") print(\"^\" + str(n) + \" = \", end = \"\") # Generating 10^2 temp = 1 for i in range(1, 3): temp *= 10 # Calling modular exponentiation temp = power(2, n, temp) # Printing leftmost zeros. # Since (2^n)%2 can have digits # less then 2. In that case we # need to print zeros for i in range(2 - numberOfDigits(temp)): print(0, end = \"\") # If temp is not zero then print temp # If temp is zero then already printed if temp: print(temp) # Driver Codeif __name__ == \"__main__\": n = 72 LastTwoDigit(n) # This code is contributed# by ChitraNayal", "e": 10284, "s": 8952, "text": null }, { "code": "// C# code to find last// 2 digits of 2^nusing System; class GFG{ /* Iterative Function to calculate (x^y)%p in O(log y) */static int power(long x, long y, long p){int res = 1; // Initialize result x = x % p; // Update x if it is more // than or equal to p while (y > 0){ // If y is odd, multiply // x with result long r = y & 1; if (r == 1) res = (res * (int)x) % (int)p; // y must be even now y = y >> 1; // y = y/2 x = (x * x) % p;}return res;} // C# function to calculate// number of digits in xstatic int numberOfDigits(int x){ int i = 0; while (x != 0) { x /= 10; i++; } return i;} // C# function to print// last 2 digits of 2^nstatic void LastTwoDigit(int n){Console.Write(\"Last \" + 2 + \" digits of \" + 2 + \"^\");Console.Write(n + \" = \"); // Generating 10^2int temp = 1;for (int i = 1; i <= 2; i++) temp *= 10; // Calling modular exponentiationtemp = power(2, n, temp); // Printing leftmost zeros. Since// (2^n)%2 can have digits less// then 2. In that case we need// to print zerosfor (int i = 0; i < ( 2 - numberOfDigits(temp)); i++) Console.Write(0 + \" \"); // If temp is not zero then print temp// If temp is zero then already printedif (temp != 0) Console.Write(temp);} // Driver Codepublic static void Main(){ int n = 72; LastTwoDigit(n);}} // This code is contributed// by ChitraNayal", "e": 11713, "s": 10284, "text": null }, { "code": "<?php// PHP code to find last// 2 digits of 2^n /* Iterative Function tocalculate (x^y)%p in O(log y) */function power($x, $y, $p){ $res = 1; // Initialize result $x = $x % $p; // Update x if it // is more than or // equal to p while ($y > 0) { // If y is odd, multiply // x with result if ($y & 1) $res = ($res * $x) % $p; // y must be even now $y = $y >> 1; // y = y/2 $x = ($x * $x) % $p; } return $res;} // PHP function to calculate// number of digits in xfunction numberOfDigits($x){ $i = 0; while ($x) { $x /= 10; $i++; } return $i;} // PHP function to print// last 2 digits of 2^nfunction LastTwoDigit($n){ echo(\"Last \" . 2); echo(\" digits of \" . 2); echo(\"^\" . $n .\" = \"); // Generating 10^2 $temp = 1; for ($i = 1; $i <= 2; $i++) $temp *= 10; // Calling modular // exponentiation $temp = power(2, $n, $temp); // Printing leftmost zeros. // Since (2^n)%2 can have // digits less then 2. In // that case we need to // print zeros for ($i = 0; $i < 2 - numberOfDigits($temp); $i++) echo (0); // If temp is not zero then // print temp. If temp is zero // then already printed if ($temp) echo ($temp);} // Driver Code$n = 72;LastTwoDigit($n); // This code is contributed// by Shivi_Aggarwal?>", "e": 13138, "s": 11713, "text": null }, { "code": "<script> // Javascript code to find last// 2 digits of 2^n /* Iterative Function tocalculate (x^y)%p in O(log y) */function power(x, y, p){let res = 1; // Initialize result x = x % p; // Update x if it is more // than or equal to p while (y > 0){ // If y is odd, multiply // x with result let r = y & 1; if (r == 1) res = (res * x) % p; // y must be even now y = y >> 1; // y = y/2 x = (x * x) % p;}return res;} // JavaScript function to calculate// number of digits in xfunction numberOfDigits(x){let i = 0;while (x != 0){ x /= 10; i++;}return i;} // JavaScript function to print// last 2 digits of 2^nfunction LastTwoDigit(n){document.write(\"Last \" + 2 + \" digits of \" + 2 + \"^\");document.write(n +\" = \"); // Generating 10^2let temp = 1;for (let i = 1; i <= 2; i++) temp *= 10; // Calling modular exponentiationtemp = power(2, n, temp); // Printing leftmost zeros.// Since (2^n)%2 can have digits// less then 2. In that case// we need to print zerosfor (let i = 0; i < ( 2 - numberOfDigits(temp)); i++) document.write(0 + \" \"); // If temp is not zero then// print temp. If temp is zero// then already printedif (temp != 0) document.write(temp);} // driver program let n = 72; LastTwoDigit(n); </script>", "e": 14449, "s": 13138, "text": null }, { "code": null, "e": 14476, "s": 14449, "text": "Last 2 digits of 2^72 = 96" }, { "code": null, "e": 14505, "s": 14478, "text": "Time Complexity: O(log n) " }, { "code": null, "e": 14518, "s": 14505, "text": "ankita_saini" }, { "code": null, "e": 14533, "s": 14518, "text": "Shivi_Aggarwal" }, { "code": null, "e": 14539, "s": 14533, "text": "ukasp" }, { "code": null, "e": 14555, "s": 14539, "text": "mayanktyagi1709" }, { "code": null, "e": 14577, "s": 14555, "text": "susmitakundugoaldanga" }, { "code": null, "e": 14596, "s": 14577, "text": "surindertarika1234" }, { "code": null, "e": 14609, "s": 14596, "text": "Kirti_Mangal" }, { "code": null, "e": 14625, "s": 14609, "text": "simranarora5sos" }, { "code": null, "e": 14630, "s": 14625, "text": "math" }, { "code": null, "e": 14649, "s": 14630, "text": "Modular Arithmetic" }, { "code": null, "e": 14673, "s": 14649, "text": "Competitive Programming" }, { "code": null, "e": 14686, "s": 14673, "text": "Mathematical" }, { "code": null, "e": 14699, "s": 14686, "text": "Mathematical" }, { "code": null, "e": 14718, "s": 14699, "text": "Modular Arithmetic" } ]
Lexicographically largest permutation possible by a swap that is smaller than a given array - GeeksforGeeks
06 Jul, 2021 Given an array arr[] consisting of N integers, the task is to find the lexicographically largest permutation of the given array possible by exactly one swap, which is smaller than the given array. If it is possible to obtain such a permutation, then print that permutation. Otherwise, print “-1”. Examples: Input: arr[] = {5, 4, 3, 2, 1} Output: 5 4 3 1 2Explanation:Lexicographically, the largest permutation which is smaller than the given array can be formed by swapping 2 and 1.Hence, the resultant permutation is {5, 4, 3, 1, 2} Input: arr[] = {1, 2, 3, 4, 5}Output: -1 Approach: The given problem can be solved by finding the last element which is greater than its next element, and swapping it with the next smaller element in the array. Follow the steps below to solve the problem: If the given array is sorted in ascending order, then print “-1” as it is not possible to find lexicographically the largest permutation of the given array which is smaller than the given array. Traverse the given array from the end and find that index, say idx which is strictly greater than the next element. Now, again traverse the given array from the end and find the index(say j) of the first element, which is smaller, the element arr[idx]. Decreasing the value of j until arr[j – 1] is the same as arr[j]. Swap the elements at the index idx and j in the array arr[] to get the resultant permutation. After completing the above steps, print the array as the resultant permutation. Below is the implementation of the above approach: C++ Java C# Python3 Javascript // C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to lexicographic largest// permutation possible by a swap// that is smaller than given arrayvoid findPermutation(vector<int>& arr){ int N = arr.size(); int i = N - 2; // Find the index of first element // such that arr[i] > arr[i + 1] while (i >= 0 && arr[i] <= arr[i + 1]) i--; // If the array is sorted // in increasing order if (i == -1) { cout << "-1"; return; } int j = N - 1; // Find the index of first element // which is smaller than arr[i] while (j > i && arr[j] >= arr[i]) j--; // If arr[j] == arr[j-1] while (j > i && arr[j] == arr[j - 1]) { // Decrement j j--; } // Swap the element swap(arr[i], arr[j]); // Print the array arr[] for (auto& it : arr) { cout << it << ' '; }} // Driver Codeint main(){ vector<int> arr = { 1, 2, 5, 3, 4, 6 }; findPermutation(arr); return 0;} // java program for the above approachimport java.util.*;class GFG{ // Function to lexicographic largest// permutation possible by a swap// that is smaller than given arraystatic void findPermutation(int[] arr){ int N = arr.length; int i = N - 2; // Find the index of first element // such that arr[i] > arr[i + 1] while (i >= 0 && arr[i] <= arr[i + 1]) i--; // If the array is sorted // in increasing order if (i == -1) { System.out.print("-1"); return; } int j = N - 1; // Find the index of first element // which is smaller than arr[i] while (j > i && arr[j] >= arr[i]) j--; // If arr[j] == arr[j-1] while (j > i && arr[j] == arr[j - 1]) { // Decrement j j--; } // Swap the element int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; // Print the array arr[] for(int it : arr) { System.out.print(it + " "); }} // Driver codepublic static void main(String[] args){ int[] arr = { 1, 2, 5, 3, 4, 6 }; findPermutation(arr);}} // This code is contributed by splevel62. // C# program for the above approachusing System; class GFG{ // Function to lexicographic largest// permutation possible by a swap// that is smaller than given arraystatic void findPermutation(int[] arr){ int N = arr.Length; int i = N - 2; // Find the index of first element // such that arr[i] > arr[i + 1] while (i >= 0 && arr[i] <= arr[i + 1]) i--; // If the array is sorted // in increasing order if (i == -1) { Console.Write("-1"); return; } int j = N - 1; // Find the index of first element // which is smaller than arr[i] while (j > i && arr[j] >= arr[i]) j--; // If arr[j] == arr[j-1] while (j > i && arr[j] == arr[j - 1]) { // Decrement j j--; } // Swap the element int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; // Print the array arr[] foreach(int it in arr) { Console.Write(it + " "); }} // Driver Codepublic static void Main(){ int[] arr = { 1, 2, 5, 3, 4, 6 }; findPermutation(arr);}} // This code is contributed by ukasp # Python program for the above approach # Function to lexicographic largest# permutation possible by a swap# that is smaller than given arraydef findPermutation(arr): N = len(arr) i = N - 2 # Find the index of first element # such that arr[i] > arr[i + 1] while (i >= 0 and arr[i] <= arr[i + 1]): i -= 1 # If the array is sorted # in increasing order if (i == -1) : print("-1") return j = N - 1 # Find the index of first element # which is smaller than arr[i] while (j > i and arr[j] >= arr[i]): j -= 1 # If arr[j] == arr[j-1] while (j > i and arr[j] == arr[j - 1]) : # Decrement j j -= 1 # Swap the element temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; # Pr the array arr[] for it in arr : print(it, end = " ") # Driver Codearr = [ 1, 2, 5, 3, 4, 6 ]findPermutation(arr) # This code is contributed by code_hunt. <script> // Javascript program for the above approach // Function to lexicographic largest// permutation possible by a swap// that is smaller than given arrayfunction findPermutation(arr){ let N = arr.length; let i = N - 2; // Find the index of first element // such that arr[i] > arr[i + 1] while (i >= 0 && arr[i] <= arr[i + 1]) i--; // If the array is sorted // in increasing order if (i == -1) { document.write("-1"); return; } let j = N - 1; // Find the index of first element // which is smaller than arr[i] while (j > i && arr[j] >= arr[i]) j--; // If arr[j] == arr[j-1] while (j > i && arr[j] == arr[j - 1]) { // Decrement j j--; } // Swap the element let temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; // Print the array arr[] for(let it in arr) { document.write(arr[it] + " "); }} // Driver Code let arr = [ 1, 2, 5, 3, 4, 6 ]; findPermutation(arr); </script> 1 2 4 3 5 6 Time Complexity: O(N)Auxiliary Space: O(1) ukasp splevel62 code_hunt sanjoy_62 anikakapoor lexicographic-ordering permutation Arrays Mathematical Arrays Mathematical permutation Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Window Sliding Technique Trapping Rain Water Building Heap from Array Program to find sum of elements in a given array Reversal algorithm for array rotation Program for Fibonacci numbers Write a program to print all permutations of a given string C++ Data Types Set in C++ Standard Template Library (STL) Coin Change | DP-7
[ { "code": null, "e": 24822, "s": 24794, "text": "\n06 Jul, 2021" }, { "code": null, "e": 25119, "s": 24822, "text": "Given an array arr[] consisting of N integers, the task is to find the lexicographically largest permutation of the given array possible by exactly one swap, which is smaller than the given array. If it is possible to obtain such a permutation, then print that permutation. Otherwise, print “-1”." }, { "code": null, "e": 25129, "s": 25119, "text": "Examples:" }, { "code": null, "e": 25356, "s": 25129, "text": "Input: arr[] = {5, 4, 3, 2, 1} Output: 5 4 3 1 2Explanation:Lexicographically, the largest permutation which is smaller than the given array can be formed by swapping 2 and 1.Hence, the resultant permutation is {5, 4, 3, 1, 2}" }, { "code": null, "e": 25397, "s": 25356, "text": "Input: arr[] = {1, 2, 3, 4, 5}Output: -1" }, { "code": null, "e": 25612, "s": 25397, "text": "Approach: The given problem can be solved by finding the last element which is greater than its next element, and swapping it with the next smaller element in the array. Follow the steps below to solve the problem:" }, { "code": null, "e": 25807, "s": 25612, "text": "If the given array is sorted in ascending order, then print “-1” as it is not possible to find lexicographically the largest permutation of the given array which is smaller than the given array." }, { "code": null, "e": 25923, "s": 25807, "text": "Traverse the given array from the end and find that index, say idx which is strictly greater than the next element." }, { "code": null, "e": 26060, "s": 25923, "text": "Now, again traverse the given array from the end and find the index(say j) of the first element, which is smaller, the element arr[idx]." }, { "code": null, "e": 26126, "s": 26060, "text": "Decreasing the value of j until arr[j – 1] is the same as arr[j]." }, { "code": null, "e": 26220, "s": 26126, "text": "Swap the elements at the index idx and j in the array arr[] to get the resultant permutation." }, { "code": null, "e": 26300, "s": 26220, "text": "After completing the above steps, print the array as the resultant permutation." }, { "code": null, "e": 26351, "s": 26300, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 26355, "s": 26351, "text": "C++" }, { "code": null, "e": 26360, "s": 26355, "text": "Java" }, { "code": null, "e": 26363, "s": 26360, "text": "C#" }, { "code": null, "e": 26371, "s": 26363, "text": "Python3" }, { "code": null, "e": 26382, "s": 26371, "text": "Javascript" }, { "code": "// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to lexicographic largest// permutation possible by a swap// that is smaller than given arrayvoid findPermutation(vector<int>& arr){ int N = arr.size(); int i = N - 2; // Find the index of first element // such that arr[i] > arr[i + 1] while (i >= 0 && arr[i] <= arr[i + 1]) i--; // If the array is sorted // in increasing order if (i == -1) { cout << \"-1\"; return; } int j = N - 1; // Find the index of first element // which is smaller than arr[i] while (j > i && arr[j] >= arr[i]) j--; // If arr[j] == arr[j-1] while (j > i && arr[j] == arr[j - 1]) { // Decrement j j--; } // Swap the element swap(arr[i], arr[j]); // Print the array arr[] for (auto& it : arr) { cout << it << ' '; }} // Driver Codeint main(){ vector<int> arr = { 1, 2, 5, 3, 4, 6 }; findPermutation(arr); return 0;}", "e": 27393, "s": 26382, "text": null }, { "code": "// java program for the above approachimport java.util.*;class GFG{ // Function to lexicographic largest// permutation possible by a swap// that is smaller than given arraystatic void findPermutation(int[] arr){ int N = arr.length; int i = N - 2; // Find the index of first element // such that arr[i] > arr[i + 1] while (i >= 0 && arr[i] <= arr[i + 1]) i--; // If the array is sorted // in increasing order if (i == -1) { System.out.print(\"-1\"); return; } int j = N - 1; // Find the index of first element // which is smaller than arr[i] while (j > i && arr[j] >= arr[i]) j--; // If arr[j] == arr[j-1] while (j > i && arr[j] == arr[j - 1]) { // Decrement j j--; } // Swap the element int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; // Print the array arr[] for(int it : arr) { System.out.print(it + \" \"); }} // Driver codepublic static void main(String[] args){ int[] arr = { 1, 2, 5, 3, 4, 6 }; findPermutation(arr);}} // This code is contributed by splevel62.", "e": 28516, "s": 27393, "text": null }, { "code": "// C# program for the above approachusing System; class GFG{ // Function to lexicographic largest// permutation possible by a swap// that is smaller than given arraystatic void findPermutation(int[] arr){ int N = arr.Length; int i = N - 2; // Find the index of first element // such that arr[i] > arr[i + 1] while (i >= 0 && arr[i] <= arr[i + 1]) i--; // If the array is sorted // in increasing order if (i == -1) { Console.Write(\"-1\"); return; } int j = N - 1; // Find the index of first element // which is smaller than arr[i] while (j > i && arr[j] >= arr[i]) j--; // If arr[j] == arr[j-1] while (j > i && arr[j] == arr[j - 1]) { // Decrement j j--; } // Swap the element int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; // Print the array arr[] foreach(int it in arr) { Console.Write(it + \" \"); }} // Driver Codepublic static void Main(){ int[] arr = { 1, 2, 5, 3, 4, 6 }; findPermutation(arr);}} // This code is contributed by ukasp", "e": 29597, "s": 28516, "text": null }, { "code": "# Python program for the above approach # Function to lexicographic largest# permutation possible by a swap# that is smaller than given arraydef findPermutation(arr): N = len(arr) i = N - 2 # Find the index of first element # such that arr[i] > arr[i + 1] while (i >= 0 and arr[i] <= arr[i + 1]): i -= 1 # If the array is sorted # in increasing order if (i == -1) : print(\"-1\") return j = N - 1 # Find the index of first element # which is smaller than arr[i] while (j > i and arr[j] >= arr[i]): j -= 1 # If arr[j] == arr[j-1] while (j > i and arr[j] == arr[j - 1]) : # Decrement j j -= 1 # Swap the element temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; # Pr the array arr[] for it in arr : print(it, end = \" \") # Driver Codearr = [ 1, 2, 5, 3, 4, 6 ]findPermutation(arr) # This code is contributed by code_hunt.", "e": 30544, "s": 29597, "text": null }, { "code": "<script> // Javascript program for the above approach // Function to lexicographic largest// permutation possible by a swap// that is smaller than given arrayfunction findPermutation(arr){ let N = arr.length; let i = N - 2; // Find the index of first element // such that arr[i] > arr[i + 1] while (i >= 0 && arr[i] <= arr[i + 1]) i--; // If the array is sorted // in increasing order if (i == -1) { document.write(\"-1\"); return; } let j = N - 1; // Find the index of first element // which is smaller than arr[i] while (j > i && arr[j] >= arr[i]) j--; // If arr[j] == arr[j-1] while (j > i && arr[j] == arr[j - 1]) { // Decrement j j--; } // Swap the element let temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; // Print the array arr[] for(let it in arr) { document.write(arr[it] + \" \"); }} // Driver Code let arr = [ 1, 2, 5, 3, 4, 6 ]; findPermutation(arr); </script>", "e": 31572, "s": 30544, "text": null }, { "code": null, "e": 31584, "s": 31572, "text": "1 2 4 3 5 6" }, { "code": null, "e": 31629, "s": 31586, "text": "Time Complexity: O(N)Auxiliary Space: O(1)" }, { "code": null, "e": 31635, "s": 31629, "text": "ukasp" }, { "code": null, "e": 31645, "s": 31635, "text": "splevel62" }, { "code": null, "e": 31655, "s": 31645, "text": "code_hunt" }, { "code": null, "e": 31665, "s": 31655, "text": "sanjoy_62" }, { "code": null, "e": 31677, "s": 31665, "text": "anikakapoor" }, { "code": null, "e": 31700, "s": 31677, "text": "lexicographic-ordering" }, { "code": null, "e": 31712, "s": 31700, "text": "permutation" }, { "code": null, "e": 31719, "s": 31712, "text": "Arrays" }, { "code": null, "e": 31732, "s": 31719, "text": "Mathematical" }, { "code": null, "e": 31739, "s": 31732, "text": "Arrays" }, { "code": null, "e": 31752, "s": 31739, "text": "Mathematical" }, { "code": null, "e": 31764, "s": 31752, "text": "permutation" }, { "code": null, "e": 31862, "s": 31764, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31871, "s": 31862, "text": "Comments" }, { "code": null, "e": 31884, "s": 31871, "text": "Old Comments" }, { "code": null, "e": 31909, "s": 31884, "text": "Window Sliding Technique" }, { "code": null, "e": 31929, "s": 31909, "text": "Trapping Rain Water" }, { "code": null, "e": 31954, "s": 31929, "text": "Building Heap from Array" }, { "code": null, "e": 32003, "s": 31954, "text": "Program to find sum of elements in a given array" }, { "code": null, "e": 32041, "s": 32003, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 32071, "s": 32041, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 32131, "s": 32071, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 32146, "s": 32131, "text": "C++ Data Types" }, { "code": null, "e": 32189, "s": 32146, "text": "Set in C++ Standard Template Library (STL)" } ]
How to read form data using JSP via POST Method?
Below is the main.jsp JSP program to handle the input given by web browser using the GET or the POST methods. Infact there is no change in the above JSP because the only way of passing parameters is changed and no binary data is being passed to the JSP program. File handling related concepts will be explained in a separate chapter where we need to read the binary data stream. <html> <head> <title>Using GET and POST Method to Read Form Data</title> </head> <body> <center> <h1>Using POST Method to Read Form Data</h1> <ul> <li><p><b>First Name:</b> <%= request.getParameter("first_name")%> </p></li> <li><p><b>Last Name:</b> <%= request.getParameter("last_name")%> </p></li> </ul> <center> </body> </html> Following is the content of the Hello.htm file − <html> <body> <form action = "main.jsp" method = "POST"> First Name: <input type = "text" name = "first_name"> <br /> Last Name: <input type = "text" name = "last_name" /> <input type = "submit" value = "Submit" /> </form> </body> </html> Let us now keep main.jsp and hello.htm in <Tomcat-installationdirectory>/webapps/ROOT directory. When you access http://localhost:8080/Hello.htm, you will receive the following output. Try to enter the First and the Last Name and then click the submit button to see the result on your local machine where tomcat is running. Based on the input provided, you will receive similar results as in the above examples.
[ { "code": null, "e": 1172, "s": 1062, "text": "Below is the main.jsp JSP program to handle the input given by web browser using the GET or the POST methods." }, { "code": null, "e": 1441, "s": 1172, "text": "Infact there is no change in the above JSP because the only way of passing parameters is changed and no binary data is being passed to the JSP program. File handling related concepts will be explained in a separate chapter where we need to read the binary data stream." }, { "code": null, "e": 1912, "s": 1441, "text": "<html>\n <head>\n <title>Using GET and POST Method to Read Form Data</title>\n </head>\n <body>\n <center>\n <h1>Using POST Method to Read Form Data</h1>\n <ul>\n <li><p><b>First Name:</b>\n <%= request.getParameter(\"first_name\")%>\n </p></li>\n <li><p><b>Last Name:</b>\n <%= request.getParameter(\"last_name\")%>\n </p></li>\n </ul>\n <center>\n </body>\n</html>" }, { "code": null, "e": 1961, "s": 1912, "text": "Following is the content of the Hello.htm file −" }, { "code": null, "e": 2254, "s": 1961, "text": "<html>\n <body>\n <form action = \"main.jsp\" method = \"POST\">\n First Name: <input type = \"text\" name = \"first_name\">\n <br />\n Last Name: <input type = \"text\" name = \"last_name\" />\n <input type = \"submit\" value = \"Submit\" />\n </form>\n </body>\n</html>" }, { "code": null, "e": 2439, "s": 2254, "text": "Let us now keep main.jsp and hello.htm in <Tomcat-installationdirectory>/webapps/ROOT directory. When you access http://localhost:8080/Hello.htm, you will receive the following output." }, { "code": null, "e": 2578, "s": 2439, "text": "Try to enter the First and the Last Name and then click the submit button to see the result on your local machine where tomcat is running." }, { "code": null, "e": 2666, "s": 2578, "text": "Based on the input provided, you will receive similar results as in the above examples." } ]
Program to find sum of first n natural numbers in C++
In this tutorial, we will be discussing a program to find sum of first n natural numbers. For this we will be provided with an integer n. Our task is to add up, find the sum of the first n natural numbers and print it out. Live Demo #include<iostream> using namespace std; //returning sum of first n natural numbers int findSum(int n) { int sum = 0; for (int x=1; x<=n; x++) sum = sum + x; return sum; } int main() { int n = 5; cout << findSum(n); return 0; } 15
[ { "code": null, "e": 1152, "s": 1062, "text": "In this tutorial, we will be discussing a program to find sum of first n natural numbers." }, { "code": null, "e": 1285, "s": 1152, "text": "For this we will be provided with an integer n. Our task is to add up, find the sum of the first n natural numbers and print it out." }, { "code": null, "e": 1296, "s": 1285, "text": " Live Demo" }, { "code": null, "e": 1547, "s": 1296, "text": "#include<iostream>\nusing namespace std;\n//returning sum of first n natural numbers\nint findSum(int n) {\n int sum = 0;\n for (int x=1; x<=n; x++)\n sum = sum + x;\n return sum;\n}\nint main() {\n int n = 5;\n cout << findSum(n);\n return 0;\n}" }, { "code": null, "e": 1550, "s": 1547, "text": "15" } ]
How to convert RGB image to HSV using Java OpenCV library?
The cvtColor() method of the Imgproc class changes/converts the color of the image from one to another. This method accepts three parameters − src − A Matrix object representing source. src − A Matrix object representing source. dst − A Matrix object representing the destination. dst − A Matrix object representing the destination. code − An integer value representing the color of the destination image. code − An integer value representing the color of the destination image. To convert an RGB image to HSV you need to pass Imgproc.COLOR_RGB2HSV as the third parameter to this method. import org.opencv.core.Core; import org.opencv.core.Mat; import org.opencv.imgcodecs.Imgcodecs; import org.opencv.imgproc.Imgproc; public class RGB2HSV { public static void main(String args[]) throws Exception { //Loading the OpenCV core library System.loadLibrary( Core.NATIVE_LIBRARY_NAME ); //Reading the image Mat src = Imgcodecs.imread("D:\\images\\ladakh.jpg"); //Creating the empty destination matrix Mat dst = new Mat(); //Converting the image to gray scale Imgproc.cvtColor(src, dst, Imgproc.COLOR_RGB2HSV); //Instantiating the Imagecodecs class Imgcodecs imageCodecs = new Imgcodecs(); //Writing the image imageCodecs.imwrite("D:\\images\\colorTOhsv.jpg", dst); System.out.println("Image Saved"); } }
[ { "code": null, "e": 1205, "s": 1062, "text": "The cvtColor() method of the Imgproc class changes/converts the color of the image from one to another. This method accepts three parameters −" }, { "code": null, "e": 1248, "s": 1205, "text": "src − A Matrix object representing source." }, { "code": null, "e": 1291, "s": 1248, "text": "src − A Matrix object representing source." }, { "code": null, "e": 1343, "s": 1291, "text": "dst − A Matrix object representing the destination." }, { "code": null, "e": 1395, "s": 1343, "text": "dst − A Matrix object representing the destination." }, { "code": null, "e": 1468, "s": 1395, "text": "code − An integer value representing the color of the destination image." }, { "code": null, "e": 1541, "s": 1468, "text": "code − An integer value representing the color of the destination image." }, { "code": null, "e": 1650, "s": 1541, "text": "To convert an RGB image to HSV you need to pass Imgproc.COLOR_RGB2HSV as the third parameter to this method." }, { "code": null, "e": 2445, "s": 1650, "text": "import org.opencv.core.Core;\nimport org.opencv.core.Mat;\nimport org.opencv.imgcodecs.Imgcodecs;\nimport org.opencv.imgproc.Imgproc;\npublic class RGB2HSV {\n public static void main(String args[]) throws Exception {\n //Loading the OpenCV core library\n System.loadLibrary( Core.NATIVE_LIBRARY_NAME );\n //Reading the image\n Mat src = Imgcodecs.imread(\"D:\\\\images\\\\ladakh.jpg\");\n //Creating the empty destination matrix\n Mat dst = new Mat();\n //Converting the image to gray scale\n Imgproc.cvtColor(src, dst, Imgproc.COLOR_RGB2HSV);\n //Instantiating the Imagecodecs class\n Imgcodecs imageCodecs = new Imgcodecs();\n //Writing the image\n imageCodecs.imwrite(\"D:\\\\images\\\\colorTOhsv.jpg\", dst);\n System.out.println(\"Image Saved\");\n }\n}" } ]
Bigram formation from given a Python list
A bigram is formed by creating a pair of words from every two consecutive words from a given sentence. In python, this technique is heavily used in text analytics. Below we see two approaches on how to achieve this. Using these two methods we first split the sentence into multiple words and then use the enumerate function to create a pair of words from consecutive words. Live Demo list = ['Stop. look left right. go'] print ("The given list is : \n" + str(list)) # Using enumerate() and split() for Bigram formation output = [(k, m.split()[n + 1]) for m in list for n, k in enumerate(m.split()) if n < len(m.split()) - 1] print ("Bigram formation from given list is: \n" + str(output)) Running the above code gives us the following result − The given list is : ['Stop. look left right. go'] Bigram formation from given list is: [('Stop.', 'look'), ('look', 'left'), ('left', 'right.'), ('right.', 'go')] We can also create the biagram using zip and split function. The zip() function puts tithers the words in sequence which are created from the sentence using the split(). Live Demo list = ['Stop. look left right. go'] print ("The given list is : \n" + str(list)) # Using zip() and split() for Bigram formation output = [m for n in list for m in zip(n.split(" ")[:-1], n.split(" ")[1:])] print ("Bigram formation from given list is: \n" + str(output)) Running the above code gives us the following result − The given list is : ['Stop. look left right. go'] Bigram formation from given list is: [('Stop.', 'look'), ('look', 'left'), ('left', 'right.'), ('right.', 'go')]
[ { "code": null, "e": 1278, "s": 1062, "text": "A bigram is formed by creating a pair of words from every two consecutive words from a given sentence. In python, this technique is heavily used in text analytics. Below we see two approaches on how to achieve this." }, { "code": null, "e": 1436, "s": 1278, "text": "Using these two methods we first split the sentence into multiple words and then use the enumerate function to create a pair of words from consecutive words." }, { "code": null, "e": 1447, "s": 1436, "text": " Live Demo" }, { "code": null, "e": 1752, "s": 1447, "text": "list = ['Stop. look left right. go']\nprint (\"The given list is : \\n\" + str(list))\n# Using enumerate() and split() for Bigram formation\noutput = [(k, m.split()[n + 1]) for m in list for n, k in enumerate(m.split()) if n < len(m.split()) - 1]\nprint (\"Bigram formation from given list is: \\n\" + str(output))" }, { "code": null, "e": 1807, "s": 1752, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 1970, "s": 1807, "text": "The given list is :\n['Stop. look left right. go']\nBigram formation from given list is:\n[('Stop.', 'look'), ('look', 'left'), ('left', 'right.'), ('right.', 'go')]" }, { "code": null, "e": 2140, "s": 1970, "text": "We can also create the biagram using zip and split function. The zip() function puts tithers the words in sequence which are created from the sentence using the split()." }, { "code": null, "e": 2151, "s": 2140, "text": " Live Demo" }, { "code": null, "e": 2421, "s": 2151, "text": "list = ['Stop. look left right. go']\nprint (\"The given list is : \\n\" + str(list))\n# Using zip() and split() for Bigram formation\noutput = [m for n in list for m in zip(n.split(\" \")[:-1], n.split(\" \")[1:])]\nprint (\"Bigram formation from given list is: \\n\" + str(output))" }, { "code": null, "e": 2476, "s": 2421, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 2639, "s": 2476, "text": "The given list is :\n['Stop. look left right. go']\nBigram formation from given list is:\n[('Stop.', 'look'), ('look', 'left'), ('left', 'right.'), ('right.', 'go')]" } ]
Python Program to Find the Total Sum of a Nested List Using Recursion
When it is required to find the total sum of a nest list using the recursion technique, a user defined method is used, that takes the list as a parameter. The recursion computes output of small bits of the bigger problem, and combines these bits to give the solution to the bigger problem. A list can be used to store heterogeneous values (i.e data of any data type like integer, floating point, strings, and so on). Below is a demonstration for the same − Live Demo def recursion_sum(my_list): my_total = 0 for elem in my_list: if (type(elem) == type([])): my_total = my_total + recursion_sum(elem) else: my_total = my_total + elem return my_total my_list = [[2,3], [7,9], [11,45], [78,98]] print("The list elements are :") print(my_list) print( "The sum is :") print(recursion_sum(my_list)) The list elements are : [[2, 3], [7, 9], [11, 45], [78, 98]] The sum is : 253 A method named ‘recursion_sum’ is defined, with list as a paramteter. Initially, a variable is assigned to 0. The elements in the list are iterated over, and if their type matches, the elements in the list are added, and the method is called again. Otherwise, the elements are just added to a variable. This variable is displayed as output on the console. Outside the function, the below operations take place − The nested list is defined, and is displayed on the console. The method is called by passing this list as a parameter. The output is displayed on the console.
[ { "code": null, "e": 1217, "s": 1062, "text": "When it is required to find the total sum of a nest list using the recursion technique, a user defined method is used, that takes the list as a parameter." }, { "code": null, "e": 1352, "s": 1217, "text": "The recursion computes output of small bits of the bigger problem, and combines these bits to give the solution to the bigger problem." }, { "code": null, "e": 1479, "s": 1352, "text": "A list can be used to store heterogeneous values (i.e data of any data type like integer, floating point, strings, and so on)." }, { "code": null, "e": 1519, "s": 1479, "text": "Below is a demonstration for the same −" }, { "code": null, "e": 1530, "s": 1519, "text": " Live Demo" }, { "code": null, "e": 1895, "s": 1530, "text": "def recursion_sum(my_list):\n my_total = 0\n for elem in my_list:\n if (type(elem) == type([])):\n my_total = my_total + recursion_sum(elem)\n else:\n my_total = my_total + elem\n return my_total\nmy_list = [[2,3], [7,9], [11,45], [78,98]]\nprint(\"The list elements are :\")\nprint(my_list)\nprint( \"The sum is :\")\nprint(recursion_sum(my_list))" }, { "code": null, "e": 1973, "s": 1895, "text": "The list elements are :\n[[2, 3], [7, 9], [11, 45], [78, 98]]\nThe sum is :\n253" }, { "code": null, "e": 2043, "s": 1973, "text": "A method named ‘recursion_sum’ is defined, with list as a paramteter." }, { "code": null, "e": 2083, "s": 2043, "text": "Initially, a variable is assigned to 0." }, { "code": null, "e": 2222, "s": 2083, "text": "The elements in the list are iterated over, and if their type matches, the elements in the list are added, and the method is called again." }, { "code": null, "e": 2276, "s": 2222, "text": "Otherwise, the elements are just added to a variable." }, { "code": null, "e": 2329, "s": 2276, "text": "This variable is displayed as output on the console." }, { "code": null, "e": 2385, "s": 2329, "text": "Outside the function, the below operations take place −" }, { "code": null, "e": 2446, "s": 2385, "text": "The nested list is defined, and is displayed on the console." }, { "code": null, "e": 2504, "s": 2446, "text": "The method is called by passing this list as a parameter." }, { "code": null, "e": 2544, "s": 2504, "text": "The output is displayed on the console." } ]
Thread Safe Concurrent Collection in C#
The .NET Framework 4 brought the System.Collections.Concurrent namespace. This has several collection classes that are thread-safe and scalable. These collections are called concurrent collections because they can be accessed by multiple threads at a time. The following are the concurrent collection in C# − Let us see how to work with ConcurrentStack<T> that is a thread-safe last in-first out (LIFO) collection. Create a ConcurrentStack. ConcurrentStack<int> s = new ConcurrentStack<int>(); Add elements s.Push(1); s.Push(2); s.Push(3); s.Push(4); s.Push(5); s.Push(6); Let us see an example Live Demo using System; using System.Collections.Concurrent; class Demo{ static void Main (){ ConcurrentStack s = new ConcurrentStack(); s.Push(50); s.Push(100); s.Push(150); s.Push(200); s.Push(250); s.Push(300); if (s.IsEmpty){ Console.WriteLine("The stack is empty!"); } else { Console.WriteLine("The stack isn't empty"); } } }
[ { "code": null, "e": 1319, "s": 1062, "text": "The .NET Framework 4 brought the System.Collections.Concurrent namespace. This has several collection classes that are thread-safe and scalable. These collections are called concurrent collections because they can be accessed by multiple threads at a time." }, { "code": null, "e": 1371, "s": 1319, "text": "The following are the concurrent collection in C# −" }, { "code": null, "e": 1477, "s": 1371, "text": "Let us see how to work with ConcurrentStack<T> that is a thread-safe last in-first out (LIFO) collection." }, { "code": null, "e": 1503, "s": 1477, "text": "Create a ConcurrentStack." }, { "code": null, "e": 1556, "s": 1503, "text": "ConcurrentStack<int> s = new ConcurrentStack<int>();" }, { "code": null, "e": 1569, "s": 1556, "text": "Add elements" }, { "code": null, "e": 1635, "s": 1569, "text": "s.Push(1);\ns.Push(2);\ns.Push(3);\ns.Push(4);\ns.Push(5);\ns.Push(6);" }, { "code": null, "e": 1657, "s": 1635, "text": "Let us see an example" }, { "code": null, "e": 1668, "s": 1657, "text": " Live Demo" }, { "code": null, "e": 2083, "s": 1668, "text": "using System;\nusing System.Collections.Concurrent;\n\nclass Demo{\n static void Main (){\n ConcurrentStack s = new ConcurrentStack();\n\n s.Push(50);\n s.Push(100);\n s.Push(150);\n s.Push(200);\n s.Push(250);\n s.Push(300);\n\n if (s.IsEmpty){\n Console.WriteLine(\"The stack is empty!\");\n }\n\n else {\n Console.WriteLine(\"The stack isn't empty\");\n }\n }\n}" } ]
How can we create and use a MySQL trigger?
For creating a new trigger, we need to use the CREATE TRIGGER statement. Its syntax is as follows − CREATE TRIGGER trigger_name trigger_time trigger_event ON table_name FOR EACH ROW BEGIN ... END; Here, Trigger_name is the name of the trigger which must be put after the CREATE TRIGGER statement. The naming convention for trigger_name can be like [trigger time]_[table name]_[trigger event]. For example, before_student_update or after_student_insert can be the name of the trigger. Trigger_time is the time of trigger activation and it can be BEFORE or AFTER. We must have to specify the activation time while defining a trigger. We must use BEFORE if we want to process action prior to the change made on the table and AFTER if we want to process action post to the change made on the table. Trigger_event can be INSERT, UPDATE, or DELETE. This event causes the trigger to be invoked. A trigger only can be invoked by one event. To define a trigger that is invoked by multiple events, we have to define multiple triggers, one for each event. Table_name is the name of the table. Actually, a trigger is always associated with a specific table. Without a table, a trigger would not exist hence we have to specify the table name after the ‘ON’ keyword. BEGIN...END is the block in which we will define the logic for the trigger. Suppose we want to apply trigger on the table Student_age which is created as follows − mysql> Create table Student_age(age INT, Name Varchar(35)); Query OK, 0 rows affected (0.80 sec) Now, the following trigger will automatically insert the age = 0 if someone tries to insert age < 0. mysql> DELIMITER // mysql> Create Trigger before_inser_studentage BEFORE INSERT ON student_age FOR EACH ROW BEGIN IF NEW.age < 0 THEN SET NEW.age = 0; END IF; END // Query OK, 0 rows affected (0.30 sec) Now, for invoking this trigger, we can use the following statements − mysql> INSERT INTO Student_age(age, Name) values(30, 'Rahul'); Query OK, 1 row affected (0.14 sec) mysql> INSERT INTO Student_age(age, Name) values(-10, 'Harshit'); Query OK, 1 row affected (0.11 sec) mysql> Select * from Student_age; +------+---------+ | age | Name | +------+---------+ | 30 | Rahul | | 0 | Harshit | +------+---------+ 2 rows in set (0.00 sec) The above result set shows that on inserting the negative value in the table will lead to insert 0 by a trigger. The above was the example of a trigger with trigger_event as INSERT and trigger_time are BEFORE.
[ { "code": null, "e": 1162, "s": 1062, "text": "For creating a new trigger, we need to use the CREATE TRIGGER statement. Its syntax is as follows −" }, { "code": null, "e": 1259, "s": 1162, "text": "CREATE TRIGGER trigger_name trigger_time trigger_event\nON table_name\nFOR EACH ROW\nBEGIN\n...\nEND;" }, { "code": null, "e": 1265, "s": 1259, "text": "Here," }, { "code": null, "e": 1546, "s": 1265, "text": "Trigger_name is the name of the trigger which must be put after the CREATE TRIGGER statement. The naming convention for trigger_name can be like [trigger time]_[table name]_[trigger event]. For example, before_student_update or after_student_insert can be the name of the trigger." }, { "code": null, "e": 1857, "s": 1546, "text": "Trigger_time is the time of trigger activation and it can be BEFORE or AFTER. We must have to specify the activation time while defining a trigger. We must use BEFORE if we want to process action prior to the change made on the table and AFTER if we want to process action post to the change made on the table." }, { "code": null, "e": 2107, "s": 1857, "text": "Trigger_event can be INSERT, UPDATE, or DELETE. This event causes the trigger to be invoked. A trigger only can be invoked by one event. To define a trigger that is invoked by multiple events, we have to define multiple triggers, one for each event." }, { "code": null, "e": 2315, "s": 2107, "text": "Table_name is the name of the table. Actually, a trigger is always associated with a specific table. Without a table, a trigger would not exist hence we have to specify the table name after the ‘ON’ keyword." }, { "code": null, "e": 2391, "s": 2315, "text": "BEGIN...END is the block in which we will define the logic for the trigger." }, { "code": null, "e": 2479, "s": 2391, "text": "Suppose we want to apply trigger on the table Student_age which is created as follows −" }, { "code": null, "e": 2576, "s": 2479, "text": "mysql> Create table Student_age(age INT, Name Varchar(35));\nQuery OK, 0 rows affected (0.80 sec)" }, { "code": null, "e": 2677, "s": 2576, "text": "Now, the following trigger will automatically insert the age = 0 if someone tries to insert age < 0." }, { "code": null, "e": 2880, "s": 2677, "text": "mysql> DELIMITER //\nmysql> Create Trigger before_inser_studentage BEFORE INSERT ON student_age FOR EACH ROW\nBEGIN\nIF NEW.age < 0 THEN SET NEW.age = 0;\nEND IF;\nEND //\nQuery OK, 0 rows affected (0.30 sec)" }, { "code": null, "e": 2950, "s": 2880, "text": "Now, for invoking this trigger, we can use the following statements −" }, { "code": null, "e": 3326, "s": 2950, "text": "mysql> INSERT INTO Student_age(age, Name) values(30, 'Rahul');\nQuery OK, 1 row affected (0.14 sec)\n\nmysql> INSERT INTO Student_age(age, Name) values(-10, 'Harshit');\nQuery OK, 1 row affected (0.11 sec)\n\nmysql> Select * from Student_age;\n+------+---------+\n| age | Name |\n+------+---------+\n| 30 | Rahul |\n| 0 | Harshit |\n+------+---------+\n2 rows in set (0.00 sec)" }, { "code": null, "e": 3439, "s": 3326, "text": "The above result set shows that on inserting the negative value in the table will lead to insert 0 by a trigger." }, { "code": null, "e": 3536, "s": 3439, "text": "The above was the example of a trigger with trigger_event as INSERT and trigger_time are BEFORE." } ]
Coroutines in C/C++
In this tutorial, we will be discussing a program to understand coroutines in C/C++. Coroutines are control instructions which switch the execution control between two routines which returning any of them. Live Demo #include<stdio.h> int range(int a, int b){ static long long int i; static int state = 0; switch (state){ case 0: state = 1; for (i = a; i < b; i++){ return i; //returning control case 1:; //resuming control } } state = 0; return 0; } int main(){ int i; for (; i=range(1, 5);) printf("control at main :%d\n", i); return 0; } control at main :1 control at main :2 control at main :3 control at main :4
[ { "code": null, "e": 1147, "s": 1062, "text": "In this tutorial, we will be discussing a program to understand coroutines in C/C++." }, { "code": null, "e": 1268, "s": 1147, "text": "Coroutines are control instructions which switch the execution control between two routines which returning any of them." }, { "code": null, "e": 1279, "s": 1268, "text": " Live Demo" }, { "code": null, "e": 1678, "s": 1279, "text": "#include<stdio.h>\nint range(int a, int b){\n static long long int i;\n static int state = 0;\n switch (state){\n case 0:\n state = 1;\n for (i = a; i < b; i++){\n return i;\n //returning control\n case 1:; //resuming control\n }\n }\n state = 0;\n return 0;\n}\nint main(){\n int i;\n for (; i=range(1, 5);)\n printf(\"control at main :%d\\n\", i);\n return 0;\n}" }, { "code": null, "e": 1754, "s": 1678, "text": "control at main :1\ncontrol at main :2\ncontrol at main :3\ncontrol at main :4" } ]
What are conditional attributes in C#?
Attributes are used for adding metadata, such as compiler instruction and other information such as comments, description, methods, and classes to a program. This predefined attribute marks a conditional method whose execution depends on a specified preprocessing identifier. It causes conditional compilation of method calls, depending on the specified value such as Debug or Trace. For example, it displays the values of the variables while debugging a code. The following is the syntax of conditional attributes − [Conditional( conditionalSymbol )] Let us see how to work with Conditional attributes − Live Demo #define DEBUG using System; using System.Diagnostics; public class Myclass { [Conditional("DEBUG")] public static void Message(string msg) { Console.WriteLine(msg); } } class Test { static void function1() { Myclass.Message("In Function 1"); function2(); } static void function2() { Myclass.Message("In Function 2"); } public static void Main() { Myclass.Message("In Main function"); function1(); Console.ReadKey(); } } In Main function In Function 1 In Function 2
[ { "code": null, "e": 1220, "s": 1062, "text": "Attributes are used for adding metadata, such as compiler instruction and other information such as comments, description, methods, and classes to a program." }, { "code": null, "e": 1338, "s": 1220, "text": "This predefined attribute marks a conditional method whose execution depends on a specified preprocessing identifier." }, { "code": null, "e": 1523, "s": 1338, "text": "It causes conditional compilation of method calls, depending on the specified value such as Debug or Trace. For example, it displays the values of the variables while debugging a code." }, { "code": null, "e": 1579, "s": 1523, "text": "The following is the syntax of conditional attributes −" }, { "code": null, "e": 1617, "s": 1579, "text": "[Conditional(\n conditionalSymbol\n)]" }, { "code": null, "e": 1670, "s": 1617, "text": "Let us see how to work with Conditional attributes −" }, { "code": null, "e": 1681, "s": 1670, "text": " Live Demo" }, { "code": null, "e": 2175, "s": 1681, "text": "#define DEBUG\nusing System;\nusing System.Diagnostics;\n\npublic class Myclass {\n [Conditional(\"DEBUG\")]\n\n public static void Message(string msg) {\n Console.WriteLine(msg);\n }\n}\n\nclass Test {\n static void function1() {\n Myclass.Message(\"In Function 1\");\n function2();\n }\n\n static void function2() {\n Myclass.Message(\"In Function 2\");\n }\n\n public static void Main() {\n Myclass.Message(\"In Main function\");\n function1();\n Console.ReadKey();\n }\n}" }, { "code": null, "e": 2220, "s": 2175, "text": "In Main function\nIn Function 1\nIn Function 2" } ]
Remove borders from an element in Bootstrap
Use the border-0 class in Bootstrap 4 to remove all borders from an element in Bootstrap 4 − <div class="mystyle border no-border"> no border </div> Above, we have the div class to no-border class and this allow us to remove the borders from the element. Let us see an example to implement the border-0 class in Bootstrap − Live Demo <!DOCTYPE html> <html lang="en"> <head> <title>Bootstrap Example</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script> <style> .mystyle { width: 120px; height: 100px; margin: 10px; background: maroon; } </style> </head> <body> <div class="container"> <h4>Rectangle</h4> <div class="mystyle border no-border">no border</div> </div> </body> </html>
[ { "code": null, "e": 1155, "s": 1062, "text": "Use the border-0 class in Bootstrap 4 to remove all borders from an element in Bootstrap 4 −" }, { "code": null, "e": 1213, "s": 1155, "text": "<div class=\"mystyle border no-border\">\n no border\n</div>" }, { "code": null, "e": 1319, "s": 1213, "text": "Above, we have the div class to no-border class and this allow us to remove the borders from the element." }, { "code": null, "e": 1388, "s": 1319, "text": "Let us see an example to implement the border-0 class in Bootstrap −" }, { "code": null, "e": 1398, "s": 1388, "text": "Live Demo" }, { "code": null, "e": 2144, "s": 1398, "text": "<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <title>Bootstrap Example</title>\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css\">\n <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js\"></script>\n <style>\n .mystyle {\n width: 120px;\n height: 100px;\n margin: 10px;\n background: maroon;\n }\n </style>\n </head>\n<body>\n <div class=\"container\">\n <h4>Rectangle</h4>\n <div class=\"mystyle border no-border\">no border</div>\n </div>\n</body>\n</html>" } ]
K-Nearest Neighbors. All you need to know about KNN. | by Sangeet Aggarwal | Towards Data Science
“A man is known for the company he keeps.” A perfect opening line I must say for presenting the K-Nearest Neighbors. Yes, that's how simple the concept behind KNN is. It just classifies a data point based on its few nearest neighbors. How many neighbors? That is what we decide. Looks like you already know a lot of there is to know about this simple model. Let’s dive in to have a much closer look. Before moving on, it’s important to know that KNN can be used for both classification and regression problems. We will first understand how it works for a classification problem, thereby making it easier to visualize regression. The data we are going to use is the Breast Cancer Wisconsin(Diagnostic) Data Set. There are 30 attributes that correspond to the real-valued features computed for a cell nucleus under consideration. A total of 569 such samples are present in this data, out of which 357 are classified as ‘benign’ (harmless) and the rest 212 are classified as ‘malignant’ (harmful). The diagnosis column contains ‘M’ or ‘B’ values for malignant and benign cancers respectively. I have changed these values to 1 and 0 respectively, for better analysis. Also, for the sake of this post, I will only use two attributes from the data → ‘mean radius’ and ‘mean texture’. This will later help us visualize the decision boundaries drawn by KNN. Here’s how the final data looks like (after shuffling): Let’s code the KNN: # Defining X and yX = data.drop('diagnosis',axis=1)y = data.diagnosis# Splitting data into train and testfrom sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(X,y,test_size=0.25,random_state=42)# Importing and fitting KNN classifier for k=3from sklearn.neighbors import KNeighborsClassifierknn = KNeighborsClassifier(n_neighbors=3)knn.fit(X_train,y_train)# Predicting results using Test data setpred = knn.predict(X_test)from sklearn.metrics import accuracy_scoreaccuracy_score(pred,y_test) The above code should give you the following output with a slight variation. 0.8601398601398601 What just happened? When we trained the KNN on training data, it took the following steps for each data sample: Calculate the distance between the data sample and every other sample with the help of a method such as Euclidean.Sort these values of distances in ascending order.Choose the top K values from the sorted distances.Assign the class to the sample based on the most frequent class in the above K values. Calculate the distance between the data sample and every other sample with the help of a method such as Euclidean. Sort these values of distances in ascending order. Choose the top K values from the sorted distances. Assign the class to the sample based on the most frequent class in the above K values. Let’s visualize how KNN drew a decision boundary on the train data set and how the same boundary is then used to classify the test data set. With the training accuracy of 93% and the test accuracy of 86%, our model might have shown overfitting here. Why so? When the value of K or the number of neighbors is too low, the model picks only the values that are closest to the data sample, thus forming a very complex decision boundary as shown above. Such a model fails to generalize well on the test data set, thereby showing poor results. The problem can be solved by tuning the value of n_neighbors parameter. As we increase the number of neighbors, the model starts to generalize well, but increasing the value too much would again drop the performance. Therefore, it’s important to find an optimal value of K, such that the model is able to classify well on the test data set. Let’s observe the train and test accuracies as we increase the number of neighbors. The above result can be best visualized by the following plot. The plot shows an overall upward trend in test accuracy up to a point, after which the accuracy starts declining again. This is the optimal number of nearest neighbors, which in this case is 11, with a test accuracy of 90%. Let’s plot the decision boundary again for k=11, and see how it looks. We have improved the results by fine-tuning the number of neighbors. Also, the decision boundary by KNN now is much smoother and is able to generalize well on test data. Let’s now understand how KNN is used for regression. While the KNN classifier returns the mode of the nearest K neighbors, the KNN regressor returns the mean of the nearest K neighbors. We will use advertising data to understand KNN’s regression. Here are the first few rows of TV budget and sales. # Defining X and YX_ad = ad.TV.values.reshape(-1,1)y_ad = ad.sales# Splitting data into train and testtrain_x, test_x, train_y, test_y = train_test_split(X_ad, y_ad, test_size=0.25, random_state=42)# Running KNN for various values of n_neighbors and storing resultsknn_r_acc = []for i in range(1,17,1): knn = KNeighborsRegressor(n_neighbors=i) knn.fit(train_x,train_y) test_score = knn.score(test_x,test_y) train_score = knn.score(train_x,train_y) knn_r_acc.append((i, test_score ,train_score))df = pd.DataFrame(knn_r_acc, columns=['K','Test Score','Train Score'])print(df) The above code will run KNN for various values of K (from 1 to 16) and store the train and test scores in a Dataframe. Let’s see how these scores vary as we increase the value of n_neighbors (or K). At K=1, the KNN tends to closely follow the training data and thus shows a high training score. However, in comparison, the test score is quite low, thus indicating overfitting. Let’s visualize how the KNN draws the regression path for different values of K. As K increases, the KNN fits a smoother curve to the data. This is because a higher value of K reduces the edginess by taking more data into account, thus reducing the overall complexity and flexibility of the model. As we saw earlier, increasing the value of K improves the score to a certain point, after which it again starts dropping. This can be better understood by the following plot. As we see in this figure, the model yields the best results at K=4. I have used R2 to evaluate the model, and this was the best we could get. This is because our dataset was too small and scattered. Some other points are important to know about KNN are: KNN classifier does not have any specialized training phase as it uses all the training samples for classification and simply stores the results in memory. KNN is a non-parametric algorithm because it does not assume anything about the training data. This makes it useful for problems having non-linear data. KNN can be computationally expensive both in terms of time and storage, if the data is very large because KNN has to store the training data to work. This is generally not the case with other supervised learning models. KNN can be very sensitive to the scale of data as it relies on computing the distances. For features with a higher scale, the calculated distances can be very high and might produce poor results. It is thus advised to scale the data before running the KNN. That’s all for this post. I hope you had a good time learning KNN. For more, stay tuned.
[ { "code": null, "e": 214, "s": 171, "text": "“A man is known for the company he keeps.”" }, { "code": null, "e": 450, "s": 214, "text": "A perfect opening line I must say for presenting the K-Nearest Neighbors. Yes, that's how simple the concept behind KNN is. It just classifies a data point based on its few nearest neighbors. How many neighbors? That is what we decide." }, { "code": null, "e": 571, "s": 450, "text": "Looks like you already know a lot of there is to know about this simple model. Let’s dive in to have a much closer look." }, { "code": null, "e": 800, "s": 571, "text": "Before moving on, it’s important to know that KNN can be used for both classification and regression problems. We will first understand how it works for a classification problem, thereby making it easier to visualize regression." }, { "code": null, "e": 1166, "s": 800, "text": "The data we are going to use is the Breast Cancer Wisconsin(Diagnostic) Data Set. There are 30 attributes that correspond to the real-valued features computed for a cell nucleus under consideration. A total of 569 such samples are present in this data, out of which 357 are classified as ‘benign’ (harmless) and the rest 212 are classified as ‘malignant’ (harmful)." }, { "code": null, "e": 1335, "s": 1166, "text": "The diagnosis column contains ‘M’ or ‘B’ values for malignant and benign cancers respectively. I have changed these values to 1 and 0 respectively, for better analysis." }, { "code": null, "e": 1577, "s": 1335, "text": "Also, for the sake of this post, I will only use two attributes from the data → ‘mean radius’ and ‘mean texture’. This will later help us visualize the decision boundaries drawn by KNN. Here’s how the final data looks like (after shuffling):" }, { "code": null, "e": 1597, "s": 1577, "text": "Let’s code the KNN:" }, { "code": null, "e": 2138, "s": 1597, "text": "# Defining X and yX = data.drop('diagnosis',axis=1)y = data.diagnosis# Splitting data into train and testfrom sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(X,y,test_size=0.25,random_state=42)# Importing and fitting KNN classifier for k=3from sklearn.neighbors import KNeighborsClassifierknn = KNeighborsClassifier(n_neighbors=3)knn.fit(X_train,y_train)# Predicting results using Test data setpred = knn.predict(X_test)from sklearn.metrics import accuracy_scoreaccuracy_score(pred,y_test)" }, { "code": null, "e": 2215, "s": 2138, "text": "The above code should give you the following output with a slight variation." }, { "code": null, "e": 2234, "s": 2215, "text": "0.8601398601398601" }, { "code": null, "e": 2346, "s": 2234, "text": "What just happened? When we trained the KNN on training data, it took the following steps for each data sample:" }, { "code": null, "e": 2647, "s": 2346, "text": "Calculate the distance between the data sample and every other sample with the help of a method such as Euclidean.Sort these values of distances in ascending order.Choose the top K values from the sorted distances.Assign the class to the sample based on the most frequent class in the above K values." }, { "code": null, "e": 2762, "s": 2647, "text": "Calculate the distance between the data sample and every other sample with the help of a method such as Euclidean." }, { "code": null, "e": 2813, "s": 2762, "text": "Sort these values of distances in ascending order." }, { "code": null, "e": 2864, "s": 2813, "text": "Choose the top K values from the sorted distances." }, { "code": null, "e": 2951, "s": 2864, "text": "Assign the class to the sample based on the most frequent class in the above K values." }, { "code": null, "e": 3092, "s": 2951, "text": "Let’s visualize how KNN drew a decision boundary on the train data set and how the same boundary is then used to classify the test data set." }, { "code": null, "e": 3209, "s": 3092, "text": "With the training accuracy of 93% and the test accuracy of 86%, our model might have shown overfitting here. Why so?" }, { "code": null, "e": 3489, "s": 3209, "text": "When the value of K or the number of neighbors is too low, the model picks only the values that are closest to the data sample, thus forming a very complex decision boundary as shown above. Such a model fails to generalize well on the test data set, thereby showing poor results." }, { "code": null, "e": 3706, "s": 3489, "text": "The problem can be solved by tuning the value of n_neighbors parameter. As we increase the number of neighbors, the model starts to generalize well, but increasing the value too much would again drop the performance." }, { "code": null, "e": 3914, "s": 3706, "text": "Therefore, it’s important to find an optimal value of K, such that the model is able to classify well on the test data set. Let’s observe the train and test accuracies as we increase the number of neighbors." }, { "code": null, "e": 3977, "s": 3914, "text": "The above result can be best visualized by the following plot." }, { "code": null, "e": 4201, "s": 3977, "text": "The plot shows an overall upward trend in test accuracy up to a point, after which the accuracy starts declining again. This is the optimal number of nearest neighbors, which in this case is 11, with a test accuracy of 90%." }, { "code": null, "e": 4272, "s": 4201, "text": "Let’s plot the decision boundary again for k=11, and see how it looks." }, { "code": null, "e": 4442, "s": 4272, "text": "We have improved the results by fine-tuning the number of neighbors. Also, the decision boundary by KNN now is much smoother and is able to generalize well on test data." }, { "code": null, "e": 4495, "s": 4442, "text": "Let’s now understand how KNN is used for regression." }, { "code": null, "e": 4628, "s": 4495, "text": "While the KNN classifier returns the mode of the nearest K neighbors, the KNN regressor returns the mean of the nearest K neighbors." }, { "code": null, "e": 4741, "s": 4628, "text": "We will use advertising data to understand KNN’s regression. Here are the first few rows of TV budget and sales." }, { "code": null, "e": 5330, "s": 4741, "text": "# Defining X and YX_ad = ad.TV.values.reshape(-1,1)y_ad = ad.sales# Splitting data into train and testtrain_x, test_x, train_y, test_y = train_test_split(X_ad, y_ad, test_size=0.25, random_state=42)# Running KNN for various values of n_neighbors and storing resultsknn_r_acc = []for i in range(1,17,1): knn = KNeighborsRegressor(n_neighbors=i) knn.fit(train_x,train_y) test_score = knn.score(test_x,test_y) train_score = knn.score(train_x,train_y) knn_r_acc.append((i, test_score ,train_score))df = pd.DataFrame(knn_r_acc, columns=['K','Test Score','Train Score'])print(df)" }, { "code": null, "e": 5529, "s": 5330, "text": "The above code will run KNN for various values of K (from 1 to 16) and store the train and test scores in a Dataframe. Let’s see how these scores vary as we increase the value of n_neighbors (or K)." }, { "code": null, "e": 5707, "s": 5529, "text": "At K=1, the KNN tends to closely follow the training data and thus shows a high training score. However, in comparison, the test score is quite low, thus indicating overfitting." }, { "code": null, "e": 5788, "s": 5707, "text": "Let’s visualize how the KNN draws the regression path for different values of K." }, { "code": null, "e": 6005, "s": 5788, "text": "As K increases, the KNN fits a smoother curve to the data. This is because a higher value of K reduces the edginess by taking more data into account, thus reducing the overall complexity and flexibility of the model." }, { "code": null, "e": 6180, "s": 6005, "text": "As we saw earlier, increasing the value of K improves the score to a certain point, after which it again starts dropping. This can be better understood by the following plot." }, { "code": null, "e": 6379, "s": 6180, "text": "As we see in this figure, the model yields the best results at K=4. I have used R2 to evaluate the model, and this was the best we could get. This is because our dataset was too small and scattered." }, { "code": null, "e": 6434, "s": 6379, "text": "Some other points are important to know about KNN are:" }, { "code": null, "e": 6590, "s": 6434, "text": "KNN classifier does not have any specialized training phase as it uses all the training samples for classification and simply stores the results in memory." }, { "code": null, "e": 6743, "s": 6590, "text": "KNN is a non-parametric algorithm because it does not assume anything about the training data. This makes it useful for problems having non-linear data." }, { "code": null, "e": 6963, "s": 6743, "text": "KNN can be computationally expensive both in terms of time and storage, if the data is very large because KNN has to store the training data to work. This is generally not the case with other supervised learning models." }, { "code": null, "e": 7220, "s": 6963, "text": "KNN can be very sensitive to the scale of data as it relies on computing the distances. For features with a higher scale, the calculated distances can be very high and might produce poor results. It is thus advised to scale the data before running the KNN." } ]
TensorFlow vs PyTorch — Convolutional Neural Networks (CNN) | by Gurucharan M K | Towards Data Science
In my previous article, I had given the implementation of a Simple Linear Regression in both TensorFlow and PyTorch frameworks and compared their results. In this article, we shall go through the application of a Convolutional Neural Network (CNN) on a very famous Fashion MNIST dataset using both the frameworks and compare the results. Let us get a brief idea on both the frameworks and their history. Firstly, PyTorch is an open source machine learning library based on the Torch library. PyTorch was primarily developed by Facebook’s AI Research lab (FAIR). It is free and open-source software. On the other hand, TensorFlow was developed by the Google Brain team for internal Google research purpose. It is widely used for machine learning applications such as neural networks. It is also free and open-source software. In order to see which framework is more efficient and simpler to use, we shall build a ConvNet using both the frameworks and compare them. For the TensorFlow, we shall be using the Keras library. For comparison of both the frameworks, we will use the famous Fashion-MNIST dataset. It is a dataset of Zalando’s article images consisting of a training set of 60,000 examples and a test set of 10,000 examples. Each example is a 28×28 grayscale image, associated with a label from 10 classes such as shirt, bag, sandal, coat, sneaker etc. We will build a CNN network with a common architecture of LeNet with both the frameworks and compare their results. In the first step, we will be importing the required libraries for both the TensorFlow and PyTorch frameworks. In the next step, we will get the Fashion MNIST dataset. As it is a very common dataset, both the frameworks have preloaded functions that enable us to download the dataset and use it. In PyTorch, the built-in module is used to load the dataset. As we need the data in the form of tensors,the data is converted into tensors by using thetorchvision.transforms.ToTensor()and assigning it to the variable transforms. The data is then downloaded with torchvision.datasets. The data is correspondingly split into the train_dataset and the test_dataset. On the other hand, getting the data from the keras library using TensorFlow is more simpler compared to the PyTorch version. The dataset is loaded from keras.datasets and it is split into the train_images and test_images accordingly. In this step, we shall load the data into the training set and test set. Additionally, we shall also view how the image is stored in both the frameworks. In PyTorch, the images are stored in the ranges 0–1 and hence the images are displayed in B/W. The images are loaded into the train_loader and the test_loader using the DataLoaderfunction. Additionally, the label of the image is also printed. On the other hand, TensorFlow stores the images in the range 0–255 and hence there is a color gradient in the same image. TensorFlow is more simple in its approach of loading the data. In this step, we shall build the CNN Model. For this, we will build the standard LeNet-5 Architecture which is a very simple Architecture that was built in the year 1998. Given below is the architecture of LeNet-5. In this, we build the LeNet-5 Architecture using the PyTorch framework. It has 2 Convolutional layers each followed by a Average Pooling Layer, 2 Fully connected layers and a final output classifier layer with 10 classes as the final output has 10 categories of fashion items. In this, the model is built by creating a special class ‘NeuralNet’ where we have to define each layer of the network/model using the __init__ method. It is important to call this function ‘forward’ as this will override the base forward function in nn.Module and allow all the nn.Module functionality to work correctly. On the other hand, building the same model in TensorFlow doesn’t require creating a class even though we use the Sequential() method. We find that building the same model with TensorFlow framework is much more simpler and explicit than building the same model in a PyTorch framework first hand. In this step, we shall compile the model built in the previous step and set the optimizer and the loss functions. For this, in both the frameworks, we will use the Adam optimizer and the Categorical Cross Entropy loss function as there are more than 2 classes in the dataset. In PyTotch, we first create an instance of the ‘NeuralNet’ model built in the last step as modelpy. We then assign the optimizer and the loss function to the corresponding variables. Then we visualize the model by printing the modelpy. On the other hand, in the TensorFlow framework, we use the compile() function in which we will define the optimizer and the loss function as defined above. Then we use the summary() to see the layers of the LeNet-5 Architecture built above. It is in this step that we deploy the models built for training on the data in the training set. For both the frameworks, we will train the model for 30 epochs and see the results. For PyTorch, we have to individually compute all the steps including the loss function, optimizer, back-propagation and update each step in a for loop. In TensorFlow, the Fashion MNIST is an array with two dimensions, we have to reshape our training dataset to a tensor and convert the labels from integers to binary class matrix. The model is trained using the fit() function which consists of the defined number of epochs. In this final step, we shall compare the results of both the models built using the frameworks on the test set with the accuracy. In PyTorch, the output prediction is predicted by outputs = modelpy(images). The accuracy of the test set is then calculated and displayed. In TensorFlow, the predict() function is used to predict the classes of the images in the test dataset and the accuracy is calculated and displayed. The Test Set consists of 1000 images and the models built on both the PyTorch and the TensorFlow frameworks are used to predict the classes of the test set images. >>Test Accuracy of the model on the 10000 test images: 89% with PyTorch>>Test Accuracy of the model on the 10000 test images: 91.34% with TensorFlow From the results, we see that the test set accuracy of the TensorFlow model is 91.34% which is a little higher than that of the PyTorch model with 89%. From the above comparison, we were able to get an understanding of building a CNN model using two of the most popular frameworks used in Deep Learning today. In my opinion, if you are a beginner and are totally confused as to which framework to use, I’d suggest you start with the TensorFlow framework as it is simpler and easy to understand. On the other hand, PyTorch is more fast and dynamic but needs a bit of understanding of Python API. I have attached my GitHub repository where you can find the entire code of this comparison. github.com Do check out my previous article where I had given a comparison of both the frameworks in building a Simple Linear Regression model. towardsdatascience.com I do hope that I was able to give a good comparison of the two most popular frameworks that are used in Deep Learning today. Meet you all in my next article. Till then, Happy Machine Learning!
[ { "code": null, "e": 510, "s": 172, "text": "In my previous article, I had given the implementation of a Simple Linear Regression in both TensorFlow and PyTorch frameworks and compared their results. In this article, we shall go through the application of a Convolutional Neural Network (CNN) on a very famous Fashion MNIST dataset using both the frameworks and compare the results." }, { "code": null, "e": 771, "s": 510, "text": "Let us get a brief idea on both the frameworks and their history. Firstly, PyTorch is an open source machine learning library based on the Torch library. PyTorch was primarily developed by Facebook’s AI Research lab (FAIR). It is free and open-source software." }, { "code": null, "e": 997, "s": 771, "text": "On the other hand, TensorFlow was developed by the Google Brain team for internal Google research purpose. It is widely used for machine learning applications such as neural networks. It is also free and open-source software." }, { "code": null, "e": 1193, "s": 997, "text": "In order to see which framework is more efficient and simpler to use, we shall build a ConvNet using both the frameworks and compare them. For the TensorFlow, we shall be using the Keras library." }, { "code": null, "e": 1649, "s": 1193, "text": "For comparison of both the frameworks, we will use the famous Fashion-MNIST dataset. It is a dataset of Zalando’s article images consisting of a training set of 60,000 examples and a test set of 10,000 examples. Each example is a 28×28 grayscale image, associated with a label from 10 classes such as shirt, bag, sandal, coat, sneaker etc. We will build a CNN network with a common architecture of LeNet with both the frameworks and compare their results." }, { "code": null, "e": 1760, "s": 1649, "text": "In the first step, we will be importing the required libraries for both the TensorFlow and PyTorch frameworks." }, { "code": null, "e": 1945, "s": 1760, "text": "In the next step, we will get the Fashion MNIST dataset. As it is a very common dataset, both the frameworks have preloaded functions that enable us to download the dataset and use it." }, { "code": null, "e": 2308, "s": 1945, "text": "In PyTorch, the built-in module is used to load the dataset. As we need the data in the form of tensors,the data is converted into tensors by using thetorchvision.transforms.ToTensor()and assigning it to the variable transforms. The data is then downloaded with torchvision.datasets. The data is correspondingly split into the train_dataset and the test_dataset." }, { "code": null, "e": 2542, "s": 2308, "text": "On the other hand, getting the data from the keras library using TensorFlow is more simpler compared to the PyTorch version. The dataset is loaded from keras.datasets and it is split into the train_images and test_images accordingly." }, { "code": null, "e": 2696, "s": 2542, "text": "In this step, we shall load the data into the training set and test set. Additionally, we shall also view how the image is stored in both the frameworks." }, { "code": null, "e": 2939, "s": 2696, "text": "In PyTorch, the images are stored in the ranges 0–1 and hence the images are displayed in B/W. The images are loaded into the train_loader and the test_loader using the DataLoaderfunction. Additionally, the label of the image is also printed." }, { "code": null, "e": 3124, "s": 2939, "text": "On the other hand, TensorFlow stores the images in the range 0–255 and hence there is a color gradient in the same image. TensorFlow is more simple in its approach of loading the data." }, { "code": null, "e": 3339, "s": 3124, "text": "In this step, we shall build the CNN Model. For this, we will build the standard LeNet-5 Architecture which is a very simple Architecture that was built in the year 1998. Given below is the architecture of LeNet-5." }, { "code": null, "e": 3616, "s": 3339, "text": "In this, we build the LeNet-5 Architecture using the PyTorch framework. It has 2 Convolutional layers each followed by a Average Pooling Layer, 2 Fully connected layers and a final output classifier layer with 10 classes as the final output has 10 categories of fashion items." }, { "code": null, "e": 3937, "s": 3616, "text": "In this, the model is built by creating a special class ‘NeuralNet’ where we have to define each layer of the network/model using the __init__ method. It is important to call this function ‘forward’ as this will override the base forward function in nn.Module and allow all the nn.Module functionality to work correctly." }, { "code": null, "e": 4232, "s": 3937, "text": "On the other hand, building the same model in TensorFlow doesn’t require creating a class even though we use the Sequential() method. We find that building the same model with TensorFlow framework is much more simpler and explicit than building the same model in a PyTorch framework first hand." }, { "code": null, "e": 4508, "s": 4232, "text": "In this step, we shall compile the model built in the previous step and set the optimizer and the loss functions. For this, in both the frameworks, we will use the Adam optimizer and the Categorical Cross Entropy loss function as there are more than 2 classes in the dataset." }, { "code": null, "e": 4744, "s": 4508, "text": "In PyTotch, we first create an instance of the ‘NeuralNet’ model built in the last step as modelpy. We then assign the optimizer and the loss function to the corresponding variables. Then we visualize the model by printing the modelpy." }, { "code": null, "e": 4985, "s": 4744, "text": "On the other hand, in the TensorFlow framework, we use the compile() function in which we will define the optimizer and the loss function as defined above. Then we use the summary() to see the layers of the LeNet-5 Architecture built above." }, { "code": null, "e": 5166, "s": 4985, "text": "It is in this step that we deploy the models built for training on the data in the training set. For both the frameworks, we will train the model for 30 epochs and see the results." }, { "code": null, "e": 5318, "s": 5166, "text": "For PyTorch, we have to individually compute all the steps including the loss function, optimizer, back-propagation and update each step in a for loop." }, { "code": null, "e": 5591, "s": 5318, "text": "In TensorFlow, the Fashion MNIST is an array with two dimensions, we have to reshape our training dataset to a tensor and convert the labels from integers to binary class matrix. The model is trained using the fit() function which consists of the defined number of epochs." }, { "code": null, "e": 5721, "s": 5591, "text": "In this final step, we shall compare the results of both the models built using the frameworks on the test set with the accuracy." }, { "code": null, "e": 5861, "s": 5721, "text": "In PyTorch, the output prediction is predicted by outputs = modelpy(images). The accuracy of the test set is then calculated and displayed." }, { "code": null, "e": 6010, "s": 5861, "text": "In TensorFlow, the predict() function is used to predict the classes of the images in the test dataset and the accuracy is calculated and displayed." }, { "code": null, "e": 6174, "s": 6010, "text": "The Test Set consists of 1000 images and the models built on both the PyTorch and the TensorFlow frameworks are used to predict the classes of the test set images." }, { "code": null, "e": 6323, "s": 6174, "text": ">>Test Accuracy of the model on the 10000 test images: 89% with PyTorch>>Test Accuracy of the model on the 10000 test images: 91.34% with TensorFlow" }, { "code": null, "e": 6475, "s": 6323, "text": "From the results, we see that the test set accuracy of the TensorFlow model is 91.34% which is a little higher than that of the PyTorch model with 89%." }, { "code": null, "e": 6633, "s": 6475, "text": "From the above comparison, we were able to get an understanding of building a CNN model using two of the most popular frameworks used in Deep Learning today." }, { "code": null, "e": 6918, "s": 6633, "text": "In my opinion, if you are a beginner and are totally confused as to which framework to use, I’d suggest you start with the TensorFlow framework as it is simpler and easy to understand. On the other hand, PyTorch is more fast and dynamic but needs a bit of understanding of Python API." }, { "code": null, "e": 7010, "s": 6918, "text": "I have attached my GitHub repository where you can find the entire code of this comparison." }, { "code": null, "e": 7021, "s": 7010, "text": "github.com" }, { "code": null, "e": 7154, "s": 7021, "text": "Do check out my previous article where I had given a comparison of both the frameworks in building a Simple Linear Regression model." }, { "code": null, "e": 7177, "s": 7154, "text": "towardsdatascience.com" } ]
King's War | Practice | GeeksforGeeks
King is getting ready for a war. He know his strengths and weeknesses so he is taking required number of soldiers with him. King can only defeat enemies with strongest and weakest power, and one soldier can only kill one enemy. Your task is to calculate that how many soldiers are required by king to take with him for the war. Note: The array may contain duplicates. Example 1: Input: N = 2 A[] = {1, 5} Output: 0 Explanatation: The king will itself be able to defeat all the enemies. Example 2: Input: N = 3 A[] = {1, 2, 5} Output: 1 Explanatation: The king will defeat enemies with power 1 and 5, and he will need 1 soldier to defeat the enemy with power 2. Your Task: You don't need to read input or print anything. Your task is to complete the function SoldierRequired() which takes the array A[] and its size N as inputs and returns the number of soldiers, king will need to take with him for the war. Expected Time Complexity: O(NLogN) Expected Auxiliary Space: O(1) Constraints: 1 ≤ N ≤ 106 1 ≤ Ai ≤ 106 Array may contain duplicates 0 hasnainraza1998hr1 month ago C++, 0.5, O(n), without sorting long long SoldierRequired(long long a[], long long n) { int weakest = *min_element(a,a+n); int strongest = *max_element(a,a+n); long long soldiers = 0; for(int i=0;i<n;i++){ if(a[i]!=weakest && a[i]!=strongest) soldiers++; } return soldiers; } 0 rahulrs2 months ago JAVA CODE................................ public static long SoldierRequired(long arr[], long n){ // Your code goes here Arrays.sort(arr); int strong = (int)arr[(int)(n-1)]; int weak = (int)arr[0]; long count=0; if(n==2){ return 0; }else{ for(int i=0;i<arr.length;i++){ if(arr[i]!=strong && arr[i]!=weak){ count++; } } } return (long)count; } +1 princejee20192 months ago C++ Code ||EASY TO UNDERSTAND|| 0(N*log(n)) class Solution{ public: long long SoldierRequired(long long a[], long long n) { // Your code goes here if(n<=2){ return 0; } sort(a,a+n); long long count =2; for(int i =1;i<(n-1);i++){ if(a[0]==a[i]){ count++; } if(a[n-1]==a[i]){ count++; } } return (n-count); }}; 0 vidhigupta123 months ago long long SoldierRequired(long long a[], long long n) { // Your code goes here long long min=0,max=0; if(n<=1) return 0; sort(a,a+n); for(long long i=1;i<n-1;i++) { if(a[0]==a[i]) { min++; } else if(a[n-1]==a[i]) { max++; } } return n-2-min-max; } 0 shashwatsatna3 months ago I don't understand this question. 0 deveshamway4 months ago O(N) C++ Solution : long long SoldierRequired(long long arr[], long long n) { int max=INT_MIN, min =INT_MAX; for(int i =0;i<n;i++){ if(arr[i]>max){ max= arr[i]; } if(arr[i]<min){ min = arr[i]; } } long long count=n; for(int i =0;i<n;i++){ if(arr[i]==min || arr[i]==max){ count--; } } return count; } 0 Rahul Kakkar1 year ago Rahul Kakkar long long SoldierRequired(long long a[], long long n) { // Your code goes here sort(a,a+n); int max = a[n-1]; int min = a[0]; long long count = 0; int i = 0; int j = n-1; while(i<j) {="" if(a[i]="=min)" {="" count++;="" i++;="" }="" else="" if(a[j]="=max)" {="" count++;="" j--;="" }="" else="" break;="" }="" if(n="=2" ||="" n="=1)" {="" return="" 0;="" }="" return="" n-count;="" }<="" code=""> 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": 596, "s": 226, "text": "King is getting ready for a war. He know his strengths and weeknesses so he is taking required number of soldiers with him. King can only defeat enemies with strongest and weakest power, and one soldier can only kill one enemy. Your task is to calculate that how many soldiers are required by king to take with him for the war.\nNote: The array may contain duplicates.\n " }, { "code": null, "e": 607, "s": 596, "text": "Example 1:" }, { "code": null, "e": 714, "s": 607, "text": "Input:\nN = 2\nA[] = {1, 5}\nOutput:\n0\nExplanatation:\nThe king will itself be able to defeat all the enemies." }, { "code": null, "e": 727, "s": 716, "text": "Example 2:" }, { "code": null, "e": 891, "s": 727, "text": "Input:\nN = 3\nA[] = {1, 2, 5}\nOutput:\n1\nExplanatation:\nThe king will defeat enemies with power\n1 and 5, and he will need 1 soldier to\ndefeat the enemy with power 2." }, { "code": null, "e": 1211, "s": 893, "text": "Your Task: \nYou don't need to read input or print anything. Your task is to complete the function SoldierRequired() which takes the array A[] and its size N as inputs and returns the number of soldiers, king will need to take with him for the war.\n\nExpected Time Complexity: O(NLogN)\nExpected Auxiliary Space: O(1)\n " }, { "code": null, "e": 1279, "s": 1211, "text": "Constraints:\n1 ≤ N ≤ 106 \n1 ≤ Ai ≤ 106\nArray may contain duplicates" }, { "code": null, "e": 1281, "s": 1279, "text": "0" }, { "code": null, "e": 1310, "s": 1281, "text": "hasnainraza1998hr1 month ago" }, { "code": null, "e": 1342, "s": 1310, "text": "C++, 0.5, O(n), without sorting" }, { "code": null, "e": 1657, "s": 1342, "text": "long long SoldierRequired(long long a[], long long n) { int weakest = *min_element(a,a+n); int strongest = *max_element(a,a+n); long long soldiers = 0; for(int i=0;i<n;i++){ if(a[i]!=weakest && a[i]!=strongest) soldiers++; } return soldiers; }" }, { "code": null, "e": 1659, "s": 1657, "text": "0" }, { "code": null, "e": 1679, "s": 1659, "text": "rahulrs2 months ago" }, { "code": null, "e": 1722, "s": 1679, "text": "JAVA CODE................................ " }, { "code": null, "e": 2156, "s": 1722, "text": "public static long SoldierRequired(long arr[], long n){ // Your code goes here Arrays.sort(arr); int strong = (int)arr[(int)(n-1)]; int weak = (int)arr[0]; long count=0; if(n==2){ return 0; }else{ for(int i=0;i<arr.length;i++){ if(arr[i]!=strong && arr[i]!=weak){ count++; } } } return (long)count; }" }, { "code": null, "e": 2159, "s": 2156, "text": "+1" }, { "code": null, "e": 2185, "s": 2159, "text": "princejee20192 months ago" }, { "code": null, "e": 2229, "s": 2185, "text": "C++ Code ||EASY TO UNDERSTAND|| 0(N*log(n))" }, { "code": null, "e": 2634, "s": 2229, "text": "class Solution{ public: long long SoldierRequired(long long a[], long long n) { // Your code goes here if(n<=2){ return 0; } sort(a,a+n); long long count =2; for(int i =1;i<(n-1);i++){ if(a[0]==a[i]){ count++; } if(a[n-1]==a[i]){ count++; } } return (n-count); }};" }, { "code": null, "e": 2636, "s": 2634, "text": "0" }, { "code": null, "e": 2661, "s": 2636, "text": "vidhigupta123 months ago" }, { "code": null, "e": 3056, "s": 2661, "text": "long long SoldierRequired(long long a[], long long n) { // Your code goes here long long min=0,max=0; if(n<=1) return 0; sort(a,a+n); for(long long i=1;i<n-1;i++) { if(a[0]==a[i]) { min++; } else if(a[n-1]==a[i]) { max++; } } return n-2-min-max; }" }, { "code": null, "e": 3058, "s": 3056, "text": "0" }, { "code": null, "e": 3084, "s": 3058, "text": "shashwatsatna3 months ago" }, { "code": null, "e": 3118, "s": 3084, "text": "I don't understand this question." }, { "code": null, "e": 3120, "s": 3118, "text": "0" }, { "code": null, "e": 3144, "s": 3120, "text": "deveshamway4 months ago" }, { "code": null, "e": 3598, "s": 3144, "text": "O(N) C++ Solution : long long SoldierRequired(long long arr[], long long n) { int max=INT_MIN, min =INT_MAX; for(int i =0;i<n;i++){ if(arr[i]>max){ max= arr[i]; } if(arr[i]<min){ min = arr[i]; } } long long count=n; for(int i =0;i<n;i++){ if(arr[i]==min || arr[i]==max){ count--; } } return count; }" }, { "code": null, "e": 3600, "s": 3598, "text": "0" }, { "code": null, "e": 3623, "s": 3600, "text": "Rahul Kakkar1 year ago" }, { "code": null, "e": 3636, "s": 3623, "text": "Rahul Kakkar" }, { "code": null, "e": 4129, "s": 3636, "text": "long long SoldierRequired(long long a[], long long n) { // Your code goes here sort(a,a+n); int max = a[n-1]; int min = a[0]; long long count = 0; int i = 0; int j = n-1; while(i<j) {=\"\" if(a[i]=\"=min)\" {=\"\" count++;=\"\" i++;=\"\" }=\"\" else=\"\" if(a[j]=\"=max)\" {=\"\" count++;=\"\" j--;=\"\" }=\"\" else=\"\" break;=\"\" }=\"\" if(n=\"=2\" ||=\"\" n=\"=1)\" {=\"\" return=\"\" 0;=\"\" }=\"\" return=\"\" n-count;=\"\" }<=\"\" code=\"\">" }, { "code": null, "e": 4275, "s": 4129, "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": 4311, "s": 4275, "text": " Login to access your submissions. " }, { "code": null, "e": 4321, "s": 4311, "text": "\nProblem\n" }, { "code": null, "e": 4331, "s": 4321, "text": "\nContest\n" }, { "code": null, "e": 4394, "s": 4331, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 4542, "s": 4394, "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": 4750, "s": 4542, "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": 4856, "s": 4750, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Increasing the space for X-axis labels in Matplotlib
To increase the space for X-axis labels in Matplotlib, we can use the spacing variable in subplots_adjust() method's argument. 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. Create a new figure or activate an existing figure using figure() method. Create a new figure or activate an existing figure using figure() method. Create x and y data points using numpy. Create x and y data points using numpy. Plot x and y using plot() method. Plot x and y using plot() method. Put xlabel using xlabel() method with LaTex expression. Put xlabel using xlabel() method with LaTex expression. Use subplots_adjust() method to increase or decrease the space for X-axis labels Use subplots_adjust() method to increase or decrease the space for X-axis labels To display the figure, use show() method. To display the figure, use show() method. import numpy as np from matplotlib import pyplot as plt plt.rcParams["figure.figsize"] = [7.50, 3.50] plt.rcParams["figure.autolayout"] = True fig = plt.figure() x = np.linspace(-2, 2, 10) y = np.exp(x) plt.plot(x, y) plt.xlabel("$\\bf{y=e^{x}}$") spacing = 0.100 fig.subplots_adjust(bottom=spacing) plt.show()
[ { "code": null, "e": 1189, "s": 1062, "text": "To increase the space for X-axis labels in Matplotlib, we can use the spacing variable in subplots_adjust() method's argument." }, { "code": null, "e": 1265, "s": 1189, "text": "Set the figure size and adjust the padding between and around the subplots." }, { "code": null, "e": 1341, "s": 1265, "text": "Set the figure size and adjust the padding between and around the subplots." }, { "code": null, "e": 1415, "s": 1341, "text": "Create a new figure or activate an existing figure using figure() method." }, { "code": null, "e": 1489, "s": 1415, "text": "Create a new figure or activate an existing figure using figure() method." }, { "code": null, "e": 1529, "s": 1489, "text": "Create x and y data points using numpy." }, { "code": null, "e": 1569, "s": 1529, "text": "Create x and y data points using numpy." }, { "code": null, "e": 1603, "s": 1569, "text": "Plot x and y using plot() method." }, { "code": null, "e": 1637, "s": 1603, "text": "Plot x and y using plot() method." }, { "code": null, "e": 1693, "s": 1637, "text": "Put xlabel using xlabel() method with LaTex expression." }, { "code": null, "e": 1749, "s": 1693, "text": "Put xlabel using xlabel() method with LaTex expression." }, { "code": null, "e": 1830, "s": 1749, "text": "Use subplots_adjust() method to increase or decrease the space for X-axis labels" }, { "code": null, "e": 1911, "s": 1830, "text": "Use subplots_adjust() method to increase or decrease the space for X-axis labels" }, { "code": null, "e": 1953, "s": 1911, "text": "To display the figure, use show() method." }, { "code": null, "e": 1995, "s": 1953, "text": "To display the figure, use show() method." }, { "code": null, "e": 2306, "s": 1995, "text": "import numpy as np\nfrom matplotlib import pyplot as plt\nplt.rcParams[\"figure.figsize\"] = [7.50, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\nfig = plt.figure()\nx = np.linspace(-2, 2, 10)\ny = np.exp(x)\nplt.plot(x, y)\nplt.xlabel(\"$\\\\bf{y=e^{x}}$\")\nspacing = 0.100\nfig.subplots_adjust(bottom=spacing)\nplt.show()" } ]
Censoring toxic comments using fastai v2 with a multi-label text classifier | by Vinayak Nayak | Towards Data Science
The internet has become a basic necessity in recent times and a lot of things which happen physically in our world are on the verge of being digitised. Already a substantial proportion of the world population uses the internet for day to day chores, entertainment, academic research etc. It then is a big responsibility to keep the internet a safe space for everyone to come and interact because there are all sorts of people posting stuff on the internet without being conscious of its consequences. This post goes through the process of making a text classifier which takes in a piece of text (phrase, sentence, paragraph any length text) and tells if the text falls under a range of different types of malignant prose. The topics covered in this post are Introduction Getting Data From Kaggle Data Exploration Approach toward multilabel text classification Language Model in fastai v2 Classification Model in fastai v2 Making inferences References You can click on any of the above bullet points to navigate to the respective section. Disclaimer: The dataset used here contains some text that may be considered profane, vulgar, or offensive. Natural Language Processing is a field that deals with understanding the interactions between computers and human language. Since a lot of things are going online or digital, and since these services are democratised to the whole world, the scale at which this data is generated is humongous. In these times where everyone on the planet is putting their opinions, thoughts, facts, essays, poems etc. online, monitoring and moderating these pieces of text is an inhuman task (even when we think of humans as a community and not an individual being). Thanks to the advent of high capacity GPUs and TPUs and the recent advances in AI for text applications, we have come up with a lot of techniques to tackle this problem. Recurrent Neural Networks are the key element with the help of which these problems are addressed. fastai, a deep learning library built on top of PyTorch, developed by Jeremy Howard and Sylvain Gugger makes building applications for tasks like these very user-friendly and simple. Let’s the get started and learn how to do text classification using fastai. The data we’ll use for demonstrating the process of multi-label text classification is obtained from Toxic Comment Classification Challenge on Kaggle. Our model will be responsible for detecting different types of toxicity like threats, obscenity, insults, and identity-based hate. The dataset consists comments from Wikipedia’s talk page edits. Without any further ado, let’s get started with downloading this dataset. You can either download the dataset from Kaggle manually or use the API provided by kaggle using the above commands. To use the API, you’ll have to create an account with Kaggle and generate the API key which allows you to use shell commands for downloading the dataset from kaggle and also making submissions for predictions from the working notebook or from the shell. Once you create a Kaggle account and create the API key, you will get a json file which contains both your username and key. Those need to be input in the above code as per your unique credentials. This post by MRINALI GUPTA nicely explains how to get started with Kaggle API for downloading datasets. Let’s read in both the train and test sets and get a hang of what data is contained in them. There are several fields in the dataframe. id: An identifier which is associated with ever comment text. Since this is picked up from Wikipedia’s talk page, it could probably be the identification of a person who has commented, or an HTML DOM id of the text that they’ve posted. comment_text: The text of the comment which the user has posted. toxic, severe_toxic, obscene, threat, insult, identity_hate: These columns denote the presence of the eponymous elements in comment_text. If they’re absent they’re represented by zeros else they’re represented by a 1. These elements are independent in the sense, they’re not mutually exclusive for eg. A comment can be both toxic and insulting, or it’s not necessary that if a comment is toxic it couldn’t be obscene and so on. In general, there’s a lot less comments that have objectionable text; considering that we’ve got more than a hundred thousand comments, there’s less than tens of thousand objectionable categories (except toxic which is just a few more). This is good to know but it would be for the best if there were still fewer texts of this kind. Also, the text was annotated by humans to have these labels. This task of annotation is a huge task and a lot of human interpretation and bias will have come along with these annotations. It’s something that needs to be remembered and we’ll talk about this in closing thoughts. Text or sentences are sequences of individual units — words, sub-words or characters (depends on the language you speak). Any Machine Learning algorithm is not capable of handling anything other than numbers. So, we will first have to represent the data in terms of numbers. In any text related problems, first we create a vocabulary of words which basically is the total corpus of words which we will consider; any other word will be tagged with a special tag called unknown and put in that bucket. This process is called tokenization. Next, we map every word to a numerical token and create a dictionary of words that stores this mapping. So every prose/comment/text is now converted into a list of numbers. This process is called numericalization. Most certainly the comments will not be of equal length, because people are not restricted to comment in exactly a fixed number of words. But when creating batches of text to feed to our network, we need them all to be of the same length. Therefore we pad the sentences with a special token or truncate the sentence if it’s too big to constrict to a fixed length. This process is called padding. While doing all the above, there are some other operations like lowercasing all the text, dealing with punctuation as separate tokens, understanding capitalization in spite of lowercasing and so on. This is where the good people at fastai make all of these things super easy for us. xxpad: For padding, this is the standard token that’s used. xxunk: When an oov (out of vocabulary) word is encountered, this token is used to replace that word. xxbos: At the start of every sentence, this is a token which indicates the start/beginning of a sequence. xxmaj: If a word is capitalised or title cased, this token is prefixed to capture that information. xxrep: If a word is repeated, then in the tokenized representation, we will have that word followed by xxrep token followed by number of repetitions. There’s some more semantic information handled with more such tokens but all of this makes sure to capture precious information about the text and the meaning behind it. Once this preprocessing is done, we can then right of the bat build an LSTM model to classify the texts into the respective labels. Words are represented as n-dimensional vectors which are colloquially called encoding/embedding. There’s a construct for Embedding in PyTorch which helps lookup the vector representation for a word given it’s numerical token and that’s followed by other RNN layers and fully connected layers to build an architecture which can take sequence as an input and return a bunch of probabilities as the output. These vector embeddings could be randomly initialized or borrowed from commonly available GLoVE or Word2Vec embeddings which have been trained on a large corpus of text so that they have a good semantic word understanding about context in that particular language in a generic sense. However, there’s a trick which could improve the results if we perform it before building a classifier. That’s what we’ll look at next. fastai has suggested this tried and tested method of fine-tuning a Language Model before building any kind of classifier or application. In a nutshell, what they say is if you have a set of word embeddings which were trained on a huge corpus, they have a very generic understanding of the words that they learned from that corpus. However, when we talk about classification of hate speech and obnoxious comments and toxic stuff, there’s a specific negative vibe associated with these sentences and that semantic context is not yet present in our embeddings. Also, many words/terms specific to our application (it may be medicine or law or toxic speech) may not be encountered often in that huge corpus from which we obtained the word embeddings. Those should be there included and represented well in the embeddings that our classifier is going to use. So, before building a classifier we’ll finetune a Language Model which has been trained on wikipedia text corpus. We will bind the train and test dataset comments together and feed them to the language model. This is because we’re not doing classification but simply guessing the next word of a sequence given the current sequence; it’s called a self supervised task. With the embeddings learned this way, we’ll be able to build a better classifier because it has an idea of the concepts specific to our corpus. Let’s see how we can instantiate and fine-tune a language model in fastai v2. We append the train and test data and throw away the labels because we don’t need them in this self-supervised learning task. Next, we have to create a dataloader to tokenize these texts, do all the numericalization, padding and preprocessing before feeding it to the language model. That’s how simple it is in fastai, you just have to wrap all the arguments in a factory method and instantiate the TextDataLoaders class with it. This would have otherwise taken at least a hundred lines of codes with proper commenting and stuff but thanks to fastai, it’s short and sweet. We can have a look at a couple of entries from a batch. As we can see the output is just offsetting the given sequence by one word which is in alignment with what we want, i.e. given a sequence, predict next word of a sequence. Once we have this dataloader, we can create a language model learner which can tune the encodings as per our corpus instead of the previous corpus of text. After we have the language model learner, we can fit the learner over several epochs and save the encodings using the save_encoder method. We can see that the language model can on an average predict with a 38% accuracy what the next word would be given the current sequence of words which is pretty decent for this dataset. Once we have this ready, now we can move to the next step of creating a classifier to identify the probabilities for different labels of the comment_text. Before we move to creating a classification model, there’s some bit of preprocessing that we need to perform in order to build a proper dataloader. At the time of writing this post, there’s an issue with the DataBlocks API for text which avoids it from inferring all the dependent variables properly, hence we have to resort to this method. Basically, we will have to create another column in our dataframe which indicates the presence or absence of individual label using a fixed delimiter. So, if a comment is obscene and toxic, our new column will show obscene;toxic where delimiter is “;”. Also for the rows which don’t have any objectionable text, we will call them sober for now for the sake of giving a label (without any label, fastai won’t create the dataloader). So we can see that there’s a column Labels added which contains a “;” delimited labels field where all our labels are denoted instead of the one-hot encoded format in which they’re provided. Now, we create the dataloaders using the datablocks API using “comment_text” field for x and “Labels” field for y respectively. If we would have mentioned the names of 6 columns as a list in the get_y field, it always picks up only two fields; due to this incorrect inference on the dataloader’s part, we have to go through the process of creating a separate label column for getting the dependent variable i.e. y’s values. Next, once we have the dataloader, we can build a classifier model using an LSTM architecture. Also we need to load the language model encodings/embeddings to the classifier once have instantiated it. Then we can start training the classifier. Initially, we will keep most of the network except the final FC layer frozen. This means that the back-propagation weight updates will only happen in the penultimate layer. Gradually we will unfreeze the previous layers until eventually we unfreeze the whole network. We do this because if we start with an unfrozen network, it will become difficult for the model to converge quickly to the optimal solution. It can be seen that the accuracy has reached a pretty solid 98% buy the end of the training. Since both train and valid loss both are decreasing, we can ideally train for more epochs and keep going but in the interest of time, we shall consider this a good enough score and start with the inference. Now that we have a trained model and we’ve stored it as a pkl, we can use it for making predictions on previously unseen i.e. test data. We shall first load the model that we just created and trained on the GPU. (Since we have hundreds of thousands of comment texts, CPU inference will take a lot of time). Next we will tokenize the test_df and then pass it through the same transforms that were used for train and validation data to create a dataloader of test comments for inference. Next we will use the get_preds method for inference and remember to pass the reorder method to False otherwise there’s a random shuffling of the texts that happens which will lead to incorrect order of predictions at the end. Finally, we shall format these predictions in the sample_submissions.csv style. So, after predictions, we get a set of 7 values one for each class and the probability of “sober” class is not needed since it was introduced by us as a placeholder. We remove that and get all the ids in proper order. This is how the final submission looks like. Finally we can submit these predictions using the kaggle API itself. No need to manually go to kaggle and submit the csv file. It could be done simply by this shell command. # Submit the predictions to kaggle!kaggle competitions submit -c jigsaw-toxic-comment-classification-challenge -f submissions_toxic.csv -m "First submission for toxic comments classification" You can change the submissions file name and message as per your own convenience. The final submission score I got is as shown below The top score on the leaderboard is around .9885 so our score is somewhat good with such few lines of code and little to no preprocessing. We could’ve removed stopwords, cleaned html tags, tackled punctuation, tuned language model even more or used GloVE or Word2Vec embeddings and went for a complex model like Transformer instead of a simple LSTM. Many people have approached this differently and used some of these techniques to get to such high scores. However, with little effort and using the already implemented fastai library we could get a decent enough score right in our first attempt. On a closing thought, it is worth mentioning that this dataset as annotated by humans may have been mislabelled or there could have been subjective differences between people which is also fair because it’s a very manual and monotonous job. We could aid that process by building a model, then using it to annotate and have humans supervise the annotations to make the process simpler or crowd-source this work to multiple volunteers to get a large corpus of labelled data in a small amount of time. In any case, NLP has become highly instrumental in tackling many language problems in the real world and hope after reading this post, you feel confident to start your journey in the world of text with fastai! Toxic Comments dataset from KaggleHow to use Kaggle API for downloading dataGithub repo with all code for this postText classification notebook using fastai Toxic Comments dataset from Kaggle How to use Kaggle API for downloading data Github repo with all code for this post Text classification notebook using fastai
[ { "code": null, "e": 673, "s": 172, "text": "The internet has become a basic necessity in recent times and a lot of things which happen physically in our world are on the verge of being digitised. Already a substantial proportion of the world population uses the internet for day to day chores, entertainment, academic research etc. It then is a big responsibility to keep the internet a safe space for everyone to come and interact because there are all sorts of people posting stuff on the internet without being conscious of its consequences." }, { "code": null, "e": 930, "s": 673, "text": "This post goes through the process of making a text classifier which takes in a piece of text (phrase, sentence, paragraph any length text) and tells if the text falls under a range of different types of malignant prose. The topics covered in this post are" }, { "code": null, "e": 943, "s": 930, "text": "Introduction" }, { "code": null, "e": 968, "s": 943, "text": "Getting Data From Kaggle" }, { "code": null, "e": 985, "s": 968, "text": "Data Exploration" }, { "code": null, "e": 1032, "s": 985, "text": "Approach toward multilabel text classification" }, { "code": null, "e": 1060, "s": 1032, "text": "Language Model in fastai v2" }, { "code": null, "e": 1094, "s": 1060, "text": "Classification Model in fastai v2" }, { "code": null, "e": 1112, "s": 1094, "text": "Making inferences" }, { "code": null, "e": 1123, "s": 1112, "text": "References" }, { "code": null, "e": 1210, "s": 1123, "text": "You can click on any of the above bullet points to navigate to the respective section." }, { "code": null, "e": 1317, "s": 1210, "text": "Disclaimer: The dataset used here contains some text that may be considered profane, vulgar, or offensive." }, { "code": null, "e": 1866, "s": 1317, "text": "Natural Language Processing is a field that deals with understanding the interactions between computers and human language. Since a lot of things are going online or digital, and since these services are democratised to the whole world, the scale at which this data is generated is humongous. In these times where everyone on the planet is putting their opinions, thoughts, facts, essays, poems etc. online, monitoring and moderating these pieces of text is an inhuman task (even when we think of humans as a community and not an individual being)." }, { "code": null, "e": 2318, "s": 1866, "text": "Thanks to the advent of high capacity GPUs and TPUs and the recent advances in AI for text applications, we have come up with a lot of techniques to tackle this problem. Recurrent Neural Networks are the key element with the help of which these problems are addressed. fastai, a deep learning library built on top of PyTorch, developed by Jeremy Howard and Sylvain Gugger makes building applications for tasks like these very user-friendly and simple." }, { "code": null, "e": 2394, "s": 2318, "text": "Let’s the get started and learn how to do text classification using fastai." }, { "code": null, "e": 2545, "s": 2394, "text": "The data we’ll use for demonstrating the process of multi-label text classification is obtained from Toxic Comment Classification Challenge on Kaggle." }, { "code": null, "e": 2814, "s": 2545, "text": "Our model will be responsible for detecting different types of toxicity like threats, obscenity, insults, and identity-based hate. The dataset consists comments from Wikipedia’s talk page edits. Without any further ado, let’s get started with downloading this dataset." }, { "code": null, "e": 2931, "s": 2814, "text": "You can either download the dataset from Kaggle manually or use the API provided by kaggle using the above commands." }, { "code": null, "e": 3383, "s": 2931, "text": "To use the API, you’ll have to create an account with Kaggle and generate the API key which allows you to use shell commands for downloading the dataset from kaggle and also making submissions for predictions from the working notebook or from the shell. Once you create a Kaggle account and create the API key, you will get a json file which contains both your username and key. Those need to be input in the above code as per your unique credentials." }, { "code": null, "e": 3487, "s": 3383, "text": "This post by MRINALI GUPTA nicely explains how to get started with Kaggle API for downloading datasets." }, { "code": null, "e": 3580, "s": 3487, "text": "Let’s read in both the train and test sets and get a hang of what data is contained in them." }, { "code": null, "e": 3623, "s": 3580, "text": "There are several fields in the dataframe." }, { "code": null, "e": 3859, "s": 3623, "text": "id: An identifier which is associated with ever comment text. Since this is picked up from Wikipedia’s talk page, it could probably be the identification of a person who has commented, or an HTML DOM id of the text that they’ve posted." }, { "code": null, "e": 3924, "s": 3859, "text": "comment_text: The text of the comment which the user has posted." }, { "code": null, "e": 4142, "s": 3924, "text": "toxic, severe_toxic, obscene, threat, insult, identity_hate: These columns denote the presence of the eponymous elements in comment_text. If they’re absent they’re represented by zeros else they’re represented by a 1." }, { "code": null, "e": 4352, "s": 4142, "text": "These elements are independent in the sense, they’re not mutually exclusive for eg. A comment can be both toxic and insulting, or it’s not necessary that if a comment is toxic it couldn’t be obscene and so on." }, { "code": null, "e": 4685, "s": 4352, "text": "In general, there’s a lot less comments that have objectionable text; considering that we’ve got more than a hundred thousand comments, there’s less than tens of thousand objectionable categories (except toxic which is just a few more). This is good to know but it would be for the best if there were still fewer texts of this kind." }, { "code": null, "e": 4963, "s": 4685, "text": "Also, the text was annotated by humans to have these labels. This task of annotation is a huge task and a lot of human interpretation and bias will have come along with these annotations. It’s something that needs to be remembered and we’ll talk about this in closing thoughts." }, { "code": null, "e": 5238, "s": 4963, "text": "Text or sentences are sequences of individual units — words, sub-words or characters (depends on the language you speak). Any Machine Learning algorithm is not capable of handling anything other than numbers. So, we will first have to represent the data in terms of numbers." }, { "code": null, "e": 5500, "s": 5238, "text": "In any text related problems, first we create a vocabulary of words which basically is the total corpus of words which we will consider; any other word will be tagged with a special tag called unknown and put in that bucket. This process is called tokenization." }, { "code": null, "e": 5714, "s": 5500, "text": "Next, we map every word to a numerical token and create a dictionary of words that stores this mapping. So every prose/comment/text is now converted into a list of numbers. This process is called numericalization." }, { "code": null, "e": 6110, "s": 5714, "text": "Most certainly the comments will not be of equal length, because people are not restricted to comment in exactly a fixed number of words. But when creating batches of text to feed to our network, we need them all to be of the same length. Therefore we pad the sentences with a special token or truncate the sentence if it’s too big to constrict to a fixed length. This process is called padding." }, { "code": null, "e": 6393, "s": 6110, "text": "While doing all the above, there are some other operations like lowercasing all the text, dealing with punctuation as separate tokens, understanding capitalization in spite of lowercasing and so on. This is where the good people at fastai make all of these things super easy for us." }, { "code": null, "e": 6453, "s": 6393, "text": "xxpad: For padding, this is the standard token that’s used." }, { "code": null, "e": 6554, "s": 6453, "text": "xxunk: When an oov (out of vocabulary) word is encountered, this token is used to replace that word." }, { "code": null, "e": 6660, "s": 6554, "text": "xxbos: At the start of every sentence, this is a token which indicates the start/beginning of a sequence." }, { "code": null, "e": 6760, "s": 6660, "text": "xxmaj: If a word is capitalised or title cased, this token is prefixed to capture that information." }, { "code": null, "e": 6910, "s": 6760, "text": "xxrep: If a word is repeated, then in the tokenized representation, we will have that word followed by xxrep token followed by number of repetitions." }, { "code": null, "e": 7080, "s": 6910, "text": "There’s some more semantic information handled with more such tokens but all of this makes sure to capture precious information about the text and the meaning behind it." }, { "code": null, "e": 7900, "s": 7080, "text": "Once this preprocessing is done, we can then right of the bat build an LSTM model to classify the texts into the respective labels. Words are represented as n-dimensional vectors which are colloquially called encoding/embedding. There’s a construct for Embedding in PyTorch which helps lookup the vector representation for a word given it’s numerical token and that’s followed by other RNN layers and fully connected layers to build an architecture which can take sequence as an input and return a bunch of probabilities as the output. These vector embeddings could be randomly initialized or borrowed from commonly available GLoVE or Word2Vec embeddings which have been trained on a large corpus of text so that they have a good semantic word understanding about context in that particular language in a generic sense." }, { "code": null, "e": 8036, "s": 7900, "text": "However, there’s a trick which could improve the results if we perform it before building a classifier. That’s what we’ll look at next." }, { "code": null, "e": 8173, "s": 8036, "text": "fastai has suggested this tried and tested method of fine-tuning a Language Model before building any kind of classifier or application." }, { "code": null, "e": 8889, "s": 8173, "text": "In a nutshell, what they say is if you have a set of word embeddings which were trained on a huge corpus, they have a very generic understanding of the words that they learned from that corpus. However, when we talk about classification of hate speech and obnoxious comments and toxic stuff, there’s a specific negative vibe associated with these sentences and that semantic context is not yet present in our embeddings. Also, many words/terms specific to our application (it may be medicine or law or toxic speech) may not be encountered often in that huge corpus from which we obtained the word embeddings. Those should be there included and represented well in the embeddings that our classifier is going to use." }, { "code": null, "e": 9401, "s": 8889, "text": "So, before building a classifier we’ll finetune a Language Model which has been trained on wikipedia text corpus. We will bind the train and test dataset comments together and feed them to the language model. This is because we’re not doing classification but simply guessing the next word of a sequence given the current sequence; it’s called a self supervised task. With the embeddings learned this way, we’ll be able to build a better classifier because it has an idea of the concepts specific to our corpus." }, { "code": null, "e": 9479, "s": 9401, "text": "Let’s see how we can instantiate and fine-tune a language model in fastai v2." }, { "code": null, "e": 9763, "s": 9479, "text": "We append the train and test data and throw away the labels because we don’t need them in this self-supervised learning task. Next, we have to create a dataloader to tokenize these texts, do all the numericalization, padding and preprocessing before feeding it to the language model." }, { "code": null, "e": 10108, "s": 9763, "text": "That’s how simple it is in fastai, you just have to wrap all the arguments in a factory method and instantiate the TextDataLoaders class with it. This would have otherwise taken at least a hundred lines of codes with proper commenting and stuff but thanks to fastai, it’s short and sweet. We can have a look at a couple of entries from a batch." }, { "code": null, "e": 10436, "s": 10108, "text": "As we can see the output is just offsetting the given sequence by one word which is in alignment with what we want, i.e. given a sequence, predict next word of a sequence. Once we have this dataloader, we can create a language model learner which can tune the encodings as per our corpus instead of the previous corpus of text." }, { "code": null, "e": 10761, "s": 10436, "text": "After we have the language model learner, we can fit the learner over several epochs and save the encodings using the save_encoder method. We can see that the language model can on an average predict with a 38% accuracy what the next word would be given the current sequence of words which is pretty decent for this dataset." }, { "code": null, "e": 10916, "s": 10761, "text": "Once we have this ready, now we can move to the next step of creating a classifier to identify the probabilities for different labels of the comment_text." }, { "code": null, "e": 11257, "s": 10916, "text": "Before we move to creating a classification model, there’s some bit of preprocessing that we need to perform in order to build a proper dataloader. At the time of writing this post, there’s an issue with the DataBlocks API for text which avoids it from inferring all the dependent variables properly, hence we have to resort to this method." }, { "code": null, "e": 11689, "s": 11257, "text": "Basically, we will have to create another column in our dataframe which indicates the presence or absence of individual label using a fixed delimiter. So, if a comment is obscene and toxic, our new column will show obscene;toxic where delimiter is “;”. Also for the rows which don’t have any objectionable text, we will call them sober for now for the sake of giving a label (without any label, fastai won’t create the dataloader)." }, { "code": null, "e": 11880, "s": 11689, "text": "So we can see that there’s a column Labels added which contains a “;” delimited labels field where all our labels are denoted instead of the one-hot encoded format in which they’re provided." }, { "code": null, "e": 12505, "s": 11880, "text": "Now, we create the dataloaders using the datablocks API using “comment_text” field for x and “Labels” field for y respectively. If we would have mentioned the names of 6 columns as a list in the get_y field, it always picks up only two fields; due to this incorrect inference on the dataloader’s part, we have to go through the process of creating a separate label column for getting the dependent variable i.e. y’s values. Next, once we have the dataloader, we can build a classifier model using an LSTM architecture. Also we need to load the language model encodings/embeddings to the classifier once have instantiated it." }, { "code": null, "e": 12957, "s": 12505, "text": "Then we can start training the classifier. Initially, we will keep most of the network except the final FC layer frozen. This means that the back-propagation weight updates will only happen in the penultimate layer. Gradually we will unfreeze the previous layers until eventually we unfreeze the whole network. We do this because if we start with an unfrozen network, it will become difficult for the model to converge quickly to the optimal solution." }, { "code": null, "e": 13257, "s": 12957, "text": "It can be seen that the accuracy has reached a pretty solid 98% buy the end of the training. Since both train and valid loss both are decreasing, we can ideally train for more epochs and keep going but in the interest of time, we shall consider this a good enough score and start with the inference." }, { "code": null, "e": 13394, "s": 13257, "text": "Now that we have a trained model and we’ve stored it as a pkl, we can use it for making predictions on previously unseen i.e. test data." }, { "code": null, "e": 13743, "s": 13394, "text": "We shall first load the model that we just created and trained on the GPU. (Since we have hundreds of thousands of comment texts, CPU inference will take a lot of time). Next we will tokenize the test_df and then pass it through the same transforms that were used for train and validation data to create a dataloader of test comments for inference." }, { "code": null, "e": 13969, "s": 13743, "text": "Next we will use the get_preds method for inference and remember to pass the reorder method to False otherwise there’s a random shuffling of the texts that happens which will lead to incorrect order of predictions at the end." }, { "code": null, "e": 14312, "s": 13969, "text": "Finally, we shall format these predictions in the sample_submissions.csv style. So, after predictions, we get a set of 7 values one for each class and the probability of “sober” class is not needed since it was introduced by us as a placeholder. We remove that and get all the ids in proper order. This is how the final submission looks like." }, { "code": null, "e": 14486, "s": 14312, "text": "Finally we can submit these predictions using the kaggle API itself. No need to manually go to kaggle and submit the csv file. It could be done simply by this shell command." }, { "code": null, "e": 14678, "s": 14486, "text": "# Submit the predictions to kaggle!kaggle competitions submit -c jigsaw-toxic-comment-classification-challenge -f submissions_toxic.csv -m \"First submission for toxic comments classification\"" }, { "code": null, "e": 14811, "s": 14678, "text": "You can change the submissions file name and message as per your own convenience. The final submission score I got is as shown below" }, { "code": null, "e": 15408, "s": 14811, "text": "The top score on the leaderboard is around .9885 so our score is somewhat good with such few lines of code and little to no preprocessing. We could’ve removed stopwords, cleaned html tags, tackled punctuation, tuned language model even more or used GloVE or Word2Vec embeddings and went for a complex model like Transformer instead of a simple LSTM. Many people have approached this differently and used some of these techniques to get to such high scores. However, with little effort and using the already implemented fastai library we could get a decent enough score right in our first attempt." }, { "code": null, "e": 16117, "s": 15408, "text": "On a closing thought, it is worth mentioning that this dataset as annotated by humans may have been mislabelled or there could have been subjective differences between people which is also fair because it’s a very manual and monotonous job. We could aid that process by building a model, then using it to annotate and have humans supervise the annotations to make the process simpler or crowd-source this work to multiple volunteers to get a large corpus of labelled data in a small amount of time. In any case, NLP has become highly instrumental in tackling many language problems in the real world and hope after reading this post, you feel confident to start your journey in the world of text with fastai!" }, { "code": null, "e": 16274, "s": 16117, "text": "Toxic Comments dataset from KaggleHow to use Kaggle API for downloading dataGithub repo with all code for this postText classification notebook using fastai" }, { "code": null, "e": 16309, "s": 16274, "text": "Toxic Comments dataset from Kaggle" }, { "code": null, "e": 16352, "s": 16309, "text": "How to use Kaggle API for downloading data" }, { "code": null, "e": 16392, "s": 16352, "text": "Github repo with all code for this post" } ]
HTML | <link> sizes Attribute - GeeksforGeeks
19 Oct, 2020 The HTML link sizes Attribute is used to specify the sizes of the icon for visual media and it only works when rel=”icon”. It is a read-only Property. Syntax: <link sizes="HeightxWidth | any"> Attribute Values HeightxWidth It is used to specify the one or more sizes of a linked icon. The value of the height and the width are separated by an “x” or “X”.For Example:<link rel=”icon” href=”geeks.png” sizes=”16×16′′ type=”image/png”> (1 size)<link rel=”icon” href=”sudo.png” sizes=”16×16 32×32′′ type=”image/png”> (2 sizes) For Example: <link rel=”icon” href=”geeks.png” sizes=”16×16′′ type=”image/png”> (1 size)<link rel=”icon” href=”sudo.png” sizes=”16×16 32×32′′ type=”image/png”> (2 sizes) <link rel=”icon” href=”geeks.png” sizes=”16×16′′ type=”image/png”> (1 size) <link rel=”icon” href=”sudo.png” sizes=”16×16 32×32′′ type=”image/png”> (2 sizes) any: Specifies that the icon is scalable (like an SVG image).Examples: <link rel=”icon” href=”icon.svg” sizes=”any” type=”image/svg+xml”> (any size). Example: <!DOCTYPE html><html> <head> <link id="linkid" rel="stylesheet" type="text/css" href="styles.css" sizes="16*16"></head> <body style="text-align:center;"> <h1>GeeksForGeeks</h1> <h2>HTML <Link> sizes Attribute</h2></body> </html> Output: Supported Browsers: No browser supported by HTML <link> sizes Attribute. Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. arorakashish0911 HTML-Attributes HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. REST API (Introduction) Design a web page using HTML and CSS Angular File Upload Form validation using jQuery DOM (Document Object Model) Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux How to fetch data from an API in ReactJS ? Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 24894, "s": 24866, "text": "\n19 Oct, 2020" }, { "code": null, "e": 25045, "s": 24894, "text": "The HTML link sizes Attribute is used to specify the sizes of the icon for visual media and it only works when rel=”icon”. It is a read-only Property." }, { "code": null, "e": 25053, "s": 25045, "text": "Syntax:" }, { "code": null, "e": 25087, "s": 25053, "text": "<link sizes=\"HeightxWidth | any\">" }, { "code": null, "e": 25104, "s": 25087, "text": "Attribute Values" }, { "code": null, "e": 25417, "s": 25104, "text": "HeightxWidth It is used to specify the one or more sizes of a linked icon. The value of the height and the width are separated by an “x” or “X”.For Example:<link rel=”icon” href=”geeks.png” sizes=”16×16′′ type=”image/png”> (1 size)<link rel=”icon” href=”sudo.png” sizes=”16×16 32×32′′ type=”image/png”> (2 sizes)" }, { "code": null, "e": 25430, "s": 25417, "text": "For Example:" }, { "code": null, "e": 25587, "s": 25430, "text": "<link rel=”icon” href=”geeks.png” sizes=”16×16′′ type=”image/png”> (1 size)<link rel=”icon” href=”sudo.png” sizes=”16×16 32×32′′ type=”image/png”> (2 sizes)" }, { "code": null, "e": 25663, "s": 25587, "text": "<link rel=”icon” href=”geeks.png” sizes=”16×16′′ type=”image/png”> (1 size)" }, { "code": null, "e": 25745, "s": 25663, "text": "<link rel=”icon” href=”sudo.png” sizes=”16×16 32×32′′ type=”image/png”> (2 sizes)" }, { "code": null, "e": 25895, "s": 25745, "text": "any: Specifies that the icon is scalable (like an SVG image).Examples: <link rel=”icon” href=”icon.svg” sizes=”any” type=”image/svg+xml”> (any size)." }, { "code": null, "e": 25904, "s": 25895, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <link id=\"linkid\" rel=\"stylesheet\" type=\"text/css\" href=\"styles.css\" sizes=\"16*16\"></head> <body style=\"text-align:center;\"> <h1>GeeksForGeeks</h1> <h2>HTML <Link> sizes Attribute</h2></body> </html>", "e": 26183, "s": 25904, "text": null }, { "code": null, "e": 26191, "s": 26183, "text": "Output:" }, { "code": null, "e": 26264, "s": 26191, "text": "Supported Browsers: No browser supported by HTML <link> sizes Attribute." }, { "code": null, "e": 26401, "s": 26264, "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": 26418, "s": 26401, "text": "arorakashish0911" }, { "code": null, "e": 26434, "s": 26418, "text": "HTML-Attributes" }, { "code": null, "e": 26439, "s": 26434, "text": "HTML" }, { "code": null, "e": 26456, "s": 26439, "text": "Web Technologies" }, { "code": null, "e": 26461, "s": 26456, "text": "HTML" }, { "code": null, "e": 26559, "s": 26461, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26583, "s": 26559, "text": "REST API (Introduction)" }, { "code": null, "e": 26620, "s": 26583, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 26640, "s": 26620, "text": "Angular File Upload" }, { "code": null, "e": 26669, "s": 26640, "text": "Form validation using jQuery" }, { "code": null, "e": 26697, "s": 26669, "text": "DOM (Document Object Model)" }, { "code": null, "e": 26739, "s": 26697, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 26772, "s": 26739, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 26815, "s": 26772, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 26860, "s": 26815, "text": "Convert a string to an integer in JavaScript" } ]
Convert one array to another using adjacent swaps of elements - GeeksforGeeks
23 Aug, 2021 Given two arrays arr1[] and arr2[] of N integers. We can choose any two adjacent elements from array arr1[] and swap them if they are of opposite parity, the task is to check if it is possible to convert array arr1[] to array arr2[] by performing the given operation on arr1[]. Print “Yes” if it is possible to convert array arr1[] to arr2[] Else print “No”.Examples: Input: arr1[] = {5, 7, 8, 2, 10, 13}, arr2[] = {8, 5, 2, 7, 13, 10} Output: Yes Explanation: At first, swap 10 and 13 so arr1[] = [5, 7, 8, 2, 13, 10]. Now, swap 7 and 8 so arr1[] = [5, 8, 7, 2, 13, 10]. Now, swap 5 and 8 so arr1[] = [8, 5, 7, 2, 13, 10]. Now, swap 7 and 2 so arr1[] = [8, 5, 2, 7, 13, 10] = arr2[]. In each operation, we swap adjacent elements with different parity.Input: arr1[] = {0, 1, 13, 3, 4, 14, 6}, arr2[] = {0, 1, 14, 3, 4, 13, 6} Output: No Explanation: It is not possible to swap 13, 14 because they are not adjacent. Approach: The problem can be solved using Greedy Approach. Since we cannot swap any two even or odd numbers. So the relative position of both even and odd numbers in the arrays arr1[] and arr2[] must be exactly the same to make both the arrays equal with the given operation. Below are the steps: Create two arrays(say even[] and odd[]) insert all the even and odd numbers from arr1[] in even[] and odd[] respectively.Now check whether the even and odd numbers in arr2[] are in the same order as in even[] and odd[].If the above steps doesn’t gives any number from arr2[] which are not in the order of numbers in even[] and odd[] arrays respectively then, print “Yes” else print “No”. Create two arrays(say even[] and odd[]) insert all the even and odd numbers from arr1[] in even[] and odd[] respectively. Now check whether the even and odd numbers in arr2[] are in the same order as in even[] and odd[]. If the above steps doesn’t gives any number from arr2[] which are not in the order of numbers in even[] and odd[] arrays respectively then, print “Yes” else print “No”. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function which checks if it is// possible to convert arr1[] to// arr2[] by given operationsvoid convert(int a[], int b[], int n){ // even[] will store the even // elements of a[] // odd[] will store the odd // elements of a[] vector<int> even, odd; // Traverse a[] and insert the even // and odd element respectively for (int x = 0; x < n; x++) { if (a[x] % 2 == 0) even.push_back(a[x]); else odd.push_back(a[x]); } // ei points to the next // available even element // oi points to the next // available odd element int ei = 0, oi = 0; // poss will store whether the // given transformation // of a[] to b[] is possible bool poss = true; // Traverse b[] for (int x = 0; x < n; x++) { if (b[x] % 2 == 0) { // Check if both even // elements are equal if (ei < even.size() && b[x] == even[ei]) { ei++; } else { poss = false; break; } } else { // Check if both odd // elements are equal if (oi < odd.size() && b[x] == odd[oi]) { oi++; } else { poss = false; break; } } } // If poss is true, then we can // transform a[] to b[] if (poss) cout << "Yes" << endl; else cout << "No" << endl;} // Driver Codeint main(){ // Given arrays int arr1[] = { 0, 1, 13, 3, 4, 14, 6 }; int arr2[] = { 0, 1, 14, 3, 4, 13, 6 }; int N = sizeof(arr1) / sizeof(arr1[0]); // Function Call convert(arr1, arr2, N); return 0;} // Java program for the above approachimport java.util.*; class GFG{ // Function which checks if it is// possible to convert arr1[] to// arr2[] by given operationsstatic void convert(int a[], int b[], int n){ // even[] will store the even // elements of a[] // odd[] will store the odd // elements of a[] Vector<Integer> even = new Vector<Integer>(), odd = new Vector<Integer>(); // Traverse a[] and insert the even // and odd element respectively for(int x = 0; x < n; x++) { if (a[x] % 2 == 0) even.add(a[x]); else odd.add(a[x]); } // ei points to the next // available even element // oi points to the next // available odd element int ei = 0, oi = 0; // poss will store whether the // given transformation // of a[] to b[] is possible boolean poss = true; // Traverse b[] for(int x = 0; x < n; x++) { if (b[x] % 2 == 0) { // Check if both even // elements are equal if (ei < even.size() && b[x] == even.get(ei)) { ei++; } else { poss = false; break; } } else { // Check if both odd // elements are equal if (oi < odd.size() && b[x] == odd.get(oi)) { oi++; } else { poss = false; break; } } } // If poss is true, then we can // transform a[] to b[] if (poss) System.out.print("Yes" + "\n"); else System.out.print("No" + "\n");} // Driver Codepublic static void main(String[] args){ // Given arrays int arr1[] = { 0, 1, 13, 3, 4, 14, 6 }; int arr2[] = { 0, 1, 14, 3, 4, 13, 6 }; int N = arr1.length; // Function Call convert(arr1, arr2, N);}} // This code is contributed by gauravrajput1 # Python3 program for the above approach # Function which checks if it is# possible to convert arr1[] to# arr2[] by given operationsdef convert(a, b, n): # even[] will store the even # elements of a[] # odd[] will store the odd # elements of a[] even = [] odd = [] # Traverse a[] and insert the even # and odd element respectively for x in range(n): if (a[x] % 2 == 0): even.append(a[x]) else: odd.append(a[x]) # ei points to the next # available even element # oi points to the next # available odd element ei, oi = 0, 0 # poss will store whether the # given transformation # of a[] to b[] is possible poss = True # Traverse b[] for x in range(n): if (b[x] % 2 == 0): # Check if both even # elements are equal if (ei < len(even) and b[x] == even[ei]): ei += 1 else: poss = False break else: # Check if both odd # elements are equal if (oi < len(odd) and b[x] == odd[oi]): oi += 1 else: poss = False break # If poss is true, then we can # transform a[] to b[] if (poss): print("Yes") else: print("No") # Driver Codeif __name__ == "__main__": # Given arrays arr1 = [ 0, 1, 13, 3, 4, 14, 6 ] arr2 = [ 0, 1, 14, 3, 4, 13, 6 ] N = len(arr1) # Function call convert(arr1, arr2, N) # This code is contributed by chitranayal // C# program for the above approachusing System;using System.Collections.Generic; class GFG{ // Function which checks if it is// possible to convert arr1[] to// arr2[] by given operationsstatic void convert(int []a, int []b, int n){ // even[] will store the even // elements of []a // odd[] will store the odd // elements of []a List<int> even = new List<int>(), odd = new List<int>(); // Traverse []a and insert the even // and odd element respectively for(int x = 0; x < n; x++) { if (a[x] % 2 == 0) even.Add(a[x]); else odd.Add(a[x]); } // ei points to the next // available even element // oi points to the next // available odd element int ei = 0, oi = 0; // poss will store whether the // given transformation // of []a to []b is possible bool poss = true; // Traverse []b for(int x = 0; x < n; x++) { if (b[x] % 2 == 0) { // Check if both even // elements are equal if (ei < even.Count && b[x] == even[ei]) { ei++; } else { poss = false; break; } } else { // Check if both odd // elements are equal if (oi < odd.Count && b[x] == odd[oi]) { oi++; } else { poss = false; break; } } } // If poss is true, then we can // transform []a to []b if (poss) Console.Write("Yes" + "\n"); else Console.Write("No" + "\n");} // Driver Codepublic static void Main(String[] args){ // Given arrays int []arr1 = { 0, 1, 13, 3, 4, 14, 6 }; int []arr2 = { 0, 1, 14, 3, 4, 13, 6 }; int N = arr1.Length; // Function call convert(arr1, arr2, N);}} // This code is contributed by gauravrajput1 <script> // JavaScript program for the above approach // Function which checks if it is// possible to convert arr1[] to// arr2[] by given operationsfunction convert(a, b, n){ // even[] will store the even // elements of a[] // odd[] will store the odd // elements of a[] var even = [], odd = []; // Traverse a[] and insert the even // and odd element respectively for (var x = 0; x < n; x++) { if (a[x] % 2 == 0) even.push(a[x]); else odd.push(a[x]); } // ei points to the next // available even element // oi points to the next // available odd element var ei = 0, oi = 0; // poss will store whether the // given transformation // of a[] to b[] is possible var poss = true; // Traverse b[] for (var x = 0; x < n; x++) { if (b[x] % 2 == 0) { // Check if both even // elements are equal if (ei < even.length && b[x] == even[ei]) { ei++; } else { poss = false; break; } } else { // Check if both odd // elements are equal if (oi < odd.length && b[x] == odd[oi]) { oi++; } else { poss = false; break; } } } // If poss is true, then we can // transform a[] to b[] if (poss) document.write( "Yes" ); else document.write( "No" );} // Driver Code // Given arraysvar arr1 = [0, 1, 13, 3, 4, 14, 6 ];var arr2 = [0, 1, 14, 3, 4, 13, 6 ];var N = arr1.length; // Function Callconvert(arr1, arr2, N); </script> No Time Complexity: O(N), where N is the number of elements in the array. Auxiliary Space: O(N), where N is the number of elements in the array. GauravRajput1 ukasp rutvik_56 abhishek0719kadiyan Arrays Data Structures Greedy Algorithms Algorithms Arrays Data Structures Data Structures Arrays Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. DSA Sheet by Love Babbar How to Start Learning DSA? K means Clustering - Introduction Quadratic Probing in Hashing Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete Arrays in Java Arrays in C/C++ Maximum and minimum of an array using minimum number of comparisons Write a program to reverse an array or string Program for array rotation
[ { "code": null, "e": 26468, "s": 26440, "text": "\n23 Aug, 2021" }, { "code": null, "e": 26838, "s": 26468, "text": "Given two arrays arr1[] and arr2[] of N integers. We can choose any two adjacent elements from array arr1[] and swap them if they are of opposite parity, the task is to check if it is possible to convert array arr1[] to array arr2[] by performing the given operation on arr1[]. Print “Yes” if it is possible to convert array arr1[] to arr2[] Else print “No”.Examples: " }, { "code": null, "e": 27387, "s": 26838, "text": "Input: arr1[] = {5, 7, 8, 2, 10, 13}, arr2[] = {8, 5, 2, 7, 13, 10} Output: Yes Explanation: At first, swap 10 and 13 so arr1[] = [5, 7, 8, 2, 13, 10]. Now, swap 7 and 8 so arr1[] = [5, 8, 7, 2, 13, 10]. Now, swap 5 and 8 so arr1[] = [8, 5, 7, 2, 13, 10]. Now, swap 7 and 2 so arr1[] = [8, 5, 2, 7, 13, 10] = arr2[]. In each operation, we swap adjacent elements with different parity.Input: arr1[] = {0, 1, 13, 3, 4, 14, 6}, arr2[] = {0, 1, 14, 3, 4, 13, 6} Output: No Explanation: It is not possible to swap 13, 14 because they are not adjacent. " }, { "code": null, "e": 27685, "s": 27387, "text": "Approach: The problem can be solved using Greedy Approach. Since we cannot swap any two even or odd numbers. So the relative position of both even and odd numbers in the arrays arr1[] and arr2[] must be exactly the same to make both the arrays equal with the given operation. Below are the steps: " }, { "code": null, "e": 28073, "s": 27685, "text": "Create two arrays(say even[] and odd[]) insert all the even and odd numbers from arr1[] in even[] and odd[] respectively.Now check whether the even and odd numbers in arr2[] are in the same order as in even[] and odd[].If the above steps doesn’t gives any number from arr2[] which are not in the order of numbers in even[] and odd[] arrays respectively then, print “Yes” else print “No”." }, { "code": null, "e": 28195, "s": 28073, "text": "Create two arrays(say even[] and odd[]) insert all the even and odd numbers from arr1[] in even[] and odd[] respectively." }, { "code": null, "e": 28294, "s": 28195, "text": "Now check whether the even and odd numbers in arr2[] are in the same order as in even[] and odd[]." }, { "code": null, "e": 28463, "s": 28294, "text": "If the above steps doesn’t gives any number from arr2[] which are not in the order of numbers in even[] and odd[] arrays respectively then, print “Yes” else print “No”." }, { "code": null, "e": 28516, "s": 28463, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 28520, "s": 28516, "text": "C++" }, { "code": null, "e": 28525, "s": 28520, "text": "Java" }, { "code": null, "e": 28533, "s": 28525, "text": "Python3" }, { "code": null, "e": 28536, "s": 28533, "text": "C#" }, { "code": null, "e": 28547, "s": 28536, "text": "Javascript" }, { "code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function which checks if it is// possible to convert arr1[] to// arr2[] by given operationsvoid convert(int a[], int b[], int n){ // even[] will store the even // elements of a[] // odd[] will store the odd // elements of a[] vector<int> even, odd; // Traverse a[] and insert the even // and odd element respectively for (int x = 0; x < n; x++) { if (a[x] % 2 == 0) even.push_back(a[x]); else odd.push_back(a[x]); } // ei points to the next // available even element // oi points to the next // available odd element int ei = 0, oi = 0; // poss will store whether the // given transformation // of a[] to b[] is possible bool poss = true; // Traverse b[] for (int x = 0; x < n; x++) { if (b[x] % 2 == 0) { // Check if both even // elements are equal if (ei < even.size() && b[x] == even[ei]) { ei++; } else { poss = false; break; } } else { // Check if both odd // elements are equal if (oi < odd.size() && b[x] == odd[oi]) { oi++; } else { poss = false; break; } } } // If poss is true, then we can // transform a[] to b[] if (poss) cout << \"Yes\" << endl; else cout << \"No\" << endl;} // Driver Codeint main(){ // Given arrays int arr1[] = { 0, 1, 13, 3, 4, 14, 6 }; int arr2[] = { 0, 1, 14, 3, 4, 13, 6 }; int N = sizeof(arr1) / sizeof(arr1[0]); // Function Call convert(arr1, arr2, N); return 0;}", "e": 30375, "s": 28547, "text": null }, { "code": "// Java program for the above approachimport java.util.*; class GFG{ // Function which checks if it is// possible to convert arr1[] to// arr2[] by given operationsstatic void convert(int a[], int b[], int n){ // even[] will store the even // elements of a[] // odd[] will store the odd // elements of a[] Vector<Integer> even = new Vector<Integer>(), odd = new Vector<Integer>(); // Traverse a[] and insert the even // and odd element respectively for(int x = 0; x < n; x++) { if (a[x] % 2 == 0) even.add(a[x]); else odd.add(a[x]); } // ei points to the next // available even element // oi points to the next // available odd element int ei = 0, oi = 0; // poss will store whether the // given transformation // of a[] to b[] is possible boolean poss = true; // Traverse b[] for(int x = 0; x < n; x++) { if (b[x] % 2 == 0) { // Check if both even // elements are equal if (ei < even.size() && b[x] == even.get(ei)) { ei++; } else { poss = false; break; } } else { // Check if both odd // elements are equal if (oi < odd.size() && b[x] == odd.get(oi)) { oi++; } else { poss = false; break; } } } // If poss is true, then we can // transform a[] to b[] if (poss) System.out.print(\"Yes\" + \"\\n\"); else System.out.print(\"No\" + \"\\n\");} // Driver Codepublic static void main(String[] args){ // Given arrays int arr1[] = { 0, 1, 13, 3, 4, 14, 6 }; int arr2[] = { 0, 1, 14, 3, 4, 13, 6 }; int N = arr1.length; // Function Call convert(arr1, arr2, N);}} // This code is contributed by gauravrajput1", "e": 32385, "s": 30375, "text": null }, { "code": "# Python3 program for the above approach # Function which checks if it is# possible to convert arr1[] to# arr2[] by given operationsdef convert(a, b, n): # even[] will store the even # elements of a[] # odd[] will store the odd # elements of a[] even = [] odd = [] # Traverse a[] and insert the even # and odd element respectively for x in range(n): if (a[x] % 2 == 0): even.append(a[x]) else: odd.append(a[x]) # ei points to the next # available even element # oi points to the next # available odd element ei, oi = 0, 0 # poss will store whether the # given transformation # of a[] to b[] is possible poss = True # Traverse b[] for x in range(n): if (b[x] % 2 == 0): # Check if both even # elements are equal if (ei < len(even) and b[x] == even[ei]): ei += 1 else: poss = False break else: # Check if both odd # elements are equal if (oi < len(odd) and b[x] == odd[oi]): oi += 1 else: poss = False break # If poss is true, then we can # transform a[] to b[] if (poss): print(\"Yes\") else: print(\"No\") # Driver Codeif __name__ == \"__main__\": # Given arrays arr1 = [ 0, 1, 13, 3, 4, 14, 6 ] arr2 = [ 0, 1, 14, 3, 4, 13, 6 ] N = len(arr1) # Function call convert(arr1, arr2, N) # This code is contributed by chitranayal", "e": 34006, "s": 32385, "text": null }, { "code": "// C# program for the above approachusing System;using System.Collections.Generic; class GFG{ // Function which checks if it is// possible to convert arr1[] to// arr2[] by given operationsstatic void convert(int []a, int []b, int n){ // even[] will store the even // elements of []a // odd[] will store the odd // elements of []a List<int> even = new List<int>(), odd = new List<int>(); // Traverse []a and insert the even // and odd element respectively for(int x = 0; x < n; x++) { if (a[x] % 2 == 0) even.Add(a[x]); else odd.Add(a[x]); } // ei points to the next // available even element // oi points to the next // available odd element int ei = 0, oi = 0; // poss will store whether the // given transformation // of []a to []b is possible bool poss = true; // Traverse []b for(int x = 0; x < n; x++) { if (b[x] % 2 == 0) { // Check if both even // elements are equal if (ei < even.Count && b[x] == even[ei]) { ei++; } else { poss = false; break; } } else { // Check if both odd // elements are equal if (oi < odd.Count && b[x] == odd[oi]) { oi++; } else { poss = false; break; } } } // If poss is true, then we can // transform []a to []b if (poss) Console.Write(\"Yes\" + \"\\n\"); else Console.Write(\"No\" + \"\\n\");} // Driver Codepublic static void Main(String[] args){ // Given arrays int []arr1 = { 0, 1, 13, 3, 4, 14, 6 }; int []arr2 = { 0, 1, 14, 3, 4, 13, 6 }; int N = arr1.Length; // Function call convert(arr1, arr2, N);}} // This code is contributed by gauravrajput1", "e": 36038, "s": 34006, "text": null }, { "code": "<script> // JavaScript program for the above approach // Function which checks if it is// possible to convert arr1[] to// arr2[] by given operationsfunction convert(a, b, n){ // even[] will store the even // elements of a[] // odd[] will store the odd // elements of a[] var even = [], odd = []; // Traverse a[] and insert the even // and odd element respectively for (var x = 0; x < n; x++) { if (a[x] % 2 == 0) even.push(a[x]); else odd.push(a[x]); } // ei points to the next // available even element // oi points to the next // available odd element var ei = 0, oi = 0; // poss will store whether the // given transformation // of a[] to b[] is possible var poss = true; // Traverse b[] for (var x = 0; x < n; x++) { if (b[x] % 2 == 0) { // Check if both even // elements are equal if (ei < even.length && b[x] == even[ei]) { ei++; } else { poss = false; break; } } else { // Check if both odd // elements are equal if (oi < odd.length && b[x] == odd[oi]) { oi++; } else { poss = false; break; } } } // If poss is true, then we can // transform a[] to b[] if (poss) document.write( \"Yes\" ); else document.write( \"No\" );} // Driver Code // Given arraysvar arr1 = [0, 1, 13, 3, 4, 14, 6 ];var arr2 = [0, 1, 14, 3, 4, 13, 6 ];var N = arr1.length; // Function Callconvert(arr1, arr2, N); </script>", "e": 37757, "s": 36038, "text": null }, { "code": null, "e": 37760, "s": 37757, "text": "No" }, { "code": null, "e": 37905, "s": 37762, "text": "Time Complexity: O(N), where N is the number of elements in the array. Auxiliary Space: O(N), where N is the number of elements in the array. " }, { "code": null, "e": 37919, "s": 37905, "text": "GauravRajput1" }, { "code": null, "e": 37925, "s": 37919, "text": "ukasp" }, { "code": null, "e": 37935, "s": 37925, "text": "rutvik_56" }, { "code": null, "e": 37955, "s": 37935, "text": "abhishek0719kadiyan" }, { "code": null, "e": 37962, "s": 37955, "text": "Arrays" }, { "code": null, "e": 37978, "s": 37962, "text": "Data Structures" }, { "code": null, "e": 37996, "s": 37978, "text": "Greedy Algorithms" }, { "code": null, "e": 38007, "s": 37996, "text": "Algorithms" }, { "code": null, "e": 38014, "s": 38007, "text": "Arrays" }, { "code": null, "e": 38030, "s": 38014, "text": "Data Structures" }, { "code": null, "e": 38046, "s": 38030, "text": "Data Structures" }, { "code": null, "e": 38053, "s": 38046, "text": "Arrays" }, { "code": null, "e": 38064, "s": 38053, "text": "Algorithms" }, { "code": null, "e": 38162, "s": 38064, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 38187, "s": 38162, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 38214, "s": 38187, "text": "How to Start Learning DSA?" }, { "code": null, "e": 38248, "s": 38214, "text": "K means Clustering - Introduction" }, { "code": null, "e": 38277, "s": 38248, "text": "Quadratic Probing in Hashing" }, { "code": null, "e": 38344, "s": 38277, "text": "Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete" }, { "code": null, "e": 38359, "s": 38344, "text": "Arrays in Java" }, { "code": null, "e": 38375, "s": 38359, "text": "Arrays in C/C++" }, { "code": null, "e": 38443, "s": 38375, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 38489, "s": 38443, "text": "Write a program to reverse an array or string" } ]
Quick Sort(Lomuto Partition) Visualization using JavaScript - GeeksforGeeks
25 Feb, 2021 GUI(Graphical User Interface) helps in better in understanding than programs. In this article, we will visualize Quick Sort using JavaScript. We will see how the array is being partitioned using Lomuto Partition and then how we get the final sorted array. We will also visualize the time complexity of Quick Sort. Reference: Quick Sort Lomuto Partition Asynchronous Function in JavaScript Approach: First, we will generate a random array using Math.random() function. Different colors are used to indicate which element is compared, left partition, right partition and pivot element. Since the algorithm performs the operation very fast, the setTimeout() function has been used to slow down the process. New array can be generated by pressing the “Ctrl+R” key. The sorting is performed using QuickSort() function using lometo_partition() function Example: Before Sorting After Sorting Below is the program to visualize the Quick Sort algorithm. index.html <!DOCTYPE html><html lang="en"> <head> <link rel="stylesheet" href="style.css" /> </head> <body> <br /> <p class="header"> Quick Sort (Lometo Partition) </p> <div id="array"></div> <div id="count"></div> <br /> <h2 class="range" style="text-align: center"></h2> <script src="script.js"></script> </body></html> style.css * { margin: 0px; padding: 0px; box-sizing: border-box;}.header { font-size: 20px; text-align: center;}#array { background-color: white; height: 278px; width: 598px; margin: auto; position: relative; margin-top: 64px;}.block { width: 28px; background-color: #6b5b95; position: absolute; bottom: 0px; transition: 0.2s all ease;}.block_id { position: absolute; color: black; margin-top: -20px; width: 100%; text-align: center;}.block_id2 { position: absolute; color: black; margin-top: 22px; width: 100%; text-align: center;}.block2 { width: 28px; background-color: darkgray; position: absolute; transition: 0.2s all ease;}.block_id3 { position: absolute; color: black; margin-top: 1px; width: 100%; text-align: center;}#count { height: 20px; width: 598px; margin: auto;} script.js var container = document.getElementById("array"); // Function to generate the array of blocksfunction generatearray() { for (var i = 0; i < 20; i++) { // Return a value from 1 to 100 (both inclusive) var value = Math.ceil(Math.random() * 100); // Creating element div var array_ele = document.createElement("div"); // Adding class 'block' to div array_ele.classList.add("block"); // Adding style to div array_ele.style.height = `${value * 3}px`; array_ele.style.transform = `translate(${i * 30}px)`; // Creating label element for displaying // size of particular block var array_ele_label = document.createElement("label"); array_ele_label.classList.add("block_id"); array_ele_label.innerText = value; // Appending created elements to index.html array_ele.appendChild(array_ele_label); container.appendChild(array_ele); }} // Function to generate indexesvar count_container = document.getElementById("count");function generate_idx() { for (var i = 0; i < 20; i++) { // Creating element div var array_ele2 = document.createElement("div"); // Adding class 'block2' to div array_ele2.classList.add("block2"); // Adding style to div array_ele2.style.height = `${20}px`; array_ele2.style.transform = `translate(${i * 30}px)`; // Adding indexes var array_ele_label2 = document.createElement("label"); array_ele_label2.classList.add("block_id3"); array_ele_label2.innerText = i; // Appending created elements to index.html array_ele2.appendChild(array_ele_label2); count_container.appendChild(array_ele2); }} async function lometo_partition(l, r, delay = 700) { var blocks = document.querySelectorAll(".block"); // Storing the value of pivot element var pivot = Number(blocks[r].childNodes[0].innerHTML); var i = l - 1; blocks[r].style.backgroundColor = "red"; document. getElementsByClassName("range")[0].innerText = `[${l},${r}]`; for (var j = l; j <= r - 1; j++) { // To change background-color of the // blocks to be compared blocks[j].style.backgroundColor = "yellow"; // To wait for 700 milliseconds await new Promise((resolve) => setTimeout(() => { resolve(); }, delay) ); var value = Number(blocks[j].childNodes[0].innerHTML); // To compare value of two blocks if (value < pivot) { i++; var temp1 = blocks[i].style.height; var temp2 = blocks[i].childNodes[0].innerText; blocks[i].style.height = blocks[j].style.height; blocks[j].style.height = temp1; blocks[i].childNodes[0].innerText = blocks[j].childNodes[0].innerText; blocks[j].childNodes[0].innerText = temp2; blocks[i].style.backgroundColor = "orange"; if (i != j) blocks[j].style.backgroundColor = "pink"; //To wait for 700 milliseconds await new Promise((resolve) => setTimeout(() => { resolve(); }, delay) ); } else blocks[j].style.backgroundColor = "pink"; } // Swapping the ith with pivot element i++; var temp1 = blocks[i].style.height; var temp2 = blocks[i].childNodes[0].innerText; blocks[i].style.height = blocks[r].style.height; blocks[r].style.height = temp1; blocks[i].childNodes[0].innerText = blocks[r].childNodes[0].innerText; blocks[r].childNodes[0].innerText = temp2; blocks[r].style.backgroundColor = "pink"; blocks[i].style.backgroundColor = "green"; // To wait for 2100 milliseconds await new Promise((resolve) => setTimeout(() => { resolve(); }, delay * 3) ); document.getElementsByClassName("range")[0].innerText = ""; for (var k = 0; k < 20; k++) blocks[k].style.backgroundColor = "#6b5b95"; return i;} // Asynchronous QuickSort functionasync function QuickSort(l, r, delay = 100) { if (l < r) { // Storing the index of pivot element after partition var pivot_idx = await lometo_partition(l, r); // Recursively calling quicksort for left partition await QuickSort(l, pivot_idx - 1); // Recursively calling quicksort for right partition await QuickSort(pivot_idx + 1, r); }} // Calling generatearray functiongeneratearray(); // Calling generate_idx functiongenerate_idx(); // Calling QuickSort functionQuickSort(0, 19); Output: Quick Sort Technical Scripter 2020 JavaScript Sorting Technical Scripter Web Technologies Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Difference between var, let and const keywords in JavaScript Difference Between PUT and PATCH Request JavaScript | Promises How to get character array from string in JavaScript?
[ { "code": null, "e": 26621, "s": 26593, "text": "\n25 Feb, 2021" }, { "code": null, "e": 26936, "s": 26621, "text": "GUI(Graphical User Interface) helps in better in understanding than programs. In this article, we will visualize Quick Sort using JavaScript. We will see how the array is being partitioned using Lomuto Partition and then how we get the final sorted array. We will also visualize the time complexity of Quick Sort. " }, { "code": null, "e": 26947, "s": 26936, "text": "Reference:" }, { "code": null, "e": 26958, "s": 26947, "text": "Quick Sort" }, { "code": null, "e": 26975, "s": 26958, "text": "Lomuto Partition" }, { "code": null, "e": 27011, "s": 26975, "text": "Asynchronous Function in JavaScript" }, { "code": null, "e": 27021, "s": 27011, "text": "Approach:" }, { "code": null, "e": 27090, "s": 27021, "text": "First, we will generate a random array using Math.random() function." }, { "code": null, "e": 27206, "s": 27090, "text": "Different colors are used to indicate which element is compared, left partition, right partition and pivot element." }, { "code": null, "e": 27326, "s": 27206, "text": "Since the algorithm performs the operation very fast, the setTimeout() function has been used to slow down the process." }, { "code": null, "e": 27383, "s": 27326, "text": "New array can be generated by pressing the “Ctrl+R” key." }, { "code": null, "e": 27469, "s": 27383, "text": "The sorting is performed using QuickSort() function using lometo_partition() function" }, { "code": null, "e": 27478, "s": 27469, "text": "Example:" }, { "code": null, "e": 27493, "s": 27478, "text": "Before Sorting" }, { "code": null, "e": 27507, "s": 27493, "text": "After Sorting" }, { "code": null, "e": 27567, "s": 27507, "text": "Below is the program to visualize the Quick Sort algorithm." }, { "code": null, "e": 27578, "s": 27567, "text": "index.html" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <link rel=\"stylesheet\" href=\"style.css\" /> </head> <body> <br /> <p class=\"header\"> Quick Sort (Lometo Partition) </p> <div id=\"array\"></div> <div id=\"count\"></div> <br /> <h2 class=\"range\" style=\"text-align: center\"></h2> <script src=\"script.js\"></script> </body></html>", "e": 27941, "s": 27578, "text": null }, { "code": null, "e": 27951, "s": 27941, "text": "style.css" }, { "code": "* { margin: 0px; padding: 0px; box-sizing: border-box;}.header { font-size: 20px; text-align: center;}#array { background-color: white; height: 278px; width: 598px; margin: auto; position: relative; margin-top: 64px;}.block { width: 28px; background-color: #6b5b95; position: absolute; bottom: 0px; transition: 0.2s all ease;}.block_id { position: absolute; color: black; margin-top: -20px; width: 100%; text-align: center;}.block_id2 { position: absolute; color: black; margin-top: 22px; width: 100%; text-align: center;}.block2 { width: 28px; background-color: darkgray; position: absolute; transition: 0.2s all ease;}.block_id3 { position: absolute; color: black; margin-top: 1px; width: 100%; text-align: center;}#count { height: 20px; width: 598px; margin: auto;}", "e": 28758, "s": 27951, "text": null }, { "code": null, "e": 28768, "s": 28758, "text": "script.js" }, { "code": "var container = document.getElementById(\"array\"); // Function to generate the array of blocksfunction generatearray() { for (var i = 0; i < 20; i++) { // Return a value from 1 to 100 (both inclusive) var value = Math.ceil(Math.random() * 100); // Creating element div var array_ele = document.createElement(\"div\"); // Adding class 'block' to div array_ele.classList.add(\"block\"); // Adding style to div array_ele.style.height = `${value * 3}px`; array_ele.style.transform = `translate(${i * 30}px)`; // Creating label element for displaying // size of particular block var array_ele_label = document.createElement(\"label\"); array_ele_label.classList.add(\"block_id\"); array_ele_label.innerText = value; // Appending created elements to index.html array_ele.appendChild(array_ele_label); container.appendChild(array_ele); }} // Function to generate indexesvar count_container = document.getElementById(\"count\");function generate_idx() { for (var i = 0; i < 20; i++) { // Creating element div var array_ele2 = document.createElement(\"div\"); // Adding class 'block2' to div array_ele2.classList.add(\"block2\"); // Adding style to div array_ele2.style.height = `${20}px`; array_ele2.style.transform = `translate(${i * 30}px)`; // Adding indexes var array_ele_label2 = document.createElement(\"label\"); array_ele_label2.classList.add(\"block_id3\"); array_ele_label2.innerText = i; // Appending created elements to index.html array_ele2.appendChild(array_ele_label2); count_container.appendChild(array_ele2); }} async function lometo_partition(l, r, delay = 700) { var blocks = document.querySelectorAll(\".block\"); // Storing the value of pivot element var pivot = Number(blocks[r].childNodes[0].innerHTML); var i = l - 1; blocks[r].style.backgroundColor = \"red\"; document. getElementsByClassName(\"range\")[0].innerText = `[${l},${r}]`; for (var j = l; j <= r - 1; j++) { // To change background-color of the // blocks to be compared blocks[j].style.backgroundColor = \"yellow\"; // To wait for 700 milliseconds await new Promise((resolve) => setTimeout(() => { resolve(); }, delay) ); var value = Number(blocks[j].childNodes[0].innerHTML); // To compare value of two blocks if (value < pivot) { i++; var temp1 = blocks[i].style.height; var temp2 = blocks[i].childNodes[0].innerText; blocks[i].style.height = blocks[j].style.height; blocks[j].style.height = temp1; blocks[i].childNodes[0].innerText = blocks[j].childNodes[0].innerText; blocks[j].childNodes[0].innerText = temp2; blocks[i].style.backgroundColor = \"orange\"; if (i != j) blocks[j].style.backgroundColor = \"pink\"; //To wait for 700 milliseconds await new Promise((resolve) => setTimeout(() => { resolve(); }, delay) ); } else blocks[j].style.backgroundColor = \"pink\"; } // Swapping the ith with pivot element i++; var temp1 = blocks[i].style.height; var temp2 = blocks[i].childNodes[0].innerText; blocks[i].style.height = blocks[r].style.height; blocks[r].style.height = temp1; blocks[i].childNodes[0].innerText = blocks[r].childNodes[0].innerText; blocks[r].childNodes[0].innerText = temp2; blocks[r].style.backgroundColor = \"pink\"; blocks[i].style.backgroundColor = \"green\"; // To wait for 2100 milliseconds await new Promise((resolve) => setTimeout(() => { resolve(); }, delay * 3) ); document.getElementsByClassName(\"range\")[0].innerText = \"\"; for (var k = 0; k < 20; k++) blocks[k].style.backgroundColor = \"#6b5b95\"; return i;} // Asynchronous QuickSort functionasync function QuickSort(l, r, delay = 100) { if (l < r) { // Storing the index of pivot element after partition var pivot_idx = await lometo_partition(l, r); // Recursively calling quicksort for left partition await QuickSort(l, pivot_idx - 1); // Recursively calling quicksort for right partition await QuickSort(pivot_idx + 1, r); }} // Calling generatearray functiongeneratearray(); // Calling generate_idx functiongenerate_idx(); // Calling QuickSort functionQuickSort(0, 19);", "e": 33005, "s": 28768, "text": null }, { "code": null, "e": 33013, "s": 33005, "text": "Output:" }, { "code": null, "e": 33024, "s": 33013, "text": "Quick Sort" }, { "code": null, "e": 33048, "s": 33024, "text": "Technical Scripter 2020" }, { "code": null, "e": 33059, "s": 33048, "text": "JavaScript" }, { "code": null, "e": 33067, "s": 33059, "text": "Sorting" }, { "code": null, "e": 33086, "s": 33067, "text": "Technical Scripter" }, { "code": null, "e": 33103, "s": 33086, "text": "Web Technologies" }, { "code": null, "e": 33111, "s": 33103, "text": "Sorting" }, { "code": null, "e": 33209, "s": 33111, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33249, "s": 33209, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 33310, "s": 33249, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 33351, "s": 33310, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 33373, "s": 33351, "text": "JavaScript | Promises" } ]
Output of Java program | Set 27 - GeeksforGeeks
10 Aug, 2017 Ques1. What is the output of the following? import java.util.*; public class Test {public static void main(String[] args) { int[] x = new int[3]; System.out.println("x[0] is " + x[0]); }} Options :A. The program has a compile error because the size of the array wasn’t specified when declaring the array.B. The program has a runtime error because the array elements are not initialized.C. The program runs fine and displays x[0] is 0.D. The program has a runtime error because the array element x[0] is not defined. Answer : C Explanation : Program is syntactically correct, so no error. In java, if the array is not initialized at the time of declaration and creation then all the elements of the array are initialized to 0 by default. Ques2. What is the output of the following? import java.util.*; public class Test {public static void main(String[] args) { int[] x = { 120, 200, 016 }; for (int i = 0; i < x.length; i++) System.out.print(x[i] + " "); }} Options :A. 120 200 16B. 120 200 14C. 120 200 016D. 016 is a compile error. It should be written as 16. Answer : B Explanation : 016 is an octal number. The prefix 0 indicates that a number is in octal and in octal 16 is equal to 14. Ques3. What is the output of the following? import java.util.*; public class Test {public static void main(String args[]) { String s1 = "java"; String s2 = "java"; System.out.println(s1.equals(s2)); System.out.println(s1 == s2); }} Options :A. false trueB. false falseC. true falseD. true true Answer : D Explanation : Both == and equals() are same things and evaluate to true/false. Ques4. What is the output of the following? import java.util.*; public class Test {public static void main(String args[]) { String S1 = "S1 =" + "123" + "456"; String S2 = "S2 =" + (123 + 456); System.out.println(S1); System.out.println(S2); }} Options :A. S1=123456, S2=579B. S1=123456, S2=123456C. S1=579, S2=579D. None of This Answer : A Explanation : If a number is quoted in “” then it becomes a string, not a number any more. So in S1 it is concatenated as string and in S2 as numeric values. Ques5. What is the output of the following? import java.util.*;public class Test {public static void main(String[] args) { int[] x = { 1, 2, 3, 4 }; int[] y = x; x = new int[2]; for (int i = 0; i < x.length; i++) System.out.print(y[i] + " "); }} Options :A. 1 2 3 4B. 0 0 0 0C. 1 2D. 0 0 Answer : C Explanation : The length of x array is 2. So the loop will execute from i=0 to i=1. This article is contributed by Rishabh Jain. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Java-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 C++ programs | Set 34 (File Handling) Different ways to copy a string in C/C++ Output of Python Program | Set 1 Output of C++ programs | Set 50 Runtime Errors Output of C Programs | Set 2 C++ Programming Multiple Choice Questions Output of Java Program | Set 20 (Inheritance) Output of C++ Program | Set 1
[ { "code": null, "e": 25685, "s": 25657, "text": "\n10 Aug, 2017" }, { "code": null, "e": 25729, "s": 25685, "text": "Ques1. What is the output of the following?" }, { "code": "import java.util.*; public class Test {public static void main(String[] args) { int[] x = new int[3]; System.out.println(\"x[0] is \" + x[0]); }}", "e": 25894, "s": 25729, "text": null }, { "code": null, "e": 26222, "s": 25894, "text": "Options :A. The program has a compile error because the size of the array wasn’t specified when declaring the array.B. The program has a runtime error because the array elements are not initialized.C. The program runs fine and displays x[0] is 0.D. The program has a runtime error because the array element x[0] is not defined." }, { "code": null, "e": 26233, "s": 26222, "text": "Answer : C" }, { "code": null, "e": 26443, "s": 26233, "text": "Explanation : Program is syntactically correct, so no error. In java, if the array is not initialized at the time of declaration and creation then all the elements of the array are initialized to 0 by default." }, { "code": null, "e": 26487, "s": 26443, "text": "Ques2. What is the output of the following?" }, { "code": "import java.util.*; public class Test {public static void main(String[] args) { int[] x = { 120, 200, 016 }; for (int i = 0; i < x.length; i++) System.out.print(x[i] + \" \"); }}", "e": 26696, "s": 26487, "text": null }, { "code": null, "e": 26800, "s": 26696, "text": "Options :A. 120 200 16B. 120 200 14C. 120 200 016D. 016 is a compile error. It should be written as 16." }, { "code": null, "e": 26811, "s": 26800, "text": "Answer : B" }, { "code": null, "e": 26930, "s": 26811, "text": "Explanation : 016 is an octal number. The prefix 0 indicates that a number is in octal and in octal 16 is equal to 14." }, { "code": null, "e": 26974, "s": 26930, "text": "Ques3. What is the output of the following?" }, { "code": "import java.util.*; public class Test {public static void main(String args[]) { String s1 = \"java\"; String s2 = \"java\"; System.out.println(s1.equals(s2)); System.out.println(s1 == s2); }}", "e": 27197, "s": 26974, "text": null }, { "code": null, "e": 27259, "s": 27197, "text": "Options :A. false trueB. false falseC. true falseD. true true" }, { "code": null, "e": 27270, "s": 27259, "text": "Answer : D" }, { "code": null, "e": 27349, "s": 27270, "text": "Explanation : Both == and equals() are same things and evaluate to true/false." }, { "code": null, "e": 27393, "s": 27349, "text": "Ques4. What is the output of the following?" }, { "code": "import java.util.*; public class Test {public static void main(String args[]) { String S1 = \"S1 =\" + \"123\" + \"456\"; String S2 = \"S2 =\" + (123 + 456); System.out.println(S1); System.out.println(S2); }}", "e": 27629, "s": 27393, "text": null }, { "code": null, "e": 27714, "s": 27629, "text": "Options :A. S1=123456, S2=579B. S1=123456, S2=123456C. S1=579, S2=579D. None of This" }, { "code": null, "e": 27725, "s": 27714, "text": "Answer : A" }, { "code": null, "e": 27883, "s": 27725, "text": "Explanation : If a number is quoted in “” then it becomes a string, not a number any more. So in S1 it is concatenated as string and in S2 as numeric values." }, { "code": null, "e": 27927, "s": 27883, "text": "Ques5. What is the output of the following?" }, { "code": "import java.util.*;public class Test {public static void main(String[] args) { int[] x = { 1, 2, 3, 4 }; int[] y = x; x = new int[2]; for (int i = 0; i < x.length; i++) System.out.print(y[i] + \" \"); }}", "e": 28178, "s": 27927, "text": null }, { "code": null, "e": 28220, "s": 28178, "text": "Options :A. 1 2 3 4B. 0 0 0 0C. 1 2D. 0 0" }, { "code": null, "e": 28231, "s": 28220, "text": "Answer : C" }, { "code": null, "e": 28315, "s": 28231, "text": "Explanation : The length of x array is 2. So the loop will execute from i=0 to i=1." }, { "code": null, "e": 28615, "s": 28315, "text": "This article is contributed by Rishabh Jain. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 28740, "s": 28615, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 28752, "s": 28740, "text": "Java-Output" }, { "code": null, "e": 28767, "s": 28752, "text": "Program Output" }, { "code": null, "e": 28865, "s": 28767, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28910, "s": 28865, "text": "Output of Java program | Set 18 (Overriding)" }, { "code": null, "e": 28958, "s": 28910, "text": "Output of C++ programs | Set 34 (File Handling)" }, { "code": null, "e": 28999, "s": 28958, "text": "Different ways to copy a string in C/C++" }, { "code": null, "e": 29032, "s": 28999, "text": "Output of Python Program | Set 1" }, { "code": null, "e": 29064, "s": 29032, "text": "Output of C++ programs | Set 50" }, { "code": null, "e": 29079, "s": 29064, "text": "Runtime Errors" }, { "code": null, "e": 29108, "s": 29079, "text": "Output of C Programs | Set 2" }, { "code": null, "e": 29150, "s": 29108, "text": "C++ Programming Multiple Choice Questions" }, { "code": null, "e": 29196, "s": 29150, "text": "Output of Java Program | Set 20 (Inheritance)" } ]
How to solve “Submit is not a function” error in JavaScript ? - GeeksforGeeks
28 Jun, 2019 Ever tried to submit a form, by using a JavaScript? But when you tried to submit the form by using JavaScript, you might be getting a “Submit is not a function” error in the code. Well, don’t panic as of yet. This article is being dedicated to solving that problem of yours. So what are we waiting for? Let’s dig in. Example: You will get “Submit is not a function” error in this. <!DOCTYPE html><html> <head> <title>“Submit is not a function” error in JavaScript</title></head> <body> <body style="text-align:center;"> <h2 style="color:green">GeeksForGeeks</h2> <h2 style="color:purple"> “Submit is not a function” error </h2> <form action="product.php" method="get" name="frmProduct" id="frmProduct" enctype="multipart/form-data"> <input onclick="submitAction()" id="submit_value" type="button" name="submit_value" value="CLICK HERE"> </form> <script type="text/javascript"> function submitAction() { document.frmProduct.submit(); } </script> </body> <html> The Error:(The article continues after the image) There are 5 different types of solution to this problem. Solution 1:Simply rename your button’s name to btnSubmit or any other name. Your code will miraculously work. This is because you have already named the submit button or any other element in the code as submit. When the button is named as submit, it is going to override the submit() function on this code. btnSubmit Example: <!DOCTYPE html><html> <head> <title> “Submit is not a function” error in JavaScript </title></head> <body style="text-align:center;"> <h2 style="color:green">GeeksForGeeks</h2> <h2 style="color:purple"> “Submit is not a function” error </h2> <form action="product.php" method="get" name="frmProduct" id="frmProduct" enctype="multipart/form-data"> <input onclick="submitAction()" id="submit_value" type="button" name="submit_value" value="CLICK HERE"> </form> <script type="text/javascript"> function submitAction() { document.frmProduct.btnSubmit(); } </script></body><html> Solution 2:Simply let the button handle and decide which object of the form to be used. onclick="return SubmitForm(this.form)" Example: <!DOCTYPE html><html> <head> <title> “Submit is not a function” error in JavaScript </title></head> <body> <body style="text-align:center;"> <h2 style="color:green"> GeeksForGeeks </h2> <h2 style="color:purple"> “Submit is not a function” error </h2> <form action="product.php" method="get" name="frmProduct" id="frmProduct" enctype="multipart/form-data"> <input onclick="return SubmitForm(this.form)" id="submit_value" type="button" name="submit_value" value="CLICK HERE"> </form> <script type="text/javascript"> function submitAction() { document.frmProduct.submit(); } </script> </body> <html> Solution 3:If there is no name=”submit” or id=”submit” in the form, make sure to remove or edit it. Also by making sure that there will no other form that is having the same name. This will give an error. Solution 4:If there are no changes in the output (still getting an error) by implementing the Solution 3 i.e. having a chance to change name=”submit” or id=”submit”, you could also prevent the error by making changes in the JavaScript. Example: <!DOCTYPE html><html> <head> <title> “Submit is not a function” error in JavaScript </title></head> <body style="text-align:center;"> <h2 style="color:green"> GeeksForGeeks </h2> <h2 style="color:purple"> “Submit is not a function” error </h2> <form action="product.php" method="get" name="frmProduct" id="frmProduct" enctype="multipart/form-data"> <input onclick="submitAction()" id="submit_value" type="button" name="submit_value" value="CLICK HERE"> </form> <script type="text/javascript"> function submitForm(form) { var submitFormFunction = Object.getPrototypeOf(form).submit; submitFormFunction.call(form); } </script></body><html> Solution 5:By making some changes in the JavaScript. Example: <!DOCTYPE html><html> <head> <title> “Submit is not a function” error in JavaScript </title></head> <body style="text-align:center;"> <h2 style="color:green"> GeeksForGeeks </h2> <h2 style="color:purple"> “Submit is not a function” error </h2> <form action="product.php" method="get" name="frmProduct" id="frmProduct" enctype="multipart/form-data"> <input onclick="submitAction()" id="submit_value" type="button" name="submit_value" value="CLICK HERE"> </form> <script type="text/javascript"> function submitForm(form) { var enviar = document.getElementById("enviar"); enviar.type = "submit"; } </script></body><html> Output:When we lead the code The error message After using the solutions:“Submit is not a function” error JavaScript-Misc Picked JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React Difference Between PUT and PATCH Request 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": 26775, "s": 26747, "text": "\n28 Jun, 2019" }, { "code": null, "e": 27050, "s": 26775, "text": "Ever tried to submit a form, by using a JavaScript? But when you tried to submit the form by using JavaScript, you might be getting a “Submit is not a function” error in the code. Well, don’t panic as of yet. This article is being dedicated to solving that problem of yours." }, { "code": null, "e": 27092, "s": 27050, "text": "So what are we waiting for? Let’s dig in." }, { "code": null, "e": 27156, "s": 27092, "text": "Example: You will get “Submit is not a function” error in this." }, { "code": "<!DOCTYPE html><html> <head> <title>“Submit is not a function” error in JavaScript</title></head> <body> <body style=\"text-align:center;\"> <h2 style=\"color:green\">GeeksForGeeks</h2> <h2 style=\"color:purple\"> “Submit is not a function” error </h2> <form action=\"product.php\" method=\"get\" name=\"frmProduct\" id=\"frmProduct\" enctype=\"multipart/form-data\"> <input onclick=\"submitAction()\" id=\"submit_value\" type=\"button\" name=\"submit_value\" value=\"CLICK HERE\"> </form> <script type=\"text/javascript\"> function submitAction() { document.frmProduct.submit(); } </script> </body> <html>", "e": 28001, "s": 27156, "text": null }, { "code": null, "e": 28051, "s": 28001, "text": "The Error:(The article continues after the image)" }, { "code": null, "e": 28108, "s": 28051, "text": "There are 5 different types of solution to this problem." }, { "code": null, "e": 28415, "s": 28108, "text": "Solution 1:Simply rename your button’s name to btnSubmit or any other name. Your code will miraculously work. This is because you have already named the submit button or any other element in the code as submit. When the button is named as submit, it is going to override the submit() function on this code." }, { "code": null, "e": 28425, "s": 28415, "text": "btnSubmit" }, { "code": null, "e": 28434, "s": 28425, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <title> “Submit is not a function” error in JavaScript </title></head> <body style=\"text-align:center;\"> <h2 style=\"color:green\">GeeksForGeeks</h2> <h2 style=\"color:purple\"> “Submit is not a function” error </h2> <form action=\"product.php\" method=\"get\" name=\"frmProduct\" id=\"frmProduct\" enctype=\"multipart/form-data\"> <input onclick=\"submitAction()\" id=\"submit_value\" type=\"button\" name=\"submit_value\" value=\"CLICK HERE\"> </form> <script type=\"text/javascript\"> function submitAction() { document.frmProduct.btnSubmit(); } </script></body><html>", "e": 29182, "s": 28434, "text": null }, { "code": null, "e": 29270, "s": 29182, "text": "Solution 2:Simply let the button handle and decide which object of the form to be used." }, { "code": null, "e": 29309, "s": 29270, "text": "onclick=\"return SubmitForm(this.form)\"" }, { "code": null, "e": 29318, "s": 29309, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <title> “Submit is not a function” error in JavaScript </title></head> <body> <body style=\"text-align:center;\"> <h2 style=\"color:green\"> GeeksForGeeks </h2> <h2 style=\"color:purple\"> “Submit is not a function” error </h2> <form action=\"product.php\" method=\"get\" name=\"frmProduct\" id=\"frmProduct\" enctype=\"multipart/form-data\"> <input onclick=\"return SubmitForm(this.form)\" id=\"submit_value\" type=\"button\" name=\"submit_value\" value=\"CLICK HERE\"> </form> <script type=\"text/javascript\"> function submitAction() { document.frmProduct.submit(); } </script> </body> <html>", "e": 30189, "s": 29318, "text": null }, { "code": null, "e": 30394, "s": 30189, "text": "Solution 3:If there is no name=”submit” or id=”submit” in the form, make sure to remove or edit it. Also by making sure that there will no other form that is having the same name. This will give an error." }, { "code": null, "e": 30630, "s": 30394, "text": "Solution 4:If there are no changes in the output (still getting an error) by implementing the Solution 3 i.e. having a chance to change name=”submit” or id=”submit”, you could also prevent the error by making changes in the JavaScript." }, { "code": null, "e": 30639, "s": 30630, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <title> “Submit is not a function” error in JavaScript </title></head> <body style=\"text-align:center;\"> <h2 style=\"color:green\"> GeeksForGeeks </h2> <h2 style=\"color:purple\"> “Submit is not a function” error </h2> <form action=\"product.php\" method=\"get\" name=\"frmProduct\" id=\"frmProduct\" enctype=\"multipart/form-data\"> <input onclick=\"submitAction()\" id=\"submit_value\" type=\"button\" name=\"submit_value\" value=\"CLICK HERE\"> </form> <script type=\"text/javascript\"> function submitForm(form) { var submitFormFunction = Object.getPrototypeOf(form).submit; submitFormFunction.call(form); } </script></body><html>", "e": 31487, "s": 30639, "text": null }, { "code": null, "e": 31540, "s": 31487, "text": "Solution 5:By making some changes in the JavaScript." }, { "code": null, "e": 31549, "s": 31540, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <title> “Submit is not a function” error in JavaScript </title></head> <body style=\"text-align:center;\"> <h2 style=\"color:green\"> GeeksForGeeks </h2> <h2 style=\"color:purple\"> “Submit is not a function” error </h2> <form action=\"product.php\" method=\"get\" name=\"frmProduct\" id=\"frmProduct\" enctype=\"multipart/form-data\"> <input onclick=\"submitAction()\" id=\"submit_value\" type=\"button\" name=\"submit_value\" value=\"CLICK HERE\"> </form> <script type=\"text/javascript\"> function submitForm(form) { var enviar = document.getElementById(\"enviar\"); enviar.type = \"submit\"; } </script></body><html>", "e": 32379, "s": 31549, "text": null }, { "code": null, "e": 32408, "s": 32379, "text": "Output:When we lead the code" }, { "code": null, "e": 32426, "s": 32408, "text": "The error message" }, { "code": null, "e": 32485, "s": 32426, "text": "After using the solutions:“Submit is not a function” error" }, { "code": null, "e": 32501, "s": 32485, "text": "JavaScript-Misc" }, { "code": null, "e": 32508, "s": 32501, "text": "Picked" }, { "code": null, "e": 32519, "s": 32508, "text": "JavaScript" }, { "code": null, "e": 32536, "s": 32519, "text": "Web Technologies" }, { "code": null, "e": 32634, "s": 32536, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32674, "s": 32634, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 32719, "s": 32674, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 32780, "s": 32719, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 32852, "s": 32780, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 32893, "s": 32852, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 32933, "s": 32893, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 32966, "s": 32933, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 33011, "s": 32966, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 33054, "s": 33011, "text": "How to fetch data from an API in ReactJS ?" } ]
HTTP headers | X-XSS-Protection - GeeksforGeeks
10 Jan, 2022 HTTP headers are used to pass additional information with HTTP response or HTTP requests. The X-XSS-Protection in HTTP header is a feature that stops a page from loading when it detects XSS attacks. This feature is becoming unnecessary with increasing content-security-policy of sites. XSS attacks: The XSS stands for Cross-site Scripting. In this attack, the procedure is to bypass the Same-origin policy into vulnerable web applications. When the HTML code generated dynamically and the user input is not sanitized only then the attacker can use this attack. In this attack, an attacker can insert his own HTML code into the webpage which will be not detected by the browsers. For his own HTML code attacker can easily gain access to the database and the cookies. To stop this kind of attacks X-XSS Protection was used in previous days. Syntax: X-XSS-Protection: directive Type of XSS Attack: Cross site scripting attacks are broadly classified into two categories. Server XSS: In this type of attack hacker attaches untrusted data with the HTML response. In this case, vulnerability is present at the server end and the browser just runs the script present in the response. Client XSS: In this type of XSS attack unsafe javascript is used to update the DOM data. If we add javascript code in DOM with a javascript call, such a javascript call is called an unsafe javascript call. Directives: In this headers filed there are four directives: 0: It disables the X-XSS-Protection. 1: It is the by default directive and enables the X-XSS-Protection. 1; mode=block: It enables the X-XSS-Protection. If the browser detects an attack, it will not render the page. 1; report=<reporting-URI>: It enables the X-XSS-Protection. If the Cross-site Scripting attack detected then the page will be sanitizes and reported by report-uri directive. Example 1: Block pages from loading when they detect reflected Cross-site Scripting attacks: HTML // It enable the protectionX-XSS-Protection: 1; mode=block // It disable the protectionX-XSS-Protection: 0 Example 2: This will work on an apache server. HTML <IfModule mod_headers.c> Header set X-XSS-Protection "1; mode=block" </IfModule> Example 3: This will work on Nginx server. html add_header "X-XSS-Protection" "1; mode=block"; Supported Browsers: The browsers supported by HTTP headers X-XSS-Protection are listed below: Google Chrome Internet Explorer Safari Opera rkbhola5 HTTP-headers Picked Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React How to apply style to parent if it has child with CSS? Difference Between PUT and PATCH Request How to execute PHP code using command line ? REST API (Introduction) How to redirect to another page in ReactJS ?
[ { "code": null, "e": 26169, "s": 26141, "text": "\n10 Jan, 2022" }, { "code": null, "e": 26455, "s": 26169, "text": "HTTP headers are used to pass additional information with HTTP response or HTTP requests. The X-XSS-Protection in HTTP header is a feature that stops a page from loading when it detects XSS attacks. This feature is becoming unnecessary with increasing content-security-policy of sites." }, { "code": null, "e": 27008, "s": 26455, "text": "XSS attacks: The XSS stands for Cross-site Scripting. In this attack, the procedure is to bypass the Same-origin policy into vulnerable web applications. When the HTML code generated dynamically and the user input is not sanitized only then the attacker can use this attack. In this attack, an attacker can insert his own HTML code into the webpage which will be not detected by the browsers. For his own HTML code attacker can easily gain access to the database and the cookies. To stop this kind of attacks X-XSS Protection was used in previous days." }, { "code": null, "e": 27017, "s": 27008, "text": "Syntax: " }, { "code": null, "e": 27045, "s": 27017, "text": "X-XSS-Protection: directive" }, { "code": null, "e": 27140, "s": 27045, "text": "Type of XSS Attack: Cross site scripting attacks are broadly classified into two categories. " }, { "code": null, "e": 27349, "s": 27140, "text": "Server XSS: In this type of attack hacker attaches untrusted data with the HTML response. In this case, vulnerability is present at the server end and the browser just runs the script present in the response." }, { "code": null, "e": 27555, "s": 27349, "text": "Client XSS: In this type of XSS attack unsafe javascript is used to update the DOM data. If we add javascript code in DOM with a javascript call, such a javascript call is called an unsafe javascript call." }, { "code": null, "e": 27618, "s": 27555, "text": "Directives: In this headers filed there are four directives: " }, { "code": null, "e": 27655, "s": 27618, "text": "0: It disables the X-XSS-Protection." }, { "code": null, "e": 27723, "s": 27655, "text": "1: It is the by default directive and enables the X-XSS-Protection." }, { "code": null, "e": 27834, "s": 27723, "text": "1; mode=block: It enables the X-XSS-Protection. If the browser detects an attack, it will not render the page." }, { "code": null, "e": 28008, "s": 27834, "text": "1; report=<reporting-URI>: It enables the X-XSS-Protection. If the Cross-site Scripting attack detected then the page will be sanitizes and reported by report-uri directive." }, { "code": null, "e": 28103, "s": 28008, "text": "Example 1: Block pages from loading when they detect reflected Cross-site Scripting attacks: " }, { "code": null, "e": 28108, "s": 28103, "text": "HTML" }, { "code": "// It enable the protectionX-XSS-Protection: 1; mode=block // It disable the protectionX-XSS-Protection: 0", "e": 28217, "s": 28108, "text": null }, { "code": null, "e": 28265, "s": 28217, "text": "Example 2: This will work on an apache server. " }, { "code": null, "e": 28270, "s": 28265, "text": "HTML" }, { "code": "<IfModule mod_headers.c> Header set X-XSS-Protection \"1; mode=block\" </IfModule>", "e": 28353, "s": 28270, "text": null }, { "code": null, "e": 28397, "s": 28353, "text": "Example 3: This will work on Nginx server. " }, { "code": null, "e": 28402, "s": 28397, "text": "html" }, { "code": "add_header \"X-XSS-Protection\" \"1; mode=block\";", "e": 28449, "s": 28402, "text": null }, { "code": null, "e": 28544, "s": 28449, "text": "Supported Browsers: The browsers supported by HTTP headers X-XSS-Protection are listed below: " }, { "code": null, "e": 28558, "s": 28544, "text": "Google Chrome" }, { "code": null, "e": 28576, "s": 28558, "text": "Internet Explorer" }, { "code": null, "e": 28583, "s": 28576, "text": "Safari" }, { "code": null, "e": 28589, "s": 28583, "text": "Opera" }, { "code": null, "e": 28600, "s": 28591, "text": "rkbhola5" }, { "code": null, "e": 28613, "s": 28600, "text": "HTTP-headers" }, { "code": null, "e": 28620, "s": 28613, "text": "Picked" }, { "code": null, "e": 28637, "s": 28620, "text": "Web Technologies" }, { "code": null, "e": 28735, "s": 28637, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28775, "s": 28735, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28820, "s": 28775, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 28863, "s": 28820, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 28924, "s": 28863, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 28996, "s": 28924, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 29051, "s": 28996, "text": "How to apply style to parent if it has child with CSS?" }, { "code": null, "e": 29092, "s": 29051, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 29137, "s": 29092, "text": "How to execute PHP code using command line ?" }, { "code": null, "e": 29161, "s": 29137, "text": "REST API (Introduction)" } ]
Time complexity of insertion sort when there are O(n) inversions? - GeeksforGeeks
20 Dec, 2016 What is an inversion?Given an array arr[], a pair arr[i] and arr[j] forms an inversion if arr[i] < arr[j] and i > j. For example, the array {1, 3, 2, 5} has one inversion (3, 2) and array {5, 4, 3} has inversions (5, 4), (5, 3) and (4, 3). We have discussed a merge sort based algorithm to count inversions What is the time complexity of Insertion Sort when there are O(n) inversions?Consider the following function of insertion sort. /* Function to sort an array using insertion sort*/void insertionSort(int arr[], int n){ int i, key, j; for (i = 1; i < n; i++) { key = arr[i]; j = i-1; /* Move elements of arr[0..i-1], that are greater than key, to one position ahead of their current position */ while (j >= 0 && arr[j] > key) { arr[j+1] = arr[j]; j = j-1; } arr[j+1] = key; }} If we take a closer look at the insertion sort code, we can notice that every iteration of while loop reduces one inversion. The while loop executes only if i > j and arr[i] < arr[j]. Therefore total number of while loop iterations (For all values of i) is same as number of inversions. Therefore overall time complexity of the insertion sort is O(n + f(n)) where f(n) is inversion count. If the inversion count is O(n), then the time complexity of insertion sort is O(n). In worst case, there can be n*(n-1)/2 inversions. The worst case occurs when the array is sorted in reverse order. So the worst case time complexity of insertion sort is O(n2). Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above Insertion Sort inversion Sorting Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. std::sort() in C++ STL Time Complexities of all Sorting Algorithms Radix Sort Merge two sorted arrays Chocolate Distribution Problem Count Inversions in an array | Set 1 (Using Merge Sort) Sort an array of 0s, 1s and 2s k largest(or smallest) elements in an array Python Program for Bubble Sort sort() in Python
[ { "code": null, "e": 24983, "s": 24955, "text": "\n20 Dec, 2016" }, { "code": null, "e": 25290, "s": 24983, "text": "What is an inversion?Given an array arr[], a pair arr[i] and arr[j] forms an inversion if arr[i] < arr[j] and i > j. For example, the array {1, 3, 2, 5} has one inversion (3, 2) and array {5, 4, 3} has inversions (5, 4), (5, 3) and (4, 3). We have discussed a merge sort based algorithm to count inversions" }, { "code": null, "e": 25418, "s": 25290, "text": "What is the time complexity of Insertion Sort when there are O(n) inversions?Consider the following function of insertion sort." }, { "code": "/* Function to sort an array using insertion sort*/void insertionSort(int arr[], int n){ int i, key, j; for (i = 1; i < n; i++) { key = arr[i]; j = i-1; /* Move elements of arr[0..i-1], that are greater than key, to one position ahead of their current position */ while (j >= 0 && arr[j] > key) { arr[j+1] = arr[j]; j = j-1; } arr[j+1] = key; }}", "e": 25855, "s": 25418, "text": null }, { "code": null, "e": 26505, "s": 25855, "text": "If we take a closer look at the insertion sort code, we can notice that every iteration of while loop reduces one inversion. The while loop executes only if i > j and arr[i] < arr[j]. Therefore total number of while loop iterations (For all values of i) is same as number of inversions. Therefore overall time complexity of the insertion sort is O(n + f(n)) where f(n) is inversion count. If the inversion count is O(n), then the time complexity of insertion sort is O(n).\nIn worst case, there can be n*(n-1)/2 inversions. The worst case occurs when the array is sorted in reverse order. So the worst case time complexity of insertion sort is O(n2)." }, { "code": null, "e": 26629, "s": 26505, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above" }, { "code": null, "e": 26644, "s": 26629, "text": "Insertion Sort" }, { "code": null, "e": 26654, "s": 26644, "text": "inversion" }, { "code": null, "e": 26662, "s": 26654, "text": "Sorting" }, { "code": null, "e": 26670, "s": 26662, "text": "Sorting" }, { "code": null, "e": 26768, "s": 26670, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26791, "s": 26768, "text": "std::sort() in C++ STL" }, { "code": null, "e": 26835, "s": 26791, "text": "Time Complexities of all Sorting Algorithms" }, { "code": null, "e": 26846, "s": 26835, "text": "Radix Sort" }, { "code": null, "e": 26870, "s": 26846, "text": "Merge two sorted arrays" }, { "code": null, "e": 26901, "s": 26870, "text": "Chocolate Distribution Problem" }, { "code": null, "e": 26957, "s": 26901, "text": "Count Inversions in an array | Set 1 (Using Merge Sort)" }, { "code": null, "e": 26988, "s": 26957, "text": "Sort an array of 0s, 1s and 2s" }, { "code": null, "e": 27032, "s": 26988, "text": "k largest(or smallest) elements in an array" }, { "code": null, "e": 27063, "s": 27032, "text": "Python Program for Bubble Sort" } ]
GATE | GATE-CS-2016 (Set 2) | Question 22 - GeeksforGeeks
12 Aug, 2021 The value printed by the following program is void f(int* p, int m){ m = m + 5; *p = *p + m; return;}void main(){ int i=5, j=10; f(&i, j); printf("%d", i+j);} (A) 10(B) 20(C) 30(D) 40Answer: (C)Explanation: #include"stdio.h" void f(int* p, int m) { m = m + 5; *p = *p + m; return; } int main() { int i=5, j=10; f(&i, j); printf("%d", i+j); } For i, address is passed. For j, value is passed. So in function f, p will contain address of i and m will contain value 10. Ist statement of f() will change m to 15. Then 15 will be added to value at address p. It will make i = 5+15 = 20. j will remain 10. print statement will print 20+10 = 30. So answer is (C). YouTubeGeeksforGeeks GATE Computer Science16.4K subscribersGATE PYQs 2016 with Shubham Agrawal | GeeksforGeeks GATE CSEWatch 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:0046:25 / 1:07:54•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=Key2RKhzRGY" 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 2007 | Question 25 GATE | GATE-CS-2001 | Question 39 GATE | GATE-CS-2000 | Question 41 GATE | GATE-CS-2005 | Question 6 GATE | GATE MOCK 2017 | Question 21 GATE | GATE MOCK 2017 | Question 24 GATE | GATE-CS-2006 | Question 47 GATE | Gate IT 2008 | Question 43 GATE | GATE-CS-2009 | Question 38 GATE | GATE-CS-2003 | Question 90
[ { "code": null, "e": 25879, "s": 25851, "text": "\n12 Aug, 2021" }, { "code": null, "e": 25925, "s": 25879, "text": "The value printed by the following program is" }, { "code": "void f(int* p, int m){ m = m + 5; *p = *p + m; return;}void main(){ int i=5, j=10; f(&i, j); printf(\"%d\", i+j);}", "e": 26056, "s": 25925, "text": null }, { "code": null, "e": 26104, "s": 26056, "text": "(A) 10(B) 20(C) 30(D) 40Answer: (C)Explanation:" }, { "code": null, "e": 26265, "s": 26104, "text": "#include\"stdio.h\"\n\nvoid f(int* p, int m)\n{\n m = m + 5;\n *p = *p + m;\n return;\n}\nint main()\n{\n int i=5, j=10;\n f(&i, j);\n printf(\"%d\", i+j);\n}\n" }, { "code": null, "e": 26580, "s": 26265, "text": "For i, address is passed. For j, value is passed. So in function f, p will contain address of i and m will contain value 10. Ist statement of f() will change m to 15. Then 15 will be added to value at address p. It will make i = 5+15 = 20. j will remain 10. print statement will print 20+10 = 30. So answer is (C)." }, { "code": null, "e": 27471, "s": 26580, "text": "YouTubeGeeksforGeeks GATE Computer Science16.4K subscribersGATE PYQs 2016 with Shubham Agrawal | GeeksforGeeks GATE CSEWatch 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:0046:25 / 1:07:54•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=Key2RKhzRGY\" 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": 27492, "s": 27471, "text": "GATE-CS-2016 (Set 2)" }, { "code": null, "e": 27518, "s": 27492, "text": "GATE-GATE-CS-2016 (Set 2)" }, { "code": null, "e": 27523, "s": 27518, "text": "GATE" }, { "code": null, "e": 27621, "s": 27523, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27655, "s": 27621, "text": "GATE | Gate IT 2007 | Question 25" }, { "code": null, "e": 27689, "s": 27655, "text": "GATE | GATE-CS-2001 | Question 39" }, { "code": null, "e": 27723, "s": 27689, "text": "GATE | GATE-CS-2000 | Question 41" }, { "code": null, "e": 27756, "s": 27723, "text": "GATE | GATE-CS-2005 | Question 6" }, { "code": null, "e": 27792, "s": 27756, "text": "GATE | GATE MOCK 2017 | Question 21" }, { "code": null, "e": 27828, "s": 27792, "text": "GATE | GATE MOCK 2017 | Question 24" }, { "code": null, "e": 27862, "s": 27828, "text": "GATE | GATE-CS-2006 | Question 47" }, { "code": null, "e": 27896, "s": 27862, "text": "GATE | Gate IT 2008 | Question 43" }, { "code": null, "e": 27930, "s": 27896, "text": "GATE | GATE-CS-2009 | Question 38" } ]
SQL Query to Find the Highest Salary of Each Department - GeeksforGeeks
07 Apr, 2021 Structured Query Language or SQL is a standard Database language that is used to create, maintain and retrieve the data from relational databases like MySQL, Oracle, etc. In this article, we will be using the Microsoft SQL Server. Here we are going to see how to get the highest salary of each department. Here, we will first create a database named “geeks” then we will create a table “department” in that database. After, that we will execute our query on that table. Creating Database: CREATE geeks; To use this database: USE geeks; This is our table in the geeks database: CREATE TABLE department( ID int, SALARY int, NAME Varchar(20), DEPT_ID Varchar(255)); To see the description of the table: EXEC sp_columns department; Add value into the table: INSERT INTO department VALUES (1, 34000, 'ANURAG', 'UI DEVELOPERS'); INSERT INTO department VALUES (2, 33000, 'harsh', 'BACKEND DEVELOPERS'); INSERT INTO department VALUES (3, 36000, 'SUMIT', 'BACKEND DEVELOPERS'); INSERT INTO department VALUES (4, 36000, 'RUHI', 'UI DEVELOPERS'); INSERT INTO department VALUES (5, 37000, 'KAE', 'UI DEVELOPERS'); This is our data inside the table: SELECT * FROM department; Get the highest salary of each department on the table. Here our table contains a DEPT_ID and it has two different categories UI DEVELOPERS and BACKEND DEVELOPERS, and we will find out the highest salary of the column. SELECT colunm_name, MAX(column_name) FROM table_name GROUP BY column_name; Example: SELECT DEPT_ID, MAX(SALARY) FROM department GROUP BY DEPT_ID; Output: RajuKumar19 SQL-Query SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. SQL Interview Questions CTE in SQL How to Update Multiple Columns in Single Update Statement in SQL? Difference between SQL and NoSQL Difference between DDL and DML in DBMS SQL | Views Difference between DELETE, DROP and TRUNCATE MySQL | Group_CONCAT() Function Difference between DELETE and TRUNCATE SQL - ORDER BY
[ { "code": null, "e": 25981, "s": 25953, "text": "\n07 Apr, 2021" }, { "code": null, "e": 26212, "s": 25981, "text": "Structured Query Language or SQL is a standard Database language that is used to create, maintain and retrieve the data from relational databases like MySQL, Oracle, etc. In this article, we will be using the Microsoft SQL Server." }, { "code": null, "e": 26451, "s": 26212, "text": "Here we are going to see how to get the highest salary of each department. Here, we will first create a database named “geeks” then we will create a table “department” in that database. After, that we will execute our query on that table." }, { "code": null, "e": 26470, "s": 26451, "text": "Creating Database:" }, { "code": null, "e": 26484, "s": 26470, "text": "CREATE geeks;" }, { "code": null, "e": 26506, "s": 26484, "text": "To use this database:" }, { "code": null, "e": 26517, "s": 26506, "text": "USE geeks;" }, { "code": null, "e": 26558, "s": 26517, "text": "This is our table in the geeks database:" }, { "code": null, "e": 26660, "s": 26558, "text": "CREATE TABLE department(\n ID int,\n SALARY int,\n NAME Varchar(20),\n DEPT_ID Varchar(255));" }, { "code": null, "e": 26697, "s": 26660, "text": "To see the description of the table:" }, { "code": null, "e": 26725, "s": 26697, "text": "EXEC sp_columns department;" }, { "code": null, "e": 26751, "s": 26725, "text": "Add value into the table:" }, { "code": null, "e": 27099, "s": 26751, "text": "INSERT INTO department VALUES (1, 34000, 'ANURAG', 'UI DEVELOPERS');\nINSERT INTO department VALUES (2, 33000, 'harsh', 'BACKEND DEVELOPERS');\nINSERT INTO department VALUES (3, 36000, 'SUMIT', 'BACKEND DEVELOPERS');\nINSERT INTO department VALUES (4, 36000, 'RUHI', 'UI DEVELOPERS');\nINSERT INTO department VALUES (5, 37000, 'KAE', 'UI DEVELOPERS');" }, { "code": null, "e": 27134, "s": 27099, "text": "This is our data inside the table:" }, { "code": null, "e": 27160, "s": 27134, "text": "SELECT * FROM department;" }, { "code": null, "e": 27379, "s": 27160, "text": "Get the highest salary of each department on the table. Here our table contains a DEPT_ID and it has two different categories UI DEVELOPERS and BACKEND DEVELOPERS, and we will find out the highest salary of the column." }, { "code": null, "e": 27454, "s": 27379, "text": "SELECT colunm_name, MAX(column_name) FROM table_name GROUP BY column_name;" }, { "code": null, "e": 27463, "s": 27454, "text": "Example:" }, { "code": null, "e": 27525, "s": 27463, "text": "SELECT DEPT_ID, MAX(SALARY) FROM department GROUP BY DEPT_ID;" }, { "code": null, "e": 27533, "s": 27525, "text": "Output:" }, { "code": null, "e": 27545, "s": 27533, "text": "RajuKumar19" }, { "code": null, "e": 27555, "s": 27545, "text": "SQL-Query" }, { "code": null, "e": 27559, "s": 27555, "text": "SQL" }, { "code": null, "e": 27563, "s": 27559, "text": "SQL" }, { "code": null, "e": 27661, "s": 27563, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27685, "s": 27661, "text": "SQL Interview Questions" }, { "code": null, "e": 27696, "s": 27685, "text": "CTE in SQL" }, { "code": null, "e": 27762, "s": 27696, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 27795, "s": 27762, "text": "Difference between SQL and NoSQL" }, { "code": null, "e": 27834, "s": 27795, "text": "Difference between DDL and DML in DBMS" }, { "code": null, "e": 27846, "s": 27834, "text": "SQL | Views" }, { "code": null, "e": 27891, "s": 27846, "text": "Difference between DELETE, DROP and TRUNCATE" }, { "code": null, "e": 27923, "s": 27891, "text": "MySQL | Group_CONCAT() Function" }, { "code": null, "e": 27962, "s": 27923, "text": "Difference between DELETE and TRUNCATE" } ]
Euler Tour of Tree - GeeksforGeeks
09 Dec, 2021 A Tree is a generalization of connected graph where it has N nodes that will have exactly N-1 edges, i.e one edge between every pair of vertices. Find the Euler tour of tree represented by adjacency list.Examples:Input : Output : 1 2 3 2 4 2 1Input : Output : 1 5 4 2 4 3 4 5 1 Euler tour is defined as a way of traversing tree such that each vertex is added to the tour when we visit it (either moving down from parent vertex or returning from child vertex). We start from root and reach back to root after visiting all vertices.It requires exactly 2*N-1 vertices to store Euler tour. Approach: We will run DFS(Depth first search) algorithm on Tree as: (1) Visit root node, i.e 1 vis[1]=1, Euler[0]=1 run dfs() for all unvisited adjacent nodes(2) (2) Visit node 2 vis[2]=1, Euler[1]=2 run dfs() for all unvisited adjacent nodes(3, 4) (3) Visit node 3 vis[3]=1, Euler[2]=3 All adjacent nodes are already visited, return to parent node and add parent to Euler tour Euler[3]=2 (4) Visit node 4 vis[4]=1, Euler[4]=4 All adjacent nodes are already visited, return to parent node and add parent to Euler tour, Euler[5]=2 (5) Visit node 2 All adjacent nodes are already visited, return to parent node and add parent to Euler tour, Euler[6]=1 (6) Visit node 1 All adjacent nodes are already visited, and node 1 is root node so, we stop our recursion here. Similarly, for example 2: C++ Java Javascript // C++ program to print Euler tour of a// tree.#include <bits/stdc++.h>using namespace std; #define MAX 1001 // Adjacency list representation of treevector<int> adj[MAX]; // Visited array to keep track visited// nodes on tourint vis[MAX]; // Array to store Euler Tourint Euler[2 * MAX]; // Function to add edges to treevoid add_edge(int u, int v){ adj[u].push_back(v); adj[v].push_back(u);} // Function to store Euler Tour of treevoid eulerTree(int u, int &index){ vis[u] = 1; Euler[index++] = u; for (auto it : adj[u]) { if (!vis[it]) { eulerTree(it, index); Euler[index++] = u; } }} // Function to print Euler Tour of treevoid printEulerTour(int root, int N){ int index = 0; eulerTree(root, index); for (int i = 0; i < (2*N-1); i++) cout << Euler[i] << " ";} // Driver codeint main(){ int N = 4; add_edge(1, 2); add_edge(2, 3); add_edge(2, 4); // Consider 1 as root and print // Euler tour printEulerTour(1, N); return 0;} // Java program to print Euler tour of a// tree.import java.util.*; class GFG{ static final int MAX = 1001;static int index = 0; // Adjacency list representation of treestatic ArrayList< ArrayList<Integer>> adj = new ArrayList<>(); // Visited array to keep track visited// nodes on tourstatic int vis[] = new int[MAX]; // Array to store Euler Tourstatic int Euler[] = new int[2 * MAX]; // Function to add edges to treestatic void add_edge(int u, int v){ adj.get(u).add(v); adj.get(v).add(u);} // Function to store Euler Tour of treestatic void eulerTree(int u){ vis[u] = 1; Euler[index++] = u; for(int it : adj.get(u)) { if (vis[it] == 0) { eulerTree(it); Euler[index++] = u; } }} // Function to print Euler Tour of treestatic void printEulerTour(int root, int N){ eulerTree(root); for(int i = 0; i < (2 * N - 1); i++) System.out.print(Euler[i] + " ");} // Driver codepublic static void main(String[] args){ int N = 4; for(int i = 0; i <= N; i++) adj.add(new ArrayList<>()); add_edge(1, 2); add_edge(2, 3); add_edge(2, 4); // Consider 1 as root and print // Euler tour printEulerTour(1, N);}} // This code is contributed by jrishabh99 <script> // Javascript program to print Euler tour of a// tree.var MAX = 1001; // Adjacency list representation of treevar adj = Array.from(Array(MAX), () => Array()); // Visited array to keep track visited// nodes on tourvar vis = Array(MAX); // Array to store Euler Tourvar Euler = Array(2 * MAX); // Function to add edges to treefunction add_edge(u, v){ adj[u].push(v); adj[v].push(u);} // Function to store Euler Tour of treefunction eulerTree(u, index){ vis[u] = 1; Euler[index++] = u; for(var it of adj[u]) { if (!vis[it]) { index = eulerTree(it, index); Euler[index++] = u; } } return index;} // Function to print Euler Tour of treefunction printEulerTour(root, N){ var index = 0; index = eulerTree(root, index); for(var i = 0; i < (2 * N - 1); i++) document.write(Euler[i] + " ");} // Driver codevar N = 4;add_edge(1, 2);add_edge(2, 3);add_edge(2, 4); // Consider 1 as root and print// Euler tourprintEulerTour(1, N); // This code is contributed by rrrtnx </script> 1 2 3 2 4 2 1 Auxiliary Space :O(N) Time Complexity: O(N) jrishabh99 rrrtnx kk773572498 Tree Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Binary Tree | Set 3 (Types of Binary Tree) Inorder Tree Traversal without Recursion Binary Tree | Set 2 (Properties) Decision Tree A program to check if a binary tree is BST or not Construct Tree from given Inorder and Preorder traversals Introduction to Tree Data Structure Lowest Common Ancestor in a Binary Tree | Set 1 Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
[ { "code": null, "e": 25991, "s": 25963, "text": "\n09 Dec, 2021" }, { "code": null, "e": 26214, "s": 25991, "text": "A Tree is a generalization of connected graph where it has N nodes that will have exactly N-1 edges, i.e one edge between every pair of vertices. Find the Euler tour of tree represented by adjacency list.Examples:Input : " }, { "code": null, "e": 26246, "s": 26214, "text": "Output : 1 2 3 2 4 2 1Input : " }, { "code": null, "e": 26273, "s": 26246, "text": "Output : 1 5 4 2 4 3 4 5 1" }, { "code": null, "e": 26581, "s": 26273, "text": "Euler tour is defined as a way of traversing tree such that each vertex is added to the tour when we visit it (either moving down from parent vertex or returning from child vertex). We start from root and reach back to root after visiting all vertices.It requires exactly 2*N-1 vertices to store Euler tour." }, { "code": null, "e": 26651, "s": 26581, "text": "Approach: We will run DFS(Depth first search) algorithm on Tree as: " }, { "code": null, "e": 27374, "s": 26651, "text": "(1) Visit root node, i.e 1 vis[1]=1, Euler[0]=1 run dfs() for all unvisited adjacent nodes(2) (2) Visit node 2 vis[2]=1, Euler[1]=2 run dfs() for all unvisited adjacent nodes(3, 4) (3) Visit node 3 vis[3]=1, Euler[2]=3 All adjacent nodes are already visited, return to parent node and add parent to Euler tour Euler[3]=2 (4) Visit node 4 vis[4]=1, Euler[4]=4 All adjacent nodes are already visited, return to parent node and add parent to Euler tour, Euler[5]=2 (5) Visit node 2 All adjacent nodes are already visited, return to parent node and add parent to Euler tour, Euler[6]=1 (6) Visit node 1 All adjacent nodes are already visited, and node 1 is root node so, we stop our recursion here. Similarly, for example 2: " }, { "code": null, "e": 27380, "s": 27376, "text": "C++" }, { "code": null, "e": 27385, "s": 27380, "text": "Java" }, { "code": null, "e": 27396, "s": 27385, "text": "Javascript" }, { "code": "// C++ program to print Euler tour of a// tree.#include <bits/stdc++.h>using namespace std; #define MAX 1001 // Adjacency list representation of treevector<int> adj[MAX]; // Visited array to keep track visited// nodes on tourint vis[MAX]; // Array to store Euler Tourint Euler[2 * MAX]; // Function to add edges to treevoid add_edge(int u, int v){ adj[u].push_back(v); adj[v].push_back(u);} // Function to store Euler Tour of treevoid eulerTree(int u, int &index){ vis[u] = 1; Euler[index++] = u; for (auto it : adj[u]) { if (!vis[it]) { eulerTree(it, index); Euler[index++] = u; } }} // Function to print Euler Tour of treevoid printEulerTour(int root, int N){ int index = 0; eulerTree(root, index); for (int i = 0; i < (2*N-1); i++) cout << Euler[i] << \" \";} // Driver codeint main(){ int N = 4; add_edge(1, 2); add_edge(2, 3); add_edge(2, 4); // Consider 1 as root and print // Euler tour printEulerTour(1, N); return 0;}", "e": 28419, "s": 27396, "text": null }, { "code": "// Java program to print Euler tour of a// tree.import java.util.*; class GFG{ static final int MAX = 1001;static int index = 0; // Adjacency list representation of treestatic ArrayList< ArrayList<Integer>> adj = new ArrayList<>(); // Visited array to keep track visited// nodes on tourstatic int vis[] = new int[MAX]; // Array to store Euler Tourstatic int Euler[] = new int[2 * MAX]; // Function to add edges to treestatic void add_edge(int u, int v){ adj.get(u).add(v); adj.get(v).add(u);} // Function to store Euler Tour of treestatic void eulerTree(int u){ vis[u] = 1; Euler[index++] = u; for(int it : adj.get(u)) { if (vis[it] == 0) { eulerTree(it); Euler[index++] = u; } }} // Function to print Euler Tour of treestatic void printEulerTour(int root, int N){ eulerTree(root); for(int i = 0; i < (2 * N - 1); i++) System.out.print(Euler[i] + \" \");} // Driver codepublic static void main(String[] args){ int N = 4; for(int i = 0; i <= N; i++) adj.add(new ArrayList<>()); add_edge(1, 2); add_edge(2, 3); add_edge(2, 4); // Consider 1 as root and print // Euler tour printEulerTour(1, N);}} // This code is contributed by jrishabh99", "e": 29688, "s": 28419, "text": null }, { "code": "<script> // Javascript program to print Euler tour of a// tree.var MAX = 1001; // Adjacency list representation of treevar adj = Array.from(Array(MAX), () => Array()); // Visited array to keep track visited// nodes on tourvar vis = Array(MAX); // Array to store Euler Tourvar Euler = Array(2 * MAX); // Function to add edges to treefunction add_edge(u, v){ adj[u].push(v); adj[v].push(u);} // Function to store Euler Tour of treefunction eulerTree(u, index){ vis[u] = 1; Euler[index++] = u; for(var it of adj[u]) { if (!vis[it]) { index = eulerTree(it, index); Euler[index++] = u; } } return index;} // Function to print Euler Tour of treefunction printEulerTour(root, N){ var index = 0; index = eulerTree(root, index); for(var i = 0; i < (2 * N - 1); i++) document.write(Euler[i] + \" \");} // Driver codevar N = 4;add_edge(1, 2);add_edge(2, 3);add_edge(2, 4); // Consider 1 as root and print// Euler tourprintEulerTour(1, N); // This code is contributed by rrrtnx </script>", "e": 30751, "s": 29688, "text": null }, { "code": null, "e": 30765, "s": 30751, "text": "1 2 3 2 4 2 1" }, { "code": null, "e": 30812, "s": 30767, "text": "Auxiliary Space :O(N) Time Complexity: O(N) " }, { "code": null, "e": 30823, "s": 30812, "text": "jrishabh99" }, { "code": null, "e": 30830, "s": 30823, "text": "rrrtnx" }, { "code": null, "e": 30842, "s": 30830, "text": "kk773572498" }, { "code": null, "e": 30847, "s": 30842, "text": "Tree" }, { "code": null, "e": 30852, "s": 30847, "text": "Tree" }, { "code": null, "e": 30950, "s": 30852, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30993, "s": 30950, "text": "Binary Tree | Set 3 (Types of Binary Tree)" }, { "code": null, "e": 31034, "s": 30993, "text": "Inorder Tree Traversal without Recursion" }, { "code": null, "e": 31067, "s": 31034, "text": "Binary Tree | Set 2 (Properties)" }, { "code": null, "e": 31081, "s": 31067, "text": "Decision Tree" }, { "code": null, "e": 31131, "s": 31081, "text": "A program to check if a binary tree is BST or not" }, { "code": null, "e": 31189, "s": 31131, "text": "Construct Tree from given Inorder and Preorder traversals" }, { "code": null, "e": 31225, "s": 31189, "text": "Introduction to Tree Data Structure" }, { "code": null, "e": 31273, "s": 31225, "text": "Lowest Common Ancestor in a Binary Tree | Set 1" } ]