title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Kth largest factor of number N
16 Jun, 2022 Given two positive integers N and K, the task is to print the Kth largest factor of N. Input: N = 12, K = 3Output: 4Explanation: The factors of 12 are {1, 2, 3, 4, 6, 12}. The largest factor is 12 and the 3rd largest factor is 4. Input: N = 30, K = 2Output: 15Explanation: The factors of 30 are {1, 2, 3, 5, 6, 10, 15, 30} and the 2nd largest factor is 15. Approach: The idea is to check for each number in the range [N, 1], and print the Kth number that divides N completely. Iterate through the loop from N to 0. Now, for each number in this loop: Check if it divides N or not. If N is divisible by the current number, decrement the value of K by 1. When K becomes 0, this means that the current number is the Kth largest factor of N. Print the answer according to the above observation. Below is the implementation of the above approach: C C++ Java Python C# Javascript // C program for the above approach #include <stdio.h> // Function to print Kth largest// factor of Nint KthLargestFactor(int N, int K){ // Check for numbers // in the range [N, 1] for (int i = N; i > 0; i--) { // Check if i is a factor of N if (N % i == 0) // If Yes, reduce K by 1 K--; // If K is 0, it means // i is the required // Kth factor of N if (K == 0) { return i; } } // When K is more // than the factors of N return -1;} // Driver Codeint main(){ int N = 12, K = 3; printf("%d", KthLargestFactor(N, K)); return 0;} // C++ program for the above approach #include <iostream>using namespace std; // Function to print Kth largest// factor of Nint KthLargestFactor(int N, int K){ // Check for numbers // in the range [N, 1] for (int i = N; i > 0; i--) { // Check if i is a factor of N if (N % i == 0) // If Yes, reduce K by 1 K--; // If K is 0, it means // i is the required // Kth factor of N if (K == 0) { return i; } } // When K is more // than the factors of N return -1;} // Driver Codeint main(){ int N = 12, K = 3; cout << KthLargestFactor(N, K);} // Java program for the above approach import java.io.*; class GFG { // Function to print Kth largest // factor of N static int KthLargestFactor(int N, int K) { // Check for numbers // in the range [N, 1] for (int i = N; i > 0; i--) { // Check if i is a factor of N if (N % i == 0) // If Yes, reduce K by 1 K--; // If K is 0, it means // i is the required // Kth factor of N if (K == 0) { return i; } } // When K is more // than the factors of N return -1; } // Driver Code public static void main(String[] args) { int N = 12, K = 3; System.out.println(KthLargestFactor(N, K)); }} # Python program for the above approach # Function to print Kth largest# factor of Ndef KthLargestFactor(N, K): for i in range(N, 0, -1): if N % i == 0: K -= 1 if K == 0: return i return -1 # Driver CodeN = 12K = 3print(KthLargestFactor(N, K)) // C# program for the above approachusing System;using System.Collections.Generic; class GFG{ // Function to print Kth largest// factor of Nstatic int KthLargestFactor(int N, int K){ // Check for numbers // in the range [N, 1] for (int i = N; i > 0; i--) { // Check if i is a factor of N if (N % i == 0) // If Yes, reduce K by 1 K--; // If K is 0, it means // i is the required // Kth factor of N if (K == 0) { return i; } } // When K is more // than the factors of N return -1;} // Driver Codepublic static void Main(){ int N = 12, K = 3; Console.Write(KthLargestFactor(N, K));}} // This code is contributed by ipg2016107. <script>// JavaScript program for the above approach// Function to print Kth largest// factor of Nfunction KthLargestFactor(N, K) { // Check for numbers // in the range [N, 1] for (let i = N; i > 0; i--) { // Check if i is a factor of N if (N % i == 0) // If Yes, reduce K by 1 K--; // If K is 0, it means // i is the required // Kth factor of N if (K == 0) { return i; } } // When K is more // than the factors of N return -1; } // Driver Codelet N = 12, K = 3;document.write(KthLargestFactor(N, K)); // This code is contributed by shivanisinghss2110</script> 4 Time Complexity: Auxiliary Space: Efficient Approach: The problem can be solved in an optimized way in sqrt(n) complexity by using the fact that factors of any number remain in the form of pairs. In other words, if i is a factor of number n then n/i will also be a factor of n. So in order to find all the factors of the number we need to check for factors till sqrt(n) and their corresponding pairs. A similar type of approach is used in the article: find divisors of natural numbers. Illustration: If n = 80, then all the various pairs of divisors possible are: (1,80), (2,40), (4,20), (5,16), (8,10). Hence in order to store all the factors of 80, we will iterate the loop from 1 to √80 ≈ 8 and store the factors in the range(which includes 1,2,4,5,8 here in this case). After this, we run a reverse loop and store the pairs of these previous factors (which will give 10, 16, 20, 40, and 80). Here we are running a reverse loop so that we can get the pairs in increasing order. In this way, we will get all the factors which include {1, 2, 4, 5, 8, 10, 16, 20, 40, and 80}. Approach: Initialize a vector to store the elements in increasing order.First, iterate a loop from 1 to sqrt(n) and store all the factors.Then iterate the loop in reverse order and for each factor store its corresponding pair. So if i is the factor then store n/i.If the size of the vector is greater or equal to k then return the kth largest factor(which will be v[v.size()-k] as the vector v is in increasing order).If k elements do not exist that means there is no kth largest factor and hence return -1. Initialize a vector to store the elements in increasing order. First, iterate a loop from 1 to sqrt(n) and store all the factors. Then iterate the loop in reverse order and for each factor store its corresponding pair. So if i is the factor then store n/i. If the size of the vector is greater or equal to k then return the kth largest factor(which will be v[v.size()-k] as the vector v is in increasing order). If k elements do not exist that means there is no kth largest factor and hence return -1. Handling the corner cases:A corner case will arise when any factor is exactly equal to sqrt(n). For example, if n=100, then in this case 10 will be a factor of the number, and also its corresponding pair is 10 as (10*10=100). So in this case 10 will be taken two times. In order to tackle this case, we use an if statement between two loops and remove the issue by considering this factor only one time. Below is the implementation of the above approach: C++ // C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to print Kth largest// factor of Nint KthLargestFactor(int n, int k){ // vector v to store the factors // of n in increasing order vector<int> v; int i; // Iterating the loop and checking // factors till sqrt(n) for (i = 1; i * i <= n; i++) { if (n % i == 0) v.push_back(i); } // corner cases if (i * i == n) { i--; } for (; i >= 1; i--) { if (n % i == 0) v.push_back(n / i); } // When k is less than the factors // of n then return the kth // largest element which will be // will kth element from the end // in the vector if (k <= v.size()) { return v[v.size() - k]; } // When k is more // than the factors of n else return -1;} // Driver Codeint main(){ int N = 12, K = 3; cout << KthLargestFactor(N, K);} // This code is contributed by Pushpesh raj 4 Time Complexity: O(sqrt(n)) Auxiliary Space: O(m) where m is the total number of factors of n. ipg2016107 shivanisinghss2110 pushpeshrajdx01 factor Mathematical School Programming Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n16 Jun, 2022" }, { "code": null, "e": 117, "s": 28, "text": "Given two positive integers N and K, the task is to print the Kth largest factor of N. " }, { "code": null, "e": 260, "s": 117, "text": "Input: N = 12, K = 3Output: 4Explanation: The factors of 12 are {1, 2, 3, 4, 6, 12}. The largest factor is 12 and the 3rd largest factor is 4." }, { "code": null, "e": 387, "s": 260, "text": "Input: N = 30, K = 2Output: 15Explanation: The factors of 30 are {1, 2, 3, 5, 6, 10, 15, 30} and the 2nd largest factor is 15." }, { "code": null, "e": 507, "s": 387, "text": "Approach: The idea is to check for each number in the range [N, 1], and print the Kth number that divides N completely." }, { "code": null, "e": 580, "s": 507, "text": "Iterate through the loop from N to 0. Now, for each number in this loop:" }, { "code": null, "e": 610, "s": 580, "text": "Check if it divides N or not." }, { "code": null, "e": 682, "s": 610, "text": "If N is divisible by the current number, decrement the value of K by 1." }, { "code": null, "e": 767, "s": 682, "text": "When K becomes 0, this means that the current number is the Kth largest factor of N." }, { "code": null, "e": 820, "s": 767, "text": "Print the answer according to the above observation." }, { "code": null, "e": 871, "s": 820, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 873, "s": 871, "text": "C" }, { "code": null, "e": 877, "s": 873, "text": "C++" }, { "code": null, "e": 882, "s": 877, "text": "Java" }, { "code": null, "e": 889, "s": 882, "text": "Python" }, { "code": null, "e": 892, "s": 889, "text": "C#" }, { "code": null, "e": 903, "s": 892, "text": "Javascript" }, { "code": "// C program for the above approach #include <stdio.h> // Function to print Kth largest// factor of Nint KthLargestFactor(int N, int K){ // Check for numbers // in the range [N, 1] for (int i = N; i > 0; i--) { // Check if i is a factor of N if (N % i == 0) // If Yes, reduce K by 1 K--; // If K is 0, it means // i is the required // Kth factor of N if (K == 0) { return i; } } // When K is more // than the factors of N return -1;} // Driver Codeint main(){ int N = 12, K = 3; printf(\"%d\", KthLargestFactor(N, K)); return 0;}", "e": 1548, "s": 903, "text": null }, { "code": "// C++ program for the above approach #include <iostream>using namespace std; // Function to print Kth largest// factor of Nint KthLargestFactor(int N, int K){ // Check for numbers // in the range [N, 1] for (int i = N; i > 0; i--) { // Check if i is a factor of N if (N % i == 0) // If Yes, reduce K by 1 K--; // If K is 0, it means // i is the required // Kth factor of N if (K == 0) { return i; } } // When K is more // than the factors of N return -1;} // Driver Codeint main(){ int N = 12, K = 3; cout << KthLargestFactor(N, K);}", "e": 2196, "s": 1548, "text": null }, { "code": "// Java program for the above approach import java.io.*; class GFG { // Function to print Kth largest // factor of N static int KthLargestFactor(int N, int K) { // Check for numbers // in the range [N, 1] for (int i = N; i > 0; i--) { // Check if i is a factor of N if (N % i == 0) // If Yes, reduce K by 1 K--; // If K is 0, it means // i is the required // Kth factor of N if (K == 0) { return i; } } // When K is more // than the factors of N return -1; } // Driver Code public static void main(String[] args) { int N = 12, K = 3; System.out.println(KthLargestFactor(N, K)); }}", "e": 2995, "s": 2196, "text": null }, { "code": "# Python program for the above approach # Function to print Kth largest# factor of Ndef KthLargestFactor(N, K): for i in range(N, 0, -1): if N % i == 0: K -= 1 if K == 0: return i return -1 # Driver CodeN = 12K = 3print(KthLargestFactor(N, K))", "e": 3282, "s": 2995, "text": null }, { "code": "// C# program for the above approachusing System;using System.Collections.Generic; class GFG{ // Function to print Kth largest// factor of Nstatic int KthLargestFactor(int N, int K){ // Check for numbers // in the range [N, 1] for (int i = N; i > 0; i--) { // Check if i is a factor of N if (N % i == 0) // If Yes, reduce K by 1 K--; // If K is 0, it means // i is the required // Kth factor of N if (K == 0) { return i; } } // When K is more // than the factors of N return -1;} // Driver Codepublic static void Main(){ int N = 12, K = 3; Console.Write(KthLargestFactor(N, K));}} // This code is contributed by ipg2016107.", "e": 4020, "s": 3282, "text": null }, { "code": "<script>// JavaScript program for the above approach// Function to print Kth largest// factor of Nfunction KthLargestFactor(N, K) { // Check for numbers // in the range [N, 1] for (let i = N; i > 0; i--) { // Check if i is a factor of N if (N % i == 0) // If Yes, reduce K by 1 K--; // If K is 0, it means // i is the required // Kth factor of N if (K == 0) { return i; } } // When K is more // than the factors of N return -1; } // Driver Codelet N = 12, K = 3;document.write(KthLargestFactor(N, K)); // This code is contributed by shivanisinghss2110</script>", "e": 4770, "s": 4020, "text": null }, { "code": null, "e": 4772, "s": 4770, "text": "4" }, { "code": null, "e": 4807, "s": 4772, "text": "Time Complexity: Auxiliary Space: " }, { "code": null, "e": 5260, "s": 4807, "text": "Efficient Approach: The problem can be solved in an optimized way in sqrt(n) complexity by using the fact that factors of any number remain in the form of pairs. In other words, if i is a factor of number n then n/i will also be a factor of n. So in order to find all the factors of the number we need to check for factors till sqrt(n) and their corresponding pairs. A similar type of approach is used in the article: find divisors of natural numbers." }, { "code": null, "e": 5851, "s": 5260, "text": "Illustration: If n = 80, then all the various pairs of divisors possible are: (1,80), (2,40), (4,20), (5,16), (8,10). Hence in order to store all the factors of 80, we will iterate the loop from 1 to √80 ≈ 8 and store the factors in the range(which includes 1,2,4,5,8 here in this case). After this, we run a reverse loop and store the pairs of these previous factors (which will give 10, 16, 20, 40, and 80). Here we are running a reverse loop so that we can get the pairs in increasing order. In this way, we will get all the factors which include {1, 2, 4, 5, 8, 10, 16, 20, 40, and 80}." }, { "code": null, "e": 5861, "s": 5851, "text": "Approach:" }, { "code": null, "e": 6359, "s": 5861, "text": "Initialize a vector to store the elements in increasing order.First, iterate a loop from 1 to sqrt(n) and store all the factors.Then iterate the loop in reverse order and for each factor store its corresponding pair. So if i is the factor then store n/i.If the size of the vector is greater or equal to k then return the kth largest factor(which will be v[v.size()-k] as the vector v is in increasing order).If k elements do not exist that means there is no kth largest factor and hence return -1." }, { "code": null, "e": 6422, "s": 6359, "text": "Initialize a vector to store the elements in increasing order." }, { "code": null, "e": 6489, "s": 6422, "text": "First, iterate a loop from 1 to sqrt(n) and store all the factors." }, { "code": null, "e": 6616, "s": 6489, "text": "Then iterate the loop in reverse order and for each factor store its corresponding pair. So if i is the factor then store n/i." }, { "code": null, "e": 6771, "s": 6616, "text": "If the size of the vector is greater or equal to k then return the kth largest factor(which will be v[v.size()-k] as the vector v is in increasing order)." }, { "code": null, "e": 6861, "s": 6771, "text": "If k elements do not exist that means there is no kth largest factor and hence return -1." }, { "code": null, "e": 7265, "s": 6861, "text": "Handling the corner cases:A corner case will arise when any factor is exactly equal to sqrt(n). For example, if n=100, then in this case 10 will be a factor of the number, and also its corresponding pair is 10 as (10*10=100). So in this case 10 will be taken two times. In order to tackle this case, we use an if statement between two loops and remove the issue by considering this factor only one time." }, { "code": null, "e": 7316, "s": 7265, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 7320, "s": 7316, "text": "C++" }, { "code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to print Kth largest// factor of Nint KthLargestFactor(int n, int k){ // vector v to store the factors // of n in increasing order vector<int> v; int i; // Iterating the loop and checking // factors till sqrt(n) for (i = 1; i * i <= n; i++) { if (n % i == 0) v.push_back(i); } // corner cases if (i * i == n) { i--; } for (; i >= 1; i--) { if (n % i == 0) v.push_back(n / i); } // When k is less than the factors // of n then return the kth // largest element which will be // will kth element from the end // in the vector if (k <= v.size()) { return v[v.size() - k]; } // When k is more // than the factors of n else return -1;} // Driver Codeint main(){ int N = 12, K = 3; cout << KthLargestFactor(N, K);} // This code is contributed by Pushpesh raj", "e": 8304, "s": 7320, "text": null }, { "code": null, "e": 8306, "s": 8304, "text": "4" }, { "code": null, "e": 8401, "s": 8306, "text": "Time Complexity: O(sqrt(n)) Auxiliary Space: O(m) where m is the total number of factors of n." }, { "code": null, "e": 8412, "s": 8401, "text": "ipg2016107" }, { "code": null, "e": 8431, "s": 8412, "text": "shivanisinghss2110" }, { "code": null, "e": 8447, "s": 8431, "text": "pushpeshrajdx01" }, { "code": null, "e": 8454, "s": 8447, "text": "factor" }, { "code": null, "e": 8467, "s": 8454, "text": "Mathematical" }, { "code": null, "e": 8486, "s": 8467, "text": "School Programming" }, { "code": null, "e": 8499, "s": 8486, "text": "Mathematical" } ]
turtle.onclick() function in Python
26 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. This function is used to bind fun to a mouse-click event on this turtle or on canvas. Syntax : turtle.onclick(fun, btn=1, add=None) Parameters: Below is the implementation of the above method with some examples : Example 1 : Python3 # import packageimport turtle # method to actiondef fxn(x,y): # some motion turtle.right(90) turtle.forward(100) # turtle speed to slowestturtle.speed(1) # motionturtle.fd(100) # allow user to click # for some actionturtle.onclick(fxn) Output : Example 2 : Python3 # import packageimport turtle # screen objectwn = turtle.Screen() # method to perform actiondef fxn(x, y): turtle.goto(x, y) turtle.write(str(x)+","+str(y)) # onclick action wn.onclick(fxn)wn.mainloop() Output : Python-turtle 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 Convert integer to string in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n26 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": 332, "s": 245, "text": "This function is used to bind fun to a mouse-click event on this turtle or on canvas. " }, { "code": null, "e": 341, "s": 332, "text": "Syntax :" }, { "code": null, "e": 379, "s": 341, "text": "turtle.onclick(fun, btn=1, add=None)\n" }, { "code": null, "e": 391, "s": 379, "text": "Parameters:" }, { "code": null, "e": 460, "s": 391, "text": "Below is the implementation of the above method with some examples :" }, { "code": null, "e": 472, "s": 460, "text": "Example 1 :" }, { "code": null, "e": 480, "s": 472, "text": "Python3" }, { "code": "# import packageimport turtle # method to actiondef fxn(x,y): # some motion turtle.right(90) turtle.forward(100) # turtle speed to slowestturtle.speed(1) # motionturtle.fd(100) # allow user to click # for some actionturtle.onclick(fxn)", "e": 737, "s": 480, "text": null }, { "code": null, "e": 746, "s": 737, "text": "Output :" }, { "code": null, "e": 758, "s": 746, "text": "Example 2 :" }, { "code": null, "e": 766, "s": 758, "text": "Python3" }, { "code": "# import packageimport turtle # screen objectwn = turtle.Screen() # method to perform actiondef fxn(x, y): turtle.goto(x, y) turtle.write(str(x)+\",\"+str(y)) # onclick action wn.onclick(fxn)wn.mainloop()", "e": 976, "s": 766, "text": null }, { "code": null, "e": 985, "s": 976, "text": "Output :" }, { "code": null, "e": 999, "s": 985, "text": "Python-turtle" }, { "code": null, "e": 1006, "s": 999, "text": "Python" }, { "code": null, "e": 1104, "s": 1006, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1122, "s": 1104, "text": "Python Dictionary" }, { "code": null, "e": 1164, "s": 1122, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 1186, "s": 1164, "text": "Enumerate() in Python" }, { "code": null, "e": 1221, "s": 1186, "text": "Read a file line by line in Python" }, { "code": null, "e": 1247, "s": 1221, "text": "Python String | replace()" }, { "code": null, "e": 1279, "s": 1247, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1308, "s": 1279, "text": "*args and **kwargs in Python" }, { "code": null, "e": 1335, "s": 1308, "text": "Python Classes and Objects" }, { "code": null, "e": 1365, "s": 1335, "text": "Iterate over a list in Python" } ]
Python | os.path.basename() method
12 Oct, 2021 OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality. os.path module is sub module of OS module in Python used for common path name manipulation.os.path.basename() method in Python is used to get the base name in specified path. This method internally use os.path.split() method to split the specified path into a pair (head, tail). os.path.basename() method returns the tail part after splitting the specified path into (head, tail) pair. Syntax: os.path.basename(path)Parameter: path: A path-like object representing a file system path. Return Type: This method returns a string value which represents the base name the specified path. Code: Use of os.path.basename() method Python3 # Python program to explain os.path.basename() method # importing os.path moduleimport os.path # Pathpath = '/home/User/Documents' # Above specified path# will be splitted into# (head, tail) pair as# ('/home/User', 'Documents') # Get the base name # of the specified pathbasename = os.path.basename(path) # Print the base name print(basename) # Pathpath = '/home/User/Documents/file.txt' # Above specified path# will be splitted into# (head, tail) pair as# ('/home/User/Documents', 'file.txt') # Get the base name # of the specified pathbasename = os.path.basename(path) # Print the basename name print(basename) # Pathpath = 'file.txt' # The above specified path# will be splitted into# head and tail pair# as ('', 'file.txt')# so 'file.txt' will be printed # Get the base name # of the specified pathbasename = os.path.basename(path) # Print the base name print(basename) Documents file.txt file.txt Reference: https://docs.python.org/3/library/os.path.html sooda367 Python OS-path-module python-os-module Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Iterate over a list in Python Python OOPs Concepts
[ { "code": null, "e": 28, "s": 0, "text": "\n12 Oct, 2021" }, { "code": null, "e": 635, "s": 28, "text": "OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality. os.path module is sub module of OS module in Python used for common path name manipulation.os.path.basename() method in Python is used to get the base name in specified path. This method internally use os.path.split() method to split the specified path into a pair (head, tail). os.path.basename() method returns the tail part after splitting the specified path into (head, tail) pair. " }, { "code": null, "e": 835, "s": 635, "text": "Syntax: os.path.basename(path)Parameter: path: A path-like object representing a file system path. Return Type: This method returns a string value which represents the base name the specified path. " }, { "code": null, "e": 876, "s": 835, "text": "Code: Use of os.path.basename() method " }, { "code": null, "e": 884, "s": 876, "text": "Python3" }, { "code": "# Python program to explain os.path.basename() method # importing os.path moduleimport os.path # Pathpath = '/home/User/Documents' # Above specified path# will be splitted into# (head, tail) pair as# ('/home/User', 'Documents') # Get the base name # of the specified pathbasename = os.path.basename(path) # Print the base name print(basename) # Pathpath = '/home/User/Documents/file.txt' # Above specified path# will be splitted into# (head, tail) pair as# ('/home/User/Documents', 'file.txt') # Get the base name # of the specified pathbasename = os.path.basename(path) # Print the basename name print(basename) # Pathpath = 'file.txt' # The above specified path# will be splitted into# head and tail pair# as ('', 'file.txt')# so 'file.txt' will be printed # Get the base name # of the specified pathbasename = os.path.basename(path) # Print the base name print(basename)", "e": 1764, "s": 884, "text": null }, { "code": null, "e": 1792, "s": 1764, "text": "Documents\nfile.txt\nfile.txt" }, { "code": null, "e": 1853, "s": 1794, "text": "Reference: https://docs.python.org/3/library/os.path.html " }, { "code": null, "e": 1862, "s": 1853, "text": "sooda367" }, { "code": null, "e": 1884, "s": 1862, "text": "Python OS-path-module" }, { "code": null, "e": 1901, "s": 1884, "text": "python-os-module" }, { "code": null, "e": 1908, "s": 1901, "text": "Python" }, { "code": null, "e": 2006, "s": 1908, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2024, "s": 2006, "text": "Python Dictionary" }, { "code": null, "e": 2066, "s": 2024, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2088, "s": 2066, "text": "Enumerate() in Python" }, { "code": null, "e": 2123, "s": 2088, "text": "Read a file line by line in Python" }, { "code": null, "e": 2149, "s": 2123, "text": "Python String | replace()" }, { "code": null, "e": 2181, "s": 2149, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2210, "s": 2181, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2237, "s": 2210, "text": "Python Classes and Objects" }, { "code": null, "e": 2267, "s": 2237, "text": "Iterate over a list in Python" } ]
Types of Models in Object Oriented Modeling and Design
11 Dec, 2019 Intention of object oriented modeling and design is to learn how to apply object -oriented concepts to all the stages of the software development life cycle.Object-oriented modeling and design is a way of thinking about problems using models organized around real world concepts. The fundamental construct is the object, which combines both data structure and behavior. Purpose of Models: Testing a physical entity before building itCommunication with customersVisualizationReduction of complexity Testing a physical entity before building it Communication with customers Visualization Reduction of complexity Types of Models:There are 3 types of models in the object oriented modeling and design are: Class Model, State Model, and Interaction Model. These are explained as following below. Class Model:The class model shows all the classes present in the system. The class model shows the attributes and the behavior associated with the objects.The class diagram is used to show the class model.The class diagram shows the class name followed by the attributes followed by the functions or the methods that are associated with the object of the class.Goal in constructing class model is to capture those concepts from the real world that are important to an application.State Model:State model describes those aspects of objects concerned with time and the sequencing of operations – events that mark changes, states that define the context for events, and the organization of events and states.Actions and events in a state diagram become operations on objects in the class model. State diagram describes the state model.Interaction Model:Interaction model is used to show the various interactions between objects, how the objects collaborate to achieve the behavior of the system as a whole.The following diagrams are used to show the interaction model:Use Case DiagramSequence DiagramActivity Diagram Class Model:The class model shows all the classes present in the system. The class model shows the attributes and the behavior associated with the objects.The class diagram is used to show the class model.The class diagram shows the class name followed by the attributes followed by the functions or the methods that are associated with the object of the class.Goal in constructing class model is to capture those concepts from the real world that are important to an application. The class diagram is used to show the class model.The class diagram shows the class name followed by the attributes followed by the functions or the methods that are associated with the object of the class.Goal in constructing class model is to capture those concepts from the real world that are important to an application. State Model:State model describes those aspects of objects concerned with time and the sequencing of operations – events that mark changes, states that define the context for events, and the organization of events and states.Actions and events in a state diagram become operations on objects in the class model. State diagram describes the state model. Interaction Model:Interaction model is used to show the various interactions between objects, how the objects collaborate to achieve the behavior of the system as a whole.The following diagrams are used to show the interaction model:Use Case DiagramSequence DiagramActivity Diagram Use Case Diagram Sequence Diagram Activity Diagram Object-Oriented-Design GBlog Misc Misc Misc Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. DSA Sheet by Love Babbar GEEK-O-LYMPICS 2022 - May The Geeks Force Be With You! Geek Streak - 24 Days POTD Challenge What is Hashing | A Complete Tutorial GeeksforGeeks Jobathon - Are You Ready For This Hiring Challenge? Overview of Data Structures | Set 1 (Linear Data Structures) vector::push_back() and vector::pop_back() in C++ STL Top 10 algorithms in Interview Questions How to write Regular Expressions? Program for nth Catalan Number
[ { "code": null, "e": 54, "s": 26, "text": "\n11 Dec, 2019" }, { "code": null, "e": 424, "s": 54, "text": "Intention of object oriented modeling and design is to learn how to apply object -oriented concepts to all the stages of the software development life cycle.Object-oriented modeling and design is a way of thinking about problems using models organized around real world concepts. The fundamental construct is the object, which combines both data structure and behavior." }, { "code": null, "e": 443, "s": 424, "text": "Purpose of Models:" }, { "code": null, "e": 552, "s": 443, "text": "Testing a physical entity before building itCommunication with customersVisualizationReduction of complexity" }, { "code": null, "e": 597, "s": 552, "text": "Testing a physical entity before building it" }, { "code": null, "e": 626, "s": 597, "text": "Communication with customers" }, { "code": null, "e": 640, "s": 626, "text": "Visualization" }, { "code": null, "e": 664, "s": 640, "text": "Reduction of complexity" }, { "code": null, "e": 845, "s": 664, "text": "Types of Models:There are 3 types of models in the object oriented modeling and design are: Class Model, State Model, and Interaction Model. These are explained as following below." }, { "code": null, "e": 1959, "s": 845, "text": "Class Model:The class model shows all the classes present in the system. The class model shows the attributes and the behavior associated with the objects.The class diagram is used to show the class model.The class diagram shows the class name followed by the attributes followed by the functions or the methods that are associated with the object of the class.Goal in constructing class model is to capture those concepts from the real world that are important to an application.State Model:State model describes those aspects of objects concerned with time and the sequencing of operations – events that mark changes, states that define the context for events, and the organization of events and states.Actions and events in a state diagram become operations on objects in the class model. State diagram describes the state model.Interaction Model:Interaction model is used to show the various interactions between objects, how the objects collaborate to achieve the behavior of the system as a whole.The following diagrams are used to show the interaction model:Use Case DiagramSequence DiagramActivity Diagram" }, { "code": null, "e": 2440, "s": 1959, "text": "Class Model:The class model shows all the classes present in the system. The class model shows the attributes and the behavior associated with the objects.The class diagram is used to show the class model.The class diagram shows the class name followed by the attributes followed by the functions or the methods that are associated with the object of the class.Goal in constructing class model is to capture those concepts from the real world that are important to an application." }, { "code": null, "e": 2766, "s": 2440, "text": "The class diagram is used to show the class model.The class diagram shows the class name followed by the attributes followed by the functions or the methods that are associated with the object of the class.Goal in constructing class model is to capture those concepts from the real world that are important to an application." }, { "code": null, "e": 3119, "s": 2766, "text": "State Model:State model describes those aspects of objects concerned with time and the sequencing of operations – events that mark changes, states that define the context for events, and the organization of events and states.Actions and events in a state diagram become operations on objects in the class model. State diagram describes the state model." }, { "code": null, "e": 3401, "s": 3119, "text": "Interaction Model:Interaction model is used to show the various interactions between objects, how the objects collaborate to achieve the behavior of the system as a whole.The following diagrams are used to show the interaction model:Use Case DiagramSequence DiagramActivity Diagram" }, { "code": null, "e": 3418, "s": 3401, "text": "Use Case Diagram" }, { "code": null, "e": 3435, "s": 3418, "text": "Sequence Diagram" }, { "code": null, "e": 3452, "s": 3435, "text": "Activity Diagram" }, { "code": null, "e": 3475, "s": 3452, "text": "Object-Oriented-Design" }, { "code": null, "e": 3481, "s": 3475, "text": "GBlog" }, { "code": null, "e": 3486, "s": 3481, "text": "Misc" }, { "code": null, "e": 3491, "s": 3486, "text": "Misc" }, { "code": null, "e": 3496, "s": 3491, "text": "Misc" }, { "code": null, "e": 3594, "s": 3496, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3619, "s": 3594, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 3674, "s": 3619, "text": "GEEK-O-LYMPICS 2022 - May The Geeks Force Be With You!" }, { "code": null, "e": 3711, "s": 3674, "text": "Geek Streak - 24 Days POTD Challenge" }, { "code": null, "e": 3749, "s": 3711, "text": "What is Hashing | A Complete Tutorial" }, { "code": null, "e": 3815, "s": 3749, "text": "GeeksforGeeks Jobathon - Are You Ready For This Hiring Challenge?" }, { "code": null, "e": 3876, "s": 3815, "text": "Overview of Data Structures | Set 1 (Linear Data Structures)" }, { "code": null, "e": 3930, "s": 3876, "text": "vector::push_back() and vector::pop_back() in C++ STL" }, { "code": null, "e": 3971, "s": 3930, "text": "Top 10 algorithms in Interview Questions" }, { "code": null, "e": 4005, "s": 3971, "text": "How to write Regular Expressions?" } ]
Python Program for Heap Sort
06 Jul, 2022 Heapsort is a comparison based sorting technique based on a Binary Heap data structure. It is similar to selection sort where we first find the maximum element and place the maximum element at the end. We repeat the same process for the remaining element. Python # Python program for implementation of heap Sort # To heapify subtree rooted at index i. # n is size of heap def heapify(arr, n, i): largest = i # Initialize largest as root l = 2 * i + 1 # left = 2*i + 1 r = 2 * i + 2 # right = 2*i + 2 # See if left child of root exists and is # greater than root if l < n and arr[i] < arr[l]: largest = l # See if right child of root exists and is # greater than root if r < n and arr[largest] < arr[r]: largest = r # Change root, if needed if largest != i: arr[i],arr[largest] = arr[largest],arr[i] # swap # Heapify the root. heapify(arr, n, largest) # The main function to sort an array of given size def heapSort(arr): n = len(arr) # Build a maxheap. # Since last parent will be at ((n//2)-1) we can start at that location. for i in range(n // 2 - 1, -1, -1): heapify(arr, n, i) # One by one extract elements for i in range(n-1, 0, -1): arr[i], arr[0] = arr[0], arr[i] # swap heapify(arr, i, 0) # Driver code to test above arr = [ 12, 11, 13, 5, 6, 7] heapSort(arr) n = len(arr) print ("Sorted array is") for i in range(n): print ("%d" %arr[i]), # This code is contributed by Mohit Kumra Sorted array is 5 6 7 11 12 13 Time Complexity: O(n*log(n)) Time complexity of heapify is O(log(n)). Time complexity of createAndBuildHeap() is O(n). And, hence the overall time complexity of Heap Sort is O(n*log(n)). Auxiliary Space: O(logn) Please refer complete article on Heap Sort for more details! jroberto amankr0211 hardikkoriintern Heap Sort python sorting-exercises Python-Data-Structures Heap Python Programs Sorting Sorting Heap Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n06 Jul, 2022" }, { "code": null, "e": 310, "s": 54, "text": "Heapsort is a comparison based sorting technique based on a Binary Heap data structure. It is similar to selection sort where we first find the maximum element and place the maximum element at the end. We repeat the same process for the remaining element." }, { "code": null, "e": 317, "s": 310, "text": "Python" }, { "code": "# Python program for implementation of heap Sort # To heapify subtree rooted at index i. # n is size of heap def heapify(arr, n, i): largest = i # Initialize largest as root l = 2 * i + 1 # left = 2*i + 1 r = 2 * i + 2 # right = 2*i + 2 # See if left child of root exists and is # greater than root if l < n and arr[i] < arr[l]: largest = l # See if right child of root exists and is # greater than root if r < n and arr[largest] < arr[r]: largest = r # Change root, if needed if largest != i: arr[i],arr[largest] = arr[largest],arr[i] # swap # Heapify the root. heapify(arr, n, largest) # The main function to sort an array of given size def heapSort(arr): n = len(arr) # Build a maxheap. # Since last parent will be at ((n//2)-1) we can start at that location. for i in range(n // 2 - 1, -1, -1): heapify(arr, n, i) # One by one extract elements for i in range(n-1, 0, -1): arr[i], arr[0] = arr[0], arr[i] # swap heapify(arr, i, 0) # Driver code to test above arr = [ 12, 11, 13, 5, 6, 7] heapSort(arr) n = len(arr) print (\"Sorted array is\") for i in range(n): print (\"%d\" %arr[i]), # This code is contributed by Mohit Kumra ", "e": 1499, "s": 317, "text": null }, { "code": null, "e": 1531, "s": 1499, "text": "Sorted array is\n5 6 7 11 12 13\n" }, { "code": null, "e": 1560, "s": 1531, "text": "Time Complexity: O(n*log(n))" }, { "code": null, "e": 1601, "s": 1560, "text": "Time complexity of heapify is O(log(n))." }, { "code": null, "e": 1650, "s": 1601, "text": "Time complexity of createAndBuildHeap() is O(n)." }, { "code": null, "e": 1718, "s": 1650, "text": "And, hence the overall time complexity of Heap Sort is O(n*log(n))." }, { "code": null, "e": 1743, "s": 1718, "text": "Auxiliary Space: O(logn)" }, { "code": null, "e": 1804, "s": 1743, "text": "Please refer complete article on Heap Sort for more details!" }, { "code": null, "e": 1813, "s": 1804, "text": "jroberto" }, { "code": null, "e": 1824, "s": 1813, "text": "amankr0211" }, { "code": null, "e": 1841, "s": 1824, "text": "hardikkoriintern" }, { "code": null, "e": 1851, "s": 1841, "text": "Heap Sort" }, { "code": null, "e": 1876, "s": 1851, "text": "python sorting-exercises" }, { "code": null, "e": 1899, "s": 1876, "text": "Python-Data-Structures" }, { "code": null, "e": 1904, "s": 1899, "text": "Heap" }, { "code": null, "e": 1920, "s": 1904, "text": "Python Programs" }, { "code": null, "e": 1928, "s": 1920, "text": "Sorting" }, { "code": null, "e": 1936, "s": 1928, "text": "Sorting" }, { "code": null, "e": 1941, "s": 1936, "text": "Heap" } ]
What is the difference between virtual and abstract functions in C#?
Abstract methods do not provide an implementation and they force the derived classes to override the method. It is declared under abstract class. An abstract method only has the method definition Virtual methods have an implementation, unlike the Abstract method and it can exist in the abstract and non-abstract class. It provides the derived classes with the option of overriding it. The virtual keyword is useful in modifying a method, property, indexer, or event. When you have a function defined in a class that you want to be implemented in an inherited class(es), you use virtual functions. The virtual functions could be implemented differently in different inherited class and the call to these functions will be decided at runtime. The following is a virtual function − public virtual int area() { } Here is an example showing how to work with virtual functions − Live Demo using System; namespace PolymorphismApplication { class Shape { protected int width, height; public Shape( int a = 0, int b = 0) { width = a; height = b; } public virtual int area() { Console.WriteLine("Parent class area :"); return 0; } } class Rectangle: Shape { public Rectangle( int a = 0, int b = 0): base(a, b) { } public override int area () { Console.WriteLine("Rectangle class area "); return (width * height); } } class Triangle: Shape { public Triangle(int a = 0, int b = 0): base(a, b) { } public override int area() { Console.WriteLine("Triangle class area:"); return (width * height / 2); } } class Caller { public void CallArea(Shape sh) { int a; a = sh.area(); Console.WriteLine("Area: {0}", a); } } class Tester { static void Main(string[] args) { Caller c = new Caller(); Rectangle r = new Rectangle(10, 7); Triangle t = new Triangle(10, 5); c.CallArea(r); c.CallArea(t); Console.ReadKey(); } } } Rectangle class area Area: 70 Triangle class area: Area: 25 The abstract keyword in C# is used for abstract classes and abstract functions. An abstract class in C# includes abstract and non-abstract methods. The following is an example of abstract functions in an abstract class in C# − Live Demo using System; public abstract class Vehicle { public abstract void display(); } public class Bus : Vehicle { public override void display() { Console.WriteLine("Bus"); } } public class Car : Vehicle { public override void display() { Console.WriteLine("Car"); } } public class Motorcycle : Vehicle { public override void display() { Console.WriteLine("Motorcycle"); } } public class MyClass { public static void Main() { Vehicle v; v = new Bus(); v.display(); v = new Car(); v.display(); v = new Motorcycle(); v.display(); } } Bus Car Motorcycle
[ { "code": null, "e": 1383, "s": 1187, "text": "Abstract methods do not provide an implementation and they force the derived classes to override the method. It is declared under abstract class. An abstract method only has the method definition" }, { "code": null, "e": 1573, "s": 1383, "text": "Virtual methods have an implementation, unlike the Abstract method and it can exist in the abstract and non-abstract class. It provides the derived classes with the option of overriding it." }, { "code": null, "e": 1929, "s": 1573, "text": "The virtual keyword is useful in modifying a method, property, indexer, or event. When you have a function defined in a class that you want to be implemented in an inherited class(es), you use virtual functions. The virtual functions could be implemented differently in different inherited class and the call to these functions will be decided at runtime." }, { "code": null, "e": 1967, "s": 1929, "text": "The following is a virtual function −" }, { "code": null, "e": 1997, "s": 1967, "text": "public virtual int area() { }" }, { "code": null, "e": 2061, "s": 1997, "text": "Here is an example showing how to work with virtual functions −" }, { "code": null, "e": 2072, "s": 2061, "text": " Live Demo" }, { "code": null, "e": 3274, "s": 2072, "text": "using System;\n\nnamespace PolymorphismApplication {\n class Shape {\n protected int width, height;\n public Shape( int a = 0, int b = 0) {\n width = a;\n height = b;\n }\n public virtual int area() {\n Console.WriteLine(\"Parent class area :\");\n return 0;\n }\n }\n class Rectangle: Shape {\n public Rectangle( int a = 0, int b = 0): base(a, b) {\n }\n public override int area () {\n Console.WriteLine(\"Rectangle class area \");\n return (width * height);\n }\n }\n class Triangle: Shape {\n public Triangle(int a = 0, int b = 0): base(a, b) {\n }\n public override int area() {\n Console.WriteLine(\"Triangle class area:\");\n return (width * height / 2);\n }\n }\n class Caller {\n public void CallArea(Shape sh) {\n int a;\n a = sh.area();\n Console.WriteLine(\"Area: {0}\", a);\n }\n }\n class Tester {\n static void Main(string[] args) {\n Caller c = new Caller();\n Rectangle r = new Rectangle(10, 7);\n Triangle t = new Triangle(10, 5);\n\n c.CallArea(r);\n c.CallArea(t);\n Console.ReadKey();\n }\n }\n}" }, { "code": null, "e": 3334, "s": 3274, "text": "Rectangle class area\nArea: 70\nTriangle class area:\nArea: 25" }, { "code": null, "e": 3482, "s": 3334, "text": "The abstract keyword in C# is used for abstract classes and abstract functions. An abstract class in C# includes abstract and non-abstract methods." }, { "code": null, "e": 3561, "s": 3482, "text": "The following is an example of abstract functions in an abstract class in C# −" }, { "code": null, "e": 3572, "s": 3561, "text": " Live Demo" }, { "code": null, "e": 4189, "s": 3572, "text": "using System;\npublic abstract class Vehicle {\n public abstract void display();\n}\npublic class Bus : Vehicle {\n public override void display() {\n Console.WriteLine(\"Bus\");\n }\n}\npublic class Car : Vehicle {\n public override void display() {\n Console.WriteLine(\"Car\");\n }\n}\npublic class Motorcycle : Vehicle {\n public override void display() {\n Console.WriteLine(\"Motorcycle\");\n }\n}\npublic class MyClass {\n public static void Main() {\n Vehicle v;\n v = new Bus();\n v.display();\n v = new Car();\n v.display();\n v = new Motorcycle();\n v.display();\n }\n}" }, { "code": null, "e": 4208, "s": 4189, "text": "Bus\nCar\nMotorcycle" } ]
Alternate element summation in list (Python)
Given a list of numbers in this article we are going to calculate the sum of alternate elements in that list. Every second number and also use the range function along with length function to get the number of elements to be summed. Live Demo listA = [13,65,78,13,12,13,65] # printing original list print("Given list : " , str(listA)) # With list slicing res = [sum(listA[i:: 2]) for i in range(len(listA) // (len(listA) // 2))] # print result print("Sum of alternate elements in the list :\n ",res) Running the above code gives us the following result − Given list : [13, 65, 78, 13, 12, 13, 65] Sum of alternate elements in the list : [168, 91] Use the percentage operator to separate the numbers at Even and Odd positions. And then add the elements to the respective position of a new empty list. Finally giving a list which shows sum of elements at odd position and sum of elements at even position. Live Demo listA = [13,65,78,13,12,13,65] # printing original list print("Given list : " , str(listA)) res = [0, 0] for i in range(0, len(listA)): if(i % 2): res[1] += listA[i] else : res[0] += listA[i] # print result print("Sum of alternate elements in the list :\n ",res) Running the above code gives us the following result − Given list : [13, 65, 78, 13, 12, 13, 65] Sum of alternate elements in the list : [168, 91]
[ { "code": null, "e": 1172, "s": 1062, "text": "Given a list of numbers in this article we are going to calculate the sum of alternate elements in that list." }, { "code": null, "e": 1295, "s": 1172, "text": "Every second number and also use the range function along with length function to get the number of elements to be summed." }, { "code": null, "e": 1306, "s": 1295, "text": " Live Demo" }, { "code": null, "e": 1569, "s": 1306, "text": "listA = [13,65,78,13,12,13,65]\n# printing original list\nprint(\"Given list : \" , str(listA))\n# With list slicing\nres = [sum(listA[i:: 2])\nfor i in range(len(listA) // (len(listA) // 2))]\n # print result\n print(\"Sum of alternate elements in the list :\\n \",res)" }, { "code": null, "e": 1624, "s": 1569, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 1716, "s": 1624, "text": "Given list : [13, 65, 78, 13, 12, 13, 65]\nSum of alternate elements in the list :\n[168, 91]" }, { "code": null, "e": 1973, "s": 1716, "text": "Use the percentage operator to separate the numbers at Even and Odd positions. And then add the elements to the respective position of a new empty list. Finally giving a list which shows sum of elements at odd position and sum of elements at even position." }, { "code": null, "e": 1984, "s": 1973, "text": " Live Demo" }, { "code": null, "e": 2265, "s": 1984, "text": "listA = [13,65,78,13,12,13,65]\n# printing original list\nprint(\"Given list : \" , str(listA))\nres = [0, 0]\nfor i in range(0, len(listA)):\n if(i % 2):\n res[1] += listA[i]\n else :\n res[0] += listA[i]\n# print result\nprint(\"Sum of alternate elements in the list :\\n \",res)" }, { "code": null, "e": 2320, "s": 2265, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 2412, "s": 2320, "text": "Given list : [13, 65, 78, 13, 12, 13, 65]\nSum of alternate elements in the list :\n[168, 91]" } ]
LocalDate plusMonths() method in Java with Examples - GeeksforGeeks
30 Jul, 2019 The plusMonths() method of LocalDate class in Java is used to add the number of specified months in this LocalDate and return a copy of LocalDate. This method adds the months field in the following steps: Add the months to the month-of-year field. Check if the date after adding months is valid or not. If date is invalid then method adjust the day-of-month to the last valid day. For example, 2018-08-31 plus one month gives date 2018-09-31 but this is invalid result, so the last valid day of the month, 2018-09-30, is returned.This instance is immutable and unaffected by this method call. Syntax: public LocalDate plusMonths(long monthsToAdd) Parameters: This method accepts a single parameter monthsToAdd which represents the months to add, may be negative. Return Value: This method returns a LocalDate based on this date with the months added, not null. Exception: This method throws DateTimeException if the result exceeds the supported date range. Below programs illustrate the plusMonths() method:Program 1: // Java program to demonstrate// LocalDate.plusMonths() method import java.time.*; public class GFG { public static void main(String[] args) { // create a LocalDate object LocalDate date = LocalDate.parse("2018-11-13"); // print instance System.out.println("LocalDate before" + " adding months: " + date); // add 5 months LocalDate returnvalue = date.plusMonths(5); // print result System.out.println("LocalDate after " + " adding months: " + returnvalue); }} LocalDate before adding months: 2018-11-13 LocalDate after adding months: 2019-04-13 Program 2: // Java program to demonstrate// LocalDate.plusMonths() method import java.time.*; public class GFG { public static void main(String[] args) { // create a LocalDate object LocalDate date = LocalDate.parse("2018-12-31"); // print instance System.out.println("LocalDate before" + " adding months: " + date); // add 9 months LocalDate returnvalue = date.plusMonths(9); // print result System.out.println("LocalDate after " + " adding months: " + returnvalue); }} LocalDate before adding months: 2018-12-31 LocalDate after adding months: 2019-09-30 References:https://docs.oracle.com/javase/10/docs/api/java/time/LocalDate.html#plusMonths(long) Akanksha_Rai Java-Functions Java-LocalDate Java-time package Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Initialize an ArrayList in Java Overriding in Java Multidimensional Arrays in Java Stack Class in Java PriorityQueue in Java LinkedList in Java Collections.sort() in Java with Examples Set in Java Hashtable in Java Queue Interface In Java
[ { "code": null, "e": 23835, "s": 23807, "text": "\n30 Jul, 2019" }, { "code": null, "e": 23982, "s": 23835, "text": "The plusMonths() method of LocalDate class in Java is used to add the number of specified months in this LocalDate and return a copy of LocalDate." }, { "code": null, "e": 24040, "s": 23982, "text": "This method adds the months field in the following steps:" }, { "code": null, "e": 24083, "s": 24040, "text": "Add the months to the month-of-year field." }, { "code": null, "e": 24138, "s": 24083, "text": "Check if the date after adding months is valid or not." }, { "code": null, "e": 24216, "s": 24138, "text": "If date is invalid then method adjust the day-of-month to the last valid day." }, { "code": null, "e": 24428, "s": 24216, "text": "For example, 2018-08-31 plus one month gives date 2018-09-31 but this is invalid result, so the last valid day of the month, 2018-09-30, is returned.This instance is immutable and unaffected by this method call." }, { "code": null, "e": 24436, "s": 24428, "text": "Syntax:" }, { "code": null, "e": 24483, "s": 24436, "text": "public LocalDate plusMonths(long monthsToAdd)\n" }, { "code": null, "e": 24599, "s": 24483, "text": "Parameters: This method accepts a single parameter monthsToAdd which represents the months to add, may be negative." }, { "code": null, "e": 24697, "s": 24599, "text": "Return Value: This method returns a LocalDate based on this date with the months added, not null." }, { "code": null, "e": 24793, "s": 24697, "text": "Exception: This method throws DateTimeException if the result exceeds the supported date range." }, { "code": null, "e": 24854, "s": 24793, "text": "Below programs illustrate the plusMonths() method:Program 1:" }, { "code": "// Java program to demonstrate// LocalDate.plusMonths() method import java.time.*; public class GFG { public static void main(String[] args) { // create a LocalDate object LocalDate date = LocalDate.parse(\"2018-11-13\"); // print instance System.out.println(\"LocalDate before\" + \" adding months: \" + date); // add 5 months LocalDate returnvalue = date.plusMonths(5); // print result System.out.println(\"LocalDate after \" + \" adding months: \" + returnvalue); }}", "e": 25463, "s": 24854, "text": null }, { "code": null, "e": 25550, "s": 25463, "text": "LocalDate before adding months: 2018-11-13\nLocalDate after adding months: 2019-04-13\n" }, { "code": null, "e": 25561, "s": 25550, "text": "Program 2:" }, { "code": "// Java program to demonstrate// LocalDate.plusMonths() method import java.time.*; public class GFG { public static void main(String[] args) { // create a LocalDate object LocalDate date = LocalDate.parse(\"2018-12-31\"); // print instance System.out.println(\"LocalDate before\" + \" adding months: \" + date); // add 9 months LocalDate returnvalue = date.plusMonths(9); // print result System.out.println(\"LocalDate after \" + \" adding months: \" + returnvalue); }}", "e": 26170, "s": 25561, "text": null }, { "code": null, "e": 26257, "s": 26170, "text": "LocalDate before adding months: 2018-12-31\nLocalDate after adding months: 2019-09-30\n" }, { "code": null, "e": 26353, "s": 26257, "text": "References:https://docs.oracle.com/javase/10/docs/api/java/time/LocalDate.html#plusMonths(long)" }, { "code": null, "e": 26366, "s": 26353, "text": "Akanksha_Rai" }, { "code": null, "e": 26381, "s": 26366, "text": "Java-Functions" }, { "code": null, "e": 26396, "s": 26381, "text": "Java-LocalDate" }, { "code": null, "e": 26414, "s": 26396, "text": "Java-time package" }, { "code": null, "e": 26419, "s": 26414, "text": "Java" }, { "code": null, "e": 26424, "s": 26419, "text": "Java" }, { "code": null, "e": 26522, "s": 26424, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26531, "s": 26522, "text": "Comments" }, { "code": null, "e": 26544, "s": 26531, "text": "Old Comments" }, { "code": null, "e": 26576, "s": 26544, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 26595, "s": 26576, "text": "Overriding in Java" }, { "code": null, "e": 26627, "s": 26595, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 26647, "s": 26627, "text": "Stack Class in Java" }, { "code": null, "e": 26669, "s": 26647, "text": "PriorityQueue in Java" }, { "code": null, "e": 26688, "s": 26669, "text": "LinkedList in Java" }, { "code": null, "e": 26729, "s": 26688, "text": "Collections.sort() in Java with Examples" }, { "code": null, "e": 26741, "s": 26729, "text": "Set in Java" }, { "code": null, "e": 26759, "s": 26741, "text": "Hashtable in Java" } ]
code.compile_command() in Python - GeeksforGeeks
22 Apr, 2020 With the help of code.compile_command() method, we can compile the single or multiple lines of code to check for the syntax error if any by using code.compile_command() method. Syntax : code.compile_command(code)Return : Return the object or compilation error if any. Example #1 :In this example we can see that by using code.compile_command() method, we are able to compile the multiple lines of code by using this method. # import codefrom code import compile_command code = 'a = 5 b = 9; print(a + b)'# Using code.compile_command() methodcompile_command(code) Output : a = 5 b = 9; print(a + b)^SyntaxError: invalid syntax Example #2 : # import codefrom code import compile_command code = '-a=5'# Using code.compile_command() methodcompile_command(code) Output : SyntaxError: can’t assign to operator Python code-module Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install PIP on Windows ? How to drop one or multiple columns in Pandas Dataframe Python OOPs Concepts Python | Get unique values from a list Check if element exists in list in Python Python Classes and Objects Python | os.path.join() method How To Convert Python Dictionary To JSON? Python | Pandas dataframe.groupby() Create a directory in Python
[ { "code": null, "e": 24212, "s": 24184, "text": "\n22 Apr, 2020" }, { "code": null, "e": 24389, "s": 24212, "text": "With the help of code.compile_command() method, we can compile the single or multiple lines of code to check for the syntax error if any by using code.compile_command() method." }, { "code": null, "e": 24480, "s": 24389, "text": "Syntax : code.compile_command(code)Return : Return the object or compilation error if any." }, { "code": null, "e": 24636, "s": 24480, "text": "Example #1 :In this example we can see that by using code.compile_command() method, we are able to compile the multiple lines of code by using this method." }, { "code": "# import codefrom code import compile_command code = 'a = 5 b = 9; print(a + b)'# Using code.compile_command() methodcompile_command(code) ", "e": 24777, "s": 24636, "text": null }, { "code": null, "e": 24786, "s": 24777, "text": "Output :" }, { "code": null, "e": 24840, "s": 24786, "text": "a = 5 b = 9; print(a + b)^SyntaxError: invalid syntax" }, { "code": null, "e": 24853, "s": 24840, "text": "Example #2 :" }, { "code": "# import codefrom code import compile_command code = '-a=5'# Using code.compile_command() methodcompile_command(code) ", "e": 24973, "s": 24853, "text": null }, { "code": null, "e": 24982, "s": 24973, "text": "Output :" }, { "code": null, "e": 25020, "s": 24982, "text": "SyntaxError: can’t assign to operator" }, { "code": null, "e": 25039, "s": 25020, "text": "Python code-module" }, { "code": null, "e": 25046, "s": 25039, "text": "Python" }, { "code": null, "e": 25144, "s": 25046, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25153, "s": 25144, "text": "Comments" }, { "code": null, "e": 25166, "s": 25153, "text": "Old Comments" }, { "code": null, "e": 25198, "s": 25166, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 25254, "s": 25198, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 25275, "s": 25254, "text": "Python OOPs Concepts" }, { "code": null, "e": 25314, "s": 25275, "text": "Python | Get unique values from a list" }, { "code": null, "e": 25356, "s": 25314, "text": "Check if element exists in list in Python" }, { "code": null, "e": 25383, "s": 25356, "text": "Python Classes and Objects" }, { "code": null, "e": 25414, "s": 25383, "text": "Python | os.path.join() method" }, { "code": null, "e": 25456, "s": 25414, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 25492, "s": 25456, "text": "Python | Pandas dataframe.groupby()" } ]
How to convert an object array to an integer array in Java?
You can convert an object array to an integer array in one of the following ways − By copying each element from integer array to object array − import java.util.Arrays; public class ObjectArrayToStringArray { public static void main(String args[]){ Object[] objArray = {21, 58, 69, 33, 65}; int length = objArray.length; int intArray[] = new int[length]; for(int i=0; i<length; i++){ intArray[i] = (int) objArray[i]; } System.out.println("Contents of the integer array: "+Arrays.toString(intArray)); } } Contents of the integer array: [21, 58, 69, 33, 65] Using the arrayCopy() method of the System class − import java.util.Arrays; public class ObjectArrayToStringArray { public static void main(String args[]){ Object[] objArray = {21, 58, 69, 33, 65}; int length = objArray.length; Integer intArray[] = new Integer[length]; System.arraycopy(objArray, 0, intArray, 0, length); System.out.println("Contents of the integer array: "+Arrays.toString(intArray)); } } Contents of the integer array: [21, 58, 69, 33, 65] Using the copyOf() method of the arrays class − import java.util.Arrays; public class ObjectArrayToStringArray { public static void main(String args[]){ Object[] objArray = {21, 58, 69, 33, 65}; int length = objArray.length; Integer[] intArray = Arrays.copyOf(objArray, length, Integer[].class); System.out.println("Contents of the integer array: "+Arrays.toString(intArray)); } } Contents of the integer array: [21, 58, 69, 33, 65] Using the toArray() method of the List class − import java.util.Arrays; public class ObjectArrayToStringArray { public static void main(String args[]){ Object[] objArray = {21, 58, 69, 33, 65}; Integer[] intArray = Arrays.asList(objArray).toArray(new Integer[0]); System.out.println("Contents of the integer array: "+Arrays.toString(intArray)); } } Contents of the integer array: [21, 58, 69, 33, 65]
[ { "code": null, "e": 1145, "s": 1062, "text": "You can convert an object array to an integer array in one of the following ways −" }, { "code": null, "e": 1206, "s": 1145, "text": "By copying each element from integer array to object array −" }, { "code": null, "e": 1617, "s": 1206, "text": "import java.util.Arrays;\npublic class ObjectArrayToStringArray {\n public static void main(String args[]){\n Object[] objArray = {21, 58, 69, 33, 65};\n int length = objArray.length;\n int intArray[] = new int[length];\n for(int i=0; i<length; i++){\n intArray[i] = (int) objArray[i];\n }\n System.out.println(\"Contents of the integer array: \"+Arrays.toString(intArray));\n }\n}" }, { "code": null, "e": 1669, "s": 1617, "text": "Contents of the integer array: [21, 58, 69, 33, 65]" }, { "code": null, "e": 1720, "s": 1669, "text": "Using the arrayCopy() method of the System class −" }, { "code": null, "e": 2112, "s": 1720, "text": "import java.util.Arrays;\npublic class ObjectArrayToStringArray {\n public static void main(String args[]){\n Object[] objArray = {21, 58, 69, 33, 65};\n int length = objArray.length;\n Integer intArray[] = new Integer[length];\n System.arraycopy(objArray, 0, intArray, 0, length);\n System.out.println(\"Contents of the integer array: \"+Arrays.toString(intArray));\n }\n}" }, { "code": null, "e": 2164, "s": 2112, "text": "Contents of the integer array: [21, 58, 69, 33, 65]" }, { "code": null, "e": 2212, "s": 2164, "text": "Using the copyOf() method of the arrays class −" }, { "code": null, "e": 2575, "s": 2212, "text": "import java.util.Arrays;\npublic class ObjectArrayToStringArray {\n public static void main(String args[]){\n Object[] objArray = {21, 58, 69, 33, 65};\n int length = objArray.length;\n Integer[] intArray = Arrays.copyOf(objArray, length, Integer[].class);\n System.out.println(\"Contents of the integer array: \"+Arrays.toString(intArray));\n }\n}" }, { "code": null, "e": 2627, "s": 2575, "text": "Contents of the integer array: [21, 58, 69, 33, 65]" }, { "code": null, "e": 2674, "s": 2627, "text": "Using the toArray() method of the List class −" }, { "code": null, "e": 3000, "s": 2674, "text": "import java.util.Arrays;\npublic class ObjectArrayToStringArray {\n public static void main(String args[]){\n Object[] objArray = {21, 58, 69, 33, 65};\n Integer[] intArray = Arrays.asList(objArray).toArray(new Integer[0]);\n System.out.println(\"Contents of the integer array: \"+Arrays.toString(intArray));\n }\n}" }, { "code": null, "e": 3052, "s": 3000, "text": "Contents of the integer array: [21, 58, 69, 33, 65]" } ]
Scrapy - Link Extractors
As the name itself indicates, Link Extractors are the objects that are used to extract links from web pages using scrapy.http.Response objects. In Scrapy, there are built-in extractors such as scrapy.linkextractors import LinkExtractor. You can customize your own link extractor according to your needs by implementing a simple interface. Every link extractor has a public method called extract_links which includes a Response object and returns a list of scrapy.link.Link objects. You can instantiate the link extractors only once and call the extract_links method various times to extract links with different responses. The CrawlSpiderclass uses link extractors with a set of rules whose main purpose is to extract links. Normally link extractors are grouped with Scrapy and are provided in scrapy.linkextractors module. By default, the link extractor will be LinkExtractor which is equal in functionality with LxmlLinkExtractor − from scrapy.linkextractors import LinkExtractor class scrapy.linkextractors.lxmlhtml.LxmlLinkExtractor(allow = (), deny = (), allow_domains = (), deny_domains = (), deny_extensions = None, restrict_xpaths = (), restrict_css = (), tags = ('a', 'area'), attrs = ('href', ), canonicalize = True, unique = True, process_value = None) The LxmlLinkExtractor is a highly recommended link extractor, because it has handy filtering options and it is used with lxml’s robust HTMLParser. allow (a regular expression (or list of)) It allows a single expression or group of expressions that should match the url which is to be extracted. If it is not mentioned, it will match all the links. deny (a regular expression (or list of)) It blocks or excludes a single expression or group of expressions that should match the url which is not to be extracted. If it is not mentioned or left empty, then it will not eliminate the undesired links. allow_domains (str or list) It allows a single string or list of strings that should match the domains from which the links are to be extracted. deny_domains (str or list) It blocks or excludes a single string or list of strings that should match the domains from which the links are not to be extracted. deny_extensions (list) It blocks the list of strings with the extensions when extracting the links. If it is not set, then by default it will be set to IGNORED_EXTENSIONS which contains predefined list in scrapy.linkextractors package. restrict_xpaths (str or list) It is an XPath list region from where the links are to be extracted from the response. If given, the links will be extracted only from the text, which is selected by XPath. restrict_css (str or list) It behaves similar to restrict_xpaths parameter which will extract the links from the CSS selected regions inside the response. tags (str or list) A single tag or a list of tags that should be considered when extracting the links. By default, it will be (’a’, ’area’). attrs (list) A single attribute or list of attributes should be considered while extracting links. By default, it will be (’href’,). canonicalize (boolean) The extracted url is brought to standard form using scrapy.utils.url.canonicalize_url. By default, it will be True. unique (boolean) It will be used if the extracted links are repeated. process_value (callable) It is a function which receives a value from scanned tags and attributes. The value received may be altered and returned or else nothing will be returned to reject the link. If not used, by default it will be lambda x: x. The following code is used to extract the links − <a href = "javascript:goToPage('../other/page.html'); return false">Link text</a> The following code function can be used in process_value − def process_value(val): m = re.search("javascript:goToPage\('(.*?)'", val) if m: return m.group(1) 27 Lectures 3.5 hours Attreya Bhatt Print Add Notes Bookmark this page
[ { "code": null, "e": 2576, "s": 2237, "text": "As the name itself indicates, Link Extractors are the objects that are used to extract links from web pages using scrapy.http.Response objects. In Scrapy, there are built-in extractors such as scrapy.linkextractors import LinkExtractor. You can customize your own link extractor according to your needs by implementing a simple interface." }, { "code": null, "e": 2962, "s": 2576, "text": "Every link extractor has a public method called extract_links which includes a Response object and returns a list of scrapy.link.Link objects. You can instantiate the link extractors only once and call the extract_links method various times to extract links with different responses. The CrawlSpiderclass uses link extractors with a set of rules whose main purpose is to extract links." }, { "code": null, "e": 3171, "s": 2962, "text": "Normally link extractors are grouped with Scrapy and are provided in scrapy.linkextractors module. By default, the link extractor will be LinkExtractor which is equal in functionality with LxmlLinkExtractor −" }, { "code": null, "e": 3220, "s": 3171, "text": "from scrapy.linkextractors import LinkExtractor\n" }, { "code": null, "e": 3514, "s": 3220, "text": "class scrapy.linkextractors.lxmlhtml.LxmlLinkExtractor(allow = (), deny = (), \n allow_domains = (), deny_domains = (), deny_extensions = None, restrict_xpaths = (), \n restrict_css = (), tags = ('a', 'area'), attrs = ('href', ), \n canonicalize = True, unique = True, process_value = None)" }, { "code": null, "e": 3661, "s": 3514, "text": "The LxmlLinkExtractor is a highly recommended link extractor, because it has handy filtering options and it is used with lxml’s robust HTMLParser." }, { "code": null, "e": 3703, "s": 3661, "text": "allow (a regular expression (or list of))" }, { "code": null, "e": 3862, "s": 3703, "text": "It allows a single expression or group of expressions that should match the url which is to be extracted. If it is not mentioned, it will match all the links." }, { "code": null, "e": 3903, "s": 3862, "text": "deny (a regular expression (or list of))" }, { "code": null, "e": 4111, "s": 3903, "text": "It blocks or excludes a single expression or group of expressions that should match the url which is not to be extracted. If it is not mentioned or left empty, then it will not eliminate the undesired links." }, { "code": null, "e": 4139, "s": 4111, "text": "allow_domains (str or list)" }, { "code": null, "e": 4256, "s": 4139, "text": "It allows a single string or list of strings that should match the domains from which the links are to be extracted." }, { "code": null, "e": 4283, "s": 4256, "text": "deny_domains (str or list)" }, { "code": null, "e": 4416, "s": 4283, "text": "It blocks or excludes a single string or list of strings that should match the domains from which the links are not to be extracted." }, { "code": null, "e": 4439, "s": 4416, "text": "deny_extensions (list)" }, { "code": null, "e": 4652, "s": 4439, "text": "It blocks the list of strings with the extensions when extracting the links. If it is not set, then by default it will be set to IGNORED_EXTENSIONS which contains predefined list in scrapy.linkextractors package." }, { "code": null, "e": 4682, "s": 4652, "text": "restrict_xpaths (str or list)" }, { "code": null, "e": 4855, "s": 4682, "text": "It is an XPath list region from where the links are to be extracted from the response. If given, the links will be extracted only from the text, which is selected by XPath." }, { "code": null, "e": 4882, "s": 4855, "text": "restrict_css (str or list)" }, { "code": null, "e": 5010, "s": 4882, "text": "It behaves similar to restrict_xpaths parameter which will extract the links from the CSS selected regions inside the response." }, { "code": null, "e": 5029, "s": 5010, "text": "tags (str or list)" }, { "code": null, "e": 5151, "s": 5029, "text": "A single tag or a list of tags that should be considered when extracting the links. By default, it will be (’a’, ’area’)." }, { "code": null, "e": 5164, "s": 5151, "text": "attrs (list)" }, { "code": null, "e": 5284, "s": 5164, "text": "A single attribute or list of attributes should be considered while extracting links. By default, it will be (’href’,)." }, { "code": null, "e": 5307, "s": 5284, "text": "canonicalize (boolean)" }, { "code": null, "e": 5423, "s": 5307, "text": "The extracted url is brought to standard form using scrapy.utils.url.canonicalize_url. By default, it will be True." }, { "code": null, "e": 5440, "s": 5423, "text": "unique (boolean)" }, { "code": null, "e": 5493, "s": 5440, "text": "It will be used if the extracted links are repeated." }, { "code": null, "e": 5518, "s": 5493, "text": "process_value (callable)" }, { "code": null, "e": 5740, "s": 5518, "text": "It is a function which receives a value from scanned tags and attributes. The value received may be altered and returned or else nothing will be returned to reject the link. If not used, by default it will be lambda x: x." }, { "code": null, "e": 5790, "s": 5740, "text": "The following code is used to extract the links −" }, { "code": null, "e": 5872, "s": 5790, "text": "<a href = \"javascript:goToPage('../other/page.html'); return false\">Link text</a>" }, { "code": null, "e": 5931, "s": 5872, "text": "The following code function can be used in process_value −" }, { "code": null, "e": 6046, "s": 5931, "text": "def process_value(val): \n m = re.search(\"javascript:goToPage\\('(.*?)'\", val) \n if m: \n return m.group(1) " }, { "code": null, "e": 6081, "s": 6046, "text": "\n 27 Lectures \n 3.5 hours \n" }, { "code": null, "e": 6096, "s": 6081, "text": " Attreya Bhatt" }, { "code": null, "e": 6103, "s": 6096, "text": " Print" }, { "code": null, "e": 6114, "s": 6103, "text": " Add Notes" } ]
PyQt5 QSpinBox - Getting current value - GeeksforGeeks
03 May, 2020 In this article we will see how we can get the current value of the spin box. By default its value is 0 although user can change it any time and programmatically we use setValue method to change its value. In order to get the value of spin box we use value method Syntax : spin.value() Argument : It takes no argument Return : It returns integer i.e current value Implementation steps – 1. Create a spin box widget2. Create a label to show current value3. Add action to the spin box4. Inside the action get the current value with the help of value method5. Show this value with the help of label. Below is the implementation – # importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import *import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle("Python ") # setting geometry self.setGeometry(100, 100, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for widgets def UiComponents(self): # creating spin box self.spin = QSpinBox(self) # setting geometry to spin box self.spin.setGeometry(100, 100, 100, 40) # adding action to the spin box self.spin.valueChanged.connect(self.show_result) # creating label show result self.label = QLabel(self) # setting geometry self.label.setGeometry(100, 200, 200, 40) # method called by spin box def show_result(self): # getting current value value = self.spin.value() # setting value of spin box to the label self.label.setText("Value : " + str(value)) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() window.show() # start the appsys.exit(App.exec()) Output : Python PyQt-SpinBox Python-gui Python-PyQt Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary How to Install PIP on Windows ? Read a file line by line in Python Enumerate() in Python Iterate over a list in Python Different ways to create Pandas Dataframe Python program to convert a list to string Create a Pandas DataFrame from Lists Python String | replace() Reading and Writing to text files in Python
[ { "code": null, "e": 24220, "s": 24192, "text": "\n03 May, 2020" }, { "code": null, "e": 24426, "s": 24220, "text": "In this article we will see how we can get the current value of the spin box. By default its value is 0 although user can change it any time and programmatically we use setValue method to change its value." }, { "code": null, "e": 24484, "s": 24426, "text": "In order to get the value of spin box we use value method" }, { "code": null, "e": 24506, "s": 24484, "text": "Syntax : spin.value()" }, { "code": null, "e": 24538, "s": 24506, "text": "Argument : It takes no argument" }, { "code": null, "e": 24584, "s": 24538, "text": "Return : It returns integer i.e current value" }, { "code": null, "e": 24607, "s": 24584, "text": "Implementation steps –" }, { "code": null, "e": 24817, "s": 24607, "text": "1. Create a spin box widget2. Create a label to show current value3. Add action to the spin box4. Inside the action get the current value with the help of value method5. Show this value with the help of label." }, { "code": null, "e": 24847, "s": 24817, "text": "Below is the implementation –" }, { "code": "# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import *import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle(\"Python \") # setting geometry self.setGeometry(100, 100, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for widgets def UiComponents(self): # creating spin box self.spin = QSpinBox(self) # setting geometry to spin box self.spin.setGeometry(100, 100, 100, 40) # adding action to the spin box self.spin.valueChanged.connect(self.show_result) # creating label show result self.label = QLabel(self) # setting geometry self.label.setGeometry(100, 200, 200, 40) # method called by spin box def show_result(self): # getting current value value = self.spin.value() # setting value of spin box to the label self.label.setText(\"Value : \" + str(value)) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() window.show() # start the appsys.exit(App.exec())", "e": 26146, "s": 24847, "text": null }, { "code": null, "e": 26155, "s": 26146, "text": "Output :" }, { "code": null, "e": 26175, "s": 26155, "text": "Python PyQt-SpinBox" }, { "code": null, "e": 26186, "s": 26175, "text": "Python-gui" }, { "code": null, "e": 26198, "s": 26186, "text": "Python-PyQt" }, { "code": null, "e": 26205, "s": 26198, "text": "Python" }, { "code": null, "e": 26303, "s": 26205, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26312, "s": 26303, "text": "Comments" }, { "code": null, "e": 26325, "s": 26312, "text": "Old Comments" }, { "code": null, "e": 26343, "s": 26325, "text": "Python Dictionary" }, { "code": null, "e": 26375, "s": 26343, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26410, "s": 26375, "text": "Read a file line by line in Python" }, { "code": null, "e": 26432, "s": 26410, "text": "Enumerate() in Python" }, { "code": null, "e": 26462, "s": 26432, "text": "Iterate over a list in Python" }, { "code": null, "e": 26504, "s": 26462, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 26547, "s": 26504, "text": "Python program to convert a list to string" }, { "code": null, "e": 26584, "s": 26547, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 26610, "s": 26584, "text": "Python String | replace()" } ]
Write a program in Python Pandas to convert a dataframe Celsius data column into Fahrenheit
The result for converting celsius to Fahrenheit as, Id Celsius Fahrenheit 0 1 37.5 99.5 1 2 36.0 96.8 2 3 40.0 104.0 3 4 38.5 101.3 4 5 39.0 102.2 To solve this, we will follow below approaches − Define a dataframe with ‘Id’ and ‘Celsius’ column values Define a dataframe with ‘Id’ and ‘Celsius’ column values Apply df.assign function inside write lambda function to convert celsius values by multiplying (9/5)*df[celsius]+32 and assign it to Fahrenheit. It is defined below − Apply df.assign function inside write lambda function to convert celsius values by multiplying (9/5)*df[celsius]+32 and assign it to Fahrenheit. It is defined below − df.assign(Fahrenheit = lambda x: (9/5)*x['Celsius']+32) Let’s check the following code to get a better understanding − import pandas as pd df = pd.DataFrame({'Id':[1,2,3,4,5], 'Celsius':[37.5,36,40,38.5,39] }) print("DataFrame is\n",df) df = df.assign(Fahrenheit = lambda x: (9/5)*x['Celsius']+32) print(df) DataFrame is Id Celsius 0 1 37.5 1 2 36.0 2 3 40.0 3 4 38.5 4 5 39.0 Id Celsius Fahrenheit 0 1 37.5 99.5 1 2 36.0 96.8 2 3 40.0 104.0 3 4 38.5 101.3 4 5 39.0 102.2 Define a dataframe with ‘Id’ and ‘Celsius’ column values Define a dataframe with ‘Id’ and ‘Celsius’ column values Set df.apply function inside writing lambda function to convert celsius values by multiplying (9/5)*df[celsius]+32 and save it as inside df[Fahrenheit]. It is defined below, Set df.apply function inside writing lambda function to convert celsius values by multiplying (9/5)*df[celsius]+32 and save it as inside df[Fahrenheit]. It is defined below, df['Fahrenheit'] = df.apply(lambda x: (9/5)*x['Celsius']+32,axis=1) Let’s check the following code to get a better understanding − import pandas as pd df = pd.DataFrame({'Id':[1,2,3,4,5], 'Celsius':[37.5,36,40,38.5,39] }) print("DataFrame is\n",df) df['Fahrenheit'] = df.apply(lambda x: (9/5)*x['Celsius']+32,axis=1) print(df) DataFrame is Id Celsius 0 1 37.5 1 2 36.0 2 3 40.0 3 4 38.5 4 5 39.0 Id Celsius Fahrenheit 0 1 37.5 99.5 1 2 36.0 96.8 2 3 40.0 104.0 3 4 38.5 101.3 4 5 39.0 102.2
[ { "code": null, "e": 1114, "s": 1062, "text": "The result for converting celsius to Fahrenheit as," }, { "code": null, "e": 1230, "s": 1114, "text": " Id Celsius Fahrenheit\n0 1 37.5 99.5\n1 2 36.0 96.8\n2 3 40.0 104.0\n3 4 38.5 101.3\n4 5 39.0 102.2" }, { "code": null, "e": 1279, "s": 1230, "text": "To solve this, we will follow below approaches −" }, { "code": null, "e": 1336, "s": 1279, "text": "Define a dataframe with ‘Id’ and ‘Celsius’ column values" }, { "code": null, "e": 1393, "s": 1336, "text": "Define a dataframe with ‘Id’ and ‘Celsius’ column values" }, { "code": null, "e": 1560, "s": 1393, "text": "Apply df.assign function inside write lambda function to convert celsius values by multiplying (9/5)*df[celsius]+32 and assign it to Fahrenheit. It is defined below −" }, { "code": null, "e": 1727, "s": 1560, "text": "Apply df.assign function inside write lambda function to convert celsius values by multiplying (9/5)*df[celsius]+32 and assign it to Fahrenheit. It is defined below −" }, { "code": null, "e": 1783, "s": 1727, "text": "df.assign(Fahrenheit = lambda x: (9/5)*x['Celsius']+32)" }, { "code": null, "e": 1846, "s": 1783, "text": "Let’s check the following code to get a better understanding −" }, { "code": null, "e": 2074, "s": 1846, "text": "import pandas as pd\ndf = pd.DataFrame({'Id':[1,2,3,4,5],\n 'Celsius':[37.5,36,40,38.5,39]\n })\nprint(\"DataFrame is\\n\",df)\ndf = df.assign(Fahrenheit = lambda x: (9/5)*x['Celsius']+32)\nprint(df)" }, { "code": null, "e": 2260, "s": 2074, "text": "DataFrame is\n Id Celsius\n0 1 37.5\n1 2 36.0\n2 3 40.0\n3 4 38.5\n4 5 39.0\n Id Celsius Fahrenheit\n0 1 37.5 99.5\n1 2 36.0 96.8\n2 3 40.0 104.0\n3 4 38.5 101.3\n4 5 39.0 102.2" }, { "code": null, "e": 2317, "s": 2260, "text": "Define a dataframe with ‘Id’ and ‘Celsius’ column values" }, { "code": null, "e": 2374, "s": 2317, "text": "Define a dataframe with ‘Id’ and ‘Celsius’ column values" }, { "code": null, "e": 2548, "s": 2374, "text": "Set df.apply function inside writing lambda function to convert celsius values by multiplying (9/5)*df[celsius]+32 and save it as inside df[Fahrenheit]. It is defined below," }, { "code": null, "e": 2722, "s": 2548, "text": "Set df.apply function inside writing lambda function to convert celsius values by multiplying (9/5)*df[celsius]+32 and save it as inside df[Fahrenheit]. It is defined below," }, { "code": null, "e": 2790, "s": 2722, "text": "df['Fahrenheit'] = df.apply(lambda x: (9/5)*x['Celsius']+32,axis=1)" }, { "code": null, "e": 2853, "s": 2790, "text": "Let’s check the following code to get a better understanding −" }, { "code": null, "e": 3088, "s": 2853, "text": "import pandas as pd\ndf = pd.DataFrame({'Id':[1,2,3,4,5],\n 'Celsius':[37.5,36,40,38.5,39]\n })\nprint(\"DataFrame is\\n\",df)\ndf['Fahrenheit'] = df.apply(lambda x: (9/5)*x['Celsius']+32,axis=1)\nprint(df)" }, { "code": null, "e": 3274, "s": 3088, "text": "DataFrame is\n Id Celsius\n0 1 37.5\n1 2 36.0\n2 3 40.0\n3 4 38.5\n4 5 39.0\n Id Celsius Fahrenheit\n0 1 37.5 99.5\n1 2 36.0 96.8\n2 3 40.0 104.0\n3 4 38.5 101.3\n4 5 39.0 102.2" } ]
ArangoDB - AQL Example Queries
In this chapter, we will consider a few AQL Example Queries on an Actors and Movies Database. These queries are based on graphs. Given a collection of actors and a collection of movies, and an actIn edges collection (with a year property) to connect the vertex as indicated below − [Actor] <- act in -> [Movie] How do we get − All actors who acted in "movie1" OR "movie2"? All actors who acted in both "movie1" AND "movie2”? All common movies between "actor1" and "actor2”? All actors who acted in 3 or more movies? All movies where exactly 6 actors acted in? The number of actors by movie? The number of movies by actor? The number of movies acted in between 2005 and 2010 by actor? During the process of solving and obtaining the answers to the above queries, we will use Arangosh to create the dataset and run queries on that. All the AQL queries are strings and can simply be copied over to your favorite driver instead of Arangosh. Let us start by creating a Test Dataset in Arangosh. First, download this file − # wget -O dataset.js https://drive.google.com/file/d/0B4WLtBDZu_QWMWZYZ3pYMEdqajA/view?usp=sharing ... HTTP request sent, awaiting response... 200 OK Length: unspecified [text/html] Saving to: ‘dataset.js’ dataset.js [ <=> ] 115.14K --.-KB/s in 0.01s 2017-09-17 14:19:12 (11.1 MB/s) - ‘dataset.js’ saved [117907] You can see in the output above that we have downloaded a JavaScript file dataset.js. This file contains the Arangosh commands to create the dataset in the database. Instead of copying and pasting the commands one by one, we will use the --javascript.execute option on Arangosh to execute the multiple commands non-interactively. Consider it the life saver command! Now execute the following command on the shell − $ arangosh --javascript.execute dataset.js Supply the password when prompted as you can see in the above screenshot. Now we have saved the data, so we will construct the AQL queries to answer the specific questions raised in the beginning of this chapter. Let us take the first question: All actors who acted in "movie1" OR "movie2". Suppose, we want to find the names of all the actors who acted in "TheMatrix" OR "TheDevilsAdvocate" − We will start with one movie at a time to get the names of the actors − 127.0.0.1:8529@_system> db._query("FOR x IN ANY 'movies/TheMatrix' actsIn OPTIONS {bfs: true, uniqueVertices: 'global'} RETURN x._id").toArray(); We will receive the following output − [ "actors/Hugo", "actors/Emil", "actors/Carrie", "actors/Keanu", "actors/Laurence" ] Now we continue to form a UNION_DISTINCT of two NEIGHBORS queries which will be the solution − 127.0.0.1:8529@_system> db._query("FOR x IN UNION_DISTINCT ((FOR y IN ANY 'movies/TheMatrix' actsIn OPTIONS {bfs: true, uniqueVertices: 'global'} RETURN y._id), (FOR y IN ANY 'movies/TheDevilsAdvocate' actsIn OPTIONS {bfs: true, uniqueVertices: 'global'} RETURN y._id)) RETURN x").toArray(); [ "actors/Charlize", "actors/Al", "actors/Laurence", "actors/Keanu", "actors/Carrie", "actors/Emil", "actors/Hugo" ] Let us now consider the second question: All actors who acted in both "movie1" AND "movie2". This is almost identical to the question above. But this time we are not interested in a UNION but in an INTERSECTION − 127.0.0.1:8529@_system> db._query("FOR x IN INTERSECTION ((FOR y IN ANY 'movies/TheMatrix' actsIn OPTIONS {bfs: true, uniqueVertices: 'global'} RETURN y._id), (FOR y IN ANY 'movies/TheDevilsAdvocate' actsIn OPTIONS {bfs: true, uniqueVertices: 'global'} RETURN y._id)) RETURN x").toArray(); We will receive the following output − [ "actors/Keanu" ] Let us now consider the third question: All common movies between "actor1" and "actor2". This is actually identical to the question about common actors in movie1 and movie2. We just have to change the starting vertices. As an example, let us find all the movies where Hugo Weaving ("Hugo") and Keanu Reeves are co-starring − 127.0.0.1:8529@_system> db._query( "FOR x IN INTERSECTION ( ( FOR y IN ANY 'actors/Hugo' actsIn OPTIONS {bfs: true, uniqueVertices: 'global'} RETURN y._id ), ( FOR y IN ANY 'actors/Keanu' actsIn OPTIONS {bfs: true, uniqueVertices:'global'} RETURN y._id ) ) RETURN x").toArray(); We will receive the following output − [ "movies/TheMatrixReloaded", "movies/TheMatrixRevolutions", "movies/TheMatrix" ] Let us now consider the fourth question. All actors who acted in 3 or more movies. This question is different; we cannot make use of the neighbors function here. Instead we will make use of the edge-index and the COLLECT statement of AQL for grouping. The basic idea is to group all edges by their startVertex (which in this dataset is always the actor). Then we remove all actors with less than 3 movies from the result as here we have included the number of movies an actor has acted in − 127.0.0.1:8529@_system> db._query("FOR x IN actsIn COLLECT actor = x._from WITH COUNT INTO counter FILTER counter >= 3 RETURN {actor: actor, movies: counter}"). toArray() [ { "actor" : "actors/Carrie", "movies" : 3 }, { "actor" : "actors/CubaG", "movies" : 4 }, { "actor" : "actors/Hugo", "movies" : 3 }, { "actor" : "actors/Keanu", "movies" : 4 }, { "actor" : "actors/Laurence", "movies" : 3 }, { "actor" : "actors/MegR", "movies" : 5 }, { "actor" : "actors/TomC", "movies" : 3 }, { "actor" : "actors/TomH", "movies" : 3 } ] For the remaining questions, we will discuss the query formation, and provide the queries only. The reader should run the query themselves on the Arangosh terminal. Let us now consider the fifth question: All movies where exactly 6 actors acted in. The same idea as in the query before, but with the equality filter. However, now we need the movie instead of the actor, so we return the _to attribute − db._query("FOR x IN actsIn COLLECT movie = x._to WITH COUNT INTO counter FILTER counter == 6 RETURN movie").toArray() The number of actors by movie? We remember in our dataset _to on the edge corresponds to the movie, so we count how often the same _to appears. This is the number of actors. The query is almost identical to the ones before but without the FILTER after COLLECT − db._query("FOR x IN actsIn COLLECT movie = x._to WITH COUNT INTO counter RETURN {movie: movie, actors: counter}").toArray() Let us now consider the sixth question: The number of movies by an actor. The way we found solutions to our above queries will help you find the solution to this query as well. db._query("FOR x IN actsIn COLLECT actor = x._from WITH COUNT INTO counter RETURN {actor: actor, movies: counter}").toArray() Print Add Notes Bookmark this page
[ { "code": null, "e": 2109, "s": 1980, "text": "In this chapter, we will consider a few AQL Example Queries on an Actors and Movies Database. These queries are based on graphs." }, { "code": null, "e": 2262, "s": 2109, "text": "Given a collection of actors and a collection of movies, and an actIn edges collection (with a year property) to connect the vertex as indicated below −" }, { "code": null, "e": 2291, "s": 2262, "text": "[Actor] <- act in -> [Movie]" }, { "code": null, "e": 2307, "s": 2291, "text": "How do we get −" }, { "code": null, "e": 2353, "s": 2307, "text": "All actors who acted in \"movie1\" OR \"movie2\"?" }, { "code": null, "e": 2405, "s": 2353, "text": "All actors who acted in both \"movie1\" AND \"movie2”?" }, { "code": null, "e": 2454, "s": 2405, "text": "All common movies between \"actor1\" and \"actor2”?" }, { "code": null, "e": 2496, "s": 2454, "text": "All actors who acted in 3 or more movies?" }, { "code": null, "e": 2540, "s": 2496, "text": "All movies where exactly 6 actors acted in?" }, { "code": null, "e": 2571, "s": 2540, "text": "The number of actors by movie?" }, { "code": null, "e": 2602, "s": 2571, "text": "The number of movies by actor?" }, { "code": null, "e": 2664, "s": 2602, "text": "The number of movies acted in between 2005 and 2010 by actor?" }, { "code": null, "e": 2917, "s": 2664, "text": "During the process of solving and obtaining the answers to the above queries, we will use Arangosh to create the dataset and run queries on that. All the AQL queries are strings and can simply be copied over to your favorite driver instead of Arangosh." }, { "code": null, "e": 2998, "s": 2917, "text": "Let us start by creating a Test Dataset in Arangosh. First, download this file −" }, { "code": null, "e": 3098, "s": 2998, "text": "# wget -O dataset.js\nhttps://drive.google.com/file/d/0B4WLtBDZu_QWMWZYZ3pYMEdqajA/view?usp=sharing\n" }, { "code": null, "e": 3313, "s": 3098, "text": "...\nHTTP request sent, awaiting response... 200 OK\nLength: unspecified [text/html]\nSaving to: ‘dataset.js’\ndataset.js [ <=> ] 115.14K --.-KB/s in 0.01s\n2017-09-17 14:19:12 (11.1 MB/s) - ‘dataset.js’ saved [117907]\n" }, { "code": null, "e": 3679, "s": 3313, "text": "You can see in the output above that we have downloaded a JavaScript file dataset.js. This file contains the Arangosh commands to create the dataset in the database. Instead of copying and pasting the commands one by one, we will use the --javascript.execute option on Arangosh to execute the multiple commands non-interactively. Consider it the life saver command!" }, { "code": null, "e": 3728, "s": 3679, "text": "Now execute the following command on the shell −" }, { "code": null, "e": 3772, "s": 3728, "text": "$ arangosh --javascript.execute dataset.js\n" }, { "code": null, "e": 3985, "s": 3772, "text": "Supply the password when prompted as you can see in the above screenshot. Now we have saved the data, so we will construct the AQL queries to answer the specific questions raised in the beginning of this chapter." }, { "code": null, "e": 4166, "s": 3985, "text": "Let us take the first question: All actors who acted in \"movie1\" OR \"movie2\". Suppose, we want to find the names of all the actors who acted in \"TheMatrix\" OR \"TheDevilsAdvocate\" −" }, { "code": null, "e": 4238, "s": 4166, "text": "We will start with one movie at a time to get the names of the actors −" }, { "code": null, "e": 4385, "s": 4238, "text": "127.0.0.1:8529@_system> db._query(\"FOR x IN ANY 'movies/TheMatrix' actsIn\nOPTIONS {bfs: true, uniqueVertices: 'global'} RETURN x._id\").toArray();\n" }, { "code": null, "e": 4424, "s": 4385, "text": "We will receive the following output −" }, { "code": null, "e": 4525, "s": 4424, "text": "[\n \"actors/Hugo\",\n \"actors/Emil\",\n \"actors/Carrie\",\n \"actors/Keanu\",\n \"actors/Laurence\"\n]\n" }, { "code": null, "e": 4620, "s": 4525, "text": "Now we continue to form a UNION_DISTINCT of two NEIGHBORS queries which will be the solution −" }, { "code": null, "e": 4913, "s": 4620, "text": "127.0.0.1:8529@_system> db._query(\"FOR x IN UNION_DISTINCT ((FOR y IN ANY\n'movies/TheMatrix' actsIn OPTIONS {bfs: true, uniqueVertices: 'global'} RETURN\ny._id), (FOR y IN ANY 'movies/TheDevilsAdvocate' actsIn OPTIONS {bfs: true,\nuniqueVertices: 'global'} RETURN y._id)) RETURN x\").toArray();\n" }, { "code": null, "e": 5052, "s": 4913, "text": "[\n \"actors/Charlize\",\n \"actors/Al\",\n \"actors/Laurence\",\n \"actors/Keanu\",\n \"actors/Carrie\",\n \"actors/Emil\",\n \"actors/Hugo\"\n]\n" }, { "code": null, "e": 5265, "s": 5052, "text": "Let us now consider the second question: All actors who acted in both \"movie1\" AND \"movie2\". This is almost identical to the question above. But this time we are not interested in a UNION but in an INTERSECTION −" }, { "code": null, "e": 5556, "s": 5265, "text": "127.0.0.1:8529@_system> db._query(\"FOR x IN INTERSECTION ((FOR y IN ANY\n'movies/TheMatrix' actsIn OPTIONS {bfs: true, uniqueVertices: 'global'} RETURN\ny._id), (FOR y IN ANY 'movies/TheDevilsAdvocate' actsIn OPTIONS {bfs: true,\nuniqueVertices: 'global'} RETURN y._id)) RETURN x\").toArray();\n" }, { "code": null, "e": 5595, "s": 5556, "text": "We will receive the following output −" }, { "code": null, "e": 5618, "s": 5595, "text": "[\n \"actors/Keanu\"\n]\n" }, { "code": null, "e": 5943, "s": 5618, "text": "Let us now consider the third question: All common movies between \"actor1\" and \"actor2\". This is actually identical to the question about common actors in movie1 and movie2. We just have to change the starting vertices. As an example, let us find all the movies where Hugo Weaving (\"Hugo\") and Keanu Reeves are co-starring −" }, { "code": null, "e": 6312, "s": 5943, "text": "127.0.0.1:8529@_system> db._query(\n \"FOR x IN INTERSECTION (\n (\n FOR y IN ANY 'actors/Hugo' actsIn OPTIONS \n {bfs: true, uniqueVertices: 'global'}\n RETURN y._id\n ),\n \n (\n FOR y IN ANY 'actors/Keanu' actsIn OPTIONS \n {bfs: true, uniqueVertices:'global'} RETURN y._id\n )\n ) \n RETURN x\").toArray();\n" }, { "code": null, "e": 6351, "s": 6312, "text": "We will receive the following output −" }, { "code": null, "e": 6443, "s": 6351, "text": "[\n \"movies/TheMatrixReloaded\",\n \"movies/TheMatrixRevolutions\",\n \"movies/TheMatrix\"\n]\n" }, { "code": null, "e": 6934, "s": 6443, "text": "Let us now consider the fourth question. All actors who acted in 3 or more movies. This question is different; we cannot make use of the neighbors function here. Instead we will make use of the edge-index and the COLLECT statement of AQL for grouping. The basic idea is to group all edges by their startVertex (which in this dataset is always the actor). Then we remove all actors with less than 3 movies from the result as here we have included the number of movies an actor has acted in −" }, { "code": null, "e": 7106, "s": 6934, "text": "127.0.0.1:8529@_system> db._query(\"FOR x IN actsIn COLLECT actor = x._from WITH\nCOUNT INTO counter FILTER counter >= 3 RETURN {actor: actor, movies:\ncounter}\"). toArray()\n" }, { "code": null, "e": 7619, "s": 7106, "text": "[\n {\n \"actor\" : \"actors/Carrie\",\n \"movies\" : 3\n },\n \n {\n \"actor\" : \"actors/CubaG\",\n \"movies\" : 4\n },\n\n {\n \"actor\" : \"actors/Hugo\",\n \"movies\" : 3\n },\n\n {\n \"actor\" : \"actors/Keanu\",\n \"movies\" : 4\n },\n\n {\n \"actor\" : \"actors/Laurence\",\n \"movies\" : 3\n },\n\n {\n \"actor\" : \"actors/MegR\",\n \"movies\" : 5\n },\n\n {\n \"actor\" : \"actors/TomC\",\n \"movies\" : 3\n },\n \n {\n \"actor\" : \"actors/TomH\",\n \"movies\" : 3\n }\n]\n" }, { "code": null, "e": 7784, "s": 7619, "text": "For the remaining questions, we will discuss the query formation, and provide the queries only. The reader should run the query themselves on the Arangosh terminal." }, { "code": null, "e": 8022, "s": 7784, "text": "Let us now consider the fifth question: All movies where exactly 6 actors acted in. The same idea as in the query before, but with the equality filter. However, now we need the movie instead of the actor, so we return the _to attribute −" }, { "code": null, "e": 8141, "s": 8022, "text": "db._query(\"FOR x IN actsIn COLLECT movie = x._to WITH COUNT INTO counter FILTER\ncounter == 6 RETURN movie\").toArray()\n" }, { "code": null, "e": 8172, "s": 8141, "text": "The number of actors by movie?" }, { "code": null, "e": 8403, "s": 8172, "text": "We remember in our dataset _to on the edge corresponds to the movie, so we count how\noften the same _to appears. This is the number of actors. The query is almost identical to\nthe ones before but without the FILTER after COLLECT −" }, { "code": null, "e": 8528, "s": 8403, "text": "db._query(\"FOR x IN actsIn COLLECT movie = x._to WITH COUNT INTO counter RETURN\n{movie: movie, actors: counter}\").toArray()\n" }, { "code": null, "e": 8602, "s": 8528, "text": "Let us now consider the sixth question: The number of movies by an actor." }, { "code": null, "e": 8705, "s": 8602, "text": "The way we found solutions to our above queries will help you find the solution to this query as well." }, { "code": null, "e": 8832, "s": 8705, "text": "db._query(\"FOR x IN actsIn COLLECT actor = x._from WITH COUNT INTO counter\nRETURN {actor: actor, movies: counter}\").toArray()\n" }, { "code": null, "e": 8839, "s": 8832, "text": " Print" }, { "code": null, "e": 8850, "s": 8839, "text": " Add Notes" } ]
Creating a Simple Map with Folium and Python | by Liam Connors | Towards Data Science
Often when working with data you will have access to geospatial features such as latitude and longitude coordinates. It can be interesting to map these to get an idea of how instances of a data set are spread across different locations. In this short article, I walk through the steps I took to get bike rental location data and show the locations on a map. I use Dublin Bikes data (https://data.smartdublin.ie/dataset/dublinbikes-api) and the Folium library (https://python-visualization.github.io/folium/), which, as the documentation says, “builds on the data wrangling strengths of the Python ecosystem and the mapping strengths of the leaflet.js library”. More information on Leaflet can be found in the docs here. I used Python 3.7, Folium 0.12.1 and Pandas 1.2.4. I also use Jupyter Notebooks in Anaconda Navigator. The data I am working with is from the Dublin Bikes API, specifically the location of bike rental stations: https://data.smartdublin.ie/dataset/33ec9fe2-4957-4e9a-ab55-c5e917c7a9ab/resource/2dec86ed-76ed-47a3-ae28-646db5c5b965/download/dublin.csv There is lots of other interesting data available in relation to Dublin Bikes data, including data on bike usage. Something I would like to explore in the future. The first step, as always, is importing the libraries: import pandas as pdimport folium Using Pandas I go direct to the location of the CSV file I want: location = "https://data.smartdublin.ie/dataset/33ec9fe2-4957-4e9a-ab55-c5e917c7a9ab/resource/2dec86ed-76ed-47a3-ae28-646db5c5b965/download/dublin.csv"bike_station_locations = pd.read_csv(location) Now I have the bike_station_locations dataframe: I want to keep the Latitude, Longitude and the Name of the location. The former two columns will allow me to map the locations and the latter I will use to give each location pin a name: bike_station_locations = bike_station_locations[["Latitude", "Longitude", "Name"]] For the map, the first step is to create a map of the location I want. Using the location parameter, I pass in the mean of the latitude and longitude coordinates I have to centre the map there. map = folium.Map(location=[bike_station_locations.Latitude.mean(), bike_station_locations.Longitude.mean()], zoom_start=14, control_scale=True This gives a blank map centered on the location previously given and zoomed to 14. Now I add the points for each bike station location to the map. Iterating through each row of the dataframe, I pass the location latitude and longitudes to folium.Marker as a list and pass the name to the popup parameter. And for each location I add to map: for index, location_info in bike_station_locations.iterrows(): folium.Marker([location_info["Latitude"], location_info["Longitude"]], popup=location_info["Name"]).add_to(map) I then display the map: Note: The maps use an OpenStreetMap tile by default, though other options can be used by adding the parameter tiles parameter and value when creating the map. There are examples in the docs here. More information on OpenStreetMap can be found here. Using Folium with Python is a great way to get stared with mapping geospatial data. With a few lines of code it is possible to put together basic maps. There are many other options available and the documentation is well worth exploring. Jupyter Notebook available here. All screenshots taken by the author. Introductory image by Calvin Hanson on Unsplash.
[ { "code": null, "e": 409, "s": 172, "text": "Often when working with data you will have access to geospatial features such as latitude and longitude coordinates. It can be interesting to map these to get an idea of how instances of a data set are spread across different locations." }, { "code": null, "e": 892, "s": 409, "text": "In this short article, I walk through the steps I took to get bike rental location data and show the locations on a map. I use Dublin Bikes data (https://data.smartdublin.ie/dataset/dublinbikes-api) and the Folium library (https://python-visualization.github.io/folium/), which, as the documentation says, “builds on the data wrangling strengths of the Python ecosystem and the mapping strengths of the leaflet.js library”. More information on Leaflet can be found in the docs here." }, { "code": null, "e": 995, "s": 892, "text": "I used Python 3.7, Folium 0.12.1 and Pandas 1.2.4. I also use Jupyter Notebooks in Anaconda Navigator." }, { "code": null, "e": 1103, "s": 995, "text": "The data I am working with is from the Dublin Bikes API, specifically the location of bike rental stations:" }, { "code": null, "e": 1242, "s": 1103, "text": "https://data.smartdublin.ie/dataset/33ec9fe2-4957-4e9a-ab55-c5e917c7a9ab/resource/2dec86ed-76ed-47a3-ae28-646db5c5b965/download/dublin.csv" }, { "code": null, "e": 1405, "s": 1242, "text": "There is lots of other interesting data available in relation to Dublin Bikes data, including data on bike usage. Something I would like to explore in the future." }, { "code": null, "e": 1460, "s": 1405, "text": "The first step, as always, is importing the libraries:" }, { "code": null, "e": 1493, "s": 1460, "text": "import pandas as pdimport folium" }, { "code": null, "e": 1558, "s": 1493, "text": "Using Pandas I go direct to the location of the CSV file I want:" }, { "code": null, "e": 1756, "s": 1558, "text": "location = \"https://data.smartdublin.ie/dataset/33ec9fe2-4957-4e9a-ab55-c5e917c7a9ab/resource/2dec86ed-76ed-47a3-ae28-646db5c5b965/download/dublin.csv\"bike_station_locations = pd.read_csv(location)" }, { "code": null, "e": 1805, "s": 1756, "text": "Now I have the bike_station_locations dataframe:" }, { "code": null, "e": 1992, "s": 1805, "text": "I want to keep the Latitude, Longitude and the Name of the location. The former two columns will allow me to map the locations and the latter I will use to give each location pin a name:" }, { "code": null, "e": 2075, "s": 1992, "text": "bike_station_locations = bike_station_locations[[\"Latitude\", \"Longitude\", \"Name\"]]" }, { "code": null, "e": 2269, "s": 2075, "text": "For the map, the first step is to create a map of the location I want. Using the location parameter, I pass in the mean of the latitude and longitude coordinates I have to centre the map there." }, { "code": null, "e": 2412, "s": 2269, "text": "map = folium.Map(location=[bike_station_locations.Latitude.mean(), bike_station_locations.Longitude.mean()], zoom_start=14, control_scale=True" }, { "code": null, "e": 2495, "s": 2412, "text": "This gives a blank map centered on the location previously given and zoomed to 14." }, { "code": null, "e": 2753, "s": 2495, "text": "Now I add the points for each bike station location to the map. Iterating through each row of the dataframe, I pass the location latitude and longitudes to folium.Marker as a list and pass the name to the popup parameter. And for each location I add to map:" }, { "code": null, "e": 2931, "s": 2753, "text": "for index, location_info in bike_station_locations.iterrows(): folium.Marker([location_info[\"Latitude\"], location_info[\"Longitude\"]], popup=location_info[\"Name\"]).add_to(map)" }, { "code": null, "e": 2955, "s": 2931, "text": "I then display the map:" }, { "code": null, "e": 3151, "s": 2955, "text": "Note: The maps use an OpenStreetMap tile by default, though other options can be used by adding the parameter tiles parameter and value when creating the map. There are examples in the docs here." }, { "code": null, "e": 3204, "s": 3151, "text": "More information on OpenStreetMap can be found here." }, { "code": null, "e": 3442, "s": 3204, "text": "Using Folium with Python is a great way to get stared with mapping geospatial data. With a few lines of code it is possible to put together basic maps. There are many other options available and the documentation is well worth exploring." }, { "code": null, "e": 3475, "s": 3442, "text": "Jupyter Notebook available here." } ]
Spark - Installation
Spark is Hadoop’s sub-project. Therefore, it is better to install Spark into a Linux based system. The following steps show how to install Apache Spark. Java installation is one of the mandatory things in installing Spark. Try the following command to verify the JAVA version. $java -version If Java is already, installed on your system, you get to see the following response − java version "1.7.0_71" Java(TM) SE Runtime Environment (build 1.7.0_71-b13) Java HotSpot(TM) Client VM (build 25.0-b02, mixed mode) In case you do not have Java installed on your system, then Install Java before proceeding to next step. You should Scala language to implement Spark. So let us verify Scala installation using following command. $scala -version If Scala is already installed on your system, you get to see the following response − Scala code runner version 2.11.6 -- Copyright 2002-2013, LAMP/EPFL In case you don’t have Scala installed on your system, then proceed to next step for Scala installation. Download the latest version of Scala by visit the following link Download Scala. For this tutorial, we are using scala-2.11.6 version. After downloading, you will find the Scala tar file in the download folder. Follow the below given steps for installing Scala. Type the following command for extracting the Scala tar file. $ tar xvf scala-2.11.6.tgz Use the following commands for moving the Scala software files, to respective directory (/usr/local/scala). $ su – Password: # cd /home/Hadoop/Downloads/ # mv scala-2.11.6 /usr/local/scala # exit Use the following command for setting PATH for Scala. $ export PATH = $PATH:/usr/local/scala/bin After installation, it is better to verify it. Use the following command for verifying Scala installation. $scala -version If Scala is already installed on your system, you get to see the following response − Scala code runner version 2.11.6 -- Copyright 2002-2013, LAMP/EPFL Download the latest version of Spark by visiting the following link Download Spark. For this tutorial, we are using spark-1.3.1-bin-hadoop2.6 version. After downloading it, you will find the Spark tar file in the download folder. Follow the steps given below for installing Spark. The following command for extracting the spark tar file. $ tar xvf spark-1.3.1-bin-hadoop2.6.tgz The following commands for moving the Spark software files to respective directory (/usr/local/spark). $ su – Password: # cd /home/Hadoop/Downloads/ # mv spark-1.3.1-bin-hadoop2.6 /usr/local/spark # exit Add the following line to ~/.bashrc file. It means adding the location, where the spark software file are located to the PATH variable. export PATH = $PATH:/usr/local/spark/bin Use the following command for sourcing the ~/.bashrc file. $ source ~/.bashrc Write the following command for opening Spark shell. $spark-shell If spark is installed successfully then you will find the following output. Spark assembly has been built with Hive, including Datanucleus jars on classpath Using Spark's default log4j profile: org/apache/spark/log4j-defaults.properties 15/06/04 15:25:22 INFO SecurityManager: Changing view acls to: hadoop 15/06/04 15:25:22 INFO SecurityManager: Changing modify acls to: hadoop disabled; ui acls disabled; users with view permissions: Set(hadoop); users with modify permissions: Set(hadoop) 15/06/04 15:25:22 INFO HttpServer: Starting HTTP Server 15/06/04 15:25:23 INFO Utils: Successfully started service 'HTTP class server' on port 43292. Welcome to ____ __ / __/__ ___ _____/ /__ _\ \/ _ \/ _ `/ __/ '_/ /___/ .__/\_,_/_/ /_/\_\ version 1.4.0 /_/ Using Scala version 2.10.4 (Java HotSpot(TM) 64-Bit Server VM, Java 1.7.0_71) Type in expressions to have them evaluated. Spark context available as sc scala> 46 Lectures 3.5 hours Arnab Chakraborty 31 Lectures 1 hours Frahaan Hussain 12 Lectures 1 hours Pranjal Srivastava 23 Lectures 1.5 hours Mukund Kumar Mishra 52 Lectures 1.5 hours Bigdata Engineer 23 Lectures 1 hours Bigdata Engineer Print Add Notes Bookmark this page
[ { "code": null, "e": 1873, "s": 1720, "text": "Spark is Hadoop’s sub-project. Therefore, it is better to install Spark into a Linux based system. The following steps show how to install Apache Spark." }, { "code": null, "e": 1997, "s": 1873, "text": "Java installation is one of the mandatory things in installing Spark. Try the following command to verify the JAVA version." }, { "code": null, "e": 2013, "s": 1997, "text": "$java -version\n" }, { "code": null, "e": 2099, "s": 2013, "text": "If Java is already, installed on your system, you get to see the following response −" }, { "code": null, "e": 2233, "s": 2099, "text": "java version \"1.7.0_71\"\nJava(TM) SE Runtime Environment (build 1.7.0_71-b13)\nJava HotSpot(TM) Client VM (build 25.0-b02, mixed mode)\n" }, { "code": null, "e": 2338, "s": 2233, "text": "In case you do not have Java installed on your system, then Install Java before proceeding to next step." }, { "code": null, "e": 2445, "s": 2338, "text": "You should Scala language to implement Spark. So let us verify Scala installation using following command." }, { "code": null, "e": 2462, "s": 2445, "text": "$scala -version\n" }, { "code": null, "e": 2548, "s": 2462, "text": "If Scala is already installed on your system, you get to see the following response −" }, { "code": null, "e": 2616, "s": 2548, "text": "Scala code runner version 2.11.6 -- Copyright 2002-2013, LAMP/EPFL\n" }, { "code": null, "e": 2721, "s": 2616, "text": "In case you don’t have Scala installed on your system, then proceed to next step for Scala installation." }, { "code": null, "e": 2932, "s": 2721, "text": "Download the latest version of Scala by visit the following link Download Scala. For this tutorial, we are using scala-2.11.6 version. After downloading, you will find the Scala tar file in the download folder." }, { "code": null, "e": 2983, "s": 2932, "text": "Follow the below given steps for installing Scala." }, { "code": null, "e": 3045, "s": 2983, "text": "Type the following command for extracting the Scala tar file." }, { "code": null, "e": 3073, "s": 3045, "text": "$ tar xvf scala-2.11.6.tgz\n" }, { "code": null, "e": 3181, "s": 3073, "text": "Use the following commands for moving the Scala software files, to respective directory (/usr/local/scala)." }, { "code": null, "e": 3270, "s": 3181, "text": "$ su –\nPassword:\n# cd /home/Hadoop/Downloads/\n# mv scala-2.11.6 /usr/local/scala\n# exit\n" }, { "code": null, "e": 3324, "s": 3270, "text": "Use the following command for setting PATH for Scala." }, { "code": null, "e": 3368, "s": 3324, "text": "$ export PATH = $PATH:/usr/local/scala/bin\n" }, { "code": null, "e": 3475, "s": 3368, "text": "After installation, it is better to verify it. Use the following command for verifying Scala installation." }, { "code": null, "e": 3492, "s": 3475, "text": "$scala -version\n" }, { "code": null, "e": 3578, "s": 3492, "text": "If Scala is already installed on your system, you get to see the following response −" }, { "code": null, "e": 3646, "s": 3578, "text": "Scala code runner version 2.11.6 -- Copyright 2002-2013, LAMP/EPFL\n" }, { "code": null, "e": 3876, "s": 3646, "text": "Download the latest version of Spark by visiting the following link Download Spark. For this tutorial, we are using spark-1.3.1-bin-hadoop2.6 version. After downloading it, you will find the Spark tar file in the download folder." }, { "code": null, "e": 3927, "s": 3876, "text": "Follow the steps given below for installing Spark." }, { "code": null, "e": 3984, "s": 3927, "text": "The following command for extracting the spark tar file." }, { "code": null, "e": 4025, "s": 3984, "text": "$ tar xvf spark-1.3.1-bin-hadoop2.6.tgz\n" }, { "code": null, "e": 4128, "s": 4025, "text": "The following commands for moving the Spark software files to respective directory (/usr/local/spark)." }, { "code": null, "e": 4230, "s": 4128, "text": "$ su –\nPassword:\n# cd /home/Hadoop/Downloads/\n# mv spark-1.3.1-bin-hadoop2.6 /usr/local/spark\n# exit\n" }, { "code": null, "e": 4366, "s": 4230, "text": "Add the following line to ~/.bashrc file. It means adding the location, where the spark software file are located to the PATH variable." }, { "code": null, "e": 4408, "s": 4366, "text": "export PATH = $PATH:/usr/local/spark/bin\n" }, { "code": null, "e": 4467, "s": 4408, "text": "Use the following command for sourcing the ~/.bashrc file." }, { "code": null, "e": 4487, "s": 4467, "text": "$ source ~/.bashrc\n" }, { "code": null, "e": 4540, "s": 4487, "text": "Write the following command for opening Spark shell." }, { "code": null, "e": 4554, "s": 4540, "text": "$spark-shell\n" }, { "code": null, "e": 4630, "s": 4554, "text": "If spark is installed successfully then you will find the following output." }, { "code": null, "e": 5499, "s": 4630, "text": "Spark assembly has been built with Hive, including Datanucleus jars on classpath\nUsing Spark's default log4j profile: org/apache/spark/log4j-defaults.properties\n15/06/04 15:25:22 INFO SecurityManager: Changing view acls to: hadoop\n15/06/04 15:25:22 INFO SecurityManager: Changing modify acls to: hadoop\ndisabled; ui acls disabled; users with view permissions: Set(hadoop); users with modify permissions: Set(hadoop)\n15/06/04 15:25:22 INFO HttpServer: Starting HTTP Server\n15/06/04 15:25:23 INFO Utils: Successfully started service 'HTTP class server' on port 43292.\nWelcome to\n ____ __\n / __/__ ___ _____/ /__\n _\\ \\/ _ \\/ _ `/ __/ '_/\n /___/ .__/\\_,_/_/ /_/\\_\\ version 1.4.0\n /_/\n\t\t\nUsing Scala version 2.10.4 (Java HotSpot(TM) 64-Bit Server VM, Java 1.7.0_71)\nType in expressions to have them evaluated.\nSpark context available as sc\nscala>\n" }, { "code": null, "e": 5534, "s": 5499, "text": "\n 46 Lectures \n 3.5 hours \n" }, { "code": null, "e": 5553, "s": 5534, "text": " Arnab Chakraborty" }, { "code": null, "e": 5586, "s": 5553, "text": "\n 31 Lectures \n 1 hours \n" }, { "code": null, "e": 5603, "s": 5586, "text": " Frahaan Hussain" }, { "code": null, "e": 5636, "s": 5603, "text": "\n 12 Lectures \n 1 hours \n" }, { "code": null, "e": 5656, "s": 5636, "text": " Pranjal Srivastava" }, { "code": null, "e": 5691, "s": 5656, "text": "\n 23 Lectures \n 1.5 hours \n" }, { "code": null, "e": 5712, "s": 5691, "text": " Mukund Kumar Mishra" }, { "code": null, "e": 5747, "s": 5712, "text": "\n 52 Lectures \n 1.5 hours \n" }, { "code": null, "e": 5765, "s": 5747, "text": " Bigdata Engineer" }, { "code": null, "e": 5798, "s": 5765, "text": "\n 23 Lectures \n 1 hours \n" }, { "code": null, "e": 5816, "s": 5798, "text": " Bigdata Engineer" }, { "code": null, "e": 5823, "s": 5816, "text": " Print" }, { "code": null, "e": 5834, "s": 5823, "text": " Add Notes" } ]
W3.CSS Examples
We just launchedW3Schools videos Get certifiedby completinga course today! If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail: help@w3schools.com Your message has been sent to W3Schools.
[ { "code": null, "e": 736, "s": 703, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 778, "s": 736, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 885, "s": 778, "text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:" }, { "code": null, "e": 904, "s": 885, "text": "help@w3schools.com" } ]
Python program to capitalize the first letter of every word in the file - GeeksforGeeks
26 Nov, 2020 The following article contains programs to read a file and capitalize the first letter of every word in the file and print it as output. To capitalize the first letter we will use the title() function in python. The title function in python is the Python String Method which is used to convert the first character in each word to Uppercase and the remaining characters to Lowercase in the string and returns the new string. Examples: # Content of the file serves as input Input: hello world Output: Hello World # Content of the file serves as input Input: geeks for geeks Output: Geeks For Geeks Approach: We will take the content of the file as input. We will open the file and save its content by using the open() function in python. Printing the content after altering it. Input File: Content of the gfg.txt file Below is the Implementation. Python3 # Python program to read a file and capitalize# the first letter of every word in the file. # A file named "gfg", will be opened with the # reading mode. file_gfg = open('gfg.txt', 'r') # This will traverse through every line one by one# in the filefor line in file_gfg: # This will convert the content # of that line with capitalized # first letter of every word output = line.title() # This will print the output print(output) Output: Geeksforgeeks Is A Computer Science Portal For Geeks. It Contains Well Written, Well Thought And Well Explained Computer Science And Programming Articles, Quizzes Etc. Python file-handling-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install PIP on Windows ? How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Pandas dataframe.groupby() Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary Python program to check whether a number is Prime or not
[ { "code": null, "e": 23901, "s": 23873, "text": "\n26 Nov, 2020" }, { "code": null, "e": 24325, "s": 23901, "text": "The following article contains programs to read a file and capitalize the first letter of every word in the file and print it as output. To capitalize the first letter we will use the title() function in python. The title function in python is the Python String Method which is used to convert the first character in each word to Uppercase and the remaining characters to Lowercase in the string and returns the new string." }, { "code": null, "e": 24335, "s": 24325, "text": "Examples:" }, { "code": null, "e": 24499, "s": 24335, "text": "# Content of the file serves as input\nInput: hello world\nOutput: Hello World\n\n# Content of the file serves as input\nInput: geeks for geeks\nOutput: Geeks For Geeks\n" }, { "code": null, "e": 24509, "s": 24499, "text": "Approach:" }, { "code": null, "e": 24556, "s": 24509, "text": "We will take the content of the file as input." }, { "code": null, "e": 24639, "s": 24556, "text": "We will open the file and save its content by using the open() function in python." }, { "code": null, "e": 24679, "s": 24639, "text": "Printing the content after altering it." }, { "code": null, "e": 24691, "s": 24679, "text": "Input File:" }, { "code": null, "e": 24719, "s": 24691, "text": "Content of the gfg.txt file" }, { "code": null, "e": 24748, "s": 24719, "text": "Below is the Implementation." }, { "code": null, "e": 24756, "s": 24748, "text": "Python3" }, { "code": "# Python program to read a file and capitalize# the first letter of every word in the file. # A file named \"gfg\", will be opened with the # reading mode. file_gfg = open('gfg.txt', 'r') # This will traverse through every line one by one# in the filefor line in file_gfg: # This will convert the content # of that line with capitalized # first letter of every word output = line.title() # This will print the output print(output)", "e": 25217, "s": 24756, "text": null }, { "code": null, "e": 25225, "s": 25217, "text": "Output:" }, { "code": null, "e": 25394, "s": 25225, "text": "Geeksforgeeks Is A Computer Science Portal For Geeks. It Contains Well Written, Well Thought And Well Explained Computer Science And Programming Articles, Quizzes Etc." }, { "code": null, "e": 25424, "s": 25394, "text": "Python file-handling-programs" }, { "code": null, "e": 25431, "s": 25424, "text": "Python" }, { "code": null, "e": 25447, "s": 25431, "text": "Python Programs" }, { "code": null, "e": 25545, "s": 25447, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25554, "s": 25545, "text": "Comments" }, { "code": null, "e": 25567, "s": 25554, "text": "Old Comments" }, { "code": null, "e": 25599, "s": 25567, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 25655, "s": 25599, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 25697, "s": 25655, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 25739, "s": 25697, "text": "Check if element exists in list in Python" }, { "code": null, "e": 25775, "s": 25739, "text": "Python | Pandas dataframe.groupby()" }, { "code": null, "e": 25797, "s": 25775, "text": "Defaultdict in Python" }, { "code": null, "e": 25836, "s": 25797, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 25882, "s": 25836, "text": "Python | Split string into list of characters" }, { "code": null, "e": 25920, "s": 25882, "text": "Python | Convert a list to dictionary" } ]
How can I shutdown MySQL Server?
With the help of ‘mysqladmin’ program we would be able to shutdown our MySQL server. It can be used as follows on command line − C:\mysql\bin>mysqladmin -u root shutdown We will see nothing after entering the above command because it will not print any message in command window. We should have to trust that MySQL server has been shutdown properly.
[ { "code": null, "e": 1191, "s": 1062, "text": "With the help of ‘mysqladmin’ program we would be able to shutdown our MySQL server. It can be used as follows on command line −" }, { "code": null, "e": 1232, "s": 1191, "text": "C:\\mysql\\bin>mysqladmin -u root shutdown" }, { "code": null, "e": 1412, "s": 1232, "text": "We will see nothing after entering the above command because it will not print any message in command window. We should have to trust that MySQL server has been shutdown properly." } ]
WebAssembly - Quick Guide
WebAssembly is a new computer programming language for the web. WebAssembly code is a low level binary format, that is compatible with the web and can easily run in modern web browsers. The file size generated is small and it loads and executes faster. You can now compile languages like C, C++, Rust, etc. to binary format and it can run on the web just like javascript. As per the official website of WebAssembly, which is available at https://webassembly.org/, it is defined as WebAssembly (abbreviated as Wasm) is a binary instruction format for a stack-based virtual machine. Wasm is designed as a portable target for compilation of high-level languages like C/C++/Rust, enabling deployment on the web for client and server applications. Web Assembly is not something that a developer will have to write, but the code is written in languages like C, C++, Rust and can be compiled to WebAssembly (wasm). The same code can be run inside the web browsers. Web Assembly is a new language, the code is low-level assembly language, but with its text format feature, the code is readable and debugging is possible, if necessary. The open standards for WebAssembly are developed in a W3C Community Group that includes representatives from all major browsers as well as a W3C Working Group. The main goals of WebAssembly are mentioned below − Faster, Efficient and Portable − WebAssembly code is meant to run faster on different platforms taking advantage of the hardware available. Faster, Efficient and Portable − WebAssembly code is meant to run faster on different platforms taking advantage of the hardware available. Easy to read and debug − WebAssembly, being a low level assembly language, has text format support, that allows you to debug the code for any issues and also to rewrite the code, if necessary. Easy to read and debug − WebAssembly, being a low level assembly language, has text format support, that allows you to debug the code for any issues and also to rewrite the code, if necessary. Security − WebAssembly is safe to run on the web browsers, as it takes care of permissions and same-origin policies. Security − WebAssembly is safe to run on the web browsers, as it takes care of permissions and same-origin policies. The following are the advantages of WebAssembly − Run is Modern Browsers − WebAssembly is able to execute without any issues on the modern web browsers which are available. Run is Modern Browsers − WebAssembly is able to execute without any issues on the modern web browsers which are available. Multiple Language support − Languages like C, C++, Rust, Go can now compile the code to WebAssembly and run the same in web browsers. So, the languages which were not able to run in a browser will now be able to do so. Multiple Language support − Languages like C, C++, Rust, Go can now compile the code to WebAssembly and run the same in web browsers. So, the languages which were not able to run in a browser will now be able to do so. Faster, Efficient and Portable − Due to the small size of the code, it loads and executes faster. Faster, Efficient and Portable − Due to the small size of the code, it loads and executes faster. Easy to understand − Developers don’t have to do much stress in understanding WebAssembly coding, as they don’t have to write the code in WebAssembly. Instead compile the code in WebAssembly and execute the same on the web. Easy to understand − Developers don’t have to do much stress in understanding WebAssembly coding, as they don’t have to write the code in WebAssembly. Instead compile the code in WebAssembly and execute the same on the web. Easy to Debug − Though the final code is in low level assembly language, you can also get it in text format, that is easy to read and debug. Easy to Debug − Though the final code is in low level assembly language, you can also get it in text format, that is easy to read and debug. The following are the disadvantages of WebAssembly − WebAssembly is still being worked on and it is too early to decide the future of it. WebAssembly is still being worked on and it is too early to decide the future of it. WebAssembly is dependent on javascript to interact with the Document Object Model (DOM). WebAssembly is dependent on javascript to interact with the Document Object Model (DOM). WebAssembly is also called WASM which was first introduced in the year 2017. The big technology companies behind the origin of WebAssembly are Google, Apple, Microsoft, Mozilla and W3C. The buzz is that WebAssembly is going to replace Javascript because of its faster execution, but that is not the case. WebAssembly and Javascript are meant to work together towards solving the complex issues. So far, we have only Javascript that can work successfully inside the browser. There are very heavy tasks that are difficult to carry out in the browsers using javascript. To name a few they are Image recognition, Computer-Aided Design (CAD) applications, Live video augmentation, VR and augmented reality, Music applications, Scientific visualization and simulation, Games, Image / video editing etc. WebAssembly is a new language with binary instruction that can load and execute faster. The task stated above, can be easily done in high level languages like C, C++, Rust etc. We need a way that, the code we have in C, C++, Rust can be compiled and can use it in web browsers. The same is achievable using WebAssembly. When the WebAssembly code is loaded inside the browser. Then, the browser takes care of converting into machine format that can be understood by the processors. For javascript the code has to be downloaded, parsed and converted to machine format. A lot of time goes into it and for heavy tasks like, we mentioned earlier can be very slow. High level languages like C, C++ and Rust are compiled into binary format, that is, .wasm and text format .wat. The source code written in C, C++ and Rust is compiled to .wasm using a compiler. You can make use of the Emscripten SDK for compiling C/C++ to .wasm. The flow is as follows − C/C++ code can be compiled to .wasm using Emscripten SDK. Later, the .wasm code can be used with the help of javascript in your html file to display the output. The Key concepts are as explained below − A module is an object that is compiled by the browser to executable machine code. A module is said to be stateless and it can be shared between windows and web workers. Memory in WebAssembly, is an arraybuffer that holds the data. You can allocate memory by using the Javascript api WebAssembly.memory(). Table in WebAssembly is a typed array that is, outside WebAssembly memory and mostly has a reference to functions. It stores the memory address of the functions. Instance is an object that will have, all the exported functions that can be called from javascript to execute inside the browser. WebAssembly is also called wasm, which is an improvement to Javascript. It is designed to run inside browsers just like javascript and also with nodejs. You happen to get wasm output, when any high level language like C, C++, Rust is compiled. Consider the following C program − int factorial(int n) { if (n == 0) return 1; else return n * factorial(n-1); } Make use of WasmExplorer, which is available at https://mbebenita.github.io/WasmExplorer/ to get the compiled code as shown below − The WebAssembly text format for factorial program is as stated below − (module (table 0 anyfunc) (memory $0 1) (export "memory" (memory $0)) (export "factorial" (func $factorial)) (func $factorial (; 0 ;) (param $0 i32) (result i32) (local $1 i32) (local $2 i32) (block $label$0 (br_if $label$0 (i32.eqz (get_local $0) ) ) (set_local $2 (i32.const 1) ) (loop $label$1 (set_local $2 (i32.mul (get_local $0) (get_local $2) ) ) (set_local $0 (tee_local $1 (i32.add (get_local $0) (i32.const -1) ) ) ) (br_if $label$1 (get_local $1) ) ) (return (get_local $2) ) ) (i32.const 1) ) ) Using the Wat2Wasm tool, you can view the WASM code, just like how it is mentioned below − Developers are not supposed to write code in wasm or learn to code in it, as it is mostly generated when you compile high level languages. In WASM, all the instructions are pushed on to the stack. The arguments are popped and the result is pushed back to the stack. Consider the following WebAssembly Text format that adds 2 numbers − (module (func $add (param $a i32) (param $b i32) (result i32) get_local $a get_local $b i32.add ) (export "add" (func $add)) ) The name of the function is $add, it takes in 2 params $a and $b. The result is a type 32-bit integer. The local variables are accessed using get_local and the add operation is performed using i32.add. The stack representation to add 2 numbers while execution will be as follows − In step 1 − The execution of get_local $a instruction, the first parameters i.e., $a is pushed on the stack. In step 2 − During execution of get_local $b instruction, the second parameters i.e., $b is pushed on the stack. In step 3 − The execution of i32.add will pop the elements from the stack and will push the result back to the stack. The value that remains in the end inside the stack is the result of the function $add. In this chapter, will learn how to install Emscripten SDK to compile C/C++. Emscripten is a Low level virtual machine (LLVM) that takes bytecode generated from C/C++ and compiles it into JavaScript that can easily execute inside the browser. To compile C/C++ to WebAssembly, we need to first install Emscripten sdk. The steps to install Emscripten sdk are as follows − Step 1 − Clone the emsdk repo : git clone https://github.com/emscripten-core/emsdk.git. E:\wa>git clone https://github.com/emscripten-core/emsdk.git Cloning into 'emsdk'... remote: Enumerating objects: 14, done. remote: Counting objects: 100% (14/14), done. remote: Compressing objects: 100% (12/12), done. remote: Total 1823 (delta 4), reused 4 (delta 2), pack-reused 1809 receiving obje cts: 99% (1819/1823), 924.01 KiB | 257.00 KiB/s Receiving objects: 100% (1823/1823), 1.01 MiB | 257.00 KiB/s, done. Resolving deltas: 100% (1152/1152), done. Step 2 − Enter inside the directory emsdk. cd emsdk Step 3 − For windows: Execute following command. emsdk install latest For linux, this command will take some time to install the necessary tools like java, python etc. Follow the below mentioned code − ./emsdk install latest Step 4 − To activate latest SDK execute following command in your terminal. For windows, execute the following command − emsdk activate latest For linux, execute the below mentioned command − ./emsdk activate latest Step 5 − To activate PATH and other environment variables run following command in your terminal. For windows, execute the command − emsdk_env.bat For linux, execute the following command − source ./emsdk_env.sh We are done installing the emsdk and can now compile C or C++ code. The compiling of C/C++ will be done in the next chapters. To compile any C or C++ code following is the command − emcc source.c or source.cpp -s WASM=1 -o source.html The output will give you a source.html file, source.js and source.wasm files. The js will have the api that will fetch the source.wasm and you can see the output, when you hit source.html in the browser. To just get the wasm file you can use following command. This command will give you only source.wasm file. emcc source.c or source.cpp -s STANDALONE_WASM This chapter will discuss some easy to use tools that are very helpful, while working with WebAssembly. Let us begin by learning about WebAssembly.studio tool. This tool allows you to compile C, Rust, Wat to Wasm etc. To start with you can click on Empty C Project, Empty Rust Project, Empty Wat Project to compile C and Rust to WASM. 5. It has Build, Run to build the code and check the output. The download button allows you to download .wasm file, that can be used to test inside browser. This tool is very helpful to compile C and Rust code and check the output. WebAssembly Explorer allows you to compile C and C++ code. Refer the link https://mbebenita.github.io/WasmExplorer/ for more details. The screen that will appear after clicking the link is shown below − You can choose the C and C++ version. The source code of C or C++ is written here − Once, you click on Compile button, it gives the WebAssembly text format (WAT) and Firefox x86 Assembly code in the blocks below − You can download the .wasm code to test it inside the browser. Wasmfiddle helps you to compile C code to WebAssembly and also test the output. After clicking on the link https://wasdk.github.io/WasmFiddle/, you will see the following page − Click on Build to compile the code. You can download the Wat and Wasm code by clicking on the Wat and Wasm. To test the output click on Run button. The tool wat2wasm will give you wasm code when you enter the WebAssembly text format. You can click on the link https://webassembly.github.io/wabt/demo/wat2wasm/ for demo and the screen that will appear is given below − You can make use of the upload button to upload .wasm and the textarea will display the text format. The tool wat2wasm will give you wasm code when you enter the WebAssembly text format. You can click on the link https://webassembly.github.io/wabt/demo/wat2wasm/ for demo and the screen that will appear is given below − This tool is very helpful, as it helps to get the output also tested. You can enter the WAT code and take a look at the .wasm code and also execute the code to see the output. WebAssembly, also called WASM, is binary format low level code developed to be executed inside browsers in the most efficient way. WebAssembly code is structured with following concepts − Values Types Instructions Let us learn them in detail now. Values in WebAssembly are meant to store complex data such as text, strings and vectors. WebAssembly supports the following − Bytes Integers Floating point Names Bytes is the simplest form of values supported in WebAssembly. The value is in hexadecimal format. Bytes represented as b, can also take natural numbers n, where n <256. byte ::= 0x00| .... |0xFF In WebAssembly, integers supported are as given below − i32: 32-bit integer i64: 64-bit integer In WebAssembly floating point numbers supported are as follows − f32: 32-bit floating point f64: 64-bit floating point Names are sequence of character, with scalar values defined by Unicode, which is available at the link http://www.unicode.org/versions/Unicode12.1.0/ given herewith. The entities in WebAssembly are classified as types. The types supported are as stated below − Value Types Result Types Function Types Limits Memory Types Table Types Global Types External Types Let us study them one by one. The values type supported by WebAssembly are as mentioned below − i32: 32-bit integer i64: 64-bit integer f32: 32-bit floating point f64: 64-bit floating point valtype ::= i32|i64|f32|f64 The values written inside brackets are executed and stored inside result types. The result type is the output of the execution of a block of code made up of values. resulttype::=[valtype?] A function type will take in vector of parameters returns a vector of results. functype::=[vec(valtype)]--> [vec(valtype)] Limits are the storage range linked with memory and table types. limits ::= {min u32, max u32} Memory types deal with linear memories and the size range. memtype ::= limits Table Types are classified by the element type assigned to it. tabletype ::= limits elemtype elemtype ::= funcref Table type is dependent on the limit for the minimum and maximum size assigned to it. Global Type holds the global variables that have the value, that can change or remain the same. globaltype ::= mut valtype mut ::= const|var External Types deals with imports and external values. externtype ::= func functype | table tabletype | mem memtype | global globaltype WebAssembly code is a sequence of instructions that follows a stack machine model. As WebAssembly follows a stack machine model, the instructions are pushed on the stack. The argument values for a function, for example, are popped from stack and the result is pushed back on the stack. In the end, there will be only one value in the stack and that is the result. Some of the commonly used Instructions are as follows − Numeric Instructions Variable Instructions Numeric Instructions are operations, which are performed on numeric value. nn, mm ::= 32|64 ibinop ::= add|sub|mul|div_sx|rem_sx|and|or|xor irelop ::= eq | ne | lt_sx | gt_sx | le_sx | ge_sx frelop ::= eq | ne | lt | gt | le | ge Variable instructions are about accessing the local and global variables. For example To access local variables − get_local $a get_local $b To set local variables − set_local $a set_local $b To access global variables − get_global $a get_global $b To set global variables − set_global $a set_global $b This chapter will list out the comparison between WebAssembly and Javascript. Javascript is a language, that we have used a lot inside the browser. Now, with WebAssembly release, we can also use WebAssembly inside the browser. The reason for WebAssembly to come into existence is not to replace javascript, but to take care of certain things, that are difficult to handle with javascript. For example It is difficult to get the tasks such as Image recognition, CAD applications, Live video augmentation, VR and augmented reality, Music applications, Scientific visualization and simulation, Games, Image / video editing etc. to be done with javascript. Using high level languages like C/C++, Rust, which now can be compiled to WebAssembly, it is easy to get the task mentioned above to be done. WebAssembly generates a binary code that is easy to execute inside the browser. So here, is the list of comparison done between Javascript and WebAssembly. Coding You can easily write code in Javascript. The code written is human readable and saved as .js. When used inside the browser you need to use a <script> tag. The code can be written in text format in WebAssembly and it is saved as .wat. It is difficult to write the code in .wat format. It is best to compile the code from some other high level language instead of writing from start in .wat. You cannot execute the .wat file inside the browser and has to convert to .wasm using the compilers or online tools available. Execution The code written in javascript when used inside the browser has to be downloaded, parsed, compiled and optimized. We have WebAssembly code in .wasm already compiled and in binary format. Memory Management Javascript assigns memory when, variables are created and the memory is released when not used and are added to garbage collection. Memory in WebAssembly is an arraybuffer that holds the data. You can allocate memory by using the Javascript API WebAssembly.memory(). WebAssembly memory is stored in an array format i.e. a flat memory model that is easy to understand and perform the execution. The disadvantage of memory model in WebAssembly is − Complex calculation takes time. Complex calculation takes time. Webassembly does not support garbage collection that does not allow reuse of the memory and the memory is wasted. Webassembly does not support garbage collection that does not allow reuse of the memory and the memory is wasted. Load Time & Performance In case of javascript, when called inside the browser, the javascript file has to be downloaded, and parsed. Later, the parser converts the source code to bytecode that the javascript engine executes the code in the browser. The Javascript engine is very powerful and hence, the load time and performance of javascript is very fast in comparison to WebAssembly. A most important goal of WebAssembly is to be faster than JavaScript.Wasm code generated from high-level languages is smaller in size and hence, the load time is faster. But, languages like GO, when compiled to wasm produce a big file size for a small piece of code. WebAssembly is designed in such a way that it is faster in compilation, and can run across all the major browsers. WebAssembly still has to add lots of improvements in terms of performance in comparison to javascript. Debugging Javascript is human-readable and can be debugged easily. Adding breakpoints to your javascript code inside the browser allows you to easily debug the code. WebAssembly provides the code in text format, that is readable but, still very difficult to debug. Firefox does allow you to view the wasm code in .wat format inside the browser. You cannot add breakpoints in .wat and that is something that will be available in the future. Browser Support Javascript works well in all browsers. All major web browsers have support for WebAssembly. In this chapter, we will understand how to load the wasm code and execute them in the browser using the help of javascript webassembly API. Here are some important API's, we are going to make use throughout the tutorial to execute wasm code. fetch() Browser API WebAssembly.compile WebAssembly.instance WebAssembly.instantiate WebAssembly.instantiateStreaming Before we discuss the WebAssembly javascript API's, to test the API and the output we are going to use the following C program and the .wasm code generated from the c program using wasm explorer. An example for C Program is as follows − #include<stdio.h> int square(int n) { return n*n; } We will make use of WASM explorer, to get the wasm code − Download WASM code and use it to test the API's. fetch() API is meant to load .wasm network resource. <script> var result = fetch("findsquare.wasm"); console.log(result); </script> It returns a promise as shown below − You can also make use of XMLHttpRequest method to fetch the wasm network resource. The api responsibility is to compile the module details that are fetched from .wasm. The syntax is as given below − WebAssembly.compile(buffer); Buffer − This code from .wasm has to be converted to a typed array or arraybuffer, before giving as input to compile. It will return a promise that will have the compiled module. Let us see one example, that gives the output as a compiled module using webAssembly.compile(). <script> fetch("findsquare.wasm") .then(bytes => bytes.arrayBuffer()) .then(mod => { var compiledmod = WebAssembly.compile(mod); compiledmod.then(test=> { console.log(test); }) }) </script> The console.log, when checked in the browser, will give you the compiled module details − The module has a constructor object with imports, exports, and customSections. Let us see the next API, to get more details of the compiled module. Using the WebAssembly.instance, API will give you the executable instance of the compiled module that can be further executed to get the output. The syntax is as given below − new WebAssembly.Instance(compiled module) The return value will be an object with the array of exports function that can be executed. <script> fetch("findsquare.wasm") .then(bytes => bytes.arrayBuffer()) .then(mod => WebAssembly.compile(mod)).then(module => { let instance = new WebAssembly.Instance(module); console.log(instance); }) </script> The output will give us an array of exports function as shown below − You can see the square function, that we got from the C code that is compiled. To execute the square function, you can do the following − <script> fetch("findsquare.wasm") .then(bytes => bytes.arrayBuffer()) .then(mod => WebAssembly.compile(mod)) .then(module => { let instance = new WebAssembly.Instance(module); console.log(instance.exports.square(15)); }) </script> The output will be − 225 This API takes care of compiling and instantiating the module together. The syntax is as follows − WebAssembly.instantiate(arraybuffer, importObject) arraybuffer − The code from .wasm has to be converted to typed array or arraybuffer before giving as input to instantiate. importObject − The import object has to have details of the memory, imported functions to be used inside the module. It can be an empty module object, in case, there is nothing to be shared. It will return a promise, that will have module and instance details. <script type="text/javascript"> const importObj = { module: {} }; fetch("findsquare.wasm") .then(bytes => bytes.arrayBuffer()) .then(module => WebAssembly.instantiate(module, importObj)) .then(finalcode => { console.log(finalcode); console.log(finalcode.instance.exports.square(25)); }); </script> When you execute the code, you will get the below mentioned output. This API takes care of compiling as well as instantiating the WebAssembly module from the .wasm code given. The syntax is as given below − WebAssembly.instantiateStreaming(wasmcode, importObject); wasmcode − Response from fetch or any other API that gives the wasm code and returns a promise. importObject − The import object has to have details of the memory, imported functions to be used inside the module. It can be an empty module object in case there is nothing to be shared. It will return a promise, that will have module and instance details. An example is discussed below − <script type="text/javascript"> const importObj = { module: {} }; WebAssembly.instantiateStreaming(fetch("findsquare.wasm"), importObj).then(obj => { console.log(obj); }); </script> When you test it in the browser, you will see an error − To make it work at your server end, you will have to add the mime type application/wasm or else make use of WebAssembly.instantiate(arraybuffer, importObject). WebAssembly support is added to all the latest browsers available with you today like Chrome, Firefox. The Firefox version 54+ onwards gives you a special feature to debug your wasm code. To do that, execute your code inside Firefox browsers that call wasm. For example, consider following C code that finds the square of the number. An example for the C Program is as follows − #include<stdio.h> int square(int n) { return n*n; } We will make use of WASM explorer to get the wasm code − Download WASM code and use it to see the output in the browser. The html file that loads the wasm is as follows − !doctype html> <html> <head> <meta charset="utf-8"> <title>WebAssembly Square function</title> <style> div { font-size : 30px; text-align : center; color:orange; } </style> </head> <body> <div id="textcontent"></div> <script> let square; fetch("findsquare.wasm").then(bytes => bytes.arrayBuffer()) .then(mod => WebAssembly.compile(mod)) .then(module => {return new WebAssembly.Instance(module) }) .then(instance => { square = instance.exports.square(13); console.log("The square of 13 = " +square); document.getElementById("textcontent").innerHTML = "The square of 13 = " +square; }); </script> </body> </html> Open your Firefox browser and load the above html file and open the debugger tool. You should see wasm:// entry in the debugger tool. Click on wasm:// and it shows the wasm code converted to .wat format as shown above. You can take a look at the code of the exported function and can debug the code, if any issue comes up. Firefox also intends to add breakpoints, so that you can debug the code and check the execution flow. In this chapter we are going to write a simple program in C and convert it into .wasm and execute the same in the browser to get the text "Hello World". Will make use of wasm explorer tool that will convert the C program to .wasm and will make use of the .wasm inside our .html file. The Wasm explorer tool which is available at https://mbebenita.github.io/WasmExplorer/ looks as follows − The C code that we are going to use is as follows − #include <stdio.h> char *c_hello() { return "Hello World"; } Update the first block in wasm explorer with the C code as shown below − Click on COMPILE Button to compile to WASM and WAT and Firefox x86 Web Assembly as shown below − Use the DOWNLOAD to get the .wasm file and save it as firstprog.wasm. Create a .html file called firstprog.html as shown below − <!doctype html> <html> <head> <meta charset="utf-8"> <title>WebAssembly Hello World</title> </head> <body> <div id="textcontent"></div> <script type="text/javascript"> //Your code from webassembly here </script> </body> </html> Let us now use firstprog.wasm to read the helloworld from the C function c_hello(). Use fetch() api to read the firstprog.wasm code. The .wasm code has to be converted into arraybuffer by using ArrayBuffer. The ArrayBuffer object will return you a fixed length binary data buffer. The code so far will be as follows − <script type="text/javascript"> fetch("firstprog.wasm") .then(bytes => bytes.arrayBuffer()) </script> The bytes from ArrayBuffer have to be compiled into a module by using WebAssembly.compile(buffer) function. The code will look like below − <script type="text/javascript"> fetch("firstprog.wasm") .then(bytes => bytes.arrayBuffer()) .then(mod => WebAssembly.compile(mod)) </script> To get the module we have to call the webassembly.instance constructor as shown below − <script type="text/javascript"> fetch("firstprog.wasm") .then(bytes => bytes.arrayBuffer()) .then(mod => WebAssembly.compile(mod)) .then(module => {return new WebAssembly.Instance(module) }) </script> Let us now console the instance to see the details in the browser. <script type="text/javascript"> fetch("firstprog.wasm") .then(bytes => bytes.arrayBuffer()) .then(mod => WebAssembly.compile(mod)) .then(module => { return new WebAssembly.Instance(module) }) .then(instance => { console.log(instance); }); </script> The console.log details are shown below − To get the string “Hello World” from the function c_hello(), we need to add some code in javascript. First, get the memory buffer details as shown below − let buffer = instance.exports.memory.buffer;; The buffer value has to be converted to a typed array so that we can read the values from it. The buffer has the string Hello World in it. To convert to typed call the constructor Uint8Array as shown below − let buffer = new Uint8Array(instance.exports.memory.buffer); Now, we can read the value from the buffer in a for - loop. Let us now get the start point to read the buffer, by calling the function we wrote as shown below − let test = instance.exports.c_hello(); Now, the test variable has the start point to read our string. WebAssembly does not have anything for string values, everything is stored as integers. So when, we read the value from the buffer, they will be an integer value and we need to convert it into a string using fromCharCode() in javascript. The code is as follows − let mytext = ""; for (let i=test; buffer[i]; i++){ mytext += String.fromCharCode(buffer[i]); } Now, when you console mytext you should see the string “Hello World”. The complete code is as follows − <!doctype html> <html> <head> <meta charset="utf-8"> <title>WebAssembly Add Function</title> <style> div { font-size : 30px; text-align : center; color:orange; } </style> </head> <body> <div id="textcontent"></div> <script> fetch("firstprog.wasm") .then(bytes => bytes.arrayBuffer()) .then(mod => WebAssembly.compile(mod)) .then(module => {return new WebAssembly.Instance(module)}) .then(instance => { console.log(instance); let buffer = new Uint8Array(instance.exports.memory.buffer); let test = instance.exports.c_hello(); let mytext = ""; for (let i=test; buffer[i]; i++) { mytext += String.fromCharCode(buffer[i]); } console.log(mytext); document.getElementById("textcontent").innerHTML = mytext; }); </script> </body> </html> We have added a div and the content is added to the div, so the string is displayed on the browser. The output is mentioned below − We have seen how to get a .wasm file from c /c++ code. In this chapter, we will convert the wasm into a WebAssembly module and execute the same in the browser. Let us use the C++ Factorial code as shown below − int fact(int n) { if ((n==0)||(n==1)) return 1; else return n*fact(n-1); } Open Wasm Explorer which is available at https://mbebenita.github.io/WasmExplorer/ as shown below − The first column has the C++ factorial function, the 2nd column has the WebAssembly text format and the last column has x86 Assembly code. The WebAssembly Text format − (module (table 0 anyfunc) (memory $0 1) (export "memory" (memory $0)) (export "_Z4facti" (func $_Z4facti)) (func $_Z4facti (; 0 ;) (param $0 i32) (result i32) (local $1 i32) (set_local $1 (i32.const 1) ) (block $label$0 (br_if $label$0 (i32.eq (i32.or (get_local $0) (i32.const 1) ) (i32.const 1) ) ) (set_local $1 (i32.const 1) ) (loop $label$1 (set_local $1 (i32.mul (get_local $0) (get_local $1) ) ) (br_if $label$1 (i32.ne (i32.or (tee_local $0 (i32.add (get_local $0) (i32.const -1) ) ) (i32.const 1) ) (i32.const 1) ) ) ) ) (get_local $1) ) ) The C++ function fact has been exported as “_Z4facti” in WebAssembly Text format. Click on the download button to download the wasm code and save the file as factorial.wasm. Now to convert the .wasm code to the module we have to do the following − Convert the .wasm into arraybuffer by using ArrayBuffer. The ArrayBuffer object will return you a fixed-length binary data buffer. The bytes from ArrayBuffer have to be compiled into a module by using WebAssembly.compile(buffer) function. The WebAssembly.compile() function compiles and returns a WebAssembly.Module from the bytes given. Here, is the Javascript code that is discussed in Step 1 and 2. <script type="text/javascript"> let factorial; fetch("factorial.wasm") .then(bytes => bytes.arrayBuffer()) .then(mod => WebAssembly.compile(mod)) .then(module => {return new WebAssembly.Instance(module) }) .then(instance => { factorial = instance.exports._Z4facti; console.log('Test the output in Brower Console by using factorial(n)'); }); </script> Javascript browser API fetch is used to get the contents of factorial.wasm. Javascript browser API fetch is used to get the contents of factorial.wasm. The content is converted to bytes using arrayBuffer(). The content is converted to bytes using arrayBuffer(). The module is created from bytes by calling WebAssembly.compile(mod). The module is created from bytes by calling WebAssembly.compile(mod). The instance of a module is created using new WebAssembly.Instance(module) The instance of a module is created using new WebAssembly.Instance(module) The factorial function export _Z4facti is assigned to variable factorial by using WebAssembly.Module.exports(). The factorial function export _Z4facti is assigned to variable factorial by using WebAssembly.Module.exports(). Here, is the module.html along with the javascript code − module.html <!doctype html> <html> <head> <meta charset="utf-8"> <title>WebAssembly Module</title> </head> <body> <script> let factorial; fetch("factorial.wasm") .then(bytes => bytes.arrayBuffer()) .then(mod => WebAssembly.compile(mod)) .then(module => {return new WebAssembly.Instance(module) }) .then(instance => { factorial = instance.exports._Z4facti; console.log('Test the output in Browser Console by using factorial(n)'); }); </script> </body> </html> Execute module.html in the browser to see the output − In this chapter, we are going to discuss the webassembly.validate() function that will validate the .wasm output. The .wasm is available when we compile C, C++ or rust code. You can make use of the following tools to get the wasm code. Wasm Fiddler,which is available at https://wasdk.github.io/WasmFiddle/ Wasm Fiddler,which is available at https://wasdk.github.io/WasmFiddle/ WebAssembly Explorer, which is available at https://mbebenita.github.io/WasmExplorer/. WebAssembly Explorer, which is available at https://mbebenita.github.io/WasmExplorer/. The syntax is as given below − WebAssembly.validate(bufferSource); bufferSource − The bufferSource has the binary code that comes from either C, C++ or Rust program. It is in the form of typedarray or ArrayBuffer. The function will return true if the .wasm code is valid and false if not. Let us try one example. Go to Wasm fiddler, which is available at https://wasdk.github.io/WasmFiddle/, enter C code of your choice and down the wasm code. The block marked in red is the C code. Click on the Build button at the center to execute the code. Click on the Wasm , button to download the .wasm code. Save the .wasm at your end and let us use the same for validating. For Example: validate.html <!doctype html> <html> <head> <meta charset="utf-8"> <title>Testing WASM validate()</title> </head> <body> <script> fetch('program.wasm').then(res => res.arrayBuffer() ).then(function(testbytes) { var valid = WebAssembly.validate(testbytes); if (valid) { console.log("Valid Wasm Bytes!"); } else { console.log("Invalid Wasm Code!"); } }); </script> </body> </html> I have hosted the above .html file in wamp server along with the download .wasm file. Here, is the output when you test it in the browser. The output is the mentioned below − WebAssembly has the code in a binary format called WASM. You can also get the text format in WebAssembly and it is called WAT (WebAssembly Text format). As a developer you are not supposed to write code in WebAssembly, instead, you have to compile high-level languages like C, C++ and Rust to WebAssembly. Let us write WAT code stepwise. Step 1 − The starting point in a WAT is to declare the module. (module) Step 2 − Let us now, add some functionality to it in the form of function. The function is declared as shown below − (func <parameters/result> <local variables> <function body>) The function starts with func keyword which is followed by parameters or result. The parameters and the return value as a result. The parameters can have the following type supported by wasm − i32: 32-bit integer i64: 64-bit integer f32: 32-bit float f64: 64-bit float The params for the functions are written as given below − (param i32) (param i64) (param f32) (param f64) The result will be written as follows − (result i32) (result i64) (result f32) (result f64) The function with parameters and return value will be defined as follows − (func (param i32) (param i32) (result i64) <function body>) The local variables are those that you need in your function. A local value to the function will be defined as follows − (func (param i32) (param i32) (local i32) (result i64) <function body>) Function body is the logic to be performed. The final program will look like this − (module (func (param i32) (param i32) (local i32) (result i64) <function body>) ) Step 3 − To read and set parameters and local variables. To read the parameters and local variables, make use of get_local and set_local command. Example (module (func (param i32) (param i32) (local i32) (result i64) get_local 0 get_local 1 get_local 2 ) ) As per the function signature, get_local 0 will give the param i32 get_local 0 will give the param i32 get_local 1 will give the next parameter param i32 get_local 1 will give the next parameter param i32 get_local 2 will give local value i32 get_local 2 will give local value i32 Instead of referring to the parameters and locals using numeric values like 0,1,2, you can also use the name before the parameters, prefixing the name with a dollar sign. The following example shows, how to use the name with parameters and locals. Example (module (func (param $a i32) (param $b i32) (local $c i32) (result i64) get_local $a get_local $b get_local $c ) ) Step 4 − Instruction in Function body and execution. The execution in wasm follows the stack strategy. The instructions executed are sent one by one on the stack. For example, the instruction get_local $a will push the value, it reads on the stack. The instruction like i32.add that will add the will pop the elements from the stack. (func (param $a i32) (param $b i32) get_local $a get_local $b i32.add ) The instruction for i32.add is ($a+$b). The final value of i32.add, will be pushed on the stack and that will be assigned to the result. If the function signature has a result declared, there should be one value in the stack at the end of the execution. If there is no result param, the stack has to be empty at the end. So, the final code along with function body will be as follows − (module (func (param $a i32) (param $b i32) (result i32) get_local $a get_local $b i32.add ) ) Step 5 − Making call to the function. The final code with the function body is as shown in step 4. Now, to call the function, we need to export it. To export the function, it can be done with index values like 0,1, but, we can also give names. The name will be prefixed by $ and it will be added after the func keyword. Example (module (func $add (param $a i32) (param $b i32) (result i32) get_local $a get_local $b i32.add ) ) The function $add has to be exported, using export keyword as shown below − (module (func $add (param $a i32) (param $b i32) (result i32) get_local $a get_local $b i32.add ) (export "add" (func $add)) ) To test the above code in the browser, you will have to convert it into binary form (.wasm). Refer to the next chapter that shows how to convert .WAT to .WASM. In the previous chapter, we have seen how to write code in .wat i.e., WebAssembly text format. The WebAssembly text format will not directly work inside the browser and you need to convert it into binary format i.e., WASM to work inside browser. Let us convert .WAT to .WASM. The code we are going to use is as follows − (module (func $add (param $a i32) (param $b i32) (result i32) get_local $a get_local $b i32.add ) (export "add" (func $add)) ) Now, go to WebAssembly Studio, which is available at https://webassembly.studio/. You should see something like this, when you hit the link − Click on Empty Wat project and click on Create button at the bottom. It will take you to an empty project as shown below − Click on main.wat and replace the existing code with yours and click on the save button. Once saved, click on the build to convert to .wasm − If the build is successful you should see .wasm file created as shown below − Down the main.wasm file and use it inside your .html file to see the output as shown below. For Example − add.html <!doctype html> <html> <head> <meta charset="utf-8"> <title>WebAssembly Add Function</title> </head> <body> <script> let sum; fetch("main.wasm") .then(bytes => bytes.arrayBuffer()) .then(mod => WebAssembly.compile(mod)) .then(module => { return new WebAssembly.Instance(module) }) .then(instance => { sum = instance.exports.add(10,40); console.log("The sum of 10 and 40 = " +sum); }); </script> </body> </html> The function add is exported as shown in the code. The params passed are 2 integer values 10 and 40 and it returns the sum of it. The output is displayed in the browser. Dynamic linking is the process in which two or more modules will be linked together during runtime. To demonstrate how dynamic linking works, we will use C program and compile it to wasm using Ecmascript sdk. So here we have − test1.c int test1(){ return 100; } test2.c int test2(){ return 200; } main.c #include <stdio.h> int test1(); int test2(); int main() { int result = test1() + test2(); return result; } In main.c code, it makes use of test1() and test2(), which are defined inside test1.c and test2.c. Let us check how to link these modules in WebAssembly. The command to compile the above code is as follows: make use of SIDE_MODULE =1 for dynamic linking as shown in the command. emcc test1.c test2.c main.c -s SIDE_MODULE=1 -o maintest.wasm Using WasmtoWat, which is available at https://webassembly.github.io/wabt/demo/wasm2wat/, will get the WebAssembly text format of maintest.wasm. (module (type $t0 (func (result i32))) (type $t1 (func)) (type $t2 (func (param i32))) (type $t3 (func (param i32 i32) (result i32))) (import "env" "stackSave" (func $env.stackSave (type $t0))) (import "env" "stackRestore" (func $env.stackRestore (type $t2))) (import "env" "__memory_base" (global $env.__memory_base i32)) (import "env" "__table_base" (global $env.__table_base i32)) (import "env" "memory" (memory $env.memory 0)) (import "env" "table" (table $env.table 0 funcref)) (func $f2 (type $t1) (call $__wasm_apply_relocs) ) (func $__wasm_apply_relocs (export "__wasm_apply_relocs") (type $t1)) (func $test1 (export "test1") (type $t0) (result i32) (local $l0 i32) (local.set $l0 (i32.const 100) ) (return (local.get $l0) ) ) (func $test2 (export "test2") (type $t0) (result i32) (local $l0 i32) (local.set $l0 (i32.const 200)) (return (local.get $l0) ) ) (func $__original_main (export "__original_main") (type $t0) (result i32) (local $l0 i32) (local $l1 i32) (local $l2 i32) (local $l3 i32) (local $l4 i32) (local $l5 i32) (local $l6 i32) (local $l7 i32) (local $l8 i32) (local $l9 i32) (local.set $l0(call $env.stackSave)) (local.set $l1 (i32.const 16)) (local.set $l2 (i32.sub (local.get $l0) (local.get $l1))) (call $env.stackRestore (local.get $l2) ) (local.set $l3(i32.const 0)) (i32.store offset=12 (local.get $l2) (local.get $l3)) (local.set $l4 (call $test1)) (local.set $l5 (call $test2)) (local.set $l6 (i32.add (local.get $l4) (local.get $l5))) (i32.store offset=8 (local.get $l2) (local.get $l6)) (local.set $l7 (i32.load offset=8 (local.get $l2))) (local.set $l8 (i32.const 16)) (local.set $l9 (i32.add (local.get $l2) (local.get $l8))) (call $env.stackRestore (local.get $l9)) (return(local.get $l7)) ) (func $main (export "main") (type $t3) (param $p0 i32) (param $p1 i32) (result i32) (local $l2 i32) (local.set $l2 (call $__original_main)) (return (local.get $l2)) ) (func $__post_instantiate (export "__post_instantiate") (type $t1) (call $f2)) (global $__dso_handle (export "__dso_handle") i32 (i32.const 0)) ) The WebAssembly text format has some imports defined as shown below − (import "env" "stackSave" (func $env.stackSave (type $t0))) (import "env" "stackRestore" (func $env.stackRestore (type $t2))) (import "env" "__memory_base" (global $env.__memory_base i32)) (import "env" "__table_base" (global $env.__table_base i32)) (import "env" "memory" (memory $env.memory 0)) (import "env" "table" (table $env.table 0 funcref)) This is added while compiling code by emcc(emscripten sdk) and it deals with memory management in WebAssembly. Now to see the output, we will have to define the imports that you can see in the .wat code − (import "env" "stackSave" (func $env.stackSave (type $t0))) (import "env" "stackRestore" (func $env.stackRestore (type $t2))) (import "env" "__memory_base" (global $env.__memory_base i32)) (import "env" "__table_base" (global $env.__table_base i32)) (import "env" "memory" (memory $env.memory 0)) (import "env" "table" (table $env.table 0 funcref)) The above terms are explained as follows − env.stackSave − It is used for stack management, a functionality that is provided by the emscripten compiled code. env.stackSave − It is used for stack management, a functionality that is provided by the emscripten compiled code. env.stackRestore − It is used for stack management, a functionality that is provided by the emscripten compiled code. env.stackRestore − It is used for stack management, a functionality that is provided by the emscripten compiled code. env.__memory_base − It is an immutable i32 global offset that is, used in env.memory and reserved for the wasm module. The module can use this global in the initializer of its data segments, so that, they are loaded at the correct address. env.__memory_base − It is an immutable i32 global offset that is, used in env.memory and reserved for the wasm module. The module can use this global in the initializer of its data segments, so that, they are loaded at the correct address. env.__table_base − It is an immutable i32 global offset that is, used in env.table and reserved for the wasm module. The module can use this global in the initializer of its table element segments, so that, they are loaded at the correct offset. env.__table_base − It is an immutable i32 global offset that is, used in env.table and reserved for the wasm module. The module can use this global in the initializer of its table element segments, so that, they are loaded at the correct offset. env.memory − This will have the memory details that are required to be shared between the wasm modules. env.memory − This will have the memory details that are required to be shared between the wasm modules. env.table − This will have the table details that are required to be shared between the wasm modules. env.table − This will have the table details that are required to be shared between the wasm modules. The imports have to be defined in javascript as follows − var wasmMemory = new WebAssembly.Memory({'initial': 256,'maximum': 65536}); const importObj = { env: { stackSave: n => 2, stackRestore: n => 3, //abortStackOverflow: () => { throw new Error('overflow'); }, table: new WebAssembly.Table({ initial: 0, maximum: 65536, element: 'anyfunc' }), __table_base: 0, memory: wasmMemory, __memory_base: 256 } }; Following is the javascript code that makes use of the importObj inside WebAssembly.instantiate. <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> </head> <body> <script> var wasmMemory = new WebAssembly.Memory({'initial': 256,'maximum': 65536}); const importObj = { env: { stackSave: n => 2, stackRestore: n => 3, //abortStackOverflow: () => { throw new Error('overflow'); }, table: new WebAssembly.Table({ initial: 0, maximum: 65536, element: 'anyfunc' }), __table_base: 0, memory: wasmMemory, __memory_base: 256 } }; fetch("maintest.wasm") .then(bytes => bytes.arrayBuffer()) .then( module => WebAssembly.instantiate(module, importObj) ) .then(finalcode => { console.log(finalcode); console.log(WebAssembly.Module.imports(finalcode.module)); console.log(finalcode.instance.exports.test1()); console.log(finalcode.instance.exports.test2()); console.log(finalcode.instance.exports.main()); }); </script> </body> </html> The output is as follows − As per the official website of WebAssembly.org, which is available at https://webassembly.org/docs/security/ the main goal of WebAssembly in terms of security is as follows − The security model of WebAssembly has two important goals − Protect users from buggy or malicious modules, and Protect users from buggy or malicious modules, and Provide developers with useful primitives and mitigations for developing safe applications, within the constraints of (1). Provide developers with useful primitives and mitigations for developing safe applications, within the constraints of (1). The compiled code i.e. WASM from C/C++/Rust is not directly executed inside the browser and makes use of Javascript API's. The WASM code is sandboxed i.e. executed through Javascript API wrapper and the browser talks to WASM using the API. Here, is an example of using a .wasm file inside the browser. Example − C Program #include<stdio.h> int square(int n) { return n*n; } We will make use of WASM explorer to get the wasm code − Download WASM code and use it to test the api’s. <script type="text/javascript"> const importObj = { module: {} }; fetch("findsquare.wasm") .then(bytes => bytes.arrayBuffer()) .then(module => WebAssembly.instantiate(module,importObj)) .then(finalcode => { console.log(finalcode); console.log(finalcode.instance.exports.square(25)); }); </script> You will get the following output − The exports objects have a reference to the function to be called. To call the function square, you will have to do it as follows − console.log(finalcode.instance.exports.square(25)); Following are the issues with WASM compiled code − It is difficult to check, if there is any malicious code being inserted, while compiling the code to wasm. There are no tools available at this moment to validate the code. It is difficult to check, if there is any malicious code being inserted, while compiling the code to wasm. There are no tools available at this moment to validate the code. Wasm is difficult to analyse and the buggy/malicious code can be easily executed inside the browser. Wasm is difficult to analyse and the buggy/malicious code can be easily executed inside the browser. In this chapter, we are going to compile a simple C program to javascript and execute the same in the browser. For Example − C Program #include<stdio.h> int square(int n) { return n*n; } We have done the installation of emsdk in folder wa/. In same folder, create another folder cprog/ and save above code as square.c. We have already installed emsdk in the previous chapter. Here, we are going to make use of emsdk to compile the above c code. Compile test.c in your command prompt as shown below − emcc square.c -s STANDALONE_WASM –o findsquare.wasm emcc command takes care of compiling the code as well as give you the .wasm code. We have used STANDALONE_WASM option that will give only the .wasm file. Example − findsquare.html <!doctype html> <html> <head> <meta charset="utf-8"> <title>WebAssembly Square function</title> <style> div { font-size : 30px; text-align : center; color:orange; } </style> </head> <body> <div id="textcontent"></div> <script> let square; fetch("findsquare.wasm").then(bytes => bytes.arrayBuffer()) .then(mod => WebAssembly.compile(mod)) .then(module => { return new WebAssembly.Instance(module) }) .then(instance => { square = instance.exports.square(13); console.log("The square of 13 = " +square); document.getElementById("textcontent").innerHTML = "The square of 13 = " +square; }); </script> </body> </html> The output is as mentioned below − In this chapter, we are going to compile a simple C++ program to javascript and execute the same in the browser. C++ Program - Reversing a given number. #include <iostream> int reversenumber(int n) { int reverse=0, rem; while(n!=0) { rem=n%10; reverse=reverse*10+rem; n/=10; } return reverse; } We have done the installation of emsdk in folder wa/. In same folder, create another folder cprog/ and save above code as reverse.cpp. We have already installed emsdk in the previous chapter. Here, we are going to make use of emsdk to compile the above c code. Compile test.c in your command prompt as shown below − emcc reverse.cpp -s STANDALONE_WASM –o reverse.wasm emcc command takes care of compiling the code as well as give you the .wasm code. Example − reversenumber.html <!doctype html> <html> <head> <meta charset="utf-8"> <title>WebAssembly Reverse Number</title> <style> div { font-size : 30px; text-align : center; color:orange; } </style> </head> <body> <div id="textcontent"></div> <script> let reverse; fetch("reverse.wasm") .then(bytes => bytes.arrayBuffer()) .then(mod => WebAssembly.compile(mod)) .then(module => {return new WebAssembly.Instance(module) }) .then(instance => { console.log(instance); reverse = instance.exports._Z13reversenumberi(1439898); console.log("The reverse of 1439898 = " +reverse); document.getElementById("textcontent") .innerHTML = "The reverse of 1439898 = " +reverse; }); </script> </body> </html> The output is as follows − To get RUST compile code we will make use of WebAssembly.studio tool. Go to WebAssembly.studio which is available at Go to https://webassembly.studio/ and it will display you screen as shown below − Click on Empty Rust Project. Once done you will get three files in src/ folder − Open the file main.rs and change the code of your choice. I am adding following function that will add two given numbers − fn add_ints(lhs: i32, rhs: i32) -> i32 { lhs+rhs } The code available in main.rs is as follows − #[no_mangle] pub extern "C" fn add_one(x: i32) -> i32 { x + 1 } Replace the fn add_one with yours as shown below − #[no_mangle] pub extern "C" fn add_ints(lhs: i32, rhs: i32) -> i32 { lhs+rhs } In main.js, change the function name from add_one to add_ints fetch('../out/main.wasm').then( response => response.arrayBuffer() ).then(bytes => WebAssembly.instantiate(bytes)).then(results => { instance = results.instance; document.getElementById("container").textContent = instance.exports.add_one(41); }).catch(console.error); Replace instance.exports.add_one to instance.exports.add_ints(100,100) fetch('../out/main.wasm').then( response => response.arrayBuffer() ).then(bytes => WebAssembly.instantiate(bytes)).then(results => { instance = results.instance; document.getElementById("container").textContent = instance.exports.add_ints(100,100) }).catch(console.error); Click on the build button available on webassembly.studio UI to build the code. Once the build is done, click on Run button available on UI, to see the output − We get the output as 200, as we passed instance.exports.add_ints(100,100). Similarly, you can write a different program for rust and get it compiled in webassembly.studio. Go has added support for WebAssembly from version 1.1 onwards. To test it first download, Go. Go to the golang site, which is available at https://golang.org/dl/ and click on Download Go. As per your operating system download and install Go. Once done, write a simple program that adds two numbers in go. testnum.go package main import "fmt" func main() { var a int = 100 var b int = 200 var ret int ret = sum(a, b) fmt.Printf( "Sum is : %d\n", ret ) } /* function returning the max between two numbers */ func sum(num1, num2 int) int { return num1+num2 } To compile above code to wasm, first set the environment variables in Go. You will have to run following command − Set GOOS=js GOARCH=wasm Once done, execute the below command − go build -o testnum.wasm testnum.go You should get testnum.wasm file once the command is executed. Let us now test the code in the browser. To do that, we need to get the wasm_exec.js, that is installed with go. The file wasm_exec.js will be available inside misc/wasm/ folder in go. Here, is the code for testgo.html that makes use of wasm_exec.js and testnum.wasm. <html> <head> <meta charset="utf-8"/> <script src="wasm_exec.js"></script> </head> <body> <script type="text/javascript"> const importObj = { module: {} }; const go = new Go(); async function fetchAndInstantiate() { const response = await fetch("testnum.wasm"); const buffer = await response.arrayBuffer(); const obj = await WebAssembly.instantiate(buffer, go.importObject); console.log(obj); go.run(obj.instance); } fetchAndInstantiate(); </script> </body> </html> The output is as follows − Javascript has a bunch of API that can work with wasm code. The API is also supported in nodejs. Get NODEJS installed on your system. Create a Factorialtest.js file. Let us use the C++ Factorial code as shown below − int fact(int n) { if ((n==0)||(n==1)) return 1; else return n*fact(n-1); } Open Wasm Explorer, which is available at https://mbebenita.github.io/WasmExplorer/ as shown below − The first column has the C++ factorial function, the 2nd column has the WebAssembly text format and the last column has x86 Assembly code. The WebAssembly Text format is as follows − (module (table 0 anyfunc) (memory $0 1) (export "memory" (memory $0)) (export "_Z4facti" (func $_Z4facti)) (func $_Z4facti (; 0 ;) (param $0 i32) (result i32) (local $1 i32) (set_local $1(i32.const 1)) (block $label$0 (br_if $label$0 (i32.eq (i32.or (get_local $0) (i32.const 1) ) (i32.const 1) ) ) (set_local $1 (i32.const 1) ) (loop $label$1 (set_local $1 (i32.mul (get_local $0) (get_local $1) ) ) (br_if $label$1 (i32.ne (i32.or (tee_local $0 (i32.add (get_local $0) (i32.const -1) ) ) (i32.const 1) ) (i32.const 1) ) ) ) ) (get_local $1) ) ) The C++ function fact has been exported as “_Z4facti” in WebAssembly Text format. Factorialtest.js const fs = require('fs'); const buf = fs.readFileSync('./factorial.wasm'); const lib = WebAssembly.instantiate(new Uint8Array(buf)). then(res => { for (var i=1;i<=10;i++) { console.log("The factorial of "+i+" = "+res.instance.exports._Z4facti(i)) } } ); In your command line, run the command node factorialtest.js and the output is as follows − C:\wasmnode>node factorialtest.js The factorial of 1 = 1 The factorial of 2 = 2 The factorial of 3 = 6 The factorial of 4 = 24 The factorial of 5 = 120 The factorial of 6 = 720 The factorial of 7 = 5040 The factorial of 8 = 40320 The factorial of 9 = 362880 The factorial of 10 = 3628800 The chapter discusses the examples with regards to WebAssembly. Following is the example of C Program to get the max Element − void displaylog(int n); /* function returning the max between two numbers */ int max(int num1, int num2) { /* local variable declaration */ int result; if (num1 > num2) result = num1; else result = num2; displaylog(result); return result; } Compile the code in wasm fiddle and download the .wasm and .wat code. Wat code The Wat code is as follows − (module (type $FUNCSIG$vi (func (param i32))) (import "env" "displaylog" (func $displaylog (param i32))) (table 0 anyfunc) (memory $0 1) (export "memory" (memory $0)) (export "max" (func $max)) (func $max (; 1 ;) (param $0 i32) (param $1 i32) (result i32) (call $displaylog (tee_local $0 (select (get_local $0) (get_local $1) (i32.gt_s (get_local $0) (get_local $1)) ) ) ) (get_local $0) ) ) Download .wasm code and let us use in the .html file as shown below − <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> </head> <body> <script> const importObj = { env: { displaylog: n => alert("The max of (400, 130) is " +n) } }; fetch("testmax.wasm") .then(bytes => bytes.arrayBuffer()) .then(module => WebAssembly.instantiate(module, importObj)) .then(finalcode => { console.log(finalcode); console.log(finalcode.instance.exports.max(400,130)); }); </script> </body> </html> The output is as follows − Following is the C++ code to get the fibonacci series of given number. #include <iostream>> void displaylog(int n); int fibonacciSeries(int number) { int n1=0,n2=1,n3,i; for(i=2;i<number;++i) { n3=n1+n2; displaylog(n); n1=n2; n2=n3; } return 0; } I am using wasm explorer to compile the code. Download Wat and Wasm and test the same in the browser. You can use the below mentioned code − <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> </head> <body> <script> const importObj = { env: { _Z10displaylogi: n => console.log(n) } }; fetch("fib.wasm") .then(bytes => bytes.arrayBuffer()) .then(module => WebAssembly.instantiate(module, importObj)) .then(finalcode => { console.log(finalcode); console.log(finalcode.instance.exports._Z15fibonacciSeriesi(10)); }); </script> </body> </html> The output is as follows − Following is the Rust code to add elements in a given array. fn add_array(x: i32) -> i32 { let mut sum = 0; let mut numbers = [10,20,30]; for i in 0..3 { sum += numbers[i]; } sum } We are going to make use of WebAssembly Studio to compile RUST to wasm. Build the code and download the wasm file and execute the same in the browser. <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> </head> <body> <script> const importObj = { env: { } }; fetch("add_array.wasm") .then(bytes => bytes.arrayBuffer()) .then(module => WebAssembly.instantiate(module, importObj)) .then(finalcode => { console.log(finalcode); console.log(finalcode.instance.exports.add_array()); }); </script> </body> </html> The output will be as given below − Print Add Notes Bookmark this page
[ { "code": null, "e": 2605, "s": 2233, "text": "WebAssembly is a new computer programming language for the web. WebAssembly code is a low level binary format, that is compatible with the web and can easily run in modern web browsers. The file size generated is small and it loads and executes faster. You can now compile languages like C, C++, Rust, etc. to binary format and it can run on the web just like javascript." }, { "code": null, "e": 2976, "s": 2605, "text": "As per the official website of WebAssembly, which is available at https://webassembly.org/, it is defined as WebAssembly (abbreviated as Wasm) is a binary instruction format for a stack-based virtual machine. Wasm is designed as a portable target for compilation of high-level languages like C/C++/Rust, enabling deployment on the web for client and server applications." }, { "code": null, "e": 3191, "s": 2976, "text": "Web Assembly is not something that a developer will have to write, but the code is written in languages like C, C++, Rust and can be compiled to WebAssembly (wasm). The same code can be run inside the web browsers." }, { "code": null, "e": 3360, "s": 3191, "text": "Web Assembly is a new language, the code is low-level assembly language, but with its text format feature, the code is readable and debugging is possible, if necessary." }, { "code": null, "e": 3520, "s": 3360, "text": "The open standards for WebAssembly are developed in a W3C Community Group that includes representatives from all major browsers as well as a W3C Working Group." }, { "code": null, "e": 3572, "s": 3520, "text": "The main goals of WebAssembly are mentioned below −" }, { "code": null, "e": 3712, "s": 3572, "text": "Faster, Efficient and Portable − WebAssembly code is meant to run faster on different platforms taking advantage of the hardware available." }, { "code": null, "e": 3852, "s": 3712, "text": "Faster, Efficient and Portable − WebAssembly code is meant to run faster on different platforms taking advantage of the hardware available." }, { "code": null, "e": 4045, "s": 3852, "text": "Easy to read and debug − WebAssembly, being a low level assembly language, has text format support, that allows you to debug the code for any issues and also to rewrite the code, if necessary." }, { "code": null, "e": 4238, "s": 4045, "text": "Easy to read and debug − WebAssembly, being a low level assembly language, has text format support, that allows you to debug the code for any issues and also to rewrite the code, if necessary." }, { "code": null, "e": 4355, "s": 4238, "text": "Security − WebAssembly is safe to run on the web browsers, as it takes care of permissions and same-origin policies." }, { "code": null, "e": 4472, "s": 4355, "text": "Security − WebAssembly is safe to run on the web browsers, as it takes care of permissions and same-origin policies." }, { "code": null, "e": 4522, "s": 4472, "text": "The following are the advantages of WebAssembly −" }, { "code": null, "e": 4645, "s": 4522, "text": "Run is Modern Browsers − WebAssembly is able to execute without any issues on the modern web browsers which are available." }, { "code": null, "e": 4768, "s": 4645, "text": "Run is Modern Browsers − WebAssembly is able to execute without any issues on the modern web browsers which are available." }, { "code": null, "e": 4987, "s": 4768, "text": "Multiple Language support − Languages like C, C++, Rust, Go can now compile the code to WebAssembly and run the same in web browsers. So, the languages which were not able to run in a browser will now be able to do so." }, { "code": null, "e": 5206, "s": 4987, "text": "Multiple Language support − Languages like C, C++, Rust, Go can now compile the code to WebAssembly and run the same in web browsers. So, the languages which were not able to run in a browser will now be able to do so." }, { "code": null, "e": 5304, "s": 5206, "text": "Faster, Efficient and Portable − Due to the small size of the code, it loads and executes faster." }, { "code": null, "e": 5402, "s": 5304, "text": "Faster, Efficient and Portable − Due to the small size of the code, it loads and executes faster." }, { "code": null, "e": 5626, "s": 5402, "text": "Easy to understand − Developers don’t have to do much stress in understanding WebAssembly coding, as they don’t have to write the code in WebAssembly. Instead compile the code in WebAssembly and execute the same on the web." }, { "code": null, "e": 5850, "s": 5626, "text": "Easy to understand − Developers don’t have to do much stress in understanding WebAssembly coding, as they don’t have to write the code in WebAssembly. Instead compile the code in WebAssembly and execute the same on the web." }, { "code": null, "e": 5991, "s": 5850, "text": "Easy to Debug − Though the final code is in low level assembly language, you can also get it in text format, that is easy to read and debug." }, { "code": null, "e": 6132, "s": 5991, "text": "Easy to Debug − Though the final code is in low level assembly language, you can also get it in text format, that is easy to read and debug." }, { "code": null, "e": 6185, "s": 6132, "text": "The following are the disadvantages of WebAssembly −" }, { "code": null, "e": 6270, "s": 6185, "text": "WebAssembly is still being worked on and it is too early to decide the future of it." }, { "code": null, "e": 6355, "s": 6270, "text": "WebAssembly is still being worked on and it is too early to decide the future of it." }, { "code": null, "e": 6444, "s": 6355, "text": "WebAssembly is dependent on javascript to interact with the Document Object Model (DOM)." }, { "code": null, "e": 6533, "s": 6444, "text": "WebAssembly is dependent on javascript to interact with the Document Object Model (DOM)." }, { "code": null, "e": 6719, "s": 6533, "text": "WebAssembly is also called WASM which was first introduced in the year 2017. The big technology companies behind the origin of WebAssembly are Google, Apple, Microsoft, Mozilla and W3C." }, { "code": null, "e": 6928, "s": 6719, "text": "The buzz is that WebAssembly is going to replace Javascript because of its faster execution, but that is not the case. WebAssembly and Javascript are meant to work together towards solving the complex issues." }, { "code": null, "e": 7100, "s": 6928, "text": "So far, we have only Javascript that can work successfully inside the browser. There are very heavy tasks that are difficult to carry out in the browsers using javascript." }, { "code": null, "e": 7330, "s": 7100, "text": "To name a few they are Image recognition, Computer-Aided Design (CAD) applications, Live video augmentation, VR and augmented reality, Music applications, Scientific visualization and simulation, Games, Image / video editing etc." }, { "code": null, "e": 7650, "s": 7330, "text": "WebAssembly is a new language with binary instruction that can load and execute faster. The task stated above, can be easily done in high level languages like C, C++, Rust etc. We need a way that, the code we have in C, C++, Rust can be compiled and can use it in web browsers. The same is achievable using WebAssembly." }, { "code": null, "e": 7811, "s": 7650, "text": "When the WebAssembly code is loaded inside the browser. Then, the browser takes care of converting into machine format that can be understood by the processors." }, { "code": null, "e": 7989, "s": 7811, "text": "For javascript the code has to be downloaded, parsed and converted to machine format. A lot of time goes into it and for heavy tasks like, we mentioned earlier can be very slow." }, { "code": null, "e": 8101, "s": 7989, "text": "High level languages like C, C++ and Rust are compiled into binary format, that is, .wasm and text format .wat." }, { "code": null, "e": 8252, "s": 8101, "text": "The source code written in C, C++ and Rust is compiled to .wasm using a compiler. You can make use of the Emscripten SDK for compiling C/C++ to .wasm." }, { "code": null, "e": 8277, "s": 8252, "text": "The flow is as follows −" }, { "code": null, "e": 8438, "s": 8277, "text": "C/C++ code can be compiled to .wasm using Emscripten SDK. Later, the .wasm code can be used with the help of javascript in your html file to display the output." }, { "code": null, "e": 8480, "s": 8438, "text": "The Key concepts are as explained below −" }, { "code": null, "e": 8649, "s": 8480, "text": "A module is an object that is compiled by the browser to executable machine code. A module is said to be stateless and it can be shared between windows and web workers." }, { "code": null, "e": 8785, "s": 8649, "text": "Memory in WebAssembly, is an arraybuffer that holds the data. You can allocate memory by using the Javascript api WebAssembly.memory()." }, { "code": null, "e": 8947, "s": 8785, "text": "Table in WebAssembly is a typed array that is, outside WebAssembly memory and mostly has a reference to functions. It stores the memory address of the functions." }, { "code": null, "e": 9078, "s": 8947, "text": "Instance is an object that will have, all the exported functions that can be called from javascript to execute inside the browser." }, { "code": null, "e": 9322, "s": 9078, "text": "WebAssembly is also called wasm, which is an improvement to Javascript. It is designed to run inside browsers just like javascript and also with nodejs. You happen to get wasm output, when any high level language like C, C++, Rust is compiled." }, { "code": null, "e": 9357, "s": 9322, "text": "Consider the following C program −" }, { "code": null, "e": 9459, "s": 9357, "text": "int factorial(int n) {\n if (n == 0) \n return 1; \n else \n return n * factorial(n-1); \n}\n" }, { "code": null, "e": 9591, "s": 9459, "text": "Make use of WasmExplorer, which is available at https://mbebenita.github.io/WasmExplorer/ to get the compiled code as shown below −" }, { "code": null, "e": 9662, "s": 9591, "text": "The WebAssembly text format for factorial program is as stated below −" }, { "code": null, "e": 10576, "s": 9662, "text": "(module \n (table 0 anyfunc) \n (memory $0 1) \n (export \"memory\" (memory $0)) (export \"factorial\" (func $factorial)) \n (func $factorial (; 0 ;) (param $0 i32) (result i32)\n (local $1 i32) \n (local $2 i32) \n (block $label$0 \n (br_if $label$0 \n (i32.eqz \n (get_local $0) \n )\n )\n (set_local $2 \n (i32.const 1) \n ) \n (loop $label$1 \n (set_local $2 \n (i32.mul \n (get_local $0) (get_local $2) \n ) \n ) \n (set_local $0 \n (tee_local $1 (i32.add \n (get_local $0) (i32.const -1) \n ) \n ) \n ) \n (br_if $label$1 (get_local $1) \n ) \n ) \n (return \n (get_local $2)\n ) \n ) \n (i32.const 1) \n )\n)" }, { "code": null, "e": 10667, "s": 10576, "text": "Using the Wat2Wasm tool, you can view the WASM code, just like how it is mentioned below −" }, { "code": null, "e": 10806, "s": 10667, "text": "Developers are not supposed to write code in wasm or learn to code in it, as it is mostly generated when you compile high level languages." }, { "code": null, "e": 10933, "s": 10806, "text": "In WASM, all the instructions are pushed on to the stack. The arguments are popped and the result is pushed back to the stack." }, { "code": null, "e": 11002, "s": 10933, "text": "Consider the following WebAssembly Text format that adds 2 numbers −" }, { "code": null, "e": 11159, "s": 11002, "text": "(module\n (func $add (param $a i32) (param $b i32) (result i32) \n get_local $a \n get_local $b \n i32.add\n )\n (export \"add\" (func $add))\n)" }, { "code": null, "e": 11361, "s": 11159, "text": "The name of the function is $add, it takes in 2 params $a and $b. The result is a type 32-bit integer. The local variables are accessed using get_local and the add operation is performed using i32.add." }, { "code": null, "e": 11440, "s": 11361, "text": "The stack representation to add 2 numbers while execution will be as follows −" }, { "code": null, "e": 11549, "s": 11440, "text": "In step 1 − The execution of get_local $a instruction, the first parameters i.e., $a is pushed on the stack." }, { "code": null, "e": 11662, "s": 11549, "text": "In step 2 − During execution of get_local $b instruction, the second parameters i.e., $b is pushed on the stack." }, { "code": null, "e": 11867, "s": 11662, "text": "In step 3 − The execution of i32.add will pop the elements from the stack and will push the result back to the stack. The value that remains in the end inside the stack is the result of the function $add." }, { "code": null, "e": 12109, "s": 11867, "text": "In this chapter, will learn how to install Emscripten SDK to compile C/C++. Emscripten is a Low level virtual machine (LLVM) that takes bytecode generated from C/C++ and compiles it into JavaScript that can easily execute inside the browser." }, { "code": null, "e": 12183, "s": 12109, "text": "To compile C/C++ to WebAssembly, we need to first install Emscripten sdk." }, { "code": null, "e": 12236, "s": 12183, "text": "The steps to install Emscripten sdk are as follows −" }, { "code": null, "e": 12324, "s": 12236, "text": "Step 1 − Clone the emsdk repo : git clone https://github.com/emscripten-core/emsdk.git." }, { "code": null, "e": 12792, "s": 12324, "text": "E:\\wa>git clone https://github.com/emscripten-core/emsdk.git \nCloning into 'emsdk'... \nremote: Enumerating objects: 14, done. \nremote: Counting objects: 100% (14/14), done. \nremote: Compressing objects: 100% (12/12), done. \nremote: Total 1823 (delta 4), reused 4 (delta 2), pack-reused 1809 receiving obje \ncts: 99% (1819/1823), 924.01 KiB | 257.00 KiB/s \nReceiving objects: 100% (1823/1823), 1.01 MiB | 257.00 KiB/s, done. \nResolving deltas: 100% (1152/1152), done.\n" }, { "code": null, "e": 12835, "s": 12792, "text": "Step 2 − Enter inside the directory emsdk." }, { "code": null, "e": 12845, "s": 12835, "text": "cd emsdk\n" }, { "code": null, "e": 12894, "s": 12845, "text": "Step 3 − For windows: Execute following command." }, { "code": null, "e": 12916, "s": 12894, "text": "emsdk install latest\n" }, { "code": null, "e": 13048, "s": 12916, "text": "For linux, this command will take some time to install the necessary tools like java, python etc. Follow the below mentioned code −" }, { "code": null, "e": 13072, "s": 13048, "text": "./emsdk install latest\n" }, { "code": null, "e": 13148, "s": 13072, "text": "Step 4 − To activate latest SDK execute following command in your terminal." }, { "code": null, "e": 13193, "s": 13148, "text": "For windows, execute the following command −" }, { "code": null, "e": 13216, "s": 13193, "text": "emsdk activate latest\n" }, { "code": null, "e": 13265, "s": 13216, "text": "For linux, execute the below mentioned command −" }, { "code": null, "e": 13290, "s": 13265, "text": "./emsdk activate latest\n" }, { "code": null, "e": 13388, "s": 13290, "text": "Step 5 − To activate PATH and other environment variables run following command in your terminal." }, { "code": null, "e": 13423, "s": 13388, "text": "For windows, execute the command −" }, { "code": null, "e": 13438, "s": 13423, "text": "emsdk_env.bat\n" }, { "code": null, "e": 13481, "s": 13438, "text": "For linux, execute the following command −" }, { "code": null, "e": 13504, "s": 13481, "text": "source ./emsdk_env.sh\n" }, { "code": null, "e": 13630, "s": 13504, "text": "We are done installing the emsdk and can now compile C or C++ code. The compiling of C/C++ will be done in the next chapters." }, { "code": null, "e": 13686, "s": 13630, "text": "To compile any C or C++ code following is the command −" }, { "code": null, "e": 13740, "s": 13686, "text": "emcc source.c or source.cpp -s WASM=1 -o source.html\n" }, { "code": null, "e": 13944, "s": 13740, "text": "The output will give you a source.html file, source.js and source.wasm files. The js will have the api that will fetch the source.wasm and you can see the output, when you hit source.html in the browser." }, { "code": null, "e": 14051, "s": 13944, "text": "To just get the wasm file you can use following command. This command will give you only source.wasm file." }, { "code": null, "e": 14099, "s": 14051, "text": "emcc source.c or source.cpp -s STANDALONE_WASM\n" }, { "code": null, "e": 14259, "s": 14099, "text": "This chapter will discuss some easy to use tools that are very helpful, while working with WebAssembly. Let us begin by learning about WebAssembly.studio tool." }, { "code": null, "e": 14317, "s": 14259, "text": "This tool allows you to compile C, Rust, Wat to Wasm etc." }, { "code": null, "e": 14437, "s": 14317, "text": "To start with you can click on Empty C Project, Empty Rust Project, Empty Wat Project to compile C and Rust to WASM. 5." }, { "code": null, "e": 14666, "s": 14437, "text": "It has Build, Run to build the code and check the output. The download button allows you to download .wasm file, that can be used to test inside browser. This tool is very helpful to compile C and Rust code and check the output." }, { "code": null, "e": 14869, "s": 14666, "text": "WebAssembly Explorer allows you to compile C and C++ code. Refer the link https://mbebenita.github.io/WasmExplorer/ for more details. The screen that will appear after clicking the link is shown below −" }, { "code": null, "e": 14953, "s": 14869, "text": "You can choose the C and C++ version. The source code of C or C++ is written here −" }, { "code": null, "e": 15083, "s": 14953, "text": "Once, you click on Compile button, it gives the WebAssembly text format (WAT) and Firefox x86 Assembly code in the blocks below −" }, { "code": null, "e": 15146, "s": 15083, "text": "You can download the .wasm code to test it inside the browser." }, { "code": null, "e": 15324, "s": 15146, "text": "Wasmfiddle helps you to compile C code to WebAssembly and also test the output. After clicking on the link https://wasdk.github.io/WasmFiddle/, you will see the following page −" }, { "code": null, "e": 15472, "s": 15324, "text": "Click on Build to compile the code. You can download the Wat and Wasm code by clicking on the Wat and Wasm. To test the output click on Run button." }, { "code": null, "e": 15692, "s": 15472, "text": "The tool wat2wasm will give you wasm code when you enter the WebAssembly text format. You can click on the link https://webassembly.github.io/wabt/demo/wat2wasm/ for demo and the screen that will appear is given below −" }, { "code": null, "e": 15793, "s": 15692, "text": "You can make use of the upload button to upload .wasm and the textarea will display the text format." }, { "code": null, "e": 16013, "s": 15793, "text": "The tool wat2wasm will give you wasm code when you enter the WebAssembly text format. You can click on the link https://webassembly.github.io/wabt/demo/wat2wasm/ for demo and the screen that will appear is given below −" }, { "code": null, "e": 16189, "s": 16013, "text": "This tool is very helpful, as it helps to get the output also tested. You can enter the WAT code and take a look at the .wasm code and also execute the code to see the output." }, { "code": null, "e": 16377, "s": 16189, "text": "WebAssembly, also called WASM, is binary format low level code developed to be executed inside browsers in the most efficient way. WebAssembly code is structured with following concepts −" }, { "code": null, "e": 16384, "s": 16377, "text": "Values" }, { "code": null, "e": 16390, "s": 16384, "text": "Types" }, { "code": null, "e": 16403, "s": 16390, "text": "Instructions" }, { "code": null, "e": 16436, "s": 16403, "text": "Let us learn them in detail now." }, { "code": null, "e": 16562, "s": 16436, "text": "Values in WebAssembly are meant to store complex data such as text, strings and vectors. WebAssembly supports the following −" }, { "code": null, "e": 16568, "s": 16562, "text": "Bytes" }, { "code": null, "e": 16577, "s": 16568, "text": "Integers" }, { "code": null, "e": 16592, "s": 16577, "text": "Floating point" }, { "code": null, "e": 16598, "s": 16592, "text": "Names" }, { "code": null, "e": 16697, "s": 16598, "text": "Bytes is the simplest form of values supported in WebAssembly. The value is in hexadecimal format." }, { "code": null, "e": 16768, "s": 16697, "text": "Bytes represented as b, can also take natural numbers n, where n <256." }, { "code": null, "e": 16795, "s": 16768, "text": "byte ::= 0x00| .... |0xFF\n" }, { "code": null, "e": 16851, "s": 16795, "text": "In WebAssembly, integers supported are as given below −" }, { "code": null, "e": 16871, "s": 16851, "text": "i32: 32-bit integer" }, { "code": null, "e": 16891, "s": 16871, "text": "i64: 64-bit integer" }, { "code": null, "e": 16956, "s": 16891, "text": "In WebAssembly floating point numbers supported are as follows −" }, { "code": null, "e": 16983, "s": 16956, "text": "f32: 32-bit floating point" }, { "code": null, "e": 17010, "s": 16983, "text": "f64: 64-bit floating point" }, { "code": null, "e": 17176, "s": 17010, "text": "Names are sequence of character, with scalar values defined by Unicode, which is available at the link http://www.unicode.org/versions/Unicode12.1.0/ given herewith." }, { "code": null, "e": 17271, "s": 17176, "text": "The entities in WebAssembly are classified as types. The types supported are as stated below −" }, { "code": null, "e": 17283, "s": 17271, "text": "Value Types" }, { "code": null, "e": 17296, "s": 17283, "text": "Result Types" }, { "code": null, "e": 17311, "s": 17296, "text": "Function Types" }, { "code": null, "e": 17318, "s": 17311, "text": "Limits" }, { "code": null, "e": 17331, "s": 17318, "text": "Memory Types" }, { "code": null, "e": 17343, "s": 17331, "text": "Table Types" }, { "code": null, "e": 17356, "s": 17343, "text": "Global Types" }, { "code": null, "e": 17371, "s": 17356, "text": "External Types" }, { "code": null, "e": 17401, "s": 17371, "text": "Let us study them one by one." }, { "code": null, "e": 17467, "s": 17401, "text": "The values type supported by WebAssembly are as mentioned below −" }, { "code": null, "e": 17487, "s": 17467, "text": "i32: 32-bit integer" }, { "code": null, "e": 17507, "s": 17487, "text": "i64: 64-bit integer" }, { "code": null, "e": 17534, "s": 17507, "text": "f32: 32-bit floating point" }, { "code": null, "e": 17561, "s": 17534, "text": "f64: 64-bit floating point" }, { "code": null, "e": 17590, "s": 17561, "text": "valtype ::= i32|i64|f32|f64\n" }, { "code": null, "e": 17755, "s": 17590, "text": "The values written inside brackets are executed and stored inside result types. The result type is the output of the execution of a block of code made up of values." }, { "code": null, "e": 17780, "s": 17755, "text": "resulttype::=[valtype?]\n" }, { "code": null, "e": 17859, "s": 17780, "text": "A function type will take in vector of parameters returns a vector of results." }, { "code": null, "e": 17904, "s": 17859, "text": "functype::=[vec(valtype)]--> [vec(valtype)]\n" }, { "code": null, "e": 17969, "s": 17904, "text": "Limits are the storage range linked with memory and table types." }, { "code": null, "e": 18000, "s": 17969, "text": "limits ::= {min u32, max u32}\n" }, { "code": null, "e": 18059, "s": 18000, "text": "Memory types deal with linear memories and the size range." }, { "code": null, "e": 18079, "s": 18059, "text": "memtype ::= limits\n" }, { "code": null, "e": 18142, "s": 18079, "text": "Table Types are classified by the element type assigned to it." }, { "code": null, "e": 18194, "s": 18142, "text": "tabletype ::= limits elemtype\nelemtype ::= funcref\n" }, { "code": null, "e": 18280, "s": 18194, "text": "Table type is dependent on the limit for the minimum and maximum size assigned to it." }, { "code": null, "e": 18376, "s": 18280, "text": "Global Type holds the global variables that have the value, that can change or remain the same." }, { "code": null, "e": 18422, "s": 18376, "text": "globaltype ::= mut valtype\nmut ::= const|var\n" }, { "code": null, "e": 18477, "s": 18422, "text": "External Types deals with imports and external values." }, { "code": null, "e": 18559, "s": 18477, "text": "externtype ::= func functype | table tabletype | mem memtype | global globaltype\n" }, { "code": null, "e": 18730, "s": 18559, "text": "WebAssembly code is a sequence of instructions that follows a stack machine model. As WebAssembly follows a stack machine model, the instructions are pushed on the stack." }, { "code": null, "e": 18923, "s": 18730, "text": "The argument values for a function, for example, are popped from stack and the result is pushed back on the stack. In the end, there will be only one value in the stack and that is the result." }, { "code": null, "e": 18979, "s": 18923, "text": "Some of the commonly used Instructions are as follows −" }, { "code": null, "e": 19000, "s": 18979, "text": "Numeric Instructions" }, { "code": null, "e": 19022, "s": 19000, "text": "Variable Instructions" }, { "code": null, "e": 19097, "s": 19022, "text": "Numeric Instructions are operations, which are performed on numeric value." }, { "code": null, "e": 19253, "s": 19097, "text": "nn, mm ::= 32|64\nibinop ::= add|sub|mul|div_sx|rem_sx|and|or|xor\nirelop ::= eq | ne | lt_sx | gt_sx | le_sx | ge_sx\nfrelop ::= eq | ne | lt | gt | le | ge\n" }, { "code": null, "e": 19327, "s": 19253, "text": "Variable instructions are about accessing the local and global variables." }, { "code": null, "e": 19339, "s": 19327, "text": "For example" }, { "code": null, "e": 19367, "s": 19339, "text": "To access local variables −" }, { "code": null, "e": 19394, "s": 19367, "text": "get_local $a\nget_local $b\n" }, { "code": null, "e": 19419, "s": 19394, "text": "To set local variables −" }, { "code": null, "e": 19446, "s": 19419, "text": "set_local $a\nset_local $b\n" }, { "code": null, "e": 19475, "s": 19446, "text": "To access global variables −" }, { "code": null, "e": 19504, "s": 19475, "text": "get_global $a\nget_global $b\n" }, { "code": null, "e": 19530, "s": 19504, "text": "To set global variables −" }, { "code": null, "e": 19559, "s": 19530, "text": "set_global $a\nset_global $b\n" }, { "code": null, "e": 19637, "s": 19559, "text": "This chapter will list out the comparison between WebAssembly and Javascript." }, { "code": null, "e": 19786, "s": 19637, "text": "Javascript is a language, that we have used a lot inside the browser. Now, with WebAssembly release, we can also use WebAssembly inside the browser." }, { "code": null, "e": 19948, "s": 19786, "text": "The reason for WebAssembly to come into existence is not to replace javascript, but to take care of certain things, that are difficult to handle with javascript." }, { "code": null, "e": 19960, "s": 19948, "text": "For example" }, { "code": null, "e": 20212, "s": 19960, "text": "It is difficult to get the tasks such as Image recognition, CAD applications, Live video augmentation, VR and augmented reality, Music applications, Scientific visualization and simulation, Games, Image / video editing etc. to be done with javascript." }, { "code": null, "e": 20434, "s": 20212, "text": "Using high level languages like C/C++, Rust, which now can be compiled to WebAssembly, it is easy to get the task mentioned above to be done. WebAssembly generates a binary code that is easy to execute inside the browser." }, { "code": null, "e": 20510, "s": 20434, "text": "So here, is the list of comparison done between Javascript and WebAssembly." }, { "code": null, "e": 20517, "s": 20510, "text": "Coding" }, { "code": null, "e": 20672, "s": 20517, "text": "You can easily write code in Javascript. The code written is human readable and saved as .js. When used inside the browser you need to use a <script> tag." }, { "code": null, "e": 20907, "s": 20672, "text": "The code can be written in text format in WebAssembly and it is saved as .wat. It is difficult to write the code in .wat format. It is best to compile the code from some other high level language instead of writing from start in .wat." }, { "code": null, "e": 21034, "s": 20907, "text": "You cannot execute the .wat file inside the browser and has to convert to .wasm using the compilers or online tools available." }, { "code": null, "e": 21044, "s": 21034, "text": "Execution" }, { "code": null, "e": 21158, "s": 21044, "text": "The code written in javascript when used inside the browser has to be downloaded, parsed, compiled and optimized." }, { "code": null, "e": 21231, "s": 21158, "text": "We have WebAssembly code in .wasm already compiled and in binary format." }, { "code": null, "e": 21249, "s": 21231, "text": "Memory Management" }, { "code": null, "e": 21381, "s": 21249, "text": "Javascript assigns memory when, variables are created and the memory is released when not used and are added to garbage collection." }, { "code": null, "e": 21516, "s": 21381, "text": "Memory in WebAssembly is an arraybuffer that holds the data. You can allocate memory by using the Javascript API WebAssembly.memory()." }, { "code": null, "e": 21643, "s": 21516, "text": "WebAssembly memory is stored in an array format i.e. a flat memory model that is easy to understand and perform the execution." }, { "code": null, "e": 21696, "s": 21643, "text": "The disadvantage of memory model in WebAssembly is −" }, { "code": null, "e": 21728, "s": 21696, "text": "Complex calculation takes time." }, { "code": null, "e": 21760, "s": 21728, "text": "Complex calculation takes time." }, { "code": null, "e": 21874, "s": 21760, "text": "Webassembly does not support garbage collection that does not allow reuse of the memory and the memory is wasted." }, { "code": null, "e": 21988, "s": 21874, "text": "Webassembly does not support garbage collection that does not allow reuse of the memory and the memory is wasted." }, { "code": null, "e": 22012, "s": 21988, "text": "Load Time & Performance" }, { "code": null, "e": 22237, "s": 22012, "text": "In case of javascript, when called inside the browser, the javascript file has to be downloaded, and parsed. Later, the parser converts the source code to bytecode that the javascript engine executes the code in the browser." }, { "code": null, "e": 22374, "s": 22237, "text": "The Javascript engine is very powerful and hence, the load time and performance of javascript is very fast in comparison to WebAssembly." }, { "code": null, "e": 22544, "s": 22374, "text": "A most important goal of WebAssembly is to be faster than JavaScript.Wasm code generated from high-level languages is smaller in size and hence, the load time is faster." }, { "code": null, "e": 22641, "s": 22544, "text": "But, languages like GO, when compiled to wasm produce a big file size for a small piece of code." }, { "code": null, "e": 22859, "s": 22641, "text": "WebAssembly is designed in such a way that it is faster in compilation, and can run across all the major browsers. WebAssembly still has to add lots of improvements in terms of performance in comparison to javascript." }, { "code": null, "e": 22869, "s": 22859, "text": "Debugging" }, { "code": null, "e": 23025, "s": 22869, "text": "Javascript is human-readable and can be debugged easily. Adding breakpoints to your javascript code inside the browser allows you to easily debug the code." }, { "code": null, "e": 23204, "s": 23025, "text": "WebAssembly provides the code in text format, that is readable but, still very difficult to debug. Firefox does allow you to view the wasm code in .wat format inside the browser." }, { "code": null, "e": 23299, "s": 23204, "text": "You cannot add breakpoints in .wat and that is something that will be available in the future." }, { "code": null, "e": 23315, "s": 23299, "text": "Browser Support" }, { "code": null, "e": 23354, "s": 23315, "text": "Javascript works well in all browsers." }, { "code": null, "e": 23407, "s": 23354, "text": "All major web browsers have support for WebAssembly." }, { "code": null, "e": 23547, "s": 23407, "text": "In this chapter, we will understand how to load the wasm code and execute them in the browser using the help of javascript webassembly API." }, { "code": null, "e": 23649, "s": 23547, "text": "Here are some important API's, we are going to make use throughout the tutorial to execute wasm code." }, { "code": null, "e": 23669, "s": 23649, "text": "fetch() Browser API" }, { "code": null, "e": 23689, "s": 23669, "text": "WebAssembly.compile" }, { "code": null, "e": 23710, "s": 23689, "text": "WebAssembly.instance" }, { "code": null, "e": 23734, "s": 23710, "text": "WebAssembly.instantiate" }, { "code": null, "e": 23767, "s": 23734, "text": "WebAssembly.instantiateStreaming" }, { "code": null, "e": 23963, "s": 23767, "text": "Before we discuss the WebAssembly javascript API's, to test the API and the output we are going to use the following C program and the .wasm code generated from the c program using wasm explorer." }, { "code": null, "e": 24004, "s": 23963, "text": "An example for C Program is as follows −" }, { "code": null, "e": 24061, "s": 24004, "text": "#include<stdio.h>\nint square(int n) { \n return n*n; \n}" }, { "code": null, "e": 24119, "s": 24061, "text": "We will make use of WASM explorer, to get the wasm code −" }, { "code": null, "e": 24168, "s": 24119, "text": "Download WASM code and use it to test the API's." }, { "code": null, "e": 24221, "s": 24168, "text": "fetch() API is meant to load .wasm network resource." }, { "code": null, "e": 24306, "s": 24221, "text": "<script>\n var result = fetch(\"findsquare.wasm\");\n console.log(result);\n</script>" }, { "code": null, "e": 24344, "s": 24306, "text": "It returns a promise as shown below −" }, { "code": null, "e": 24427, "s": 24344, "text": "You can also make use of XMLHttpRequest method to fetch the wasm network resource." }, { "code": null, "e": 24512, "s": 24427, "text": "The api responsibility is to compile the module details that are fetched from .wasm." }, { "code": null, "e": 24543, "s": 24512, "text": "The syntax is as given below −" }, { "code": null, "e": 24573, "s": 24543, "text": "WebAssembly.compile(buffer);\n" }, { "code": null, "e": 24691, "s": 24573, "text": "Buffer − This code from .wasm has to be converted to a typed array or arraybuffer, before giving as input to compile." }, { "code": null, "e": 24752, "s": 24691, "text": "It will return a promise that will have the compiled module." }, { "code": null, "e": 24848, "s": 24752, "text": "Let us see one example, that gives the output as a compiled module using webAssembly.compile()." }, { "code": null, "e": 25077, "s": 24848, "text": "<script> \n fetch(\"findsquare.wasm\") .then(bytes => bytes.arrayBuffer()) \n .then(mod => {\n var compiledmod = WebAssembly.compile(mod);\n compiledmod.then(test=> {\n console.log(test); \n })\n })\n</script>" }, { "code": null, "e": 25167, "s": 25077, "text": "The console.log, when checked in the browser, will give you the compiled module details −" }, { "code": null, "e": 25315, "s": 25167, "text": "The module has a constructor object with imports, exports, and customSections. Let us see the next API, to get more details of the compiled module." }, { "code": null, "e": 25460, "s": 25315, "text": "Using the WebAssembly.instance, API will give you the executable instance of the compiled module that can be further executed to get the output." }, { "code": null, "e": 25491, "s": 25460, "text": "The syntax is as given below −" }, { "code": null, "e": 25534, "s": 25491, "text": "new WebAssembly.Instance(compiled module)\n" }, { "code": null, "e": 25626, "s": 25534, "text": "The return value will be an object with the array of exports function that can be executed." }, { "code": null, "e": 25881, "s": 25626, "text": "<script> \n fetch(\"findsquare.wasm\") \n .then(bytes => bytes.arrayBuffer())\n .then(mod => WebAssembly.compile(mod)).then(module => {\n let instance = new WebAssembly.Instance(module); \n console.log(instance); \n })\n</script>\n" }, { "code": null, "e": 25951, "s": 25881, "text": "The output will give us an array of exports function as shown below −" }, { "code": null, "e": 26030, "s": 25951, "text": "You can see the square function, that we got from the C code that is compiled." }, { "code": null, "e": 26089, "s": 26030, "text": "To execute the square function, you can do the following −" }, { "code": null, "e": 26351, "s": 26089, "text": "<script>\n fetch(\"findsquare.wasm\") \n .then(bytes => bytes.arrayBuffer()) \n .then(mod => WebAssembly.compile(mod)) \n .then(module => { \n let instance = new WebAssembly.Instance(module);\n console.log(instance.exports.square(15));\n })\n</script>" }, { "code": null, "e": 26372, "s": 26351, "text": "The output will be −" }, { "code": null, "e": 26377, "s": 26372, "text": "225\n" }, { "code": null, "e": 26449, "s": 26377, "text": "This API takes care of compiling and instantiating the module together." }, { "code": null, "e": 26476, "s": 26449, "text": "The syntax is as follows −" }, { "code": null, "e": 26528, "s": 26476, "text": "WebAssembly.instantiate(arraybuffer, importObject)\n" }, { "code": null, "e": 26651, "s": 26528, "text": "arraybuffer − The code from .wasm has to be converted to typed array or arraybuffer before giving as input to instantiate." }, { "code": null, "e": 26842, "s": 26651, "text": "importObject − The import object has to have details of the memory, imported functions to be used inside the module. It can be an empty module object, in case, there is nothing to be shared." }, { "code": null, "e": 26912, "s": 26842, "text": "It will return a promise, that will have module and instance details." }, { "code": null, "e": 27262, "s": 26912, "text": "<script type=\"text/javascript\">\n const importObj = {\n module: {}\n };\n fetch(\"findsquare.wasm\")\n .then(bytes => bytes.arrayBuffer())\n .then(module => WebAssembly.instantiate(module, importObj)) \n .then(finalcode => { \n console.log(finalcode); console.log(finalcode.instance.exports.square(25)); \n }); \n</script>" }, { "code": null, "e": 27330, "s": 27262, "text": "When you execute the code, you will get the below mentioned output." }, { "code": null, "e": 27438, "s": 27330, "text": "This API takes care of compiling as well as instantiating the WebAssembly module from the .wasm code given." }, { "code": null, "e": 27469, "s": 27438, "text": "The syntax is as given below −" }, { "code": null, "e": 27528, "s": 27469, "text": "WebAssembly.instantiateStreaming(wasmcode, importObject);\n" }, { "code": null, "e": 27624, "s": 27528, "text": "wasmcode − Response from fetch or any other API that gives the wasm code and returns a promise." }, { "code": null, "e": 27813, "s": 27624, "text": "importObject − The import object has to have details of the memory, imported functions to be used inside the module. It can be an empty module object in case there is nothing to be shared." }, { "code": null, "e": 27883, "s": 27813, "text": "It will return a promise, that will have module and instance details." }, { "code": null, "e": 27915, "s": 27883, "text": "An example is discussed below −" }, { "code": null, "e": 28130, "s": 27915, "text": "<script type=\"text/javascript\"> \n const importObj = { \n module: {} \n };\n WebAssembly.instantiateStreaming(fetch(\"findsquare.wasm\"), importObj).then(obj => {\n console.log(obj); \n }); \n</script>" }, { "code": null, "e": 28187, "s": 28130, "text": "When you test it in the browser, you will see an error −" }, { "code": null, "e": 28347, "s": 28187, "text": "To make it work at your server end, you will have to add the mime type application/wasm or else make use of WebAssembly.instantiate(arraybuffer, importObject)." }, { "code": null, "e": 28535, "s": 28347, "text": "WebAssembly support is added to all the latest browsers available with you today like Chrome, Firefox. The Firefox version 54+ onwards gives you a special feature to debug your wasm code." }, { "code": null, "e": 28681, "s": 28535, "text": "To do that, execute your code inside Firefox browsers that call wasm. For example, consider following C code that finds the square of the number." }, { "code": null, "e": 28726, "s": 28681, "text": "An example for the C Program is as follows −" }, { "code": null, "e": 28781, "s": 28726, "text": "#include<stdio.h>\nint square(int n) {\n return n*n;\n}" }, { "code": null, "e": 28838, "s": 28781, "text": "We will make use of WASM explorer to get the wasm code −" }, { "code": null, "e": 28902, "s": 28838, "text": "Download WASM code and use it to see the output in the browser." }, { "code": null, "e": 28952, "s": 28902, "text": "The html file that loads the wasm is as follows −" }, { "code": null, "e": 29779, "s": 28952, "text": "!doctype html> \n<html>\n <head>\n <meta charset=\"utf-8\"> \n <title>WebAssembly Square function</title> \n <style> \n div { \n font-size : 30px; text-align : center; color:orange; \n } \n </style> \n </head> \n <body> \n <div id=\"textcontent\"></div> \n <script> \n let square; \n fetch(\"findsquare.wasm\").then(bytes => bytes.arrayBuffer()) \n .then(mod => WebAssembly.compile(mod)) \n .then(module => {return new WebAssembly.Instance(module) }) \n .then(instance => { \n square = instance.exports.square(13);\n console.log(\"The square of 13 = \" +square); \n document.getElementById(\"textcontent\").innerHTML = \"The square of 13 = \" +square; \n }); \n </script> \n </body> \n</html>" }, { "code": null, "e": 29862, "s": 29779, "text": "Open your Firefox browser and load the above html file and open the debugger tool." }, { "code": null, "e": 29998, "s": 29862, "text": "You should see wasm:// entry in the debugger tool. Click on wasm:// and it shows the wasm code converted to .wat format as shown above." }, { "code": null, "e": 30204, "s": 29998, "text": "You can take a look at the code of the exported function and can debug the code, if any issue comes up. Firefox also intends to add breakpoints, so that you can debug the code and check the execution flow." }, { "code": null, "e": 30357, "s": 30204, "text": "In this chapter we are going to write a simple program in C and convert it into .wasm and execute the same in the browser to get the text \"Hello World\"." }, { "code": null, "e": 30488, "s": 30357, "text": "Will make use of wasm explorer tool that will convert the C program to .wasm and will make use of the .wasm inside our .html file." }, { "code": null, "e": 30594, "s": 30488, "text": "The Wasm explorer tool which is available at https://mbebenita.github.io/WasmExplorer/ looks as follows −" }, { "code": null, "e": 30646, "s": 30594, "text": "The C code that we are going to use is as follows −" }, { "code": null, "e": 30711, "s": 30646, "text": "#include <stdio.h>\nchar *c_hello() {\n return \"Hello World\"; \n}" }, { "code": null, "e": 30784, "s": 30711, "text": "Update the first block in wasm explorer with the C code as shown below −" }, { "code": null, "e": 30881, "s": 30784, "text": "Click on COMPILE Button to compile to WASM and WAT and Firefox x86 Web Assembly as shown below −" }, { "code": null, "e": 30951, "s": 30881, "text": "Use the DOWNLOAD to get the .wasm file and save it as firstprog.wasm." }, { "code": null, "e": 31010, "s": 30951, "text": "Create a .html file called firstprog.html as shown below −" }, { "code": null, "e": 31299, "s": 31010, "text": "<!doctype html>\n<html>\n <head>\n <meta charset=\"utf-8\"> \n <title>WebAssembly Hello World</title> \n </head> \n <body>\n <div id=\"textcontent\"></div> \n <script type=\"text/javascript\"> \n //Your code from webassembly here\n </script> \n </body>\n</html>" }, { "code": null, "e": 31383, "s": 31299, "text": "Let us now use firstprog.wasm to read the helloworld from the C function c_hello()." }, { "code": null, "e": 31432, "s": 31383, "text": "Use fetch() api to read the firstprog.wasm code." }, { "code": null, "e": 31580, "s": 31432, "text": "The .wasm code has to be converted into arraybuffer by using ArrayBuffer. The ArrayBuffer object will return you a fixed length binary data buffer." }, { "code": null, "e": 31617, "s": 31580, "text": "The code so far will be as follows −" }, { "code": null, "e": 31725, "s": 31617, "text": "<script type=\"text/javascript\"> \n fetch(\"firstprog.wasm\") .then(bytes => bytes.arrayBuffer()) \n</script>\n" }, { "code": null, "e": 31833, "s": 31725, "text": "The bytes from ArrayBuffer have to be compiled into a module by using WebAssembly.compile(buffer) function." }, { "code": null, "e": 31865, "s": 31833, "text": "The code will look like below −" }, { "code": null, "e": 32015, "s": 31865, "text": "<script type=\"text/javascript\">\n fetch(\"firstprog.wasm\")\n .then(bytes => bytes.arrayBuffer())\n .then(mod => WebAssembly.compile(mod))\n</script>" }, { "code": null, "e": 32103, "s": 32015, "text": "To get the module we have to call the webassembly.instance constructor as shown below −" }, { "code": null, "e": 32323, "s": 32103, "text": "<script type=\"text/javascript\"> \n fetch(\"firstprog.wasm\") \n .then(bytes => bytes.arrayBuffer())\n .then(mod => WebAssembly.compile(mod))\n .then(module => {return new WebAssembly.Instance(module) }) \n</script>" }, { "code": null, "e": 32390, "s": 32323, "text": "Let us now console the instance to see the details in the browser." }, { "code": null, "e": 32671, "s": 32390, "text": "<script type=\"text/javascript\"> \n fetch(\"firstprog.wasm\") .then(bytes => bytes.arrayBuffer()) \n .then(mod => WebAssembly.compile(mod)) .then(module => {\n return new WebAssembly.Instance(module) \n }) \n .then(instance => {\n console.log(instance);\n }); \n</script>" }, { "code": null, "e": 32713, "s": 32671, "text": "The console.log details are shown below −" }, { "code": null, "e": 32814, "s": 32713, "text": "To get the string “Hello World” from the function c_hello(), we need to add some code in javascript." }, { "code": null, "e": 32868, "s": 32814, "text": "First, get the memory buffer details as shown below −" }, { "code": null, "e": 32915, "s": 32868, "text": "let buffer = instance.exports.memory.buffer;;\n" }, { "code": null, "e": 33054, "s": 32915, "text": "The buffer value has to be converted to a typed array so that we can read the values from it. The buffer has the string Hello World in it." }, { "code": null, "e": 33123, "s": 33054, "text": "To convert to typed call the constructor Uint8Array as shown below −" }, { "code": null, "e": 33185, "s": 33123, "text": "let buffer = new Uint8Array(instance.exports.memory.buffer);\n" }, { "code": null, "e": 33245, "s": 33185, "text": "Now, we can read the value from the buffer in a for - loop." }, { "code": null, "e": 33346, "s": 33245, "text": "Let us now get the start point to read the buffer, by calling the function we wrote as shown below −" }, { "code": null, "e": 33386, "s": 33346, "text": "let test = instance.exports.c_hello();\n" }, { "code": null, "e": 33537, "s": 33386, "text": "Now, the test variable has the start point to read our string. WebAssembly does not have anything for string values, everything is stored as integers." }, { "code": null, "e": 33687, "s": 33537, "text": "So when, we read the value from the buffer, they will be an integer value and we need to convert it into a string using fromCharCode() in javascript." }, { "code": null, "e": 33712, "s": 33687, "text": "The code is as follows −" }, { "code": null, "e": 33812, "s": 33712, "text": "let mytext = \"\"; \nfor (let i=test; buffer[i]; i++){ \n mytext += String.fromCharCode(buffer[i]);\n}" }, { "code": null, "e": 33882, "s": 33812, "text": "Now, when you console mytext you should see the string “Hello World”." }, { "code": null, "e": 33916, "s": 33882, "text": "The complete code is as follows −" }, { "code": null, "e": 34900, "s": 33916, "text": "<!doctype html> \n<html> \n <head> \n <meta charset=\"utf-8\"> \n <title>WebAssembly Add Function</title>\n <style>\n div { \n font-size : 30px; text-align : center; color:orange; \n } \n </style>\n </head>\n <body>\n <div id=\"textcontent\"></div>\n <script> \n fetch(\"firstprog.wasm\")\n .then(bytes => bytes.arrayBuffer())\n .then(mod => WebAssembly.compile(mod))\n .then(module => {return new WebAssembly.Instance(module)})\n .then(instance => { \n console.log(instance); \n let buffer = new Uint8Array(instance.exports.memory.buffer); \n let test = instance.exports.c_hello(); \n let mytext = \"\"; \n for (let i=test; buffer[i]; i++) {\n mytext += String.fromCharCode(buffer[i]);\n }\n console.log(mytext); document.getElementById(\"textcontent\").innerHTML = mytext; \n });\n </script>\n </body>\n</html>" }, { "code": null, "e": 35000, "s": 34900, "text": "We have added a div and the content is added to the div, so the string is displayed on the browser." }, { "code": null, "e": 35032, "s": 35000, "text": "The output is mentioned below −" }, { "code": null, "e": 35192, "s": 35032, "text": "We have seen how to get a .wasm file from c /c++ code. In this chapter, we will convert the wasm into a WebAssembly module and execute the same in the browser." }, { "code": null, "e": 35243, "s": 35192, "text": "Let us use the C++ Factorial code as shown below −" }, { "code": null, "e": 35336, "s": 35243, "text": "int fact(int n) {\n if ((n==0)||(n==1))\n return 1;\n else\n return n*fact(n-1);\n}" }, { "code": null, "e": 35436, "s": 35336, "text": "Open Wasm Explorer which is available at https://mbebenita.github.io/WasmExplorer/ as shown below −" }, { "code": null, "e": 35575, "s": 35436, "text": "The first column has the C++ factorial function, the 2nd column has the WebAssembly text format and the last column has x86 Assembly code." }, { "code": null, "e": 35605, "s": 35575, "text": "The WebAssembly Text format −" }, { "code": null, "e": 36751, "s": 35605, "text": "(module\n (table 0 anyfunc)\n (memory $0 1)\n (export \"memory\" (memory $0))\n (export \"_Z4facti\" (func $_Z4facti))\n (func $_Z4facti (; 0 ;) (param $0 i32) (result i32)\n (local $1 i32)\n (set_local $1\n (i32.const 1)\n )\n (block $label$0\n (br_if $label$0\n (i32.eq\n (i32.or\n (get_local $0)\n (i32.const 1)\n )\n (i32.const 1)\n )\n )\n (set_local $1\n (i32.const 1)\n )\n (loop $label$1\n (set_local $1\n (i32.mul\n (get_local $0)\n (get_local $1)\n )\n )\n (br_if $label$1\n (i32.ne\n (i32.or\n (tee_local $0\n (i32.add\n (get_local $0)\n (i32.const -1)\n )\n )\n (i32.const 1)\n )\n (i32.const 1)\n )\n )\n )\n )\n (get_local $1)\n )\n)" }, { "code": null, "e": 36833, "s": 36751, "text": "The C++ function fact has been exported as “_Z4facti” in WebAssembly Text format." }, { "code": null, "e": 36925, "s": 36833, "text": "Click on the download button to download the wasm code and save the file as factorial.wasm." }, { "code": null, "e": 36999, "s": 36925, "text": "Now to convert the .wasm code to the module we have to do the following −" }, { "code": null, "e": 37130, "s": 36999, "text": "Convert the .wasm into arraybuffer by using ArrayBuffer. The ArrayBuffer object will return you a fixed-length binary data buffer." }, { "code": null, "e": 37238, "s": 37130, "text": "The bytes from ArrayBuffer have to be compiled into a module by using WebAssembly.compile(buffer) function." }, { "code": null, "e": 37337, "s": 37238, "text": "The WebAssembly.compile() function compiles and returns a WebAssembly.Module from the bytes given." }, { "code": null, "e": 37401, "s": 37337, "text": "Here, is the Javascript code that is discussed in Step 1 and 2." }, { "code": null, "e": 37804, "s": 37401, "text": "<script type=\"text/javascript\">\n let factorial;\n fetch(\"factorial.wasm\")\n .then(bytes => bytes.arrayBuffer())\n .then(mod => WebAssembly.compile(mod))\n .then(module => {return new WebAssembly.Instance(module) })\n .then(instance => {\n \n factorial = instance.exports._Z4facti;\n console.log('Test the output in Brower Console by using factorial(n)');\n });\n</script>" }, { "code": null, "e": 37880, "s": 37804, "text": "Javascript browser API fetch is used to get the contents of factorial.wasm." }, { "code": null, "e": 37956, "s": 37880, "text": "Javascript browser API fetch is used to get the contents of factorial.wasm." }, { "code": null, "e": 38011, "s": 37956, "text": "The content is converted to bytes using arrayBuffer()." }, { "code": null, "e": 38066, "s": 38011, "text": "The content is converted to bytes using arrayBuffer()." }, { "code": null, "e": 38136, "s": 38066, "text": "The module is created from bytes by calling WebAssembly.compile(mod)." }, { "code": null, "e": 38206, "s": 38136, "text": "The module is created from bytes by calling WebAssembly.compile(mod)." }, { "code": null, "e": 38282, "s": 38206, "text": "The instance of a module is created using new\nWebAssembly.Instance(module)\n" }, { "code": null, "e": 38329, "s": 38282, "text": "The instance of a module is created using new\n" }, { "code": null, "e": 38358, "s": 38329, "text": "WebAssembly.Instance(module)" }, { "code": null, "e": 38470, "s": 38358, "text": "The factorial function export _Z4facti is assigned to variable factorial by using WebAssembly.Module.exports()." }, { "code": null, "e": 38582, "s": 38470, "text": "The factorial function export _Z4facti is assigned to variable factorial by using WebAssembly.Module.exports()." }, { "code": null, "e": 38640, "s": 38582, "text": "Here, is the module.html along with the javascript code −" }, { "code": null, "e": 38652, "s": 38640, "text": "module.html" }, { "code": null, "e": 39195, "s": 38652, "text": "<!doctype html>\n<html>\n <head>\n <meta charset=\"utf-8\">\n <title>WebAssembly Module</title>\n </head>\n <body>\n <script>\n let factorial;\n fetch(\"factorial.wasm\")\n .then(bytes => bytes.arrayBuffer())\n .then(mod => WebAssembly.compile(mod))\n .then(module => {return new WebAssembly.Instance(module) })\n .then(instance => {\n factorial = instance.exports._Z4facti;\n console.log('Test the output in Browser Console by using factorial(n)');\n });\n </script>\n </body>\n</html>" }, { "code": null, "e": 39250, "s": 39195, "text": "Execute module.html in the browser to see the output −" }, { "code": null, "e": 39424, "s": 39250, "text": "In this chapter, we are going to discuss the webassembly.validate() function that will validate the .wasm output. The .wasm is available when we compile C, C++ or rust code." }, { "code": null, "e": 39486, "s": 39424, "text": "You can make use of the following tools to get the wasm code." }, { "code": null, "e": 39557, "s": 39486, "text": "Wasm Fiddler,which is available at https://wasdk.github.io/WasmFiddle/" }, { "code": null, "e": 39628, "s": 39557, "text": "Wasm Fiddler,which is available at https://wasdk.github.io/WasmFiddle/" }, { "code": null, "e": 39715, "s": 39628, "text": "WebAssembly Explorer, which is available at https://mbebenita.github.io/WasmExplorer/." }, { "code": null, "e": 39802, "s": 39715, "text": "WebAssembly Explorer, which is available at https://mbebenita.github.io/WasmExplorer/." }, { "code": null, "e": 39833, "s": 39802, "text": "The syntax is as given below −" }, { "code": null, "e": 39870, "s": 39833, "text": "WebAssembly.validate(bufferSource);\n" }, { "code": null, "e": 40017, "s": 39870, "text": "bufferSource − The bufferSource has the binary code that comes from either C, C++ or Rust program. It is in the form of typedarray or ArrayBuffer." }, { "code": null, "e": 40092, "s": 40017, "text": "The function will return true if the .wasm code is valid and false if not." }, { "code": null, "e": 40247, "s": 40092, "text": "Let us try one example. Go to Wasm fiddler, which is available at https://wasdk.github.io/WasmFiddle/, enter C code of your choice and down the wasm code." }, { "code": null, "e": 40347, "s": 40247, "text": "The block marked in red is the C code. Click on the Build button at the center to execute the code." }, { "code": null, "e": 40469, "s": 40347, "text": "Click on the Wasm , button to download the .wasm code. Save the .wasm at your end and let us use the same for validating." }, { "code": null, "e": 40496, "s": 40469, "text": "For Example: validate.html" }, { "code": null, "e": 40997, "s": 40496, "text": "<!doctype html>\n<html>\n <head> \n <meta charset=\"utf-8\">\n <title>Testing WASM validate()</title>\n </head>\n <body>\n <script> \n fetch('program.wasm').then(res => res.arrayBuffer() ).then(function(testbytes) {\n var valid = WebAssembly.validate(testbytes); \n if (valid) {\n console.log(\"Valid Wasm Bytes!\"); \n } else {\n console.log(\"Invalid Wasm Code!\"); \n }\n }); \n </script> \n </body>\n</html>" }, { "code": null, "e": 41136, "s": 40997, "text": "I have hosted the above .html file in wamp server along with the download .wasm file. Here, is the output when you test it in the browser." }, { "code": null, "e": 41172, "s": 41136, "text": "The output is the mentioned below −" }, { "code": null, "e": 41478, "s": 41172, "text": "WebAssembly has the code in a binary format called WASM. You can also get the text format in WebAssembly and it is called WAT (WebAssembly Text format). As a developer you are not supposed to write code in WebAssembly, instead, you have to compile high-level languages like C, C++ and Rust to WebAssembly." }, { "code": null, "e": 41510, "s": 41478, "text": "Let us write WAT code stepwise." }, { "code": null, "e": 41573, "s": 41510, "text": "Step 1 − The starting point in a WAT is to declare the module." }, { "code": null, "e": 41583, "s": 41573, "text": "(module)\n" }, { "code": null, "e": 41658, "s": 41583, "text": "Step 2 − Let us now, add some functionality to it in the form of function." }, { "code": null, "e": 41700, "s": 41658, "text": "The function is declared as shown below −" }, { "code": null, "e": 41762, "s": 41700, "text": "(func <parameters/result> <local variables> <function body>)\n" }, { "code": null, "e": 41843, "s": 41762, "text": "The function starts with func keyword which is followed by parameters or result." }, { "code": null, "e": 41892, "s": 41843, "text": "The parameters and the return value as a result." }, { "code": null, "e": 41955, "s": 41892, "text": "The parameters can have the following type supported by wasm −" }, { "code": null, "e": 41975, "s": 41955, "text": "i32: 32-bit integer" }, { "code": null, "e": 41995, "s": 41975, "text": "i64: 64-bit integer" }, { "code": null, "e": 42013, "s": 41995, "text": "f32: 32-bit float" }, { "code": null, "e": 42031, "s": 42013, "text": "f64: 64-bit float" }, { "code": null, "e": 42089, "s": 42031, "text": "The params for the functions are written as given below −" }, { "code": null, "e": 42101, "s": 42089, "text": "(param i32)" }, { "code": null, "e": 42113, "s": 42101, "text": "(param i64)" }, { "code": null, "e": 42125, "s": 42113, "text": "(param f32)" }, { "code": null, "e": 42137, "s": 42125, "text": "(param f64)" }, { "code": null, "e": 42177, "s": 42137, "text": "The result will be written as follows −" }, { "code": null, "e": 42190, "s": 42177, "text": "(result i32)" }, { "code": null, "e": 42203, "s": 42190, "text": "(result i64)" }, { "code": null, "e": 42216, "s": 42203, "text": "(result f32)" }, { "code": null, "e": 42229, "s": 42216, "text": "(result f64)" }, { "code": null, "e": 42304, "s": 42229, "text": "The function with parameters and return value will be defined as follows −" }, { "code": null, "e": 42365, "s": 42304, "text": "(func (param i32) (param i32) (result i64) <function body>)\n" }, { "code": null, "e": 42486, "s": 42365, "text": "The local variables are those that you need in your function. A local value to the function will be defined as follows −" }, { "code": null, "e": 42559, "s": 42486, "text": "(func (param i32) (param i32) (local i32) (result i64) <function body>)\n" }, { "code": null, "e": 42643, "s": 42559, "text": "Function body is the logic to be performed. The final program will look like this −" }, { "code": null, "e": 42726, "s": 42643, "text": "(module (func (param i32) (param i32) (local i32) (result i64) <function body>) )\n" }, { "code": null, "e": 42783, "s": 42726, "text": "Step 3 − To read and set parameters and local variables." }, { "code": null, "e": 42872, "s": 42783, "text": "To read the parameters and local variables, make use of get_local and set_local command." }, { "code": null, "e": 42880, "s": 42872, "text": "Example" }, { "code": null, "e": 43007, "s": 42880, "text": "(module \n (func (param i32) (param i32) (local i32) (result i64) get_local 0 \n get_local 1 \n get_local 2 \n ) \n)\n" }, { "code": null, "e": 43038, "s": 43007, "text": "As per the function signature," }, { "code": null, "e": 43074, "s": 43038, "text": "get_local 0 will give the param i32" }, { "code": null, "e": 43110, "s": 43074, "text": "get_local 0 will give the param i32" }, { "code": null, "e": 43161, "s": 43110, "text": "get_local 1 will give the next parameter param i32" }, { "code": null, "e": 43212, "s": 43161, "text": "get_local 1 will give the next parameter param i32" }, { "code": null, "e": 43250, "s": 43212, "text": "get_local 2 will give local value i32" }, { "code": null, "e": 43288, "s": 43250, "text": "get_local 2 will give local value i32" }, { "code": null, "e": 43459, "s": 43288, "text": "Instead of referring to the parameters and locals using numeric values like 0,1,2, you can also use the name before the parameters, prefixing the name with a dollar sign." }, { "code": null, "e": 43536, "s": 43459, "text": "The following example shows, how to use the name with parameters and locals." }, { "code": null, "e": 43544, "s": 43536, "text": "Example" }, { "code": null, "e": 43697, "s": 43544, "text": "(module \n (func \n (param $a i32) \n (param $b i32) \n (local $c i32) \n (result i64) get_local $a get_local $b get_local $c \n ) \n)\n" }, { "code": null, "e": 43750, "s": 43697, "text": "Step 4 − Instruction in Function body and execution." }, { "code": null, "e": 43946, "s": 43750, "text": "The execution in wasm follows the stack strategy. The instructions executed are sent one by one on the stack. For example, the instruction get_local $a will push the value, it reads on the stack." }, { "code": null, "e": 44031, "s": 43946, "text": "The instruction like i32.add that will add the will pop the elements from the stack." }, { "code": null, "e": 44116, "s": 44031, "text": "(func (param $a i32) (param $b i32) \n get_local $a \n get_local $b \n i32.add\n)\n" }, { "code": null, "e": 44253, "s": 44116, "text": "The instruction for i32.add is ($a+$b). The final value of i32.add, will be pushed on the stack and that will be assigned to the result." }, { "code": null, "e": 44437, "s": 44253, "text": "If the function signature has a result declared, there should be one value in the stack at the end of the execution. If there is no result param, the stack has to be empty at the end." }, { "code": null, "e": 44502, "s": 44437, "text": "So, the final code along with function body will be as follows −" }, { "code": null, "e": 44624, "s": 44502, "text": "(module \n (func (param $a i32) (param $b i32) (result i32) \n get_local $a\n get_local $b \n i32.add\n )\n)" }, { "code": null, "e": 44662, "s": 44624, "text": "Step 5 − Making call to the function." }, { "code": null, "e": 44772, "s": 44662, "text": "The final code with the function body is as shown in step 4. Now, to call the function, we need to export it." }, { "code": null, "e": 44944, "s": 44772, "text": "To export the function, it can be done with index values like 0,1, but, we can also give names. The name will be prefixed by $ and it will be added after the func keyword." }, { "code": null, "e": 44952, "s": 44944, "text": "Example" }, { "code": null, "e": 45074, "s": 44952, "text": "(module \n (func $add (param $a i32) (param $b i32) (result i32) \n get_local $a \n get_local $b i32.add\n ) \n)" }, { "code": null, "e": 45150, "s": 45074, "text": "The function $add has to be exported, using export keyword as shown below −" }, { "code": null, "e": 45316, "s": 45150, "text": "(module \n (func $add \n (param $a i32) \n (param $b i32) \n (result i32) \n get_local $a get_local $b i32.add\n ) \n (export \"add\" (func $add))\n)" }, { "code": null, "e": 45476, "s": 45316, "text": "To test the above code in the browser, you will have to convert it into binary form (.wasm). Refer to the next chapter that shows how to convert .WAT to .WASM." }, { "code": null, "e": 45722, "s": 45476, "text": "In the previous chapter, we have seen how to write code in .wat i.e., WebAssembly text format. The WebAssembly text format will not directly work inside the browser and you need to convert it into binary format i.e., WASM to work inside browser." }, { "code": null, "e": 45752, "s": 45722, "text": "Let us convert .WAT to .WASM." }, { "code": null, "e": 45797, "s": 45752, "text": "The code we are going to use is as follows −" }, { "code": null, "e": 45957, "s": 45797, "text": "(module \n (func $add (param $a i32) (param $b i32) (result i32) \n get_local $a \n get_local $b \n i32.add\n ) \n (export \"add\" (func $add)) \n)" }, { "code": null, "e": 46039, "s": 45957, "text": "Now, go to WebAssembly Studio, which is available at https://webassembly.studio/." }, { "code": null, "e": 46099, "s": 46039, "text": "You should see something like this, when you hit the link −" }, { "code": null, "e": 46168, "s": 46099, "text": "Click on Empty Wat project and click on Create button at the bottom." }, { "code": null, "e": 46222, "s": 46168, "text": "It will take you to an empty project as shown below −" }, { "code": null, "e": 46311, "s": 46222, "text": "Click on main.wat and replace the existing code with yours and click on the save button." }, { "code": null, "e": 46364, "s": 46311, "text": "Once saved, click on the build to convert to .wasm −" }, { "code": null, "e": 46442, "s": 46364, "text": "If the build is successful you should see .wasm file created as shown below −" }, { "code": null, "e": 46534, "s": 46442, "text": "Down the main.wasm file and use it inside your .html file to see the output as shown below." }, { "code": null, "e": 46557, "s": 46534, "text": "For Example − add.html" }, { "code": null, "e": 47129, "s": 46557, "text": "<!doctype html>\n<html>\n <head>\n <meta charset=\"utf-8\">\n <title>WebAssembly Add Function</title>\n </head>\n <body>\n <script> \n let sum; \n fetch(\"main.wasm\")\n .then(bytes => bytes.arrayBuffer()) \n .then(mod => WebAssembly.compile(mod)) .then(module => {\n \n return new WebAssembly.Instance(module) \n })\n .then(instance => {\n sum = instance.exports.add(10,40); \n console.log(\"The sum of 10 and 40 = \" +sum); \n }); \n </script>\n </body>\n</html>" }, { "code": null, "e": 47259, "s": 47129, "text": "The function add is exported as shown in the code. The params passed are 2 integer values 10 and 40 and it returns the sum of it." }, { "code": null, "e": 47299, "s": 47259, "text": "The output is displayed in the browser." }, { "code": null, "e": 47399, "s": 47299, "text": "Dynamic linking is the process in which two or more modules will be linked together during runtime." }, { "code": null, "e": 47508, "s": 47399, "text": "To demonstrate how dynamic linking works, we will use C program and compile it to wasm using Ecmascript sdk." }, { "code": null, "e": 47526, "s": 47508, "text": "So here we have −" }, { "code": null, "e": 47534, "s": 47526, "text": "test1.c" }, { "code": null, "e": 47566, "s": 47534, "text": "int test1(){ \n return 100; \n}" }, { "code": null, "e": 47574, "s": 47566, "text": "test2.c" }, { "code": null, "e": 47606, "s": 47574, "text": "int test2(){ \n return 200; \n}" }, { "code": null, "e": 47613, "s": 47606, "text": "main.c" }, { "code": null, "e": 47731, "s": 47613, "text": "#include <stdio.h>\n\nint test1(); \nint test2();\nint main() { \n int result = test1() + test2(); \n return result; \n}" }, { "code": null, "e": 47885, "s": 47731, "text": "In main.c code, it makes use of test1() and test2(), which are defined inside test1.c and test2.c. Let us check how to link these modules in WebAssembly." }, { "code": null, "e": 48010, "s": 47885, "text": "The command to compile the above code is as follows: make use of SIDE_MODULE =1 for dynamic linking as shown in the command." }, { "code": null, "e": 48073, "s": 48010, "text": "emcc test1.c test2.c main.c -s SIDE_MODULE=1 -o maintest.wasm\n" }, { "code": null, "e": 48218, "s": 48073, "text": "Using WasmtoWat, which is available at https://webassembly.github.io/wabt/demo/wasm2wat/, will get the WebAssembly text format of maintest.wasm." }, { "code": null, "e": 50684, "s": 48218, "text": "(module \n (type $t0 (func (result i32))) (type $t1 (func)) \n (type $t2 (func (param i32))) (type $t3 (func (param i32 i32) (result i32))) \n (import \"env\" \"stackSave\" (func $env.stackSave (type $t0))) \n (import \"env\" \"stackRestore\" (func $env.stackRestore (type $t2))) \n (import \"env\" \"__memory_base\" (global $env.__memory_base i32)) \n (import \"env\" \"__table_base\" (global $env.__table_base i32)) \n (import \"env\" \"memory\" (memory $env.memory 0)) \n (import \"env\" \"table\" (table $env.table 0 funcref)) \n (func $f2 (type $t1) \n (call $__wasm_apply_relocs)\n )\n (func $__wasm_apply_relocs (export \"__wasm_apply_relocs\") (type $t1)) \n (func $test1 (export \"test1\") (type $t0) (result i32) \n (local $l0 i32) \n (local.set $l0 \n (i32.const 100)\n )\n (return \n (local.get $l0)\n )\n )\n (func $test2 (export \"test2\") (type $t0) (result i32) \n (local $l0 i32) \n (local.set $l0 \n (i32.const 200)) \n (return \n (local.get $l0)\n )\n ) \n (func $__original_main \n (export \"__original_main\") \n (type $t0) \n (result i32) \n (local $l0 i32) \n (local $l1 i32) \n (local $l2 i32) \n (local $l3 i32) \n (local $l4 i32) \n (local $l5 i32) \n (local $l6 i32) \n (local $l7 i32) \n (local $l8 i32) \n (local $l9 i32) \n (local.set $l0(call $env.stackSave))\n (local.set $l1 (i32.const 16))\n (local.set $l2 (i32.sub (local.get $l0) (local.get $l1)))\n (call $env.stackRestore (local.get $l2) ) (local.set $l3(i32.const 0)) \n (i32.store offset=12 (local.get $l2) (local.get $l3)) \n (local.set $l4 (call $test1)) \n (local.set $l5 (call $test2)) \n (local.set $l6 (i32.add (local.get $l4) (local.get $l5))) \n (i32.store offset=8 (local.get $l2) (local.get $l6)) \n (local.set $l7 (i32.load offset=8 (local.get $l2))) \n (local.set $l8 (i32.const 16)) \n (local.set $l9 (i32.add (local.get $l2) (local.get $l8))) \n (call $env.stackRestore (local.get $l9)) (return(local.get $l7))\n )\n (func $main \n (export \"main\") \n (type $t3) \n (param $p0 i32) \n (param $p1 i32) \n (result i32) \n (local $l2 i32) \n (local.set $l2 \n (call $__original_main)) \n (return (local.get $l2))\n ) \n (func $__post_instantiate (export \"__post_instantiate\") (type $t1) (call $f2)) \n (global $__dso_handle (export \"__dso_handle\") i32 (i32.const 0))\n)" }, { "code": null, "e": 50754, "s": 50684, "text": "The WebAssembly text format has some imports defined as shown below −" }, { "code": null, "e": 51114, "s": 50754, "text": "(import \"env\" \"stackSave\" (func $env.stackSave (type $t0))) \n(import \"env\" \"stackRestore\" (func $env.stackRestore (type $t2))) \n(import \"env\" \"__memory_base\" (global $env.__memory_base i32)) \n(import \"env\" \"__table_base\" (global $env.__table_base i32)) \n(import \"env\" \"memory\" (memory $env.memory 0)) \n(import \"env\" \"table\" (table $env.table 0 funcref))" }, { "code": null, "e": 51225, "s": 51114, "text": "This is added while compiling code by emcc(emscripten sdk) and it deals with memory management in WebAssembly." }, { "code": null, "e": 51319, "s": 51225, "text": "Now to see the output, we will have to define the imports that you can see in the .wat code −" }, { "code": null, "e": 51679, "s": 51319, "text": "(import \"env\" \"stackSave\" (func $env.stackSave (type $t0))) \n(import \"env\" \"stackRestore\" (func $env.stackRestore (type $t2))) \n(import \"env\" \"__memory_base\" (global $env.__memory_base i32)) \n(import \"env\" \"__table_base\" (global $env.__table_base i32)) \n(import \"env\" \"memory\" (memory $env.memory 0)) \n(import \"env\" \"table\" (table $env.table 0 funcref))" }, { "code": null, "e": 51722, "s": 51679, "text": "The above terms are explained as follows −" }, { "code": null, "e": 51837, "s": 51722, "text": "env.stackSave − It is used for stack management, a functionality that is provided by the emscripten compiled code." }, { "code": null, "e": 51952, "s": 51837, "text": "env.stackSave − It is used for stack management, a functionality that is provided by the emscripten compiled code." }, { "code": null, "e": 52070, "s": 51952, "text": "env.stackRestore − It is used for stack management, a functionality that is provided by the emscripten compiled code." }, { "code": null, "e": 52188, "s": 52070, "text": "env.stackRestore − It is used for stack management, a functionality that is provided by the emscripten compiled code." }, { "code": null, "e": 52428, "s": 52188, "text": "env.__memory_base − It is an immutable i32 global offset that is, used in env.memory and reserved for the wasm module. The module can use this global in the initializer of its data segments, so that, they are loaded at the correct address." }, { "code": null, "e": 52668, "s": 52428, "text": "env.__memory_base − It is an immutable i32 global offset that is, used in env.memory and reserved for the wasm module. The module can use this global in the initializer of its data segments, so that, they are loaded at the correct address." }, { "code": null, "e": 52914, "s": 52668, "text": "env.__table_base − It is an immutable i32 global offset that is, used in env.table and reserved for the wasm module. The module can use this global in the initializer of its table element segments, so that, they are loaded at the correct offset." }, { "code": null, "e": 53160, "s": 52914, "text": "env.__table_base − It is an immutable i32 global offset that is, used in env.table and reserved for the wasm module. The module can use this global in the initializer of its table element segments, so that, they are loaded at the correct offset." }, { "code": null, "e": 53264, "s": 53160, "text": "env.memory − This will have the memory details that are required to be shared between the wasm modules." }, { "code": null, "e": 53368, "s": 53264, "text": "env.memory − This will have the memory details that are required to be shared between the wasm modules." }, { "code": null, "e": 53470, "s": 53368, "text": "env.table − This will have the table details that are required to be shared between the wasm modules." }, { "code": null, "e": 53572, "s": 53470, "text": "env.table − This will have the table details that are required to be shared between the wasm modules." }, { "code": null, "e": 53630, "s": 53572, "text": "The imports have to be defined in javascript as follows −" }, { "code": null, "e": 54041, "s": 53630, "text": "var wasmMemory = new WebAssembly.Memory({'initial': 256,'maximum': 65536}); \nconst importObj = { \n env: {\n stackSave: n => 2, stackRestore: n => 3, //abortStackOverflow: () => {\n throw new Error('overflow'); \n }, \n table: new WebAssembly.Table({ \n initial: 0, maximum: 65536, element: 'anyfunc' \n }), __table_base: 0,\n memory: wasmMemory, __memory_base: 256 \n } \n};" }, { "code": null, "e": 54138, "s": 54041, "text": "Following is the javascript code that makes use of the importObj inside WebAssembly.instantiate." }, { "code": null, "e": 55295, "s": 54138, "text": "<!DOCTYPE html> \n<html>\n <head>\n <meta charset=\"UTF-8\">\n </head>\n <body>\n <script>\n var wasmMemory = new WebAssembly.Memory({'initial': 256,'maximum': 65536}); \n const importObj = {\n env: {\n stackSave: n => 2, stackRestore: n => 3, //abortStackOverflow: () => {\n throw new Error('overflow'); \n }, \n table: new WebAssembly.Table({ \n initial: 0, maximum: 65536, element: 'anyfunc' \n }), __table_base: 0,\n memory: wasmMemory, __memory_base: 256 \n } \n };\n fetch(\"maintest.wasm\") .then(bytes => bytes.arrayBuffer()) .then(\n module => WebAssembly.instantiate(module, importObj)\n )\n .then(finalcode => { \n console.log(finalcode); \n console.log(WebAssembly.Module.imports(finalcode.module)); \n console.log(finalcode.instance.exports.test1()); \n console.log(finalcode.instance.exports.test2()); \n console.log(finalcode.instance.exports.main()); \n });\n </script>\n </body>\n</html>" }, { "code": null, "e": 55322, "s": 55295, "text": "The output is as follows −" }, { "code": null, "e": 55497, "s": 55322, "text": "As per the official website of WebAssembly.org, which is available at https://webassembly.org/docs/security/ the main goal of WebAssembly in terms of security is as follows −" }, { "code": null, "e": 55557, "s": 55497, "text": "The security model of WebAssembly has two important goals −" }, { "code": null, "e": 55608, "s": 55557, "text": "Protect users from buggy or malicious modules, and" }, { "code": null, "e": 55659, "s": 55608, "text": "Protect users from buggy or malicious modules, and" }, { "code": null, "e": 55782, "s": 55659, "text": "Provide developers with useful primitives and mitigations for developing safe applications, within the constraints of (1)." }, { "code": null, "e": 55905, "s": 55782, "text": "Provide developers with useful primitives and mitigations for developing safe applications, within the constraints of (1)." }, { "code": null, "e": 56145, "s": 55905, "text": "The compiled code i.e. WASM from C/C++/Rust is not directly executed inside the browser and makes use of Javascript API's. The WASM code is sandboxed i.e. executed through Javascript API wrapper and the browser talks to WASM using the API." }, { "code": null, "e": 56207, "s": 56145, "text": "Here, is an example of using a .wasm file inside the browser." }, { "code": null, "e": 56227, "s": 56207, "text": "Example − C Program" }, { "code": null, "e": 56285, "s": 56227, "text": "#include<stdio.h> \nint square(int n) { \n return n*n; \n}" }, { "code": null, "e": 56342, "s": 56285, "text": "We will make use of WASM explorer to get the wasm code −" }, { "code": null, "e": 56391, "s": 56342, "text": "Download WASM code and use it to test the api’s." }, { "code": null, "e": 56777, "s": 56391, "text": "<script type=\"text/javascript\"> \n const importObj = {\n module: {}\n }; \n fetch(\"findsquare.wasm\") \n .then(bytes => bytes.arrayBuffer()) \n .then(module => WebAssembly.instantiate(module,importObj)) \n .then(finalcode => {\n \n console.log(finalcode); console.log(finalcode.instance.exports.square(25)); \n }); \n</script>" }, { "code": null, "e": 56813, "s": 56777, "text": "You will get the following output −" }, { "code": null, "e": 56945, "s": 56813, "text": "The exports objects have a reference to the function to be called. To call the function square, you will have to do it as follows −" }, { "code": null, "e": 56998, "s": 56945, "text": "console.log(finalcode.instance.exports.square(25));\n" }, { "code": null, "e": 57049, "s": 56998, "text": "Following are the issues with WASM compiled code −" }, { "code": null, "e": 57222, "s": 57049, "text": "It is difficult to check, if there is any malicious code being inserted, while compiling the code to wasm. There are no tools available at this moment to validate the code." }, { "code": null, "e": 57395, "s": 57222, "text": "It is difficult to check, if there is any malicious code being inserted, while compiling the code to wasm. There are no tools available at this moment to validate the code." }, { "code": null, "e": 57496, "s": 57395, "text": "Wasm is difficult to analyse and the buggy/malicious code can be easily executed inside the browser." }, { "code": null, "e": 57597, "s": 57496, "text": "Wasm is difficult to analyse and the buggy/malicious code can be easily executed inside the browser." }, { "code": null, "e": 57708, "s": 57597, "text": "In this chapter, we are going to compile a simple C program to javascript and execute the same in the browser." }, { "code": null, "e": 57732, "s": 57708, "text": "For Example − C Program" }, { "code": null, "e": 57790, "s": 57732, "text": "#include<stdio.h> \nint square(int n) { \n return n*n; \n}" }, { "code": null, "e": 57922, "s": 57790, "text": "We have done the installation of emsdk in folder wa/. In same folder, create another folder cprog/ and save above code as square.c." }, { "code": null, "e": 58048, "s": 57922, "text": "We have already installed emsdk in the previous chapter. Here, we are going to make use of emsdk to compile the above c code." }, { "code": null, "e": 58103, "s": 58048, "text": "Compile test.c in your command prompt as shown below −" }, { "code": null, "e": 58156, "s": 58103, "text": "emcc square.c -s STANDALONE_WASM –o findsquare.wasm\n" }, { "code": null, "e": 58310, "s": 58156, "text": "emcc command takes care of compiling the code as well as give you the .wasm code. We have used STANDALONE_WASM option that will give only the .wasm file." }, { "code": null, "e": 58336, "s": 58310, "text": "Example − findsquare.html" }, { "code": null, "e": 59120, "s": 58336, "text": "<!doctype html> \n<html>\n <head>\n <meta charset=\"utf-8\">\n <title>WebAssembly Square function</title>\n <style>\n div { \n font-size : 30px; text-align : center; color:orange; \n } \n </style>\n </head> \n <body>\n <div id=\"textcontent\"></div>\n <script> \n let square; fetch(\"findsquare.wasm\").then(bytes => bytes.arrayBuffer()) \n .then(mod => WebAssembly.compile(mod)) .then(module => {\n return new WebAssembly.Instance(module) \n }) \n .then(instance => {\n square = instance.exports.square(13); \n console.log(\"The square of 13 = \" +square); \n document.getElementById(\"textcontent\").innerHTML = \"The square of 13 = \" +square; \n }); \n </script>\n </body>\n</html>" }, { "code": null, "e": 59155, "s": 59120, "text": "The output is as mentioned below −" }, { "code": null, "e": 59268, "s": 59155, "text": "In this chapter, we are going to compile a simple C++ program to javascript and execute the same in the browser." }, { "code": null, "e": 59308, "s": 59268, "text": "C++ Program - Reversing a given number." }, { "code": null, "e": 59475, "s": 59308, "text": "#include <iostream> \nint reversenumber(int n) { \n int reverse=0, rem; \n while(n!=0) { \n rem=n%10; reverse=reverse*10+rem; n/=10; \n } \n return reverse; \n}" }, { "code": null, "e": 59610, "s": 59475, "text": "We have done the installation of emsdk in folder wa/. In same folder, create another folder cprog/ and save above code as reverse.cpp." }, { "code": null, "e": 59736, "s": 59610, "text": "We have already installed emsdk in the previous chapter. Here, we are going to make use of emsdk to compile the above c code." }, { "code": null, "e": 59791, "s": 59736, "text": "Compile test.c in your command prompt as shown below −" }, { "code": null, "e": 59844, "s": 59791, "text": "emcc reverse.cpp -s STANDALONE_WASM –o reverse.wasm\n" }, { "code": null, "e": 59926, "s": 59844, "text": "emcc command takes care of compiling the code as well as give you the .wasm code." }, { "code": null, "e": 59955, "s": 59926, "text": "Example − reversenumber.html" }, { "code": null, "e": 60873, "s": 59955, "text": "<!doctype html> \n<html>\n <head> \n <meta charset=\"utf-8\">\n <title>WebAssembly Reverse Number</title>\n <style>\n div { \n font-size : 30px; text-align : center; color:orange; \n } \n </style>\n </head>\n <body>\n <div id=\"textcontent\"></div>\n <script> \n let reverse; \n fetch(\"reverse.wasm\") \n .then(bytes => bytes.arrayBuffer()) \n .then(mod => WebAssembly.compile(mod)) \n .then(module => {return new WebAssembly.Instance(module) })\n .then(instance => { \n \n console.log(instance); \n reverse = instance.exports._Z13reversenumberi(1439898); \n console.log(\"The reverse of 1439898 = \" +reverse); \n document.getElementById(\"textcontent\")\n .innerHTML = \"The reverse of 1439898 = \" +reverse; \n }); \n </script>\n </body>\n</html>" }, { "code": null, "e": 60900, "s": 60873, "text": "The output is as follows −" }, { "code": null, "e": 60970, "s": 60900, "text": "To get RUST compile code we will make use of WebAssembly.studio tool." }, { "code": null, "e": 61099, "s": 60970, "text": "Go to WebAssembly.studio which is available at Go to https://webassembly.studio/ and it will display you screen as shown below −" }, { "code": null, "e": 61180, "s": 61099, "text": "Click on Empty Rust Project. Once done you will get three files in src/ folder −" }, { "code": null, "e": 61238, "s": 61180, "text": "Open the file main.rs and change the code of your choice." }, { "code": null, "e": 61303, "s": 61238, "text": "I am adding following function that will add two given numbers −" }, { "code": null, "e": 61357, "s": 61303, "text": "fn add_ints(lhs: i32, rhs: i32) -> i32 {\n lhs+rhs\n}" }, { "code": null, "e": 61403, "s": 61357, "text": "The code available in main.rs is as follows −" }, { "code": null, "e": 61470, "s": 61403, "text": "#[no_mangle]\npub extern \"C\" fn add_one(x: i32) -> i32 {\n x + 1\n}" }, { "code": null, "e": 61521, "s": 61470, "text": "Replace the fn add_one with yours as shown below −" }, { "code": null, "e": 61603, "s": 61521, "text": "#[no_mangle]\npub extern \"C\" fn add_ints(lhs: i32, rhs: i32) -> i32 {\n lhs+rhs\n}" }, { "code": null, "e": 61665, "s": 61603, "text": "In main.js, change the function name from add_one to add_ints" }, { "code": null, "e": 61945, "s": 61665, "text": "fetch('../out/main.wasm').then(\n response =>\n response.arrayBuffer()\n).then(bytes => WebAssembly.instantiate(bytes)).then(results => {\n instance = results.instance;\n document.getElementById(\"container\").textContent = instance.exports.add_one(41);\n}).catch(console.error);" }, { "code": null, "e": 62016, "s": 61945, "text": "Replace instance.exports.add_one to instance.exports.add_ints(100,100)" }, { "code": null, "e": 62301, "s": 62016, "text": "fetch('../out/main.wasm').then(\n response =>\n response.arrayBuffer()\n).then(bytes => WebAssembly.instantiate(bytes)).then(results => {\n instance = results.instance;\n document.getElementById(\"container\").textContent = instance.exports.add_ints(100,100)\n}).catch(console.error);" }, { "code": null, "e": 62381, "s": 62301, "text": "Click on the build button available on webassembly.studio UI to build the code." }, { "code": null, "e": 62462, "s": 62381, "text": "Once the build is done, click on Run button available on UI, to see the output −" }, { "code": null, "e": 62537, "s": 62462, "text": "We get the output as 200, as we passed instance.exports.add_ints(100,100)." }, { "code": null, "e": 62634, "s": 62537, "text": "Similarly, you can write a different program for rust and get it compiled in webassembly.studio." }, { "code": null, "e": 62728, "s": 62634, "text": "Go has added support for WebAssembly from version 1.1 onwards. To test it first download, Go." }, { "code": null, "e": 62876, "s": 62728, "text": "Go to the golang site, which is available at https://golang.org/dl/ and click on Download Go. As per your operating system download and install Go." }, { "code": null, "e": 62939, "s": 62876, "text": "Once done, write a simple program that adds two numbers in go." }, { "code": null, "e": 62950, "s": 62939, "text": "testnum.go" }, { "code": null, "e": 63219, "s": 62950, "text": "package main\nimport \"fmt\"\nfunc main() { \n var a int = 100 \n var b int = 200 \n var ret int \n ret = sum(a, b) \n fmt.Printf( \"Sum is : %d\\n\", ret ) \n}\n \n/* function returning the max between two numbers */ \nfunc sum(num1, num2 int) int { \n return num1+num2 \n}" }, { "code": null, "e": 63293, "s": 63219, "text": "To compile above code to wasm, first set the environment variables in Go." }, { "code": null, "e": 63334, "s": 63293, "text": "You will have to run following command −" }, { "code": null, "e": 63359, "s": 63334, "text": "Set GOOS=js\nGOARCH=wasm\n" }, { "code": null, "e": 63398, "s": 63359, "text": "Once done, execute the below command −" }, { "code": null, "e": 63435, "s": 63398, "text": "go build -o testnum.wasm testnum.go\n" }, { "code": null, "e": 63498, "s": 63435, "text": "You should get testnum.wasm file once the command is executed." }, { "code": null, "e": 63611, "s": 63498, "text": "Let us now test the code in the browser. To do that, we need to get the wasm_exec.js, that is installed with go." }, { "code": null, "e": 63683, "s": 63611, "text": "The file wasm_exec.js will be available inside misc/wasm/ folder in go." }, { "code": null, "e": 63766, "s": 63683, "text": "Here, is the code for testgo.html that makes use of wasm_exec.js and testnum.wasm." }, { "code": null, "e": 64407, "s": 63766, "text": "<html> \n <head> \n <meta charset=\"utf-8\"/>\n <script src=\"wasm_exec.js\"></script>\n </head>\n <body>\n <script type=\"text/javascript\"> \n const importObj = {\n module: {} \n };\n const go = new Go(); \n async function fetchAndInstantiate() { \n const response = await fetch(\"testnum.wasm\"); \n const buffer = await response.arrayBuffer(); \n const obj = await WebAssembly.instantiate(buffer, go.importObject); \n console.log(obj); \n go.run(obj.instance); \n } \n fetchAndInstantiate(); \n </script>\n </body>\n</html>" }, { "code": null, "e": 64434, "s": 64407, "text": "The output is as follows −" }, { "code": null, "e": 64531, "s": 64434, "text": "Javascript has a bunch of API that can work with wasm code. The API is also supported in nodejs." }, { "code": null, "e": 64600, "s": 64531, "text": "Get NODEJS installed on your system. Create a Factorialtest.js file." }, { "code": null, "e": 64651, "s": 64600, "text": "Let us use the C++ Factorial code as shown below −" }, { "code": null, "e": 64744, "s": 64651, "text": "int fact(int n) {\n if ((n==0)||(n==1))\n return 1;\n else\n return n*fact(n-1);\n}" }, { "code": null, "e": 64845, "s": 64744, "text": "Open Wasm Explorer, which is available at https://mbebenita.github.io/WasmExplorer/ as shown below −" }, { "code": null, "e": 64984, "s": 64845, "text": "The first column has the C++ factorial function, the 2nd column has the WebAssembly text format and the last column has x86 Assembly code." }, { "code": null, "e": 65028, "s": 64984, "text": "The WebAssembly Text format is as follows −" }, { "code": null, "e": 66160, "s": 65028, "text": "(module\n (table 0 anyfunc)\n (memory $0 1)\n (export \"memory\" (memory $0))\n (export \"_Z4facti\" (func $_Z4facti))\n (func $_Z4facti (; 0 ;) (param $0 i32) (result i32)\n (local $1 i32)\n (set_local $1(i32.const 1))\n (block $label$0\n (br_if $label$0\n (i32.eq\n (i32.or\n (get_local $0)\n (i32.const 1)\n )\n (i32.const 1)\n )\n )\n (set_local $1\n (i32.const 1)\n )\n (loop $label$1\n (set_local $1\n (i32.mul\n (get_local $0)\n (get_local $1)\n )\n )\n (br_if $label$1\n (i32.ne\n (i32.or\n (tee_local $0\n (i32.add\n (get_local $0)\n (i32.const -1)\n )\n )\n (i32.const 1)\n )\n (i32.const 1)\n )\n )\n )\n )\n (get_local $1)\n )\n)" }, { "code": null, "e": 66242, "s": 66160, "text": "The C++ function fact has been exported as “_Z4facti” in WebAssembly Text format." }, { "code": null, "e": 66259, "s": 66242, "text": "Factorialtest.js" }, { "code": null, "e": 66540, "s": 66259, "text": "const fs = require('fs');\nconst buf = fs.readFileSync('./factorial.wasm');\nconst lib = WebAssembly.instantiate(new Uint8Array(buf)).\n then(res => {\n for (var i=1;i<=10;i++) {\n console.log(\"The factorial of \"+i+\" = \"+res.instance.exports._Z4facti(i))\n }\n }\n);" }, { "code": null, "e": 66631, "s": 66540, "text": "In your command line, run the command node factorialtest.js and the output is as follows −" }, { "code": null, "e": 66920, "s": 66631, "text": "C:\\wasmnode>node factorialtest.js\nThe factorial of 1 = 1\nThe factorial of 2 = 2\nThe factorial of 3 = 6\nThe factorial of 4 = 24\nThe factorial of 5 = 120\nThe factorial of 6 = 720\nThe factorial of 7 = 5040\nThe factorial of 8 = 40320\nThe factorial of 9 = 362880\nThe factorial of 10 = 3628800\n" }, { "code": null, "e": 66984, "s": 66920, "text": "The chapter discusses the examples with regards to WebAssembly." }, { "code": null, "e": 67047, "s": 66984, "text": "Following is the example of C Program to get the max Element −" }, { "code": null, "e": 67317, "s": 67047, "text": "void displaylog(int n);\n/* function returning the max between two numbers */ \nint max(int num1, int num2) {\n /* local variable declaration */ int result; \n if (num1 > num2) \n result = num1; \n else result = num2;\n displaylog(result);\n return result; \n}" }, { "code": null, "e": 67387, "s": 67317, "text": "Compile the code in wasm fiddle and download the .wasm and .wat code." }, { "code": null, "e": 67396, "s": 67387, "text": "Wat code" }, { "code": null, "e": 67425, "s": 67396, "text": "The Wat code is as follows −" }, { "code": null, "e": 67967, "s": 67425, "text": "(module \n (type $FUNCSIG$vi (func (param i32))) \n (import \"env\" \"displaylog\" (func $displaylog (param i32))) \n (table 0 anyfunc) \n (memory $0 1) \n (export \"memory\" (memory $0)) \n (export \"max\" (func $max)) \n (func $max (; 1 ;) (param $0 i32) (param $1 i32) (result i32) \n (call $displaylog \n (tee_local $0 \n (select \n (get_local $0) \n (get_local $1) \n (i32.gt_s (get_local $0) (get_local $1)) \n )\n )\n )\n (get_local $0) \n )\n)" }, { "code": null, "e": 68037, "s": 67967, "text": "Download .wasm code and let us use in the .html file as shown below −" }, { "code": null, "e": 68612, "s": 68037, "text": "<!DOCTYPE html> \n<html>\n <head>\n <meta charset=\"UTF-8\">\n </head>\n <body>\n <script>\n const importObj = {\n env: { \n displaylog: n => alert(\"The max of (400, 130) is \" +n) \n } \n };\n fetch(\"testmax.wasm\") .then(bytes => bytes.arrayBuffer()) \n .then(module => WebAssembly.instantiate(module, importObj)) \n .then(finalcode => { \n console.log(finalcode); \n console.log(finalcode.instance.exports.max(400,130)); \n }); \n </script> \n </body>\n</html>" }, { "code": null, "e": 68639, "s": 68612, "text": "The output is as follows −" }, { "code": null, "e": 68710, "s": 68639, "text": "Following is the C++ code to get the fibonacci series of given number." }, { "code": null, "e": 68908, "s": 68710, "text": "#include <iostream>>\nvoid displaylog(int n); \nint fibonacciSeries(int number) {\n int n1=0,n2=1,n3,i; \n for(i=2;i<number;++i) { \n n3=n1+n2; displaylog(n); n1=n2; n2=n3;\n }\n return 0; \n}" }, { "code": null, "e": 69010, "s": 68908, "text": "I am using wasm explorer to compile the code. Download Wat and Wasm and test the same in the browser." }, { "code": null, "e": 69049, "s": 69010, "text": "You can use the below mentioned code −" }, { "code": null, "e": 69600, "s": 69049, "text": "<!DOCTYPE html> \n<html>\n <head> \n <meta charset=\"UTF-8\">\n </head>\n <body>\n <script> \n const importObj = { \n env: { _Z10displaylogi: n => console.log(n) } \n };\n fetch(\"fib.wasm\") \n .then(bytes => bytes.arrayBuffer()) \n .then(module => WebAssembly.instantiate(module, importObj)) \n .then(finalcode => { \n console.log(finalcode); \n console.log(finalcode.instance.exports._Z15fibonacciSeriesi(10)); \n });\n </script> \n </body>\n</html>" }, { "code": null, "e": 69627, "s": 69600, "text": "The output is as follows −" }, { "code": null, "e": 69688, "s": 69627, "text": "Following is the Rust code to add elements in a given array." }, { "code": null, "e": 69832, "s": 69688, "text": "fn add_array(x: i32) -> i32 { \n let mut sum = 0; \n let mut numbers = [10,20,30]; for i in 0..3 { \n sum += numbers[i]; \n } \n sum \n}" }, { "code": null, "e": 69904, "s": 69832, "text": "We are going to make use of WebAssembly Studio to compile RUST to wasm." }, { "code": null, "e": 69983, "s": 69904, "text": "Build the code and download the wasm file and execute the same in the browser." }, { "code": null, "e": 70492, "s": 69983, "text": "<!DOCTYPE html> \n<html>\n <head> \n <meta charset=\"UTF-8\">\n </head>\n <body>\n <script> \n const importObj = { \n env: {\n } \n };\n fetch(\"add_array.wasm\") .then(bytes => bytes.arrayBuffer())\n .then(module => WebAssembly.instantiate(module, importObj)) \n .then(finalcode => { \n console.log(finalcode); \n console.log(finalcode.instance.exports.add_array());\n }); \n </script> \n </body> \n</html>" }, { "code": null, "e": 70528, "s": 70492, "text": "The output will be as given below −" }, { "code": null, "e": 70535, "s": 70528, "text": " Print" }, { "code": null, "e": 70546, "s": 70535, "text": " Add Notes" } ]
JSTL - SQL <sql:transaction> Tag
The <sql:transaction> tag is used to group the <sql:query> and <sql:update> tags into transactions. You can put as many <sql:query> and <sql:update> tags as statements inside the <sql:transaction> tag to create a single transaction. It ensures that the database modifications performed by the nested actions are either committed or rolled back if an exception is thrown by any nested action. The <sql:transaction> tag has the following attributes − To start with the basic concept, let us create a Students table in the TEST database and create a few records in that table as follows − Open a Command Prompt and change to the installation directory as follows − C:\> C:\>cd Program Files\MySQL\bin C:\Program Files\MySQL\bin> Login to the database as follows − C:\Program Files\MySQL\bin>mysql -u root -p Enter password: ******** mysql> Create the Employee table in the TEST database as follows − mysql> use TEST; mysql> create table Students ( id int not null, first varchar (255), last varchar (255), dob date ); Query OK, 0 rows affected (0.08 sec) mysql> We will now create a few records in the Employee table as follows − mysql> INSERT INTO Students VALUES (100, 'Zara', 'Ali', '2002/05/16'); Query OK, 1 row affected (0.05 sec) mysql> INSERT INTO Students VALUES (101, 'Mahnaz', 'Fatma', '1978/11/28'); Query OK, 1 row affected (0.00 sec) mysql> INSERT INTO Students VALUES (102, 'Zaid', 'Khan', '1980/10/10'); Query OK, 1 row affected (0.00 sec) mysql> INSERT INTO Students VALUES (103, 'Sumit', 'Mittal', '1971/05/08'); Query OK, 1 row affected (0.00 sec) mysql> Let us now write a JSP which will make use of the <sql:update> tag along with <sql:transaction> tag to execute an SQL UPDATE statement. Here the code inside <sql:transaction> tag either will be executed completely or not at all − <%@ page import = "java.io.*,java.util.*,java.sql.*"%> <%@ page import = "javax.servlet.http.*,javax.servlet.*"%> <%@ page import = "java.util.Date,java.text.*" %> <%@ taglib uri = "http://java.sun.com/jsp/jstl/core" prefix = "c"%> <%@ taglib uri = "http://java.sun.com/jsp/jstl/sql" prefix = "sql"%> <html> <head> <title>JSTL sql:transaction Tag</title> </head> <body> <sql:setDataSource var = "snapshot" driver = "com.mysql.jdbc.Driver" url = "jdbc:mysql://localhost/TEST" user = "root" password = "cohondob"/> <% Date DoB = new Date("2001/12/16"); int studentId = 100; %> <sql:transaction dataSource = "${snapshot}"> <sql:update var = "count"> UPDATE Students SET last = 'Ali' WHERE Id = 102 </sql:update> <sql:update var = "count"> UPDATE Students SET last = 'Shah' WHERE Id = 103 </sql:update> <sql:update var = "count"> INSERT INTO Students VALUES (104,'Nuha', 'Ali', '2010/05/26'); </sql:update> </sql:transaction> <sql:query dataSource = "${snapshot}" var = "result"> SELECT * from Students; </sql:query> <table border = "1" width = "100%"> <tr> <th>Emp ID</th> <th>First Name</th> <th>Last Name</th> <th>DoB</th> </tr> <c:forEach var = "row" items = "${result.rows}"> <tr> <td> <c:out value = "${row.id}"/></td> <td> <c:out value = "${row.first}"/></td> <td> <c:out value = "${row.last}"/></td> <td> <c:out value = "${row.dob}"/></td> </tr> </c:forEach> </table> </body> </html> Access the above JSP, the following result will be displayed − +-------------+----------------+-----------------+-----------------+ | Emp ID | First Name | Last Name | DoB | +-------------+----------------+-----------------+-----------------+ | 100 | Zara | Ali | 2001-12-16 | | 101 | Mahnaz | Fatma | 1978-11-28 | | 102 | Zaid | Ali | 1980-10-10 | | 103 | Sumit | Mittal | 1971-05-08 | | 104 | Nuha | Ali | 2010-05-26 | +-------------+----------------+-----------------+-----------------+ 108 Lectures 11 hours Chaand Sheikh 517 Lectures 57 hours Chaand Sheikh 41 Lectures 4.5 hours Karthikeya T 42 Lectures 5.5 hours TELCOMA Global 15 Lectures 3 hours TELCOMA Global 44 Lectures 15 hours Uplatz Print Add Notes Bookmark this page
[ { "code": null, "e": 2472, "s": 2239, "text": "The <sql:transaction> tag is used to group the <sql:query> and <sql:update> tags into transactions. You can put as many <sql:query> and <sql:update> tags as statements inside the <sql:transaction> tag to create a single transaction." }, { "code": null, "e": 2631, "s": 2472, "text": "It ensures that the database modifications performed by the nested actions are either committed or rolled back if an exception is thrown by any nested action." }, { "code": null, "e": 2688, "s": 2631, "text": "The <sql:transaction> tag has the following attributes −" }, { "code": null, "e": 2825, "s": 2688, "text": "To start with the basic concept, let us create a Students table in the TEST database and create a few records in that table as follows −" }, { "code": null, "e": 2901, "s": 2825, "text": "Open a Command Prompt and change to the installation directory as follows −" }, { "code": null, "e": 2966, "s": 2901, "text": "C:\\>\nC:\\>cd Program Files\\MySQL\\bin\nC:\\Program Files\\MySQL\\bin>\n" }, { "code": null, "e": 3001, "s": 2966, "text": "Login to the database as follows −" }, { "code": null, "e": 3078, "s": 3001, "text": "C:\\Program Files\\MySQL\\bin>mysql -u root -p\nEnter password: ********\nmysql>\n" }, { "code": null, "e": 3138, "s": 3078, "text": "Create the Employee table in the TEST database as follows −" }, { "code": null, "e": 3331, "s": 3138, "text": "mysql> use TEST;\nmysql> create table Students\n (\n id int not null,\n first varchar (255),\n last varchar (255),\n dob date\n );\nQuery OK, 0 rows affected (0.08 sec)\nmysql>\n" }, { "code": null, "e": 3399, "s": 3331, "text": "We will now create a few records in the Employee table as follows −" }, { "code": null, "e": 3867, "s": 3399, "text": "mysql> INSERT INTO Students \n VALUES (100, 'Zara', 'Ali', '2002/05/16');\nQuery OK, 1 row affected (0.05 sec)\n \nmysql> INSERT INTO Students \n VALUES (101, 'Mahnaz', 'Fatma', '1978/11/28');\nQuery OK, 1 row affected (0.00 sec)\n \nmysql> INSERT INTO Students \n VALUES (102, 'Zaid', 'Khan', '1980/10/10');\nQuery OK, 1 row affected (0.00 sec)\n \nmysql> INSERT INTO Students \n VALUES (103, 'Sumit', 'Mittal', '1971/05/08');\nQuery OK, 1 row affected (0.00 sec)\n \nmysql>" }, { "code": null, "e": 4097, "s": 3867, "text": "Let us now write a JSP which will make use of the <sql:update> tag along with <sql:transaction> tag to execute an SQL UPDATE statement. Here the code inside <sql:transaction> tag either will be executed completely or not at all −" }, { "code": null, "e": 5902, "s": 4097, "text": "<%@ page import = \"java.io.*,java.util.*,java.sql.*\"%>\n<%@ page import = \"javax.servlet.http.*,javax.servlet.*\"%>\n<%@ page import = \"java.util.Date,java.text.*\" %>\n\n<%@ taglib uri = \"http://java.sun.com/jsp/jstl/core\" prefix = \"c\"%>\n<%@ taglib uri = \"http://java.sun.com/jsp/jstl/sql\" prefix = \"sql\"%>\n \n<html>\n <head>\n <title>JSTL sql:transaction Tag</title>\n </head>\n\n <body>\n <sql:setDataSource var = \"snapshot\" driver = \"com.mysql.jdbc.Driver\"\n url = \"jdbc:mysql://localhost/TEST\" user = \"root\" password = \"cohondob\"/>\n\n <%\n Date DoB = new Date(\"2001/12/16\");\n int studentId = 100;\n %>\n\n <sql:transaction dataSource = \"${snapshot}\">\n <sql:update var = \"count\">\n UPDATE Students SET last = 'Ali' WHERE Id = 102\n </sql:update>\n \n <sql:update var = \"count\">\n UPDATE Students SET last = 'Shah' WHERE Id = 103\n </sql:update>\n \n <sql:update var = \"count\">\n INSERT INTO Students \n VALUES (104,'Nuha', 'Ali', '2010/05/26');\n </sql:update>\n </sql:transaction>\n\n <sql:query dataSource = \"${snapshot}\" var = \"result\">\n SELECT * from Students;\n </sql:query>\n \n <table border = \"1\" width = \"100%\">\n <tr>\n <th>Emp ID</th>\n <th>First Name</th>\n <th>Last Name</th>\n <th>DoB</th>\n </tr>\n \n <c:forEach var = \"row\" items = \"${result.rows}\">\n <tr>\n <td> <c:out value = \"${row.id}\"/></td>\n <td> <c:out value = \"${row.first}\"/></td>\n <td> <c:out value = \"${row.last}\"/></td>\n <td> <c:out value = \"${row.dob}\"/></td>\n </tr>\n </c:forEach>\n </table>\n \n </body>\n</html>" }, { "code": null, "e": 5965, "s": 5902, "text": "Access the above JSP, the following result will be displayed −" }, { "code": null, "e": 6587, "s": 5965, "text": "+-------------+----------------+-----------------+-----------------+\n| Emp ID | First Name | Last Name | DoB |\n+-------------+----------------+-----------------+-----------------+\n| 100 | Zara | Ali | 2001-12-16 |\n| 101 | Mahnaz | Fatma | 1978-11-28 |\n| 102 | Zaid | Ali | 1980-10-10 |\n| 103 | Sumit | Mittal | 1971-05-08 |\n| 104 | Nuha | Ali | 2010-05-26 |\n+-------------+----------------+-----------------+-----------------+\n" }, { "code": null, "e": 6622, "s": 6587, "text": "\n 108 Lectures \n 11 hours \n" }, { "code": null, "e": 6637, "s": 6622, "text": " Chaand Sheikh" }, { "code": null, "e": 6672, "s": 6637, "text": "\n 517 Lectures \n 57 hours \n" }, { "code": null, "e": 6687, "s": 6672, "text": " Chaand Sheikh" }, { "code": null, "e": 6722, "s": 6687, "text": "\n 41 Lectures \n 4.5 hours \n" }, { "code": null, "e": 6736, "s": 6722, "text": " Karthikeya T" }, { "code": null, "e": 6771, "s": 6736, "text": "\n 42 Lectures \n 5.5 hours \n" }, { "code": null, "e": 6787, "s": 6771, "text": " TELCOMA Global" }, { "code": null, "e": 6820, "s": 6787, "text": "\n 15 Lectures \n 3 hours \n" }, { "code": null, "e": 6836, "s": 6820, "text": " TELCOMA Global" }, { "code": null, "e": 6870, "s": 6836, "text": "\n 44 Lectures \n 15 hours \n" }, { "code": null, "e": 6878, "s": 6870, "text": " Uplatz" }, { "code": null, "e": 6885, "s": 6878, "text": " Print" }, { "code": null, "e": 6896, "s": 6885, "text": " Add Notes" } ]
self in Python class
In this tutorial, we are going to learn about the self in Python. You must be familiar with it if you are working with Python. We will see some interesting things about. Note − self is not a keyword in Python. Let's start with the most common usage of self in Python. We'll use self in classes to represent the instance of an object. We can create multiple of a class and each instance will have different values. And self helps us to get those property values within the class instance. Let's see ane example. # class class Laptop: # init method def __init__(self, company, model): # self self.company = company self.model = model We are defining the properties of a class as self.[something]. So, whenever we create an instance of the class, the self will refer to a different instance from which we are accessing class properties or methods. Now, let create two instances of the class Laptop and see how the self works. Live Demo # class class Laptop: # init method def __init__(self, company, model): # self self.company = company self.model = model # creating instances for the class Laptop laptop_one = Laptop('Lenovo', 'ideapad320') laptop_two = Laptop('Dell', 'inspiron 7000') # printing the properties of the instances print(f"Laptop One: {laptop_one.company}") print(f"Laptop Two: {laptop_two.company}") If you run the above code, then you will get the following result. Laptop One: Lenovo Laptop Two: Dell We got two different names for the same property. Let's see some details behind it. Python sends a reference to the instance by default while accessing it methods or And the reference is captured in self. So, for each instance the reference is different. And we will get the respective instance properties. We know that the self is not a keyword of Python. It's more of like an argument that you don't need to send while accessing any property or method of an instance. Python will automatically send a reference to the instance for you. We can capture the of the instance with any variable name. Run the following code and see the output. Live Demo import inspect # class class Laptop: # init method def __init__(other_than_self, company, model, colors): # self not really other_than_self.company = company other_than_self.model = model other_than_self.colors_available = colors # method def is_laptop_available(not_self_but_still_self, color): # return whether a laptop in specified color is available or not return color in not_self_but_still_self.colors_available # creating an instance to the class laptop = Laptop('Dell', 'inspiron 7000', ['Silver', 'Black']) # invoking the is_laptop_available method withour color keyword print("Available") if laptop.is_laptop_available('Silver') else print("Not available") print("Available") if laptop.is_laptop_available('White') else print("Not available") If you run the above code, then you will get the following result. Available Not available We have changed the name self to something else. But still, it works as it before. There is no difference. So, self is not a keyword. And moreover, we can change the self to whatever we like to have. It's more like an argument. Note − best practice is to use the self.. It's a standard that every Python programmer follows If you have any doubts in the tutorial, mention them in the comment section.
[ { "code": null, "e": 1232, "s": 1062, "text": "In this tutorial, we are going to learn about the self in Python. You must be familiar with it if you are working with Python. We will see some interesting things about." }, { "code": null, "e": 1272, "s": 1232, "text": "Note − self is not a keyword in Python." }, { "code": null, "e": 1330, "s": 1272, "text": "Let's start with the most common usage of self in Python." }, { "code": null, "e": 1573, "s": 1330, "text": "We'll use self in classes to represent the instance of an object. We can create multiple of a class and each instance will have different values. And self helps us to get those property values within the class instance. Let's see ane example." }, { "code": null, "e": 1718, "s": 1573, "text": "# class\nclass Laptop:\n # init method\n def __init__(self, company, model):\n # self\n self.company = company\n self.model = model" }, { "code": null, "e": 1931, "s": 1718, "text": "We are defining the properties of a class as self.[something]. So, whenever we create an instance of the class, the self will refer to a different instance from which we are accessing class properties or methods." }, { "code": null, "e": 2009, "s": 1931, "text": "Now, let create two instances of the class Laptop and see how the self works." }, { "code": null, "e": 2020, "s": 2009, "text": " Live Demo" }, { "code": null, "e": 2425, "s": 2020, "text": "# class\nclass Laptop:\n # init method\n def __init__(self, company, model):\n # self\n self.company = company\n self.model = model\n# creating instances for the class Laptop\nlaptop_one = Laptop('Lenovo', 'ideapad320')\nlaptop_two = Laptop('Dell', 'inspiron 7000')\n# printing the properties of the instances\nprint(f\"Laptop One: {laptop_one.company}\")\nprint(f\"Laptop Two: {laptop_two.company}\")" }, { "code": null, "e": 2492, "s": 2425, "text": "If you run the above code, then you will get the following result." }, { "code": null, "e": 2528, "s": 2492, "text": "Laptop One: Lenovo\nLaptop Two: Dell" }, { "code": null, "e": 2612, "s": 2528, "text": "We got two different names for the same property. Let's see some details behind it." }, { "code": null, "e": 2835, "s": 2612, "text": "Python sends a reference to the instance by default while accessing it methods or And the reference is captured in self. So, for each instance the reference is different. And we\nwill get the respective instance properties." }, { "code": null, "e": 2998, "s": 2835, "text": "We know that the self is not a keyword of Python. It's more of like an argument that you don't need to send while accessing any property or method of an instance." }, { "code": null, "e": 3168, "s": 2998, "text": "Python will automatically send a reference to the instance for you. We can capture the of the instance with any variable name. Run the following code and see the output." }, { "code": null, "e": 3179, "s": 3168, "text": " Live Demo" }, { "code": null, "e": 4010, "s": 3179, "text": "import inspect\n# class\nclass Laptop:\n # init method\n def __init__(other_than_self, company, model, colors):\n # self not really\n other_than_self.company = company\n other_than_self.model = model\n other_than_self.colors_available = colors\n # method\n def is_laptop_available(not_self_but_still_self, color):\n # return whether a laptop in specified color is available or not\n return color in not_self_but_still_self.colors_available\n # creating an instance to the class\n laptop = Laptop('Dell', 'inspiron 7000', ['Silver', 'Black'])\n# invoking the is_laptop_available method withour color keyword\nprint(\"Available\") if laptop.is_laptop_available('Silver') else print(\"Not available\")\nprint(\"Available\") if laptop.is_laptop_available('White') else print(\"Not available\")" }, { "code": null, "e": 4077, "s": 4010, "text": "If you run the above code, then you will get the following result." }, { "code": null, "e": 4101, "s": 4077, "text": "Available\nNot available" }, { "code": null, "e": 4329, "s": 4101, "text": "We have changed the name self to something else. But still, it works as it before. There is no difference. So, self is not a keyword. And moreover, we can change the self to whatever we like to have. It's more like an argument." }, { "code": null, "e": 4424, "s": 4329, "text": "Note − best practice is to use the self.. It's a standard that every Python programmer follows" }, { "code": null, "e": 4501, "s": 4424, "text": "If you have any doubts in the tutorial, mention them in the comment section." } ]
OpenCV - Canny Edge Detection
Canny Edge Detection is used to detect the edges in an image. It accepts a gray scale image as input and it uses a multistage algorithm. You can perform this operation on an image using the Canny() method of the imgproc class, following is the syntax of this method. Canny(image, edges, threshold1, threshold2) This method accepts the following parameters − image − A Mat object representing the source (input image) for this operation. image − A Mat object representing the source (input image) for this operation. edges − A Mat object representing the destination (edges) for this operation. edges − A Mat object representing the destination (edges) for this operation. threshold1 − A variable of the type double representing the first threshold for the hysteresis procedure. threshold1 − A variable of the type double representing the first threshold for the hysteresis procedure. threshold2 − A variable of the type double representing the second threshold for the hysteresis procedure. threshold2 − A variable of the type double representing the second threshold for the hysteresis procedure. Following program is an example demonstrating, how to perform Canny Edge Detection operation on a given image. import org.opencv.core.Core; import org.opencv.core.Mat; import org.opencv.imgcodecs.Imgcodecs; import org.opencv.imgproc.Imgproc; public class CannyEdgeDetection { public static void main(String args[]) throws Exception { // Loading the OpenCV core library System.loadLibrary(Core.NATIVE_LIBRARY_NAME); // Reading the Image from the file and storing it in to a Matrix object String file = "E:/OpenCV/chap17/canny_input.jpg"; // Reading the image Mat src = Imgcodecs.imread(file); // Creating an empty matrix to store the result Mat gray = new Mat(); // Converting the image from color to Gray Imgproc.cvtColor(src, gray, Imgproc.COLOR_BGR2GRAY); Mat edges = new Mat(); // Detecting the edges Imgproc.Canny(gray, edges, 60, 60*3); // Writing the image Imgcodecs.imwrite("E:/OpenCV/chap17/canny_output.jpg", edges); System.out.println("Image Loaded"); } } Assume that following is the input image canny_input.jpg specified in the above program. On executing the above program, you will get the following output − Image Processed If you open the specified path, you can observe the output image as follows − 70 Lectures 9 hours Abhilash Nelson 41 Lectures 4 hours Abhilash Nelson 20 Lectures 2 hours Spotle Learn 12 Lectures 46 mins Srikanth Guskra 19 Lectures 2 hours Haithem Gasmi 67 Lectures 6.5 hours Gianluca Mottola Print Add Notes Bookmark this page
[ { "code": null, "e": 3141, "s": 3004, "text": "Canny Edge Detection is used to detect the edges in an image. It accepts a gray scale image as input and it uses a multistage algorithm." }, { "code": null, "e": 3271, "s": 3141, "text": "You can perform this operation on an image using the Canny() method of the imgproc class, following is the syntax of this method." }, { "code": null, "e": 3316, "s": 3271, "text": "Canny(image, edges, threshold1, threshold2)\n" }, { "code": null, "e": 3363, "s": 3316, "text": "This method accepts the following parameters −" }, { "code": null, "e": 3442, "s": 3363, "text": "image − A Mat object representing the source (input image) for this operation." }, { "code": null, "e": 3521, "s": 3442, "text": "image − A Mat object representing the source (input image) for this operation." }, { "code": null, "e": 3599, "s": 3521, "text": "edges − A Mat object representing the destination (edges) for this operation." }, { "code": null, "e": 3677, "s": 3599, "text": "edges − A Mat object representing the destination (edges) for this operation." }, { "code": null, "e": 3783, "s": 3677, "text": "threshold1 − A variable of the type double representing the first threshold for the hysteresis procedure." }, { "code": null, "e": 3889, "s": 3783, "text": "threshold1 − A variable of the type double representing the first threshold for the hysteresis procedure." }, { "code": null, "e": 3996, "s": 3889, "text": "threshold2 − A variable of the type double representing the second threshold for the hysteresis procedure." }, { "code": null, "e": 4103, "s": 3996, "text": "threshold2 − A variable of the type double representing the second threshold for the hysteresis procedure." }, { "code": null, "e": 4214, "s": 4103, "text": "Following program is an example demonstrating, how to perform Canny Edge Detection operation on a given image." }, { "code": null, "e": 5180, "s": 4214, "text": "import org.opencv.core.Core;\nimport org.opencv.core.Mat;\n\nimport org.opencv.imgcodecs.Imgcodecs;\nimport org.opencv.imgproc.Imgproc;\n\npublic class CannyEdgeDetection {\n public static void main(String args[]) throws Exception {\n // Loading the OpenCV core library\n System.loadLibrary(Core.NATIVE_LIBRARY_NAME);\n\n // Reading the Image from the file and storing it in to a Matrix object\n String file = \"E:/OpenCV/chap17/canny_input.jpg\";\n\n // Reading the image\n Mat src = Imgcodecs.imread(file);\n\n // Creating an empty matrix to store the result\n Mat gray = new Mat();\n\n // Converting the image from color to Gray\n Imgproc.cvtColor(src, gray, Imgproc.COLOR_BGR2GRAY);\n Mat edges = new Mat();\n\n // Detecting the edges\n Imgproc.Canny(gray, edges, 60, 60*3);\n\n // Writing the image\n Imgcodecs.imwrite(\"E:/OpenCV/chap17/canny_output.jpg\", edges);\n System.out.println(\"Image Loaded\");\n } \n}" }, { "code": null, "e": 5269, "s": 5180, "text": "Assume that following is the input image canny_input.jpg specified in the above program." }, { "code": null, "e": 5337, "s": 5269, "text": "On executing the above program, you will get the following output −" }, { "code": null, "e": 5354, "s": 5337, "text": "Image Processed\n" }, { "code": null, "e": 5432, "s": 5354, "text": "If you open the specified path, you can observe the output image as follows −" }, { "code": null, "e": 5465, "s": 5432, "text": "\n 70 Lectures \n 9 hours \n" }, { "code": null, "e": 5482, "s": 5465, "text": " Abhilash Nelson" }, { "code": null, "e": 5515, "s": 5482, "text": "\n 41 Lectures \n 4 hours \n" }, { "code": null, "e": 5532, "s": 5515, "text": " Abhilash Nelson" }, { "code": null, "e": 5565, "s": 5532, "text": "\n 20 Lectures \n 2 hours \n" }, { "code": null, "e": 5579, "s": 5565, "text": " Spotle Learn" }, { "code": null, "e": 5611, "s": 5579, "text": "\n 12 Lectures \n 46 mins\n" }, { "code": null, "e": 5628, "s": 5611, "text": " Srikanth Guskra" }, { "code": null, "e": 5661, "s": 5628, "text": "\n 19 Lectures \n 2 hours \n" }, { "code": null, "e": 5676, "s": 5661, "text": " Haithem Gasmi" }, { "code": null, "e": 5711, "s": 5676, "text": "\n 67 Lectures \n 6.5 hours \n" }, { "code": null, "e": 5729, "s": 5711, "text": " Gianluca Mottola" }, { "code": null, "e": 5736, "s": 5729, "text": " Print" }, { "code": null, "e": 5747, "s": 5736, "text": " Add Notes" } ]
How to add a column based on other columns in R DataFrame ? - GeeksforGeeks
30 Apr, 2021 A data frame can be accessed and modified to store new insertions and deletions. The data frame can undergo mutations to increase its dimensions and store more data, as well as the rows and columns values, which can be modified based on other cell values. In this article, we will see how to add columns based on other columns in DataFrame in R Programming Language. There can be various methods to do the same. Let’s discuss them in detail. The transform() method in R is used to modify the data and perform mutations. It transforms the first argument that is supplied to the function. New columns can also be added as a second argument of the function, where it may be either a list declared at the beginning or initialized during run times using the desired regular expression evaluation. We can specify the newly added column name on the left side of the second argument, and declare the if-else expression on the right. The if-else expression consists of three parts, The condition to test the data upon The second part is evaluated when the condition is not satisfied Third when it isn’t. The result has to be explicitly into the original data frame, in order to pertain to the results. Syntax: transform(dataframe,x=c(..)) where x is the newly added column. Example: R # creating a data framedata_frame = data.frame(col1=c(1,2,3,-4), col2=c(8,9,5,10), col3=c(0,2,3,5)) # printing original data frameprint("Original Data Frame")print (data_frame) # transforming data frame# declare col4 where if col1 is equal # to col3, replace by col1+col3 value, # otherwise by col1+col2 valuedata_frame <- transform( data_frame, col4= ifelse(col1==col3, col1+col2, col1+col3)) print("Modified Data Frame")print(data_frame) Output [1] "Original Data Frame" col1 col2 col3 1 1 8 0 2 2 9 2 3 3 5 3 4 -4 10 5 [1] "Modified Data Frame" col1 col2 col3 col4 1 1 8 0 1 2 2 9 2 11 3 3 5 3 8 4 -4 10 5 1 The with() method in R can be used to evaluate expressions and then transform the data contained in a data frame. With is a generic function that evaluates expression specified as the second argument of the function in a local environment constructed from data, which is defined in the first argument of the function. Any logical expression can be provided as the first argument of the method and the value in the new column is replaced depending on the truth value of the expression after evaluating the condition in the argument parts of the with method. Syntax: with(data, expr, ...) Example: R # creating a data framedata_frame = data.frame(col1=c(1,2,3,-4), col2=c(8,9,5,10), col3=c(0,2,3,5)) # printing original data frameprint("Original Data Frame")print (data_frame) # transforming data frame# declare col4 where if col1 is equal# to col3, replace by col1+col3 value,# otherwise by col1+col2 valuedata_frame$col4 <- with( data_frame, ifelse(col1+col3>5, col1+col3, col1+col2)) print("Modified Data Frame")print(data_frame) Output [1] "Original Data Frame" col1 col2 col3 1 1 8 0 2 2 9 2 3 3 5 3 4 -4 10 5 [1] "Modified Data Frame" col1 col2 col3 col4 1 1 8 0 9 2 2 9 2 11 3 3 5 3 6 4 -4 10 5 6 apply() method in R takes a well-organized data frame or matrix as an input and gives as output a vector, list, or an array. apply() method is primarily used to avoid explicit uses of loop constructs. Any function can be specified into the apply() method. The result has to be explicitly into the original data frame, in order to pertain the results. Syntax: apply(X, margin, FUN) Parameter : x: a data frame or a matrix margin: take a value or range between 1 and 2 to define where to apply the function:margin=1 : the manipulation is performed on rowsmargin=2 : the manipulation is performed on columnsmargin=c(1,2) : the manipulation is performed on both rows and columns margin=1 : the manipulation is performed on rows margin=2 : the manipulation is performed on columns margin=c(1,2) : the manipulation is performed on both rows and columns FUN: the function to apply where in built functions like mean, median, sum, min, max and even user-defined functions can be applied Example: R # creating a data framedata_frame = data.frame(col1=c(1,2,3,-4), col2=c(8,9,5,10), col3=c(0,2,3,5)) # printing original data frameprint("Original Data Frame")print (data_frame) # transforming data frame# declare col4 where if col1 is# equal to col3, replace by col1+col2# value, otherwise by col3-col2 valuedata_frame$col4 <- apply( data_frame, 1, FUN = function(x) if(mean(x[1])>1) x[2]+x[1] else x[3]-x[2]) print("Modified Data Frame")print(data_frame) Output [1] "Original Data Frame" col1 col2 col3 1 1 8 0 2 2 9 2 3 3 5 3 4 -4 10 5 [1] "Modified Data Frame" col1 col2 col3 col4 1 1 8 0 -8 2 2 9 2 11 3 3 5 3 8 4 -4 10 5 -5 Picked R DataFrame-Programs R-DataFrame R Language R Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Change Color of Bars in Barchart using ggplot2 in R How to Change Axis Scales in R Plots? Group by function in R using Dplyr How to Split Column Into Multiple Columns in R DataFrame? How to filter R DataFrame by values in a column? How to Split Column Into Multiple Columns in R DataFrame? How to filter R DataFrame by values in a column? How to filter R dataframe by multiple conditions? Replace Specific Characters in String in R Convert Matrix to Dataframe in R
[ { "code": null, "e": 25242, "s": 25214, "text": "\n30 Apr, 2021" }, { "code": null, "e": 25499, "s": 25242, "text": "A data frame can be accessed and modified to store new insertions and deletions. The data frame can undergo mutations to increase its dimensions and store more data, as well as the rows and columns values, which can be modified based on other cell values. " }, { "code": null, "e": 25685, "s": 25499, "text": "In this article, we will see how to add columns based on other columns in DataFrame in R Programming Language. There can be various methods to do the same. Let’s discuss them in detail." }, { "code": null, "e": 26216, "s": 25685, "text": "The transform() method in R is used to modify the data and perform mutations. It transforms the first argument that is supplied to the function. New columns can also be added as a second argument of the function, where it may be either a list declared at the beginning or initialized during run times using the desired regular expression evaluation. We can specify the newly added column name on the left side of the second argument, and declare the if-else expression on the right. The if-else expression consists of three parts," }, { "code": null, "e": 26252, "s": 26216, "text": "The condition to test the data upon" }, { "code": null, "e": 26317, "s": 26252, "text": "The second part is evaluated when the condition is not satisfied" }, { "code": null, "e": 26338, "s": 26317, "text": "Third when it isn’t." }, { "code": null, "e": 26437, "s": 26338, "text": "The result has to be explicitly into the original data frame, in order to pertain to the results. " }, { "code": null, "e": 26445, "s": 26437, "text": "Syntax:" }, { "code": null, "e": 26474, "s": 26445, "text": "transform(dataframe,x=c(..))" }, { "code": null, "e": 26510, "s": 26474, "text": "where x is the newly added column. " }, { "code": null, "e": 26519, "s": 26510, "text": "Example:" }, { "code": null, "e": 26521, "s": 26519, "text": "R" }, { "code": "# creating a data framedata_frame = data.frame(col1=c(1,2,3,-4), col2=c(8,9,5,10), col3=c(0,2,3,5)) # printing original data frameprint(\"Original Data Frame\")print (data_frame) # transforming data frame# declare col4 where if col1 is equal # to col3, replace by col1+col3 value, # otherwise by col1+col2 valuedata_frame <- transform( data_frame, col4= ifelse(col1==col3, col1+col2, col1+col3)) print(\"Modified Data Frame\")print(data_frame)", "e": 27011, "s": 26521, "text": null }, { "code": null, "e": 27018, "s": 27011, "text": "Output" }, { "code": null, "e": 27263, "s": 27018, "text": "[1] \"Original Data Frame\"\n col1 col2 col3\n1 1 8 0\n2 2 9 2\n3 3 5 3\n4 -4 10 5\n[1] \"Modified Data Frame\"\n col1 col2 col3 col4\n1 1 8 0 1\n2 2 9 2 11\n3 3 5 3 8\n4 -4 10 5 1" }, { "code": null, "e": 27821, "s": 27263, "text": "The with() method in R can be used to evaluate expressions and then transform the data contained in a data frame. With is a generic function that evaluates expression specified as the second argument of the function in a local environment constructed from data, which is defined in the first argument of the function. Any logical expression can be provided as the first argument of the method and the value in the new column is replaced depending on the truth value of the expression after evaluating the condition in the argument parts of the with method. " }, { "code": null, "e": 27829, "s": 27821, "text": "Syntax:" }, { "code": null, "e": 27851, "s": 27829, "text": "with(data, expr, ...)" }, { "code": null, "e": 27860, "s": 27851, "text": "Example:" }, { "code": null, "e": 27862, "s": 27860, "text": "R" }, { "code": "# creating a data framedata_frame = data.frame(col1=c(1,2,3,-4), col2=c(8,9,5,10), col3=c(0,2,3,5)) # printing original data frameprint(\"Original Data Frame\")print (data_frame) # transforming data frame# declare col4 where if col1 is equal# to col3, replace by col1+col3 value,# otherwise by col1+col2 valuedata_frame$col4 <- with( data_frame, ifelse(col1+col3>5, col1+col3, col1+col2)) print(\"Modified Data Frame\")print(data_frame)", "e": 28345, "s": 27862, "text": null }, { "code": null, "e": 28352, "s": 28345, "text": "Output" }, { "code": null, "e": 28597, "s": 28352, "text": "[1] \"Original Data Frame\"\n col1 col2 col3\n1 1 8 0\n2 2 9 2\n3 3 5 3\n4 -4 10 5\n[1] \"Modified Data Frame\"\n col1 col2 col3 col4\n1 1 8 0 9\n2 2 9 2 11\n3 3 5 3 6\n4 -4 10 5 6" }, { "code": null, "e": 28950, "s": 28597, "text": "apply() method in R takes a well-organized data frame or matrix as an input and gives as output a vector, list, or an array. apply() method is primarily used to avoid explicit uses of loop constructs. Any function can be specified into the apply() method. The result has to be explicitly into the original data frame, in order to pertain the results. " }, { "code": null, "e": 28980, "s": 28950, "text": "Syntax: apply(X, margin, FUN)" }, { "code": null, "e": 28993, "s": 28980, "text": "Parameter : " }, { "code": null, "e": 29021, "s": 28993, "text": "x: a data frame or a matrix" }, { "code": null, "e": 29276, "s": 29021, "text": "margin: take a value or range between 1 and 2 to define where to apply the function:margin=1 : the manipulation is performed on rowsmargin=2 : the manipulation is performed on columnsmargin=c(1,2) : the manipulation is performed on both rows and columns" }, { "code": null, "e": 29325, "s": 29276, "text": "margin=1 : the manipulation is performed on rows" }, { "code": null, "e": 29377, "s": 29325, "text": "margin=2 : the manipulation is performed on columns" }, { "code": null, "e": 29448, "s": 29377, "text": "margin=c(1,2) : the manipulation is performed on both rows and columns" }, { "code": null, "e": 29580, "s": 29448, "text": "FUN: the function to apply where in built functions like mean, median, sum, min, max and even user-defined functions can be applied" }, { "code": null, "e": 29589, "s": 29580, "text": "Example:" }, { "code": null, "e": 29591, "s": 29589, "text": "R" }, { "code": "# creating a data framedata_frame = data.frame(col1=c(1,2,3,-4), col2=c(8,9,5,10), col3=c(0,2,3,5)) # printing original data frameprint(\"Original Data Frame\")print (data_frame) # transforming data frame# declare col4 where if col1 is# equal to col3, replace by col1+col2# value, otherwise by col3-col2 valuedata_frame$col4 <- apply( data_frame, 1, FUN = function(x) if(mean(x[1])>1) x[2]+x[1] else x[3]-x[2]) print(\"Modified Data Frame\")print(data_frame)", "e": 30096, "s": 29591, "text": null }, { "code": null, "e": 30103, "s": 30096, "text": "Output" }, { "code": null, "e": 30350, "s": 30103, "text": "[1] \"Original Data Frame\"\n col1 col2 col3\n1 1 8 0\n2 2 9 2\n3 3 5 3\n4 -4 10 5\n[1] \"Modified Data Frame\"\n col1 col2 col3 col4\n1 1 8 0 -8\n2 2 9 2 11\n3 3 5 3 8\n4 -4 10 5 -5" }, { "code": null, "e": 30357, "s": 30350, "text": "Picked" }, { "code": null, "e": 30378, "s": 30357, "text": "R DataFrame-Programs" }, { "code": null, "e": 30390, "s": 30378, "text": "R-DataFrame" }, { "code": null, "e": 30401, "s": 30390, "text": "R Language" }, { "code": null, "e": 30412, "s": 30401, "text": "R Programs" }, { "code": null, "e": 30510, "s": 30412, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30562, "s": 30510, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 30600, "s": 30562, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 30635, "s": 30600, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 30693, "s": 30635, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 30742, "s": 30693, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 30800, "s": 30742, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 30849, "s": 30800, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 30899, "s": 30849, "text": "How to filter R dataframe by multiple conditions?" }, { "code": null, "e": 30942, "s": 30899, "text": "Replace Specific Characters in String in R" } ]
How can we set the background/foreground color for individual column of a JTable in Java?
A JTable is a subclass of JComponent class for displaying complex data structures. A JTable component can follow the Model View Controller (MVC) design pattern for displaying the data in rows and columns. A JTable can generate TableModelListener, TableColumnModelListener, ListSelectionListener, CellEditorListener, RowSorterListener interfaces. We can change the background and foreground color for each column of a JTable by customizing the DefaultTableCellRenderer class and it has only one method getTableCellRendererComponent() to implement it. import java.awt.*; import javax.swing.*; import javax.swing.table.*; public class JTableColumnColorTest extends JFrame { private JTable table; private TableColumn tColumn; public JTableColumnColorTest() { setTitle("JTableColumnColor Test"); table = new JTable(10, 5); tColumn = table.getColumnModel().getColumn(2); tColumn.setCellRenderer(new ColumnColorRenderer(Color.lightGray, Color.red)); add(new JScrollPane(table), BorderLayout.CENTER); setSize(400, 300); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLocationRelativeTo(null); setVisible(true); } public static void main(String [] args) { new JTableColumnColorTest(); } } // Customize the code to set the background and foreground color for each column of a JTable class ColumnColorRenderer extends DefaultTableCellRenderer { Color backgroundColor, foregroundColor; public ColumnColorRenderer(Color backgroundColor, Color foregroundColor) { super(); this.backgroundColor = backgroundColor; this.foregroundColor = foregroundColor; } public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { Component cell = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); cell.setBackground(backgroundColor); cell.setForeground(foregroundColor); return cell; } }
[ { "code": null, "e": 1612, "s": 1062, "text": "A JTable is a subclass of JComponent class for displaying complex data structures. A JTable component can follow the Model View Controller (MVC) design pattern for displaying the data in rows and columns. A JTable can generate TableModelListener, TableColumnModelListener, ListSelectionListener, CellEditorListener, RowSorterListener interfaces. We can change the background and foreground color for each column of a JTable by customizing the DefaultTableCellRenderer class and it has only one method getTableCellRendererComponent() to implement it." }, { "code": null, "e": 3073, "s": 1612, "text": "import java.awt.*;\nimport javax.swing.*;\nimport javax.swing.table.*;\npublic class JTableColumnColorTest extends JFrame {\n private JTable table;\n private TableColumn tColumn;\n public JTableColumnColorTest() {\n setTitle(\"JTableColumnColor Test\");\n table = new JTable(10, 5);\n tColumn = table.getColumnModel().getColumn(2);\n tColumn.setCellRenderer(new ColumnColorRenderer(Color.lightGray, Color.red));\n add(new JScrollPane(table), BorderLayout.CENTER);\n setSize(400, 300);\n setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n setLocationRelativeTo(null);\n setVisible(true);\n }\n public static void main(String [] args) {\n new JTableColumnColorTest();\n }\n}\n// Customize the code to set the background and foreground color for each column of a JTable\nclass ColumnColorRenderer extends DefaultTableCellRenderer {\n Color backgroundColor, foregroundColor;\n public ColumnColorRenderer(Color backgroundColor, Color foregroundColor) {\n super();\n this.backgroundColor = backgroundColor;\n this.foregroundColor = foregroundColor;\n }\n public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {\n Component cell = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);\n cell.setBackground(backgroundColor);\n cell.setForeground(foregroundColor);\n return cell;\n }\n}" } ]
How to Set Classpath When Class Files are in .jar file in Java? - GeeksforGeeks
11 Feb, 2021 Classpath is a parameter in JVM or the java compiler that specifies the location of the user–defined classes as well as the packages. While programming in Java, we many times use import statements. Illustration: import java.util.ArrayList; It makes the ArrayList class available in the package java.util to the current class. ArrayList<Integer> list = new ArrayList<>() ; Such that when we call as the JVM knows where to find the class ArrayList. Now, it is impractical for it to go through every folder on your system and search for it. Thus, in java do exists a CLASSPATH variable which is directly used as we provide it the place where we want it to look. Directories and jars are directly put in the CLASSPATH variable. We can use the – classpath option to set the classpath when calling a JDK tool (the recommended method) or by setting the CLASSPATH environment variable. The -classpath option is preferred because you can independently set it for each application without impacting other applications and without changing its meaning for other applications. Methods: Setting classpath as a command lineSetting classpath as the Environment variable Setting classpath as a command line Setting classpath as the Environment variable Method 1: Setting CLASSPATH as a command line Each classpath should end with a filename or directory depending on what you are setting the classpath.For a .jar or .zip file that contains .class files, the class path ends with the name of the .zip or .jar file. For .class files in an unnamed package, the class path ends with the directory that contains the .class files.For .class files in a named package, the class path ends with the directory that contains the “root” package (the first package in the full package name). For a .jar or .zip file that contains .class files, the class path ends with the name of the .zip or .jar file. For .class files in an unnamed package, the class path ends with the directory that contains the .class files. For .class files in a named package, the class path ends with the directory that contains the “root” package (the first package in the full package name). Semi-colons separate multiple path entries. With the set command, it’s important to omit spaces from around the equals sign (=). Implementation: The below specific command is used to set the classpath for any jar files separated by semi-columns. C:> set CLASSPATH=classpath1;classpath2... 1. C:> set CLASSPATH=.;C:\dependency\framework.jar 2. //Add multiple jars $ set CLASSPATH=C:\dependency\framework.jar;C:\location\otherFramework.jar 3. //* means all the files with .jar extension $ set CLASSPATH=C:\dependency\framework.jar;C:\location\*.jar Method 2: Setting classpath as the Environment variable In order to set classpath as the Environment variable, simply find the user environment variables window which as stepwise discussed. Procedure: From the desktop, right-click the Computer icon.Choose Properties from the context menu.Click the Advanced system settings link (a pop-up box will open).Click Environment Variables. In the section System Variables, find the CLASSPATH environment variable and select it. Click Edit. (If the CLASSPATH environment variable does not exist, click New and create a new variable with the name CLASSPATH)Add all folders separated with separator. Click OK.Close all remaining windows by clicking OK. From the desktop, right-click the Computer icon. Choose Properties from the context menu. Click the Advanced system settings link (a pop-up box will open). Click Environment Variables. In the section System Variables, find the CLASSPATH environment variable and select it. Click Edit. (If the CLASSPATH environment variable does not exist, click New and create a new variable with the name CLASSPATH) Add all folders separated with separator. Click OK. Close all remaining windows by clicking OK. It is also pictorially depicted below to mind-map clearly in finding the user environment variable window. Picked How To Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install FFmpeg on Windows? How to Set Git Username and Password in GitBash? How to Add External JAR File to an IntelliJ IDEA Project? How to Create and Setup Spring Boot Project in Eclipse IDE? How to Check the OS Version in Linux? Arrays in Java Split() String method in Java with examples For-each loop in Java Arrays.sort() in Java with examples Reverse a string in Java
[ { "code": null, "e": 24952, "s": 24924, "text": "\n11 Feb, 2021" }, { "code": null, "e": 25151, "s": 24952, "text": "Classpath is a parameter in JVM or the java compiler that specifies the location of the user–defined classes as well as the packages. While programming in Java, we many times use import statements. " }, { "code": null, "e": 25165, "s": 25151, "text": "Illustration:" }, { "code": null, "e": 25193, "s": 25165, "text": "import java.util.ArrayList;" }, { "code": null, "e": 25280, "s": 25193, "text": " It makes the ArrayList class available in the package java.util to the current class." }, { "code": null, "e": 25327, "s": 25280, "text": "ArrayList<Integer> list = new ArrayList<>() ;" }, { "code": null, "e": 25680, "s": 25327, "text": " Such that when we call as the JVM knows where to find the class ArrayList. Now, it is impractical for it to go through every folder on your system and search for it. Thus, in java do exists a CLASSPATH variable which is directly used as we provide it the place where we want it to look. Directories and jars are directly put in the CLASSPATH variable." }, { "code": null, "e": 26021, "s": 25680, "text": "We can use the – classpath option to set the classpath when calling a JDK tool (the recommended method) or by setting the CLASSPATH environment variable. The -classpath option is preferred because you can independently set it for each application without impacting other applications and without changing its meaning for other applications." }, { "code": null, "e": 26030, "s": 26021, "text": "Methods:" }, { "code": null, "e": 26111, "s": 26030, "text": "Setting classpath as a command lineSetting classpath as the Environment variable" }, { "code": null, "e": 26147, "s": 26111, "text": "Setting classpath as a command line" }, { "code": null, "e": 26193, "s": 26147, "text": "Setting classpath as the Environment variable" }, { "code": null, "e": 26239, "s": 26193, "text": "Method 1: Setting CLASSPATH as a command line" }, { "code": null, "e": 26719, "s": 26239, "text": "Each classpath should end with a filename or directory depending on what you are setting the classpath.For a .jar or .zip file that contains .class files, the class path ends with the name of the .zip or .jar file. For .class files in an unnamed package, the class path ends with the directory that contains the .class files.For .class files in a named package, the class path ends with the directory that contains the “root” package (the first package in the full package name)." }, { "code": null, "e": 26942, "s": 26719, "text": "For a .jar or .zip file that contains .class files, the class path ends with the name of the .zip or .jar file. For .class files in an unnamed package, the class path ends with the directory that contains the .class files." }, { "code": null, "e": 27097, "s": 26942, "text": "For .class files in a named package, the class path ends with the directory that contains the “root” package (the first package in the full package name)." }, { "code": null, "e": 27226, "s": 27097, "text": "Semi-colons separate multiple path entries. With the set command, it’s important to omit spaces from around the equals sign (=)." }, { "code": null, "e": 27242, "s": 27226, "text": "Implementation:" }, { "code": null, "e": 27343, "s": 27242, "text": "The below specific command is used to set the classpath for any jar files separated by semi-columns." }, { "code": null, "e": 27386, "s": 27343, "text": "C:> set CLASSPATH=classpath1;classpath2..." }, { "code": null, "e": 27648, "s": 27386, "text": "1. C:> set CLASSPATH=.;C:\\dependency\\framework.jar\n\n2. //Add multiple jars\n$ set CLASSPATH=C:\\dependency\\framework.jar;C:\\location\\otherFramework.jar \n\n3. //* means all the files with .jar extension\n$ set CLASSPATH=C:\\dependency\\framework.jar;C:\\location\\*.jar" }, { "code": null, "e": 27704, "s": 27648, "text": "Method 2: Setting classpath as the Environment variable" }, { "code": null, "e": 27838, "s": 27704, "text": "In order to set classpath as the Environment variable, simply find the user environment variables window which as stepwise discussed." }, { "code": null, "e": 27849, "s": 27838, "text": "Procedure:" }, { "code": null, "e": 28341, "s": 27849, "text": "From the desktop, right-click the Computer icon.Choose Properties from the context menu.Click the Advanced system settings link (a pop-up box will open).Click Environment Variables. In the section System Variables, find the CLASSPATH environment variable and select it. Click Edit. (If the CLASSPATH environment variable does not exist, click New and create a new variable with the name CLASSPATH)Add all folders separated with separator. Click OK.Close all remaining windows by clicking OK." }, { "code": null, "e": 28390, "s": 28341, "text": "From the desktop, right-click the Computer icon." }, { "code": null, "e": 28431, "s": 28390, "text": "Choose Properties from the context menu." }, { "code": null, "e": 28497, "s": 28431, "text": "Click the Advanced system settings link (a pop-up box will open)." }, { "code": null, "e": 28742, "s": 28497, "text": "Click Environment Variables. In the section System Variables, find the CLASSPATH environment variable and select it. Click Edit. (If the CLASSPATH environment variable does not exist, click New and create a new variable with the name CLASSPATH)" }, { "code": null, "e": 28794, "s": 28742, "text": "Add all folders separated with separator. Click OK." }, { "code": null, "e": 28838, "s": 28794, "text": "Close all remaining windows by clicking OK." }, { "code": null, "e": 28945, "s": 28838, "text": "It is also pictorially depicted below to mind-map clearly in finding the user environment variable window." }, { "code": null, "e": 28952, "s": 28945, "text": "Picked" }, { "code": null, "e": 28959, "s": 28952, "text": "How To" }, { "code": null, "e": 28964, "s": 28959, "text": "Java" }, { "code": null, "e": 28969, "s": 28964, "text": "Java" }, { "code": null, "e": 29067, "s": 28969, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29101, "s": 29067, "text": "How to Install FFmpeg on Windows?" }, { "code": null, "e": 29150, "s": 29101, "text": "How to Set Git Username and Password in GitBash?" }, { "code": null, "e": 29208, "s": 29150, "text": "How to Add External JAR File to an IntelliJ IDEA Project?" }, { "code": null, "e": 29268, "s": 29208, "text": "How to Create and Setup Spring Boot Project in Eclipse IDE?" }, { "code": null, "e": 29306, "s": 29268, "text": "How to Check the OS Version in Linux?" }, { "code": null, "e": 29321, "s": 29306, "text": "Arrays in Java" }, { "code": null, "e": 29365, "s": 29321, "text": "Split() String method in Java with examples" }, { "code": null, "e": 29387, "s": 29365, "text": "For-each loop in Java" }, { "code": null, "e": 29423, "s": 29387, "text": "Arrays.sort() in Java with examples" } ]
The Ultimate Guide to Conditional Statements in R | by Linda Ngo | Towards Data Science
Relational operators tell us how R objects relate, and logical operators allow us to combine logical values. R provides a way to use the results from these operators to change the behaviour of our own R scripts. This is done by if and else statements. The if statement takes a condition; if the condition evaluates to TRUE, the R code associated with the if statement is executed. if (condition) { expr} The condition to check appears inside parentheses, while the R code that has to be executed if the condition is TRUE, follows in curly brackets ( expr). Here is an example: x <- -3if (x < 0) { print("x is a negative number")} Suppose we have a variable x equal to -3. If this x is smaller than zero, we want R to print out “x is a negative number”. We can do this by using the if statement. We first assign the variable x, and then write the if condition. In this case, assign -3 to x, and set the if condition to be true if x is smaller than 0 (x < 0 ). If we run the example code, we indeed see that the string “x is a negative number” gets printed out. However, if we were to change x to 5, and re-run the code, the condition would be FALSE, and the print statement would not be executed. Suppose you are given the following variables: medium — information about the social website num_views — the actual number of views that particular medium had on the last day of your recordings of social profile views # Variables related to your last day of recordingsmedium <- "LinkedIn"num_views <- 14 Code an if statement that prints "You are popular" if the num_views variable exceeds 15. Recall the syntax of the if statement: if (condition) { expr} Here is an example of the if statement for medium that prints out which social website is being shown: if (medium == "LinkedIn") { print("Showing LinkedIn information")} # Write the if statement for num_viewsif (num_views > 15) { print("You are popular!")} The else statement does not need an explicit condition; instead, it has to be used with an if statement. The code associated with the else statement gets executed whenever the condition of the if condition is not TRUE. if (condition) { expr1} else { expr2} Suppose we want to print out for the following scenarios: if x is less than 0, print “x is a negative number” if x is greater than or equal to 0, print “x is either a positive number or zero” The second condition occurs whenever x < 0 is not met. So, we can simply add an else statement. x <- -3if (x < 0) { print("x is a negative number")} else { print ("x is either a positive number or zero")} If we ran the code with x equal to -3, we would get the printout “x is a negative number”. However, if x was 5 instead, then we would get the printout “x is either a positive number or zero”. The x < 0 condition is not satisfied, so R turns to the expression in the else statement. For this for you to try, you’ll be using the same variables as the previous for you to try. # Variables related to your last day of recordingsmedium <- "LinkedIn"num_views <- 14 Code control structures using an if and else statement that accomplishes the following: If medium is LinkedIn, print "Showing LinkedIn information", otherwise, print "Unknown medium". If num_views exceeds 15 views, print "You're popular!". If the if condition is not met, print "Try to be more visible!". Recall that you can only use an else statement in combination with an if statement. The else statement does not require a condition; its corresponding code is simply run if all the preceding conditions in the control structure are FALSE. Here is the syntax for its usage: if (condition) { expr1 } else { expr2} It’s important that the else keyword comes on the same line as the closing bracket of the the if part! # Variables related to your last day of recordingsmedium <- "LinkedIn"num_views <- 14# Control structure for mediumif (medium == "LinkedIn") { print("Showing LinkedIn information")} else { print("Unknown medium")}# Control structure for num_viewsif (num_views > 15) { print("You're popular!")} else { print("Try to be more visible!")} There are also cases when you want to customize your programs even further. The else if statement comes in between the if and else statement. The else if condition is checked if the first condition is not satisfied. If the second condition is then met, then the code inside it is executed. if (condition1) { expr1} else if (condition2) { expr2} else { expr3} Suppose we wanted another printout if x equals exactly 0. With the previous code block, that wouldn’t be possible. Instead, we would need another condition check. We can achieve this by using the else if statement. Say we now want to print out for the following conditions: if x less than 0, print “x is a negative number” if x equals 0, print “x is zero” otherwise, print out “x is a positive number” We can accomplish this by adding the else if, together with a new print statement, and adapt the message we print on the else statement. x <- -3if (x < 0) { print("x is a negative number")} else if (x == 0) { print("x is zero")} else { print("x is a positive number")} R processes this control structure depending on the conditions met. In the case x is -3, the condition for the if statement evaluates to TRUE, so “x is a negative number” is printed out, and R ignores the rest of the statements. If x equals 0, R will first check the if condition, sees that it is FALSE, and will then head over to the else if condition. This condition, x==0, evaluates to TRUE, so “x is zero” gets printed out, and R ignores the else statement entirely. If x equals 5, the if condition evaluates to FALSE, so does the else if condition, so R executes the else statement, printing “x is a positive number”. As soon as R stumbles upon a condition that evaluates to TRUE, R executes the corresponding code and then ignores the rest of the control structure. This becomes important if the conditions you list are not mutually exclusive. Consider the following example, that sees if a number is divisible by 2 or by 3. x <- -6if (x %% 2 == 0) { print("divisible by 2")} else if (x %% 3 == 0) { print("divisible by 3")} else { print("not divisible by 2 nor by 3...")} When x equals 6, the first condition evaluates to TRUE, so R prints out “divisible by 2”. R then exits the control structure and will not look at the rest of the statements. So although the second condition, for the else if part, would evaluate to TRUE, nothing gets printed out. Using your code from the previous for you to try, add code to both control structures such that: R prints out "Showing Facebook information" if medium is equal to “Facebook”. Keep in mind that R is case sensitive. If num_views is between 15 (inclusive) and 10 (exclusive) print out "Your number of views is average". The else if statement allows you to further customize your control structure. You can add as many else if statements as you like. Keep in mind that R ignores the remainder of the control structures once a condition has been found that is TRUE and the corresponding expressions have been executed. Here is an overview of the syntax: if (condition1) { expr1} else if (condition2) { expr2} else if (condition3) { expr3} else { expr4} Again, it is important that the else if keywords comes on the same line as the closing as the closing bracket of the previous part of the control construct. # Variables related to your last day of recordingsmedium <- "LinkedIn"num_views <- 14# Control structure for mediumif (medium == "LinkedIn") { print("Showing LinkedIn information")} else if (medium == "Facebook") { print("Showing Facebook information")} else { print("Unknown medium")}# Control structure for num_viewsif (num_views > 15) { print("You're popular!")} else if (num_views <= 15 & num_views > 10) { print("Your number of views is average")} else { print("Try to be more visible!")} You can do anything you want inside if-else constructs. You can even put in another set of conditional statements. Examine the following code: if (number < 10) { if (number < 5) { result <- "extra small" } else { result <- "small" }} else if (number < 100) { result <- "medium"} else { result <- "large"}print(result) Consider the following statements: If number is set to 6, “small” gets printed.If number is set to 100, "medium" is printed.If number is set to 4, "extra small" gets printed.If number is set to 2500, R will generate an error, as result will not be defined. If number is set to 6, “small” gets printed. If number is set to 100, "medium" is printed. If number is set to 4, "extra small" gets printed. If number is set to 2500, R will generate an error, as result will not be defined. Determine which of the statements are true. Suppose that number is 6. The condition of the if block (number < 10) is satisfied, so we enter the second if-else flow. The if condition of the second flow (number < 5) is not met, so the else code is executed (result <- "small"). Thus, the statement “If number is set to 6, “small” gets printed” is true.Suppose that number is 100. The first condition from the if statement (number < 10) and the second condition from the else if condition (number < 100) do not hold. Thus, the code within the else block is executed, and "large" is printed. The statement “If number is set to 100, "medium" is printed” is false.Suppose that number is 4. The condition of the if block (number < 10) is met, so the second if-else control is entered. The if condition of the second if-else control (number < 5) is met, so the code return <- "extra small" is executed. Thus, the statement “If number is set to 4, "extra small" gets printed” is true.Suppose that number is 2500. The number is neither less than 10, nor less than 100. So, it does not meet either of the conditions and the else code is executed instead (result <- “large”). Thus, the statement “If number is set to 2500, R will generate an error, as result will not be defined” is false. Suppose that number is 6. The condition of the if block (number < 10) is satisfied, so we enter the second if-else flow. The if condition of the second flow (number < 5) is not met, so the else code is executed (result <- "small"). Thus, the statement “If number is set to 6, “small” gets printed” is true. Suppose that number is 100. The first condition from the if statement (number < 10) and the second condition from the else if condition (number < 100) do not hold. Thus, the code within the else block is executed, and "large" is printed. The statement “If number is set to 100, "medium" is printed” is false. Suppose that number is 4. The condition of the if block (number < 10) is met, so the second if-else control is entered. The if condition of the second if-else control (number < 5) is met, so the code return <- "extra small" is executed. Thus, the statement “If number is set to 4, "extra small" gets printed” is true. Suppose that number is 2500. The number is neither less than 10, nor less than 100. So, it does not meet either of the conditions and the else code is executed instead (result <- “large”). Thus, the statement “If number is set to 2500, R will generate an error, as result will not be defined” is false. This challenge combines relational operators, logical operators, and control constructs. Consider two variables: li and fb, denoting the number of profile views your LinkedIn and Facebook profile had yesterday. # Variables related to yesterday's profile views.li <- 15fb <- 9 Generate a ‘social media score’, sms, based on the values of li and fb, based on the following behaviour: If both li and fb are 15 or higher, set sms equal to double the sum of li and fb. If both li and fb are strictly below 10, set sms equal to half the sum of li and fb. In all other cases, set sms equal to li + fb. Print the resulting sms variable. # Code the control-flow constructif (___ & ___) { sms <- 2 * (li + fb)} ___ (___) { sms <- 0.5 * (li + fb)} else { sms <- ___} # Variables related to your last day of recordingsli <- 15fb <- 9# Code the control-flow constructif (li >= 15 & fb >= 15) { sms <- 2 * (li + fb)} else if (li < 10 & fb < 10) { sms <- 0.5 * (li + fb)} else { sms <- li + fb}# Print the resulting sms to the consoleprint(sms) All images, unless specified, are owned by the author. The banner image was created using Canva.
[ { "code": null, "e": 424, "s": 172, "text": "Relational operators tell us how R objects relate, and logical operators allow us to combine logical values. R provides a way to use the results from these operators to change the behaviour of our own R scripts. This is done by if and else statements." }, { "code": null, "e": 553, "s": 424, "text": "The if statement takes a condition; if the condition evaluates to TRUE, the R code associated with the if statement is executed." }, { "code": null, "e": 577, "s": 553, "text": "if (condition) { expr}" }, { "code": null, "e": 730, "s": 577, "text": "The condition to check appears inside parentheses, while the R code that has to be executed if the condition is TRUE, follows in curly brackets ( expr)." }, { "code": null, "e": 750, "s": 730, "text": "Here is an example:" }, { "code": null, "e": 804, "s": 750, "text": "x <- -3if (x < 0) { print(\"x is a negative number\")}" }, { "code": null, "e": 1034, "s": 804, "text": "Suppose we have a variable x equal to -3. If this x is smaller than zero, we want R to print out “x is a negative number”. We can do this by using the if statement. We first assign the variable x, and then write the if condition." }, { "code": null, "e": 1133, "s": 1034, "text": "In this case, assign -3 to x, and set the if condition to be true if x is smaller than 0 (x < 0 )." }, { "code": null, "e": 1234, "s": 1133, "text": "If we run the example code, we indeed see that the string “x is a negative number” gets printed out." }, { "code": null, "e": 1370, "s": 1234, "text": "However, if we were to change x to 5, and re-run the code, the condition would be FALSE, and the print statement would not be executed." }, { "code": null, "e": 1417, "s": 1370, "text": "Suppose you are given the following variables:" }, { "code": null, "e": 1463, "s": 1417, "text": "medium — information about the social website" }, { "code": null, "e": 1588, "s": 1463, "text": "num_views — the actual number of views that particular medium had on the last day of your recordings of social profile views" }, { "code": null, "e": 1674, "s": 1588, "text": "# Variables related to your last day of recordingsmedium <- \"LinkedIn\"num_views <- 14" }, { "code": null, "e": 1763, "s": 1674, "text": "Code an if statement that prints \"You are popular\" if the num_views variable exceeds 15." }, { "code": null, "e": 1802, "s": 1763, "text": "Recall the syntax of the if statement:" }, { "code": null, "e": 1826, "s": 1802, "text": "if (condition) { expr}" }, { "code": null, "e": 1929, "s": 1826, "text": "Here is an example of the if statement for medium that prints out which social website is being shown:" }, { "code": null, "e": 1997, "s": 1929, "text": "if (medium == \"LinkedIn\") { print(\"Showing LinkedIn information\")}" }, { "code": null, "e": 2085, "s": 1997, "text": "# Write the if statement for num_viewsif (num_views > 15) { print(\"You are popular!\")}" }, { "code": null, "e": 2304, "s": 2085, "text": "The else statement does not need an explicit condition; instead, it has to be used with an if statement. The code associated with the else statement gets executed whenever the condition of the if condition is not TRUE." }, { "code": null, "e": 2344, "s": 2304, "text": "if (condition) { expr1} else { expr2}" }, { "code": null, "e": 2402, "s": 2344, "text": "Suppose we want to print out for the following scenarios:" }, { "code": null, "e": 2454, "s": 2402, "text": "if x is less than 0, print “x is a negative number”" }, { "code": null, "e": 2536, "s": 2454, "text": "if x is greater than or equal to 0, print “x is either a positive number or zero”" }, { "code": null, "e": 2632, "s": 2536, "text": "The second condition occurs whenever x < 0 is not met. So, we can simply add an else statement." }, { "code": null, "e": 2743, "s": 2632, "text": "x <- -3if (x < 0) { print(\"x is a negative number\")} else { print (\"x is either a positive number or zero\")}" }, { "code": null, "e": 2834, "s": 2743, "text": "If we ran the code with x equal to -3, we would get the printout “x is a negative number”." }, { "code": null, "e": 3025, "s": 2834, "text": "However, if x was 5 instead, then we would get the printout “x is either a positive number or zero”. The x < 0 condition is not satisfied, so R turns to the expression in the else statement." }, { "code": null, "e": 3117, "s": 3025, "text": "For this for you to try, you’ll be using the same variables as the previous for you to try." }, { "code": null, "e": 3203, "s": 3117, "text": "# Variables related to your last day of recordingsmedium <- \"LinkedIn\"num_views <- 14" }, { "code": null, "e": 3291, "s": 3203, "text": "Code control structures using an if and else statement that accomplishes the following:" }, { "code": null, "e": 3387, "s": 3291, "text": "If medium is LinkedIn, print \"Showing LinkedIn information\", otherwise, print \"Unknown medium\"." }, { "code": null, "e": 3508, "s": 3387, "text": "If num_views exceeds 15 views, print \"You're popular!\". If the if condition is not met, print \"Try to be more visible!\"." }, { "code": null, "e": 3780, "s": 3508, "text": "Recall that you can only use an else statement in combination with an if statement. The else statement does not require a condition; its corresponding code is simply run if all the preceding conditions in the control structure are FALSE. Here is the syntax for its usage:" }, { "code": null, "e": 3821, "s": 3780, "text": "if (condition) { expr1 } else { expr2}" }, { "code": null, "e": 3924, "s": 3821, "text": "It’s important that the else keyword comes on the same line as the closing bracket of the the if part!" }, { "code": null, "e": 4263, "s": 3924, "text": "# Variables related to your last day of recordingsmedium <- \"LinkedIn\"num_views <- 14# Control structure for mediumif (medium == \"LinkedIn\") { print(\"Showing LinkedIn information\")} else { print(\"Unknown medium\")}# Control structure for num_viewsif (num_views > 15) { print(\"You're popular!\")} else { print(\"Try to be more visible!\")}" }, { "code": null, "e": 4553, "s": 4263, "text": "There are also cases when you want to customize your programs even further. The else if statement comes in between the if and else statement. The else if condition is checked if the first condition is not satisfied. If the second condition is then met, then the code inside it is executed." }, { "code": null, "e": 4625, "s": 4553, "text": "if (condition1) { expr1} else if (condition2) { expr2} else { expr3}" }, { "code": null, "e": 4840, "s": 4625, "text": "Suppose we wanted another printout if x equals exactly 0. With the previous code block, that wouldn’t be possible. Instead, we would need another condition check. We can achieve this by using the else if statement." }, { "code": null, "e": 4899, "s": 4840, "text": "Say we now want to print out for the following conditions:" }, { "code": null, "e": 4948, "s": 4899, "text": "if x less than 0, print “x is a negative number”" }, { "code": null, "e": 4981, "s": 4948, "text": "if x equals 0, print “x is zero”" }, { "code": null, "e": 5027, "s": 4981, "text": "otherwise, print out “x is a positive number”" }, { "code": null, "e": 5164, "s": 5027, "text": "We can accomplish this by adding the else if, together with a new print statement, and adapt the message we print on the else statement." }, { "code": null, "e": 5299, "s": 5164, "text": "x <- -3if (x < 0) { print(\"x is a negative number\")} else if (x == 0) { print(\"x is zero\")} else { print(\"x is a positive number\")}" }, { "code": null, "e": 5367, "s": 5299, "text": "R processes this control structure depending on the conditions met." }, { "code": null, "e": 5528, "s": 5367, "text": "In the case x is -3, the condition for the if statement evaluates to TRUE, so “x is a negative number” is printed out, and R ignores the rest of the statements." }, { "code": null, "e": 5770, "s": 5528, "text": "If x equals 0, R will first check the if condition, sees that it is FALSE, and will then head over to the else if condition. This condition, x==0, evaluates to TRUE, so “x is zero” gets printed out, and R ignores the else statement entirely." }, { "code": null, "e": 5922, "s": 5770, "text": "If x equals 5, the if condition evaluates to FALSE, so does the else if condition, so R executes the else statement, printing “x is a positive number”." }, { "code": null, "e": 6149, "s": 5922, "text": "As soon as R stumbles upon a condition that evaluates to TRUE, R executes the corresponding code and then ignores the rest of the control structure. This becomes important if the conditions you list are not mutually exclusive." }, { "code": null, "e": 6230, "s": 6149, "text": "Consider the following example, that sees if a number is divisible by 2 or by 3." }, { "code": null, "e": 6381, "s": 6230, "text": "x <- -6if (x %% 2 == 0) { print(\"divisible by 2\")} else if (x %% 3 == 0) { print(\"divisible by 3\")} else { print(\"not divisible by 2 nor by 3...\")}" }, { "code": null, "e": 6471, "s": 6381, "text": "When x equals 6, the first condition evaluates to TRUE, so R prints out “divisible by 2”." }, { "code": null, "e": 6661, "s": 6471, "text": "R then exits the control structure and will not look at the rest of the statements. So although the second condition, for the else if part, would evaluate to TRUE, nothing gets printed out." }, { "code": null, "e": 6758, "s": 6661, "text": "Using your code from the previous for you to try, add code to both control structures such that:" }, { "code": null, "e": 6875, "s": 6758, "text": "R prints out \"Showing Facebook information\" if medium is equal to “Facebook”. Keep in mind that R is case sensitive." }, { "code": null, "e": 6978, "s": 6875, "text": "If num_views is between 15 (inclusive) and 10 (exclusive) print out \"Your number of views is average\"." }, { "code": null, "e": 7310, "s": 6978, "text": "The else if statement allows you to further customize your control structure. You can add as many else if statements as you like. Keep in mind that R ignores the remainder of the control structures once a condition has been found that is TRUE and the corresponding expressions have been executed. Here is an overview of the syntax:" }, { "code": null, "e": 7413, "s": 7310, "text": "if (condition1) { expr1} else if (condition2) { expr2} else if (condition3) { expr3} else { expr4}" }, { "code": null, "e": 7570, "s": 7413, "text": "Again, it is important that the else if keywords comes on the same line as the closing as the closing bracket of the previous part of the control construct." }, { "code": null, "e": 8070, "s": 7570, "text": "# Variables related to your last day of recordingsmedium <- \"LinkedIn\"num_views <- 14# Control structure for mediumif (medium == \"LinkedIn\") { print(\"Showing LinkedIn information\")} else if (medium == \"Facebook\") { print(\"Showing Facebook information\")} else { print(\"Unknown medium\")}# Control structure for num_viewsif (num_views > 15) { print(\"You're popular!\")} else if (num_views <= 15 & num_views > 10) { print(\"Your number of views is average\")} else { print(\"Try to be more visible!\")}" }, { "code": null, "e": 8185, "s": 8070, "text": "You can do anything you want inside if-else constructs. You can even put in another set of conditional statements." }, { "code": null, "e": 8213, "s": 8185, "text": "Examine the following code:" }, { "code": null, "e": 8399, "s": 8213, "text": "if (number < 10) { if (number < 5) { result <- \"extra small\" } else { result <- \"small\" }} else if (number < 100) { result <- \"medium\"} else { result <- \"large\"}print(result)" }, { "code": null, "e": 8434, "s": 8399, "text": "Consider the following statements:" }, { "code": null, "e": 8656, "s": 8434, "text": "If number is set to 6, “small” gets printed.If number is set to 100, \"medium\" is printed.If number is set to 4, \"extra small\" gets printed.If number is set to 2500, R will generate an error, as result will not be defined." }, { "code": null, "e": 8701, "s": 8656, "text": "If number is set to 6, “small” gets printed." }, { "code": null, "e": 8747, "s": 8701, "text": "If number is set to 100, \"medium\" is printed." }, { "code": null, "e": 8798, "s": 8747, "text": "If number is set to 4, \"extra small\" gets printed." }, { "code": null, "e": 8881, "s": 8798, "text": "If number is set to 2500, R will generate an error, as result will not be defined." }, { "code": null, "e": 8925, "s": 8881, "text": "Determine which of the statements are true." }, { "code": null, "e": 10159, "s": 8925, "text": "Suppose that number is 6. The condition of the if block (number < 10) is satisfied, so we enter the second if-else flow. The if condition of the second flow (number < 5) is not met, so the else code is executed (result <- \"small\"). Thus, the statement “If number is set to 6, “small” gets printed” is true.Suppose that number is 100. The first condition from the if statement (number < 10) and the second condition from the else if condition (number < 100) do not hold. Thus, the code within the else block is executed, and \"large\" is printed. The statement “If number is set to 100, \"medium\" is printed” is false.Suppose that number is 4. The condition of the if block (number < 10) is met, so the second if-else control is entered. The if condition of the second if-else control (number < 5) is met, so the code return <- \"extra small\" is executed. Thus, the statement “If number is set to 4, \"extra small\" gets printed” is true.Suppose that number is 2500. The number is neither less than 10, nor less than 100. So, it does not meet either of the conditions and the else code is executed instead (result <- “large”). Thus, the statement “If number is set to 2500, R will generate an error, as result will not be defined” is false." }, { "code": null, "e": 10466, "s": 10159, "text": "Suppose that number is 6. The condition of the if block (number < 10) is satisfied, so we enter the second if-else flow. The if condition of the second flow (number < 5) is not met, so the else code is executed (result <- \"small\"). Thus, the statement “If number is set to 6, “small” gets printed” is true." }, { "code": null, "e": 10775, "s": 10466, "text": "Suppose that number is 100. The first condition from the if statement (number < 10) and the second condition from the else if condition (number < 100) do not hold. Thus, the code within the else block is executed, and \"large\" is printed. The statement “If number is set to 100, \"medium\" is printed” is false." }, { "code": null, "e": 11093, "s": 10775, "text": "Suppose that number is 4. The condition of the if block (number < 10) is met, so the second if-else control is entered. The if condition of the second if-else control (number < 5) is met, so the code return <- \"extra small\" is executed. Thus, the statement “If number is set to 4, \"extra small\" gets printed” is true." }, { "code": null, "e": 11396, "s": 11093, "text": "Suppose that number is 2500. The number is neither less than 10, nor less than 100. So, it does not meet either of the conditions and the else code is executed instead (result <- “large”). Thus, the statement “If number is set to 2500, R will generate an error, as result will not be defined” is false." }, { "code": null, "e": 11485, "s": 11396, "text": "This challenge combines relational operators, logical operators, and control constructs." }, { "code": null, "e": 11607, "s": 11485, "text": "Consider two variables: li and fb, denoting the number of profile views your LinkedIn and Facebook profile had yesterday." }, { "code": null, "e": 11672, "s": 11607, "text": "# Variables related to yesterday's profile views.li <- 15fb <- 9" }, { "code": null, "e": 11778, "s": 11672, "text": "Generate a ‘social media score’, sms, based on the values of li and fb, based on the following behaviour:" }, { "code": null, "e": 11860, "s": 11778, "text": "If both li and fb are 15 or higher, set sms equal to double the sum of li and fb." }, { "code": null, "e": 11945, "s": 11860, "text": "If both li and fb are strictly below 10, set sms equal to half the sum of li and fb." }, { "code": null, "e": 11991, "s": 11945, "text": "In all other cases, set sms equal to li + fb." }, { "code": null, "e": 12025, "s": 11991, "text": "Print the resulting sms variable." }, { "code": null, "e": 12155, "s": 12025, "text": "# Code the control-flow constructif (___ & ___) { sms <- 2 * (li + fb)} ___ (___) { sms <- 0.5 * (li + fb)} else { sms <- ___}" }, { "code": null, "e": 12432, "s": 12155, "text": "# Variables related to your last day of recordingsli <- 15fb <- 9# Code the control-flow constructif (li >= 15 & fb >= 15) { sms <- 2 * (li + fb)} else if (li < 10 & fb < 10) { sms <- 0.5 * (li + fb)} else { sms <- li + fb}# Print the resulting sms to the consoleprint(sms)" } ]
Spark 3.2: Session Windowing Feature for Streaming Data | by Pınar Ersoy | Towards Data Science
The latest version of Spark 3.2 was released on October 13, 2021 [1]. In addition to its improvements on different topics, The existing windowing framework for streaming data processing provides only tumbling and sliding windows as highlighted in the Spark technical documentation[2]. In the terminology, there exists an additional windowing operation which is called a session window. Unlike the other two windowing approaches, the session window doesn’t hold solid window start and end times. Session window creation depends on a defined session period which can be static or dynamic. In the static version of session windowing, the events which are happening in a specific period of time are regarded as a session window. A session window stops when it does not collect events for the specified time period. In the dynamic version of session windowing, the period could be varied from event to event. For each windowing approach, you may find a corresponding implementation in PySpark language in the upcoming sections. For the development platform, and programming language, Google Colab, and PySpark will be used respectively. Before installing Spark 3.2, initially, we are required to install the matching version of Java. With the script below, you can set up Java 8 version. !apt-get install openjdk-8-jdk-headless -qq > /dev/null After an appropriate version of Java installation is completed, Spark 3.2 installation can be started. The following script will help you to set up Spark 3.2. version [3]. !wget -q https://archive.apache.org/dist/spark/spark-3.2.0/spark-3.2.0-bin-hadoop2.7.tgz When the installation concluded successfully, you are required to extract the spark file with the help of the following script. !tar xf spark-3.2.0-bin-hadoop2.7.tgz The installation of Java and Spark 3.2. is finished. The next step is to assign the environment variables for both of them. If you work on Google Colab, you may set the path environments like the following. import osos.environ["JAVA_HOME"] = "/usr/lib/jvm/java-8-openjdk-amd64"os.environ["SPARK_HOME"] = "/content/spark-3.2.0-bin-hadoop2.7" For testing purposes, you may run the findspark library like the following script. import findsparkfindspark.init() With the newest updates, Spark 3.2 contains three unique types of windowing functions as Tumbling, Sliding, and Session. To be able to test them individually, a spark session shall be created with the latest Spark version. The following script creates a session by using all the local cores on the Google Colab environment. from pyspark.sql import SparkSessionspark = SparkSession.builder.master("local[*]").getOrCreate() To test the version of the Spark, the .version function can be executed for the spark session. spark.version To be able to apply windowing functions, a spark session and a sample dataframe are required. A sample spark session can be initialized as the following code snippet. from pyspark.sql import SparkSessionspark = SparkSession.builder.master("local[*]").getOrCreate()spark.version Sample data can be generated with the following script. # Sample Data is generated for windowing exampleswindowingData = (("12", "2019-01-02 15:30:00"),("12", "2019-01-02 15:30:30"),("12", "2019-01-02 15:31:00"),("12", "2019-01-02 15:31:50"),("12", "2019-01-02 15:31:55"),("16", "2019-01-02 15:33:00"),("16", "2019-01-02 15:35:20"),("16", "2019-01-02 15:37:00"),("20", "2019-01-02 15:30:30"),("20", "2019-01-02 15:31:00"),("20", "2019-01-02 15:31:50"),("20", "2019-01-02 15:31:55"),("20", "2019-01-02 15:33:00"),("20", "2019-01-02 15:35:20"),("20", "2019-01-02 15:37:00"),("20", "2019-01-02 15:40:00"),("20", "2019-01-02 15:45:00"),("20", "2019-01-02 15:46:00"),("20", "2019-01-02 15:47:30"),("20", "2019-01-02 15:48:00"),("20", "2019-01-02 15:48:10"),("20", "2019-01-02 15:48:20"),("20", "2019-01-02 15:48:30"),("20", "2019-01-02 15:50:00"),("20", "2019-01-02 15:53:00"),("20", "2019-01-02 15:54:30"),("20", "2019-01-02 15:55:00"),("22", "2019-01-02 15:50:30"),("22", "2019-01-02 15:52:00"),("22", "2019-01-02 15:50:30"),("22", "2019-01-02 15:52:00"),("22", "2019-01-02 15:50:30"),("22", "2019-01-02 15:52:00"))columns = ["eventId", "timeReceived"]windowing_df = spark.createDataFrame(data = windowingData, schema = columns)windowing_df.printSchema()windowing_df.show(truncate=False) The tumbling windows can be represented as a group of equally partitioned, adjacent time periods without having any intersecting intervals. The inputted data may be subject to an individual window. from pyspark.sql.functions import *tumblingWindows = windowing_df.withWatermark("timeReceived", "10 minutes").groupBy("eventId", window("timeReceived", "10 minutes")).count()tumblingWindows.show(truncate = False) When observed on a timeline, the windows can be viewed as a sequence followed by each other in a static manner as in the following image. The sliding windows may have intersecting time periods when the time span contains a shorter interval than the range of the window. In such cases, timestamped items can be found in more than one window. from pyspark.sql.functions import *slidingWindows = windowing_df.withWatermark("timeReceived", "10 minutes").groupBy("eventId", window("timeReceived", "10 minutes", "5 minutes")).count()slidingWindows.show(truncate = False) When observed on a timeline, the windows can be overlapping or not overlapping according to the length of the time range when compared to the length of the main sliding window with a static manner as the tumbling window. Session windows may contain the nature of a dynamic length by means of the window size relative to the inputting item type. A session window begins with a single data point and broadens itself in case of the upcoming element has been collected inside of the gap period. When the last item is accepted, the session window ends when no items are acknowledged inside of the gap period. This feature permits the user to cluster the events when there are no advanced events injected for a selected period of time as also described in the official article as an inactive period [4]. In the real world, the logic of the session windowing operates as timeout occurrences. In some specific time gap, you shall be performing an activity, otherwise, the existing session closes when an adequate amount of time is passed. The session period can be enlarged in case having additional activity is recorded. For the specific usage of the session window, it can be depicted as creating a session window with upcoming events, and the continually gathering events inside the timeout period will be added in the current session. from pyspark.sql.functions import *sessionWindows = windowing_df.withWatermark("timeReceived", "10 minutes").groupBy("eventId", session_window("timeReceived", "5 minutes")).count()sessionWindows.show(truncate = False) Every event that is acquired will be capable of increasing the range of the session timeout. With this feature, the time period of the session window can be accepted as not static compared to the other two windowing approaches. For the specific example that is added above, the event with an id of 20, session windowing flow can be observed as one closes after a specified time period and begins again when a new element is acknowledged. The session window functionality has an additional feature which is called dynamic gap duration as mentioned in the Databricks blog post [4]. The period of the session may have various values when requested. The sessions that have an overlapping behavior can be grouped into a single session. The total duration of this session will be equal to the sum of the time duration of the intersecting events. You may group the data by the eventId, session window, and calculate its occurrences with the following script by inserting two values for the session_window() function as described in the latest programming guide of Spark 3.2 [5]. windowedCountsDF = windowing_df.withWatermark("timeReceived", "10 minutes").groupBy(windowing_df.eventId, session_window(windowing_df.timeReceived, \when(windowing_df.eventId == "20", "10 seconds").when(windowing_df.eventId == "12","30 seconds").otherwise("10 minutes"))).count()windowedCountsDF.show(100, truncate = False) In the literature, there exist three main windowing functionalities. The ones that have a static manner are tumbling and sliding windows which were already available in the previous version of Spark 3.2. The dynamic natured session windows capability is now available with the latest version of Spark 3.2 [6]. You can find the full PySpark scripted code on the Google Colab environment. Questions and comments are highly appreciated! Thank you so much for reading! Spark Release 3.2.0Structured Streaming Programming GuideAdvanced Spark Streaming Spark Release 3.2.0 Structured Streaming Programming Guide Advanced Spark Streaming
[ { "code": null, "e": 294, "s": 171, "text": "The latest version of Spark 3.2 was released on October 13, 2021 [1]. In addition to its improvements on different topics," }, { "code": null, "e": 557, "s": 294, "text": "The existing windowing framework for streaming data processing provides only tumbling and sliding windows as highlighted in the Spark technical documentation[2]. In the terminology, there exists an additional windowing operation which is called a session window." }, { "code": null, "e": 758, "s": 557, "text": "Unlike the other two windowing approaches, the session window doesn’t hold solid window start and end times. Session window creation depends on a defined session period which can be static or dynamic." }, { "code": null, "e": 982, "s": 758, "text": "In the static version of session windowing, the events which are happening in a specific period of time are regarded as a session window. A session window stops when it does not collect events for the specified time period." }, { "code": null, "e": 1075, "s": 982, "text": "In the dynamic version of session windowing, the period could be varied from event to event." }, { "code": null, "e": 1303, "s": 1075, "text": "For each windowing approach, you may find a corresponding implementation in PySpark language in the upcoming sections. For the development platform, and programming language, Google Colab, and PySpark will be used respectively." }, { "code": null, "e": 1454, "s": 1303, "text": "Before installing Spark 3.2, initially, we are required to install the matching version of Java. With the script below, you can set up Java 8 version." }, { "code": null, "e": 1510, "s": 1454, "text": "!apt-get install openjdk-8-jdk-headless -qq > /dev/null" }, { "code": null, "e": 1682, "s": 1510, "text": "After an appropriate version of Java installation is completed, Spark 3.2 installation can be started. The following script will help you to set up Spark 3.2. version [3]." }, { "code": null, "e": 1771, "s": 1682, "text": "!wget -q https://archive.apache.org/dist/spark/spark-3.2.0/spark-3.2.0-bin-hadoop2.7.tgz" }, { "code": null, "e": 1899, "s": 1771, "text": "When the installation concluded successfully, you are required to extract the spark file with the help of the following script." }, { "code": null, "e": 1937, "s": 1899, "text": "!tar xf spark-3.2.0-bin-hadoop2.7.tgz" }, { "code": null, "e": 2144, "s": 1937, "text": "The installation of Java and Spark 3.2. is finished. The next step is to assign the environment variables for both of them. If you work on Google Colab, you may set the path environments like the following." }, { "code": null, "e": 2278, "s": 2144, "text": "import osos.environ[\"JAVA_HOME\"] = \"/usr/lib/jvm/java-8-openjdk-amd64\"os.environ[\"SPARK_HOME\"] = \"/content/spark-3.2.0-bin-hadoop2.7\"" }, { "code": null, "e": 2361, "s": 2278, "text": "For testing purposes, you may run the findspark library like the following script." }, { "code": null, "e": 2394, "s": 2361, "text": "import findsparkfindspark.init()" }, { "code": null, "e": 2617, "s": 2394, "text": "With the newest updates, Spark 3.2 contains three unique types of windowing functions as Tumbling, Sliding, and Session. To be able to test them individually, a spark session shall be created with the latest Spark version." }, { "code": null, "e": 2718, "s": 2617, "text": "The following script creates a session by using all the local cores on the Google Colab environment." }, { "code": null, "e": 2816, "s": 2718, "text": "from pyspark.sql import SparkSessionspark = SparkSession.builder.master(\"local[*]\").getOrCreate()" }, { "code": null, "e": 2911, "s": 2816, "text": "To test the version of the Spark, the .version function can be executed for the spark session." }, { "code": null, "e": 2925, "s": 2911, "text": "spark.version" }, { "code": null, "e": 3092, "s": 2925, "text": "To be able to apply windowing functions, a spark session and a sample dataframe are required. A sample spark session can be initialized as the following code snippet." }, { "code": null, "e": 3203, "s": 3092, "text": "from pyspark.sql import SparkSessionspark = SparkSession.builder.master(\"local[*]\").getOrCreate()spark.version" }, { "code": null, "e": 3259, "s": 3203, "text": "Sample data can be generated with the following script." }, { "code": null, "e": 4520, "s": 3259, "text": "# Sample Data is generated for windowing exampleswindowingData = ((\"12\", \"2019-01-02 15:30:00\"),(\"12\", \"2019-01-02 15:30:30\"),(\"12\", \"2019-01-02 15:31:00\"),(\"12\", \"2019-01-02 15:31:50\"),(\"12\", \"2019-01-02 15:31:55\"),(\"16\", \"2019-01-02 15:33:00\"),(\"16\", \"2019-01-02 15:35:20\"),(\"16\", \"2019-01-02 15:37:00\"),(\"20\", \"2019-01-02 15:30:30\"),(\"20\", \"2019-01-02 15:31:00\"),(\"20\", \"2019-01-02 15:31:50\"),(\"20\", \"2019-01-02 15:31:55\"),(\"20\", \"2019-01-02 15:33:00\"),(\"20\", \"2019-01-02 15:35:20\"),(\"20\", \"2019-01-02 15:37:00\"),(\"20\", \"2019-01-02 15:40:00\"),(\"20\", \"2019-01-02 15:45:00\"),(\"20\", \"2019-01-02 15:46:00\"),(\"20\", \"2019-01-02 15:47:30\"),(\"20\", \"2019-01-02 15:48:00\"),(\"20\", \"2019-01-02 15:48:10\"),(\"20\", \"2019-01-02 15:48:20\"),(\"20\", \"2019-01-02 15:48:30\"),(\"20\", \"2019-01-02 15:50:00\"),(\"20\", \"2019-01-02 15:53:00\"),(\"20\", \"2019-01-02 15:54:30\"),(\"20\", \"2019-01-02 15:55:00\"),(\"22\", \"2019-01-02 15:50:30\"),(\"22\", \"2019-01-02 15:52:00\"),(\"22\", \"2019-01-02 15:50:30\"),(\"22\", \"2019-01-02 15:52:00\"),(\"22\", \"2019-01-02 15:50:30\"),(\"22\", \"2019-01-02 15:52:00\"))columns = [\"eventId\", \"timeReceived\"]windowing_df = spark.createDataFrame(data = windowingData, schema = columns)windowing_df.printSchema()windowing_df.show(truncate=False)" }, { "code": null, "e": 4718, "s": 4520, "text": "The tumbling windows can be represented as a group of equally partitioned, adjacent time periods without having any intersecting intervals. The inputted data may be subject to an individual window." }, { "code": null, "e": 4931, "s": 4718, "text": "from pyspark.sql.functions import *tumblingWindows = windowing_df.withWatermark(\"timeReceived\", \"10 minutes\").groupBy(\"eventId\", window(\"timeReceived\", \"10 minutes\")).count()tumblingWindows.show(truncate = False)" }, { "code": null, "e": 5069, "s": 4931, "text": "When observed on a timeline, the windows can be viewed as a sequence followed by each other in a static manner as in the following image." }, { "code": null, "e": 5272, "s": 5069, "text": "The sliding windows may have intersecting time periods when the time span contains a shorter interval than the range of the window. In such cases, timestamped items can be found in more than one window." }, { "code": null, "e": 5496, "s": 5272, "text": "from pyspark.sql.functions import *slidingWindows = windowing_df.withWatermark(\"timeReceived\", \"10 minutes\").groupBy(\"eventId\", window(\"timeReceived\", \"10 minutes\", \"5 minutes\")).count()slidingWindows.show(truncate = False)" }, { "code": null, "e": 5717, "s": 5496, "text": "When observed on a timeline, the windows can be overlapping or not overlapping according to the length of the time range when compared to the length of the main sliding window with a static manner as the tumbling window." }, { "code": null, "e": 5841, "s": 5717, "text": "Session windows may contain the nature of a dynamic length by means of the window size relative to the inputting item type." }, { "code": null, "e": 5987, "s": 5841, "text": "A session window begins with a single data point and broadens itself in case of the upcoming element has been collected inside of the gap period." }, { "code": null, "e": 6294, "s": 5987, "text": "When the last item is accepted, the session window ends when no items are acknowledged inside of the gap period. This feature permits the user to cluster the events when there are no advanced events injected for a selected period of time as also described in the official article as an inactive period [4]." }, { "code": null, "e": 6610, "s": 6294, "text": "In the real world, the logic of the session windowing operates as timeout occurrences. In some specific time gap, you shall be performing an activity, otherwise, the existing session closes when an adequate amount of time is passed. The session period can be enlarged in case having additional activity is recorded." }, { "code": null, "e": 6827, "s": 6610, "text": "For the specific usage of the session window, it can be depicted as creating a session window with upcoming events, and the continually gathering events inside the timeout period will be added in the current session." }, { "code": null, "e": 7045, "s": 6827, "text": "from pyspark.sql.functions import *sessionWindows = windowing_df.withWatermark(\"timeReceived\", \"10 minutes\").groupBy(\"eventId\", session_window(\"timeReceived\", \"5 minutes\")).count()sessionWindows.show(truncate = False)" }, { "code": null, "e": 7273, "s": 7045, "text": "Every event that is acquired will be capable of increasing the range of the session timeout. With this feature, the time period of the session window can be accepted as not static compared to the other two windowing approaches." }, { "code": null, "e": 7483, "s": 7273, "text": "For the specific example that is added above, the event with an id of 20, session windowing flow can be observed as one closes after a specified time period and begins again when a new element is acknowledged." }, { "code": null, "e": 7885, "s": 7483, "text": "The session window functionality has an additional feature which is called dynamic gap duration as mentioned in the Databricks blog post [4]. The period of the session may have various values when requested. The sessions that have an overlapping behavior can be grouped into a single session. The total duration of this session will be equal to the sum of the time duration of the intersecting events." }, { "code": null, "e": 8117, "s": 7885, "text": "You may group the data by the eventId, session window, and calculate its occurrences with the following script by inserting two values for the session_window() function as described in the latest programming guide of Spark 3.2 [5]." }, { "code": null, "e": 8441, "s": 8117, "text": "windowedCountsDF = windowing_df.withWatermark(\"timeReceived\", \"10 minutes\").groupBy(windowing_df.eventId, session_window(windowing_df.timeReceived, \\when(windowing_df.eventId == \"20\", \"10 seconds\").when(windowing_df.eventId == \"12\",\"30 seconds\").otherwise(\"10 minutes\"))).count()windowedCountsDF.show(100, truncate = False)" }, { "code": null, "e": 8751, "s": 8441, "text": "In the literature, there exist three main windowing functionalities. The ones that have a static manner are tumbling and sliding windows which were already available in the previous version of Spark 3.2. The dynamic natured session windows capability is now available with the latest version of Spark 3.2 [6]." }, { "code": null, "e": 8828, "s": 8751, "text": "You can find the full PySpark scripted code on the Google Colab environment." }, { "code": null, "e": 8906, "s": 8828, "text": "Questions and comments are highly appreciated! Thank you so much for reading!" }, { "code": null, "e": 8988, "s": 8906, "text": "Spark Release 3.2.0Structured Streaming Programming GuideAdvanced Spark Streaming" }, { "code": null, "e": 9008, "s": 8988, "text": "Spark Release 3.2.0" }, { "code": null, "e": 9047, "s": 9008, "text": "Structured Streaming Programming Guide" } ]
MySQL's DESCRIBE command?
The MySQL’s DESCRIBE or DESC both are equivalent. The DESC is the short form of DESCRIBE command and used to dipslay the information about a table like column names and constraints on column name. The DESCRIBE command is equivalent to the following command − SHOW columns from yourTableName command. The following is the query that display information about a table with the help of DESCRIBE command. The query is as follows. mysql> DESCRIBE Student; Above, Student is the table name in my database. The above query generates the following output. +-------+--------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +-------+--------------+------+-----+---------+-------+ | id | int(11) | YES | MUL | NULL | | | Name | varchar(100) | YES | MUL | NULL | | +-------+--------------+------+-----+---------+-------+ 2 rows in set (0.13 sec) Here is the equivalent query that gives the same result. The query is as follows. mysql> show columns from student; The following is the output. +-------+--------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +-------+--------------+------+-----+---------+-------+ | id | int(11) | YES | MUL | NULL | | | Name | varchar(100) | YES | MUL | NULL | | +-------+--------------+------+-----+---------+-------+ 2 rows in set (0.03 sec) As you see above, both of them gives the same output.
[ { "code": null, "e": 1259, "s": 1062, "text": "The MySQL’s DESCRIBE or DESC both are equivalent. The DESC is the short form of DESCRIBE command and used to dipslay the information about a table like column names and constraints on column name." }, { "code": null, "e": 1321, "s": 1259, "text": "The DESCRIBE command is equivalent to the following command −" }, { "code": null, "e": 1362, "s": 1321, "text": "SHOW columns from yourTableName command." }, { "code": null, "e": 1488, "s": 1362, "text": "The following is the query that display information about a table with the help of DESCRIBE command. The query is as follows." }, { "code": null, "e": 1513, "s": 1488, "text": "mysql> DESCRIBE Student;" }, { "code": null, "e": 1562, "s": 1513, "text": "Above, Student is the table name in my database." }, { "code": null, "e": 1610, "s": 1562, "text": "The above query generates the following output." }, { "code": null, "e": 1972, "s": 1610, "text": "+-------+--------------+------+-----+---------+-------+\n| Field | Type | Null | Key | Default | Extra |\n+-------+--------------+------+-----+---------+-------+\n| id | int(11) | YES | MUL | NULL | |\n| Name | varchar(100) | YES | MUL | NULL | |\n+-------+--------------+------+-----+---------+-------+\n2 rows in set (0.13 sec)\n" }, { "code": null, "e": 2054, "s": 1972, "text": "Here is the equivalent query that gives the same result. The query is as follows." }, { "code": null, "e": 2088, "s": 2054, "text": "mysql> show columns from student;" }, { "code": null, "e": 2117, "s": 2088, "text": "The following is the output." }, { "code": null, "e": 2479, "s": 2117, "text": "+-------+--------------+------+-----+---------+-------+\n| Field | Type | Null | Key | Default | Extra |\n+-------+--------------+------+-----+---------+-------+\n| id | int(11) | YES | MUL | NULL | |\n| Name | varchar(100) | YES | MUL | NULL | |\n+-------+--------------+------+-----+---------+-------+\n2 rows in set (0.03 sec)\n" }, { "code": null, "e": 2533, "s": 2479, "text": "As you see above, both of them gives the same output." } ]
C Quiz - 101 | Question 1 - GeeksforGeeks
28 Jun, 2021 Suppose that in a C program snippet, followings statements are used. i) sizeof(int);ii) sizeof(int*);iii) sizeof(int**); Assuming size of pointer is 4 bytes and size of int is also 4 bytes, pick the most correct answer from the given options.(A) Only i) would compile successfully and it would return size as 4.(B) i), ii) and iii) would compile successfully and size of each would be same i.e. 4(C) i), ii) and iii) would compile successfully but the size of each would be different and would be decided at run time.(D) ii) and iii) would result in compile error but i) would compile and result in size as 4.Answer: (B)Explanation: Size of all pointer types is same. And whether it is a ‘pointer to char’ or ‘pointer to int’ or ‘pointer to pointer to int’, the size always remain same. That’s why all i), ii) and iii) would compile successfully and would result in same size value of 4.Quiz of this Question C Quiz - 101 C-C Quiz - 101 C Language C Quiz Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to dynamically allocate a 2D array in C? fgets() and gets() in C language Exception Handling in C++ void pointer in C / C++ sizeof operator in C Compiling a C program:- Behind the Scenes Operator Precedence and Associativity in C C | File Handling | Question 1 C | Misc | Question 7 Output of C programs | Set 64 (Pointers)
[ { "code": null, "e": 23841, "s": 23813, "text": "\n28 Jun, 2021" }, { "code": null, "e": 23910, "s": 23841, "text": "Suppose that in a C program snippet, followings statements are used." }, { "code": "i) sizeof(int);ii) sizeof(int*);iii) sizeof(int**);", "e": 23962, "s": 23910, "text": null }, { "code": null, "e": 24509, "s": 23962, "text": "Assuming size of pointer is 4 bytes and size of int is also 4 bytes, pick the most correct answer from the given options.(A) Only i) would compile successfully and it would return size as 4.(B) i), ii) and iii) would compile successfully and size of each would be same i.e. 4(C) i), ii) and iii) would compile successfully but the size of each would be different and would be decided at run time.(D) ii) and iii) would result in compile error but i) would compile and result in size as 4.Answer: (B)Explanation: Size of all pointer types is same." }, { "code": null, "e": 24628, "s": 24509, "text": "And whether it is a ‘pointer to char’ or ‘pointer to int’ or ‘pointer to pointer to int’, the size always remain same." }, { "code": null, "e": 24750, "s": 24628, "text": "That’s why all i), ii) and iii) would compile successfully and would result in same size value of 4.Quiz of this Question" }, { "code": null, "e": 24763, "s": 24750, "text": "C Quiz - 101" }, { "code": null, "e": 24778, "s": 24763, "text": "C-C Quiz - 101" }, { "code": null, "e": 24789, "s": 24778, "text": "C Language" }, { "code": null, "e": 24796, "s": 24789, "text": "C Quiz" }, { "code": null, "e": 24894, "s": 24796, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 24903, "s": 24894, "text": "Comments" }, { "code": null, "e": 24916, "s": 24903, "text": "Old Comments" }, { "code": null, "e": 24961, "s": 24916, "text": "How to dynamically allocate a 2D array in C?" }, { "code": null, "e": 24994, "s": 24961, "text": "fgets() and gets() in C language" }, { "code": null, "e": 25020, "s": 24994, "text": "Exception Handling in C++" }, { "code": null, "e": 25044, "s": 25020, "text": "void pointer in C / C++" }, { "code": null, "e": 25065, "s": 25044, "text": "sizeof operator in C" }, { "code": null, "e": 25107, "s": 25065, "text": "Compiling a C program:- Behind the Scenes" }, { "code": null, "e": 25150, "s": 25107, "text": "Operator Precedence and Associativity in C" }, { "code": null, "e": 25181, "s": 25150, "text": "C | File Handling | Question 1" }, { "code": null, "e": 25203, "s": 25181, "text": "C | Misc | Question 7" } ]
Data Science Case Study: Optimizing Product Placement in Retail (Part 1) | by Andrew Olton | Towards Data Science
In a previous post, I wrote about an approach that I take to creating value with my data science project. To quickly recap and summarize what I said in that post, the goal of Data Science is to empower better decision making. Doing this requires that we have the empathy to ensure that we ask the right questions and that we use the right information. When juxtaposed against the Value Proposition Canvas, data science projects can be seen as products that meet the needs of our customers (namely decision making), deal with the challenges associated to making those decisions and maximize the benefits to be gained from making the right decisions. For today’s post, the dataset I’m going to use comes from Analytics Vidhya’s ‘Big Mart Sales III’ dataset which is available through one of their practice competitions. You can take a look using the link below. datahack.analyticsvidhya.com The data scientists at BigMart have collected 2013 sales data for 1559 products across 10 stores in different cities. Also, certain attributes of each product and store have been defined. The data contained in the dataset is as follows: Item_Identifier: Unique product ID Item_Weight Weight of product Item_Fat_Content: Whether the product is low fat or not Item_Visibility: The % of total display area of all products in a store allocated to the particular product Item_Type: The category to which the product belongs Item_MRP: Maximum Retail Price (list price) of the product Outlet_Identifier: Unique store ID Outlet_Establishment_Year: The year in which store was established Outlet_Size: The size of the store in terms of ground area covered Outlet_Location_Type: The type of city in which the store is located Outlet_Type: Whether the outlet is just a grocery store or some sort of supermarket Item_Outlet_Sales: Sales of the product in the particular store. As stated previously, in this project, we will try to find the best product placement options for maximising the Item_Outlet_Sales variable. We will do so by creating a model to forecast that value for certain items, then suggest possible ways of improving that product’s placement. Using what we know to create our customer profile we get: Job: Optimizing product placement Pains: Ignorance of the factors that influence sales Gains: Insight into customer preferences. To create the right data product, this is what we’ll do: Build a Model for creating sales forecastsUnderstand what affects salesBased on what affects sales, provide suggestions for increasing originals forecasts Build a Model for creating sales forecasts Understand what affects sales Based on what affects sales, provide suggestions for increasing originals forecasts I thought it would be worth sharing that I used XGBoost’s feature importance function for determining the features I’d like to manipulate in order to change the sales forecast. The graph below shows the importance of various features in the dataset: Of all the features shown on the graph, it’s important to pay attention to the Item_MRP, Outlet_Type, Item_Visibility, Outlet_Size and Outlet_Location_Type — these are the tractable features. For this project, I’m going to assume we wish to leave the MRP as is. The most significant of which is the ‘Outlet_Type’ variable. Adjusting the forecast primarily means selecting the outlet type that will yield the most promising forecast. In doing this, I decided that it was best to cycle through the existing outlet (and their respective configuration) due to the fact that there are only 10 BigMart outlets. The code for doing so is as follows: Generating our new forecast was fairly simple and was done like so: After running the program I wrote, the following recommendation was produced: I recommend that Item 'FDW58', be moved from Outlet 'OUT049', to Outlet 'OUT027'.The adjusted forecast is expected to be 64.0% better (2606.40), than the original forecast of $1589.31.Configuration details:Outlet_Size: Medium --> MediumOutlet_Location_Type: Tier 1 --> Tier 3Outlet_Type: Supermarket Type1 --> Supermarket Type3Outlet_Age: 19 --> 33 Tying all of this back to what I mentioned previously about Value Proposition Design and Data Science projects, we can summarize what we have designed like so: Products and Services: A data product which suggests the best placement options for a product. Pain Relievers: Reduced uncertainty in decision making. Gain Creators: Products being within reach of the customers that need them most. Note that in this example, our solution not only solves a problem for the staff at Big Mart, but is also affects their customers. Thinking about those affected by the decisions our products support is vital to creating the right product. It is important to note that this algorithm is commonly found in ‘perfect system’ use cases such as game-playing and simulation in which all the rules of the system are known and there are no unknown variables. Unfortunately, this is not how life works. Machine Learning techniques applied to “what if” scenarios serve only to provide a guide on what may yield the best results. Even though were provided with sales data, were are still not sure of the seasonality of the shopping habits observed, which can certainly have an impact on the quality of the recommendation produced. A better version of this system would be able to find the best placement options for multiple products while allowing users to prioritize one product over another. I hope that this post gave you a clear and practical approach to using creating value with your Data Science to projects and I hope that you learned something new. As usual I welcome your feedback and look forward to producing more content. I would like to end this post by giving a shout to some very important people. Firstly I would like to thank the lovely folks at Data Helpers for making themselves available for questions, guidance and data science help in general. If you are looking for a Data Science mentor, I highly recommend that you start there. I would also like to thank Rachael Tatman for putting me on to them and also for the excellent work she’s doing at Kaggle in Data Science education. If you would like to learn more about the tools I used to build the solution mentioned in this case study, please see the links below:
[ { "code": null, "e": 524, "s": 172, "text": "In a previous post, I wrote about an approach that I take to creating value with my data science project. To quickly recap and summarize what I said in that post, the goal of Data Science is to empower better decision making. Doing this requires that we have the empathy to ensure that we ask the right questions and that we use the right information." }, { "code": null, "e": 821, "s": 524, "text": "When juxtaposed against the Value Proposition Canvas, data science projects can be seen as products that meet the needs of our customers (namely decision making), deal with the challenges associated to making those decisions and maximize the benefits to be gained from making the right decisions." }, { "code": null, "e": 1032, "s": 821, "text": "For today’s post, the dataset I’m going to use comes from Analytics Vidhya’s ‘Big Mart Sales III’ dataset which is available through one of their practice competitions. You can take a look using the link below." }, { "code": null, "e": 1061, "s": 1032, "text": "datahack.analyticsvidhya.com" }, { "code": null, "e": 1249, "s": 1061, "text": "The data scientists at BigMart have collected 2013 sales data for 1559 products across 10 stores in different cities. Also, certain attributes of each product and store have been defined." }, { "code": null, "e": 1298, "s": 1249, "text": "The data contained in the dataset is as follows:" }, { "code": null, "e": 1333, "s": 1298, "text": "Item_Identifier: Unique product ID" }, { "code": null, "e": 1363, "s": 1333, "text": "Item_Weight Weight of product" }, { "code": null, "e": 1419, "s": 1363, "text": "Item_Fat_Content: Whether the product is low fat or not" }, { "code": null, "e": 1527, "s": 1419, "text": "Item_Visibility: The % of total display area of all products in a store allocated to the particular product" }, { "code": null, "e": 1580, "s": 1527, "text": "Item_Type: The category to which the product belongs" }, { "code": null, "e": 1639, "s": 1580, "text": "Item_MRP: Maximum Retail Price (list price) of the product" }, { "code": null, "e": 1674, "s": 1639, "text": "Outlet_Identifier: Unique store ID" }, { "code": null, "e": 1741, "s": 1674, "text": "Outlet_Establishment_Year: The year in which store was established" }, { "code": null, "e": 1808, "s": 1741, "text": "Outlet_Size: The size of the store in terms of ground area covered" }, { "code": null, "e": 1877, "s": 1808, "text": "Outlet_Location_Type: The type of city in which the store is located" }, { "code": null, "e": 1961, "s": 1877, "text": "Outlet_Type: Whether the outlet is just a grocery store or some sort of supermarket" }, { "code": null, "e": 2026, "s": 1961, "text": "Item_Outlet_Sales: Sales of the product in the particular store." }, { "code": null, "e": 2309, "s": 2026, "text": "As stated previously, in this project, we will try to find the best product placement options for maximising the Item_Outlet_Sales variable. We will do so by creating a model to forecast that value for certain items, then suggest possible ways of improving that product’s placement." }, { "code": null, "e": 2367, "s": 2309, "text": "Using what we know to create our customer profile we get:" }, { "code": null, "e": 2401, "s": 2367, "text": "Job: Optimizing product placement" }, { "code": null, "e": 2454, "s": 2401, "text": "Pains: Ignorance of the factors that influence sales" }, { "code": null, "e": 2496, "s": 2454, "text": "Gains: Insight into customer preferences." }, { "code": null, "e": 2553, "s": 2496, "text": "To create the right data product, this is what we’ll do:" }, { "code": null, "e": 2708, "s": 2553, "text": "Build a Model for creating sales forecastsUnderstand what affects salesBased on what affects sales, provide suggestions for increasing originals forecasts" }, { "code": null, "e": 2751, "s": 2708, "text": "Build a Model for creating sales forecasts" }, { "code": null, "e": 2781, "s": 2751, "text": "Understand what affects sales" }, { "code": null, "e": 2865, "s": 2781, "text": "Based on what affects sales, provide suggestions for increasing originals forecasts" }, { "code": null, "e": 3115, "s": 2865, "text": "I thought it would be worth sharing that I used XGBoost’s feature importance function for determining the features I’d like to manipulate in order to change the sales forecast. The graph below shows the importance of various features in the dataset:" }, { "code": null, "e": 3548, "s": 3115, "text": "Of all the features shown on the graph, it’s important to pay attention to the Item_MRP, Outlet_Type, Item_Visibility, Outlet_Size and Outlet_Location_Type — these are the tractable features. For this project, I’m going to assume we wish to leave the MRP as is. The most significant of which is the ‘Outlet_Type’ variable. Adjusting the forecast primarily means selecting the outlet type that will yield the most promising forecast." }, { "code": null, "e": 3720, "s": 3548, "text": "In doing this, I decided that it was best to cycle through the existing outlet (and their respective configuration) due to the fact that there are only 10 BigMart outlets." }, { "code": null, "e": 3757, "s": 3720, "text": "The code for doing so is as follows:" }, { "code": null, "e": 3825, "s": 3757, "text": "Generating our new forecast was fairly simple and was done like so:" }, { "code": null, "e": 3903, "s": 3825, "text": "After running the program I wrote, the following recommendation was produced:" }, { "code": null, "e": 4253, "s": 3903, "text": "I recommend that Item 'FDW58', be moved from Outlet 'OUT049', to Outlet 'OUT027'.The adjusted forecast is expected to be 64.0% better (2606.40), than the original forecast of $1589.31.Configuration details:Outlet_Size: Medium --> MediumOutlet_Location_Type: Tier 1 --> Tier 3Outlet_Type: Supermarket Type1 --> Supermarket Type3Outlet_Age: 19 --> 33" }, { "code": null, "e": 4413, "s": 4253, "text": "Tying all of this back to what I mentioned previously about Value Proposition Design and Data Science projects, we can summarize what we have designed like so:" }, { "code": null, "e": 4508, "s": 4413, "text": "Products and Services: A data product which suggests the best placement options for a product." }, { "code": null, "e": 4564, "s": 4508, "text": "Pain Relievers: Reduced uncertainty in decision making." }, { "code": null, "e": 4645, "s": 4564, "text": "Gain Creators: Products being within reach of the customers that need them most." }, { "code": null, "e": 4883, "s": 4645, "text": "Note that in this example, our solution not only solves a problem for the staff at Big Mart, but is also affects their customers. Thinking about those affected by the decisions our products support is vital to creating the right product." }, { "code": null, "e": 5262, "s": 4883, "text": "It is important to note that this algorithm is commonly found in ‘perfect system’ use cases such as game-playing and simulation in which all the rules of the system are known and there are no unknown variables. Unfortunately, this is not how life works. Machine Learning techniques applied to “what if” scenarios serve only to provide a guide on what may yield the best results." }, { "code": null, "e": 5627, "s": 5262, "text": "Even though were provided with sales data, were are still not sure of the seasonality of the shopping habits observed, which can certainly have an impact on the quality of the recommendation produced. A better version of this system would be able to find the best placement options for multiple products while allowing users to prioritize one product over another." }, { "code": null, "e": 5868, "s": 5627, "text": "I hope that this post gave you a clear and practical approach to using creating value with your Data Science to projects and I hope that you learned something new. As usual I welcome your feedback and look forward to producing more content." }, { "code": null, "e": 6336, "s": 5868, "text": "I would like to end this post by giving a shout to some very important people. Firstly I would like to thank the lovely folks at Data Helpers for making themselves available for questions, guidance and data science help in general. If you are looking for a Data Science mentor, I highly recommend that you start there. I would also like to thank Rachael Tatman for putting me on to them and also for the excellent work she’s doing at Kaggle in Data Science education." } ]
Longest Common Subsequence | DP using Memoization - GeeksforGeeks
14 May, 2021 Given two strings s1 and s2, the task is to find the length of the longest common subsequence present in both of them. Examples: Input: s1 = “ABCDGH”, s2 = “AEDFHR” Output: 3 LCS for input Sequences “AGGTAB” and “GXTXAYB” is “GTAB” of length 4.Input: s1 = “striver”, s2 = “raj” Output: 1 The naive solution for this problem is to generate all subsequences of both given sequences and find the longest matching subsequence. This solution is exponential in terms of time complexity. The general recursive solution of the problem is to generate all subsequences of both given sequences and find the longest matching subsequence. The total possible combinations will be 2n. Hence, the recursive solution will take O(2n). Optimal Substructure: Let the input sequences are X[0... m-1] and Y[0...n-1] of lengths m and n respectively. And let L(X[0... m-1], Y[0...n-1]) be the length of LCS of the two sequences X and Y. Following is the recursive definition of L(X[0... m-1], Y[0...n-1]). If last characters of both sequences match (or X[m-1] == Y[n-1]) then L(X[0... m-1], Y[0...n-1]) = 1 + L(X[0... m-2], Y[0...n-2]) If last characters of both sequences do not match (or X[m-1] != Y[n-1]) then L(X[0... m-1], Y[0...n-1]) = MAX (L(X[0... m-2], Y[0...n-1]), L(X[0... m-1], Y[0...n-2]) Given below is the recursive solution to the LCS problem: C++ Java Python3 C# PHP Javascript // A Naive C++ recursive implementation// of LCS of two strings#include <bits/stdc++.h>using namespace std; // Returns length of LCS for X[0..m-1], Y[0..n-1]int lcs(string X, string Y, int m, int n){ if (m == 0 || n == 0) return 0; if (X[m - 1] == Y[n - 1]) return 1 + lcs(X, Y, m - 1, n - 1); else return max(lcs(X, Y, m, n - 1), lcs(X, Y, m - 1, n));} // Driver Codeint main(){ string X = "AGGTAB"; string Y = "GXTXAYB"; // Find the length of string int m = X.length(); int n = Y.length(); cout << "Length of LCS: " << lcs(X, Y, m, n); return 0;} // A Naive Java recursive implementation// of LCS of two strings class GFG { // Returns length of LCS for X[0..m-1], Y[0..n-1] static int lcs(String X, String Y, int m, int n) { if (m == 0 || n == 0) { return 0; } if (X.charAt(m - 1) == Y.charAt(n - 1)) { return 1 + lcs(X, Y, m - 1, n - 1); } else { return Math.max(lcs(X, Y, m, n - 1), lcs(X, Y, m - 1, n)); } }// Driver Code public static void main(String[] args) { String X = "AGGTAB"; String Y = "GXTXAYB"; // Find the length of String int m = X.length(); int n = Y.length(); System.out.println("Length of LCS: " + lcs(X, Y, m, n)); }} // This code is contributed by 29AjayKumar # A Naive Python recursive implementation# of LCS of two strings # Returns length of LCS for X[0..m-1], Y[0..n-1]def lcs(X, Y, m, n): if (m == 0 or n == 0): return 0 if (X[m - 1] == Y[n - 1]): return 1 + lcs(X, Y, m - 1, n - 1) else: return max(lcs(X, Y, m, n - 1), lcs(X, Y, m - 1, n)) # Driver Codeif __name__ == '__main__': X = "AGGTAB" Y = "GXTXAYB" # Find the length of string m = len(X) n = len(Y) print("Length of LCS:", lcs(X, Y, m, n)) # This code is contributed by 29AjayKumar // A Naive recursive C#implementation of// LCS of two stringsusing System; class GFG{ // Returns length of LCS for// X[0..m-1], Y[0..n-1]static int lcs(String X, String Y, int m, int n){ if (m == 0 || n == 0) { return 0; } if (X[m - 1] == Y[n - 1]) { return 1 + lcs(X, Y, m - 1, n - 1); } else { return Math.Max(lcs(X, Y, m, n - 1), lcs(X, Y, m - 1, n)); }} // Driver Codepublic static void Main(){ String X = "AGGTAB"; String Y = "GXTXAYB"; // Find the length of String int m = X.Length; int n = Y.Length; Console.Write("Length of LCS: " + lcs(X, Y, m, n));}} // This code is contributed by 29AjayKumar <?php// A Naive PHP recursive implementation// of LCS of two strings // Returns length of LCS for// X[0..m-1], Y[0..n-1]function lcs($X, $Y, $m, $n){ if ($m == 0 || $n == 0) return 0; if ($X[$m - 1] == $Y[$n - 1]) return 1 + lcs($X, $Y, $m - 1, $n - 1); else return max(lcs($X, $Y, $m, $n - 1), lcs($X, $Y, $m - 1, $n));} // Driver Code$X = "AGGTAB";$Y = "GXTXAYB"; // Find the length of string$m = strlen($X);$n = strlen($Y); echo "Length of LCS: " . lcs($X, $Y, $m, $n); // This code is contributed by ita_c?> <script>// A Naive Javascript recursive implementation// of LCS of two strings // Returns length of LCS for X[0..m-1], Y[0..n-1] function lcs(X,Y,m,n) { if (m == 0 || n == 0) { return 0; } if (X[m-1] == Y[n-1]) { return 1 + lcs(X, Y, m - 1, n - 1); } else { return Math.max(lcs(X, Y, m, n - 1), lcs(X, Y, m - 1, n)); } } // Driver Code let X = "AGGTAB"; let Y = "GXTXAYB"; // Find the length of String let m = X.length; let n = Y.length; document.write("Length of LCS: " + lcs(X, Y, m, n)); // This code is contributed by rag2127</script> Length of LCS: 4 Dynamic Programming using Memoization Considering the above implementation, the following is a partial recursion tree for input strings “AXYT” and “AYZX” lcs("AXYT", "AYZX") / \ lcs("AXY", "AYZX") lcs("AXYT", "AYZ") / \ / \ lcs("AX", "AYZX") lcs("AXY", "AYZ") lcs("AXY", "AYZ") lcs("AXYT", "AY") In the above partial recursion tree, lcs(“AXY”, “AYZ”) are being solved twice. On drawing the complete recursion tree, it has been observed that there are many subproblems that are solved again and again. So this problem has Overlapping Substructure property and recomputation of same subproblems can be avoided by either using Memoization or Tabulation. The tabulation method has been discussed here. A common point of observation to use memoization in the recursive code will be the two non-constant arguments M and N in every function call. The function has 4 arguments, but 2 arguments are constant which does not affect the Memoization. The repetitive calls occur for N and M which have been called previously. Following the below steps will help us to write the DP solution using memoization. Use a 2-D array to store the computed lcs(m, n) value at arr[m-1][n-1] as the string index starts from 0. Whenever the function with the same argument m and n are called again, do not perform any further recursive call and return arr[m-1][n-1] as the previous computation of the lcs(m, n) has already been stored in arr[m-1][n-1], hence reducing the recursive calls that happen more than once. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program to memoize// recursive implementation of LCS problem#include <bits/stdc++.h>using namespace std; const int maximum = 1000; // Returns length of LCS for X[0..m-1], Y[0..n-1] */// memoization applied in recursive solutionint lcs(string X, string Y, int m, int n, int dp[][maximum]){ // base case if (m == 0 || n == 0) return 0; // if the same state has already been // computed if (dp[m - 1][n - 1] != -1) return dp[m - 1][n - 1]; // if equal, then we store the value of the // function call if (X[m - 1] == Y[n - 1]) { // store it in arr to avoid further repetitive // work in future function calls dp[m - 1][n - 1] = 1 + lcs(X, Y, m - 1, n - 1, dp); return dp[m - 1][n - 1]; } else { // store it in arr to avoid further repetitive // work in future function calls dp[m - 1][n - 1] = max(lcs(X, Y, m, n - 1, dp), lcs(X, Y, m - 1, n, dp)); return dp[m - 1][n - 1]; }} // Driver Codeint main(){ string X = "AGGTAB"; string Y = "GXTXAYB"; int m = X.length(); int n = Y.length(); int dp[m][maximum]; // assign -1 to all positions memset(dp, -1, sizeof(dp)); cout << "Length of LCS: " << lcs(X, Y, m, n, dp); return 0;} import java.util.Arrays; // Java program to memoize// recursive implementation of LCS problemclass GFG { static final int maximum = 1000; // Returns length of LCS for X[0..m-1], Y[0..n-1] */// memoization applied in recursive solution static int lcs(String X, String Y, int m, int n, int dp[][]) { // base case if (m == 0 || n == 0) { return 0; } // if the same state has already been // computed if (dp[m - 1][n - 1] != -1) { return dp[m - 1][n - 1]; } // if equal, then we store the value of the // function call if (X.charAt(m - 1) == Y.charAt(n - 1)) { // store it in arr to avoid further repetitive // work in future function calls dp[m - 1][n - 1] = 1 + lcs(X, Y, m - 1, n - 1, dp); return dp[m - 1][n - 1]; } else { // store it in arr to avoid further repetitive // work in future function calls dp[m - 1][n - 1] = Math.max(lcs(X, Y, m, n - 1, dp), lcs(X, Y, m - 1, n, dp)); return dp[m - 1][n - 1]; } } // Driver Code public static void main(String[] args) { String X = "AGGTAB"; String Y = "GXTXAYB"; int m = X.length(); int n = Y.length(); int dp[][] = new int[m][maximum]; // assign -1 to all positions for (int[] row : dp) { Arrays.fill(row, -1); } System.out.println("Length of LCS: " + lcs(X, Y, m, n, dp)); }}/* This Java code is contributed by 29AjayKumar*/ # Python3 program to memoize# recursive implementation of LCS problemmaximum = 1000 # Returns length of LCS for X[0..m-1], Y[0..n-1] */# memoization applied in recursive solutiondef lcs(X, Y, m, n, dp): # base case if (m == 0 or n == 0): return 0 # if the same state has already been # computed if (dp[m - 1][n - 1] != -1): return dp[m - 1][n - 1] # if equal, then we store the value of the # function call if (X[m - 1] == Y[n - 1]): # store it in arr to avoid further repetitive # work in future function calls dp[m - 1][n - 1] = 1 + lcs(X, Y, m - 1, n - 1, dp) return dp[m - 1][n - 1] else : # store it in arr to avoid further repetitive # work in future function calls dp[m - 1][n - 1] = max(lcs(X, Y, m, n - 1, dp), lcs(X, Y, m - 1, n, dp)) return dp[m - 1][n - 1] # Driver CodeX = "AGGTAB"Y = "GXTXAYB"m = len(X)n = len(Y) dp = [[-1 for i in range(maximum)] for i in range(m)] print("Length of LCS:", lcs(X, Y, m, n, dp)) # This code is contributed by Mohit Kumar // C# program to memoize// recursive implementation of LCS problemusing System; class GFG{static readonly int maximum = 1000; // Returns length of LCS for// X[0..m-1], Y[0..n-1]// memoization applied in// recursive solutionstatic int lcs(String X, String Y, int m, int n, int [,]dp){ // base case if (m == 0 || n == 0) { return 0; } // if the same state has already been // computed if (dp[m - 1, n - 1] != -1) { return dp[m - 1, n - 1]; } // if equal, then we store the value // of the function call if (X[m - 1] == Y[n - 1]) { // store it in arr to avoid // further repetitive work // in future function calls dp[m - 1, n - 1] = 1 + lcs(X, Y, m - 1, n - 1, dp); return dp[m - 1, n - 1]; } else { // store it in arr to avoid // further repetitive work // in future function calls dp[m - 1, n - 1] = Math.Max(lcs(X, Y, m, n - 1, dp), lcs(X, Y, m - 1, n, dp)); return dp[m - 1, n - 1]; }} // Driver Codepublic static void Main(String[] args){ String X = "AGGTAB"; String Y = "GXTXAYB"; int m = X.Length; int n = Y.Length; int [,]dp = new int[m, maximum]; // assign -1 to all positions for(int i = 0; i < m; i++) { for(int j = 0; j < maximum; j++) { dp[i, j] = -1; } } Console.WriteLine("Length of LCS: " + lcs(X, Y, m, n, dp));}} // This code is contributed by PrinciRaj1992 <script>// Javascript program to memoize// recursive implementation of LCS problem let maximum = 1000; // Returns length of LCS for X[0..m-1], Y[0..n-1] */// memoization applied in recursive solutionfunction lcs(X,Y,m,n,dp){ // base case if (m == 0 || n == 0) { return 0; } // if the same state has already been // computed if (dp[m - 1][n - 1] != -1) { return dp[m - 1][n - 1]; } // if equal, then we store the value of the // function call if (X[m-1] == Y[n-1]) { // store it in arr to avoid further repetitive // work in future function calls dp[m - 1][n - 1] = 1 + lcs(X, Y, m - 1, n - 1, dp); return dp[m - 1][n - 1]; } else { // store it in arr to avoid further repetitive // work in future function calls dp[m - 1][n - 1] = Math.max(lcs(X, Y, m, n - 1, dp), lcs(X, Y, m - 1, n, dp)); return dp[m - 1][n - 1]; }} // Driver Codelet X = "AGGTAB";let Y = "GXTXAYB";let m = X.length;let n = Y.length; let dp=new Array(m);for(let i=0;i<dp.length;i++){ dp[i]=new Array(maximum); for(let j=0;j<dp[i].length;j++) { dp[i][j]=-1; }} document.write("Length of LCS: " + lcs(X, Y, m, n, dp)); // This code is contributed by avanitrachhadiya2155</script> Length of LCS: 4 Time Complexity: O(N * M), where N and M are lengths of the first and second string respectively. Auxiliary Space: (N * M) 29AjayKumar ukasp mohit kumar 29 princiraj1992 rag2127 avanitrachhadiya2155 LCS Memoization Dynamic Programming Strings Strings Dynamic Programming LCS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Optimal Substructure Property in Dynamic Programming | DP-2 Maximum sum such that no two elements are adjacent Min Cost Path | DP-6 Maximum Subarray Sum using Divide and Conquer algorithm Gold Mine Problem Reverse a string in Java Write a program to print all permutations of a given string KMP Algorithm for Pattern Searching C++ Data Types Array of Strings in C++ (5 Different Ways to Create)
[ { "code": null, "e": 24307, "s": 24279, "text": "\n14 May, 2021" }, { "code": null, "e": 24426, "s": 24307, "text": "Given two strings s1 and s2, the task is to find the length of the longest common subsequence present in both of them." }, { "code": null, "e": 24438, "s": 24426, "text": "Examples: " }, { "code": null, "e": 24599, "s": 24438, "text": "Input: s1 = “ABCDGH”, s2 = “AEDFHR” Output: 3 LCS for input Sequences “AGGTAB” and “GXTXAYB” is “GTAB” of length 4.Input: s1 = “striver”, s2 = “raj” Output: 1 " }, { "code": null, "e": 25051, "s": 24599, "text": "The naive solution for this problem is to generate all subsequences of both given sequences and find the longest matching subsequence. This solution is exponential in terms of time complexity. The general recursive solution of the problem is to generate all subsequences of both given sequences and find the longest matching subsequence. The total possible combinations will be 2n. Hence, the recursive solution will take O(2n). Optimal Substructure: " }, { "code": null, "e": 25294, "s": 25051, "text": "Let the input sequences are X[0... m-1] and Y[0...n-1] of lengths m and n respectively. And let L(X[0... m-1], Y[0...n-1]) be the length of LCS of the two sequences X and Y. Following is the recursive definition of L(X[0... m-1], Y[0...n-1])." }, { "code": null, "e": 25424, "s": 25294, "text": "If last characters of both sequences match (or X[m-1] == Y[n-1]) then L(X[0... m-1], Y[0...n-1]) = 1 + L(X[0... m-2], Y[0...n-2])" }, { "code": null, "e": 25590, "s": 25424, "text": "If last characters of both sequences do not match (or X[m-1] != Y[n-1]) then L(X[0... m-1], Y[0...n-1]) = MAX (L(X[0... m-2], Y[0...n-1]), L(X[0... m-1], Y[0...n-2])" }, { "code": null, "e": 25649, "s": 25590, "text": "Given below is the recursive solution to the LCS problem: " }, { "code": null, "e": 25653, "s": 25649, "text": "C++" }, { "code": null, "e": 25658, "s": 25653, "text": "Java" }, { "code": null, "e": 25666, "s": 25658, "text": "Python3" }, { "code": null, "e": 25669, "s": 25666, "text": "C#" }, { "code": null, "e": 25673, "s": 25669, "text": "PHP" }, { "code": null, "e": 25684, "s": 25673, "text": "Javascript" }, { "code": "// A Naive C++ recursive implementation// of LCS of two strings#include <bits/stdc++.h>using namespace std; // Returns length of LCS for X[0..m-1], Y[0..n-1]int lcs(string X, string Y, int m, int n){ if (m == 0 || n == 0) return 0; if (X[m - 1] == Y[n - 1]) return 1 + lcs(X, Y, m - 1, n - 1); else return max(lcs(X, Y, m, n - 1), lcs(X, Y, m - 1, n));} // Driver Codeint main(){ string X = \"AGGTAB\"; string Y = \"GXTXAYB\"; // Find the length of string int m = X.length(); int n = Y.length(); cout << \"Length of LCS: \" << lcs(X, Y, m, n); return 0;}", "e": 26306, "s": 25684, "text": null }, { "code": "// A Naive Java recursive implementation// of LCS of two strings class GFG { // Returns length of LCS for X[0..m-1], Y[0..n-1] static int lcs(String X, String Y, int m, int n) { if (m == 0 || n == 0) { return 0; } if (X.charAt(m - 1) == Y.charAt(n - 1)) { return 1 + lcs(X, Y, m - 1, n - 1); } else { return Math.max(lcs(X, Y, m, n - 1), lcs(X, Y, m - 1, n)); } }// Driver Code public static void main(String[] args) { String X = \"AGGTAB\"; String Y = \"GXTXAYB\"; // Find the length of String int m = X.length(); int n = Y.length(); System.out.println(\"Length of LCS: \" + lcs(X, Y, m, n)); }} // This code is contributed by 29AjayKumar", "e": 27085, "s": 26306, "text": null }, { "code": "# A Naive Python recursive implementation# of LCS of two strings # Returns length of LCS for X[0..m-1], Y[0..n-1]def lcs(X, Y, m, n): if (m == 0 or n == 0): return 0 if (X[m - 1] == Y[n - 1]): return 1 + lcs(X, Y, m - 1, n - 1) else: return max(lcs(X, Y, m, n - 1), lcs(X, Y, m - 1, n)) # Driver Codeif __name__ == '__main__': X = \"AGGTAB\" Y = \"GXTXAYB\" # Find the length of string m = len(X) n = len(Y) print(\"Length of LCS:\", lcs(X, Y, m, n)) # This code is contributed by 29AjayKumar", "e": 27651, "s": 27085, "text": null }, { "code": "// A Naive recursive C#implementation of// LCS of two stringsusing System; class GFG{ // Returns length of LCS for// X[0..m-1], Y[0..n-1]static int lcs(String X, String Y, int m, int n){ if (m == 0 || n == 0) { return 0; } if (X[m - 1] == Y[n - 1]) { return 1 + lcs(X, Y, m - 1, n - 1); } else { return Math.Max(lcs(X, Y, m, n - 1), lcs(X, Y, m - 1, n)); }} // Driver Codepublic static void Main(){ String X = \"AGGTAB\"; String Y = \"GXTXAYB\"; // Find the length of String int m = X.Length; int n = Y.Length; Console.Write(\"Length of LCS: \" + lcs(X, Y, m, n));}} // This code is contributed by 29AjayKumar", "e": 28373, "s": 27651, "text": null }, { "code": "<?php// A Naive PHP recursive implementation// of LCS of two strings // Returns length of LCS for// X[0..m-1], Y[0..n-1]function lcs($X, $Y, $m, $n){ if ($m == 0 || $n == 0) return 0; if ($X[$m - 1] == $Y[$n - 1]) return 1 + lcs($X, $Y, $m - 1, $n - 1); else return max(lcs($X, $Y, $m, $n - 1), lcs($X, $Y, $m - 1, $n));} // Driver Code$X = \"AGGTAB\";$Y = \"GXTXAYB\"; // Find the length of string$m = strlen($X);$n = strlen($Y); echo \"Length of LCS: \" . lcs($X, $Y, $m, $n); // This code is contributed by ita_c?>", "e": 28956, "s": 28373, "text": null }, { "code": "<script>// A Naive Javascript recursive implementation// of LCS of two strings // Returns length of LCS for X[0..m-1], Y[0..n-1] function lcs(X,Y,m,n) { if (m == 0 || n == 0) { return 0; } if (X[m-1] == Y[n-1]) { return 1 + lcs(X, Y, m - 1, n - 1); } else { return Math.max(lcs(X, Y, m, n - 1), lcs(X, Y, m - 1, n)); } } // Driver Code let X = \"AGGTAB\"; let Y = \"GXTXAYB\"; // Find the length of String let m = X.length; let n = Y.length; document.write(\"Length of LCS: \" + lcs(X, Y, m, n)); // This code is contributed by rag2127</script>", "e": 29629, "s": 28956, "text": null }, { "code": null, "e": 29646, "s": 29629, "text": "Length of LCS: 4" }, { "code": null, "e": 29686, "s": 29648, "text": "Dynamic Programming using Memoization" }, { "code": null, "e": 29804, "s": 29686, "text": "Considering the above implementation, the following is a partial recursion tree for input strings “AXYT” and “AYZX” " }, { "code": null, "e": 30081, "s": 29804, "text": " lcs(\"AXYT\", \"AYZX\")\n / \\\n lcs(\"AXY\", \"AYZX\") lcs(\"AXYT\", \"AYZ\")\n / \\ / \\\nlcs(\"AX\", \"AYZX\") lcs(\"AXY\", \"AYZ\") lcs(\"AXY\", \"AYZ\") lcs(\"AXYT\", \"AY\")" }, { "code": null, "e": 30881, "s": 30081, "text": "In the above partial recursion tree, lcs(“AXY”, “AYZ”) are being solved twice. On drawing the complete recursion tree, it has been observed that there are many subproblems that are solved again and again. So this problem has Overlapping Substructure property and recomputation of same subproblems can be avoided by either using Memoization or Tabulation. The tabulation method has been discussed here. A common point of observation to use memoization in the recursive code will be the two non-constant arguments M and N in every function call. The function has 4 arguments, but 2 arguments are constant which does not affect the Memoization. The repetitive calls occur for N and M which have been called previously. Following the below steps will help us to write the DP solution using memoization. " }, { "code": null, "e": 30987, "s": 30881, "text": "Use a 2-D array to store the computed lcs(m, n) value at arr[m-1][n-1] as the string index starts from 0." }, { "code": null, "e": 31275, "s": 30987, "text": "Whenever the function with the same argument m and n are called again, do not perform any further recursive call and return arr[m-1][n-1] as the previous computation of the lcs(m, n) has already been stored in arr[m-1][n-1], hence reducing the recursive calls that happen more than once." }, { "code": null, "e": 31327, "s": 31275, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 31331, "s": 31327, "text": "C++" }, { "code": null, "e": 31336, "s": 31331, "text": "Java" }, { "code": null, "e": 31344, "s": 31336, "text": "Python3" }, { "code": null, "e": 31347, "s": 31344, "text": "C#" }, { "code": null, "e": 31358, "s": 31347, "text": "Javascript" }, { "code": "// C++ program to memoize// recursive implementation of LCS problem#include <bits/stdc++.h>using namespace std; const int maximum = 1000; // Returns length of LCS for X[0..m-1], Y[0..n-1] */// memoization applied in recursive solutionint lcs(string X, string Y, int m, int n, int dp[][maximum]){ // base case if (m == 0 || n == 0) return 0; // if the same state has already been // computed if (dp[m - 1][n - 1] != -1) return dp[m - 1][n - 1]; // if equal, then we store the value of the // function call if (X[m - 1] == Y[n - 1]) { // store it in arr to avoid further repetitive // work in future function calls dp[m - 1][n - 1] = 1 + lcs(X, Y, m - 1, n - 1, dp); return dp[m - 1][n - 1]; } else { // store it in arr to avoid further repetitive // work in future function calls dp[m - 1][n - 1] = max(lcs(X, Y, m, n - 1, dp), lcs(X, Y, m - 1, n, dp)); return dp[m - 1][n - 1]; }} // Driver Codeint main(){ string X = \"AGGTAB\"; string Y = \"GXTXAYB\"; int m = X.length(); int n = Y.length(); int dp[m][maximum]; // assign -1 to all positions memset(dp, -1, sizeof(dp)); cout << \"Length of LCS: \" << lcs(X, Y, m, n, dp); return 0;}", "e": 32658, "s": 31358, "text": null }, { "code": "import java.util.Arrays; // Java program to memoize// recursive implementation of LCS problemclass GFG { static final int maximum = 1000; // Returns length of LCS for X[0..m-1], Y[0..n-1] */// memoization applied in recursive solution static int lcs(String X, String Y, int m, int n, int dp[][]) { // base case if (m == 0 || n == 0) { return 0; } // if the same state has already been // computed if (dp[m - 1][n - 1] != -1) { return dp[m - 1][n - 1]; } // if equal, then we store the value of the // function call if (X.charAt(m - 1) == Y.charAt(n - 1)) { // store it in arr to avoid further repetitive // work in future function calls dp[m - 1][n - 1] = 1 + lcs(X, Y, m - 1, n - 1, dp); return dp[m - 1][n - 1]; } else { // store it in arr to avoid further repetitive // work in future function calls dp[m - 1][n - 1] = Math.max(lcs(X, Y, m, n - 1, dp), lcs(X, Y, m - 1, n, dp)); return dp[m - 1][n - 1]; } } // Driver Code public static void main(String[] args) { String X = \"AGGTAB\"; String Y = \"GXTXAYB\"; int m = X.length(); int n = Y.length(); int dp[][] = new int[m][maximum]; // assign -1 to all positions for (int[] row : dp) { Arrays.fill(row, -1); } System.out.println(\"Length of LCS: \" + lcs(X, Y, m, n, dp)); }}/* This Java code is contributed by 29AjayKumar*/", "e": 34244, "s": 32658, "text": null }, { "code": "# Python3 program to memoize# recursive implementation of LCS problemmaximum = 1000 # Returns length of LCS for X[0..m-1], Y[0..n-1] */# memoization applied in recursive solutiondef lcs(X, Y, m, n, dp): # base case if (m == 0 or n == 0): return 0 # if the same state has already been # computed if (dp[m - 1][n - 1] != -1): return dp[m - 1][n - 1] # if equal, then we store the value of the # function call if (X[m - 1] == Y[n - 1]): # store it in arr to avoid further repetitive # work in future function calls dp[m - 1][n - 1] = 1 + lcs(X, Y, m - 1, n - 1, dp) return dp[m - 1][n - 1] else : # store it in arr to avoid further repetitive # work in future function calls dp[m - 1][n - 1] = max(lcs(X, Y, m, n - 1, dp), lcs(X, Y, m - 1, n, dp)) return dp[m - 1][n - 1] # Driver CodeX = \"AGGTAB\"Y = \"GXTXAYB\"m = len(X)n = len(Y) dp = [[-1 for i in range(maximum)] for i in range(m)] print(\"Length of LCS:\", lcs(X, Y, m, n, dp)) # This code is contributed by Mohit Kumar", "e": 35361, "s": 34244, "text": null }, { "code": "// C# program to memoize// recursive implementation of LCS problemusing System; class GFG{static readonly int maximum = 1000; // Returns length of LCS for// X[0..m-1], Y[0..n-1]// memoization applied in// recursive solutionstatic int lcs(String X, String Y, int m, int n, int [,]dp){ // base case if (m == 0 || n == 0) { return 0; } // if the same state has already been // computed if (dp[m - 1, n - 1] != -1) { return dp[m - 1, n - 1]; } // if equal, then we store the value // of the function call if (X[m - 1] == Y[n - 1]) { // store it in arr to avoid // further repetitive work // in future function calls dp[m - 1, n - 1] = 1 + lcs(X, Y, m - 1, n - 1, dp); return dp[m - 1, n - 1]; } else { // store it in arr to avoid // further repetitive work // in future function calls dp[m - 1, n - 1] = Math.Max(lcs(X, Y, m, n - 1, dp), lcs(X, Y, m - 1, n, dp)); return dp[m - 1, n - 1]; }} // Driver Codepublic static void Main(String[] args){ String X = \"AGGTAB\"; String Y = \"GXTXAYB\"; int m = X.Length; int n = Y.Length; int [,]dp = new int[m, maximum]; // assign -1 to all positions for(int i = 0; i < m; i++) { for(int j = 0; j < maximum; j++) { dp[i, j] = -1; } } Console.WriteLine(\"Length of LCS: \" + lcs(X, Y, m, n, dp));}} // This code is contributed by PrinciRaj1992", "e": 36954, "s": 35361, "text": null }, { "code": "<script>// Javascript program to memoize// recursive implementation of LCS problem let maximum = 1000; // Returns length of LCS for X[0..m-1], Y[0..n-1] */// memoization applied in recursive solutionfunction lcs(X,Y,m,n,dp){ // base case if (m == 0 || n == 0) { return 0; } // if the same state has already been // computed if (dp[m - 1][n - 1] != -1) { return dp[m - 1][n - 1]; } // if equal, then we store the value of the // function call if (X[m-1] == Y[n-1]) { // store it in arr to avoid further repetitive // work in future function calls dp[m - 1][n - 1] = 1 + lcs(X, Y, m - 1, n - 1, dp); return dp[m - 1][n - 1]; } else { // store it in arr to avoid further repetitive // work in future function calls dp[m - 1][n - 1] = Math.max(lcs(X, Y, m, n - 1, dp), lcs(X, Y, m - 1, n, dp)); return dp[m - 1][n - 1]; }} // Driver Codelet X = \"AGGTAB\";let Y = \"GXTXAYB\";let m = X.length;let n = Y.length; let dp=new Array(m);for(let i=0;i<dp.length;i++){ dp[i]=new Array(maximum); for(let j=0;j<dp[i].length;j++) { dp[i][j]=-1; }} document.write(\"Length of LCS: \" + lcs(X, Y, m, n, dp)); // This code is contributed by avanitrachhadiya2155</script>", "e": 38347, "s": 36954, "text": null }, { "code": null, "e": 38364, "s": 38347, "text": "Length of LCS: 4" }, { "code": null, "e": 38490, "s": 38366, "text": "Time Complexity: O(N * M), where N and M are lengths of the first and second string respectively. Auxiliary Space: (N * M) " }, { "code": null, "e": 38502, "s": 38490, "text": "29AjayKumar" }, { "code": null, "e": 38508, "s": 38502, "text": "ukasp" }, { "code": null, "e": 38523, "s": 38508, "text": "mohit kumar 29" }, { "code": null, "e": 38537, "s": 38523, "text": "princiraj1992" }, { "code": null, "e": 38545, "s": 38537, "text": "rag2127" }, { "code": null, "e": 38566, "s": 38545, "text": "avanitrachhadiya2155" }, { "code": null, "e": 38570, "s": 38566, "text": "LCS" }, { "code": null, "e": 38582, "s": 38570, "text": "Memoization" }, { "code": null, "e": 38602, "s": 38582, "text": "Dynamic Programming" }, { "code": null, "e": 38610, "s": 38602, "text": "Strings" }, { "code": null, "e": 38618, "s": 38610, "text": "Strings" }, { "code": null, "e": 38638, "s": 38618, "text": "Dynamic Programming" }, { "code": null, "e": 38642, "s": 38638, "text": "LCS" }, { "code": null, "e": 38740, "s": 38642, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 38749, "s": 38740, "text": "Comments" }, { "code": null, "e": 38762, "s": 38749, "text": "Old Comments" }, { "code": null, "e": 38822, "s": 38762, "text": "Optimal Substructure Property in Dynamic Programming | DP-2" }, { "code": null, "e": 38873, "s": 38822, "text": "Maximum sum such that no two elements are adjacent" }, { "code": null, "e": 38894, "s": 38873, "text": "Min Cost Path | DP-6" }, { "code": null, "e": 38950, "s": 38894, "text": "Maximum Subarray Sum using Divide and Conquer algorithm" }, { "code": null, "e": 38968, "s": 38950, "text": "Gold Mine Problem" }, { "code": null, "e": 38993, "s": 38968, "text": "Reverse a string in Java" }, { "code": null, "e": 39053, "s": 38993, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 39089, "s": 39053, "text": "KMP Algorithm for Pattern Searching" }, { "code": null, "e": 39104, "s": 39089, "text": "C++ Data Types" } ]
GitLab - Create Backup
GitLab allows to take backup copy of your repository by using simple command. In this chapter, we will discuss about how to take backup copy in the GitLab − Step 1 − First, login to your GitLab server using SSH (Secure Shell). Step 2 − Create the backup of GitLab by using the below command − sudo gitlab-rake gitlab:backup:create Step 3 − You can exclude some directories from the backup by adding environment variable SKIP as shown below − sudo gitlab-rake gitlab:backup:create SKIP = db,uploads Step 4 − The backup tar file will get created in the default /var/opt/gitlab/backups directory. Navigate to this path and type ls -l to see the created backup file − Print Add Notes Bookmark this page
[ { "code": null, "e": 2481, "s": 2324, "text": "GitLab allows to take backup copy of your repository by using simple command. In this chapter, we will discuss about how to take backup copy in the GitLab −" }, { "code": null, "e": 2551, "s": 2481, "text": "Step 1 − First, login to your GitLab server using SSH (Secure Shell)." }, { "code": null, "e": 2617, "s": 2551, "text": "Step 2 − Create the backup of GitLab by using the below command −" }, { "code": null, "e": 2655, "s": 2617, "text": "sudo gitlab-rake gitlab:backup:create" }, { "code": null, "e": 2766, "s": 2655, "text": "Step 3 − You can exclude some directories from the backup by adding environment variable SKIP as shown below −" }, { "code": null, "e": 2822, "s": 2766, "text": "sudo gitlab-rake gitlab:backup:create SKIP = db,uploads" }, { "code": null, "e": 2988, "s": 2822, "text": "Step 4 − The backup tar file will get created in the default /var/opt/gitlab/backups directory. Navigate to this path and type ls -l to see the created backup file −" }, { "code": null, "e": 2995, "s": 2988, "text": " Print" }, { "code": null, "e": 3006, "s": 2995, "text": " Add Notes" } ]
Select into in MySQL?
To do select into in MySQL, use CREATE TABLE SELECT command. The syntax is as follows − CREATE TABLE yourTableName SELECT *FROM yourOriginalTableName; To understand, let us first create a table − mysql> create table SelectIntoDemo -> ( -> Id int, -> Name varchar(200) -> ); Query OK, 0 rows affected (0.50 sec) Let us insert some records into the table with the help of insert command. The query is as follows − mysql> insert into SelectIntoDemo values(1,'Bob'),(2,'Carol'),(3,'David'); Query OK, 3 rows affected (0.15 sec) Records: 3 Duplicates: 0 Warnings: 0 Displaying all records with the help of select statement. The query is as follows − mysql> select *from SelectIntoDemo; Here is the output − +------+-------+ | Id | Name | +------+-------+ | 1 | Bob | | 2 | Carol | | 3 | David | +------+-------+ 3 rows in set (0.00 sec) Now you can apply the above syntax discussed in the beginning. The query is as follows − mysql> create table yourTempTable select *from SelectIntoDemo; Query OK, 3 rows affected (0.56 sec) Records: 3 Duplicates: 0 Warnings: 0 Check all records with new table name “yourTempTable”. The query is as follows − mysql> select *from yourTempTable; The following is the output − +------+-------+ | Id | Name | +------+-------+ | 1 | Bob | | 2 | Carol | | 3 | David | +------+-------+ 3 rows in set (0.00 sec)
[ { "code": null, "e": 1150, "s": 1062, "text": "To do select into in MySQL, use CREATE TABLE SELECT command. The syntax is as follows −" }, { "code": null, "e": 1213, "s": 1150, "text": "CREATE TABLE yourTableName SELECT *FROM yourOriginalTableName;" }, { "code": null, "e": 1258, "s": 1213, "text": "To understand, let us first create a table −" }, { "code": null, "e": 1373, "s": 1258, "text": "mysql> create table SelectIntoDemo\n-> (\n-> Id int,\n-> Name varchar(200)\n-> );\nQuery OK, 0 rows affected (0.50 sec)" }, { "code": null, "e": 1474, "s": 1373, "text": "Let us insert some records into the table with the help of insert command. The query is as follows −" }, { "code": null, "e": 1623, "s": 1474, "text": "mysql> insert into SelectIntoDemo values(1,'Bob'),(2,'Carol'),(3,'David');\nQuery OK, 3 rows affected (0.15 sec)\nRecords: 3 Duplicates: 0 Warnings: 0" }, { "code": null, "e": 1707, "s": 1623, "text": "Displaying all records with the help of select statement. The query is as follows −" }, { "code": null, "e": 1743, "s": 1707, "text": "mysql> select *from SelectIntoDemo;" }, { "code": null, "e": 1764, "s": 1743, "text": "Here is the output −" }, { "code": null, "e": 1907, "s": 1764, "text": "+------+-------+\n| Id | Name |\n+------+-------+\n| 1 | Bob |\n| 2 | Carol |\n| 3 | David |\n+------+-------+\n3 rows in set (0.00 sec)" }, { "code": null, "e": 1996, "s": 1907, "text": "Now you can apply the above syntax discussed in the beginning. The query is as follows −" }, { "code": null, "e": 2133, "s": 1996, "text": "mysql> create table yourTempTable select *from SelectIntoDemo;\nQuery OK, 3 rows affected (0.56 sec)\nRecords: 3 Duplicates: 0 Warnings: 0" }, { "code": null, "e": 2214, "s": 2133, "text": "Check all records with new table name “yourTempTable”. The query is as follows −" }, { "code": null, "e": 2249, "s": 2214, "text": "mysql> select *from yourTempTable;" }, { "code": null, "e": 2279, "s": 2249, "text": "The following is the output −" }, { "code": null, "e": 2423, "s": 2279, "text": "+------+-------+\n| Id | Name |\n+------+-------+\n| 1 | Bob |\n| 2 | Carol |\n| 3 | David |\n+------+-------+\n3 rows in set (0.00 sec)" } ]
How to use the Google Maps API with Custom styling in React.js | by Sabesan Sathananthan | Towards Data Science
When my friend tried a new hairstyle I asked him “Why did you cut like this?” And he told that he wanted to shine as a model. Therefore, I understood that people like to show them uniquely and beautifully. When I developed a personal react application I wanted to implement google map API. I searched a lot of examples on google and finally, I found a simple solution. Here I will briefly explain how I used the application and what are the custom styles we could add to the google map. Here we will look from scratch. You could see the demo here. This is my 29th article in Medium. If you don’t have Google maps API token signup Google maps API and get the token to use! To receive your token you must enter a credit card number. Yet Google says they won’t charge your account without you updating your service personally. Go ahead at your decision. Once you’ve got an API key, begin to develop your app! To create a react application run the following command in your shell/terminal in a specific folder (e.g., desktop ) npx create-react-app google-map A new folder will be created, and it will be named as google-map. From this step, your application is bootstrapped with Create React App. For more information, click the link. Then open that project in your IDE. I am using VS Code IDE. If you open the react application then you need to remove the unwanted files. Therefore you need to go to the src folder and delete Logo.svg, App.css, index.css, and App.test.js files. And create the following folders inside the src folder named components, assets and helpers then move your serviceWorker.js into the helper’s folder and App.js file into the Components folder. Then open the index.js file and delete the following snippet in index.js file. import ‘./index.css’; Then modify the App.js and serviceWorker.js files paths in index.js import like following. import App from ‘./components/App’;import * as serviceWorker from ‘./helpers/serviceWorker’; Go to the Components folder and open the App.js. Delete the return part of the App function. You need to install a dependency to get the google map as a component. For that, use the following command to install the dependency. npm install --save google-maps-react Create a new file inside your Component app and name it as Map.js. Then you need to import google-maps-rect. For that, add the following snippet in the Map.js. import { Map, GoogleApiWrapper } from 'google-maps-react'; Now you need to render the Map component. Therefore add the Map Component to your render function. In the above code, I added ordinary styling. I did as a constant variable inside the render method. const mapStyles = { width: '100%', height: '100%',}; you need to add your export default statement in the Maps.js file like below the snippet export default GoogleApiWrapper({ apiKey: 'TOKEN HERE'})(MapContainer); Make sure to enter your API key here! Import the Maps component inside the App.js file. So your App.js should be like below. When you start your development server by using npm startthen you could see the below result. Boom! you did it but what is the point of using google map. But legitimately, what is the meaning of using google map without any marker. Therefore, let’s add a marker. For that, update your Map component to include the Marker component. Here I used a different latitude and longitude, you could use whatever the latitude and longitude that you need. import { Map, GoogleApiWrapper, Marker } from 'google-maps-react'; Great! you added the marker on the map. Now you are in the most interesting part of this article. Now, let’s look after the custom styles. It is simply a JSON object. You’ll store the custom styles JSON in GoogleMapStyles.js file. The theme I used from Styling wizard: Google Map APIs. If you need more beautiful styles then try a style from Snazzy Maps or Build your own unique map style by customizing the JSON object. your GoogleMapStyles.js file will look like the following. Now you need to import this style JSON in your Maps component. import googleMapStyles from “./GoogelMapStyle”; After you import styles JSON, you can set the style JSON as a defaultProps of the Maps Component. This can be done by defining defaultProps on the component class itself, outside of the class body, as shown in the following code snippet: Maps.defaultProps = googleMapStyles; Then you need to pass this prop to the styles props of the Map component as shown in the following code snippet: <Map google={this.props.google} zoom={15} styles={this.props.mapStyle} initialCenter={{ lat: 9.761927, lng: 79.95244 }}/>; Now your Maps component will be like as shown in the below file. It is easy to implement google map in react. There are a lot of npm packages to help to implement the google map in React. For me,google-maps-react is easy to use and It is a small bundle size than others. You can clone the repo from this link. Happy Coding 😊 !!!
[ { "code": null, "e": 377, "s": 171, "text": "When my friend tried a new hairstyle I asked him “Why did you cut like this?” And he told that he wanted to shine as a model. Therefore, I understood that people like to show them uniquely and beautifully." }, { "code": null, "e": 754, "s": 377, "text": "When I developed a personal react application I wanted to implement google map API. I searched a lot of examples on google and finally, I found a simple solution. Here I will briefly explain how I used the application and what are the custom styles we could add to the google map. Here we will look from scratch. You could see the demo here. This is my 29th article in Medium." }, { "code": null, "e": 1077, "s": 754, "text": "If you don’t have Google maps API token signup Google maps API and get the token to use! To receive your token you must enter a credit card number. Yet Google says they won’t charge your account without you updating your service personally. Go ahead at your decision. Once you’ve got an API key, begin to develop your app!" }, { "code": null, "e": 1194, "s": 1077, "text": "To create a react application run the following command in your shell/terminal in a specific folder (e.g., desktop )" }, { "code": null, "e": 1226, "s": 1194, "text": "npx create-react-app google-map" }, { "code": null, "e": 1462, "s": 1226, "text": "A new folder will be created, and it will be named as google-map. From this step, your application is bootstrapped with Create React App. For more information, click the link. Then open that project in your IDE. I am using VS Code IDE." }, { "code": null, "e": 1919, "s": 1462, "text": "If you open the react application then you need to remove the unwanted files. Therefore you need to go to the src folder and delete Logo.svg, App.css, index.css, and App.test.js files. And create the following folders inside the src folder named components, assets and helpers then move your serviceWorker.js into the helper’s folder and App.js file into the Components folder. Then open the index.js file and delete the following snippet in index.js file." }, { "code": null, "e": 1941, "s": 1919, "text": "import ‘./index.css’;" }, { "code": null, "e": 2032, "s": 1941, "text": "Then modify the App.js and serviceWorker.js files paths in index.js import like following." }, { "code": null, "e": 2125, "s": 2032, "text": "import App from ‘./components/App’;import * as serviceWorker from ‘./helpers/serviceWorker’;" }, { "code": null, "e": 2218, "s": 2125, "text": "Go to the Components folder and open the App.js. Delete the return part of the App function." }, { "code": null, "e": 2352, "s": 2218, "text": "You need to install a dependency to get the google map as a component. For that, use the following command to install the dependency." }, { "code": null, "e": 2389, "s": 2352, "text": "npm install --save google-maps-react" }, { "code": null, "e": 2549, "s": 2389, "text": "Create a new file inside your Component app and name it as Map.js. Then you need to import google-maps-rect. For that, add the following snippet in the Map.js." }, { "code": null, "e": 2608, "s": 2549, "text": "import { Map, GoogleApiWrapper } from 'google-maps-react';" }, { "code": null, "e": 2707, "s": 2608, "text": "Now you need to render the Map component. Therefore add the Map Component to your render function." }, { "code": null, "e": 2807, "s": 2707, "text": "In the above code, I added ordinary styling. I did as a constant variable inside the render method." }, { "code": null, "e": 2862, "s": 2807, "text": "const mapStyles = { width: '100%', height: '100%',};" }, { "code": null, "e": 2951, "s": 2862, "text": "you need to add your export default statement in the Maps.js file like below the snippet" }, { "code": null, "e": 3024, "s": 2951, "text": "export default GoogleApiWrapper({ apiKey: 'TOKEN HERE'})(MapContainer);" }, { "code": null, "e": 3062, "s": 3024, "text": "Make sure to enter your API key here!" }, { "code": null, "e": 3149, "s": 3062, "text": "Import the Maps component inside the App.js file. So your App.js should be like below." }, { "code": null, "e": 3243, "s": 3149, "text": "When you start your development server by using npm startthen you could see the below result." }, { "code": null, "e": 3594, "s": 3243, "text": "Boom! you did it but what is the point of using google map. But legitimately, what is the meaning of using google map without any marker. Therefore, let’s add a marker. For that, update your Map component to include the Marker component. Here I used a different latitude and longitude, you could use whatever the latitude and longitude that you need." }, { "code": null, "e": 3661, "s": 3594, "text": "import { Map, GoogleApiWrapper, Marker } from 'google-maps-react';" }, { "code": null, "e": 3701, "s": 3661, "text": "Great! you added the marker on the map." }, { "code": null, "e": 4141, "s": 3701, "text": "Now you are in the most interesting part of this article. Now, let’s look after the custom styles. It is simply a JSON object. You’ll store the custom styles JSON in GoogleMapStyles.js file. The theme I used from Styling wizard: Google Map APIs. If you need more beautiful styles then try a style from Snazzy Maps or Build your own unique map style by customizing the JSON object. your GoogleMapStyles.js file will look like the following." }, { "code": null, "e": 4204, "s": 4141, "text": "Now you need to import this style JSON in your Maps component." }, { "code": null, "e": 4252, "s": 4204, "text": "import googleMapStyles from “./GoogelMapStyle”;" }, { "code": null, "e": 4490, "s": 4252, "text": "After you import styles JSON, you can set the style JSON as a defaultProps of the Maps Component. This can be done by defining defaultProps on the component class itself, outside of the class body, as shown in the following code snippet:" }, { "code": null, "e": 4527, "s": 4490, "text": "Maps.defaultProps = googleMapStyles;" }, { "code": null, "e": 4640, "s": 4527, "text": "Then you need to pass this prop to the styles props of the Map component as shown in the following code snippet:" }, { "code": null, "e": 4767, "s": 4640, "text": "<Map google={this.props.google} zoom={15} styles={this.props.mapStyle} initialCenter={{ lat: 9.761927, lng: 79.95244 }}/>;" }, { "code": null, "e": 4832, "s": 4767, "text": "Now your Maps component will be like as shown in the below file." }, { "code": null, "e": 5077, "s": 4832, "text": "It is easy to implement google map in react. There are a lot of npm packages to help to implement the google map in React. For me,google-maps-react is easy to use and It is a small bundle size than others. You can clone the repo from this link." } ]
Meta-Learning: Learning to Learn. Extensive innovation for machine... | by Wie Kiang H. | Towards Data Science
In order to successfully understand and study new concepts or views, people generally use one example in their commonplace. They learn new skills much quicker and in more productive ways than machines; action, imagination, and explanation. For instance, children who have seen butterflies and ants a few times can promptly recognize them. In the same way, teens who grasp how to handle a bike are likely to discover how to ride a motorcycle with a limited demonstration. However, hundreds of models to label and train are required by machine learning algorithms to deliver similar accuracy. In computer science, meta-learning is a member of machine learning, which can be defined as learning to learn. It is an automatic algorithm that applies to metadata to recognize how learning can become flexible in interpreting difficulties, thus enhancing the performance of an existent algorithm or learning the algorithm itself (Thrun & Pratt, 19981; Andrychowicz et al., 20162) This research studies the use of evolutionary algorithms and neural networks in terms of meta-learning process. Begin with an explanation of the evolutionary algorithm process to avoid overfitting, followed by the concept of neural networks. Finally, a conclusion of the relationship between evolutionary algorithms and neural networks due to the meta-learning technique. Meta-learning algorithms generally make Artificial Intelligence (AI) systems learn effectively, adapt to shifts in their conditions in a more robust way, and generalize to more tasks. They can be used to optimize a model’s architecture, parameters, and some combination of them. This research focuses on a particular meta-learning technique called neuro-evolution, as well it is called an evolutionary algorithm to learn neural architectures. Charles Darwin, an evolutionary biologist, visited the Galapagos Islands decades ago and noticed that some birds appeared to have evolved from a single genetic flock. They shared standard features characterized by their distinct beak figures, which sprung from their unique DNA (Steinheimer, 20043), as represented in Figure 1. Steinheimer (2004) asserts that DNA is a blueprint that controls the replication of cells. The hypothesis was the withdrawal of each species into a popular theory of natural selection. This process is algorithmic and can be simulated by creating evolutionary algorithms. Additionally, the evolutionary algorithms are mutating some members randomly to attempt to find even more qualified applicants. This process repeats countless iterations as necessary. Actually, in this context, they can be represented as generations. These steps are all stimulated by the Darwin theory of natural selection. They are all a part of the broader class of algorithms called evolutionary computation. Currently, neural networks can perform tasks that are likely challenging for humans if they present large amounts of training data. The optimal architectures for these networks are non-trivial and take a lot of trial and error. In fact, researchers worked hard on improving architectures that are progressively delivered to newer levels over the years. Researchers discovered that neuro-evolution approaches are being used by a famous tech company, Uber, who started adopting Evolution Strategies (ES) to help enhance the performance of their services by concatenating with the Atari games. “even a very basic decades-old evolution strategy provides comparable results; thus, more modern evolution strategies should be considered as a potentially competitive approach to modern deep Reinforcement Learning (RL) algorithms” (Such et al., 20174; Chrabaszcz, Loshchilov & Hutter, 20185). In Figure 2, Uber AI Labs conducted a test with several Atari games. This line chart depicts the comparison between standard evolution strategies with an enhanced exploration of the algorithms. It seems that various tweaking in the hyperparameters gives significant rewards value. The number of reward amounts rises significantly, from 0 to further than 30. In the first 200 generation numbers, rewards value in both strategies is racing up to 5, and keeping steadily to more than 300 generation numbers. It then dramatically grows from 320 generation numbers until the maximum 800 generation numbers. In contemporary work, appearances in deep learning patterns have been associated mainly with the number and diversity of data collected. Practically speaking, data augmentation recognizes a significantly enhanced uniqueness of available data to train the models, except, discovering the most current data existence. Data augmentation has several routines, which are cropping, padding, and horizontal flipping (Figure 3). These techniques are frequently applied to train deep neural networks (Shorten & Khoshgoftaar, 20196). Indeed, most of the neural networks’ training time strategy is using the basic types of data augmentation. “the best classification accuracy obtained by our models is not in the top 10 approaches using the CIFAR-10 dataset. This makes the proposed architecture ideal for embedded systems unlike the best performing approaches” (Çalik & Demirci, 20187) Despite this, the Canadian Institute for Advanced Research (CIFAR-10) successfully applied the image classification problems with Convolutional Neural Networks (CNN). Furthermore, Cubuk, Zoph, Mane, Vasudevan, and Le (2019)8 explain that the most recent accuracy on datasets, such as CIFAR-10 with AutoAugment is an innovative automated data augmentation method. Li, Zhou, Chen, and Li (2017)9 study that research in meta-learning has commonly concentrated on data and model designs, with exemptions such as meta-learning optimizers, Stochastic Gradient Descent (SGD) for instance, which appears to still fall under the model optimization. Data augmentation is the most easily recognized in the context of image data. These image augmentations typically involve horizontal flips and small magnitudes of rotations or translations. There is a combined interaction in two intertwined processes, inter-life learning, and intra-life learning. Think of inter-life learning as a process of evolution through natural selection. In contrast, intra-life learning relates to how an animal learns throughout its existence, for example, identifying an object, learning to communicate, and walking. Furthermore, evolutionary algorithms can be reflected as inter-life learning, whereas neural networks can be thought of as intra-life learning. Evolutionary algorithms and neural networks are likely the main factor to accomplish an optimized algorithm in deep reinforcement learning techniques. Bingham, Macke, and Miikkulainen (2020)10 emphasize there are four main features associated with evolutionary algorithms, which are, numbers of network layers, numbers of neurons in each layer, activation function, and optimization algorithm. These start with the initialization of multiple neural networks with random weights to generate a population. Next is to train the weights of each network using an image dataset, then benchmark how strongly it performs at classifying test data. Moreover, another feature is applying the classification precision on the test set and implementing the fitness function to decide the top-scoring networks to be a member of the next generation. On the other hand, evolutionary algorithms filter out the lowest-performing networks and eliminate them. Finally, they feature selecting a few of the lower-scoring networks, which might be conceivably valuable in a local maximum when optimizing the networks. These techniques are an evolutionary way of preventing overfitting. Neural Networks are an attempt to simulate the information processing abilities of the biological nervous scheme, reflected in Figure 4. The human body consists of trillions of cell bodies, and the nervous system cells called nucleus are trained to transfer messages or information through an electrochemical means. In simple terms, neural networks are a collection of connected input and output units, in which each connection has an associated weight (Figure 5). Neural networks generate a new network by blending a random collection of parameters from their parent networks. An instance could have an equal number of layers as one origin, and the rest of its parameters are from a different parent. This process reflects how biology works in real life and helps algorithms converge on an optimized network. As the parameter complexity of the network rises, evolutionary algorithms produce exponential speedups. Krizhevsky, Sutskever, and Hinton (2017)11 mentioned that this process requires stacks of data and computing power and uses hundreds of GPUs and TPUs for days. It is initialized as 1000 identical convolutional neural networks with no hidden layers. Then through the evolutionary process, networks with higher accuracies are elected as parents, copied and mutated to generate children, while the rest are eliminated. In later practice, neural networks utilized a fixed stack of repeated modules called cells. The number of cells stayed the same, but the architecture of each cell mutated over time. They also decided to use a specific form of regularisation to improve network accuracy. Instead of eliminating the lowest-scoring networks, they exclude the oldest ones regardless of how well they scored, and it ended up enhancing the accuracy, and training from scratch. This technique elects for neural networks that remain accurate when they are retrained along with the evolution algorithms. Meta-learning is the process of learning to learn. Moreover, Artificial Intelligence (AI) optimizes one or numerous other AIs. This research has concluded that evolutionary algorithms use notions from the evolutionary means and mimic the Charles Darwin hypothesis, for instance, mutation and natural selection, to interpret complicated puzzles. In contrast, a meta-learning technique called neuro-evolution might utilize evolutionary algorithms to optimize neural networks individually. Although meta-learning is currently extremely fashionable, utilizing these algorithms on real-life problems remains particularly challenging. However, with the continually advancing computational power, dedicated machine learning hardware, and advancements in meta-learning algorithms, these will likely become more reliable and trustworthy. References#1 Learning to Learn#2 Learning to learn by gradient descent by gradient descent#3 Charles Darwin’s bird collection and ornithological knowledge during the voyage of H.M.S. “Beagle”, 1831–1836#4 Deep Neuroevolution: Genetic Algorithms Are a Competitive Alternative for Training Deep Neural Networks for Reinforcement Learning#5 Back to Basics: Benchmarking Canonical Evolution Strategies for Playing Atari#6 A survey on Image Data Augmentation for Deep Learning#7 Cifar-10 Image Classification with Convolutional Neural Networks for Embedded Systems#8 AutoAugment: Learning Augmentation Strategies From Data#9 Meta-SGD: Learning to Learn Quickly for Few-Shot Learning#10 Evolutionary Optimization of Deep Learning Activation Functions#11 ImageNet classification with deep convolutional neural networks
[ { "code": null, "e": 296, "s": 172, "text": "In order to successfully understand and study new concepts or views, people generally use one example in their commonplace." }, { "code": null, "e": 412, "s": 296, "text": "They learn new skills much quicker and in more productive ways than machines; action, imagination, and explanation." }, { "code": null, "e": 763, "s": 412, "text": "For instance, children who have seen butterflies and ants a few times can promptly recognize them. In the same way, teens who grasp how to handle a bike are likely to discover how to ride a motorcycle with a limited demonstration. However, hundreds of models to label and train are required by machine learning algorithms to deliver similar accuracy." }, { "code": null, "e": 1144, "s": 763, "text": "In computer science, meta-learning is a member of machine learning, which can be defined as learning to learn. It is an automatic algorithm that applies to metadata to recognize how learning can become flexible in interpreting difficulties, thus enhancing the performance of an existent algorithm or learning the algorithm itself (Thrun & Pratt, 19981; Andrychowicz et al., 20162)" }, { "code": null, "e": 1516, "s": 1144, "text": "This research studies the use of evolutionary algorithms and neural networks in terms of meta-learning process. Begin with an explanation of the evolutionary algorithm process to avoid overfitting, followed by the concept of neural networks. Finally, a conclusion of the relationship between evolutionary algorithms and neural networks due to the meta-learning technique." }, { "code": null, "e": 1959, "s": 1516, "text": "Meta-learning algorithms generally make Artificial Intelligence (AI) systems learn effectively, adapt to shifts in their conditions in a more robust way, and generalize to more tasks. They can be used to optimize a model’s architecture, parameters, and some combination of them. This research focuses on a particular meta-learning technique called neuro-evolution, as well it is called an evolutionary algorithm to learn neural architectures." }, { "code": null, "e": 2287, "s": 1959, "text": "Charles Darwin, an evolutionary biologist, visited the Galapagos Islands decades ago and noticed that some birds appeared to have evolved from a single genetic flock. They shared standard features characterized by their distinct beak figures, which sprung from their unique DNA (Steinheimer, 20043), as represented in Figure 1." }, { "code": null, "e": 2558, "s": 2287, "text": "Steinheimer (2004) asserts that DNA is a blueprint that controls the replication of cells. The hypothesis was the withdrawal of each species into a popular theory of natural selection. This process is algorithmic and can be simulated by creating evolutionary algorithms." }, { "code": null, "e": 2971, "s": 2558, "text": "Additionally, the evolutionary algorithms are mutating some members randomly to attempt to find even more qualified applicants. This process repeats countless iterations as necessary. Actually, in this context, they can be represented as generations. These steps are all stimulated by the Darwin theory of natural selection. They are all a part of the broader class of algorithms called evolutionary computation." }, { "code": null, "e": 3324, "s": 2971, "text": "Currently, neural networks can perform tasks that are likely challenging for humans if they present large amounts of training data. The optimal architectures for these networks are non-trivial and take a lot of trial and error. In fact, researchers worked hard on improving architectures that are progressively delivered to newer levels over the years." }, { "code": null, "e": 3562, "s": 3324, "text": "Researchers discovered that neuro-evolution approaches are being used by a famous tech company, Uber, who started adopting Evolution Strategies (ES) to help enhance the performance of their services by concatenating with the Atari games." }, { "code": null, "e": 3856, "s": 3562, "text": "“even a very basic decades-old evolution strategy provides comparable results; thus, more modern evolution strategies should be considered as a potentially competitive approach to modern deep Reinforcement Learning (RL) algorithms” (Such et al., 20174; Chrabaszcz, Loshchilov & Hutter, 20185)." }, { "code": null, "e": 4214, "s": 3856, "text": "In Figure 2, Uber AI Labs conducted a test with several Atari games. This line chart depicts the comparison between standard evolution strategies with an enhanced exploration of the algorithms. It seems that various tweaking in the hyperparameters gives significant rewards value. The number of reward amounts rises significantly, from 0 to further than 30." }, { "code": null, "e": 4458, "s": 4214, "text": "In the first 200 generation numbers, rewards value in both strategies is racing up to 5, and keeping steadily to more than 300 generation numbers. It then dramatically grows from 320 generation numbers until the maximum 800 generation numbers." }, { "code": null, "e": 4879, "s": 4458, "text": "In contemporary work, appearances in deep learning patterns have been associated mainly with the number and diversity of data collected. Practically speaking, data augmentation recognizes a significantly enhanced uniqueness of available data to train the models, except, discovering the most current data existence. Data augmentation has several routines, which are cropping, padding, and horizontal flipping (Figure 3)." }, { "code": null, "e": 5089, "s": 4879, "text": "These techniques are frequently applied to train deep neural networks (Shorten & Khoshgoftaar, 20196). Indeed, most of the neural networks’ training time strategy is using the basic types of data augmentation." }, { "code": null, "e": 5335, "s": 5089, "text": "“the best classification accuracy obtained by our models is not in the top 10 approaches using the CIFAR-10 dataset. This makes the proposed architecture ideal for embedded systems unlike the best performing approaches” (Çalik & Demirci, 20187)" }, { "code": null, "e": 5698, "s": 5335, "text": "Despite this, the Canadian Institute for Advanced Research (CIFAR-10) successfully applied the image classification problems with Convolutional Neural Networks (CNN). Furthermore, Cubuk, Zoph, Mane, Vasudevan, and Le (2019)8 explain that the most recent accuracy on datasets, such as CIFAR-10 with AutoAugment is an innovative automated data augmentation method." }, { "code": null, "e": 6165, "s": 5698, "text": "Li, Zhou, Chen, and Li (2017)9 study that research in meta-learning has commonly concentrated on data and model designs, with exemptions such as meta-learning optimizers, Stochastic Gradient Descent (SGD) for instance, which appears to still fall under the model optimization. Data augmentation is the most easily recognized in the context of image data. These image augmentations typically involve horizontal flips and small magnitudes of rotations or translations." }, { "code": null, "e": 6520, "s": 6165, "text": "There is a combined interaction in two intertwined processes, inter-life learning, and intra-life learning. Think of inter-life learning as a process of evolution through natural selection. In contrast, intra-life learning relates to how an animal learns throughout its existence, for example, identifying an object, learning to communicate, and walking." }, { "code": null, "e": 6815, "s": 6520, "text": "Furthermore, evolutionary algorithms can be reflected as inter-life learning, whereas neural networks can be thought of as intra-life learning. Evolutionary algorithms and neural networks are likely the main factor to accomplish an optimized algorithm in deep reinforcement learning techniques." }, { "code": null, "e": 7058, "s": 6815, "text": "Bingham, Macke, and Miikkulainen (2020)10 emphasize there are four main features associated with evolutionary algorithms, which are, numbers of network layers, numbers of neurons in each layer, activation function, and optimization algorithm." }, { "code": null, "e": 7498, "s": 7058, "text": "These start with the initialization of multiple neural networks with random weights to generate a population. Next is to train the weights of each network using an image dataset, then benchmark how strongly it performs at classifying test data. Moreover, another feature is applying the classification precision on the test set and implementing the fitness function to decide the top-scoring networks to be a member of the next generation." }, { "code": null, "e": 7825, "s": 7498, "text": "On the other hand, evolutionary algorithms filter out the lowest-performing networks and eliminate them. Finally, they feature selecting a few of the lower-scoring networks, which might be conceivably valuable in a local maximum when optimizing the networks. These techniques are an evolutionary way of preventing overfitting." }, { "code": null, "e": 8141, "s": 7825, "text": "Neural Networks are an attempt to simulate the information processing abilities of the biological nervous scheme, reflected in Figure 4. The human body consists of trillions of cell bodies, and the nervous system cells called nucleus are trained to transfer messages or information through an electrochemical means." }, { "code": null, "e": 8635, "s": 8141, "text": "In simple terms, neural networks are a collection of connected input and output units, in which each connection has an associated weight (Figure 5). Neural networks generate a new network by blending a random collection of parameters from their parent networks. An instance could have an equal number of layers as one origin, and the rest of its parameters are from a different parent. This process reflects how biology works in real life and helps algorithms converge on an optimized network." }, { "code": null, "e": 9155, "s": 8635, "text": "As the parameter complexity of the network rises, evolutionary algorithms produce exponential speedups. Krizhevsky, Sutskever, and Hinton (2017)11 mentioned that this process requires stacks of data and computing power and uses hundreds of GPUs and TPUs for days. It is initialized as 1000 identical convolutional neural networks with no hidden layers. Then through the evolutionary process, networks with higher accuracies are elected as parents, copied and mutated to generate children, while the rest are eliminated." }, { "code": null, "e": 9425, "s": 9155, "text": "In later practice, neural networks utilized a fixed stack of repeated modules called cells. The number of cells stayed the same, but the architecture of each cell mutated over time. They also decided to use a specific form of regularisation to improve network accuracy." }, { "code": null, "e": 9733, "s": 9425, "text": "Instead of eliminating the lowest-scoring networks, they exclude the oldest ones regardless of how well they scored, and it ended up enhancing the accuracy, and training from scratch. This technique elects for neural networks that remain accurate when they are retrained along with the evolution algorithms." }, { "code": null, "e": 9860, "s": 9733, "text": "Meta-learning is the process of learning to learn. Moreover, Artificial Intelligence (AI) optimizes one or numerous other AIs." }, { "code": null, "e": 10078, "s": 9860, "text": "This research has concluded that evolutionary algorithms use notions from the evolutionary means and mimic the Charles Darwin hypothesis, for instance, mutation and natural selection, to interpret complicated puzzles." }, { "code": null, "e": 10362, "s": 10078, "text": "In contrast, a meta-learning technique called neuro-evolution might utilize evolutionary algorithms to optimize neural networks individually. Although meta-learning is currently extremely fashionable, utilizing these algorithms on real-life problems remains particularly challenging." }, { "code": null, "e": 10562, "s": 10362, "text": "However, with the continually advancing computational power, dedicated machine learning hardware, and advancements in meta-learning algorithms, these will likely become more reliable and trustworthy." } ]
Bootstrap - Input Groups
This chapter explains about one more feature Bootstrap supports, the Input Groups. Input groups are extended Form Controls. Using input groups you can easily prepend and append text or buttons to the text-based inputs. By adding prepended and appended content to an input field, you can add common elements to the user’s input. For example, you can add the dollar symbol, the @ for a Twitter username, or anything else that might be common for your application interface. To prepend or append elements to a .form-control− Wrap it in a <div> with class .input-group Wrap it in a <div> with class .input-group As a next step, within that same <div> , place your extra content inside a <span> with class .input-group-addon. As a next step, within that same <div> , place your extra content inside a <span> with class .input-group-addon. Now place this <span> either before or after the <input> element. Now place this <span> either before or after the <input> element. The following example demonstrates basic input group − <div style = "padding: 100px 100px 10px;"> <form class = "bs-example bs-example-form" role = "form"> <div class = "input-group"> <span class = "input-group-addon">@</span> <input type = "text" class = "form-control" placeholder = "twitterhandle"> </div> <br> <div class = "input-group"> <input type = "text" class = "form-control"> <span class = "input-group-addon">.00</span> </div> <br> <div class = "input-group"> <span class = "input-group-addon">$</span> <input type = "text" class =" form-control"> <span class = "input-group-addon">.00</span> </div> </form> </div> You can change the size of the input groups, by adding the relative form sizing classes like .input-group-lg, input-group-sm, input-group-xs to the .input-group itself. The contents within will automatically resize. Following examples demonstrates this − <div style = "padding: 100px 100px 10px;"> <form class = "bs-example bs-example-form" role = "form"> <div class = "input-group input-group-lg"> <span class = "input-group-addon">@</span> <input type = "text" class = "form-control" placeholder = "Twitterhandle"> </div> <br> <div class = "input-group"> <span class = "input-group-addon">@</span> <input type = "text" class = "form-control" placeholder = "Twitterhandle"> </div> <br> <div class = "input-group input-group-sm"> <span class = "input-group-addon">@</span> <input type = "text" class = "form-control" placeholder = "Twitterhandle"> </div> </form> </div> You can preappend or append radio buttons and checkboxes instead of text as demonstrated in the following example − <div style = "padding: 100px 100px 10px;"> <form class = "bs-example bs-example-form" role = "form"> <div class = "row"> <div class = "col-lg-6"> <div class = "input-group"> <span class = "input-group-addon"> <input type = "checkbox"> </span> <input type = "text" class = "form-control"> </div><!-- /input-group --> </div><!-- /.col-lg-6 --><br> <div class = "col-lg-6"> <div class = "input-group"> <span class = "input-group-addon"> <input type = "radio"> </span> <input type = "text" class = "form-control"> </div><!-- /input-group --> </div><!-- /.col-lg-6 --> </div><!-- /.row --> </form> </div> You can even preappend or append buttons in input groups. Instead of .input-group-addon class, you'll need to use class .input-group-btn to wrap the buttons. This is required due to the default browser styles that cannot be overridden. Following examples demonstrates this − <div style = "padding: 100px 100px 10px;"> <form class = "bs-example bs-example-form" role = "form"> <div class = "row"> <div class = "col-lg-6"> <div class = "input-group"> <span class = "input-group-btn"> <button class = "btn btn-default" type = "button"> Go! </button> </span> <input type = "text" class = "form-control"> </div><!-- /input-group --> </div><!-- /.col-lg-6 --><br> <div class = "col-lg-6"> <div class = "input-group"> <input type = "text" class = "form-control"> <span class = "input-group-btn"> <button class = "btn btn-default" type = "button"> Go! </button> </span> </div><!-- /input-group --> </div><!-- /.col-lg-6 --> </div><!-- /.row --> </form> </div> Adding buttons with dropdown menus in input groups can be done by simply wrapping the button and dropdown menu in a .input-group-btn class as demonstrated in the following example − <div style = "padding: 100px 100px 10px;"> <form class = "bs-example bs-example-form" role = "form"> <div class = "row"> <div class = "col-lg-6"> <div class = "input-group"> <div class = "input-group-btn"> <button type = "button" class = "btn btn-default dropdown-toggle" data-toggle = "dropdown"> DropdownMenu <span class = "caret"></span> </button> <ul class = "dropdown-menu"> <li><a href = "#">Action</a></li> <li><a href = "#">Another action</a></li> <li><a href = "#">Something else here</a></li> <li class = "divider"></li> <li><a href = "#">Separated link</a></li> </ul> </div><!-- /btn-group --> <input type = "text" class = "form-control"> </div><!-- /input-group --> </div><!-- /.col-lg-6 --><br> <div class = "col-lg-6"> <div class = "input-group"> <input type = "text" class = "form-control"> <div class = "input-group-btn"> <button type = "button" class = "btn btn-default dropdown-toggle" data-toggle = "dropdown"> DropdownMenu <span class = "caret"></span> </button> <ul class = "dropdown-menu pull-right"> <li><a href = "#">Action</a></li> <li><a href = "#">Another action</a></li> <li><a href = "#">Something else here</a></li> <li class = "divider"></li> <li><a href = "#">Separated link</a></li> </ul> </div><!-- /btn-group --> </div><!-- /input-group --> </div><!-- /.col-lg-6 --> </div><!-- /.row --> </form> </div> Action Another action Something else here Separated link Action Another action Something else here Separated link To segment button dropdowns in input groups, use the same general style as the dropdown button, but add a primary action along with the dropdown as can be seen in the following example − <div style = "padding: 100px 100px 10px;"> <form class = "bs-example bs-example-form" role = "form"> <div class = "row"> <div class = "col-lg-6"> <div class = "input-group"> <div class = "input-group-btn"> <button type = "button" class = "btn btn-default" tabindex = "-1">Dropdown Menu</button> <button type = "button" class = "btn btn-default dropdown-toggle" data-toggle = "dropdown" tabindex = "-1"> <span class = "caret"></span> <span class = "sr-only">Toggle Dropdown</span> </button> <ul class = "dropdown-menu"> <li><a href = "#">Action</a></li> <li><a href ="#">Another action</a></li> <li><a href = "#">Something else here</a></li> <li class = "divider"></li> <li><a href = "#">Separated link</a></li> </ul> </div><!-- /btn-group --> <input type = "text" class = "form-control"> </div><!-- /input-group --> </div><!-- /.col-lg-6 --><br> <div class = "col-lg-6"> <div class = "input-group"> <input type = "text" class = "form-control"> <div class = "input-group-btn"> <button type = "button" class = "btn btn-default" tabindex = "-1"> Dropdown Menu </button> <button type = "button" class = "btn btn-default dropdown-toggle" data-toggle = "dropdown" tabindex = "-1"> <span class = "caret"></span> <span class = "sr-only">Toggle Dropdown</span> </button> <ul class = "dropdown-menu pull-right"> <li><a href = "#">Action</a></li> <li><a href = "#">Another action</a></li> <li><a href = "#">Something else here</a></li> <li class = "divider"></li> <li><a href = "#">Separated link</a></li> </ul> </div><!-- /btn-group --> </div><!-- /input-group --> </div><!-- /.col-lg-6 --> </div><!-- /.row --> </form> </div> Action Another action Something else here Separated link Action Another action Something else here Separated link 26 Lectures 2 hours Anadi Sharma 54 Lectures 4.5 hours Frahaan Hussain 161 Lectures 14.5 hours Eduonix Learning Solutions 20 Lectures 4 hours Azaz Patel 15 Lectures 1.5 hours Muhammad Ismail 62 Lectures 8 hours Yossef Ayman Zedan Print Add Notes Bookmark this page
[ { "code": null, "e": 3551, "s": 3331, "text": "This chapter explains about one more feature Bootstrap supports, the Input Groups. Input groups are extended Form Controls. Using input groups you can easily prepend and append text or buttons to the text-based inputs." }, { "code": null, "e": 3804, "s": 3551, "text": "By adding prepended and appended content to an input field, you can add common elements to the user’s input. For example, you can add the dollar symbol, the @ for a Twitter username, or anything else that might be common for your application interface." }, { "code": null, "e": 3854, "s": 3804, "text": "To prepend or append elements to a .form-control−" }, { "code": null, "e": 3897, "s": 3854, "text": "Wrap it in a <div> with class .input-group" }, { "code": null, "e": 3940, "s": 3897, "text": "Wrap it in a <div> with class .input-group" }, { "code": null, "e": 4053, "s": 3940, "text": "As a next step, within that same <div> , place your extra content inside a <span> with class .input-group-addon." }, { "code": null, "e": 4166, "s": 4053, "text": "As a next step, within that same <div> , place your extra content inside a <span> with class .input-group-addon." }, { "code": null, "e": 4232, "s": 4166, "text": "Now place this <span> either before or after the <input> element." }, { "code": null, "e": 4298, "s": 4232, "text": "Now place this <span> either before or after the <input> element." }, { "code": null, "e": 4353, "s": 4298, "text": "The following example demonstrates basic input group −" }, { "code": null, "e": 5064, "s": 4353, "text": "<div style = \"padding: 100px 100px 10px;\">\n \n <form class = \"bs-example bs-example-form\" role = \"form\">\n <div class = \"input-group\">\n <span class = \"input-group-addon\">@</span>\n <input type = \"text\" class = \"form-control\" placeholder = \"twitterhandle\">\n </div>\n\t\t\n <br>\n\n <div class = \"input-group\">\n <input type = \"text\" class = \"form-control\">\n <span class = \"input-group-addon\">.00</span>\n </div>\n\t\t\n <br>\n \n <div class = \"input-group\">\n <span class = \"input-group-addon\">$</span>\n <input type = \"text\" class =\" form-control\">\n <span class = \"input-group-addon\">.00</span>\n </div>\n </form>\n \n</div>" }, { "code": null, "e": 5280, "s": 5064, "text": "You can change the size of the input groups, by adding the relative form sizing classes like .input-group-lg, input-group-sm, input-group-xs to the .input-group itself. The contents within will automatically resize." }, { "code": null, "e": 5319, "s": 5280, "text": "Following examples demonstrates this −" }, { "code": null, "e": 6058, "s": 5319, "text": "<div style = \"padding: 100px 100px 10px;\">\n \n <form class = \"bs-example bs-example-form\" role = \"form\">\n <div class = \"input-group input-group-lg\">\n <span class = \"input-group-addon\">@</span>\n <input type = \"text\" class = \"form-control\" placeholder = \"Twitterhandle\">\n </div>\n\t\t\n <br>\n\n <div class = \"input-group\">\n <span class = \"input-group-addon\">@</span>\n <input type = \"text\" class = \"form-control\" placeholder = \"Twitterhandle\">\n </div>\n\t\t\n <br>\n\n <div class = \"input-group input-group-sm\">\n <span class = \"input-group-addon\">@</span>\n <input type = \"text\" class = \"form-control\" placeholder = \"Twitterhandle\">\n </div>\n </form>\n \n</div>" }, { "code": null, "e": 6174, "s": 6058, "text": "You can preappend or append radio buttons and checkboxes instead of text as demonstrated in the following example −" }, { "code": null, "e": 7104, "s": 6174, "text": "<div style = \"padding: 100px 100px 10px;\">\n \n <form class = \"bs-example bs-example-form\" role = \"form\">\n <div class = \"row\">\n \n <div class = \"col-lg-6\">\n <div class = \"input-group\">\n \n <span class = \"input-group-addon\">\n <input type = \"checkbox\">\n </span>\n \n <input type = \"text\" class = \"form-control\">\n </div><!-- /input-group -->\n </div><!-- /.col-lg-6 --><br>\n \n <div class = \"col-lg-6\">\n <div class = \"input-group\">\n \n <span class = \"input-group-addon\">\n <input type = \"radio\">\n </span>\n \n <input type = \"text\" class = \"form-control\">\n </div><!-- /input-group -->\n </div><!-- /.col-lg-6 -->\n \n </div><!-- /.row -->\n </form>\n \n</div>" }, { "code": null, "e": 7379, "s": 7104, "text": "You can even preappend or append buttons in input groups. Instead of .input-group-addon class, you'll need to use class .input-group-btn to wrap the buttons. This is required due to the default browser styles that cannot be overridden. Following examples demonstrates this −" }, { "code": null, "e": 8470, "s": 7379, "text": "<div style = \"padding: 100px 100px 10px;\">\n \n <form class = \"bs-example bs-example-form\" role = \"form\">\n <div class = \"row\">\n \n <div class = \"col-lg-6\">\n <div class = \"input-group\">\n \n <span class = \"input-group-btn\">\n <button class = \"btn btn-default\" type = \"button\">\n Go!\n </button>\n </span>\n\t\t\t\t\t\n <input type = \"text\" class = \"form-control\">\n \n </div><!-- /input-group -->\n </div><!-- /.col-lg-6 --><br>\n \n <div class = \"col-lg-6\">\n <div class = \"input-group\">\n <input type = \"text\" class = \"form-control\">\n \n <span class = \"input-group-btn\">\n <button class = \"btn btn-default\" type = \"button\">\n Go!\n </button>\n </span>\n \n </div><!-- /input-group -->\n </div><!-- /.col-lg-6 -->\n \n </div><!-- /.row -->\n </form>\n \n</div>" }, { "code": null, "e": 8652, "s": 8470, "text": "Adding buttons with dropdown menus in input groups can be done by simply wrapping the button and dropdown menu in a .input-group-btn class as demonstrated in the following example −" }, { "code": null, "e": 10869, "s": 8652, "text": "<div style = \"padding: 100px 100px 10px;\">\n \n <form class = \"bs-example bs-example-form\" role = \"form\">\n <div class = \"row\">\n \n <div class = \"col-lg-6\">\n <div class = \"input-group\">\n \n <div class = \"input-group-btn\">\n <button type = \"button\" class = \"btn btn-default dropdown-toggle\" \n data-toggle = \"dropdown\">\n DropdownMenu \n <span class = \"caret\"></span>\n </button>\n \n <ul class = \"dropdown-menu\">\n <li><a href = \"#\">Action</a></li>\n <li><a href = \"#\">Another action</a></li>\n <li><a href = \"#\">Something else here</a></li>\n \n <li class = \"divider\"></li>\n <li><a href = \"#\">Separated link</a></li>\n </ul>\n </div><!-- /btn-group -->\n \n <input type = \"text\" class = \"form-control\">\n </div><!-- /input-group -->\n </div><!-- /.col-lg-6 --><br>\n \n <div class = \"col-lg-6\">\n <div class = \"input-group\">\n \n <input type = \"text\" class = \"form-control\">\n <div class = \"input-group-btn\">\n \n <button type = \"button\" class = \"btn btn-default dropdown-toggle\" \n data-toggle = \"dropdown\">\n DropdownMenu \n <span class = \"caret\"></span>\n </button>\n \n <ul class = \"dropdown-menu pull-right\">\n <li><a href = \"#\">Action</a></li>\n <li><a href = \"#\">Another action</a></li>\n <li><a href = \"#\">Something else here</a></li>\n \n <li class = \"divider\"></li>\n <li><a href = \"#\">Separated link</a></li>\n </ul>\n </div><!-- /btn-group -->\n \n </div><!-- /input-group -->\n </div><!-- /.col-lg-6 -->\n \n </div><!-- /.row -->\n </form>\n \n</div>" }, { "code": null, "e": 10876, "s": 10869, "text": "Action" }, { "code": null, "e": 10891, "s": 10876, "text": "Another action" }, { "code": null, "e": 10911, "s": 10891, "text": "Something else here" }, { "code": null, "e": 10926, "s": 10911, "text": "Separated link" }, { "code": null, "e": 10933, "s": 10926, "text": "Action" }, { "code": null, "e": 10948, "s": 10933, "text": "Another action" }, { "code": null, "e": 10968, "s": 10948, "text": "Something else here" }, { "code": null, "e": 10983, "s": 10968, "text": "Separated link" }, { "code": null, "e": 11170, "s": 10983, "text": "To segment button dropdowns in input groups, use the same general style as the dropdown button, but add a primary action along with the dropdown as can be seen in the following example −" }, { "code": null, "e": 13824, "s": 11170, "text": "<div style = \"padding: 100px 100px 10px;\">\n \n <form class = \"bs-example bs-example-form\" role = \"form\">\n <div class = \"row\">\n \n <div class = \"col-lg-6\">\n <div class = \"input-group\">\n \n <div class = \"input-group-btn\">\n <button type = \"button\" class = \"btn btn-default\" \n tabindex = \"-1\">Dropdown Menu</button>\n \n <button type = \"button\" class = \"btn btn-default dropdown-toggle\" \n data-toggle = \"dropdown\" tabindex = \"-1\">\n <span class = \"caret\"></span>\n <span class = \"sr-only\">Toggle Dropdown</span>\n </button>\n \n <ul class = \"dropdown-menu\">\n <li><a href = \"#\">Action</a></li>\n <li><a href =\"#\">Another action</a></li>\n <li><a href = \"#\">Something else here</a></li>\n \n <li class = \"divider\"></li>\n <li><a href = \"#\">Separated link</a></li>\n </ul>\n \n </div><!-- /btn-group -->\n <input type = \"text\" class = \"form-control\">\n \n </div><!-- /input-group -->\n </div><!-- /.col-lg-6 --><br>\n \n <div class = \"col-lg-6\">\n <div class = \"input-group\">\n <input type = \"text\" class = \"form-control\">\n <div class = \"input-group-btn\">\n \n <button type = \"button\" class = \"btn btn-default\" tabindex = \"-1\">\n Dropdown Menu\n </button>\n \n <button type = \"button\" class = \"btn btn-default dropdown-toggle\" \n data-toggle = \"dropdown\" tabindex = \"-1\">\n \n <span class = \"caret\"></span>\n <span class = \"sr-only\">Toggle Dropdown</span>\n </button>\n \n <ul class = \"dropdown-menu pull-right\">\n <li><a href = \"#\">Action</a></li>\n <li><a href = \"#\">Another action</a></li>\n <li><a href = \"#\">Something else here</a></li>\n \n <li class = \"divider\"></li>\n <li><a href = \"#\">Separated link</a></li>\n </ul>\n \n </div><!-- /btn-group -->\n </div><!-- /input-group -->\n </div><!-- /.col-lg-6 -->\n \n </div><!-- /.row -->\n </form>\n \n</div>" }, { "code": null, "e": 13831, "s": 13824, "text": "Action" }, { "code": null, "e": 13846, "s": 13831, "text": "Another action" }, { "code": null, "e": 13866, "s": 13846, "text": "Something else here" }, { "code": null, "e": 13881, "s": 13866, "text": "Separated link" }, { "code": null, "e": 13888, "s": 13881, "text": "Action" }, { "code": null, "e": 13903, "s": 13888, "text": "Another action" }, { "code": null, "e": 13923, "s": 13903, "text": "Something else here" }, { "code": null, "e": 13938, "s": 13923, "text": "Separated link" }, { "code": null, "e": 13971, "s": 13938, "text": "\n 26 Lectures \n 2 hours \n" }, { "code": null, "e": 13985, "s": 13971, "text": " Anadi Sharma" }, { "code": null, "e": 14020, "s": 13985, "text": "\n 54 Lectures \n 4.5 hours \n" }, { "code": null, "e": 14037, "s": 14020, "text": " Frahaan Hussain" }, { "code": null, "e": 14074, "s": 14037, "text": "\n 161 Lectures \n 14.5 hours \n" }, { "code": null, "e": 14102, "s": 14074, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 14135, "s": 14102, "text": "\n 20 Lectures \n 4 hours \n" }, { "code": null, "e": 14147, "s": 14135, "text": " Azaz Patel" }, { "code": null, "e": 14182, "s": 14147, "text": "\n 15 Lectures \n 1.5 hours \n" }, { "code": null, "e": 14199, "s": 14182, "text": " Muhammad Ismail" }, { "code": null, "e": 14232, "s": 14199, "text": "\n 62 Lectures \n 8 hours \n" }, { "code": null, "e": 14252, "s": 14232, "text": " Yossef Ayman Zedan" }, { "code": null, "e": 14259, "s": 14252, "text": " Print" }, { "code": null, "e": 14270, "s": 14259, "text": " Add Notes" } ]
How to find the day of the year from dates in R?
To find the day of the year from dates, we can use yday function of lubridate package. For example, if we have a date or a date of vectors then we simply need to pass that date or the vector inside yday function by using the below syntax − yday(“date”) or yday(“vector_of_date”) Loading lubridate package − library(lubridate) date1<-"2020-01-01" yday(date1) [1] 1 date2<-"2020-01-25" yday(date2) [1] 25 date3<-c("2020-01-25","2020-01-15","2020-02-25","2020-10-03","2020-02-25","2020-05-15","2020-01-28","2020-01-20","2020-11-25","2020-12-25","2020-01-05","2020-06-21","2020-06-22","2020-02-20","2020-03-18","2020-04-19","2020-04-04","2020-04-29","2020-01-03","2020-01-17","2020-11-05","2020-09-09","2020-10-09","2020-04-14","2020-10-02","2020-12-03","2020-11-07","2020-08-15","2020-07-22","2020-07-25","2020-08-25","2020-05-07","2020-05-23","2020-04-01","2020-04-30","2020-07-15","2020-08-17","2020-09-12","2020-10-03","2020-11-16","2020-01-11","2020-06-06","2020-07-24") date3 [1] "2020-01-25" "2020-01-15" "2020-02-25" "2020-10-03" "2020-02-25" [6] "2020-05-15" "2020-01-28" "2020-01-20" "2020-11-25" "2020-12-25" [11] "2020-01-05" "2020-06-21" "2020-06-22" "2020-02-20" "2020-03-18" [16] "2020-04-19" "2020-04-04" "2020-04-29" "2020-01-03" "2020-01-17" [21] "2020-11-05" "2020-09-09" "2020-10-09" "2020-04-14" "2020-10-02" [26] "2020-12-03" "2020-11-07" "2020-08-15" "2020-07-22" "2020-07-25" [31] "2020-08-25" "2020-05-07" "2020-05-23" "2020-04-01" "2020-04-30" [36] "2020-07-15" "2020-08-17" "2020-09-12" "2020-10-03" "2020-11-16" [41] "2020-01-11" "2020-06-06" "2020-07-24" yday(date3) [1] 25 15 56 277 56 136 28 20 330 360 5 173 174 51 78 110 95 120 3 [20] 17 310 253 283 105 276 338 312 228 204 207 238 128 144 92 121 197 230 256 [39] 277 321 11 158 206 date4<-seq(as.Date("2020-01-01"),as.Date("2020-04-01"),by="days") date4 [1] "2020-01-01" "2020-01-02" "2020-01-03" "2020-01-04" "2020-01-05" [6] "2020-01-06" "2020-01-07" "2020-01-08" "2020-01-09" "2020-01-10" [11] "2020-01-11" "2020-01-12" "2020-01-13" "2020-01-14" "2020-01-15" [16] "2020-01-16" "2020-01-17" "2020-01-18" "2020-01-19" "2020-01-20" [21] "2020-01-21" "2020-01-22" "2020-01-23" "2020-01-24" "2020-01-25" [26] "2020-01-26" "2020-01-27" "2020-01-28" "2020-01-29" "2020-01-30" [31] "2020-01-31" "2020-02-01" "2020-02-02" "2020-02-03" "2020-02-04" [36] "2020-02-05" "2020-02-06" "2020-02-07" "2020-02-08" "2020-02-09" [41] "2020-02-10" "2020-02-11" "2020-02-12" "2020-02-13" "2020-02-14" [46] "2020-02-15" "2020-02-16" "2020-02-17" "2020-02-18" "2020-02-19" [51] "2020-02-20" "2020-02-21" "2020-02-22" "2020-02-23" "2020-02-24" [56] "2020-02-25" "2020-02-26" "2020-02-27" "2020-02-28" "2020-02-29" [61] "2020-03-01" "2020-03-02" "2020-03-03" "2020-03-04" "2020-03-05" [66] "2020-03-06" "2020-03-07" "2020-03-08" "2020-03-09" "2020-03-10" [71] "2020-03-11" "2020-03-12" "2020-03-13" "2020-03-14" "2020-03-15" [76] "2020-03-16" "2020-03-17" "2020-03-18" "2020-03-19" "2020-03-20" [81] "2020-03-21" "2020-03-22" "2020-03-23" "2020-03-24" "2020-03-25" [86] "2020-03-26" "2020-03-27" "2020-03-28" "2020-03-29" "2020-03-30" [91] "2020-03-31" "2020-04-01" yday(date4) [1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 [26] 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 [51] 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 [76] 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 date5<-seq(as.Date("2020-01-01"),as.Date("2020-06-01"),by="2 days") date5 [1] "2020-01-01" "2020-01-03" "2020-01-05" "2020-01-07" "2020-01-09" [6] "2020-01-11" "2020-01-13" "2020-01-15" "2020-01-17" "2020-01-19" [11] "2020-01-21" "2020-01-23" "2020-01-25" "2020-01-27" "2020-01-29" [16] "2020-01-31" "2020-02-02" "2020-02-04" "2020-02-06" "2020-02-08" [21] "2020-02-10" "2020-02-12" "2020-02-14" "2020-02-16" "2020-02-18" [26] "2020-02-20" "2020-02-22" "2020-02-24" "2020-02-26" "2020-02-28" [31] "2020-03-01" "2020-03-03" "2020-03-05" "2020-03-07" "2020-03-09" [36] "2020-03-11" "2020-03-13" "2020-03-15" "2020-03-17" "2020-03-19" [41] "2020-03-21" "2020-03-23" "2020-03-25" "2020-03-27" "2020-03-29" [46] "2020-03-31" "2020-04-02" "2020-04-04" "2020-04-06" "2020-04-08" [51] "2020-04-10" "2020-04-12" "2020-04-14" "2020-04-16" "2020-04-18" [56] "2020-04-20" "2020-04-22" "2020-04-24" "2020-04-26" "2020-04-28" [61] "2020-04-30" "2020-05-02" "2020-05-04" "2020-05-06" "2020-05-08" [66] "2020-05-10" "2020-05-12" "2020-05-14" "2020-05-16" "2020-05-18" [71] "2020-05-20" "2020-05-22" "2020-05-24" "2020-05-26" "2020-05-28" [76] "2020-05-30" "2020-06-01" yday(date5) [1] 1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 [20] 39 41 43 45 47 49 51 53 55 57 59 61 63 65 67 69 71 73 75 [39] 77 79 81 83 85 87 89 91 93 95 97 99 101 103 105 107 109 111 113 [58] 115 117 119 121 123 125 127 129 131 133 135 137 139 141 143 145 147 149 151 [77] 153
[ { "code": null, "e": 1302, "s": 1062, "text": "To find the day of the year from dates, we can use yday function of lubridate package. For example, if we have a date or a date of vectors then we simply need to pass that date or the vector inside yday function by using the below syntax −" }, { "code": null, "e": 1315, "s": 1302, "text": "yday(“date”)" }, { "code": null, "e": 1318, "s": 1315, "text": "or" }, { "code": null, "e": 1341, "s": 1318, "text": "yday(“vector_of_date”)" }, { "code": null, "e": 1369, "s": 1341, "text": "Loading lubridate package −" }, { "code": null, "e": 1388, "s": 1369, "text": "library(lubridate)" }, { "code": null, "e": 5926, "s": 1388, "text": "date1<-\"2020-01-01\"\nyday(date1)\n[1] 1\ndate2<-\"2020-01-25\"\nyday(date2)\n[1] 25\ndate3<-c(\"2020-01-25\",\"2020-01-15\",\"2020-02-25\",\"2020-10-03\",\"2020-02-25\",\"2020-05-15\",\"2020-01-28\",\"2020-01-20\",\"2020-11-25\",\"2020-12-25\",\"2020-01-05\",\"2020-06-21\",\"2020-06-22\",\"2020-02-20\",\"2020-03-18\",\"2020-04-19\",\"2020-04-04\",\"2020-04-29\",\"2020-01-03\",\"2020-01-17\",\"2020-11-05\",\"2020-09-09\",\"2020-10-09\",\"2020-04-14\",\"2020-10-02\",\"2020-12-03\",\"2020-11-07\",\"2020-08-15\",\"2020-07-22\",\"2020-07-25\",\"2020-08-25\",\"2020-05-07\",\"2020-05-23\",\"2020-04-01\",\"2020-04-30\",\"2020-07-15\",\"2020-08-17\",\"2020-09-12\",\"2020-10-03\",\"2020-11-16\",\"2020-01-11\",\"2020-06-06\",\"2020-07-24\")\ndate3\n[1] \"2020-01-25\" \"2020-01-15\" \"2020-02-25\" \"2020-10-03\" \"2020-02-25\"\n[6] \"2020-05-15\" \"2020-01-28\" \"2020-01-20\" \"2020-11-25\" \"2020-12-25\"\n[11] \"2020-01-05\" \"2020-06-21\" \"2020-06-22\" \"2020-02-20\" \"2020-03-18\"\n[16] \"2020-04-19\" \"2020-04-04\" \"2020-04-29\" \"2020-01-03\" \"2020-01-17\"\n[21] \"2020-11-05\" \"2020-09-09\" \"2020-10-09\" \"2020-04-14\" \"2020-10-02\"\n[26] \"2020-12-03\" \"2020-11-07\" \"2020-08-15\" \"2020-07-22\" \"2020-07-25\"\n[31] \"2020-08-25\" \"2020-05-07\" \"2020-05-23\" \"2020-04-01\" \"2020-04-30\"\n[36] \"2020-07-15\" \"2020-08-17\" \"2020-09-12\" \"2020-10-03\" \"2020-11-16\"\n[41] \"2020-01-11\" \"2020-06-06\" \"2020-07-24\" \nyday(date3)\n[1] 25 15 56 277 56 136 28 20 330 360 5 173 174 51 78 110 95 120 3\n[20] 17 310 253 283 105 276 338 312 228 204 207 238 128 144 92 121 197 230 256\n[39] 277 321 11 158 206\ndate4<-seq(as.Date(\"2020-01-01\"),as.Date(\"2020-04-01\"),by=\"days\")\ndate4\n[1] \"2020-01-01\" \"2020-01-02\" \"2020-01-03\" \"2020-01-04\" \"2020-01-05\"\n[6] \"2020-01-06\" \"2020-01-07\" \"2020-01-08\" \"2020-01-09\" \"2020-01-10\"\n[11] \"2020-01-11\" \"2020-01-12\" \"2020-01-13\" \"2020-01-14\" \"2020-01-15\"\n[16] \"2020-01-16\" \"2020-01-17\" \"2020-01-18\" \"2020-01-19\" \"2020-01-20\"\n[21] \"2020-01-21\" \"2020-01-22\" \"2020-01-23\" \"2020-01-24\" \"2020-01-25\"\n[26] \"2020-01-26\" \"2020-01-27\" \"2020-01-28\" \"2020-01-29\" \"2020-01-30\"\n[31] \"2020-01-31\" \"2020-02-01\" \"2020-02-02\" \"2020-02-03\" \"2020-02-04\"\n[36] \"2020-02-05\" \"2020-02-06\" \"2020-02-07\" \"2020-02-08\" \"2020-02-09\"\n[41] \"2020-02-10\" \"2020-02-11\" \"2020-02-12\" \"2020-02-13\" \"2020-02-14\"\n[46] \"2020-02-15\" \"2020-02-16\" \"2020-02-17\" \"2020-02-18\" \"2020-02-19\"\n[51] \"2020-02-20\" \"2020-02-21\" \"2020-02-22\" \"2020-02-23\" \"2020-02-24\"\n[56] \"2020-02-25\" \"2020-02-26\" \"2020-02-27\" \"2020-02-28\" \"2020-02-29\"\n[61] \"2020-03-01\" \"2020-03-02\" \"2020-03-03\" \"2020-03-04\" \"2020-03-05\"\n[66] \"2020-03-06\" \"2020-03-07\" \"2020-03-08\" \"2020-03-09\" \"2020-03-10\"\n[71] \"2020-03-11\" \"2020-03-12\" \"2020-03-13\" \"2020-03-14\" \"2020-03-15\"\n[76] \"2020-03-16\" \"2020-03-17\" \"2020-03-18\" \"2020-03-19\" \"2020-03-20\"\n[81] \"2020-03-21\" \"2020-03-22\" \"2020-03-23\" \"2020-03-24\" \"2020-03-25\"\n[86] \"2020-03-26\" \"2020-03-27\" \"2020-03-28\" \"2020-03-29\" \"2020-03-30\"\n[91] \"2020-03-31\" \"2020-04-01\"\nyday(date4)\n[1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25\n[26] 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50\n[51] 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75\n[76] 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92\ndate5<-seq(as.Date(\"2020-01-01\"),as.Date(\"2020-06-01\"),by=\"2 days\")\ndate5\n[1] \"2020-01-01\" \"2020-01-03\" \"2020-01-05\" \"2020-01-07\" \"2020-01-09\"\n[6] \"2020-01-11\" \"2020-01-13\" \"2020-01-15\" \"2020-01-17\" \"2020-01-19\"\n[11] \"2020-01-21\" \"2020-01-23\" \"2020-01-25\" \"2020-01-27\" \"2020-01-29\"\n[16] \"2020-01-31\" \"2020-02-02\" \"2020-02-04\" \"2020-02-06\" \"2020-02-08\"\n[21] \"2020-02-10\" \"2020-02-12\" \"2020-02-14\" \"2020-02-16\" \"2020-02-18\"\n[26] \"2020-02-20\" \"2020-02-22\" \"2020-02-24\" \"2020-02-26\" \"2020-02-28\"\n[31] \"2020-03-01\" \"2020-03-03\" \"2020-03-05\" \"2020-03-07\" \"2020-03-09\"\n[36] \"2020-03-11\" \"2020-03-13\" \"2020-03-15\" \"2020-03-17\" \"2020-03-19\"\n[41] \"2020-03-21\" \"2020-03-23\" \"2020-03-25\" \"2020-03-27\" \"2020-03-29\"\n[46] \"2020-03-31\" \"2020-04-02\" \"2020-04-04\" \"2020-04-06\" \"2020-04-08\"\n[51] \"2020-04-10\" \"2020-04-12\" \"2020-04-14\" \"2020-04-16\" \"2020-04-18\"\n[56] \"2020-04-20\" \"2020-04-22\" \"2020-04-24\" \"2020-04-26\" \"2020-04-28\"\n[61] \"2020-04-30\" \"2020-05-02\" \"2020-05-04\" \"2020-05-06\" \"2020-05-08\"\n[66] \"2020-05-10\" \"2020-05-12\" \"2020-05-14\" \"2020-05-16\" \"2020-05-18\"\n[71] \"2020-05-20\" \"2020-05-22\" \"2020-05-24\" \"2020-05-26\" \"2020-05-28\"\n[76] \"2020-05-30\" \"2020-06-01\"\nyday(date5)\n[1] 1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37\n[20] 39 41 43 45 47 49 51 53 55 57 59 61 63 65 67 69 71 73 75\n[39] 77 79 81 83 85 87 89 91 93 95 97 99 101 103 105 107 109 111 113\n[58] 115 117 119 121 123 125 127 129 131 133 135 137 139 141 143 145 147 149 151\n[77] 153" } ]
HTTP - Requests
An HTTP client sends an HTTP request to a server in the form of a request message which includes following format: A Request-line Zero or more header (General|Request|Entity) fields followed by CRLF An empty line (i.e., a line with nothing preceding the CRLF) indicating the end of the header fields Optionally a message-body A Request-line Zero or more header (General|Request|Entity) fields followed by CRLF An empty line (i.e., a line with nothing preceding the CRLF) indicating the end of the header fields Optionally a message-body The following sections explain each of the entities used in an HTTP request message. The Request-Line begins with a method token, followed by the Request-URI and the protocol version, and ending with CRLF. The elements are separated by space SP characters. Request-Line = Method SP Request-URI SP HTTP-Version CRLF Let's discuss each of the parts mentioned in the Request-Line. The request method indicates the method to be performed on the resource identified by the given Request-URI. The method is case-sensitive and should always be mentioned in uppercase. The following table lists all the supported methods in HTTP/1.1. The GET method is used to retrieve information from the given server using a given URI. Requests using GET should only retrieve data and should have no other effect on the data. Same as GET, but it transfers the status line and the header section only. A POST request is used to send data to the server, for example, customer information, file upload, etc. using HTML forms. Replaces all the current representations of the target resource with the uploaded content. Removes all the current representations of the target resource given by URI. Establishes a tunnel to the server identified by a given URI. Describe the communication options for the target resource. Performs a message loop back test along with the path to the target resource. The Request-URI is a Uniform Resource Identifier and identifies the resource upon which to apply the request. Following are the most commonly used forms to specify an URI: Request-URI = "*" | absoluteURI | abs_path | authority OPTIONS * HTTP/1.1 GET http://www.w3.org/pub/WWW/TheProject.html HTTP/1.1 GET /pub/WWW/TheProject.html HTTP/1.1 Host: www.w3.org Note that the absolute path cannot be empty; if none is present in the original URI, it MUST be given as "/" (the server root). We will study General-header and Entity-header in a separate chapter when we will learn HTTP header fields. For now, let's check what Request header fields are. The request-header fields allow the client to pass additional information about the request, and about the client itself, to the server. These fields act as request modifiers.Here is a list of some important Request-header fields that can be used based on the requirement: Accept-Charset Accept-Charset Accept-Encoding Accept-Encoding Accept-Language Accept-Language Authorization Authorization Expect Expect From From Host Host If-Match If-Match If-Modified-Since If-Modified-Since If-None-Match If-None-Match If-Range If-Range If-Unmodified-Since If-Unmodified-Since Max-Forwards Max-Forwards Proxy-Authorization Proxy-Authorization Range Range Referer Referer TE TE User-Agent User-Agent You can introduce your custom fields in case you are going to write your own custom Client and Web Server. Now let's put it all together to form an HTTP request to fetch hello.htm page from the web server running on tutorialspoint.com GET /hello.htm HTTP/1.1 User-Agent: Mozilla/4.0 (compatible; MSIE5.01; Windows NT) Host: www.tutorialspoint.com Accept-Language: en-us Accept-Encoding: gzip, deflate Connection: Keep-Alive Here we are not sending any request data to the server because we are fetching a plain HTML page from the server. Connection is a general-header, and the rest of the headers are request headers. The following example shows how to send form data to the server using request message body: POST /cgi-bin/process.cgi HTTP/1.1 User-Agent: Mozilla/4.0 (compatible; MSIE5.01; Windows NT) Host: www.tutorialspoint.com Content-Type: application/x-www-form-urlencoded Content-Length: length Accept-Language: en-us Accept-Encoding: gzip, deflate Connection: Keep-Alive licenseID=string&content=string&/paramsXML=string Here the given URL /cgi-bin/process.cgi will be used to process the passed data and accordingly, a response will be returned. Here content-type tells the server that the passed data is a simple web form data and length will be the actual length of the data put in the message body. The following example shows how you can pass plain XML to your web server: POST /cgi-bin/process.cgi HTTP/1.1 User-Agent: Mozilla/4.0 (compatible; MSIE5.01; Windows NT) Host: www.tutorialspoint.com Content-Type: text/xml; charset=utf-8 Content-Length: length Accept-Language: en-us Accept-Encoding: gzip, deflate Connection: Keep-Alive <?xml version="1.0" encoding="utf-8"?> <string xmlns="http://clearforest.com/">string</string> Print Add Notes Bookmark this page
[ { "code": null, "e": 1894, "s": 1779, "text": "An HTTP client sends an HTTP request to a server in the form of a request message which includes following format:" }, { "code": null, "e": 2108, "s": 1894, "text": "\nA Request-line\nZero or more header (General|Request|Entity) fields followed by CRLF\nAn empty line (i.e., a line with nothing preceding the CRLF) \nindicating the end of the header fields\nOptionally a message-body\n" }, { "code": null, "e": 2123, "s": 2108, "text": "A Request-line" }, { "code": null, "e": 2192, "s": 2123, "text": "Zero or more header (General|Request|Entity) fields followed by CRLF" }, { "code": null, "e": 2294, "s": 2192, "text": "An empty line (i.e., a line with nothing preceding the CRLF) \nindicating the end of the header fields" }, { "code": null, "e": 2320, "s": 2294, "text": "Optionally a message-body" }, { "code": null, "e": 2405, "s": 2320, "text": "The following sections explain each of the entities used in an HTTP request message." }, { "code": null, "e": 2577, "s": 2405, "text": "The Request-Line begins with a method token, followed by the Request-URI and the protocol version, and ending with CRLF. The elements are separated by space SP characters." }, { "code": null, "e": 2636, "s": 2577, "text": "Request-Line = Method SP Request-URI SP HTTP-Version CRLF\n" }, { "code": null, "e": 2699, "s": 2636, "text": "Let's discuss each of the parts mentioned in the Request-Line." }, { "code": null, "e": 2947, "s": 2699, "text": "The request method indicates the method to be performed on the resource identified by the given Request-URI. The method is case-sensitive and should always be mentioned in uppercase. The following table lists all the supported methods in HTTP/1.1." }, { "code": null, "e": 3127, "s": 2947, "text": "The GET method is used to retrieve information from the given server using a given URI. Requests using GET should only retrieve data and should have no other effect on the data." }, { "code": null, "e": 3202, "s": 3127, "text": "Same as GET, but it transfers the status line and the header section only." }, { "code": null, "e": 3324, "s": 3202, "text": "A POST request is used to send data to the server, for example, customer information, file upload, etc. using HTML forms." }, { "code": null, "e": 3415, "s": 3324, "text": "Replaces all the current representations of the target resource with the uploaded content." }, { "code": null, "e": 3492, "s": 3415, "text": "Removes all the current representations of the target resource given by URI." }, { "code": null, "e": 3554, "s": 3492, "text": "Establishes a tunnel to the server identified by a given URI." }, { "code": null, "e": 3614, "s": 3554, "text": "Describe the communication options for the target resource." }, { "code": null, "e": 3692, "s": 3614, "text": "Performs a message loop back test along with the path to the target resource." }, { "code": null, "e": 3864, "s": 3692, "text": "The Request-URI is a Uniform Resource Identifier and identifies the resource upon which to apply the request. Following are the most commonly used forms to specify an URI:" }, { "code": null, "e": 3920, "s": 3864, "text": "Request-URI = \"*\" | absoluteURI | abs_path | authority\n" }, { "code": null, "e": 3939, "s": 3920, "text": "OPTIONS * HTTP/1.1" }, { "code": null, "e": 3994, "s": 3939, "text": "GET http://www.w3.org/pub/WWW/TheProject.html HTTP/1.1" }, { "code": null, "e": 4032, "s": 3994, "text": "GET /pub/WWW/TheProject.html HTTP/1.1" }, { "code": null, "e": 4049, "s": 4032, "text": "Host: www.w3.org" }, { "code": null, "e": 4177, "s": 4049, "text": "Note that the absolute path cannot be empty; if none is present in the original URI, it MUST be given as \"/\" (the server root)." }, { "code": null, "e": 4338, "s": 4177, "text": "We will study General-header and Entity-header in a separate chapter when we will learn HTTP header fields. For now, let's check what Request header fields are." }, { "code": null, "e": 4611, "s": 4338, "text": "The request-header fields allow the client to pass additional information about the request, and about the client itself, to the server. These fields act as request modifiers.Here is a list of some important Request-header fields that can be used based on the requirement:" }, { "code": null, "e": 4626, "s": 4611, "text": "Accept-Charset" }, { "code": null, "e": 4641, "s": 4626, "text": "Accept-Charset" }, { "code": null, "e": 4658, "s": 4641, "text": " Accept-Encoding" }, { "code": null, "e": 4675, "s": 4658, "text": " Accept-Encoding" }, { "code": null, "e": 4692, "s": 4675, "text": " Accept-Language" }, { "code": null, "e": 4709, "s": 4692, "text": " Accept-Language" }, { "code": null, "e": 4724, "s": 4709, "text": " Authorization" }, { "code": null, "e": 4739, "s": 4724, "text": " Authorization" }, { "code": null, "e": 4747, "s": 4739, "text": " Expect" }, { "code": null, "e": 4755, "s": 4747, "text": " Expect" }, { "code": null, "e": 4761, "s": 4755, "text": " From" }, { "code": null, "e": 4767, "s": 4761, "text": " From" }, { "code": null, "e": 4773, "s": 4767, "text": " Host" }, { "code": null, "e": 4779, "s": 4773, "text": " Host" }, { "code": null, "e": 4789, "s": 4779, "text": " If-Match" }, { "code": null, "e": 4799, "s": 4789, "text": " If-Match" }, { "code": null, "e": 4818, "s": 4799, "text": " If-Modified-Since" }, { "code": null, "e": 4837, "s": 4818, "text": " If-Modified-Since" }, { "code": null, "e": 4852, "s": 4837, "text": " If-None-Match" }, { "code": null, "e": 4867, "s": 4852, "text": " If-None-Match" }, { "code": null, "e": 4877, "s": 4867, "text": " If-Range" }, { "code": null, "e": 4887, "s": 4877, "text": " If-Range" }, { "code": null, "e": 4908, "s": 4887, "text": " If-Unmodified-Since" }, { "code": null, "e": 4929, "s": 4908, "text": " If-Unmodified-Since" }, { "code": null, "e": 4943, "s": 4929, "text": " Max-Forwards" }, { "code": null, "e": 4957, "s": 4943, "text": " Max-Forwards" }, { "code": null, "e": 4978, "s": 4957, "text": " Proxy-Authorization" }, { "code": null, "e": 4999, "s": 4978, "text": " Proxy-Authorization" }, { "code": null, "e": 5006, "s": 4999, "text": " Range" }, { "code": null, "e": 5013, "s": 5006, "text": " Range" }, { "code": null, "e": 5022, "s": 5013, "text": " Referer" }, { "code": null, "e": 5031, "s": 5022, "text": " Referer" }, { "code": null, "e": 5035, "s": 5031, "text": " TE" }, { "code": null, "e": 5039, "s": 5035, "text": " TE" }, { "code": null, "e": 5051, "s": 5039, "text": " User-Agent" }, { "code": null, "e": 5063, "s": 5051, "text": " User-Agent" }, { "code": null, "e": 5170, "s": 5063, "text": "You can introduce your custom fields in case you are going to write your own custom Client and Web Server." }, { "code": null, "e": 5298, "s": 5170, "text": "Now let's put it all together to form an HTTP request to fetch hello.htm page from the web server running on tutorialspoint.com" }, { "code": null, "e": 5488, "s": 5298, "text": "GET /hello.htm HTTP/1.1\nUser-Agent: Mozilla/4.0 (compatible; MSIE5.01; Windows NT)\nHost: www.tutorialspoint.com\nAccept-Language: en-us\nAccept-Encoding: gzip, deflate\nConnection: Keep-Alive\n" }, { "code": null, "e": 5775, "s": 5488, "text": "Here we are not sending any request data to the server because we are fetching a plain HTML page from the server. Connection is a general-header, and the rest of the headers are request headers. The following example shows how to send form data to the server using request message body:" }, { "code": null, "e": 6098, "s": 5775, "text": "POST /cgi-bin/process.cgi HTTP/1.1\nUser-Agent: Mozilla/4.0 (compatible; MSIE5.01; Windows NT)\nHost: www.tutorialspoint.com\nContent-Type: application/x-www-form-urlencoded\nContent-Length: length\nAccept-Language: en-us\nAccept-Encoding: gzip, deflate\nConnection: Keep-Alive\n\nlicenseID=string&content=string&/paramsXML=string\n" }, { "code": null, "e": 6455, "s": 6098, "text": "Here the given URL /cgi-bin/process.cgi will be used to process the passed data and accordingly, a response will be returned. Here content-type tells the server that the passed data is a simple web form data and length will be the actual length of the data put in the message body. The following example shows how you can pass plain XML to your web server:" }, { "code": null, "e": 6813, "s": 6455, "text": "POST /cgi-bin/process.cgi HTTP/1.1\nUser-Agent: Mozilla/4.0 (compatible; MSIE5.01; Windows NT)\nHost: www.tutorialspoint.com\nContent-Type: text/xml; charset=utf-8\nContent-Length: length\nAccept-Language: en-us\nAccept-Encoding: gzip, deflate\nConnection: Keep-Alive\n\n<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<string xmlns=\"http://clearforest.com/\">string</string>\n" }, { "code": null, "e": 6820, "s": 6813, "text": " Print" }, { "code": null, "e": 6831, "s": 6820, "text": " Add Notes" } ]
PyQt5 QListWidget - Current Item Changed Signal - GeeksforGeeks
01 Aug, 2020 In this article we will see how we can get the current item changed signal of the QListWidget. QListWidget is a convenience class that provides a list view with a classic item-based interface for adding and removing items. QListWidget uses an internal model to manage each QListWidgetItem in the list. Current item can be set from the list of item. Unless the selection mode is NoSelection, the item is also selected. It can be set with the help of setCurrentItem method. This signal is emitted when current item is changed. In order to do this we will use currentItemChanged method with the list widget object. Syntax : list_widget.currentItemChanged.connect(method) Argument : It takes method as argument Return : It returns None Below is the implementation # importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle("Python ") # setting geometry self.setGeometry(100, 100, 500, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for components def UiComponents(self): # creating a QListWidget list_widget = QListWidget(self) # setting geometry to it list_widget.setGeometry(50, 70, 150, 60) # list widget items item1 = QListWidgetItem("A") item2 = QListWidgetItem("B") item3 = QListWidgetItem("C") # adding items to the list widget list_widget.addItem(item1) list_widget.addItem(item2) list_widget.addItem(item3) # setting current item list_widget.setCurrentItem(item2) # creating a label label = QLabel("GeesforGeeks", self) # setting geometry to the label label.setGeometry(230, 80, 280, 80) # making label multi line label.setWordWrap(True) # getting item changed signal list_widget.currentItemChanged.connect(lambda: label.setText("Item Changed Signal")) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec()) Output : Python PyQt-QListWidget Python-gui Python-PyQt 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 Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python Different ways to create Pandas Dataframe Python String | replace() Python program to convert a list to string Create a Pandas DataFrame from Lists Reading and Writing to text files in Python
[ { "code": null, "e": 25030, "s": 25002, "text": "\n01 Aug, 2020" }, { "code": null, "e": 25555, "s": 25030, "text": "In this article we will see how we can get the current item changed signal of the QListWidget. QListWidget is a convenience class that provides a list view with a classic item-based interface for adding and removing items. QListWidget uses an internal model to manage each QListWidgetItem in the list. Current item can be set from the list of item. Unless the selection mode is NoSelection, the item is also selected. It can be set with the help of setCurrentItem method. This signal is emitted when current item is changed." }, { "code": null, "e": 25642, "s": 25555, "text": "In order to do this we will use currentItemChanged method with the list widget object." }, { "code": null, "e": 25698, "s": 25642, "text": "Syntax : list_widget.currentItemChanged.connect(method)" }, { "code": null, "e": 25737, "s": 25698, "text": "Argument : It takes method as argument" }, { "code": null, "e": 25762, "s": 25737, "text": "Return : It returns None" }, { "code": null, "e": 25790, "s": 25762, "text": "Below is the implementation" }, { "code": "# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle(\"Python \") # setting geometry self.setGeometry(100, 100, 500, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for components def UiComponents(self): # creating a QListWidget list_widget = QListWidget(self) # setting geometry to it list_widget.setGeometry(50, 70, 150, 60) # list widget items item1 = QListWidgetItem(\"A\") item2 = QListWidgetItem(\"B\") item3 = QListWidgetItem(\"C\") # adding items to the list widget list_widget.addItem(item1) list_widget.addItem(item2) list_widget.addItem(item3) # setting current item list_widget.setCurrentItem(item2) # creating a label label = QLabel(\"GeesforGeeks\", self) # setting geometry to the label label.setGeometry(230, 80, 280, 80) # making label multi line label.setWordWrap(True) # getting item changed signal list_widget.currentItemChanged.connect(lambda: label.setText(\"Item Changed Signal\")) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())", "e": 27338, "s": 25790, "text": null }, { "code": null, "e": 27347, "s": 27338, "text": "Output :" }, { "code": null, "e": 27371, "s": 27347, "text": "Python PyQt-QListWidget" }, { "code": null, "e": 27382, "s": 27371, "text": "Python-gui" }, { "code": null, "e": 27394, "s": 27382, "text": "Python-PyQt" }, { "code": null, "e": 27401, "s": 27394, "text": "Python" }, { "code": null, "e": 27499, "s": 27401, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27517, "s": 27499, "text": "Python Dictionary" }, { "code": null, "e": 27552, "s": 27517, "text": "Read a file line by line in Python" }, { "code": null, "e": 27574, "s": 27552, "text": "Enumerate() in Python" }, { "code": null, "e": 27606, "s": 27574, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27636, "s": 27606, "text": "Iterate over a list in Python" }, { "code": null, "e": 27678, "s": 27636, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 27704, "s": 27678, "text": "Python String | replace()" }, { "code": null, "e": 27747, "s": 27704, "text": "Python program to convert a list to string" }, { "code": null, "e": 27784, "s": 27747, "text": "Create a Pandas DataFrame from Lists" } ]
EJB - Exception Handling
EJBs are a part of enterprise applications which are normally based on distributed environments. So, apart from the normal exceptions that can occur, there can be exceptions like communication failure, security permissions, server down, etc. EJB container considers exceptions in two ways − Application Exception − If business rule is violated or exception occurs while executing the business logic. Application Exception − If business rule is violated or exception occurs while executing the business logic. System Exception − Any exception, which is not caused by business logic or business code. RuntimeException, RemoteException are SystemException. For example, error during EJB lookup. RuntimeException, RemoteException are SystemException. System Exception − Any exception, which is not caused by business logic or business code. RuntimeException, RemoteException are SystemException. For example, error during EJB lookup. RuntimeException, RemoteException are SystemException. When Application Exception occurs, EJB container intercepts the exception, but returns the same to the client as it is. It does not roll back the transaction unless it is specified in the code by EJBContext.setRollBackOnly() method. EJB Container does not wrap the exception in case of Application Exception. When System Exception occurs, EJB container intercepts the exception, rollbacks the transaction and start the clean up tasks. It wraps the exception into RemoteException and throws it to the client. Application exceptions are generally thrown in Session EJB methods as these are the methods responsible to execute business logic. Application exception should be declared in throws clause of business method and should be thrown in case business logic fails. @Stateless public class LibraryPersistentBean implements LibraryPersistentBeanRemote { ... public List<Book> getBooks() throws NoBookAvailableException { List<Book> books = entityManager.createQuery("From Books").getResultList(); if(books.size == 0) throw NoBookAvailableException ("No Book available in library."); return books; } ... } System exception can occur at any time like naming lookup fails, sql error occurs while fetching data. In such a case, such exception should be wrapped under EJBException and thrown back to the client. @Stateless public class LibraryPersistentBean implements LibraryPersistentBeanRemote { ... public List<Book> getBooks() { try { List<Book> books = entityManager.createQuery("From Books").getResultList(); } catch (CreateException ce) { throw (EJBException) new EJBException(ce).initCause(ce); } catch (SqlException se) { throw (EJBException) new EJBException(se).initCause(se); } return books; } ... } At client side, handle the EJBException. public class EJBTester { private void testEntityEjb() { ... try{ LibraryPersistentBeanRemote libraryBean = LibraryPersistentBeanRemote)ctx.lookup("LibraryPersistentBean/remote"); List<Book> booksList = libraryBean.getBooks(); } catch(EJBException e) { Exception ne = (Exception) e.getCause(); if(ne.getClass().getName().equals("SqlException")) { System.out.println("Database error: "+ e.getMessage()); } } ... } } Print Add Notes Bookmark this page
[ { "code": null, "e": 2289, "s": 2047, "text": "EJBs are a part of enterprise applications which are normally based on distributed environments. So, apart from the normal exceptions that can occur, there can be exceptions like communication failure, security permissions, server down, etc." }, { "code": null, "e": 2338, "s": 2289, "text": "EJB container considers exceptions in two ways −" }, { "code": null, "e": 2447, "s": 2338, "text": "Application Exception − If business rule is violated or exception occurs while executing the business logic." }, { "code": null, "e": 2556, "s": 2447, "text": "Application Exception − If business rule is violated or exception occurs while executing the business logic." }, { "code": null, "e": 2794, "s": 2556, "text": "System Exception − Any exception, which is not caused by business logic or business code. RuntimeException, RemoteException are SystemException. For example, error during EJB lookup. RuntimeException, RemoteException are SystemException." }, { "code": null, "e": 3032, "s": 2794, "text": "System Exception − Any exception, which is not caused by business logic or business code. RuntimeException, RemoteException are SystemException. For example, error during EJB lookup. RuntimeException, RemoteException are SystemException." }, { "code": null, "e": 3341, "s": 3032, "text": "When Application Exception occurs, EJB container intercepts the exception, but returns the same to the client as it is. It does not roll back the transaction unless it is specified in the code by EJBContext.setRollBackOnly() method. EJB Container does not wrap the exception in case of Application Exception." }, { "code": null, "e": 3540, "s": 3341, "text": "When System Exception occurs, EJB container intercepts the exception, rollbacks the transaction and start the clean up tasks. It wraps the exception into RemoteException and throws it to the client." }, { "code": null, "e": 3799, "s": 3540, "text": "Application exceptions are generally thrown in Session EJB methods as these are the methods responsible to execute business logic. Application exception should be declared in throws clause of business method and should be thrown in case business logic fails." }, { "code": null, "e": 4201, "s": 3799, "text": "@Stateless\npublic class LibraryPersistentBean implements LibraryPersistentBeanRemote {\n\t\n ...\n\n public List<Book> getBooks() throws NoBookAvailableException { \n List<Book> books = \n entityManager.createQuery(\"From Books\").getResultList();\n if(books.size == 0)\n\t\tthrow NoBookAvailableException\n (\"No Book available in library.\");\n return books;\n }\n ...\n}" }, { "code": null, "e": 4403, "s": 4201, "text": "System exception can occur at any time like naming lookup fails, sql error occurs while fetching data. In such a case, such exception should be wrapped under EJBException and thrown back to the client." }, { "code": null, "e": 4899, "s": 4403, "text": "@Stateless\npublic class LibraryPersistentBean implements LibraryPersistentBeanRemote {\n\t\n ...\n\n public List<Book> getBooks() { \n try {\n List<Book> books = \n entityManager.createQuery(\"From Books\").getResultList();\n } catch (CreateException ce) {\n throw (EJBException) new EJBException(ce).initCause(ce);\n } catch (SqlException se) {\n throw (EJBException) new EJBException(se).initCause(se); \n }\t \n return books;\n }\n ...\n}" }, { "code": null, "e": 4940, "s": 4899, "text": "At client side, handle the EJBException." }, { "code": null, "e": 5424, "s": 4940, "text": "public class EJBTester {\n private void testEntityEjb() {\n ...\n try{\n LibraryPersistentBeanRemote libraryBean =\n LibraryPersistentBeanRemote)ctx.lookup(\"LibraryPersistentBean/remote\");\n \n List<Book> booksList = libraryBean.getBooks();\n } catch(EJBException e) {\n Exception ne = (Exception) e.getCause();\n if(ne.getClass().getName().equals(\"SqlException\")) {\n System.out.println(\"Database error: \"+ e.getMessage());\n }\n }\n ...\n }\n}" }, { "code": null, "e": 5431, "s": 5424, "text": " Print" }, { "code": null, "e": 5442, "s": 5431, "text": " Add Notes" } ]
CSS3 top to bottom Gradient
You can try to run the following code to implement top to the bottom gradient in CSS3 − Live Demo <html> <head> <style> #grad1 { height: 100px; background: -webkit-linear-gradient(pink,green); background: -o-linear-gradient(pink,green); background: -moz-linear-gradient(pink,green); background: linear-gradient(pink,green); } </style> </head> <body> <div id = "grad1"></div> </body> </html>
[ { "code": null, "e": 1150, "s": 1062, "text": "You can try to run the following code to implement top to the bottom gradient in CSS3 −" }, { "code": null, "e": 1160, "s": 1150, "text": "Live Demo" }, { "code": null, "e": 1561, "s": 1160, "text": "<html>\n <head>\n <style>\n #grad1 {\n height: 100px;\n background: -webkit-linear-gradient(pink,green);\n background: -o-linear-gradient(pink,green);\n background: -moz-linear-gradient(pink,green);\n background: linear-gradient(pink,green);\n }\n </style>\n </head>\n <body>\n <div id = \"grad1\"></div>\n </body>\n</html>" } ]
How to overwrite a specific chunk in a byte array using java?
Java provides a ByteBuffer class which allows you to wrap an array into a byte buffer using its wrap() method. Once you did that you can replace the contents of the buffer using the position(): To select the starting position and, put(): To replace the data methods: Live Demo import java.nio.ByteBuffer; public class OverwriteChunkOfByteArray { public static void main(String args[]) { String str = "Hello how are you what are you doing"; byte[] byteArray = str.getBytes(); System.out.println("Contents of the byet array :: "); for(int i = 0; i<byteArray.length; i++) { System.out.println((char)byteArray[i]); } ByteBuffer buffer = ByteBuffer.wrap(byteArray); byte[] newArray = "where do you live ".getBytes(); buffer.position(18); buffer.put(newArray); System.out.println("Contents of the byte array after replacement::"); for(int i = 0; i<byteArray.length; i++) { System.out.println((char)byteArray[i]); } } } of the byte array :: H e l l o h o w a r e y o u w h a t a r e y o u d o i n g Contents of the byet array after replacement :: H e l l o h o w a r e y o u w h e r e d o y o u l i v e
[ { "code": null, "e": 1329, "s": 1062, "text": "Java provides a ByteBuffer class which allows you to wrap an array into a byte buffer using its wrap() method. Once you did that you can replace the contents of the buffer using the position(): To select the starting position and, put(): To replace the data methods:" }, { "code": null, "e": 1339, "s": 1329, "text": "Live Demo" }, { "code": null, "e": 2084, "s": 1339, "text": "import java.nio.ByteBuffer;\n\npublic class OverwriteChunkOfByteArray {\n public static void main(String args[]) {\n String str = \"Hello how are you what are you doing\";\n byte[] byteArray = str.getBytes();\n System.out.println(\"Contents of the byet array :: \");\n \n for(int i = 0; i<byteArray.length; i++) {\n System.out.println((char)byteArray[i]);\n }\n ByteBuffer buffer = ByteBuffer.wrap(byteArray);\n byte[] newArray = \"where do you live \".getBytes();\n buffer.position(18);\n buffer.put(newArray);\n System.out.println(\"Contents of the byte array after replacement::\");\n \n for(int i = 0; i<byteArray.length; i++) {\n System.out.println((char)byteArray[i]);\n }\n }\n}" }, { "code": null, "e": 2281, "s": 2084, "text": "of the byte array ::\nH\ne\nl\nl\no\n\nh\no\nw\n\na\nr\ne\n\ny\no\nu\n\nw\nh\na\nt\n\na\nr\ne\n\ny\no\nu\n\nd\no\ni\nn\ng\nContents of the byet array after replacement ::\nH\ne\nl\nl\no\n\nh\no\nw\n\na\nr\ne\n\ny\no\nu\n\nw\nh\ne\nr\ne\n\nd\no\n\ny\no\nu\n\nl\ni\nv\ne" } ]
HTML | DOM Style fontSize Property - GeeksforGeeks
01 Aug, 2019 The fontSize property is used to set or get the font size of characters in a word should appear. Syntax: It returns the fontSize property.object.style.fontSize object.style.fontSize It sets the fontSize Property.object.style.fontSize = "value|initial|inherit" object.style.fontSize = "value|initial|inherit" Property Values: Return value: It returns the font size of the text of element. Example-1: Change font size into small. <!DOCTYPE html><html> <head> <title>DOM Style fontSize Property </title></head> <body> <center> <p style="color: green; width: 100%; font-size: 30px; font-weight: bold;" id="Geek1"> GeeksForGeeks </p> <h2>DOM Style fontSize Property </h2> <br> <button type="button" onclick="myGeeks()"> Click to change </button> <script> function myGeeks() { // Change font size in to small. document.getElementById( "Geek1").style.fontSize = "small"; } </script> </center></body> </html> Output: Before click on button: After click on button: Example-2: Change font-size into xx-large. <!DOCTYPE html><html> <head> <title>DOM Style fontSize Property </title></head> <body> <center> <p style="color: green; width: 100%; font-size: 10px; font-weight: bold;" id="Geek1"> GeeksForGeeks </p> <h2>DOM Style fontSize Property </h2> <br> <button type="button" onclick="myGeeks()"> Click to change </button> <script> function myGeeks() { // change into xx-large. document.getElementById( "Geek1").style.fontSize = "xx-large"; } </script> </center></body> </html> Output: Before click on button: After click on button: Example-3: Change font-size using length unit. <!DOCTYPE html><html> <head> <title>DOM Style fontSize Property </title></head> <body> <center> <p style="color: green; width: 100%; font-size: 10px; font-weight: bold;" id="Geek1"> GeeksForGeeks </p> <h2>DOM Style fontSize Property </h2> <br> <button type="button" onclick="myGeeks()"> Click to change </button> <script> function myGeeks() { // Change font size from // from 10px to 30px document.getElementById( "Geek1").style.fontSize = "30px"; } </script> </center></body> </html> Output: Before click on button: After click on button: Example-4: Change font-size using ‘%’ <!DOCTYPE html><html> <head> <title>DOM Style fontSize Property </title></head> <body> <center> <p style="color: green; width: 100%; font-size: 10px; font-weight: bold;" id="Geek1"> GeeksForGeeks </p> <h2>DOM Style fontSize Property </h2> <br> <button type="button" onclick="myGeeks()"> Click to change </button> <script> function myGeeks() { // Change font-size from 100% to 200% document.getElementById( "Geek1").style.fontSize = "200%"; } </script> </center></body> </html> Output: Before click on button After click on button Supported Browsers: The browser supported by HTML | DOM Style fontSize Property are listed below: Google Chrome Internet Explorer Mozilla firefox Opera Safari Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. HTML-DOM HTML-Property Picked 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 set the default value for an HTML <select> element ? Hide or show elements in HTML using display property 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": 25363, "s": 25335, "text": "\n01 Aug, 2019" }, { "code": null, "e": 25460, "s": 25363, "text": "The fontSize property is used to set or get the font size of characters in a word should appear." }, { "code": null, "e": 25468, "s": 25460, "text": "Syntax:" }, { "code": null, "e": 25524, "s": 25468, "text": "It returns the fontSize property.object.style.fontSize\n" }, { "code": null, "e": 25547, "s": 25524, "text": "object.style.fontSize\n" }, { "code": null, "e": 25626, "s": 25547, "text": "It sets the fontSize Property.object.style.fontSize = \"value|initial|inherit\"\n" }, { "code": null, "e": 25675, "s": 25626, "text": "object.style.fontSize = \"value|initial|inherit\"\n" }, { "code": null, "e": 25692, "s": 25675, "text": "Property Values:" }, { "code": null, "e": 25755, "s": 25692, "text": "Return value: It returns the font size of the text of element." }, { "code": null, "e": 25795, "s": 25755, "text": "Example-1: Change font size into small." }, { "code": "<!DOCTYPE html><html> <head> <title>DOM Style fontSize Property </title></head> <body> <center> <p style=\"color: green; width: 100%; font-size: 30px; font-weight: bold;\" id=\"Geek1\"> GeeksForGeeks </p> <h2>DOM Style fontSize Property </h2> <br> <button type=\"button\" onclick=\"myGeeks()\"> Click to change </button> <script> function myGeeks() { // Change font size in to small. document.getElementById( \"Geek1\").style.fontSize = \"small\"; } </script> </center></body> </html>", "e": 26526, "s": 25795, "text": null }, { "code": null, "e": 26534, "s": 26526, "text": "Output:" }, { "code": null, "e": 26558, "s": 26534, "text": "Before click on button:" }, { "code": null, "e": 26581, "s": 26558, "text": "After click on button:" }, { "code": null, "e": 26624, "s": 26581, "text": "Example-2: Change font-size into xx-large." }, { "code": "<!DOCTYPE html><html> <head> <title>DOM Style fontSize Property </title></head> <body> <center> <p style=\"color: green; width: 100%; font-size: 10px; font-weight: bold;\" id=\"Geek1\"> GeeksForGeeks </p> <h2>DOM Style fontSize Property </h2> <br> <button type=\"button\" onclick=\"myGeeks()\"> Click to change </button> <script> function myGeeks() { // change into xx-large. document.getElementById( \"Geek1\").style.fontSize = \"xx-large\"; } </script> </center></body> </html>", "e": 27337, "s": 26624, "text": null }, { "code": null, "e": 27345, "s": 27337, "text": "Output:" }, { "code": null, "e": 27369, "s": 27345, "text": "Before click on button:" }, { "code": null, "e": 27392, "s": 27369, "text": "After click on button:" }, { "code": null, "e": 27439, "s": 27392, "text": "Example-3: Change font-size using length unit." }, { "code": "<!DOCTYPE html><html> <head> <title>DOM Style fontSize Property </title></head> <body> <center> <p style=\"color: green; width: 100%; font-size: 10px; font-weight: bold;\" id=\"Geek1\"> GeeksForGeeks </p> <h2>DOM Style fontSize Property </h2> <br> <button type=\"button\" onclick=\"myGeeks()\"> Click to change </button> <script> function myGeeks() { // Change font size from // from 10px to 30px document.getElementById( \"Geek1\").style.fontSize = \"30px\"; } </script> </center></body> </html>", "e": 28183, "s": 27439, "text": null }, { "code": null, "e": 28191, "s": 28183, "text": "Output:" }, { "code": null, "e": 28215, "s": 28191, "text": "Before click on button:" }, { "code": null, "e": 28238, "s": 28215, "text": "After click on button:" }, { "code": null, "e": 28276, "s": 28238, "text": "Example-4: Change font-size using ‘%’" }, { "code": "<!DOCTYPE html><html> <head> <title>DOM Style fontSize Property </title></head> <body> <center> <p style=\"color: green; width: 100%; font-size: 10px; font-weight: bold;\" id=\"Geek1\"> GeeksForGeeks </p> <h2>DOM Style fontSize Property </h2> <br> <button type=\"button\" onclick=\"myGeeks()\"> Click to change </button> <script> function myGeeks() { // Change font-size from 100% to 200% document.getElementById( \"Geek1\").style.fontSize = \"200%\"; } </script> </center></body> </html>", "e": 28996, "s": 28276, "text": null }, { "code": null, "e": 29004, "s": 28996, "text": "Output:" }, { "code": null, "e": 29027, "s": 29004, "text": "Before click on button" }, { "code": null, "e": 29049, "s": 29027, "text": "After click on button" }, { "code": null, "e": 29147, "s": 29049, "text": "Supported Browsers: The browser supported by HTML | DOM Style fontSize Property are listed below:" }, { "code": null, "e": 29161, "s": 29147, "text": "Google Chrome" }, { "code": null, "e": 29179, "s": 29161, "text": "Internet Explorer" }, { "code": null, "e": 29195, "s": 29179, "text": "Mozilla firefox" }, { "code": null, "e": 29201, "s": 29195, "text": "Opera" }, { "code": null, "e": 29208, "s": 29201, "text": "Safari" }, { "code": null, "e": 29345, "s": 29208, "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": 29354, "s": 29345, "text": "HTML-DOM" }, { "code": null, "e": 29368, "s": 29354, "text": "HTML-Property" }, { "code": null, "e": 29375, "s": 29368, "text": "Picked" }, { "code": null, "e": 29380, "s": 29375, "text": "HTML" }, { "code": null, "e": 29397, "s": 29380, "text": "Web Technologies" }, { "code": null, "e": 29402, "s": 29397, "text": "HTML" }, { "code": null, "e": 29500, "s": 29402, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29550, "s": 29500, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 29612, "s": 29550, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 29660, "s": 29612, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 29720, "s": 29660, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 29773, "s": 29720, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 29813, "s": 29773, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 29846, "s": 29813, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 29891, "s": 29846, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 29934, "s": 29891, "text": "How to fetch data from an API in ReactJS ?" } ]
How do I get time of a Python program's execution?
To measure time time of a program's execution, either use time.clock() or time.time() functions. The python docs state that this function should be used for benchmarking purposes. import time t0= time.clock() print("Hello") t1 = time.clock() - t0 print("Time elapsed: ", t1 - t0) # CPU seconds elapsed (floating point) This will give the output − Time elapsed: 0.0009403145040156798 You can also use the timeit module to get proper statistical analysis of a code snippet's execution time. It runs the snippet multiple times and then it tells you how long the shortest run took. You can use it as follows − def f(x): return x * x import timeit timeit.repeat("for x in range(100): f(x)", "from __main__ import f", number=100000) This will give the output − [2.0640320777893066, 2.0876040458679199, 2.0520210266113281]
[ { "code": null, "e": 1243, "s": 1062, "text": "To measure time time of a program's execution, either use time.clock() or time.time() functions. The python docs state that this function should be used for benchmarking purposes. " }, { "code": null, "e": 1382, "s": 1243, "text": "import time\nt0= time.clock()\nprint(\"Hello\")\nt1 = time.clock() - t0\nprint(\"Time elapsed: \", t1 - t0) # CPU seconds elapsed (floating point)" }, { "code": null, "e": 1410, "s": 1382, "text": "This will give the output −" }, { "code": null, "e": 1447, "s": 1410, "text": "Time elapsed: 0.0009403145040156798" }, { "code": null, "e": 1671, "s": 1447, "text": "You can also use the timeit module to get proper statistical analysis of a code snippet's execution time. It runs the snippet multiple times and then it tells you how long the shortest run took. You can use it as follows −" }, { "code": null, "e": 1796, "s": 1671, "text": "def f(x):\n return x * x\n \nimport timeit\ntimeit.repeat(\"for x in range(100): f(x)\", \"from __main__ import f\", number=100000)" }, { "code": null, "e": 1824, "s": 1796, "text": "This will give the output −" }, { "code": null, "e": 1885, "s": 1824, "text": "[2.0640320777893066, 2.0876040458679199, 2.0520210266113281]" } ]
How to write a JavaScript function to get the difference between two numbers?
Use Math.abs() inside a JavaScript function to get the difference between two numbers in JavaScript. You can try to run the following code to get the difference of numbers Live Demo <html> <head> <script> var num1, num2; num1 = 50; num2 = 35; var difference = function (num1, num2){ return Math.abs(num1 - num2); } document.write("Difference = "+difference(num1,num2)); </script> </head> <body></body> </html>
[ { "code": null, "e": 1163, "s": 1062, "text": "Use Math.abs() inside a JavaScript function to get the difference between two numbers in JavaScript." }, { "code": null, "e": 1234, "s": 1163, "text": "You can try to run the following code to get the difference of numbers" }, { "code": null, "e": 1244, "s": 1234, "text": "Live Demo" }, { "code": null, "e": 1559, "s": 1244, "text": "<html>\n <head>\n <script>\n var num1, num2;\n num1 = 50;\n num2 = 35;\n var difference = function (num1, num2){\n return Math.abs(num1 - num2);\n }\n document.write(\"Difference = \"+difference(num1,num2));\n </script>\n </head>\n <body></body>\n</html>" } ]
Build Fuel Price Tracker Using Python - GeeksforGeeks
31 Mar, 2022 In this modern-day lifestyle, fuel has become a necessity for all human beings. It is a base for our life-style. So, we are going to write a script to track their price using Python. Modules Needed bs4: Beautiful Soup(bs4) is a Python library for pulling data out of HTML and XML files. This module does not come built-in with Python. To install this type the below command in the terminal. pip install bs4 requests: Request allows you to send HTTP/1.1 requests extremely easily. This module also does not come built-in with Python. To install this type the below command in the terminal. pip install requests Let’s see the stepwise execution of the script Step 1: Import all dependence Python3 # import moduleimport pandas as pdimport requestsfrom bs4 import BeautifulSoup Step 2: Create a URL get function Python3 # user define function# Scrape the datadef getdata(url): r = requests.get(url) return r.text Step 3: Now pass the URL into the getdata() function and Convert that data into HTML code Python3 # link for extract html datahtmldata = getdata("https://www.goodreturns.in/petrol-price.html")soup = BeautifulSoup(htmldata, 'html.parser')result = soup.find_all("div", class_="gold_silver_table")print(result) Output : [<div class=”gold_silver_table”> <table border=”0′′ cellpadding=”1′′ cellspacing=”1′′ width=”100%”> <tr class=”first”> <td class=”heading” width=”200′′>City</td> <td class=”heading” width=”200′′>Today Price</td> <td class=”heading” width=”200′′>Yesterday’s Price</td> </tr> <tr class=”even_row”> <td><a href=”/petrol-price-in-new-delhi.html” title=”New Delhi”>New Delhi</a></td> <td> ₹ 82.08</td> <td> ₹ 82.03</td> </tr> <tr class=”odd_row”> <td><a href=”/petrol-price-in-kolkata.html” title=”Kolkata”>Kolkata</a></td> <td> ₹ 83.57</td> <td> ₹ 83.52</td> </tr> <tr class=”even_row”> <td><a href=”/petrol-price-in-mumbai.html” title=”Mumbai”>Mumbai</a></td> <td> ₹ 88.73</td> <td> ₹ 88.68</td> </tr> <tr class=”odd_row”> <td><a href=”/petrol-price-in-chennai.html” title=”Chennai”>Chennai</a></td> <td> ₹ 85.04</td> <td> ₹ 85.00</td> </tr> <tr class=”even_row”> <td><a href=”/petrol-price-in-gurgaon.html” title=”Gurgaon”>Gurgaon</a></td> <td> ₹ 79.92</td> <td> ₹ 79.84</td> </tr> <tr class=”odd_row”> <td><a href=”/petrol-price-in-noida.html” title=”Noida”>Noida</a></td> <td> ₹ 82.23</td> <td> ₹ 82.30</td> </tr> <tr class=”even_row”> <td><a href=”/petrol-price-in-bangalore.html” title=”Bangalore”>Bangalore</a></td> <td> ₹ 84.75</td> <td> ₹ 84.70</td> </tr> <tr class=”odd_row”> <td><a href=”/petrol-price-in-bhubaneswar.html” title=”Bhubaneswar”>Bhubaneswar</a></td> <td> ₹ 82.47</td> <td> ₹ 82.59</td> </tr> <tr class=”even_row”> <td><a href=”/petrol-price-in-chandigarh.html” title=”Chandigarh”>Chandigarh</a></td> <td> ₹ 78.96</td> <td> ₹ 78.92</td> </tr> <tr class=”odd_row”> <td><a href=”/petrol-price-in-hyderabad.html” title=”Hyderabad”>Hyderabad</a></td> <td> ₹ 85.30</td> <td> ₹ 85.25</td> </tr> <tr class=”even_row”> <td><a href=”/petrol-price-in-jaipur.html” title=”Jaipur”>Jaipur</a></td> <td> ₹ 90.08</td> <td> ₹ 89.24</td> </tr> <tr class=”odd_row”> <td><a href=”/petrol-price-in-lucknow.html” title=”Lucknow”>Lucknow</a></td> <td> ₹ 82.20</td> <td> ₹ 82.09</td> </tr> <tr class=”even_row”> <td><a href=”/petrol-price-in-patna.html” title=”Patna”>Patna</a></td> <td> ₹ 84.73</td> <td> ₹ 84.88</td> </tr> <tr class=”odd_row”> <td><a href=”/petrol-price-in-trivandrum.html” title=”Trivandrum”>Trivandrum</a></td> <td> ₹ 83.91</td> <td> ₹ 84.03</td> </tr> </table> </div>] Note: These scripts will give you only Raw data in String format you have to print your data with your needs. Step 4: Now, Search your needed data into sting with soup.find_all(). Python3 # Declare string var# Declare listmydatastr = ''result = [] # searching all tr in the html data# storing as a stringfor table in soup.find_all('tr'): mydatastr += table.get_text() # set according to your requiredmydatastr = mydatastr[1:]itemlist = mydatastr.split("\n\n") for item in itemlist[:-5]: result.append(item.split("\n")) result Output : Step 4: Make a DataFrame for displaying your result. Python3 # Calling DataFrame constructor on listdf = pd.DataFrame(result[:-8])df Complete code: Python3 # import moduleimport requestsimport pandas as pdfrom bs4 import BeautifulSoup # link for extract html data def getdata(url): r = requests.get(url) return r.text htmldata = getdata("https://www.goodreturns.in/petrol-price.html")soup = BeautifulSoup(htmldata, 'html.parser') # Declare string var# Declare listmydatastr = ''result = [] # searching all tr in the html data# storing as a stringfor table in soup.find_all('tr'): mydatastr += table.get_text() # set according to your requiredmydatastr = mydatastr[1:]itemlist = mydatastr.split("\n\n") for item in itemlist[:-5]: result.append(item.split("\n")) # Calling DataFrame constructor on listdf = pd.DataFrame(result[:-8])df Output : simmytarika5 Python web-scraping-exercises Python-pandas Python-requests python-utility Web-scraping Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? How To Convert Python Dictionary To JSON? Check if element exists in list in Python How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | os.path.join() method Create a directory in Python Defaultdict in Python Python | Pandas dataframe.groupby() Python | Get unique values from a list
[ { "code": null, "e": 25647, "s": 25619, "text": "\n31 Mar, 2022" }, { "code": null, "e": 25830, "s": 25647, "text": "In this modern-day lifestyle, fuel has become a necessity for all human beings. It is a base for our life-style. So, we are going to write a script to track their price using Python." }, { "code": null, "e": 25845, "s": 25830, "text": "Modules Needed" }, { "code": null, "e": 26038, "s": 25845, "text": "bs4: Beautiful Soup(bs4) is a Python library for pulling data out of HTML and XML files. This module does not come built-in with Python. To install this type the below command in the terminal." }, { "code": null, "e": 26054, "s": 26038, "text": "pip install bs4" }, { "code": null, "e": 26236, "s": 26054, "text": "requests: Request allows you to send HTTP/1.1 requests extremely easily. This module also does not come built-in with Python. To install this type the below command in the terminal." }, { "code": null, "e": 26257, "s": 26236, "text": "pip install requests" }, { "code": null, "e": 26304, "s": 26257, "text": "Let’s see the stepwise execution of the script" }, { "code": null, "e": 26334, "s": 26304, "text": "Step 1: Import all dependence" }, { "code": null, "e": 26342, "s": 26334, "text": "Python3" }, { "code": "# import moduleimport pandas as pdimport requestsfrom bs4 import BeautifulSoup", "e": 26421, "s": 26342, "text": null }, { "code": null, "e": 26455, "s": 26421, "text": "Step 2: Create a URL get function" }, { "code": null, "e": 26463, "s": 26455, "text": "Python3" }, { "code": "# user define function# Scrape the datadef getdata(url): r = requests.get(url) return r.text", "e": 26562, "s": 26463, "text": null }, { "code": null, "e": 26652, "s": 26562, "text": "Step 3: Now pass the URL into the getdata() function and Convert that data into HTML code" }, { "code": null, "e": 26660, "s": 26652, "text": "Python3" }, { "code": "# link for extract html datahtmldata = getdata(\"https://www.goodreturns.in/petrol-price.html\")soup = BeautifulSoup(htmldata, 'html.parser')result = soup.find_all(\"div\", class_=\"gold_silver_table\")print(result)", "e": 26870, "s": 26660, "text": null }, { "code": null, "e": 26879, "s": 26870, "text": "Output :" }, { "code": null, "e": 29167, "s": 26879, "text": "[<div class=”gold_silver_table”> <table border=”0′′ cellpadding=”1′′ cellspacing=”1′′ width=”100%”> <tr class=”first”> <td class=”heading” width=”200′′>City</td> <td class=”heading” width=”200′′>Today Price</td> <td class=”heading” width=”200′′>Yesterday’s Price</td> </tr> <tr class=”even_row”> <td><a href=”/petrol-price-in-new-delhi.html” title=”New Delhi”>New Delhi</a></td> <td> ₹ 82.08</td> <td> ₹ 82.03</td> </tr> <tr class=”odd_row”> <td><a href=”/petrol-price-in-kolkata.html” title=”Kolkata”>Kolkata</a></td> <td> ₹ 83.57</td> <td> ₹ 83.52</td> </tr> <tr class=”even_row”> <td><a href=”/petrol-price-in-mumbai.html” title=”Mumbai”>Mumbai</a></td> <td> ₹ 88.73</td> <td> ₹ 88.68</td> </tr> <tr class=”odd_row”> <td><a href=”/petrol-price-in-chennai.html” title=”Chennai”>Chennai</a></td> <td> ₹ 85.04</td> <td> ₹ 85.00</td> </tr> <tr class=”even_row”> <td><a href=”/petrol-price-in-gurgaon.html” title=”Gurgaon”>Gurgaon</a></td> <td> ₹ 79.92</td> <td> ₹ 79.84</td> </tr> <tr class=”odd_row”> <td><a href=”/petrol-price-in-noida.html” title=”Noida”>Noida</a></td> <td> ₹ 82.23</td> <td> ₹ 82.30</td> </tr> <tr class=”even_row”> <td><a href=”/petrol-price-in-bangalore.html” title=”Bangalore”>Bangalore</a></td> <td> ₹ 84.75</td> <td> ₹ 84.70</td> </tr> <tr class=”odd_row”> <td><a href=”/petrol-price-in-bhubaneswar.html” title=”Bhubaneswar”>Bhubaneswar</a></td> <td> ₹ 82.47</td> <td> ₹ 82.59</td> </tr> <tr class=”even_row”> <td><a href=”/petrol-price-in-chandigarh.html” title=”Chandigarh”>Chandigarh</a></td> <td> ₹ 78.96</td> <td> ₹ 78.92</td> </tr> <tr class=”odd_row”> <td><a href=”/petrol-price-in-hyderabad.html” title=”Hyderabad”>Hyderabad</a></td> <td> ₹ 85.30</td> <td> ₹ 85.25</td> </tr> <tr class=”even_row”> <td><a href=”/petrol-price-in-jaipur.html” title=”Jaipur”>Jaipur</a></td> <td> ₹ 90.08</td> <td> ₹ 89.24</td> </tr> <tr class=”odd_row”> <td><a href=”/petrol-price-in-lucknow.html” title=”Lucknow”>Lucknow</a></td> <td> ₹ 82.20</td> <td> ₹ 82.09</td> </tr> <tr class=”even_row”> <td><a href=”/petrol-price-in-patna.html” title=”Patna”>Patna</a></td> <td> ₹ 84.73</td> <td> ₹ 84.88</td> </tr> <tr class=”odd_row”> <td><a href=”/petrol-price-in-trivandrum.html” title=”Trivandrum”>Trivandrum</a></td> <td> ₹ 83.91</td> <td> ₹ 84.03</td> </tr> </table> </div>]" }, { "code": null, "e": 29278, "s": 29167, "text": "Note: These scripts will give you only Raw data in String format you have to print your data with your needs. " }, { "code": null, "e": 29348, "s": 29278, "text": "Step 4: Now, Search your needed data into sting with soup.find_all()." }, { "code": null, "e": 29356, "s": 29348, "text": "Python3" }, { "code": "# Declare string var# Declare listmydatastr = ''result = [] # searching all tr in the html data# storing as a stringfor table in soup.find_all('tr'): mydatastr += table.get_text() # set according to your requiredmydatastr = mydatastr[1:]itemlist = mydatastr.split(\"\\n\\n\") for item in itemlist[:-5]: result.append(item.split(\"\\n\")) result", "e": 29700, "s": 29356, "text": null }, { "code": null, "e": 29709, "s": 29700, "text": "Output :" }, { "code": null, "e": 29762, "s": 29709, "text": "Step 4: Make a DataFrame for displaying your result." }, { "code": null, "e": 29770, "s": 29762, "text": "Python3" }, { "code": "# Calling DataFrame constructor on listdf = pd.DataFrame(result[:-8])df", "e": 29842, "s": 29770, "text": null }, { "code": null, "e": 29857, "s": 29842, "text": "Complete code:" }, { "code": null, "e": 29865, "s": 29857, "text": "Python3" }, { "code": "# import moduleimport requestsimport pandas as pdfrom bs4 import BeautifulSoup # link for extract html data def getdata(url): r = requests.get(url) return r.text htmldata = getdata(\"https://www.goodreturns.in/petrol-price.html\")soup = BeautifulSoup(htmldata, 'html.parser') # Declare string var# Declare listmydatastr = ''result = [] # searching all tr in the html data# storing as a stringfor table in soup.find_all('tr'): mydatastr += table.get_text() # set according to your requiredmydatastr = mydatastr[1:]itemlist = mydatastr.split(\"\\n\\n\") for item in itemlist[:-5]: result.append(item.split(\"\\n\")) # Calling DataFrame constructor on listdf = pd.DataFrame(result[:-8])df", "e": 30556, "s": 29865, "text": null }, { "code": null, "e": 30565, "s": 30556, "text": "Output :" }, { "code": null, "e": 30578, "s": 30565, "text": "simmytarika5" }, { "code": null, "e": 30608, "s": 30578, "text": "Python web-scraping-exercises" }, { "code": null, "e": 30622, "s": 30608, "text": "Python-pandas" }, { "code": null, "e": 30638, "s": 30622, "text": "Python-requests" }, { "code": null, "e": 30653, "s": 30638, "text": "python-utility" }, { "code": null, "e": 30666, "s": 30653, "text": "Web-scraping" }, { "code": null, "e": 30673, "s": 30666, "text": "Python" }, { "code": null, "e": 30771, "s": 30673, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30803, "s": 30771, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 30845, "s": 30803, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 30887, "s": 30845, "text": "Check if element exists in list in Python" }, { "code": null, "e": 30943, "s": 30887, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 30970, "s": 30943, "text": "Python Classes and Objects" }, { "code": null, "e": 31001, "s": 30970, "text": "Python | os.path.join() method" }, { "code": null, "e": 31030, "s": 31001, "text": "Create a directory in Python" }, { "code": null, "e": 31052, "s": 31030, "text": "Defaultdict in Python" }, { "code": null, "e": 31088, "s": 31052, "text": "Python | Pandas dataframe.groupby()" } ]
What is a fat arrow function in JavaScript?
Fat arrow function as the name suggests helps in decreasing line of code. The syntax => shows fat arrow. This also avoids you to write the keyword “function” repeatedly. Here’s the syntax: argument => expression Use the following for more than one argument: (argument1 [, argument2]) => expression Let’s compare a function with and without fat arrow: Function in JavaScript var rank = [7,8,9]; var display = rank.map(function(num) { return num * num; }); Fat Arrow function in JavaScript var rank= [7,8,9]; var display = rank.map((num) => num*num); document.write(arr) Arrow function definitely reduces the code lines.
[ { "code": null, "e": 1232, "s": 1062, "text": "Fat arrow function as the name suggests helps in decreasing line of code. The syntax => shows fat arrow. This also avoids you to write the keyword “function” repeatedly." }, { "code": null, "e": 1251, "s": 1232, "text": "Here’s the syntax:" }, { "code": null, "e": 1274, "s": 1251, "text": "argument => expression" }, { "code": null, "e": 1320, "s": 1274, "text": "Use the following for more than one argument:" }, { "code": null, "e": 1360, "s": 1320, "text": "(argument1 [, argument2]) => expression" }, { "code": null, "e": 1413, "s": 1360, "text": "Let’s compare a function with and without fat arrow:" }, { "code": null, "e": 1436, "s": 1413, "text": "Function in JavaScript" }, { "code": null, "e": 1520, "s": 1436, "text": "var rank = [7,8,9];\nvar display = rank.map(function(num) {\n return num * num;\n});" }, { "code": null, "e": 1553, "s": 1520, "text": "Fat Arrow function in JavaScript" }, { "code": null, "e": 1634, "s": 1553, "text": "var rank= [7,8,9];\nvar display = rank.map((num) => num*num);\ndocument.write(arr)" }, { "code": null, "e": 1684, "s": 1634, "text": "Arrow function definitely reduces the code lines." } ]
Exit a loop in C++ - GeeksforGeeks
20 Jan, 2021 Exit a Loop in C++: If the condition of an iteration statement (for, while, or do-while statement) is omitted, that loop will not terminate unless the user explicitly exits it by a break, continue, goto, or some less obvious way such as a call of exit() in C++. Break: This statement is a loop control statement used to terminate the loop. Below is the C++ program to illustrate the use of the break statement: C++ // C++ program to illustrate the use// of the break statement#include <iostream>using namespace std; // Function to illustrate the use// of break statementvoid useOfBreak(){ for (int i = 0; i < 40; i++) { cout << "Value of i: " << i << endl; // If the value of i is // equal to 2 terminate // the loop if (i == 2) { break; } }} // Driver Codeint main(){ // Function Call useOfBreak(); return 0;} Value of i: 0 Value of i: 1 Value of i: 2 Explanation: In the above code, the loop terminates after i=2 and prints the values of i before 2 i.e. from 0 to 2. Continue: The continue statement is used to get to the end of the loop body rather than exiting the loop completely. It skips the rest of the body of an iteration-statement. The main difference between break and continue is that, the break statement entirely terminates the loop, but the continue statement only terminates the current iteration. Below is the C++ program to illustrate the use of the continue statement: C++ // C++ program to illustrate the// use of the continue statement #include <iostream>using namespace std; // Function to illustrate the use// of continue statementvoid useOfContinue(){ for (int i = 0; i < 5; i++) { // If the value of i is the // same as 2 it will terminate // only the current iteration if (i == 2) { continue; } cout << "The Value of i: " << i << endl; }} // Driver Codeint main(){ // Function Call useOfContinue(); return 0;} The Value of i: 0 The Value of i: 1 The Value of i: 3 The Value of i: 4 Explanation: In the above code, the loop terminates the iteration for i=2 and prints the values of i before and after 2. Hence, it only terminates the given iteration rather than the loop. goto: This statement is an unconditional jump statement used for transferring the control of a program. It allows the program’s execution flow to jump to a specified location within the function. The only restriction is that you cannot jump past an initialize or into an exception handler. Below is the C++ program to illustrate the use of the goto statement: C++ // C++ program to illustrate the use// of goto statement#include <iostream>using namespace std; // Function to illustrate the use// of goto statementvoid useOfGoto(){ // Local variable declaration int i = 1; // Do-while loop executionLOOP: do { if (i == 2) { // Skips the iteration i = i + 1; goto LOOP; } cout << "value of i: " << i << endl; i = i + 1; } while (i < 5);} // Driver Codeint main(){ // Function call useOfGoto(); return 0;} value of i: 1 value of i: 3 value of i: 4 Explanation: In the above code, it jumps to the given location i.e., LOOP, within the function. loop Loops & Control Structure C++ C++ Programs CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Iterators in C++ STL Operator Overloading in C++ Polymorphism in C++ Destructors in C++ Friend class and function in C++ Header files in C/C++ and its uses How to return multiple values from a function in C or C++? C++ Program for QuickSort C++ program for hashing with chaining delete keyword in C++
[ { "code": null, "e": 23733, "s": 23705, "text": "\n20 Jan, 2021" }, { "code": null, "e": 23995, "s": 23733, "text": "Exit a Loop in C++: If the condition of an iteration statement (for, while, or do-while statement) is omitted, that loop will not terminate unless the user explicitly exits it by a break, continue, goto, or some less obvious way such as a call of exit() in C++." }, { "code": null, "e": 24144, "s": 23995, "text": "Break: This statement is a loop control statement used to terminate the loop. Below is the C++ program to illustrate the use of the break statement:" }, { "code": null, "e": 24148, "s": 24144, "text": "C++" }, { "code": "// C++ program to illustrate the use// of the break statement#include <iostream>using namespace std; // Function to illustrate the use// of break statementvoid useOfBreak(){ for (int i = 0; i < 40; i++) { cout << \"Value of i: \" << i << endl; // If the value of i is // equal to 2 terminate // the loop if (i == 2) { break; } }} // Driver Codeint main(){ // Function Call useOfBreak(); return 0;}", "e": 24634, "s": 24148, "text": null }, { "code": null, "e": 24677, "s": 24634, "text": "Value of i: 0\nValue of i: 1\nValue of i: 2\n" }, { "code": null, "e": 24793, "s": 24677, "text": "Explanation: In the above code, the loop terminates after i=2 and prints the values of i before 2 i.e. from 0 to 2." }, { "code": null, "e": 25139, "s": 24793, "text": "Continue: The continue statement is used to get to the end of the loop body rather than exiting the loop completely. It skips the rest of the body of an iteration-statement. The main difference between break and continue is that, the break statement entirely terminates the loop, but the continue statement only terminates the current iteration." }, { "code": null, "e": 25213, "s": 25139, "text": "Below is the C++ program to illustrate the use of the continue statement:" }, { "code": null, "e": 25217, "s": 25213, "text": "C++" }, { "code": "// C++ program to illustrate the// use of the continue statement #include <iostream>using namespace std; // Function to illustrate the use// of continue statementvoid useOfContinue(){ for (int i = 0; i < 5; i++) { // If the value of i is the // same as 2 it will terminate // only the current iteration if (i == 2) { continue; } cout << \"The Value of i: \" << i << endl; }} // Driver Codeint main(){ // Function Call useOfContinue(); return 0;}", "e": 25750, "s": 25217, "text": null }, { "code": null, "e": 25823, "s": 25750, "text": "The Value of i: 0\nThe Value of i: 1\nThe Value of i: 3\nThe Value of i: 4\n" }, { "code": null, "e": 26012, "s": 25823, "text": "Explanation: In the above code, the loop terminates the iteration for i=2 and prints the values of i before and after 2. Hence, it only terminates the given iteration rather than the loop." }, { "code": null, "e": 26302, "s": 26012, "text": "goto: This statement is an unconditional jump statement used for transferring the control of a program. It allows the program’s execution flow to jump to a specified location within the function. The only restriction is that you cannot jump past an initialize or into an exception handler." }, { "code": null, "e": 26372, "s": 26302, "text": "Below is the C++ program to illustrate the use of the goto statement:" }, { "code": null, "e": 26376, "s": 26372, "text": "C++" }, { "code": "// C++ program to illustrate the use// of goto statement#include <iostream>using namespace std; // Function to illustrate the use// of goto statementvoid useOfGoto(){ // Local variable declaration int i = 1; // Do-while loop executionLOOP: do { if (i == 2) { // Skips the iteration i = i + 1; goto LOOP; } cout << \"value of i: \" << i << endl; i = i + 1; } while (i < 5);} // Driver Codeint main(){ // Function call useOfGoto(); return 0;}", "e": 26922, "s": 26376, "text": null }, { "code": null, "e": 26965, "s": 26922, "text": "value of i: 1\nvalue of i: 3\nvalue of i: 4\n" }, { "code": null, "e": 27061, "s": 26965, "text": "Explanation: In the above code, it jumps to the given location i.e., LOOP, within the function." }, { "code": null, "e": 27066, "s": 27061, "text": "loop" }, { "code": null, "e": 27092, "s": 27066, "text": "Loops & Control Structure" }, { "code": null, "e": 27096, "s": 27092, "text": "C++" }, { "code": null, "e": 27109, "s": 27096, "text": "C++ Programs" }, { "code": null, "e": 27113, "s": 27109, "text": "CPP" }, { "code": null, "e": 27211, "s": 27113, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27220, "s": 27211, "text": "Comments" }, { "code": null, "e": 27233, "s": 27220, "text": "Old Comments" }, { "code": null, "e": 27254, "s": 27233, "text": "Iterators in C++ STL" }, { "code": null, "e": 27282, "s": 27254, "text": "Operator Overloading in C++" }, { "code": null, "e": 27302, "s": 27282, "text": "Polymorphism in C++" }, { "code": null, "e": 27321, "s": 27302, "text": "Destructors in C++" }, { "code": null, "e": 27354, "s": 27321, "text": "Friend class and function in C++" }, { "code": null, "e": 27389, "s": 27354, "text": "Header files in C/C++ and its uses" }, { "code": null, "e": 27448, "s": 27389, "text": "How to return multiple values from a function in C or C++?" }, { "code": null, "e": 27474, "s": 27448, "text": "C++ Program for QuickSort" }, { "code": null, "e": 27512, "s": 27474, "text": "C++ program for hashing with chaining" } ]
Draw an ellipse using OpenCV in C++ - GeeksforGeeks
22 Feb, 2021 In this article, the task is to draw an ellipse using OpenCV in C++. The ellipse() function from OpenCV C++ library will be used. Syntax: ellipse(image, centerCoordinates, axesLength, angle, startAngle, endAngle, color, thickness, lineType, shift) Parameters: image: It is the image on which ellipse is to be drawn. centerCoordinates: Coordinates of the center of the ellipse. (Tuple of two coordinates (X-coordinate, Y-coordinate)) axesLength:Tuple containing the major and minor axis of the ellipse (major axis length, minor axis length). angle: Ellipse rotation angle in degrees. startAngle: Starting angle of the elliptic arc(degrees). endAngle: Ending angle of the elliptic arc(degrees). color: It is the color of the borderline of the ellipse to be drawn. A tuple representing 3 colors (B, G, R) i.e., (Blue, Green, Red). thickness: It is the thickness of the ellipse borderline in px. The thickness of -1 px will fill the ellipse shape by the specified color. lineType: Type of the line. There are 3 types of line:LINE_4: Line was drawn using 4 connected Bresenham algorithm.LINE_8: Line was drawn using 8 connected Bresenham algorithm.LINE_AA: It draws Anti-aliased lines formed by using a Gaussian filter. LINE_4: Line was drawn using 4 connected Bresenham algorithm. LINE_8: Line was drawn using 8 connected Bresenham algorithm. LINE_AA: It draws Anti-aliased lines formed by using a Gaussian filter. shift: Number of fractional bits in the point coordinates. Return Value: It returns an image. Program 1: Below is the C++ program demonstrating how to draw an ellipse over a self-formed background image: C++ // C++ program to demonstrating ellipse// over a self-formed background image#include <iostream>#include <opencv2/core/core.hpp> // Drawing shapes#include <opencv2/imgproc.hpp> #include <opencv2/highgui/highgui.hpp>using namespace cv;using namespace std; // Driver Codeint main(int argc, char** argv){ // Creating a blank image with // white background Mat image(500, 500, CV_8UC3, Scalar(255, 255, 255)); // Check if the image is created // successfully or not if (!image.data) { std::cout << "Could not open or " << "find the image\n"; return 0; } // Drawing the ellipse ellipse(image, Point(256, 256), Size(100, 50), 0, 0, 360, Scalar(0, 255, 255), -1, LINE_AA); // Showing image inside a window imshow("Output", image); waitKey(0); return 0;} Output: Explanation: In the above program, an ellipse is drawn at an angle of 0 degrees i.e., horizontal ellipse. Program 2: Below is the C++ program illustrate rectangle over a loaded image with an ellipse around the GFG logo: C++ // C++ program to demonstrate rectangle// over a loaded image with an ellipse// around the GFG logo#include <iostream>#include <opencv2/core/core.hpp> // Drawing shapes#include <opencv2/imgproc.hpp> #include <opencv2/highgui/highgui.hpp>using namespace cv;using namespace std; // Driver Codeint main(int argc, char** argv){ // Reading the Image Mat image = imread("C:/Users/harsh/Downloads/geeks.png", IMREAD_COLOR); // Check if the image is created // successfully or not if (!image.data) { std::cout << "Could not open or " << "find the image\n"; return 0; } // Drawing the ellipse ellipse(image, Point(115, 110), Size(105, 55), 0, 0, 360, Scalar(0, 255, 255), 1, LINE_AA); // Show our image inside a window imshow("Output", image); waitKey(0); return 0;} Output: computer-graphics OpenCV C++ C++ Programs 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) Header files in C/C++ and its uses C++ Program for QuickSort How to return multiple values from a function in C or C++? Program to print ASCII Value of a character C++ program for hashing with chaining
[ { "code": null, "e": 23731, "s": 23703, "text": "\n22 Feb, 2021" }, { "code": null, "e": 23861, "s": 23731, "text": "In this article, the task is to draw an ellipse using OpenCV in C++. The ellipse() function from OpenCV C++ library will be used." }, { "code": null, "e": 23869, "s": 23861, "text": "Syntax:" }, { "code": null, "e": 23979, "s": 23869, "text": "ellipse(image, centerCoordinates, axesLength, angle, startAngle, endAngle, color, thickness, lineType, shift)" }, { "code": null, "e": 23991, "s": 23979, "text": "Parameters:" }, { "code": null, "e": 24047, "s": 23991, "text": "image: It is the image on which ellipse is to be drawn." }, { "code": null, "e": 24164, "s": 24047, "text": "centerCoordinates: Coordinates of the center of the ellipse. (Tuple of two coordinates (X-coordinate, Y-coordinate))" }, { "code": null, "e": 24272, "s": 24164, "text": "axesLength:Tuple containing the major and minor axis of the ellipse (major axis length, minor axis length)." }, { "code": null, "e": 24314, "s": 24272, "text": "angle: Ellipse rotation angle in degrees." }, { "code": null, "e": 24371, "s": 24314, "text": "startAngle: Starting angle of the elliptic arc(degrees)." }, { "code": null, "e": 24424, "s": 24371, "text": "endAngle: Ending angle of the elliptic arc(degrees)." }, { "code": null, "e": 24559, "s": 24424, "text": "color: It is the color of the borderline of the ellipse to be drawn. A tuple representing 3 colors (B, G, R) i.e., (Blue, Green, Red)." }, { "code": null, "e": 24698, "s": 24559, "text": "thickness: It is the thickness of the ellipse borderline in px. The thickness of -1 px will fill the ellipse shape by the specified color." }, { "code": null, "e": 24946, "s": 24698, "text": "lineType: Type of the line. There are 3 types of line:LINE_4: Line was drawn using 4 connected Bresenham algorithm.LINE_8: Line was drawn using 8 connected Bresenham algorithm.LINE_AA: It draws Anti-aliased lines formed by using a Gaussian filter." }, { "code": null, "e": 25008, "s": 24946, "text": "LINE_4: Line was drawn using 4 connected Bresenham algorithm." }, { "code": null, "e": 25070, "s": 25008, "text": "LINE_8: Line was drawn using 8 connected Bresenham algorithm." }, { "code": null, "e": 25142, "s": 25070, "text": "LINE_AA: It draws Anti-aliased lines formed by using a Gaussian filter." }, { "code": null, "e": 25201, "s": 25142, "text": "shift: Number of fractional bits in the point coordinates." }, { "code": null, "e": 25236, "s": 25201, "text": "Return Value: It returns an image." }, { "code": null, "e": 25247, "s": 25236, "text": "Program 1:" }, { "code": null, "e": 25346, "s": 25247, "text": "Below is the C++ program demonstrating how to draw an ellipse over a self-formed background image:" }, { "code": null, "e": 25350, "s": 25346, "text": "C++" }, { "code": "// C++ program to demonstrating ellipse// over a self-formed background image#include <iostream>#include <opencv2/core/core.hpp> // Drawing shapes#include <opencv2/imgproc.hpp> #include <opencv2/highgui/highgui.hpp>using namespace cv;using namespace std; // Driver Codeint main(int argc, char** argv){ // Creating a blank image with // white background Mat image(500, 500, CV_8UC3, Scalar(255, 255, 255)); // Check if the image is created // successfully or not if (!image.data) { std::cout << \"Could not open or \" << \"find the image\\n\"; return 0; } // Drawing the ellipse ellipse(image, Point(256, 256), Size(100, 50), 0, 0, 360, Scalar(0, 255, 255), -1, LINE_AA); // Showing image inside a window imshow(\"Output\", image); waitKey(0); return 0;}", "e": 26226, "s": 25350, "text": null }, { "code": null, "e": 26234, "s": 26226, "text": "Output:" }, { "code": null, "e": 26340, "s": 26234, "text": "Explanation: In the above program, an ellipse is drawn at an angle of 0 degrees i.e., horizontal ellipse." }, { "code": null, "e": 26351, "s": 26340, "text": "Program 2:" }, { "code": null, "e": 26454, "s": 26351, "text": "Below is the C++ program illustrate rectangle over a loaded image with an ellipse around the GFG logo:" }, { "code": null, "e": 26458, "s": 26454, "text": "C++" }, { "code": "// C++ program to demonstrate rectangle// over a loaded image with an ellipse// around the GFG logo#include <iostream>#include <opencv2/core/core.hpp> // Drawing shapes#include <opencv2/imgproc.hpp> #include <opencv2/highgui/highgui.hpp>using namespace cv;using namespace std; // Driver Codeint main(int argc, char** argv){ // Reading the Image Mat image = imread(\"C:/Users/harsh/Downloads/geeks.png\", IMREAD_COLOR); // Check if the image is created // successfully or not if (!image.data) { std::cout << \"Could not open or \" << \"find the image\\n\"; return 0; } // Drawing the ellipse ellipse(image, Point(115, 110), Size(105, 55), 0, 0, 360, Scalar(0, 255, 255), 1, LINE_AA); // Show our image inside a window imshow(\"Output\", image); waitKey(0); return 0;}", "e": 27349, "s": 26458, "text": null }, { "code": null, "e": 27357, "s": 27349, "text": "Output:" }, { "code": null, "e": 27375, "s": 27357, "text": "computer-graphics" }, { "code": null, "e": 27382, "s": 27375, "text": "OpenCV" }, { "code": null, "e": 27386, "s": 27382, "text": "C++" }, { "code": null, "e": 27399, "s": 27386, "text": "C++ Programs" }, { "code": null, "e": 27403, "s": 27399, "text": "CPP" }, { "code": null, "e": 27501, "s": 27403, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27510, "s": 27501, "text": "Comments" }, { "code": null, "e": 27523, "s": 27510, "text": "Old Comments" }, { "code": null, "e": 27551, "s": 27523, "text": "Operator Overloading in C++" }, { "code": null, "e": 27575, "s": 27551, "text": "Sorting a vector in C++" }, { "code": null, "e": 27608, "s": 27575, "text": "Friend class and function in C++" }, { "code": null, "e": 27628, "s": 27608, "text": "Polymorphism in C++" }, { "code": null, "e": 27672, "s": 27628, "text": "List in C++ Standard Template Library (STL)" }, { "code": null, "e": 27707, "s": 27672, "text": "Header files in C/C++ and its uses" }, { "code": null, "e": 27733, "s": 27707, "text": "C++ Program for QuickSort" }, { "code": null, "e": 27792, "s": 27733, "text": "How to return multiple values from a function in C or C++?" }, { "code": null, "e": 27836, "s": 27792, "text": "Program to print ASCII Value of a character" } ]
Gradient Descent — One Step at a Time | by Asad Mumtaz | Towards Data Science
Gradient Descent (GD) is an optimization algorithm used to minimize any given cost function iteratively. But what is a cost function? It is a function that measures the accuracy of a trained machine learning model in making predictions. Common examples include Mean Squared Error (MSE) and Cross-Entropy (or Log-Loss). GD is heavily utilized in deep machine learning models as an alternative to more traditional methodologies to minimize cost functions. It deals more efficiently with enormous volumes of data that are common in deep learning. We will go through the GD in some detail to model an overly simplified linear regression problem for an intuitive and deep understanding of its mechanics. I will assume that you have some knowledge of Least Squares, Calculus, and Linear Regression while working through the problem. Here is our toy data comprising of 3 data points: We aim to find the line of best fit using GD that can then be used to predict Y values based on some new X values (aka Linear Regression). Recall that a straight line can be described entirely by just two parameters: intercept and slope. Hence, if we can find the ideal intercept and slope parameters through an optimization algorithm, we will get our line of best fit. Our line of best fit can be represented as follows: where: y hat is the dependent variable to be predicted x1 is the X value for which we want to predict y hat θ0 is the intercept term, to be optimized θ1 is the slope, to be optimized To keep it simple initially, we will start with finding the optimal value of only θ0, while assuming θ1 to be equal to 0.64 (determined through Least Squares). Then, once we understand how GD works, we will use it to solve for both the optimal intercept and slope parameters together. So our revised equation for the line becomes: We start with picking a random value for the intercept θ0, called random initialization. The random initialization is our initial guess and can literally be any real number used by GD to improve upon. Let’s start with 0 for θ0 (not coincidentally, also my favorite number!), that gives us the following line: Next, we will evaluate how well this line fits our data with the Residual Sum of Squares (RSS) loss function: Using Eq. 2 and with θ0 = 0, we get the following predictions of y, Residuals, Squared Residuals, and Residual Sum of Squares: Repeating the above calculation for RSS with increasing values for the intercept θ0, we get the following scatter plot of θ0 against RSS: It is quite evident from the plot that an intercept value of 0.95 resulted in the least RSS. But how do we know that it is, in fact, 0.95, and not some other value between 0.75 and 1.15? We can plug in a bunch of different intercept values and find the optimal value through trial and error. But why do so when we have GD at our disposal? When GD calculates RSS at the point of random initialization, it takes a relatively bigger step to determine the next intercept to be evaluated in case of a high RSS value. As RSS approaches zero in the subsequent iterations, the change in intercept (called step sizes) gets smaller. In other words, GD identifies the optimal parameter value by taking big steps when it is far away from the minimum RSS and baby steps when it is closer to it. We can get an equation for the cost function that plots all possible intercepts against RSS by using RSS and our Eq. 2 as follows (with our three original data points): The function’s plot will look something like this, which is basically the same scatter plot as above with a polynomial trendline added to it: We can take the derivative of this function with respect to θ0 and determine the slope at any value for the intercept θ0: Now that we have the derivative, GD will use it to find where the RSS is at its lowest value. Like before, suppose that we initialize GD with an initial value of θ0 = 0. Plugging θ0 = 0 in the derivative above gives us -5.6, which is the gradient or slope of the RSS cost function at θ0 = 0. Note that the optimal value of θ0 is obtained at the point on the curve where its gradient is 0, i.e., at the curve’s bottom. Recall also that the GD takes a relatively big step when the curve’s slope is far from 0 and baby steps when it is close to 0. So the size of the step should be related to the curve’s slope since it tells GD whether it should take a baby step or a big step. However, the step should not be too big so as to jump over the minimum point on the curve and go over to the other side. The step size is regulated by a parameter called the learning rate. The step size then determines the new intercept to be used by the GD to calculate RSS: step size = slope * learning ratenew intercept = old intercept - step size The learning rate is set to a small number, usually 0.2, 0.1, or 0.01 in practice. Continuing with our example, when θ0 = 0 and with a learning rate of 0.1, the step size is -0.56: step size (at θ0 = 0): -5.6 * 0.1step size (at θ0 = 0): -0.56new intercept = 0 - (-0.56)new intercept = 0.56 The cost function’s plot with the two intercepts evaluated so far looks something like the below: The above plot clearly shows that with a relatively big first step, we are already pretty close to the minimum value of RSS! Going back to our line of best-fit, we can see that the new intercept of 0.56 has substantially shrunk the residuals: Now let’s take another step closer to the optimal value for the intercept. We go back to the derivative in Eq. 3 and plug in the new intercept value of 0.56, which gives us the slope of the curve to be -2.2 at this intercept value: RSS slope (at θ0 = 0.56): -2(1.08-0.56) - 2(0.4-0.56) - 2(1.3-0.56)RSS slope (at θ0 = 0.56): -2.2step size (at θ0 = 0.56): -2.2 * 0.1step size (at θ0 = 0.56): -0.22new intercept = 0.56 - (-0.22)new intercept = 0.78 Our two plots look like this below: Overall, the RSS is getting smaller. Also, notice that in the RSS Cost Function Plot, the first step was relatively large compared to the second step. Let’s also do the third step: RSS slope (at θ0 = 0.78): -2(1.08-0.78) - 2(0.4-0.78) - 2(1.3-0.78)RSS slope (at θ0 = 0.78): -0.88step size (at θ0 = 0.78): -0.88 * 0.1step size (at θ0 = 0.78): -0.09new intercept = 0.78 - (-0.09)new intercept = 0.87 Our two plots look like this below: Continuing for three more steps, the GD’s estimate for the intercept comes out to be 0.95, which is precisely the same as that calculated by the Least Squares method (you can check the Least Squares’ calculation yourself!). But how does GD know when to stop doing additional calculations? In other words, how does it know that it has arrived at an optimal estimate? It does so when the step size becomes very close to 0, which will occur when the gradient is very close to 0. Practitioners usually control this through the Minimum Step Size parameter, which is generally set at 0.001 or smaller. That said, GD also includes a limit on the number of steps it will take before it gives up, which is generally parameterized at 1,000 steps or more. So, even if the step size is large, it will stop if the GD has performed the maximum number of steps. Now that we have understood GD’s basics, let’s work out both the optimal intercept and the slope together. This means that we will not be using the slope of 0.64, as in Eq. 2. Instead, we will have two independent parameters, θ0 and θ1, that we need to optimize together. This calls for multivariable calculus and taking partial derivatives with respect to both the intercept θ0 and the slope θ1. The Cost Function looks like this now: The partial derivative with respect to the intercept θ0 looks like the following: The partial derivative with respect to the intercept θ1 looks like the following: We will use these two partial derivatives to find the lowest point in the RSS cost function (Eq. 4). Just like before, we will start by selecting random numbers for the intercept θ0 and the slope θ1. Let’s start with θ0 = 0 and θ1 = 1. Thus, GD will commence from this line: Now let’s plug in θ0 = 0 and θ1 = 1 in our partial derivative equations: partial derivative wrt θ0 (Eq. 5) = (6 * 0) + (11.4 * 1) - 13partial derivative wrt θ0 (Eq. 5) = -1.6partial derivative wrt θ1 (Eq. 6) = (11.4 * 0) + (27.9 * 1) - 28.7partial derivative wrt θ1 (Eq. 6) = -0.8 Calculating the step sizes with a learning rate of 0.01 together with the new values for the intercept and the slope: intercept step size = -1.6 * 0.01intercept step size = -0.016new intercept = 0 - (-0.016)new intercept = 0.016slope step size = -0.8 * 0.01slope step size = -0.008new slope = 1 - (-0.008)new slope = 1.008 Our updated line of best fit looks something like this: The difference does not appear to be material. However, after some more iterations (until either the step size is smaller than the threshold or the maximum number of iterations have been reached) of calculating the step sizes and updated parameters, we get the following line of best fit: The optimum parameters found by the GD will be the same or very close to those find by the Least Squares method, i.e. θ0 = 0.95 and θ1 = 0.64. We just completed the GD calculation for two parameters. If our data had more features (as is usually the case with practical datasets), we simply need to take more partial derivatives, and everything else will remain the same. A critical point to note here is that all the parameters should be updated simultaneously at each step (and not one-by-one). In this example, we optimized the RSS cost function. However, there are several other cost functions that work with different data types, distributions, and prediction problems. Regardless of which cost function is used, GD works the same way. What we have performed in this problem is called Batch Gradient Descent, whereby all the available data points (training data) are used when calculating the slope of the cost function (Step 3 above). This can cause a problem and inefficiencies when we have a large number of data points. This inefficiency is handled very well by a different beast, called Stochastic Gradient Descent. Stochastic Gradient Descent uses a randomly selected observation at every step rather than the entire dataset. This reduces the time spent calculating the slope of the cost function (step 3). The overall concept and methodology remain similar to Batch Gradient Descent. You would have noticed that we used two different learning rates: a higher learning rate when finding only the optimal intercept and a lower learning rate when finding both the optimal intercept and slope together. GD is highly sensitive to the learning rate. In practice, a reasonable learning rate can be automatically determined by starting large and getting smaller with each step — through a Learning Schedule. The learning rate and the learning schedule are available as parameters in most machine learning algorithms. For example, in scikit-learn’s SGDRegressor and SGDClassifier classes, the learning rate, and the learning schedule are controlled by the eta0 and the learning_rate parameters, respectively. There you have it, a very simple explanation to how GD works in the background. Let us now summarize the steps taken by the GD while optimizing the parameters given to it: Take the partial derivative of the cost function with respect to each parameter in it — resulting in multiple partial derivatives that are equal to the number of parametersPick some random initial values for each parameter — called random initializationPlug these random values into each of the partial derivatives determined under Step 1 to find the slope of the cost functionCalculate the step sizes for each parameter: step size = slope * learning rateCalculate the new parameters: new parameter = old parameter — step sizeRepeat from step 3 until the step size is very small or the maximum number of steps have been reached Take the partial derivative of the cost function with respect to each parameter in it — resulting in multiple partial derivatives that are equal to the number of parameters Pick some random initial values for each parameter — called random initialization Plug these random values into each of the partial derivatives determined under Step 1 to find the slope of the cost function Calculate the step sizes for each parameter: step size = slope * learning rate Calculate the new parameters: new parameter = old parameter — step size Repeat from step 3 until the step size is very small or the maximum number of steps have been reached Feel free to reach out to me if you would like to discuss anything related to data analytics, machine learning, financial or credit analysis. Till next time, rock on!
[ { "code": null, "e": 490, "s": 171, "text": "Gradient Descent (GD) is an optimization algorithm used to minimize any given cost function iteratively. But what is a cost function? It is a function that measures the accuracy of a trained machine learning model in making predictions. Common examples include Mean Squared Error (MSE) and Cross-Entropy (or Log-Loss)." }, { "code": null, "e": 715, "s": 490, "text": "GD is heavily utilized in deep machine learning models as an alternative to more traditional methodologies to minimize cost functions. It deals more efficiently with enormous volumes of data that are common in deep learning." }, { "code": null, "e": 998, "s": 715, "text": "We will go through the GD in some detail to model an overly simplified linear regression problem for an intuitive and deep understanding of its mechanics. I will assume that you have some knowledge of Least Squares, Calculus, and Linear Regression while working through the problem." }, { "code": null, "e": 1048, "s": 998, "text": "Here is our toy data comprising of 3 data points:" }, { "code": null, "e": 1418, "s": 1048, "text": "We aim to find the line of best fit using GD that can then be used to predict Y values based on some new X values (aka Linear Regression). Recall that a straight line can be described entirely by just two parameters: intercept and slope. Hence, if we can find the ideal intercept and slope parameters through an optimization algorithm, we will get our line of best fit." }, { "code": null, "e": 1470, "s": 1418, "text": "Our line of best fit can be represented as follows:" }, { "code": null, "e": 1477, "s": 1470, "text": "where:" }, { "code": null, "e": 1525, "s": 1477, "text": "y hat is the dependent variable to be predicted" }, { "code": null, "e": 1578, "s": 1525, "text": "x1 is the X value for which we want to predict y hat" }, { "code": null, "e": 1620, "s": 1578, "text": "θ0 is the intercept term, to be optimized" }, { "code": null, "e": 1653, "s": 1620, "text": "θ1 is the slope, to be optimized" }, { "code": null, "e": 1984, "s": 1653, "text": "To keep it simple initially, we will start with finding the optimal value of only θ0, while assuming θ1 to be equal to 0.64 (determined through Least Squares). Then, once we understand how GD works, we will use it to solve for both the optimal intercept and slope parameters together. So our revised equation for the line becomes:" }, { "code": null, "e": 2185, "s": 1984, "text": "We start with picking a random value for the intercept θ0, called random initialization. The random initialization is our initial guess and can literally be any real number used by GD to improve upon." }, { "code": null, "e": 2293, "s": 2185, "text": "Let’s start with 0 for θ0 (not coincidentally, also my favorite number!), that gives us the following line:" }, { "code": null, "e": 2403, "s": 2293, "text": "Next, we will evaluate how well this line fits our data with the Residual Sum of Squares (RSS) loss function:" }, { "code": null, "e": 2530, "s": 2403, "text": "Using Eq. 2 and with θ0 = 0, we get the following predictions of y, Residuals, Squared Residuals, and Residual Sum of Squares:" }, { "code": null, "e": 2668, "s": 2530, "text": "Repeating the above calculation for RSS with increasing values for the intercept θ0, we get the following scatter plot of θ0 against RSS:" }, { "code": null, "e": 3007, "s": 2668, "text": "It is quite evident from the plot that an intercept value of 0.95 resulted in the least RSS. But how do we know that it is, in fact, 0.95, and not some other value between 0.75 and 1.15? We can plug in a bunch of different intercept values and find the optimal value through trial and error. But why do so when we have GD at our disposal?" }, { "code": null, "e": 3450, "s": 3007, "text": "When GD calculates RSS at the point of random initialization, it takes a relatively bigger step to determine the next intercept to be evaluated in case of a high RSS value. As RSS approaches zero in the subsequent iterations, the change in intercept (called step sizes) gets smaller. In other words, GD identifies the optimal parameter value by taking big steps when it is far away from the minimum RSS and baby steps when it is closer to it." }, { "code": null, "e": 3619, "s": 3450, "text": "We can get an equation for the cost function that plots all possible intercepts against RSS by using RSS and our Eq. 2 as follows (with our three original data points):" }, { "code": null, "e": 3761, "s": 3619, "text": "The function’s plot will look something like this, which is basically the same scatter plot as above with a polynomial trendline added to it:" }, { "code": null, "e": 3883, "s": 3761, "text": "We can take the derivative of this function with respect to θ0 and determine the slope at any value for the intercept θ0:" }, { "code": null, "e": 4053, "s": 3883, "text": "Now that we have the derivative, GD will use it to find where the RSS is at its lowest value. Like before, suppose that we initialize GD with an initial value of θ0 = 0." }, { "code": null, "e": 4680, "s": 4053, "text": "Plugging θ0 = 0 in the derivative above gives us -5.6, which is the gradient or slope of the RSS cost function at θ0 = 0. Note that the optimal value of θ0 is obtained at the point on the curve where its gradient is 0, i.e., at the curve’s bottom. Recall also that the GD takes a relatively big step when the curve’s slope is far from 0 and baby steps when it is close to 0. So the size of the step should be related to the curve’s slope since it tells GD whether it should take a baby step or a big step. However, the step should not be too big so as to jump over the minimum point on the curve and go over to the other side." }, { "code": null, "e": 4835, "s": 4680, "text": "The step size is regulated by a parameter called the learning rate. The step size then determines the new intercept to be used by the GD to calculate RSS:" }, { "code": null, "e": 4910, "s": 4835, "text": "step size = slope * learning ratenew intercept = old intercept - step size" }, { "code": null, "e": 4993, "s": 4910, "text": "The learning rate is set to a small number, usually 0.2, 0.1, or 0.01 in practice." }, { "code": null, "e": 5091, "s": 4993, "text": "Continuing with our example, when θ0 = 0 and with a learning rate of 0.1, the step size is -0.56:" }, { "code": null, "e": 5200, "s": 5091, "text": "step size (at θ0 = 0): -5.6 * 0.1step size (at θ0 = 0): -0.56new intercept = 0 - (-0.56)new intercept = 0.56" }, { "code": null, "e": 5298, "s": 5200, "text": "The cost function’s plot with the two intercepts evaluated so far looks something like the below:" }, { "code": null, "e": 5541, "s": 5298, "text": "The above plot clearly shows that with a relatively big first step, we are already pretty close to the minimum value of RSS! Going back to our line of best-fit, we can see that the new intercept of 0.56 has substantially shrunk the residuals:" }, { "code": null, "e": 5773, "s": 5541, "text": "Now let’s take another step closer to the optimal value for the intercept. We go back to the derivative in Eq. 3 and plug in the new intercept value of 0.56, which gives us the slope of the curve to be -2.2 at this intercept value:" }, { "code": null, "e": 5988, "s": 5773, "text": "RSS slope (at θ0 = 0.56): -2(1.08-0.56) - 2(0.4-0.56) - 2(1.3-0.56)RSS slope (at θ0 = 0.56): -2.2step size (at θ0 = 0.56): -2.2 * 0.1step size (at θ0 = 0.56): -0.22new intercept = 0.56 - (-0.22)new intercept = 0.78" }, { "code": null, "e": 6024, "s": 5988, "text": "Our two plots look like this below:" }, { "code": null, "e": 6175, "s": 6024, "text": "Overall, the RSS is getting smaller. Also, notice that in the RSS Cost Function Plot, the first step was relatively large compared to the second step." }, { "code": null, "e": 6205, "s": 6175, "text": "Let’s also do the third step:" }, { "code": null, "e": 6422, "s": 6205, "text": "RSS slope (at θ0 = 0.78): -2(1.08-0.78) - 2(0.4-0.78) - 2(1.3-0.78)RSS slope (at θ0 = 0.78): -0.88step size (at θ0 = 0.78): -0.88 * 0.1step size (at θ0 = 0.78): -0.09new intercept = 0.78 - (-0.09)new intercept = 0.87" }, { "code": null, "e": 6458, "s": 6422, "text": "Our two plots look like this below:" }, { "code": null, "e": 6682, "s": 6458, "text": "Continuing for three more steps, the GD’s estimate for the intercept comes out to be 0.95, which is precisely the same as that calculated by the Least Squares method (you can check the Least Squares’ calculation yourself!)." }, { "code": null, "e": 7054, "s": 6682, "text": "But how does GD know when to stop doing additional calculations? In other words, how does it know that it has arrived at an optimal estimate? It does so when the step size becomes very close to 0, which will occur when the gradient is very close to 0. Practitioners usually control this through the Minimum Step Size parameter, which is generally set at 0.001 or smaller." }, { "code": null, "e": 7305, "s": 7054, "text": "That said, GD also includes a limit on the number of steps it will take before it gives up, which is generally parameterized at 1,000 steps or more. So, even if the step size is large, it will stop if the GD has performed the maximum number of steps." }, { "code": null, "e": 7412, "s": 7305, "text": "Now that we have understood GD’s basics, let’s work out both the optimal intercept and the slope together." }, { "code": null, "e": 7741, "s": 7412, "text": "This means that we will not be using the slope of 0.64, as in Eq. 2. Instead, we will have two independent parameters, θ0 and θ1, that we need to optimize together. This calls for multivariable calculus and taking partial derivatives with respect to both the intercept θ0 and the slope θ1. The Cost Function looks like this now:" }, { "code": null, "e": 7823, "s": 7741, "text": "The partial derivative with respect to the intercept θ0 looks like the following:" }, { "code": null, "e": 7905, "s": 7823, "text": "The partial derivative with respect to the intercept θ1 looks like the following:" }, { "code": null, "e": 8180, "s": 7905, "text": "We will use these two partial derivatives to find the lowest point in the RSS cost function (Eq. 4). Just like before, we will start by selecting random numbers for the intercept θ0 and the slope θ1. Let’s start with θ0 = 0 and θ1 = 1. Thus, GD will commence from this line:" }, { "code": null, "e": 8253, "s": 8180, "text": "Now let’s plug in θ0 = 0 and θ1 = 1 in our partial derivative equations:" }, { "code": null, "e": 8461, "s": 8253, "text": "partial derivative wrt θ0 (Eq. 5) = (6 * 0) + (11.4 * 1) - 13partial derivative wrt θ0 (Eq. 5) = -1.6partial derivative wrt θ1 (Eq. 6) = (11.4 * 0) + (27.9 * 1) - 28.7partial derivative wrt θ1 (Eq. 6) = -0.8" }, { "code": null, "e": 8579, "s": 8461, "text": "Calculating the step sizes with a learning rate of 0.01 together with the new values for the intercept and the slope:" }, { "code": null, "e": 8784, "s": 8579, "text": "intercept step size = -1.6 * 0.01intercept step size = -0.016new intercept = 0 - (-0.016)new intercept = 0.016slope step size = -0.8 * 0.01slope step size = -0.008new slope = 1 - (-0.008)new slope = 1.008" }, { "code": null, "e": 8840, "s": 8784, "text": "Our updated line of best fit looks something like this:" }, { "code": null, "e": 9129, "s": 8840, "text": "The difference does not appear to be material. However, after some more iterations (until either the step size is smaller than the threshold or the maximum number of iterations have been reached) of calculating the step sizes and updated parameters, we get the following line of best fit:" }, { "code": null, "e": 9272, "s": 9129, "text": "The optimum parameters found by the GD will be the same or very close to those find by the Least Squares method, i.e. θ0 = 0.95 and θ1 = 0.64." }, { "code": null, "e": 9500, "s": 9272, "text": "We just completed the GD calculation for two parameters. If our data had more features (as is usually the case with practical datasets), we simply need to take more partial derivatives, and everything else will remain the same." }, { "code": null, "e": 9625, "s": 9500, "text": "A critical point to note here is that all the parameters should be updated simultaneously at each step (and not one-by-one)." }, { "code": null, "e": 9869, "s": 9625, "text": "In this example, we optimized the RSS cost function. However, there are several other cost functions that work with different data types, distributions, and prediction problems. Regardless of which cost function is used, GD works the same way." }, { "code": null, "e": 10157, "s": 9869, "text": "What we have performed in this problem is called Batch Gradient Descent, whereby all the available data points (training data) are used when calculating the slope of the cost function (Step 3 above). This can cause a problem and inefficiencies when we have a large number of data points." }, { "code": null, "e": 10524, "s": 10157, "text": "This inefficiency is handled very well by a different beast, called Stochastic Gradient Descent. Stochastic Gradient Descent uses a randomly selected observation at every step rather than the entire dataset. This reduces the time spent calculating the slope of the cost function (step 3). The overall concept and methodology remain similar to Batch Gradient Descent." }, { "code": null, "e": 10739, "s": 10524, "text": "You would have noticed that we used two different learning rates: a higher learning rate when finding only the optimal intercept and a lower learning rate when finding both the optimal intercept and slope together." }, { "code": null, "e": 11240, "s": 10739, "text": "GD is highly sensitive to the learning rate. In practice, a reasonable learning rate can be automatically determined by starting large and getting smaller with each step — through a Learning Schedule. The learning rate and the learning schedule are available as parameters in most machine learning algorithms. For example, in scikit-learn’s SGDRegressor and SGDClassifier classes, the learning rate, and the learning schedule are controlled by the eta0 and the learning_rate parameters, respectively." }, { "code": null, "e": 11412, "s": 11240, "text": "There you have it, a very simple explanation to how GD works in the background. Let us now summarize the steps taken by the GD while optimizing the parameters given to it:" }, { "code": null, "e": 12040, "s": 11412, "text": "Take the partial derivative of the cost function with respect to each parameter in it — resulting in multiple partial derivatives that are equal to the number of parametersPick some random initial values for each parameter — called random initializationPlug these random values into each of the partial derivatives determined under Step 1 to find the slope of the cost functionCalculate the step sizes for each parameter: step size = slope * learning rateCalculate the new parameters: new parameter = old parameter — step sizeRepeat from step 3 until the step size is very small or the maximum number of steps have been reached" }, { "code": null, "e": 12213, "s": 12040, "text": "Take the partial derivative of the cost function with respect to each parameter in it — resulting in multiple partial derivatives that are equal to the number of parameters" }, { "code": null, "e": 12295, "s": 12213, "text": "Pick some random initial values for each parameter — called random initialization" }, { "code": null, "e": 12420, "s": 12295, "text": "Plug these random values into each of the partial derivatives determined under Step 1 to find the slope of the cost function" }, { "code": null, "e": 12499, "s": 12420, "text": "Calculate the step sizes for each parameter: step size = slope * learning rate" }, { "code": null, "e": 12571, "s": 12499, "text": "Calculate the new parameters: new parameter = old parameter — step size" }, { "code": null, "e": 12673, "s": 12571, "text": "Repeat from step 3 until the step size is very small or the maximum number of steps have been reached" }, { "code": null, "e": 12815, "s": 12673, "text": "Feel free to reach out to me if you would like to discuss anything related to data analytics, machine learning, financial or credit analysis." } ]
How to handle errors in HTML5 Web Workers?
The following shows an example of an error handling function in a Web Worker JavaScript file that logs errors to the console. <!DOCTYPE HTML> <html> <head> <title>Big for loop</title> <script> var worker = new Worker('bigLoop.js'); worker.onmessage = function (event) { alert("Completed " + event.data + "iterations" ); }; worker.onerror = function (event) { console.log(event.message, event); }; function sayHello(){ alert("Hello sir...." ); } </script> </head> <body> <input type = "button" onclick = "sayHello();" value = "Say Hello"/> </body> </html>
[ { "code": null, "e": 1188, "s": 1062, "text": "The following shows an example of an error handling function in a Web Worker JavaScript file that logs errors to the console." }, { "code": null, "e": 1752, "s": 1188, "text": "<!DOCTYPE HTML>\n<html>\n <head>\n <title>Big for loop</title>\n <script>\n var worker = new Worker('bigLoop.js');\n worker.onmessage = function (event) {\n alert(\"Completed \" + event.data + \"iterations\" );\n };\n worker.onerror = function (event) {\n console.log(event.message, event);\n };\n function sayHello(){\n alert(\"Hello sir....\" );\n }\n </script>\n </head>\n <body>\n <input type = \"button\" onclick = \"sayHello();\" value = \"Say Hello\"/>\n </body>\n</html>" } ]
Java Concurrency - Lock Interface
A java.util.concurrent.locks.Lock interface is used to as a thread synchronization mechanism similar to synchronized blocks. New Locking mechanism is more flexible and provides more options than a synchronized block. Main differences between a Lock and a synchronized block are following − Guarantee of sequence − Synchronized block does not provide any guarantee of sequence in which waiting thread will be given access. Lock interface handles it. Guarantee of sequence − Synchronized block does not provide any guarantee of sequence in which waiting thread will be given access. Lock interface handles it. No timeout − Synchronized block has no option of timeout if lock is not granted. Lock interface provides such option. No timeout − Synchronized block has no option of timeout if lock is not granted. Lock interface provides such option. Single method − Synchronized block must be fully contained within a single method whereas a lock interface's methods lock() and unlock() can be called in different methods. Single method − Synchronized block must be fully contained within a single method whereas a lock interface's methods lock() and unlock() can be called in different methods. Following is the list of important methods available in the Lock class. public void lock() Acquires the lock. public void lockInterruptibly() Acquires the lock unless the current thread is interrupted. public Condition newCondition() Returns a new Condition instance that is bound to this Lock instance. public boolean tryLock() Acquires the lock only if it is free at the time of invocation. public boolean tryLock(long time, TimeUnit unit) Acquires the lock if it is free within the given waiting time and the current thread has not been interrupted. public void unlock() Releases the lock. The following TestThread program demonstrates some of these methods of the Lock interface. Here we've used lock() to acquire the lock and unlock() to release the lock. import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; class PrintDemo { private final Lock queueLock = new ReentrantLock(); public void print() { queueLock.lock(); try { Long duration = (long) (Math.random() * 10000); System.out.println(Thread.currentThread().getName() + " Time Taken " + (duration / 1000) + " seconds."); Thread.sleep(duration); } catch (InterruptedException e) { e.printStackTrace(); } finally { System.out.printf( "%s printed the document successfully.\n", Thread.currentThread().getName()); queueLock.unlock(); } } } class ThreadDemo extends Thread { PrintDemo printDemo; ThreadDemo(String name, PrintDemo printDemo) { super(name); this.printDemo = printDemo; } @Override public void run() { System.out.printf( "%s starts printing a document\n", Thread.currentThread().getName()); printDemo.print(); } } public class TestThread { public static void main(String args[]) { PrintDemo PD = new PrintDemo(); ThreadDemo t1 = new ThreadDemo("Thread - 1 ", PD); ThreadDemo t2 = new ThreadDemo("Thread - 2 ", PD); ThreadDemo t3 = new ThreadDemo("Thread - 3 ", PD); ThreadDemo t4 = new ThreadDemo("Thread - 4 ", PD); t1.start(); t2.start(); t3.start(); t4.start(); } } This will produce the following result. Thread - 1 starts printing a document Thread - 4 starts printing a document Thread - 3 starts printing a document Thread - 2 starts printing a document Thread - 1 Time Taken 4 seconds. Thread - 1 printed the document successfully. Thread - 4 Time Taken 3 seconds. Thread - 4 printed the document successfully. Thread - 3 Time Taken 5 seconds. Thread - 3 printed the document successfully. Thread - 2 Time Taken 4 seconds. Thread - 2 printed the document successfully. We've use ReentrantLock class as an implementation of Lock interface here. ReentrantLock class allows a thread to lock a method even if it already have the lock on other method. 16 Lectures 2 hours Malhar Lathkar 19 Lectures 5 hours Malhar Lathkar 25 Lectures 2.5 hours Anadi Sharma 126 Lectures 7 hours Tushar Kale 119 Lectures 17.5 hours Monica Mittal 76 Lectures 7 hours Arnab Chakraborty Print Add Notes Bookmark this page
[ { "code": null, "e": 2947, "s": 2657, "text": "A java.util.concurrent.locks.Lock interface is used to as a thread synchronization mechanism similar to synchronized blocks. New Locking mechanism is more flexible and provides more options than a synchronized block. Main differences between a Lock and a synchronized block are following −" }, { "code": null, "e": 3106, "s": 2947, "text": "Guarantee of sequence − Synchronized block does not provide any guarantee of sequence in which waiting thread will be given access. Lock interface handles it." }, { "code": null, "e": 3265, "s": 3106, "text": "Guarantee of sequence − Synchronized block does not provide any guarantee of sequence in which waiting thread will be given access. Lock interface handles it." }, { "code": null, "e": 3383, "s": 3265, "text": "No timeout − Synchronized block has no option of timeout if lock is not granted. Lock interface provides such option." }, { "code": null, "e": 3501, "s": 3383, "text": "No timeout − Synchronized block has no option of timeout if lock is not granted. Lock interface provides such option." }, { "code": null, "e": 3674, "s": 3501, "text": "Single method − Synchronized block must be fully contained within a single method whereas a lock interface's methods lock() and unlock() can be called in different methods." }, { "code": null, "e": 3847, "s": 3674, "text": "Single method − Synchronized block must be fully contained within a single method whereas a lock interface's methods lock() and unlock() can be called in different methods." }, { "code": null, "e": 3919, "s": 3847, "text": "Following is the list of important methods available in the Lock class." }, { "code": null, "e": 3938, "s": 3919, "text": "public void lock()" }, { "code": null, "e": 3957, "s": 3938, "text": "Acquires the lock." }, { "code": null, "e": 3989, "s": 3957, "text": "public void lockInterruptibly()" }, { "code": null, "e": 4049, "s": 3989, "text": "Acquires the lock unless the current thread is interrupted." }, { "code": null, "e": 4081, "s": 4049, "text": "public Condition newCondition()" }, { "code": null, "e": 4151, "s": 4081, "text": "Returns a new Condition instance that is bound to this Lock instance." }, { "code": null, "e": 4176, "s": 4151, "text": "public boolean tryLock()" }, { "code": null, "e": 4240, "s": 4176, "text": "Acquires the lock only if it is free at the time of invocation." }, { "code": null, "e": 4289, "s": 4240, "text": "public boolean tryLock(long time, TimeUnit unit)" }, { "code": null, "e": 4400, "s": 4289, "text": "Acquires the lock if it is free within the given waiting time and the current thread has not been interrupted." }, { "code": null, "e": 4421, "s": 4400, "text": "public void unlock()" }, { "code": null, "e": 4440, "s": 4421, "text": "Releases the lock." }, { "code": null, "e": 4608, "s": 4440, "text": "The following TestThread program demonstrates some of these methods of the Lock interface. Here we've used lock() to acquire the lock and unlock() to release the lock." }, { "code": null, "e": 6068, "s": 4608, "text": "import java.util.concurrent.locks.Lock;\nimport java.util.concurrent.locks.ReentrantLock;\n\nclass PrintDemo {\n private final Lock queueLock = new ReentrantLock();\n\n public void print() {\n queueLock.lock();\n\n try {\n Long duration = (long) (Math.random() * 10000);\n System.out.println(Thread.currentThread().getName() \n + \" Time Taken \" + (duration / 1000) + \" seconds.\");\n Thread.sleep(duration);\n } catch (InterruptedException e) {\n e.printStackTrace();\n } finally {\n System.out.printf(\n \"%s printed the document successfully.\\n\", Thread.currentThread().getName());\n queueLock.unlock();\n }\n }\n}\n\nclass ThreadDemo extends Thread {\n PrintDemo printDemo;\n\n ThreadDemo(String name, PrintDemo printDemo) {\n super(name);\n this.printDemo = printDemo;\n } \n\n @Override\n public void run() {\n System.out.printf(\n \"%s starts printing a document\\n\", Thread.currentThread().getName());\n printDemo.print();\n }\n}\n\npublic class TestThread {\n\n public static void main(String args[]) {\n PrintDemo PD = new PrintDemo();\n\n ThreadDemo t1 = new ThreadDemo(\"Thread - 1 \", PD);\n ThreadDemo t2 = new ThreadDemo(\"Thread - 2 \", PD);\n ThreadDemo t3 = new ThreadDemo(\"Thread - 3 \", PD);\n ThreadDemo t4 = new ThreadDemo(\"Thread - 4 \", PD);\n\n t1.start();\n t2.start();\n t3.start();\n t4.start();\n }\n}" }, { "code": null, "e": 6108, "s": 6068, "text": "This will produce the following result." }, { "code": null, "e": 6593, "s": 6108, "text": "Thread - 1 starts printing a document\nThread - 4 starts printing a document\nThread - 3 starts printing a document\nThread - 2 starts printing a document\nThread - 1 Time Taken 4 seconds.\nThread - 1 printed the document successfully.\nThread - 4 Time Taken 3 seconds.\nThread - 4 printed the document successfully.\nThread - 3 Time Taken 5 seconds.\nThread - 3 printed the document successfully.\nThread - 2 Time Taken 4 seconds.\nThread - 2 printed the document successfully.\n" }, { "code": null, "e": 6771, "s": 6593, "text": "We've use ReentrantLock class as an implementation of Lock interface here. ReentrantLock class allows a thread to lock a method even if it already have the lock on other method." }, { "code": null, "e": 6804, "s": 6771, "text": "\n 16 Lectures \n 2 hours \n" }, { "code": null, "e": 6820, "s": 6804, "text": " Malhar Lathkar" }, { "code": null, "e": 6853, "s": 6820, "text": "\n 19 Lectures \n 5 hours \n" }, { "code": null, "e": 6869, "s": 6853, "text": " Malhar Lathkar" }, { "code": null, "e": 6904, "s": 6869, "text": "\n 25 Lectures \n 2.5 hours \n" }, { "code": null, "e": 6918, "s": 6904, "text": " Anadi Sharma" }, { "code": null, "e": 6952, "s": 6918, "text": "\n 126 Lectures \n 7 hours \n" }, { "code": null, "e": 6966, "s": 6952, "text": " Tushar Kale" }, { "code": null, "e": 7003, "s": 6966, "text": "\n 119 Lectures \n 17.5 hours \n" }, { "code": null, "e": 7018, "s": 7003, "text": " Monica Mittal" }, { "code": null, "e": 7051, "s": 7018, "text": "\n 76 Lectures \n 7 hours \n" }, { "code": null, "e": 7070, "s": 7051, "text": " Arnab Chakraborty" }, { "code": null, "e": 7077, "s": 7070, "text": " Print" }, { "code": null, "e": 7088, "s": 7077, "text": " Add Notes" } ]
MySQL - WITH (Common Table Expressions)
A common table expression in MySQL is a temporary result whose scope is confined to a single statement. You can refer this expression multiple times with in the statement. The WITH clause in MySQL is used to specify a Common Table Expression, a with clause can have one or more comms-separated subclauses. Following is the syntax of the WITH clause − WITH name_for_summary_data AS ( SELECT Statement) SELECT columns FROM name_for_summary_data WHERE conditions <=> ( SELECT column FROM name_for_summary_data) [ORDER BY columns] Assume we have created a table named data and populated it as shown below − mysql> CREATE TABLE data( ID INT, NAME CHAR(20), AGE INT, SALARY INT ); INSERT INTO data values (101, 'Raja', 25, 55452); INSERT INTO data values (102, 'Roja', 29, 66458); INSERT INTO data values (103, 'Roja', 35, 36944); Following query demonstrates the usage of the WITH clause − (Select ID, NAME, AGE, SALARYFROM data) Select * From CTE; +------+------+------+--------+ | ID | NAME | AGE | SALARY | +------+------+------+--------+ | 101 | Raja | 25 | 55452 | | 102 | Roja | 29 | 66458 | | 103 | Roja | 35 | 36944 | +------+------+------+--------+ 3 rows in set (0.00 sec) You can also create a Common Table Expression from multiple tables. Suppose we have created a table with name EMPLOYEE and populated data into it as shown below − mysql> CREATE TABLE EMPLOYEE( ID INT NOT NULL, FIRST_NAME CHAR(20) NOT NULL, LAST_NAME CHAR(20), AGE INT, SEX CHAR(1), INCOME FLOAT, CONTACT INT ); Query OK, 0 rows affected (0.36 sec) mysql> INSERT INTO Employee VALUES (101, 'Ramya', 'Rama Priya', 27, 'F', 9000, 101), (102, 'Vinay', 'Bhattacharya', 20, 'M', 6000, 102); And, if we have created another table and populated it as − mysql> CREATE TABLE CONTACT( ID INT NOT NULL, EMAIL CHAR(20) NOT NULL, PHONE LONG, CITY CHAR(20) ); mysql> INSERT INTO CONTACT (ID, EMAIL, CITY) VALUES (101, 'ramya@mymail.com', 'Hyderabad'), (102, 'vinay@mymail.com', 'Vishakhapatnam'); Following query create a Common Table Expression from the above two tables − mysql> WITH exp1 AS (SELECT ID, FIRST_NAME, LAST_NAME FROM EMPLOYEE), exp2 AS (SELECT EMAIL, PHONE FROM CONTACT) SELECT * FROM exp1 JOIN exp2; +-----+------------+--------------+------------------+-------+ | ID | FIRST_NAME | LAST_NAME | EMAIL | PHONE | +-----+------------+--------------+------------------+-------+ | 101 | Ramya | Rama Priya | ramya@mymail.com | NULL | | 102 | Vinay | Bhattacharya | ramya@mymail.com | NULL | | 101 | Ramya | Rama Priya | vinay@mymail.com | NULL | | 102 | Vinay | Bhattacharya | vinay@mymail.com | NULL | +-----+------------+--------------+------------------+-------+ 4 rows in set (0.00 sec) Recursive WITH or Hierarchical queries, is a form of CTE where a CTE can reference to itself, i.e., a WITH query can refer to its own output, hence the name recursive. Following query demonstrates the usage of the Recursive WITH statement − WITH RECURSIVE t AS ( SELECT SALARY FROM data UNION ALL SELECT SALARY FROM data WHERE SALARY < 50000 ) SELECT * FROM t; +--------+ | SALARY | +--------+ | 55452 | | 66458 | | 36944 | | 36944 | +--------+ 4 rows in set (0.03 sec) 31 Lectures 6 hours Eduonix Learning Solutions 84 Lectures 5.5 hours Frahaan Hussain 6 Lectures 3.5 hours DATAhill Solutions Srinivas Reddy 60 Lectures 10 hours Vijay Kumar Parvatha Reddy 10 Lectures 1 hours Harshit Srivastava 25 Lectures 4 hours Trevoir Williams Print Add Notes Bookmark this page
[ { "code": null, "e": 2505, "s": 2333, "text": "A common table expression in MySQL is a temporary result whose scope is confined to a single statement. You can refer this expression multiple times with in the statement." }, { "code": null, "e": 2639, "s": 2505, "text": "The WITH clause in MySQL is used to specify a Common Table Expression, a with clause can have one or more comms-separated subclauses." }, { "code": null, "e": 2684, "s": 2639, "text": "Following is the syntax of the WITH clause −" }, { "code": null, "e": 2894, "s": 2684, "text": "WITH\n name_for_summary_data AS (\n SELECT Statement)\n SELECT columns\n FROM name_for_summary_data\n WHERE conditions <=> (\n SELECT column\n FROM name_for_summary_data)\n [ORDER BY columns]\n" }, { "code": null, "e": 2970, "s": 2894, "text": "Assume we have created a table named data and populated it as shown below −" }, { "code": null, "e": 3204, "s": 2970, "text": "mysql> CREATE TABLE data(\n ID INT,\n NAME CHAR(20),\n AGE INT,\n SALARY INT\n);\nINSERT INTO data values (101, 'Raja', 25, 55452);\nINSERT INTO data values (102, 'Roja', 29, 66458);\nINSERT INTO data values (103, 'Roja', 35, 36944);" }, { "code": null, "e": 3264, "s": 3204, "text": "Following query demonstrates the usage of the WITH clause −" }, { "code": null, "e": 3573, "s": 3264, "text": "(Select ID, NAME, AGE, SALARYFROM data)\nSelect * From CTE; \n+------+------+------+--------+\n| ID | NAME | AGE | SALARY |\n+------+------+------+--------+\n| 101 | Raja | 25 | 55452 |\n| 102 | Roja | 29 | 66458 |\n| 103 | Roja | 35 | 36944 |\n+------+------+------+--------+\n3 rows in set (0.00 sec)" }, { "code": null, "e": 3641, "s": 3573, "text": "You can also create a Common Table Expression from multiple tables." }, { "code": null, "e": 3736, "s": 3641, "text": "Suppose we have created a table with name EMPLOYEE and populated data into it as shown below −" }, { "code": null, "e": 4085, "s": 3736, "text": "mysql> CREATE TABLE EMPLOYEE(\n ID INT NOT NULL,\n FIRST_NAME CHAR(20) NOT NULL,\n LAST_NAME CHAR(20),\n AGE INT,\n SEX CHAR(1),\n INCOME FLOAT,\n CONTACT INT\n);\nQuery OK, 0 rows affected (0.36 sec)\nmysql> INSERT INTO Employee VALUES\n (101, 'Ramya', 'Rama Priya', 27, 'F', 9000, 101),\n (102, 'Vinay', 'Bhattacharya', 20, 'M', 6000, 102);" }, { "code": null, "e": 4145, "s": 4085, "text": "And, if we have created another table and populated it as −" }, { "code": null, "e": 4401, "s": 4145, "text": "mysql> CREATE TABLE CONTACT(\n ID INT NOT NULL,\n EMAIL CHAR(20) NOT NULL,\n PHONE LONG,\n CITY CHAR(20)\n);\n\nmysql> INSERT INTO CONTACT (ID, EMAIL, CITY) VALUES\n (101, 'ramya@mymail.com', 'Hyderabad'),\n (102, 'vinay@mymail.com', 'Vishakhapatnam');" }, { "code": null, "e": 4478, "s": 4401, "text": "Following query create a Common Table Expression from the above two tables −" }, { "code": null, "e": 5156, "s": 4478, "text": "mysql> WITH\n exp1 AS (SELECT ID, FIRST_NAME, LAST_NAME FROM EMPLOYEE),\n exp2 AS (SELECT EMAIL, PHONE FROM CONTACT)\nSELECT * FROM exp1 JOIN exp2;\n+-----+------------+--------------+------------------+-------+\n| ID | FIRST_NAME | LAST_NAME | EMAIL | PHONE |\n+-----+------------+--------------+------------------+-------+\n| 101 | Ramya | Rama Priya | ramya@mymail.com | NULL |\n| 102 | Vinay | Bhattacharya | ramya@mymail.com | NULL |\n| 101 | Ramya | Rama Priya | vinay@mymail.com | NULL |\n| 102 | Vinay | Bhattacharya | vinay@mymail.com | NULL |\n+-----+------------+--------------+------------------+-------+\n4 rows in set (0.00 sec)" }, { "code": null, "e": 5324, "s": 5156, "text": "Recursive WITH or Hierarchical queries, is a form of CTE where a CTE can reference to itself, i.e., a WITH query can refer to its own output, hence the name recursive." }, { "code": null, "e": 5397, "s": 5324, "text": "Following query demonstrates the usage of the Recursive WITH statement −" }, { "code": null, "e": 5639, "s": 5397, "text": "WITH RECURSIVE t AS (\n SELECT SALARY FROM data\n UNION ALL\n SELECT SALARY FROM data WHERE SALARY < 50000\n)\nSELECT * FROM t;\n+--------+\n| SALARY |\n+--------+\n| 55452 |\n| 66458 |\n| 36944 |\n| 36944 |\n+--------+\n4 rows in set (0.03 sec)" }, { "code": null, "e": 5672, "s": 5639, "text": "\n 31 Lectures \n 6 hours \n" }, { "code": null, "e": 5700, "s": 5672, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 5735, "s": 5700, "text": "\n 84 Lectures \n 5.5 hours \n" }, { "code": null, "e": 5752, "s": 5735, "text": " Frahaan Hussain" }, { "code": null, "e": 5786, "s": 5752, "text": "\n 6 Lectures \n 3.5 hours \n" }, { "code": null, "e": 5821, "s": 5786, "text": " DATAhill Solutions Srinivas Reddy" }, { "code": null, "e": 5855, "s": 5821, "text": "\n 60 Lectures \n 10 hours \n" }, { "code": null, "e": 5883, "s": 5855, "text": " Vijay Kumar Parvatha Reddy" }, { "code": null, "e": 5916, "s": 5883, "text": "\n 10 Lectures \n 1 hours \n" }, { "code": null, "e": 5936, "s": 5916, "text": " Harshit Srivastava" }, { "code": null, "e": 5969, "s": 5936, "text": "\n 25 Lectures \n 4 hours \n" }, { "code": null, "e": 5987, "s": 5969, "text": " Trevoir Williams" }, { "code": null, "e": 5994, "s": 5987, "text": " Print" }, { "code": null, "e": 6005, "s": 5994, "text": " Add Notes" } ]
DATE() and DATE_ADD() Function in MariaDB - GeeksforGeeks
27 Nov, 2020 1. DATE() Function : In MariaDB, the DATE() function is used to return extracts the date value from a date or datetime expression. In this function, the first parameter will be a date or DateTime. This function will return extracts the date value from the expression. If the expression is not date or DateTime then this function will return the NULL Value. Syntax : DATE(expression) Parameter : Expression – date or DateTime value. Returns : The date value from datetime. Example-1 : SELECT DATE('2020-09-11 11:13:19'); Output : '2020-09-11' Example-2 : SELECT DATE('2020-04-12 11:13:01.000001'); Output : '2020-04-12' Example-3 : SELECT DATE('Today is 2020-10-17'); Output : NULL 2. DATE_ADD() Function : In MariaDB, the DATE_ADD() Function is used to return the time/DateTime value after which a certain date /timeinterval has been added. In this function, the first parameter will be a start_value and the second parameter will be the interval value. This function will return DateTime with the adding given interval. This function works similar to the DATE_SUB function. If the given interval is negative.If the interval value that is too short for the unit then DATE_ADD function will assume that the left-most portion of the interval value was not provided. Syntax : DATE_ADD(date, INTERVAL value unit) Parameters : Date – Date to which the interval should be added. Days – Number of days to add to date. value – The time/date interval that you wish to add. unit – The unit type of the interval such as DAY, MONTH, MINUTE, HOUR, etc. Returns : Time/DateTime value after which a certain date interval has been added. Example-1 : SELECT DATE_ADD('2020-01-10 08:44:21', INTERVAL 25 MINUTE); Output : '2020-01-10 09:09:21' Example-2 : SELECT DATE_ADD('2014-05-17 08:44:21.000001', INTERVAL '7 1:03:12.000001' DAY_MICROSECOND); Output : '2014-05-24 09:47:33.000002' Example-3 : SELECT DATE_ADD('2019-07-10', INTERVAL '1-2' YEAR_MONTH); Output : '2020-09-10' DBMS-SQL SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments SQL | DROP, TRUNCATE How to Select Data Between Two Dates and Times in SQL Server? SQL vs NoSQL: Which one is better to use? Advanced SQL Interview Questions SQL | OFFSET-FETCH Clause Insert multiple values into multiple tables using a single statement in SQL Server How to Update Multiple Columns in Single Update Statement in SQL? SQL | Comments SQL | CREATE Adding multiple constraints in a single table
[ { "code": null, "e": 23877, "s": 23849, "text": "\n27 Nov, 2020" }, { "code": null, "e": 23898, "s": 23877, "text": "1. DATE() Function :" }, { "code": null, "e": 24234, "s": 23898, "text": "In MariaDB, the DATE() function is used to return extracts the date value from a date or datetime expression. In this function, the first parameter will be a date or DateTime. This function will return extracts the date value from the expression. If the expression is not date or DateTime then this function will return the NULL Value." }, { "code": null, "e": 24243, "s": 24234, "text": "Syntax :" }, { "code": null, "e": 24260, "s": 24243, "text": "DATE(expression)" }, { "code": null, "e": 24272, "s": 24260, "text": "Parameter :" }, { "code": null, "e": 24309, "s": 24272, "text": "Expression – date or DateTime value." }, { "code": null, "e": 24349, "s": 24309, "text": "Returns : The date value from datetime." }, { "code": null, "e": 24361, "s": 24349, "text": "Example-1 :" }, { "code": null, "e": 24397, "s": 24361, "text": "SELECT DATE('2020-09-11 11:13:19');" }, { "code": null, "e": 24406, "s": 24397, "text": "Output :" }, { "code": null, "e": 24419, "s": 24406, "text": "'2020-09-11'" }, { "code": null, "e": 24431, "s": 24419, "text": "Example-2 :" }, { "code": null, "e": 24474, "s": 24431, "text": "SELECT DATE('2020-04-12 11:13:01.000001');" }, { "code": null, "e": 24483, "s": 24474, "text": "Output :" }, { "code": null, "e": 24496, "s": 24483, "text": "'2020-04-12'" }, { "code": null, "e": 24508, "s": 24496, "text": "Example-3 :" }, { "code": null, "e": 24544, "s": 24508, "text": "SELECT DATE('Today is 2020-10-17');" }, { "code": null, "e": 24553, "s": 24544, "text": "Output :" }, { "code": null, "e": 24558, "s": 24553, "text": "NULL" }, { "code": null, "e": 24583, "s": 24558, "text": "2. DATE_ADD() Function :" }, { "code": null, "e": 25142, "s": 24583, "text": " In MariaDB, the DATE_ADD() Function is used to return the time/DateTime value after which a certain date /timeinterval has been added. In this function, the first parameter will be a start_value and the second parameter will be the interval value. This function will return DateTime with the adding given interval. This function works similar to the DATE_SUB function. If the given interval is negative.If the interval value that is too short for the unit then DATE_ADD function will assume that the left-most portion of the interval value was not provided." }, { "code": null, "e": 25151, "s": 25142, "text": "Syntax :" }, { "code": null, "e": 25187, "s": 25151, "text": "DATE_ADD(date, INTERVAL value unit)" }, { "code": null, "e": 25200, "s": 25187, "text": "Parameters :" }, { "code": null, "e": 25251, "s": 25200, "text": "Date – Date to which the interval should be added." }, { "code": null, "e": 25289, "s": 25251, "text": "Days – Number of days to add to date." }, { "code": null, "e": 25342, "s": 25289, "text": "value – The time/date interval that you wish to add." }, { "code": null, "e": 25418, "s": 25342, "text": "unit – The unit type of the interval such as DAY, MONTH, MINUTE, HOUR, etc." }, { "code": null, "e": 25500, "s": 25418, "text": "Returns : Time/DateTime value after which a certain date interval has been added." }, { "code": null, "e": 25512, "s": 25500, "text": "Example-1 :" }, { "code": null, "e": 25572, "s": 25512, "text": "SELECT DATE_ADD('2020-01-10 08:44:21', INTERVAL 25 MINUTE);" }, { "code": null, "e": 25581, "s": 25572, "text": "Output :" }, { "code": null, "e": 25603, "s": 25581, "text": "'2020-01-10 09:09:21'" }, { "code": null, "e": 25615, "s": 25603, "text": "Example-2 :" }, { "code": null, "e": 25707, "s": 25615, "text": "SELECT DATE_ADD('2014-05-17 08:44:21.000001', INTERVAL '7 1:03:12.000001' DAY_MICROSECOND);" }, { "code": null, "e": 25716, "s": 25707, "text": "Output :" }, { "code": null, "e": 25745, "s": 25716, "text": "'2014-05-24 09:47:33.000002'" }, { "code": null, "e": 25757, "s": 25745, "text": "Example-3 :" }, { "code": null, "e": 25815, "s": 25757, "text": "SELECT DATE_ADD('2019-07-10', INTERVAL '1-2' YEAR_MONTH);" }, { "code": null, "e": 25824, "s": 25815, "text": "Output :" }, { "code": null, "e": 25837, "s": 25824, "text": "'2020-09-10'" }, { "code": null, "e": 25846, "s": 25837, "text": "DBMS-SQL" }, { "code": null, "e": 25850, "s": 25846, "text": "SQL" }, { "code": null, "e": 25854, "s": 25850, "text": "SQL" }, { "code": null, "e": 25952, "s": 25854, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25961, "s": 25952, "text": "Comments" }, { "code": null, "e": 25974, "s": 25961, "text": "Old Comments" }, { "code": null, "e": 25995, "s": 25974, "text": "SQL | DROP, TRUNCATE" }, { "code": null, "e": 26057, "s": 25995, "text": "How to Select Data Between Two Dates and Times in SQL Server?" }, { "code": null, "e": 26099, "s": 26057, "text": "SQL vs NoSQL: Which one is better to use?" }, { "code": null, "e": 26132, "s": 26099, "text": "Advanced SQL Interview Questions" }, { "code": null, "e": 26158, "s": 26132, "text": "SQL | OFFSET-FETCH Clause" }, { "code": null, "e": 26241, "s": 26158, "text": "Insert multiple values into multiple tables using a single statement in SQL Server" }, { "code": null, "e": 26307, "s": 26241, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 26322, "s": 26307, "text": "SQL | Comments" }, { "code": null, "e": 26335, "s": 26322, "text": "SQL | CREATE" } ]
Python 3 - XML Processing
XML is a portable, open source language that allows programmers to develop applications that can be read by other applications, regardless of operating system and/or developmental language. The Extensible Markup Language (XML) is a markup language much like HTML or SGML. This is recommended by the World Wide Web Consortium and available as an open standard. XML is extremely useful for keeping track of small to medium amounts of data without requiring an SQL-based backbone. The Python standard library provides a minimal but useful set of interfaces to work with XML. The two most basic and broadly used APIs to XML data are the SAX and DOM interfaces. Simple API for XML (SAX) − Here, you register callbacks for events of interest and then let the parser proceed through the document. This is useful when your documents are large or you have memory limitations, it parses the file as it reads it from the disk and the entire file is never stored in the memory. Simple API for XML (SAX) − Here, you register callbacks for events of interest and then let the parser proceed through the document. This is useful when your documents are large or you have memory limitations, it parses the file as it reads it from the disk and the entire file is never stored in the memory. Document Object Model (DOM) API − This is a World Wide Web Consortium recommendation wherein the entire file is read into the memory and stored in a hierarchical (tree-based) form to represent all the features of an XML document. Document Object Model (DOM) API − This is a World Wide Web Consortium recommendation wherein the entire file is read into the memory and stored in a hierarchical (tree-based) form to represent all the features of an XML document. SAX obviously cannot process information as fast as DOM, when working with large files. On the other hand, using DOM exclusively can really kill your resources, especially if used on many small files. SAX is read-only, while DOM allows changes to the XML file. Since these two different APIs literally complement each other, there is no reason why you cannot use them both for large projects. For all our XML code examples, let us use a simple XML file movies.xml as an input − <collection shelf = "New Arrivals"> <movie title = "Enemy Behind"> <type>War, Thriller</type> <format>DVD</format> <year>2003</year> <rating>PG</rating> <stars>10</stars> <description>Talk about a US-Japan war</description> </movie> <movie title = "Transformers"> <type>Anime, Science Fiction</type> <format>DVD</format> <year>1989</year> <rating>R</rating> <stars>8</stars> <description>A schientific fiction</description> </movie> <movie title = "Trigun"> <type>Anime, Action</type> <format>DVD</format> <episodes>4</episodes> <rating>PG</rating> <stars>10</stars> <description>Vash the Stampede!</description> </movie> <movie title = "Ishtar"> <type>Comedy</type> <format>VHS</format> <rating>PG</rating> <stars>2</stars> <description>Viewable boredom</description> </movie> </collection> SAX is a standard interface for event-driven XML parsing. Parsing XML with SAX generally requires you to create your own ContentHandler by subclassing xml.sax.ContentHandler. Your ContentHandler handles the particular tags and attributes of your flavor(s) of XML. A ContentHandler object provides methods to handle various parsing events. Its owning parser calls ContentHandler methods as it parses the XML file. The methods startDocument and endDocument are called at the start and the end of the XML file. The method characters(text) is passed the character data of the XML file via the parameter text. The ContentHandler is called at the start and end of each element. If the parser is not in namespace mode, the methods startElement(tag, attributes) and endElement(tag) are called; otherwise, the corresponding methods startElementNS and endElementNS are called. Here, tag is the element tag, and attributes is an Attributes object. Here are other important methods to understand before proceeding − The following method creates a new parser object and returns it. The parser object created will be of the first parser type, the system finds. xml.sax.make_parser( [parser_list] ) Here are the details of the parameters − parser_list − The optional argument consisting of a list of parsers to use which must all implement the make_parser method. parser_list − The optional argument consisting of a list of parsers to use which must all implement the make_parser method. The following method creates a SAX parser and uses it to parse a document. xml.sax.parse( xmlfile, contenthandler[, errorhandler]) Here are the details of the parameters − xmlfile − This is the name of the XML file to read from. xmlfile − This is the name of the XML file to read from. contenthandler − This must be a ContentHandler object. contenthandler − This must be a ContentHandler object. errorhandler − If specified, errorhandler must be a SAX ErrorHandler object. errorhandler − If specified, errorhandler must be a SAX ErrorHandler object. There is one more method to create a SAX parser and to parse the specified XML string. xml.sax.parseString(xmlstring, contenthandler[, errorhandler]) Here are the details of the parameters − xmlstring − This is the name of the XML string to read from. xmlstring − This is the name of the XML string to read from. contenthandler − This must be a ContentHandler object. contenthandler − This must be a ContentHandler object. errorhandler − If specified, errorhandler must be a SAX ErrorHandler object. errorhandler − If specified, errorhandler must be a SAX ErrorHandler object. #!/usr/bin/python3 import xml.sax class MovieHandler( xml.sax.ContentHandler ): def __init__(self): self.CurrentData = "" self.type = "" self.format = "" self.year = "" self.rating = "" self.stars = "" self.description = "" # Call when an element starts def startElement(self, tag, attributes): self.CurrentData = tag if tag == "movie": print ("*****Movie*****") title = attributes["title"] print ("Title:", title) # Call when an elements ends def endElement(self, tag): if self.CurrentData == "type": print ("Type:", self.type) elif self.CurrentData == "format": print ("Format:", self.format) elif self.CurrentData == "year": print ("Year:", self.year) elif self.CurrentData == "rating": print ("Rating:", self.rating) elif self.CurrentData == "stars": print ("Stars:", self.stars) elif self.CurrentData == "description": print ("Description:", self.description) self.CurrentData = "" # Call when a character is read def characters(self, content): if self.CurrentData == "type": self.type = content elif self.CurrentData == "format": self.format = content elif self.CurrentData == "year": self.year = content elif self.CurrentData == "rating": self.rating = content elif self.CurrentData == "stars": self.stars = content elif self.CurrentData == "description": self.description = content if ( __name__ == "__main__"): # create an XMLReader parser = xml.sax.make_parser() # turn off namepsaces parser.setFeature(xml.sax.handler.feature_namespaces, 0) # override the default ContextHandler Handler = MovieHandler() parser.setContentHandler( Handler ) parser.parse("movies.xml") This would produce the following result − *****Movie***** Title: Enemy Behind Type: War, Thriller Format: DVD Year: 2003 Rating: PG Stars: 10 Description: Talk about a US-Japan war *****Movie***** Title: Transformers Type: Anime, Science Fiction Format: DVD Year: 1989 Rating: R Stars: 8 Description: A scientific fiction *****Movie***** Title: Trigun Type: Anime, Action Format: DVD Rating: PG Stars: 10 Description: Vash the Stampede! *****Movie***** Title: Ishtar Type: Comedy Format: VHS Rating: PG Stars: 2 Description: Viewable boredom For a complete detail on SAX API documentation, please refer to the standard Python SAX APIs. The Document Object Model ("DOM") is a cross-language API from the World Wide Web Consortium (W3C) for accessing and modifying the XML documents. The DOM is extremely useful for random-access applications. SAX only allows you a view of one bit of the document at a time. If you are looking at one SAX element, you have no access to another. Here is the easiest way to load an XML document quickly and to create a minidom object using the xml.dom module. The minidom object provides a simple parser method that quickly creates a DOM tree from the XML file. The sample phrase calls the parse( file [,parser] ) function of the minidom object to parse the XML file, designated by file into a DOM tree object. #!/usr/bin/python3 from xml.dom.minidom import parse import xml.dom.minidom # Open XML document using minidom parser DOMTree = xml.dom.minidom.parse("movies.xml") collection = DOMTree.documentElement if collection.hasAttribute("shelf"): print ("Root element : %s" % collection.getAttribute("shelf")) # Get all the movies in the collection movies = collection.getElementsByTagName("movie") # Print detail of each movie. for movie in movies: print ("*****Movie*****") if movie.hasAttribute("title"): print ("Title: %s" % movie.getAttribute("title")) type = movie.getElementsByTagName('type')[0] print ("Type: %s" % type.childNodes[0].data) format = movie.getElementsByTagName('format')[0] print ("Format: %s" % format.childNodes[0].data) rating = movie.getElementsByTagName('rating')[0] print ("Rating: %s" % rating.childNodes[0].data) description = movie.getElementsByTagName('description')[0] print ("Description: %s" % description.childNodes[0].data) This would produce the following result − Root element : New Arrivals *****Movie***** Title: Enemy Behind Type: War, Thriller Format: DVD Rating: PG Description: Talk about a US-Japan war *****Movie***** Title: Transformers Type: Anime, Science Fiction Format: DVD Rating: R Description: A scientific fiction *****Movie***** Title: Trigun Type: Anime, Action Format: DVD Rating: PG Description: Vash the Stampede! *****Movie***** Title: Ishtar Type: Comedy Format: VHS Rating: PG Description: Viewable boredom For a complete detail on DOM API documentation, please refer to the standard Python DOM APIs. 187 Lectures 17.5 hours Malhar Lathkar 55 Lectures 8 hours Arnab Chakraborty 136 Lectures 11 hours In28Minutes Official 75 Lectures 13 hours Eduonix Learning Solutions 70 Lectures 8.5 hours Lets Kode It 63 Lectures 6 hours Abhilash Nelson Print Add Notes Bookmark this page
[ { "code": null, "e": 2530, "s": 2340, "text": "XML is a portable, open source language that allows programmers to develop applications that can be read by other applications, regardless of operating system and/or developmental language." }, { "code": null, "e": 2700, "s": 2530, "text": "The Extensible Markup Language (XML) is a markup language much like HTML or SGML. This is recommended by the World Wide Web Consortium and available as an open standard." }, { "code": null, "e": 2818, "s": 2700, "text": "XML is extremely useful for keeping track of small to medium amounts of data without requiring an SQL-based backbone." }, { "code": null, "e": 2912, "s": 2818, "text": "The Python standard library provides a minimal but useful set of interfaces to work with XML." }, { "code": null, "e": 2997, "s": 2912, "text": "The two most basic and broadly used APIs to XML data are the SAX and DOM interfaces." }, { "code": null, "e": 3306, "s": 2997, "text": "Simple API for XML (SAX) − Here, you register callbacks for events of interest and then let the parser proceed through the document. This is useful when your documents are large or you have memory limitations, it parses the file as it reads it from the disk and the entire file is never stored in the memory." }, { "code": null, "e": 3615, "s": 3306, "text": "Simple API for XML (SAX) − Here, you register callbacks for events of interest and then let the parser proceed through the document. This is useful when your documents are large or you have memory limitations, it parses the file as it reads it from the disk and the entire file is never stored in the memory." }, { "code": null, "e": 3846, "s": 3615, "text": "Document Object Model (DOM) API − This is a World Wide Web Consortium recommendation wherein the entire file is read into the memory and stored in a hierarchical (tree-based) form to represent all the features of an XML document.\n" }, { "code": null, "e": 4077, "s": 3846, "text": "Document Object Model (DOM) API − This is a World Wide Web Consortium recommendation wherein the entire file is read into the memory and stored in a hierarchical (tree-based) form to represent all the features of an XML document.\n" }, { "code": null, "e": 4278, "s": 4077, "text": "SAX obviously cannot process information as fast as DOM, when working with large files. On the other hand, using DOM exclusively can really kill your resources, especially if used on many small files." }, { "code": null, "e": 4470, "s": 4278, "text": "SAX is read-only, while DOM allows changes to the XML file. Since these two different APIs literally complement each other, there is no reason why you cannot use them both for large projects." }, { "code": null, "e": 4555, "s": 4470, "text": "For all our XML code examples, let us use a simple XML file movies.xml as an input −" }, { "code": null, "e": 5419, "s": 4555, "text": "<collection shelf = \"New Arrivals\">\n<movie title = \"Enemy Behind\">\n <type>War, Thriller</type>\n <format>DVD</format>\n <year>2003</year>\n <rating>PG</rating>\n <stars>10</stars>\n <description>Talk about a US-Japan war</description>\n</movie>\n<movie title = \"Transformers\">\n <type>Anime, Science Fiction</type>\n <format>DVD</format>\n <year>1989</year>\n <rating>R</rating>\n <stars>8</stars>\n <description>A schientific fiction</description>\n</movie>\n <movie title = \"Trigun\">\n <type>Anime, Action</type>\n <format>DVD</format>\n <episodes>4</episodes>\n <rating>PG</rating>\n <stars>10</stars>\n <description>Vash the Stampede!</description>\n</movie>\n<movie title = \"Ishtar\">\n <type>Comedy</type>\n <format>VHS</format>\n <rating>PG</rating>\n <stars>2</stars>\n <description>Viewable boredom</description>\n</movie>\n</collection>" }, { "code": null, "e": 5594, "s": 5419, "text": "SAX is a standard interface for event-driven XML parsing. Parsing XML with SAX generally requires you to create your own ContentHandler by subclassing xml.sax.ContentHandler." }, { "code": null, "e": 5832, "s": 5594, "text": "Your ContentHandler handles the particular tags and attributes of your flavor(s) of XML. A ContentHandler object provides methods to handle various parsing events. Its owning parser calls ContentHandler methods as it parses the XML file." }, { "code": null, "e": 6024, "s": 5832, "text": "The methods startDocument and endDocument are called at the start and the end of the XML file. The method characters(text) is passed the character data of the XML file via the parameter text." }, { "code": null, "e": 6356, "s": 6024, "text": "The ContentHandler is called at the start and end of each element. If the parser is not in namespace mode, the methods startElement(tag, attributes) and endElement(tag) are called; otherwise, the corresponding methods startElementNS and endElementNS are called. Here, tag is the element tag, and attributes is an Attributes object." }, { "code": null, "e": 6423, "s": 6356, "text": "Here are other important methods to understand before proceeding −" }, { "code": null, "e": 6566, "s": 6423, "text": "The following method creates a new parser object and returns it. The parser object created will be of the first parser type, the system finds." }, { "code": null, "e": 6603, "s": 6566, "text": "xml.sax.make_parser( [parser_list] )" }, { "code": null, "e": 6644, "s": 6603, "text": "Here are the details of the parameters −" }, { "code": null, "e": 6768, "s": 6644, "text": "parser_list − The optional argument consisting of a list of parsers to use which must all implement the make_parser method." }, { "code": null, "e": 6892, "s": 6768, "text": "parser_list − The optional argument consisting of a list of parsers to use which must all implement the make_parser method." }, { "code": null, "e": 6967, "s": 6892, "text": "The following method creates a SAX parser and uses it to parse a document." }, { "code": null, "e": 7023, "s": 6967, "text": "xml.sax.parse( xmlfile, contenthandler[, errorhandler])" }, { "code": null, "e": 7064, "s": 7023, "text": "Here are the details of the parameters −" }, { "code": null, "e": 7121, "s": 7064, "text": "xmlfile − This is the name of the XML file to read from." }, { "code": null, "e": 7178, "s": 7121, "text": "xmlfile − This is the name of the XML file to read from." }, { "code": null, "e": 7233, "s": 7178, "text": "contenthandler − This must be a ContentHandler object." }, { "code": null, "e": 7288, "s": 7233, "text": "contenthandler − This must be a ContentHandler object." }, { "code": null, "e": 7365, "s": 7288, "text": "errorhandler − If specified, errorhandler must be a SAX ErrorHandler object." }, { "code": null, "e": 7442, "s": 7365, "text": "errorhandler − If specified, errorhandler must be a SAX ErrorHandler object." }, { "code": null, "e": 7529, "s": 7442, "text": "There is one more method to create a SAX parser and to parse the specified XML string." }, { "code": null, "e": 7592, "s": 7529, "text": "xml.sax.parseString(xmlstring, contenthandler[, errorhandler])" }, { "code": null, "e": 7633, "s": 7592, "text": "Here are the details of the parameters −" }, { "code": null, "e": 7694, "s": 7633, "text": "xmlstring − This is the name of the XML string to read from." }, { "code": null, "e": 7755, "s": 7694, "text": "xmlstring − This is the name of the XML string to read from." }, { "code": null, "e": 7810, "s": 7755, "text": "contenthandler − This must be a ContentHandler object." }, { "code": null, "e": 7865, "s": 7810, "text": "contenthandler − This must be a ContentHandler object." }, { "code": null, "e": 7942, "s": 7865, "text": "errorhandler − If specified, errorhandler must be a SAX ErrorHandler object." }, { "code": null, "e": 8019, "s": 7942, "text": "errorhandler − If specified, errorhandler must be a SAX ErrorHandler object." }, { "code": null, "e": 9926, "s": 8019, "text": "#!/usr/bin/python3\n\nimport xml.sax\n\nclass MovieHandler( xml.sax.ContentHandler ):\n def __init__(self):\n self.CurrentData = \"\"\n self.type = \"\"\n self.format = \"\"\n self.year = \"\"\n self.rating = \"\"\n self.stars = \"\"\n self.description = \"\"\n\n # Call when an element starts\n def startElement(self, tag, attributes):\n self.CurrentData = tag\n if tag == \"movie\":\n print (\"*****Movie*****\")\n title = attributes[\"title\"]\n print (\"Title:\", title)\n\n # Call when an elements ends\n def endElement(self, tag):\n if self.CurrentData == \"type\":\n print (\"Type:\", self.type)\n elif self.CurrentData == \"format\":\n print (\"Format:\", self.format)\n elif self.CurrentData == \"year\":\n print (\"Year:\", self.year)\n elif self.CurrentData == \"rating\":\n print (\"Rating:\", self.rating)\n elif self.CurrentData == \"stars\":\n print (\"Stars:\", self.stars)\n elif self.CurrentData == \"description\":\n print (\"Description:\", self.description)\n self.CurrentData = \"\"\n\n # Call when a character is read\n def characters(self, content):\n if self.CurrentData == \"type\":\n self.type = content\n elif self.CurrentData == \"format\":\n self.format = content\n elif self.CurrentData == \"year\":\n self.year = content\n elif self.CurrentData == \"rating\":\n self.rating = content\n elif self.CurrentData == \"stars\":\n self.stars = content\n elif self.CurrentData == \"description\":\n self.description = content\n \nif ( __name__ == \"__main__\"):\n \n # create an XMLReader\n parser = xml.sax.make_parser()\n # turn off namepsaces\n parser.setFeature(xml.sax.handler.feature_namespaces, 0)\n\n # override the default ContextHandler\n Handler = MovieHandler()\n parser.setContentHandler( Handler )\n \n parser.parse(\"movies.xml\")" }, { "code": null, "e": 9968, "s": 9926, "text": "This would produce the following result −" }, { "code": null, "e": 10469, "s": 9968, "text": "*****Movie*****\nTitle: Enemy Behind\nType: War, Thriller\nFormat: DVD\nYear: 2003\nRating: PG\nStars: 10\nDescription: Talk about a US-Japan war\n*****Movie*****\nTitle: Transformers\nType: Anime, Science Fiction\nFormat: DVD\nYear: 1989\nRating: R\nStars: 8\nDescription: A scientific fiction\n*****Movie*****\nTitle: Trigun\nType: Anime, Action\nFormat: DVD\nRating: PG\nStars: 10\nDescription: Vash the Stampede!\n*****Movie*****\nTitle: Ishtar\nType: Comedy\nFormat: VHS\nRating: PG\nStars: 2\nDescription: Viewable boredom\n" }, { "code": null, "e": 10563, "s": 10469, "text": "For a complete detail on SAX API documentation, please refer to the standard Python SAX APIs." }, { "code": null, "e": 10709, "s": 10563, "text": "The Document Object Model (\"DOM\") is a cross-language API from the World Wide Web Consortium (W3C) for accessing and modifying the XML documents." }, { "code": null, "e": 10904, "s": 10709, "text": "The DOM is extremely useful for random-access applications. SAX only allows you a view of one bit of the document at a time. If you are looking at one SAX element, you have no access to another." }, { "code": null, "e": 11119, "s": 10904, "text": "Here is the easiest way to load an XML document quickly and to create a minidom object using the xml.dom module. The minidom object provides a simple parser method that quickly creates a DOM tree from the XML file." }, { "code": null, "e": 11268, "s": 11119, "text": "The sample phrase calls the parse( file [,parser] ) function of the minidom object to parse the XML file, designated by file into a DOM tree object." }, { "code": null, "e": 12264, "s": 11268, "text": "#!/usr/bin/python3\n\nfrom xml.dom.minidom import parse\nimport xml.dom.minidom\n\n# Open XML document using minidom parser\nDOMTree = xml.dom.minidom.parse(\"movies.xml\")\ncollection = DOMTree.documentElement\nif collection.hasAttribute(\"shelf\"):\n print (\"Root element : %s\" % collection.getAttribute(\"shelf\"))\n\n# Get all the movies in the collection\nmovies = collection.getElementsByTagName(\"movie\")\n\n# Print detail of each movie.\nfor movie in movies:\n print (\"*****Movie*****\")\n if movie.hasAttribute(\"title\"):\n print (\"Title: %s\" % movie.getAttribute(\"title\"))\n\n type = movie.getElementsByTagName('type')[0]\n print (\"Type: %s\" % type.childNodes[0].data)\n format = movie.getElementsByTagName('format')[0]\n print (\"Format: %s\" % format.childNodes[0].data)\n rating = movie.getElementsByTagName('rating')[0]\n print (\"Rating: %s\" % rating.childNodes[0].data)\n description = movie.getElementsByTagName('description')[0]\n print (\"Description: %s\" % description.childNodes[0].data)" }, { "code": null, "e": 12306, "s": 12264, "text": "This would produce the following result −" }, { "code": null, "e": 12775, "s": 12306, "text": "Root element : New Arrivals\n*****Movie*****\nTitle: Enemy Behind\nType: War, Thriller\nFormat: DVD\nRating: PG\nDescription: Talk about a US-Japan war\n*****Movie*****\nTitle: Transformers\nType: Anime, Science Fiction\nFormat: DVD\nRating: R\nDescription: A scientific fiction\n*****Movie*****\nTitle: Trigun\nType: Anime, Action\nFormat: DVD\nRating: PG\nDescription: Vash the Stampede!\n*****Movie*****\nTitle: Ishtar\nType: Comedy\nFormat: VHS\nRating: PG\nDescription: Viewable boredom\n" }, { "code": null, "e": 12869, "s": 12775, "text": "For a complete detail on DOM API documentation, please refer to the standard Python DOM APIs." }, { "code": null, "e": 12906, "s": 12869, "text": "\n 187 Lectures \n 17.5 hours \n" }, { "code": null, "e": 12922, "s": 12906, "text": " Malhar Lathkar" }, { "code": null, "e": 12955, "s": 12922, "text": "\n 55 Lectures \n 8 hours \n" }, { "code": null, "e": 12974, "s": 12955, "text": " Arnab Chakraborty" }, { "code": null, "e": 13009, "s": 12974, "text": "\n 136 Lectures \n 11 hours \n" }, { "code": null, "e": 13031, "s": 13009, "text": " In28Minutes Official" }, { "code": null, "e": 13065, "s": 13031, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 13093, "s": 13065, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 13128, "s": 13093, "text": "\n 70 Lectures \n 8.5 hours \n" }, { "code": null, "e": 13142, "s": 13128, "text": " Lets Kode It" }, { "code": null, "e": 13175, "s": 13142, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 13192, "s": 13175, "text": " Abhilash Nelson" }, { "code": null, "e": 13199, "s": 13192, "text": " Print" }, { "code": null, "e": 13210, "s": 13199, "text": " Add Notes" } ]
How to do online prediction with BigQuery ML | by Lak Lakshmanan | Towards Data Science
BigQuery ML is a way of doing machine learning directly in the petabyte-scale, interactive data warehouse on Google Cloud. You can train machine learning models on millions of rows in a few minutes without having to move data around. Note: BigQuery ML now supports extracting the trained model as a TensorFlow SavedModel. So you can simply export the model, and then deploy it to Cloud AI Platform Predictions. That said, this article is still useful as a reminder of how to view the weights and to reiterate the point that BQML is an open system. Having trained your model, though, you need to predict with it. Out of the box, BigQuery supports batch prediction — this is suitable for reporting and dashboard applications. However, BigQuery queries usually have a latency of 1–2 seconds and so, the batch prediction capability can not be used for online prediction (such as from a web or mobile application). In this article, I’ll show you how to pull out the necessary weights and scaling parameters from the training output tables and compute the prediction yourself. This code could be wrapped up in a web application framework or wherever you want the prediction code to live. The full code for this article is on GitHub. Let’s start by creating a simple prediction model to predict arrival delays of aircraft (for more details, see this article). I’ll use this model to illustrate the process. CREATE OR REPLACE MODEL flights.arrdelayOPTIONS (model_type='linear_reg', input_label_cols=['arr_delay']) ASSELECT arr_delay, carrier, origin, dest, dep_delay, taxi_out, distanceFROM `cloud-training-demos.flights.tzcorr`WHERE arr_delay IS NOT NULL This took me about 6 minutes, trained on 6 million rows and 267 MB data, and cost about $1.25. (BigQuery‘s free tier might cover this for you; to reduce the cost, use a smaller table). Once you have a trained model, batch prediction can be done within BigQuery itself. For example, to find the predicted arrival delays for a flight from DFW to LAX for a range of departure delays, you could run this query: SELECT * FROM ml.PREDICT(MODEL flights.arrdelay, (SELECT 'AA' as carrier, 'DFW' as origin, 'LAX' as dest, dep_delay, 18 as taxi_out, 1235 as distanceFROM UNNEST(GENERATE_ARRAY(-3, 10)) as dep_delay)) In the query above, I am hardcoding the input values for carrier, origin, etc. and using the GENERATE_ARRAY function to generate departure delays in the range -3 minutes to 10 minutes. This yields a table with predicted arrival delays for each departure delay: Batch prediction is inexpensive. The above query processed 16 KB and cost 0.000008 cents. While this prediction mechanism works for offline predictions, you can not realistically use it for online prediction. If the predictions are to be displayed as a result of user interactions in a website or mobile application, you can not afford the 1–2 second latency associated with each BigQuery call. You typically want latencies on the order of a few milliseconds and so you need a faster inference solution. Fortunately, BigQuery exposes all the necessary information to compute the prediction value yourself. You can embed this code directly into your application. I’m illustrating this in Python, but you can do this in pretty much any language you want. You need to pull 3 pieces of information: The weights for each of your numeric columns which you can get using this query: SELECT processed_input AS input, model.weight AS input_weightFROM ml.WEIGHTS(MODEL flights.arrdelay) AS model The scaling for each of your numeric columns which you can get using this query: SELECT input, min, max, mean, stddevFROM ml.FEATURE_INFO(MODEL flights.arrdelay) AS model The vocabulary and weights for each of your categorical columns which you can get using this query (If you are not familiar with UNNEST, see this article): SELECT processed_input AS input, model.weight AS input_weight, category.category AS category_name, category.weight AS category_weightFROM ml.WEIGHTS(MODEL flights.arrdelay) AS model, UNNEST(category_weights) AS category Assuming that you have read the results of all three of these queries into three separate Pandas Dataframes, here is a function that will calculate the prediction: What I am doing is this: I am walking through each of the numeric columns and finding the weight associated with that column. Then, I pull out the mean and standard deviation and use them to scale the input value. The product of the two is the contribution associated with this column. Then, I walk through the categorical columns. For each categorical column, there is a separate weight associated with each value that the column takes. So, I find the weight associated with the input value — this becomes the contribution. The sum of all the contributions is the prediction. The above code assumes that you trained a regression model. If you trained a classification model, you need to apply a logistic function to the prediction to get the probability (to avoid overflow, treat the probability for pred < -500 as zero): prob = (1.0/(1 + np.exp(-pred)) if (-500 < pred) else 0) Here is an example of predicting the arrival delay of a specific flight: rowdict = { 'carrier' : 'AA', 'origin': 'DFW', 'dest': 'LAX', 'dep_delay': -3, 'taxi_out': 18, 'distance': 1235}predicted_arrival_delay = compute_prediction( rowdict, numeric_weights, scaling_df, categorical_weights) This yields the following columns and their contributions: col=dep_delay wt=36.5569545237 scaled_value=-0.329782492822 contrib=-12.0558435928col=taxi_out wt=8.15557957221 scaled_value=0.213461991601 contrib=1.74090625815col=distance wt=-1.88324519311 scaled_value=0.672196648431 contrib=-1.26591110699col=__INTERCEPT__ wt=1.09017737502 scaled_value=1.0 contrib=1.09017737502col=carrier wt=-0.0548843604154 value=AA contrib=-0.0548843604154col=origin wt=0.966535564037 value=DFW contrib=0.966535564037col=dest wt=1.26816262538 value=LAX contrib=1.26816262538 The total of the contributions is -8.31 minutes, which matches the batch prediction value, confirming that the code is correct. The full code for this article is on GitHub. Enjoy!
[ { "code": null, "e": 406, "s": 172, "text": "BigQuery ML is a way of doing machine learning directly in the petabyte-scale, interactive data warehouse on Google Cloud. You can train machine learning models on millions of rows in a few minutes without having to move data around." }, { "code": null, "e": 720, "s": 406, "text": "Note: BigQuery ML now supports extracting the trained model as a TensorFlow SavedModel. So you can simply export the model, and then deploy it to Cloud AI Platform Predictions. That said, this article is still useful as a reminder of how to view the weights and to reiterate the point that BQML is an open system." }, { "code": null, "e": 1082, "s": 720, "text": "Having trained your model, though, you need to predict with it. Out of the box, BigQuery supports batch prediction — this is suitable for reporting and dashboard applications. However, BigQuery queries usually have a latency of 1–2 seconds and so, the batch prediction capability can not be used for online prediction (such as from a web or mobile application)." }, { "code": null, "e": 1354, "s": 1082, "text": "In this article, I’ll show you how to pull out the necessary weights and scaling parameters from the training output tables and compute the prediction yourself. This code could be wrapped up in a web application framework or wherever you want the prediction code to live." }, { "code": null, "e": 1399, "s": 1354, "text": "The full code for this article is on GitHub." }, { "code": null, "e": 1572, "s": 1399, "text": "Let’s start by creating a simple prediction model to predict arrival delays of aircraft (for more details, see this article). I’ll use this model to illustrate the process." }, { "code": null, "e": 1830, "s": 1572, "text": "CREATE OR REPLACE MODEL flights.arrdelayOPTIONS (model_type='linear_reg', input_label_cols=['arr_delay']) ASSELECT arr_delay, carrier, origin, dest, dep_delay, taxi_out, distanceFROM `cloud-training-demos.flights.tzcorr`WHERE arr_delay IS NOT NULL" }, { "code": null, "e": 2015, "s": 1830, "text": "This took me about 6 minutes, trained on 6 million rows and 267 MB data, and cost about $1.25. (BigQuery‘s free tier might cover this for you; to reduce the cost, use a smaller table)." }, { "code": null, "e": 2237, "s": 2015, "text": "Once you have a trained model, batch prediction can be done within BigQuery itself. For example, to find the predicted arrival delays for a flight from DFW to LAX for a range of departure delays, you could run this query:" }, { "code": null, "e": 2445, "s": 2237, "text": "SELECT * FROM ml.PREDICT(MODEL flights.arrdelay, (SELECT 'AA' as carrier, 'DFW' as origin, 'LAX' as dest, dep_delay, 18 as taxi_out, 1235 as distanceFROM UNNEST(GENERATE_ARRAY(-3, 10)) as dep_delay))" }, { "code": null, "e": 2706, "s": 2445, "text": "In the query above, I am hardcoding the input values for carrier, origin, etc. and using the GENERATE_ARRAY function to generate departure delays in the range -3 minutes to 10 minutes. This yields a table with predicted arrival delays for each departure delay:" }, { "code": null, "e": 2796, "s": 2706, "text": "Batch prediction is inexpensive. The above query processed 16 KB and cost 0.000008 cents." }, { "code": null, "e": 3210, "s": 2796, "text": "While this prediction mechanism works for offline predictions, you can not realistically use it for online prediction. If the predictions are to be displayed as a result of user interactions in a website or mobile application, you can not afford the 1–2 second latency associated with each BigQuery call. You typically want latencies on the order of a few milliseconds and so you need a faster inference solution." }, { "code": null, "e": 3459, "s": 3210, "text": "Fortunately, BigQuery exposes all the necessary information to compute the prediction value yourself. You can embed this code directly into your application. I’m illustrating this in Python, but you can do this in pretty much any language you want." }, { "code": null, "e": 3501, "s": 3459, "text": "You need to pull 3 pieces of information:" }, { "code": null, "e": 3582, "s": 3501, "text": "The weights for each of your numeric columns which you can get using this query:" }, { "code": null, "e": 3695, "s": 3582, "text": "SELECT processed_input AS input, model.weight AS input_weightFROM ml.WEIGHTS(MODEL flights.arrdelay) AS model" }, { "code": null, "e": 3776, "s": 3695, "text": "The scaling for each of your numeric columns which you can get using this query:" }, { "code": null, "e": 3868, "s": 3776, "text": "SELECT input, min, max, mean, stddevFROM ml.FEATURE_INFO(MODEL flights.arrdelay) AS model" }, { "code": null, "e": 4024, "s": 3868, "text": "The vocabulary and weights for each of your categorical columns which you can get using this query (If you are not familiar with UNNEST, see this article):" }, { "code": null, "e": 4250, "s": 4024, "text": "SELECT processed_input AS input, model.weight AS input_weight, category.category AS category_name, category.weight AS category_weightFROM ml.WEIGHTS(MODEL flights.arrdelay) AS model, UNNEST(category_weights) AS category" }, { "code": null, "e": 4414, "s": 4250, "text": "Assuming that you have read the results of all three of these queries into three separate Pandas Dataframes, here is a function that will calculate the prediction:" }, { "code": null, "e": 4991, "s": 4414, "text": "What I am doing is this: I am walking through each of the numeric columns and finding the weight associated with that column. Then, I pull out the mean and standard deviation and use them to scale the input value. The product of the two is the contribution associated with this column. Then, I walk through the categorical columns. For each categorical column, there is a separate weight associated with each value that the column takes. So, I find the weight associated with the input value — this becomes the contribution. The sum of all the contributions is the prediction." }, { "code": null, "e": 5237, "s": 4991, "text": "The above code assumes that you trained a regression model. If you trained a classification model, you need to apply a logistic function to the prediction to get the probability (to avoid overflow, treat the probability for pred < -500 as zero):" }, { "code": null, "e": 5294, "s": 5237, "text": "prob = (1.0/(1 + np.exp(-pred)) if (-500 < pred) else 0)" }, { "code": null, "e": 5367, "s": 5294, "text": "Here is an example of predicting the arrival delay of a specific flight:" }, { "code": null, "e": 5592, "s": 5367, "text": "rowdict = { 'carrier' : 'AA', 'origin': 'DFW', 'dest': 'LAX', 'dep_delay': -3, 'taxi_out': 18, 'distance': 1235}predicted_arrival_delay = compute_prediction( rowdict, numeric_weights, scaling_df, categorical_weights)" }, { "code": null, "e": 5651, "s": 5592, "text": "This yields the following columns and their contributions:" }, { "code": null, "e": 6150, "s": 5651, "text": "col=dep_delay wt=36.5569545237 scaled_value=-0.329782492822 contrib=-12.0558435928col=taxi_out wt=8.15557957221 scaled_value=0.213461991601 contrib=1.74090625815col=distance wt=-1.88324519311 scaled_value=0.672196648431 contrib=-1.26591110699col=__INTERCEPT__ wt=1.09017737502 scaled_value=1.0 contrib=1.09017737502col=carrier wt=-0.0548843604154 value=AA contrib=-0.0548843604154col=origin wt=0.966535564037 value=DFW contrib=0.966535564037col=dest wt=1.26816262538 value=LAX contrib=1.26816262538" }, { "code": null, "e": 6278, "s": 6150, "text": "The total of the contributions is -8.31 minutes, which matches the batch prediction value, confirming that the code is correct." } ]
Accessing variables of a data frame in R Programming - attach() and detach() function - GeeksforGeeks
23 Dec, 2021 In this article, we will see how to Access variables of a data frame in R Programming Language. attach() function in R Language is used to access the variables present in the data framework without calling the data frame. Syntax: attach(data, pos) Parameters: data: data frame pos: position of database Example: Accessing variables of a data frame in R using attach() function R # R program to illustrate# attach function # Create example datadata <- data.frame(x1 = c(1, 2, 3, 4, 5), x2 = c(6, 7, 8, 9, 0), x3 = c(1, 2, 5, 4, 5)) # Try to print x1# Error: object 'x1' not found # attach dataattach(data, pos = x1) Output: 1 2 3 4 5 Here in the above code, we have created a data framework and assigned a value to it, when we tried to return value an error occurred. Then we use the attach function and returned value of x1. detach() function is used to remove the attachment in data framework that was made by attach() function. Syntax: detach(data, unload) Parameters: data: data frame unload: boolean value Example: Accessing variables of a data frame in R using detach() Function R # R program to illustrate# detach function # Install dplyr packageinstall.packages("dplyr") # attach dplyrlibrary("dplyr") # Apply as.tbl function of dplyr packagedata_tbl <- as.tbl(data) detach("package:dplyr", unload = FALSE) # Apply as.tbl after detaching dplyr packagedata_tbl <- as.tbl(data) Output: Error in as.tbl(data) : could not find function “as.tbl” Here in the above code, we have installed a dplyr package and used its function as.tbl. Then we detach the package and try to use the function again, and an error occurred. detach functions are used to unpack the libraries which were added to the library. kumar_satyam R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Replace specific values in column in R DataFrame ? Filter data by multiple conditions in R using Dplyr Loops in R (for, while, repeat) Change Color of Bars in Barchart using ggplot2 in R How to change Row Names of DataFrame in R ? Printing Output of an R Program How to Change Axis Scales in R Plots? Group by function in R using Dplyr Remove rows with NA in one column of R DataFrame K-Means Clustering in R Programming
[ { "code": null, "e": 24888, "s": 24860, "text": "\n23 Dec, 2021" }, { "code": null, "e": 24984, "s": 24888, "text": "In this article, we will see how to Access variables of a data frame in R Programming Language." }, { "code": null, "e": 25110, "s": 24984, "text": "attach() function in R Language is used to access the variables present in the data framework without calling the data frame." }, { "code": null, "e": 25136, "s": 25110, "text": "Syntax: attach(data, pos)" }, { "code": null, "e": 25149, "s": 25136, "text": "Parameters: " }, { "code": null, "e": 25166, "s": 25149, "text": "data: data frame" }, { "code": null, "e": 25192, "s": 25166, "text": "pos: position of database" }, { "code": null, "e": 25266, "s": 25192, "text": "Example: Accessing variables of a data frame in R using attach() function" }, { "code": null, "e": 25268, "s": 25266, "text": "R" }, { "code": "# R program to illustrate# attach function # Create example datadata <- data.frame(x1 = c(1, 2, 3, 4, 5), x2 = c(6, 7, 8, 9, 0), x3 = c(1, 2, 5, 4, 5)) # Try to print x1# Error: object 'x1' not found # attach dataattach(data, pos = x1) ", "e": 25584, "s": 25268, "text": null }, { "code": null, "e": 25593, "s": 25584, "text": "Output: " }, { "code": null, "e": 25603, "s": 25593, "text": "1 2 3 4 5" }, { "code": null, "e": 25795, "s": 25603, "text": "Here in the above code, we have created a data framework and assigned a value to it, when we tried to return value an error occurred. Then we use the attach function and returned value of x1." }, { "code": null, "e": 25900, "s": 25795, "text": "detach() function is used to remove the attachment in data framework that was made by attach() function." }, { "code": null, "e": 25929, "s": 25900, "text": "Syntax: detach(data, unload)" }, { "code": null, "e": 25942, "s": 25929, "text": "Parameters: " }, { "code": null, "e": 25959, "s": 25942, "text": "data: data frame" }, { "code": null, "e": 25981, "s": 25959, "text": "unload: boolean value" }, { "code": null, "e": 26056, "s": 25981, "text": "Example: Accessing variables of a data frame in R using detach() Function " }, { "code": null, "e": 26058, "s": 26056, "text": "R" }, { "code": "# R program to illustrate# detach function # Install dplyr packageinstall.packages(\"dplyr\") # attach dplyrlibrary(\"dplyr\") # Apply as.tbl function of dplyr packagedata_tbl <- as.tbl(data) detach(\"package:dplyr\", unload = FALSE) # Apply as.tbl after detaching dplyr packagedata_tbl <- as.tbl(data)", "e": 26409, "s": 26058, "text": null }, { "code": null, "e": 26418, "s": 26409, "text": "Output: " }, { "code": null, "e": 26475, "s": 26418, "text": "Error in as.tbl(data) : could not find function “as.tbl”" }, { "code": null, "e": 26731, "s": 26475, "text": "Here in the above code, we have installed a dplyr package and used its function as.tbl. Then we detach the package and try to use the function again, and an error occurred. detach functions are used to unpack the libraries which were added to the library." }, { "code": null, "e": 26744, "s": 26731, "text": "kumar_satyam" }, { "code": null, "e": 26755, "s": 26744, "text": "R Language" }, { "code": null, "e": 26853, "s": 26755, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26911, "s": 26853, "text": "How to Replace specific values in column in R DataFrame ?" }, { "code": null, "e": 26963, "s": 26911, "text": "Filter data by multiple conditions in R using Dplyr" }, { "code": null, "e": 26995, "s": 26963, "text": "Loops in R (for, while, repeat)" }, { "code": null, "e": 27047, "s": 26995, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 27091, "s": 27047, "text": "How to change Row Names of DataFrame in R ?" }, { "code": null, "e": 27123, "s": 27091, "text": "Printing Output of an R Program" }, { "code": null, "e": 27161, "s": 27123, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 27196, "s": 27161, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 27245, "s": 27196, "text": "Remove rows with NA in one column of R DataFrame" } ]
Angular 10 NgTemplateOutlet Directive - GeeksforGeeks
03 Jun, 2021 In this article, we are going to see what is NgTemplateOutlet in Angular 10 and how to use it. The NgTemplateOutlet in Angular10 is used to insert an embedded view from a prepared TemplateRef. NgTemplateOutlet adds the reference element which is displayed on the page. Syntax: <li *NgTemplateOutlet='condition'></li> NgModule: Module used by NgTemplateOutlet is: CommonModule Selectors: [NgTemplateOutlet] Approach: Create an angular app to be used. There is no need for any import for the NgIf to be used. in app.component.html add NgTemplateOutlet Directive to the element with its reference. Serve the angular app using ng serve to see the output. Example 1: app.component.html <ng-container *ngTemplateOutlet="gfg"></ng-container> <ng-template #gfg> <h1>GeeksforGeeks</h1> <div> ngTemplateOutlet Directive </div></ng-template> Output: Example 2: app.component.html <div *ngTemplateOutlet="gfg"></div> <ng-template #gfg> <h1> GeeksforGeeks </h1> <div> We can also use ngTemplateOutlet Directive with a div </div></ng-template> Output: Reference: https://angular.io/api/common/NgTemplateOutlet Angular10 AngularJS-Directives AngularJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Top 10 Angular Libraries For Web Developers Angular PrimeNG Dropdown Component Angular 10 (blur) Event How to make a Bootstrap Modal Popup in Angular 9/8 ? How to create module with Routing in Angular 9 ? Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills Convert a string to an integer in JavaScript
[ { "code": null, "e": 25109, "s": 25081, "text": "\n03 Jun, 2021" }, { "code": null, "e": 25204, "s": 25109, "text": "In this article, we are going to see what is NgTemplateOutlet in Angular 10 and how to use it." }, { "code": null, "e": 25378, "s": 25204, "text": "The NgTemplateOutlet in Angular10 is used to insert an embedded view from a prepared TemplateRef. NgTemplateOutlet adds the reference element which is displayed on the page." }, { "code": null, "e": 25386, "s": 25378, "text": "Syntax:" }, { "code": null, "e": 25426, "s": 25386, "text": "<li *NgTemplateOutlet='condition'></li>" }, { "code": null, "e": 25472, "s": 25426, "text": "NgModule: Module used by NgTemplateOutlet is:" }, { "code": null, "e": 25485, "s": 25472, "text": "CommonModule" }, { "code": null, "e": 25498, "s": 25487, "text": "Selectors:" }, { "code": null, "e": 25517, "s": 25498, "text": "[NgTemplateOutlet]" }, { "code": null, "e": 25528, "s": 25517, "text": "Approach: " }, { "code": null, "e": 25562, "s": 25528, "text": "Create an angular app to be used." }, { "code": null, "e": 25619, "s": 25562, "text": "There is no need for any import for the NgIf to be used." }, { "code": null, "e": 25707, "s": 25619, "text": "in app.component.html add NgTemplateOutlet Directive to the element with its reference." }, { "code": null, "e": 25763, "s": 25707, "text": "Serve the angular app using ng serve to see the output." }, { "code": null, "e": 25774, "s": 25763, "text": "Example 1:" }, { "code": null, "e": 25793, "s": 25774, "text": "app.component.html" }, { "code": "<ng-container *ngTemplateOutlet=\"gfg\"></ng-container> <ng-template #gfg> <h1>GeeksforGeeks</h1> <div> ngTemplateOutlet Directive </div></ng-template>", "e": 25962, "s": 25793, "text": null }, { "code": null, "e": 25970, "s": 25962, "text": "Output:" }, { "code": null, "e": 25981, "s": 25970, "text": "Example 2:" }, { "code": null, "e": 26000, "s": 25981, "text": "app.component.html" }, { "code": "<div *ngTemplateOutlet=\"gfg\"></div> <ng-template #gfg> <h1> GeeksforGeeks </h1> <div> We can also use ngTemplateOutlet Directive with a div </div></ng-template>", "e": 26189, "s": 26000, "text": null }, { "code": null, "e": 26197, "s": 26189, "text": "Output:" }, { "code": null, "e": 26255, "s": 26197, "text": "Reference: https://angular.io/api/common/NgTemplateOutlet" }, { "code": null, "e": 26265, "s": 26255, "text": "Angular10" }, { "code": null, "e": 26286, "s": 26265, "text": "AngularJS-Directives" }, { "code": null, "e": 26296, "s": 26286, "text": "AngularJS" }, { "code": null, "e": 26313, "s": 26296, "text": "Web Technologies" }, { "code": null, "e": 26411, "s": 26313, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26455, "s": 26411, "text": "Top 10 Angular Libraries For Web Developers" }, { "code": null, "e": 26490, "s": 26455, "text": "Angular PrimeNG Dropdown Component" }, { "code": null, "e": 26514, "s": 26490, "text": "Angular 10 (blur) Event" }, { "code": null, "e": 26567, "s": 26514, "text": "How to make a Bootstrap Modal Popup in Angular 9/8 ?" }, { "code": null, "e": 26616, "s": 26567, "text": "How to create module with Routing in Angular 9 ?" }, { "code": null, "e": 26658, "s": 26616, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 26691, "s": 26658, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 26734, "s": 26691, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 26796, "s": 26734, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" } ]
How to download images using Invoke-Webrequest in PowerShell?
To download the images from the webpage using the Invoke-WebRequest command, we can use the images property from the result to retrieve the images URL, and later we can use the method to download them at the specific location. Consider we have the URI: https://theautomationcode.com to retrieve the images. Once you run the below command, you can see the Images property there. Invoke-WebRequest -Uri "https://theautomationcode.com/feed/" To retrieves the images URL, $req = Invoke-WebRequest -Uri "https://theautomationcode.com/feed/" $req.Images | Select -ExpandProperty src https://i1.wp.com/theautomationcode.com/wp-content/uploads/2020/11/image-9.png?resize=178%2C60&ssl=1 https://i0.wp.com/theautomationcode.com/wp-content/uploads/2020/11/image-10.png?resize=640%2C68&ssl=1 All the above URLs point to the images, so we can download that. $wc = New-Object System.Net.WebClient $req = Invoke-WebRequest -Uri "https://theautomationcode.com/feed/" $images = $req.Images | Select -ExpandProperty src $count = 0 foreach($img in $images){ $wc.DownloadFile($img,"C:\Temp\WebImages\img$count.jpg") } The output images will be stored in the C:\temp\WebImages folder.
[ { "code": null, "e": 1369, "s": 1062, "text": "To download the images from the webpage using the Invoke-WebRequest command, we can use the images property from the result to retrieve the images URL, and later we can use the method to download them at the specific location. Consider we have the URI: https://theautomationcode.com to retrieve the images." }, { "code": null, "e": 1440, "s": 1369, "text": "Once you run the below command, you can see the Images property there." }, { "code": null, "e": 1501, "s": 1440, "text": "Invoke-WebRequest -Uri \"https://theautomationcode.com/feed/\"" }, { "code": null, "e": 1530, "s": 1501, "text": "To retrieves the images URL," }, { "code": null, "e": 1639, "s": 1530, "text": "$req = Invoke-WebRequest -Uri \"https://theautomationcode.com/feed/\"\n$req.Images | Select -ExpandProperty src" }, { "code": null, "e": 1842, "s": 1639, "text": "https://i1.wp.com/theautomationcode.com/wp-content/uploads/2020/11/image-9.png?resize=178%2C60&ssl=1 https://i0.wp.com/theautomationcode.com/wp-content/uploads/2020/11/image-10.png?resize=640%2C68&ssl=1" }, { "code": null, "e": 1907, "s": 1842, "text": "All the above URLs point to the images, so we can download that." }, { "code": null, "e": 2167, "s": 1907, "text": "$wc = New-Object System.Net.WebClient\n$req = Invoke-WebRequest -Uri \"https://theautomationcode.com/feed/\"\n$images = $req.Images | Select -ExpandProperty src\n$count = 0\nforeach($img in $images){ \n $wc.DownloadFile($img,\"C:\\Temp\\WebImages\\img$count.jpg\")\n}" }, { "code": null, "e": 2233, "s": 2167, "text": "The output images will be stored in the C:\\temp\\WebImages folder." } ]
Convert the given BCD to its equivalent Binary form - GeeksforGeeks
11 Jun, 2021 Given a BCD (Binary Coded Decimal), the task is to convert this to its equivalent Binary number. Examples: Input: 1001000 Output: 110000 Explanation: Integer value of the given BCD is 48(0100 -> 4, 1000 -> 8). (48)10 = (110000)2Input: 1001001 Output: 110001 Approach: In order to solve this problem we need to split the given BCD number into binary chunks of length 4 and convert them to integer one by one to generate the final integer representation of the given BCD. Once generated, convert the integer to its binary form.Below is the implementation of the above approach. C++ Java Python3 C# Javascript // C++ code to convert BCD to its// equivalent Binary #include <bits/stdc++.h>using namespace std; // Function to convert BCD to Decimalstring bcdToBinary(string s){ int l = s.length(); int num = 0; int mul = 1; int sum = 0; // If the length of given BCD is not // divisible by 4 for (int i = l % 4 - 1; i >= 0; i--) { sum += (s[i] - '0') * mul; mul *= 2; } num = sum; sum = 0; mul = pow(2, 3); int ctr = 0; for (int i = l % 4; i < l; i++) { ctr++; sum += (s[i] - '0') * mul; mul /= 2; if (ctr == 4) { num = num * 10 + sum; sum = 0; mul = pow(2, 3); ctr = 0; } } // Convert decimal to binary string ans = ""; while (num > 0) { ans += (char)(num % 2 + '0'); num /= 2; } reverse(ans.begin(), ans.end()); return ans;} // Driver Codeint main(){ string s = "1001000"; // Function Call cout << bcdToBinary(s); return 0;} // Java code to convert BCD to its// equivalent Binaryimport java.io.*;import java.util.*; class GFG{ // Function to convert BCD to Decimalstatic String bcdToBinary(String s){ int l = s.length(); int num = 0; int mul = 1; int sum = 0; // If the length of given BCD is not // divisible by 4 for(int i = l % 4 - 1; i >= 0; i--) { sum += (s.charAt(i) - '0') * mul; mul *= 2; } num = sum; sum = 0; mul = (int)Math.pow(2, 3); int ctr = 0; for(int i = l % 4; i < l; i++) { ctr++; sum += (s.charAt(i) - '0') * mul; mul /= 2; if (ctr == 4) { num = num * 10 + sum; sum = 0; mul = (int)Math.pow(2, 3); ctr = 0; } } // Convert decimal to binary String ans = ""; while (num > 0) { ans += (char)(num % 2 + '0'); num /= 2; } StringBuilder ans1 = new StringBuilder(); // Append a string into StringBuilder input1 ans1.append(ans); // Reverse StringBuilder input1 ans = ans1.reverse().toString(); return ans;} // Driver codepublic static void main(String[] args){ String s = "1001000"; // Function call System.out.println(bcdToBinary(s));}} // This code is contributed by coder001 # Python3 code to convert# BCD to its equivalent Binary # Function to convert# BCD to Decimaldef bcdToBinary(s): l = len(s) num = 0; mul = 1; sum = 0; # If the length of given # BCD is not divisible by 4 for i in range(l % 4 - 1, -1, -1): sum += (ord(s[i]) - ord('0')) * mul; mul *= 2; num = sum; sum = 0; mul = pow(2, 3); ctr = 0; for i in range(l % 4, l): ctr += 1; sum += (ord(s[i]) - ord('0')) * mul; mul //= 2; if (ctr == 4): num = num * 10 + sum; sum = 0; mul = pow(2, 3); ctr = 0; # Convert decimal to binary ans = ""; while (num > 0): ans += (chr((num % 2) + ord('0'))); num //= 2; ans = ans[:: -1] return ans; # Driver codeif __name__ == "__main__": s = "1001000"; # Function Call print(bcdToBinary(s)); # This code is contributed by rutvik_56 // C# code to convert BCD to its// equivalent Binaryusing System;using System.Text;public class GFG{ // Function to convert BCD to Decimalstatic String bcdToBinary(String s){ int l = s.Length; int num = 0; int mul = 1; int sum = 0; // If the length of given BCD is not // divisible by 4 for(int i = l % 4 - 1; i >= 0; i--) { sum += (s[i] - '0') * mul; mul *= 2; } num = sum; sum = 0; mul = (int)Math.Pow(2, 3); int ctr = 0; for(int i = l % 4; i < l; i++) { ctr++; sum += (s[i] - '0') * mul; mul /= 2; if (ctr == 4) { num = num * 10 + sum; sum = 0; mul = (int)Math.Pow(2, 3); ctr = 0; } } // Convert decimal to binary String ans = ""; while (num > 0) { ans += (char)(num % 2 + '0'); num /= 2; } StringBuilder ans1 = new StringBuilder(); // Append a string into StringBuilder input1 ans1.Append(ans); // Reverse StringBuilder input1 ans = reverse(ans1.ToString()); return ans;}static String reverse(String input){ char[] a = input.ToCharArray(); int l, r = a.Length - 1; for (l = 0; l < r; l++, r--) { char temp = a[l]; a[l] = a[r]; a[r] = temp; } return String.Join("",a); } // Driver codepublic static void Main(String[] args){ String s = "1001000"; // Function call Console.WriteLine(bcdToBinary(s));}} // This code is contributed by shikhasingrajput <script>// Javascript code to convert BCD to its// equivalent Binary // Function to convert BCD to Decimalfunction bcdToBinary(s){ let l = s.length; let num = 0; let mul = 1; let sum = 0; // If the length of given BCD is not // divisible by 4 for (let i = l % 4 - 1; i >= 0; i--) { sum += (s[i].charCodeAt(0) - '0'.charCodeAt(0)) * mul; mul *= 2; } num = sum; sum = 0; mul = Math.pow(2, 3); let ctr = 0; for (let i = l % 4; i < l; i++) { ctr++; sum += (s[i].charCodeAt(0) - '0'.charCodeAt(0)) * mul; mul = Math.floor(mul / 2); if (ctr == 4) { num = num * 10 + sum; sum = 0; mul = Math.pow(2, 3); ctr = 0; } } // Convert decimal to binary let ans = ""; while (num > 0) { ans += String.fromCharCode(num % 2 + '0'.charCodeAt(0)); num = Math.floor(num / 2); } ans = ans.split("").reverse().join("") console.log(ans) return ans;} // Driver Codelet s = "1001000"; // Function Calldocument.write(bcdToBinary(s)); // This code is contributed by _saurabh_jaiswal</script> 110000 Time Complexity: O(N) where N denotes the length of the BCD string provided Auxiliary Space: O(1) coder001 shikhasingrajput rutvik_56 _saurabh_jaiswal base-conversion Bit Magic Mathematical Mathematical Bit Magic Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Set, Clear and Toggle a given bit of a number in C Check whether K-th bit is set or not Write an Efficient Method to Check if a Number is Multiple of 3 Reverse actual bits of the given number Program to find parity 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": 24597, "s": 24569, "text": "\n11 Jun, 2021" }, { "code": null, "e": 24705, "s": 24597, "text": "Given a BCD (Binary Coded Decimal), the task is to convert this to its equivalent Binary number. Examples: " }, { "code": null, "e": 24857, "s": 24705, "text": "Input: 1001000 Output: 110000 Explanation: Integer value of the given BCD is 48(0100 -> 4, 1000 -> 8). (48)10 = (110000)2Input: 1001001 Output: 110001 " }, { "code": null, "e": 25176, "s": 24857, "text": "Approach: In order to solve this problem we need to split the given BCD number into binary chunks of length 4 and convert them to integer one by one to generate the final integer representation of the given BCD. Once generated, convert the integer to its binary form.Below is the implementation of the above approach. " }, { "code": null, "e": 25180, "s": 25176, "text": "C++" }, { "code": null, "e": 25185, "s": 25180, "text": "Java" }, { "code": null, "e": 25193, "s": 25185, "text": "Python3" }, { "code": null, "e": 25196, "s": 25193, "text": "C#" }, { "code": null, "e": 25207, "s": 25196, "text": "Javascript" }, { "code": "// C++ code to convert BCD to its// equivalent Binary #include <bits/stdc++.h>using namespace std; // Function to convert BCD to Decimalstring bcdToBinary(string s){ int l = s.length(); int num = 0; int mul = 1; int sum = 0; // If the length of given BCD is not // divisible by 4 for (int i = l % 4 - 1; i >= 0; i--) { sum += (s[i] - '0') * mul; mul *= 2; } num = sum; sum = 0; mul = pow(2, 3); int ctr = 0; for (int i = l % 4; i < l; i++) { ctr++; sum += (s[i] - '0') * mul; mul /= 2; if (ctr == 4) { num = num * 10 + sum; sum = 0; mul = pow(2, 3); ctr = 0; } } // Convert decimal to binary string ans = \"\"; while (num > 0) { ans += (char)(num % 2 + '0'); num /= 2; } reverse(ans.begin(), ans.end()); return ans;} // Driver Codeint main(){ string s = \"1001000\"; // Function Call cout << bcdToBinary(s); return 0;}", "e": 26215, "s": 25207, "text": null }, { "code": "// Java code to convert BCD to its// equivalent Binaryimport java.io.*;import java.util.*; class GFG{ // Function to convert BCD to Decimalstatic String bcdToBinary(String s){ int l = s.length(); int num = 0; int mul = 1; int sum = 0; // If the length of given BCD is not // divisible by 4 for(int i = l % 4 - 1; i >= 0; i--) { sum += (s.charAt(i) - '0') * mul; mul *= 2; } num = sum; sum = 0; mul = (int)Math.pow(2, 3); int ctr = 0; for(int i = l % 4; i < l; i++) { ctr++; sum += (s.charAt(i) - '0') * mul; mul /= 2; if (ctr == 4) { num = num * 10 + sum; sum = 0; mul = (int)Math.pow(2, 3); ctr = 0; } } // Convert decimal to binary String ans = \"\"; while (num > 0) { ans += (char)(num % 2 + '0'); num /= 2; } StringBuilder ans1 = new StringBuilder(); // Append a string into StringBuilder input1 ans1.append(ans); // Reverse StringBuilder input1 ans = ans1.reverse().toString(); return ans;} // Driver codepublic static void main(String[] args){ String s = \"1001000\"; // Function call System.out.println(bcdToBinary(s));}} // This code is contributed by coder001", "e": 27522, "s": 26215, "text": null }, { "code": "# Python3 code to convert# BCD to its equivalent Binary # Function to convert# BCD to Decimaldef bcdToBinary(s): l = len(s) num = 0; mul = 1; sum = 0; # If the length of given # BCD is not divisible by 4 for i in range(l % 4 - 1, -1, -1): sum += (ord(s[i]) - ord('0')) * mul; mul *= 2; num = sum; sum = 0; mul = pow(2, 3); ctr = 0; for i in range(l % 4, l): ctr += 1; sum += (ord(s[i]) - ord('0')) * mul; mul //= 2; if (ctr == 4): num = num * 10 + sum; sum = 0; mul = pow(2, 3); ctr = 0; # Convert decimal to binary ans = \"\"; while (num > 0): ans += (chr((num % 2) + ord('0'))); num //= 2; ans = ans[:: -1] return ans; # Driver codeif __name__ == \"__main__\": s = \"1001000\"; # Function Call print(bcdToBinary(s)); # This code is contributed by rutvik_56", "e": 28545, "s": 27522, "text": null }, { "code": "// C# code to convert BCD to its// equivalent Binaryusing System;using System.Text;public class GFG{ // Function to convert BCD to Decimalstatic String bcdToBinary(String s){ int l = s.Length; int num = 0; int mul = 1; int sum = 0; // If the length of given BCD is not // divisible by 4 for(int i = l % 4 - 1; i >= 0; i--) { sum += (s[i] - '0') * mul; mul *= 2; } num = sum; sum = 0; mul = (int)Math.Pow(2, 3); int ctr = 0; for(int i = l % 4; i < l; i++) { ctr++; sum += (s[i] - '0') * mul; mul /= 2; if (ctr == 4) { num = num * 10 + sum; sum = 0; mul = (int)Math.Pow(2, 3); ctr = 0; } } // Convert decimal to binary String ans = \"\"; while (num > 0) { ans += (char)(num % 2 + '0'); num /= 2; } StringBuilder ans1 = new StringBuilder(); // Append a string into StringBuilder input1 ans1.Append(ans); // Reverse StringBuilder input1 ans = reverse(ans1.ToString()); return ans;}static String reverse(String input){ char[] a = input.ToCharArray(); int l, r = a.Length - 1; for (l = 0; l < r; l++, r--) { char temp = a[l]; a[l] = a[r]; a[r] = temp; } return String.Join(\"\",a); } // Driver codepublic static void Main(String[] args){ String s = \"1001000\"; // Function call Console.WriteLine(bcdToBinary(s));}} // This code is contributed by shikhasingrajput", "e": 30108, "s": 28545, "text": null }, { "code": "<script>// Javascript code to convert BCD to its// equivalent Binary // Function to convert BCD to Decimalfunction bcdToBinary(s){ let l = s.length; let num = 0; let mul = 1; let sum = 0; // If the length of given BCD is not // divisible by 4 for (let i = l % 4 - 1; i >= 0; i--) { sum += (s[i].charCodeAt(0) - '0'.charCodeAt(0)) * mul; mul *= 2; } num = sum; sum = 0; mul = Math.pow(2, 3); let ctr = 0; for (let i = l % 4; i < l; i++) { ctr++; sum += (s[i].charCodeAt(0) - '0'.charCodeAt(0)) * mul; mul = Math.floor(mul / 2); if (ctr == 4) { num = num * 10 + sum; sum = 0; mul = Math.pow(2, 3); ctr = 0; } } // Convert decimal to binary let ans = \"\"; while (num > 0) { ans += String.fromCharCode(num % 2 + '0'.charCodeAt(0)); num = Math.floor(num / 2); } ans = ans.split(\"\").reverse().join(\"\") console.log(ans) return ans;} // Driver Codelet s = \"1001000\"; // Function Calldocument.write(bcdToBinary(s)); // This code is contributed by _saurabh_jaiswal</script>", "e": 31246, "s": 30108, "text": null }, { "code": null, "e": 31253, "s": 31246, "text": "110000" }, { "code": null, "e": 31353, "s": 31255, "text": "Time Complexity: O(N) where N denotes the length of the BCD string provided Auxiliary Space: O(1)" }, { "code": null, "e": 31362, "s": 31353, "text": "coder001" }, { "code": null, "e": 31379, "s": 31362, "text": "shikhasingrajput" }, { "code": null, "e": 31389, "s": 31379, "text": "rutvik_56" }, { "code": null, "e": 31406, "s": 31389, "text": "_saurabh_jaiswal" }, { "code": null, "e": 31422, "s": 31406, "text": "base-conversion" }, { "code": null, "e": 31432, "s": 31422, "text": "Bit Magic" }, { "code": null, "e": 31445, "s": 31432, "text": "Mathematical" }, { "code": null, "e": 31458, "s": 31445, "text": "Mathematical" }, { "code": null, "e": 31468, "s": 31458, "text": "Bit Magic" }, { "code": null, "e": 31566, "s": 31468, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31575, "s": 31566, "text": "Comments" }, { "code": null, "e": 31588, "s": 31575, "text": "Old Comments" }, { "code": null, "e": 31639, "s": 31588, "text": "Set, Clear and Toggle a given bit of a number in C" }, { "code": null, "e": 31676, "s": 31639, "text": "Check whether K-th bit is set or not" }, { "code": null, "e": 31740, "s": 31676, "text": "Write an Efficient Method to Check if a Number is Multiple of 3" }, { "code": null, "e": 31780, "s": 31740, "text": "Reverse actual bits of the given number" }, { "code": null, "e": 31803, "s": 31780, "text": "Program to find parity" }, { "code": null, "e": 31833, "s": 31803, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 31893, "s": 31833, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 31908, "s": 31893, "text": "C++ Data Types" }, { "code": null, "e": 31951, "s": 31908, "text": "Set in C++ Standard Template Library (STL)" } ]
How to handle the errors generated while deserializing a JSON in Java?
The DeserializationProblemHandler class can be registered to get called when a potentially recoverable problem is encountered during the deserialization process. We can handle the errors generated while deserializing the JSON by implementing the handleUnknownProperty() method of DeserializationProblemHandler class. public boolean handleUnknownProperty(DeserializationContext ctxt, JsonParser p, JsonDeserializer deserializer, Object beanOrClass, String propertyName) throws IOException import java.io.*; import com.fasterxml.jackson.core.*; import com.fasterxml.jackson.databind.*; import com.fasterxml.jackson.databind.deser.*; public class DeserializationErrorTest { public static void main(String[] args) throws JsonMappingException, JsonGenerationException, IOException { String jsonString = "{\"id\":\"101\", \"name\":\"Ravi Chandra\", \"address\":\"Pune\", \"salary\":\"40000\" }"; ObjectMapper objectMapper = new ObjectMapper(); DeserializationProblemHandler deserializationProblemHandler = new UnMarshallingErrorHandler(); objectMapper.addHandler(deserializationProblemHandler); Customer customer = objectMapper.readValue(jsonString, Customer.class); System.out.println(customer); } } // UnMarshallingErrorHandler class class UnMarshallingErrorHandler extends DeserializationProblemHandler { @Override public boolean handleUnknownProperty(DeserializationContext ctxt, JsonParser jp, JsonDeserializer deserializer, Object beanOrClass, String propertyName) throws IOException, JsonProcessingException { boolean result = false; super.handleUnknownProperty(ctxt, jp, deserializer, beanOrClass, propertyName); System.out.println("Property with name '" + propertyName + "' doesn't exist in Class of type '" + beanOrClass.getClass().getName() + "'"); return true; // returns true to inform the deserialization process that we can handle the error and it can continue deserializing and returns false, if we want to stop the deserialization immediately. } } // Customer class class Customer { private int id; private String name; private String address; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } @Override public String toString() { return "Customer [id=" + id + ", name=" + name + ", address=" + address + "]"; } } Property with name 'salary' doesn't exist in Class of type 'Customer' Customer [id=101, name=Ravi Chandra, address=Pune] Property with name 'salary' doesn't exist in Class of type 'Customer' Exception in thread "main" com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "salary" (class Customer), not marked as ignorable (3 known properties: "id", "address", "name"]) at [Source: (String)"{"id":"101", "name":"Ravi Chandra", "address":"Pune", "salary":"40000" }"; line: 1, column: 65] (through reference chain: Customer["salary"]) at com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException.from(UnrecognizedPropertyException.java:61) at com.fasterxml.jackson.databind.DeserializationContext.handleUnknownProperty(DeserializationContext.java:840) at com.fasterxml.jackson.databind.deser.std.StdDeserializer.handleUnknownProperty(StdDeserializer.java:1179) at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.handleUnknownProperty(BeanDeserializerBase.java:1592) at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.handleUnknownVanilla(BeanDeserializerBase.java:1570) at com.fasterxml.jackson.databind.deser.BeanDeserializer.vanillaDeserialize(BeanDeserializer.java:294) at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:151) at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4202) at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3205) at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3173) at DeserializationErrorTest.main(DeserializationErrorTest.java:12)
[ { "code": null, "e": 1379, "s": 1062, "text": "The DeserializationProblemHandler class can be registered to get called when a potentially recoverable problem is encountered during the deserialization process. We can handle the errors generated while deserializing the JSON by implementing the handleUnknownProperty() method of DeserializationProblemHandler class." }, { "code": null, "e": 1550, "s": 1379, "text": "public boolean handleUnknownProperty(DeserializationContext ctxt, JsonParser p, JsonDeserializer deserializer, Object beanOrClass, String propertyName) throws IOException" }, { "code": null, "e": 3696, "s": 1550, "text": "import java.io.*;\nimport com.fasterxml.jackson.core.*;\nimport com.fasterxml.jackson.databind.*;\nimport com.fasterxml.jackson.databind.deser.*;\npublic class DeserializationErrorTest {\n public static void main(String[] args) throws JsonMappingException, JsonGenerationException, IOException {\n String jsonString = \"{\\\"id\\\":\\\"101\\\", \\\"name\\\":\\\"Ravi Chandra\\\", \\\"address\\\":\\\"Pune\\\", \\\"salary\\\":\\\"40000\\\" }\";\n ObjectMapper objectMapper = new ObjectMapper();\n DeserializationProblemHandler deserializationProblemHandler = new UnMarshallingErrorHandler();\n objectMapper.addHandler(deserializationProblemHandler);\n Customer customer = objectMapper.readValue(jsonString, Customer.class);\n System.out.println(customer);\n }\n}\n// UnMarshallingErrorHandler class\nclass UnMarshallingErrorHandler extends DeserializationProblemHandler {\n @Override\n public boolean handleUnknownProperty(DeserializationContext ctxt, JsonParser jp, JsonDeserializer deserializer, Object beanOrClass, String propertyName) throws IOException, JsonProcessingException {\n boolean result = false;\n super.handleUnknownProperty(ctxt, jp, deserializer, beanOrClass, propertyName);\n System.out.println(\"Property with name '\" + propertyName + \"' doesn't exist in Class of type '\" + beanOrClass.getClass().getName() + \"'\");\n return true; // returns true to inform the deserialization process that we can handle the error and it can continue deserializing and returns false, if we want to stop the deserialization immediately.\n }\n}\n// Customer class\nclass Customer {\n private int id;\n private String name;\n private String address;\n public int getId() {\n return id;\n }\n public void setId(int id) {\n this.id = id;\n }\n public String getName() {\n return name;\n }\n public void setName(String name) {\n this.name = name;\n }\n public String getAddress() {\n return address;\n }\n public void setAddress(String address) {\n this.address = address;\n }\n @Override\n public String toString() {\n return \"Customer [id=\" + id + \", name=\" + name + \", address=\" + address + \"]\";\n }\n}" }, { "code": null, "e": 3817, "s": 3696, "text": "Property with name 'salary' doesn't exist in Class of type 'Customer'\nCustomer [id=101, name=Ravi Chandra, address=Pune]" }, { "code": null, "e": 5339, "s": 3817, "text": "Property with name 'salary' doesn't exist in Class of type 'Customer'\nException in thread \"main\" com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field \"salary\" (class Customer), not marked as ignorable (3 known properties: \"id\", \"address\", \"name\"])\nat [Source: (String)\"{\"id\":\"101\", \"name\":\"Ravi Chandra\", \"address\":\"Pune\", \"salary\":\"40000\" }\"; line: 1, column: 65] (through reference chain: Customer[\"salary\"]) at com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException.from(UnrecognizedPropertyException.java:61)\nat com.fasterxml.jackson.databind.DeserializationContext.handleUnknownProperty(DeserializationContext.java:840)\nat com.fasterxml.jackson.databind.deser.std.StdDeserializer.handleUnknownProperty(StdDeserializer.java:1179)\nat com.fasterxml.jackson.databind.deser.BeanDeserializerBase.handleUnknownProperty(BeanDeserializerBase.java:1592) at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.handleUnknownVanilla(BeanDeserializerBase.java:1570) at com.fasterxml.jackson.databind.deser.BeanDeserializer.vanillaDeserialize(BeanDeserializer.java:294)\nat com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:151)\nat com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4202)\nat com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3205)\nat com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3173)\nat DeserializationErrorTest.main(DeserializationErrorTest.java:12)\n" } ]
How to get Time in Milliseconds for the Given date and time in Java?
The java.text.SimpleDateFormat class is used to format and parse a string to date and date to string. One of the constructors of this class accepts a String value representing the desired date format and creates SimpleDateFormat object. To parse/convert a string as a Date object Instantiate this class by passing desired format string. Parse the date string using the parse() method. You can get the epoch time using the getTime() method. Live Demo import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class Sample { public static void main(String args[]) throws ParseException { //Instantiating the SimpleDateFormat class SimpleDateFormat dateformatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss"); //Parsing the given String to Date object String str = "25-08-2009 11:20:45"; Date date = dateformatter.parse(str); long msec = date.getTime(); System.out.println("Epoch of the given date: "+msec); } } Epoch of the given date: 1251179445000 Epoch of the given date: 1251179445000 You can set date and time values to a calendar object using the set() method. The getTimeInMillis() of this class returns the epoch time of the date value. Live Demo import java.util.Calendar; public class Sample { public static void main(String args[]) { Calendar cal = Calendar.getInstance(); cal.set(2014, 9, 11, 10, 25, 30); long msec = cal.getTimeInMillis(); System.out.print(msec); } } 1413003330758 1413003330758 You can set date and time values to a ZonedDateTime object using the of() method. The toEpochMilli() of the Instant class returns the epoch time of the date value. Live Demo import java.time.Instant; import java.time.ZoneId; import java.time.ZonedDateTime; public class Sample { public static void main(String args[]){ //Creating the ZonedDateTime object ZoneId id = ZoneId.of("Asia/Kolkata"); ZonedDateTime obj = ZonedDateTime.of(2014, 9, 11, 10, 25, 30, 22, id); Instant instant = obj.toInstant(); long msec = instant.toEpochMilli(); System.out.println("Milli Seconds: "+msec); } } Milli Seconds: 1410411330000 Milli Seconds: 1410411330000
[ { "code": null, "e": 1164, "s": 1062, "text": "The java.text.SimpleDateFormat class is used to format and parse a string to date and date to string." }, { "code": null, "e": 1300, "s": 1164, "text": "One of the constructors of this class accepts a String value representing the desired date format and creates SimpleDateFormat object. " }, { "code": null, "e": 1400, "s": 1300, "text": "To parse/convert a string as a Date object Instantiate this class by passing desired format string." }, { "code": null, "e": 1448, "s": 1400, "text": "Parse the date string using the parse() method." }, { "code": null, "e": 1503, "s": 1448, "text": "You can get the epoch time using the getTime() method." }, { "code": null, "e": 1513, "s": 1503, "text": "Live Demo" }, { "code": null, "e": 2070, "s": 1513, "text": "import java.text.ParseException;\nimport java.text.SimpleDateFormat;\nimport java.util.Date;\npublic class Sample {\n public static void main(String args[]) throws ParseException { \n //Instantiating the SimpleDateFormat class\n SimpleDateFormat dateformatter = new SimpleDateFormat(\"dd-MM-yyyy HH:mm:ss\"); \n //Parsing the given String to Date object\n String str = \"25-08-2009 11:20:45\";\n Date date = dateformatter.parse(str); \n long msec = date.getTime();\n System.out.println(\"Epoch of the given date: \"+msec);\n }\n}" }, { "code": null, "e": 2109, "s": 2070, "text": "Epoch of the given date: 1251179445000" }, { "code": null, "e": 2148, "s": 2109, "text": "Epoch of the given date: 1251179445000" }, { "code": null, "e": 2304, "s": 2148, "text": "You can set date and time values to a calendar object using the set() method. The getTimeInMillis() of this class returns the epoch time of the date value." }, { "code": null, "e": 2314, "s": 2304, "text": "Live Demo" }, { "code": null, "e": 2578, "s": 2314, "text": "import java.util.Calendar;\npublic class Sample {\n public static void main(String args[]) { \n Calendar cal = Calendar.getInstance();\n cal.set(2014, 9, 11, 10, 25, 30);\n long msec = cal.getTimeInMillis();\n System.out.print(msec); \n }\n}" }, { "code": null, "e": 2592, "s": 2578, "text": "1413003330758" }, { "code": null, "e": 2606, "s": 2592, "text": "1413003330758" }, { "code": null, "e": 2770, "s": 2606, "text": "You can set date and time values to a ZonedDateTime object using the of() method. The toEpochMilli() of the Instant class returns the epoch time of the date value." }, { "code": null, "e": 2780, "s": 2770, "text": "Live Demo" }, { "code": null, "e": 3240, "s": 2780, "text": "import java.time.Instant;\nimport java.time.ZoneId;\nimport java.time.ZonedDateTime;\npublic class Sample {\n public static void main(String args[]){ \n //Creating the ZonedDateTime object\n ZoneId id = ZoneId.of(\"Asia/Kolkata\");\n ZonedDateTime obj = ZonedDateTime.of(2014, 9, 11, 10, 25, 30, 22, id);\n Instant instant = obj.toInstant(); \n long msec = instant.toEpochMilli();\n System.out.println(\"Milli Seconds: \"+msec);\n }\n}" }, { "code": null, "e": 3269, "s": 3240, "text": "Milli Seconds: 1410411330000" }, { "code": null, "e": 3298, "s": 3269, "text": "Milli Seconds: 1410411330000" } ]
Image button with HTML5
To add image button with HTML5, use the <button> element and set the image inside it before it is closed </button> − <button type = "submit" name = "learn" value = "myimage"> <p>Tutorials for all</p> <img src="https://www.tutorialspoint.com/latest/inter-process-communication.png " /> </button>
[ { "code": null, "e": 1179, "s": 1062, "text": "To add image button with HTML5, use the <button> element and set the image inside it before it is closed </button> −" }, { "code": null, "e": 1363, "s": 1179, "text": "<button type = \"submit\" name = \"learn\" value = \"myimage\">\n <p>Tutorials for all</p>\n <img src=\"https://www.tutorialspoint.com/latest/inter-process-communication.png \" />\n</button>" } ]
How to close sidebar by default using Bootstrap ? - GeeksforGeeks
26 Aug, 2020 Bootstrap is the most popular responsive and open source CSS framework used by software developers. The sidebar is a widget that contains navigational links to other parts of the website. The sidebar is generally used to display a list of menu items. This article demonstrates two methods to create a sidebar of a webpage where the sidebar remains closed or hidden by default. The first method displays the sidebar on clicking the Menu button and later the sidebar can be closed by clicking the X icon on the top right corner. The second method demonstrates a toggling sidebar that remains hidden by default. Clicking the Menu button displays the sidebar and clicking the Menu button again hides the sidebar. Method 1: The webpage contains a division with id=main, This division contains the actual content of the webpage. A button labeled as “Menu” is created which triggers the openNav() function. The function openNav() fetches the sidebar division using document.getElementById() and sets the width of the sidebar and the ‘main’ division. After the sidebar is displayed the user clicks on the close button on the top right corner of the sidebar which triggers the closeNav() function. The function closeNav() fetches the main division using document.getElementById() and sets the width of the sidebar to 0 hiding it from the webpage and the left margin of main division is set to 0 which makes it take the full width of the screen. Since both the functions are javascript functions they are placed within the script tags. The CSS specified within the style tag enables proper positioning and transition of the sidebar and main division. Example 1: <!DOCTYPE html><html lang="en"> <head> <style> /* The sidebar menu */ .sidebar { height: 100%; /* 100% Full-height */ width: 0; /* 0 width */ position: fixed; /* Fixed place */ z-index: 1; /* Stay on top */ top: 0; left: 0; background-color: black; /* Disable horizontal scroll */ overflow-x: hidden; /* Place content 60px from the top */ padding-top: 60px; /* Transition effect to slide in the sidebar */ transition: 0.5s; } /* The sidebar links */ .sidebar a { padding: 8px 8px 8px 32px; text-decoration: none; font-size: 20px; color: #818181; display: block; transition: 0.3s; } /* Mouse over the navigation links, to change their color */ .sidebar a:hover { color: green; } /* Position and style the close button at top right corner */ .sidebar .closebtn { position: absolute; top: 0; right: 25px; font-size: 36px; margin-left: 50px; } /* The button used to open the sidebar */ .openbtn { font-size: 20px; cursor: pointer; background-color: #111; color: white; padding: 10px 15px; border: none; } .openbtn:hover { background-color: #444; } /* Style page content - pushes the page content to the right when the sidebar is opened */ #main { /* If you want a transition effect */ transition: margin-left 0.5s; padding: 20px; } /* On smaller screens, where height is less than 450px, change the style of the side-nav (less padding and a smaller font size) */ @media screen and (max-height: 450px) { .sidebar { padding-top: 15px; } .sidebar a { font-size: 18px; } } </style></head> <body> <div id="mySidebar" class="sidebar"> <a href="javascript:void(0)" class="closebtn" onclick="closeNav()"> × </a> <a href="#">My Account</a> <a href="#">My Articles</a> <a href="#">Interests</a> <a href="#">Practice</a> <a href="#">Testimonials</a> <a href="#">About Us</a> <a href="#">Contact Us</a> </div> <!-- The main division contains the actual content of the webpage --> <div id="main"> <h1 style="color: green;"> Welcome to GeeksForGeeks </h1> <button class="openbtn" onclick="openNav()">Menu </button> <h2> This is a demonstration of collapsed sidebar by default. The sidebar opens on clicking the Menu button. </h2> </div> <script> function openNav() { document.getElementById( "mySidebar").style.width = "200px"; document.getElementById( "main").style.marginLeft = "200px"; } /* Set the width of the sidebar to 0 and the left margin of the page content to 0 */ function closeNav() { document.getElementById( "mySidebar").style.width = "0"; document.getElementById( "main").style.marginLeft = "0"; } </script></body> </html> Output Method 2: This method displays the sidebar using the toggling functionality of an input field having type ‘checkbox’ and role ‘button’. When the user clicks the button, the checkbox is checked and it sets the left margin of the ‘content’ division to 0 which means it occupies the entire screen. When the user clicks the button again, the checkbox is unchecked and the left margin of ‘content’ division is set to 200px and the sidebar is displayed. This transition happens in the CSS, unlike the previous example where the entire operation was carried out by the javascript functions. Example: <html> <head> <style> .sidebar { background-color: black; /* Occupies 100% height of the page */ height: 100%; /* Specifies the width of sidebar */ width: 500px; position: absolute; top: 0; left: 0; bottom: 0; padding-right: 60px; /* Transition effect of sidebar */ transition: 0.5s; } .sidebar h2, li { padding: 8px 8px 8px 32px; text-decoration: none; font-size: 20px; color: #818181; display: block; /* Transition effect of h2 and li */ transition: 0.3s; } .sidebar li:hover { /* Sidebar items change color when hovered over */ color: green; } .content { background-color: white; position: absolute; top: 0; /* The left margin when sidebar is visible */ left: 200px; right: 0; bottom: 0; -moz-transition: left 0.5s ease; transition: left 0.5s ease; } input[type="checkbox"] { display: none; } /* Toggling of sidebar */ input:checked~.content { left: 0; } input:checked~label { left: 0; } /* Styling of the button */ label { z-index: 2; position: absolute; top: 0; left: 200px; background-color: black; color: white; -moz-transition: left 0.5s ease; transition: left 0.5s ease; } </style></head> <body> <!-- This division contains the sidebar and its content --> <div class="main-wrap"> <input id="slide-sidebar" type="checkbox" role="button" /> <label for="slide-sidebar"> <span>Toggle</span> </label> <div class="sidebar"> <h2>Menu Bar</h2> <ul> <li>Basic</li> <li>Profile</li> <li>Articles</li> <li>Testimonial</li> <li>Practice</li> </ul> </div> <!-- This division contains the actual content of the webpage --> <div class="content"> <h1 style="color: green;"> Welcome to GeeksForGeeks </h1> </div> </div></body> </html> Output By default, the sidebar in both the examples remains closed or hidden. It is only when the user clicks the button the sidebar displays. Collapsing sidebars are space-efficient and make the webpage look clean and spacious. Sidebars can be fixed and scrolling as per the user requirement. The article, however, demonstrates fixed sidebars. Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. nidhi_biet Bootstrap-Misc CSS-Misc HTML-Misc Picked Bootstrap CSS HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to change navigation bar color in Bootstrap ? Form validation using jQuery How to pass data into a bootstrap modal? How to align navbar items to the right in Bootstrap 4 ? How to Show Images on Click using HTML ? How to insert spaces/tabs in text using HTML/CSS? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to create footer to stay at the bottom of a Web page? How to update Node.js and NPM to next version ? CSS to put icon inside an input element in a form
[ { "code": null, "e": 28416, "s": 28388, "text": "\n26 Aug, 2020" }, { "code": null, "e": 29125, "s": 28416, "text": "Bootstrap is the most popular responsive and open source CSS framework used by software developers. The sidebar is a widget that contains navigational links to other parts of the website. The sidebar is generally used to display a list of menu items. This article demonstrates two methods to create a sidebar of a webpage where the sidebar remains closed or hidden by default. The first method displays the sidebar on clicking the Menu button and later the sidebar can be closed by clicking the X icon on the top right corner. The second method demonstrates a toggling sidebar that remains hidden by default. Clicking the Menu button displays the sidebar and clicking the Menu button again hides the sidebar." }, { "code": null, "e": 30057, "s": 29125, "text": "Method 1: The webpage contains a division with id=main, This division contains the actual content of the webpage. A button labeled as “Menu” is created which triggers the openNav() function. The function openNav() fetches the sidebar division using document.getElementById() and sets the width of the sidebar and the ‘main’ division. After the sidebar is displayed the user clicks on the close button on the top right corner of the sidebar which triggers the closeNav() function. The function closeNav() fetches the main division using document.getElementById() and sets the width of the sidebar to 0 hiding it from the webpage and the left margin of main division is set to 0 which makes it take the full width of the screen. Since both the functions are javascript functions they are placed within the script tags. The CSS specified within the style tag enables proper positioning and transition of the sidebar and main division." }, { "code": null, "e": 30068, "s": 30057, "text": "Example 1:" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <style> /* The sidebar menu */ .sidebar { height: 100%; /* 100% Full-height */ width: 0; /* 0 width */ position: fixed; /* Fixed place */ z-index: 1; /* Stay on top */ top: 0; left: 0; background-color: black; /* Disable horizontal scroll */ overflow-x: hidden; /* Place content 60px from the top */ padding-top: 60px; /* Transition effect to slide in the sidebar */ transition: 0.5s; } /* The sidebar links */ .sidebar a { padding: 8px 8px 8px 32px; text-decoration: none; font-size: 20px; color: #818181; display: block; transition: 0.3s; } /* Mouse over the navigation links, to change their color */ .sidebar a:hover { color: green; } /* Position and style the close button at top right corner */ .sidebar .closebtn { position: absolute; top: 0; right: 25px; font-size: 36px; margin-left: 50px; } /* The button used to open the sidebar */ .openbtn { font-size: 20px; cursor: pointer; background-color: #111; color: white; padding: 10px 15px; border: none; } .openbtn:hover { background-color: #444; } /* Style page content - pushes the page content to the right when the sidebar is opened */ #main { /* If you want a transition effect */ transition: margin-left 0.5s; padding: 20px; } /* On smaller screens, where height is less than 450px, change the style of the side-nav (less padding and a smaller font size) */ @media screen and (max-height: 450px) { .sidebar { padding-top: 15px; } .sidebar a { font-size: 18px; } } </style></head> <body> <div id=\"mySidebar\" class=\"sidebar\"> <a href=\"javascript:void(0)\" class=\"closebtn\" onclick=\"closeNav()\"> × </a> <a href=\"#\">My Account</a> <a href=\"#\">My Articles</a> <a href=\"#\">Interests</a> <a href=\"#\">Practice</a> <a href=\"#\">Testimonials</a> <a href=\"#\">About Us</a> <a href=\"#\">Contact Us</a> </div> <!-- The main division contains the actual content of the webpage --> <div id=\"main\"> <h1 style=\"color: green;\"> Welcome to GeeksForGeeks </h1> <button class=\"openbtn\" onclick=\"openNav()\">Menu </button> <h2> This is a demonstration of collapsed sidebar by default. The sidebar opens on clicking the Menu button. </h2> </div> <script> function openNav() { document.getElementById( \"mySidebar\").style.width = \"200px\"; document.getElementById( \"main\").style.marginLeft = \"200px\"; } /* Set the width of the sidebar to 0 and the left margin of the page content to 0 */ function closeNav() { document.getElementById( \"mySidebar\").style.width = \"0\"; document.getElementById( \"main\").style.marginLeft = \"0\"; } </script></body> </html>", "e": 33738, "s": 30068, "text": null }, { "code": null, "e": 33745, "s": 33738, "text": "Output" }, { "code": null, "e": 34329, "s": 33745, "text": "Method 2: This method displays the sidebar using the toggling functionality of an input field having type ‘checkbox’ and role ‘button’. When the user clicks the button, the checkbox is checked and it sets the left margin of the ‘content’ division to 0 which means it occupies the entire screen. When the user clicks the button again, the checkbox is unchecked and the left margin of ‘content’ division is set to 200px and the sidebar is displayed. This transition happens in the CSS, unlike the previous example where the entire operation was carried out by the javascript functions." }, { "code": null, "e": 34338, "s": 34329, "text": "Example:" }, { "code": "<html> <head> <style> .sidebar { background-color: black; /* Occupies 100% height of the page */ height: 100%; /* Specifies the width of sidebar */ width: 500px; position: absolute; top: 0; left: 0; bottom: 0; padding-right: 60px; /* Transition effect of sidebar */ transition: 0.5s; } .sidebar h2, li { padding: 8px 8px 8px 32px; text-decoration: none; font-size: 20px; color: #818181; display: block; /* Transition effect of h2 and li */ transition: 0.3s; } .sidebar li:hover { /* Sidebar items change color when hovered over */ color: green; } .content { background-color: white; position: absolute; top: 0; /* The left margin when sidebar is visible */ left: 200px; right: 0; bottom: 0; -moz-transition: left 0.5s ease; transition: left 0.5s ease; } input[type=\"checkbox\"] { display: none; } /* Toggling of sidebar */ input:checked~.content { left: 0; } input:checked~label { left: 0; } /* Styling of the button */ label { z-index: 2; position: absolute; top: 0; left: 200px; background-color: black; color: white; -moz-transition: left 0.5s ease; transition: left 0.5s ease; } </style></head> <body> <!-- This division contains the sidebar and its content --> <div class=\"main-wrap\"> <input id=\"slide-sidebar\" type=\"checkbox\" role=\"button\" /> <label for=\"slide-sidebar\"> <span>Toggle</span> </label> <div class=\"sidebar\"> <h2>Menu Bar</h2> <ul> <li>Basic</li> <li>Profile</li> <li>Articles</li> <li>Testimonial</li> <li>Practice</li> </ul> </div> <!-- This division contains the actual content of the webpage --> <div class=\"content\"> <h1 style=\"color: green;\"> Welcome to GeeksForGeeks </h1> </div> </div></body> </html>", "e": 36864, "s": 34338, "text": null }, { "code": null, "e": 36871, "s": 36864, "text": "Output" }, { "code": null, "e": 37209, "s": 36871, "text": "By default, the sidebar in both the examples remains closed or hidden. It is only when the user clicks the button the sidebar displays. Collapsing sidebars are space-efficient and make the webpage look clean and spacious. Sidebars can be fixed and scrolling as per the user requirement. The article, however, demonstrates fixed sidebars." }, { "code": null, "e": 37346, "s": 37209, "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": 37357, "s": 37346, "text": "nidhi_biet" }, { "code": null, "e": 37372, "s": 37357, "text": "Bootstrap-Misc" }, { "code": null, "e": 37381, "s": 37372, "text": "CSS-Misc" }, { "code": null, "e": 37391, "s": 37381, "text": "HTML-Misc" }, { "code": null, "e": 37398, "s": 37391, "text": "Picked" }, { "code": null, "e": 37408, "s": 37398, "text": "Bootstrap" }, { "code": null, "e": 37412, "s": 37408, "text": "CSS" }, { "code": null, "e": 37417, "s": 37412, "text": "HTML" }, { "code": null, "e": 37434, "s": 37417, "text": "Web Technologies" }, { "code": null, "e": 37439, "s": 37434, "text": "HTML" }, { "code": null, "e": 37537, "s": 37439, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 37587, "s": 37537, "text": "How to change navigation bar color in Bootstrap ?" }, { "code": null, "e": 37616, "s": 37587, "text": "Form validation using jQuery" }, { "code": null, "e": 37657, "s": 37616, "text": "How to pass data into a bootstrap modal?" }, { "code": null, "e": 37713, "s": 37657, "text": "How to align navbar items to the right in Bootstrap 4 ?" }, { "code": null, "e": 37754, "s": 37713, "text": "How to Show Images on Click using HTML ?" }, { "code": null, "e": 37804, "s": 37754, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 37866, "s": 37804, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 37924, "s": 37866, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 37972, "s": 37924, "text": "How to update Node.js and NPM to next version ?" } ]
How to use union and order by clause in MySQL?
Union is a type of operator in MySQL. We can use ORDER BY with this to filter records. Use UNION if you want to select rows one after the other from several tables or several sets of rows from a single table all as a single result set. Let us see an example. Creating first table mysql> create table UnionDemo1 -> ( -> id int -> ); Query OK, 0 rows affected (0.59 sec) Inserting records into first table. mysql> insert into UnionDemo1 values(1),(4),(10); Query OK, 3 rows affected (0.21 sec) Records: 3 Duplicates: 0 Warnings: 0 To display all records. mysql> select *from UnionDemo1; The following is the output that displays all the records. +------+ | id | +------+ | 1 | | 4 | | 10 | +------+ 3 rows in set (0.00 sec) Let us create second table. mysql> create table UnionDemo2 -> ( -> id int -> ); Query OK, 0 rows affected (0.54 sec) Inserting records into second table. mysql> insert into UnionDemo2 values(2),(3),(5),(6),(7),(8),(9); Query OK, 7 rows affected (0.21 sec) Records: 7 Duplicates: 0 Warnings: 0 To display all the records. mysql> select *from UnionDemo2; Here is the output. +------+ | id | +------+ | 2 | | 3 | | 5 | | 6 | | 7 | | 8 | | 9 | +------+ 7 rows in set (0.00 sec) Let us now see the query to apply UNION with Order by. mysql> select id from UnionDemo1 -> union -> select id from UnionDemo2 -> order by id desc; The following is the output. +------+ | id | +------+ | 10 | | 9 | | 8 | | 7 | | 6 | | 5 | | 4 | | 3 | | 2 | | 1 | +------+ 10 rows in set (0.05 sec)
[ { "code": null, "e": 1298, "s": 1062, "text": "Union is a type of operator in MySQL. We can use ORDER BY with this to filter records. Use UNION if you want to select rows one after the other from several tables or several sets of rows from a single table all as a single result set." }, { "code": null, "e": 1321, "s": 1298, "text": "Let us see an example." }, { "code": null, "e": 1342, "s": 1321, "text": "Creating first table" }, { "code": null, "e": 1440, "s": 1342, "text": "mysql> create table UnionDemo1\n -> (\n -> id int\n -> );\nQuery OK, 0 rows affected (0.59 sec)" }, { "code": null, "e": 1476, "s": 1440, "text": "Inserting records into first table." }, { "code": null, "e": 1602, "s": 1476, "text": "mysql> insert into UnionDemo1 values(1),(4),(10);\nQuery OK, 3 rows affected (0.21 sec)\nRecords: 3 Duplicates: 0 Warnings: 0" }, { "code": null, "e": 1626, "s": 1602, "text": "To display all records." }, { "code": null, "e": 1658, "s": 1626, "text": "mysql> select *from UnionDemo1;" }, { "code": null, "e": 1717, "s": 1658, "text": "The following is the output that displays all the records." }, { "code": null, "e": 1806, "s": 1717, "text": "+------+\n| id |\n+------+\n| 1 |\n| 4 |\n| 10 |\n+------+\n3 rows in set (0.00 sec)\n" }, { "code": null, "e": 1834, "s": 1806, "text": "Let us create second table." }, { "code": null, "e": 1932, "s": 1834, "text": "mysql> create table UnionDemo2\n -> (\n -> id int\n -> );\nQuery OK, 0 rows affected (0.54 sec)" }, { "code": null, "e": 1969, "s": 1932, "text": "Inserting records into second table." }, { "code": null, "e": 2110, "s": 1969, "text": "mysql> insert into UnionDemo2 values(2),(3),(5),(6),(7),(8),(9);\nQuery OK, 7 rows affected (0.21 sec)\nRecords: 7 Duplicates: 0 Warnings: 0" }, { "code": null, "e": 2138, "s": 2110, "text": "To display all the records." }, { "code": null, "e": 2170, "s": 2138, "text": "mysql> select *from UnionDemo2;" }, { "code": null, "e": 2190, "s": 2170, "text": "Here is the output." }, { "code": null, "e": 2315, "s": 2190, "text": "+------+\n| id |\n+------+\n| 2 |\n| 3 |\n| 5 |\n| 6 |\n| 7 |\n| 8 |\n| 9 |\n+------+\n7 rows in set (0.00 sec)\n" }, { "code": null, "e": 2370, "s": 2315, "text": "Let us now see the query to apply UNION with Order by." }, { "code": null, "e": 2471, "s": 2370, "text": "mysql> select id from UnionDemo1\n -> union\n -> select id from UnionDemo2\n -> order by id desc;" }, { "code": null, "e": 2500, "s": 2471, "text": "The following is the output." }, { "code": null, "e": 2653, "s": 2500, "text": "+------+\n| id |\n+------+\n| 10 |\n| 9 |\n| 8 |\n| 7 |\n| 6 |\n| 5 |\n| 4 |\n| 3 |\n| 2 |\n| 1 |\n+------+\n10 rows in set (0.05 sec)\n" } ]
How to copy the content of a div into another div using jQuery ? - GeeksforGeeks
11 Oct, 2019 Given an HTML document containing some div element and the task is to copy a div content into another div as its child using jQuery. There are two approaches to solve this problem which are discussed below: Approach 1: First, select the div element which need to be copy into another div element. Select the target element where div eleemtn is copied. Use the append() method to copy the element as its child. Example: This example uses append() method to copy the div element into another div. <!DOCTYPE HTML> <html> <head> <title> How to copy the content of a div into another div using jQuery ? </title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script> <style> .parent { background: green; color: white; } .child { background: blue; color: white; margin: 10px; } #GFG_UP { font-size: 15px; font-weight: bold; } #GFG_DOWN { font-size: 24px; font-weight: bold; color: green; } </style></head> <body id = "body" style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <p id = "GFG_UP"></p> <div class="parent"> Outer DIV <div class="child"> Inner DIV </div> </div> <br> <div class="parent" id = "parent2"> Outer DIV </div> <br> <button onclick = "GFG_Fun()"> click here </button> <p id = "GFG_DOWN"></p> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); up.innerHTML = "Click on the button to " + "copy a DIV into another DIV."; function GFG_Fun() { var $el = $('.child').clone(); $('#parent2').append($el); down.innerHTML = "Inner DIV is copied " + "to another element."; } </script> </body> </html> Output: Before clicking on the button: After clicking on the button: Approach 2: First, select the div element which need to be copy into another div element. Select the target element where div eleemtn is copied. Use the appendTo() method to copy the element as its child. Example: This example uses appendTo() method to copy the div element into another div. <!DOCTYPE HTML> <html> <head> <title> How to copy the content of a div into another div using jQuery ? </title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script> <style> .parent { background: green; color: white; } .child { background: blue; color: white; margin: 10px; } #GFG_UP { font-size: 15px; font-weight: bold; } #GFG_DOWN { font-size: 24px; font-weight: bold; color: green; } </style></head> <body id = "body" style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <p id = "GFG_UP"></p> <div class="parent"> Outer DIV <div class="child"> Inner DIV </div> </div> <br> <div class="parent" id = "parent2"> Outer DIV </div> <br> <button onclick = "GFG_Fun()"> click here </button> <p id = "GFG_DOWN"></p> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); up.innerHTML = "Click on the button to " + "copy a DIV into another DIV."; function GFG_Fun() { $('.child').clone().appendTo('#parent2'); down.innerHTML = "Inner DIV is copied" + " to another element."; } </script> </body> </html> Output: Before clicking on the button: After clicking on the button: JavaScript Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Difference between var, let and const keywords in JavaScript Convert a string to an integer in JavaScript Differences between Functional Components and Class Components in React How to append HTML code to a div using JavaScript ? How to Open URL in New Tab using JavaScript ? Top 10 Front End Developer Skills That You Need in 2022 Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 24105, "s": 24077, "text": "\n11 Oct, 2019" }, { "code": null, "e": 24312, "s": 24105, "text": "Given an HTML document containing some div element and the task is to copy a div content into another div as its child using jQuery. There are two approaches to solve this problem which are discussed below:" }, { "code": null, "e": 24324, "s": 24312, "text": "Approach 1:" }, { "code": null, "e": 24402, "s": 24324, "text": "First, select the div element which need to be copy into another div element." }, { "code": null, "e": 24457, "s": 24402, "text": "Select the target element where div eleemtn is copied." }, { "code": null, "e": 24515, "s": 24457, "text": "Use the append() method to copy the element as its child." }, { "code": null, "e": 24600, "s": 24515, "text": "Example: This example uses append() method to copy the div element into another div." }, { "code": "<!DOCTYPE HTML> <html> <head> <title> How to copy the content of a div into another div using jQuery ? </title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script> <style> .parent { background: green; color: white; } .child { background: blue; color: white; margin: 10px; } #GFG_UP { font-size: 15px; font-weight: bold; } #GFG_DOWN { font-size: 24px; font-weight: bold; color: green; } </style></head> <body id = \"body\" style = \"text-align:center;\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <p id = \"GFG_UP\"></p> <div class=\"parent\"> Outer DIV <div class=\"child\"> Inner DIV </div> </div> <br> <div class=\"parent\" id = \"parent2\"> Outer DIV </div> <br> <button onclick = \"GFG_Fun()\"> click here </button> <p id = \"GFG_DOWN\"></p> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); up.innerHTML = \"Click on the button to \" + \"copy a DIV into another DIV.\"; function GFG_Fun() { var $el = $('.child').clone(); $('#parent2').append($el); down.innerHTML = \"Inner DIV is copied \" + \"to another element.\"; } </script> </body> </html>", "e": 26215, "s": 24600, "text": null }, { "code": null, "e": 26223, "s": 26215, "text": "Output:" }, { "code": null, "e": 26254, "s": 26223, "text": "Before clicking on the button:" }, { "code": null, "e": 26284, "s": 26254, "text": "After clicking on the button:" }, { "code": null, "e": 26296, "s": 26284, "text": "Approach 2:" }, { "code": null, "e": 26374, "s": 26296, "text": "First, select the div element which need to be copy into another div element." }, { "code": null, "e": 26429, "s": 26374, "text": "Select the target element where div eleemtn is copied." }, { "code": null, "e": 26489, "s": 26429, "text": "Use the appendTo() method to copy the element as its child." }, { "code": null, "e": 26576, "s": 26489, "text": "Example: This example uses appendTo() method to copy the div element into another div." }, { "code": "<!DOCTYPE HTML> <html> <head> <title> How to copy the content of a div into another div using jQuery ? </title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script> <style> .parent { background: green; color: white; } .child { background: blue; color: white; margin: 10px; } #GFG_UP { font-size: 15px; font-weight: bold; } #GFG_DOWN { font-size: 24px; font-weight: bold; color: green; } </style></head> <body id = \"body\" style = \"text-align:center;\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <p id = \"GFG_UP\"></p> <div class=\"parent\"> Outer DIV <div class=\"child\"> Inner DIV </div> </div> <br> <div class=\"parent\" id = \"parent2\"> Outer DIV </div> <br> <button onclick = \"GFG_Fun()\"> click here </button> <p id = \"GFG_DOWN\"></p> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); up.innerHTML = \"Click on the button to \" + \"copy a DIV into another DIV.\"; function GFG_Fun() { $('.child').clone().appendTo('#parent2'); down.innerHTML = \"Inner DIV is copied\" + \" to another element.\"; } </script> </body> </html>", "e": 28168, "s": 26576, "text": null }, { "code": null, "e": 28176, "s": 28168, "text": "Output:" }, { "code": null, "e": 28207, "s": 28176, "text": "Before clicking on the button:" }, { "code": null, "e": 28237, "s": 28207, "text": "After clicking on the button:" }, { "code": null, "e": 28248, "s": 28237, "text": "JavaScript" }, { "code": null, "e": 28265, "s": 28248, "text": "Web Technologies" }, { "code": null, "e": 28292, "s": 28265, "text": "Web technologies Questions" }, { "code": null, "e": 28390, "s": 28292, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28399, "s": 28390, "text": "Comments" }, { "code": null, "e": 28412, "s": 28399, "text": "Old Comments" }, { "code": null, "e": 28473, "s": 28412, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 28518, "s": 28473, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 28590, "s": 28518, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 28642, "s": 28590, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 28688, "s": 28642, "text": "How to Open URL in New Tab using JavaScript ?" }, { "code": null, "e": 28744, "s": 28688, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 28777, "s": 28744, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 28839, "s": 28777, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 28882, "s": 28839, "text": "How to fetch data from an API in ReactJS ?" } ]
Reactive Data Analysis with Julia in Pluto Notebooks | by René | Towards Data Science
Pluto is a lightweight and easy to use reactive notebook for the Julia language. In this story I will share my experience with Pluto, especially the five features I love most. Getting started with Pluto is easy. You just add the Pluto package to your project environment and you are good to go. Start Pluto by typing Pluto.run() from the Julia REPL and Pluto opens in your default web browser. In my workflow I usually navigate to my project directory and start Pluto with the command: julia --threads auto --project=. -e "using Pluto; Pluto.run()" There a many thing to love about coding in Julia with Pluto notebooks. Based on my experience with Pluto this are the 5 features I love most for Exploratory Data Analysis (EDA). A key feature of Pluto is it’s reactive nature. When changing a function or variable, Pluto automatically updates all affected cells. No need the remember which cells to execute and in which order. Pluto does all that for you automagically so you can focus on analyzing data. That’s a huge plus. When you execute a cell (by pressing ctrl + enter or shift + enter) it shows the execution time of that cell. Very handy for code optimization. A cell can also be execute by pressing the little ▶️ button to the lower right of the cell. To enhance the reactive nature of Pluto notebooks even further, there is support for interactive HTML-widgets out-of-the-box. By using widgets, you can minimize the times you needs to change variable values in your code manually. Lots of HTML-widgets are supported. To make thing even more easy to use, there is a package — called PlutoUI — which has convenient Julia objects for some of the widgets. Instead of using @bind p html"<input type=range min=1 max=10>" you can use @bind p Slider(1:10). Here a an example of a combination of HTML-widgets and widgets supported by the PlutoUI package. In Pluto, you can chose any cell order you like. It is also possible to hide cells. So for your final notebook, you can move helper functions to the end of your notebook and move the interactive data visualizations to the top. That does focus the attention of the reader to the message you want communicate. In more traditional notebooks, the most interesting part for the average reader comes at the end of a notebook. A Pluto notebook is stored as pure Julia code. Without output, figures or whatsoever. Just plain Julia code. This is great for version control and comparing source files. I saved the notebook as notebook.jl. In this text file, each notebook cell has a unique identifier. At the and of the file you find the cell order. Pluto has a live documentation feature. It shows documentation while coding. Can be very helpful! Here’s how it works. No interruption from your workflow, just keep coding :-) There is a lot more to say about Pluto notebooks. About it’s support of markdown and LaTeX, options for exporting to HTML and PDF. No hidden state, no hidden bugs. At any instant, the program state is completely described by the code you see. —Fons van der Plas and Mikołaj Bochenski (creators) Pluto is a relative new project with frequent new updates and features. More information on the project is available on its GitHub page. It is a great project and definitely worth trying. Let me know your thoughts.
[ { "code": null, "e": 348, "s": 172, "text": "Pluto is a lightweight and easy to use reactive notebook for the Julia language. In this story I will share my experience with Pluto, especially the five features I love most." }, { "code": null, "e": 566, "s": 348, "text": "Getting started with Pluto is easy. You just add the Pluto package to your project environment and you are good to go. Start Pluto by typing Pluto.run() from the Julia REPL and Pluto opens in your default web browser." }, { "code": null, "e": 658, "s": 566, "text": "In my workflow I usually navigate to my project directory and start Pluto with the command:" }, { "code": null, "e": 721, "s": 658, "text": "julia --threads auto --project=. -e \"using Pluto; Pluto.run()\"" }, { "code": null, "e": 899, "s": 721, "text": "There a many thing to love about coding in Julia with Pluto notebooks. Based on my experience with Pluto this are the 5 features I love most for Exploratory Data Analysis (EDA)." }, { "code": null, "e": 1195, "s": 899, "text": "A key feature of Pluto is it’s reactive nature. When changing a function or variable, Pluto automatically updates all affected cells. No need the remember which cells to execute and in which order. Pluto does all that for you automagically so you can focus on analyzing data. That’s a huge plus." }, { "code": null, "e": 1431, "s": 1195, "text": "When you execute a cell (by pressing ctrl + enter or shift + enter) it shows the execution time of that cell. Very handy for code optimization. A cell can also be execute by pressing the little ▶️ button to the lower right of the cell." }, { "code": null, "e": 1661, "s": 1431, "text": "To enhance the reactive nature of Pluto notebooks even further, there is support for interactive HTML-widgets out-of-the-box. By using widgets, you can minimize the times you needs to change variable values in your code manually." }, { "code": null, "e": 2026, "s": 1661, "text": "Lots of HTML-widgets are supported. To make thing even more easy to use, there is a package — called PlutoUI — which has convenient Julia objects for some of the widgets. Instead of using @bind p html\"<input type=range min=1 max=10>\" you can use @bind p Slider(1:10). Here a an example of a combination of HTML-widgets and widgets supported by the PlutoUI package." }, { "code": null, "e": 2446, "s": 2026, "text": "In Pluto, you can chose any cell order you like. It is also possible to hide cells. So for your final notebook, you can move helper functions to the end of your notebook and move the interactive data visualizations to the top. That does focus the attention of the reader to the message you want communicate. In more traditional notebooks, the most interesting part for the average reader comes at the end of a notebook." }, { "code": null, "e": 2765, "s": 2446, "text": "A Pluto notebook is stored as pure Julia code. Without output, figures or whatsoever. Just plain Julia code. This is great for version control and comparing source files. I saved the notebook as notebook.jl. In this text file, each notebook cell has a unique identifier. At the and of the file you find the cell order." }, { "code": null, "e": 2941, "s": 2765, "text": "Pluto has a live documentation feature. It shows documentation while coding. Can be very helpful! Here’s how it works. No interruption from your workflow, just keep coding :-)" }, { "code": null, "e": 3105, "s": 2941, "text": "There is a lot more to say about Pluto notebooks. About it’s support of markdown and LaTeX, options for exporting to HTML and PDF. No hidden state, no hidden bugs." }, { "code": null, "e": 3236, "s": 3105, "text": "At any instant, the program state is completely described by the code you see. —Fons van der Plas and Mikołaj Bochenski (creators)" } ]
How to train_test_split : KFold vs StratifiedKFold | by Soner Yıldırım | Towards Data Science
The data used in supervised learning tasks contains features and a label for a set of observations. The algorithms try to model the relationship between features (independent variables) and label (dependent variable). We first train the model by providing both features and label for some observations. Then test the model by only providing features and expecting it to predict the labels. Thus, we need to split the data into training and test subsets. We let the model to learn on training set and then measure its performance on test set. Scikit-learn library provides many tools to split data into training and test sets. The most basic one is train_test_split which just divides the data into two parts according to the specified partitioning ratio. For instance, train_test_split(test_size=0.2) will set aside 20% of the data for testing and 80% for training. Let’s see how it is done on an example. We will create a sample dataframe with one feature and a label: import pandas as pdimport numpy as nptarget = np.ones(25)target[-5:] = 0df = pd.DataFrame({'col_a':np.random.random(25), 'target':target})df Then we apply train_test_split function: from sklearn.model_selection import train_test_splitX = df.col_ay = df.targetX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, shuffle=False)print("TRAIN:", X_train.index, "TEST:", X_test.index) The first 80% is training and the last 20% is test set. If we set the shuffle parameter to True, the data will be randomly split: X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, shuffle=True)print("TRAIN:", X_train.index, "TEST:", X_test.index) The default value of shuffle is True so data will be randomly splitted if we do not specify shuffle parameter. If we want the splits to be reproducible, we also need to pass in an integer to random_state parameter. Otherwise, each time we run train_test_split, different indices will be splitted into training and test set. Please note that the numbers seen in the outputs are indices of data points, not the actual values. Data is a valuable asset and we want to make use of every bit of it. If we split data using train_test_split, we can only train a model with the portion set aside for training. The models get better as the amount of training data increases. One solution to overcome this issue is cross validation. With cross validation, dataset is divided into n splits. N-1 split is used for training and the remaining split is used for testing. The model runs through the entire dataset n times and at each time, a different split is used for testing. Thus, we use all of data points for both training and testing. Cross validation is also useful to measure the performance of a model more accurately, especially on new, previously unseen data points. There are different methods to split data in cross validation. KFold and StratifiedKFold are commonly used. As the name suggests, KFold divides the dataset into k folds. If shuffle is set to False, consecutive folds will be the shifted version of previous fold: X = df.col_ay = df.targetkf = KFold(n_splits=4)for train_index, test_index in kf.split(X): print("TRAIN:", train_index, "TEST:", test_index) At first iteration, test set is the first four indices. Then KFold keeps shifting the test set k times. If shuffle is set to True, then the splitting will be random. kf = KFold(n_splits=4, shuffle=True, random_state=1)for train_index, test_index in kf.split(X): print("TRAIN:", train_index, "TEST:", test_index) StratifiedKFold takes the cross validation one step further. The class distribution in the dataset is preserved in the training and test splits. Let’s take a look at our sample dataframe: There are 16 data points. 12 of them belong to class 1 and remaining 4 belong to class 0 so this is an imbalanced class distribution. KFold does not take this into consideration. Therefore, in classifications tasks with imbalanced class distributions, we should prefer StratifiedKFold over KFold. The ratio of class 0 to class 1 is 1/3. If we set k=4, then the test sets include three data points from class 1 and one data point from class 0. Thus, training sets include three data points from class 0 and nine data points from class 1. skf = StratifiedKFold(n_splits=4)for train_index, test_index in skf.split(X, y): print("TRAIN:", train_index, "TEST:", test_index) The indices of class 0 are 12, 13, 14, and 15. As we can see, the class distribution of the dataset is preserved in the splits. We can also use shuffling with StratifiedKFold: skf = StratifiedKFold(n_splits=4, shuffle=True, random_state=1)for train_index, test_index in skf.split(X, y): print("TRAIN:", train_index, "TEST:", test_index) Another method used for splitting is called “leave one out” which only use one data point for testing and remaining data points for training. Scikit learn has LeaveOneOut class to perform this type of partitioning. Finally, I would like to mention about another important tool provided by scikit-learn which is cross_val_score. Cross_val_score takes the dataset and applies cross validation to split the data. Then, train a model using the specified estimator (e.g. logistic regression, decision tree, ...) and measure the performance of the model (scoring parameter). Thank you for reading. Please let me know if you have any feedback.
[ { "code": null, "e": 714, "s": 172, "text": "The data used in supervised learning tasks contains features and a label for a set of observations. The algorithms try to model the relationship between features (independent variables) and label (dependent variable). We first train the model by providing both features and label for some observations. Then test the model by only providing features and expecting it to predict the labels. Thus, we need to split the data into training and test subsets. We let the model to learn on training set and then measure its performance on test set." }, { "code": null, "e": 1142, "s": 714, "text": "Scikit-learn library provides many tools to split data into training and test sets. The most basic one is train_test_split which just divides the data into two parts according to the specified partitioning ratio. For instance, train_test_split(test_size=0.2) will set aside 20% of the data for testing and 80% for training. Let’s see how it is done on an example. We will create a sample dataframe with one feature and a label:" }, { "code": null, "e": 1300, "s": 1142, "text": "import pandas as pdimport numpy as nptarget = np.ones(25)target[-5:] = 0df = pd.DataFrame({'col_a':np.random.random(25), 'target':target})df" }, { "code": null, "e": 1341, "s": 1300, "text": "Then we apply train_test_split function:" }, { "code": null, "e": 1559, "s": 1341, "text": "from sklearn.model_selection import train_test_splitX = df.col_ay = df.targetX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, shuffle=False)print(\"TRAIN:\", X_train.index, \"TEST:\", X_test.index)" }, { "code": null, "e": 1689, "s": 1559, "text": "The first 80% is training and the last 20% is test set. If we set the shuffle parameter to True, the data will be randomly split:" }, { "code": null, "e": 1829, "s": 1689, "text": "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, shuffle=True)print(\"TRAIN:\", X_train.index, \"TEST:\", X_test.index)" }, { "code": null, "e": 2253, "s": 1829, "text": "The default value of shuffle is True so data will be randomly splitted if we do not specify shuffle parameter. If we want the splits to be reproducible, we also need to pass in an integer to random_state parameter. Otherwise, each time we run train_test_split, different indices will be splitted into training and test set. Please note that the numbers seen in the outputs are indices of data points, not the actual values." }, { "code": null, "e": 2991, "s": 2253, "text": "Data is a valuable asset and we want to make use of every bit of it. If we split data using train_test_split, we can only train a model with the portion set aside for training. The models get better as the amount of training data increases. One solution to overcome this issue is cross validation. With cross validation, dataset is divided into n splits. N-1 split is used for training and the remaining split is used for testing. The model runs through the entire dataset n times and at each time, a different split is used for testing. Thus, we use all of data points for both training and testing. Cross validation is also useful to measure the performance of a model more accurately, especially on new, previously unseen data points." }, { "code": null, "e": 3099, "s": 2991, "text": "There are different methods to split data in cross validation. KFold and StratifiedKFold are commonly used." }, { "code": null, "e": 3253, "s": 3099, "text": "As the name suggests, KFold divides the dataset into k folds. If shuffle is set to False, consecutive folds will be the shifted version of previous fold:" }, { "code": null, "e": 3397, "s": 3253, "text": "X = df.col_ay = df.targetkf = KFold(n_splits=4)for train_index, test_index in kf.split(X): print(\"TRAIN:\", train_index, \"TEST:\", test_index)" }, { "code": null, "e": 3563, "s": 3397, "text": "At first iteration, test set is the first four indices. Then KFold keeps shifting the test set k times. If shuffle is set to True, then the splitting will be random." }, { "code": null, "e": 3712, "s": 3563, "text": "kf = KFold(n_splits=4, shuffle=True, random_state=1)for train_index, test_index in kf.split(X): print(\"TRAIN:\", train_index, \"TEST:\", test_index)" }, { "code": null, "e": 3900, "s": 3712, "text": "StratifiedKFold takes the cross validation one step further. The class distribution in the dataset is preserved in the training and test splits. Let’s take a look at our sample dataframe:" }, { "code": null, "e": 4197, "s": 3900, "text": "There are 16 data points. 12 of them belong to class 1 and remaining 4 belong to class 0 so this is an imbalanced class distribution. KFold does not take this into consideration. Therefore, in classifications tasks with imbalanced class distributions, we should prefer StratifiedKFold over KFold." }, { "code": null, "e": 4437, "s": 4197, "text": "The ratio of class 0 to class 1 is 1/3. If we set k=4, then the test sets include three data points from class 1 and one data point from class 0. Thus, training sets include three data points from class 0 and nine data points from class 1." }, { "code": null, "e": 4571, "s": 4437, "text": "skf = StratifiedKFold(n_splits=4)for train_index, test_index in skf.split(X, y): print(\"TRAIN:\", train_index, \"TEST:\", test_index)" }, { "code": null, "e": 4747, "s": 4571, "text": "The indices of class 0 are 12, 13, 14, and 15. As we can see, the class distribution of the dataset is preserved in the splits. We can also use shuffling with StratifiedKFold:" }, { "code": null, "e": 4911, "s": 4747, "text": "skf = StratifiedKFold(n_splits=4, shuffle=True, random_state=1)for train_index, test_index in skf.split(X, y): print(\"TRAIN:\", train_index, \"TEST:\", test_index)" }, { "code": null, "e": 5126, "s": 4911, "text": "Another method used for splitting is called “leave one out” which only use one data point for testing and remaining data points for training. Scikit learn has LeaveOneOut class to perform this type of partitioning." }, { "code": null, "e": 5239, "s": 5126, "text": "Finally, I would like to mention about another important tool provided by scikit-learn which is cross_val_score." }, { "code": null, "e": 5480, "s": 5239, "text": "Cross_val_score takes the dataset and applies cross validation to split the data. Then, train a model using the specified estimator (e.g. logistic regression, decision tree, ...) and measure the performance of the model (scoring parameter)." } ]
Explain Binary Search in Python
Binary search is a searching algorithm which is used to search an element from a sorted array. It cannot be used to search from an unsorted array. Binary search is an efficient algorithm and is better than linear search in terms of time complexity. The time complexity of linear search is O(n). Whereas the time complexity of binary search is O(log n). Hence, binary search is efficient and faster-searching algorithm but can be used only for searching from a sorted array. The basic idea behind binary search is that instead of comparing the required element with all the elements of the array, we will compare the required element with the middle element of the array. If this turns out to be the element we are looking for, we are done with the search successfully. Else, if the element we are looking for is less than the middle element, it is sure that the element lies in the first or left half of the array, since the array is sorted. Similarly, if the element we are looking for is greater than the middle element, it is sure that the element lies in the second half of the array. Thus, Binary search continuously reduces the array into half. The above process is recursively applied on the selected half of the array until we find the element we are looking for. We will start searching with the left index 0 and right index equal to the last index of the array. The middle element index (mid)is calculated which is the sum of the left and right index divided by 2. If the required element is less than the middle element, then the right index is changed to mid-1, which means we will now be looking at the first half of the array only. Likewise, if the required element is greater than the middle element, then the left index is changed to mid+1, which means we will now be looking at the second half of the array only. We will repeat the above process for the selected array half. We need to have some condition to stop searching further which will indicate that the element is not present in the array. We will iteratively search for the element in the array as long as the left index is less than or equal to the right index. Once this condition turns false and we haven’t found the element yet, this means that the element is not present in the array. Let us take the following sorted array and we need to search element 6. L=0 H=8 Mid=4 6<10, therefore take the first half. H=Mid-1 L=0 H=3 Mid=1 6>5, therefore choose the second half. L=Mid+1 L=2 H=3 Mid=2 6==6, an element found Hence the element 6 is found at index 2. From a given sorted array, search for a required element and print its index if the element is present in the array. If the element is not present, print -1. The code for the implementation of binary search is given below. Live Demo def binary_search(arr,x): l=0 r=len(arr)-1 while(l<=r): mid=(l+r)//2 if(arr[mid]==x): return mid elif(x<arr[mid]): r=mid-1 elif(x>arr[mid]): l=mid+1 return -1 array=[1,2,3,4,5,6,7,8,9,10] a=7 print(binary_search(array,a)) b=15 print(binary_search(array,b)) 6 -1 Element 7 is present at index 6. Element 15 is not present in the array, hence -1 is printed.
[ { "code": null, "e": 1311, "s": 1062, "text": "Binary search is a searching algorithm which is used to search an element from a sorted array. It cannot be used to search from an unsorted array. Binary search is an efficient algorithm and is better than linear search in terms of time complexity." }, { "code": null, "e": 1536, "s": 1311, "text": "The time complexity of linear search is O(n). Whereas the time complexity of binary search is O(log n). Hence, binary search is efficient and faster-searching algorithm but can be used only for searching from a sorted array." }, { "code": null, "e": 2151, "s": 1536, "text": "The basic idea behind binary search is that instead of comparing the required element with all the elements of the array, we will compare the required element with the middle element of the array. If this turns out to be the element we are looking for, we are done with the search successfully. Else, if the element we are looking for is less than the middle element, it is sure that the element lies in the first or left half of the array, since the array is sorted. Similarly, if the element we are looking for is greater than the middle element, it is sure that the element lies in the second half of the array." }, { "code": null, "e": 2334, "s": 2151, "text": "Thus, Binary search continuously reduces the array into half. The above process is recursively applied on the selected half of the array until we find the element we are looking for." }, { "code": null, "e": 2954, "s": 2334, "text": "We will start searching with the left index 0 and right index equal to the last index of the array. The middle element index (mid)is calculated which is the sum of the left and right index divided by 2. If the required element is less than the middle element, then the right index is changed to mid-1, which means we will now be looking at the first half of the array only. Likewise, if the required element is greater than the middle element, then the left index is changed to mid+1, which means we will now be looking at the second half of the array only. We will repeat the above process for the selected array half." }, { "code": null, "e": 3328, "s": 2954, "text": "We need to have some condition to stop searching further which will indicate that the element is not present in the array. We will iteratively search for the element in the array as long as the left index is less than or equal to the right index. Once this condition turns false and we haven’t found the element yet, this means that the element is not present in the array." }, { "code": null, "e": 3400, "s": 3328, "text": "Let us take the following sorted array and we need to search element 6." }, { "code": null, "e": 3414, "s": 3400, "text": "L=0 H=8 Mid=4" }, { "code": null, "e": 3451, "s": 3414, "text": "6<10, therefore take the first half." }, { "code": null, "e": 3459, "s": 3451, "text": "H=Mid-1" }, { "code": null, "e": 3473, "s": 3459, "text": "L=0 H=3 Mid=1" }, { "code": null, "e": 3512, "s": 3473, "text": "6>5, therefore choose the second half." }, { "code": null, "e": 3520, "s": 3512, "text": "L=Mid+1" }, { "code": null, "e": 3534, "s": 3520, "text": "L=2 H=3 Mid=2" }, { "code": null, "e": 3557, "s": 3534, "text": "6==6, an element found" }, { "code": null, "e": 3598, "s": 3557, "text": "Hence the element 6 is found at index 2." }, { "code": null, "e": 3756, "s": 3598, "text": "From a given sorted array, search for a required element and print its index if the element is present in the array. If the element is not present, print -1." }, { "code": null, "e": 3821, "s": 3756, "text": "The code for the implementation of binary search is given below." }, { "code": null, "e": 3832, "s": 3821, "text": " Live Demo" }, { "code": null, "e": 4152, "s": 3832, "text": "def binary_search(arr,x):\n l=0\n r=len(arr)-1\n while(l<=r):\n mid=(l+r)//2\n if(arr[mid]==x):\n return mid\n elif(x<arr[mid]):\n r=mid-1\n elif(x>arr[mid]):\n l=mid+1\n return -1\narray=[1,2,3,4,5,6,7,8,9,10]\na=7\nprint(binary_search(array,a))\nb=15\nprint(binary_search(array,b))" }, { "code": null, "e": 4157, "s": 4152, "text": "6\n-1" }, { "code": null, "e": 4190, "s": 4157, "text": "Element 7 is present at index 6." }, { "code": null, "e": 4251, "s": 4190, "text": "Element 15 is not present in the array, hence -1 is printed." } ]
C library function - strcpy()
The C library function char *strcpy(char *dest, const char *src) copies the string pointed to, by src to dest. Following is the declaration for strcpy() function. char *strcpy(char *dest, const char *src) dest − This is the pointer to the destination array where the content is to be copied. dest − This is the pointer to the destination array where the content is to be copied. src − This is the string to be copied. src − This is the string to be copied. This returns a pointer to the destination string dest. The following example shows the usage of strcpy() function. #include <stdio.h> #include <string.h> int main () { char src[40]; char dest[100]; memset(dest, '\0', sizeof(dest)); strcpy(src, "This is tutorialspoint.com"); strcpy(dest, src); printf("Final copied string : %s\n", dest); return(0); } Let us compile and run the above program that will produce the following result − Final copied string : This is tutorialspoint.com 12 Lectures 2 hours Nishant Malik 12 Lectures 2.5 hours Nishant Malik 48 Lectures 6.5 hours Asif Hussain 12 Lectures 2 hours Richa Maheshwari 20 Lectures 3.5 hours Vandana Annavaram 44 Lectures 1 hours Amit Diwan Print Add Notes Bookmark this page
[ { "code": null, "e": 2118, "s": 2007, "text": "The C library function char *strcpy(char *dest, const char *src) copies the string pointed to, by src to dest." }, { "code": null, "e": 2170, "s": 2118, "text": "Following is the declaration for strcpy() function." }, { "code": null, "e": 2212, "s": 2170, "text": "char *strcpy(char *dest, const char *src)" }, { "code": null, "e": 2299, "s": 2212, "text": "dest − This is the pointer to the destination array where the content is to be copied." }, { "code": null, "e": 2386, "s": 2299, "text": "dest − This is the pointer to the destination array where the content is to be copied." }, { "code": null, "e": 2425, "s": 2386, "text": "src − This is the string to be copied." }, { "code": null, "e": 2464, "s": 2425, "text": "src − This is the string to be copied." }, { "code": null, "e": 2519, "s": 2464, "text": "This returns a pointer to the destination string dest." }, { "code": null, "e": 2579, "s": 2519, "text": "The following example shows the usage of strcpy() function." }, { "code": null, "e": 2845, "s": 2579, "text": "#include <stdio.h>\n#include <string.h>\n\nint main () {\n char src[40];\n char dest[100];\n \n memset(dest, '\\0', sizeof(dest));\n strcpy(src, \"This is tutorialspoint.com\");\n strcpy(dest, src);\n\n printf(\"Final copied string : %s\\n\", dest);\n \n return(0);\n}" }, { "code": null, "e": 2927, "s": 2845, "text": "Let us compile and run the above program that will produce the following result −" }, { "code": null, "e": 2977, "s": 2927, "text": "Final copied string : This is tutorialspoint.com\n" }, { "code": null, "e": 3010, "s": 2977, "text": "\n 12 Lectures \n 2 hours \n" }, { "code": null, "e": 3025, "s": 3010, "text": " Nishant Malik" }, { "code": null, "e": 3060, "s": 3025, "text": "\n 12 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3075, "s": 3060, "text": " Nishant Malik" }, { "code": null, "e": 3110, "s": 3075, "text": "\n 48 Lectures \n 6.5 hours \n" }, { "code": null, "e": 3124, "s": 3110, "text": " Asif Hussain" }, { "code": null, "e": 3157, "s": 3124, "text": "\n 12 Lectures \n 2 hours \n" }, { "code": null, "e": 3175, "s": 3157, "text": " Richa Maheshwari" }, { "code": null, "e": 3210, "s": 3175, "text": "\n 20 Lectures \n 3.5 hours \n" }, { "code": null, "e": 3229, "s": 3210, "text": " Vandana Annavaram" }, { "code": null, "e": 3262, "s": 3229, "text": "\n 44 Lectures \n 1 hours \n" }, { "code": null, "e": 3274, "s": 3262, "text": " Amit Diwan" }, { "code": null, "e": 3281, "s": 3274, "text": " Print" }, { "code": null, "e": 3292, "s": 3281, "text": " Add Notes" } ]
A Simple Way to Get a Stock’s Fundamental Data | Towards Data Science
Retrieving or scraping stock data is sometimes easier said than done. It can be fairly difficult to find the right resources or websites containing the appropriately, relevant data. In my data science projects, over the past few years, I have needed to use many different datasets and quite a few of them involved stock data and analysis. In my experience, a stock’s price history is one of the easiest pieces of data to find and retrieve. Usually, I would resort to using Yahoo Finance and the accompanying Python libraries to access this historical price data. However, I have found that the same cannot be said for a stock’s fundamental data. To find fundamental data, such as financial statements and earnings reports, you would potentially need to do some extensive Google searching and tiresome web-scraping. In a previous project of mine, I was fortunate to stumble upon a now defunct website called stockpup.com. This site contained thousands of rows of fundamental data for thousands of stocks. And they were all neatly organized into a simple CSV file for me to download and use for my machine learning projects. Since that website was no longer available, I had to find that data elsewhere... Sign up for a Medium Membership here to gain unlimited access and support content like mine! With your support I earn a small portion of the membership fee. Thanks! There are numerous financial data APIs out there that can give you access to a stock’s fundamental data. Personally, I have found and use one website which is able to provide more than just fundamental data and it is free to sign up called — eodhistoricaldata.com also known as EOD HD. Disclosure: I earn a small commission from any purchases made through the link above. Using this financial data API, I was able to retrieve the fundamental data from thousands of companies. The data was ready and available but now I needed to organize and format it into a Pandas DataFrame that I’ll be able to use. To do so, I utilized Python to get everything set up: # Librariesimport pandas as pdfrom eod import EodHistoricalDatafrom functools import reducefrom datetime import datetime, timedelta# Importing and assigning the api keywith open("../eodHistoricalData-API.txt", "r") as f: api_key = f.read() # EOD Historical Data clientclient = EodHistoricalData(api_key) With my provided API key and the code above, I was ready to begin retrieving and formatting the fundamental data. The API I used is able to provide me with quarterly fundamental data such as Balance Sheets, Income Statements, Cash Flow, and Earnings Reports but they are all neatly stored in their own sections within the API’s return object. I needed to create function that is able to access, then consolidate all of this data into one large DataFrame. So I created a function that is able to transform these separate pieces of data into their own DataFrame, then merge them together into one big DF: In this function, I was able to retrieve fundamental data from the given stock ticker. As you can see, each financial statement is stored within a specific attribute I needed to access. Once I have stored them into their own respective DataFrames, I was then able to consolidate them by merging them together. I also removed any redundant columns such as the “Date” column which was being repeated throughout before I dropped them and any duplicate columns as well. One thing that I found that was missing from the returned fundamental data was the stock price at the time. I figured that would be an important piece of information to have. The API is able to retrieve historical prices fairly easy as well so that wasn’t going to be a problem but I needed to combine those prices with the DataFrame I created above. I created a function that was able to retrieve the daily historical prices and added them to the larger DataFrame: A problem I have found to occur when I was initially adding the prices to the DataFrame was that some price data was missing for certain dates on the larger DF. I assume those dates were sometimes either holidays, weekends, or something similar. Regardless, I just wanted to know what the stock price was around the reported date from the financial statements. It didn’t need to be exact, and in fact it could be just a day or two before or after the reported date. As you can see in the function above, I was able to fill in weekends, holidays, etc. with the previous stock price. Afterwards, I added them to the larger DataFrame which was returned in the end. Since I was able to create two functions to retrieve the fundamental and price data, I decided to condense them into one function: In this one function, I incorporated the previous two functions. I also added the option for additional cleaning of the data by providing choice to remove null values within the larger DF. This option could be useful if you needed to train a machine learning model on this data and couldn’t use NA values in the dataset. The previous functions are all useful in retrieving fundamental data from one given stock ticker but what if I wanted to retrieve data from more than just one stock? To do so, I created the following function which allows the retrieval of fundamental data from multiple stocks: This is a relatively simple function that utilizes the functions above. The first thing I needed to do was cross-reference the given tickers with the available tickers from the API. This is done in case a given ticker doesn’t exist or was improperly given. Afterwards, if the given tickers were valid, then it will retrieve the fundamental data from all the given stocks and combine them into a bigger DF containing the fundamental data from multiple stocks. By using Python and this Financial Data API, I was able to easily retrieve the fundamental data of nearly any stock. Besides coding the formatting process, the overall task was fairly simple. With the fundamental data from multiple stocks ready to go, I can now apply this dataset to any future data science project. A classification or regression ML model could be used on this dataset. Or a simple analysis using Python’s numerous visualization libraries. There are a never-ending assortment of projects that can use a dataset such as this.
[ { "code": null, "e": 511, "s": 172, "text": "Retrieving or scraping stock data is sometimes easier said than done. It can be fairly difficult to find the right resources or websites containing the appropriately, relevant data. In my data science projects, over the past few years, I have needed to use many different datasets and quite a few of them involved stock data and analysis." }, { "code": null, "e": 818, "s": 511, "text": "In my experience, a stock’s price history is one of the easiest pieces of data to find and retrieve. Usually, I would resort to using Yahoo Finance and the accompanying Python libraries to access this historical price data. However, I have found that the same cannot be said for a stock’s fundamental data." }, { "code": null, "e": 1295, "s": 818, "text": "To find fundamental data, such as financial statements and earnings reports, you would potentially need to do some extensive Google searching and tiresome web-scraping. In a previous project of mine, I was fortunate to stumble upon a now defunct website called stockpup.com. This site contained thousands of rows of fundamental data for thousands of stocks. And they were all neatly organized into a simple CSV file for me to download and use for my machine learning projects." }, { "code": null, "e": 1376, "s": 1295, "text": "Since that website was no longer available, I had to find that data elsewhere..." }, { "code": null, "e": 1541, "s": 1376, "text": "Sign up for a Medium Membership here to gain unlimited access and support content like mine! With your support I earn a small portion of the membership fee. Thanks!" }, { "code": null, "e": 1913, "s": 1541, "text": "There are numerous financial data APIs out there that can give you access to a stock’s fundamental data. Personally, I have found and use one website which is able to provide more than just fundamental data and it is free to sign up called — eodhistoricaldata.com also known as EOD HD. Disclosure: I earn a small commission from any purchases made through the link above." }, { "code": null, "e": 2197, "s": 1913, "text": "Using this financial data API, I was able to retrieve the fundamental data from thousands of companies. The data was ready and available but now I needed to organize and format it into a Pandas DataFrame that I’ll be able to use. To do so, I utilized Python to get everything set up:" }, { "code": null, "e": 2507, "s": 2197, "text": "# Librariesimport pandas as pdfrom eod import EodHistoricalDatafrom functools import reducefrom datetime import datetime, timedelta# Importing and assigning the api keywith open(\"../eodHistoricalData-API.txt\", \"r\") as f: api_key = f.read() # EOD Historical Data clientclient = EodHistoricalData(api_key)" }, { "code": null, "e": 2621, "s": 2507, "text": "With my provided API key and the code above, I was ready to begin retrieving and formatting the fundamental data." }, { "code": null, "e": 2962, "s": 2621, "text": "The API I used is able to provide me with quarterly fundamental data such as Balance Sheets, Income Statements, Cash Flow, and Earnings Reports but they are all neatly stored in their own sections within the API’s return object. I needed to create function that is able to access, then consolidate all of this data into one large DataFrame." }, { "code": null, "e": 3110, "s": 2962, "text": "So I created a function that is able to transform these separate pieces of data into their own DataFrame, then merge them together into one big DF:" }, { "code": null, "e": 3576, "s": 3110, "text": "In this function, I was able to retrieve fundamental data from the given stock ticker. As you can see, each financial statement is stored within a specific attribute I needed to access. Once I have stored them into their own respective DataFrames, I was then able to consolidate them by merging them together. I also removed any redundant columns such as the “Date” column which was being repeated throughout before I dropped them and any duplicate columns as well." }, { "code": null, "e": 3927, "s": 3576, "text": "One thing that I found that was missing from the returned fundamental data was the stock price at the time. I figured that would be an important piece of information to have. The API is able to retrieve historical prices fairly easy as well so that wasn’t going to be a problem but I needed to combine those prices with the DataFrame I created above." }, { "code": null, "e": 4042, "s": 3927, "text": "I created a function that was able to retrieve the daily historical prices and added them to the larger DataFrame:" }, { "code": null, "e": 4508, "s": 4042, "text": "A problem I have found to occur when I was initially adding the prices to the DataFrame was that some price data was missing for certain dates on the larger DF. I assume those dates were sometimes either holidays, weekends, or something similar. Regardless, I just wanted to know what the stock price was around the reported date from the financial statements. It didn’t need to be exact, and in fact it could be just a day or two before or after the reported date." }, { "code": null, "e": 4704, "s": 4508, "text": "As you can see in the function above, I was able to fill in weekends, holidays, etc. with the previous stock price. Afterwards, I added them to the larger DataFrame which was returned in the end." }, { "code": null, "e": 4835, "s": 4704, "text": "Since I was able to create two functions to retrieve the fundamental and price data, I decided to condense them into one function:" }, { "code": null, "e": 5156, "s": 4835, "text": "In this one function, I incorporated the previous two functions. I also added the option for additional cleaning of the data by providing choice to remove null values within the larger DF. This option could be useful if you needed to train a machine learning model on this data and couldn’t use NA values in the dataset." }, { "code": null, "e": 5434, "s": 5156, "text": "The previous functions are all useful in retrieving fundamental data from one given stock ticker but what if I wanted to retrieve data from more than just one stock? To do so, I created the following function which allows the retrieval of fundamental data from multiple stocks:" }, { "code": null, "e": 5893, "s": 5434, "text": "This is a relatively simple function that utilizes the functions above. The first thing I needed to do was cross-reference the given tickers with the available tickers from the API. This is done in case a given ticker doesn’t exist or was improperly given. Afterwards, if the given tickers were valid, then it will retrieve the fundamental data from all the given stocks and combine them into a bigger DF containing the fundamental data from multiple stocks." }, { "code": null, "e": 6085, "s": 5893, "text": "By using Python and this Financial Data API, I was able to easily retrieve the fundamental data of nearly any stock. Besides coding the formatting process, the overall task was fairly simple." } ]
How can I get a stack trace for a JavaScript exception?
To get a JavaScript stack trace, simply add the following in your code. It will display the stack trace − Live Demo <html> <head> <script> function stackTrace() { var err = new Error(); return err.stack; } console.log(stackTrace()); document.write(stackTrace()); </script> </head> <body> <p>Stacktrace prints above.</p> </body> </html>
[ { "code": null, "e": 1168, "s": 1062, "text": "To get a JavaScript stack trace, simply add the following in your code. It will display the stack trace −" }, { "code": null, "e": 1179, "s": 1168, "text": " Live Demo" }, { "code": null, "e": 1490, "s": 1179, "text": "<html>\n <head>\n <script>\n function stackTrace() {\n var err = new Error();\n return err.stack;\n }\n\n console.log(stackTrace());\n document.write(stackTrace());\n </script>\n </head>\n <body>\n <p>Stacktrace prints above.</p>\n </body>\n</html>" } ]
Char.IsUpper() Method in C#
The Char.IsUpper() method in C# indicates whether the specified Unicode character is categorized as an uppercase letter. public static bool IsUpper (char ch); Above, the parameter ch is the Unicode character to evaluate. Let us now see an example to implement the Char.IsUpper() method − using System; public class Demo { public static void Main(){ bool res; char val = 'H'; Console.WriteLine("Value = "+val); res = Char.IsUpper(val); Console.WriteLine("Is the value an uppercae letter? = "+res); } } This will produce the following output − Value = H Is the value an uppercae letter? = True Let us now see another example to implement IsUpper() method − using System; public class Demo { public static void Main(){ bool res; char val = 'j'; Console.WriteLine("Value = "+val); res = Char.IsUpper(val); Console.WriteLine("Is the value an uppercae letter? = "+res); } } This will produce the following output − Value = j Is the value an uppercae letter? = False
[ { "code": null, "e": 1183, "s": 1062, "text": "The Char.IsUpper() method in C# indicates whether the specified Unicode character is categorized as an uppercase letter." }, { "code": null, "e": 1221, "s": 1183, "text": "public static bool IsUpper (char ch);" }, { "code": null, "e": 1283, "s": 1221, "text": "Above, the parameter ch is the Unicode character to evaluate." }, { "code": null, "e": 1350, "s": 1283, "text": "Let us now see an example to implement the Char.IsUpper() method −" }, { "code": null, "e": 1599, "s": 1350, "text": "using System;\npublic class Demo {\n public static void Main(){\n bool res;\n char val = 'H';\n Console.WriteLine(\"Value = \"+val);\n res = Char.IsUpper(val);\n Console.WriteLine(\"Is the value an uppercae letter? = \"+res);\n }\n}" }, { "code": null, "e": 1640, "s": 1599, "text": "This will produce the following output −" }, { "code": null, "e": 1690, "s": 1640, "text": "Value = H\nIs the value an uppercae letter? = True" }, { "code": null, "e": 1753, "s": 1690, "text": "Let us now see another example to implement IsUpper() method −" }, { "code": null, "e": 2002, "s": 1753, "text": "using System;\npublic class Demo {\n public static void Main(){\n bool res;\n char val = 'j';\n Console.WriteLine(\"Value = \"+val);\n res = Char.IsUpper(val);\n Console.WriteLine(\"Is the value an uppercae letter? = \"+res);\n }\n}" }, { "code": null, "e": 2043, "s": 2002, "text": "This will produce the following output −" }, { "code": null, "e": 2094, "s": 2043, "text": "Value = j\nIs the value an uppercae letter? = False" } ]
C# | Check if two String objects have the same value | Set-1 - GeeksforGeeks
03 Aug, 2021 String.Equals Method method is used to check whether the two String objects have the same value. This method can be overloaded by passing different numbers and types of parameters to it. There are total 5 methods in the overload list of this method in which the first 2 are discussed in this article and the remaining are discussed in Set-2 and Set-3. Equals(Object)Equals(String)Equals(String, String)Equals(String, StringComparison)Equals(String, String, StringComparison) Equals(Object) Equals(String) Equals(String, String) Equals(String, StringComparison) Equals(String, String, StringComparison) This method is used to check whether this instance and a specified object, which must also be a String object, have the same value or not. This method also performs an ordinal comparison in both case-sensitive and culture-insensitive. Syntax: public override bool Equals (object ob1); Here, ob1 is the string object that is used to compare with this instance. Return Value: The return type of this method is System.Boolean. If ob1 is a String and its value is the same as this instance, then this method will return true, otherwise return false. And if the value of ob1 is null then this method will return false. Example: C# // C# program to illustrate// Equals(Object) methodusing System; // Structurepublic struct Student{ private string name; public string StudentName { get { return name; } } public Student(string Sname) { name = Sname; } public override string ToString() { return name; }} // Driver Classpublic class GFG { // Main method static void Main(String[] args) { // Creating object of Student structure Student s1 = new Student("Ankita"); Student s2 = new Student("Soniya"); Student s3 = new Student("Ankita"); // Check the given objects are equal or not Console.WriteLine("Object 1 is equal to object 2: {0}", s1.Equals(s2)); Console.WriteLine("Object 1 is equal to object 3: {0}", s1.Equals(s3)); }} Object 1 is equal to object 2: False Object 1 is equal to object 3: True This method is used to check whether this instance and another specified String object have the same value. This method also performs an ordinal comparison in both case-sensitive and culture-insensitive. Syntax: public bool Equals (string item); Here, item is a string that is used to compare with this instance. Return Value: The return type of this method is System.Boolean. If the value of item is same as the value of this instance, then this method will return true, otherwise, return false. And if the value of item is null then this method will return false. Example: C# // C# program to illustrate// Equals(String) methodusing System; class GFG { // Main method static void Main(String[] args) { // Creating object of Student structure string s1 = "GeeksforGeeks"; string s2 = "hellogeeksforgeeks"; string s3 = "GeeksforGeeks"; // Check the given strings are equal or not Console.WriteLine("String 1 is equal to String 2: {0}", s1.Equals(s2)); Console.WriteLine("String 1 is equal to String 3: {0}", s1.Equals(s3)); }} String 1 is equal to String 2: False String 1 is equal to String 3: True Next: Set-2 and Set-3Reference: https://docs.microsoft.com/en-us/dotnet/api/system.string.equals?view=netframework-4.7.2 nidhi_biet arorakashish0911 CSharp-method CSharp-string C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments C# | Class and Object Lambda Expressions in C# HashSet in C# with Examples C# | How to use strings in switch statement C# | Replace() Method Collections in C# C# | Abstract Classes C# | Data Types Introduction to .NET Framework C# | Math.Floor() Method
[ { "code": null, "e": 24081, "s": 24053, "text": "\n03 Aug, 2021" }, { "code": null, "e": 24434, "s": 24081, "text": "String.Equals Method method is used to check whether the two String objects have the same value. This method can be overloaded by passing different numbers and types of parameters to it. There are total 5 methods in the overload list of this method in which the first 2 are discussed in this article and the remaining are discussed in Set-2 and Set-3. " }, { "code": null, "e": 24557, "s": 24434, "text": "Equals(Object)Equals(String)Equals(String, String)Equals(String, StringComparison)Equals(String, String, StringComparison)" }, { "code": null, "e": 24572, "s": 24557, "text": "Equals(Object)" }, { "code": null, "e": 24587, "s": 24572, "text": "Equals(String)" }, { "code": null, "e": 24610, "s": 24587, "text": "Equals(String, String)" }, { "code": null, "e": 24643, "s": 24610, "text": "Equals(String, StringComparison)" }, { "code": null, "e": 24684, "s": 24643, "text": "Equals(String, String, StringComparison)" }, { "code": null, "e": 24919, "s": 24684, "text": "This method is used to check whether this instance and a specified object, which must also be a String object, have the same value or not. This method also performs an ordinal comparison in both case-sensitive and culture-insensitive." }, { "code": null, "e": 24928, "s": 24919, "text": "Syntax: " }, { "code": null, "e": 24970, "s": 24928, "text": "public override bool Equals (object ob1);" }, { "code": null, "e": 25045, "s": 24970, "text": "Here, ob1 is the string object that is used to compare with this instance." }, { "code": null, "e": 25300, "s": 25045, "text": "Return Value: The return type of this method is System.Boolean. If ob1 is a String and its value is the same as this instance, then this method will return true, otherwise return false. And if the value of ob1 is null then this method will return false. " }, { "code": null, "e": 25309, "s": 25300, "text": "Example:" }, { "code": null, "e": 25312, "s": 25309, "text": "C#" }, { "code": "// C# program to illustrate// Equals(Object) methodusing System; // Structurepublic struct Student{ private string name; public string StudentName { get { return name; } } public Student(string Sname) { name = Sname; } public override string ToString() { return name; }} // Driver Classpublic class GFG { // Main method static void Main(String[] args) { // Creating object of Student structure Student s1 = new Student(\"Ankita\"); Student s2 = new Student(\"Soniya\"); Student s3 = new Student(\"Ankita\"); // Check the given objects are equal or not Console.WriteLine(\"Object 1 is equal to object 2: {0}\", s1.Equals(s2)); Console.WriteLine(\"Object 1 is equal to object 3: {0}\", s1.Equals(s3)); }}", "e": 26243, "s": 25312, "text": null }, { "code": null, "e": 26316, "s": 26243, "text": "Object 1 is equal to object 2: False\nObject 1 is equal to object 3: True" }, { "code": null, "e": 26522, "s": 26318, "text": "This method is used to check whether this instance and another specified String object have the same value. This method also performs an ordinal comparison in both case-sensitive and culture-insensitive." }, { "code": null, "e": 26531, "s": 26522, "text": "Syntax: " }, { "code": null, "e": 26565, "s": 26531, "text": "public bool Equals (string item);" }, { "code": null, "e": 26632, "s": 26565, "text": "Here, item is a string that is used to compare with this instance." }, { "code": null, "e": 26885, "s": 26632, "text": "Return Value: The return type of this method is System.Boolean. If the value of item is same as the value of this instance, then this method will return true, otherwise, return false. And if the value of item is null then this method will return false." }, { "code": null, "e": 26894, "s": 26885, "text": "Example:" }, { "code": null, "e": 26897, "s": 26894, "text": "C#" }, { "code": "// C# program to illustrate// Equals(String) methodusing System; class GFG { // Main method static void Main(String[] args) { // Creating object of Student structure string s1 = \"GeeksforGeeks\"; string s2 = \"hellogeeksforgeeks\"; string s3 = \"GeeksforGeeks\"; // Check the given strings are equal or not Console.WriteLine(\"String 1 is equal to String 2: {0}\", s1.Equals(s2)); Console.WriteLine(\"String 1 is equal to String 3: {0}\", s1.Equals(s3)); }}", "e": 27505, "s": 26897, "text": null }, { "code": null, "e": 27578, "s": 27505, "text": "String 1 is equal to String 2: False\nString 1 is equal to String 3: True" }, { "code": null, "e": 27702, "s": 27580, "text": "Next: Set-2 and Set-3Reference: https://docs.microsoft.com/en-us/dotnet/api/system.string.equals?view=netframework-4.7.2 " }, { "code": null, "e": 27713, "s": 27702, "text": "nidhi_biet" }, { "code": null, "e": 27730, "s": 27713, "text": "arorakashish0911" }, { "code": null, "e": 27744, "s": 27730, "text": "CSharp-method" }, { "code": null, "e": 27758, "s": 27744, "text": "CSharp-string" }, { "code": null, "e": 27761, "s": 27758, "text": "C#" }, { "code": null, "e": 27859, "s": 27761, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27868, "s": 27859, "text": "Comments" }, { "code": null, "e": 27881, "s": 27868, "text": "Old Comments" }, { "code": null, "e": 27903, "s": 27881, "text": "C# | Class and Object" }, { "code": null, "e": 27928, "s": 27903, "text": "Lambda Expressions in C#" }, { "code": null, "e": 27956, "s": 27928, "text": "HashSet in C# with Examples" }, { "code": null, "e": 28000, "s": 27956, "text": "C# | How to use strings in switch statement" }, { "code": null, "e": 28022, "s": 28000, "text": "C# | Replace() Method" }, { "code": null, "e": 28040, "s": 28022, "text": "Collections in C#" }, { "code": null, "e": 28062, "s": 28040, "text": "C# | Abstract Classes" }, { "code": null, "e": 28078, "s": 28062, "text": "C# | Data Types" }, { "code": null, "e": 28109, "s": 28078, "text": "Introduction to .NET Framework" } ]
How to remove table row from table using jQuery ? - GeeksforGeeks
03 Aug, 2021 The jQuery remove() method is used to remove a row from HTML table.jQuery remove() Method: This method removes the selected elements alongwith text and child nodes. This method also removes data and events of the selected elements. Syntax: $(selector).remove(selector) Parameters: It accepts single parameter selector which is optional. It specifies one or more elements to be removed. If multiple elements are to be removed, separate them with a comma (,) operator. Example 1: This example first selects the row by id value and then removes it by using remove() method. <!DOCTYPE HTML> <html> <head> <title> How to remove a table row from table </title> <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"> </script> <style> #myCol { background:green; } table { color:white; } #Geek_p { color:green; font-size:30px; } td { padding:10px; } </style> </head> <body> <center> <h1 style = "color:green;" > GeeksForGeeks </h1> <table> <colgroup> <col id="myCol" span="2"> <col style="background-color:green"> </colgroup> <tr> <th>S.No</th> <th>Title</th> <th>Geek_id</th> </tr> <tr id = "row1"> <td>Geek_1</td> <td>GeekForGeeks</td> <th>Geek_id_1</th> </tr> <tr> <td>Geek_2</td> <td>GeeksForGeeks</td> <th>Geek_id_2</th> </tr> </table> <br> <button onclick = "Geeks()"> Click here </button> <!-- Script to remove table row from table --> <script> function Geeks() { $("#row1").remove(); } </script> </center> </body> </html> Output: Before clicking on the button: After clicking on the button: Example 2: This example first select the last <tr> element of its parent and removes it by using remove() method. <!DOCTYPE HTML> <html> <head> <title> How to remove table row from table </title> <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"> </script> <style> #myCol { background:green; } table { color:white; } #Geek_p { color:green; font-size:30px; } td { padding:10px; } </style> </head> <body> <center> <h1 style = "color:green;" > GeeksForGeeks </h1> <table> <colgroup> <col id="myCol" span="2"> <col style="background-color:green"> </colgroup> <tr> <th>S.No</th> <th>Title</th> <th>Geek_id</th> </tr> <tr id = "row1"> <td>Geek_1</td> <td>GeekForGeeks</td> <th>Geek_id_1</th> </tr> <tr> <td>Geek_2</td> <td>GeeksForGeeks</td> <th>Geek_id_2</th> </tr> </table> <br> <button onclick = "Geeks()"> Click here </button> <script> function Geeks() { $('tr:last-child').remove(); } </script> </center> </body> </html> Output: Before clicking on the button: After clicking 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. jQuery-Misc JQuery Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Show and Hide div elements using radio buttons? How to prevent Body from scrolling when a modal is opened using jQuery ? jQuery | ajax() Method jQuery | removeAttr() with Examples How to get the value in an input text box using jQuery ? 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": 27064, "s": 27036, "text": "\n03 Aug, 2021" }, { "code": null, "e": 27296, "s": 27064, "text": "The jQuery remove() method is used to remove a row from HTML table.jQuery remove() Method: This method removes the selected elements alongwith text and child nodes. This method also removes data and events of the selected elements." }, { "code": null, "e": 27304, "s": 27296, "text": "Syntax:" }, { "code": null, "e": 27333, "s": 27304, "text": "$(selector).remove(selector)" }, { "code": null, "e": 27531, "s": 27333, "text": "Parameters: It accepts single parameter selector which is optional. It specifies one or more elements to be removed. If multiple elements are to be removed, separate them with a comma (,) operator." }, { "code": null, "e": 27635, "s": 27531, "text": "Example 1: This example first selects the row by id value and then removes it by using remove() method." }, { "code": "<!DOCTYPE HTML> <html> <head> <title> How to remove a table row from table </title> <script src = \"https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js\"> </script> <style> #myCol { background:green; } table { color:white; } #Geek_p { color:green; font-size:30px; } td { padding:10px; } </style> </head> <body> <center> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <table> <colgroup> <col id=\"myCol\" span=\"2\"> <col style=\"background-color:green\"> </colgroup> <tr> <th>S.No</th> <th>Title</th> <th>Geek_id</th> </tr> <tr id = \"row1\"> <td>Geek_1</td> <td>GeekForGeeks</td> <th>Geek_id_1</th> </tr> <tr> <td>Geek_2</td> <td>GeeksForGeeks</td> <th>Geek_id_2</th> </tr> </table> <br> <button onclick = \"Geeks()\"> Click here </button> <!-- Script to remove table row from table --> <script> function Geeks() { $(\"#row1\").remove(); } </script> </center> </body> </html> ", "e": 29431, "s": 27635, "text": null }, { "code": null, "e": 29439, "s": 29431, "text": "Output:" }, { "code": null, "e": 29470, "s": 29439, "text": "Before clicking on the button:" }, { "code": null, "e": 29500, "s": 29470, "text": "After clicking on the button:" }, { "code": null, "e": 29614, "s": 29500, "text": "Example 2: This example first select the last <tr> element of its parent and removes it by using remove() method." }, { "code": "<!DOCTYPE HTML> <html> <head> <title> How to remove table row from table </title> <script src = \"https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js\"> </script> <style> #myCol { background:green; } table { color:white; } #Geek_p { color:green; font-size:30px; } td { padding:10px; } </style> </head> <body> <center> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <table> <colgroup> <col id=\"myCol\" span=\"2\"> <col style=\"background-color:green\"> </colgroup> <tr> <th>S.No</th> <th>Title</th> <th>Geek_id</th> </tr> <tr id = \"row1\"> <td>Geek_1</td> <td>GeekForGeeks</td> <th>Geek_id_1</th> </tr> <tr> <td>Geek_2</td> <td>GeeksForGeeks</td> <th>Geek_id_2</th> </tr> </table> <br> <button onclick = \"Geeks()\"> Click here </button> <script> function Geeks() { $('tr:last-child').remove(); } </script> </center> </body> </html> ", "e": 31353, "s": 29614, "text": null }, { "code": null, "e": 31361, "s": 31353, "text": "Output:" }, { "code": null, "e": 31392, "s": 31361, "text": "Before clicking on the button:" }, { "code": null, "e": 31422, "s": 31392, "text": "After clicking on the button:" }, { "code": null, "e": 31690, "s": 31422, "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": 31702, "s": 31690, "text": "jQuery-Misc" }, { "code": null, "e": 31709, "s": 31702, "text": "JQuery" }, { "code": null, "e": 31726, "s": 31709, "text": "Web Technologies" }, { "code": null, "e": 31753, "s": 31726, "text": "Web technologies Questions" }, { "code": null, "e": 31851, "s": 31753, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31906, "s": 31851, "text": "How to Show and Hide div elements using radio buttons?" }, { "code": null, "e": 31979, "s": 31906, "text": "How to prevent Body from scrolling when a modal is opened using jQuery ?" }, { "code": null, "e": 32002, "s": 31979, "text": "jQuery | ajax() Method" }, { "code": null, "e": 32038, "s": 32002, "text": "jQuery | removeAttr() with Examples" }, { "code": null, "e": 32095, "s": 32038, "text": "How to get the value in an input text box using jQuery ?" }, { "code": null, "e": 32135, "s": 32095, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 32168, "s": 32135, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 32213, "s": 32168, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 32256, "s": 32213, "text": "How to fetch data from an API in ReactJS ?" } ]
Count subsets having product divisible by K - GeeksforGeeks
24 Apr, 2021 Given an array arr[] of size N and an integer K, the task is to count the number of subsets from the given array with product of elements divisible by K Examples: Input: arr[] = {1, 2, 3, 4, 5}, K = 60Output: 4Explanation: Subsets whose product of elements is divisible by K(= 60) are { {1, 2, 3, 4, 5}, {2, 3, 4, 5}, {3, 4, 5}, {1, 3, 4, 5} } Input: arr[] = {1, 2, 3, 4, 5, 6}, K = 60Output: 16 Naive Approach: The simplest approach to solve this problem is to generate all possible subsets and for each subset, check if the product of its elements is divisible by K or not. If found to be true, then increment the count. Finally, print the count. Time Complexity: O(N * 2N)Auxiliary Space: O(N) Efficient Approach: To optimize the above approach the idea is to use Dynamic programming. Below is the recurrence relation and the base case: Recurrence Relation: cntSubDivK(N, rem) = cntSubDivK(N – 1, (rem * arr[N – 1]) % K) + cntSubDivK(N – 1, rem). cntSubDivK(N, rem) store the count of subset having product divisible by K. rem: Store the remainder when K divides the product of all elements of the subset. Base Case: if N == 0 and rem == 0 then return 1. If N == 0 and rem != 0 then return 0. Follow the steps below to solve the problem: Initialize a 2D array, say dp[N][rem] to compute and store the values of all subproblems of the above recurrence relation. Finally, return the value of dp[N][rem]. 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 count the subsets whose// product of elements is divisible by Kint cntSubDivK(int arr[], int N, int K, int rem, vector<vector<int> >& dp){ // If count of elements // in the array is 0 if (N == 0) { // If rem is 0, then return 1 // Otherwise, return 0 return rem == 0; } // If already computed // subproblem occurred if (dp[N][rem] != -1) { return dp[N][rem]; } // Stores count of subsets having product // divisible by K when arr[N - 1] // present in the subset int X = cntSubDivK(arr, N - 1, K, (rem * arr[N - 1]) % K, dp); // Stores count of subsets having product // divisible by K when arr[N - 1] not // present in the subset int Y = cntSubDivK(arr, N - 1, K, rem, dp); // Return total subset return X + Y;} // Utility Function to count the subsets whose// product of elements is divisible by Kint UtilCntSubDivK(int arr[], int N, int K){ // Initialize a 2D array to store values // of overlapping subproblems vector<vector<int> > dp(N + 1, vector<int>(K + 1, -1)); return cntSubDivK(arr, N, K, 1, dp);} // Driver Codeint main(){ int arr[] = { 1, 2, 3, 4, 5, 6 }; int K = 60; int N = sizeof(arr) / sizeof(arr[0]); cout << UtilCntSubDivK(arr, N, K);} // Java program to implement// the above approachimport java.util.*; class GFG{ // Function to count the subsets whose// product of elements is divisible by Kstatic int cntSubDivK(int arr[], int N, int K, int rem, int[][]dp){ // If count of elements // in the array is 0 if (N == 0) { // If rem is 0, then return 1 // Otherwise, return 0 return rem == 0 ? 1 : 0; } // If already computed // subproblem occurred if (dp[N][rem] != -1) { return dp[N][rem]; } // Stores count of subsets having product // divisible by K when arr[N - 1] // present in the subset int X = cntSubDivK(arr, N - 1, K, (rem * arr[N - 1]) % K, dp); // Stores count of subsets having product // divisible by K when arr[N - 1] not // present in the subset int Y = cntSubDivK(arr, N - 1, K, rem, dp); // Return total subset return X + Y;} // Utility Function to count the subsets whose// product of elements is divisible by Kstatic int UtilCntSubDivK(int arr[], int N, int K){ // Initialize a 2D array to store values // of overlapping subproblems int [][]dp = new int[N + 1][K + 1]; for(int i = 0; i < N + 1; i++) { for(int j = 0; j < K + 1; j++) dp[i][j] = -1; } return cntSubDivK(arr, N, K, 1, dp);} // Driver Codepublic static void main(String args[]){ int arr[] = { 1, 2, 3, 4, 5, 6 }; int K = 60; int N = arr.length; System.out.println(UtilCntSubDivK(arr, N, K));}} // This code is contributed by SURENDRA_GANGWAR # Python3 program to# implement the above# approach # Function to count the# subsets whose product# of elements is divisible# by Kdef cntSubDivK(arr, N, K, rem, dp): # If count of elements # in the array is 0 if (N == 0): # If rem is 0, then # return 1 Otherwise, # return 0 return rem == 0 # If already computed # subproblem occurred if (dp[N][rem] != -1): return dp[N][rem] # Stores count of subsets # having product divisible # by K when arr[N - 1] # present in the subset X = cntSubDivK(arr, N - 1, K, (rem * arr[N - 1]) % K, dp) # Stores count of subsets having # product divisible by K when # arr[N - 1] not present in # the subset Y = cntSubDivK(arr, N - 1, K, rem, dp) # Return total subset return X + Y # Utility Function to count# the subsets whose product of# elements is divisible by Kdef UtilCntSubDivK(arr, N, K): # Initialize a 2D array to # store values of overlapping # subproblems dp = [[-1 for x in range(K + 1)] for y in range(N + 1)] return cntSubDivK(arr, N, K, 1, dp) # Driver Codeif __name__ == "__main__": arr = [1, 2, 3, 4, 5, 6] K = 60 N = len(arr) print(UtilCntSubDivK(arr, N, K)) # This code is contributed by Chitranayal // C# program to implement// the above approachusing System; class GFG{ // Function to count the subsets whose// product of elements is divisible by Kstatic int cntSubDivK(int[] arr, int N, int K, int rem, int[,] dp){ // If count of elements // in the array is 0 if (N == 0) { // If rem is 0, then return 1 // Otherwise, return 0 return rem == 0 ? 1 : 0; } // If already computed // subproblem occurred if (dp[N, rem] != -1) { return dp[N, rem]; } // Stores count of subsets having product // divisible by K when arr[N - 1] // present in the subset int X = cntSubDivK(arr, N - 1, K, (rem * arr[N - 1]) % K, dp); // Stores count of subsets having product // divisible by K when arr[N - 1] not // present in the subset int Y = cntSubDivK(arr, N - 1, K, rem, dp); // Return total subset return X + Y;} // Utility Function to count the subsets whose// product of elements is divisible by Kstatic int UtilCntSubDivK(int[] arr, int N, int K){ // Initialize a 2D array to store values // of overlapping subproblems int[,] dp = new int[N + 1, K + 1]; for(int i = 0; i < N + 1; i++) { for(int j = 0; j < K + 1; j++) dp[i, j] = -1; } return cntSubDivK(arr, N, K, 1, dp);} // Driver codestatic void Main(){ int[] arr = { 1, 2, 3, 4, 5, 6 }; int K = 60; int N = arr.Length; Console.WriteLine(UtilCntSubDivK(arr, N, K));}} // This code is contributed by divyeshrabadiya07 <script> // JavaScript program to implement// the above approach // Function to count the subsets whose// product of elements is divisible by Kfunction cntSubDivK(arr, N, K, rem, dp){ // If count of elements // in the array is 0 if (N == 0) { // If rem is 0, then return 1 // Otherwise, return 0 return rem == 0 ? 1 : 0; } // If already computed // subproblem occurred if (dp[N][rem] != -1) { return dp[N][rem]; } // Stores count of subsets having product // divisible by K when arr[N - 1] // present in the subset let X = cntSubDivK(arr, N - 1, K, (rem * arr[N - 1]) % K, dp); // Stores count of subsets having product // divisible by K when arr[N - 1] not // present in the subset let Y = cntSubDivK(arr, N - 1, K, rem, dp); // Return total subset return X + Y;} // Utility Function to count the subsets whose// product of elements is divisible by Kfunction UtilCntSubDivK(arr, N, K){ // Initialize a 2D array to store values // of overlapping subproblems let dp = new Array(N + 1); // Loop to create 2D array using 1D array for(var i = 0; i < dp.length; i++) { dp[i] = new Array(2); } for(let i = 0; i < N + 1; i++) { for(let j = 0; j < K + 1; j++) dp[i][j] = -1; } return cntSubDivK(arr, N, K, 1, dp);} // Driver Codelet arr = [ 1, 2, 3, 4, 5, 6 ];let K = 60;let N = arr.length; document.write(UtilCntSubDivK(arr, N, K)); // This code is contribute by target_2 </script> 16 Time Complexity: O(N * K)Space Complexity: O(N * K) ukasp SURENDRA_GANGWAR divyeshrabadiya07 target_2 divisibility subset Arrays Backtracking Mathematical Arrays Mathematical subset Backtracking 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 Introduction to Arrays Multidimensional Arrays in Java Linear Search N Queen Problem | Backtracking-3 Write a program to print all permutations of a given string Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) Backtracking | Introduction Rat in a Maze | Backtracking-2
[ { "code": null, "e": 27113, "s": 27085, "text": "\n24 Apr, 2021" }, { "code": null, "e": 27266, "s": 27113, "text": "Given an array arr[] of size N and an integer K, the task is to count the number of subsets from the given array with product of elements divisible by K" }, { "code": null, "e": 27276, "s": 27266, "text": "Examples:" }, { "code": null, "e": 27457, "s": 27276, "text": "Input: arr[] = {1, 2, 3, 4, 5}, K = 60Output: 4Explanation: Subsets whose product of elements is divisible by K(= 60) are { {1, 2, 3, 4, 5}, {2, 3, 4, 5}, {3, 4, 5}, {1, 3, 4, 5} }" }, { "code": null, "e": 27509, "s": 27457, "text": "Input: arr[] = {1, 2, 3, 4, 5, 6}, K = 60Output: 16" }, { "code": null, "e": 27762, "s": 27509, "text": "Naive Approach: The simplest approach to solve this problem is to generate all possible subsets and for each subset, check if the product of its elements is divisible by K or not. If found to be true, then increment the count. Finally, print the count." }, { "code": null, "e": 27810, "s": 27762, "text": "Time Complexity: O(N * 2N)Auxiliary Space: O(N)" }, { "code": null, "e": 27953, "s": 27810, "text": "Efficient Approach: To optimize the above approach the idea is to use Dynamic programming. Below is the recurrence relation and the base case:" }, { "code": null, "e": 28224, "s": 27953, "text": "Recurrence Relation: cntSubDivK(N, rem) = cntSubDivK(N – 1, (rem * arr[N – 1]) % K) + cntSubDivK(N – 1, rem). cntSubDivK(N, rem) store the count of subset having product divisible by K. rem: Store the remainder when K divides the product of all elements of the subset. " }, { "code": null, "e": 28311, "s": 28224, "text": "Base Case: if N == 0 and rem == 0 then return 1. If N == 0 and rem != 0 then return 0." }, { "code": null, "e": 28356, "s": 28311, "text": "Follow the steps below to solve the problem:" }, { "code": null, "e": 28479, "s": 28356, "text": "Initialize a 2D array, say dp[N][rem] to compute and store the values of all subproblems of the above recurrence relation." }, { "code": null, "e": 28520, "s": 28479, "text": "Finally, return the value of dp[N][rem]." }, { "code": null, "e": 28571, "s": 28520, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 28575, "s": 28571, "text": "C++" }, { "code": null, "e": 28580, "s": 28575, "text": "Java" }, { "code": null, "e": 28588, "s": 28580, "text": "Python3" }, { "code": null, "e": 28591, "s": 28588, "text": "C#" }, { "code": null, "e": 28602, "s": 28591, "text": "Javascript" }, { "code": "// C++ program to implement// the above approach #include <bits/stdc++.h>using namespace std; // Function to count the subsets whose// product of elements is divisible by Kint cntSubDivK(int arr[], int N, int K, int rem, vector<vector<int> >& dp){ // If count of elements // in the array is 0 if (N == 0) { // If rem is 0, then return 1 // Otherwise, return 0 return rem == 0; } // If already computed // subproblem occurred if (dp[N][rem] != -1) { return dp[N][rem]; } // Stores count of subsets having product // divisible by K when arr[N - 1] // present in the subset int X = cntSubDivK(arr, N - 1, K, (rem * arr[N - 1]) % K, dp); // Stores count of subsets having product // divisible by K when arr[N - 1] not // present in the subset int Y = cntSubDivK(arr, N - 1, K, rem, dp); // Return total subset return X + Y;} // Utility Function to count the subsets whose// product of elements is divisible by Kint UtilCntSubDivK(int arr[], int N, int K){ // Initialize a 2D array to store values // of overlapping subproblems vector<vector<int> > dp(N + 1, vector<int>(K + 1, -1)); return cntSubDivK(arr, N, K, 1, dp);} // Driver Codeint main(){ int arr[] = { 1, 2, 3, 4, 5, 6 }; int K = 60; int N = sizeof(arr) / sizeof(arr[0]); cout << UtilCntSubDivK(arr, N, K);}", "e": 30063, "s": 28602, "text": null }, { "code": "// Java program to implement// the above approachimport java.util.*; class GFG{ // Function to count the subsets whose// product of elements is divisible by Kstatic int cntSubDivK(int arr[], int N, int K, int rem, int[][]dp){ // If count of elements // in the array is 0 if (N == 0) { // If rem is 0, then return 1 // Otherwise, return 0 return rem == 0 ? 1 : 0; } // If already computed // subproblem occurred if (dp[N][rem] != -1) { return dp[N][rem]; } // Stores count of subsets having product // divisible by K when arr[N - 1] // present in the subset int X = cntSubDivK(arr, N - 1, K, (rem * arr[N - 1]) % K, dp); // Stores count of subsets having product // divisible by K when arr[N - 1] not // present in the subset int Y = cntSubDivK(arr, N - 1, K, rem, dp); // Return total subset return X + Y;} // Utility Function to count the subsets whose// product of elements is divisible by Kstatic int UtilCntSubDivK(int arr[], int N, int K){ // Initialize a 2D array to store values // of overlapping subproblems int [][]dp = new int[N + 1][K + 1]; for(int i = 0; i < N + 1; i++) { for(int j = 0; j < K + 1; j++) dp[i][j] = -1; } return cntSubDivK(arr, N, K, 1, dp);} // Driver Codepublic static void main(String args[]){ int arr[] = { 1, 2, 3, 4, 5, 6 }; int K = 60; int N = arr.length; System.out.println(UtilCntSubDivK(arr, N, K));}} // This code is contributed by SURENDRA_GANGWAR", "e": 31690, "s": 30063, "text": null }, { "code": "# Python3 program to# implement the above# approach # Function to count the# subsets whose product# of elements is divisible# by Kdef cntSubDivK(arr, N, K, rem, dp): # If count of elements # in the array is 0 if (N == 0): # If rem is 0, then # return 1 Otherwise, # return 0 return rem == 0 # If already computed # subproblem occurred if (dp[N][rem] != -1): return dp[N][rem] # Stores count of subsets # having product divisible # by K when arr[N - 1] # present in the subset X = cntSubDivK(arr, N - 1, K, (rem * arr[N - 1]) % K, dp) # Stores count of subsets having # product divisible by K when # arr[N - 1] not present in # the subset Y = cntSubDivK(arr, N - 1, K, rem, dp) # Return total subset return X + Y # Utility Function to count# the subsets whose product of# elements is divisible by Kdef UtilCntSubDivK(arr, N, K): # Initialize a 2D array to # store values of overlapping # subproblems dp = [[-1 for x in range(K + 1)] for y in range(N + 1)] return cntSubDivK(arr, N, K, 1, dp) # Driver Codeif __name__ == \"__main__\": arr = [1, 2, 3, 4, 5, 6] K = 60 N = len(arr) print(UtilCntSubDivK(arr, N, K)) # This code is contributed by Chitranayal", "e": 33062, "s": 31690, "text": null }, { "code": "// C# program to implement// the above approachusing System; class GFG{ // Function to count the subsets whose// product of elements is divisible by Kstatic int cntSubDivK(int[] arr, int N, int K, int rem, int[,] dp){ // If count of elements // in the array is 0 if (N == 0) { // If rem is 0, then return 1 // Otherwise, return 0 return rem == 0 ? 1 : 0; } // If already computed // subproblem occurred if (dp[N, rem] != -1) { return dp[N, rem]; } // Stores count of subsets having product // divisible by K when arr[N - 1] // present in the subset int X = cntSubDivK(arr, N - 1, K, (rem * arr[N - 1]) % K, dp); // Stores count of subsets having product // divisible by K when arr[N - 1] not // present in the subset int Y = cntSubDivK(arr, N - 1, K, rem, dp); // Return total subset return X + Y;} // Utility Function to count the subsets whose// product of elements is divisible by Kstatic int UtilCntSubDivK(int[] arr, int N, int K){ // Initialize a 2D array to store values // of overlapping subproblems int[,] dp = new int[N + 1, K + 1]; for(int i = 0; i < N + 1; i++) { for(int j = 0; j < K + 1; j++) dp[i, j] = -1; } return cntSubDivK(arr, N, K, 1, dp);} // Driver codestatic void Main(){ int[] arr = { 1, 2, 3, 4, 5, 6 }; int K = 60; int N = arr.Length; Console.WriteLine(UtilCntSubDivK(arr, N, K));}} // This code is contributed by divyeshrabadiya07", "e": 34709, "s": 33062, "text": null }, { "code": "<script> // JavaScript program to implement// the above approach // Function to count the subsets whose// product of elements is divisible by Kfunction cntSubDivK(arr, N, K, rem, dp){ // If count of elements // in the array is 0 if (N == 0) { // If rem is 0, then return 1 // Otherwise, return 0 return rem == 0 ? 1 : 0; } // If already computed // subproblem occurred if (dp[N][rem] != -1) { return dp[N][rem]; } // Stores count of subsets having product // divisible by K when arr[N - 1] // present in the subset let X = cntSubDivK(arr, N - 1, K, (rem * arr[N - 1]) % K, dp); // Stores count of subsets having product // divisible by K when arr[N - 1] not // present in the subset let Y = cntSubDivK(arr, N - 1, K, rem, dp); // Return total subset return X + Y;} // Utility Function to count the subsets whose// product of elements is divisible by Kfunction UtilCntSubDivK(arr, N, K){ // Initialize a 2D array to store values // of overlapping subproblems let dp = new Array(N + 1); // Loop to create 2D array using 1D array for(var i = 0; i < dp.length; i++) { dp[i] = new Array(2); } for(let i = 0; i < N + 1; i++) { for(let j = 0; j < K + 1; j++) dp[i][j] = -1; } return cntSubDivK(arr, N, K, 1, dp);} // Driver Codelet arr = [ 1, 2, 3, 4, 5, 6 ];let K = 60;let N = arr.length; document.write(UtilCntSubDivK(arr, N, K)); // This code is contribute by target_2 </script>", "e": 36312, "s": 34709, "text": null }, { "code": null, "e": 36315, "s": 36312, "text": "16" }, { "code": null, "e": 36369, "s": 36317, "text": "Time Complexity: O(N * K)Space Complexity: O(N * K)" }, { "code": null, "e": 36375, "s": 36369, "text": "ukasp" }, { "code": null, "e": 36392, "s": 36375, "text": "SURENDRA_GANGWAR" }, { "code": null, "e": 36410, "s": 36392, "text": "divyeshrabadiya07" }, { "code": null, "e": 36419, "s": 36410, "text": "target_2" }, { "code": null, "e": 36432, "s": 36419, "text": "divisibility" }, { "code": null, "e": 36439, "s": 36432, "text": "subset" }, { "code": null, "e": 36446, "s": 36439, "text": "Arrays" }, { "code": null, "e": 36459, "s": 36446, "text": "Backtracking" }, { "code": null, "e": 36472, "s": 36459, "text": "Mathematical" }, { "code": null, "e": 36479, "s": 36472, "text": "Arrays" }, { "code": null, "e": 36492, "s": 36479, "text": "Mathematical" }, { "code": null, "e": 36499, "s": 36492, "text": "subset" }, { "code": null, "e": 36512, "s": 36499, "text": "Backtracking" }, { "code": null, "e": 36610, "s": 36512, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36678, "s": 36610, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 36722, "s": 36678, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 36745, "s": 36722, "text": "Introduction to Arrays" }, { "code": null, "e": 36777, "s": 36745, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 36791, "s": 36777, "text": "Linear Search" }, { "code": null, "e": 36824, "s": 36791, "text": "N Queen Problem | Backtracking-3" }, { "code": null, "e": 36884, "s": 36824, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 36969, "s": 36884, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 36997, "s": 36969, "text": "Backtracking | Introduction" } ]
Program to convert binary search tree to a singly linked list in C++?
Suppose we have a binary tree; we have to convert this into a singly linked list (in place). So, if the input is like then the output will be To solve this, we will follow these steps: ser prev := null ser prev := null Define a recursive function solve(), that will take root as input. Define a recursive function solve(), that will take root as input. if root is null, then return if root is null, then return solve(right of root) solve(right of root) solve(left of root) solve(left of root) right of root := prev, left of root := null right of root := prev, left of root := null prev := root prev := root Let us see the following implementation to get better understanding: Live Demo #include <bits/stdc++.h> using namespace std; class TreeNode{ public: int val; TreeNode *left, *right; TreeNode(int data){ val = data; left = NULL; right = NULL; } }; void insert(TreeNode **root, int val){ queue<TreeNode*> q; q.push(*root); while(q.size()){ TreeNode *temp = q.front(); q.pop(); if(!temp->left){ if(val != NULL) temp->left = new TreeNode(val); else temp->left = new TreeNode(0); return; }else{ q.push(temp->left); } if(!temp->right){ if(val != NULL) temp->right = new TreeNode(val); else temp->right = new TreeNode(0); return; }else{ q.push(temp->right); } } } TreeNode *make_tree(vector<int> v){ TreeNode *root = new TreeNode(v[0]); for(int i = 1; i<v.size(); i++){ insert(&root, v[i]); } return root; } class Solution { public: TreeNode* prev = NULL; void flatten(TreeNode* root) { if(!root) return; flatten(root->right); flatten(root->left); root->right = prev; root->left = NULL; prev = root; } }; main(){ vector<int> v = {1,2,5,3,4}; TreeNode *root = make_tree(v); Solution ob; (ob.flatten(root)); TreeNode *ptr = root; while(ptr != NULL && ptr->val != 0){ cout << ptr->val << ", "; ptr = ptr->right; } } {1,2,5,3,4} 1, 2, 3, 4, 5,
[ { "code": null, "e": 1155, "s": 1062, "text": "Suppose we have a binary tree; we have to convert this into a singly linked list (in place)." }, { "code": null, "e": 1180, "s": 1155, "text": "So, if the input is like" }, { "code": null, "e": 1204, "s": 1180, "text": "then the output will be" }, { "code": null, "e": 1247, "s": 1204, "text": "To solve this, we will follow these steps:" }, { "code": null, "e": 1264, "s": 1247, "text": "ser prev := null" }, { "code": null, "e": 1281, "s": 1264, "text": "ser prev := null" }, { "code": null, "e": 1348, "s": 1281, "text": "Define a recursive function solve(), that will take root as input." }, { "code": null, "e": 1415, "s": 1348, "text": "Define a recursive function solve(), that will take root as input." }, { "code": null, "e": 1444, "s": 1415, "text": "if root is null, then return" }, { "code": null, "e": 1473, "s": 1444, "text": "if root is null, then return" }, { "code": null, "e": 1494, "s": 1473, "text": "solve(right of root)" }, { "code": null, "e": 1515, "s": 1494, "text": "solve(right of root)" }, { "code": null, "e": 1535, "s": 1515, "text": "solve(left of root)" }, { "code": null, "e": 1555, "s": 1535, "text": "solve(left of root)" }, { "code": null, "e": 1599, "s": 1555, "text": "right of root := prev, left of root := null" }, { "code": null, "e": 1643, "s": 1599, "text": "right of root := prev, left of root := null" }, { "code": null, "e": 1656, "s": 1643, "text": "prev := root" }, { "code": null, "e": 1669, "s": 1656, "text": "prev := root" }, { "code": null, "e": 1738, "s": 1669, "text": "Let us see the following implementation to get better understanding:" }, { "code": null, "e": 1749, "s": 1738, "text": " Live Demo" }, { "code": null, "e": 3193, "s": 1749, "text": "#include <bits/stdc++.h>\nusing namespace std;\nclass TreeNode{\n public:\n int val;\n TreeNode *left, *right;\n TreeNode(int data){\n val = data;\n left = NULL;\n right = NULL;\n }\n};\nvoid insert(TreeNode **root, int val){\n queue<TreeNode*> q;\n q.push(*root);\n while(q.size()){\n TreeNode *temp = q.front();\n q.pop();\n if(!temp->left){\n if(val != NULL)\n temp->left = new TreeNode(val);\n else\n temp->left = new TreeNode(0);\n return;\n }else{\n q.push(temp->left);\n }\n if(!temp->right){\n if(val != NULL)\n temp->right = new TreeNode(val);\n else\n temp->right = new TreeNode(0);\n return;\n }else{\n q.push(temp->right);\n }\n }\n}\nTreeNode *make_tree(vector<int> v){\n TreeNode *root = new TreeNode(v[0]);\n for(int i = 1; i<v.size(); i++){\n insert(&root, v[i]);\n }\n return root;\n}\nclass Solution {\n public:\n TreeNode* prev = NULL;\n void flatten(TreeNode* root) {\n if(!root) return;\n flatten(root->right);\n flatten(root->left);\n root->right = prev;\n root->left = NULL;\n prev = root;\n }\n};\nmain(){\n vector<int> v = {1,2,5,3,4};\n TreeNode *root = make_tree(v);\n Solution ob;\n (ob.flatten(root));\n TreeNode *ptr = root;\n while(ptr != NULL && ptr->val != 0){\n cout << ptr->val << \", \";\n ptr = ptr->right;\n }\n}" }, { "code": null, "e": 3205, "s": 3193, "text": "{1,2,5,3,4}" }, { "code": null, "e": 3220, "s": 3205, "text": "1, 2, 3, 4, 5," } ]
Count All Palindromic Subsequence in a given String - GeeksforGeeks
04 Mar, 2022 Find how many palindromic subsequences (need not necessarily be distinct) can be formed in a given string. Note that the empty string is not considered as a palindrome. Examples: Input : str = "abcd" Output : 4 Explanation :- palindromic subsequence are : "a" ,"b", "c" ,"d" Input : str = "aab" Output : 4 Explanation :- palindromic subsequence are :"a", "a", "b", "aa" Input : str = "aaaa" Output : 15 The above problem can be recursively defined. Initial Values : i= 0, j= n-1; CountPS(i,j) // Every single character of a string is a palindrome // subsequence if i == j return 1 // palindrome of length 1 // If first and last characters are same, then we // consider it as palindrome subsequence and check // for the rest subsequence (i+1, j), (i, j-1) Else if (str[i] == str[j)] return countPS(i+1, j) + countPS(i, j-1) + 1; else // check for rest sub-sequence and remove common // palindromic subsequences as they are counted // twice when we do countPS(i+1, j) + countPS(i,j-1) return countPS(i+1, j) + countPS(i, j-1) - countPS(i+1, j-1) If we draw recursion tree of above recursive solution, we can observe overlapping Subproblems. Since the problem has overlapping subproblems, we can solve it efficiently using Dynamic Programming. Below is Dynamic Programming based solution. C++ Java Python3 C# PHP Javascript // Counts Palindromic Subsequence in a given String#include <cstring>#include <iostream>using namespace std; // Function return the total palindromic subsequenceint countPS(string str){ int N = str.length(); // create a 2D array to store the count of palindromic // subsequence int cps[N + 1][N + 1]; memset(cps, 0, sizeof(cps)); // palindromic subsequence of length 1 for (int i = 0; i < N; i++) cps[i][i] = 1; // check subsequence of length L is palindrome or not for (int L = 2; L <= N; L++) { for (int i = 0; i <= N-L; i++) { int k = L + i - 1; if (str[i] == str[k]) cps[i][k] = cps[i][k - 1] + cps[i + 1][k] + 1; else cps[i][k] = cps[i][k - 1] + cps[i + 1][k] - cps[i + 1][k - 1]; } } // return total palindromic subsequence return cps[0][N - 1];} // Driver programint main(){ string str = "abcb"; cout << "Total palindromic subsequence are : " << countPS(str) << endl; return 0;} // Java code to Count Palindromic Subsequence// in a given Stringpublic class GFG { // Function return the total palindromic // subsequence static int countPS(String str) { int N = str.length(); // create a 2D array to store the count // of palindromic subsequence int[][] cps = new int[N][N]; // palindromic subsequence of length 1 for (int i = 0; i < N; i++) cps[i][i] = 1; // check subsequence of length L is // palindrome or not for (int L = 2; L <= N; L++) { for (int i = 0; i <= N-L; i++) { int k = L + i - 1; if (str.charAt(i) == str.charAt(k)) { cps[i][k] = cps[i][k - 1] + cps[i + 1][k] + 1; }else{ cps[i][k] = cps[i][k - 1] + cps[i + 1][k] - cps[i + 1][k - 1]; } } } // return total palindromic subsequence return cps[0][N - 1]; } // Driver program public static void main(String args[]) { String str = "abcb"; System.out.println("Total palindromic " + "subsequence are : " + countPS(str)); }}// This code is contributed by Sumit Ghosh # Python3 code to Count Palindromic# Subsequence in a given String # Function return the total# palindromic subsequence def countPS(str): N = len(str) # Create a 2D array to store the count # of palindromic subsequence cps = [[0 for i in range(N + 2)]for j in range(N + 2)] # palindromic subsequence of length 1 for i in range(N): cps[i][i] = 1 # check subsequence of length L # is palindrome or not for L in range(2, N + 1): for i in range(N): k = L + i - 1 if (k < N): if (str[i] == str[k]): cps[i][k] = (cps[i][k - 1] + cps[i + 1][k] + 1) else: cps[i][k] = (cps[i][k - 1] + cps[i + 1][k] - cps[i + 1][k - 1]) # return total palindromic subsequence return cps[0][N - 1] # Driver programstr = "abcb"print("Total palindromic subsequence are : ", countPS(str)) # This code is contributed by Anant Agarwal. // C# code to Count Palindromic Subsequence// Subsequence in a given Stringusing System; class GFG { // Function return the total // palindromic subsequence static int countPS(string str) { int N = str.Length; // create a 2D array to store the // count of palindromic subsequence int[, ] cps = new int[N + 1, N + 1]; // palindromic subsequence // of length 1 for (int i = 0; i < N; i++) cps[i, i] = 1; // check subsequence of length // L is palindrome or not for (int L = 2; L <= N; L++) { for (int i = 0; i <= N-L; i++) { int k = L + i - 1; if (k < N) { if (str[i] == str[k]) cps[i, k] = cps[i, k - 1] + cps[i + 1, k] + 1; else cps[i, k] = cps[i, k - 1] + cps[i + 1, k] - cps[i + 1, k - 1]; } } } // return total palindromic // subsequence return cps[0, N - 1]; } // Driver Code public static void Main() { string str = "abcb"; Console.Write("Total palindromic " + "subsequence are : " + countPS(str)); }} // This code is contributed by nitin mittal. <?php// Counts Palindromic Subsequence in// a given String // Function return the total// palindromic subsequencefunction countPS($str){ $N = strlen($str); // create a 2D array to store the // count of palindromic subsequence $cps = array_fill(0, $N + 1, array_fill(0, $N + 1, NULL)); // palindromic subsequence of length 1 for ($i = 0; $i < $N; $i++) $cps[$i][$i] = 1; // check subsequence of length L // is palindrome or not for ($L = 2; $L <= $N; $L++) { for ($i = 0; $i <= $N-$L; $i++) { $k = $L + $i - 1; if ($str[$i] == $str[$k]) $cps[$i][$k] = $cps[$i][$k - 1] + $cps[$i + 1][$k] + 1; else $cps[$i][$k] = $cps[$i][$k - 1] + $cps[$i + 1][$k] - $cps[$i + 1][$k - 1]; } } // return total palindromic subsequence return $cps[0][$N - 1];} // Driver Code$str = "abcb";echo "Total palindromic subsequence are : " . countPS($str) . "\n"; // This code is contributed by ita_c?> <script> // Javascript code to Count Palindromic Subsequence// in a given String // Function return the total palindromic // subsequence function countPS(str) { let N = str.length; // create a 2D array to store the count // of palindromic subsequence let cps = new Array(N); for(let i=0;i<N;i++) { cps[i]=new Array(N); for(let j=0;j<N;j++) { cps[i][j]=0; } } // palindromic subsequence of length 1 for (let i = 0; i < N; i++) cps[i][i] = 1; // check subsequence of length L is // palindrome or not for (let L = 2; L <= N; L++) { for (let i = 0; i <= N-L; i++) { let k = L + i - 1; if (str[i] == str[k]) { cps[i][k] = cps[i][k - 1] + cps[i + 1][k] + 1; }else{ cps[i][k] = cps[i][k - 1] + cps[i + 1][k] - cps[i + 1][k - 1]; } } } // return total palindromic subsequence return cps[0][N - 1]; } // Driver program let str = "abcb"; document.write("Total palindromic " + "subsequence are : " + countPS(str)); // This code is contributed by avanitrachhadiya2155 </script> Output: Total palindromic subsequence are : 6 Time Complexity : O(N2) Another approach: (Using recursion) C++ Java Python 3 C# PHP Javascript // C++ program to counts Palindromic Subsequence// in a given String using recursion#include <bits/stdc++.h>using namespace std; int n, dp[1000][1000];string str = "abcb"; // Function return the total// palindromic subsequenceint countPS(int i, int j){ if (i > j) return 0; if (dp[i][j] != -1) return dp[i][j]; if (i == j) return dp[i][j] = 1; else if (str[i] == str[j]) return dp[i][j] = countPS(i + 1, j) + countPS(i, j - 1) + 1; else return dp[i][j] = countPS(i + 1, j) + countPS(i, j - 1) - countPS(i + 1, j - 1);} // Driver codeint main(){ memset(dp, -1, sizeof(dp)); n = str.size(); cout << "Total palindromic subsequence are : " << countPS(0, n - 1) << endl; return 0;}// this code is contributed by Kushdeep Mittal // Java program to counts Palindromic Subsequence// in a given String using recursion class GFG { static int n; static int[][] dp = new int[1000][1000]; static String str = "abcb"; // Function return the total // palindromic subsequence static int countPS(int i, int j) { if (i > j) return 0; if (dp[i][j] != -1) return dp[i][j]; if (i == j) return dp[i][j] = 1; else if (str.charAt(i) == str.charAt(j)) return dp[i][j] = countPS(i + 1, j) + countPS(i, j - 1) + 1; else return dp[i][j] = countPS(i + 1, j) + countPS(i, j - 1) - countPS(i + 1, j - 1); } // Driver code public static void main(String[] args) { for (int i = 0; i < 1000; i++) for (int j = 0; j < 1000; j++) dp[i][j] = -1; n = str.length(); System.out.println("Total palindromic subsequence" + "are : " + countPS(0, n - 1)); }} // This code is contributed by Ryuga # Python 3 program to counts Palindromic# Subsequence in a given String using recursion str = "abcb" # Function return the total# palindromic subsequence def countPS(i, j): if(i > j): return 0 if(dp[i][j] != -1): return dp[i][j] if(i == j): dp[i][j] = 1 return dp[i][j] else if (str[i] == str[j]): dp[i][j] = (countPS(i + 1, j) + countPS(i, j - 1) + 1) return dp[i][j] else: dp[i][j] = (countPS(i + 1, j) + countPS(i, j - 1) - countPS(i + 1, j - 1)) return dp[i][j] # Driver codeif __name__ == "__main__": dp = [[-1 for x in range(1000)] for y in range(1000)] n = len(str) print("Total palindromic subsequence are :", countPS(0, n - 1)) # This code is contributed by ita_c // C# program to counts Palindromic Subsequence// in a given String using recursionusing System; class GFG { static int n; static int[, ] dp = new int[1000, 1000]; static string str = "abcb"; // Function return the total // palindromic subsequence static int countPS(int i, int j) { if (i > j) return 0; if (dp[i, j] != -1) return dp[i, j]; if (i == j) return dp[i, j] = 1; else if (str[i] == str[j]) return dp[i, j] = countPS(i + 1, j) + countPS(i, j - 1) + 1; else return dp[i, j] = countPS(i + 1, j) + countPS(i, j - 1) - countPS(i + 1, j - 1); } // Driver code static void Main() { for (int i = 0; i < 1000; i++) for (int j = 0; j < 1000; j++) dp[i, j] = -1; n = str.Length; Console.Write("Total palindromic subsequence" + "are : " + countPS(0, n - 1)); }} // This code is contributed by DrRoot_ <?php// PHP program to counts Palindromic Subsequence// in a given String using recursion$dp = array_fill(0, 100, array_fill(0, 1000, -1)); $str = "abcb";$n = strlen($str); // Function return the total// palindromic subsequencefunction countPS($i, $j){ global $str, $dp, $n; if($i > $j) return 0; if($dp[$i][$j] != -1) return $dp[$i][$j]; if($i == $j) return $dp[$i][$j] = 1; else if ($str[$i] == $str[$j]) return $dp[$i][$j] = countPS($i + 1, $j) + countPS($i, $j - 1) + 1; else return $dp[$i][$j] = countPS($i + 1, $j) + countPS($i, $j - 1) - countPS($i + 1, $j - 1);} // Driver codeecho "Total palindromic subsequence are : " . countPS(0, $n - 1); // This code is contributed by mits?> <script>// Javascript program to counts Palindromic Subsequence// in a given String using recursion let n; let dp=new Array(1000); for(let i=0;i<1000;i++) { dp[i]=new Array(1000); for(let j=0;j<1000;j++) { dp[i][j]=-1; } } let str = "abcb"; // Function return the total // palindromic subsequence function countPS(i,j) { if (i > j) return 0; if (dp[i][j] != -1) return dp[i][j]; if (i == j) return dp[i][j] = 1; else if (str[i] == str[j]) return dp[i][j] = countPS(i + 1, j) + countPS(i, j - 1) + 1; else return dp[i][j] = countPS(i + 1, j) + countPS(i, j - 1) - countPS(i + 1, j - 1); } // Driver code n = str.length; document.write("Total palindromic subsequence" + "are : " + countPS(0, n - 1)); // This code is contributed by rag2127 </script> Output: Total palindromic subsequence are : 6 This article is contributed by Nishant_sing(pintu). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. nitin mittal Kushdeep_Mittal ukasp DrRoot_ ankthon Mithun Kumar Ankur Goel parasmadan15 ralph0609 VishalSingh58 akscodebay avanitrachhadiya2155 rag2127 surinderdawra388 palindrome subsequence Dynamic Programming Dynamic Programming palindrome Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Bellman–Ford Algorithm | DP-23 Floyd Warshall Algorithm | DP-16 Subset Sum Problem | DP-25 Matrix Chain Multiplication | DP-8 Coin Change | DP-7 Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming) Edit Distance | DP-5 Sieve of Eratosthenes Overlapping Subproblems Property in Dynamic Programming | DP-1 Find minimum number of coins that make a given value
[ { "code": null, "e": 26107, "s": 26079, "text": "\n04 Mar, 2022" }, { "code": null, "e": 26287, "s": 26107, "text": "Find how many palindromic subsequences (need not necessarily be distinct) can be formed in a given string. Note that the empty string is not considered as a palindrome. Examples: " }, { "code": null, "e": 26515, "s": 26287, "text": "Input : str = \"abcd\"\nOutput : 4\nExplanation :- palindromic subsequence are : \"a\" ,\"b\", \"c\" ,\"d\" \n\nInput : str = \"aab\"\nOutput : 4\nExplanation :- palindromic subsequence are :\"a\", \"a\", \"b\", \"aa\"\n\nInput : str = \"aaaa\"\nOutput : 15" }, { "code": null, "e": 26562, "s": 26515, "text": "The above problem can be recursively defined. " }, { "code": null, "e": 27184, "s": 26562, "text": "Initial Values : i= 0, j= n-1;\n\nCountPS(i,j)\n// Every single character of a string is a palindrome \n// subsequence \nif i == j\n return 1 // palindrome of length 1\n\n// If first and last characters are same, then we \n// consider it as palindrome subsequence and check\n// for the rest subsequence (i+1, j), (i, j-1)\nElse if (str[i] == str[j)]\n return countPS(i+1, j) + countPS(i, j-1) + 1;\n\nelse\n // check for rest sub-sequence and remove common\n // palindromic subsequences as they are counted\n // twice when we do countPS(i+1, j) + countPS(i,j-1)\n return countPS(i+1, j) + countPS(i, j-1) - countPS(i+1, j-1)" }, { "code": null, "e": 27427, "s": 27184, "text": "If we draw recursion tree of above recursive solution, we can observe overlapping Subproblems. Since the problem has overlapping subproblems, we can solve it efficiently using Dynamic Programming. Below is Dynamic Programming based solution. " }, { "code": null, "e": 27431, "s": 27427, "text": "C++" }, { "code": null, "e": 27436, "s": 27431, "text": "Java" }, { "code": null, "e": 27444, "s": 27436, "text": "Python3" }, { "code": null, "e": 27447, "s": 27444, "text": "C#" }, { "code": null, "e": 27451, "s": 27447, "text": "PHP" }, { "code": null, "e": 27462, "s": 27451, "text": "Javascript" }, { "code": "// Counts Palindromic Subsequence in a given String#include <cstring>#include <iostream>using namespace std; // Function return the total palindromic subsequenceint countPS(string str){ int N = str.length(); // create a 2D array to store the count of palindromic // subsequence int cps[N + 1][N + 1]; memset(cps, 0, sizeof(cps)); // palindromic subsequence of length 1 for (int i = 0; i < N; i++) cps[i][i] = 1; // check subsequence of length L is palindrome or not for (int L = 2; L <= N; L++) { for (int i = 0; i <= N-L; i++) { int k = L + i - 1; if (str[i] == str[k]) cps[i][k] = cps[i][k - 1] + cps[i + 1][k] + 1; else cps[i][k] = cps[i][k - 1] + cps[i + 1][k] - cps[i + 1][k - 1]; } } // return total palindromic subsequence return cps[0][N - 1];} // Driver programint main(){ string str = \"abcb\"; cout << \"Total palindromic subsequence are : \" << countPS(str) << endl; return 0;}", "e": 28535, "s": 27462, "text": null }, { "code": "// Java code to Count Palindromic Subsequence// in a given Stringpublic class GFG { // Function return the total palindromic // subsequence static int countPS(String str) { int N = str.length(); // create a 2D array to store the count // of palindromic subsequence int[][] cps = new int[N][N]; // palindromic subsequence of length 1 for (int i = 0; i < N; i++) cps[i][i] = 1; // check subsequence of length L is // palindrome or not for (int L = 2; L <= N; L++) { for (int i = 0; i <= N-L; i++) { int k = L + i - 1; if (str.charAt(i) == str.charAt(k)) { cps[i][k] = cps[i][k - 1] + cps[i + 1][k] + 1; }else{ cps[i][k] = cps[i][k - 1] + cps[i + 1][k] - cps[i + 1][k - 1]; } } } // return total palindromic subsequence return cps[0][N - 1]; } // Driver program public static void main(String args[]) { String str = \"abcb\"; System.out.println(\"Total palindromic \" + \"subsequence are : \" + countPS(str)); }}// This code is contributed by Sumit Ghosh", "e": 29885, "s": 28535, "text": null }, { "code": "# Python3 code to Count Palindromic# Subsequence in a given String # Function return the total# palindromic subsequence def countPS(str): N = len(str) # Create a 2D array to store the count # of palindromic subsequence cps = [[0 for i in range(N + 2)]for j in range(N + 2)] # palindromic subsequence of length 1 for i in range(N): cps[i][i] = 1 # check subsequence of length L # is palindrome or not for L in range(2, N + 1): for i in range(N): k = L + i - 1 if (k < N): if (str[i] == str[k]): cps[i][k] = (cps[i][k - 1] + cps[i + 1][k] + 1) else: cps[i][k] = (cps[i][k - 1] + cps[i + 1][k] - cps[i + 1][k - 1]) # return total palindromic subsequence return cps[0][N - 1] # Driver programstr = \"abcb\"print(\"Total palindromic subsequence are : \", countPS(str)) # This code is contributed by Anant Agarwal.", "e": 30932, "s": 29885, "text": null }, { "code": "// C# code to Count Palindromic Subsequence// Subsequence in a given Stringusing System; class GFG { // Function return the total // palindromic subsequence static int countPS(string str) { int N = str.Length; // create a 2D array to store the // count of palindromic subsequence int[, ] cps = new int[N + 1, N + 1]; // palindromic subsequence // of length 1 for (int i = 0; i < N; i++) cps[i, i] = 1; // check subsequence of length // L is palindrome or not for (int L = 2; L <= N; L++) { for (int i = 0; i <= N-L; i++) { int k = L + i - 1; if (k < N) { if (str[i] == str[k]) cps[i, k] = cps[i, k - 1] + cps[i + 1, k] + 1; else cps[i, k] = cps[i, k - 1] + cps[i + 1, k] - cps[i + 1, k - 1]; } } } // return total palindromic // subsequence return cps[0, N - 1]; } // Driver Code public static void Main() { string str = \"abcb\"; Console.Write(\"Total palindromic \" + \"subsequence are : \" + countPS(str)); }} // This code is contributed by nitin mittal.", "e": 32338, "s": 30932, "text": null }, { "code": "<?php// Counts Palindromic Subsequence in// a given String // Function return the total// palindromic subsequencefunction countPS($str){ $N = strlen($str); // create a 2D array to store the // count of palindromic subsequence $cps = array_fill(0, $N + 1, array_fill(0, $N + 1, NULL)); // palindromic subsequence of length 1 for ($i = 0; $i < $N; $i++) $cps[$i][$i] = 1; // check subsequence of length L // is palindrome or not for ($L = 2; $L <= $N; $L++) { for ($i = 0; $i <= $N-$L; $i++) { $k = $L + $i - 1; if ($str[$i] == $str[$k]) $cps[$i][$k] = $cps[$i][$k - 1] + $cps[$i + 1][$k] + 1; else $cps[$i][$k] = $cps[$i][$k - 1] + $cps[$i + 1][$k] - $cps[$i + 1][$k - 1]; } } // return total palindromic subsequence return $cps[0][$N - 1];} // Driver Code$str = \"abcb\";echo \"Total palindromic subsequence are : \" . countPS($str) . \"\\n\"; // This code is contributed by ita_c?>", "e": 33471, "s": 32338, "text": null }, { "code": "<script> // Javascript code to Count Palindromic Subsequence// in a given String // Function return the total palindromic // subsequence function countPS(str) { let N = str.length; // create a 2D array to store the count // of palindromic subsequence let cps = new Array(N); for(let i=0;i<N;i++) { cps[i]=new Array(N); for(let j=0;j<N;j++) { cps[i][j]=0; } } // palindromic subsequence of length 1 for (let i = 0; i < N; i++) cps[i][i] = 1; // check subsequence of length L is // palindrome or not for (let L = 2; L <= N; L++) { for (let i = 0; i <= N-L; i++) { let k = L + i - 1; if (str[i] == str[k]) { cps[i][k] = cps[i][k - 1] + cps[i + 1][k] + 1; }else{ cps[i][k] = cps[i][k - 1] + cps[i + 1][k] - cps[i + 1][k - 1]; } } } // return total palindromic subsequence return cps[0][N - 1]; } // Driver program let str = \"abcb\"; document.write(\"Total palindromic \" + \"subsequence are : \" + countPS(str)); // This code is contributed by avanitrachhadiya2155 </script>", "e": 34929, "s": 33471, "text": null }, { "code": null, "e": 34938, "s": 34929, "text": "Output: " }, { "code": null, "e": 34976, "s": 34938, "text": "Total palindromic subsequence are : 6" }, { "code": null, "e": 35000, "s": 34976, "text": "Time Complexity : O(N2)" }, { "code": null, "e": 35037, "s": 35000, "text": "Another approach: (Using recursion) " }, { "code": null, "e": 35041, "s": 35037, "text": "C++" }, { "code": null, "e": 35046, "s": 35041, "text": "Java" }, { "code": null, "e": 35055, "s": 35046, "text": "Python 3" }, { "code": null, "e": 35058, "s": 35055, "text": "C#" }, { "code": null, "e": 35062, "s": 35058, "text": "PHP" }, { "code": null, "e": 35073, "s": 35062, "text": "Javascript" }, { "code": "// C++ program to counts Palindromic Subsequence// in a given String using recursion#include <bits/stdc++.h>using namespace std; int n, dp[1000][1000];string str = \"abcb\"; // Function return the total// palindromic subsequenceint countPS(int i, int j){ if (i > j) return 0; if (dp[i][j] != -1) return dp[i][j]; if (i == j) return dp[i][j] = 1; else if (str[i] == str[j]) return dp[i][j] = countPS(i + 1, j) + countPS(i, j - 1) + 1; else return dp[i][j] = countPS(i + 1, j) + countPS(i, j - 1) - countPS(i + 1, j - 1);} // Driver codeint main(){ memset(dp, -1, sizeof(dp)); n = str.size(); cout << \"Total palindromic subsequence are : \" << countPS(0, n - 1) << endl; return 0;}// this code is contributed by Kushdeep Mittal", "e": 35950, "s": 35073, "text": null }, { "code": "// Java program to counts Palindromic Subsequence// in a given String using recursion class GFG { static int n; static int[][] dp = new int[1000][1000]; static String str = \"abcb\"; // Function return the total // palindromic subsequence static int countPS(int i, int j) { if (i > j) return 0; if (dp[i][j] != -1) return dp[i][j]; if (i == j) return dp[i][j] = 1; else if (str.charAt(i) == str.charAt(j)) return dp[i][j] = countPS(i + 1, j) + countPS(i, j - 1) + 1; else return dp[i][j] = countPS(i + 1, j) + countPS(i, j - 1) - countPS(i + 1, j - 1); } // Driver code public static void main(String[] args) { for (int i = 0; i < 1000; i++) for (int j = 0; j < 1000; j++) dp[i][j] = -1; n = str.length(); System.out.println(\"Total palindromic subsequence\" + \"are : \" + countPS(0, n - 1)); }} // This code is contributed by Ryuga", "e": 37082, "s": 35950, "text": null }, { "code": "# Python 3 program to counts Palindromic# Subsequence in a given String using recursion str = \"abcb\" # Function return the total# palindromic subsequence def countPS(i, j): if(i > j): return 0 if(dp[i][j] != -1): return dp[i][j] if(i == j): dp[i][j] = 1 return dp[i][j] else if (str[i] == str[j]): dp[i][j] = (countPS(i + 1, j) + countPS(i, j - 1) + 1) return dp[i][j] else: dp[i][j] = (countPS(i + 1, j) + countPS(i, j - 1) - countPS(i + 1, j - 1)) return dp[i][j] # Driver codeif __name__ == \"__main__\": dp = [[-1 for x in range(1000)] for y in range(1000)] n = len(str) print(\"Total palindromic subsequence are :\", countPS(0, n - 1)) # This code is contributed by ita_c", "e": 37918, "s": 37082, "text": null }, { "code": "// C# program to counts Palindromic Subsequence// in a given String using recursionusing System; class GFG { static int n; static int[, ] dp = new int[1000, 1000]; static string str = \"abcb\"; // Function return the total // palindromic subsequence static int countPS(int i, int j) { if (i > j) return 0; if (dp[i, j] != -1) return dp[i, j]; if (i == j) return dp[i, j] = 1; else if (str[i] == str[j]) return dp[i, j] = countPS(i + 1, j) + countPS(i, j - 1) + 1; else return dp[i, j] = countPS(i + 1, j) + countPS(i, j - 1) - countPS(i + 1, j - 1); } // Driver code static void Main() { for (int i = 0; i < 1000; i++) for (int j = 0; j < 1000; j++) dp[i, j] = -1; n = str.Length; Console.Write(\"Total palindromic subsequence\" + \"are : \" + countPS(0, n - 1)); }} // This code is contributed by DrRoot_", "e": 39009, "s": 37918, "text": null }, { "code": "<?php// PHP program to counts Palindromic Subsequence// in a given String using recursion$dp = array_fill(0, 100, array_fill(0, 1000, -1)); $str = \"abcb\";$n = strlen($str); // Function return the total// palindromic subsequencefunction countPS($i, $j){ global $str, $dp, $n; if($i > $j) return 0; if($dp[$i][$j] != -1) return $dp[$i][$j]; if($i == $j) return $dp[$i][$j] = 1; else if ($str[$i] == $str[$j]) return $dp[$i][$j] = countPS($i + 1, $j) + countPS($i, $j - 1) + 1; else return $dp[$i][$j] = countPS($i + 1, $j) + countPS($i, $j - 1) - countPS($i + 1, $j - 1);} // Driver codeecho \"Total palindromic subsequence are : \" . countPS(0, $n - 1); // This code is contributed by mits?>", "e": 39898, "s": 39009, "text": null }, { "code": "<script>// Javascript program to counts Palindromic Subsequence// in a given String using recursion let n; let dp=new Array(1000); for(let i=0;i<1000;i++) { dp[i]=new Array(1000); for(let j=0;j<1000;j++) { dp[i][j]=-1; } } let str = \"abcb\"; // Function return the total // palindromic subsequence function countPS(i,j) { if (i > j) return 0; if (dp[i][j] != -1) return dp[i][j]; if (i == j) return dp[i][j] = 1; else if (str[i] == str[j]) return dp[i][j] = countPS(i + 1, j) + countPS(i, j - 1) + 1; else return dp[i][j] = countPS(i + 1, j) + countPS(i, j - 1) - countPS(i + 1, j - 1); } // Driver code n = str.length; document.write(\"Total palindromic subsequence\" + \"are : \" + countPS(0, n - 1)); // This code is contributed by rag2127 </script>", "e": 40983, "s": 39898, "text": null }, { "code": null, "e": 40992, "s": 40983, "text": "Output: " }, { "code": null, "e": 41030, "s": 40992, "text": "Total palindromic subsequence are : 6" }, { "code": null, "e": 41457, "s": 41030, "text": "This article is contributed by Nishant_sing(pintu). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 41470, "s": 41457, "text": "nitin mittal" }, { "code": null, "e": 41486, "s": 41470, "text": "Kushdeep_Mittal" }, { "code": null, "e": 41492, "s": 41486, "text": "ukasp" }, { "code": null, "e": 41500, "s": 41492, "text": "DrRoot_" }, { "code": null, "e": 41508, "s": 41500, "text": "ankthon" }, { "code": null, "e": 41521, "s": 41508, "text": "Mithun Kumar" }, { "code": null, "e": 41532, "s": 41521, "text": "Ankur Goel" }, { "code": null, "e": 41545, "s": 41532, "text": "parasmadan15" }, { "code": null, "e": 41555, "s": 41545, "text": "ralph0609" }, { "code": null, "e": 41569, "s": 41555, "text": "VishalSingh58" }, { "code": null, "e": 41580, "s": 41569, "text": "akscodebay" }, { "code": null, "e": 41601, "s": 41580, "text": "avanitrachhadiya2155" }, { "code": null, "e": 41609, "s": 41601, "text": "rag2127" }, { "code": null, "e": 41626, "s": 41609, "text": "surinderdawra388" }, { "code": null, "e": 41637, "s": 41626, "text": "palindrome" }, { "code": null, "e": 41649, "s": 41637, "text": "subsequence" }, { "code": null, "e": 41669, "s": 41649, "text": "Dynamic Programming" }, { "code": null, "e": 41689, "s": 41669, "text": "Dynamic Programming" }, { "code": null, "e": 41700, "s": 41689, "text": "palindrome" }, { "code": null, "e": 41798, "s": 41700, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 41829, "s": 41798, "text": "Bellman–Ford Algorithm | DP-23" }, { "code": null, "e": 41862, "s": 41829, "text": "Floyd Warshall Algorithm | DP-16" }, { "code": null, "e": 41889, "s": 41862, "text": "Subset Sum Problem | DP-25" }, { "code": null, "e": 41924, "s": 41889, "text": "Matrix Chain Multiplication | DP-8" }, { "code": null, "e": 41943, "s": 41924, "text": "Coin Change | DP-7" }, { "code": null, "e": 42011, "s": 41943, "text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)" }, { "code": null, "e": 42032, "s": 42011, "text": "Edit Distance | DP-5" }, { "code": null, "e": 42054, "s": 42032, "text": "Sieve of Eratosthenes" }, { "code": null, "e": 42117, "s": 42054, "text": "Overlapping Subproblems Property in Dynamic Programming | DP-1" } ]
Pre-increment and Post-increment in C/C++
Here we will see what is the pre-increment and post-increment in C or C++. The pre-increment and post-increment both are increment operators. But they have little differences. The pre-increment operator increments the value of a variable at first, then sends the assign it to some other variable, but in the case of postincrement, it at first assign to a variable, then increase the value. #include<iostream> using namespace std; main() { int x, y, z; x = 10; y = 10; z = ++x; //z will hold 11 cout << "Z: " << z << endl; z = y++; //z will hold 10, then y will be 11 cout << "Z: " << z << " and y is: " << y << endl; } Z: 11 Z: 10 and y is: 11 The precedence of post increment is more than precedence of pre increment, and their associativity is also different. The associativity of pre increment is right to left, of post increment is left to right.
[ { "code": null, "e": 1238, "s": 1062, "text": "Here we will see what is the pre-increment and post-increment in C or C++. The pre-increment and post-increment both are increment operators. But they have little differences." }, { "code": null, "e": 1452, "s": 1238, "text": "The pre-increment operator increments the value of a variable at first, then sends the assign it to some other variable, but in the case of postincrement, it at first assign to a variable, then increase the value." }, { "code": null, "e": 1702, "s": 1452, "text": "#include<iostream>\nusing namespace std;\nmain() {\n int x, y, z;\n x = 10;\n y = 10;\n z = ++x; //z will hold 11\n cout << \"Z: \" << z << endl;\n z = y++; //z will hold 10, then y will be 11\n cout << \"Z: \" << z << \" and y is: \" << y << endl;\n}" }, { "code": null, "e": 1727, "s": 1702, "text": "Z: 11\nZ: 10 and y is: 11" }, { "code": null, "e": 1934, "s": 1727, "text": "The precedence of post increment is more than precedence of pre increment, and their associativity is also different. The associativity of pre increment is right to left, of post increment is left to right." } ]
Check if a given graph is tree or not - GeeksforGeeks
24 Feb, 2022 Write a function that returns true if a given undirected graph is tree and false otherwise. For example, the following graph is a tree. But the following graph is not a tree. An undirected graph is tree if it has following properties. 1) There is no cycle. 2) The graph is connected.For an undirected graph we can either use BFS or DFS to detect above two properties.How to detect cycle in an undirected graph? We can either use BFS or DFS. For every visited vertex ‘v’, if there is an adjacent ‘u’ such that u is already visited and u is not parent of v, then there is a cycle in graph. If we don’t find such an adjacent for any vertex, we say that there is no cycle (See Detect cycle in an undirected graph for more details).How to check for connectivity? Since the graph is undirected, we can start BFS or DFS from any vertex and check if all vertices are reachable or not. If all vertices are reachable, then graph is connected, otherwise not. C++ Java Python3 C# Javascript // A C++ Program to check whether a graph is tree or not#include<iostream>#include <list>#include <limits.h>using namespace std; // Class for an undirected graphclass Graph{ int V; // No. of vertices list<int> *adj; // Pointer to an array for adjacency lists bool isCyclicUtil(int v, bool visited[], int parent);public: Graph(int V); // Constructor void addEdge(int v, int w); // to add an edge to graph bool isTree(); // returns true if graph is tree}; Graph::Graph(int V){ this->V = V; adj = new list<int>[V];} void Graph::addEdge(int v, int w){ adj[v].push_back(w); // Add w to v’s list. adj[w].push_back(v); // Add v to w’s list.} // A recursive function that uses visited[] and parent to// detect cycle in subgraph reachable from vertex v.bool Graph::isCyclicUtil(int v, bool visited[], int parent){ // Mark the current node as visited visited[v] = true; // Recur for all the vertices adjacent to this vertex list<int>::iterator i; for (i = adj[v].begin(); i != adj[v].end(); ++i) { // If an adjacent is not visited, then recur for // that adjacent if (!visited[*i]) { if (isCyclicUtil(*i, visited, v)) return true; } // If an adjacent is visited and not parent of current // vertex, then there is a cycle. else if (*i != parent) return true; } return false;} // Returns true if the graph is a tree, else false.bool Graph::isTree(){ // Mark all the vertices as not visited and not part of // recursion stack bool *visited = new bool[V]; for (int i = 0; i < V; i++) visited[i] = false; // The call to isCyclicUtil serves multiple purposes. // It returns true if graph reachable from vertex 0 // is cyclic. It also marks all vertices reachable // from 0. if (isCyclicUtil(0, visited, -1)) return false; // If we find a vertex which is not reachable from 0 // (not marked by isCyclicUtil(), then we return false for (int u = 0; u < V; u++) if (!visited[u]) return false; return true;} // Driver program to test above functionsint main(){ Graph g1(5); g1.addEdge(1, 0); g1.addEdge(0, 2); g1.addEdge(0, 3); g1.addEdge(3, 4); g1.isTree()? cout << "Graph is Tree\n": cout << "Graph is not Tree\n"; Graph g2(5); g2.addEdge(1, 0); g2.addEdge(0, 2); g2.addEdge(2, 1); g2.addEdge(0, 3); g2.addEdge(3, 4); g2.isTree()? cout << "Graph is Tree\n": cout << "Graph is not Tree\n"; return 0;} // A Java Program to check whether a graph is tree or notimport java.io.*;import java.util.*; // This class represents a directed graph using adjacency// list representationclass Graph{ private int V; // No. of vertices private LinkedList<Integer> adj[]; //Adjacency List // Constructor @SuppressWarnings("unchecked") Graph(int v) { V = v; adj = new LinkedList[V]; for (int i=0; i<v; ++i) adj[i] = new LinkedList<Integer>(); } // Function to add an edge into the graph void addEdge(int v,int w) { adj[v].add(w); adj[w].add(v); } // A recursive function that uses visited[] and parent // to detect cycle in subgraph reachable from vertex v. boolean isCyclicUtil(int v, boolean visited[], int parent) { // Mark the current node as visited visited[v] = true; Integer i; // Recur for all the vertices adjacent to this vertex Iterator<Integer> it = adj[v].iterator(); while (it.hasNext()) { i = it.next(); // If an adjacent is not visited, then recur for // that adjacent if (!visited[i]) { if (isCyclicUtil(i, visited, v)) return true; } // If an adjacent is visited and not parent of // current vertex, then there is a cycle. else if (i != parent) return true; } return false; } // Returns true if the graph is a tree, else false. boolean isTree() { // Mark all the vertices as not visited and not part // of recursion stack boolean visited[] = new boolean[V]; for (int i = 0; i < V; i++) visited[i] = false; // The call to isCyclicUtil serves multiple purposes // It returns true if graph reachable from vertex 0 // is cyclic. It also marks all vertices reachable // from 0. if (isCyclicUtil(0, visited, -1)) return false; // If we find a vertex which is not reachable from 0 // (not marked by isCyclicUtil(), then we return false for (int u = 0; u < V; u++) if (!visited[u]) return false; return true; } // Driver method public static void main(String args[]) { // Create a graph given in the above diagram Graph g1 = new Graph(5); g1.addEdge(1, 0); g1.addEdge(0, 2); g1.addEdge(0, 3); g1.addEdge(3, 4); if (g1.isTree()) System.out.println("Graph is Tree"); else System.out.println("Graph is not Tree"); Graph g2 = new Graph(5); g2.addEdge(1, 0); g2.addEdge(0, 2); g2.addEdge(2, 1); g2.addEdge(0, 3); g2.addEdge(3, 4); if (g2.isTree()) System.out.println("Graph is Tree"); else System.out.println("Graph is not Tree"); }}// This code is contributed by Aakash Hasija # Python Program to check whether# a graph is tree or not from collections import defaultdict class Graph(): def __init__(self, V): self.V = V self.graph = defaultdict(list) def addEdge(self, v, w): # Add w to v ist. self.graph[v].append(w) # Add v to w list. self.graph[w].append(v) # A recursive function that uses visited[] # and parent to detect cycle in subgraph # reachable from vertex v. def isCyclicUtil(self, v, visited, parent): # Mark current node as visited visited[v] = True # Recur for all the vertices adjacent # for this vertex for i in self.graph[v]: # If an adjacent is not visited, # then recur for that adjacent if visited[i] == False: if self.isCyclicUtil(i, visited, v) == True: return True # If an adjacent is visited and not # parent of current vertex, then there # is a cycle. elif i != parent: return True return False # Returns true if the graph is a tree, # else false. def isTree(self): # Mark all the vertices as not visited # and not part of recursion stack visited = [False] * self.V # The call to isCyclicUtil serves multiple # purposes. It returns true if graph reachable # from vertex 0 is cyclic. It also marks # all vertices reachable from 0. if self.isCyclicUtil(0, visited, -1) == True: return False # If we find a vertex which is not reachable # from 0 (not marked by isCyclicUtil(), # then we return false for i in range(self.V): if visited[i] == False: return False return True # Driver program to test above functionsg1 = Graph(5)g1.addEdge(1, 0)g1.addEdge(0, 2)g1.addEdge(0, 3)g1.addEdge(3, 4)print ("Graph is a Tree" if g1.isTree() == True \ else "Graph is a not a Tree") g2 = Graph(5)g2.addEdge(1, 0)g2.addEdge(0, 2)g2.addEdge(2, 1)g2.addEdge(0, 3)g2.addEdge(3, 4)print ("Graph is a Tree" if g2.isTree() == True \ else "Graph is a not a Tree") # This code is contributed by Divyanshu Mehta // A C# Program to check whether// a graph is tree or notusing System;using System.Collections.Generic; // This class represents a directed graph// using adjacency list representationclass Graph{ private int V; // No. of vertices private List<int> []adj; // Adjacency List // Constructor Graph(int v) { V = v; adj = new List<int>[v]; for (int i = 0; i < v; ++i) adj[i] = new List<int>(); } // Function to add an edge // into the graph void addEdge(int v, int w) { adj[v].Add(w); adj[w].Add(v); } // A recursive function that uses visited[] // and parent to detect cycle in subgraph // reachable from vertex v. Boolean isCyclicUtil(int v, Boolean []visited, int parent) { // Mark the current node as visited visited[v] = true; int i; // Recur for all the vertices // adjacent to this vertex foreach(int it in adj[v]) { i = it; // If an adjacent is not visited, // then recur for that adjacent if (!visited[i]) { if (isCyclicUtil(i, visited, v)) return true; } // If an adjacent is visited and // not parent of current vertex, // then there is a cycle. else if (i != parent) return true; } return false; } // Returns true if the graph // is a tree, else false. Boolean isTree() { // Mark all the vertices as not visited // and not part of recursion stack Boolean []visited = new Boolean[V]; for (int i = 0; i < V; i++) visited[i] = false; // The call to isCyclicUtil serves // multiple purposes. It returns true if // graph reachable from vertex 0 is cyclic. // It also marks all vertices reachable from 0. if (isCyclicUtil(0, visited, -1)) return false; // If we find a vertex which is not reachable // from 0 (not marked by isCyclicUtil(), // then we return false for (int u = 0; u < V; u++) if (!visited[u]) return false; return true; } // Driver Code public static void Main(String []args) { // Create a graph given // in the above diagram Graph g1 = new Graph(5); g1.addEdge(1, 0); g1.addEdge(0, 2); g1.addEdge(0, 3); g1.addEdge(3, 4); if (g1.isTree()) Console.WriteLine("Graph is Tree"); else Console.WriteLine("Graph is not Tree"); Graph g2 = new Graph(5); g2.addEdge(1, 0); g2.addEdge(0, 2); g2.addEdge(2, 1); g2.addEdge(0, 3); g2.addEdge(3, 4); if (g2.isTree()) Console.WriteLine("Graph is Tree"); else Console.WriteLine("Graph is not Tree"); }} // This code is contributed by Rajput-Ji <script> // A JavaScript Program to check whether// a graph is tree or not // This class represents a directed graph// using adjacency list representationvar V = 0; // No. of verticesvar adj; // Adjacency List// Constructorfunction initialize(v){ V = v; adj = Array.from(Array(v), ()=>Array());}// Function to add an edge// into the graphfunction addEdge(v, w){ adj[v].push(w); adj[w].push(v);}// A recursive function that uses visited[]// and parent to detect cycle in subgraph// reachable from vertex v.function isCyclicUtil(v, visited, parent){ // Mark the current node as visited visited[v] = true; var i; // Recur for all the vertices // adjacent to this vertex for(var it of adj[v]) { i = it; // If an adjacent is not visited, // then recur for that adjacent if (!visited[i]) { if (isCyclicUtil(i, visited, v)) return true; } // If an adjacent is visited and // not parent of current vertex, // then there is a cycle. else if (i != parent) return true; } return false;}// Returns true if the graph// is a tree, else false.function isTree(){ // Mark all the vertices as not visited // and not part of recursion stack var visited = Array(V).fill(false); // The call to isCyclicUtil serves // multiple purposes. It returns true if // graph reachable from vertex 0 is cyclic. // It also marks all vertices reachable from 0. if (isCyclicUtil(0, visited, -1)) return false; // If we find a vertex which is not reachable // from 0 (not marked by isCyclicUtil(), // then we return false for (var u = 0; u < V; u++) if (!visited[u]) return false; return true;}// Driver Code// Create a graph given// in the above diagraminitialize(5)addEdge(1, 0);addEdge(0, 2);addEdge(0, 3);addEdge(3, 4);if (isTree()) document.write("Graph is Tree<br>");else document.write("Graph is not Tree<br>");initialize(5)addEdge(1, 0);addEdge(0, 2);addEdge(2, 1);addEdge(0, 3);addEdge(3, 4);if (isTree()) document.write("Graph is Tree<br>");else document.write("Graph is not Tree<br>"); </script> Output: Graph is Tree Graph is not Tree YouTubeGeeksforGeeks500K subscribersCheck if a given graph is tree or not | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 4:14•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=rFf4mXWbb9U" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> Thanks to Vinit Verma for suggesting this problem and initial solution. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above Rajput-Ji shobhit999000 rutvik_56 amartyaghoshgfg surinderdawra388 BFS DFS graph-cycle Graph Tree DFS Graph Tree BFS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Topological Sorting Bellman–Ford Algorithm | DP-23 Floyd Warshall Algorithm | DP-16 Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming) Traveling Salesman Problem (TSP) Implementation Tree Traversals (Inorder, Preorder and Postorder) Binary Tree | Set 1 (Introduction) Level Order Binary Tree Traversal AVL Tree | Set 1 (Insertion) Inorder Tree Traversal without Recursion
[ { "code": null, "e": 25154, "s": 25126, "text": "\n24 Feb, 2022" }, { "code": null, "e": 25291, "s": 25154, "text": "Write a function that returns true if a given undirected graph is tree and false otherwise. For example, the following graph is a tree. " }, { "code": null, "e": 25332, "s": 25291, "text": "But the following graph is not a tree. " }, { "code": null, "e": 26106, "s": 25332, "text": "An undirected graph is tree if it has following properties. 1) There is no cycle. 2) The graph is connected.For an undirected graph we can either use BFS or DFS to detect above two properties.How to detect cycle in an undirected graph? We can either use BFS or DFS. For every visited vertex ‘v’, if there is an adjacent ‘u’ such that u is already visited and u is not parent of v, then there is a cycle in graph. If we don’t find such an adjacent for any vertex, we say that there is no cycle (See Detect cycle in an undirected graph for more details).How to check for connectivity? Since the graph is undirected, we can start BFS or DFS from any vertex and check if all vertices are reachable or not. If all vertices are reachable, then graph is connected, otherwise not. " }, { "code": null, "e": 26110, "s": 26106, "text": "C++" }, { "code": null, "e": 26115, "s": 26110, "text": "Java" }, { "code": null, "e": 26123, "s": 26115, "text": "Python3" }, { "code": null, "e": 26126, "s": 26123, "text": "C#" }, { "code": null, "e": 26137, "s": 26126, "text": "Javascript" }, { "code": "// A C++ Program to check whether a graph is tree or not#include<iostream>#include <list>#include <limits.h>using namespace std; // Class for an undirected graphclass Graph{ int V; // No. of vertices list<int> *adj; // Pointer to an array for adjacency lists bool isCyclicUtil(int v, bool visited[], int parent);public: Graph(int V); // Constructor void addEdge(int v, int w); // to add an edge to graph bool isTree(); // returns true if graph is tree}; Graph::Graph(int V){ this->V = V; adj = new list<int>[V];} void Graph::addEdge(int v, int w){ adj[v].push_back(w); // Add w to v’s list. adj[w].push_back(v); // Add v to w’s list.} // A recursive function that uses visited[] and parent to// detect cycle in subgraph reachable from vertex v.bool Graph::isCyclicUtil(int v, bool visited[], int parent){ // Mark the current node as visited visited[v] = true; // Recur for all the vertices adjacent to this vertex list<int>::iterator i; for (i = adj[v].begin(); i != adj[v].end(); ++i) { // If an adjacent is not visited, then recur for // that adjacent if (!visited[*i]) { if (isCyclicUtil(*i, visited, v)) return true; } // If an adjacent is visited and not parent of current // vertex, then there is a cycle. else if (*i != parent) return true; } return false;} // Returns true if the graph is a tree, else false.bool Graph::isTree(){ // Mark all the vertices as not visited and not part of // recursion stack bool *visited = new bool[V]; for (int i = 0; i < V; i++) visited[i] = false; // The call to isCyclicUtil serves multiple purposes. // It returns true if graph reachable from vertex 0 // is cyclic. It also marks all vertices reachable // from 0. if (isCyclicUtil(0, visited, -1)) return false; // If we find a vertex which is not reachable from 0 // (not marked by isCyclicUtil(), then we return false for (int u = 0; u < V; u++) if (!visited[u]) return false; return true;} // Driver program to test above functionsint main(){ Graph g1(5); g1.addEdge(1, 0); g1.addEdge(0, 2); g1.addEdge(0, 3); g1.addEdge(3, 4); g1.isTree()? cout << \"Graph is Tree\\n\": cout << \"Graph is not Tree\\n\"; Graph g2(5); g2.addEdge(1, 0); g2.addEdge(0, 2); g2.addEdge(2, 1); g2.addEdge(0, 3); g2.addEdge(3, 4); g2.isTree()? cout << \"Graph is Tree\\n\": cout << \"Graph is not Tree\\n\"; return 0;}", "e": 28726, "s": 26137, "text": null }, { "code": "// A Java Program to check whether a graph is tree or notimport java.io.*;import java.util.*; // This class represents a directed graph using adjacency// list representationclass Graph{ private int V; // No. of vertices private LinkedList<Integer> adj[]; //Adjacency List // Constructor @SuppressWarnings(\"unchecked\") Graph(int v) { V = v; adj = new LinkedList[V]; for (int i=0; i<v; ++i) adj[i] = new LinkedList<Integer>(); } // Function to add an edge into the graph void addEdge(int v,int w) { adj[v].add(w); adj[w].add(v); } // A recursive function that uses visited[] and parent // to detect cycle in subgraph reachable from vertex v. boolean isCyclicUtil(int v, boolean visited[], int parent) { // Mark the current node as visited visited[v] = true; Integer i; // Recur for all the vertices adjacent to this vertex Iterator<Integer> it = adj[v].iterator(); while (it.hasNext()) { i = it.next(); // If an adjacent is not visited, then recur for // that adjacent if (!visited[i]) { if (isCyclicUtil(i, visited, v)) return true; } // If an adjacent is visited and not parent of // current vertex, then there is a cycle. else if (i != parent) return true; } return false; } // Returns true if the graph is a tree, else false. boolean isTree() { // Mark all the vertices as not visited and not part // of recursion stack boolean visited[] = new boolean[V]; for (int i = 0; i < V; i++) visited[i] = false; // The call to isCyclicUtil serves multiple purposes // It returns true if graph reachable from vertex 0 // is cyclic. It also marks all vertices reachable // from 0. if (isCyclicUtil(0, visited, -1)) return false; // If we find a vertex which is not reachable from 0 // (not marked by isCyclicUtil(), then we return false for (int u = 0; u < V; u++) if (!visited[u]) return false; return true; } // Driver method public static void main(String args[]) { // Create a graph given in the above diagram Graph g1 = new Graph(5); g1.addEdge(1, 0); g1.addEdge(0, 2); g1.addEdge(0, 3); g1.addEdge(3, 4); if (g1.isTree()) System.out.println(\"Graph is Tree\"); else System.out.println(\"Graph is not Tree\"); Graph g2 = new Graph(5); g2.addEdge(1, 0); g2.addEdge(0, 2); g2.addEdge(2, 1); g2.addEdge(0, 3); g2.addEdge(3, 4); if (g2.isTree()) System.out.println(\"Graph is Tree\"); else System.out.println(\"Graph is not Tree\"); }}// This code is contributed by Aakash Hasija", "e": 31728, "s": 28726, "text": null }, { "code": "# Python Program to check whether# a graph is tree or not from collections import defaultdict class Graph(): def __init__(self, V): self.V = V self.graph = defaultdict(list) def addEdge(self, v, w): # Add w to v ist. self.graph[v].append(w) # Add v to w list. self.graph[w].append(v) # A recursive function that uses visited[] # and parent to detect cycle in subgraph # reachable from vertex v. def isCyclicUtil(self, v, visited, parent): # Mark current node as visited visited[v] = True # Recur for all the vertices adjacent # for this vertex for i in self.graph[v]: # If an adjacent is not visited, # then recur for that adjacent if visited[i] == False: if self.isCyclicUtil(i, visited, v) == True: return True # If an adjacent is visited and not # parent of current vertex, then there # is a cycle. elif i != parent: return True return False # Returns true if the graph is a tree, # else false. def isTree(self): # Mark all the vertices as not visited # and not part of recursion stack visited = [False] * self.V # The call to isCyclicUtil serves multiple # purposes. It returns true if graph reachable # from vertex 0 is cyclic. It also marks # all vertices reachable from 0. if self.isCyclicUtil(0, visited, -1) == True: return False # If we find a vertex which is not reachable # from 0 (not marked by isCyclicUtil(), # then we return false for i in range(self.V): if visited[i] == False: return False return True # Driver program to test above functionsg1 = Graph(5)g1.addEdge(1, 0)g1.addEdge(0, 2)g1.addEdge(0, 3)g1.addEdge(3, 4)print (\"Graph is a Tree\" if g1.isTree() == True \\ else \"Graph is a not a Tree\") g2 = Graph(5)g2.addEdge(1, 0)g2.addEdge(0, 2)g2.addEdge(2, 1)g2.addEdge(0, 3)g2.addEdge(3, 4)print (\"Graph is a Tree\" if g2.isTree() == True \\ else \"Graph is a not a Tree\") # This code is contributed by Divyanshu Mehta ", "e": 34022, "s": 31728, "text": null }, { "code": "// A C# Program to check whether// a graph is tree or notusing System;using System.Collections.Generic; // This class represents a directed graph// using adjacency list representationclass Graph{ private int V; // No. of vertices private List<int> []adj; // Adjacency List // Constructor Graph(int v) { V = v; adj = new List<int>[v]; for (int i = 0; i < v; ++i) adj[i] = new List<int>(); } // Function to add an edge // into the graph void addEdge(int v, int w) { adj[v].Add(w); adj[w].Add(v); } // A recursive function that uses visited[] // and parent to detect cycle in subgraph // reachable from vertex v. Boolean isCyclicUtil(int v, Boolean []visited, int parent) { // Mark the current node as visited visited[v] = true; int i; // Recur for all the vertices // adjacent to this vertex foreach(int it in adj[v]) { i = it; // If an adjacent is not visited, // then recur for that adjacent if (!visited[i]) { if (isCyclicUtil(i, visited, v)) return true; } // If an adjacent is visited and // not parent of current vertex, // then there is a cycle. else if (i != parent) return true; } return false; } // Returns true if the graph // is a tree, else false. Boolean isTree() { // Mark all the vertices as not visited // and not part of recursion stack Boolean []visited = new Boolean[V]; for (int i = 0; i < V; i++) visited[i] = false; // The call to isCyclicUtil serves // multiple purposes. It returns true if // graph reachable from vertex 0 is cyclic. // It also marks all vertices reachable from 0. if (isCyclicUtil(0, visited, -1)) return false; // If we find a vertex which is not reachable // from 0 (not marked by isCyclicUtil(), // then we return false for (int u = 0; u < V; u++) if (!visited[u]) return false; return true; } // Driver Code public static void Main(String []args) { // Create a graph given // in the above diagram Graph g1 = new Graph(5); g1.addEdge(1, 0); g1.addEdge(0, 2); g1.addEdge(0, 3); g1.addEdge(3, 4); if (g1.isTree()) Console.WriteLine(\"Graph is Tree\"); else Console.WriteLine(\"Graph is not Tree\"); Graph g2 = new Graph(5); g2.addEdge(1, 0); g2.addEdge(0, 2); g2.addEdge(2, 1); g2.addEdge(0, 3); g2.addEdge(3, 4); if (g2.isTree()) Console.WriteLine(\"Graph is Tree\"); else Console.WriteLine(\"Graph is not Tree\"); }} // This code is contributed by Rajput-Ji", "e": 37005, "s": 34022, "text": null }, { "code": "<script> // A JavaScript Program to check whether// a graph is tree or not // This class represents a directed graph// using adjacency list representationvar V = 0; // No. of verticesvar adj; // Adjacency List// Constructorfunction initialize(v){ V = v; adj = Array.from(Array(v), ()=>Array());}// Function to add an edge// into the graphfunction addEdge(v, w){ adj[v].push(w); adj[w].push(v);}// A recursive function that uses visited[]// and parent to detect cycle in subgraph// reachable from vertex v.function isCyclicUtil(v, visited, parent){ // Mark the current node as visited visited[v] = true; var i; // Recur for all the vertices // adjacent to this vertex for(var it of adj[v]) { i = it; // If an adjacent is not visited, // then recur for that adjacent if (!visited[i]) { if (isCyclicUtil(i, visited, v)) return true; } // If an adjacent is visited and // not parent of current vertex, // then there is a cycle. else if (i != parent) return true; } return false;}// Returns true if the graph// is a tree, else false.function isTree(){ // Mark all the vertices as not visited // and not part of recursion stack var visited = Array(V).fill(false); // The call to isCyclicUtil serves // multiple purposes. It returns true if // graph reachable from vertex 0 is cyclic. // It also marks all vertices reachable from 0. if (isCyclicUtil(0, visited, -1)) return false; // If we find a vertex which is not reachable // from 0 (not marked by isCyclicUtil(), // then we return false for (var u = 0; u < V; u++) if (!visited[u]) return false; return true;}// Driver Code// Create a graph given// in the above diagraminitialize(5)addEdge(1, 0);addEdge(0, 2);addEdge(0, 3);addEdge(3, 4);if (isTree()) document.write(\"Graph is Tree<br>\");else document.write(\"Graph is not Tree<br>\");initialize(5)addEdge(1, 0);addEdge(0, 2);addEdge(2, 1);addEdge(0, 3);addEdge(3, 4);if (isTree()) document.write(\"Graph is Tree<br>\");else document.write(\"Graph is not Tree<br>\"); </script>", "e": 39198, "s": 37005, "text": null }, { "code": null, "e": 39207, "s": 39198, "text": "Output: " }, { "code": null, "e": 39239, "s": 39207, "text": "Graph is Tree\nGraph is not Tree" }, { "code": null, "e": 40077, "s": 39241, "text": "YouTubeGeeksforGeeks500K subscribersCheck if a given graph is tree or not | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 4:14•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=rFf4mXWbb9U\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>" }, { "code": null, "e": 40274, "s": 40077, "text": "Thanks to Vinit Verma for suggesting this problem and initial solution. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 40284, "s": 40274, "text": "Rajput-Ji" }, { "code": null, "e": 40298, "s": 40284, "text": "shobhit999000" }, { "code": null, "e": 40308, "s": 40298, "text": "rutvik_56" }, { "code": null, "e": 40324, "s": 40308, "text": "amartyaghoshgfg" }, { "code": null, "e": 40341, "s": 40324, "text": "surinderdawra388" }, { "code": null, "e": 40345, "s": 40341, "text": "BFS" }, { "code": null, "e": 40349, "s": 40345, "text": "DFS" }, { "code": null, "e": 40361, "s": 40349, "text": "graph-cycle" }, { "code": null, "e": 40367, "s": 40361, "text": "Graph" }, { "code": null, "e": 40372, "s": 40367, "text": "Tree" }, { "code": null, "e": 40376, "s": 40372, "text": "DFS" }, { "code": null, "e": 40382, "s": 40376, "text": "Graph" }, { "code": null, "e": 40387, "s": 40382, "text": "Tree" }, { "code": null, "e": 40391, "s": 40387, "text": "BFS" }, { "code": null, "e": 40489, "s": 40391, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 40498, "s": 40489, "text": "Comments" }, { "code": null, "e": 40511, "s": 40498, "text": "Old Comments" }, { "code": null, "e": 40531, "s": 40511, "text": "Topological Sorting" }, { "code": null, "e": 40562, "s": 40531, "text": "Bellman–Ford Algorithm | DP-23" }, { "code": null, "e": 40595, "s": 40562, "text": "Floyd Warshall Algorithm | DP-16" }, { "code": null, "e": 40663, "s": 40595, "text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)" }, { "code": null, "e": 40711, "s": 40663, "text": "Traveling Salesman Problem (TSP) Implementation" }, { "code": null, "e": 40761, "s": 40711, "text": "Tree Traversals (Inorder, Preorder and Postorder)" }, { "code": null, "e": 40796, "s": 40761, "text": "Binary Tree | Set 1 (Introduction)" }, { "code": null, "e": 40830, "s": 40796, "text": "Level Order Binary Tree Traversal" }, { "code": null, "e": 40859, "s": 40830, "text": "AVL Tree | Set 1 (Insertion)" } ]
Python | Creating a Pandas dataframe column based on a given condition - GeeksforGeeks
21 Jan, 2019 While operating on data, there could be instances where we would like to add a column based on some condition. There does not exist any library function to achieve this task directly, so we are going to see the ways in which we can achieve this goal. Problem : Given a dataframe containing the data of a cultural event, add a column called ‘Price’ which contains the ticket price for a particular day based on the type of event that will be conducted on that particular day. Solution #1 : We can use Python’s list comprehension technique to achieve this task. List comprehension is mostly faster than other methods. # importing pandas as pdimport pandas as pd # Creating the dataframedf = pd.DataFrame({'Date' : ['11/8/2011', '11/9/2011', '11/10/2011', '11/11/2011', '11/12/2011'], 'Event' : ['Music', 'Poetry', 'Music', 'Music', 'Poetry']}) # Print the dataframeprint(df) Output : Now we will add a new column called ‘Price’ to the dataframe. For that purpose, we will use list comprehension technique. Set the price to 1500 if the ‘Event’ is ‘Music’ else 800. # Add a new column named 'Price'df['Price'] = [1500 if x =='Music' else 800 for x in df['Event']] # Print the DataFrameprint(df) Output :As we can see in the output, we have successfully added a new column to the dataframe based on some condition. Solution #2 : We can use DataFrame.apply() function to achieve the goal. There could be instances when we have more than two values, in that case, we can use a dictionary to map new values onto the keys. This does provide a lot of flexibility when we are having a larger number of categories for which we want to assign different values to the newly added column. # importing pandas as pdimport pandas as pd # Creating the dataframedf = pd.DataFrame({'Date' : ['11/8/2011', '11/9/2011', '11/10/2011', '11/11/2011', '11/12/2011'], 'Event' : ['Music', 'Poetry', 'Music', 'Comedy', 'Poetry']}) # Print the dataframeprint(df) Output : Now we will add a new column called ‘Price’ to the dataframe. For that purpose we will use DataFrame.apply() function to achieve the goal. Set the price to 1500 if the ‘Event’ is ‘Music’, 1200 if the ‘Event’ is ‘Comedy’ and 800 if the ‘Event’ is ‘Poetry’. # Define a function to map the valuesdef set_value(row_number, assigned_value): return assigned_value[row_number] # Create the dictionaryevent_dictionary ={'Music' : 1500, 'Poetry' : 800, 'Comedy' : 1200} # Add a new column named 'Price'df['Price'] = df['Event'].apply(set_value, args =(event_dictionary, )) # Print the DataFrameprint(df) Output :As we can see in the output, we have successfully added a new column to the dataframe based on some condition. Solution #3 : We can use DataFrame.map() function to achieve the goal. It is a very straight forward method where we use a dictionary to simply map values to the newly added column based on the key. # importing pandas as pdimport pandas as pd # Creating the dataframedf = pd.DataFrame({'Date' : ['11/8/2011', '11/9/2011', '11/10/2011', '11/11/2011', '11/12/2011'], 'Event' : ['Music', 'Poetry', 'Music', 'Comedy', 'Poetry']}) # Print the dataframeprint(df) Output : Now we will add a new column called ‘Price’ to the dataframe. For that purpose we will use DataFrame.map() function to achieve the goal. Set the price to 1500 if the ‘Event’ is ‘Music’, 1200 if the ‘Event’ is ‘Comedy’ and 800 if the ‘Event’ is ‘Poetry’. # Create the dictionaryevent_dictionary ={'Music' : 1500, 'Poetry' : 800, 'Comedy' : 1200} # Add a new column named 'Price'df['Price'] = df['Event'].map(event_dictionary) # Print the DataFrameprint(df) Output : pandas-dataframe-program Python pandas-dataFrame Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Enumerate() in Python How to Install PIP on Windows ? Different ways to create Pandas Dataframe Create a Pandas DataFrame from Lists sum() function in Python *args and **kwargs in Python How to drop one or multiple columns in Pandas Dataframe Convert integer to string in Python Print lists in Python (4 Different Ways) Python | Get unique values from a list
[ { "code": null, "e": 24777, "s": 24749, "text": "\n21 Jan, 2019" }, { "code": null, "e": 25028, "s": 24777, "text": "While operating on data, there could be instances where we would like to add a column based on some condition. There does not exist any library function to achieve this task directly, so we are going to see the ways in which we can achieve this goal." }, { "code": null, "e": 25252, "s": 25028, "text": "Problem : Given a dataframe containing the data of a cultural event, add a column called ‘Price’ which contains the ticket price for a particular day based on the type of event that will be conducted on that particular day." }, { "code": null, "e": 25393, "s": 25252, "text": "Solution #1 : We can use Python’s list comprehension technique to achieve this task. List comprehension is mostly faster than other methods." }, { "code": "# importing pandas as pdimport pandas as pd # Creating the dataframedf = pd.DataFrame({'Date' : ['11/8/2011', '11/9/2011', '11/10/2011', '11/11/2011', '11/12/2011'], 'Event' : ['Music', 'Poetry', 'Music', 'Music', 'Poetry']}) # Print the dataframeprint(df)", "e": 25706, "s": 25393, "text": null }, { "code": null, "e": 25715, "s": 25706, "text": "Output :" }, { "code": null, "e": 25895, "s": 25715, "text": "Now we will add a new column called ‘Price’ to the dataframe. For that purpose, we will use list comprehension technique. Set the price to 1500 if the ‘Event’ is ‘Music’ else 800." }, { "code": "# Add a new column named 'Price'df['Price'] = [1500 if x =='Music' else 800 for x in df['Event']] # Print the DataFrameprint(df)", "e": 26025, "s": 25895, "text": null }, { "code": null, "e": 26508, "s": 26025, "text": "Output :As we can see in the output, we have successfully added a new column to the dataframe based on some condition. Solution #2 : We can use DataFrame.apply() function to achieve the goal. There could be instances when we have more than two values, in that case, we can use a dictionary to map new values onto the keys. This does provide a lot of flexibility when we are having a larger number of categories for which we want to assign different values to the newly added column." }, { "code": "# importing pandas as pdimport pandas as pd # Creating the dataframedf = pd.DataFrame({'Date' : ['11/8/2011', '11/9/2011', '11/10/2011', '11/11/2011', '11/12/2011'], 'Event' : ['Music', 'Poetry', 'Music', 'Comedy', 'Poetry']}) # Print the dataframeprint(df)", "e": 26822, "s": 26508, "text": null }, { "code": null, "e": 26831, "s": 26822, "text": "Output :" }, { "code": null, "e": 27087, "s": 26831, "text": "Now we will add a new column called ‘Price’ to the dataframe. For that purpose we will use DataFrame.apply() function to achieve the goal. Set the price to 1500 if the ‘Event’ is ‘Music’, 1200 if the ‘Event’ is ‘Comedy’ and 800 if the ‘Event’ is ‘Poetry’." }, { "code": "# Define a function to map the valuesdef set_value(row_number, assigned_value): return assigned_value[row_number] # Create the dictionaryevent_dictionary ={'Music' : 1500, 'Poetry' : 800, 'Comedy' : 1200} # Add a new column named 'Price'df['Price'] = df['Event'].apply(set_value, args =(event_dictionary, )) # Print the DataFrameprint(df)", "e": 27432, "s": 27087, "text": null }, { "code": null, "e": 27750, "s": 27432, "text": "Output :As we can see in the output, we have successfully added a new column to the dataframe based on some condition. Solution #3 : We can use DataFrame.map() function to achieve the goal. It is a very straight forward method where we use a dictionary to simply map values to the newly added column based on the key." }, { "code": "# importing pandas as pdimport pandas as pd # Creating the dataframedf = pd.DataFrame({'Date' : ['11/8/2011', '11/9/2011', '11/10/2011', '11/11/2011', '11/12/2011'], 'Event' : ['Music', 'Poetry', 'Music', 'Comedy', 'Poetry']}) # Print the dataframeprint(df)", "e": 28064, "s": 27750, "text": null }, { "code": null, "e": 28073, "s": 28064, "text": "Output :" }, { "code": null, "e": 28327, "s": 28073, "text": "Now we will add a new column called ‘Price’ to the dataframe. For that purpose we will use DataFrame.map() function to achieve the goal. Set the price to 1500 if the ‘Event’ is ‘Music’, 1200 if the ‘Event’ is ‘Comedy’ and 800 if the ‘Event’ is ‘Poetry’." }, { "code": "# Create the dictionaryevent_dictionary ={'Music' : 1500, 'Poetry' : 800, 'Comedy' : 1200} # Add a new column named 'Price'df['Price'] = df['Event'].map(event_dictionary) # Print the DataFrameprint(df)", "e": 28531, "s": 28327, "text": null }, { "code": null, "e": 28540, "s": 28531, "text": "Output :" }, { "code": null, "e": 28565, "s": 28540, "text": "pandas-dataframe-program" }, { "code": null, "e": 28589, "s": 28565, "text": "Python pandas-dataFrame" }, { "code": null, "e": 28603, "s": 28589, "text": "Python-pandas" }, { "code": null, "e": 28610, "s": 28603, "text": "Python" }, { "code": null, "e": 28708, "s": 28610, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28717, "s": 28708, "text": "Comments" }, { "code": null, "e": 28730, "s": 28717, "text": "Old Comments" }, { "code": null, "e": 28752, "s": 28730, "text": "Enumerate() in Python" }, { "code": null, "e": 28784, "s": 28752, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28826, "s": 28784, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28863, "s": 28826, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 28888, "s": 28863, "text": "sum() function in Python" }, { "code": null, "e": 28917, "s": 28888, "text": "*args and **kwargs in Python" }, { "code": null, "e": 28973, "s": 28917, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 29009, "s": 28973, "text": "Convert integer to string in Python" }, { "code": null, "e": 29050, "s": 29009, "text": "Print lists in Python (4 Different Ways)" } ]
Anomaly Detection in Python — Part 2; Multivariate Unsupervised Methods and Code | by Nitish Kumar Thakur | Towards Data Science
In my previous article(https://medium.com/analytics-vidhya/anomaly-detection-in-python-part-1-basics-code-and-standard-algorithms-37d022cdbcff) we discussed the basics of Anomaly detection, the types of problems and types of methods used. We discussed the EDA, Univariate and the Multivariate methods of performing Anomaly Detection along with one example of each. We discussed why Multivariate Outlier detection is a difficult problem and requires specialized techniques. We also discussed Mahalanobis Distance Method with FastMCD for detecting Multivariate Outliers. In this article, we will discuss 2 other widely used methods to perform Multivariate Unsupervised Anomaly Detection. We will discuss: Isolation ForestsOC-SVM(One-Class SVM) Isolation Forests OC-SVM(One-Class SVM) Anomaly detection is a tool to identify unusual or interesting occurrences in data. However, it is important to analyze the detected anomalies from a domain/business perspective before removing them. Each method has its own definition of anomalies. Multiple methods may very often not agree on which points are anomalous. It is our responsibility to validate the results from a domain/business perspective. Sometimes, detected Anomalies represent “under-sampled” regimes in data. In this case, instead of removing them, we should aim to collect more data in that regime. Multivariate Anomalies occur when the values of various features, taken together seem anomalous even though the individual features do not take unusual values. For example, imagine we have 2 features:1. odo: this is the reading of the odometer of a car in mph. It typically lies between 0–50.2. rpm: this is the rpm(rotations per minute) of the car’s wheels. It typically lies between 0–650. Now, imagine odo reads 0 mph. We know this is possible — and that the car is not moving. Let’s say, on another occasion, the rpm reads 600. We know that the car is moving. Taken separately, we know that the above readings are not anomalous — because they represent perfectly normal modes of operation of the car. However, let us imagine the odo reads 0 mph and rpm reads 600 at the same time. This is not possible — they are in conflict. rpm suggests that the car is moving and odo suggests that the car is stationary. This is an example of a multivariate outlier. Detecting a Multivariate Outlier involves examining the values of all the features simultaneously and verifying if the combination of values taken by the features is unusual. As we can understand this becomes intractable to do manually when we have large number of features(say hundreds). Alternately, we can use specialized algorithms that can identify them for us. Let us take a look at them. Isolation forests are known to work well for high dimensional data. An Isolation forest is a ensemble of “Isolation Trees”. It is discussed in detail in the following paper: https://cs.nju.edu.cn/zhouzh/zhouzh.files/publication/icdm08b.pdf?q=isolation-forest. An Isolation tree is a binary tree that stores data by dividing it into boxes(called nodes). To understand why Isolation Forests are anomaly detectors, it is important to understand how Isolation Trees are built. Here are the steps to compute an isolation tree: Select a feature at random from data. Let us call the random feature f.Select a random value from the feature f. We will use this random value as a threshold. Let us call it t.Data points where f < t are stored in Node 1 and the data points where f ≥ t go in Node 2.Repeat Steps 1–3 for Node 1 and Node 2.Terminate either when the tree is fully grown or a termination criterion is met. Select a feature at random from data. Let us call the random feature f. Select a random value from the feature f. We will use this random value as a threshold. Let us call it t. Data points where f < t are stored in Node 1 and the data points where f ≥ t go in Node 2. Repeat Steps 1–3 for Node 1 and Node 2. Terminate either when the tree is fully grown or a termination criterion is met. For Simplicity, let us start with how the Isolation tree works with univariate data. We will explore Multivariate examples later. The following figure shows its mechanism for 1 Dimensional Data: It is important to remember that the feature to split on and the threshold are chosen at random as shown in the above figure. Since the above example was univariate, we only choose the threshold at random. Now, assume the univariate data above has an anomaly. In that case, the anomalous point will be far away from the other data points. Isolation forests are able to isolate out anomalies very early on in the splitting process because the Random Threshold used for splitting has a large probability of lying in the empty space between the outlier and the data if the empty space is large enough. As a result, anomalies have shorter path lengths. After all, the split point(the threshold)is chosen at random. So, the larger the empty space, the more likely it is for a randomly chosen split point to lie in that empty region. Let us take a look at how an Isolation tree would look in the presence of an Anomaly. As we can see, due to the large space between the anomaly and the rest of the data, it is very likely that a random split will lie in this empty region. Let us now see how this would look if we had multivariate data. As we will see, Isolation trees work very similar to what we saw above — they isolate the anomalies before isolating the other points. Please note that the trees can grow either: Till there is exactly one data point in each leaf node. OrTill termination criterion regarding the minimum number of data points in a leaf node is reached. Till there is exactly one data point in each leaf node. Or Till termination criterion regarding the minimum number of data points in a leaf node is reached. I have only shown the first few splits here for illustration. As we can see, the Isolation tree divides the data into “boxes”. It has the property that it isolates the region containing anomalies earlier than the boxes containing normal data points. We can extend the idea of an Isolation tree to an isolation forest which is an ensemble of multiple Isolation trees. Here is briefly how Isolation forests work: Construct an Isolation Tree either from the entire feature set or a randomly chosen subset of the feature set.Construct n such Isolation trees.Calculate an Anomaly score for each data point. The Anomaly score is a non-linear function of the Average path length over all Isolation trees. The path length is equivalent to the number of splits made by the Isolation tree to isolate a point. The shorter the Average path length, the larger are the chances of the point being an anomaly(as we saw earlier in the diagram). Construct an Isolation Tree either from the entire feature set or a randomly chosen subset of the feature set. Construct n such Isolation trees. Calculate an Anomaly score for each data point. The Anomaly score is a non-linear function of the Average path length over all Isolation trees. The path length is equivalent to the number of splits made by the Isolation tree to isolate a point. The shorter the Average path length, the larger are the chances of the point being an anomaly(as we saw earlier in the diagram). Isolation forests work well even for data having hundreds of dimensions. The Isolation forest in skearn has 4 important inputs: n_estimators: Number of Isolation trees trained.max_samples: Number of data points used to train each tree.contamination: Fraction of anomalous data points. For example, if we suspect 5% of the data to be anomalous, we set contamination to 0.05max_features: Number of features to be used to train each tree(This is in contrast to Random Forests where we decide on a random subset of features for each split). It has 2 Important methods: decision_function(X): Returns a score — such that examples having more negative scores are more anomalous. predict(X): Returns -1 for Anomalous points and +1 for normal points. The number of points output as anomalous depends on the contamination value set while fitting the model. Let us train an Isolation Forest on the above data(we set contamination to 0.01): # Create Artificial Data with Multivariate Outliersd1 = np.random.multivariate_normal(mean = np.array([-.5, 0]), cov = np.array([[1, 0], [0, 1]]), size = 100)d2 = np.random.multivariate_normal(mean = np.array([15, 10]), cov = np.array([[1, 0.3], [.3, 1]]), size = 100)outliers = np.array([[0, 10],[0, 9.5]])d = pd.DataFrame(np.concatenate([d1, d2, outliers], axis = 0), columns = ['Var 1', 'Var 2'])################### Train Isolation Forest #################model = ensemble.IsolationForest(n_estimators=50, max_samples=500, contamination=.01, max_features=2, bootstrap=False, n_jobs=1, random_state=1, verbose=0, warm_start=False).fit(d)# Get Anomaly Scores and Predictionsanomaly_score = model.decision_function(d)predictions = model.predict(d)######### Visualize Anomaly scores and Anomaly Status ########plt.figure(figsize = (10, 6), dpi = 150)s = plt.scatter(d['Var 1'], d['Var 2'], c = anomaly_score, cmap = 'coolwarm')plt.colorbar(s, label = 'More Negative = More Anomalous')plt.xlabel('Var 1', fontsize = 16)plt.ylabel('Var 2', fontsize = 16)plt.grid()# To Plot Predictionsplt.figure(figsize = (10, 6), dpi = 150)s = plt.scatter(d['Var 1'], d['Var 2'], c = predictions, cmap = 'coolwarm')plt.colorbar(s, label = 'More Negative = More Anomalous')plt.xlabel('Var 1', fontsize = 16)plt.ylabel('Var 2', fontsize = 16)plt.grid()plt.title('Contamination = 0.01', weight = 'bold') As we can see, the 2 points are detected to be strong outliers. Deciding whether a point is an anomaly can be thus done using 2 methods: Use the Predict function: If the model predicts -1, label the point as anomaly. For this method, it is important to set the contamination carefully.Analyze the Decision Function Output distribution, and based on visual Inspection set a threshold below which anomalous points will fall. We can also apply a univariate anomaly detection algorithm on the decision function output; This is a very common method where we convert a multivariate problem into a univariate one — by calculating the anomaly scores and then use a univariate algorithm on the scores. This method is not dependent on our choice of contamination factor. Use the Predict function: If the model predicts -1, label the point as anomaly. For this method, it is important to set the contamination carefully. Analyze the Decision Function Output distribution, and based on visual Inspection set a threshold below which anomalous points will fall. We can also apply a univariate anomaly detection algorithm on the decision function output; This is a very common method where we convert a multivariate problem into a univariate one — by calculating the anomaly scores and then use a univariate algorithm on the scores. This method is not dependent on our choice of contamination factor. However, let us see what happens if we set different values of contamination and using Method 1. With increasing Contamination values, the model labels more data as anomalous. In this case, we analyze the decision_function() output. There are 2 ways of doing this: Apply a Univariate Anomaly Detection algorithm on the Isolation Forest Decision Function Output(like the tukey’s method — which we discussed in the previous article). This is a standard method — where we calculate an ‘Anomaly Score’(here, the decision function output) using a Multivariate algorithm; Then, to select which of these anomaly scores correspond to outliers, we apply a Univariate Anomaly detection algorithm on the scores.Plot a Histogram and manually select a threshold. Apply a Univariate Anomaly Detection algorithm on the Isolation Forest Decision Function Output(like the tukey’s method — which we discussed in the previous article). This is a standard method — where we calculate an ‘Anomaly Score’(here, the decision function output) using a Multivariate algorithm; Then, to select which of these anomaly scores correspond to outliers, we apply a Univariate Anomaly detection algorithm on the scores. Plot a Histogram and manually select a threshold. Let us see the results of applying Tukey’s method on the Decision Function output given by our Isolation Forest: We see 2 clear outliers which are the 2 extreme points to the left. These are actually also the 2 major outliers we wanted to detect. However, we see 4 additional points being labelled as outliers. To select the appropriate anomaly, domain/business analysis needs to be done. Let us discuss some advantages of Isolation forests: Scalability — Isolation Forests can use Parallel Processing during training and prediction— as all the isolation trees are trained in parallel- independently of each other.Interpretability — Individual trees in an Isolation forest can be visualized to give the exact rules as to what made the data point an outlier. These rules can have large business/domain importance. However, this can become hard for large data.Flexibility — They can capture very complex outliers and do not require the data to belong to a specific distribution. If we remember, the Mahalanobis Distance method with FastMCD discussed in the previous article assumed the clean data to belong to a multivariate normal distribution. Isolation forests make no such assumptions. Scalability — Isolation Forests can use Parallel Processing during training and prediction— as all the isolation trees are trained in parallel- independently of each other. Interpretability — Individual trees in an Isolation forest can be visualized to give the exact rules as to what made the data point an outlier. These rules can have large business/domain importance. However, this can become hard for large data. Flexibility — They can capture very complex outliers and do not require the data to belong to a specific distribution. If we remember, the Mahalanobis Distance method with FastMCD discussed in the previous article assumed the clean data to belong to a multivariate normal distribution. Isolation forests make no such assumptions. From Experience, I have noticed that the Decision function values of severe outliers and minor outliers can often be close. As we saw here, we had 2 clear outliers. However, their decision function output was close to the decision function output of some other points. This is in contrast to Mahalanobis distance method where for the same problem, the distinction was very clear. Overall, the outliers detected by Isolation Forest were reasonable — and the method of Using Univariate method on the Decision Function also yielded reasonable results. The OC-SVM is a multivariate method that belongs to the family of One-Class classification methods. It is discussed in detail in the following paper: https://www.microsoft.com/en-us/research/wp-content/uploads/2016/02/tr-99-87.pdf We decide a fraction of data say ν(Pronounced Nu) that we suspect to be the upper bound on the number of anomalies present in data. The OC-SVM then tries to find a boundary that encloses regions of high data density excluding at most a fraction ν of data points. It can be seen that boundaries which are linear in the problem variable space are too simple for most problems. Since SVM is a linear classifier by nature, we need to resort to kernel methods to build a flexible model with non-linear boundaries. Instead of finding a decision boundary to separate 2 classes, the OC-SVM tries to find a hyperplane separating the Data from the Origin. The idea is to map the data into the kernel feature space and to separate it from the origin with maximum margin using a linear classifier in the kernel feature space. This corresponds to using a non-linear boundary in our original problem space. Let us briefly discuss the use of kernels in OC-SVM. The SVM is a Linear model. This allows it to make very simple decision rules. One way to increase the capacity of the SVM is to create polynomial features from data — and then to use the Linear SVM on the transformed feature space. The SVM still finds a linear boundary in the Polynomial feature space — but when mapped back to our original problem variable space, the decision boundary(which was linear in the polynomial feature space) looks non-linear. But we had to explicitly calculate the polynomial features — which can take large memory if we had a large number of features to begin with. Kernels allow us to fit simple models(like the linear SVM) in very high dimensional feature spaces without explicitly calculating the high dimensional features. One of the most widely used kernels is the RBF Kernel. The important thing to remember is that SVM always fits a linear model in the kernel feature space — even though the decision boundary looks non-linear in the original problem variable space. Here are some general points about the OC-SVM: In general, it is advised to use a non-linear kernel when using OC-SVM. The RBF Kernel is widely used.Hyperparameters to tune for OC-SVM with RBF Kernel are: Gamma, νPrediction can be done using predict() and decision_function() methods. We will discuss more about them later. In general, it is advised to use a non-linear kernel when using OC-SVM. The RBF Kernel is widely used. Hyperparameters to tune for OC-SVM with RBF Kernel are: Gamma, ν Prediction can be done using predict() and decision_function() methods. We will discuss more about them later. Gamma is a parameter specific to the RBF Kernel and it controls the effect of neighboring points on the decision boundary. Large values of Gamma allow neighboring points to have larger influence on the decision boundary and smaller values of Gamma allow both neighboring and distant points to have an effect on the decision boundary. Let us discuss the effect of using different values of Gamma. Larger values of Gamma cause models with large variance — which can come at the cost of Generalization. Let us vary Gamma and see the impact on the model. def plot_anomaly2(data, predicted, ax): data2 = data.copy() data2['Predicted'] = predicted normal = data2.loc[data2['Predicted'] == 1, :] anomalies = data2.loc[data2['Predicted'] == -1, :] # Make Scatterplot column1 = data.columns[0] column2 = data.columns[1] anomalies.plot.scatter(column1, column2, color = 'tomato', fontsize = 14, sharex = False, ax=ax) normal.plot.scatter(column1, column2, color = 'grey', fontsize = 14, sharex = False, ax = ax)#plt.grid(linestyle = '--') plt.xlabel(column1, fontsize = 14, weight = 'bold') plt.ylabel(column2, fontsize = 14, weight = 'bold') return ax# Create Fake data to classify x_fake = pd.DataFrame(np.random.uniform(-5, 19, (35000, 2)), columns = ['Var 1', 'Var 2'])# Visualize effect of changing Gammagammas = [.00005, .005, .01, .025, .05, .1,.3, .6, .9, 2, 5, 10]fig, axes = plt.subplots(2, 6, figsize = (25, 6), tight_layout = True)for i, ax in zip(range(len(gammas)), axes.flatten()): gamma = gammas[i] model = svm.OneClassSVM(kernel='rbf', degree=5, gamma=gamma, coef0=0.0, tol=0.001, nu=0.01, shrinking=True, cache_size=200, verbose=False, max_iter=- 1).fit(all_data)model_predictions = model.predict(x_fake) #x_fake['Predictions'] = model_predictionsax = plot_anomaly2(x_fake, model_predictions,ax) ax.scatter(all_data.iloc[:, 0], all_data.iloc[:, 1], color = 'k', s = 10) ax.set_title('Gamma: {}'.format(np.around(gamma,6)), weight = 'bold', fontsize = 14) The Blue region in the following images refer to regions that the OC-SVM predicts as “Normal”. The red points are detected as anomalies. We Observe the following: When gamma is extremely low or high, we see that the OC-SVM Misses at-least one of the major anomalies.For Mid-Gamma Values in the range of .005 to .1, the OC-SVM identifies both major anomalies. When gamma is extremely low or high, we see that the OC-SVM Misses at-least one of the major anomalies. For Mid-Gamma Values in the range of .005 to .1, the OC-SVM identifies both major anomalies. One way to select Gamma is to let sklearn choose Gamma. We do by selecting gamma = ‘scale’. Here is what happens when we set gamma = ‘scale’: As discussed earlier, in OC-SVMs the data is separated from the origin in the kernel space using a linear decision boundary. A fraction(upto ν) of data are allowed to fall on the wrong side of the linear decision boundary. Basically, we want all the inliers to be one side of the decision boundary and all the outliers to be on the other side of the decision boundary. The decision_function method of the OC-SVM outputs the signed distance of a point from the decision boundary. This distance takes negative values for outliers and positive values for normal points(inliers). Let us apply tukey’s method on the decision_function output as we did earlier. Here, luckily tukey’s method identified the 2 major anomalies that we had in our data. However, in the general case, it may identify additional or lesser anomalies. Anomalies identified by Tukey’s method depend on our value of ‘k’(discussed in the previous article) which can be tuned. it is sometimes useful to treat k as a hyperparameter in the ML pipeline — which can be finalized through domain analysis or Optimization. Till now we have discussed unsupervised methods of performing Anomaly detection. We discussed Isolation Forests and OC-SVM methods which are used to perform Multivariate Anomaly detection. One of the advantages of this methods is that they do not require the data to belong to a particular distribution. OC-SVM is a method which can be used for Unsupervised and Semi-Supervised Anomaly detection. In the next articles we will discuss Semi-Supervised and Supervised methods of performing Anomaly detection. They include using PCA, Auto-Encoders, OC-SVM and imbalanced Classification methods for performing Anomaly Detection. Please feel free to let me know if you have any feedback and check out my previous introductory article on Anomaly detection where we discuss the different types of Anomaly detection problems and methods(https://medium.com/analytics-vidhya/anomaly-detection-in-python-part-1-basics-code-and-standard-algorithms-37d022cdbcff).
[ { "code": null, "e": 741, "s": 172, "text": "In my previous article(https://medium.com/analytics-vidhya/anomaly-detection-in-python-part-1-basics-code-and-standard-algorithms-37d022cdbcff) we discussed the basics of Anomaly detection, the types of problems and types of methods used. We discussed the EDA, Univariate and the Multivariate methods of performing Anomaly Detection along with one example of each. We discussed why Multivariate Outlier detection is a difficult problem and requires specialized techniques. We also discussed Mahalanobis Distance Method with FastMCD for detecting Multivariate Outliers." }, { "code": null, "e": 875, "s": 741, "text": "In this article, we will discuss 2 other widely used methods to perform Multivariate Unsupervised Anomaly Detection. We will discuss:" }, { "code": null, "e": 914, "s": 875, "text": "Isolation ForestsOC-SVM(One-Class SVM)" }, { "code": null, "e": 932, "s": 914, "text": "Isolation Forests" }, { "code": null, "e": 954, "s": 932, "text": "OC-SVM(One-Class SVM)" }, { "code": null, "e": 1361, "s": 954, "text": "Anomaly detection is a tool to identify unusual or interesting occurrences in data. However, it is important to analyze the detected anomalies from a domain/business perspective before removing them. Each method has its own definition of anomalies. Multiple methods may very often not agree on which points are anomalous. It is our responsibility to validate the results from a domain/business perspective." }, { "code": null, "e": 1525, "s": 1361, "text": "Sometimes, detected Anomalies represent “under-sampled” regimes in data. In this case, instead of removing them, we should aim to collect more data in that regime." }, { "code": null, "e": 1917, "s": 1525, "text": "Multivariate Anomalies occur when the values of various features, taken together seem anomalous even though the individual features do not take unusual values. For example, imagine we have 2 features:1. odo: this is the reading of the odometer of a car in mph. It typically lies between 0–50.2. rpm: this is the rpm(rotations per minute) of the car’s wheels. It typically lies between 0–650." }, { "code": null, "e": 2482, "s": 1917, "text": "Now, imagine odo reads 0 mph. We know this is possible — and that the car is not moving. Let’s say, on another occasion, the rpm reads 600. We know that the car is moving. Taken separately, we know that the above readings are not anomalous — because they represent perfectly normal modes of operation of the car. However, let us imagine the odo reads 0 mph and rpm reads 600 at the same time. This is not possible — they are in conflict. rpm suggests that the car is moving and odo suggests that the car is stationary. This is an example of a multivariate outlier." }, { "code": null, "e": 2877, "s": 2482, "text": "Detecting a Multivariate Outlier involves examining the values of all the features simultaneously and verifying if the combination of values taken by the features is unusual. As we can understand this becomes intractable to do manually when we have large number of features(say hundreds). Alternately, we can use specialized algorithms that can identify them for us. Let us take a look at them." }, { "code": null, "e": 3399, "s": 2877, "text": "Isolation forests are known to work well for high dimensional data. An Isolation forest is a ensemble of “Isolation Trees”. It is discussed in detail in the following paper: https://cs.nju.edu.cn/zhouzh/zhouzh.files/publication/icdm08b.pdf?q=isolation-forest. An Isolation tree is a binary tree that stores data by dividing it into boxes(called nodes). To understand why Isolation Forests are anomaly detectors, it is important to understand how Isolation Trees are built. Here are the steps to compute an isolation tree:" }, { "code": null, "e": 3785, "s": 3399, "text": "Select a feature at random from data. Let us call the random feature f.Select a random value from the feature f. We will use this random value as a threshold. Let us call it t.Data points where f < t are stored in Node 1 and the data points where f ≥ t go in Node 2.Repeat Steps 1–3 for Node 1 and Node 2.Terminate either when the tree is fully grown or a termination criterion is met." }, { "code": null, "e": 3857, "s": 3785, "text": "Select a feature at random from data. Let us call the random feature f." }, { "code": null, "e": 3963, "s": 3857, "text": "Select a random value from the feature f. We will use this random value as a threshold. Let us call it t." }, { "code": null, "e": 4054, "s": 3963, "text": "Data points where f < t are stored in Node 1 and the data points where f ≥ t go in Node 2." }, { "code": null, "e": 4094, "s": 4054, "text": "Repeat Steps 1–3 for Node 1 and Node 2." }, { "code": null, "e": 4175, "s": 4094, "text": "Terminate either when the tree is fully grown or a termination criterion is met." }, { "code": null, "e": 4370, "s": 4175, "text": "For Simplicity, let us start with how the Isolation tree works with univariate data. We will explore Multivariate examples later. The following figure shows its mechanism for 1 Dimensional Data:" }, { "code": null, "e": 4576, "s": 4370, "text": "It is important to remember that the feature to split on and the threshold are chosen at random as shown in the above figure. Since the above example was univariate, we only choose the threshold at random." }, { "code": null, "e": 5198, "s": 4576, "text": "Now, assume the univariate data above has an anomaly. In that case, the anomalous point will be far away from the other data points. Isolation forests are able to isolate out anomalies very early on in the splitting process because the Random Threshold used for splitting has a large probability of lying in the empty space between the outlier and the data if the empty space is large enough. As a result, anomalies have shorter path lengths. After all, the split point(the threshold)is chosen at random. So, the larger the empty space, the more likely it is for a randomly chosen split point to lie in that empty region." }, { "code": null, "e": 5284, "s": 5198, "text": "Let us take a look at how an Isolation tree would look in the presence of an Anomaly." }, { "code": null, "e": 5437, "s": 5284, "text": "As we can see, due to the large space between the anomaly and the rest of the data, it is very likely that a random split will lie in this empty region." }, { "code": null, "e": 5636, "s": 5437, "text": "Let us now see how this would look if we had multivariate data. As we will see, Isolation trees work very similar to what we saw above — they isolate the anomalies before isolating the other points." }, { "code": null, "e": 5680, "s": 5636, "text": "Please note that the trees can grow either:" }, { "code": null, "e": 5836, "s": 5680, "text": "Till there is exactly one data point in each leaf node. OrTill termination criterion regarding the minimum number of data points in a leaf node is reached." }, { "code": null, "e": 5895, "s": 5836, "text": "Till there is exactly one data point in each leaf node. Or" }, { "code": null, "e": 5993, "s": 5895, "text": "Till termination criterion regarding the minimum number of data points in a leaf node is reached." }, { "code": null, "e": 6243, "s": 5993, "text": "I have only shown the first few splits here for illustration. As we can see, the Isolation tree divides the data into “boxes”. It has the property that it isolates the region containing anomalies earlier than the boxes containing normal data points." }, { "code": null, "e": 6404, "s": 6243, "text": "We can extend the idea of an Isolation tree to an isolation forest which is an ensemble of multiple Isolation trees. Here is briefly how Isolation forests work:" }, { "code": null, "e": 6921, "s": 6404, "text": "Construct an Isolation Tree either from the entire feature set or a randomly chosen subset of the feature set.Construct n such Isolation trees.Calculate an Anomaly score for each data point. The Anomaly score is a non-linear function of the Average path length over all Isolation trees. The path length is equivalent to the number of splits made by the Isolation tree to isolate a point. The shorter the Average path length, the larger are the chances of the point being an anomaly(as we saw earlier in the diagram)." }, { "code": null, "e": 7032, "s": 6921, "text": "Construct an Isolation Tree either from the entire feature set or a randomly chosen subset of the feature set." }, { "code": null, "e": 7066, "s": 7032, "text": "Construct n such Isolation trees." }, { "code": null, "e": 7440, "s": 7066, "text": "Calculate an Anomaly score for each data point. The Anomaly score is a non-linear function of the Average path length over all Isolation trees. The path length is equivalent to the number of splits made by the Isolation tree to isolate a point. The shorter the Average path length, the larger are the chances of the point being an anomaly(as we saw earlier in the diagram)." }, { "code": null, "e": 7513, "s": 7440, "text": "Isolation forests work well even for data having hundreds of dimensions." }, { "code": null, "e": 7568, "s": 7513, "text": "The Isolation forest in skearn has 4 important inputs:" }, { "code": null, "e": 7977, "s": 7568, "text": "n_estimators: Number of Isolation trees trained.max_samples: Number of data points used to train each tree.contamination: Fraction of anomalous data points. For example, if we suspect 5% of the data to be anomalous, we set contamination to 0.05max_features: Number of features to be used to train each tree(This is in contrast to Random Forests where we decide on a random subset of features for each split)." }, { "code": null, "e": 8005, "s": 7977, "text": "It has 2 Important methods:" }, { "code": null, "e": 8287, "s": 8005, "text": "decision_function(X): Returns a score — such that examples having more negative scores are more anomalous. predict(X): Returns -1 for Anomalous points and +1 for normal points. The number of points output as anomalous depends on the contamination value set while fitting the model." }, { "code": null, "e": 8369, "s": 8287, "text": "Let us train an Isolation Forest on the above data(we set contamination to 0.01):" }, { "code": null, "e": 9839, "s": 8369, "text": "# Create Artificial Data with Multivariate Outliersd1 = np.random.multivariate_normal(mean = np.array([-.5, 0]), cov = np.array([[1, 0], [0, 1]]), size = 100)d2 = np.random.multivariate_normal(mean = np.array([15, 10]), cov = np.array([[1, 0.3], [.3, 1]]), size = 100)outliers = np.array([[0, 10],[0, 9.5]])d = pd.DataFrame(np.concatenate([d1, d2, outliers], axis = 0), columns = ['Var 1', 'Var 2'])################### Train Isolation Forest #################model = ensemble.IsolationForest(n_estimators=50, max_samples=500, contamination=.01, max_features=2, bootstrap=False, n_jobs=1, random_state=1, verbose=0, warm_start=False).fit(d)# Get Anomaly Scores and Predictionsanomaly_score = model.decision_function(d)predictions = model.predict(d)######### Visualize Anomaly scores and Anomaly Status ########plt.figure(figsize = (10, 6), dpi = 150)s = plt.scatter(d['Var 1'], d['Var 2'], c = anomaly_score, cmap = 'coolwarm')plt.colorbar(s, label = 'More Negative = More Anomalous')plt.xlabel('Var 1', fontsize = 16)plt.ylabel('Var 2', fontsize = 16)plt.grid()# To Plot Predictionsplt.figure(figsize = (10, 6), dpi = 150)s = plt.scatter(d['Var 1'], d['Var 2'], c = predictions, cmap = 'coolwarm')plt.colorbar(s, label = 'More Negative = More Anomalous')plt.xlabel('Var 1', fontsize = 16)plt.ylabel('Var 2', fontsize = 16)plt.grid()plt.title('Contamination = 0.01', weight = 'bold')" }, { "code": null, "e": 9903, "s": 9839, "text": "As we can see, the 2 points are detected to be strong outliers." }, { "code": null, "e": 9976, "s": 9903, "text": "Deciding whether a point is an anomaly can be thus done using 2 methods:" }, { "code": null, "e": 10600, "s": 9976, "text": "Use the Predict function: If the model predicts -1, label the point as anomaly. For this method, it is important to set the contamination carefully.Analyze the Decision Function Output distribution, and based on visual Inspection set a threshold below which anomalous points will fall. We can also apply a univariate anomaly detection algorithm on the decision function output; This is a very common method where we convert a multivariate problem into a univariate one — by calculating the anomaly scores and then use a univariate algorithm on the scores. This method is not dependent on our choice of contamination factor." }, { "code": null, "e": 10749, "s": 10600, "text": "Use the Predict function: If the model predicts -1, label the point as anomaly. For this method, it is important to set the contamination carefully." }, { "code": null, "e": 11225, "s": 10749, "text": "Analyze the Decision Function Output distribution, and based on visual Inspection set a threshold below which anomalous points will fall. We can also apply a univariate anomaly detection algorithm on the decision function output; This is a very common method where we convert a multivariate problem into a univariate one — by calculating the anomaly scores and then use a univariate algorithm on the scores. This method is not dependent on our choice of contamination factor." }, { "code": null, "e": 11322, "s": 11225, "text": "However, let us see what happens if we set different values of contamination and using Method 1." }, { "code": null, "e": 11401, "s": 11322, "text": "With increasing Contamination values, the model labels more data as anomalous." }, { "code": null, "e": 11490, "s": 11401, "text": "In this case, we analyze the decision_function() output. There are 2 ways of doing this:" }, { "code": null, "e": 11975, "s": 11490, "text": "Apply a Univariate Anomaly Detection algorithm on the Isolation Forest Decision Function Output(like the tukey’s method — which we discussed in the previous article). This is a standard method — where we calculate an ‘Anomaly Score’(here, the decision function output) using a Multivariate algorithm; Then, to select which of these anomaly scores correspond to outliers, we apply a Univariate Anomaly detection algorithm on the scores.Plot a Histogram and manually select a threshold." }, { "code": null, "e": 12411, "s": 11975, "text": "Apply a Univariate Anomaly Detection algorithm on the Isolation Forest Decision Function Output(like the tukey’s method — which we discussed in the previous article). This is a standard method — where we calculate an ‘Anomaly Score’(here, the decision function output) using a Multivariate algorithm; Then, to select which of these anomaly scores correspond to outliers, we apply a Univariate Anomaly detection algorithm on the scores." }, { "code": null, "e": 12461, "s": 12411, "text": "Plot a Histogram and manually select a threshold." }, { "code": null, "e": 12574, "s": 12461, "text": "Let us see the results of applying Tukey’s method on the Decision Function output given by our Isolation Forest:" }, { "code": null, "e": 12850, "s": 12574, "text": "We see 2 clear outliers which are the 2 extreme points to the left. These are actually also the 2 major outliers we wanted to detect. However, we see 4 additional points being labelled as outliers. To select the appropriate anomaly, domain/business analysis needs to be done." }, { "code": null, "e": 12903, "s": 12850, "text": "Let us discuss some advantages of Isolation forests:" }, { "code": null, "e": 13649, "s": 12903, "text": "Scalability — Isolation Forests can use Parallel Processing during training and prediction— as all the isolation trees are trained in parallel- independently of each other.Interpretability — Individual trees in an Isolation forest can be visualized to give the exact rules as to what made the data point an outlier. These rules can have large business/domain importance. However, this can become hard for large data.Flexibility — They can capture very complex outliers and do not require the data to belong to a specific distribution. If we remember, the Mahalanobis Distance method with FastMCD discussed in the previous article assumed the clean data to belong to a multivariate normal distribution. Isolation forests make no such assumptions." }, { "code": null, "e": 13822, "s": 13649, "text": "Scalability — Isolation Forests can use Parallel Processing during training and prediction— as all the isolation trees are trained in parallel- independently of each other." }, { "code": null, "e": 14067, "s": 13822, "text": "Interpretability — Individual trees in an Isolation forest can be visualized to give the exact rules as to what made the data point an outlier. These rules can have large business/domain importance. However, this can become hard for large data." }, { "code": null, "e": 14397, "s": 14067, "text": "Flexibility — They can capture very complex outliers and do not require the data to belong to a specific distribution. If we remember, the Mahalanobis Distance method with FastMCD discussed in the previous article assumed the clean data to belong to a multivariate normal distribution. Isolation forests make no such assumptions." }, { "code": null, "e": 14946, "s": 14397, "text": "From Experience, I have noticed that the Decision function values of severe outliers and minor outliers can often be close. As we saw here, we had 2 clear outliers. However, their decision function output was close to the decision function output of some other points. This is in contrast to Mahalanobis distance method where for the same problem, the distinction was very clear. Overall, the outliers detected by Isolation Forest were reasonable — and the method of Using Univariate method on the Decision Function also yielded reasonable results." }, { "code": null, "e": 15177, "s": 14946, "text": "The OC-SVM is a multivariate method that belongs to the family of One-Class classification methods. It is discussed in detail in the following paper: https://www.microsoft.com/en-us/research/wp-content/uploads/2016/02/tr-99-87.pdf" }, { "code": null, "e": 15686, "s": 15177, "text": "We decide a fraction of data say ν(Pronounced Nu) that we suspect to be the upper bound on the number of anomalies present in data. The OC-SVM then tries to find a boundary that encloses regions of high data density excluding at most a fraction ν of data points. It can be seen that boundaries which are linear in the problem variable space are too simple for most problems. Since SVM is a linear classifier by nature, we need to resort to kernel methods to build a flexible model with non-linear boundaries." }, { "code": null, "e": 16070, "s": 15686, "text": "Instead of finding a decision boundary to separate 2 classes, the OC-SVM tries to find a hyperplane separating the Data from the Origin. The idea is to map the data into the kernel feature space and to separate it from the origin with maximum margin using a linear classifier in the kernel feature space. This corresponds to using a non-linear boundary in our original problem space." }, { "code": null, "e": 17127, "s": 16070, "text": "Let us briefly discuss the use of kernels in OC-SVM. The SVM is a Linear model. This allows it to make very simple decision rules. One way to increase the capacity of the SVM is to create polynomial features from data — and then to use the Linear SVM on the transformed feature space. The SVM still finds a linear boundary in the Polynomial feature space — but when mapped back to our original problem variable space, the decision boundary(which was linear in the polynomial feature space) looks non-linear. But we had to explicitly calculate the polynomial features — which can take large memory if we had a large number of features to begin with. Kernels allow us to fit simple models(like the linear SVM) in very high dimensional feature spaces without explicitly calculating the high dimensional features. One of the most widely used kernels is the RBF Kernel. The important thing to remember is that SVM always fits a linear model in the kernel feature space — even though the decision boundary looks non-linear in the original problem variable space." }, { "code": null, "e": 17174, "s": 17127, "text": "Here are some general points about the OC-SVM:" }, { "code": null, "e": 17451, "s": 17174, "text": "In general, it is advised to use a non-linear kernel when using OC-SVM. The RBF Kernel is widely used.Hyperparameters to tune for OC-SVM with RBF Kernel are: Gamma, νPrediction can be done using predict() and decision_function() methods. We will discuss more about them later." }, { "code": null, "e": 17554, "s": 17451, "text": "In general, it is advised to use a non-linear kernel when using OC-SVM. The RBF Kernel is widely used." }, { "code": null, "e": 17619, "s": 17554, "text": "Hyperparameters to tune for OC-SVM with RBF Kernel are: Gamma, ν" }, { "code": null, "e": 17730, "s": 17619, "text": "Prediction can be done using predict() and decision_function() methods. We will discuss more about them later." }, { "code": null, "e": 18064, "s": 17730, "text": "Gamma is a parameter specific to the RBF Kernel and it controls the effect of neighboring points on the decision boundary. Large values of Gamma allow neighboring points to have larger influence on the decision boundary and smaller values of Gamma allow both neighboring and distant points to have an effect on the decision boundary." }, { "code": null, "e": 18281, "s": 18064, "text": "Let us discuss the effect of using different values of Gamma. Larger values of Gamma cause models with large variance — which can come at the cost of Generalization. Let us vary Gamma and see the impact on the model." }, { "code": null, "e": 19792, "s": 18281, "text": "def plot_anomaly2(data, predicted, ax): data2 = data.copy() data2['Predicted'] = predicted normal = data2.loc[data2['Predicted'] == 1, :] anomalies = data2.loc[data2['Predicted'] == -1, :] # Make Scatterplot column1 = data.columns[0] column2 = data.columns[1] anomalies.plot.scatter(column1, column2, color = 'tomato', fontsize = 14, sharex = False, ax=ax) normal.plot.scatter(column1, column2, color = 'grey', fontsize = 14, sharex = False, ax = ax)#plt.grid(linestyle = '--') plt.xlabel(column1, fontsize = 14, weight = 'bold') plt.ylabel(column2, fontsize = 14, weight = 'bold') return ax# Create Fake data to classify x_fake = pd.DataFrame(np.random.uniform(-5, 19, (35000, 2)), columns = ['Var 1', 'Var 2'])# Visualize effect of changing Gammagammas = [.00005, .005, .01, .025, .05, .1,.3, .6, .9, 2, 5, 10]fig, axes = plt.subplots(2, 6, figsize = (25, 6), tight_layout = True)for i, ax in zip(range(len(gammas)), axes.flatten()): gamma = gammas[i] model = svm.OneClassSVM(kernel='rbf', degree=5, gamma=gamma, coef0=0.0, tol=0.001, nu=0.01, shrinking=True, cache_size=200, verbose=False, max_iter=- 1).fit(all_data)model_predictions = model.predict(x_fake) #x_fake['Predictions'] = model_predictionsax = plot_anomaly2(x_fake, model_predictions,ax) ax.scatter(all_data.iloc[:, 0], all_data.iloc[:, 1], color = 'k', s = 10) ax.set_title('Gamma: {}'.format(np.around(gamma,6)), weight = 'bold', fontsize = 14)" }, { "code": null, "e": 19929, "s": 19792, "text": "The Blue region in the following images refer to regions that the OC-SVM predicts as “Normal”. The red points are detected as anomalies." }, { "code": null, "e": 19955, "s": 19929, "text": "We Observe the following:" }, { "code": null, "e": 20151, "s": 19955, "text": "When gamma is extremely low or high, we see that the OC-SVM Misses at-least one of the major anomalies.For Mid-Gamma Values in the range of .005 to .1, the OC-SVM identifies both major anomalies." }, { "code": null, "e": 20255, "s": 20151, "text": "When gamma is extremely low or high, we see that the OC-SVM Misses at-least one of the major anomalies." }, { "code": null, "e": 20348, "s": 20255, "text": "For Mid-Gamma Values in the range of .005 to .1, the OC-SVM identifies both major anomalies." }, { "code": null, "e": 20490, "s": 20348, "text": "One way to select Gamma is to let sklearn choose Gamma. We do by selecting gamma = ‘scale’. Here is what happens when we set gamma = ‘scale’:" }, { "code": null, "e": 21066, "s": 20490, "text": "As discussed earlier, in OC-SVMs the data is separated from the origin in the kernel space using a linear decision boundary. A fraction(upto ν) of data are allowed to fall on the wrong side of the linear decision boundary. Basically, we want all the inliers to be one side of the decision boundary and all the outliers to be on the other side of the decision boundary. The decision_function method of the OC-SVM outputs the signed distance of a point from the decision boundary. This distance takes negative values for outliers and positive values for normal points(inliers)." }, { "code": null, "e": 21145, "s": 21066, "text": "Let us apply tukey’s method on the decision_function output as we did earlier." }, { "code": null, "e": 21570, "s": 21145, "text": "Here, luckily tukey’s method identified the 2 major anomalies that we had in our data. However, in the general case, it may identify additional or lesser anomalies. Anomalies identified by Tukey’s method depend on our value of ‘k’(discussed in the previous article) which can be tuned. it is sometimes useful to treat k as a hyperparameter in the ML pipeline — which can be finalized through domain analysis or Optimization." }, { "code": null, "e": 21874, "s": 21570, "text": "Till now we have discussed unsupervised methods of performing Anomaly detection. We discussed Isolation Forests and OC-SVM methods which are used to perform Multivariate Anomaly detection. One of the advantages of this methods is that they do not require the data to belong to a particular distribution." }, { "code": null, "e": 22194, "s": 21874, "text": "OC-SVM is a method which can be used for Unsupervised and Semi-Supervised Anomaly detection. In the next articles we will discuss Semi-Supervised and Supervised methods of performing Anomaly detection. They include using PCA, Auto-Encoders, OC-SVM and imbalanced Classification methods for performing Anomaly Detection." } ]
Count the maximum number of elements that can be selected from the array - GeeksforGeeks
14 Aug, 2021 Given an array arr[], the task is to count the maximum number of elements that can be selected from the given array following the below selection process: At 1st selection, select an element which is greater than or equal to 1. At 2nd selection, select an element which is greater than or equal to 2. At 3rd selection, select an element which is greater than or equal to 3 and so on. An element can be selected only once. The operation stops when it is not possible to select any element. So, the task is to maximize the count of selection from the array. Examples: Input : arr[] = { 4, 1, 3, 1 } Output : 3 1st Selection: 1 is selected as 1 >= 1. 2nd Selection: 3 is selected as 3 >= 2. 3rd Selection: 4 is selected as 4 >= 3. No more selections are possible. Therefore, the answers is 3. Input : arr[] = { 2, 1, 1, 2, 1 } Output : 2 Approach: In order to maximize the count of selection it is necessary to select the smallest possible numbers first and then the bigger numbers if the selection is not possible. This can be done easily by sorting the array. Now, loop through the array and increment the result by 1 when the element is greater than or equal to the number to select for the current operation. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the maximum count of// selection possible from the given array// following the given processint maxSelectionCount(int a[], int n){ // Initialize result int res = 0; // Sorting the array sort(a, a + n); // Initialize the select variable int select = 1; // Loop through array for (int i = 0; i < n; i++) { // If selection is possible if (a[i] >= select) { res++; // Increment result select++; // Increment selection variable } } return res;} // Driver Codeint main(){ int arr[] = { 4, 2, 1, 3, 5, 1, 4 }; int N = sizeof(arr) / sizeof(arr[0]); cout << maxSelectionCount(arr, N); return 0;} // Java implementation of the approachimport java.util.*; class GFG{ // Function to return the maximum count of // selection possible from the given array // following the given process static int maxSelectionCount(int a[], int n) { // Initialize result int res = 0; // Sorting the array Arrays.sort(a); // Initialize the select variable int select = 1; // Loop through array for (int i = 0; i < n; i++) { // If selection is possible if (a[i] >= select) { res++; // Increment result select++; // Increment selection variable } } return res; } // Driver Code public static void main(String[] args) { int arr[] = {4, 2, 1, 3, 5, 1, 4}; int N = arr.length; System.out.println(maxSelectionCount(arr, N)); }} // This code contributed by Rajput-Ji # Python implementation of the approach # Function to return the maximum count of# selection possible from the given array# following the given processdef maxSelectionCount(a, n): # Initialize result res = 0; # Sorting the array a.sort(); # Initialize the select variable select = 1; # Loop through array for i in range(n): # If selection is possible if (a[i] >= select): res += 1; # Increment result select += 1; # Increment selection variable return res; # Driver Codearr = [ 4, 2, 1, 3, 5, 1, 4 ];N = len(arr);print(maxSelectionCount(arr, N)); # This code contributed by PrinciRaj1992 // C# implementation of the approachusing System; class GFG{ // Function to return the maximum count of // selection possible from the given array // following the given process static int maxSelectionCount(int []a, int n) { // Initialize result int res = 0; // Sorting the array Array.Sort(a); // Initialize the select variable int select = 1; // Loop through array for (int i = 0; i < n; i++) { // If selection is possible if (a[i] >= select) { res++; // Increment result select++; // Increment selection variable } } return res; } // Driver Code public static void Main() { int []arr = {4, 2, 1, 3, 5, 1, 4}; int N = arr.Length; Console.WriteLine(maxSelectionCount(arr, N)); }} // This code contributed by AnkitRai01 <script> // Javascript implementation of the approach // Function to return the maximum count of// selection possible from the given array// following the given processfunction maxSelectionCount(a, n){ // Initialize result var res = 0; // Sorting the array a.sort(); // Initialize the select variable var select = 1; // Loop through array for(var i = 0; i < n; i++) { // If selection is possible if (a[i] >= select) { // Increment result res++; // Increment selection variable select++; } } return res;} // Driver Codevar arr = [ 4, 2, 1, 3, 5, 1, 4 ];var N = arr.length; document.write(maxSelectionCount(arr, N)); // This code is contributed by rrrtnx </script> 5 Time Complexity: O(N * log(N))Auxiliary Space: O(1) Arrays Data Structures Sorting Data Structures Arrays Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Next Greater Element Window Sliding Technique Count pairs with given sum Program to find sum of elements in a given array Reversal algorithm for array rotation SDE SHEET - A Complete Guide for SDE Preparation DSA Sheet by Love Babbar Doubly Linked List | Set 1 (Introduction and Insertion) Implementing a Linked List in Java using Class Introduction to Algorithms
[ { "code": null, "e": 24405, "s": 24377, "text": "\n14 Aug, 2021" }, { "code": null, "e": 24561, "s": 24405, "text": "Given an array arr[], the task is to count the maximum number of elements that can be selected from the given array following the below selection process: " }, { "code": null, "e": 24634, "s": 24561, "text": "At 1st selection, select an element which is greater than or equal to 1." }, { "code": null, "e": 24707, "s": 24634, "text": "At 2nd selection, select an element which is greater than or equal to 2." }, { "code": null, "e": 24790, "s": 24707, "text": "At 3rd selection, select an element which is greater than or equal to 3 and so on." }, { "code": null, "e": 24962, "s": 24790, "text": "An element can be selected only once. The operation stops when it is not possible to select any element. So, the task is to maximize the count of selection from the array." }, { "code": null, "e": 24973, "s": 24962, "text": "Examples: " }, { "code": null, "e": 25198, "s": 24973, "text": "Input : arr[] = { 4, 1, 3, 1 } Output : 3 1st Selection: 1 is selected as 1 >= 1. 2nd Selection: 3 is selected as 3 >= 2. 3rd Selection: 4 is selected as 4 >= 3. No more selections are possible. Therefore, the answers is 3. " }, { "code": null, "e": 25245, "s": 25198, "text": "Input : arr[] = { 2, 1, 1, 2, 1 } Output : 2 " }, { "code": null, "e": 25620, "s": 25245, "text": "Approach: In order to maximize the count of selection it is necessary to select the smallest possible numbers first and then the bigger numbers if the selection is not possible. This can be done easily by sorting the array. Now, loop through the array and increment the result by 1 when the element is greater than or equal to the number to select for the current operation." }, { "code": null, "e": 25673, "s": 25620, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 25677, "s": 25673, "text": "C++" }, { "code": null, "e": 25682, "s": 25677, "text": "Java" }, { "code": null, "e": 25690, "s": 25682, "text": "Python3" }, { "code": null, "e": 25693, "s": 25690, "text": "C#" }, { "code": null, "e": 25704, "s": 25693, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the maximum count of// selection possible from the given array// following the given processint maxSelectionCount(int a[], int n){ // Initialize result int res = 0; // Sorting the array sort(a, a + n); // Initialize the select variable int select = 1; // Loop through array for (int i = 0; i < n; i++) { // If selection is possible if (a[i] >= select) { res++; // Increment result select++; // Increment selection variable } } return res;} // Driver Codeint main(){ int arr[] = { 4, 2, 1, 3, 5, 1, 4 }; int N = sizeof(arr) / sizeof(arr[0]); cout << maxSelectionCount(arr, N); return 0;}", "e": 26487, "s": 25704, "text": null }, { "code": "// Java implementation of the approachimport java.util.*; class GFG{ // Function to return the maximum count of // selection possible from the given array // following the given process static int maxSelectionCount(int a[], int n) { // Initialize result int res = 0; // Sorting the array Arrays.sort(a); // Initialize the select variable int select = 1; // Loop through array for (int i = 0; i < n; i++) { // If selection is possible if (a[i] >= select) { res++; // Increment result select++; // Increment selection variable } } return res; } // Driver Code public static void main(String[] args) { int arr[] = {4, 2, 1, 3, 5, 1, 4}; int N = arr.length; System.out.println(maxSelectionCount(arr, N)); }} // This code contributed by Rajput-Ji", "e": 27439, "s": 26487, "text": null }, { "code": "# Python implementation of the approach # Function to return the maximum count of# selection possible from the given array# following the given processdef maxSelectionCount(a, n): # Initialize result res = 0; # Sorting the array a.sort(); # Initialize the select variable select = 1; # Loop through array for i in range(n): # If selection is possible if (a[i] >= select): res += 1; # Increment result select += 1; # Increment selection variable return res; # Driver Codearr = [ 4, 2, 1, 3, 5, 1, 4 ];N = len(arr);print(maxSelectionCount(arr, N)); # This code contributed by PrinciRaj1992", "e": 28095, "s": 27439, "text": null }, { "code": "// C# implementation of the approachusing System; class GFG{ // Function to return the maximum count of // selection possible from the given array // following the given process static int maxSelectionCount(int []a, int n) { // Initialize result int res = 0; // Sorting the array Array.Sort(a); // Initialize the select variable int select = 1; // Loop through array for (int i = 0; i < n; i++) { // If selection is possible if (a[i] >= select) { res++; // Increment result select++; // Increment selection variable } } return res; } // Driver Code public static void Main() { int []arr = {4, 2, 1, 3, 5, 1, 4}; int N = arr.Length; Console.WriteLine(maxSelectionCount(arr, N)); }} // This code contributed by AnkitRai01", "e": 29024, "s": 28095, "text": null }, { "code": "<script> // Javascript implementation of the approach // Function to return the maximum count of// selection possible from the given array// following the given processfunction maxSelectionCount(a, n){ // Initialize result var res = 0; // Sorting the array a.sort(); // Initialize the select variable var select = 1; // Loop through array for(var i = 0; i < n; i++) { // If selection is possible if (a[i] >= select) { // Increment result res++; // Increment selection variable select++; } } return res;} // Driver Codevar arr = [ 4, 2, 1, 3, 5, 1, 4 ];var N = arr.length; document.write(maxSelectionCount(arr, N)); // This code is contributed by rrrtnx </script>", "e": 29822, "s": 29024, "text": null }, { "code": null, "e": 29824, "s": 29822, "text": "5" }, { "code": null, "e": 29880, "s": 29826, "text": "Time Complexity: O(N * log(N))Auxiliary Space: O(1) " }, { "code": null, "e": 29887, "s": 29880, "text": "Arrays" }, { "code": null, "e": 29903, "s": 29887, "text": "Data Structures" }, { "code": null, "e": 29911, "s": 29903, "text": "Sorting" }, { "code": null, "e": 29927, "s": 29911, "text": "Data Structures" }, { "code": null, "e": 29934, "s": 29927, "text": "Arrays" }, { "code": null, "e": 29942, "s": 29934, "text": "Sorting" }, { "code": null, "e": 30040, "s": 29942, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30049, "s": 30040, "text": "Comments" }, { "code": null, "e": 30062, "s": 30049, "text": "Old Comments" }, { "code": null, "e": 30083, "s": 30062, "text": "Next Greater Element" }, { "code": null, "e": 30108, "s": 30083, "text": "Window Sliding Technique" }, { "code": null, "e": 30135, "s": 30108, "text": "Count pairs with given sum" }, { "code": null, "e": 30184, "s": 30135, "text": "Program to find sum of elements in a given array" }, { "code": null, "e": 30222, "s": 30184, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 30271, "s": 30222, "text": "SDE SHEET - A Complete Guide for SDE Preparation" }, { "code": null, "e": 30296, "s": 30271, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 30352, "s": 30296, "text": "Doubly Linked List | Set 1 (Introduction and Insertion)" }, { "code": null, "e": 30399, "s": 30352, "text": "Implementing a Linked List in Java using Class" } ]
C++ static member variables and their initialization
Static C++ member variables are defined using the static keyword. The static member variables in a class are shared by all the class objects as there is only one copy of them in the memory, regardless of the number of objects of the class. The static class member variables are initialized to zero when the first object of the class is created if they are not initialized in any other way. A program that demonstrates static member variables and their initialization in C++ is given as follows. Live Demo #include <iostream> using namespace std; class Demo { public : static int num; int display() { cout << "The value of the static member variable num is: " << num; } }; int Demo::num = 100; int main() { Demo obj; obj.display(); return 0; } The output of the above program is as follows. The value of the static member variable num is: 100 Now let us understand the above program. In the class Demo, the static class member variable is num. The function display() prints the value of num. The code snippet that shows this is as follows. class Demo { public : static int num; int display() { cout << "The value of the static member variable num is: " << num; } }; int Demo::num = 100; In the function main(), an object obj of class Demo is created. Then the function display() is called that displays the value of num. The code snippet that shows this is as follows. int main() { Demo obj; obj.display(); return 0; }
[ { "code": null, "e": 1302, "s": 1062, "text": "Static C++ member variables are defined using the static keyword. The static member variables in a class are shared by all the class objects as there is only one copy of them in the memory, regardless of the number of objects of the class." }, { "code": null, "e": 1452, "s": 1302, "text": "The static class member variables are initialized to zero when the first object of the class is created if they are not initialized in any other way." }, { "code": null, "e": 1557, "s": 1452, "text": "A program that demonstrates static member variables and their initialization in C++ is given as follows." }, { "code": null, "e": 1568, "s": 1557, "text": " Live Demo" }, { "code": null, "e": 1833, "s": 1568, "text": "#include <iostream>\nusing namespace std;\nclass Demo {\n public :\n static int num;\n int display() {\n cout << \"The value of the static member variable num is: \" << num;\n }\n};\nint Demo::num = 100;\nint main() {\n Demo obj;\n obj.display();\n return 0;\n}" }, { "code": null, "e": 1880, "s": 1833, "text": "The output of the above program is as follows." }, { "code": null, "e": 1932, "s": 1880, "text": "The value of the static member variable num is: 100" }, { "code": null, "e": 1973, "s": 1932, "text": "Now let us understand the above program." }, { "code": null, "e": 2129, "s": 1973, "text": "In the class Demo, the static class member variable is num. The function display() prints the value of num. The code snippet that shows this is as follows." }, { "code": null, "e": 2294, "s": 2129, "text": "class Demo {\n public :\n static int num;\n int display() {\n cout << \"The value of the static member variable num is: \" << num;\n }\n};\nint Demo::num = 100;" }, { "code": null, "e": 2476, "s": 2294, "text": "In the function main(), an object obj of class Demo is created. Then the function display() is called that displays the value of num. The code snippet that shows this is as follows." }, { "code": null, "e": 2535, "s": 2476, "text": "int main() {\n Demo obj;\n obj.display();\n return 0;\n}" } ]
How to Plot Logarithmic Axes in Matplotlib? - GeeksforGeeks
21 Jan, 2021 Axes’ in all plots using Matplotlib are linear by default, yscale() and xscale() method of the matplotlib.pyplot library can be used to change the y-axis or x-axis scale to logarithmic respectively. The method yscale() or xscale() takes a single value as a parameter which is the type of conversion of the scale, to convert axes to logarithmic scale we pass the “log” keyword or the matplotlib.scale. LogScale class to the yscale or xscale method. xscale method syntax: Syntax : matplotlib.pyplot.xscale(value, **kwargs) Parameters: Value = { “linear”, “log”, “symlog”, “logit”, ... } **kwargs = Different keyword arguments are accepted, depending on the scale (matplotlib.scale.LinearScale, LogScale, SymmetricalLogScale, LogitScale) Returns : Converts the x-axes to the given scale type. (Here we use the “log” scale type) yscale method syntax: Syntax: matplotlib.pyplot.yscale(value, **kwargs) Parameters: value = { “linear”, “log”, “symlog”, “logit”, ... } **kwargs = Different keyword arguments are accepted, depending on the scale (matplotlib.scale.LinearScale, LogScale, SymmetricalLogScale, LogitScale) Returns : Converts the y-axes to the given scale type. (Here we use the “log” scale type) Given below are the implementation for converting the y-axis and x-axis to logarithmic scale respectively. Example 1: Without Logarithmic Axes. Python3 import matplotlib.pyplot as plt # exponential function y = 10^xdata = [10**i for i in range(5)] plt.plot(data) Output: Example 2: y-axis Logarithmic Scale. Python3 import matplotlib.pyplot as plt # exponential function y = 10^xdata = [10**i for i in range(5)] # convert y-axis to Logarithmic scaleplt.yscale("log") plt.plot(data) Output: Example 3: x-axis Logarithmic Scale. Python3 import matplotlib.pyplot as plt # exponential function x = 10^ydatax = [ 10**i for i in range(5)]datay = [ i for i in range(5)] #convert x-axis to Logarithmic scaleplt.xscale("log") plt.plot(datax,datay) Output: pragup Picked Python-matplotlib Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python Different ways to create Pandas Dataframe Python String | replace() Python program to convert a list to string Reading and Writing to text files in Python sum() function in Python
[ { "code": null, "e": 23751, "s": 23723, "text": "\n21 Jan, 2021" }, { "code": null, "e": 23950, "s": 23751, "text": "Axes’ in all plots using Matplotlib are linear by default, yscale() and xscale() method of the matplotlib.pyplot library can be used to change the y-axis or x-axis scale to logarithmic respectively." }, { "code": null, "e": 24199, "s": 23950, "text": "The method yscale() or xscale() takes a single value as a parameter which is the type of conversion of the scale, to convert axes to logarithmic scale we pass the “log” keyword or the matplotlib.scale. LogScale class to the yscale or xscale method." }, { "code": null, "e": 24221, "s": 24199, "text": "xscale method syntax:" }, { "code": null, "e": 24272, "s": 24221, "text": "Syntax : matplotlib.pyplot.xscale(value, **kwargs)" }, { "code": null, "e": 24284, "s": 24272, "text": "Parameters:" }, { "code": null, "e": 24336, "s": 24284, "text": "Value = { “linear”, “log”, “symlog”, “logit”, ... }" }, { "code": null, "e": 24486, "s": 24336, "text": "**kwargs = Different keyword arguments are accepted, depending on the scale (matplotlib.scale.LinearScale, LogScale, SymmetricalLogScale, LogitScale)" }, { "code": null, "e": 24576, "s": 24486, "text": "Returns : Converts the x-axes to the given scale type. (Here we use the “log” scale type)" }, { "code": null, "e": 24598, "s": 24576, "text": "yscale method syntax:" }, { "code": null, "e": 24648, "s": 24598, "text": "Syntax: matplotlib.pyplot.yscale(value, **kwargs)" }, { "code": null, "e": 24660, "s": 24648, "text": "Parameters:" }, { "code": null, "e": 24712, "s": 24660, "text": "value = { “linear”, “log”, “symlog”, “logit”, ... }" }, { "code": null, "e": 24862, "s": 24712, "text": "**kwargs = Different keyword arguments are accepted, depending on the scale (matplotlib.scale.LinearScale, LogScale, SymmetricalLogScale, LogitScale)" }, { "code": null, "e": 24952, "s": 24862, "text": "Returns : Converts the y-axes to the given scale type. (Here we use the “log” scale type)" }, { "code": null, "e": 25059, "s": 24952, "text": "Given below are the implementation for converting the y-axis and x-axis to logarithmic scale respectively." }, { "code": null, "e": 25097, "s": 25059, "text": "Example 1: Without Logarithmic Axes. " }, { "code": null, "e": 25105, "s": 25097, "text": "Python3" }, { "code": "import matplotlib.pyplot as plt # exponential function y = 10^xdata = [10**i for i in range(5)] plt.plot(data)", "e": 25216, "s": 25105, "text": null }, { "code": null, "e": 25225, "s": 25216, "text": "Output: " }, { "code": null, "e": 25262, "s": 25225, "text": "Example 2: y-axis Logarithmic Scale." }, { "code": null, "e": 25270, "s": 25262, "text": "Python3" }, { "code": "import matplotlib.pyplot as plt # exponential function y = 10^xdata = [10**i for i in range(5)] # convert y-axis to Logarithmic scaleplt.yscale(\"log\") plt.plot(data)", "e": 25436, "s": 25270, "text": null }, { "code": null, "e": 25445, "s": 25436, "text": "Output: " }, { "code": null, "e": 25483, "s": 25445, "text": "Example 3: x-axis Logarithmic Scale. " }, { "code": null, "e": 25491, "s": 25483, "text": "Python3" }, { "code": "import matplotlib.pyplot as plt # exponential function x = 10^ydatax = [ 10**i for i in range(5)]datay = [ i for i in range(5)] #convert x-axis to Logarithmic scaleplt.xscale(\"log\") plt.plot(datax,datay)", "e": 25695, "s": 25491, "text": null }, { "code": null, "e": 25707, "s": 25698, "text": "Output: " }, { "code": null, "e": 25718, "s": 25711, "text": "pragup" }, { "code": null, "e": 25725, "s": 25718, "text": "Picked" }, { "code": null, "e": 25743, "s": 25725, "text": "Python-matplotlib" }, { "code": null, "e": 25750, "s": 25743, "text": "Python" }, { "code": null, "e": 25848, "s": 25750, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25857, "s": 25848, "text": "Comments" }, { "code": null, "e": 25870, "s": 25857, "text": "Old Comments" }, { "code": null, "e": 25888, "s": 25870, "text": "Python Dictionary" }, { "code": null, "e": 25923, "s": 25888, "text": "Read a file line by line in Python" }, { "code": null, "e": 25945, "s": 25923, "text": "Enumerate() in Python" }, { "code": null, "e": 25977, "s": 25945, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26007, "s": 25977, "text": "Iterate over a list in Python" }, { "code": null, "e": 26049, "s": 26007, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 26075, "s": 26049, "text": "Python String | replace()" }, { "code": null, "e": 26118, "s": 26075, "text": "Python program to convert a list to string" }, { "code": null, "e": 26162, "s": 26118, "text": "Reading and Writing to text files in Python" } ]
sympy.log() method in Python - GeeksforGeeks
29 Jul, 2020 With the help of sympy.log() function, we can simplify the principal branch of the natural logarithm. Logarithms are taken with the natural base, e. To get a logarithm of a different base b, use log(x, y), which is essentially short-hand for log(x) / log(y). Syntax : sympy.log() Return : Return the simplified mathematical expression. Example #1 : Python3 # import sympy from sympy import * # Use sympy.log() method gfg = log(16, 2) print(gfg) Output : 4 Example #2 : Python3 # import sympy from sympy import * # Use sympy.log() method gfg = log(S(8) / 3, 2) print(gfg) Output : - log(3)/log(2) + 3 SymPy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install PIP on Windows ? How to drop one or multiple columns in Pandas Dataframe Python OOPs Concepts Python | Get unique values from a list Check if element exists in list in Python Python Classes and Objects Python | os.path.join() method How To Convert Python Dictionary To JSON? Python | Pandas dataframe.groupby() Create a directory in Python
[ { "code": null, "e": 24212, "s": 24184, "text": "\n29 Jul, 2020" }, { "code": null, "e": 24472, "s": 24212, "text": "With the help of sympy.log() function, we can simplify the principal branch of the natural logarithm. Logarithms are taken with the natural base, e. To get a logarithm of a different base b, use log(x, y), which is essentially short-hand for log(x) / log(y). " }, { "code": null, "e": 24494, "s": 24472, "text": "Syntax : sympy.log() " }, { "code": null, "e": 24552, "s": 24494, "text": "Return : Return the simplified mathematical expression. " }, { "code": null, "e": 24567, "s": 24552, "text": "Example #1 : " }, { "code": null, "e": 24575, "s": 24567, "text": "Python3" }, { "code": "# import sympy from sympy import * # Use sympy.log() method gfg = log(16, 2) print(gfg)", "e": 24671, "s": 24575, "text": null }, { "code": null, "e": 24682, "s": 24671, "text": "Output : " }, { "code": null, "e": 24685, "s": 24682, "text": "4\n" }, { "code": null, "e": 24699, "s": 24685, "text": "Example #2 : " }, { "code": null, "e": 24707, "s": 24699, "text": "Python3" }, { "code": "# import sympy from sympy import * # Use sympy.log() method gfg = log(S(8) / 3, 2) print(gfg)", "e": 24809, "s": 24707, "text": null }, { "code": null, "e": 24819, "s": 24809, "text": "Output : " }, { "code": null, "e": 24840, "s": 24819, "text": "- log(3)/log(2) + 3\n" }, { "code": null, "e": 24846, "s": 24840, "text": "SymPy" }, { "code": null, "e": 24853, "s": 24846, "text": "Python" }, { "code": null, "e": 24951, "s": 24853, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 24960, "s": 24951, "text": "Comments" }, { "code": null, "e": 24973, "s": 24960, "text": "Old Comments" }, { "code": null, "e": 25005, "s": 24973, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 25061, "s": 25005, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 25082, "s": 25061, "text": "Python OOPs Concepts" }, { "code": null, "e": 25121, "s": 25082, "text": "Python | Get unique values from a list" }, { "code": null, "e": 25163, "s": 25121, "text": "Check if element exists in list in Python" }, { "code": null, "e": 25190, "s": 25163, "text": "Python Classes and Objects" }, { "code": null, "e": 25221, "s": 25190, "text": "Python | os.path.join() method" }, { "code": null, "e": 25263, "s": 25221, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 25299, "s": 25263, "text": "Python | Pandas dataframe.groupby()" } ]
SQL - Group By
The SQL GROUP BY clause is used in collaboration with the SELECT statement to arrange identical data into groups. This GROUP BY clause follows the WHERE clause in a SELECT statement and precedes the ORDER BY clause. The basic syntax of a GROUP BY clause is shown in the following code block. The GROUP BY clause must follow the conditions in the WHERE clause and must precede the ORDER BY clause if one is used. SELECT column1, column2 FROM table_name WHERE [ conditions ] GROUP BY column1, column2 ORDER BY column1, column2 Consider the CUSTOMERS table is having the following records − +----+----------+-----+-----------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+-----------+----------+ | 1 | Ramesh | 32 | Ahmedabad | 2000.00 | | 2 | Khilan | 25 | Delhi | 1500.00 | | 3 | kaushik | 23 | Kota | 2000.00 | | 4 | Chaitali | 25 | Mumbai | 6500.00 | | 5 | Hardik | 27 | Bhopal | 8500.00 | | 6 | Komal | 22 | MP | 4500.00 | | 7 | Muffy | 24 | Indore | 10000.00 | +----+----------+-----+-----------+----------+ If you want to know the total amount of the salary on each customer, then the GROUP BY query would be as follows. SQL> SELECT NAME, SUM(SALARY) FROM CUSTOMERS GROUP BY NAME; This would produce the following result − +----------+-------------+ | NAME | SUM(SALARY) | +----------+-------------+ | Chaitali | 6500.00 | | Hardik | 8500.00 | | kaushik | 2000.00 | | Khilan | 1500.00 | | Komal | 4500.00 | | Muffy | 10000.00 | | Ramesh | 2000.00 | +----------+-------------+ Now, let us look at a table where the CUSTOMERS table has the following records with duplicate names − +----+----------+-----+-----------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+-----------+----------+ | 1 | Ramesh | 32 | Ahmedabad | 2000.00 | | 2 | Ramesh | 25 | Delhi | 1500.00 | | 3 | kaushik | 23 | Kota | 2000.00 | | 4 | kaushik | 25 | Mumbai | 6500.00 | | 5 | Hardik | 27 | Bhopal | 8500.00 | | 6 | Komal | 22 | MP | 4500.00 | | 7 | Muffy | 24 | Indore | 10000.00 | +----+----------+-----+-----------+----------+ Now again, if you want to know the total amount of salary on each customer, then the GROUP BY query would be as follows − SQL> SELECT NAME, SUM(SALARY) FROM CUSTOMERS GROUP BY NAME; This would produce the following result − +---------+-------------+ | NAME | SUM(SALARY) | +---------+-------------+ | Hardik | 8500.00 | | kaushik | 8500.00 | | Komal | 4500.00 | | Muffy | 10000.00 | | Ramesh | 3500.00 | +---------+-------------+ 42 Lectures 5 hours Anadi Sharma 14 Lectures 2 hours Anadi Sharma 44 Lectures 4.5 hours Anadi Sharma 94 Lectures 7 hours Abhishek And Pukhraj 80 Lectures 6.5 hours Oracle Master Training | 150,000+ Students Worldwide 31 Lectures 6 hours Eduonix Learning Solutions Print Add Notes Bookmark this page
[ { "code": null, "e": 2669, "s": 2453, "text": "The SQL GROUP BY clause is used in collaboration with the SELECT statement to arrange identical data into groups. This GROUP BY clause follows the WHERE clause in a SELECT statement and precedes the ORDER BY clause." }, { "code": null, "e": 2865, "s": 2669, "text": "The basic syntax of a GROUP BY clause is shown in the following code block. The GROUP BY clause must follow the conditions in the WHERE clause and must precede the ORDER BY clause if one is used." }, { "code": null, "e": 2979, "s": 2865, "text": "SELECT column1, column2\nFROM table_name\nWHERE [ conditions ]\nGROUP BY column1, column2\nORDER BY column1, column2\n" }, { "code": null, "e": 3042, "s": 2979, "text": "Consider the CUSTOMERS table is having the following records −" }, { "code": null, "e": 3560, "s": 3042, "text": "+----+----------+-----+-----------+----------+\n| ID | NAME | AGE | ADDRESS | SALARY |\n+----+----------+-----+-----------+----------+\n| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |\n| 2 | Khilan | 25 | Delhi | 1500.00 |\n| 3 | kaushik | 23 | Kota | 2000.00 |\n| 4 | Chaitali | 25 | Mumbai | 6500.00 |\n| 5 | Hardik | 27 | Bhopal | 8500.00 |\n| 6 | Komal | 22 | MP | 4500.00 |\n| 7 | Muffy | 24 | Indore | 10000.00 |\n+----+----------+-----+-----------+----------+\n" }, { "code": null, "e": 3674, "s": 3560, "text": "If you want to know the total amount of the salary on each customer, then the GROUP BY query would be as follows." }, { "code": null, "e": 3737, "s": 3674, "text": "SQL> SELECT NAME, SUM(SALARY) FROM CUSTOMERS\n GROUP BY NAME;" }, { "code": null, "e": 3779, "s": 3737, "text": "This would produce the following result −" }, { "code": null, "e": 4077, "s": 3779, "text": "+----------+-------------+\n| NAME | SUM(SALARY) |\n+----------+-------------+\n| Chaitali | 6500.00 |\n| Hardik | 8500.00 |\n| kaushik | 2000.00 |\n| Khilan | 1500.00 |\n| Komal | 4500.00 |\n| Muffy | 10000.00 |\n| Ramesh | 2000.00 |\n+----------+-------------+\n" }, { "code": null, "e": 4180, "s": 4077, "text": "Now, let us look at a table where the CUSTOMERS table has the following records with duplicate names −" }, { "code": null, "e": 4697, "s": 4180, "text": "+----+----------+-----+-----------+----------+\n| ID | NAME | AGE | ADDRESS | SALARY |\n+----+----------+-----+-----------+----------+\n| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |\n| 2 | Ramesh | 25 | Delhi | 1500.00 |\n| 3 | kaushik | 23 | Kota | 2000.00 |\n| 4 | kaushik | 25 | Mumbai | 6500.00 |\n| 5 | Hardik | 27 | Bhopal | 8500.00 |\n| 6 | Komal | 22 | MP | 4500.00 |\n| 7 | Muffy | 24 | Indore | 10000.00 |\n+----+----------+-----+-----------+----------+" }, { "code": null, "e": 4819, "s": 4697, "text": "Now again, if you want to know the total amount of salary on each customer, then the GROUP BY query would be as follows −" }, { "code": null, "e": 4882, "s": 4819, "text": "SQL> SELECT NAME, SUM(SALARY) FROM CUSTOMERS\n GROUP BY NAME;" }, { "code": null, "e": 4924, "s": 4882, "text": "This would produce the following result −" }, { "code": null, "e": 5159, "s": 4924, "text": "+---------+-------------+\n| NAME | SUM(SALARY) |\n+---------+-------------+\n| Hardik | 8500.00 |\n| kaushik | 8500.00 |\n| Komal | 4500.00 |\n| Muffy | 10000.00 |\n| Ramesh | 3500.00 |\n+---------+-------------+\n" }, { "code": null, "e": 5192, "s": 5159, "text": "\n 42 Lectures \n 5 hours \n" }, { "code": null, "e": 5206, "s": 5192, "text": " Anadi Sharma" }, { "code": null, "e": 5239, "s": 5206, "text": "\n 14 Lectures \n 2 hours \n" }, { "code": null, "e": 5253, "s": 5239, "text": " Anadi Sharma" }, { "code": null, "e": 5288, "s": 5253, "text": "\n 44 Lectures \n 4.5 hours \n" }, { "code": null, "e": 5302, "s": 5288, "text": " Anadi Sharma" }, { "code": null, "e": 5335, "s": 5302, "text": "\n 94 Lectures \n 7 hours \n" }, { "code": null, "e": 5357, "s": 5335, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 5392, "s": 5357, "text": "\n 80 Lectures \n 6.5 hours \n" }, { "code": null, "e": 5446, "s": 5392, "text": " Oracle Master Training | 150,000+ Students Worldwide" }, { "code": null, "e": 5479, "s": 5446, "text": "\n 31 Lectures \n 6 hours \n" }, { "code": null, "e": 5507, "s": 5479, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 5514, "s": 5507, "text": " Print" }, { "code": null, "e": 5525, "s": 5514, "text": " Add Notes" } ]
Random.NextDouble() Method in C#
The Random.NextDouble() method in C# is used to return a random floating-point number that is greater than or equal to 0.0, and less than 1.0. The syntax is as follows − public virtual double NextDouble (); Let us now see an example − Live Demo using System; public class Demo { public static void Main(){ Random r1 = new Random(); Random r2 = new Random(); Byte[] arr = new Byte[2]; r1.NextBytes(arr); Console.WriteLine("Random numbers in the byte array..."); for (int i = 0; i < 2; i++) Console.WriteLine(arr[i]); Console.WriteLine("\nRandom floating point numbers..."); for (int i = 0; i < 5; i++) Console.WriteLine(r2.NextDouble()); } } This will produce the following output − Random numbers in the byte array... 124 141 Random floating point numbers... 0.93591266727816 0.36406785872023 0.122396959514542 0.795166163144245 0.954394097884369 Let us now see another example − Live Demo using System; public class Demo { public static void Main(){ int[] val = new int[7]; Random r = new Random(); double d; for (int i = 0; i 50; i++) { d = r.NextDouble(); val[(int) Math.Ceiling(d*5)] ++; } Console.WriteLine("Random Numbers..."); for (int i = 0; i < 7; i++) Console.WriteLine(val[i]); } } This will produce the following output − Random Numbers... 0 13 9 12 8 8 0
[ { "code": null, "e": 1205, "s": 1062, "text": "The Random.NextDouble() method in C# is used to return a random floating-point number that is greater than or equal to 0.0, and less than 1.0." }, { "code": null, "e": 1232, "s": 1205, "text": "The syntax is as follows −" }, { "code": null, "e": 1269, "s": 1232, "text": "public virtual double NextDouble ();" }, { "code": null, "e": 1297, "s": 1269, "text": "Let us now see an example −" }, { "code": null, "e": 1308, "s": 1297, "text": " Live Demo" }, { "code": null, "e": 1776, "s": 1308, "text": "using System;\npublic class Demo {\n public static void Main(){\n Random r1 = new Random();\n Random r2 = new Random();\n Byte[] arr = new Byte[2];\n r1.NextBytes(arr);\n Console.WriteLine(\"Random numbers in the byte array...\");\n for (int i = 0; i < 2; i++)\n Console.WriteLine(arr[i]);\n Console.WriteLine(\"\\nRandom floating point numbers...\");\n for (int i = 0; i < 5; i++)\n Console.WriteLine(r2.NextDouble());\n }\n}" }, { "code": null, "e": 1817, "s": 1776, "text": "This will produce the following output −" }, { "code": null, "e": 1982, "s": 1817, "text": "Random numbers in the byte array...\n124\n141\nRandom floating point numbers...\n0.93591266727816\n0.36406785872023\n0.122396959514542\n0.795166163144245\n0.954394097884369" }, { "code": null, "e": 2015, "s": 1982, "text": "Let us now see another example −" }, { "code": null, "e": 2026, "s": 2015, "text": " Live Demo" }, { "code": null, "e": 2404, "s": 2026, "text": "using System;\npublic class Demo {\n public static void Main(){\n int[] val = new int[7];\n Random r = new Random();\n double d;\n for (int i = 0; i 50; i++) {\n d = r.NextDouble();\n val[(int) Math.Ceiling(d*5)] ++;\n }\n Console.WriteLine(\"Random Numbers...\");\n for (int i = 0; i < 7; i++)\n Console.WriteLine(val[i]);\n }\n}" }, { "code": null, "e": 2445, "s": 2404, "text": "This will produce the following output −" }, { "code": null, "e": 2479, "s": 2445, "text": "Random Numbers...\n0\n13\n9\n12\n8\n8\n0" } ]
Changing Layouts Based on Screen Size using CSS
To change the layouts based on screen size in CSS, the code is as follows − Live Demo <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1" /> <style> body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; } * { box-sizing: border-box; } .col { color: white; float: left; width: 25%; padding: 10px; } .colContainer:after { content: ""; display: table; clear: both; } @media screen and (max-width: 900px) { .col { width: 50%; } } @media screen and (max-width: 600px) { .col { width: 100%; } } </style> </head> <body> <h1>Changing layout on screen size using CSS</h1> <h2>Resize the screen to see the below divs resize themselves</h2> <div class="colContainer"> <div class="col" style="background-color: rgb(153, 29, 224);"> <h2>First col</h2> </div> <div class="col" style="background-color: rgb(12, 126, 120);"> <h2>Second col</h2> </div> <div class="col" style="background-color: rgb(207, 41, 91);"> <h2>Third col</h2> </div> <div class="col" style="background-color: rgb(204, 91, 39);"> <h2>Fourth col</h2> </div> </div> </body> </html> The above code will produce the following output −
[ { "code": null, "e": 1138, "s": 1062, "text": "To change the layouts based on screen size in CSS, the code is as follows −" }, { "code": null, "e": 1149, "s": 1138, "text": " Live Demo" }, { "code": null, "e": 2211, "s": 1149, "text": "<!DOCTYPE html>\n<html>\n<head>\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n<style>\nbody {\n font-family: \"Segoe UI\", Tahoma, Geneva, Verdana, sans-serif;\n}\n* {\n box-sizing: border-box;\n}\n.col {\n color: white;\n float: left;\n width: 25%;\n padding: 10px;\n}\n.colContainer:after {\n content: \"\";\n display: table;\n clear: both;\n}\n@media screen and (max-width: 900px) {\n .col {\n width: 50%;\n }\n}\n@media screen and (max-width: 600px) {\n .col {\n width: 100%;\n }\n}\n</style>\n</head>\n<body>\n<h1>Changing layout on screen size using CSS</h1>\n<h2>Resize the screen to see the below divs resize themselves</h2>\n<div class=\"colContainer\">\n<div class=\"col\" style=\"background-color: rgb(153, 29, 224);\">\n<h2>First col</h2>\n</div>\n<div class=\"col\" style=\"background-color: rgb(12, 126, 120);\">\n<h2>Second col</h2>\n</div>\n<div class=\"col\" style=\"background-color: rgb(207, 41, 91);\">\n<h2>Third col</h2>\n</div>\n<div class=\"col\" style=\"background-color: rgb(204, 91, 39);\">\n<h2>Fourth col</h2>\n</div>\n</div>\n</body>\n</html>" }, { "code": null, "e": 2262, "s": 2211, "text": "The above code will produce the following output −" } ]
Kafka-Python explained in 10 lines of code | by Steven Van Dorpe | Towards Data Science
Although it’s not the newest library Python has to offer, it’s hard to find a comprehensive tutorial on how to use Apache Kafka with Python. By means of approximately ten lines of code, I will explain the foundations of Kafka and it’s interaction with Kafka-Python. First of all you want to have installed Kafka and Zookeeper on your machine. For Windows there is an excellent guide by Shahrukh Aslam, and they definitely exist for other OS’s as well. Next install Kafka-Python. You can do this using pip or conda, if you’re using an Anaconda distribution. pip install kafka-pythonconda install -c conda-forge kafka-python Don’t forget to start your Zookeeper server and Kafka broker before executing the example code below. In this example we assume that Zookeeper is running default on localhost:2181 and Kafka on localhost:9092. We are also using a topic called numtest in this example, you can create a new topic by opening a new command prompt, navigating to .../kafka/bin/windows and execute: kafka-topics.bat --create --zookeeper localhost:2181 --replication-factor 1 --partitions 1 --topic numtest Simply put, Kafka is a distributed publish-subscribe messaging system that maintains feeds of messages in partitioned and replicated topics. In the simplest way there are three players in the Kafka ecosystem: producers, topics (run by brokers) and consumers. Producers produce messages to a topic of their choice. It is possible to attach a key to each message, in which case the producer guarantees that all messages with the same key will arrive to the same partition. Topics are logs that receive data from the producers and store them across their partitions. Producers always write new messages at the end of the log. In our example we can make abstraction of the partitions, since we’re working locally. Consumers read the messages of a set of partitions of a topic of their choice at their own pace. If the consumer is part of a consumer group, i.e. a group of consumers subscribed to the same topic, they can commit their offset. This can be important if you want to consume a topic in parallel with different consumers. The offset is the position in the log where the consumer last consumed or read a message. The consumer can then commit this offset to make the reading ‘official’. Offset committing can be done automatically in the background or explicitly. In our example we will commit automatically in the background. In our example we’ll create a producer that emits numbers from 1 to 1000 and send them to our Kafka broker. Then a consumer will read the data from the broker and store them in a MongoDb collection. The advantage of using Kafka is that, if our consumer breaks down, the new or fixed consumer will pick up reading where the previous one stopped. This is a great way to make sure all the data is fed into the database without duplicates or missing data. Create a new Python script named producer.py and start with importing json, time.sleep and KafkaProducer from our brand new Kafka-Python library. from time import sleepfrom json import dumpsfrom kafka import KafkaProducer Then initialize a new Kafka producer. Note the following arguments: bootstrap_servers=[‘localhost:9092’]: sets the host and port the producer should contact to bootstrap initial cluster metadata. It is not necessary to set this here, since the default is localhost:9092. value_serializer=lambda x: dumps(x).encode(‘utf-8’): function of how the data should be serialized before sending to the broker. Here, we convert the data to a json file and encode it to utf-8. producer = KafkaProducer(bootstrap_servers=['localhost:9092'], value_serializer=lambda x: dumps(x).encode('utf-8')) Now, we want to generate numbers from one till 1000. This can be done with a for-loop where we feed each number as the value into a dictionary with one key: number. This is not the topic key, but just a key of our data. Within the same loop we will also send our data to a broker. This can be done by calling the send method on the producer and specifying the topic and the data. Note that our value serializer will automatically convert and encode the data. To conclude our iteration,we take a 5 second break. If you want to make sure the message is received by the broker, it’s advised to include a callback. for e in range(1000): data = {'number' : e} producer.send('numtest', value=data) sleep(5) If you want to test the code, it’s advised to create a new topic and send the data to this new topic. This way, you’ll avoid duplicates and possible confusion in the numtest topic when we’re later testing the producer and consumer together. Before we start coding our consumer, create a new file consumer.py and import json.loads, the KafkaConsumer class and MongoClient from pymongo. I won’t dig any deeper in the PyMongo code, since that’s outside the scope of this article. Furthermore, you can replace the mongo code with any other code. This can be code to feed the data into another database, code to process the data or anything else you can think of. For more information about PyMongo and MongoDb, please consult the documentation. from kafka import KafkaConsumerfrom pymongo import MongoClientfrom json import loads Let’s create our KafkaConsumer and take a closer look at the arguments. The first argument is the topic, numtest in our case. bootstrap_servers=[‘localhost:9092’]: same as our producer auto_offset_reset=’earliest’: one of the most important arguments. It handles where the consumer restarts reading after breaking down or being turned off and can be set either to earliest or latest. When set to latest, the consumer starts reading at the end of the log. When set to earliest, the consumer starts reading at the latest committed offset. And that’s exactly what we want here. enable_auto_commit=True: makes sure the consumer commits its read offset every interval. auto_commit_interval_ms=1000ms: sets the interval between two commits. Since messages are coming in every five second, committing every second seems fair. group_id=’counters’: this is the consumer group to which the consumer belongs. Remember from the introduction that a consumer needs to be part of a consumer group to make the auto commit work. The value deserializer deserializes the data into a common json format, the inverse of what our value serializer was doing. consumer = KafkaConsumer( 'numtest', bootstrap_servers=['localhost:9092'], auto_offset_reset='earliest', enable_auto_commit=True, group_id='my-group', value_deserializer=lambda x: loads(x.decode('utf-8'))) The code below connects to the numtest collection (a collection is similar to a table in a relational database) of our MongoDb database. client = MongoClient('localhost:27017')collection = client.numtest.numtest We can extract the data from our consumer by looping through it (the consumer is an iterable). The consumer will keep listening until the broker doesn’t respond anymore. A value of a message can be accessed with the value attribute. Here, we overwrite the message with the message value. The next line inserts the data into our database collection. The last line prints a confirmation that the message was added to our collection. Note that it is possible to add callbacks to all the actions in this loop. for message in consumer: message = message.value collection.insert_one(message) print('{} added to {}'.format(message, collection)) Let’s test our two scripts. Open a command prompt and go to the directory where you saved producer.py and consumer.py. Execute producer.py and open a new command prompt. Launch consumer.py and look how it reads all the messages, including the new ones. Now interrupt the consumer, remember at which number it was (or check it in the database) and restart the consumer. Notice that the consumer picks up all the missed messages and then continues listening for new ones. Note that if you turn off the consumer within 1 second after reading the message, the message will be retrieved again upon restart. Why? Because our auto_commit_interval is set to 1 second, remember that if the offset is not committed, the consumer will read the message again (if auto_offset_reset is set to earliest). — Please feel free to bring any inconsistencies or mistakes to my attention in the comments or by leaving a private note. — This article is by no means a complete guide to Kafka or Kafka-Python, but rather a comprehensive teaser that will familiarize you with essential Kafka concepts and how to transform these in useful Python code. For more advanced topics reading the documentation is advised. If you want to deploy code, it is probably a good idea to take a look at Confluent-Kafka and this post by Russell Jurney. Kafka-Python documentation Consume JSON Messages From Kafka using Kafka-Python’s Deserializer Apache Kafka documentation Cloudera Kafka documentation Putting Apache Kafka To Use: A Practical Guide to Building a Streaming Platform Introducing the Kafka Consumer: Getting Started with the New Apache Kafka 0.9 Consumer Client
[ { "code": null, "e": 438, "s": 172, "text": "Although it’s not the newest library Python has to offer, it’s hard to find a comprehensive tutorial on how to use Apache Kafka with Python. By means of approximately ten lines of code, I will explain the foundations of Kafka and it’s interaction with Kafka-Python." }, { "code": null, "e": 624, "s": 438, "text": "First of all you want to have installed Kafka and Zookeeper on your machine. For Windows there is an excellent guide by Shahrukh Aslam, and they definitely exist for other OS’s as well." }, { "code": null, "e": 729, "s": 624, "text": "Next install Kafka-Python. You can do this using pip or conda, if you’re using an Anaconda distribution." }, { "code": null, "e": 795, "s": 729, "text": "pip install kafka-pythonconda install -c conda-forge kafka-python" }, { "code": null, "e": 1004, "s": 795, "text": "Don’t forget to start your Zookeeper server and Kafka broker before executing the example code below. In this example we assume that Zookeeper is running default on localhost:2181 and Kafka on localhost:9092." }, { "code": null, "e": 1171, "s": 1004, "text": "We are also using a topic called numtest in this example, you can create a new topic by opening a new command prompt, navigating to .../kafka/bin/windows and execute:" }, { "code": null, "e": 1278, "s": 1171, "text": "kafka-topics.bat --create --zookeeper localhost:2181 --replication-factor 1 --partitions 1 --topic numtest" }, { "code": null, "e": 1537, "s": 1278, "text": "Simply put, Kafka is a distributed publish-subscribe messaging system that maintains feeds of messages in partitioned and replicated topics. In the simplest way there are three players in the Kafka ecosystem: producers, topics (run by brokers) and consumers." }, { "code": null, "e": 1749, "s": 1537, "text": "Producers produce messages to a topic of their choice. It is possible to attach a key to each message, in which case the producer guarantees that all messages with the same key will arrive to the same partition." }, { "code": null, "e": 1988, "s": 1749, "text": "Topics are logs that receive data from the producers and store them across their partitions. Producers always write new messages at the end of the log. In our example we can make abstraction of the partitions, since we’re working locally." }, { "code": null, "e": 2307, "s": 1988, "text": "Consumers read the messages of a set of partitions of a topic of their choice at their own pace. If the consumer is part of a consumer group, i.e. a group of consumers subscribed to the same topic, they can commit their offset. This can be important if you want to consume a topic in parallel with different consumers." }, { "code": null, "e": 2610, "s": 2307, "text": "The offset is the position in the log where the consumer last consumed or read a message. The consumer can then commit this offset to make the reading ‘official’. Offset committing can be done automatically in the background or explicitly. In our example we will commit automatically in the background." }, { "code": null, "e": 2809, "s": 2610, "text": "In our example we’ll create a producer that emits numbers from 1 to 1000 and send them to our Kafka broker. Then a consumer will read the data from the broker and store them in a MongoDb collection." }, { "code": null, "e": 3062, "s": 2809, "text": "The advantage of using Kafka is that, if our consumer breaks down, the new or fixed consumer will pick up reading where the previous one stopped. This is a great way to make sure all the data is fed into the database without duplicates or missing data." }, { "code": null, "e": 3208, "s": 3062, "text": "Create a new Python script named producer.py and start with importing json, time.sleep and KafkaProducer from our brand new Kafka-Python library." }, { "code": null, "e": 3284, "s": 3208, "text": "from time import sleepfrom json import dumpsfrom kafka import KafkaProducer" }, { "code": null, "e": 3352, "s": 3284, "text": "Then initialize a new Kafka producer. Note the following arguments:" }, { "code": null, "e": 3555, "s": 3352, "text": "bootstrap_servers=[‘localhost:9092’]: sets the host and port the producer should contact to bootstrap initial cluster metadata. It is not necessary to set this here, since the default is localhost:9092." }, { "code": null, "e": 3749, "s": 3555, "text": "value_serializer=lambda x: dumps(x).encode(‘utf-8’): function of how the data should be serialized before sending to the broker. Here, we convert the data to a json file and encode it to utf-8." }, { "code": null, "e": 3914, "s": 3749, "text": "producer = KafkaProducer(bootstrap_servers=['localhost:9092'], value_serializer=lambda x: dumps(x).encode('utf-8'))" }, { "code": null, "e": 4195, "s": 3914, "text": "Now, we want to generate numbers from one till 1000. This can be done with a for-loop where we feed each number as the value into a dictionary with one key: number. This is not the topic key, but just a key of our data. Within the same loop we will also send our data to a broker." }, { "code": null, "e": 4525, "s": 4195, "text": "This can be done by calling the send method on the producer and specifying the topic and the data. Note that our value serializer will automatically convert and encode the data. To conclude our iteration,we take a 5 second break. If you want to make sure the message is received by the broker, it’s advised to include a callback." }, { "code": null, "e": 4624, "s": 4525, "text": "for e in range(1000): data = {'number' : e} producer.send('numtest', value=data) sleep(5)" }, { "code": null, "e": 4865, "s": 4624, "text": "If you want to test the code, it’s advised to create a new topic and send the data to this new topic. This way, you’ll avoid duplicates and possible confusion in the numtest topic when we’re later testing the producer and consumer together." }, { "code": null, "e": 5101, "s": 4865, "text": "Before we start coding our consumer, create a new file consumer.py and import json.loads, the KafkaConsumer class and MongoClient from pymongo. I won’t dig any deeper in the PyMongo code, since that’s outside the scope of this article." }, { "code": null, "e": 5365, "s": 5101, "text": "Furthermore, you can replace the mongo code with any other code. This can be code to feed the data into another database, code to process the data or anything else you can think of. For more information about PyMongo and MongoDb, please consult the documentation." }, { "code": null, "e": 5450, "s": 5365, "text": "from kafka import KafkaConsumerfrom pymongo import MongoClientfrom json import loads" }, { "code": null, "e": 5522, "s": 5450, "text": "Let’s create our KafkaConsumer and take a closer look at the arguments." }, { "code": null, "e": 5576, "s": 5522, "text": "The first argument is the topic, numtest in our case." }, { "code": null, "e": 5635, "s": 5576, "text": "bootstrap_servers=[‘localhost:9092’]: same as our producer" }, { "code": null, "e": 6025, "s": 5635, "text": "auto_offset_reset=’earliest’: one of the most important arguments. It handles where the consumer restarts reading after breaking down or being turned off and can be set either to earliest or latest. When set to latest, the consumer starts reading at the end of the log. When set to earliest, the consumer starts reading at the latest committed offset. And that’s exactly what we want here." }, { "code": null, "e": 6114, "s": 6025, "text": "enable_auto_commit=True: makes sure the consumer commits its read offset every interval." }, { "code": null, "e": 6269, "s": 6114, "text": "auto_commit_interval_ms=1000ms: sets the interval between two commits. Since messages are coming in every five second, committing every second seems fair." }, { "code": null, "e": 6462, "s": 6269, "text": "group_id=’counters’: this is the consumer group to which the consumer belongs. Remember from the introduction that a consumer needs to be part of a consumer group to make the auto commit work." }, { "code": null, "e": 6586, "s": 6462, "text": "The value deserializer deserializes the data into a common json format, the inverse of what our value serializer was doing." }, { "code": null, "e": 6815, "s": 6586, "text": "consumer = KafkaConsumer( 'numtest', bootstrap_servers=['localhost:9092'], auto_offset_reset='earliest', enable_auto_commit=True, group_id='my-group', value_deserializer=lambda x: loads(x.decode('utf-8')))" }, { "code": null, "e": 6952, "s": 6815, "text": "The code below connects to the numtest collection (a collection is similar to a table in a relational database) of our MongoDb database." }, { "code": null, "e": 7027, "s": 6952, "text": "client = MongoClient('localhost:27017')collection = client.numtest.numtest" }, { "code": null, "e": 7315, "s": 7027, "text": "We can extract the data from our consumer by looping through it (the consumer is an iterable). The consumer will keep listening until the broker doesn’t respond anymore. A value of a message can be accessed with the value attribute. Here, we overwrite the message with the message value." }, { "code": null, "e": 7533, "s": 7315, "text": "The next line inserts the data into our database collection. The last line prints a confirmation that the message was added to our collection. Note that it is possible to add callbacks to all the actions in this loop." }, { "code": null, "e": 7674, "s": 7533, "text": "for message in consumer: message = message.value collection.insert_one(message) print('{} added to {}'.format(message, collection))" }, { "code": null, "e": 7927, "s": 7674, "text": "Let’s test our two scripts. Open a command prompt and go to the directory where you saved producer.py and consumer.py. Execute producer.py and open a new command prompt. Launch consumer.py and look how it reads all the messages, including the new ones." }, { "code": null, "e": 8144, "s": 7927, "text": "Now interrupt the consumer, remember at which number it was (or check it in the database) and restart the consumer. Notice that the consumer picks up all the missed messages and then continues listening for new ones." }, { "code": null, "e": 8464, "s": 8144, "text": "Note that if you turn off the consumer within 1 second after reading the message, the message will be retrieved again upon restart. Why? Because our auto_commit_interval is set to 1 second, remember that if the offset is not committed, the consumer will read the message again (if auto_offset_reset is set to earliest)." }, { "code": null, "e": 8588, "s": 8464, "text": "— Please feel free to bring any inconsistencies or mistakes to my attention in the comments or by leaving a private note. —" }, { "code": null, "e": 8799, "s": 8588, "text": "This article is by no means a complete guide to Kafka or Kafka-Python, but rather a comprehensive teaser that will familiarize you with essential Kafka concepts and how to transform these in useful Python code." }, { "code": null, "e": 8984, "s": 8799, "text": "For more advanced topics reading the documentation is advised. If you want to deploy code, it is probably a good idea to take a look at Confluent-Kafka and this post by Russell Jurney." }, { "code": null, "e": 9011, "s": 8984, "text": "Kafka-Python documentation" }, { "code": null, "e": 9078, "s": 9011, "text": "Consume JSON Messages From Kafka using Kafka-Python’s Deserializer" }, { "code": null, "e": 9105, "s": 9078, "text": "Apache Kafka documentation" }, { "code": null, "e": 9134, "s": 9105, "text": "Cloudera Kafka documentation" }, { "code": null, "e": 9214, "s": 9134, "text": "Putting Apache Kafka To Use: A Practical Guide to Building a Streaming Platform" } ]
Check if a number is formed by Concatenation of 1, 14 or 144 only - GeeksforGeeks
08 Nov, 2021 Given a number . The task is to check if the number is formed by concatenating the numbers 1, 14 and 144 only any number of times and in any order.If it is possible, print YES otherwise print NO.Example: Input: N = 141411 Output: YES Input: N = 14134 Output: NO The idea is to fetch single digit, double digit and triple digit numbers from the end and check if any of them matches with 1, 14 and 144 respectively. If any of them matches, divide the number with that and repeat the above step until the number is greater than zero.Below is the implementation of using above approach: C++ Java Python 3 C# PHP Javascript // C++ program to check if a number is formed// by Concatenation of 1, 14 or 144 only #include <iostream>using namespace std; // Function to check if a number is formed// by Concatenation of 1, 14 or 144 onlystring checkNumber(int N){ int temp = N; while (temp > 0) { // check for each possible digit // if given number consist other then // 1, 14, 144 print NO else print YES if (temp % 1000 == 144) temp /= 1000; else if (temp % 100 == 14) temp /= 100; else if (temp % 10 == 1) temp /= 10; else { return "NO"; } } return "YES";} // Driver Codeint main(){ int N = 1414; cout << checkNumber(N); return 0;} // Java program to check if a number is formed// by Concatenation of 1, 14 or 144 only import java.io.*; class GFG { // Function to check if a number is formed// by Concatenation of 1, 14 or 144 onlystatic String checkNumber(int N){ int temp = N; while (temp > 0) { // check for each possible digit // if given number consist other then // 1, 14, 144 print NO else print YES if (temp % 1000 == 144) temp /= 1000; else if (temp % 100 == 14) temp /= 100; else if (temp % 10 == 1) temp /= 10; else { return "NO"; } } return "YES";} // Driver Code public static void main (String[] args) { int N = 1414; System.out.println(checkNumber(N)); }}// This code is contributed by anuj_67.. # Python 3 program to check if a# number is formed by Concatenation# of 1, 14 or 144 only # Function to check if a number is formed# by Concatenation of 1, 14 or 144 onlydef checkNumber(N): temp = N while (temp > 0): # check for each possible digit # if given number consist other then # 1, 14, 144 print NO else print YES if (temp % 1000 == 144): temp /= 1000 elif (temp % 100 == 14): temp /= 100 elif (temp % 10 == 1): temp /= 10 else: return "YES" return "NO" # Driver CodeN = 1414; print(checkNumber(N)); # This code is contributed# by Akanksha Rai // C# program to check if a number is formed// by Concatenation of 1, 14 or 144 only using System; class GFG { // Function to check if a number is formed// by Concatenation of 1, 14 or 144 onlystatic String checkNumber(int N){ int temp = N; while (temp > 0) { // check for each possible digit // if given number consist other then // 1, 14, 144 print NO else print YES if (temp % 1000 == 144) temp /= 1000; else if (temp % 100 == 14) temp /= 100; else if (temp % 10 == 1) temp /= 10; else { return "NO"; } } return "YES";} // Driver Code public static void Main () { int N = 1414; Console.WriteLine(checkNumber(N)); }}// This code is contributed by anuj_67.. <?php// PHP program to check if a number// is formed by Concatenation of// 1, 14 or 144 only // Function to check if a number is formed// by Concatenation of 1, 14 or 144 onlyfunction checkNumber($N){ $temp = $N; while ($temp > 0) { // check for each possible digit // if given number consist other then // 1, 14, 144 print NO else print YES if ($temp % 1000 == 144) $temp /= 1000; else if ($temp % 100 == 14) $temp /= 100; else if ($temp % 10 == 1) $temp /= 10; else { return "YES"; } } return "NO";} // Driver Code$N = 1414;echo checkNumber($N); // This code is contributed by Tushil?> <script> // Javascript program to check if a number is formed // by Concatenation of 1, 14 or 144 only // Function to check if a number is formed // by Concatenation of 1, 14 or 144 only function checkNumber(N) { let temp = N; while (temp > 0) { // check for each possible digit // if given number consist other then // 1, 14, 144 print NO else print YES if (temp % 1000 == 144) temp = parseInt(temp / 1000, 10); else if (temp % 100 == 14) temp = parseInt(temp / 100, 10); else if (temp % 10 == 1) temp = parseInt(temp / 10, 10); else { return "NO"; } } return "YES"; } let N = 1414; document.write(checkNumber(N)); </script> YES Time Complexity: O(N/10) Auxiliary Space: O(1) vt_m jit_t Akanksha_Rai divyesh072019 rohan07 Constructive Algorithms number-digits Competitive Programming Mathematical Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Breadth First Traversal ( BFS ) on a 2D array Runtime Errors Most important type of Algorithms Multistage Graph (Shortest Path) Shortest path in a directed graph by Dijkstra’s algorithm 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": 24737, "s": 24709, "text": "\n08 Nov, 2021" }, { "code": null, "e": 24943, "s": 24737, "text": "Given a number . The task is to check if the number is formed by concatenating the numbers 1, 14 and 144 only any number of times and in any order.If it is possible, print YES otherwise print NO.Example: " }, { "code": null, "e": 25003, "s": 24943, "text": "Input: N = 141411\nOutput: YES \n\nInput: N = 14134\nOutput: NO" }, { "code": null, "e": 25328, "s": 25005, "text": "The idea is to fetch single digit, double digit and triple digit numbers from the end and check if any of them matches with 1, 14 and 144 respectively. If any of them matches, divide the number with that and repeat the above step until the number is greater than zero.Below is the implementation of using above approach: " }, { "code": null, "e": 25332, "s": 25328, "text": "C++" }, { "code": null, "e": 25337, "s": 25332, "text": "Java" }, { "code": null, "e": 25346, "s": 25337, "text": "Python 3" }, { "code": null, "e": 25349, "s": 25346, "text": "C#" }, { "code": null, "e": 25353, "s": 25349, "text": "PHP" }, { "code": null, "e": 25364, "s": 25353, "text": "Javascript" }, { "code": "// C++ program to check if a number is formed// by Concatenation of 1, 14 or 144 only #include <iostream>using namespace std; // Function to check if a number is formed// by Concatenation of 1, 14 or 144 onlystring checkNumber(int N){ int temp = N; while (temp > 0) { // check for each possible digit // if given number consist other then // 1, 14, 144 print NO else print YES if (temp % 1000 == 144) temp /= 1000; else if (temp % 100 == 14) temp /= 100; else if (temp % 10 == 1) temp /= 10; else { return \"NO\"; } } return \"YES\";} // Driver Codeint main(){ int N = 1414; cout << checkNumber(N); return 0;}", "e": 26095, "s": 25364, "text": null }, { "code": "// Java program to check if a number is formed// by Concatenation of 1, 14 or 144 only import java.io.*; class GFG { // Function to check if a number is formed// by Concatenation of 1, 14 or 144 onlystatic String checkNumber(int N){ int temp = N; while (temp > 0) { // check for each possible digit // if given number consist other then // 1, 14, 144 print NO else print YES if (temp % 1000 == 144) temp /= 1000; else if (temp % 100 == 14) temp /= 100; else if (temp % 10 == 1) temp /= 10; else { return \"NO\"; } } return \"YES\";} // Driver Code public static void main (String[] args) { int N = 1414; System.out.println(checkNumber(N)); }}// This code is contributed by anuj_67..", "e": 26912, "s": 26095, "text": null }, { "code": "# Python 3 program to check if a# number is formed by Concatenation# of 1, 14 or 144 only # Function to check if a number is formed# by Concatenation of 1, 14 or 144 onlydef checkNumber(N): temp = N while (temp > 0): # check for each possible digit # if given number consist other then # 1, 14, 144 print NO else print YES if (temp % 1000 == 144): temp /= 1000 elif (temp % 100 == 14): temp /= 100 elif (temp % 10 == 1): temp /= 10 else: return \"YES\" return \"NO\" # Driver CodeN = 1414; print(checkNumber(N)); # This code is contributed# by Akanksha Rai", "e": 27578, "s": 26912, "text": null }, { "code": "// C# program to check if a number is formed// by Concatenation of 1, 14 or 144 only using System; class GFG { // Function to check if a number is formed// by Concatenation of 1, 14 or 144 onlystatic String checkNumber(int N){ int temp = N; while (temp > 0) { // check for each possible digit // if given number consist other then // 1, 14, 144 print NO else print YES if (temp % 1000 == 144) temp /= 1000; else if (temp % 100 == 14) temp /= 100; else if (temp % 10 == 1) temp /= 10; else { return \"NO\"; } } return \"YES\";} // Driver Code public static void Main () { int N = 1414; Console.WriteLine(checkNumber(N)); }}// This code is contributed by anuj_67..", "e": 28375, "s": 27578, "text": null }, { "code": "<?php// PHP program to check if a number// is formed by Concatenation of// 1, 14 or 144 only // Function to check if a number is formed// by Concatenation of 1, 14 or 144 onlyfunction checkNumber($N){ $temp = $N; while ($temp > 0) { // check for each possible digit // if given number consist other then // 1, 14, 144 print NO else print YES if ($temp % 1000 == 144) $temp /= 1000; else if ($temp % 100 == 14) $temp /= 100; else if ($temp % 10 == 1) $temp /= 10; else { return \"YES\"; } } return \"NO\";} // Driver Code$N = 1414;echo checkNumber($N); // This code is contributed by Tushil?>", "e": 29087, "s": 28375, "text": null }, { "code": "<script> // Javascript program to check if a number is formed // by Concatenation of 1, 14 or 144 only // Function to check if a number is formed // by Concatenation of 1, 14 or 144 only function checkNumber(N) { let temp = N; while (temp > 0) { // check for each possible digit // if given number consist other then // 1, 14, 144 print NO else print YES if (temp % 1000 == 144) temp = parseInt(temp / 1000, 10); else if (temp % 100 == 14) temp = parseInt(temp / 100, 10); else if (temp % 10 == 1) temp = parseInt(temp / 10, 10); else { return \"NO\"; } } return \"YES\"; } let N = 1414; document.write(checkNumber(N)); </script>", "e": 29939, "s": 29087, "text": null }, { "code": null, "e": 29943, "s": 29939, "text": "YES" }, { "code": null, "e": 29970, "s": 29945, "text": "Time Complexity: O(N/10)" }, { "code": null, "e": 29992, "s": 29970, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 29997, "s": 29992, "text": "vt_m" }, { "code": null, "e": 30003, "s": 29997, "text": "jit_t" }, { "code": null, "e": 30016, "s": 30003, "text": "Akanksha_Rai" }, { "code": null, "e": 30030, "s": 30016, "text": "divyesh072019" }, { "code": null, "e": 30038, "s": 30030, "text": "rohan07" }, { "code": null, "e": 30062, "s": 30038, "text": "Constructive Algorithms" }, { "code": null, "e": 30076, "s": 30062, "text": "number-digits" }, { "code": null, "e": 30100, "s": 30076, "text": "Competitive Programming" }, { "code": null, "e": 30113, "s": 30100, "text": "Mathematical" }, { "code": null, "e": 30126, "s": 30113, "text": "Mathematical" }, { "code": null, "e": 30224, "s": 30126, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30233, "s": 30224, "text": "Comments" }, { "code": null, "e": 30246, "s": 30233, "text": "Old Comments" }, { "code": null, "e": 30292, "s": 30246, "text": "Breadth First Traversal ( BFS ) on a 2D array" }, { "code": null, "e": 30307, "s": 30292, "text": "Runtime Errors" }, { "code": null, "e": 30341, "s": 30307, "text": "Most important type of Algorithms" }, { "code": null, "e": 30374, "s": 30341, "text": "Multistage Graph (Shortest Path)" }, { "code": null, "e": 30432, "s": 30374, "text": "Shortest path in a directed graph by Dijkstra’s algorithm" }, { "code": null, "e": 30462, "s": 30432, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 30522, "s": 30462, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 30537, "s": 30522, "text": "C++ Data Types" }, { "code": null, "e": 30580, "s": 30537, "text": "Set in C++ Standard Template Library (STL)" } ]
How to remove all leading whitespace in string in Python?
The lstrip() method will remove leading whitespaces, newline and tab characters on a string beginning. You can use it in the following way: >>> ' hello world!'.lstrip() 'hello world!' You can also use the strip() function to remove both trailing and leading whitespace in the same manner. For example: >>> ' hello world! '.strip() 'hello world!'
[ { "code": null, "e": 1202, "s": 1062, "text": "The lstrip() method will remove leading whitespaces, newline and tab characters on a string beginning. You can use it in the following way:" }, { "code": null, "e": 1250, "s": 1202, "text": ">>> ' hello world!'.lstrip()\n'hello world!'" }, { "code": null, "e": 1368, "s": 1250, "text": "You can also use the strip() function to remove both trailing and leading whitespace in the same manner. For example:" }, { "code": null, "e": 1419, "s": 1368, "text": ">>> ' hello world! '.strip()\n'hello world!'" } ]
Elixir - Variables
A variable provides us with named storage that our programs can manipulate. Each variable in Elixir has a specific type, which determines the size and layout of the variable's memory; the range of values that can be stored within that memory; and the set of operations that can be applied to the variable. Elixir supports the following basic types of variables. These are used for Integers. They are of size 32bit on a 32bit architecture and 64 bits on a 64-bit architecture. Integers are always signed in elixir. If an integer starts to expand in size above its limit, elixir convers it in a Big Integer which takes up memory in range 3 to n words whichever can fit it in memory. Floats have a 64-bit precision in elixir. They are also like integers in terms of memory. When defining a float, exponential notation can be used. They can take up 2 values which is either true or false. Strings are utf-8 encoded in elixir. They have a strings module which provides a lot of functionality to the programmer to manipulate strings. These are functions that can be defined and assigned to a variable, which can then be used to call this function. There are a lot of collection types available in Elixir. Some of them are Lists, Tuples, Maps, Binaries, etc. These will be discussed in subsequent chapters. A variable declaration tells the interpreter where and how much to create the storage for the variable. Elixir does not allow us to just declare a variable. A variable must be declared and assigned a value at the same time. For example, to create a variable named life and assign it a value 42, we do the following − life = 42 This will bind the variable life to value 42. If we want to reassign this variable a new value, we can do this by using the same syntax as above, i.e., life = "Hello world" Naming variables follow a snake_case convention in Elixir, i.e., all variables must start with a lowercase letter, followed by 0 or more letters(both upper and lower case), followed at the end by an optional '?' OR '!'. Variable names can also be started with a leading underscore but that must be used only when ignoring the variable, i.e., that variable will not be used again but is needed to be assigned to something. In the interactive shell, variables will print if you just enter the variable name. For example, if you create a variable − life = 42 And enter 'life' in your shell, you'll get the output as − 42 But if you want to output a variable to the console (When running an external script from a file), you need to provide the variable as input to IO.puts function − life = 42 IO.puts life or life = 42 IO.puts(life) This will give you the following output − 42 35 Lectures 3 hours Pranjal Srivastava 54 Lectures 6 hours Pranjal Srivastava, Harshit Srivastava 80 Lectures 9.5 hours Pranjal Srivastava 43 Lectures 4 hours Mohammad Nauman Print Add Notes Bookmark this page
[ { "code": null, "e": 2488, "s": 2182, "text": "A variable provides us with named storage that our programs can manipulate. Each variable in Elixir has a specific type, which determines the size and layout of the variable's memory; the range of values that can be stored within that memory; and the set of operations that can be applied to the variable." }, { "code": null, "e": 2544, "s": 2488, "text": "Elixir supports the following basic types of variables." }, { "code": null, "e": 2863, "s": 2544, "text": "These are used for Integers. They are of size 32bit on a 32bit architecture and 64 bits on a 64-bit architecture. Integers are always signed in elixir. If an integer starts to expand in size above its limit, elixir convers it in a Big Integer which takes up memory in range 3 to n words whichever can fit it in memory." }, { "code": null, "e": 3010, "s": 2863, "text": "Floats have a 64-bit precision in elixir. They are also like integers in terms of memory. When defining a float, exponential notation can be used." }, { "code": null, "e": 3067, "s": 3010, "text": "They can take up 2 values which is either true or false." }, { "code": null, "e": 3210, "s": 3067, "text": "Strings are utf-8 encoded in elixir. They have a strings module which provides a lot of functionality to the programmer to manipulate strings." }, { "code": null, "e": 3324, "s": 3210, "text": "These are functions that can be defined and assigned to a variable, which can then be used to call this function." }, { "code": null, "e": 3482, "s": 3324, "text": "There are a lot of collection types available in Elixir. Some of them are Lists, Tuples, Maps, Binaries, etc. These will be discussed in subsequent chapters." }, { "code": null, "e": 3799, "s": 3482, "text": "A variable declaration tells the interpreter where and how much to create the storage for the variable. Elixir does not allow us to just declare a variable. A variable must be declared and assigned a value at the same time. For example, to create a variable named life and assign it a value 42, we do the following −" }, { "code": null, "e": 3810, "s": 3799, "text": "life = 42\n" }, { "code": null, "e": 3962, "s": 3810, "text": "This will bind the variable life to value 42. If we want to reassign this variable a new value, we can do this by using the same syntax as above, i.e.," }, { "code": null, "e": 3984, "s": 3962, "text": "life = \"Hello world\"\n" }, { "code": null, "e": 4204, "s": 3984, "text": "Naming variables follow a snake_case convention in Elixir, i.e., all variables must start with a lowercase letter, followed by 0 or more letters(both upper and lower case), followed at the end by an optional '?' OR '!'." }, { "code": null, "e": 4406, "s": 4204, "text": "Variable names can also be started with a leading underscore but that must be used only when ignoring the variable, i.e., that variable will not be used again but is needed to be assigned to something." }, { "code": null, "e": 4530, "s": 4406, "text": "In the interactive shell, variables will print if you just enter the variable name. For example, if you create a variable −" }, { "code": null, "e": 4542, "s": 4530, "text": "life = 42 \n" }, { "code": null, "e": 4601, "s": 4542, "text": "And enter 'life' in your shell, you'll get the output as −" }, { "code": null, "e": 4605, "s": 4601, "text": "42\n" }, { "code": null, "e": 4768, "s": 4605, "text": "But if you want to output a variable to the console (When running an external script from a file), you need to provide the variable as input to IO.puts function −" }, { "code": null, "e": 4794, "s": 4768, "text": "life = 42 \nIO.puts life " }, { "code": null, "e": 4797, "s": 4794, "text": "or" }, { "code": null, "e": 4823, "s": 4797, "text": "life = 42 \nIO.puts(life) " }, { "code": null, "e": 4865, "s": 4823, "text": "This will give you the following output −" }, { "code": null, "e": 4869, "s": 4865, "text": "42\n" }, { "code": null, "e": 4902, "s": 4869, "text": "\n 35 Lectures \n 3 hours \n" }, { "code": null, "e": 4922, "s": 4902, "text": " Pranjal Srivastava" }, { "code": null, "e": 4955, "s": 4922, "text": "\n 54 Lectures \n 6 hours \n" }, { "code": null, "e": 4995, "s": 4955, "text": " Pranjal Srivastava, Harshit Srivastava" }, { "code": null, "e": 5030, "s": 4995, "text": "\n 80 Lectures \n 9.5 hours \n" }, { "code": null, "e": 5050, "s": 5030, "text": " Pranjal Srivastava" }, { "code": null, "e": 5083, "s": 5050, "text": "\n 43 Lectures \n 4 hours \n" }, { "code": null, "e": 5100, "s": 5083, "text": " Mohammad Nauman" }, { "code": null, "e": 5107, "s": 5100, "text": " Print" }, { "code": null, "e": 5118, "s": 5107, "text": " Add Notes" } ]
Averaging over every N elements of a Numpy Array - GeeksforGeeks
16 May, 2021 In this article, we will learn how to find the average over every n element of a NumPy array. For doing our task, we will some inbuilt methods provided by NumPy module which are as follows: numpy.average() to calculate the average i.e the sum of all the numbers divided by the number of elements numpy.reshape() to reshape the array taking n elements at a time without changing the original data numpy.mean() to calculate the average as mean is nothing but the sum of elements divided by the number of elements Example 1: Average over a 1-D array Python3 import numpy as np # converting list to numpy arraygivenArray = np.array([6, 5, 4, 3, 2, 1, 9, 8, 7, 12, 11, 10, 15, 14, 13]) # here we took 3 as our inputn = 3 # calculates the averageavgResult = np.average(givenArray.reshape(-1, n), axis=1) print("Given array:")print(givenArray) print("Averaging over every ", n, " elements of a numpy array:")print(avgResult) Output: Note: N should be an integer multiple of the size of 1d array. Example 2: Average over a 1-D array(Row-wise) Here we have taken an array of dimensions (5,3) i.e it has 5 rows and 3 columns. Since the axis=1, it will reshape the elements in groups of n and then calculate the average row-wise using axis=1. Python3 import numpy as np # converting list to numpy arraygivenArray = np.array([[60, 50, 40], [30, 20, 10], [90, 80,70], [120, 110, 100], [150, 140, 130]]) # here we took 5 as our inputn = 5 # calculates the averageavgResult = np.average(givenArray.reshape(-1, n), axis=1) print("Given array:")print(givenArray, "\n") print("Dimensions of given array:", givenArray.shape, "\n") print("Averaging over every ", n, " elements of a numpy array:")print(avgResult) Output: Example 3: Average over a 1-D array(Column-wise) Remember we need to give the axis=1 only then it can group elements row-wise starting from the 0th index. Now if we change the axis value to 0, then after reshaping in groups of n, it will perform the average operation column-wise as given below which will not give us the desired result. It is best if we want to calculate the average column-wise. Python3 import numpy as np # converting list to numpy arraygivenArray = np.array([[60, 50, 40], [30, 20, 10], [90, 80, 70], [120, 110, 100], [150, 140, 130]]) # here we will calculate average# over every 5 elementsn = 5 # calculates the averageavgResult = np.average(givenArray.reshape(-1, n), axis=0) print("Given array:")print(givenArray, "\n") print("Dimensions of given array:", givenArray.shape, "\n") print("Averaging over every ", n, " elements of a numpy array:")print(avgResult) After reshaping the 2D array it looks like below: Then performing the average column wise we get the answer. Output: Example 4: Average over a 1-D array(Column-wise without reshaping) Note here that taking axis=0 we cannot perform the average row-wise over every n element. It will just calculate the average of each column separately. The below code will calculate the average over every column element. Python3 import numpy as np# converting list to numpy arraygivenArray = np.array([[60, 50, 40], [30, 20, 10], [90, 80,70], [120, 110, 100], [150, 140, 130]]) # here we will calculate average over# every 5 elementsn = 5 # calculates the averageavgResult1 = givenArray.mean(axis=0) print("Given array:")print(givenArray, "\n") print("Dimensions of given array:", givenArray.shape, "\n") print("Averaging over every ", n, " elements of a numpy array:")print(avgResult1) Output: Picked Python numpy-Mathematical Function Python-numpy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python OOPs Concepts How to Install PIP on Windows ? Bar Plot in Matplotlib Defaultdict in Python Python Classes and Objects Deque in Python Check if element exists in list in Python How to drop one or multiple columns in Pandas Dataframe Python - Ways to remove duplicates from list Class method vs Static method in Python
[ { "code": null, "e": 23925, "s": 23897, "text": "\n16 May, 2021" }, { "code": null, "e": 24115, "s": 23925, "text": "In this article, we will learn how to find the average over every n element of a NumPy array. For doing our task, we will some inbuilt methods provided by NumPy module which are as follows:" }, { "code": null, "e": 24221, "s": 24115, "text": "numpy.average() to calculate the average i.e the sum of all the numbers divided by the number of elements" }, { "code": null, "e": 24321, "s": 24221, "text": "numpy.reshape() to reshape the array taking n elements at a time without changing the original data" }, { "code": null, "e": 24436, "s": 24321, "text": "numpy.mean() to calculate the average as mean is nothing but the sum of elements divided by the number of elements" }, { "code": null, "e": 24472, "s": 24436, "text": "Example 1: Average over a 1-D array" }, { "code": null, "e": 24480, "s": 24472, "text": "Python3" }, { "code": "import numpy as np # converting list to numpy arraygivenArray = np.array([6, 5, 4, 3, 2, 1, 9, 8, 7, 12, 11, 10, 15, 14, 13]) # here we took 3 as our inputn = 3 # calculates the averageavgResult = np.average(givenArray.reshape(-1, n), axis=1) print(\"Given array:\")print(givenArray) print(\"Averaging over every \", n, \" elements of a numpy array:\")print(avgResult)", "e": 24893, "s": 24480, "text": null }, { "code": null, "e": 24901, "s": 24893, "text": "Output:" }, { "code": null, "e": 24965, "s": 24901, "text": "Note: N should be an integer multiple of the size of 1d array. " }, { "code": null, "e": 25011, "s": 24965, "text": "Example 2: Average over a 1-D array(Row-wise)" }, { "code": null, "e": 25208, "s": 25011, "text": "Here we have taken an array of dimensions (5,3) i.e it has 5 rows and 3 columns. Since the axis=1, it will reshape the elements in groups of n and then calculate the average row-wise using axis=1." }, { "code": null, "e": 25216, "s": 25208, "text": "Python3" }, { "code": "import numpy as np # converting list to numpy arraygivenArray = np.array([[60, 50, 40], [30, 20, 10], [90, 80,70], [120, 110, 100], [150, 140, 130]]) # here we took 5 as our inputn = 5 # calculates the averageavgResult = np.average(givenArray.reshape(-1, n), axis=1) print(\"Given array:\")print(givenArray, \"\\n\") print(\"Dimensions of given array:\", givenArray.shape, \"\\n\") print(\"Averaging over every \", n, \" elements of a numpy array:\")print(avgResult)", "e": 25697, "s": 25216, "text": null }, { "code": null, "e": 25705, "s": 25697, "text": "Output:" }, { "code": null, "e": 25754, "s": 25705, "text": "Example 3: Average over a 1-D array(Column-wise)" }, { "code": null, "e": 26103, "s": 25754, "text": "Remember we need to give the axis=1 only then it can group elements row-wise starting from the 0th index. Now if we change the axis value to 0, then after reshaping in groups of n, it will perform the average operation column-wise as given below which will not give us the desired result. It is best if we want to calculate the average column-wise." }, { "code": null, "e": 26111, "s": 26103, "text": "Python3" }, { "code": "import numpy as np # converting list to numpy arraygivenArray = np.array([[60, 50, 40], [30, 20, 10], [90, 80, 70], [120, 110, 100], [150, 140, 130]]) # here we will calculate average# over every 5 elementsn = 5 # calculates the averageavgResult = np.average(givenArray.reshape(-1, n), axis=0) print(\"Given array:\")print(givenArray, \"\\n\") print(\"Dimensions of given array:\", givenArray.shape, \"\\n\") print(\"Averaging over every \", n, \" elements of a numpy array:\")print(avgResult)", "e": 26619, "s": 26111, "text": null }, { "code": null, "e": 26669, "s": 26619, "text": "After reshaping the 2D array it looks like below:" }, { "code": null, "e": 26728, "s": 26669, "text": "Then performing the average column wise we get the answer." }, { "code": null, "e": 26736, "s": 26728, "text": "Output:" }, { "code": null, "e": 26803, "s": 26736, "text": "Example 4: Average over a 1-D array(Column-wise without reshaping)" }, { "code": null, "e": 27024, "s": 26803, "text": "Note here that taking axis=0 we cannot perform the average row-wise over every n element. It will just calculate the average of each column separately. The below code will calculate the average over every column element." }, { "code": null, "e": 27032, "s": 27024, "text": "Python3" }, { "code": "import numpy as np# converting list to numpy arraygivenArray = np.array([[60, 50, 40], [30, 20, 10], [90, 80,70], [120, 110, 100], [150, 140, 130]]) # here we will calculate average over# every 5 elementsn = 5 # calculates the averageavgResult1 = givenArray.mean(axis=0) print(\"Given array:\")print(givenArray, \"\\n\") print(\"Dimensions of given array:\", givenArray.shape, \"\\n\") print(\"Averaging over every \", n, \" elements of a numpy array:\")print(avgResult1)", "e": 27517, "s": 27032, "text": null }, { "code": null, "e": 27525, "s": 27517, "text": "Output:" }, { "code": null, "e": 27532, "s": 27525, "text": "Picked" }, { "code": null, "e": 27567, "s": 27532, "text": "Python numpy-Mathematical Function" }, { "code": null, "e": 27580, "s": 27567, "text": "Python-numpy" }, { "code": null, "e": 27587, "s": 27580, "text": "Python" }, { "code": null, "e": 27685, "s": 27587, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27694, "s": 27685, "text": "Comments" }, { "code": null, "e": 27707, "s": 27694, "text": "Old Comments" }, { "code": null, "e": 27728, "s": 27707, "text": "Python OOPs Concepts" }, { "code": null, "e": 27760, "s": 27728, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27783, "s": 27760, "text": "Bar Plot in Matplotlib" }, { "code": null, "e": 27805, "s": 27783, "text": "Defaultdict in Python" }, { "code": null, "e": 27832, "s": 27805, "text": "Python Classes and Objects" }, { "code": null, "e": 27848, "s": 27832, "text": "Deque in Python" }, { "code": null, "e": 27890, "s": 27848, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27946, "s": 27890, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27991, "s": 27946, "text": "Python - Ways to remove duplicates from list" } ]
How to create Custom Template Tags in Django ? - GeeksforGeeks
04 Jan, 2021 Django offers a variety of built-in template tags such as {% if %} or {% block %}. However, Django also allows you to create your own template tags to perform custom actions. The power of custom template tags is that you can process any data and add it to any template regardless of the view executed. You can perform QuerySets or process any data to display results in your templates. The most common place to specify custom template tags is inside a Django app. If they relate to an existing app, it makes sense to bundle them there; otherwise, they can be added to a new app. Django provides the following helper functions that allow you to create your own template tags in an easy manner: simple_tag: Processes the data and returns a string inclusion_tag: Processes the data and returns a rendered template assignment_tag: Processes the data and sets a variable in the context Explanation: illustration of How to create a custom template tag using an Example. Consider a project named geeksforgeeks having an app named geeks. Refer to the following articles to check how to create a project and an app in Django. How to Create Basic Project using MVT in Django ? How to Create an App in Django ? Inside your django application (geeks app) directory, create a new directory, name it templatetags, and add an empty __init__.py file to it to ensure the directory is treated as a Python package. Create another file in the same folder and name it custom_tags.py. The name of the module file is the name you’ll use to load the tags later, so be careful to pick a name that won’t clash with custom tags and filters in another app. The file structure of the django application should look like the following: geeks/ __init__.py models.py ... templatetags/ __init__.py custom_tags.py In your template you would use the following: {% load custom_tags %} There’s no limit on how many modules you put in the templatetags package. Just keep in mind that a {% load %} statement will load tags for the given Python module name, not the name of the app. To be a valid tag library, the module(custom_tags.py) must contain a module-level variable named register that is a template Library instance in which all the tags are registered. So, near the top of your module, put the following: from django import template register = template.Library() Inside the models.py add the following code: Python3 from django.db import models # Create your models here.class YourModel(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) def __str__(self): return self.first_name After creating this model, we need to run two commands in order to create Database for the same. Python manage.py makemigrations Python manage.py migrate We will start by creating a simple tag to retrieve the total count of objects in our model named as YourModel. Edit the custom_tags.py file you just created and add the following code: Python3 from django import templateregister = template.Library() from .models import YourModel @register.simple_tagdef any_function(): return YourModel.objects.count() Inside the urls.py flle of project named geeksforgeeks add the following code Python3 from django.contrib import adminfrom django.urls import pathfrom django.views.generic.base import TemplateView urlpatterns = [ path('admin/', admin.site.urls), path('',TemplateView.as_view(template_name="Intro.html"),name="intro")] Create the folder named templates inside the app directory(geeks) and create the file named Intro.py and add the following code: HTML {% load custom_tag %}<!DOCTYPE html><html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>Intro</title> </head> <body> {% any_function %} Persons in your model </body></html> Now run, python manage.py runserver Let’s check what is there on http://localhost:8000/ – Output – Django Models Entries in DB – Django-templates Python Django Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Check if element exists in list in Python Selecting rows in pandas DataFrame based on conditions Python | os.path.join() method Defaultdict in Python Python | Get unique values from a list Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 24318, "s": 24290, "text": "\n04 Jan, 2021" }, { "code": null, "e": 24704, "s": 24318, "text": "Django offers a variety of built-in template tags such as {% if %} or {% block %}. However, Django also allows you to create your own template tags to perform custom actions. The power of custom template tags is that you can process any data and add it to any template regardless of the view executed. You can perform QuerySets or process any data to display results in your templates." }, { "code": null, "e": 24899, "s": 24704, "text": "The most common place to specify custom template tags is inside a Django app. If they relate to an existing app, it makes sense to bundle them there; otherwise, they can be added to a new app. " }, { "code": null, "e": 25013, "s": 24899, "text": "Django provides the following helper functions that allow you to create your own template tags in an easy manner:" }, { "code": null, "e": 25065, "s": 25013, "text": "simple_tag: Processes the data and returns a string" }, { "code": null, "e": 25131, "s": 25065, "text": "inclusion_tag: Processes the data and returns a rendered template" }, { "code": null, "e": 25201, "s": 25131, "text": "assignment_tag: Processes the data and sets a variable in the context" }, { "code": null, "e": 25214, "s": 25201, "text": "Explanation:" }, { "code": null, "e": 25351, "s": 25214, "text": " illustration of How to create a custom template tag using an Example. Consider a project named geeksforgeeks having an app named geeks." }, { "code": null, "e": 25442, "s": 25351, "text": "Refer to the following articles to check how to create a project and an app in Django. " }, { "code": null, "e": 25501, "s": 25442, "text": " How to Create Basic Project using MVT in Django ? " }, { "code": null, "e": 25537, "s": 25501, "text": " How to Create an App in Django ?" }, { "code": null, "e": 26044, "s": 25537, "text": "Inside your django application (geeks app) directory, create a new directory, name it templatetags, and add an empty __init__.py file to it to ensure the directory is treated as a Python package. Create another file in the same folder and name it custom_tags.py. The name of the module file is the name you’ll use to load the tags later, so be careful to pick a name that won’t clash with custom tags and filters in another app. The file structure of the django application should look like the following:" }, { "code": null, "e": 26162, "s": 26044, "text": "geeks/\n __init__.py\n models.py\n ...\n templatetags/\n __init__.py\n custom_tags.py" }, { "code": null, "e": 26208, "s": 26162, "text": "In your template you would use the following:" }, { "code": null, "e": 26231, "s": 26208, "text": "{% load custom_tags %}" }, { "code": null, "e": 26425, "s": 26231, "text": "There’s no limit on how many modules you put in the templatetags package. Just keep in mind that a {% load %} statement will load tags for the given Python module name, not the name of the app." }, { "code": null, "e": 26659, "s": 26425, "text": "To be a valid tag library, the module(custom_tags.py) must contain a module-level variable named register that is a template Library instance in which all the tags are registered. So, near the top of your module, put the following:" }, { "code": null, "e": 26718, "s": 26659, "text": "from django import template\n\nregister = template.Library()" }, { "code": null, "e": 26763, "s": 26718, "text": "Inside the models.py add the following code:" }, { "code": null, "e": 26771, "s": 26763, "text": "Python3" }, { "code": "from django.db import models # Create your models here.class YourModel(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) def __str__(self): return self.first_name", "e": 27005, "s": 26771, "text": null }, { "code": null, "e": 27102, "s": 27005, "text": "After creating this model, we need to run two commands in order to create Database for the same." }, { "code": null, "e": 27160, "s": 27102, "text": "Python manage.py makemigrations\n\nPython manage.py migrate" }, { "code": null, "e": 27345, "s": 27160, "text": "We will start by creating a simple tag to retrieve the total count of objects in our model named as YourModel. Edit the custom_tags.py file you just created and add the following code:" }, { "code": null, "e": 27353, "s": 27345, "text": "Python3" }, { "code": "from django import templateregister = template.Library() from .models import YourModel @register.simple_tagdef any_function(): return YourModel.objects.count()", "e": 27522, "s": 27353, "text": null }, { "code": null, "e": 27600, "s": 27522, "text": "Inside the urls.py flle of project named geeksforgeeks add the following code" }, { "code": null, "e": 27608, "s": 27600, "text": "Python3" }, { "code": "from django.contrib import adminfrom django.urls import pathfrom django.views.generic.base import TemplateView urlpatterns = [ path('admin/', admin.site.urls), path('',TemplateView.as_view(template_name=\"Intro.html\"),name=\"intro\")]", "e": 27847, "s": 27608, "text": null }, { "code": null, "e": 27977, "s": 27847, "text": "Create the folder named templates inside the app directory(geeks) and create the file named Intro.py and add the following code:" }, { "code": null, "e": 27982, "s": 27977, "text": "HTML" }, { "code": "{% load custom_tag %}<!DOCTYPE html><html lang=\"en\" dir=\"ltr\"> <head> <meta charset=\"utf-8\"> <title>Intro</title> </head> <body> {% any_function %} Persons in your model </body></html>", "e": 28180, "s": 27982, "text": null }, { "code": null, "e": 28189, "s": 28180, "text": "Now run," }, { "code": null, "e": 28216, "s": 28189, "text": "python manage.py runserver" }, { "code": null, "e": 28270, "s": 28216, "text": "Let’s check what is there on http://localhost:8000/ –" }, { "code": null, "e": 28280, "s": 28270, "text": "Output – " }, { "code": null, "e": 28311, "s": 28280, "text": "Django Models Entries in DB – " }, { "code": null, "e": 28328, "s": 28311, "text": "Django-templates" }, { "code": null, "e": 28342, "s": 28328, "text": "Python Django" }, { "code": null, "e": 28349, "s": 28342, "text": "Python" }, { "code": null, "e": 28447, "s": 28349, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28479, "s": 28447, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28521, "s": 28479, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 28577, "s": 28521, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28619, "s": 28577, "text": "Check if element exists in list in Python" }, { "code": null, "e": 28674, "s": 28619, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 28705, "s": 28674, "text": "Python | os.path.join() method" }, { "code": null, "e": 28727, "s": 28705, "text": "Defaultdict in Python" }, { "code": null, "e": 28766, "s": 28727, "text": "Python | Get unique values from a list" }, { "code": null, "e": 28795, "s": 28766, "text": "Create a directory in Python" } ]
Python Program for Insertion Sort
In this article, we will learn about the implementation of the Insertion sort in Python 3.x. Or earlier. 1. Iterate over the input elements by growing the sorted array at each iteration. 2. Compare the current element with the largest value available in the sorted array. 3. If the current element is greater, then it leaves the element in its place and moves on to the next element else it finds its correct position in the sorted array and moves it to that position in the array. 4. This is achieved by shifting all the elements towards the right, which are larger than the current element, in the sorted array to one position ahead. Now let’s see the visual representation of the algorithm − Now let’s see the implementation Live Demo def insertionSort(arr): for i in range(1, len(arr)): key = arr[i] # Move elements of arr[0..i-1], that are greater than key, # to one position ahead of their current position j = i-1 while j >=0 and key < arr[j] : arr[j+1] = arr[j] j -= 1 arr[j+1] = key # main arr = ['t','u','t','o','r','i','a','l'] insertionSort(arr) print ("The sorted array is:") for i in range(len(arr)): print (arr[i]) The sorted array is: a i l o r t t u Time Complexity − O(n*2) Auxiliary Space − O(1) All the variables are declared in the global frame as shown in the figure below − In this article, we learned about the Insertion sort and its implementation in Python 3.x. or earlier.
[ { "code": null, "e": 1167, "s": 1062, "text": "In this article, we will learn about the implementation of the Insertion sort in Python 3.x. Or earlier." }, { "code": null, "e": 1710, "s": 1167, "text": "1. Iterate over the input elements by growing the sorted array at each iteration.\n2. Compare the current element with the largest value available in the sorted array.\n3. If the current element is greater, then it leaves the element in its place \n and moves on to the next element else it finds its correct position in the \n sorted array and moves it to that position in the array.\n4. This is achieved by shifting all the elements towards the right, which are \n larger than the current element, in the sorted array to one position ahead." }, { "code": null, "e": 1769, "s": 1710, "text": "Now let’s see the visual representation of the algorithm −" }, { "code": null, "e": 1802, "s": 1769, "text": "Now let’s see the implementation" }, { "code": null, "e": 1813, "s": 1802, "text": " Live Demo" }, { "code": null, "e": 2276, "s": 1813, "text": "def insertionSort(arr):\n for i in range(1, len(arr)):\n key = arr[i]\n # Move elements of arr[0..i-1], that are greater than key,\n # to one position ahead of their current position\n j = i-1\n while j >=0 and key < arr[j] :\n arr[j+1] = arr[j]\n j -= 1 \n arr[j+1] = key\n# main\narr = ['t','u','t','o','r','i','a','l']\ninsertionSort(arr)\nprint (\"The sorted array is:\")\nfor i in range(len(arr)):\n print (arr[i])" }, { "code": null, "e": 2313, "s": 2276, "text": "The sorted array is:\na\ni\nl\no\nr\nt\nt\nu" }, { "code": null, "e": 2338, "s": 2313, "text": "Time Complexity − O(n*2)" }, { "code": null, "e": 2361, "s": 2338, "text": "Auxiliary Space − O(1)" }, { "code": null, "e": 2443, "s": 2361, "text": "All the variables are declared in the global frame as shown in the figure below −" }, { "code": null, "e": 2546, "s": 2443, "text": "In this article, we learned about the Insertion sort and its implementation in Python 3.x. or earlier." } ]
VHDL Programming for Sequential Circuits
This chapter explains how to do VHDL programming for Sequential Circuits. library ieee; use ieee.std_logic_1164.all; entity srl is port(r,s:in bit; q,qbar:buffer bit); end srl; architecture virat of srl is signal s1,r1:bit; begin q<= s nand qbar; qbar<= r nand q; end virat; library ieee; use ieee.std_logic_1164.all; entity Dl is port(d:in bit; q,qbar:buffer bit); end Dl; architecture virat of Dl is signal s1,r1:bit; begin q<= d nand qbar; qbar<= d nand q; end virat; library ieee; use ieee.std_logic_1164.all; entity srflip is port(r,s,clk:in bit; q,qbar:buffer bit); end srflip; architecture virat of srflip is signal s1,r1:bit; begin s1<=s nand clk; r1<=r nand clk; q<= s1 nand qbar; qbar<= r1 nand q; end virat; library IEEE; use IEEE.STD_LOGIC_1164.all; entity jk is port( j : in STD_LOGIC; k : in STD_LOGIC; clk : in STD_LOGIC; reset : in STD_LOGIC; q : out STD_LOGIC; qb : out STD_LOGIC ); end jk; architecture virat of jk is begin jkff : process (j,k,clk,reset) is variable m : std_logic := '0'; begin if (reset = '1') then m : = '0'; elsif (rising_edge (clk)) then if (j/ = k) then m : = j; elsif (j = '1' and k = '1') then m : = not m; end if; end if; q <= m; qb <= not m; end process jkff; end virat; Library ieee; use ieee.std_logic_1164.all; entity dflip is port(d,clk:in bit; q,qbar:buffer bit); end dflip; architecture virat of dflip is signal d1,d2:bit; begin d1<=d nand clk; d2<=(not d) nand clk; q<= d1 nand qbar; qbar<= d2 nand q; end virat; library IEEE; use IEEE.STD_LOGIC_1164.all; entity Toggle_flip_flop is port( t : in STD_LOGIC; clk : in STD_LOGIC; reset : in STD_LOGIC; dout : out STD_LOGIC ); end Toggle_flip_flop; architecture virat of Toggle_flip_flop is begin tff : process (t,clk,reset) is variable m : std_logic : = '0'; begin if (reset = '1') then m : = '0'; elsif (rising_edge (clk)) then if (t = '1') then m : = not m; end if; end if; dout < = m; end process tff; end virat; library IEEE; use ieee.std_logic_1164.all; use ieee.std_logic_unsigned.all; entity counter is port(Clock, CLR : in std_logic; Q : out std_logic_vector(3 downto 0) ); end counter; architecture virat of counter is signal tmp: std_logic_vector(3 downto 0); begin process (Clock, CLR) begin if (CLR = '1') then tmp < = "0000"; elsif (Clock'event and Clock = '1') then mp <= tmp + 1; end if; end process; Q <= tmp; end virat; library ieee; use ieee.std_logic_1164.all; use ieee.std_logic_unsigned.all; entity dcounter is port(Clock, CLR : in std_logic; Q : out std_logic_vector(3 downto 0)); end dcounter; architecture virat of dcounter is signal tmp: std_logic_vector(3 downto 0); begin process (Clock, CLR) begin if (CLR = '1') then tmp <= "1111"; elsif (Clock'event and Clock = '1') then tmp <= tmp - 1; end if; end process; Q <= tmp; end virat; 23 Lectures 12 hours Uplatz 12 Lectures 1.5 hours Rajeev Raghu Raman Arunachalam Print Add Notes Bookmark this page
[ { "code": null, "e": 2013, "s": 1939, "text": "This chapter explains how to do VHDL programming for Sequential Circuits." }, { "code": null, "e": 2241, "s": 2013, "text": "library ieee; \nuse ieee.std_logic_1164.all;\n \nentity srl is \n port(r,s:in bit; q,qbar:buffer bit); \nend srl; \n\narchitecture virat of srl is \n signal s1,r1:bit; \nbegin \n q<= s nand qbar; \n qbar<= r nand q; \nend virat; " }, { "code": null, "e": 2462, "s": 2241, "text": "library ieee; \nuse ieee.std_logic_1164.all;\n\nentity Dl is \n port(d:in bit; q,qbar:buffer bit); \nend Dl; \n \narchitecture virat of Dl is \n signal s1,r1:bit; \nbegin \n q<= d nand qbar; \n qbar<= d nand q; \nend virat; " }, { "code": null, "e": 2745, "s": 2462, "text": "library ieee; \nuse ieee.std_logic_1164.all;\n \nentity srflip is \n port(r,s,clk:in bit; q,qbar:buffer bit); \nend srflip;\n \narchitecture virat of srflip is \n signal s1,r1:bit; \nbegin \n s1<=s nand clk; \n r1<=r nand clk;\n q<= s1 nand qbar;\n qbar<= r1 nand q;\nend virat; " }, { "code": null, "e": 3427, "s": 2745, "text": "library IEEE; \nuse IEEE.STD_LOGIC_1164.all; \n\nentity jk is \n port(\n j : in STD_LOGIC; \n k : in STD_LOGIC; \n clk : in STD_LOGIC; \n reset : in STD_LOGIC; \n q : out STD_LOGIC; \n qb : out STD_LOGIC \n ); \nend jk;\n \narchitecture virat of jk is \nbegin \n jkff : process (j,k,clk,reset) is \n variable m : std_logic := '0'; \n \n begin \n if (reset = '1') then \n m : = '0'; \n elsif (rising_edge (clk)) then \n if (j/ = k) then\n m : = j; \n elsif (j = '1' and k = '1') then \n m : = not m; \n end if; \n end if; \n \n q <= m; \n qb <= not m; \n end process jkff; \nend virat;" }, { "code": null, "e": 3710, "s": 3427, "text": "Library ieee; \nuse ieee.std_logic_1164.all; \n\nentity dflip is \n port(d,clk:in bit; q,qbar:buffer bit); \nend dflip; \n \narchitecture virat of dflip is \n signal d1,d2:bit; \nbegin \n d1<=d nand clk; \n d2<=(not d) nand clk; \n q<= d1 nand qbar; \n qbar<= d2 nand q; \nend virat;" }, { "code": null, "e": 4304, "s": 3710, "text": "library IEEE; \nuse IEEE.STD_LOGIC_1164.all; \n\nentity Toggle_flip_flop is \n port( \n t : in STD_LOGIC; \n clk : in STD_LOGIC; \n reset : in STD_LOGIC; \n dout : out STD_LOGIC\n ); \nend Toggle_flip_flop; \n\narchitecture virat of Toggle_flip_flop is \nbegin \n tff : process (t,clk,reset) is \n variable m : std_logic : = '0'; \n \n begin \n if (reset = '1') then \n m : = '0'; \n elsif (rising_edge (clk)) then \n if (t = '1') then \n m : = not m; \n end if; \n end if; \n dout < = m; \n end process tff; \nend virat; " }, { "code": null, "e": 4815, "s": 4304, "text": "library IEEE; \nuse ieee.std_logic_1164.all; \nuse ieee.std_logic_unsigned.all;\n \nentity counter is \n port(Clock, CLR : in std_logic; \n Q : out std_logic_vector(3 downto 0)\n ); \nend counter; \n\narchitecture virat of counter is \n signal tmp: std_logic_vector(3 downto 0); \nbegin \n process (Clock, CLR) \n \n begin \n if (CLR = '1') then \n tmp < = \"0000\"; \n elsif (Clock'event and Clock = '1') then \n mp <= tmp + 1; \n end if; \n end process; \n Q <= tmp; \nend virat;" }, { "code": null, "e": 5322, "s": 4815, "text": "library ieee; \nuse ieee.std_logic_1164.all; \nuse ieee.std_logic_unsigned.all;\n \nentity dcounter is \n port(Clock, CLR : in std_logic; \n Q : out std_logic_vector(3 downto 0)); \nend dcounter; \n \narchitecture virat of dcounter is \n signal tmp: std_logic_vector(3 downto 0); \n\nbegin \n process (Clock, CLR) \n begin \n if (CLR = '1') then \n tmp <= \"1111\"; \n elsif (Clock'event and Clock = '1') then \n tmp <= tmp - 1; \n end if; \n end process; \n Q <= tmp; \nend virat;" }, { "code": null, "e": 5356, "s": 5322, "text": "\n 23 Lectures \n 12 hours \n" }, { "code": null, "e": 5364, "s": 5356, "text": " Uplatz" }, { "code": null, "e": 5399, "s": 5364, "text": "\n 12 Lectures \n 1.5 hours \n" }, { "code": null, "e": 5431, "s": 5399, "text": " Rajeev Raghu Raman Arunachalam" }, { "code": null, "e": 5438, "s": 5431, "text": " Print" }, { "code": null, "e": 5449, "s": 5438, "text": " Add Notes" } ]
Using a Markov chain sentence generator in Python to generate ‘real fake news’. | by Mathias Schläffer | Towards Data Science
Let’s be honest: today’s news headlines are crazy. They are especially crazy if they concern Donald Trump. So crazy sometimes that you ask yourself if they are even real! Is what you read something that actually happened or just a random collection of words made into a news headline? Need an example? Donald Trump ‘Banned’ Unicorns ‘to North Korea’ Crazy, right? Granted, this headline is based on something the small kid of actress Alyssa Milano said. No grown up would come up with something so ridiculous... “Donald Trump Is “A Unicorn, Riding A Unicorn Over A Rainbow”, According To Sean Spicer Oh boy.To me, that sounds like it was generated by a random sentence generator. While it sadly wasn’t, I wondered how much (or if) randomly generated news headlines could get crazier than that. So I decided to build a Python script and see for myself. The script consists of a quick web scraper to get as many news headlines as possible and use them in a Markov model sentence generator to create my very own ‘real fake news’ headline. Even though the Python dictionary data type seemed like an initial good fit for a Markov model, I wanted to use data frames and pandas for it. Simply because I wanted to practice some pandas functionalities and I am not ultimately interested in the most “elegant” way to do it in this case, but I wanted a quick result and learn something on the way.First, I set up a script which is accessing a popular news site using the keywords ‘Donald Trump’. I then isolated the text containing the headlines and wrote them into a text file. I found this website extremely helpful to set up my little piece of code: https://realpython.com/python-web-scraping-practical-introduction/ On any day, this would give me about 100–120 news headlines. Not bad, but of course doing it once gives very little variety of words to work with and my Markov chain is running the risk of falling to often into a unique chain of words — and in the worst case - simply repeating and already existing news headline. Thankfully it is easy to set up a task scheduler in Windows which would execute my file every day in the background and let my text file grow continuously. All I had to do now is be patient and wait until a significant amount of headlines was accumulated. After about 1 1/2 weeks I had more than 1000 headlines. I decided that that is sufficient for such a highly unscientific and nonsensical project. After loading my text file and doing some coarse cleanup in eliminating some recurring news outlet signatures and double punctuation etc., I could finally start working the text into my Markov model. I decided to use a prefix or ‘lead’ of one word. I don’t want to get into details on Markov chains, but in very short I would summarize it like this: For each word we collect each following word in any sentence. Based on the frequency of a following word compared to its ‘rivals’, we will assign the likelihood of a word following a certain lead word. We can then start with a random word from the entire list of words in our text and then randomly select the next word in our sentence with probabilities based on the likelihoods we assigned. Word for word we will create a new sentence that is based on the properties of the text we used as input. Real news in → real fake news out. After splitting the text file into individual words and storing them in a variable ‘words’, I defined a pandas data frame with three columns: one column ‘lead’ defining the leading word. For each leading word, there is a word that ‘follows’ and be captured in our second column ‘follow’. The third column -‘freq’- will display how many times we can observe a certain combination of a ‘lead’ and a ‘follow’ in our text. What will we fill these columns with? Well, the first column is easy — simply every word in our text will be written in a row in this column. For every word with index i in our text, the following word is then the word with index i + 1. We simply start by filling the column ‘follow’ with our text again, but this time starting with the second word in the text. For a text of initially n rows, this fills n-1 “follow” words. The very last word in our text does not automatically have a follower, so we will use a synthetic string variable to fill the gap. I called it the ‘EndWord’ (please don’t confuse it with a similar sounding thing the president allegedly said on some mysterious apprentice tape). import pandas as pddict_df = pd.DataFrame(columns = [‘lead’, ‘follow’, ‘freq’])dict_df['lead']=wordsfollow = words[1:]follow.append('EndWord') Before I move on, I’ll create a separate array of words containing all the very last words of each sentence. In my later code, I will use these end-words to “naturally” end my randomly generated sentence. This has the nice side effect that I don’t have to worry about my Markov chain running ‘across’ headlines, meaning that the last word of one headline should not be considered a lead for the first word of the following headline. After all I am not dealing with one continuous text, but with individual and independent sentences. By cutting of my sentence after my sentence generator gets to such an end_word, this should not be a concern. end_words = []for word in words: if word[-1] in ['.','!','?'] and word != '.': end_words.append(word)print(end_words) So far so good. Now I count the occurrence of each combination of lead- and follow word and assign the result to the frequency column using group_by and transform. dict_df['freq']= dict_df.groupby(by=['lead','follow'])['lead','follow'].transform('count').copy() The rows are still not unique, so I delete duplicate rows before using the pivot functionality in Python to create one big matrix with every lead word as the row-index and every follow word as a column. The frequency of the combination of lead word in row i and following word in column j is then element a_ij in this matrix. dict_df = dict_df.drop_duplicates()pivot_df = dict_df.pivot(index = 'lead', columns= 'follow', values='freq') For each row, I then summed up all frequencies and divided each element in row i by the total of row i. This leads to percentages summing up to 1 that my sentence generator will use as a probability distribution when selecting the follow word for a certain lead word. E.g. if after the word ‘fake’ we observe 7 times the follow word ‘news’ and 3 times the word ‘tan’, the resulting probabilities to be selected would be 0.7 and 0.3 respectively. sum_words = pivot_df.sum(axis=1)pivot_df = pivot_df.apply(lambda x: x/sum_words) With all this in place, I can define my function for the sentence generator. I take one start word to initialize the sentence generator. This word could be a randomly chosen word from the set of all words. But since my text consists of only headlines of Donald Trump, I think it makes sense to make sure his name appears in our fake news headline as well. In my examples, I therefore start with ‘Donald’. Starting with this word, the generator selects a follow word based on the probability matrix we set up. It will continue by using the selected follow word as the new leading word to append word after word to our sentence. If the sentence generator gets to a word which is in our array of end-words, the sentence will take this word as the very last and return our sentence. If the generator gets to our synthetic ‘EndWord’ we defined earlier, it will simply draw a new follow word for the lead word that brought us down this dead-end road. The same applies if we get to an end word and our sentence is just 2 words long (I had a few example sentences that read only “Donald Trump.”. Like in “Donald Trump.” — nuff said). from numpy.random import choicedef make_a_sentence(start): word= start sentence=[word] while len(sentence) < 30: next_word = choice(a = list(pivot_df.columns), p = (pivot_df.iloc[pivot_df.index ==word].fillna(0).values)[0]) if next_word == 'EndWord': continue elif next_word in end_words: if len(sentence) > 2: sentence.append(next_word) break else : continue else : sentence.append(next_word) word=next_word sentence = ' '.join(sentence) return sentencesentence = make_a_sentence('Donald') And that’s it. I certainly won’t win a (Trump hosted) beauty pageant with this code, but it is quick, dirty, Python-noob friendly and does the job. Granted, the bigger the text, the slower the entire process of assigning probabilities will become, but as for my sample, it still took only a few seconds so I don’t see the need for time consuming optimization just yet. Let’s have a look at some of the ‘real fake news’ headlines instead: Donald Trumps Criticism Of Trump Obsessed With Star Wars Burn. - (Sounds plausible) Donald Trump broke the real Donald Trump loyalty test.- (How cool would it be if that happened?) Donald Trump’s Team Files Complaint Against Whites.- (Yeah.... probably not) Donald Trumps best people boast.- (His worst too) Donald Trumps aides feel his presidency this fall.- (We all do... we all do) Donald Trump, Omarosa, and other individuals, including the 45th president is Junior Mint.-(Fresh?) Donald Trump, you are so far.-(Maybe a bit too far for my taste) Of course these are some of the successful examples. A lot of sentences come out as absolute gibberish (not covfefe worthy, but still gibberish): Donald Trump Know Who Aretha Franklin Work for Utahs former aide Omarosa Manigault Newman.-(???) So what did we learn through this? You as a reader, probably not much. But I had a few good laughs with my code and got to work on data in a structure I usually wouldn’t encounter. If you have feedback or suggestion, please feel free to reach out. Thanks! P.S.: If you want a more sophisticated version of a Trump Markov chain, check out this random Trump Tweet generator by someone smarter:
[ { "code": null, "e": 474, "s": 172, "text": "Let’s be honest: today’s news headlines are crazy. They are especially crazy if they concern Donald Trump. So crazy sometimes that you ask yourself if they are even real! Is what you read something that actually happened or just a random collection of words made into a news headline? Need an example?" }, { "code": null, "e": 522, "s": 474, "text": "Donald Trump ‘Banned’ Unicorns ‘to North Korea’" }, { "code": null, "e": 684, "s": 522, "text": "Crazy, right? Granted, this headline is based on something the small kid of actress Alyssa Milano said. No grown up would come up with something so ridiculous..." }, { "code": null, "e": 772, "s": 684, "text": "“Donald Trump Is “A Unicorn, Riding A Unicorn Over A Rainbow”, According To Sean Spicer" }, { "code": null, "e": 1024, "s": 772, "text": "Oh boy.To me, that sounds like it was generated by a random sentence generator. While it sadly wasn’t, I wondered how much (or if) randomly generated news headlines could get crazier than that. So I decided to build a Python script and see for myself." }, { "code": null, "e": 1814, "s": 1024, "text": "The script consists of a quick web scraper to get as many news headlines as possible and use them in a Markov model sentence generator to create my very own ‘real fake news’ headline. Even though the Python dictionary data type seemed like an initial good fit for a Markov model, I wanted to use data frames and pandas for it. Simply because I wanted to practice some pandas functionalities and I am not ultimately interested in the most “elegant” way to do it in this case, but I wanted a quick result and learn something on the way.First, I set up a script which is accessing a popular news site using the keywords ‘Donald Trump’. I then isolated the text containing the headlines and wrote them into a text file. I found this website extremely helpful to set up my little piece of code:" }, { "code": null, "e": 3481, "s": 1814, "text": "https://realpython.com/python-web-scraping-practical-introduction/ On any day, this would give me about 100–120 news headlines. Not bad, but of course doing it once gives very little variety of words to work with and my Markov chain is running the risk of falling to often into a unique chain of words — and in the worst case - simply repeating and already existing news headline. Thankfully it is easy to set up a task scheduler in Windows which would execute my file every day in the background and let my text file grow continuously. All I had to do now is be patient and wait until a significant amount of headlines was accumulated. After about 1 1/2 weeks I had more than 1000 headlines. I decided that that is sufficient for such a highly unscientific and nonsensical project. After loading my text file and doing some coarse cleanup in eliminating some recurring news outlet signatures and double punctuation etc., I could finally start working the text into my Markov model. I decided to use a prefix or ‘lead’ of one word. I don’t want to get into details on Markov chains, but in very short I would summarize it like this: For each word we collect each following word in any sentence. Based on the frequency of a following word compared to its ‘rivals’, we will assign the likelihood of a word following a certain lead word. We can then start with a random word from the entire list of words in our text and then randomly select the next word in our sentence with probabilities based on the likelihoods we assigned. Word for word we will create a new sentence that is based on the properties of the text we used as input. Real news in → real fake news out." }, { "code": null, "e": 4603, "s": 3481, "text": "After splitting the text file into individual words and storing them in a variable ‘words’, I defined a pandas data frame with three columns: one column ‘lead’ defining the leading word. For each leading word, there is a word that ‘follows’ and be captured in our second column ‘follow’. The third column -‘freq’- will display how many times we can observe a certain combination of a ‘lead’ and a ‘follow’ in our text. What will we fill these columns with? Well, the first column is easy — simply every word in our text will be written in a row in this column. For every word with index i in our text, the following word is then the word with index i + 1. We simply start by filling the column ‘follow’ with our text again, but this time starting with the second word in the text. For a text of initially n rows, this fills n-1 “follow” words. The very last word in our text does not automatically have a follower, so we will use a synthetic string variable to fill the gap. I called it the ‘EndWord’ (please don’t confuse it with a similar sounding thing the president allegedly said on some mysterious apprentice tape)." }, { "code": null, "e": 4746, "s": 4603, "text": "import pandas as pddict_df = pd.DataFrame(columns = [‘lead’, ‘follow’, ‘freq’])dict_df['lead']=wordsfollow = words[1:]follow.append('EndWord')" }, { "code": null, "e": 5389, "s": 4746, "text": "Before I move on, I’ll create a separate array of words containing all the very last words of each sentence. In my later code, I will use these end-words to “naturally” end my randomly generated sentence. This has the nice side effect that I don’t have to worry about my Markov chain running ‘across’ headlines, meaning that the last word of one headline should not be considered a lead for the first word of the following headline. After all I am not dealing with one continuous text, but with individual and independent sentences. By cutting of my sentence after my sentence generator gets to such an end_word, this should not be a concern." }, { "code": null, "e": 5517, "s": 5389, "text": "end_words = []for word in words: if word[-1] in ['.','!','?'] and word != '.': end_words.append(word)print(end_words)" }, { "code": null, "e": 5681, "s": 5517, "text": "So far so good. Now I count the occurrence of each combination of lead- and follow word and assign the result to the frequency column using group_by and transform." }, { "code": null, "e": 5779, "s": 5681, "text": "dict_df['freq']= dict_df.groupby(by=['lead','follow'])['lead','follow'].transform('count').copy()" }, { "code": null, "e": 6105, "s": 5779, "text": "The rows are still not unique, so I delete duplicate rows before using the pivot functionality in Python to create one big matrix with every lead word as the row-index and every follow word as a column. The frequency of the combination of lead word in row i and following word in column j is then element a_ij in this matrix." }, { "code": null, "e": 6215, "s": 6105, "text": "dict_df = dict_df.drop_duplicates()pivot_df = dict_df.pivot(index = 'lead', columns= 'follow', values='freq')" }, { "code": null, "e": 6661, "s": 6215, "text": "For each row, I then summed up all frequencies and divided each element in row i by the total of row i. This leads to percentages summing up to 1 that my sentence generator will use as a probability distribution when selecting the follow word for a certain lead word. E.g. if after the word ‘fake’ we observe 7 times the follow word ‘news’ and 3 times the word ‘tan’, the resulting probabilities to be selected would be 0.7 and 0.3 respectively." }, { "code": null, "e": 6742, "s": 6661, "text": "sum_words = pivot_df.sum(axis=1)pivot_df = pivot_df.apply(lambda x: x/sum_words)" }, { "code": null, "e": 7868, "s": 6742, "text": "With all this in place, I can define my function for the sentence generator. I take one start word to initialize the sentence generator. This word could be a randomly chosen word from the set of all words. But since my text consists of only headlines of Donald Trump, I think it makes sense to make sure his name appears in our fake news headline as well. In my examples, I therefore start with ‘Donald’. Starting with this word, the generator selects a follow word based on the probability matrix we set up. It will continue by using the selected follow word as the new leading word to append word after word to our sentence. If the sentence generator gets to a word which is in our array of end-words, the sentence will take this word as the very last and return our sentence. If the generator gets to our synthetic ‘EndWord’ we defined earlier, it will simply draw a new follow word for the lead word that brought us down this dead-end road. The same applies if we get to an end word and our sentence is just 2 words long (I had a few example sentences that read only “Donald Trump.”. Like in “Donald Trump.” — nuff said)." }, { "code": null, "e": 8506, "s": 7868, "text": "from numpy.random import choicedef make_a_sentence(start): word= start sentence=[word] while len(sentence) < 30: next_word = choice(a = list(pivot_df.columns), p = (pivot_df.iloc[pivot_df.index ==word].fillna(0).values)[0]) if next_word == 'EndWord': continue elif next_word in end_words: if len(sentence) > 2: sentence.append(next_word) break else : continue else : sentence.append(next_word) word=next_word sentence = ' '.join(sentence) return sentencesentence = make_a_sentence('Donald')" }, { "code": null, "e": 8521, "s": 8506, "text": "And that’s it." }, { "code": null, "e": 8944, "s": 8521, "text": "I certainly won’t win a (Trump hosted) beauty pageant with this code, but it is quick, dirty, Python-noob friendly and does the job. Granted, the bigger the text, the slower the entire process of assigning probabilities will become, but as for my sample, it still took only a few seconds so I don’t see the need for time consuming optimization just yet. Let’s have a look at some of the ‘real fake news’ headlines instead:" }, { "code": null, "e": 9028, "s": 8944, "text": "Donald Trumps Criticism Of Trump Obsessed With Star Wars Burn. - (Sounds plausible)" }, { "code": null, "e": 9125, "s": 9028, "text": "Donald Trump broke the real Donald Trump loyalty test.- (How cool would it be if that happened?)" }, { "code": null, "e": 9202, "s": 9125, "text": "Donald Trump’s Team Files Complaint Against Whites.- (Yeah.... probably not)" }, { "code": null, "e": 9252, "s": 9202, "text": "Donald Trumps best people boast.- (His worst too)" }, { "code": null, "e": 9329, "s": 9252, "text": "Donald Trumps aides feel his presidency this fall.- (We all do... we all do)" }, { "code": null, "e": 9429, "s": 9329, "text": "Donald Trump, Omarosa, and other individuals, including the 45th president is Junior Mint.-(Fresh?)" }, { "code": null, "e": 9494, "s": 9429, "text": "Donald Trump, you are so far.-(Maybe a bit too far for my taste)" }, { "code": null, "e": 9640, "s": 9494, "text": "Of course these are some of the successful examples. A lot of sentences come out as absolute gibberish (not covfefe worthy, but still gibberish):" }, { "code": null, "e": 9737, "s": 9640, "text": "Donald Trump Know Who Aretha Franklin Work for Utahs former aide Omarosa Manigault Newman.-(???)" }, { "code": null, "e": 9993, "s": 9737, "text": "So what did we learn through this? You as a reader, probably not much. But I had a few good laughs with my code and got to work on data in a structure I usually wouldn’t encounter. If you have feedback or suggestion, please feel free to reach out. Thanks!" }, { "code": null, "e": 9999, "s": 9993, "text": "P.S.:" } ]
Count number of ways to jump to reach end - GeeksforGeeks
26 Apr, 2021 Given an array of numbers where each element represents the max number of jumps that can be made forward from that element. For each array element, count the number of ways jumps can be made from that element to reach the end of the array. If an element is 0, then a move cannot be made through that element. The element that cannot reach the end should have a count “-1”. Examples: Input : {3, 2, 0, 1} Output : 2 1 -1 0 For 3 number of steps or jumps that can be taken are 1, 2 or 3. The different ways are: 3 -> 2 -> 1 3 -> 1 For 2 number of steps or jumps that can be taken are 1, or 2. The different ways are: 2 -> 1 For 0 number of steps or jumps that can be taken are 0. One cannot move forward from this point. For 1 number of steps or jumps that can be taken are 1. But the element is at the end so no jump is required. Input : {1, 3, 5, 8, 9, 1, 0, 7, 6, 8, 9} Output : 52 52 28 16 8 -1 -1 4 2 1 0 This problem is a variation of the Minimum number of jumps to reach end(Method 3). Here we need to count all the ways to reach the end from every cell.The solution is a modified version of the solution to the problem of the Minimum number of jumps to reach end(Method 3). This problem aims to count the different ways to jump from each element to reach the end. For each element, the count is being calculated by adding the counts of all those forward elements that can reach the end and to which the current element could reach + 1(if the element can directly reach the end). Algorithm: countWays(arr, n) Initialize array count_jump[n] = {0} count_jump[n-1] = 0 for i = n-2 to 0 if arr[i] >= (n-i-1) count_jump[i]++ for j=i+1; j < n-1 && j <= arr[i]+i; i++ if count_jump[j] != -1 count_jump[i] += count_jump[j] if count_jump[i] == 0 count_jump[i] = -1 for i = 0 to n-1 print count_jump[i] C++ Java Python3 C# PHP Javascript // C++ implementation to count number// of ways to jump to reach end#include <bits/stdc++.h>using namespace std; // function to count ways to jump to// reach end for each array elementvoid countWaysToJump(int arr[], int n){ // count_jump[i] store number of ways // arr[i] can reach to the end int count_jump[n]; memset(count_jump, 0, sizeof(count_jump)); // Last element does not require to jump. // Count ways to jump for remaining // elements for (int i=n-2; i>=0; i--) { // if the element can directly // jump to the end if (arr[i] >= n - i - 1) count_jump[i]++; // add the count of all the elements // that can reach to end and arr[i] can // reach to them for (int j=i+1; j < n-1 && j <= arr[i] + i; j++) // if element can reach to end then add // its count to count_jump[i] if (count_jump[j] != -1) count_jump[i] += count_jump[j]; // if arr[i] cannot reach to the end if (count_jump[i] == 0) count_jump[i] = -1; } // print count_jump for each // array element for (int i=0; i<n; i++) cout << count_jump[i] << " ";} // Driver program to test aboveint main(){ int arr[] = {1, 3, 5, 8, 9, 1, 0, 7, 6, 8, 9}; int n = sizeof(arr) / sizeof(arr[0]); countWaysToJump(arr, n); return 0;} // Java implementation to count number// of ways to jump to reach endimport java.util.Arrays; class GFG { // function to count ways to jump to // reach end for each array element static void countWaysToJump(int arr[], int n) { // count_jump[i] store number of ways // arr[i] can reach to the end int count_jump[] = new int[n]; Arrays.fill(count_jump, 0); // Last element does not require to jump. // Count ways to jump for remaining // elements for (int i = n-2; i >= 0; i--) { // if the element can directly // jump to the end if (arr[i] >= n - i - 1) count_jump[i]++; // add the count of all the elements // that can reach to end and arr[i] can // reach to them for (int j = i+1; j < n-1 && j <= arr[i] + i; j++) // if element can reach to end then add // its count to count_jump[i] if (count_jump[j] != -1) count_jump[i] += count_jump[j]; // if arr[i] cannot reach to the end if (count_jump[i] == 0) count_jump[i] = -1; } // print count_jump for each // array element for (int i = 0; i < n; i++) System.out.print(count_jump[i] + " "); } //driver code public static void main (String[] args) { int arr[] = {1, 3, 5, 8, 9, 1, 0, 7, 6, 8, 9}; int n = arr.length; countWaysToJump(arr, n); }} // This code is contributed by Anant Agarwal. # Python3 implementation to count# number of ways to jump to reach end # Function to count ways to jump to# reach end for each array elementdef countWaysToJump(arr, n): # count_jump[i] store number of ways # arr[i] can reach to the end count_jump = [0 for i in range(n)] # Last element does not require # to jump. Count ways to jump for # remaining elements for i in range(n - 2, -1, -1): # if the element can directly # jump to the end if (arr[i] >= n - i - 1): count_jump[i] += 1 # Add the count of all the elements # that can reach to end and arr[i] # can reach to them j = i + 1 while(j < n-1 and j <= arr[i] + i): # if element can reach to end then # add its count to count_jump[i] if (count_jump[j] != -1): count_jump[i] += count_jump[j] j += 1 # if arr[i] cannot reach to the end if (count_jump[i] == 0): count_jump[i] = -1 # print count_jump for each # array element for i in range(n): print(count_jump[i], end = " ") # Driver codearr = [1, 3, 5, 8, 9, 1, 0, 7, 6, 8, 9]n = len(arr)countWaysToJump(arr, n) # This code is contributed by Anant Agarwal. // C# implementation to count number// of ways to jump to reach endusing System; class GFG { // function to count ways to jump to // reach end for each array element static void countWaysToJump(int[] arr, int n) { // count_jump[i] store number of ways // arr[i] can reach to the end int[] count_jump = new int[n]; for(int i = 0; i < n; i++) count_jump[i] = 0; // Last element does not require to jump. // Count ways to jump for remaining // elements for (int i = n-2; i >= 0; i--) { // if the element can directly // jump to the end if (arr[i] >= n - i - 1) count_jump[i]++; // add the count of all the elements // that can reach to end and arr[i] can // reach to them for (int j = i+1; j < n-1 && j <= arr[i] + i; j++) // if element can reach to end then add // its count to count_jump[i] if (count_jump[j] != -1) count_jump[i] += count_jump[j]; // if arr[i] cannot reach to the end if (count_jump[i] == 0) count_jump[i] = -1; } // print count_jump for each // array element for (int i = 0; i < n; i++) Console.Write(count_jump[i] + " "); } // Driver code public static void Main () { int[] arr = {1, 3, 5, 8, 9, 1, 0, 7, 6, 8, 9}; int n = arr.Length; countWaysToJump(arr, n); }} // This code is contributed by ChitraNayal <?php// PHP implementation to count number// of ways to jump to reach end // function to count ways to jump to// reach end for each array elementfunction countWaysToJump($arr, $n){ // count_jump[i] store number of ways // arr[i] can reach to the end $count_jump; for($i = 0; $i < $n; $i++) $count_jump[$i] = 0; // Last element does not require to jump. // Count ways to jump for remaining // elements for ($i = $n - 2; $i >= 0; $i--) { // if the element can directly // jump to the end if ($arr[$i] >= $n - $i - 1) $count_jump[$i]++; // add the count of all the elements // that can reach to end and arr[i] // can reach to them for ($j = $i + 1; $j < $n - 1 && $j <= $arr[$i] + $i; $j++) // if element can reach to end then // add its count to count_jump[i] if ($count_jump[$j] != -1) $count_jump[$i] += $count_jump[$j]; // if arr[i] cannot reach to the end if ($count_jump[$i] == 0) $count_jump[$i] = -1; } // print count_jump for each // array element for ($i = 0; $i < $n; $i++) echo $count_jump[$i] . " ";} // Driver Code$arr = array(1, 3, 5, 8, 9, 1, 0, 7, 6, 8, 9);$n = count($arr);countWaysToJump($arr, $n); // This code is contributed by Rajput-Ji?> <script> // Javascript implementation to count number// of ways to jump to reach end // function to count ways to jump to // reach end for each array element function countWaysToJump(arr,n) { // count_jump[i] store number of ways // arr[i] can reach to the end let count_jump = new Array(n); for(let i=0;i<n;i++) { count_jump[i]=0; } // Last element does not require to jump. // Count ways to jump for remaining // elements for (let i = n-2; i >= 0; i--) { // if the element can directly // jump to the end if (arr[i] >= n - i - 1) count_jump[i]++; // add the count of all the elements // that can reach to end and arr[i] can // reach to them for (let j = i+1; j < n-1 && j <= arr[i] + i; j++) // if element can reach to end then add // its count to count_jump[i] if (count_jump[j] != -1) count_jump[i] += count_jump[j]; // if arr[i] cannot reach to the end if (count_jump[i] == 0) count_jump[i] = -1; } // print count_jump for each // array element for (let i = 0; i < n; i++) document.write(count_jump[i] + " "); } //driver code let arr=[1, 3, 5, 8, 9, 1, 0, 7, 6, 8, 9]; let n = arr.length; countWaysToJump(arr, n); // This code is contributed by avanitrachhadiya2155</script> Output: 52 52 28 16 8 -1 -1 4 2 1 0 Time Complexity: O(n2) in worst case. ukasp Rajput-Ji lakshaygupta2807 avanitrachhadiya2155 Arrays Dynamic Programming Arrays Dynamic Programming Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Window Sliding Technique Trapping Rain Water Reversal algorithm for array rotation Building Heap from Array Program to find sum of elements in a given array 0-1 Knapsack Problem | DP-10 Program for Fibonacci numbers Longest Common Subsequence | DP-4 Bellman–Ford Algorithm | DP-23 Floyd Warshall Algorithm | DP-16
[ { "code": null, "e": 24822, "s": 24794, "text": "\n26 Apr, 2021" }, { "code": null, "e": 25196, "s": 24822, "text": "Given an array of numbers where each element represents the max number of jumps that can be made forward from that element. For each array element, count the number of ways jumps can be made from that element to reach the end of the array. If an element is 0, then a move cannot be made through that element. The element that cannot reach the end should have a count “-1”. " }, { "code": null, "e": 25206, "s": 25196, "text": "Examples:" }, { "code": null, "e": 25740, "s": 25206, "text": "Input : {3, 2, 0, 1}\nOutput : 2 1 -1 0\nFor 3 number of steps or jumps that \ncan be taken are 1, 2 or 3. The different ways are:\n3 -> 2 -> 1\n3 -> 1\n\nFor 2 number of steps or jumps that \ncan be taken are 1, or 2. The different ways are:\n2 -> 1\n\nFor 0 number of steps or jumps that \ncan be taken are 0. \nOne cannot move forward from this point.\n\nFor 1 number of steps or jumps that \ncan be taken are 1. But the element is at\nthe end so no jump is required.\n\nInput : {1, 3, 5, 8, 9, 1, 0, 7, 6, 8, 9}\nOutput : 52 52 28 16 8 -1 -1 4 2 1 0" }, { "code": null, "e": 26317, "s": 25740, "text": "This problem is a variation of the Minimum number of jumps to reach end(Method 3). Here we need to count all the ways to reach the end from every cell.The solution is a modified version of the solution to the problem of the Minimum number of jumps to reach end(Method 3). This problem aims to count the different ways to jump from each element to reach the end. For each element, the count is being calculated by adding the counts of all those forward elements that can reach the end and to which the current element could reach + 1(if the element can directly reach the end)." }, { "code": null, "e": 26329, "s": 26317, "text": "Algorithm: " }, { "code": null, "e": 26722, "s": 26329, "text": "countWays(arr, n)\n Initialize array count_jump[n] = {0}\n\n count_jump[n-1] = 0\n for i = n-2 to 0\n if arr[i] >= (n-i-1)\n count_jump[i]++\n for j=i+1; j < n-1 && j <= arr[i]+i; i++\n if count_jump[j] != -1\n count_jump[i] += count_jump[j]\n if count_jump[i] == 0\n count_jump[i] = -1\n\n for i = 0 to n-1\n print count_jump[i]" }, { "code": null, "e": 26726, "s": 26722, "text": "C++" }, { "code": null, "e": 26731, "s": 26726, "text": "Java" }, { "code": null, "e": 26739, "s": 26731, "text": "Python3" }, { "code": null, "e": 26742, "s": 26739, "text": "C#" }, { "code": null, "e": 26746, "s": 26742, "text": "PHP" }, { "code": null, "e": 26757, "s": 26746, "text": "Javascript" }, { "code": "// C++ implementation to count number// of ways to jump to reach end#include <bits/stdc++.h>using namespace std; // function to count ways to jump to// reach end for each array elementvoid countWaysToJump(int arr[], int n){ // count_jump[i] store number of ways // arr[i] can reach to the end int count_jump[n]; memset(count_jump, 0, sizeof(count_jump)); // Last element does not require to jump. // Count ways to jump for remaining // elements for (int i=n-2; i>=0; i--) { // if the element can directly // jump to the end if (arr[i] >= n - i - 1) count_jump[i]++; // add the count of all the elements // that can reach to end and arr[i] can // reach to them for (int j=i+1; j < n-1 && j <= arr[i] + i; j++) // if element can reach to end then add // its count to count_jump[i] if (count_jump[j] != -1) count_jump[i] += count_jump[j]; // if arr[i] cannot reach to the end if (count_jump[i] == 0) count_jump[i] = -1; } // print count_jump for each // array element for (int i=0; i<n; i++) cout << count_jump[i] << \" \";} // Driver program to test aboveint main(){ int arr[] = {1, 3, 5, 8, 9, 1, 0, 7, 6, 8, 9}; int n = sizeof(arr) / sizeof(arr[0]); countWaysToJump(arr, n); return 0;}", "e": 28138, "s": 26757, "text": null }, { "code": "// Java implementation to count number// of ways to jump to reach endimport java.util.Arrays; class GFG { // function to count ways to jump to // reach end for each array element static void countWaysToJump(int arr[], int n) { // count_jump[i] store number of ways // arr[i] can reach to the end int count_jump[] = new int[n]; Arrays.fill(count_jump, 0); // Last element does not require to jump. // Count ways to jump for remaining // elements for (int i = n-2; i >= 0; i--) { // if the element can directly // jump to the end if (arr[i] >= n - i - 1) count_jump[i]++; // add the count of all the elements // that can reach to end and arr[i] can // reach to them for (int j = i+1; j < n-1 && j <= arr[i] + i; j++) // if element can reach to end then add // its count to count_jump[i] if (count_jump[j] != -1) count_jump[i] += count_jump[j]; // if arr[i] cannot reach to the end if (count_jump[i] == 0) count_jump[i] = -1; } // print count_jump for each // array element for (int i = 0; i < n; i++) System.out.print(count_jump[i] + \" \"); } //driver code public static void main (String[] args) { int arr[] = {1, 3, 5, 8, 9, 1, 0, 7, 6, 8, 9}; int n = arr.length; countWaysToJump(arr, n); }} // This code is contributed by Anant Agarwal.", "e": 29793, "s": 28138, "text": null }, { "code": "# Python3 implementation to count# number of ways to jump to reach end # Function to count ways to jump to# reach end for each array elementdef countWaysToJump(arr, n): # count_jump[i] store number of ways # arr[i] can reach to the end count_jump = [0 for i in range(n)] # Last element does not require # to jump. Count ways to jump for # remaining elements for i in range(n - 2, -1, -1): # if the element can directly # jump to the end if (arr[i] >= n - i - 1): count_jump[i] += 1 # Add the count of all the elements # that can reach to end and arr[i] # can reach to them j = i + 1 while(j < n-1 and j <= arr[i] + i): # if element can reach to end then # add its count to count_jump[i] if (count_jump[j] != -1): count_jump[i] += count_jump[j] j += 1 # if arr[i] cannot reach to the end if (count_jump[i] == 0): count_jump[i] = -1 # print count_jump for each # array element for i in range(n): print(count_jump[i], end = \" \") # Driver codearr = [1, 3, 5, 8, 9, 1, 0, 7, 6, 8, 9]n = len(arr)countWaysToJump(arr, n) # This code is contributed by Anant Agarwal.", "e": 31068, "s": 29793, "text": null }, { "code": "// C# implementation to count number// of ways to jump to reach endusing System; class GFG { // function to count ways to jump to // reach end for each array element static void countWaysToJump(int[] arr, int n) { // count_jump[i] store number of ways // arr[i] can reach to the end int[] count_jump = new int[n]; for(int i = 0; i < n; i++) count_jump[i] = 0; // Last element does not require to jump. // Count ways to jump for remaining // elements for (int i = n-2; i >= 0; i--) { // if the element can directly // jump to the end if (arr[i] >= n - i - 1) count_jump[i]++; // add the count of all the elements // that can reach to end and arr[i] can // reach to them for (int j = i+1; j < n-1 && j <= arr[i] + i; j++) // if element can reach to end then add // its count to count_jump[i] if (count_jump[j] != -1) count_jump[i] += count_jump[j]; // if arr[i] cannot reach to the end if (count_jump[i] == 0) count_jump[i] = -1; } // print count_jump for each // array element for (int i = 0; i < n; i++) Console.Write(count_jump[i] + \" \"); } // Driver code public static void Main () { int[] arr = {1, 3, 5, 8, 9, 1, 0, 7, 6, 8, 9}; int n = arr.Length; countWaysToJump(arr, n); }} // This code is contributed by ChitraNayal", "e": 32737, "s": 31068, "text": null }, { "code": "<?php// PHP implementation to count number// of ways to jump to reach end // function to count ways to jump to// reach end for each array elementfunction countWaysToJump($arr, $n){ // count_jump[i] store number of ways // arr[i] can reach to the end $count_jump; for($i = 0; $i < $n; $i++) $count_jump[$i] = 0; // Last element does not require to jump. // Count ways to jump for remaining // elements for ($i = $n - 2; $i >= 0; $i--) { // if the element can directly // jump to the end if ($arr[$i] >= $n - $i - 1) $count_jump[$i]++; // add the count of all the elements // that can reach to end and arr[i] // can reach to them for ($j = $i + 1; $j < $n - 1 && $j <= $arr[$i] + $i; $j++) // if element can reach to end then // add its count to count_jump[i] if ($count_jump[$j] != -1) $count_jump[$i] += $count_jump[$j]; // if arr[i] cannot reach to the end if ($count_jump[$i] == 0) $count_jump[$i] = -1; } // print count_jump for each // array element for ($i = 0; $i < $n; $i++) echo $count_jump[$i] . \" \";} // Driver Code$arr = array(1, 3, 5, 8, 9, 1, 0, 7, 6, 8, 9);$n = count($arr);countWaysToJump($arr, $n); // This code is contributed by Rajput-Ji?>", "e": 34113, "s": 32737, "text": null }, { "code": "<script> // Javascript implementation to count number// of ways to jump to reach end // function to count ways to jump to // reach end for each array element function countWaysToJump(arr,n) { // count_jump[i] store number of ways // arr[i] can reach to the end let count_jump = new Array(n); for(let i=0;i<n;i++) { count_jump[i]=0; } // Last element does not require to jump. // Count ways to jump for remaining // elements for (let i = n-2; i >= 0; i--) { // if the element can directly // jump to the end if (arr[i] >= n - i - 1) count_jump[i]++; // add the count of all the elements // that can reach to end and arr[i] can // reach to them for (let j = i+1; j < n-1 && j <= arr[i] + i; j++) // if element can reach to end then add // its count to count_jump[i] if (count_jump[j] != -1) count_jump[i] += count_jump[j]; // if arr[i] cannot reach to the end if (count_jump[i] == 0) count_jump[i] = -1; } // print count_jump for each // array element for (let i = 0; i < n; i++) document.write(count_jump[i] + \" \"); } //driver code let arr=[1, 3, 5, 8, 9, 1, 0, 7, 6, 8, 9]; let n = arr.length; countWaysToJump(arr, n); // This code is contributed by avanitrachhadiya2155</script>", "e": 35718, "s": 34113, "text": null }, { "code": null, "e": 35727, "s": 35718, "text": "Output: " }, { "code": null, "e": 35755, "s": 35727, "text": "52 52 28 16 8 -1 -1 4 2 1 0" }, { "code": null, "e": 35794, "s": 35755, "text": "Time Complexity: O(n2) in worst case. " }, { "code": null, "e": 35800, "s": 35794, "text": "ukasp" }, { "code": null, "e": 35810, "s": 35800, "text": "Rajput-Ji" }, { "code": null, "e": 35827, "s": 35810, "text": "lakshaygupta2807" }, { "code": null, "e": 35848, "s": 35827, "text": "avanitrachhadiya2155" }, { "code": null, "e": 35855, "s": 35848, "text": "Arrays" }, { "code": null, "e": 35875, "s": 35855, "text": "Dynamic Programming" }, { "code": null, "e": 35882, "s": 35875, "text": "Arrays" }, { "code": null, "e": 35902, "s": 35882, "text": "Dynamic Programming" }, { "code": null, "e": 36000, "s": 35902, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36025, "s": 36000, "text": "Window Sliding Technique" }, { "code": null, "e": 36045, "s": 36025, "text": "Trapping Rain Water" }, { "code": null, "e": 36083, "s": 36045, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 36108, "s": 36083, "text": "Building Heap from Array" }, { "code": null, "e": 36157, "s": 36108, "text": "Program to find sum of elements in a given array" }, { "code": null, "e": 36186, "s": 36157, "text": "0-1 Knapsack Problem | DP-10" }, { "code": null, "e": 36216, "s": 36186, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 36250, "s": 36216, "text": "Longest Common Subsequence | DP-4" }, { "code": null, "e": 36281, "s": 36250, "text": "Bellman–Ford Algorithm | DP-23" } ]