title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Instant getEpochSecond() method in Java with Examples - GeeksforGeeks
22 Nov, 2018 The getEpochSecond() method of Instant class is used to return the number of seconds from the Java epoch of 1970-01-01T00:00:00Z. It means the difference between time in seconds of this instance and time represented by “1970-01-01T00:00:00Z” is returned by this method. The epoch second count is a simple incrementing count of seconds where the second 0 is 1970-01-01T00:00:00Z. Syntax: public long getEpochSecond() Returns: This method returns the seconds from the epoch of 1970-01-01T00:00:00Z. Below programs illustrate the Instant.getEpochSecond() method: Program 1: // Java program to demonstrate// Instant.getEpochSecond() method import java.time.*; public class GFG { public static void main(String[] args) { // create instance object Instant instant = Instant.parse("2018-10-20T16:55:30.00Z"); // print Instant Value System.out.println("Instant: " + instant); // get epochValue using getEpochSecond long epochValue = instant.getEpochSecond(); // print results System.out.println("Java epoch Value: " + epochValue); }} Instant: 2018-10-20T16:55:30Z Java epoch Value: 1540054530 Program 2: // Java program to demonstrate// Instant.getEpochSecond() method import java.time.*; public class GFG { public static void main(String[] args) { // create current instance object Instant instant = Instant.now(); // print Instant Value System.out.println("Current Instant: " + instant); // get epochValue using getEpochSecond long epochValue = instant.getEpochSecond(); // print results System.out.println("Java epoch Value: " + epochValue); }} Current Instant: 2018-11-22T08:26:19.502Z Java epoch Value: 1542875179 Reference: https://docs.oracle.com/javase/10/docs/api/java/time/Instant.html#getEpochSecond() java-basics Java-Functions Java-Instant Java-time package Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Constructors in Java Exceptions in Java Functional Interfaces in Java Different ways of Reading a text file in Java Generics in Java Introduction to Java Comparator Interface in Java with Examples Internal Working of HashMap in Java Strings in Java
[ { "code": null, "e": 25225, "s": 25197, "text": "\n22 Nov, 2018" }, { "code": null, "e": 25604, "s": 25225, "text": "The getEpochSecond() method of Instant class is used to return the number of seconds from the Java epoch of 1970-01-01T00:00:00Z. It means the difference between time in seconds of this instance and time represented by “1970-01-01T00:00:00Z” is returned by this method. The epoch second count is a simple incrementing count of seconds where the second 0 is 1970-01-01T00:00:00Z." }, { "code": null, "e": 25612, "s": 25604, "text": "Syntax:" }, { "code": null, "e": 25641, "s": 25612, "text": "public long getEpochSecond()" }, { "code": null, "e": 25722, "s": 25641, "text": "Returns: This method returns the seconds from the epoch of 1970-01-01T00:00:00Z." }, { "code": null, "e": 25785, "s": 25722, "text": "Below programs illustrate the Instant.getEpochSecond() method:" }, { "code": null, "e": 25796, "s": 25785, "text": "Program 1:" }, { "code": "// Java program to demonstrate// Instant.getEpochSecond() method import java.time.*; public class GFG { public static void main(String[] args) { // create instance object Instant instant = Instant.parse(\"2018-10-20T16:55:30.00Z\"); // print Instant Value System.out.println(\"Instant: \" + instant); // get epochValue using getEpochSecond long epochValue = instant.getEpochSecond(); // print results System.out.println(\"Java epoch Value: \" + epochValue); }}", "e": 26364, "s": 25796, "text": null }, { "code": null, "e": 26424, "s": 26364, "text": "Instant: 2018-10-20T16:55:30Z\nJava epoch Value: 1540054530\n" }, { "code": null, "e": 26435, "s": 26424, "text": "Program 2:" }, { "code": "// Java program to demonstrate// Instant.getEpochSecond() method import java.time.*; public class GFG { public static void main(String[] args) { // create current instance object Instant instant = Instant.now(); // print Instant Value System.out.println(\"Current Instant: \" + instant); // get epochValue using getEpochSecond long epochValue = instant.getEpochSecond(); // print results System.out.println(\"Java epoch Value: \" + epochValue); }}", "e": 27017, "s": 26435, "text": null }, { "code": null, "e": 27089, "s": 27017, "text": "Current Instant: 2018-11-22T08:26:19.502Z\nJava epoch Value: 1542875179\n" }, { "code": null, "e": 27183, "s": 27089, "text": "Reference: https://docs.oracle.com/javase/10/docs/api/java/time/Instant.html#getEpochSecond()" }, { "code": null, "e": 27195, "s": 27183, "text": "java-basics" }, { "code": null, "e": 27210, "s": 27195, "text": "Java-Functions" }, { "code": null, "e": 27223, "s": 27210, "text": "Java-Instant" }, { "code": null, "e": 27241, "s": 27223, "text": "Java-time package" }, { "code": null, "e": 27246, "s": 27241, "text": "Java" }, { "code": null, "e": 27251, "s": 27246, "text": "Java" }, { "code": null, "e": 27349, "s": 27251, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27364, "s": 27349, "text": "Stream In Java" }, { "code": null, "e": 27385, "s": 27364, "text": "Constructors in Java" }, { "code": null, "e": 27404, "s": 27385, "text": "Exceptions in Java" }, { "code": null, "e": 27434, "s": 27404, "text": "Functional Interfaces in Java" }, { "code": null, "e": 27480, "s": 27434, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 27497, "s": 27480, "text": "Generics in Java" }, { "code": null, "e": 27518, "s": 27497, "text": "Introduction to Java" }, { "code": null, "e": 27561, "s": 27518, "text": "Comparator Interface in Java with Examples" }, { "code": null, "e": 27597, "s": 27561, "text": "Internal Working of HashMap in Java" } ]
PyQt5 QDial - Getting Slider's Value - GeeksforGeeks
07 Jul, 2020 In this article we will see how we can get slider’s value of the QDial. User can change the value with the help of mouse although we can change it programmatically with the help of setValue method. The slider forces the value to be within the legal range i.e value should be greater than or equal to the minimum value and it should be less than or equal to the maximum limit. Changing the value also changes the slider position. In order to do this we use value method with the QDial object Syntax : dial.value() Argument : It takes no argument Return : It returns integer 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 QDial object dial = QDial(self) # setting geometry to the dial dial.setGeometry(100, 100, 100, 100) # making notch visible dial.setNotchesVisible(True) # value value = 50 # setting value to the dial slider dial.setValue(value) # creating a label label = QLabel("GeeksforGeeks", self) # setting geometry to the label label.setGeometry(220, 125, 200, 60) # making label multiline label.setWordWrap(True) # getting slider value value = dial.value() # setting text to the label label.setText("Value : " + str(value)) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec()) Output : Python PyQt-QDial Python-gui Python-PyQt Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | Get unique values from a list Python | os.path.join() method Create a directory in Python Defaultdict in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n07 Jul, 2020" }, { "code": null, "e": 25966, "s": 25537, "text": "In this article we will see how we can get slider’s value of the QDial. User can change the value with the help of mouse although we can change it programmatically with the help of setValue method. The slider forces the value to be within the legal range i.e value should be greater than or equal to the minimum value and it should be less than or equal to the maximum limit. Changing the value also changes the slider position." }, { "code": null, "e": 26028, "s": 25966, "text": "In order to do this we use value method with the QDial object" }, { "code": null, "e": 26050, "s": 26028, "text": "Syntax : dial.value()" }, { "code": null, "e": 26082, "s": 26050, "text": "Argument : It takes no argument" }, { "code": null, "e": 26110, "s": 26082, "text": "Return : It returns integer" }, { "code": null, "e": 26138, "s": 26110, "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 QDial object dial = QDial(self) # setting geometry to the dial dial.setGeometry(100, 100, 100, 100) # making notch visible dial.setNotchesVisible(True) # value value = 50 # setting value to the dial slider dial.setValue(value) # creating a label label = QLabel(\"GeeksforGeeks\", self) # setting geometry to the label label.setGeometry(220, 125, 200, 60) # making label multiline label.setWordWrap(True) # getting slider value value = dial.value() # setting text to the label label.setText(\"Value : \" + str(value)) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())", "e": 27510, "s": 26138, "text": null }, { "code": null, "e": 27519, "s": 27510, "text": "Output :" }, { "code": null, "e": 27537, "s": 27519, "text": "Python PyQt-QDial" }, { "code": null, "e": 27548, "s": 27537, "text": "Python-gui" }, { "code": null, "e": 27560, "s": 27548, "text": "Python-PyQt" }, { "code": null, "e": 27567, "s": 27560, "text": "Python" }, { "code": null, "e": 27665, "s": 27567, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27697, "s": 27665, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27739, "s": 27697, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27781, "s": 27739, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27837, "s": 27781, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27864, "s": 27837, "text": "Python Classes and Objects" }, { "code": null, "e": 27903, "s": 27864, "text": "Python | Get unique values from a list" }, { "code": null, "e": 27934, "s": 27903, "text": "Python | os.path.join() method" }, { "code": null, "e": 27963, "s": 27934, "text": "Create a directory in Python" }, { "code": null, "e": 27985, "s": 27963, "text": "Defaultdict in Python" } ]
Counts Path in an Array - GeeksforGeeks
30 Apr, 2021 Given an array A consisting of positive integer, of size N. If the element in the array at index i is K then you can jump between index ranges (i + 1) to (i + K). The task is to find the number of possible ways to reach the end with module 109 + 7.The starting position is considered as index 0.Examples: Input: A = {5, 3, 1, 4, 3} Output: 6Input: A = {2, 3, 1, 1, 2} Output: 4 Naive Approach: We can form a recursive structure to solve the problem.Let F[i] denotes the number of paths starting at index i, at every index i if the element A[i] is K then the total number of ways the jump can be performed is: F(i) = F(i+1) + F(i+2) +...+ F(i+k), where i + k <= n, where F(n) = 1 By using this recursive formula we can solve the problem: C++ Java Python3 C# Javascript // C++ implementation of// the above approach#include <bits/stdc++.h>using namespace std; const int mod = 1e9 + 7; // Find the number of ways// to reach the endint ways(int i, int arr[], int n){ // Base case if (i == n - 1) return 1; int sum = 0; // Recursive structure for (int j = 1; j + i < n && j <= arr[i]; j++) { sum += (ways(i + j, arr, n)) % mod; sum %= mod; } return sum % mod;} // Driver codeint main(){ int arr[] = { 5, 3, 1, 4, 3 }; int n = sizeof(arr) / sizeof(arr[0]); cout << ways(0, arr, n) << endl; return 0;} // Java implementation of// the above approachimport java.io.*; class GFG{static int mod = 1000000000; // Find the number of ways// to reach the endstatic int ways(int i, int arr[], int n){ // Base case if (i == n - 1) return 1; int sum = 0; // Recursive structure for (int j = 1; j + i < n && j <= arr[i]; j++) { sum += (ways(i + j, arr, n)) % mod; sum %= mod; } return sum % mod;} // Driver codepublic static void main (String[] args){ int arr[] = { 5, 3, 1, 4, 3 }; int n = arr.length; System.out.println (ways(0, arr, n));}} // This code is contributed by ajit # Python3 implementation of# the above approach mod = 1e9 + 7; # Find the number of ways# to reach the enddef ways(i, arr, n): # Base case if (i == n - 1): return 1; sum = 0; # Recursive structure for j in range(1, arr[i] + 1): if(i + j < n): sum += (ways(i + j, arr, n)) % mod; sum %= mod; return int(sum % mod); # Driver codeif __name__ == '__main__': arr = [5, 3, 1, 4, 3]; n = len(arr); print(ways(0, arr, n)); # This code is contributed by PrinciRaj1992 // C# implementation of// the above approachusing System; class GFG{static int mod = 1000000000; // Find the number of ways// to reach the endstatic int ways(int i, int []arr, int n){ // Base case if (i == n - 1) return 1; int sum = 0; // Recursive structure for (int j = 1; j + i < n && j <= arr[i]; j++) { sum += (ways(i + j, arr, n)) % mod; sum %= mod; } return sum % mod;} // Driver codepublic static void Main (String[] args){ int []arr = { 5, 3, 1, 4, 3 }; int n = arr.Length; Console.WriteLine(ways(0, arr, n));}} // This code is contributed by 29AjayKumar <script> // Javascript implementation of the above approach let mod = 1000000000; // Find the number of ways // to reach the end function ways(i, arr, n) { // Base case if (i == n - 1) return 1; let sum = 0; // Recursive structure for (let j = 1; j + i < n && j <= arr[i]; j++) { sum += (ways(i + j, arr, n)) % mod; sum %= mod; } return sum % mod; } let arr = [ 5, 3, 1, 4, 3 ]; let n = arr.length; document.write(ways(0, arr, n)); </script> 6 Efficient Approach: In the previous approach, there are some calculations that are being done more than once. It will be better to store these values in a dp array and dp[i] will store the number of paths starting at index i and ending at the end of the array.Hence dp[0] will be the solution to the problem.Below is the implementation of the approach: C++ Java Python3 C# Javascript // C++ implementation#include <bits/stdc++.h>using namespace std; const int mod = 1e9 + 7; // find the number of ways to reach the endint ways(int arr[], int n){ // dp to store value int dp[n + 1]; // base case dp[n - 1] = 1; // Bottom up dp structure for (int i = n - 2; i >= 0; i--) { dp[i] = 0; // F[i] is dependent of // F[i+1] to F[i+k] for (int j = 1; ((j + i) < n && j <= arr[i]); j++) { dp[i] += dp[i + j]; dp[i] %= mod; } } // Return value of dp[0] return dp[0] % mod;} // Driver codeint main(){ int arr[] = { 5, 3, 1, 4, 3 }; int n = sizeof(arr) / sizeof(arr[0]); cout << ways(arr, n) % mod << endl; return 0;} // Java implementation of above approachclass GFG{ static final int mod = (int)(1e9 + 7); // find the number of ways to reach the end static int ways(int arr[], int n) { // dp to store value int dp[] = new int[n + 1]; // base case dp[n - 1] = 1; // Bottom up dp structure for (int i = n - 2; i >= 0; i--) { dp[i] = 0; // F[i] is dependent of // F[i+1] to F[i+k] for (int j = 1; ((j + i) < n && j <= arr[i]); j++) { dp[i] += dp[i + j]; dp[i] %= mod; } } // Return value of dp[0] return dp[0] % mod; } // Driver code public static void main (String[] args) { int arr[] = { 5, 3, 1, 4, 3 }; int n = arr.length; System.out.println(ways(arr, n) % mod); }} // This code is contributed by AnkitRai01 # Python3 implementation of above approachmod = 10**9 + 7 # find the number of ways to reach the enddef ways(arr, n): # dp to store value dp = [0] * (n + 1) # base case dp[n - 1] = 1 # Bottom up dp structure for i in range(n - 2, -1, -1): dp[i] = 0 # F[i] is dependent of # F[i + 1] to F[i + k] j = 1 while((j + i) < n and j <= arr[i]): dp[i] += dp[i + j] dp[i] %= mod j += 1 # Return value of dp[0] return dp[0] % mod # Driver codearr = [5, 3, 1, 4, 3 ]n = len(arr)print(ways(arr, n) % mod) # This code is contributed by SHUBHAMSINGH10 // C# implementation of above approachusing System; class GFG{ static readonly int mod = (int)(1e9 + 7); // find the number of ways to reach the end static int ways(int []arr, int n) { // dp to store value int []dp = new int[n + 1]; // base case dp[n - 1] = 1; // Bottom up dp structure for (int i = n - 2; i >= 0; i--) { dp[i] = 0; // F[i] is dependent of // F[i+1] to F[i+k] for (int j = 1; ((j + i) < n && j <= arr[i]); j++) { dp[i] += dp[i + j]; dp[i] %= mod; } } // Return value of dp[0] return dp[0] % mod; } // Driver code public static void Main (String[] args) { int []arr = { 5, 3, 1, 4, 3 }; int n = arr.Length; Console.WriteLine(ways(arr, n) % mod); }} // This code is contributed by Rajput-Ji <script> // Javascript implementation // of above approach let mod = (1e9 + 7); // find the number of ways // to reach the end function ways(arr, n) { // dp to store value let dp = new Array(n + 1); dp.fill(0); // base case dp[n - 1] = 1; // Bottom up dp structure for (let i = n - 2; i >= 0; i--) { dp[i] = 0; // F[i] is dependent of // F[i+1] to F[i+k] for (let j = 1; ((j + i) < n && j <= arr[i]); j++) { dp[i] += dp[i + j]; dp[i] %= mod; } } // Return value of dp[0] return dp[0] % mod; } let arr = [ 5, 3, 1, 4, 3 ]; let n = arr.length; document.write(ways(arr, n) % mod); </script> 6 Time Complexity: O(K) jit_t 29AjayKumar ankthon Rajput-Ji princiraj1992 SHUBHAMSINGH10 rameshtravel07 divyesh072019 tail-recursion Arrays Dynamic Programming Arrays Dynamic Programming Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Count pairs with given sum Chocolate Distribution Problem Window Sliding Technique Reversal algorithm for array rotation Next Greater Element 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": 26067, "s": 26039, "text": "\n30 Apr, 2021" }, { "code": null, "e": 26374, "s": 26067, "text": "Given an array A consisting of positive integer, of size N. If the element in the array at index i is K then you can jump between index ranges (i + 1) to (i + K). The task is to find the number of possible ways to reach the end with module 109 + 7.The starting position is considered as index 0.Examples: " }, { "code": null, "e": 26449, "s": 26374, "text": "Input: A = {5, 3, 1, 4, 3} Output: 6Input: A = {2, 3, 1, 1, 2} Output: 4 " }, { "code": null, "e": 26684, "s": 26451, "text": "Naive Approach: We can form a recursive structure to solve the problem.Let F[i] denotes the number of paths starting at index i, at every index i if the element A[i] is K then the total number of ways the jump can be performed is: " }, { "code": null, "e": 26755, "s": 26684, "text": "F(i) = F(i+1) + F(i+2) +...+ F(i+k), where i + k <= n, \nwhere F(n) = 1" }, { "code": null, "e": 26814, "s": 26755, "text": "By using this recursive formula we can solve the problem: " }, { "code": null, "e": 26818, "s": 26814, "text": "C++" }, { "code": null, "e": 26823, "s": 26818, "text": "Java" }, { "code": null, "e": 26831, "s": 26823, "text": "Python3" }, { "code": null, "e": 26834, "s": 26831, "text": "C#" }, { "code": null, "e": 26845, "s": 26834, "text": "Javascript" }, { "code": "// C++ implementation of// the above approach#include <bits/stdc++.h>using namespace std; const int mod = 1e9 + 7; // Find the number of ways// to reach the endint ways(int i, int arr[], int n){ // Base case if (i == n - 1) return 1; int sum = 0; // Recursive structure for (int j = 1; j + i < n && j <= arr[i]; j++) { sum += (ways(i + j, arr, n)) % mod; sum %= mod; } return sum % mod;} // Driver codeint main(){ int arr[] = { 5, 3, 1, 4, 3 }; int n = sizeof(arr) / sizeof(arr[0]); cout << ways(0, arr, n) << endl; return 0;}", "e": 27482, "s": 26845, "text": null }, { "code": "// Java implementation of// the above approachimport java.io.*; class GFG{static int mod = 1000000000; // Find the number of ways// to reach the endstatic int ways(int i, int arr[], int n){ // Base case if (i == n - 1) return 1; int sum = 0; // Recursive structure for (int j = 1; j + i < n && j <= arr[i]; j++) { sum += (ways(i + j, arr, n)) % mod; sum %= mod; } return sum % mod;} // Driver codepublic static void main (String[] args){ int arr[] = { 5, 3, 1, 4, 3 }; int n = arr.length; System.out.println (ways(0, arr, n));}} // This code is contributed by ajit", "e": 28163, "s": 27482, "text": null }, { "code": "# Python3 implementation of# the above approach mod = 1e9 + 7; # Find the number of ways# to reach the enddef ways(i, arr, n): # Base case if (i == n - 1): return 1; sum = 0; # Recursive structure for j in range(1, arr[i] + 1): if(i + j < n): sum += (ways(i + j, arr, n)) % mod; sum %= mod; return int(sum % mod); # Driver codeif __name__ == '__main__': arr = [5, 3, 1, 4, 3]; n = len(arr); print(ways(0, arr, n)); # This code is contributed by PrinciRaj1992", "e": 28695, "s": 28163, "text": null }, { "code": "// C# implementation of// the above approachusing System; class GFG{static int mod = 1000000000; // Find the number of ways// to reach the endstatic int ways(int i, int []arr, int n){ // Base case if (i == n - 1) return 1; int sum = 0; // Recursive structure for (int j = 1; j + i < n && j <= arr[i]; j++) { sum += (ways(i + j, arr, n)) % mod; sum %= mod; } return sum % mod;} // Driver codepublic static void Main (String[] args){ int []arr = { 5, 3, 1, 4, 3 }; int n = arr.Length; Console.WriteLine(ways(0, arr, n));}} // This code is contributed by 29AjayKumar", "e": 29379, "s": 28695, "text": null }, { "code": "<script> // Javascript implementation of the above approach let mod = 1000000000; // Find the number of ways // to reach the end function ways(i, arr, n) { // Base case if (i == n - 1) return 1; let sum = 0; // Recursive structure for (let j = 1; j + i < n && j <= arr[i]; j++) { sum += (ways(i + j, arr, n)) % mod; sum %= mod; } return sum % mod; } let arr = [ 5, 3, 1, 4, 3 ]; let n = arr.length; document.write(ways(0, arr, n)); </script>", "e": 29969, "s": 29379, "text": null }, { "code": null, "e": 29971, "s": 29969, "text": "6" }, { "code": null, "e": 30327, "s": 29973, "text": "Efficient Approach: In the previous approach, there are some calculations that are being done more than once. It will be better to store these values in a dp array and dp[i] will store the number of paths starting at index i and ending at the end of the array.Hence dp[0] will be the solution to the problem.Below is the implementation of the approach: " }, { "code": null, "e": 30331, "s": 30327, "text": "C++" }, { "code": null, "e": 30336, "s": 30331, "text": "Java" }, { "code": null, "e": 30344, "s": 30336, "text": "Python3" }, { "code": null, "e": 30347, "s": 30344, "text": "C#" }, { "code": null, "e": 30358, "s": 30347, "text": "Javascript" }, { "code": "// C++ implementation#include <bits/stdc++.h>using namespace std; const int mod = 1e9 + 7; // find the number of ways to reach the endint ways(int arr[], int n){ // dp to store value int dp[n + 1]; // base case dp[n - 1] = 1; // Bottom up dp structure for (int i = n - 2; i >= 0; i--) { dp[i] = 0; // F[i] is dependent of // F[i+1] to F[i+k] for (int j = 1; ((j + i) < n && j <= arr[i]); j++) { dp[i] += dp[i + j]; dp[i] %= mod; } } // Return value of dp[0] return dp[0] % mod;} // Driver codeint main(){ int arr[] = { 5, 3, 1, 4, 3 }; int n = sizeof(arr) / sizeof(arr[0]); cout << ways(arr, n) % mod << endl; return 0;}", "e": 31117, "s": 30358, "text": null }, { "code": "// Java implementation of above approachclass GFG{ static final int mod = (int)(1e9 + 7); // find the number of ways to reach the end static int ways(int arr[], int n) { // dp to store value int dp[] = new int[n + 1]; // base case dp[n - 1] = 1; // Bottom up dp structure for (int i = n - 2; i >= 0; i--) { dp[i] = 0; // F[i] is dependent of // F[i+1] to F[i+k] for (int j = 1; ((j + i) < n && j <= arr[i]); j++) { dp[i] += dp[i + j]; dp[i] %= mod; } } // Return value of dp[0] return dp[0] % mod; } // Driver code public static void main (String[] args) { int arr[] = { 5, 3, 1, 4, 3 }; int n = arr.length; System.out.println(ways(arr, n) % mod); }} // This code is contributed by AnkitRai01", "e": 32093, "s": 31117, "text": null }, { "code": "# Python3 implementation of above approachmod = 10**9 + 7 # find the number of ways to reach the enddef ways(arr, n): # dp to store value dp = [0] * (n + 1) # base case dp[n - 1] = 1 # Bottom up dp structure for i in range(n - 2, -1, -1): dp[i] = 0 # F[i] is dependent of # F[i + 1] to F[i + k] j = 1 while((j + i) < n and j <= arr[i]): dp[i] += dp[i + j] dp[i] %= mod j += 1 # Return value of dp[0] return dp[0] % mod # Driver codearr = [5, 3, 1, 4, 3 ]n = len(arr)print(ways(arr, n) % mod) # This code is contributed by SHUBHAMSINGH10", "e": 32751, "s": 32093, "text": null }, { "code": "// C# implementation of above approachusing System; class GFG{ static readonly int mod = (int)(1e9 + 7); // find the number of ways to reach the end static int ways(int []arr, int n) { // dp to store value int []dp = new int[n + 1]; // base case dp[n - 1] = 1; // Bottom up dp structure for (int i = n - 2; i >= 0; i--) { dp[i] = 0; // F[i] is dependent of // F[i+1] to F[i+k] for (int j = 1; ((j + i) < n && j <= arr[i]); j++) { dp[i] += dp[i + j]; dp[i] %= mod; } } // Return value of dp[0] return dp[0] % mod; } // Driver code public static void Main (String[] args) { int []arr = { 5, 3, 1, 4, 3 }; int n = arr.Length; Console.WriteLine(ways(arr, n) % mod); }} // This code is contributed by Rajput-Ji", "e": 33744, "s": 32751, "text": null }, { "code": "<script> // Javascript implementation // of above approach let mod = (1e9 + 7); // find the number of ways // to reach the end function ways(arr, n) { // dp to store value let dp = new Array(n + 1); dp.fill(0); // base case dp[n - 1] = 1; // Bottom up dp structure for (let i = n - 2; i >= 0; i--) { dp[i] = 0; // F[i] is dependent of // F[i+1] to F[i+k] for (let j = 1; ((j + i) < n && j <= arr[i]); j++) { dp[i] += dp[i + j]; dp[i] %= mod; } } // Return value of dp[0] return dp[0] % mod; } let arr = [ 5, 3, 1, 4, 3 ]; let n = arr.length; document.write(ways(arr, n) % mod); </script>", "e": 34607, "s": 33744, "text": null }, { "code": null, "e": 34609, "s": 34607, "text": "6" }, { "code": null, "e": 34634, "s": 34611, "text": "Time Complexity: O(K) " }, { "code": null, "e": 34640, "s": 34634, "text": "jit_t" }, { "code": null, "e": 34652, "s": 34640, "text": "29AjayKumar" }, { "code": null, "e": 34660, "s": 34652, "text": "ankthon" }, { "code": null, "e": 34670, "s": 34660, "text": "Rajput-Ji" }, { "code": null, "e": 34684, "s": 34670, "text": "princiraj1992" }, { "code": null, "e": 34699, "s": 34684, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 34714, "s": 34699, "text": "rameshtravel07" }, { "code": null, "e": 34728, "s": 34714, "text": "divyesh072019" }, { "code": null, "e": 34743, "s": 34728, "text": "tail-recursion" }, { "code": null, "e": 34750, "s": 34743, "text": "Arrays" }, { "code": null, "e": 34770, "s": 34750, "text": "Dynamic Programming" }, { "code": null, "e": 34777, "s": 34770, "text": "Arrays" }, { "code": null, "e": 34797, "s": 34777, "text": "Dynamic Programming" }, { "code": null, "e": 34895, "s": 34797, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34922, "s": 34895, "text": "Count pairs with given sum" }, { "code": null, "e": 34953, "s": 34922, "text": "Chocolate Distribution Problem" }, { "code": null, "e": 34978, "s": 34953, "text": "Window Sliding Technique" }, { "code": null, "e": 35016, "s": 34978, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 35037, "s": 35016, "text": "Next Greater Element" }, { "code": null, "e": 35066, "s": 35037, "text": "0-1 Knapsack Problem | DP-10" }, { "code": null, "e": 35096, "s": 35066, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 35130, "s": 35096, "text": "Longest Common Subsequence | DP-4" }, { "code": null, "e": 35161, "s": 35130, "text": "Bellman–Ford Algorithm | DP-23" } ]
PyQt5 – Set Icon for Check Box - GeeksforGeeks
22 Apr, 2020 In this article we will see about how to set icon to a check box. Setting icon to a check box is similar to setting icon to a main window, icon of check box appear in between the indicator and the check box it self below is how normal check box vs check box with icon looks like. In order to do this we will use setIcon method. Syntax : checkbox.setIcon(QIcon(‘icon.png’)) Argument : It takes file name or path as argument. Action performed : It will set icon to the check box 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 the check-box checkbox = QCheckBox('Geek ?', self) # setting geometry of check box checkbox.setGeometry(200, 150, 100, 30) # setting icon to check box checkbox.setIcon(QIcon('logo.png')) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec()) Output : 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 How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace() *args and **kwargs in Python Reading and Writing to text files in Python Create a Pandas DataFrame from Lists
[ { "code": null, "e": 25393, "s": 25365, "text": "\n22 Apr, 2020" }, { "code": null, "e": 25673, "s": 25393, "text": "In this article we will see about how to set icon to a check box. Setting icon to a check box is similar to setting icon to a main window, icon of check box appear in between the indicator and the check box it self below is how normal check box vs check box with icon looks like." }, { "code": null, "e": 25723, "s": 25675, "text": "In order to do this we will use setIcon method." }, { "code": null, "e": 25768, "s": 25723, "text": "Syntax : checkbox.setIcon(QIcon(‘icon.png’))" }, { "code": null, "e": 25819, "s": 25768, "text": "Argument : It takes file name or path as argument." }, { "code": null, "e": 25872, "s": 25819, "text": "Action performed : It will set icon to the check box" }, { "code": null, "e": 25901, "s": 25872, "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 the check-box checkbox = QCheckBox('Geek ?', self) # setting geometry of check box checkbox.setGeometry(200, 150, 100, 30) # setting icon to check box checkbox.setIcon(QIcon('logo.png')) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())", "e": 26812, "s": 25901, "text": null }, { "code": null, "e": 26821, "s": 26812, "text": "Output :" }, { "code": null, "e": 26832, "s": 26821, "text": "Python-gui" }, { "code": null, "e": 26844, "s": 26832, "text": "Python-PyQt" }, { "code": null, "e": 26851, "s": 26844, "text": "Python" }, { "code": null, "e": 26949, "s": 26851, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26967, "s": 26949, "text": "Python Dictionary" }, { "code": null, "e": 27002, "s": 26967, "text": "Read a file line by line in Python" }, { "code": null, "e": 27034, "s": 27002, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27056, "s": 27034, "text": "Enumerate() in Python" }, { "code": null, "e": 27098, "s": 27056, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 27128, "s": 27098, "text": "Iterate over a list in Python" }, { "code": null, "e": 27154, "s": 27128, "text": "Python String | replace()" }, { "code": null, "e": 27183, "s": 27154, "text": "*args and **kwargs in Python" }, { "code": null, "e": 27227, "s": 27183, "text": "Reading and Writing to text files in Python" } ]
SQLite - Triggers
SQLite Triggers are database callback functions, which are automatically performed/invoked when a specified database event occurs. Following are the important points about SQLite triggers − SQLite trigger may be specified to fire whenever a DELETE, INSERT or UPDATE of a particular database table occurs or whenever an UPDATE occurs on one or more specified columns of a table. SQLite trigger may be specified to fire whenever a DELETE, INSERT or UPDATE of a particular database table occurs or whenever an UPDATE occurs on one or more specified columns of a table. At this time, SQLite supports only FOR EACH ROW triggers, not FOR EACH STATEMENT triggers. Hence, explicitly specifying FOR EACH ROW is optional. At this time, SQLite supports only FOR EACH ROW triggers, not FOR EACH STATEMENT triggers. Hence, explicitly specifying FOR EACH ROW is optional. Both the WHEN clause and the trigger actions may access elements of the row being inserted, deleted, or updated using references of the form NEW.column-name and OLD.column-name, where column-name is the name of a column from the table that the trigger is associated with. Both the WHEN clause and the trigger actions may access elements of the row being inserted, deleted, or updated using references of the form NEW.column-name and OLD.column-name, where column-name is the name of a column from the table that the trigger is associated with. If a WHEN clause is supplied, the SQL statements specified are only executed for rows for which the WHEN clause is true. If no WHEN clause is supplied, the SQL statements are executed for all rows. If a WHEN clause is supplied, the SQL statements specified are only executed for rows for which the WHEN clause is true. If no WHEN clause is supplied, the SQL statements are executed for all rows. The BEFORE or AFTER keyword determines when the trigger actions will be executed relative to the insertion, modification, or removal of the associated row. The BEFORE or AFTER keyword determines when the trigger actions will be executed relative to the insertion, modification, or removal of the associated row. Triggers are automatically dropped when the table that they are associated with is dropped. Triggers are automatically dropped when the table that they are associated with is dropped. The table to be modified must exist in the same database as the table or view to which the trigger is attached and one must use just tablename not database.tablename. The table to be modified must exist in the same database as the table or view to which the trigger is attached and one must use just tablename not database.tablename. A special SQL function RAISE() may be used within a trigger-program to raise an exception. A special SQL function RAISE() may be used within a trigger-program to raise an exception. Following is the basic syntax of creating a trigger. CREATE TRIGGER trigger_name [BEFORE|AFTER] event_name ON table_name BEGIN -- Trigger logic goes here.... END; Here, event_name could be INSERT, DELETE, and UPDATE database operation on the mentioned table table_name. You can optionally specify FOR EACH ROW after table name. Following is the syntax for creating a trigger on an UPDATE operation on one or more specified columns of a table. CREATE TRIGGER trigger_name [BEFORE|AFTER] UPDATE OF column_name ON table_name BEGIN -- Trigger logic goes here.... END; Let us consider a case where we want to keep audit trial for every record being inserted in COMPANY table, which we create newly as follows (Drop COMPANY table if you already have it). sqlite> CREATE TABLE COMPANY( ID INT PRIMARY KEY NOT NULL, NAME TEXT NOT NULL, AGE INT NOT NULL, ADDRESS CHAR(50), SALARY REAL ); To keep audit trial, we will create a new table called AUDIT where the log messages will be inserted, whenever there is an entry in COMPANY table for a new record. sqlite> CREATE TABLE AUDIT( EMP_ID INT NOT NULL, ENTRY_DATE TEXT NOT NULL ); Here, ID is the AUDIT record ID, and EMP_ID is the ID which will come from COMPANY table and DATE will keep timestamp when the record will be created in COMPANY table. Now let's create a trigger on COMPANY table as follows − sqlite> CREATE TRIGGER audit_log AFTER INSERT ON COMPANY BEGIN INSERT INTO AUDIT(EMP_ID, ENTRY_DATE) VALUES (new.ID, datetime('now')); END; Now, we will start actual work, Let's start inserting record in COMPANY table which should result in creating an audit log record in AUDIT table. Create one record in COMPANY table as follows − sqlite> INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) VALUES (1, 'Paul', 32, 'California', 20000.00 ); This will create one record in COMPANY table, which is as follows − ID NAME AGE ADDRESS SALARY ---------- ---------- ---------- ---------- ---------- 1 Paul 32 California 20000.0 Same time, one record will be created in AUDIT table. This record is the result of a trigger, which we have created on INSERT operation in COMPANY table. Similarly, you can create your triggers on UPDATE and DELETE operations based on your requirements. EMP_ID ENTRY_DATE ---------- ------------------- 1 2013-04-05 06:26:00 You can list down all the triggers from sqlite_master table as follows − sqlite> SELECT name FROM sqlite_master WHERE type = 'trigger'; The above SQLite statement will list down only one entry as follows − name ---------- audit_log If you want to list down triggers on a particular table, then use AND clause with table name as follows − sqlite> SELECT name FROM sqlite_master WHERE type = 'trigger' AND tbl_name = 'COMPANY'; The above SQLite statement will also list down only one entry as follows − name ---------- audit_log Following is the DROP command, which can be used to drop an existing trigger. sqlite> DROP TRIGGER trigger_name; 25 Lectures 4.5 hours Sandip Bhattacharya 17 Lectures 1 hours Laurence Svekis 5 Lectures 51 mins Vinay Kumar Print Add Notes Bookmark this page
[ { "code": null, "e": 2828, "s": 2638, "text": "SQLite Triggers are database callback functions, which are automatically performed/invoked when a specified database event occurs. Following are the important points about SQLite triggers −" }, { "code": null, "e": 3016, "s": 2828, "text": "SQLite trigger may be specified to fire whenever a DELETE, INSERT or UPDATE of a particular database table occurs or whenever an UPDATE occurs on one or more specified columns of a table." }, { "code": null, "e": 3204, "s": 3016, "text": "SQLite trigger may be specified to fire whenever a DELETE, INSERT or UPDATE of a particular database table occurs or whenever an UPDATE occurs on one or more specified columns of a table." }, { "code": null, "e": 3350, "s": 3204, "text": "At this time, SQLite supports only FOR EACH ROW triggers, not FOR EACH STATEMENT triggers. Hence, explicitly specifying FOR EACH ROW is optional." }, { "code": null, "e": 3496, "s": 3350, "text": "At this time, SQLite supports only FOR EACH ROW triggers, not FOR EACH STATEMENT triggers. Hence, explicitly specifying FOR EACH ROW is optional." }, { "code": null, "e": 3768, "s": 3496, "text": "Both the WHEN clause and the trigger actions may access elements of the row being inserted, deleted, or updated using references of the form NEW.column-name and OLD.column-name, where column-name is the name of a column from the table that the trigger is associated with." }, { "code": null, "e": 4040, "s": 3768, "text": "Both the WHEN clause and the trigger actions may access elements of the row being inserted, deleted, or updated using references of the form NEW.column-name and OLD.column-name, where column-name is the name of a column from the table that the trigger is associated with." }, { "code": null, "e": 4238, "s": 4040, "text": "If a WHEN clause is supplied, the SQL statements specified are only executed for rows for which the WHEN clause is true. If no WHEN clause is supplied, the SQL statements are executed for all rows." }, { "code": null, "e": 4436, "s": 4238, "text": "If a WHEN clause is supplied, the SQL statements specified are only executed for rows for which the WHEN clause is true. If no WHEN clause is supplied, the SQL statements are executed for all rows." }, { "code": null, "e": 4592, "s": 4436, "text": "The BEFORE or AFTER keyword determines when the trigger actions will be executed relative to the insertion, modification, or removal of the associated row." }, { "code": null, "e": 4748, "s": 4592, "text": "The BEFORE or AFTER keyword determines when the trigger actions will be executed relative to the insertion, modification, or removal of the associated row." }, { "code": null, "e": 4840, "s": 4748, "text": "Triggers are automatically dropped when the table that they are associated with is dropped." }, { "code": null, "e": 4932, "s": 4840, "text": "Triggers are automatically dropped when the table that they are associated with is dropped." }, { "code": null, "e": 5099, "s": 4932, "text": "The table to be modified must exist in the same database as the table or view to which the trigger is attached and one must use just tablename not database.tablename." }, { "code": null, "e": 5266, "s": 5099, "text": "The table to be modified must exist in the same database as the table or view to which the trigger is attached and one must use just tablename not database.tablename." }, { "code": null, "e": 5357, "s": 5266, "text": "A special SQL function RAISE() may be used within a trigger-program to raise an exception." }, { "code": null, "e": 5448, "s": 5357, "text": "A special SQL function RAISE() may be used within a trigger-program to raise an exception." }, { "code": null, "e": 5501, "s": 5448, "text": "Following is the basic syntax of creating a trigger." }, { "code": null, "e": 5614, "s": 5501, "text": "CREATE TRIGGER trigger_name [BEFORE|AFTER] event_name \nON table_name\nBEGIN\n -- Trigger logic goes here....\nEND;\n" }, { "code": null, "e": 5779, "s": 5614, "text": "Here, event_name could be INSERT, DELETE, and UPDATE database operation on the mentioned table table_name. You can optionally specify FOR EACH ROW after table name." }, { "code": null, "e": 5894, "s": 5779, "text": "Following is the syntax for creating a trigger on an UPDATE operation on one or more specified columns of a table." }, { "code": null, "e": 6020, "s": 5894, "text": "CREATE TRIGGER trigger_name [BEFORE|AFTER] UPDATE OF column_name \nON table_name\nBEGIN\n -- Trigger logic goes here....\nEND;\n" }, { "code": null, "e": 6205, "s": 6020, "text": "Let us consider a case where we want to keep audit trial for every record being inserted in COMPANY table, which we create newly as follows (Drop COMPANY table if you already have it)." }, { "code": null, "e": 6397, "s": 6205, "text": "sqlite> CREATE TABLE COMPANY(\n ID INT PRIMARY KEY NOT NULL,\n NAME TEXT NOT NULL,\n AGE INT NOT NULL,\n ADDRESS CHAR(50),\n SALARY REAL\n);" }, { "code": null, "e": 6561, "s": 6397, "text": "To keep audit trial, we will create a new table called AUDIT where the log messages will be inserted, whenever there is an entry in COMPANY table for a new record." }, { "code": null, "e": 6644, "s": 6561, "text": "sqlite> CREATE TABLE AUDIT(\n EMP_ID INT NOT NULL,\n ENTRY_DATE TEXT NOT NULL\n);" }, { "code": null, "e": 6869, "s": 6644, "text": "Here, ID is the AUDIT record ID, and EMP_ID is the ID which will come from COMPANY table and DATE will keep timestamp when the record will be created in COMPANY table. Now let's create a trigger on COMPANY table as follows −" }, { "code": null, "e": 7013, "s": 6869, "text": "sqlite> CREATE TRIGGER audit_log AFTER INSERT \nON COMPANY\nBEGIN\n INSERT INTO AUDIT(EMP_ID, ENTRY_DATE) VALUES (new.ID, datetime('now'));\nEND;" }, { "code": null, "e": 7207, "s": 7013, "text": "Now, we will start actual work, Let's start inserting record in COMPANY table which should result in creating an audit log record in AUDIT table. Create one record in COMPANY table as follows −" }, { "code": null, "e": 7313, "s": 7207, "text": "sqlite> INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)\nVALUES (1, 'Paul', 32, 'California', 20000.00 );" }, { "code": null, "e": 7381, "s": 7313, "text": "This will create one record in COMPANY table, which is as follows −" }, { "code": null, "e": 7551, "s": 7381, "text": "ID NAME AGE ADDRESS SALARY\n---------- ---------- ---------- ---------- ----------\n1 Paul 32 California 20000.0" }, { "code": null, "e": 7805, "s": 7551, "text": "Same time, one record will be created in AUDIT table. This record is the result of a trigger, which we have created on INSERT operation in COMPANY table. Similarly, you can create your triggers on UPDATE and DELETE operations based on your requirements." }, { "code": null, "e": 7892, "s": 7805, "text": "EMP_ID ENTRY_DATE\n---------- -------------------\n1 2013-04-05 06:26:00" }, { "code": null, "e": 7965, "s": 7892, "text": "You can list down all the triggers from sqlite_master table as follows −" }, { "code": null, "e": 8028, "s": 7965, "text": "sqlite> SELECT name FROM sqlite_master\nWHERE type = 'trigger';" }, { "code": null, "e": 8098, "s": 8028, "text": "The above SQLite statement will list down only one entry as follows −" }, { "code": null, "e": 8124, "s": 8098, "text": "name\n----------\naudit_log" }, { "code": null, "e": 8230, "s": 8124, "text": "If you want to list down triggers on a particular table, then use AND clause with table name as follows −" }, { "code": null, "e": 8318, "s": 8230, "text": "sqlite> SELECT name FROM sqlite_master\nWHERE type = 'trigger' AND tbl_name = 'COMPANY';" }, { "code": null, "e": 8393, "s": 8318, "text": "The above SQLite statement will also list down only one entry as follows −" }, { "code": null, "e": 8419, "s": 8393, "text": "name\n----------\naudit_log" }, { "code": null, "e": 8497, "s": 8419, "text": "Following is the DROP command, which can be used to drop an existing trigger." }, { "code": null, "e": 8532, "s": 8497, "text": "sqlite> DROP TRIGGER trigger_name;" }, { "code": null, "e": 8567, "s": 8532, "text": "\n 25 Lectures \n 4.5 hours \n" }, { "code": null, "e": 8588, "s": 8567, "text": " Sandip Bhattacharya" }, { "code": null, "e": 8621, "s": 8588, "text": "\n 17 Lectures \n 1 hours \n" }, { "code": null, "e": 8638, "s": 8621, "text": " Laurence Svekis" }, { "code": null, "e": 8669, "s": 8638, "text": "\n 5 Lectures \n 51 mins\n" }, { "code": null, "e": 8682, "s": 8669, "text": " Vinay Kumar" }, { "code": null, "e": 8689, "s": 8682, "text": " Print" }, { "code": null, "e": 8700, "s": 8689, "text": " Add Notes" } ]
Rank of All Elements in an Array using C++
In the given problem, we need to rank all the given elements of an array, with the smallest number having the smallest rank and the largest having the largest rank. We also need to change the ranks of a number depending on their frequencies, for examples − Input : 20 30 10 Output : 2.0 3.0 1.0 Input : 10 12 15 12 10 25 12 Output : 1.5, 4.0, 6.0, 4.0, 1.5, 7.0, 4.0 Here the rank of 10 is 1.5 because there are two 10s present in the given array now if we assume they both take different ranks i.e. 1 and 2 and we thus divide it within themselves so their rank becomes 1.5 and 1.5. Input : 1, 2, 5, 2, 1, 60, 3 Output : 1.5, 3.5, 6.0, 3.5, 1.5, 7.0, 5.0 There are two different approaches to find the solution, and they are − In this approach, we will loop, select any particular element, and determine its rank. #include <bits/stdc++.h> using namespace std; int main() { int arr[] = {1, 2, 5, 2, 1, 25, 2}; // given array int n = sizeof(arr) / sizeof(arr[0]); // size of our given array float rank[n] = {0}; // our ranking array for (int i = 0; i < n; i++) { int r = 1; // the number of elements greater than arr[i] int s = 1; // the number of elements equal to arr[i] for (int j = 0; j < n; j++) { if (j != i && arr[j] < arr[i]) r += 1; if (j != i && arr[j] == arr[i]) s += 1; } rank[i] = r + (float)(s - 1) / (float) 2; // using formula //to obtain rank of particular element } for (int i = 0; i < n; i++) // outputting the ranks cout << rank[i] << ' '; return 0; } 1.5 4 6 4 1.5 7 4 This program has a time complexity of O(N*N) where N is the size of a given array now; as you can see, our time complexity is not good, so we will increase its efficiency to work for higher constraints well. In this approach, we are going to take a new array and sort it now as the array is sorted now we know that all the elements of the same rank will be together, so now we rank them as usual and then calculate the rank of a particular element. #include <bits/stdc++.h> using namespace std; int main() { int arr[] = {1, 2, 5, 2, 1, 60, 3}; // given array int n = sizeof(arr) / sizeof(arr[0]); // size of our given array float rank[n] = {0}; // our ranking array int old[n]; for(int i = 0; i < n; i++) old[i] = arr[i]; sort(arr, arr+n); // sorting the array int prev = arr[0]; int r = 1; // ranks int s = 0; // frequency int tot = 0; // will stack up all the rank contained by an element map<int, float> rrank; for (int i = 0; i < n; i++) { if(prev == arr[i]) { s++; tot += r; } else { float now = 0; now = (float)tot/s; // dividing the ranks equally rrank[prev] = now; prev = arr[i]; tot = r; s = 1; } r++; } rrank[arr[n-1]] = (float)tot/s; for (int i = 0; i < n; i++) // outputting the ranks cout << rrank[old[i]] << " "; return 0; } 1.5 3.5 6 3.5 1.5 7 5 In this approach, we sort our array, and then we rank each of the elements from the starting (ranks starting from 1). Now, if our prev element is equal to our current element, we increase s and stack up to our sum of ranks. When our elements are changed, we divide the ranks among previous elements, refresh s and total, and continue our code. In this article, we solve a problem to find the Rank of all elements in an array. We also learned the C++ program for this problem and the complete approach ( Normal and efficient ) by which we solved this problem. We can write the same program in other languages such as C, java, python, and other languages.
[ { "code": null, "e": 1319, "s": 1062, "text": "In the given problem, we need to rank all the given elements of an array, with the smallest number having the smallest rank and the largest having the largest rank. We also need to change the ranks of a number depending on their frequencies, for examples −" }, { "code": null, "e": 1720, "s": 1319, "text": "Input : 20 30 10\nOutput : 2.0 3.0 1.0\n\nInput : 10 12 15 12 10 25 12\nOutput : 1.5, 4.0, 6.0, 4.0, 1.5, 7.0, 4.0\n\nHere the rank of 10 is 1.5 because there are two 10s present in the given array now if we assume they both take different ranks i.e. 1 and 2 and we thus divide it within themselves so their rank becomes 1.5 and 1.5.\n\nInput : 1, 2, 5, 2, 1, 60, 3\nOutput : 1.5, 3.5, 6.0, 3.5, 1.5, 7.0, 5.0" }, { "code": null, "e": 1792, "s": 1720, "text": "There are two different approaches to find the solution, and they are −" }, { "code": null, "e": 1879, "s": 1792, "text": "In this approach, we will loop, select any particular element, and determine its rank." }, { "code": null, "e": 2650, "s": 1879, "text": "#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n int arr[] = {1, 2, 5, 2, 1, 25, 2}; // given array\n int n = sizeof(arr) / sizeof(arr[0]); // size of our given array\n\n float rank[n] = {0}; // our ranking array\n for (int i = 0; i < n; i++) {\n int r = 1; // the number of elements greater than arr[i]\n int s = 1; // the number of elements equal to arr[i]\n\n for (int j = 0; j < n; j++) {\n if (j != i && arr[j] < arr[i])\n r += 1;\n \n if (j != i && arr[j] == arr[i])\n s += 1;\n }\n rank[i] = r + (float)(s - 1) / (float) 2; // using formula\n //to obtain rank of particular element\n\n }\n\n for (int i = 0; i < n; i++) // outputting the ranks\n cout << rank[i] << ' ';\n\n return 0;\n}" }, { "code": null, "e": 2668, "s": 2650, "text": "1.5 4 6 4 1.5 7 4" }, { "code": null, "e": 2876, "s": 2668, "text": "This program has a time complexity of O(N*N) where N is the size of a given array now; as you can see, our time complexity is not good, so we will increase its efficiency to work for higher constraints well." }, { "code": null, "e": 3117, "s": 2876, "text": "In this approach, we are going to take a new array and sort it now as the array is sorted now we know that all the elements of the same rank will be together, so now we rank them as usual and then calculate the rank of a particular element." }, { "code": null, "e": 4064, "s": 3117, "text": "#include <bits/stdc++.h>\n\nusing namespace std;\n\nint main() {\n int arr[] = {1, 2, 5, 2, 1, 60, 3}; // given array\n int n = sizeof(arr) / sizeof(arr[0]); // size of our given array\n float rank[n] = {0}; // our ranking array\n int old[n];\n for(int i = 0; i < n; i++)\n old[i] = arr[i];\n sort(arr, arr+n); // sorting the array\n int prev = arr[0];\n int r = 1; // ranks\n int s = 0; // frequency\n int tot = 0; // will stack up all the rank contained by an element\n map<int, float> rrank;\n\n for (int i = 0; i < n; i++) {\n if(prev == arr[i]) {\n s++;\n tot += r;\n } else {\n float now = 0;\n now = (float)tot/s; // dividing the ranks equally\n rrank[prev] = now;\n prev = arr[i];\n tot = r;\n s = 1;\n }\n r++;\n }\n rrank[arr[n-1]] = (float)tot/s;\n for (int i = 0; i < n; i++) // outputting the ranks\n cout << rrank[old[i]] << \" \";\n\n return 0;\n}" }, { "code": null, "e": 4086, "s": 4064, "text": "1.5 3.5 6 3.5 1.5 7 5" }, { "code": null, "e": 4430, "s": 4086, "text": "In this approach, we sort our array, and then we rank each of the elements from the starting (ranks starting from 1). Now, if our prev element is equal to our current element, we increase s and stack up to our sum of ranks. When our elements are changed, we divide the ranks among previous elements, refresh s and total, and continue our code." }, { "code": null, "e": 4740, "s": 4430, "text": "In this article, we solve a problem to find the Rank of all elements in an array. We also learned the C++ program for this problem and the complete approach ( Normal and efficient ) by which we solved this problem. We can write the same program in other languages such as C, java, python, and other languages." } ]
CSV Full Form - GeeksforGeeks
12 Jun, 2020 Comma Separated Value (CSV) is a text file containing data contents. It facilitates the storage of data in a table like structure. CSV files are stored with a CSV extension.The data fields in a ksd)(*&^%$#@nslnl like in databases or spreadsheets CSV are usually separated by delimiters, a space or a comma 1. alex, 528, IT 2. mallika, 650, Commerce 3. joy, 670, Humanities 4. yash, 679, IT The CSV files are used for transferring large databases between multiple programs maintaining a strict format. The CSV files can be opened with any text editor, Notepad, Excel etc Characteristics : The data fields are separated by commasEach data record is entered in a new line. In case the record is too large, it can cover multiple lines.The fields containing commas are separated by double-quotes are contained in a set of double quotes.The fields containing double quotes are contained in a set of double quotes.The space characters that are next to built-in commas are not taken into account. The data fields are separated by commas Each data record is entered in a new line. In case the record is too large, it can cover multiple lines. The fields containing commas are separated by double-quotes are contained in a set of double quotes. The fields containing double quotes are contained in a set of double quotes. The space characters that are next to built-in commas are not taken into account. Advantages : Faster in handling Easy to generate User friendly : processed by almost all apps and easy to read and understand. Easy implementation : easy to store and edit data and simple to parse the file. It is a standard format for a text file providing and easy to look straight forward data schema. Smaller in size : overcomes the redundancy of storage of header and footer tags. Disadvantages : No distinction between textual and numerical data. It facilitates the storage of simple data only. Complex fields are difficult to handle. Special characters and control characters are not represented correctly Lack of standard way of denoting binary data. Picked DBMS Full Form DBMS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Types of Functional dependencies in DBMS Introduction of Relational Algebra in DBMS What is Temporary Table in SQL? Two Phase Locking Protocol KDD Process in Data Mining HTTP Full Form DBA Full Form CDMA Full Form Peripheral Component Interconnect (PCI) RDBMS Full Form
[ { "code": null, "e": 24304, "s": 24276, "text": "\n12 Jun, 2020" }, { "code": null, "e": 24610, "s": 24304, "text": "Comma Separated Value (CSV) is a text file containing data contents. It facilitates the storage of data in a table like structure. CSV files are stored with a CSV extension.The data fields in a ksd)(*&^%$#@nslnl like in databases or spreadsheets CSV are usually separated by delimiters, a space or a comma" }, { "code": null, "e": 24695, "s": 24610, "text": "1. alex, 528, IT\n2. mallika, 650, Commerce\n3. joy, 670, Humanities\n4. yash, 679, IT " }, { "code": null, "e": 24875, "s": 24695, "text": "The CSV files are used for transferring large databases between multiple programs maintaining a strict format. The CSV files can be opened with any text editor, Notepad, Excel etc" }, { "code": null, "e": 24893, "s": 24875, "text": "Characteristics :" }, { "code": null, "e": 25294, "s": 24893, "text": "The data fields are separated by commasEach data record is entered in a new line. In case the record is too large, it can cover multiple lines.The fields containing commas are separated by double-quotes are contained in a set of double quotes.The fields containing double quotes are contained in a set of double quotes.The space characters that are next to built-in commas are not taken into account." }, { "code": null, "e": 25334, "s": 25294, "text": "The data fields are separated by commas" }, { "code": null, "e": 25439, "s": 25334, "text": "Each data record is entered in a new line. In case the record is too large, it can cover multiple lines." }, { "code": null, "e": 25540, "s": 25439, "text": "The fields containing commas are separated by double-quotes are contained in a set of double quotes." }, { "code": null, "e": 25617, "s": 25540, "text": "The fields containing double quotes are contained in a set of double quotes." }, { "code": null, "e": 25699, "s": 25617, "text": "The space characters that are next to built-in commas are not taken into account." }, { "code": null, "e": 25712, "s": 25699, "text": "Advantages :" }, { "code": null, "e": 25731, "s": 25712, "text": "Faster in handling" }, { "code": null, "e": 25748, "s": 25731, "text": "Easy to generate" }, { "code": null, "e": 25826, "s": 25748, "text": "User friendly : processed by almost all apps and easy to read and understand." }, { "code": null, "e": 25906, "s": 25826, "text": "Easy implementation : easy to store and edit data and simple to parse the file." }, { "code": null, "e": 26003, "s": 25906, "text": "It is a standard format for a text file providing and easy to look straight forward data schema." }, { "code": null, "e": 26084, "s": 26003, "text": "Smaller in size : overcomes the redundancy of storage of header and footer tags." }, { "code": null, "e": 26100, "s": 26084, "text": "Disadvantages :" }, { "code": null, "e": 26151, "s": 26100, "text": "No distinction between textual and numerical data." }, { "code": null, "e": 26239, "s": 26151, "text": "It facilitates the storage of simple data only. Complex fields are difficult to handle." }, { "code": null, "e": 26311, "s": 26239, "text": "Special characters and control characters are not represented correctly" }, { "code": null, "e": 26357, "s": 26311, "text": "Lack of standard way of denoting binary data." }, { "code": null, "e": 26364, "s": 26357, "text": "Picked" }, { "code": null, "e": 26369, "s": 26364, "text": "DBMS" }, { "code": null, "e": 26379, "s": 26369, "text": "Full Form" }, { "code": null, "e": 26384, "s": 26379, "text": "DBMS" }, { "code": null, "e": 26482, "s": 26384, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26523, "s": 26482, "text": "Types of Functional dependencies in DBMS" }, { "code": null, "e": 26566, "s": 26523, "text": "Introduction of Relational Algebra in DBMS" }, { "code": null, "e": 26598, "s": 26566, "text": "What is Temporary Table in SQL?" }, { "code": null, "e": 26625, "s": 26598, "text": "Two Phase Locking Protocol" }, { "code": null, "e": 26652, "s": 26625, "text": "KDD Process in Data Mining" }, { "code": null, "e": 26667, "s": 26652, "text": "HTTP Full Form" }, { "code": null, "e": 26681, "s": 26667, "text": "DBA Full Form" }, { "code": null, "e": 26696, "s": 26681, "text": "CDMA Full Form" }, { "code": null, "e": 26736, "s": 26696, "text": "Peripheral Component Interconnect (PCI)" } ]
The MySQL Command-Line Client
The mysql is a simple SQL shell that has input line editing capabilities. It supports interactive and noninteractive usage. When it is used interactively, query results are presented in an ASCII-table format. When it is used noninteractively, like a filter, the result would be presented in tab-separated format. The output format can be changed with the help of command options. If there are issues because of insufficient memory for large result sets, the --quick option can be used. This forces the mysql to retrieve results from the server, a row at a time instead of retrieving the entire result set at once and buffering it in memory before it is being displayed. This is done by returning the result set with the help of the mysql_use_result() C API function which is present in the client/server library instead of mysql_store_result(). Using mysql is an easy task. It can be invoked from the prompt of the user’s command interpreter. It has been demonstrated below − shell> mysql db_name (or) shell> mysql --user=user_name --password db_name Enter password: your_password Then an SQL statement can be typed, and can be ended with ;, \g, or \G. Typing Control+C interrupts the current statement if there is such a statement, or cancels any partial input line if not. SQL statements can be executed in a script file (or batch file). It has been shown below − shell> mysql db_name < script.sql > output.tab On Unix, the mysql client logs statements which are executed interactively to a history file.
[ { "code": null, "e": 1375, "s": 1062, "text": "The mysql is a simple SQL shell that has input line editing capabilities. It supports interactive and noninteractive usage. When it is used interactively, query results are presented in an ASCII-table format. When it is used noninteractively, like a filter, the result would be presented in tab-separated format." }, { "code": null, "e": 1548, "s": 1375, "text": "The output format can be changed with the help of command options. If there are issues because of insufficient memory for large result sets, the --quick option can be used." }, { "code": null, "e": 1907, "s": 1548, "text": "This forces the mysql to retrieve results from the server, a row at a time instead of retrieving the entire result set at once and buffering it in memory before it is being displayed. This is done by returning the result set with the help of the mysql_use_result() C API function which is present in the client/server library instead of mysql_store_result()." }, { "code": null, "e": 2038, "s": 1907, "text": "Using mysql is an easy task. It can be invoked from the prompt of the user’s command interpreter. It has been demonstrated below −" }, { "code": null, "e": 2059, "s": 2038, "text": "shell> mysql db_name" }, { "code": null, "e": 2064, "s": 2059, "text": "(or)" }, { "code": null, "e": 2113, "s": 2064, "text": "shell> mysql --user=user_name --password db_name" }, { "code": null, "e": 2143, "s": 2113, "text": "Enter password: your_password" }, { "code": null, "e": 2215, "s": 2143, "text": "Then an SQL statement can be typed, and can be ended with ;, \\g, or \\G." }, { "code": null, "e": 2337, "s": 2215, "text": "Typing Control+C interrupts the current statement if there is such a statement, or cancels any partial input line if not." }, { "code": null, "e": 2428, "s": 2337, "text": "SQL statements can be executed in a script file (or batch file). It has been shown below −" }, { "code": null, "e": 2476, "s": 2428, "text": "shell> mysql db_name < script.sql > output.tab\n" }, { "code": null, "e": 2570, "s": 2476, "text": "On Unix, the mysql client logs statements which are executed interactively to a history file." } ]
Arranging words in Ascending order in a string - JavaScript
Let’s say, we are required to write a JavaScript function that takes in a string and returns a new string with words rearranged according to their increasing length. Following is the code − const str = 'This is a sample string only'; const arrangeByLength = str => { const strArr = str.split(' '); const sorted = strArr.sort((a, b) => { return a.length - b.length; }); return sorted.join(' '); }; console.log(arrangeByLength(str)); Following is the output in the console − a is This only sample string
[ { "code": null, "e": 1228, "s": 1062, "text": "Let’s say, we are required to write a JavaScript function that takes in a string and returns a new string with words rearranged according to their increasing length." }, { "code": null, "e": 1252, "s": 1228, "text": "Following is the code −" }, { "code": null, "e": 1512, "s": 1252, "text": "const str = 'This is a sample string only';\nconst arrangeByLength = str => {\n const strArr = str.split(' ');\n const sorted = strArr.sort((a, b) => {\n return a.length - b.length;\n });\n return sorted.join(' ');\n};\nconsole.log(arrangeByLength(str));" }, { "code": null, "e": 1553, "s": 1512, "text": "Following is the output in the console −" }, { "code": null, "e": 1582, "s": 1553, "text": "a is This only sample string" } ]
How to use setInterval function call in JavaScript?
The setInterval() method is JavaScript is used to evaluate an expression at intervals. Here’s the syntax: setInterval(function, interval_in_milliseconds, param1, param2, param3...) Here, interval_in_milliseconds sets the intervals in milliseconds, after the code will execute. param are the optional parameters, which is passend to the function. You can try to run the following code to use setInterval() function call Live Demo <!DOCTYPE html> <html> <body> <p id="test"></p> <script> var myVar = setInterval(function(){ displayTimer() }, 500); function displayTimer() { var date = new Date(); var time = date.toLocaleTimeString(); document.getElementById("test").innerHTML = "Time: "+time; } </script> </body> </html>
[ { "code": null, "e": 1168, "s": 1062, "text": "The setInterval() method is JavaScript is used to evaluate an expression at intervals. Here’s the syntax:" }, { "code": null, "e": 1243, "s": 1168, "text": "setInterval(function, interval_in_milliseconds, param1, param2, param3...)" }, { "code": null, "e": 1339, "s": 1243, "text": "Here, interval_in_milliseconds sets the intervals in milliseconds, after the code will execute." }, { "code": null, "e": 1408, "s": 1339, "text": "param are the optional parameters, which is passend to the function." }, { "code": null, "e": 1481, "s": 1408, "text": "You can try to run the following code to use setInterval() function call" }, { "code": null, "e": 1491, "s": 1481, "text": "Live Demo" }, { "code": null, "e": 1870, "s": 1491, "text": "<!DOCTYPE html>\n<html>\n <body>\n <p id=\"test\"></p>\n <script>\n var myVar = setInterval(function(){ displayTimer() }, 500);\n function displayTimer() {\n var date = new Date();\n var time = date.toLocaleTimeString();\n document.getElementById(\"test\").innerHTML = \"Time: \"+time;\n }\n </script>\n </body>\n</html>" } ]
Draw a line in C++ graphics
In this tutorial, we will be discussing a program to draw a line in C++ graphics. To implement different shapes and sizes, animations, graphics.h library is used in C++. #include <graphics.h> int main(){ int gd = DETECT, gm; initgraph(&gd, &gm, ""); line(150, 150, 450, 150); line(150, 200, 450, 200); line(150, 250, 450, 250); getch(); closegraph(); return 0; }
[ { "code": null, "e": 1144, "s": 1062, "text": "In this tutorial, we will be discussing a program to draw a line in C++ graphics." }, { "code": null, "e": 1232, "s": 1144, "text": "To implement different shapes and sizes, animations, graphics.h library is used in C++." }, { "code": null, "e": 1449, "s": 1232, "text": "#include <graphics.h>\nint main(){\n int gd = DETECT, gm;\n initgraph(&gd, &gm, \"\");\n line(150, 150, 450, 150);\n line(150, 200, 450, 200);\n line(150, 250, 450, 250);\n getch();\n closegraph();\n return 0;\n}" } ]
JDBC Delete Example | JDBC Delete Program | executeUpdate() JDBC
PROGRAMMINGJava ExamplesC Examples Java Examples C Examples C Tutorials aws JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC EXCEPTIONS COLLECTIONS SWING JDBC JAVA 8 SPRING SPRING BOOT HIBERNATE PYTHON PHP JQUERY PROGRAMMINGJava ExamplesC Examples Java Examples C Examples C Tutorials aws In this tutorials, we are going to understand the JDBC delete program example. To do the delete data from database in JDBC, the API has given us two different methods executeUpdate(String qry) and execute(String qry). By using the any one of those two, we can do the jdbc delete program in java. Here is the difference between the Jdbc executeUpdate() and execute(). executepdate() method returns the integer value. The value represents that the number of rows effected in the database. int rowsEffected = stmt.executepUpdate("delete command"); execute() method returns boolean value. As we already discussed in the JDBC select example, we can use the execute() method for both select and non-select (insert, update, delete) operations. If the resultant object contains ResultSet then the execute() method returns the true, it returns false if it is an update count or no records found. boolean isResultSet = stmt.executep("update command"); Here is the complete example for JDBC Delete. package com.onlinetutorialspoint.jdbc; import java.sql.Connection; import java.sql.DriverManager; import java.sql.Statement; import java.util.Scanner; public class Jdbc_DeleteOperation_Example { public static void main(String[] args) throws Exception { Scanner scanner = new Scanner(System.in); System.out.println("Enter Student Number to delete the record"); int studentNo = scanner.nextInt(); Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/onlinetutorialspoint", "root", "systemuser23!"); con.setAutoCommit(false); Statement stmt = con.createStatement(); String query = "delete from student where sid='" + studentNo + "'"; int result = stmt.executeUpdate(query); con.commit(); if (result == 0) { System.out.println("record not found to delete"); } else { System.out.println(result+" no.of record(s) found and deleted"); } stmt.close(); con.close(); } } Enter Student Number to delete the record 2002 1 record(s) found and deleted Happy Learning 🙂 HQL update, delete Query Example JDBC Interview Questions and Answers JDBC Select Program Example JDBC Insert Program Example JDBC Update Program Example JDBC PreparedStatement Example Program Step by Step JDBC Program Example Insert an Image using JDBC in Mysql DB Read an Image in JDBC Example CallableStatement in jdbc Example ResultSetMetaData in JDBC Example DatabaseMetaData in JDBC Example Transaction Management in JDBC Example Batch Processing in JDBC Example JDBC Connection with Properties file HQL update, delete Query Example JDBC Interview Questions and Answers JDBC Select Program Example JDBC Insert Program Example JDBC Update Program Example JDBC PreparedStatement Example Program Step by Step JDBC Program Example Insert an Image using JDBC in Mysql DB Read an Image in JDBC Example CallableStatement in jdbc Example ResultSetMetaData in JDBC Example DatabaseMetaData in JDBC Example Transaction Management in JDBC Example Batch Processing in JDBC Example JDBC Connection with Properties file Δ JDBC Driver Types Step by Step JDBC Program JDBC Select Program JDBC Insert Program JDBC Update Program JDBC Delete Program JDBC Connection – Properties File JDBC PreparedStatement Program JDBC – CallableStatement Example JDBC – Read an Image from DB JDBC – Insert an Image in DB JDBC – Updatable ResultSet JDBC – Scrollable ResultSet JDBC – ResultSetMetaData JDBC – DatabaseMetaData JDBC – Transaction Management JDBC – Batch Processing JDBC Interview Questions
[ { "code": null, "e": 158, "s": 123, "text": "PROGRAMMINGJava ExamplesC Examples" }, { "code": null, "e": 172, "s": 158, "text": "Java Examples" }, { "code": null, "e": 183, "s": 172, "text": "C Examples" }, { "code": null, "e": 195, "s": 183, "text": "C Tutorials" }, { "code": null, "e": 199, "s": 195, "text": "aws" }, { "code": null, "e": 234, "s": 199, "text": "JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC" }, { "code": null, "e": 245, "s": 234, "text": "EXCEPTIONS" }, { "code": null, "e": 257, "s": 245, "text": "COLLECTIONS" }, { "code": null, "e": 263, "s": 257, "text": "SWING" }, { "code": null, "e": 268, "s": 263, "text": "JDBC" }, { "code": null, "e": 275, "s": 268, "text": "JAVA 8" }, { "code": null, "e": 282, "s": 275, "text": "SPRING" }, { "code": null, "e": 294, "s": 282, "text": "SPRING BOOT" }, { "code": null, "e": 304, "s": 294, "text": "HIBERNATE" }, { "code": null, "e": 311, "s": 304, "text": "PYTHON" }, { "code": null, "e": 315, "s": 311, "text": "PHP" }, { "code": null, "e": 322, "s": 315, "text": "JQUERY" }, { "code": null, "e": 357, "s": 322, "text": "PROGRAMMINGJava ExamplesC Examples" }, { "code": null, "e": 371, "s": 357, "text": "Java Examples" }, { "code": null, "e": 382, "s": 371, "text": "C Examples" }, { "code": null, "e": 394, "s": 382, "text": "C Tutorials" }, { "code": null, "e": 398, "s": 394, "text": "aws" }, { "code": null, "e": 616, "s": 398, "text": "In this tutorials, we are going to understand the JDBC delete program example. To do the delete data from database in JDBC, the API has given us two different methods executeUpdate(String qry) and execute(String qry)." }, { "code": null, "e": 765, "s": 616, "text": "By using the any one of those two, we can do the jdbc delete program in java. Here is the difference between the Jdbc executeUpdate() and execute()." }, { "code": null, "e": 885, "s": 765, "text": "executepdate() method returns the integer value. The value represents that the number of rows effected in the database." }, { "code": null, "e": 943, "s": 885, "text": "int rowsEffected = stmt.executepUpdate(\"delete command\");" }, { "code": null, "e": 1285, "s": 943, "text": "execute() method returns boolean value. As we already discussed in the JDBC select example, we can use the execute() method for both select and non-select (insert, update, delete) operations. If the resultant object contains ResultSet then the execute() method returns the true, it returns false if it is an update count or no records found." }, { "code": null, "e": 1340, "s": 1285, "text": "boolean isResultSet = stmt.executep(\"update command\");" }, { "code": null, "e": 1386, "s": 1340, "text": "Here is the complete example for JDBC Delete." }, { "code": null, "e": 2506, "s": 1386, "text": "package com.onlinetutorialspoint.jdbc; \n \nimport java.sql.Connection; \nimport java.sql.DriverManager; \nimport java.sql.Statement; \nimport java.util.Scanner; \n \npublic class Jdbc_DeleteOperation_Example { \n \n public static void main(String[] args) throws Exception { \n \n Scanner scanner = new Scanner(System.in); \n System.out.println(\"Enter Student Number to delete the record\"); \n \n int studentNo = scanner.nextInt(); \n Class.forName(\"sun.jdbc.odbc.JdbcOdbcDriver\"); \n Connection con = DriverManager.getConnection(\"jdbc:mysql://localhost:3306/onlinetutorialspoint\", \"root\", \"systemuser23!\"); \n con.setAutoCommit(false); \n Statement stmt = con.createStatement(); \n String query = \"delete from student where sid='\" + studentNo + \"'\"; \n int result = stmt.executeUpdate(query); \n con.commit(); \n if (result == 0) { \n System.out.println(\"record not found to delete\"); \n } else { \n System.out.println(result+\" no.of record(s) found and deleted\"); \n } \n stmt.close(); \n con.close(); \n \n } \n \n}" }, { "code": null, "e": 2584, "s": 2506, "text": "Enter Student Number to delete the record\n2002\n1 record(s) found and deleted" }, { "code": null, "e": 2601, "s": 2584, "text": "Happy Learning 🙂" }, { "code": null, "e": 3109, "s": 2601, "text": "\nHQL update, delete Query Example\nJDBC Interview Questions and Answers\nJDBC Select Program Example\nJDBC Insert Program Example\nJDBC Update Program Example\nJDBC PreparedStatement Example Program\nStep by Step JDBC Program Example\nInsert an Image using JDBC in Mysql DB\nRead an Image in JDBC Example\nCallableStatement in jdbc Example\nResultSetMetaData in JDBC Example\nDatabaseMetaData in JDBC Example\nTransaction Management in JDBC Example\nBatch Processing in JDBC Example\nJDBC Connection with Properties file\n" }, { "code": null, "e": 3142, "s": 3109, "text": "HQL update, delete Query Example" }, { "code": null, "e": 3179, "s": 3142, "text": "JDBC Interview Questions and Answers" }, { "code": null, "e": 3207, "s": 3179, "text": "JDBC Select Program Example" }, { "code": null, "e": 3235, "s": 3207, "text": "JDBC Insert Program Example" }, { "code": null, "e": 3263, "s": 3235, "text": "JDBC Update Program Example" }, { "code": null, "e": 3302, "s": 3263, "text": "JDBC PreparedStatement Example Program" }, { "code": null, "e": 3336, "s": 3302, "text": "Step by Step JDBC Program Example" }, { "code": null, "e": 3375, "s": 3336, "text": "Insert an Image using JDBC in Mysql DB" }, { "code": null, "e": 3405, "s": 3375, "text": "Read an Image in JDBC Example" }, { "code": null, "e": 3439, "s": 3405, "text": "CallableStatement in jdbc Example" }, { "code": null, "e": 3473, "s": 3439, "text": "ResultSetMetaData in JDBC Example" }, { "code": null, "e": 3506, "s": 3473, "text": "DatabaseMetaData in JDBC Example" }, { "code": null, "e": 3545, "s": 3506, "text": "Transaction Management in JDBC Example" }, { "code": null, "e": 3578, "s": 3545, "text": "Batch Processing in JDBC Example" }, { "code": null, "e": 3615, "s": 3578, "text": "JDBC Connection with Properties file" }, { "code": null, "e": 3621, "s": 3619, "text": "Δ" }, { "code": null, "e": 3640, "s": 3621, "text": " JDBC Driver Types" }, { "code": null, "e": 3667, "s": 3640, "text": " Step by Step JDBC Program" }, { "code": null, "e": 3688, "s": 3667, "text": " JDBC Select Program" }, { "code": null, "e": 3709, "s": 3688, "text": " JDBC Insert Program" }, { "code": null, "e": 3730, "s": 3709, "text": " JDBC Update Program" }, { "code": null, "e": 3751, "s": 3730, "text": " JDBC Delete Program" }, { "code": null, "e": 3786, "s": 3751, "text": " JDBC Connection – Properties File" }, { "code": null, "e": 3818, "s": 3786, "text": " JDBC PreparedStatement Program" }, { "code": null, "e": 3852, "s": 3818, "text": " JDBC – CallableStatement Example" }, { "code": null, "e": 3882, "s": 3852, "text": " JDBC – Read an Image from DB" }, { "code": null, "e": 3912, "s": 3882, "text": " JDBC – Insert an Image in DB" }, { "code": null, "e": 3940, "s": 3912, "text": " JDBC – Updatable ResultSet" }, { "code": null, "e": 3969, "s": 3940, "text": " JDBC – Scrollable ResultSet" }, { "code": null, "e": 3995, "s": 3969, "text": " JDBC – ResultSetMetaData" }, { "code": null, "e": 4020, "s": 3995, "text": " JDBC – DatabaseMetaData" }, { "code": null, "e": 4051, "s": 4020, "text": " JDBC – Transaction Management" }, { "code": null, "e": 4076, "s": 4051, "text": " JDBC – Batch Processing" } ]
All the Steps to Build your first Image Classifier (with code) | by Arthur Arnx | Towards Data Science
If you want to create an image classifier but have no idea where to start, follow this quick guide to understand the concepts and be able to train a convolutional neural network to recognize any image you want ! To achieve that, the code provided is written in Python (3.x), and we will mainly use the Keras library. First of all, if you have no idea what a neural network is, I can only encourage you to discover this concept with a quick guide. For example, here is the last one I wrote about that : towardsdatascience.com Now, we will focus on the convolutional neural network, which keeps the same idea about columns and neurons, inputs and outputs, while simply adding a way to extract information in an image. This type of neural network consists of a deep neural network preceded by some operations. Overall, keep in mind that an image is just a matrix of numbers, of dimension 2 if the image is only in gray level, and dimension 3 if it contains colors (the third dimension is for all RGB levels). First of all, when an image is given to the algorithm, it starts by applying a small filter on the initial image and takes it everywhere on it. This step is called Convolution. In Figure 1, the initial image is green, the filter is yellow and multiplies every number of the initial image by the corresponding filter’s one. After this operation, a new matrix (red) is obtained. By comparing pixels of the red matrix to a model, the program can determine if there is or not an object corresponding to a model on the first image. For example, obtaining big numbers only on a line of pixels means that the initial image contains a line there. The next step is called Pooling. It is about taking the highest value of each region and form a new matrix using only those values. It reduces the spatial dimension of the matrix and so helps the neural networks to operates quicker. In Figure 2, you can see that the dimension of the image is divided in 4 parts, with each one attributing its highest value. The new formed image is smaller. Also, an activation function is used during the process to normalize all the values obtained. In the example below, we will be using ReLU. Finally, a last step may be used to increase the accuracy, and is called Dropout. It forces a neural network to randomly disabling some neurons in the learning phase. We will implement this function in our example as well. Now that you know the basics of the convolution, we can start building one ! This part is useful only if you want to use your own data, or data that can’t be found on the web easily, to build a convolutional neural network maybe more adapted to your needs. Otherwise, here is the code to directly use datasets from Keras : from keras.datasets import mnist #replace mnist with any dataset(x_train, y_train), (x_test, y_test) = mnist.load_data() Here, we simply call the function load_data to set the dataset for training and testing phase. You can replace “mnist” by any dataset you want to use (change it in both lines). If you want to create your own dataset, here are the steps : First of all, you will need to collect a lot of images. The more there are, the better. Remember to keep approximately the same amount of image for each class. For example, for my piece of 2D chess classifier, I had 160 images for each possible piece (and the empty case), so about 2,000 images in total (which is not that much) but the size of the dataset depends on the projects (my 2D pieces always have the same aspects, while cats have a lot of breeds, different sizes, different postures, ...). There is also a powerful tool to help you creating more data, called data augmentation. It simply modifies an image and gives back plenty of new and unique images, all based on the first one, by flipping, rotating or cropping it. In the end make sure that all your data is classified in a folder meant for that purpose, in which every class has its own subfolder. Now in the main folder, we will create a python program to set up all the data. In line 14, you can change the list to any classes you need, but keep the same names that you used for the subfolders earlier. Finally, after running the program, the data are setup in files and ready to be used. If you decided to use an imported dataset, replace lines 9 & 10 by what we saw earlier, and the line 44 by : model.fit(x_train, y_train, batch_size=32, epochs=40, verbose=1, validation_data=(x_test, y_test)) In line 37, modify the parameter of Dense() to the number of classes you have. This is the number of possible output by the neural network. For every convolutional layers, you can see that we always firstly add it with its number of neurons and filter size. Then, we involve the activation function, and finally use the Pooling method. We also added a Dropout in line 30 to see how to do it. Also, before the first “normal” hidden layer, we added the function Flatten(), that transforms all information from previous convolutions into inputs for neurons. At this point, the rest simply contains layers and neurons from basic neural network. Here it is, you built your own classifier ! Now, you can use your neural network to predict any image you want. Simply make a little script involving these few lines : import cv2import tensorflow as tfCATEGORIES = ["bishopB", "bishopW", "empty", "kingB", "kingW", "knightB", "knightW", "pawnB", "pawnW", "queenB", "queenW", "rookB", "rookW"]def prepare(file): IMG_SIZE = 50 img_array = cv2.imread(file, cv2.IMREAD_GRAYSCALE) new_array = cv2.resize(img_array, (IMG_SIZE, IMG_SIZE)) return new_array.reshape(-1, IMG_SIZE, IMG_SIZE, 1)model = tf.keras.models.load_model("CNN.model")image = "test.jpg" #your image pathprediction = model.predict([image])prediction = list(prediction[0])print(CATEGORIES[prediction.index(max(prediction))]) The function prepare(file) allows us to use an image of any size, since it automatically resize it to the image size we defined in the first program. If you modified the image size in the data program, modify it here too. That’s it ! You just built your own image classifier adapted to your own images. Of course, do not hesitate to modify any line of code you see, since your neural network accuracy may vary a lot according to those parameters. Here is a non-exhaustive about those : The model : You can easily add or remove some layers in your neural network, change the number of neurons, or even the activation functions. You have a model for anything you would like to add. The data : The obtained accuracy isn’t what you expected ? Maybe you could add more data and mainly verify that all your images are stored in their good folder. IMG_SIZE : defined in the program for the dataset, it characterizes the size of the images the network will work on. Don’t try a too big number, since high quality images lead to a longer training phase. Moreover, even well-known databases such as MNIST contain very little images (28x28 for MNIST). Don’t forget to also modify the IMG_SIZE of the reshaping function in the last program. New parameters such as callbacks used with Keras. The one called “EarlyStopping” may help you to improve the length of the training phase, and mainly avoid overfitting. With this guide, we covered just enough for you to create and understand your first convolutional neural network. There are many other parameters or aspects that you could discover if you want, so don’t hesitate to go further. Thanks for reading ! I hope this little guide was useful, if you have any question and/or suggestion, let me know in the comments.
[ { "code": null, "e": 383, "s": 171, "text": "If you want to create an image classifier but have no idea where to start, follow this quick guide to understand the concepts and be able to train a convolutional neural network to recognize any image you want !" }, { "code": null, "e": 488, "s": 383, "text": "To achieve that, the code provided is written in Python (3.x), and we will mainly use the Keras library." }, { "code": null, "e": 673, "s": 488, "text": "First of all, if you have no idea what a neural network is, I can only encourage you to discover this concept with a quick guide. For example, here is the last one I wrote about that :" }, { "code": null, "e": 696, "s": 673, "text": "towardsdatascience.com" }, { "code": null, "e": 887, "s": 696, "text": "Now, we will focus on the convolutional neural network, which keeps the same idea about columns and neurons, inputs and outputs, while simply adding a way to extract information in an image." }, { "code": null, "e": 978, "s": 887, "text": "This type of neural network consists of a deep neural network preceded by some operations." }, { "code": null, "e": 1177, "s": 978, "text": "Overall, keep in mind that an image is just a matrix of numbers, of dimension 2 if the image is only in gray level, and dimension 3 if it contains colors (the third dimension is for all RGB levels)." }, { "code": null, "e": 1354, "s": 1177, "text": "First of all, when an image is given to the algorithm, it starts by applying a small filter on the initial image and takes it everywhere on it. This step is called Convolution." }, { "code": null, "e": 1500, "s": 1354, "text": "In Figure 1, the initial image is green, the filter is yellow and multiplies every number of the initial image by the corresponding filter’s one." }, { "code": null, "e": 1704, "s": 1500, "text": "After this operation, a new matrix (red) is obtained. By comparing pixels of the red matrix to a model, the program can determine if there is or not an object corresponding to a model on the first image." }, { "code": null, "e": 1816, "s": 1704, "text": "For example, obtaining big numbers only on a line of pixels means that the initial image contains a line there." }, { "code": null, "e": 2049, "s": 1816, "text": "The next step is called Pooling. It is about taking the highest value of each region and form a new matrix using only those values. It reduces the spatial dimension of the matrix and so helps the neural networks to operates quicker." }, { "code": null, "e": 2207, "s": 2049, "text": "In Figure 2, you can see that the dimension of the image is divided in 4 parts, with each one attributing its highest value. The new formed image is smaller." }, { "code": null, "e": 2346, "s": 2207, "text": "Also, an activation function is used during the process to normalize all the values obtained. In the example below, we will be using ReLU." }, { "code": null, "e": 2569, "s": 2346, "text": "Finally, a last step may be used to increase the accuracy, and is called Dropout. It forces a neural network to randomly disabling some neurons in the learning phase. We will implement this function in our example as well." }, { "code": null, "e": 2646, "s": 2569, "text": "Now that you know the basics of the convolution, we can start building one !" }, { "code": null, "e": 2892, "s": 2646, "text": "This part is useful only if you want to use your own data, or data that can’t be found on the web easily, to build a convolutional neural network maybe more adapted to your needs. Otherwise, here is the code to directly use datasets from Keras :" }, { "code": null, "e": 3013, "s": 2892, "text": "from keras.datasets import mnist #replace mnist with any dataset(x_train, y_train), (x_test, y_test) = mnist.load_data()" }, { "code": null, "e": 3190, "s": 3013, "text": "Here, we simply call the function load_data to set the dataset for training and testing phase. You can replace “mnist” by any dataset you want to use (change it in both lines)." }, { "code": null, "e": 3251, "s": 3190, "text": "If you want to create your own dataset, here are the steps :" }, { "code": null, "e": 3752, "s": 3251, "text": "First of all, you will need to collect a lot of images. The more there are, the better. Remember to keep approximately the same amount of image for each class. For example, for my piece of 2D chess classifier, I had 160 images for each possible piece (and the empty case), so about 2,000 images in total (which is not that much) but the size of the dataset depends on the projects (my 2D pieces always have the same aspects, while cats have a lot of breeds, different sizes, different postures, ...)." }, { "code": null, "e": 3982, "s": 3752, "text": "There is also a powerful tool to help you creating more data, called data augmentation. It simply modifies an image and gives back plenty of new and unique images, all based on the first one, by flipping, rotating or cropping it." }, { "code": null, "e": 4116, "s": 3982, "text": "In the end make sure that all your data is classified in a folder meant for that purpose, in which every class has its own subfolder." }, { "code": null, "e": 4196, "s": 4116, "text": "Now in the main folder, we will create a python program to set up all the data." }, { "code": null, "e": 4323, "s": 4196, "text": "In line 14, you can change the list to any classes you need, but keep the same names that you used for the subfolders earlier." }, { "code": null, "e": 4409, "s": 4323, "text": "Finally, after running the program, the data are setup in files and ready to be used." }, { "code": null, "e": 4518, "s": 4409, "text": "If you decided to use an imported dataset, replace lines 9 & 10 by what we saw earlier, and the line 44 by :" }, { "code": null, "e": 4617, "s": 4518, "text": "model.fit(x_train, y_train, batch_size=32, epochs=40, verbose=1, validation_data=(x_test, y_test))" }, { "code": null, "e": 4757, "s": 4617, "text": "In line 37, modify the parameter of Dense() to the number of classes you have. This is the number of possible output by the neural network." }, { "code": null, "e": 5009, "s": 4757, "text": "For every convolutional layers, you can see that we always firstly add it with its number of neurons and filter size. Then, we involve the activation function, and finally use the Pooling method. We also added a Dropout in line 30 to see how to do it." }, { "code": null, "e": 5258, "s": 5009, "text": "Also, before the first “normal” hidden layer, we added the function Flatten(), that transforms all information from previous convolutions into inputs for neurons. At this point, the rest simply contains layers and neurons from basic neural network." }, { "code": null, "e": 5302, "s": 5258, "text": "Here it is, you built your own classifier !" }, { "code": null, "e": 5426, "s": 5302, "text": "Now, you can use your neural network to predict any image you want. Simply make a little script involving these few lines :" }, { "code": null, "e": 6008, "s": 5426, "text": "import cv2import tensorflow as tfCATEGORIES = [\"bishopB\", \"bishopW\", \"empty\", \"kingB\", \"kingW\",\t\t\t\"knightB\", \"knightW\", \"pawnB\", \"pawnW\",\t\t\t\"queenB\", \"queenW\", \"rookB\", \"rookW\"]def prepare(file): IMG_SIZE = 50 img_array = cv2.imread(file, cv2.IMREAD_GRAYSCALE) new_array = cv2.resize(img_array, (IMG_SIZE, IMG_SIZE)) return new_array.reshape(-1, IMG_SIZE, IMG_SIZE, 1)model = tf.keras.models.load_model(\"CNN.model\")image = \"test.jpg\" #your image pathprediction = model.predict([image])prediction = list(prediction[0])print(CATEGORIES[prediction.index(max(prediction))])" }, { "code": null, "e": 6158, "s": 6008, "text": "The function prepare(file) allows us to use an image of any size, since it automatically resize it to the image size we defined in the first program." }, { "code": null, "e": 6230, "s": 6158, "text": "If you modified the image size in the data program, modify it here too." }, { "code": null, "e": 6494, "s": 6230, "text": "That’s it ! You just built your own image classifier adapted to your own images. Of course, do not hesitate to modify any line of code you see, since your neural network accuracy may vary a lot according to those parameters. Here is a non-exhaustive about those :" }, { "code": null, "e": 6688, "s": 6494, "text": "The model : You can easily add or remove some layers in your neural network, change the number of neurons, or even the activation functions. You have a model for anything you would like to add." }, { "code": null, "e": 6849, "s": 6688, "text": "The data : The obtained accuracy isn’t what you expected ? Maybe you could add more data and mainly verify that all your images are stored in their good folder." }, { "code": null, "e": 7237, "s": 6849, "text": "IMG_SIZE : defined in the program for the dataset, it characterizes the size of the images the network will work on. Don’t try a too big number, since high quality images lead to a longer training phase. Moreover, even well-known databases such as MNIST contain very little images (28x28 for MNIST). Don’t forget to also modify the IMG_SIZE of the reshaping function in the last program." }, { "code": null, "e": 7406, "s": 7237, "text": "New parameters such as callbacks used with Keras. The one called “EarlyStopping” may help you to improve the length of the training phase, and mainly avoid overfitting." }, { "code": null, "e": 7633, "s": 7406, "text": "With this guide, we covered just enough for you to create and understand your first convolutional neural network. There are many other parameters or aspects that you could discover if you want, so don’t hesitate to go further." }, { "code": null, "e": 7654, "s": 7633, "text": "Thanks for reading !" } ]
Dynamic Programming: return all matched data in JavaScript
Suppose we have a JSON object that have information about the location of some cities of some countries like this − const countryInfo = { country: [{ name: "Bangladesh", province: [{ name:"Dhaka", city: [{ name:"Tangail", lat: '11' }, { name:"Jamalpur", lat: '12' }] }, { name: "Khulna", city: [{ name:"Jossore", lat: '22' }, { name:"Tangail", lat: '23' }] }, { name: "Rajshahi", city: [{ name:"Pabna", lat: '33' }, { name:"Rangpur", lat: '33' }] }] },{ name: "India", province: [{ name:"West Bengal", city: [{ name:"Calcutta", lat: '111' }, { name:"Tangail", lat: '112' }] }, { name: "Uttar Pradesh", city: [{ name:"Agra", lat: '122' }, { name:"Tajmahal", lat: '123' }] }, { name: "Rajasthan", city: [{ name:"Kanpur", lat: '131' }, { name:"Jaypur", lat: '132' }] }] }] }; We are required to write a JavaScript function that takes in one such object and a search string. We should then search all the city names matching the search string and return an array of all the city objects that match the query. The code for this will be − const countryInfo = { country: [{ name: "Bangladesh", province: [{ name:"Dhaka", city: [{ name:"Tangail", lat: '11' }, { name:"Jamalpur", lat: '12' }] }, { name: "Khulna", city: [{ name:"Jossore", lat: '22' }, { name:"Tangail", lat: '23' }] }, { name: "Rajshahi", city: [{ name:"Pabna", lat: '33' }, { name:"Rangpur", lat: '33' }] }] },{ name: "India", province: [{ name:"West Bengal", city: [{ name:"Calcutta", lat: '111' }, { name:"Tangail", lat: '112' }] }, { name: "Uttar Pradesh", city: [{ name:"Agra", lat: '122' }, { name:"Tajmahal", lat: '123' }] }, { name: "Rajasthan", city: [{ name:"Kanpur", lat: '131' }, { name:"Jaypur", lat: '132' }] }] }] }; const searchForCity = (obj, query) => { const cities = obj.country.reduce((acc, val) => { val.province.forEach(el => { el.city.forEach(elm => { acc.push(elm); }); }); return acc; },[]); const res = cities.filter(el => { return el.name === query; }); return res; }; console.log(searchForCity(countryInfo, 'Tangail')); The output in the console − [ { name: 'Tangail', lat: '11' }, { name: 'Tangail', lat: '23' }, { name: 'Tangail', lat: '112' } ]
[ { "code": null, "e": 1178, "s": 1062, "text": "Suppose we have a JSON object that have information about the location of some cities of some countries like this −" }, { "code": null, "e": 2408, "s": 1178, "text": "const countryInfo = {\n country: [{\n name: \"Bangladesh\",\n province: [{\n name:\"Dhaka\",\n city: [{\n name:\"Tangail\",\n lat: '11'\n }, {\n name:\"Jamalpur\",\n lat: '12'\n }]\n }, {\n name: \"Khulna\",\n city: [{\n name:\"Jossore\",\n lat: '22'\n }, {\n name:\"Tangail\",\n lat: '23'\n }]\n }, {\n name: \"Rajshahi\",\n city: [{\n name:\"Pabna\",\n lat: '33'\n }, {\n name:\"Rangpur\",\n lat: '33'\n }]\n }]\n },{\n name: \"India\",\n province: [{\n name:\"West Bengal\",\n city: [{\n name:\"Calcutta\",\n lat: '111'\n }, {\n name:\"Tangail\",\n lat: '112'\n }]\n }, {\n name: \"Uttar Pradesh\",\n city: [{\n name:\"Agra\",\n lat: '122'\n }, {\n name:\"Tajmahal\",\n lat: '123'\n }]\n }, {\n name: \"Rajasthan\",\n city: [{\n name:\"Kanpur\",\n lat: '131'\n }, {\n name:\"Jaypur\",\n lat: '132'\n }]\n }]\n }]\n};" }, { "code": null, "e": 2506, "s": 2408, "text": "We are required to write a JavaScript function that takes in one such object and a search string." }, { "code": null, "e": 2640, "s": 2506, "text": "We should then search all the city names matching the search string and return an array of all the city objects that match the query." }, { "code": null, "e": 2668, "s": 2640, "text": "The code for this will be −" }, { "code": null, "e": 4284, "s": 2668, "text": "const countryInfo = {\n country: [{\n name: \"Bangladesh\",\n province: [{\n name:\"Dhaka\",\n city: [{\n name:\"Tangail\",\n lat: '11'\n }, {\n name:\"Jamalpur\",\n lat: '12'\n }]\n }, {\n name: \"Khulna\",\n city: [{\n name:\"Jossore\",\n lat: '22'\n }, {\n name:\"Tangail\",\n lat: '23'\n }]\n }, {\n name: \"Rajshahi\",\n city: [{\n name:\"Pabna\",\n lat: '33'\n }, {\n name:\"Rangpur\",\n lat: '33'\n }]\n }]\n },{\n name: \"India\",\n province: [{\n name:\"West Bengal\",\n city: [{\n name:\"Calcutta\",\n lat: '111'\n }, {\n name:\"Tangail\",\n lat: '112'\n }]\n }, {\n name: \"Uttar Pradesh\",\n city: [{\n name:\"Agra\",\n lat: '122'\n }, {\n name:\"Tajmahal\",\n lat: '123'\n }]\n }, {\n name: \"Rajasthan\",\n city: [{\n name:\"Kanpur\",\n lat: '131'\n }, {\n name:\"Jaypur\",\n lat: '132'\n }]\n }]\n }]\n};\nconst searchForCity = (obj, query) => {\n const cities = obj.country.reduce((acc, val) => {\n val.province.forEach(el => {\n el.city.forEach(elm => {\n acc.push(elm);\n });\n });\n return acc;\n },[]);\n const res = cities.filter(el => {\n return el.name === query;\n });\n return res;\n};\nconsole.log(searchForCity(countryInfo, 'Tangail'));" }, { "code": null, "e": 4312, "s": 4284, "text": "The output in the console −" }, { "code": null, "e": 4421, "s": 4312, "text": "[\n { name: 'Tangail', lat: '11' },\n { name: 'Tangail', lat: '23' },\n { name: 'Tangail', lat: '112' }\n]" } ]
do...while loop in C
Unlike for and while loops, which test the loop condition at the top of the loop, the do...while loop in C programming checks its condition at the bottom of the loop. A do...while loop is similar to a while loop, except the fact that it is guaranteed to execute at least one time. The syntax of a do...while loop in C programming language is − do { statement(s); } while( condition ); Notice that the conditional expression appears at the end of the loop, so the statement(s) in the loop executes once before the condition is tested. If the condition is true, the flow of control jumps back up to do, and the statement(s) in the loop executes again. This process repeats until the given condition becomes false. #include <stdio.h> int main () { /* local variable definition */ int a = 10; /* do loop execution */ do { printf("value of a: %d\n", a); a = a + 1; }while( a < 20 ); return 0; } When the above code is compiled and executed, it produces the following result − value of a: 10 value of a: 11 value of a: 12 value of a: 13 value of a: 14 value of a: 15 value of a: 16 value of a: 17 value of a: 18 value of a: 19 Print Add Notes Bookmark this page
[ { "code": null, "e": 2251, "s": 2084, "text": "Unlike for and while loops, which test the loop condition at the top of the loop, the do...while loop in C programming checks its condition at the bottom of the loop." }, { "code": null, "e": 2365, "s": 2251, "text": "A do...while loop is similar to a while loop, except the fact that it is guaranteed to execute at least one time." }, { "code": null, "e": 2428, "s": 2365, "text": "The syntax of a do...while loop in C programming language is −" }, { "code": null, "e": 2473, "s": 2428, "text": "do {\n statement(s);\n} while( condition );\n" }, { "code": null, "e": 2622, "s": 2473, "text": "Notice that the conditional expression appears at the end of the loop, so the statement(s) in the loop executes once before the condition is tested." }, { "code": null, "e": 2801, "s": 2622, "text": "If the condition is true, the flow of control jumps back up to do, and the statement(s) in the loop executes again. This process repeats until the given condition becomes false." }, { "code": null, "e": 3015, "s": 2801, "text": "#include <stdio.h>\n \nint main () {\n\n /* local variable definition */\n int a = 10;\n\n /* do loop execution */\n do {\n printf(\"value of a: %d\\n\", a);\n a = a + 1;\n }while( a < 20 );\n \n return 0;\n}" }, { "code": null, "e": 3096, "s": 3015, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 3247, "s": 3096, "text": "value of a: 10\nvalue of a: 11\nvalue of a: 12\nvalue of a: 13\nvalue of a: 14\nvalue of a: 15\nvalue of a: 16\nvalue of a: 17\nvalue of a: 18\nvalue of a: 19\n" }, { "code": null, "e": 3254, "s": 3247, "text": " Print" }, { "code": null, "e": 3265, "s": 3254, "text": " Add Notes" } ]
C Library - <time.h>
The time.h header defines four variable types, two macro and various functions for manipulating date and time. Following are the variable types defined in the header time.h − size_t This is the unsigned integral type and is the result of the sizeof keyword. clock_t This is a type suitable for storing the processor time. time_t is This is a type suitable for storing the calendar time. struct tm This is a structure used to hold the time and date. The tm structure has the following definition − struct tm { int tm_sec; /* seconds, range 0 to 59 */ int tm_min; /* minutes, range 0 to 59 */ int tm_hour; /* hours, range 0 to 23 */ int tm_mday; /* day of the month, range 1 to 31 */ int tm_mon; /* month, range 0 to 11 */ int tm_year; /* The number of years since 1900 */ int tm_wday; /* day of the week, range 0 to 6 */ int tm_yday; /* day in the year, range 0 to 365 */ int tm_isdst; /* daylight saving time */ }; Following are the macros defined in the header time.h − NULL This macro is the value of a null pointer constant. CLOCKS_PER_SEC This macro represents the number of processor clocks per second. Following are the functions defined in the header time.h − Returns a pointer to a string which represents the day and time of the structure timeptr. Returns the processor clock time used since the beginning of an implementation defined era (normally the beginning of the program). Returns a string representing the localtime based on the argument timer. Returns the difference of seconds between time1 and time2 (time1-time2). The value of timer is broken up into the structure tm and expressed in Coordinated Universal Time (UTC) also known as Greenwich Mean Time (GMT). The value of timer is broken up into the structure tm and expressed in the local time zone. Converts the structure pointed to by timeptr into a time_t value according to the local time zone. Formats the time represented in the structure timeptr according to the formatting rules defined in format and stored into str. Calculates the current calender time and encodes it into time_t format. 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 time.h header defines four variable types, two macro and various functions for manipulating date and time." }, { "code": null, "e": 2182, "s": 2118, "text": "Following are the variable types defined in the header time.h −" }, { "code": null, "e": 2189, "s": 2182, "text": "size_t" }, { "code": null, "e": 2265, "s": 2189, "text": "This is the unsigned integral type and is the result of the sizeof keyword." }, { "code": null, "e": 2273, "s": 2265, "text": "clock_t" }, { "code": null, "e": 2329, "s": 2273, "text": "This is a type suitable for storing the processor time." }, { "code": null, "e": 2339, "s": 2329, "text": "time_t is" }, { "code": null, "e": 2394, "s": 2339, "text": "This is a type suitable for storing the calendar time." }, { "code": null, "e": 2404, "s": 2394, "text": "struct tm" }, { "code": null, "e": 2456, "s": 2404, "text": "This is a structure used to hold the time and date." }, { "code": null, "e": 2504, "s": 2456, "text": "The tm structure has the following definition −" }, { "code": null, "e": 3077, "s": 2504, "text": "struct tm {\n int tm_sec; /* seconds, range 0 to 59 */\n int tm_min; /* minutes, range 0 to 59 */\n int tm_hour; /* hours, range 0 to 23 */\n int tm_mday; /* day of the month, range 1 to 31 */\n int tm_mon; /* month, range 0 to 11 */\n int tm_year; /* The number of years since 1900 */\n int tm_wday; /* day of the week, range 0 to 6 */\n int tm_yday; /* day in the year, range 0 to 365 */\n int tm_isdst; /* daylight saving time */\n};" }, { "code": null, "e": 3133, "s": 3077, "text": "Following are the macros defined in the header time.h −" }, { "code": null, "e": 3138, "s": 3133, "text": "NULL" }, { "code": null, "e": 3190, "s": 3138, "text": "This macro is the value of a null pointer constant." }, { "code": null, "e": 3205, "s": 3190, "text": "CLOCKS_PER_SEC" }, { "code": null, "e": 3270, "s": 3205, "text": "This macro represents the number of processor clocks per second." }, { "code": null, "e": 3329, "s": 3270, "text": "Following are the functions defined in the header time.h −" }, { "code": null, "e": 3419, "s": 3329, "text": "Returns a pointer to a string which represents the day and time of the structure timeptr." }, { "code": null, "e": 3551, "s": 3419, "text": "Returns the processor clock time used since the beginning of an implementation defined era (normally the beginning of the program)." }, { "code": null, "e": 3624, "s": 3551, "text": "Returns a string representing the localtime based on the argument timer." }, { "code": null, "e": 3697, "s": 3624, "text": "Returns the difference of seconds between time1 and time2 (time1-time2)." }, { "code": null, "e": 3842, "s": 3697, "text": "The value of timer is broken up into the structure tm and expressed in Coordinated Universal Time (UTC) also known as Greenwich Mean Time (GMT)." }, { "code": null, "e": 3934, "s": 3842, "text": "The value of timer is broken up into the structure tm and expressed in the local time zone." }, { "code": null, "e": 4033, "s": 3934, "text": "Converts the structure pointed to by timeptr into a time_t value according to the local time zone." }, { "code": null, "e": 4160, "s": 4033, "text": "Formats the time represented in the structure timeptr according to the formatting rules defined in format and stored into str." }, { "code": null, "e": 4232, "s": 4160, "text": "Calculates the current calender time and encodes it into time_t format." }, { "code": null, "e": 4265, "s": 4232, "text": "\n 12 Lectures \n 2 hours \n" }, { "code": null, "e": 4280, "s": 4265, "text": " Nishant Malik" }, { "code": null, "e": 4315, "s": 4280, "text": "\n 12 Lectures \n 2.5 hours \n" }, { "code": null, "e": 4330, "s": 4315, "text": " Nishant Malik" }, { "code": null, "e": 4365, "s": 4330, "text": "\n 48 Lectures \n 6.5 hours \n" }, { "code": null, "e": 4379, "s": 4365, "text": " Asif Hussain" }, { "code": null, "e": 4412, "s": 4379, "text": "\n 12 Lectures \n 2 hours \n" }, { "code": null, "e": 4430, "s": 4412, "text": " Richa Maheshwari" }, { "code": null, "e": 4465, "s": 4430, "text": "\n 20 Lectures \n 3.5 hours \n" }, { "code": null, "e": 4484, "s": 4465, "text": " Vandana Annavaram" }, { "code": null, "e": 4517, "s": 4484, "text": "\n 44 Lectures \n 1 hours \n" }, { "code": null, "e": 4529, "s": 4517, "text": " Amit Diwan" }, { "code": null, "e": 4536, "s": 4529, "text": " Print" }, { "code": null, "e": 4547, "s": 4536, "text": " Add Notes" } ]
How can I set the content of an iframe without src using jQuery?
To set the content of an iframe without src, use the jQuery html() method. You can try to run the following code to learn how to set the content of an iframe without src attribute − Live Demo <html> <head> <title>jQuery Selector</title> <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"> </script> <script> $(document).ready(function() { var context = $('iframe')[0].contentWindow.document; var $body = $('body', context); $body.html('Hello World!'); }); </script> </head> <body> <iframe style="border-style: dotted;"></iframe> </body> </html>
[ { "code": null, "e": 1244, "s": 1062, "text": "To set the content of an iframe without src, use the jQuery html() method. You can try to run the following code to learn how to set the content of an iframe without src attribute −" }, { "code": null, "e": 1254, "s": 1244, "text": "Live Demo" }, { "code": null, "e": 1678, "s": 1254, "text": "<html>\n <head>\n <title>jQuery Selector</title>\n <script src = \"https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js\"> \n </script>\n <script>\n $(document).ready(function() {\n var context = $('iframe')[0].contentWindow.document;\n var $body = $('body', context);\n $body.html('Hello World!');\n });\n </script>\n </head>\n<body>\n <iframe style=\"border-style: dotted;\"></iframe> \n</body>\n</html>" } ]
Display Month of Year using Java Calendar
For using Calendar class, import the following package. import java.util.Calendar; Using the Calendar class, create an object. Calendar calendar = Calendar.getInstance(); Now, create a string array of the month names. String[] month = new String[] {"January", "February", "March", "April", "May", "June", "July", "August","September", "October", "November", "December" }; Display the month name. month[calendar.get(Calendar.MONTH)] The following is an example. Live Demo import java.util.Calendar; public class Demo { public static void main(String[] args) { Calendar calendar = Calendar.getInstance(); String[] month = new String[] {"January", "February", "March", "April", "May", "June", "July", "August","September", "October", "November", "December" }; System.out.println("Current Month = " + month[calendar.get(Calendar.MONTH)]); } } The following is the output − Current Month = Dec
[ { "code": null, "e": 1118, "s": 1062, "text": "For using Calendar class, import the following package." }, { "code": null, "e": 1145, "s": 1118, "text": "import java.util.Calendar;" }, { "code": null, "e": 1189, "s": 1145, "text": "Using the Calendar class, create an object." }, { "code": null, "e": 1233, "s": 1189, "text": "Calendar calendar = Calendar.getInstance();" }, { "code": null, "e": 1280, "s": 1233, "text": "Now, create a string array of the month names." }, { "code": null, "e": 1434, "s": 1280, "text": "String[] month = new String[] {\"January\", \"February\", \"March\", \"April\", \"May\", \"June\", \"July\", \"August\",\"September\", \"October\", \"November\", \"December\" };" }, { "code": null, "e": 1458, "s": 1434, "text": "Display the month name." }, { "code": null, "e": 1494, "s": 1458, "text": "month[calendar.get(Calendar.MONTH)]" }, { "code": null, "e": 1523, "s": 1494, "text": "The following is an example." }, { "code": null, "e": 1534, "s": 1523, "text": " Live Demo" }, { "code": null, "e": 1926, "s": 1534, "text": "import java.util.Calendar;\npublic class Demo {\n public static void main(String[] args) {\n Calendar calendar = Calendar.getInstance();\n String[] month = new String[] {\"January\", \"February\", \"March\", \"April\", \"May\", \"June\", \"July\", \"August\",\"September\", \"October\", \"November\", \"December\" };\n System.out.println(\"Current Month = \" + month[calendar.get(Calendar.MONTH)]);\n }\n}" }, { "code": null, "e": 1956, "s": 1926, "text": "The following is the output −" }, { "code": null, "e": 1976, "s": 1956, "text": "Current Month = Dec" } ]
MVC Framework - Layouts
Layouts are used in MVC to provide a consistent look and feel on all the pages of our application. It is the same as defining the Master Pages but MVC provides some more functionalities. Step 1 − Create a sample MVC application with Internet application as Template and create a Content folder in the root directory of the web application. Step 2 − Create a Style Sheet file named MyStyleSheet.css under the CONTENT folder. This CSS file will contain all the CSS classes necessary for a consistent web application page design. Step 3 − Create a Shared folder under the View folder. Step 4 − Create a MasterLayout.cshtml file under the Shared folder. The file MasterLayout.cshtml represents the layout of each page in the application. Right-click on the Shared folder in the Solution Explorer, then go to Add item and click View. Copy the following layout code. <!DOCTYPE html> <html lang = "en"> <head> <meta charset = "utf-8" /> <title>@ViewBag.Title - Tutorial Point</title> <link href = "~/favicon.ico" rel = "shortcut icon" type = "image/x-icon" /> <link rel = "stylesheet" href = "@Url.Content("~/Content/MyStyleSheet.css")" /> </head> <body> <header> <div class = "content-wrapper"> <div class = "float-left"> <p class = "site-title"> @Html.ActionLink("Tutorial Point", "Index", "Home") </p> </div> <div class = "float-right"> <nav> <ul id = "menu"> <li>@Html.ActionLink("Home", "Index", "Home")</li> <li>@Html.ActionLink("About", "About", "Home")</li> </ul> </nav> </div> </div> </header> <div id = "body"> @RenderSection("featured", required: false) <section class = "content-wrapper main-content clear-fix"> @RenderBody() </section> </div> <footer> <div class = "content-wrapper"> <div class = "float-left"> <p>© @DateTime.Now.Year - Tutorial Point</p> </div> </div> </footer> </body> </html> In this layout, we are using an HTML helper method and some other system-defined methods, hence let's look at these methods one by one. Url.Content() − This method specifies the path of any file that we are using in our View code. It takes the virtual path as input and returns the absolute path. Url.Content() − This method specifies the path of any file that we are using in our View code. It takes the virtual path as input and returns the absolute path. Html.ActionLink() − This method renders HTML links that links to action of some controller. The first parameter specifies the display name, the second parameter specifies the Action name, and the third parameter specifies the Controller name. Html.ActionLink() − This method renders HTML links that links to action of some controller. The first parameter specifies the display name, the second parameter specifies the Action name, and the third parameter specifies the Controller name. RenderSection() − Specifies the name of the section that we want to display at that location in the template. RenderSection() − Specifies the name of the section that we want to display at that location in the template. RenderBody() − Renders the actual body of the associated View. RenderBody() − Renders the actual body of the associated View. Step 5 − Finally, open the _ViewStart.cshtml file inside Views folder and add the following code − @{ Layout = "~/Views/Shared/_Layout.cshtml"; } If the file is not present, you can create the file with this name. Step 6 − Run the application now to see the modified home page. 44 Lectures 4.5 hours Kaushik Roy Chowdhury 42 Lectures 18 hours SHIVPRASAD KOIRALA 57 Lectures 3.5 hours University Code 55 Lectures 4.5 hours University Code 40 Lectures 2.5 hours University Code 140 Lectures 9 hours Bhrugen Patel Print Add Notes Bookmark this page
[ { "code": null, "e": 2212, "s": 2025, "text": "Layouts are used in MVC to provide a consistent look and feel on all the pages of our application. It is the same as defining the Master Pages but MVC provides some more functionalities." }, { "code": null, "e": 2365, "s": 2212, "text": "Step 1 − Create a sample MVC application with Internet application as Template and create a Content folder in the root directory of the web application." }, { "code": null, "e": 2552, "s": 2365, "text": "Step 2 − Create a Style Sheet file named MyStyleSheet.css under the CONTENT folder. This CSS file will contain all the CSS classes necessary for a consistent web application page design." }, { "code": null, "e": 2607, "s": 2552, "text": "Step 3 − Create a Shared folder under the View folder." }, { "code": null, "e": 2886, "s": 2607, "text": "Step 4 − Create a MasterLayout.cshtml file under the Shared folder. The file MasterLayout.cshtml represents the layout of each page in the application. Right-click on the Shared folder in the Solution Explorer, then go to Add item and click View. Copy the following layout code." }, { "code": null, "e": 4293, "s": 2886, "text": "<!DOCTYPE html> \n\n<html lang = \"en\"> \n <head> \n <meta charset = \"utf-8\" /> \n <title>@ViewBag.Title - Tutorial Point</title> \n <link href = \"~/favicon.ico\" rel = \"shortcut icon\" type = \"image/x-icon\" />\n <link rel = \"stylesheet\" href = \"@Url.Content(\"~/Content/MyStyleSheet.css\")\" />\n </head> \n \n <body> \n <header> \n \n <div class = \"content-wrapper\"> \n <div class = \"float-left\"> \n <p class = \"site-title\"> \n @Html.ActionLink(\"Tutorial Point\", \"Index\", \"Home\")\n </p> \n </div> \n \n <div class = \"float-right\">\n <nav> \n <ul id = \"menu\"> \n <li>@Html.ActionLink(\"Home\", \"Index\", \"Home\")</li> \n <li>@Html.ActionLink(\"About\", \"About\", \"Home\")</li>\n </ul> \n </nav> \n </div> \n </div> \n \n </header>\n <div id = \"body\"> \n @RenderSection(\"featured\", required: false) \n <section class = \"content-wrapper main-content clear-fix\"> \n @RenderBody() \n </section> \n </div>\n \n <footer>\n <div class = \"content-wrapper\">\n <div class = \"float-left\"> \n <p>© @DateTime.Now.Year - Tutorial Point</p> \n </div> \n </div> \n </footer>\n \n </body>\n</html>" }, { "code": null, "e": 4429, "s": 4293, "text": "In this layout, we are using an HTML helper method and some other system-defined methods, hence let's look at these methods one by one." }, { "code": null, "e": 4590, "s": 4429, "text": "Url.Content() − This method specifies the path of any file that we are using in our View code. It takes the virtual path as input and returns the absolute path." }, { "code": null, "e": 4751, "s": 4590, "text": "Url.Content() − This method specifies the path of any file that we are using in our View code. It takes the virtual path as input and returns the absolute path." }, { "code": null, "e": 4994, "s": 4751, "text": "Html.ActionLink() − This method renders HTML links that links to action of some controller. The first parameter specifies the display name, the second parameter specifies the Action name, and the third parameter specifies the Controller name." }, { "code": null, "e": 5237, "s": 4994, "text": "Html.ActionLink() − This method renders HTML links that links to action of some controller. The first parameter specifies the display name, the second parameter specifies the Action name, and the third parameter specifies the Controller name." }, { "code": null, "e": 5347, "s": 5237, "text": "RenderSection() − Specifies the name of the section that we want to display at that location in the template." }, { "code": null, "e": 5457, "s": 5347, "text": "RenderSection() − Specifies the name of the section that we want to display at that location in the template." }, { "code": null, "e": 5520, "s": 5457, "text": "RenderBody() − Renders the actual body of the associated View." }, { "code": null, "e": 5583, "s": 5520, "text": "RenderBody() − Renders the actual body of the associated View." }, { "code": null, "e": 5682, "s": 5583, "text": "Step 5 − Finally, open the _ViewStart.cshtml file inside Views folder and add the following code −" }, { "code": null, "e": 5734, "s": 5682, "text": "@{ \n Layout = \"~/Views/Shared/_Layout.cshtml\"; \n}" }, { "code": null, "e": 5802, "s": 5734, "text": "If the file is not present, you can create the file with this name." }, { "code": null, "e": 5866, "s": 5802, "text": "Step 6 − Run the application now to see the modified home page." }, { "code": null, "e": 5901, "s": 5866, "text": "\n 44 Lectures \n 4.5 hours \n" }, { "code": null, "e": 5924, "s": 5901, "text": " Kaushik Roy Chowdhury" }, { "code": null, "e": 5958, "s": 5924, "text": "\n 42 Lectures \n 18 hours \n" }, { "code": null, "e": 5978, "s": 5958, "text": " SHIVPRASAD KOIRALA" }, { "code": null, "e": 6013, "s": 5978, "text": "\n 57 Lectures \n 3.5 hours \n" }, { "code": null, "e": 6030, "s": 6013, "text": " University Code" }, { "code": null, "e": 6065, "s": 6030, "text": "\n 55 Lectures \n 4.5 hours \n" }, { "code": null, "e": 6082, "s": 6065, "text": " University Code" }, { "code": null, "e": 6117, "s": 6082, "text": "\n 40 Lectures \n 2.5 hours \n" }, { "code": null, "e": 6134, "s": 6117, "text": " University Code" }, { "code": null, "e": 6168, "s": 6134, "text": "\n 140 Lectures \n 9 hours \n" }, { "code": null, "e": 6183, "s": 6168, "text": " Bhrugen Patel" }, { "code": null, "e": 6190, "s": 6183, "text": " Print" }, { "code": null, "e": 6201, "s": 6190, "text": " Add Notes" } ]
Python Program to calculate the Round Trip Time (RTT)
Here we will see how Python can be used to get the Round Trip Time (RTT). The RTT is the time which is taken by the entire trip of a signal. It means the time between the starting time when a signal is sent and the receiving time of the acknowledge signal. The RTT results varies on different parameters like. The data transfer rate of the sender’s side. The nature of the transmission media. The actual distance between the sender and receiver. The number of nodes between sender and receiver. The amount of traffic on LAN. Number of requests handled by intermediate points. import time import requests import sys deffind_roundtriptime(url): initial_time = time.time() #Store the time when request is sent request = requests.get(url) ending_time = time.time() #Time when acknowledged the request elapsed_time = str(ending_time - initial_time) print('The Round Trip Time for {} is {}'.format(url, elapsed_time)) find_roundtriptime(sys.argv[1]) $ python3 319.RoundTripTime.py https://www.tutorialspoint.com/ The Round Trip Time for https://www.tutorialspoint.com/ is 0.8301455974578857 $ python3 319.RoundTripTime.py https://www.google.com The Round Trip Time for https://www.google.com is 0.5217089653015137 $
[ { "code": null, "e": 1319, "s": 1062, "text": "Here we will see how Python can be used to get the Round Trip Time (RTT). The RTT is the time which is taken by the entire trip of a signal. It means the time between the starting time when a signal is sent and the receiving time of the acknowledge signal." }, { "code": null, "e": 1372, "s": 1319, "text": "The RTT results varies on different parameters like." }, { "code": null, "e": 1417, "s": 1372, "text": "The data transfer rate of the sender’s side." }, { "code": null, "e": 1455, "s": 1417, "text": "The nature of the transmission media." }, { "code": null, "e": 1508, "s": 1455, "text": "The actual distance between the sender and receiver." }, { "code": null, "e": 1557, "s": 1508, "text": "The number of nodes between sender and receiver." }, { "code": null, "e": 1587, "s": 1557, "text": "The amount of traffic on LAN." }, { "code": null, "e": 1638, "s": 1587, "text": "Number of requests handled by intermediate points." }, { "code": null, "e": 2042, "s": 1638, "text": "import time\nimport requests\nimport sys\n deffind_roundtriptime(url):\n initial_time = time.time() #Store the time when request is sent\n request = requests.get(url)\n ending_time = time.time() #Time when acknowledged the request\n elapsed_time = str(ending_time - initial_time)\n print('The Round Trip Time for {} is {}'.format(url, elapsed_time))\n find_roundtriptime(sys.argv[1])" }, { "code": null, "e": 2309, "s": 2042, "text": "$ python3 319.RoundTripTime.py https://www.tutorialspoint.com/\nThe Round Trip Time for https://www.tutorialspoint.com/ is 0.8301455974578857\n\n$ python3 319.RoundTripTime.py https://www.google.com\nThe Round Trip Time for https://www.google.com is 0.5217089653015137\n$" } ]
Update a column A if null, else update column B, else if both columns are not null do nothing with MySQL
For this, use IF() with IS NULL property. Let us first create a table − mysql> create table DemoTable1976 ( FirstName varchar(20), LastName varchar(20) ); Query OK, 0 rows affected (0.00 sec) Insert some records in the table using insert command − mysql> insert into DemoTable1976 values('John','Doe'); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1976 values('John',NULL); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1976 values(NULL,'Miller'); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1976 values('Chris','Brown'); Query OK, 1 row affected (0.00 sec) Display all records from the table using select statement − mysql> select * from DemoTable1976; This will produce the following output − +-----------+----------+ | FirstName | LastName | +-----------+----------+ | John | Doe | | John | NULL | | NULL | Miller | | Chris | Brown | +-----------+----------+ 4 rows in set (0.00 sec) Here is the query to update a column if null else update anther column, else if both columns are not null do nothing − mysql> update DemoTable1976 set FirstName=if(FirstName IS NULL,'David',FirstName), LastName=if(LastName IS NULL,'Brown',LastName); Query OK, 2 rows affected (0.00 sec) Rows matched: 4 Changed: 2 Warnings: 0 Let us check the table records once again − mysql> select * from DemoTable1976; This will produce the following output − +-----------+----------+ | FirstName | LastName | +-----------+----------+ | John | Doe | | John | Brown | | David | Miller | | Chris | Brown | +-----------+----------+ 4 rows in set (0.00 sec)
[ { "code": null, "e": 1134, "s": 1062, "text": "For this, use IF() with IS NULL property. Let us first create a table −" }, { "code": null, "e": 1266, "s": 1134, "text": "mysql> create table DemoTable1976\n (\n FirstName varchar(20),\n LastName varchar(20)\n );\nQuery OK, 0 rows affected (0.00 sec)" }, { "code": null, "e": 1322, "s": 1266, "text": "Insert some records in the table using insert command −" }, { "code": null, "e": 1689, "s": 1322, "text": "mysql> insert into DemoTable1976 values('John','Doe');\nQuery OK, 1 row affected (0.00 sec)\nmysql> insert into DemoTable1976 values('John',NULL);\nQuery OK, 1 row affected (0.00 sec)\nmysql> insert into DemoTable1976 values(NULL,'Miller');\nQuery OK, 1 row affected (0.00 sec)\nmysql> insert into DemoTable1976 values('Chris','Brown');\nQuery OK, 1 row affected (0.00 sec)" }, { "code": null, "e": 1749, "s": 1689, "text": "Display all records from the table using select statement −" }, { "code": null, "e": 1785, "s": 1749, "text": "mysql> select * from DemoTable1976;" }, { "code": null, "e": 1826, "s": 1785, "text": "This will produce the following output −" }, { "code": null, "e": 2051, "s": 1826, "text": "+-----------+----------+\n| FirstName | LastName |\n+-----------+----------+\n| John | Doe |\n| John | NULL |\n| NULL | Miller |\n| Chris | Brown |\n+-----------+----------+\n4 rows in set (0.00 sec)" }, { "code": null, "e": 2170, "s": 2051, "text": "Here is the query to update a column if null else update anther column, else if both columns are not null do nothing −" }, { "code": null, "e": 2384, "s": 2170, "text": "mysql> update DemoTable1976\n set FirstName=if(FirstName IS NULL,'David',FirstName),\n LastName=if(LastName IS NULL,'Brown',LastName);\nQuery OK, 2 rows affected (0.00 sec)\nRows matched: 4 Changed: 2 Warnings: 0" }, { "code": null, "e": 2428, "s": 2384, "text": "Let us check the table records once again −" }, { "code": null, "e": 2464, "s": 2428, "text": "mysql> select * from DemoTable1976;" }, { "code": null, "e": 2505, "s": 2464, "text": "This will produce the following output −" }, { "code": null, "e": 2730, "s": 2505, "text": "+-----------+----------+\n| FirstName | LastName |\n+-----------+----------+\n| John | Doe |\n| John | Brown |\n| David | Miller |\n| Chris | Brown |\n+-----------+----------+\n4 rows in set (0.00 sec)" } ]
Swap and Maximize | Practice | GeeksforGeeks
Given an array a[ ] of N elements. Consider array as a circular array i.e. element after an is a1. The task is to find maximum sum of the absolute difference between consecutive elements with rearrangement of array elements allowed i.e. after any rearrangement of array elements find |a1 – a2| + |a2 – a3| + ...... + |an-1 – an| + |an – a1|. Example 1: Input: N = 4 a[] = {4, 2, 1, 8} Output: 18 Explanation: Rearrangement done is {1, 8, 2, 4}. Sum of absolute difference between consecutive elements after rearrangement = |1 - 8| + |8 - 2| + |2 - 4| + |4 - 1| = 7 + 6 + 2 + 3 = 18. Example 2: Input: N = 2 a[] = {10, 12} Output: 4 Your Task: This is a function problem. You don't need to take any input, as it is already accomplished by the driver code. You just need to complete the function maxSum() that takes array a[ ] and its size N as input parameters and return the maximum sum using above method. Expected Time Complexity: O(N*logN) Expected Auxiliary Space: O(1) Constraints: 2 ≤ N ≤ 105 0 shaank18182 days ago Java Solution class GFG { long maxSum(long arr[] ,int n) { //sort the array; Arrays.sort(arr); int i = 0 ; int j = n-1; //create a new array which has elements in fashon 1st smallest 1st largest 2nd smallest 2nd largest long brr[] = new long[n]; long ans = 0; for(int k = 0 ; k<n;k++){ if(k%2==0){ brr[k] = arr[i++]; }else{ brr[k] = arr[j--]; } } //take the absolute diff for(int k = 0 ; k<n-1;k++){ ans += Math.abs(brr[k]-brr[k+1]); } //take the absolute diff of 1st and last as array is circuler ans += Math.abs(brr[0]-brr[n-1]); return ans; } } 0 arvind16yadav4 weeks ago /*JAVA CODE : Time : 1.2*/ class GFG{ long maxSum(long arr[] ,int n) { long ans = 0; Arrays.sort(arr); int mid = n/2; ans += Math.abs(arr[0]-arr[n-1]); ans += Math.abs(arr[0]-arr[mid]); if(n%2 == 0){ for(int i=1; i<mid; i++){ ans += Math.abs(arr[i]-arr[n-i]); ans += Math.abs(arr[i]-arr[n-1-i]); } } else{ for(int i=1; i<=mid; i++){ ans += Math.abs(arr[i]-arr[n-i]); ans += Math.abs(arr[i]-arr[n-1-i]); } } return ans; }} 0 mitradiptamoy1 month ago long long int maxSum(int arr[], int n){ sort(arr,arr+n); int sum=0; int j=n-1; int i=0; while(i<n){ sum+=abs(arr[i]-arr[j]); j--; i++; } return sum;} 0 gupta2411sumit1 month ago long long int maxSum(int arr[], int n){ long long int sum = 0 ; int temp[n] ; sort( arr , arr+n ) ; int p = 0 ; int e = 0 ; for( int i = 0 ; i<n ; i++) { if(i%2==0) { temp[i] = arr[e] ; e++ ; } else{ temp[i] = arr[n-1-p] ; p++ ; } } for( int i = 0 ; i<n-1 ; i++) { sum += abs( temp[i]-temp[i+1]) ; // cout<<sum<<" " ; } sum += abs(temp[n-1] - temp[0]) ; return sum ;} +2 gaurabhkumarjha271020011 month ago // easy c++ approach sort (arr, arr+n); long long int sum=0; int j= n-1; for (int i=0; i< n; i++){ sum+= abs (arr[i] - arr[j--]); } return sum; 0 hasnainraza1998hr2 months ago C++, 0.4 long long int maxSum(int arr[], int n){ sort(arr,arr+n); vector<int> brr; long long sum=0; for(int i=0;i<n/2;i++){ brr.push_back(arr[i]); brr.push_back(arr[n-1-i]); } if(n%2!=0) brr.push_back(arr[n/2]); for(int i=0;i<n-1;i++){ sum += abs(brr[i]-brr[i+1]); } sum += abs(brr[n-1]-brr[0]); return sum;} 0 ashutoshrastogi2 months ago Simple Java Code class GFG { long maxSum(long arr[] ,int n) { int i,j; Arrays.sort(arr); long sum = Math.abs(arr[0]-arr[n-1]); if(n==2) return 2*sum; else{ i = 1; j = n-2; while(i<j){ long t = arr[i]; arr[i] = arr[j]; arr[j] = t; i+=2; j-=2; } for(i=0;i<n-1;i++) sum += Math.abs(arr[i]-arr[i+1]); } return sum; } } 0 pandemania2 months ago long long int maxSum(int arr[], int n){ sort(arr,arr+n); int i=0,j=n-1; int cnt = 0; vector<int> narr; while(i <= j && cnt < n){ if(cnt%2==0){ narr.push_back(arr[i]); i++; } else{ narr.push_back(arr[j]); j--; } cnt++; } long long sum = 0; for(int i=1;i<narr.size();i++){ sum += abs(narr[i-1] - narr[i]); } sum += abs(narr[n-1] - narr[0]); return sum; } 0 jhav16432 months ago long long int maxSum(int arr[], int n){ if(n==0) { return 0; } sort(arr, arr+n); long long int i = 1, j = n-2, sum = 0; while(i<j) { swap(arr[i], arr[j]); i+=2; j-=2; } for(i = 0; i<n-1; i++) { sum+=(abs(arr[i+1]- arr[i])); } sum+=abs(arr[n-1]-arr[0]); return sum;} 0 parasmovaliya43212 months ago long long int maxSum(int arr[], int n) { long long s=0,i,j=n-1,t=n-1; sort(arr,arr+n); while(j>0) { if(t-j+1<j) { s+=(arr[j]-arr[t-j])+(arr[j]-arr[t-j+1]); } else if(t-j+1==j) { s+=(arr[j]-arr[t-j])+(arr[j]-arr[0]); return s; } else { s+=(arr[j]-arr[0]); return s; } j--; } return 0; } We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 580, "s": 238, "text": "Given an array a[ ] of N elements. Consider array as a circular array i.e. element after an is a1. The task is to find maximum sum of the absolute difference between consecutive elements with rearrangement of array elements allowed i.e. after any rearrangement of array elements find |a1 – a2| + |a2 – a3| + ...... + |an-1 – an| + |an – a1|." }, { "code": null, "e": 591, "s": 580, "text": "Example 1:" }, { "code": null, "e": 826, "s": 591, "text": "Input:\nN = 4\na[] = {4, 2, 1, 8}\nOutput: \n18\nExplanation: Rearrangement done is {1, 8, \n2, 4}. Sum of absolute difference between \nconsecutive elements after rearrangement = \n|1 - 8| + |8 - 2| + |2 - 4| + |4 - 1| = \n7 + 6 + 2 + 3 = 18." }, { "code": null, "e": 837, "s": 826, "text": "Example 2:" }, { "code": null, "e": 877, "s": 837, "text": "Input:\nN = 2\na[] = {10, 12}\nOutput: \n4\n" }, { "code": null, "e": 1152, "s": 877, "text": "Your Task:\nThis is a function problem. You don't need to take any input, as it is already accomplished by the driver code. You just need to complete the function maxSum() that takes array a[ ] and its size N as input parameters and return the maximum sum using above method." }, { "code": null, "e": 1219, "s": 1152, "text": "Expected Time Complexity: O(N*logN)\nExpected Auxiliary Space: O(1)" }, { "code": null, "e": 1244, "s": 1219, "text": "Constraints:\n2 ≤ N ≤ 105" }, { "code": null, "e": 1246, "s": 1244, "text": "0" }, { "code": null, "e": 1267, "s": 1246, "text": "shaank18182 days ago" }, { "code": null, "e": 1281, "s": 1267, "text": "Java Solution" }, { "code": null, "e": 2069, "s": 1281, "text": "\nclass GFG\n{\n long maxSum(long arr[] ,int n)\n {\n \n //sort the array;\n Arrays.sort(arr);\n int i = 0 ;\n int j = n-1;\n \n //create a new array which has elements in fashon 1st smallest 1st largest 2nd smallest 2nd largest\n long brr[] = new long[n];\n \n long ans = 0;\n \n for(int k = 0 ; k<n;k++){\n \n if(k%2==0){\n brr[k] = arr[i++];\n }else{\n brr[k] = arr[j--];\n }\n }\n \n //take the absolute diff \n for(int k = 0 ; k<n-1;k++){\n ans += Math.abs(brr[k]-brr[k+1]);\n }\n \n //take the absolute diff of 1st and last as array is circuler\n ans += Math.abs(brr[0]-brr[n-1]);\n \n \n return ans;\n \n }\n}" }, { "code": null, "e": 2071, "s": 2069, "text": "0" }, { "code": null, "e": 2096, "s": 2071, "text": "arvind16yadav4 weeks ago" }, { "code": null, "e": 2123, "s": 2096, "text": "/*JAVA CODE : Time : 1.2*/" }, { "code": null, "e": 2719, "s": 2123, "text": "class GFG{ long maxSum(long arr[] ,int n) { long ans = 0; Arrays.sort(arr); int mid = n/2; ans += Math.abs(arr[0]-arr[n-1]); ans += Math.abs(arr[0]-arr[mid]); if(n%2 == 0){ for(int i=1; i<mid; i++){ ans += Math.abs(arr[i]-arr[n-i]); ans += Math.abs(arr[i]-arr[n-1-i]); } } else{ for(int i=1; i<=mid; i++){ ans += Math.abs(arr[i]-arr[n-i]); ans += Math.abs(arr[i]-arr[n-1-i]); } } return ans; }}" }, { "code": null, "e": 2721, "s": 2719, "text": "0" }, { "code": null, "e": 2746, "s": 2721, "text": "mitradiptamoy1 month ago" }, { "code": null, "e": 2929, "s": 2746, "text": "long long int maxSum(int arr[], int n){ sort(arr,arr+n); int sum=0; int j=n-1; int i=0; while(i<n){ sum+=abs(arr[i]-arr[j]); j--; i++; } return sum;} " }, { "code": null, "e": 2931, "s": 2929, "text": "0" }, { "code": null, "e": 2957, "s": 2931, "text": "gupta2411sumit1 month ago" }, { "code": null, "e": 3461, "s": 2957, "text": "long long int maxSum(int arr[], int n){ long long int sum = 0 ; int temp[n] ; sort( arr , arr+n ) ; int p = 0 ; int e = 0 ; for( int i = 0 ; i<n ; i++) { if(i%2==0) { temp[i] = arr[e] ; e++ ; } else{ temp[i] = arr[n-1-p] ; p++ ; } } for( int i = 0 ; i<n-1 ; i++) { sum += abs( temp[i]-temp[i+1]) ; // cout<<sum<<\" \" ; } sum += abs(temp[n-1] - temp[0]) ; return sum ;}" }, { "code": null, "e": 3464, "s": 3461, "text": "+2" }, { "code": null, "e": 3499, "s": 3464, "text": "gaurabhkumarjha271020011 month ago" }, { "code": null, "e": 3681, "s": 3499, "text": "// easy c++ approach\n sort (arr, arr+n);\n long long int sum=0;\n int j= n-1;\n for (int i=0; i< n; i++){\n sum+= abs (arr[i] - arr[j--]);\n }\n return sum;" }, { "code": null, "e": 3683, "s": 3681, "text": "0" }, { "code": null, "e": 3713, "s": 3683, "text": "hasnainraza1998hr2 months ago" }, { "code": null, "e": 3722, "s": 3713, "text": "C++, 0.4" }, { "code": null, "e": 4073, "s": 3722, "text": "long long int maxSum(int arr[], int n){ sort(arr,arr+n); vector<int> brr; long long sum=0; for(int i=0;i<n/2;i++){ brr.push_back(arr[i]); brr.push_back(arr[n-1-i]); } if(n%2!=0) brr.push_back(arr[n/2]); for(int i=0;i<n-1;i++){ sum += abs(brr[i]-brr[i+1]); } sum += abs(brr[n-1]-brr[0]); return sum;}" }, { "code": null, "e": 4075, "s": 4073, "text": "0" }, { "code": null, "e": 4103, "s": 4075, "text": "ashutoshrastogi2 months ago" }, { "code": null, "e": 4120, "s": 4103, "text": "Simple Java Code" }, { "code": null, "e": 4735, "s": 4122, "text": "class GFG\n{\n long maxSum(long arr[] ,int n)\n {\n int i,j;\n Arrays.sort(arr);\n \n long sum = Math.abs(arr[0]-arr[n-1]);\n \n if(n==2)\n return 2*sum;\n else{\n i = 1;\n j = n-2;\n while(i<j){\n long t = arr[i];\n arr[i] = arr[j];\n arr[j] = t;\n \n i+=2;\n j-=2;\n }\n \n for(i=0;i<n-1;i++)\n sum += Math.abs(arr[i]-arr[i+1]);\n \n }\n \n return sum;\n \n }\n}" }, { "code": null, "e": 4737, "s": 4735, "text": "0" }, { "code": null, "e": 4760, "s": 4737, "text": "pandemania2 months ago" }, { "code": null, "e": 5254, "s": 4760, "text": "long long int maxSum(int arr[], int n){\n sort(arr,arr+n);\n int i=0,j=n-1;\n int cnt = 0;\n vector<int> narr;\n while(i <= j && cnt < n){\n if(cnt%2==0){\n narr.push_back(arr[i]);\n i++;\n }\n else{\n narr.push_back(arr[j]);\n j--;\n } \n cnt++;\n }\n long long sum = 0;\n for(int i=1;i<narr.size();i++){\n sum += abs(narr[i-1] - narr[i]);\n }\n sum += abs(narr[n-1] - narr[0]);\n return sum;\n}" }, { "code": null, "e": 5256, "s": 5254, "text": "0" }, { "code": null, "e": 5277, "s": 5256, "text": "jhav16432 months ago" }, { "code": null, "e": 5617, "s": 5277, "text": "long long int maxSum(int arr[], int n){ if(n==0) { return 0; } sort(arr, arr+n); long long int i = 1, j = n-2, sum = 0; while(i<j) { swap(arr[i], arr[j]); i+=2; j-=2; } for(i = 0; i<n-1; i++) { sum+=(abs(arr[i+1]- arr[i])); } sum+=abs(arr[n-1]-arr[0]); return sum;}" }, { "code": null, "e": 5619, "s": 5617, "text": "0" }, { "code": null, "e": 5649, "s": 5619, "text": "parasmovaliya43212 months ago" }, { "code": null, "e": 6061, "s": 5649, "text": "long long int maxSum(int arr[], int n)\n{\n long long s=0,i,j=n-1,t=n-1;\n \n sort(arr,arr+n);\n while(j>0)\n {\n if(t-j+1<j)\n {\n s+=(arr[j]-arr[t-j])+(arr[j]-arr[t-j+1]);\n }\n else if(t-j+1==j)\n {\n s+=(arr[j]-arr[t-j])+(arr[j]-arr[0]);\n return s;\n }\n else\n {\n s+=(arr[j]-arr[0]);\n return s;\n }\n j--;\n }\n return 0;\n}" }, { "code": null, "e": 6207, "s": 6061, "text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?" }, { "code": null, "e": 6243, "s": 6207, "text": " Login to access your submissions. " }, { "code": null, "e": 6253, "s": 6243, "text": "\nProblem\n" }, { "code": null, "e": 6263, "s": 6253, "text": "\nContest\n" }, { "code": null, "e": 6326, "s": 6263, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 6474, "s": 6326, "text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 6682, "s": 6474, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints." }, { "code": null, "e": 6788, "s": 6682, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Teradata - Create Tables
CREATE TABLE command is used to create tables in Teradata. Following is the generic syntax of CREATE TABLE statement. CREATE <SET/MULTISET> TABLE <Tablename> <Table Options> <Column Definitions> <Index Definitions>; Table Options − Specifies the physical attributes of the table such as Journal and Fallback. Table Options − Specifies the physical attributes of the table such as Journal and Fallback. Column Definition − Specifies the list of columns, data types and their attributes. Column Definition − Specifies the list of columns, data types and their attributes. Index Definition − Additional indexing options such as Primary Index, Secondary Index and Partitioned Primary Index. Index Definition − Additional indexing options such as Primary Index, Secondary Index and Partitioned Primary Index. The following example creates a table called employee with FALLBACK option. The table contains 5 columns with EmployeeNo as the Unique Primary Index. CREATE SET TABLE EMPLOYEE,FALLBACK ( EmployeeNo INTEGER, FirstName VARCHAR(30), LastName VARCHAR(30), DOB DATE FORMAT 'YYYY-MM-DD', JoinedDate DATE FORMAT 'YYYY-MM-DD', DepartmentNo BYTEINT ) UNIQUE PRIMARY INDEX ( EmployeeNo ); Once the table is created, you can use SHOW TABLE command to view the Definition of the table. SHOW TABLE Employee; *** Text of DDL statement returned. *** Total elapsed time was 1 second. ------------------------------------------------------------------------ CREATE SET TABLE EMPLOYEE ,FALLBACK , NO BEFORE JOURNAL, NO AFTER JOURNAL, CHECKSUM = DEFAULT, DEFAULT MERGEBLOCKRATIO ( EmployeeNo INTEGER, FirstName VARCHAR(30) CHARACTER SET LATIN NOT CASESPECIFIC, LastName VARCHAR(30) CHARACTER SET LATIN NOT CASESPECIFIC, DOB DATE FORMAT 'YYYY-MM-DD', JoinedDate DATE FORMAT 'YYYY-MM-DD', DepartmentNo BYTEINT ) UNIQUE PRIMARY INDEX ( EmployeeNo ); Print Add Notes Bookmark this page
[ { "code": null, "e": 2689, "s": 2630, "text": "CREATE TABLE command is used to create tables in Teradata." }, { "code": null, "e": 2748, "s": 2689, "text": "Following is the generic syntax of CREATE TABLE statement." }, { "code": null, "e": 2850, "s": 2748, "text": "CREATE <SET/MULTISET> TABLE <Tablename> \n<Table Options> \n<Column Definitions> \n<Index Definitions>;\n" }, { "code": null, "e": 2943, "s": 2850, "text": "Table Options − Specifies the physical attributes of the table such as Journal and Fallback." }, { "code": null, "e": 3036, "s": 2943, "text": "Table Options − Specifies the physical attributes of the table such as Journal and Fallback." }, { "code": null, "e": 3120, "s": 3036, "text": "Column Definition − Specifies the list of columns, data types and their attributes." }, { "code": null, "e": 3204, "s": 3120, "text": "Column Definition − Specifies the list of columns, data types and their attributes." }, { "code": null, "e": 3321, "s": 3204, "text": "Index Definition − Additional indexing options such as Primary Index, Secondary Index and Partitioned Primary Index." }, { "code": null, "e": 3438, "s": 3321, "text": "Index Definition − Additional indexing options such as Primary Index, Secondary Index and Partitioned Primary Index." }, { "code": null, "e": 3588, "s": 3438, "text": "The following example creates a table called employee with FALLBACK option. The table contains 5 columns with EmployeeNo as the Unique Primary Index." }, { "code": null, "e": 3843, "s": 3588, "text": "CREATE SET TABLE EMPLOYEE,FALLBACK ( \n EmployeeNo INTEGER, \n FirstName VARCHAR(30), \n LastName VARCHAR(30), \n DOB DATE FORMAT 'YYYY-MM-DD', \n JoinedDate DATE FORMAT 'YYYY-MM-DD', \n DepartmentNo BYTEINT \n) \nUNIQUE PRIMARY INDEX ( EmployeeNo );" }, { "code": null, "e": 3938, "s": 3843, "text": "Once the table is created, you can use SHOW TABLE command to view the Definition of the table." }, { "code": null, "e": 4563, "s": 3938, "text": "SHOW TABLE Employee; \n*** Text of DDL statement returned. \n*** Total elapsed time was 1 second. \n------------------------------------------------------------------------ \nCREATE SET TABLE EMPLOYEE ,FALLBACK , \n NO BEFORE JOURNAL, \n NO AFTER JOURNAL, \n CHECKSUM = DEFAULT, \n \n DEFAULT MERGEBLOCKRATIO (\n EmployeeNo INTEGER, \n FirstName VARCHAR(30) CHARACTER SET LATIN NOT CASESPECIFIC, \n LastName VARCHAR(30) CHARACTER SET LATIN NOT CASESPECIFIC, \n DOB DATE FORMAT 'YYYY-MM-DD', \n JoinedDate DATE FORMAT 'YYYY-MM-DD', \n DepartmentNo BYTEINT\n ) \nUNIQUE PRIMARY INDEX ( EmployeeNo );\n" }, { "code": null, "e": 4570, "s": 4563, "text": " Print" }, { "code": null, "e": 4581, "s": 4570, "text": " Add Notes" } ]
What is a singleton class in Java?
A singleton class in Java is the one which can have only one object. The easiest implementation consists of a private constructor and a field to hold its result, and a static accessor method with a name like getInstance(). The private field can be assigned from within a static initializer block or, more simply, using an initializer. The getInstance( ) method (which must be public) then simply returns this instance − public class Singleton { private static Singleton singleton = new Singleton(); private Singleton() { } public static Singleton getInstance() { return singleton; } protected static void demoMethod() { System.out.println("demoMethod for singleton"); } } Here is the main program file where we will create a singleton object − public class SingletonDemo { public static void main(String[] args) { Singleton tmp = Singleton.getInstance(); tmp.demoMethod(); } }
[ { "code": null, "e": 1131, "s": 1062, "text": "A singleton class in Java is the one which can have only one object." }, { "code": null, "e": 1285, "s": 1131, "text": "The easiest implementation consists of a private constructor and a field to hold its result, and a static accessor method with a name like getInstance()." }, { "code": null, "e": 1483, "s": 1285, "text": " The private field can be assigned from within a static initializer block or, more simply, using an initializer. The getInstance( ) method (which must be public) then simply returns this instance −" }, { "code": null, "e": 1767, "s": 1483, "text": "public class Singleton {\n private static Singleton singleton = new Singleton(); private Singleton() { }\n \n public static Singleton getInstance() {\n return singleton;\n }\n\n protected static void demoMethod() {\n System.out.println(\"demoMethod for singleton\");\n }\n}" }, { "code": null, "e": 1839, "s": 1767, "text": "Here is the main program file where we will create a singleton object −" }, { "code": null, "e": 1990, "s": 1839, "text": "public class SingletonDemo {\n public static void main(String[] args) {\n Singleton tmp = Singleton.getInstance();\n tmp.demoMethod();\n }\n}" } ]
How to create fast and accurate scatter plots with lots of data in python | by Paul Gavrikov | Towards Data Science
Scatter plots are quite basic and easy to create — or so I thought. Recently I had to visualize a dataset with hundreds of millions of data points. If you’re a Python developer you’ll immediately import matplotlib and get started. But it turns out there are better, faster, and more intuitive ways to create scatter plots. What’s the problem with matplotlib? Well, matplotlib is a great Python library and is definitely part of the data science must-knows. But matplotlib is also a huge all-rounder and may perform suboptimally in some scenarios. This is one of those. Let’s say we have an array X and its shape is (1_000_000, 2). Each column represents one axis. So, any row is a coordinate. import matplotlib.pylot as pltplt.scatter(X[:, 0], X[:, 1])plt.show() So that produces a scatter plot but we have no idea if points overlap or generally about the intensity of a region. We can fix this by setting the s and alpha parameters. The first parameter controls the size of each point, the latter gives it opacity. We’d like size and opacity that allows us to distinguish between different points. And this is where trial and error begins. And as your data size increases, this process gets more and more painful. import matplotlib.pylot as pltplt.scatter(X[:, 0], X[:, 1], s=1, alpha=0.1)plt.show() datashaderis a great library to visualize larger datasets. The main improvement comes from the rasterization process: matplotlib will create a circle for every data point and then, when you’re displaying your data, it will have to figure out which pixels on your canvas each point occupies. Typically, each point will occupy multiple pixels. Instead, datashader will divide your 2D-space into width horizontal and height vertical bins. And then it just checks which bin each sample occupies. If this process sounds familiar to you, then that’s because that’s how you create a histogram. In this case, a 2D-histogram with equal-width bins. The histogram you’ve created is already the same shape as your image. So all that’s left is to apply the colormap. I really like fire from the colorcet library. And you’re done. Note that datashader only accepts DataFrame as input (be it pandas , dask or others) and your data must be stored as float32. There are the additional packages we need: pip install datashader, colorcet, pandas And that is the code: import datashader as dsimport pandas as pdimport colorcet as ccimport matplotlib.pyplot as pltdf = pd.DataFrame(data=X, columns=["x", "y"]) # create a DF from arraycvs = ds.Canvas(plot_width=500, plot_height=500) # auto range or provide the `bounds` argumentagg = cvs.points(df, 'x', 'y') # this is the histogramimg = ds.tf.set_background(ds.tf.shade(agg, how="log", cmap=cc.fire), "black").to_pil() # create a rasterized imageplt.imshow(img)plt.axis('off')plt.show() Dots can no longer partially overlap, and since you’re creating a histogram the colormap will handle your previous opacity problem. You can decide how you want to normalize the data (using the how parameter). Here we set it to be logarithmic, but typically I’d recommend leaving it at the default which uses a more sophisticated method. And now let’s just add a color bar to the plot. Ugh! How? All we have now is the histogram and a rasterized image. We can display the image with matplotlib but have no information of the colormap. There’s probably some hack, but let’s be honest: It would be nothing more than a dirty hack and could introduce a lot of confusion. So, datashader is great, fast, and easy to use — but it comes at a price: no color bars and no interactive plots (i.e. no GUI which allows to zoom, rotate, etc.). It really shines at creating external graphics, though. So, give it a try! Especially, when you’re dealing with geolocation data. Dynamic plots aren’t that important to me, but I really needed color bars. So, I went ahead and coded up my own solution. It’s actually really simple. Initially, I was using numpy to compute a 2D-Histogram and then let matplotlib handle the shading. But numpy.histogram2d is quite slow, which is why I switched to fast_histogram. I am again using the colorcet.fire map but accessing it via the cc.cm dict to be compatible with matplotlib . Also, I am supplying the norm argument to use a logarithmic colormap. Be aware that vmin=0 is invalid because the logarithm of zero is not defined. This is also why all 0 values are mapped to what’s called the bad color. So just set the bad color to the color for the smallest value (or to whatever color you want your background to be). There are the additional packages we need: pip install fast-histogram colorcet And run the code: import colorcet as ccimport matplotlib.colors as colorsimport matplotlib.pyplot as pltfrom fast_histogram import histogram2dcmap = cc.cm["fire"].copy()cmap.set_bad(cmap.get_under()) # set the color for 0bounds = [[X[:, 0].min(), X[:, 0].max()], [X[:, 1].min(), X[:, 1].max()]]h = histogram2d(X[:, 0], X[:, 1], range=bounds, bins=500)plt.imshow(h, norm=colors.LogNorm(vmin=1, vmax=h.max()), cmap=cmap)plt.axis('off')plt.show() Note that the created scatter plots are rotated, due to the way how fast_histogram outputs data. To show the color bar just add plt.colorbar() before plt.show() .
[ { "code": null, "e": 495, "s": 172, "text": "Scatter plots are quite basic and easy to create — or so I thought. Recently I had to visualize a dataset with hundreds of millions of data points. If you’re a Python developer you’ll immediately import matplotlib and get started. But it turns out there are better, faster, and more intuitive ways to create scatter plots." }, { "code": null, "e": 741, "s": 495, "text": "What’s the problem with matplotlib? Well, matplotlib is a great Python library and is definitely part of the data science must-knows. But matplotlib is also a huge all-rounder and may perform suboptimally in some scenarios. This is one of those." }, { "code": null, "e": 865, "s": 741, "text": "Let’s say we have an array X and its shape is (1_000_000, 2). Each column represents one axis. So, any row is a coordinate." }, { "code": null, "e": 935, "s": 865, "text": "import matplotlib.pylot as pltplt.scatter(X[:, 0], X[:, 1])plt.show()" }, { "code": null, "e": 1387, "s": 935, "text": "So that produces a scatter plot but we have no idea if points overlap or generally about the intensity of a region. We can fix this by setting the s and alpha parameters. The first parameter controls the size of each point, the latter gives it opacity. We’d like size and opacity that allows us to distinguish between different points. And this is where trial and error begins. And as your data size increases, this process gets more and more painful." }, { "code": null, "e": 1473, "s": 1387, "text": "import matplotlib.pylot as pltplt.scatter(X[:, 0], X[:, 1], s=1, alpha=0.1)plt.show()" }, { "code": null, "e": 2416, "s": 1473, "text": "datashaderis a great library to visualize larger datasets. The main improvement comes from the rasterization process: matplotlib will create a circle for every data point and then, when you’re displaying your data, it will have to figure out which pixels on your canvas each point occupies. Typically, each point will occupy multiple pixels. Instead, datashader will divide your 2D-space into width horizontal and height vertical bins. And then it just checks which bin each sample occupies. If this process sounds familiar to you, then that’s because that’s how you create a histogram. In this case, a 2D-histogram with equal-width bins. The histogram you’ve created is already the same shape as your image. So all that’s left is to apply the colormap. I really like fire from the colorcet library. And you’re done. Note that datashader only accepts DataFrame as input (be it pandas , dask or others) and your data must be stored as float32." }, { "code": null, "e": 2459, "s": 2416, "text": "There are the additional packages we need:" }, { "code": null, "e": 2500, "s": 2459, "text": "pip install datashader, colorcet, pandas" }, { "code": null, "e": 2522, "s": 2500, "text": "And that is the code:" }, { "code": null, "e": 2994, "s": 2522, "text": "import datashader as dsimport pandas as pdimport colorcet as ccimport matplotlib.pyplot as pltdf = pd.DataFrame(data=X, columns=[\"x\", \"y\"]) # create a DF from arraycvs = ds.Canvas(plot_width=500, plot_height=500) # auto range or provide the `bounds` argumentagg = cvs.points(df, 'x', 'y') # this is the histogramimg = ds.tf.set_background(ds.tf.shade(agg, how=\"log\", cmap=cc.fire), \"black\").to_pil() # create a rasterized imageplt.imshow(img)plt.axis('off')plt.show()" }, { "code": null, "e": 3331, "s": 2994, "text": "Dots can no longer partially overlap, and since you’re creating a histogram the colormap will handle your previous opacity problem. You can decide how you want to normalize the data (using the how parameter). Here we set it to be logarithmic, but typically I’d recommend leaving it at the default which uses a more sophisticated method." }, { "code": null, "e": 3953, "s": 3331, "text": "And now let’s just add a color bar to the plot. Ugh! How? All we have now is the histogram and a rasterized image. We can display the image with matplotlib but have no information of the colormap. There’s probably some hack, but let’s be honest: It would be nothing more than a dirty hack and could introduce a lot of confusion. So, datashader is great, fast, and easy to use — but it comes at a price: no color bars and no interactive plots (i.e. no GUI which allows to zoom, rotate, etc.). It really shines at creating external graphics, though. So, give it a try! Especially, when you’re dealing with geolocation data." }, { "code": null, "e": 4731, "s": 3953, "text": "Dynamic plots aren’t that important to me, but I really needed color bars. So, I went ahead and coded up my own solution. It’s actually really simple. Initially, I was using numpy to compute a 2D-Histogram and then let matplotlib handle the shading. But numpy.histogram2d is quite slow, which is why I switched to fast_histogram. I am again using the colorcet.fire map but accessing it via the cc.cm dict to be compatible with matplotlib . Also, I am supplying the norm argument to use a logarithmic colormap. Be aware that vmin=0 is invalid because the logarithm of zero is not defined. This is also why all 0 values are mapped to what’s called the bad color. So just set the bad color to the color for the smallest value (or to whatever color you want your background to be)." }, { "code": null, "e": 4774, "s": 4731, "text": "There are the additional packages we need:" }, { "code": null, "e": 4810, "s": 4774, "text": "pip install fast-histogram colorcet" }, { "code": null, "e": 4828, "s": 4810, "text": "And run the code:" }, { "code": null, "e": 5255, "s": 4828, "text": "import colorcet as ccimport matplotlib.colors as colorsimport matplotlib.pyplot as pltfrom fast_histogram import histogram2dcmap = cc.cm[\"fire\"].copy()cmap.set_bad(cmap.get_under()) # set the color for 0bounds = [[X[:, 0].min(), X[:, 0].max()], [X[:, 1].min(), X[:, 1].max()]]h = histogram2d(X[:, 0], X[:, 1], range=bounds, bins=500)plt.imshow(h, norm=colors.LogNorm(vmin=1, vmax=h.max()), cmap=cmap)plt.axis('off')plt.show()" }, { "code": null, "e": 5352, "s": 5255, "text": "Note that the created scatter plots are rotated, due to the way how fast_histogram outputs data." } ]
How to load and display an image on iOS App using Swift?
To load and display an image in iOS app we’ll first need to get an image. Then we’ll drag that image to our project and select copy if required option and our application target. Let’s see the rest with help of an example. Now, we’ll create an UIImageView and assign the image to its image property, for that we’ll create a function. func addImage(imageName img: String) { let imageView = UIImageView() imageView.frame = self.view.frame imageView.contentMode = .scaleAspectFit if let newImage = UIImage(named: img) { imageView.image = newImage } self.view.addSubview(imageView) } Now, we’ll call this code in our viewDidLoad or any other place where we need. override func viewDidLoad() { super.viewDidLoad() self.addImage(imageName: "1.png") } When we run the above code on our application it produces the following result.
[ { "code": null, "e": 1136, "s": 1062, "text": "To load and display an image in iOS app we’ll first need to get an image." }, { "code": null, "e": 1241, "s": 1136, "text": "Then we’ll drag that image to our project and select copy if required option and our application target." }, { "code": null, "e": 1285, "s": 1241, "text": "Let’s see the rest with help of an example." }, { "code": null, "e": 1396, "s": 1285, "text": "Now, we’ll create an UIImageView and assign the image to its image property, for that we’ll create a function." }, { "code": null, "e": 1666, "s": 1396, "text": "func addImage(imageName img: String) {\n let imageView = UIImageView()\n imageView.frame = self.view.frame\n imageView.contentMode = .scaleAspectFit\n if let newImage = UIImage(named: img) {\n imageView.image = newImage\n }\n self.view.addSubview(imageView)\n}" }, { "code": null, "e": 1745, "s": 1666, "text": "Now, we’ll call this code in our viewDidLoad or any other place where we need." }, { "code": null, "e": 1837, "s": 1745, "text": "override func viewDidLoad() {\n super.viewDidLoad()\n self.addImage(imageName: \"1.png\")\n}" }, { "code": null, "e": 1917, "s": 1837, "text": "When we run the above code on our application it produces the following result." } ]
Python Design Patterns - Facade
Facade design pattern provides a unified interface to a set of interfaces in a subsystem. It defines a higher-level interface that any subsystem can use. A facade class knows which subsystem is responsible for a request. Let us now see how to design a facade pattern. class _IgnitionSystem(object): @staticmethod def produce_spark(): return True class _Engine(object): def __init__(self): self.revs_per_minute = 0 def turnon(self): self.revs_per_minute = 2000 def turnoff(self): self.revs_per_minute = 0 class _FuelTank(object): def __init__(self, level=30): self._level = level @property def level(self): return self._level @level.setter def level(self, level): self._level = level class _DashBoardLight(object): def __init__(self, is_on=False): self._is_on = is_on def __str__(self): return self.__class__.__name__ @property def is_on(self): return self._is_on @is_on.setter def is_on(self, status): self._is_on = status def status_check(self): if self._is_on: print("{}: ON".format(str(self))) else: print("{}: OFF".format(str(self))) class _HandBrakeLight(_DashBoardLight): pass class _FogLampLight(_DashBoardLight): pass class _Dashboard(object): def __init__(self): self.lights = {"handbreak": _HandBrakeLight(), "fog": _FogLampLight()} def show(self): for light in self.lights.values(): light.status_check() # Facade class Car(object): def __init__(self): self.ignition_system = _IgnitionSystem() self.engine = _Engine() self.fuel_tank = _FuelTank() self.dashboard = _Dashboard() @property def km_per_litre(self): return 17.0 def consume_fuel(self, km): litres = min(self.fuel_tank.level, km / self.km_per_litre) self.fuel_tank.level -= litres def start(self): print("\nStarting...") self.dashboard.show() if self.ignition_system.produce_spark(): self.engine.turnon() else: print("Can't start. Faulty ignition system") def has_enough_fuel(self, km, km_per_litre): litres_needed = km / km_per_litre if self.fuel_tank.level > litres_needed: return True else: return False def drive(self, km = 100): print("\n") if self.engine.revs_per_minute > 0: while self.has_enough_fuel(km, self.km_per_litre): self.consume_fuel(km) print("Drove {}km".format(km)) print("{:.2f}l of fuel still left".format(self.fuel_tank.level)) else: print("Can't drive. The Engine is turned off!") def park(self): print("\nParking...") self.dashboard.lights["handbreak"].is_on = True self.dashboard.show() self.engine.turnoff() def switch_fog_lights(self, status): print("\nSwitching {} fog lights...".format(status)) boolean = True if status == "ON" else False self.dashboard.lights["fog"].is_on = boolean self.dashboard.show() def fill_up_tank(self): print("\nFuel tank filled up!") self.fuel_tank.level = 100 # the main function is the Client def main(): car = Car() car.start() car.drive() car.switch_fog_lights("ON") car.switch_fog_lights("OFF") car.park() car.fill_up_tank() car.drive() car.start() car.drive() if __name__ == "__main__": main() The above program generates the following output − This program is designed with a scenario. It is that of starting the engine of a car or any driving vehicle. If you observe the code, it includes the associated functions to drive, to park and to consume fuel as well. 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": 2633, "s": 2479, "text": "Facade design pattern provides a unified interface to a set of interfaces in a subsystem. It defines a higher-level interface that any subsystem can use." }, { "code": null, "e": 2700, "s": 2633, "text": "A facade class knows which subsystem is responsible for a request." }, { "code": null, "e": 2747, "s": 2700, "text": "Let us now see how to design a facade pattern." }, { "code": null, "e": 6107, "s": 2747, "text": "class _IgnitionSystem(object):\n \n @staticmethod\n def produce_spark():\n return True\n\nclass _Engine(object):\n\n def __init__(self):\n self.revs_per_minute = 0\n\n def turnon(self):\n self.revs_per_minute = 2000\n \n def turnoff(self):\n self.revs_per_minute = 0\n\nclass _FuelTank(object):\n \n def __init__(self, level=30):\n self._level = level\n \n @property\n def level(self):\n return self._level\n \n @level.setter\n\tdef level(self, level):\n self._level = level\n\nclass _DashBoardLight(object):\n\n def __init__(self, is_on=False):\n self._is_on = is_on\n\n def __str__(self):\n return self.__class__.__name__\n\n @property\n def is_on(self):\n return self._is_on\n \n @is_on.setter\n def is_on(self, status):\n self._is_on = status\n \n def status_check(self):\n if self._is_on:\n print(\"{}: ON\".format(str(self)))\n else:\n print(\"{}: OFF\".format(str(self)))\n\nclass _HandBrakeLight(_DashBoardLight):\n pass\n\nclass _FogLampLight(_DashBoardLight):\n pass\n\nclass _Dashboard(object):\n \n def __init__(self):\n self.lights = {\"handbreak\": _HandBrakeLight(), \"fog\": _FogLampLight()}\n \n def show(self):\n\t for light in self.lights.values():\n light.status_check()\n\n# Facade\nclass Car(object):\n \n def __init__(self):\n self.ignition_system = _IgnitionSystem()\n self.engine = _Engine()\n self.fuel_tank = _FuelTank()\n self.dashboard = _Dashboard()\n \n @property\n def km_per_litre(self):\n return 17.0\n \n def consume_fuel(self, km):\n litres = min(self.fuel_tank.level, km / self.km_per_litre)\n self.fuel_tank.level -= litres\n \n def start(self):\n print(\"\\nStarting...\")\n self.dashboard.show()\n if self.ignition_system.produce_spark():\n self.engine.turnon()\n else:\n print(\"Can't start. Faulty ignition system\")\n \n def has_enough_fuel(self, km, km_per_litre):\n litres_needed = km / km_per_litre\n if self.fuel_tank.level > litres_needed:\n return True\n else:\n return False\n\t \n def drive(self, km = 100):\n print(\"\\n\")\n if self.engine.revs_per_minute > 0:\n while self.has_enough_fuel(km, self.km_per_litre):\n self.consume_fuel(km)\n print(\"Drove {}km\".format(km))\n print(\"{:.2f}l of fuel still left\".format(self.fuel_tank.level))\n else:\n print(\"Can't drive. The Engine is turned off!\")\n \n def park(self):\n print(\"\\nParking...\")\n self.dashboard.lights[\"handbreak\"].is_on = True\n self.dashboard.show()\n self.engine.turnoff()\n \n def switch_fog_lights(self, status):\n print(\"\\nSwitching {} fog lights...\".format(status))\n boolean = True if status == \"ON\" else False\n self.dashboard.lights[\"fog\"].is_on = boolean\n self.dashboard.show()\n \n def fill_up_tank(self):\n print(\"\\nFuel tank filled up!\")\n self.fuel_tank.level = 100\n\t\t\t\t\n# the main function is the Client\ndef main():\n car = Car()\n car.start()\n car.drive()\n car.switch_fog_lights(\"ON\")\n car.switch_fog_lights(\"OFF\")\n\tcar.park()\n car.fill_up_tank()\n car.drive()\n car.start()\n car.drive()\n\nif __name__ == \"__main__\":\n main()" }, { "code": null, "e": 6158, "s": 6107, "text": "The above program generates the following output −" }, { "code": null, "e": 6376, "s": 6158, "text": "This program is designed with a scenario. It is that of starting the engine of a car or any driving vehicle. If you observe the code, it includes the associated functions to drive, to park and to consume fuel as well." }, { "code": null, "e": 6413, "s": 6376, "text": "\n 187 Lectures \n 17.5 hours \n" }, { "code": null, "e": 6429, "s": 6413, "text": " Malhar Lathkar" }, { "code": null, "e": 6462, "s": 6429, "text": "\n 55 Lectures \n 8 hours \n" }, { "code": null, "e": 6481, "s": 6462, "text": " Arnab Chakraborty" }, { "code": null, "e": 6516, "s": 6481, "text": "\n 136 Lectures \n 11 hours \n" }, { "code": null, "e": 6538, "s": 6516, "text": " In28Minutes Official" }, { "code": null, "e": 6572, "s": 6538, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 6600, "s": 6572, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 6635, "s": 6600, "text": "\n 70 Lectures \n 8.5 hours \n" }, { "code": null, "e": 6649, "s": 6635, "text": " Lets Kode It" }, { "code": null, "e": 6682, "s": 6649, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 6699, "s": 6682, "text": " Abhilash Nelson" }, { "code": null, "e": 6706, "s": 6699, "text": " Print" }, { "code": null, "e": 6717, "s": 6706, "text": " Add Notes" } ]
Bootstrap 4 Button .btn-outline-danger class
To set an outline on a button that indicates danger, you need to use the btn-outline-danger class in Bootstrap. Set the outline in the <button> element − <button type="button" class="btn btn-outline-danger"> Danger Ahead </button> You can try to run the following code to implement the btn-outline-danger class − Live Demo <!DOCTYPE html> <html lang="en"> <head> <title>Bootstrap Example</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script> </head> <body> <h2>Danger Button</h2> <button type="button" class="btn btn-outline-danger">Danger Ahead</button> </body> </html>
[ { "code": null, "e": 1174, "s": 1062, "text": "To set an outline on a button that indicates danger, you need to use the btn-outline-danger class in Bootstrap." }, { "code": null, "e": 1216, "s": 1174, "text": "Set the outline in the <button> element −" }, { "code": null, "e": 1295, "s": 1216, "text": "<button type=\"button\" class=\"btn btn-outline-danger\">\n Danger Ahead\n</button>" }, { "code": null, "e": 1377, "s": 1295, "text": "You can try to run the following code to implement the btn-outline-danger class −" }, { "code": null, "e": 1387, "s": 1377, "text": "Live Demo" }, { "code": null, "e": 2003, "s": 1387, "text": "<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <title>Bootstrap Example</title>\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css\">\n <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js\"></script>\n </head>\n <body>\n <h2>Danger Button</h2>\n <button type=\"button\" class=\"btn btn-outline-danger\">Danger Ahead</button>\n </body>\n</html>" } ]
How to find through list of ids in MongoDB?
You can use $in operator to find through the list of ids in MongoDB. To understand the concept, let us create a collection with the document. The query to create a collection with a document is as follows − > db.findListOfIdsDemo.insertOne({"StudentName":"Carol","StudentAge":21}); { "acknowledged" : true, "insertedId" : ObjectId("5c8ecadd2f684a30fbdfd575") } > db.findListOfIdsDemo.insertOne({"StudentName":"Bob","StudentAge":25}); { "acknowledged" : true, "insertedId" : ObjectId("5c8ecae42f684a30fbdfd576") } > db.findListOfIdsDemo.insertOne({"StudentName":"David","StudentAge":22}); { "acknowledged" : true, "insertedId" : ObjectId("5c8ecaed2f684a30fbdfd577") } > db.findListOfIdsDemo.insertOne({"StudentName":"John","StudentAge":20}); { "acknowledged" : true, "insertedId" : ObjectId("5c8ecaf82f684a30fbdfd578") } > db.findListOfIdsDemo.insertOne({"StudentName":"Mike","StudentAge":23}); { "acknowledged" : true, "insertedId" : ObjectId("5c8ecb092f684a30fbdfd579") } Display all documents from a collection with the help of find() method. The query is as follows − > db.findListOfIdsDemo.find().pretty(); The following is the output − { "_id" : ObjectId("5c8ecadd2f684a30fbdfd575"), "StudentName" : "Carol", "StudentAge" : 21 } { "_id" : ObjectId("5c8ecae42f684a30fbdfd576"), "StudentName" : "Bob", "StudentAge" : 25 } { "_id" : ObjectId("5c8ecaed2f684a30fbdfd577"), "StudentName" : "David", "StudentAge" : 22 } { "_id" : ObjectId("5c8ecaf82f684a30fbdfd578"), "StudentName" : "John", "StudentAge" : 20 } { "_id" : ObjectId("5c8ecb092f684a30fbdfd579"), "StudentName" : "Mike", "StudentAge" : 23 } Here is the query to find through the list of ids − > var listOfIds = ['5c8ecae42f684a30fbdfd576', '5c8ecaf82f684a30fbdfd578']; > var documentIds = listOfIds.map(function(myId) { return ObjectId(myId); }); > db.findListOfIdsDemo.find({_id: {$in: documentIds }}).pretty(); The following is the output − { "_id" : ObjectId("5c8ecae42f684a30fbdfd576"), "StudentName" : "Bob", "StudentAge" : 25 } { "_id" : ObjectId("5c8ecaf82f684a30fbdfd578"), "StudentName" : "John", "StudentAge" : 20 }
[ { "code": null, "e": 1269, "s": 1062, "text": "You can use $in operator to find through the list of ids in MongoDB. To understand the concept, let us create a collection with the document. The query to create a collection with a document is as follows −" }, { "code": null, "e": 2065, "s": 1269, "text": "> db.findListOfIdsDemo.insertOne({\"StudentName\":\"Carol\",\"StudentAge\":21});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c8ecadd2f684a30fbdfd575\")\n}\n> db.findListOfIdsDemo.insertOne({\"StudentName\":\"Bob\",\"StudentAge\":25});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c8ecae42f684a30fbdfd576\")\n}\n> db.findListOfIdsDemo.insertOne({\"StudentName\":\"David\",\"StudentAge\":22});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c8ecaed2f684a30fbdfd577\")\n}\n> db.findListOfIdsDemo.insertOne({\"StudentName\":\"John\",\"StudentAge\":20});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c8ecaf82f684a30fbdfd578\")\n}\n> db.findListOfIdsDemo.insertOne({\"StudentName\":\"Mike\",\"StudentAge\":23});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c8ecb092f684a30fbdfd579\")\n}" }, { "code": null, "e": 2163, "s": 2065, "text": "Display all documents from a collection with the help of find() method. The query is as follows −" }, { "code": null, "e": 2203, "s": 2163, "text": "> db.findListOfIdsDemo.find().pretty();" }, { "code": null, "e": 2233, "s": 2203, "text": "The following is the output −" }, { "code": null, "e": 2730, "s": 2233, "text": "{\n \"_id\" : ObjectId(\"5c8ecadd2f684a30fbdfd575\"),\n \"StudentName\" : \"Carol\",\n \"StudentAge\" : 21\n}\n{\n \"_id\" : ObjectId(\"5c8ecae42f684a30fbdfd576\"),\n \"StudentName\" : \"Bob\",\n \"StudentAge\" : 25\n}\n{\n \"_id\" : ObjectId(\"5c8ecaed2f684a30fbdfd577\"),\n \"StudentName\" : \"David\",\n \"StudentAge\" : 22\n}\n{\n \"_id\" : ObjectId(\"5c8ecaf82f684a30fbdfd578\"),\n \"StudentName\" : \"John\",\n \"StudentAge\" : 20\n}\n{\n\"_id\" : ObjectId(\"5c8ecb092f684a30fbdfd579\"),\n\"StudentName\" : \"Mike\",\n\"StudentAge\" : 23\n}" }, { "code": null, "e": 2782, "s": 2730, "text": "Here is the query to find through the list of ids −" }, { "code": null, "e": 3002, "s": 2782, "text": "> var listOfIds = ['5c8ecae42f684a30fbdfd576', '5c8ecaf82f684a30fbdfd578'];\n> var documentIds = listOfIds.map(function(myId) { return ObjectId(myId); });\n> db.findListOfIdsDemo.find({_id: {$in: documentIds }}).pretty();" }, { "code": null, "e": 3032, "s": 3002, "text": "The following is the output −" }, { "code": null, "e": 3233, "s": 3032, "text": "{\n \"_id\" : ObjectId(\"5c8ecae42f684a30fbdfd576\"),\n \"StudentName\" : \"Bob\",\n \"StudentAge\" : 25\n}\n{\n \"_id\" : ObjectId(\"5c8ecaf82f684a30fbdfd578\"),\n \"StudentName\" : \"John\",\n \"StudentAge\" : 20\n}" } ]
Python PostgreSQL - Create Database - GeeksforGeeks
23 Aug, 2021 In this article, we will discuss how to create database in PsotgreSQL using pysopg2 in Python. CREATE DATABASE is one of the Data Definition Language ( DDL ) statements supported by the PostgreSQL Database Management System. It is used to create database in PostgreSQL. Database name should be always unique. If it already exists then it shows that the particular database already exists. Syntax: CREATE DATABASE database_name; Python3 import psycopg2 # connection establishmentconn = psycopg2.connect( database="postgres", user='postgres', password='password', host='localhost', port= '5432') conn.autocommit = True # Creating a cursor objectcursor = conn.cursor() # query to create a database sql = ''' CREATE database products '''; # executing above querycursor.execute(sql)print("Database has been created successfully !!"); # Closing the connectionconn.close() Output Database has been created successfully !! Picked Python PostgreSQL Python Pyscopg2 Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Box Plot in Python using Matplotlib Python | Get dictionary keys as a list Bar Plot in Matplotlib Multithreading in Python | Set 2 (Synchronization) Python Dictionary keys() method loops in python Python - Call function from another file Ways to filter Pandas DataFrame by column values Python | Convert set into a list Python program to find number of days between two given dates
[ { "code": null, "e": 23901, "s": 23873, "text": "\n23 Aug, 2021" }, { "code": null, "e": 23996, "s": 23901, "text": "In this article, we will discuss how to create database in PsotgreSQL using pysopg2 in Python." }, { "code": null, "e": 24291, "s": 23996, "text": "CREATE DATABASE is one of the Data Definition Language ( DDL ) statements supported by the PostgreSQL Database Management System. It is used to create database in PostgreSQL. Database name should be always unique. If it already exists then it shows that the particular database already exists. " }, { "code": null, "e": 24330, "s": 24291, "text": "Syntax: CREATE DATABASE database_name;" }, { "code": null, "e": 24338, "s": 24330, "text": "Python3" }, { "code": "import psycopg2 # connection establishmentconn = psycopg2.connect( database=\"postgres\", user='postgres', password='password', host='localhost', port= '5432') conn.autocommit = True # Creating a cursor objectcursor = conn.cursor() # query to create a database sql = ''' CREATE database products '''; # executing above querycursor.execute(sql)print(\"Database has been created successfully !!\"); # Closing the connectionconn.close()", "e": 24788, "s": 24338, "text": null }, { "code": null, "e": 24795, "s": 24788, "text": "Output" }, { "code": null, "e": 24837, "s": 24795, "text": "Database has been created successfully !!" }, { "code": null, "e": 24844, "s": 24837, "text": "Picked" }, { "code": null, "e": 24862, "s": 24844, "text": "Python PostgreSQL" }, { "code": null, "e": 24878, "s": 24862, "text": "Python Pyscopg2" }, { "code": null, "e": 24885, "s": 24878, "text": "Python" }, { "code": null, "e": 24983, "s": 24885, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 24992, "s": 24983, "text": "Comments" }, { "code": null, "e": 25005, "s": 24992, "text": "Old Comments" }, { "code": null, "e": 25041, "s": 25005, "text": "Box Plot in Python using Matplotlib" }, { "code": null, "e": 25080, "s": 25041, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 25103, "s": 25080, "text": "Bar Plot in Matplotlib" }, { "code": null, "e": 25154, "s": 25103, "text": "Multithreading in Python | Set 2 (Synchronization)" }, { "code": null, "e": 25186, "s": 25154, "text": "Python Dictionary keys() method" }, { "code": null, "e": 25202, "s": 25186, "text": "loops in python" }, { "code": null, "e": 25243, "s": 25202, "text": "Python - Call function from another file" }, { "code": null, "e": 25292, "s": 25243, "text": "Ways to filter Pandas DataFrame by column values" }, { "code": null, "e": 25325, "s": 25292, "text": "Python | Convert set into a list" } ]
Keras - Deep learning
Keras provides a complete framework to create any type of neural networks. Keras is innovative as well as very easy to learn. It supports simple neural network to very large and complex neural network model. Let us understand the architecture of Keras framework and how Keras helps in deep learning in this chapter. Keras API can be divided into three main categories − Model Layer Core Modules In Keras, every ANN is represented by Keras Models. In turn, every Keras Model is composition of Keras Layers and represents ANN layers like input, hidden layer, output layers, convolution layer, pooling layer, etc., Keras model and layer access Keras modules for activation function, loss function, regularization function, etc., Using Keras model, Keras Layer, and Keras modules, any ANN algorithm (CNN, RNN, etc.,) can be represented in a simple and efficient manner. The following diagram depicts the relationship between model, layer and core modules − Let us see the overview of Keras models, Keras layers and Keras modules. Keras Models are of two types as mentioned below − Sequential Model − Sequential model is basically a linear composition of Keras Layers. Sequential model is easy, minimal as well as has the ability to represent nearly all available neural networks. A simple sequential model is as follows − from keras.models import Sequential from keras.layers import Dense, Activation model = Sequential() model.add(Dense(512, activation = 'relu', input_shape = (784,))) Where, Line 1 imports Sequential model from Keras models Line 1 imports Sequential model from Keras models Line 2 imports Dense layer and Activation module Line 2 imports Dense layer and Activation module Line 4 create a new sequential model using Sequential API Line 4 create a new sequential model using Sequential API Line 5 adds a dense layer (Dense API) with relu activation (using Activation module) function. Line 5 adds a dense layer (Dense API) with relu activation (using Activation module) function. Sequential model exposes Model class to create customized models as well. We can use sub-classing concept to create our own complex model. Functional API − Functional API is basically used to create complex models. Each Keras layer in the Keras model represent the corresponding layer (input layer, hidden layer and output layer) in the actual proposed neural network model. Keras provides a lot of pre-build layers so that any complex neural network can be easily created. Some of the important Keras layers are specified below, Core Layers Convolution Layers Pooling Layers Recurrent Layers A simple python code to represent a neural network model using sequential model is as follows − from keras.models import Sequential from keras.layers import Dense, Activation, Dropout model = Sequential() model.add(Dense(512, activation = 'relu', input_shape = (784,))) model.add(Dropout(0.2)) model.add(Dense(512, activation = 'relu')) model.add(Dropout(0.2)) model.add(Dense(num_classes, activation = 'softmax')) Where, Line 1 imports Sequential model from Keras models Line 1 imports Sequential model from Keras models Line 2 imports Dense layer and Activation module Line 2 imports Dense layer and Activation module Line 4 create a new sequential model using Sequential API Line 4 create a new sequential model using Sequential API Line 5 adds a dense layer (Dense API) with relu activation (using Activation module) function. Line 5 adds a dense layer (Dense API) with relu activation (using Activation module) function. Line 6 adds a dropout layer (Dropout API) to handle over-fitting. Line 6 adds a dropout layer (Dropout API) to handle over-fitting. Line 7 adds another dense layer (Dense API) with relu activation (using Activation module) function. Line 7 adds another dense layer (Dense API) with relu activation (using Activation module) function. Line 8 adds another dropout layer (Dropout API) to handle over-fitting. Line 8 adds another dropout layer (Dropout API) to handle over-fitting. Line 9 adds final dense layer (Dense API) with softmax activation (using Activation module) function. Line 9 adds final dense layer (Dense API) with softmax activation (using Activation module) function. Keras also provides options to create our own customized layers. Customized layer can be created by sub-classing the Keras.Layer class and it is similar to sub-classing Keras models. Keras also provides a lot of built-in neural network related functions to properly create the Keras model and Keras layers. Some of the function are as follows − Activations module − Activation function is an important concept in ANN and activation modules provides many activation function like softmax, relu, etc., Activations module − Activation function is an important concept in ANN and activation modules provides many activation function like softmax, relu, etc., Loss module − Loss module provides loss functions like mean_squared_error, mean_absolute_error, poisson, etc., Loss module − Loss module provides loss functions like mean_squared_error, mean_absolute_error, poisson, etc., Optimizer module − Optimizer module provides optimizer function like adam, sgd, etc., Optimizer module − Optimizer module provides optimizer function like adam, sgd, etc., Regularizers − Regularizer module provides functions like L1 regularizer, L2 regularizer, etc., Regularizers − Regularizer module provides functions like L1 regularizer, L2 regularizer, etc., Let us learn Keras modules in detail in the upcoming chapter. 87 Lectures 11 hours Abhilash Nelson 61 Lectures 9 hours Abhishek And Pukhraj 57 Lectures 7 hours Abhishek And Pukhraj 52 Lectures 7 hours Abhishek And Pukhraj 52 Lectures 6 hours Abhishek And Pukhraj 68 Lectures 2 hours Mike West Print Add Notes Bookmark this page
[ { "code": null, "e": 2367, "s": 2051, "text": "Keras provides a complete framework to create any type of neural networks. Keras is innovative as well as very easy to learn. It supports simple neural network to very large and complex neural network model. Let us understand the architecture of Keras framework and how Keras helps in deep learning in this chapter." }, { "code": null, "e": 2421, "s": 2367, "text": "Keras API can be divided into three main categories −" }, { "code": null, "e": 2427, "s": 2421, "text": "Model" }, { "code": null, "e": 2433, "s": 2427, "text": "Layer" }, { "code": null, "e": 2446, "s": 2433, "text": "Core Modules" }, { "code": null, "e": 2917, "s": 2446, "text": "In Keras, every ANN is represented by Keras Models. In turn, every Keras Model is composition of Keras Layers and represents ANN layers like input, hidden layer, output layers, convolution layer, pooling layer, etc., Keras model and layer access Keras modules for activation function, loss function, regularization function, etc., Using Keras model, Keras Layer, and Keras modules, any ANN algorithm (CNN, RNN, etc.,) can be represented in a simple and efficient manner." }, { "code": null, "e": 3004, "s": 2917, "text": "The following diagram depicts the relationship between model, layer and core modules −" }, { "code": null, "e": 3077, "s": 3004, "text": "Let us see the overview of Keras models, Keras layers and Keras modules." }, { "code": null, "e": 3128, "s": 3077, "text": "Keras Models are of two types as mentioned below −" }, { "code": null, "e": 3327, "s": 3128, "text": "Sequential Model − Sequential model is basically a linear composition of Keras Layers. Sequential model is easy, minimal as well as has the ability to represent nearly all available neural networks." }, { "code": null, "e": 3369, "s": 3327, "text": "A simple sequential model is as follows −" }, { "code": null, "e": 3540, "s": 3369, "text": "from keras.models import Sequential \nfrom keras.layers import Dense, Activation \n\nmodel = Sequential() \nmodel.add(Dense(512, activation = 'relu', input_shape = (784,)))\n" }, { "code": null, "e": 3547, "s": 3540, "text": "Where," }, { "code": null, "e": 3597, "s": 3547, "text": "Line 1 imports Sequential model from Keras models" }, { "code": null, "e": 3647, "s": 3597, "text": "Line 1 imports Sequential model from Keras models" }, { "code": null, "e": 3696, "s": 3647, "text": "Line 2 imports Dense layer and Activation module" }, { "code": null, "e": 3745, "s": 3696, "text": "Line 2 imports Dense layer and Activation module" }, { "code": null, "e": 3803, "s": 3745, "text": "Line 4 create a new sequential model using Sequential API" }, { "code": null, "e": 3861, "s": 3803, "text": "Line 4 create a new sequential model using Sequential API" }, { "code": null, "e": 3956, "s": 3861, "text": "Line 5 adds a dense layer (Dense API) with relu activation (using Activation module) function." }, { "code": null, "e": 4051, "s": 3956, "text": "Line 5 adds a dense layer (Dense API) with relu activation (using Activation module) function." }, { "code": null, "e": 4190, "s": 4051, "text": "Sequential model exposes Model class to create customized models as well. We can use sub-classing concept to create our own complex model." }, { "code": null, "e": 4266, "s": 4190, "text": "Functional API − Functional API is basically used to create complex models." }, { "code": null, "e": 4581, "s": 4266, "text": "Each Keras layer in the Keras model represent the corresponding layer (input layer, hidden layer and output layer) in the actual proposed neural network model. Keras provides a lot of pre-build layers so that any complex neural network can be easily created. Some of the important Keras layers are specified below," }, { "code": null, "e": 4593, "s": 4581, "text": "Core Layers" }, { "code": null, "e": 4612, "s": 4593, "text": "Convolution Layers" }, { "code": null, "e": 4627, "s": 4612, "text": "Pooling Layers" }, { "code": null, "e": 4644, "s": 4627, "text": "Recurrent Layers" }, { "code": null, "e": 4740, "s": 4644, "text": "A simple python code to represent a neural network model using sequential model is as follows −" }, { "code": null, "e": 5066, "s": 4740, "text": "from keras.models import Sequential \nfrom keras.layers import Dense, Activation, Dropout model = Sequential() \n\nmodel.add(Dense(512, activation = 'relu', input_shape = (784,))) \nmodel.add(Dropout(0.2)) \nmodel.add(Dense(512, activation = 'relu')) model.add(Dropout(0.2)) \nmodel.add(Dense(num_classes, activation = 'softmax'))\n" }, { "code": null, "e": 5073, "s": 5066, "text": "Where," }, { "code": null, "e": 5123, "s": 5073, "text": "Line 1 imports Sequential model from Keras models" }, { "code": null, "e": 5173, "s": 5123, "text": "Line 1 imports Sequential model from Keras models" }, { "code": null, "e": 5222, "s": 5173, "text": "Line 2 imports Dense layer and Activation module" }, { "code": null, "e": 5271, "s": 5222, "text": "Line 2 imports Dense layer and Activation module" }, { "code": null, "e": 5329, "s": 5271, "text": "Line 4 create a new sequential model using Sequential API" }, { "code": null, "e": 5387, "s": 5329, "text": "Line 4 create a new sequential model using Sequential API" }, { "code": null, "e": 5482, "s": 5387, "text": "Line 5 adds a dense layer (Dense API) with relu activation (using Activation module) function." }, { "code": null, "e": 5577, "s": 5482, "text": "Line 5 adds a dense layer (Dense API) with relu activation (using Activation module) function." }, { "code": null, "e": 5643, "s": 5577, "text": "Line 6 adds a dropout layer (Dropout API) to handle over-fitting." }, { "code": null, "e": 5709, "s": 5643, "text": "Line 6 adds a dropout layer (Dropout API) to handle over-fitting." }, { "code": null, "e": 5810, "s": 5709, "text": "Line 7 adds another dense layer (Dense API) with relu activation (using Activation module) function." }, { "code": null, "e": 5911, "s": 5810, "text": "Line 7 adds another dense layer (Dense API) with relu activation (using Activation module) function." }, { "code": null, "e": 5983, "s": 5911, "text": "Line 8 adds another dropout layer (Dropout API) to handle over-fitting." }, { "code": null, "e": 6055, "s": 5983, "text": "Line 8 adds another dropout layer (Dropout API) to handle over-fitting." }, { "code": null, "e": 6157, "s": 6055, "text": "Line 9 adds final dense layer (Dense API) with softmax activation (using Activation module) function." }, { "code": null, "e": 6259, "s": 6157, "text": "Line 9 adds final dense layer (Dense API) with softmax activation (using Activation module) function." }, { "code": null, "e": 6442, "s": 6259, "text": "Keras also provides options to create our own customized layers. Customized layer can be created by sub-classing the Keras.Layer class and it is similar to sub-classing Keras models." }, { "code": null, "e": 6604, "s": 6442, "text": "Keras also provides a lot of built-in neural network related functions to properly create the Keras model and Keras layers. Some of the function are as follows −" }, { "code": null, "e": 6759, "s": 6604, "text": "Activations module − Activation function is an important concept in ANN and activation modules provides many activation function like softmax, relu, etc.," }, { "code": null, "e": 6914, "s": 6759, "text": "Activations module − Activation function is an important concept in ANN and activation modules provides many activation function like softmax, relu, etc.," }, { "code": null, "e": 7025, "s": 6914, "text": "Loss module − Loss module provides loss functions like mean_squared_error, mean_absolute_error, poisson, etc.," }, { "code": null, "e": 7136, "s": 7025, "text": "Loss module − Loss module provides loss functions like mean_squared_error, mean_absolute_error, poisson, etc.," }, { "code": null, "e": 7222, "s": 7136, "text": "Optimizer module − Optimizer module provides optimizer function like adam, sgd, etc.," }, { "code": null, "e": 7308, "s": 7222, "text": "Optimizer module − Optimizer module provides optimizer function like adam, sgd, etc.," }, { "code": null, "e": 7404, "s": 7308, "text": "Regularizers − Regularizer module provides functions like L1 regularizer, L2 regularizer, etc.," }, { "code": null, "e": 7500, "s": 7404, "text": "Regularizers − Regularizer module provides functions like L1 regularizer, L2 regularizer, etc.," }, { "code": null, "e": 7562, "s": 7500, "text": "Let us learn Keras modules in detail in the upcoming chapter." }, { "code": null, "e": 7596, "s": 7562, "text": "\n 87 Lectures \n 11 hours \n" }, { "code": null, "e": 7613, "s": 7596, "text": " Abhilash Nelson" }, { "code": null, "e": 7646, "s": 7613, "text": "\n 61 Lectures \n 9 hours \n" }, { "code": null, "e": 7668, "s": 7646, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 7701, "s": 7668, "text": "\n 57 Lectures \n 7 hours \n" }, { "code": null, "e": 7723, "s": 7701, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 7756, "s": 7723, "text": "\n 52 Lectures \n 7 hours \n" }, { "code": null, "e": 7778, "s": 7756, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 7811, "s": 7778, "text": "\n 52 Lectures \n 6 hours \n" }, { "code": null, "e": 7833, "s": 7811, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 7866, "s": 7833, "text": "\n 68 Lectures \n 2 hours \n" }, { "code": null, "e": 7877, "s": 7866, "text": " Mike West" }, { "code": null, "e": 7884, "s": 7877, "text": " Print" }, { "code": null, "e": 7895, "s": 7884, "text": " Add Notes" } ]
Count number of substrings of a string consisting of same characters - GeeksforGeeks
26 Aug, 2021 Given a string. The task is to find out the numbers of substrings consisting of the same characters. Examples: Input: abba Output: 5 The desired substrings are {a}, {b}, {b}, {a}, {bb} Input: bbbcbb Output: 10 Approach: It is known for a string of length n, there are a total of n*(n+1)/2 number of substrings.Let’s initialize the result to 0. Traverse the string and find the number of consecutive element(let’s say count) of same characters. Whenever we find another character, increment the result by count*(count+1)/2, set count to 1, and from that index, repeat the above process.Remember, for each different character, the number of our desired substring is 1. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation// of the above approach#include <bits/stdc++.h>using namespace std; // Function to return the// number of substrings of// same charactersvoid findNumbers(string s){ if (s.empty()) return 0; // Size of the string int n = s.size(); // Initialize count to 1 int count = 1; int result = 0; // Initialize left to 0 and // right to 1 to traverse the // string int left = 0; int right = 1; while (right < n) { // Checking if consecutive // characters are same and // increment the count if (s[left] == s[right]) { count++; } // When we encounter a // different characters else { // Increment the result result += count * (count + 1) / 2; // To repeat the whole // process set left equals // right and count variable to 1 left = right; count = 1; } right++; } // Store the final // value of result result += count * (count + 1) / 2; cout << result << endl;} // Driver codeint main(){ string s = "bbbcbb"; findNumbers(s);} // Java implementation of the approachclass GFG{ // Function to return the // number of substrings of // same characters static void findNumbers(String s) { // Size of the string int n = s.length(); // Initialize count to 1 int count = 1; int result = 0; // Initialize left to 0 and // right to 1 to traverse the // string int left = 0; int right = 1; while (right < n) { // Checking if consecutive // characters are same and // increment the count if (s.charAt(left) == s.charAt(right)) { count++; } // When we encounter a // different characters else { // Increment the result result += count * (count + 1) / 2; // To repeat the whole // process set left equals // right and count variable to 1 left = right; count = 1; } right++; } // Store the final // value of result result += count * (count + 1) / 2; System.out.println(result); } // Driver code public static void main (String[] args) { String s = "bbbcbb"; findNumbers(s); }} // This code is contributed by AnkitRai01 # Python3 implementation of the above approach # Function to return the number of# substrings of same charactersdef findNumbers(s): # Size of the string n = len(s) # Initialize count to 1 count = 1 result = 0 # Initialize left to 0 and right to 1 # to traverse the string left = 0 right = 1 while (right < n): # Checking if consecutive # characters are same and # increment the count if (s[left] == s[right]): count += 1 # When we encounter a # different characters else: # Increment the result result += count * (count + 1) // 2 # To repeat the whole # process set left equals # right and count variable to 1 left = right count = 1 right += 1 # Store the final value of result result += count * (count + 1) // 2 print(result) # Driver codes = "bbbcbb" findNumbers(s) # This code is contributed by Mohit Kumar // C# implementation of the approachusing System; class GFG{ // Function to return the // number of substrings of // same characters static void findNumbers(String s) { // Size of the string int n = s.Length; // Initialize count to 1 int count = 1; int result = 0; // Initialize left to 0 and // right to 1 to traverse the // string int left = 0; int right = 1; while (right < n) { // Checking if consecutive // characters are same and // increment the count if (s[left] == s[right]) count++; // When we encounter a // different characters else { // Increment the result result += count * (count + 1) / 2; // To repeat the whole // process set left equals // right and count variable to 1 left = right; count = 1; } right++; } // Store the final // value of result result += count * (count + 1) / 2; Console.WriteLine(result); } // Driver code public static void Main(String[] args) { String s = "bbbcbb"; findNumbers(s); }} // This code is contributed by// sanjeev2552 <script> // Javascript implementation// of the above approach // Function to return the// number of substrings of// same charactersfunction findNumbers(s){ // Size of the string var n = s.length; // Initialize count to 1 var count = 1; var result = 0; // Initialize left to 0 and // right to 1 to traverse the // string var left = 0; var right = 1; while (right < n) { // Checking if consecutive // characters are same and // increment the count if (s[left] == s[right]) { count++; } // When we encounter a // different characters else { // Increment the result result += parseInt(count * (count + 1) / 2); // To repeat the whole // process set left equals // right and count variable to 1 left = right; count = 1; } right++; } // Store the final // value of result result += parseInt(count * (count + 1) / 2); document.write(result);} // Driver codevar s = "bbbcbb"; findNumbers(s); // This code is contributed by itsok </script> 10 ankthon sanjeev2552 mohit kumar 29 itsok kk773572498 deepakpunjabi substring Strings Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Top 50 String Coding Problems for Interviews Naive algorithm for Pattern Searching Vigenère Cipher Hill Cipher Count words in a given string How to Append a Character to a String in C Convert character array to string in C++ Program to count occurrence of a given character in a string sprintf() in C Converting Roman Numerals to Decimal lying between 1 to 3999
[ { "code": null, "e": 24854, "s": 24826, "text": "\n26 Aug, 2021" }, { "code": null, "e": 24955, "s": 24854, "text": "Given a string. The task is to find out the numbers of substrings consisting of the same characters." }, { "code": null, "e": 24966, "s": 24955, "text": "Examples: " }, { "code": null, "e": 25040, "s": 24966, "text": "Input: abba Output: 5 The desired substrings are {a}, {b}, {b}, {a}, {bb}" }, { "code": null, "e": 25067, "s": 25040, "text": "Input: bbbcbb Output: 10 " }, { "code": null, "e": 25524, "s": 25067, "text": "Approach: It is known for a string of length n, there are a total of n*(n+1)/2 number of substrings.Let’s initialize the result to 0. Traverse the string and find the number of consecutive element(let’s say count) of same characters. Whenever we find another character, increment the result by count*(count+1)/2, set count to 1, and from that index, repeat the above process.Remember, for each different character, the number of our desired substring is 1." }, { "code": null, "e": 25577, "s": 25524, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 25581, "s": 25577, "text": "C++" }, { "code": null, "e": 25586, "s": 25581, "text": "Java" }, { "code": null, "e": 25594, "s": 25586, "text": "Python3" }, { "code": null, "e": 25597, "s": 25594, "text": "C#" }, { "code": null, "e": 25608, "s": 25597, "text": "Javascript" }, { "code": "// C++ implementation// of the above approach#include <bits/stdc++.h>using namespace std; // Function to return the// number of substrings of// same charactersvoid findNumbers(string s){ if (s.empty()) return 0; // Size of the string int n = s.size(); // Initialize count to 1 int count = 1; int result = 0; // Initialize left to 0 and // right to 1 to traverse the // string int left = 0; int right = 1; while (right < n) { // Checking if consecutive // characters are same and // increment the count if (s[left] == s[right]) { count++; } // When we encounter a // different characters else { // Increment the result result += count * (count + 1) / 2; // To repeat the whole // process set left equals // right and count variable to 1 left = right; count = 1; } right++; } // Store the final // value of result result += count * (count + 1) / 2; cout << result << endl;} // Driver codeint main(){ string s = \"bbbcbb\"; findNumbers(s);}", "e": 26772, "s": 25608, "text": null }, { "code": "// Java implementation of the approachclass GFG{ // Function to return the // number of substrings of // same characters static void findNumbers(String s) { // Size of the string int n = s.length(); // Initialize count to 1 int count = 1; int result = 0; // Initialize left to 0 and // right to 1 to traverse the // string int left = 0; int right = 1; while (right < n) { // Checking if consecutive // characters are same and // increment the count if (s.charAt(left) == s.charAt(right)) { count++; } // When we encounter a // different characters else { // Increment the result result += count * (count + 1) / 2; // To repeat the whole // process set left equals // right and count variable to 1 left = right; count = 1; } right++; } // Store the final // value of result result += count * (count + 1) / 2; System.out.println(result); } // Driver code public static void main (String[] args) { String s = \"bbbcbb\"; findNumbers(s); }} // This code is contributed by AnkitRai01", "e": 28221, "s": 26772, "text": null }, { "code": "# Python3 implementation of the above approach # Function to return the number of# substrings of same charactersdef findNumbers(s): # Size of the string n = len(s) # Initialize count to 1 count = 1 result = 0 # Initialize left to 0 and right to 1 # to traverse the string left = 0 right = 1 while (right < n): # Checking if consecutive # characters are same and # increment the count if (s[left] == s[right]): count += 1 # When we encounter a # different characters else: # Increment the result result += count * (count + 1) // 2 # To repeat the whole # process set left equals # right and count variable to 1 left = right count = 1 right += 1 # Store the final value of result result += count * (count + 1) // 2 print(result) # Driver codes = \"bbbcbb\" findNumbers(s) # This code is contributed by Mohit Kumar", "e": 29229, "s": 28221, "text": null }, { "code": "// C# implementation of the approachusing System; class GFG{ // Function to return the // number of substrings of // same characters static void findNumbers(String s) { // Size of the string int n = s.Length; // Initialize count to 1 int count = 1; int result = 0; // Initialize left to 0 and // right to 1 to traverse the // string int left = 0; int right = 1; while (right < n) { // Checking if consecutive // characters are same and // increment the count if (s[left] == s[right]) count++; // When we encounter a // different characters else { // Increment the result result += count * (count + 1) / 2; // To repeat the whole // process set left equals // right and count variable to 1 left = right; count = 1; } right++; } // Store the final // value of result result += count * (count + 1) / 2; Console.WriteLine(result); } // Driver code public static void Main(String[] args) { String s = \"bbbcbb\"; findNumbers(s); }} // This code is contributed by// sanjeev2552", "e": 30601, "s": 29229, "text": null }, { "code": "<script> // Javascript implementation// of the above approach // Function to return the// number of substrings of// same charactersfunction findNumbers(s){ // Size of the string var n = s.length; // Initialize count to 1 var count = 1; var result = 0; // Initialize left to 0 and // right to 1 to traverse the // string var left = 0; var right = 1; while (right < n) { // Checking if consecutive // characters are same and // increment the count if (s[left] == s[right]) { count++; } // When we encounter a // different characters else { // Increment the result result += parseInt(count * (count + 1) / 2); // To repeat the whole // process set left equals // right and count variable to 1 left = right; count = 1; } right++; } // Store the final // value of result result += parseInt(count * (count + 1) / 2); document.write(result);} // Driver codevar s = \"bbbcbb\"; findNumbers(s); // This code is contributed by itsok </script>", "e": 31789, "s": 30601, "text": null }, { "code": null, "e": 31792, "s": 31789, "text": "10" }, { "code": null, "e": 31802, "s": 31794, "text": "ankthon" }, { "code": null, "e": 31814, "s": 31802, "text": "sanjeev2552" }, { "code": null, "e": 31829, "s": 31814, "text": "mohit kumar 29" }, { "code": null, "e": 31835, "s": 31829, "text": "itsok" }, { "code": null, "e": 31847, "s": 31835, "text": "kk773572498" }, { "code": null, "e": 31861, "s": 31847, "text": "deepakpunjabi" }, { "code": null, "e": 31871, "s": 31861, "text": "substring" }, { "code": null, "e": 31879, "s": 31871, "text": "Strings" }, { "code": null, "e": 31887, "s": 31879, "text": "Strings" }, { "code": null, "e": 31985, "s": 31887, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32030, "s": 31985, "text": "Top 50 String Coding Problems for Interviews" }, { "code": null, "e": 32068, "s": 32030, "text": "Naive algorithm for Pattern Searching" }, { "code": null, "e": 32085, "s": 32068, "text": "Vigenère Cipher" }, { "code": null, "e": 32097, "s": 32085, "text": "Hill Cipher" }, { "code": null, "e": 32127, "s": 32097, "text": "Count words in a given string" }, { "code": null, "e": 32170, "s": 32127, "text": "How to Append a Character to a String in C" }, { "code": null, "e": 32211, "s": 32170, "text": "Convert character array to string in C++" }, { "code": null, "e": 32272, "s": 32211, "text": "Program to count occurrence of a given character in a string" }, { "code": null, "e": 32287, "s": 32272, "text": "sprintf() in C" } ]
Share your Projects even more easily with this New Streamlit Feature | by Rahul Agarwal | Towards Data Science
A Machine Learning project is never really complete if we don’t have a good way to showcase it. While in the past, a well-made visualization or a small PPT used to be enough for showcasing a data science project, with the advent of dashboarding tools like RShiny and Dash, a good data scientist needs to have a fair bit of knowledge of web frameworks to get along. As Sten Sootla says in his satire piece which I thoroughly enjoyed: The secret: it’s not what you know, it’s what you show. This is where StreamLit comes in and provides a way to create web apps just using Python. I have been keeping close tabs on this excellent product for the past few months. In my last few posts, I talked about Working with Streamlit and how to Deploy the streamlit app using ec2. I have also been in constant touch with the Streamlit team while they have been working continuously to make the user experience even better by releasing additional features. So, have you ever had a problem with explaining how the app works to the stakeholders/business partners? Having to set up multiple calls with different stakeholders in different countries and explaining the whole process again and again? Or have you worked on a project that you want to share on social media? LinkedIn, Youtube, and the like? With their new version, Streamlit has released a new feature called “Record a Screencast” which will solve this problem for you. How? Read on. So to check this new feature out, which is a part of Streamlit’s version 0.55.0 offering, we need to first install or upgrade streamlit. Do this by using this command: pip install --upgrade streamlit We also need to run Streamlit. Here I will use the demo app. You can also use any of your own apps. streamlit hello You should see something like below: A tab also opens up in your browser, where you can try their demo. If that doesn’t open up in the browser, you can manually go to the Local URL http://localhost:8501/ too. Now the time has come to record our screencast to share with the world. You can find the option to record the screencast using the top-right menu in Streamlit. Once you click on that, you will get the option to record audio, and you can select the aptly named “Start Recording” button to start recording. You can then choose what you want to share — just your streamlit app or your entire desktop. One can choose to share the whole desktop if they need to go forth between different programs like Excel sheets, powerpoints, and the streamlit app, for example. Here I choose to show just the “Streamlit” App and click share. Your screencast has now started, and you can record the explanation session for your shareholders now. Once you are done with the recording, you can click on the top-right menu again and select stop recording. Or conveniently press escape to end the recording session. You will be able to preview and save the session video you recorded as a .webm file, which you can aim to send to your shareholders and even share on LinkedIn/twitter/youtube for your personal projects. And that’s it. The process is pretty simple and doesn’t need any additional software installation from our side. Streamlit has democratized the whole process of creating apps. I honestly like the way Streamlit is working on developing its product, keeping in mind all the pain points of its users. With this iteration, they have resolved one more pain point where users struggle to showcase their work in a meaningful way on social media sites or to explain the workings of an app multiple times to the shareholders. On top of that, Streamlit is a free and open-source rather than a proprietary web app that works out of the box. I couldn’t recommend it more. Also, do let me know if you want to request any additional features in Streamlit in the comments section. I will make sure to pass it on to the Streamlit team. If you want to learn more about using Streamlit to create and deploy apps, take a look at my other posts: towardsdatascience.com towardsdatascience.com If you want to learn about the best strategies for creating Visualizations, I would like to call out an excellent course about Data Visualization and applied plotting from the University of Michigan, which is a part of a pretty good Data Science Specialization with Python in itself. Do check it out. Thanks for the read. I am going to be writing more beginner-friendly posts in the future too. Follow me up at Medium or Subscribe to my blog to be informed about them. As always, I welcome feedback and constructive criticism and can be reached on Twitter @mlwhiz. Also, a small disclaimer — There might be some affiliate links in this post to relevant resources, as sharing knowledge is never a bad idea.
[ { "code": null, "e": 267, "s": 171, "text": "A Machine Learning project is never really complete if we don’t have a good way to showcase it." }, { "code": null, "e": 536, "s": 267, "text": "While in the past, a well-made visualization or a small PPT used to be enough for showcasing a data science project, with the advent of dashboarding tools like RShiny and Dash, a good data scientist needs to have a fair bit of knowledge of web frameworks to get along." }, { "code": null, "e": 604, "s": 536, "text": "As Sten Sootla says in his satire piece which I thoroughly enjoyed:" }, { "code": null, "e": 660, "s": 604, "text": "The secret: it’s not what you know, it’s what you show." }, { "code": null, "e": 1114, "s": 660, "text": "This is where StreamLit comes in and provides a way to create web apps just using Python. I have been keeping close tabs on this excellent product for the past few months. In my last few posts, I talked about Working with Streamlit and how to Deploy the streamlit app using ec2. I have also been in constant touch with the Streamlit team while they have been working continuously to make the user experience even better by releasing additional features." }, { "code": null, "e": 1352, "s": 1114, "text": "So, have you ever had a problem with explaining how the app works to the stakeholders/business partners? Having to set up multiple calls with different stakeholders in different countries and explaining the whole process again and again?" }, { "code": null, "e": 1457, "s": 1352, "text": "Or have you worked on a project that you want to share on social media? LinkedIn, Youtube, and the like?" }, { "code": null, "e": 1586, "s": 1457, "text": "With their new version, Streamlit has released a new feature called “Record a Screencast” which will solve this problem for you." }, { "code": null, "e": 1600, "s": 1586, "text": "How? Read on." }, { "code": null, "e": 1768, "s": 1600, "text": "So to check this new feature out, which is a part of Streamlit’s version 0.55.0 offering, we need to first install or upgrade streamlit. Do this by using this command:" }, { "code": null, "e": 1800, "s": 1768, "text": "pip install --upgrade streamlit" }, { "code": null, "e": 1900, "s": 1800, "text": "We also need to run Streamlit. Here I will use the demo app. You can also use any of your own apps." }, { "code": null, "e": 1916, "s": 1900, "text": "streamlit hello" }, { "code": null, "e": 1953, "s": 1916, "text": "You should see something like below:" }, { "code": null, "e": 2125, "s": 1953, "text": "A tab also opens up in your browser, where you can try their demo. If that doesn’t open up in the browser, you can manually go to the Local URL http://localhost:8501/ too." }, { "code": null, "e": 2285, "s": 2125, "text": "Now the time has come to record our screencast to share with the world. You can find the option to record the screencast using the top-right menu in Streamlit." }, { "code": null, "e": 2430, "s": 2285, "text": "Once you click on that, you will get the option to record audio, and you can select the aptly named “Start Recording” button to start recording." }, { "code": null, "e": 2749, "s": 2430, "text": "You can then choose what you want to share — just your streamlit app or your entire desktop. One can choose to share the whole desktop if they need to go forth between different programs like Excel sheets, powerpoints, and the streamlit app, for example. Here I choose to show just the “Streamlit” App and click share." }, { "code": null, "e": 3018, "s": 2749, "text": "Your screencast has now started, and you can record the explanation session for your shareholders now. Once you are done with the recording, you can click on the top-right menu again and select stop recording. Or conveniently press escape to end the recording session." }, { "code": null, "e": 3221, "s": 3018, "text": "You will be able to preview and save the session video you recorded as a .webm file, which you can aim to send to your shareholders and even share on LinkedIn/twitter/youtube for your personal projects." }, { "code": null, "e": 3334, "s": 3221, "text": "And that’s it. The process is pretty simple and doesn’t need any additional software installation from our side." }, { "code": null, "e": 3397, "s": 3334, "text": "Streamlit has democratized the whole process of creating apps." }, { "code": null, "e": 3738, "s": 3397, "text": "I honestly like the way Streamlit is working on developing its product, keeping in mind all the pain points of its users. With this iteration, they have resolved one more pain point where users struggle to showcase their work in a meaningful way on social media sites or to explain the workings of an app multiple times to the shareholders." }, { "code": null, "e": 3881, "s": 3738, "text": "On top of that, Streamlit is a free and open-source rather than a proprietary web app that works out of the box. I couldn’t recommend it more." }, { "code": null, "e": 4041, "s": 3881, "text": "Also, do let me know if you want to request any additional features in Streamlit in the comments section. I will make sure to pass it on to the Streamlit team." }, { "code": null, "e": 4147, "s": 4041, "text": "If you want to learn more about using Streamlit to create and deploy apps, take a look at my other posts:" }, { "code": null, "e": 4170, "s": 4147, "text": "towardsdatascience.com" }, { "code": null, "e": 4193, "s": 4170, "text": "towardsdatascience.com" }, { "code": null, "e": 4494, "s": 4193, "text": "If you want to learn about the best strategies for creating Visualizations, I would like to call out an excellent course about Data Visualization and applied plotting from the University of Michigan, which is a part of a pretty good Data Science Specialization with Python in itself. Do check it out." }, { "code": null, "e": 4758, "s": 4494, "text": "Thanks for the read. I am going to be writing more beginner-friendly posts in the future too. Follow me up at Medium or Subscribe to my blog to be informed about them. As always, I welcome feedback and constructive criticism and can be reached on Twitter @mlwhiz." } ]
Sorting array with conditional swapping
09 Jun, 2022 Given an array arr containing elements from [1...to n]. Each element appears exactly once in the array arr. Given an string str of length n-1. Each character of the string is either 0 or 1. In the array, swapping of the i-th element with (i + 1)-th element can be done as many times as we want, if the i-th character of the string is 1. Our task is to find whether it is possible to sort the array or not in ascending order. Examples: Input : arr = {1, 2, 5, 3, 4, 6} str = "01110" Output : Yes Explanation : Here, we can swap arr[2] and arr[3], and then swap arr[3] and arr[4]. Input : arr = {1, 2, 5, 3, 4, 6} str = "01010" Output : No Explanation : Here, the 3rd element of the array i.e. 5 can not be swapped as the 3rd character of the string is 0. Therefore it is impossible to sort the array. Approach Run a loop to length of the string str and calculate the max_element of the array from 0 to i for each i. At each iteration, if the i-th character of the string is ‘0’ and the max_element is greater than i + 1 then, it is impossible to sort the array, otherwise, possible.Basic implementation of the above approach : C++ Java Python 3 C# PHP Javascript // CPP program to Check if it// is possible to sort the// array in ascending order.#include <bits/stdc++.h>using namespace std; // Function to check if it is possible to// sort the arraystring possibleToSort(int* arr, int n, string str){ int max_element = -1; for (long i = 0; i < str.size(); i++) { // Calculating max_element // at each iteration. max_element = max(max_element, arr[i]); // if we can not swap the i-th element. if (str[i] == '0') { // if it is impossible to swap the // max_element then we can not // sort the array. if (max_element > i + 1) return "No"; } } // Otherwise, we can sort the array. return "Yes";} // Driver functionint main(){ int arr[] = { 1, 2, 5, 3, 4, 6 }; int n = sizeof(arr) / sizeof(arr[0]); string str = "01110"; cout << possibleToSort(arr, n, str); return 0;} // Java program to Check if it is possible to// sort the array in ascending order.import java.util.*;import java.lang.*; // Function to check if it is possible to// sort the arrayclass GFG{ public static String possibleToSort(int arr[], int n, String str) { int max_element = -1; for (int i = 0; i < str.length(); i++) { // Calculating max_element at each // iteration. max_element = Math.max(max_element, arr[i]); // if we can not swap the i-th // element. if (str.charAt(i) == '0') { // if it is impossible to swap // the max_element then we can // not sort the array. if (max_element > i + 1) return "No"; } } // Otherwise, we can sort the array. return "Yes"; } // Driven Program public static void main(String[] args) { int arr[] = { 1, 2, 5, 3, 4, 6 }; int n = arr.length; String str = "01110"; System.out.println( possibleToSort(arr, n, str)); }} // This code is contributed by Prasad Kshirsagar # Python 3 program to Check if it# is possible to sort the# array in ascending order. # Function to check if it is# possible to sort the arraydef possibleToSort(arr, n, str): max_element = -1 for i in range(len(str)) : # Calculating max_element # at each iteration. max_element = max(max_element, arr[i]) # if we can not swap the i-th element. if (str[i] == '0') : # if it is impossible to swap the # max_element then we can not # sort the array. if (max_element > i + 1): return "No" # Otherwise, we can sort the array. return "Yes" # Driver Codeif __name__ == "__main__": arr = [ 1, 2, 5, 3, 4, 6 ] n = len(arr) str = "01110" print(possibleToSort(arr, n, str)) # This code is contributed# by ChitraNayal // C# program to Check if it// is possible to sort the// array in ascending orderusing System;class GFG { // Function to check if it// is possible to sort the arraystatic string possibleToSort(int []arr, int n, string str){ int max_element = -1; for (int i = 0; i < str.Length; i++) { // Calculating max_element // at each iteration. max_element = Math.Max(max_element, arr[i]); // if we can not swap // the i-th element. if (str[i] == '0') { // if it is impossible to swap the // max_element then we can not // sort the array. if (max_element > i + 1) return "No"; } } // Otherwise, we can // sort the array. return "Yes";} // Driver Code static public void Main () { int []arr = {1, 2, 5, 3, 4, 6}; int n = arr.Length; string str = "01110"; Console.WriteLine(possibleToSort(arr, n, str)); }} // This code is contributed by anuj_67. <?php// PHP program to Check if it is possible// to sort the array in ascending order. // Function to check if it is possible// to sort the arrayfunction possibleToSort($arr, $n, $str){ $max_element = -1; for ($i = 0; $i < sizeof($str); $i++) { // Calculating max_element // at each iteration. $max_element = max($max_element, $arr[$i]); // if we can not swap the i-th element. if ($str[$i] == '0') { // if it is impossible to swap the // max_element then we can not // sort the array. if ($max_element > $i + 1) return "No"; } } // Otherwise, we can sort the array. return "Yes";} // Driver Code$arr = array(1, 2, 5, 3, 4, 6);$n = sizeof($arr);$str = "01110";echo possibleToSort($arr, $n, $str); // This code is contributed// by Akanksha Rai?> <script> // Javascript program to Check if it // is possible to sort the // array in ascending order // Function to check if it // is possible to sort the array function possibleToSort(arr, n, str) { let max_element = -1; for (let i = 0; i < str.length; i++) { // Calculating max_element // at each iteration. max_element = Math.max(max_element, arr[i]); // if we can not swap // the i-th element. if (str[i] == '0') { // if it is impossible to swap the // max_element then we can not // sort the array. if (max_element > i + 1) return "No"; } } // Otherwise, we can // sort the array. return "Yes"; } let arr = [1, 2, 5, 3, 4, 6]; let n = arr.Length; let str = "01110"; document.write(possibleToSort(arr, n, str)); // This code is contributed by divyesh072019.</script> Yes Time Complexity: O(n), where n is the size of the given string strAuxiliary Space: O(1), as no extra space is used vt_m Prasad_Kshirsagar ukasp Akanksha_Rai divyesh072019 surinderdawra388 singhh3010 binary-string limited-range-elements Arrays Strings Arrays Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Maximum and minimum of an array using minimum number of comparisons Top 50 Array Coding Problems for Interviews Multidimensional Arrays in Java Stack Data Structure (Introduction and Program) Linear Search Reverse a string in Java Write a program to print all permutations of a given string C++ Data Types Check for Balanced Brackets in an expression (well-formedness) using Stack Longest Common Subsequence | DP-4
[ { "code": null, "e": 52, "s": 24, "text": "\n09 Jun, 2022" }, { "code": null, "e": 489, "s": 52, "text": "Given an array arr containing elements from [1...to n]. Each element appears exactly once in the array arr. Given an string str of length n-1. Each character of the string is either 0 or 1. In the array, swapping of the i-th element with (i + 1)-th element can be done as many times as we want, if the i-th character of the string is 1. Our task is to find whether it is possible to sort the array or not in ascending order. Examples: " }, { "code": null, "e": 873, "s": 489, "text": "Input : arr = {1, 2, 5, 3, 4, 6}\n str = \"01110\"\nOutput : Yes\nExplanation :\nHere, we can swap arr[2] and arr[3], and then \nswap arr[3] and arr[4].\n\nInput : arr = {1, 2, 5, 3, 4, 6}\n str = \"01010\"\nOutput : No\nExplanation :\nHere, the 3rd element of the array i.e. 5 can not\nbe swapped as the 3rd character of the string is 0. \nTherefore it is impossible to sort the array." }, { "code": null, "e": 1203, "s": 875, "text": "Approach Run a loop to length of the string str and calculate the max_element of the array from 0 to i for each i. At each iteration, if the i-th character of the string is ‘0’ and the max_element is greater than i + 1 then, it is impossible to sort the array, otherwise, possible.Basic implementation of the above approach : " }, { "code": null, "e": 1207, "s": 1203, "text": "C++" }, { "code": null, "e": 1212, "s": 1207, "text": "Java" }, { "code": null, "e": 1221, "s": 1212, "text": "Python 3" }, { "code": null, "e": 1224, "s": 1221, "text": "C#" }, { "code": null, "e": 1228, "s": 1224, "text": "PHP" }, { "code": null, "e": 1239, "s": 1228, "text": "Javascript" }, { "code": "// CPP program to Check if it// is possible to sort the// array in ascending order.#include <bits/stdc++.h>using namespace std; // Function to check if it is possible to// sort the arraystring possibleToSort(int* arr, int n, string str){ int max_element = -1; for (long i = 0; i < str.size(); i++) { // Calculating max_element // at each iteration. max_element = max(max_element, arr[i]); // if we can not swap the i-th element. if (str[i] == '0') { // if it is impossible to swap the // max_element then we can not // sort the array. if (max_element > i + 1) return \"No\"; } } // Otherwise, we can sort the array. return \"Yes\";} // Driver functionint main(){ int arr[] = { 1, 2, 5, 3, 4, 6 }; int n = sizeof(arr) / sizeof(arr[0]); string str = \"01110\"; cout << possibleToSort(arr, n, str); return 0;}", "e": 2175, "s": 1239, "text": null }, { "code": "// Java program to Check if it is possible to// sort the array in ascending order.import java.util.*;import java.lang.*; // Function to check if it is possible to// sort the arrayclass GFG{ public static String possibleToSort(int arr[], int n, String str) { int max_element = -1; for (int i = 0; i < str.length(); i++) { // Calculating max_element at each // iteration. max_element = Math.max(max_element, arr[i]); // if we can not swap the i-th // element. if (str.charAt(i) == '0') { // if it is impossible to swap // the max_element then we can // not sort the array. if (max_element > i + 1) return \"No\"; } } // Otherwise, we can sort the array. return \"Yes\"; } // Driven Program public static void main(String[] args) { int arr[] = { 1, 2, 5, 3, 4, 6 }; int n = arr.length; String str = \"01110\"; System.out.println( possibleToSort(arr, n, str)); }} // This code is contributed by Prasad Kshirsagar", "e": 3414, "s": 2175, "text": null }, { "code": "# Python 3 program to Check if it# is possible to sort the# array in ascending order. # Function to check if it is# possible to sort the arraydef possibleToSort(arr, n, str): max_element = -1 for i in range(len(str)) : # Calculating max_element # at each iteration. max_element = max(max_element, arr[i]) # if we can not swap the i-th element. if (str[i] == '0') : # if it is impossible to swap the # max_element then we can not # sort the array. if (max_element > i + 1): return \"No\" # Otherwise, we can sort the array. return \"Yes\" # Driver Codeif __name__ == \"__main__\": arr = [ 1, 2, 5, 3, 4, 6 ] n = len(arr) str = \"01110\" print(possibleToSort(arr, n, str)) # This code is contributed# by ChitraNayal", "e": 4260, "s": 3414, "text": null }, { "code": "// C# program to Check if it// is possible to sort the// array in ascending orderusing System;class GFG { // Function to check if it// is possible to sort the arraystatic string possibleToSort(int []arr, int n, string str){ int max_element = -1; for (int i = 0; i < str.Length; i++) { // Calculating max_element // at each iteration. max_element = Math.Max(max_element, arr[i]); // if we can not swap // the i-th element. if (str[i] == '0') { // if it is impossible to swap the // max_element then we can not // sort the array. if (max_element > i + 1) return \"No\"; } } // Otherwise, we can // sort the array. return \"Yes\";} // Driver Code static public void Main () { int []arr = {1, 2, 5, 3, 4, 6}; int n = arr.Length; string str = \"01110\"; Console.WriteLine(possibleToSort(arr, n, str)); }} // This code is contributed by anuj_67.", "e": 5369, "s": 4260, "text": null }, { "code": "<?php// PHP program to Check if it is possible// to sort the array in ascending order. // Function to check if it is possible// to sort the arrayfunction possibleToSort($arr, $n, $str){ $max_element = -1; for ($i = 0; $i < sizeof($str); $i++) { // Calculating max_element // at each iteration. $max_element = max($max_element, $arr[$i]); // if we can not swap the i-th element. if ($str[$i] == '0') { // if it is impossible to swap the // max_element then we can not // sort the array. if ($max_element > $i + 1) return \"No\"; } } // Otherwise, we can sort the array. return \"Yes\";} // Driver Code$arr = array(1, 2, 5, 3, 4, 6);$n = sizeof($arr);$str = \"01110\";echo possibleToSort($arr, $n, $str); // This code is contributed// by Akanksha Rai?>", "e": 6270, "s": 5369, "text": null }, { "code": "<script> // Javascript program to Check if it // is possible to sort the // array in ascending order // Function to check if it // is possible to sort the array function possibleToSort(arr, n, str) { let max_element = -1; for (let i = 0; i < str.length; i++) { // Calculating max_element // at each iteration. max_element = Math.max(max_element, arr[i]); // if we can not swap // the i-th element. if (str[i] == '0') { // if it is impossible to swap the // max_element then we can not // sort the array. if (max_element > i + 1) return \"No\"; } } // Otherwise, we can // sort the array. return \"Yes\"; } let arr = [1, 2, 5, 3, 4, 6]; let n = arr.Length; let str = \"01110\"; document.write(possibleToSort(arr, n, str)); // This code is contributed by divyesh072019.</script>", "e": 7311, "s": 6270, "text": null }, { "code": null, "e": 7315, "s": 7311, "text": "Yes" }, { "code": null, "e": 7432, "s": 7317, "text": "Time Complexity: O(n), where n is the size of the given string strAuxiliary Space: O(1), as no extra space is used" }, { "code": null, "e": 7437, "s": 7432, "text": "vt_m" }, { "code": null, "e": 7455, "s": 7437, "text": "Prasad_Kshirsagar" }, { "code": null, "e": 7461, "s": 7455, "text": "ukasp" }, { "code": null, "e": 7474, "s": 7461, "text": "Akanksha_Rai" }, { "code": null, "e": 7488, "s": 7474, "text": "divyesh072019" }, { "code": null, "e": 7505, "s": 7488, "text": "surinderdawra388" }, { "code": null, "e": 7516, "s": 7505, "text": "singhh3010" }, { "code": null, "e": 7530, "s": 7516, "text": "binary-string" }, { "code": null, "e": 7553, "s": 7530, "text": "limited-range-elements" }, { "code": null, "e": 7560, "s": 7553, "text": "Arrays" }, { "code": null, "e": 7568, "s": 7560, "text": "Strings" }, { "code": null, "e": 7575, "s": 7568, "text": "Arrays" }, { "code": null, "e": 7583, "s": 7575, "text": "Strings" }, { "code": null, "e": 7681, "s": 7583, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7749, "s": 7681, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 7793, "s": 7749, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 7825, "s": 7793, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 7873, "s": 7825, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 7887, "s": 7873, "text": "Linear Search" }, { "code": null, "e": 7912, "s": 7887, "text": "Reverse a string in Java" }, { "code": null, "e": 7972, "s": 7912, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 7987, "s": 7972, "text": "C++ Data Types" }, { "code": null, "e": 8062, "s": 7987, "text": "Check for Balanced Brackets in an expression (well-formedness) using Stack" } ]
Node.js fs.unlinkSync() Method
08 Oct, 2021 The fs.unlinkSync() method is used to synchronously remove a file or symbolic link from the filesystem. This function does not work on directories, therefore it is recommended to use fs.rmdir() to remove a directory.Syntax: fs.unlinkSync( path ) Parameters: This method accepts one parameter as mentioned above and described below: path: It is a string, Buffer or URL which represents the file or symbolic link which has to be removed. Below examples illustrate the fs.unlinkSync() method in Node.js:Example 1: This example removes a file from the filesystem. javascript // Node.js program to demonstrate the// fs.unlinkSync() method // Import the filesystem moduleconst fs = require('fs'); // Get the files in current directory// before deletiongetFilesInDirectory(); // Delete readme.mdfs.unlinkSync("readme.md");console.log("\nFile readme.md is deleted"); // Get the files in current directory// after deletiongetFilesInDirectory(); // Function to get current filenames// in directory with specific extensionfunction getFilesInDirectory() { console.log("\nFiles present in directory:"); let files = fs.readdirSync(__dirname); files.forEach(file => { console.log(file); });} Output: Files present in directory: index.html index.js package.json readme.md File readme.md is deleted Files present in directory: index.html index.js package.json Example 2: This example removes a symbolic link from the filesystem. javascript // Node.js program to demonstrate the// fs.unlinkSync() method // Import the filesystem moduleconst fs = require('fs'); // Creating symlink to filefs.symlinkSync(__dirname + "\\readme.md", "symlinkToReadme");console.log("\nSymbolic link to readme.md created"); // Function to get current filenames// in directory with specific extensiongetFilesInDirectory(); // Deleting symbolic link to readme.mdfs.unlinkSync("symlinkToReadme");console.log("\nSymbolic link to readme.md deleted") getFilesInDirectory(); // Function to get current filenames// in directory with specific extensionfunction getFilesInDirectory() { console.log("\nFiles present in directory:"); let files = fs.readdirSync(__dirname); files.forEach(file => { console.log(file); });} Output: Symbolic link to readme.md created Files present in directory: index.html index.js package.json readme.md symlinkToReadme Symbolic link to readme.md deleted Files present in directory: index.html index.js package.json readme.md Reference: https://nodejs.org/api/fs.html#fs_fs_unlinksync_path rajeev0719singh Node.js-fs-module Picked Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n08 Oct, 2021" }, { "code": null, "e": 254, "s": 28, "text": "The fs.unlinkSync() method is used to synchronously remove a file or symbolic link from the filesystem. This function does not work on directories, therefore it is recommended to use fs.rmdir() to remove a directory.Syntax: " }, { "code": null, "e": 276, "s": 254, "text": "fs.unlinkSync( path )" }, { "code": null, "e": 364, "s": 276, "text": "Parameters: This method accepts one parameter as mentioned above and described below: " }, { "code": null, "e": 468, "s": 364, "text": "path: It is a string, Buffer or URL which represents the file or symbolic link which has to be removed." }, { "code": null, "e": 592, "s": 468, "text": "Below examples illustrate the fs.unlinkSync() method in Node.js:Example 1: This example removes a file from the filesystem." }, { "code": null, "e": 603, "s": 592, "text": "javascript" }, { "code": "// Node.js program to demonstrate the// fs.unlinkSync() method // Import the filesystem moduleconst fs = require('fs'); // Get the files in current directory// before deletiongetFilesInDirectory(); // Delete readme.mdfs.unlinkSync(\"readme.md\");console.log(\"\\nFile readme.md is deleted\"); // Get the files in current directory// after deletiongetFilesInDirectory(); // Function to get current filenames// in directory with specific extensionfunction getFilesInDirectory() { console.log(\"\\nFiles present in directory:\"); let files = fs.readdirSync(__dirname); files.forEach(file => { console.log(file); });}", "e": 1221, "s": 603, "text": null }, { "code": null, "e": 1230, "s": 1221, "text": "Output: " }, { "code": null, "e": 1390, "s": 1230, "text": "Files present in directory:\nindex.html\nindex.js\npackage.json\nreadme.md\n\nFile readme.md is deleted\n\nFiles present in directory:\nindex.html\nindex.js\npackage.json" }, { "code": null, "e": 1460, "s": 1390, "text": "Example 2: This example removes a symbolic link from the filesystem. " }, { "code": null, "e": 1471, "s": 1460, "text": "javascript" }, { "code": "// Node.js program to demonstrate the// fs.unlinkSync() method // Import the filesystem moduleconst fs = require('fs'); // Creating symlink to filefs.symlinkSync(__dirname + \"\\\\readme.md\", \"symlinkToReadme\");console.log(\"\\nSymbolic link to readme.md created\"); // Function to get current filenames// in directory with specific extensiongetFilesInDirectory(); // Deleting symbolic link to readme.mdfs.unlinkSync(\"symlinkToReadme\");console.log(\"\\nSymbolic link to readme.md deleted\") getFilesInDirectory(); // Function to get current filenames// in directory with specific extensionfunction getFilesInDirectory() { console.log(\"\\nFiles present in directory:\"); let files = fs.readdirSync(__dirname); files.forEach(file => { console.log(file); });}", "e": 2230, "s": 1471, "text": null }, { "code": null, "e": 2239, "s": 2230, "text": "Output: " }, { "code": null, "e": 2470, "s": 2239, "text": "Symbolic link to readme.md created\n\nFiles present in directory:\nindex.html\nindex.js\npackage.json\nreadme.md\nsymlinkToReadme\n\nSymbolic link to readme.md deleted\n\nFiles present in directory:\nindex.html\nindex.js\npackage.json\nreadme.md" }, { "code": null, "e": 2534, "s": 2470, "text": "Reference: https://nodejs.org/api/fs.html#fs_fs_unlinksync_path" }, { "code": null, "e": 2550, "s": 2534, "text": "rajeev0719singh" }, { "code": null, "e": 2568, "s": 2550, "text": "Node.js-fs-module" }, { "code": null, "e": 2575, "s": 2568, "text": "Picked" }, { "code": null, "e": 2583, "s": 2575, "text": "Node.js" }, { "code": null, "e": 2600, "s": 2583, "text": "Web Technologies" } ]
SOAP - Quick Guide
SOAP is an acronym for Simple Object Access Protocol. It is an XML-based messaging protocol for exchanging information among computers. SOAP is an application of the XML specification. SOAP is a communication protocol designed to communicate via Internet. SOAP is a communication protocol designed to communicate via Internet. SOAP can extend HTTP for XML messaging. SOAP can extend HTTP for XML messaging. SOAP provides data transport for Web services. SOAP provides data transport for Web services. SOAP can exchange complete documents or call a remote procedure. SOAP can exchange complete documents or call a remote procedure. SOAP can be used for broadcasting a message. SOAP can be used for broadcasting a message. SOAP is platform- and language-independent. SOAP is platform- and language-independent. SOAP is the XML way of defining what information is sent and how. SOAP is the XML way of defining what information is sent and how. SOAP enables client applications to easily connect to remote services and invoke remote methods. SOAP enables client applications to easily connect to remote services and invoke remote methods. Although SOAP can be used in a variety of messaging systems and can be delivered via a variety of transport protocols, the initial focus of SOAP is remote procedure calls transported via HTTP. Other frameworks including CORBA, DCOM, and Java RMI provide similar functionality to SOAP, but SOAP messages are written entirely in XML and are therefore uniquely platform- and language-independent. A SOAP message is an ordinary XML document containing the following elements − Envelope − Defines the start and the end of the message. It is a mandatory element. Envelope − Defines the start and the end of the message. It is a mandatory element. Header − Contains any optional attributes of the message used in processing the message, either at an intermediary point or at the ultimate end-point. It is an optional element. Header − Contains any optional attributes of the message used in processing the message, either at an intermediary point or at the ultimate end-point. It is an optional element. Body − Contains the XML data comprising the message being sent. It is a mandatory element. Body − Contains the XML data comprising the message being sent. It is a mandatory element. Fault − An optional Fault element that provides information about errors that occur while processing the message. Fault − An optional Fault element that provides information about errors that occur while processing the message. All these elements are declared in the default namespace for the SOAP envelope − http://www.w3.org/2001/12/soap-envelope and the default namespace for SOAP encoding and data types is − http://www.w3.org/2001/12/soap-encoding NOTE − All these specifications are subject to change. So keep updating yourself with the latest specifications available on the W3 website. The following block depicts the general structure of a SOAP message − <?xml version = "1.0"?> <SOAP-ENV:Envelope xmlns:SOAP-ENV = "http://www.w3.org/2001/12/soap-envelope" SOAP-ENV:encodingStyle = "http://www.w3.org/2001/12/soap-encoding"> <SOAP-ENV:Header> ... ... </SOAP-ENV:Header> <SOAP-ENV:Body> ... ... <SOAP-ENV:Fault> ... ... </SOAP-ENV:Fault> ... </SOAP-ENV:Body> </SOAP_ENV:Envelope> The SOAP envelope indicates the start and the end of the message so that the receiver knows when an entire message has been received. The SOAP envelope solves the problem of knowing when you are done receiving a message and are ready to process it. The SOAP envelope is therefore basically a packaging mechanism. Every SOAP message has a root Envelope element. Every SOAP message has a root Envelope element. Envelope is a mandatory part of SOAP message. Envelope is a mandatory part of SOAP message. Every Envelope element must contain exactly one Body element. Every Envelope element must contain exactly one Body element. If an Envelope contains a Header element, it must contain no more than one, and it must appear as the first child of the Envelope, before the Body. If an Envelope contains a Header element, it must contain no more than one, and it must appear as the first child of the Envelope, before the Body. The envelope changes when SOAP versions change. The envelope changes when SOAP versions change. The SOAP envelope is specified using the ENV namespace prefix and the Envelope element. The SOAP envelope is specified using the ENV namespace prefix and the Envelope element. The optional SOAP encoding is also specified using a namespace name and the optional encodingStyle element, which could also point to an encoding style other than the SOAP one. The optional SOAP encoding is also specified using a namespace name and the optional encodingStyle element, which could also point to an encoding style other than the SOAP one. A v1.1-compliant SOAP processor generates a fault upon receiving a message containing the v1.2 envelope namespace. A v1.1-compliant SOAP processor generates a fault upon receiving a message containing the v1.2 envelope namespace. A v1.2-compliant SOAP processor generates a VersionMismatch fault if it receives a message that does not include the v1.2 envelope namespace. A v1.2-compliant SOAP processor generates a VersionMismatch fault if it receives a message that does not include the v1.2 envelope namespace. Given below is an example of v1.2-compliant SOAP message. <?xml version = "1.0"?> <SOAP-ENV:Envelope xmlns:SOAP-ENV = "http://www.w3.org/2001/12/soap-envelope" SOAP-ENV:encodingStyle = " http://www.w3.org/2001/12/soap-encoding"> ... Message information goes here ... </SOAP-ENV:Envelope> The following example illustrates the use of a SOAP message within an HTTP POST operation, which sends the message to the server. It shows the namespaces for the envelope schema definition and for the schema definition of the encoding rules. The OrderEntry reference in the HTTP header is the name of the program to be invoked at the tutorialspoint.com website. POST /OrderEntry HTTP/1.1 Host: www.tutorialspoint.com Content-Type: application/soap; charset = "utf-8" Content-Length: nnnn <?xml version = "1.0"?> <SOAP-ENV:Envelope xmlns:SOAP-ENV = "http://www.w3.org/2001/12/soap-envelope" SOAP-ENV:encodingStyle = " http://www.w3.org/2001/12/soap-encoding"> ... Message information goes here ... </SOAP-ENV:Envelope> NOTE − The HTTP binding specifies the location of the service. The optional Header element offers a flexible framework for specifying additional application-level requirements. For example, the Header element can be used to specify a digital signature for password-protected services. Likewise, it can be used to specify an account number for pay-per-use SOAP services. It is an optional part of a SOAP message. It is an optional part of a SOAP message. Header elements can occur multiple times. Header elements can occur multiple times. Headers are intended to add new features and functionality. Headers are intended to add new features and functionality. The SOAP header contains header entries defined in a namespace. The SOAP header contains header entries defined in a namespace. The header is encoded as the first immediate child element of the SOAP envelope. The header is encoded as the first immediate child element of the SOAP envelope. When multiple headers are defined, all immediate child elements of the SOAP header are interpreted as SOAP header blocks. When multiple headers are defined, all immediate child elements of the SOAP header are interpreted as SOAP header blocks. A SOAP Header can have the following two attributes − The SOAP protocol defines a message path as a list of SOAP service nodes. Each of these intermediate nodes can perform some processing and then forward the message to the next node in the chain. By setting the Actor attribute, the client can specify the recipient of the SOAP header. It indicates whether a Header element is optional or mandatory. If set to true, the recipient must understand and process the Header attribute according to its defined semantics, or return a fault. The following example shows how to use a Header in a SOAP message. <?xml version = "1.0"?> <SOAP-ENV:Envelope xmlns:SOAP-ENV = " http://www.w3.org/2001/12/soap-envelope" SOAP-ENV:encodingStyle = " http://www.w3.org/2001/12/soap-encoding"> <SOAP-ENV:Header> <t:Transaction xmlns:t = "http://www.tutorialspoint.com/transaction/" SOAP-ENV:mustUnderstand = "true">5 </t:Transaction> </SOAP-ENV:Header> ... ... </SOAP-ENV:Envelope> The SOAP body is a mandatory element that contains the application-defined XML data being exchanged in the SOAP message. The body must be contained within the envelope and must follow any headers that might be defined for the message. The body is defined as a child element of the envelope, and the semantics for the body are defined in the associated SOAP schema. The body contains mandatory information intended for the ultimate receiver of the message. For example − <?xml version = "1.0"?> <SOAP-ENV:Envelope> ........ <SOAP-ENV:Body> <m:GetQuotation xmlns:m = "http://www.tp.com/Quotation"> <m:Item>Computers</m:Item> </m:GetQuotation> </SOAP-ENV:Body> </SOAP-ENV:Envelope> The example above requests a quotation of computer sets. Note that the m:GetQuotation and the Item elements above are application-specific elements. They are not a part of the SOAP standard. Here is the response to the above query − <?xml version = "1.0"?> <SOAP-ENV:Envelope> ........ <SOAP-ENV:Body> <m:GetQuotationResponse xmlns:m = "http://www.tp.com/Quotation"> <m:Quotation>This is Qutation</m:Quotation> </m:GetQuotationResponse> </SOAP-ENV:Body> </SOAP-ENV:Envelope> Normally, the application also defines a schema to contain semantics associated with the request and response elements. The Quotation service might be implemented using an EJB running in an application server; if so, the SOAP processor would be responsible for mapping the body information as parameters into and out of the EJB implementation of the GetQuotationResponse service. The SOAP processor could also be mapping the body information to a .NET object, a CORBA object, a COBOL program, and so on. If an error occurs during processing, the response to a SOAP message is a SOAP fault element in the body of the message, and the fault is returned to the sender of the SOAP message. The SOAP fault mechanism returns specific information about the error, including a predefined code, a description, and the address of the SOAP processor that generated the fault. A SOAP message can carry only one fault block. A SOAP message can carry only one fault block. Fault is an optional part of a SOAP message. Fault is an optional part of a SOAP message. For HTTP binding, a successful response is linked to the 200 to 299 range of status codes. For HTTP binding, a successful response is linked to the 200 to 299 range of status codes. SOAP Fault is linked to the 500 to 599 range of status codes. SOAP Fault is linked to the 500 to 599 range of status codes. The SOAP Fault has the following sub elements − <faultCode> It is a text code used to indicate a class of errors. See the next Table for a listing of predefined fault codes. <faultString> It is a text message explaining the error. <faultActor> It is a text string indicating who caused the fault. It is useful if the SOAP message travels through several nodes in the SOAP message path, and the client needs to know which node caused the error. A node that does not act as the ultimate destination must include a faultActor element. <detail> It is an element used to carry application-specific error messages. The detail element can contain child elements called detail entries. The faultCode values defined below must be used in the faultcode element while describing faults. SOAP-ENV:VersionMismatch Found an invalid namespace for the SOAP Envelope element. SOAP-ENV:MustUnderstand An immediate child element of the Header element, with the mustUnderstand attribute set to "1", was not understood. SOAP-ENV:Client The message was incorrectly formed or contained incorrect information. SOAP-ENV:Server There was a problem with the server, so the message could not proceed. The following code is a sample Fault. The client has requested a method named ValidateCreditCard, but the service does not support such a method. This represents a client request error, and the server returns the following SOAP response − <?xml version = '1.0' encoding = 'UTF-8'?> <SOAP-ENV:Envelope xmlns:SOAP-ENV = "http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi = "http://www.w3.org/1999/XMLSchema-instance" xmlns:xsd = "http://www.w3.org/1999/XMLSchema"> <SOAP-ENV:Body> <SOAP-ENV:Fault> <faultcode xsi:type = "xsd:string">SOAP-ENV:Client</faultcode> <faultstring xsi:type = "xsd:string"> Failed to locate method (ValidateCreditCard) in class (examplesCreditCard) at /usr/local/ActivePerl-5.6/lib/site_perl/5.6.0/SOAP/Lite.pm line 1555. </faultstring> </SOAP-ENV:Fault> </SOAP-ENV:Body> </SOAP-ENV:Envelope> SOAP includes a built-in set of rules for encoding data types. It enables the SOAP message to indicate specific data types, such as integers, floats, doubles, or arrays. SOAP data types are divided into two broad categories − scalar types and compound types. SOAP data types are divided into two broad categories − scalar types and compound types. Scalar types contain exactly one value such as a last name, price, or product description. Scalar types contain exactly one value such as a last name, price, or product description. Compound types contain multiple values such as a purchase order or a list of stock quotes. Compound types contain multiple values such as a purchase order or a list of stock quotes. Compound types are further subdivided into arrays and structs. Compound types are further subdivided into arrays and structs. The encoding style for a SOAP message is set via the SOAP-ENV:encodingStyle attribute. The encoding style for a SOAP message is set via the SOAP-ENV:encodingStyle attribute. To use SOAP 1.1 encoding, use the value http://schemas.xmlsoap.org/soap/encoding/ To use SOAP 1.1 encoding, use the value http://schemas.xmlsoap.org/soap/encoding/ To use SOAP 1.2 encoding, use the value http://www.w3.org/2001/12/soap-encoding To use SOAP 1.2 encoding, use the value http://www.w3.org/2001/12/soap-encoding Latest SOAP specification adopts all the built-in types defined by XML Schema. Still, SOAP maintains its own convention for defining constructs not standardized by XML Schema, such as arrays and references. Latest SOAP specification adopts all the built-in types defined by XML Schema. Still, SOAP maintains its own convention for defining constructs not standardized by XML Schema, such as arrays and references. For scalar types, SOAP adopts all the built-in simple types specified by the XML Schema specification. This includes strings, floats, doubles, and integers. The following table lists the main simple types, excerpted from the XML Schema Part 0 − Primer http://www.w3.org/TR/2000/WD-xmlschema-0-20000407/ For example, here is a SOAP response with a double data type − <?xml version = '1.0' encoding = 'UTF-8'?> <SOAP-ENV:Envelope xmlns:SOAP-ENV = "http://www.w3.org/2001/12/soap-envelope" xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd = "http://www.w3.org/2001/XMLSchema"> <SOAP-ENV:Body> <ns1:getPriceResponse xmlns:ns1 = "urn:examples:priceservice" SOAP-ENV:encodingStyle = "http://www.w3.org/2001/12/soap-encoding"> <return xsi:type = "xsd:double">54.99</return> </ns1:getPriceResponse> </SOAP-ENV:Body> </SOAP-ENV:Envelope> SOAP arrays have a very specific set of rules, which require that you specify both the element type and array size. SOAP also supports multidimensional arrays, but not all SOAP implementations support multidimensional functionality. To create an array, you must specify it as an xsi:type of array. The array must also include an arrayType attribute. This attribute is required to specify the data type for the contained elements and the dimension(s) of the array. For example, the following attribute specifies an array of 10 double values − arrayType = "xsd:double[10]" In contrast, the following attribute specifies a two-dimensional array of strings − arrayType = "xsd:string[5,5]" Here is a sample SOAP response with an array of double values − <?xml version = '1.0' encoding = 'UTF-8'?> <SOAP-ENV:Envelope xmlns:SOAP-ENV = "http://www.w3.org/2001/12/soap-envelope" xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd = "http://www.w3.org/2001/XMLSchema"> <SOAP-ENV:Body> <ns1:getPriceListResponse xmlns:ns1 = "urn:examples:pricelistservice" SOAP-ENV:encodingStyle = "http://www.w3.org/2001/12/soap-encoding"> <return xmlns:ns2 = "http://www.w3.org/2001/09/soap-encoding" xsi:type = "ns2:Array" ns2:arrayType = "xsd:double[2]"> <item xsi:type = "xsd:double">54.99</item> <item xsi:type = "xsd:double">19.99</item> </return> </ns1:getPriceListResponse> </SOAP-ENV:Body> </SOAP-ENV:Envelope> Structs contain multiple values, but each element is specified with a unique accessor element. For example, consider an item within a product catalog. In this case, the struct might contain a product SKU, product name, description, and price. Here is how such a struct would be represented in a SOAP message − <?xml version = '1.0' encoding = 'UTF-8'?> <SOAP-ENV:Envelope xmlns:SOAP-ENV = "http://www.w3.org/2001/12/soap-envelope" xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd = "http://www.w3.org/2001/XMLSchema"> <SOAP-ENV:Body> <ns1:getProductResponse xmlns:ns1 = "urn:examples:productservice" SOAP-ENV:encodingStyle = "http://www.w3.org/2001/12/soap-encoding"> <return xmlns:ns2 = "urn:examples" xsi:type = "ns2:product"> <name xsi:type = "xsd:string">Red Hat Linux</name> <price xsi:type = "xsd:double">54.99</price> <description xsi:type = "xsd:string"> Red Hat Linux Operating System </description> <SKU xsi:type = "xsd:string">A358185</SKU> </return> </ns1:getProductResponse> </SOAP-ENV:Body> </SOAP-ENV:Envelope> NOTE − Please take care of proper indentation while you write your SOAP code. Each element in a struct is specified with a unique accessor name. For example, the message above includes four accessor elements − name, price, description, and SKU. Each element can have its own data type. For example, name is specified as a string, whereas price is specified as double. SOAP is not tied to any transport protocol. SOAP can be transported via SMTP, FTP, IBM's MQSeries, or Microsoft Message Queuing (MSMQ). SOAP specification includes details on HTTP only. HTTP remains the most popular SOAP transport protocol. Quite logically, SOAP requests are sent via an HTTP request and SOAP responses are returned within the content of the HTTP response. While SOAP requests can be sent via an HTTP GET, the specification includes details on HTTP POST only. Additionally, both HTTP requests and responses are required to set their content type to text/xml. The SOAP specification mandates that the client must provide a SOAPAction header, but the actual value of the SOAPAction header is dependent on the SOAP server implementation. For example, to access the AltaVista BabelFish Translation service, hosted by XMethods, you must specify the following as a SOAPAction header. urn:xmethodsBabelFish#BabelFish Even if the server does not require a full SOAPAction header, the client must specify an empty string ("") or a null value. For example − SOAPAction: "" SOAPAction: Here is a sample request sent via HTTP to the XMethods Babelfish Translation service − POST /perl/soaplite.cgi HTTP/1.0 Host: services.xmethods.com Content-Type: text/xml; charset = utf-8 Content-Length: 538 SOAPAction: "urn:xmethodsBabelFish#BabelFish" <?xml version = '1.0' encoding = 'UTF-8'?> <SOAP-ENV:Envelope xmlns:SOAP-ENV = "http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi = "http://www.w3.org/1999/XMLSchema-instance" xmlns:xsd = "http://www.w3.org/1999/XMLSchema"> <SOAP-ENV:Body> <ns1:BabelFish xmlns:ns1 = "urn:xmethodsBabelFish" SOAP-ENV:encodingStyle = "http://schemas.xmlsoap.org/soap/encoding/"> <translationmode xsi:type = "xsd:string">en_fr</translationmode> <sourcedata xsi:type = "xsd:string">Hello, world!</sourcedata> </ns1:BabelFish> </SOAP-ENV:Body> </SOAP-ENV:Envelope> Note the content type and the SOAPAction header. Also note that the BabelFish method requires two String parameters. The translation mode en_fr translates from English to French. Here is the response from XMethods − HTTP/1.1 200 OK Date: Sat, 09 Jun 2001 15:01:55 GMT Server: Apache/1.3.14 (Unix) tomcat/1.0 PHP/4.0.1pl2 SOAPServer: SOAP::Lite/Perl/0.50 Cache-Control: s-maxage = 60, proxy-revalidate Content-Length: 539 Content-Type: text/xml <?xml version = "1.0" encoding = "UTF-8"?> <SOAP-ENV:Envelope xmlns:SOAP-ENC = "http://schemas.xmlsoap.org/soap/encoding/" SOAP-ENV:encodingStyle = "http://schemas.xmlsoap.org/soap/encoding/" xmlns:xsi = "http://www.w3.org/1999/XMLSchema-instance" xmlns:SOAP-ENV = "http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd = "http://www.w3.org/1999/XMLSchema"> <SOAP-ENV:Body> <namesp1:BabelFishResponse xmlns:namesp1 = "urn:xmethodsBabelFish"> <return xsi:type = "xsd:string">Bonjour, monde!</return> </namesp1:BabelFishResponse> </SOAP-ENV:Body> </SOAP-ENV:Envelope> SOAP responses delivered via HTTP are required to follow the same HTTP status codes. For example, a status code of 200 OK indicates a successful response. A status code of 500 Internal Server Error indicates that there is a server error and that the SOAP response includes a Fault element. In the example below, a GetQuotation request is sent to a SOAP Server over HTTP. The request has a QuotationName parameter, and a Quotation will be returned in the response. The namespace for the function is defined in http://www.xyz.org/quotation address. Here is the SOAP request − POST /Quotation HTTP/1.0 Host: www.xyz.org Content-Type: text/xml; charset = utf-8 Content-Length: nnn <?xml version = "1.0"?> <SOAP-ENV:Envelope xmlns:SOAP-ENV = "http://www.w3.org/2001/12/soap-envelope" SOAP-ENV:encodingStyle = "http://www.w3.org/2001/12/soap-encoding"> <SOAP-ENV:Body xmlns:m = "http://www.xyz.org/quotations"> <m:GetQuotation> <m:QuotationsName>MiscroSoft</m:QuotationsName> </m:GetQuotation> </SOAP-ENV:Body> </SOAP-ENV:Envelope> A corresponding SOAP response looks like − HTTP/1.0 200 OK Content-Type: text/xml; charset = utf-8 Content-Length: nnn <?xml version = "1.0"?> <SOAP-ENV:Envelope xmlns:SOAP-ENV = "http://www.w3.org/2001/12/soap-envelope" SOAP-ENV:encodingStyle = "http://www.w3.org/2001/12/soap-encoding"> <SOAP-ENV:Body xmlns:m = "http://www.xyz.org/quotation"> <m:GetQuotationResponse> <m:Quotation>Here is the quotation</m:Quotation> </m:GetQuotationResponse> </SOAP-ENV:Body> </SOAP-ENV:Envelope> SOAP 1.1 was originally submitted to the W3C in May 2000. Official submitters included large companies such as Microsoft, IBM, and Ariba, and smaller companies such as UserLand Software and DevelopMentor. In July 2001, the XML Protocol Working Group released a "working draft" of SOAP 1.2. Within the W3C, this document is officially a work in progress, meaning that the document is likely to be updated many times before it is finalized. SOAP Version 1.1 is available online at http://www.w3.org/TR/SOAP/ The working draft of SOAP Version 1.2 is available at http://www.w3.org/TR/soap12/ Note that the W3C also hosts a submission for "SOAP Messages with Attachments", which separates from the core SOAP specification. This specification enables SOAP messages to include binary attachments such as images and sound files. For full details, see the W3C Note at http://www.w3.org/TR/SOAP-attachments.
[ { "code": null, "e": 2033, "s": 1848, "text": "SOAP is an acronym for Simple Object Access Protocol. It is an XML-based messaging protocol for exchanging information among computers. SOAP is an application of the XML specification." }, { "code": null, "e": 2104, "s": 2033, "text": "SOAP is a communication protocol designed to communicate via Internet." }, { "code": null, "e": 2175, "s": 2104, "text": "SOAP is a communication protocol designed to communicate via Internet." }, { "code": null, "e": 2215, "s": 2175, "text": "SOAP can extend HTTP for XML messaging." }, { "code": null, "e": 2255, "s": 2215, "text": "SOAP can extend HTTP for XML messaging." }, { "code": null, "e": 2302, "s": 2255, "text": "SOAP provides data transport for Web services." }, { "code": null, "e": 2349, "s": 2302, "text": "SOAP provides data transport for Web services." }, { "code": null, "e": 2414, "s": 2349, "text": "SOAP can exchange complete documents or call a remote procedure." }, { "code": null, "e": 2479, "s": 2414, "text": "SOAP can exchange complete documents or call a remote procedure." }, { "code": null, "e": 2524, "s": 2479, "text": "SOAP can be used for broadcasting a message." }, { "code": null, "e": 2569, "s": 2524, "text": "SOAP can be used for broadcasting a message." }, { "code": null, "e": 2613, "s": 2569, "text": "SOAP is platform- and language-independent." }, { "code": null, "e": 2657, "s": 2613, "text": "SOAP is platform- and language-independent." }, { "code": null, "e": 2723, "s": 2657, "text": "SOAP is the XML way of defining what information is sent and how." }, { "code": null, "e": 2789, "s": 2723, "text": "SOAP is the XML way of defining what information is sent and how." }, { "code": null, "e": 2886, "s": 2789, "text": "SOAP enables client applications to easily connect to remote services and invoke remote methods." }, { "code": null, "e": 2983, "s": 2886, "text": "SOAP enables client applications to easily connect to remote services and invoke remote methods." }, { "code": null, "e": 3176, "s": 2983, "text": "Although SOAP can be used in a variety of messaging systems and can be delivered via a variety of transport protocols, the initial focus of SOAP is remote procedure calls transported via HTTP." }, { "code": null, "e": 3377, "s": 3176, "text": "Other frameworks including CORBA, DCOM, and Java RMI provide similar functionality to SOAP, but SOAP messages are written entirely in XML and are therefore uniquely platform- and language-independent." }, { "code": null, "e": 3456, "s": 3377, "text": "A SOAP message is an ordinary XML document containing the following elements −" }, { "code": null, "e": 3540, "s": 3456, "text": "Envelope − Defines the start and the end of the message. It is a mandatory element." }, { "code": null, "e": 3624, "s": 3540, "text": "Envelope − Defines the start and the end of the message. It is a mandatory element." }, { "code": null, "e": 3802, "s": 3624, "text": "Header − Contains any optional attributes of the message used in processing the message, either at an intermediary point or at the ultimate end-point. It is an optional element." }, { "code": null, "e": 3980, "s": 3802, "text": "Header − Contains any optional attributes of the message used in processing the message, either at an intermediary point or at the ultimate end-point. It is an optional element." }, { "code": null, "e": 4071, "s": 3980, "text": "Body − Contains the XML data comprising the message being sent. It is a mandatory element." }, { "code": null, "e": 4162, "s": 4071, "text": "Body − Contains the XML data comprising the message being sent. It is a mandatory element." }, { "code": null, "e": 4276, "s": 4162, "text": "Fault − An optional Fault element that provides information about errors that occur while processing the message." }, { "code": null, "e": 4390, "s": 4276, "text": "Fault − An optional Fault element that provides information about errors that occur while processing the message." }, { "code": null, "e": 4615, "s": 4390, "text": "All these elements are declared in the default namespace for the SOAP envelope − http://www.w3.org/2001/12/soap-envelope and the default namespace for SOAP encoding and data types is − http://www.w3.org/2001/12/soap-encoding" }, { "code": null, "e": 4756, "s": 4615, "text": "NOTE − All these specifications are subject to change. So keep updating yourself with the latest specifications available on the W3 website." }, { "code": null, "e": 4826, "s": 4756, "text": "The following block depicts the general structure of a SOAP message −" }, { "code": null, "e": 5227, "s": 4826, "text": "<?xml version = \"1.0\"?>\n<SOAP-ENV:Envelope xmlns:SOAP-ENV = \"http://www.w3.org/2001/12/soap-envelope\" \n SOAP-ENV:encodingStyle = \"http://www.w3.org/2001/12/soap-encoding\">\n\n <SOAP-ENV:Header>\n ...\n ...\n </SOAP-ENV:Header>\n <SOAP-ENV:Body>\n ...\n ...\n <SOAP-ENV:Fault>\n ...\n ...\n </SOAP-ENV:Fault>\n ...\n </SOAP-ENV:Body>\n</SOAP_ENV:Envelope>" }, { "code": null, "e": 5540, "s": 5227, "text": "The SOAP envelope indicates the start and the end of the message so that the receiver knows when an entire message has been received. The SOAP envelope solves the problem of knowing when you are done receiving a message and are ready to process it. The SOAP envelope is therefore basically a packaging mechanism." }, { "code": null, "e": 5588, "s": 5540, "text": "Every SOAP message has a root Envelope element." }, { "code": null, "e": 5636, "s": 5588, "text": "Every SOAP message has a root Envelope element." }, { "code": null, "e": 5682, "s": 5636, "text": "Envelope is a mandatory part of SOAP message." }, { "code": null, "e": 5728, "s": 5682, "text": "Envelope is a mandatory part of SOAP message." }, { "code": null, "e": 5790, "s": 5728, "text": "Every Envelope element must contain exactly one Body element." }, { "code": null, "e": 5852, "s": 5790, "text": "Every Envelope element must contain exactly one Body element." }, { "code": null, "e": 6000, "s": 5852, "text": "If an Envelope contains a Header element, it must contain no more than one, and it must appear as the first child of the Envelope, before the Body." }, { "code": null, "e": 6148, "s": 6000, "text": "If an Envelope contains a Header element, it must contain no more than one, and it must appear as the first child of the Envelope, before the Body." }, { "code": null, "e": 6196, "s": 6148, "text": "The envelope changes when SOAP versions change." }, { "code": null, "e": 6244, "s": 6196, "text": "The envelope changes when SOAP versions change." }, { "code": null, "e": 6332, "s": 6244, "text": "The SOAP envelope is specified using the ENV namespace prefix and the Envelope element." }, { "code": null, "e": 6420, "s": 6332, "text": "The SOAP envelope is specified using the ENV namespace prefix and the Envelope element." }, { "code": null, "e": 6597, "s": 6420, "text": "The optional SOAP encoding is also specified using a namespace name and the optional encodingStyle element, which could also point to an encoding style other than the SOAP one." }, { "code": null, "e": 6774, "s": 6597, "text": "The optional SOAP encoding is also specified using a namespace name and the optional encodingStyle element, which could also point to an encoding style other than the SOAP one." }, { "code": null, "e": 6889, "s": 6774, "text": "A v1.1-compliant SOAP processor generates a fault upon receiving a message containing the v1.2 envelope namespace." }, { "code": null, "e": 7004, "s": 6889, "text": "A v1.1-compliant SOAP processor generates a fault upon receiving a message containing the v1.2 envelope namespace." }, { "code": null, "e": 7146, "s": 7004, "text": "A v1.2-compliant SOAP processor generates a VersionMismatch fault if it receives a message that does not include the v1.2 envelope namespace." }, { "code": null, "e": 7288, "s": 7146, "text": "A v1.2-compliant SOAP processor generates a VersionMismatch fault if it receives a message that does not include the v1.2 envelope namespace." }, { "code": null, "e": 7346, "s": 7288, "text": "Given below is an example of v1.2-compliant SOAP message." }, { "code": null, "e": 7593, "s": 7346, "text": "<?xml version = \"1.0\"?>\n<SOAP-ENV:Envelope \n xmlns:SOAP-ENV = \"http://www.w3.org/2001/12/soap-envelope\" \n SOAP-ENV:encodingStyle = \" http://www.w3.org/2001/12/soap-encoding\">\n ...\n Message information goes here\n ...\n</SOAP-ENV:Envelope>" }, { "code": null, "e": 7955, "s": 7593, "text": "The following example illustrates the use of a SOAP message within an HTTP POST operation, which sends the message to the server. It shows the namespaces for the envelope schema definition and for the schema definition of the encoding rules. The OrderEntry reference in the HTTP header is the name of the program to be invoked at the tutorialspoint.com website." }, { "code": null, "e": 8329, "s": 7955, "text": "POST /OrderEntry HTTP/1.1\nHost: www.tutorialspoint.com\nContent-Type: application/soap; charset = \"utf-8\"\nContent-Length: nnnn\n\n<?xml version = \"1.0\"?>\n<SOAP-ENV:Envelope \n xmlns:SOAP-ENV = \"http://www.w3.org/2001/12/soap-envelope\" \n SOAP-ENV:encodingStyle = \" http://www.w3.org/2001/12/soap-encoding\">\n ...\n Message information goes here\n ...\n</SOAP-ENV:Envelope>" }, { "code": null, "e": 8392, "s": 8329, "text": "NOTE − The HTTP binding specifies the location of the service." }, { "code": null, "e": 8699, "s": 8392, "text": "The optional Header element offers a flexible framework for specifying additional application-level requirements. For example, the Header element can be used to specify a digital signature for password-protected services. Likewise, it can be used to specify an account number for pay-per-use SOAP services." }, { "code": null, "e": 8741, "s": 8699, "text": "It is an optional part of a SOAP message." }, { "code": null, "e": 8783, "s": 8741, "text": "It is an optional part of a SOAP message." }, { "code": null, "e": 8825, "s": 8783, "text": "Header elements can occur multiple times." }, { "code": null, "e": 8867, "s": 8825, "text": "Header elements can occur multiple times." }, { "code": null, "e": 8927, "s": 8867, "text": "Headers are intended to add new features and functionality." }, { "code": null, "e": 8987, "s": 8927, "text": "Headers are intended to add new features and functionality." }, { "code": null, "e": 9051, "s": 8987, "text": "The SOAP header contains header entries defined in a namespace." }, { "code": null, "e": 9115, "s": 9051, "text": "The SOAP header contains header entries defined in a namespace." }, { "code": null, "e": 9196, "s": 9115, "text": "The header is encoded as the first immediate child element of the SOAP envelope." }, { "code": null, "e": 9277, "s": 9196, "text": "The header is encoded as the first immediate child element of the SOAP envelope." }, { "code": null, "e": 9399, "s": 9277, "text": "When multiple headers are defined, all immediate child elements of the SOAP header are interpreted as SOAP header blocks." }, { "code": null, "e": 9521, "s": 9399, "text": "When multiple headers are defined, all immediate child elements of the SOAP header are interpreted as SOAP header blocks." }, { "code": null, "e": 9575, "s": 9521, "text": "A SOAP Header can have the following two attributes −" }, { "code": null, "e": 9859, "s": 9575, "text": "The SOAP protocol defines a message path as a list of SOAP service nodes. Each of these intermediate nodes can perform some processing and then forward the message to the next node in the chain. By setting the Actor attribute, the client can specify the recipient of the SOAP header." }, { "code": null, "e": 10057, "s": 9859, "text": "It indicates whether a Header element is optional or mandatory. If set to true, the recipient must understand and process the Header attribute according to its defined semantics, or return a fault." }, { "code": null, "e": 10124, "s": 10057, "text": "The following example shows how to use a Header in a SOAP message." }, { "code": null, "e": 10539, "s": 10124, "text": "<?xml version = \"1.0\"?>\n<SOAP-ENV:Envelope \n xmlns:SOAP-ENV = \" http://www.w3.org/2001/12/soap-envelope\" \n SOAP-ENV:encodingStyle = \" http://www.w3.org/2001/12/soap-encoding\">\n\n <SOAP-ENV:Header>\n <t:Transaction \n xmlns:t = \"http://www.tutorialspoint.com/transaction/\" \n SOAP-ENV:mustUnderstand = \"true\">5\n </t:Transaction>\n </SOAP-ENV:Header>\n ...\n ...\n</SOAP-ENV:Envelope>" }, { "code": null, "e": 10774, "s": 10539, "text": "The SOAP body is a mandatory element that contains the application-defined XML data being exchanged in the SOAP message. The body must be contained within the envelope and must follow any headers that might be defined for the message." }, { "code": null, "e": 10904, "s": 10774, "text": "The body is defined as a child element of the envelope, and the semantics for the body are defined in the associated SOAP schema." }, { "code": null, "e": 11009, "s": 10904, "text": "The body contains mandatory information intended for the ultimate receiver of the message. For example −" }, { "code": null, "e": 11248, "s": 11009, "text": "<?xml version = \"1.0\"?>\n<SOAP-ENV:Envelope>\n ........\n <SOAP-ENV:Body>\n <m:GetQuotation xmlns:m = \"http://www.tp.com/Quotation\">\n <m:Item>Computers</m:Item>\n </m:GetQuotation>\n </SOAP-ENV:Body>\n</SOAP-ENV:Envelope>" }, { "code": null, "e": 11439, "s": 11248, "text": "The example above requests a quotation of computer sets. Note that the m:GetQuotation and the Item elements above are application-specific elements. They are not a part of the SOAP standard." }, { "code": null, "e": 11481, "s": 11439, "text": "Here is the response to the above query −" }, { "code": null, "e": 11753, "s": 11481, "text": "<?xml version = \"1.0\"?>\n<SOAP-ENV:Envelope>\n ........\n <SOAP-ENV:Body>\n <m:GetQuotationResponse xmlns:m = \"http://www.tp.com/Quotation\">\n <m:Quotation>This is Qutation</m:Quotation>\n </m:GetQuotationResponse>\n </SOAP-ENV:Body>\n</SOAP-ENV:Envelope>" }, { "code": null, "e": 11873, "s": 11753, "text": "Normally, the application also defines a schema to contain semantics associated with the request and response elements." }, { "code": null, "e": 12257, "s": 11873, "text": "The Quotation service might be implemented using an EJB running in an application server; if so, the SOAP processor would be responsible for mapping the body information as parameters into and out of the EJB implementation of the GetQuotationResponse service. The SOAP processor could also be mapping the body information to a .NET object, a CORBA object, a COBOL program, and so on." }, { "code": null, "e": 12439, "s": 12257, "text": "If an error occurs during processing, the response to a SOAP message is a SOAP fault element in the body of the message, and the fault is returned to the sender of the SOAP message." }, { "code": null, "e": 12618, "s": 12439, "text": "The SOAP fault mechanism returns specific information about the error, including a predefined code, a description, and the address of the SOAP processor that generated the fault." }, { "code": null, "e": 12665, "s": 12618, "text": "A SOAP message can carry only one fault block." }, { "code": null, "e": 12712, "s": 12665, "text": "A SOAP message can carry only one fault block." }, { "code": null, "e": 12757, "s": 12712, "text": "Fault is an optional part of a SOAP message." }, { "code": null, "e": 12802, "s": 12757, "text": "Fault is an optional part of a SOAP message." }, { "code": null, "e": 12893, "s": 12802, "text": "For HTTP binding, a successful response is linked to the 200 to 299 range of status codes." }, { "code": null, "e": 12984, "s": 12893, "text": "For HTTP binding, a successful response is linked to the 200 to 299 range of status codes." }, { "code": null, "e": 13046, "s": 12984, "text": "SOAP Fault is linked to the 500 to 599 range of status codes." }, { "code": null, "e": 13108, "s": 13046, "text": "SOAP Fault is linked to the 500 to 599 range of status codes." }, { "code": null, "e": 13156, "s": 13108, "text": "The SOAP Fault has the following sub elements −" }, { "code": null, "e": 13168, "s": 13156, "text": "<faultCode>" }, { "code": null, "e": 13282, "s": 13168, "text": "It is a text code used to indicate a class of errors. See the next Table for a listing of predefined fault codes." }, { "code": null, "e": 13296, "s": 13282, "text": "<faultString>" }, { "code": null, "e": 13339, "s": 13296, "text": "It is a text message explaining the error." }, { "code": null, "e": 13352, "s": 13339, "text": "<faultActor>" }, { "code": null, "e": 13640, "s": 13352, "text": "It is a text string indicating who caused the fault. It is useful if the SOAP message travels through several nodes in the SOAP message path, and the client needs to know which node caused the error. A node that does not act as the ultimate destination must include a faultActor element." }, { "code": null, "e": 13649, "s": 13640, "text": "<detail>" }, { "code": null, "e": 13786, "s": 13649, "text": "It is an element used to carry application-specific error messages. The detail element can contain child elements called detail entries." }, { "code": null, "e": 13884, "s": 13786, "text": "The faultCode values defined below must be used in the faultcode element while describing faults." }, { "code": null, "e": 13909, "s": 13884, "text": "SOAP-ENV:VersionMismatch" }, { "code": null, "e": 13967, "s": 13909, "text": "Found an invalid namespace for the SOAP Envelope element." }, { "code": null, "e": 13991, "s": 13967, "text": "SOAP-ENV:MustUnderstand" }, { "code": null, "e": 14107, "s": 13991, "text": "An immediate child element of the Header element, with the mustUnderstand attribute set to \"1\", was not understood." }, { "code": null, "e": 14123, "s": 14107, "text": "SOAP-ENV:Client" }, { "code": null, "e": 14194, "s": 14123, "text": "The message was incorrectly formed or contained incorrect information." }, { "code": null, "e": 14210, "s": 14194, "text": "SOAP-ENV:Server" }, { "code": null, "e": 14281, "s": 14210, "text": "There was a problem with the server, so the message could not proceed." }, { "code": null, "e": 14520, "s": 14281, "text": "The following code is a sample Fault. The client has requested a method named ValidateCreditCard, but the service does not support such a method. This represents a client request error, and the server returns the following SOAP response −" }, { "code": null, "e": 15182, "s": 14520, "text": "<?xml version = '1.0' encoding = 'UTF-8'?>\n<SOAP-ENV:Envelope\n xmlns:SOAP-ENV = \"http://schemas.xmlsoap.org/soap/envelope/\"\n xmlns:xsi = \"http://www.w3.org/1999/XMLSchema-instance\"\n xmlns:xsd = \"http://www.w3.org/1999/XMLSchema\">\n\n <SOAP-ENV:Body>\n <SOAP-ENV:Fault>\n <faultcode xsi:type = \"xsd:string\">SOAP-ENV:Client</faultcode>\n <faultstring xsi:type = \"xsd:string\">\n Failed to locate method (ValidateCreditCard) in class (examplesCreditCard) at\n /usr/local/ActivePerl-5.6/lib/site_perl/5.6.0/SOAP/Lite.pm line 1555.\n </faultstring>\n </SOAP-ENV:Fault>\n </SOAP-ENV:Body>\n</SOAP-ENV:Envelope>" }, { "code": null, "e": 15352, "s": 15182, "text": "SOAP includes a built-in set of rules for encoding data types. It enables the SOAP message to indicate specific data types, such as integers, floats, doubles, or arrays." }, { "code": null, "e": 15441, "s": 15352, "text": "SOAP data types are divided into two broad categories − scalar types and compound types." }, { "code": null, "e": 15530, "s": 15441, "text": "SOAP data types are divided into two broad categories − scalar types and compound types." }, { "code": null, "e": 15621, "s": 15530, "text": "Scalar types contain exactly one value such as a last name, price, or product description." }, { "code": null, "e": 15712, "s": 15621, "text": "Scalar types contain exactly one value such as a last name, price, or product description." }, { "code": null, "e": 15803, "s": 15712, "text": "Compound types contain multiple values such as a purchase order or a list of stock quotes." }, { "code": null, "e": 15894, "s": 15803, "text": "Compound types contain multiple values such as a purchase order or a list of stock quotes." }, { "code": null, "e": 15957, "s": 15894, "text": "Compound types are further subdivided into arrays and structs." }, { "code": null, "e": 16020, "s": 15957, "text": "Compound types are further subdivided into arrays and structs." }, { "code": null, "e": 16107, "s": 16020, "text": "The encoding style for a SOAP message is set via the SOAP-ENV:encodingStyle attribute." }, { "code": null, "e": 16194, "s": 16107, "text": "The encoding style for a SOAP message is set via the SOAP-ENV:encodingStyle attribute." }, { "code": null, "e": 16276, "s": 16194, "text": "To use SOAP 1.1 encoding, use the value http://schemas.xmlsoap.org/soap/encoding/" }, { "code": null, "e": 16358, "s": 16276, "text": "To use SOAP 1.1 encoding, use the value http://schemas.xmlsoap.org/soap/encoding/" }, { "code": null, "e": 16438, "s": 16358, "text": "To use SOAP 1.2 encoding, use the value http://www.w3.org/2001/12/soap-encoding" }, { "code": null, "e": 16518, "s": 16438, "text": "To use SOAP 1.2 encoding, use the value http://www.w3.org/2001/12/soap-encoding" }, { "code": null, "e": 16725, "s": 16518, "text": "Latest SOAP specification adopts all the built-in types defined by XML Schema. Still, SOAP maintains its own convention for defining constructs not standardized by XML Schema, such as arrays and references." }, { "code": null, "e": 16932, "s": 16725, "text": "Latest SOAP specification adopts all the built-in types defined by XML Schema. Still, SOAP maintains its own convention for defining constructs not standardized by XML Schema, such as arrays and references." }, { "code": null, "e": 17089, "s": 16932, "text": "For scalar types, SOAP adopts all the built-in simple types specified by the XML Schema specification. This includes strings, floats, doubles, and integers." }, { "code": null, "e": 17235, "s": 17089, "text": "The following table lists the main simple types, excerpted from the XML Schema Part 0 − Primer http://www.w3.org/TR/2000/WD-xmlschema-0-20000407/" }, { "code": null, "e": 17298, "s": 17235, "text": "For example, here is a SOAP response with a double data type −" }, { "code": null, "e": 17841, "s": 17298, "text": "<?xml version = '1.0' encoding = 'UTF-8'?>\n<SOAP-ENV:Envelope \n xmlns:SOAP-ENV = \"http://www.w3.org/2001/12/soap-envelope\"\n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\" \n xmlns:xsd = \"http://www.w3.org/2001/XMLSchema\">\n \n <SOAP-ENV:Body>\n <ns1:getPriceResponse \n xmlns:ns1 = \"urn:examples:priceservice\" \n SOAP-ENV:encodingStyle = \"http://www.w3.org/2001/12/soap-encoding\">\n <return xsi:type = \"xsd:double\">54.99</return>\n </ns1:getPriceResponse>\n </SOAP-ENV:Body>\n</SOAP-ENV:Envelope>" }, { "code": null, "e": 18074, "s": 17841, "text": "SOAP arrays have a very specific set of rules, which require that you specify both the element type and array size. SOAP also supports multidimensional arrays, but not all SOAP implementations support multidimensional functionality." }, { "code": null, "e": 18305, "s": 18074, "text": "To create an array, you must specify it as an xsi:type of array. The array must also include an arrayType attribute. This attribute is required to specify the data type for the contained elements and the dimension(s) of the array." }, { "code": null, "e": 18383, "s": 18305, "text": "For example, the following attribute specifies an array of 10 double values −" }, { "code": null, "e": 18413, "s": 18383, "text": "arrayType = \"xsd:double[10]\"\n" }, { "code": null, "e": 18497, "s": 18413, "text": "In contrast, the following attribute specifies a two-dimensional array of strings −" }, { "code": null, "e": 18528, "s": 18497, "text": "arrayType = \"xsd:string[5,5]\"\n" }, { "code": null, "e": 18592, "s": 18528, "text": "Here is a sample SOAP response with an array of double values −" }, { "code": null, "e": 19359, "s": 18592, "text": "<?xml version = '1.0' encoding = 'UTF-8'?>\n<SOAP-ENV:Envelope\n xmlns:SOAP-ENV = \"http://www.w3.org/2001/12/soap-envelope\" \n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\" \n xmlns:xsd = \"http://www.w3.org/2001/XMLSchema\">\n\n <SOAP-ENV:Body>\n <ns1:getPriceListResponse \n xmlns:ns1 = \"urn:examples:pricelistservice\" \n SOAP-ENV:encodingStyle = \"http://www.w3.org/2001/12/soap-encoding\">\n\n <return xmlns:ns2 = \"http://www.w3.org/2001/09/soap-encoding\" \n xsi:type = \"ns2:Array\" ns2:arrayType = \"xsd:double[2]\">\n <item xsi:type = \"xsd:double\">54.99</item>\n <item xsi:type = \"xsd:double\">19.99</item>\n </return>\n </ns1:getPriceListResponse>\n </SOAP-ENV:Body>\n</SOAP-ENV:Envelope>" }, { "code": null, "e": 19669, "s": 19359, "text": "Structs contain multiple values, but each element is specified with a unique accessor element. For example, consider an item within a product catalog. In this case, the struct might contain a product SKU, product name, description, and price. Here is how such a struct would be represented in a SOAP message −" }, { "code": null, "e": 20547, "s": 19669, "text": "<?xml version = '1.0' encoding = 'UTF-8'?>\n<SOAP-ENV:Envelope \n xmlns:SOAP-ENV = \"http://www.w3.org/2001/12/soap-envelope\"\n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\" \n xmlns:xsd = \"http://www.w3.org/2001/XMLSchema\">\n\n <SOAP-ENV:Body>\n <ns1:getProductResponse\n xmlns:ns1 = \"urn:examples:productservice\" \n SOAP-ENV:encodingStyle = \"http://www.w3.org/2001/12/soap-encoding\">\n\t\t\n <return xmlns:ns2 = \"urn:examples\" xsi:type = \"ns2:product\">\n <name xsi:type = \"xsd:string\">Red Hat Linux</name>\n <price xsi:type = \"xsd:double\">54.99</price>\n <description xsi:type = \"xsd:string\">\n Red Hat Linux Operating System\n </description>\n <SKU xsi:type = \"xsd:string\">A358185</SKU>\n </return>\n </ns1:getProductResponse>\n </SOAP-ENV:Body>\n</SOAP-ENV:Envelope>" }, { "code": null, "e": 20915, "s": 20547, "text": "NOTE − Please take care of proper indentation while you write your SOAP code. Each element in a struct is specified with a unique accessor name. For example, the message above includes four accessor elements − name, price, description, and SKU. Each element can have its own data type. For example, name is specified as a string, whereas price is specified as double." }, { "code": null, "e": 21051, "s": 20915, "text": "SOAP is not tied to any transport protocol. SOAP can be transported via SMTP, FTP, IBM's MQSeries, or Microsoft Message Queuing (MSMQ)." }, { "code": null, "e": 21156, "s": 21051, "text": "SOAP specification includes details on HTTP only. HTTP remains the most popular SOAP transport protocol." }, { "code": null, "e": 21392, "s": 21156, "text": "Quite logically, SOAP requests are sent via an HTTP request and SOAP responses are returned within the content of the HTTP response. While SOAP requests can be sent via an HTTP GET, the specification includes details on HTTP POST only." }, { "code": null, "e": 21491, "s": 21392, "text": "Additionally, both HTTP requests and responses are required to set their content type to text/xml." }, { "code": null, "e": 21667, "s": 21491, "text": "The SOAP specification mandates that the client must provide a SOAPAction header, but the actual value of the SOAPAction header is dependent on the SOAP server implementation." }, { "code": null, "e": 21810, "s": 21667, "text": "For example, to access the AltaVista BabelFish Translation service, hosted by XMethods, you must specify the following as a SOAPAction header." }, { "code": null, "e": 21843, "s": 21810, "text": "urn:xmethodsBabelFish#BabelFish\n" }, { "code": null, "e": 21981, "s": 21843, "text": "Even if the server does not require a full SOAPAction header, the client must specify an empty string (\"\") or a null value. For example −" }, { "code": null, "e": 22009, "s": 21981, "text": "SOAPAction: \"\"\nSOAPAction:\n" }, { "code": null, "e": 22096, "s": 22009, "text": "Here is a sample request sent via HTTP to the XMethods Babelfish Translation service −" }, { "code": null, "e": 22877, "s": 22096, "text": "POST /perl/soaplite.cgi HTTP/1.0\nHost: services.xmethods.com\nContent-Type: text/xml; charset = utf-8\nContent-Length: 538\nSOAPAction: \"urn:xmethodsBabelFish#BabelFish\"\n\n<?xml version = '1.0' encoding = 'UTF-8'?>\n<SOAP-ENV:Envelope \n xmlns:SOAP-ENV = \"http://schemas.xmlsoap.org/soap/envelope/\" \n xmlns:xsi = \"http://www.w3.org/1999/XMLSchema-instance\"\n xmlns:xsd = \"http://www.w3.org/1999/XMLSchema\">\n\n <SOAP-ENV:Body>\n <ns1:BabelFish\n xmlns:ns1 = \"urn:xmethodsBabelFish\"\n SOAP-ENV:encodingStyle = \"http://schemas.xmlsoap.org/soap/encoding/\">\n <translationmode xsi:type = \"xsd:string\">en_fr</translationmode>\n <sourcedata xsi:type = \"xsd:string\">Hello, world!</sourcedata>\n </ns1:BabelFish>\n </SOAP-ENV:Body>\n</SOAP-ENV:Envelope>" }, { "code": null, "e": 23056, "s": 22877, "text": "Note the content type and the SOAPAction header. Also note that the BabelFish method requires two String parameters. The translation mode en_fr translates from English to French." }, { "code": null, "e": 23093, "s": 23056, "text": "Here is the response from XMethods −" }, { "code": null, "e": 23933, "s": 23093, "text": "HTTP/1.1 200 OK\nDate: Sat, 09 Jun 2001 15:01:55 GMT\nServer: Apache/1.3.14 (Unix) tomcat/1.0 PHP/4.0.1pl2\nSOAPServer: SOAP::Lite/Perl/0.50\nCache-Control: s-maxage = 60, proxy-revalidate\nContent-Length: 539\nContent-Type: text/xml\n\n<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<SOAP-ENV:Envelope\n xmlns:SOAP-ENC = \"http://schemas.xmlsoap.org/soap/encoding/\"\n SOAP-ENV:encodingStyle = \"http://schemas.xmlsoap.org/soap/encoding/\"\n xmlns:xsi = \"http://www.w3.org/1999/XMLSchema-instance\"\n xmlns:SOAP-ENV = \"http://schemas.xmlsoap.org/soap/envelope/\"\n xmlns:xsd = \"http://www.w3.org/1999/XMLSchema\">\n \n <SOAP-ENV:Body>\n <namesp1:BabelFishResponse xmlns:namesp1 = \"urn:xmethodsBabelFish\">\n <return xsi:type = \"xsd:string\">Bonjour, monde!</return>\n </namesp1:BabelFishResponse>\n </SOAP-ENV:Body>\n</SOAP-ENV:Envelope>" }, { "code": null, "e": 24223, "s": 23933, "text": "SOAP responses delivered via HTTP are required to follow the same HTTP status codes. For example, a status code of 200 OK indicates a successful response. A status code of 500 Internal Server Error indicates that there is a server error and that the SOAP response includes a Fault element." }, { "code": null, "e": 24397, "s": 24223, "text": "In the example below, a GetQuotation request is sent to a SOAP Server over HTTP. The request has a QuotationName parameter, and a Quotation will be returned in the response." }, { "code": null, "e": 24480, "s": 24397, "text": "The namespace for the function is defined in http://www.xyz.org/quotation address." }, { "code": null, "e": 24507, "s": 24480, "text": "Here is the SOAP request −" }, { "code": null, "e": 24994, "s": 24507, "text": "POST /Quotation HTTP/1.0\nHost: www.xyz.org\nContent-Type: text/xml; charset = utf-8\nContent-Length: nnn\n\n<?xml version = \"1.0\"?>\n<SOAP-ENV:Envelope\n xmlns:SOAP-ENV = \"http://www.w3.org/2001/12/soap-envelope\"\n SOAP-ENV:encodingStyle = \"http://www.w3.org/2001/12/soap-encoding\">\n\n <SOAP-ENV:Body xmlns:m = \"http://www.xyz.org/quotations\">\n <m:GetQuotation>\n <m:QuotationsName>MiscroSoft</m:QuotationsName>\n </m:GetQuotation>\n </SOAP-ENV:Body>\n</SOAP-ENV:Envelope>" }, { "code": null, "e": 25037, "s": 24994, "text": "A corresponding SOAP response looks like −" }, { "code": null, "e": 25513, "s": 25037, "text": "HTTP/1.0 200 OK\nContent-Type: text/xml; charset = utf-8\nContent-Length: nnn\n\n<?xml version = \"1.0\"?>\n<SOAP-ENV:Envelope\n xmlns:SOAP-ENV = \"http://www.w3.org/2001/12/soap-envelope\"\n SOAP-ENV:encodingStyle = \"http://www.w3.org/2001/12/soap-encoding\">\n\n <SOAP-ENV:Body xmlns:m = \"http://www.xyz.org/quotation\">\n <m:GetQuotationResponse>\n <m:Quotation>Here is the quotation</m:Quotation>\n </m:GetQuotationResponse>\n </SOAP-ENV:Body>\n</SOAP-ENV:Envelope>" }, { "code": null, "e": 25718, "s": 25513, "text": "SOAP 1.1 was originally submitted to the W3C in May 2000. Official submitters included large companies such as Microsoft, IBM, and Ariba, and smaller companies such as UserLand Software and DevelopMentor." }, { "code": null, "e": 25952, "s": 25718, "text": "In July 2001, the XML Protocol Working Group released a \"working draft\" of SOAP 1.2. Within the W3C, this document is officially a work in progress, meaning that the document is likely to be updated many times before it is finalized." }, { "code": null, "e": 26019, "s": 25952, "text": "SOAP Version 1.1 is available online at http://www.w3.org/TR/SOAP/" }, { "code": null, "e": 26102, "s": 26019, "text": "The working draft of SOAP Version 1.2 is available at http://www.w3.org/TR/soap12/" } ]
Python String replace() Method
Python string method replace() returns a copy of the string in which the occurrences of old have been replaced with new, optionally restricting the number of replacements to max. Following is the syntax for replace() method − str.replace(old, new[, max]) old − This is old substring to be replaced. old − This is old substring to be replaced. new − This is new substring, which would replace old substring. new − This is new substring, which would replace old substring. max − If this optional argument max is given, only the first count occurrences are replaced. max − If this optional argument max is given, only the first count occurrences are replaced. This method returns a copy of the string with all occurrences of substring old replaced by new. If the optional argument max is given, only the first count occurrences are replaced. The following example shows the usage of replace() method. #!/usr/bin/python str = "this is string example....wow!!! this is really string" print str.replace("is", "was") print str.replace("is", "was", 3) When we run above program, it produces following result − thwas was string example....wow!!! thwas was really string thwas was string example....wow!!! thwas is really string
[ { "code": null, "e": 2558, "s": 2378, "text": "Python string method replace() returns a copy of the string in which the occurrences of old have been replaced with new, optionally restricting the number of replacements to max." }, { "code": null, "e": 2605, "s": 2558, "text": "Following is the syntax for replace() method −" }, { "code": null, "e": 2635, "s": 2605, "text": "str.replace(old, new[, max])\n" }, { "code": null, "e": 2679, "s": 2635, "text": "old − This is old substring to be replaced." }, { "code": null, "e": 2723, "s": 2679, "text": "old − This is old substring to be replaced." }, { "code": null, "e": 2787, "s": 2723, "text": "new − This is new substring, which would replace old substring." }, { "code": null, "e": 2851, "s": 2787, "text": "new − This is new substring, which would replace old substring." }, { "code": null, "e": 2944, "s": 2851, "text": "max − If this optional argument max is given, only the first count occurrences are replaced." }, { "code": null, "e": 3037, "s": 2944, "text": "max − If this optional argument max is given, only the first count occurrences are replaced." }, { "code": null, "e": 3219, "s": 3037, "text": "This method returns a copy of the string with all occurrences of substring old replaced by new. If the optional argument max is given, only the first count occurrences are replaced." }, { "code": null, "e": 3278, "s": 3219, "text": "The following example shows the usage of replace() method." }, { "code": null, "e": 3425, "s": 3278, "text": "#!/usr/bin/python\n\nstr = \"this is string example....wow!!! this is really string\"\nprint str.replace(\"is\", \"was\")\nprint str.replace(\"is\", \"was\", 3)" }, { "code": null, "e": 3483, "s": 3425, "text": "When we run above program, it produces following result −" } ]
Export List to CSV or text File in R
16 May, 2021 In this article, we will discuss how to export a list to CSV and text file using R Programming language. Exporting to both of these types of files can be done using capture.output() function. This function is mainly used to evaluate its arguments with the output being returned as a character string or sent to a file. By just changing the file name in the parameter user and change the format of the file in which he/she want to export the list. Syntax: capture.output(..., file = NULL, append = FALSE, type = c(“output”, “message”), split = FALSE) Parameter: ...: Expressions to be evaluated. file: A file name or a connection, or NULL to return the output as a character vector. append: logical. If file a file name or unopened connection, append or overwrite? type, split: are passed to sink(), see there. Returns: This function will be return the file to user which is specified to the function as the parameter. In this approach user first need to create the list of any datatype and then need to call capture.output() function with the created list by the user and name of the file into which the user has to export the created list as the parameter of the function. For this simply pass the destination of the file to created along with its name. It will create a CSV file and add a list to it. Program: R gfg_list <- list(c("geeks"),c("for"), c("geeks")) capture.output(gfg_list, file = "gfg_list.csv") Output: For this simply pass the destination of the file to created along with its name. It will create a text file and add a list to it. Program: R gfg_list <- list(c("geeks"),c("for"), c("geeks")) capture.output(gfg_list, file = "gfg_list_txt.txt") Output: Picked R-CSV R-FileHandling R-List R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n16 May, 2021" }, { "code": null, "e": 475, "s": 28, "text": "In this article, we will discuss how to export a list to CSV and text file using R Programming language. Exporting to both of these types of files can be done using capture.output() function. This function is mainly used to evaluate its arguments with the output being returned as a character string or sent to a file. By just changing the file name in the parameter user and change the format of the file in which he/she want to export the list." }, { "code": null, "e": 578, "s": 475, "text": "Syntax: capture.output(..., file = NULL, append = FALSE, type = c(“output”, “message”), split = FALSE)" }, { "code": null, "e": 589, "s": 578, "text": "Parameter:" }, { "code": null, "e": 623, "s": 589, "text": "...: Expressions to be evaluated." }, { "code": null, "e": 710, "s": 623, "text": "file: A file name or a connection, or NULL to return the output as a character vector." }, { "code": null, "e": 792, "s": 710, "text": "append: logical. If file a file name or unopened connection, append or overwrite?" }, { "code": null, "e": 838, "s": 792, "text": "type, split: are passed to sink(), see there." }, { "code": null, "e": 946, "s": 838, "text": "Returns: This function will be return the file to user which is specified to the function as the parameter." }, { "code": null, "e": 1202, "s": 946, "text": "In this approach user first need to create the list of any datatype and then need to call capture.output() function with the created list by the user and name of the file into which the user has to export the created list as the parameter of the function." }, { "code": null, "e": 1331, "s": 1202, "text": "For this simply pass the destination of the file to created along with its name. It will create a CSV file and add a list to it." }, { "code": null, "e": 1340, "s": 1331, "text": "Program:" }, { "code": null, "e": 1342, "s": 1340, "text": "R" }, { "code": "gfg_list <- list(c(\"geeks\"),c(\"for\"), c(\"geeks\")) capture.output(gfg_list, file = \"gfg_list.csv\")", "e": 1441, "s": 1342, "text": null }, { "code": null, "e": 1449, "s": 1441, "text": "Output:" }, { "code": null, "e": 1579, "s": 1449, "text": "For this simply pass the destination of the file to created along with its name. It will create a text file and add a list to it." }, { "code": null, "e": 1588, "s": 1579, "text": "Program:" }, { "code": null, "e": 1590, "s": 1588, "text": "R" }, { "code": "gfg_list <- list(c(\"geeks\"),c(\"for\"), c(\"geeks\")) capture.output(gfg_list, file = \"gfg_list_txt.txt\")", "e": 1693, "s": 1590, "text": null }, { "code": null, "e": 1701, "s": 1693, "text": "Output:" }, { "code": null, "e": 1708, "s": 1701, "text": "Picked" }, { "code": null, "e": 1714, "s": 1708, "text": "R-CSV" }, { "code": null, "e": 1729, "s": 1714, "text": "R-FileHandling" }, { "code": null, "e": 1736, "s": 1729, "text": "R-List" }, { "code": null, "e": 1747, "s": 1736, "text": "R Language" } ]
How to Send Data From Activity to Fragment in Android?
15 Feb, 2022 Prerequisites: Introduction to Activities in Android Introduction to Fragments in Android In Android, a fragment is a portion of the user interface that can be used again and again. Fragment manages its own layout and has its own life cycle. Since fragment is a small portion of the bigger user interface, it can only be initialized inside an activity or another fragment. So if we wish to display any type of resources, such as a string, or an image inside the fragment, we will need to declare them in the activity and then pass it to the fragment. So in this article, we will show you how you can pass data from an Activity to the Fragment. Step 1: Create a New Project in Android Studio To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. We demonstrated the application in Kotlin, so make sure you select Kotlin as the primary language while creating a New Project. Step 2: Create a custom fragment layout (my_custom_fragment.xml) in the layout folder We shall pass a string to the fragment. To display this string, we implemented a TextView. XML <?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <!-- TextVIew to display the passed text --> <TextView android:id="@+id/fragmentTextView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:textColor="@color/white" android:textSize="50sp" android:background="#0f9d58"/> </LinearLayout> Step 3: Add EditText, Button, and Frame in the layout file (activity_main.xml) Refer to the comments inside the code for better understanding. XML <?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <!-- We will type text in this EditText --> <EditText android:id="@+id/editText" android:layout_width="match_parent" android:layout_height="50sp"/> <!-- Click this button to pass text in EditText to the Fragment --> <Button android:id="@+id/button" android:layout_below="@+id/editText" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:text="Pass"/> <!-- Text will be displayed in a TextView in this Fragment --> <FrameLayout android:id="@+id/frameLayout" android:layout_below="@+id/button" android:layout_width="match_parent" android:layout_height="match_parent"/> </RelativeLayout> Step 4: Create a class for the custom fragment (MyCustomFragment.kt) This is a custom fragment class to inflate the custom layout in the frame layout present in the main activity. Kotlin import android.os.Bundleimport android.view.LayoutInflaterimport android.view.Viewimport android.view.ViewGroupimport android.widget.TextViewimport androidx.fragment.app.Fragment class MyCustomFragment: Fragment() { // Declaring TextView from the custom fragment layout private lateinit var myTextView: TextView // Override function when the view is being created override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { // Inflates the custom fragment layout val view: View = inflater.inflate(R.layout.my_custom_fragment, container, false) // Finds the TextView in the custom fragment myTextView = view.findViewById<View>(R.id.fragmentTextView) as TextView // Gets the data from the passed bundle val bundle = arguments val message = bundle!!.getString("mText") // Sets the derived data (type String) in the TextView myTextView.text = message return view }} Step 5: Initialize MyCustomFragment class and pass the values from the EditText (MainActivity.kt) In this program, the EditText value (input string) is fetched on a button click. The custom fragment class is initialized and the input string is passed to get desired results. Please refer to the comments inside the code below for a better understanding. Kotlin import androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.widget.Buttonimport android.widget.EditText class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Declaring and initializing the EditText and Button from the layout val mEditText = findViewById<EditText>(R.id.editText) val mButton = findViewById<Button>(R.id.button) // Declaring fragment manager from making data // transactions using the custom fragment val mFragmentManager = supportFragmentManager val mFragmentTransaction = mFragmentManager.beginTransaction() val mFragment = MyCustomFragment() // On button click, a bundle is initialized and the // text from the EditText is passed in the custom // fragment using this bundle mButton.setOnClickListener { val mBundle = Bundle() mBundle.putString("mText",mEditText.text.toString()) mFragment.arguments = mBundle mFragmentTransaction.add(R.id.frameLayout, mFragment).commit() } }} Output: We can see that when the text is typed in the EditText and the button is clicked, the same text is displayed in our custom fragment. simmytarika5 Android Kotlin Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Add Views Dynamically and Store Data in Arraylist in Android? Android SDK and it's Components Flutter - Custom Bottom Navigation Bar How to Communicate Between Fragments in Android? Retrofit with Kotlin Coroutine in Android How to Add Views Dynamically and Store Data in Arraylist in Android? Android UI Layouts Kotlin Array How to Communicate Between Fragments in Android? Retrofit with Kotlin Coroutine in Android
[ { "code": null, "e": 28, "s": 0, "text": "\n15 Feb, 2022" }, { "code": null, "e": 43, "s": 28, "text": "Prerequisites:" }, { "code": null, "e": 81, "s": 43, "text": "Introduction to Activities in Android" }, { "code": null, "e": 118, "s": 81, "text": "Introduction to Fragments in Android" }, { "code": null, "e": 672, "s": 118, "text": "In Android, a fragment is a portion of the user interface that can be used again and again. Fragment manages its own layout and has its own life cycle. Since fragment is a small portion of the bigger user interface, it can only be initialized inside an activity or another fragment. So if we wish to display any type of resources, such as a string, or an image inside the fragment, we will need to declare them in the activity and then pass it to the fragment. So in this article, we will show you how you can pass data from an Activity to the Fragment." }, { "code": null, "e": 719, "s": 672, "text": "Step 1: Create a New Project in Android Studio" }, { "code": null, "e": 958, "s": 719, "text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. We demonstrated the application in Kotlin, so make sure you select Kotlin as the primary language while creating a New Project." }, { "code": null, "e": 1044, "s": 958, "text": "Step 2: Create a custom fragment layout (my_custom_fragment.xml) in the layout folder" }, { "code": null, "e": 1135, "s": 1044, "text": "We shall pass a string to the fragment. To display this string, we implemented a TextView." }, { "code": null, "e": 1139, "s": 1135, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:orientation=\"vertical\"> <!-- TextVIew to display the passed text --> <TextView android:id=\"@+id/fragmentTextView\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_gravity=\"center\" android:textColor=\"@color/white\" android:textSize=\"50sp\" android:background=\"#0f9d58\"/> </LinearLayout>", "e": 1725, "s": 1139, "text": null }, { "code": null, "e": 1804, "s": 1725, "text": "Step 3: Add EditText, Button, and Frame in the layout file (activity_main.xml)" }, { "code": null, "e": 1868, "s": 1804, "text": "Refer to the comments inside the code for better understanding." }, { "code": null, "e": 1872, "s": 1868, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <!-- We will type text in this EditText --> <EditText android:id=\"@+id/editText\" android:layout_width=\"match_parent\" android:layout_height=\"50sp\"/> <!-- Click this button to pass text in EditText to the Fragment --> <Button android:id=\"@+id/button\" android:layout_below=\"@+id/editText\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_centerHorizontal=\"true\" android:text=\"Pass\"/> <!-- Text will be displayed in a TextView in this Fragment --> <FrameLayout android:id=\"@+id/frameLayout\" android:layout_below=\"@+id/button\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\"/> </RelativeLayout>", "e": 2994, "s": 1872, "text": null }, { "code": null, "e": 3063, "s": 2994, "text": "Step 4: Create a class for the custom fragment (MyCustomFragment.kt)" }, { "code": null, "e": 3174, "s": 3063, "text": "This is a custom fragment class to inflate the custom layout in the frame layout present in the main activity." }, { "code": null, "e": 3181, "s": 3174, "text": "Kotlin" }, { "code": "import android.os.Bundleimport android.view.LayoutInflaterimport android.view.Viewimport android.view.ViewGroupimport android.widget.TextViewimport androidx.fragment.app.Fragment class MyCustomFragment: Fragment() { // Declaring TextView from the custom fragment layout private lateinit var myTextView: TextView // Override function when the view is being created override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { // Inflates the custom fragment layout val view: View = inflater.inflate(R.layout.my_custom_fragment, container, false) // Finds the TextView in the custom fragment myTextView = view.findViewById<View>(R.id.fragmentTextView) as TextView // Gets the data from the passed bundle val bundle = arguments val message = bundle!!.getString(\"mText\") // Sets the derived data (type String) in the TextView myTextView.text = message return view }}", "e": 4195, "s": 3181, "text": null }, { "code": null, "e": 4293, "s": 4195, "text": "Step 5: Initialize MyCustomFragment class and pass the values from the EditText (MainActivity.kt)" }, { "code": null, "e": 4549, "s": 4293, "text": "In this program, the EditText value (input string) is fetched on a button click. The custom fragment class is initialized and the input string is passed to get desired results. Please refer to the comments inside the code below for a better understanding." }, { "code": null, "e": 4556, "s": 4549, "text": "Kotlin" }, { "code": "import androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.widget.Buttonimport android.widget.EditText class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Declaring and initializing the EditText and Button from the layout val mEditText = findViewById<EditText>(R.id.editText) val mButton = findViewById<Button>(R.id.button) // Declaring fragment manager from making data // transactions using the custom fragment val mFragmentManager = supportFragmentManager val mFragmentTransaction = mFragmentManager.beginTransaction() val mFragment = MyCustomFragment() // On button click, a bundle is initialized and the // text from the EditText is passed in the custom // fragment using this bundle mButton.setOnClickListener { val mBundle = Bundle() mBundle.putString(\"mText\",mEditText.text.toString()) mFragment.arguments = mBundle mFragmentTransaction.add(R.id.frameLayout, mFragment).commit() } }}", "e": 5759, "s": 4556, "text": null }, { "code": null, "e": 5767, "s": 5759, "text": "Output:" }, { "code": null, "e": 5900, "s": 5767, "text": "We can see that when the text is typed in the EditText and the button is clicked, the same text is displayed in our custom fragment." }, { "code": null, "e": 5913, "s": 5900, "text": "simmytarika5" }, { "code": null, "e": 5921, "s": 5913, "text": "Android" }, { "code": null, "e": 5928, "s": 5921, "text": "Kotlin" }, { "code": null, "e": 5936, "s": 5928, "text": "Android" }, { "code": null, "e": 6034, "s": 5936, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6103, "s": 6034, "text": "How to Add Views Dynamically and Store Data in Arraylist in Android?" }, { "code": null, "e": 6135, "s": 6103, "text": "Android SDK and it's Components" }, { "code": null, "e": 6174, "s": 6135, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 6223, "s": 6174, "text": "How to Communicate Between Fragments in Android?" }, { "code": null, "e": 6265, "s": 6223, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 6334, "s": 6265, "text": "How to Add Views Dynamically and Store Data in Arraylist in Android?" }, { "code": null, "e": 6353, "s": 6334, "text": "Android UI Layouts" }, { "code": null, "e": 6366, "s": 6353, "text": "Kotlin Array" }, { "code": null, "e": 6415, "s": 6366, "text": "How to Communicate Between Fragments in Android?" } ]
Print all the prime numbers between ‘m’ and ‘n’ in PL/SQL
10 May, 2020 Prerequisite – PL/SQL Introduction In PL/SQL code groups of commands are arranged within a block. A block group related declarations or statements. In declare part, we declare variables and between begin and end part, we perform the operations. Problem :Write a script in PL/SQL to display all the prime numbers between any two positive whole numbers. Explanation :Here, all the prime numbers between any two numbers taken as input as the upper limit and the lower limit are returned.A prime number is a natural number greater than 1 that cannot be formed by multiplying two smaller natural numbers. In this implementation, the number of divisors of a number that occurs between the two limits is counted which should be 2 (1 and the number itself). If the number of divisors is 2, then that number is returned. For example, consider the number 5. It has only two divisors: 1 and the number 5 itself.Hence, it is a prime number. Examples : Input: 10 20 Output: 11 13 17 19 Input: 20 30 Output: 23 29 Below is the implementation : DECLARE--the upper limit and the lower limit are taken as user inputs. low number(2); high number(2); n number(2); m number(2); c number(20);BEGIN dbms_output.put_line('Enter the lower and higher limit:'); low:=&low; high:=&high;--The main operation happens in this loop for n IN low.. high loop c:=0; for m IN 1.. n loop if mod(n, m)=0 then c:=c+1; end if; end loop;--the number of divisors for each number in the range is counted and then checked. if c<=2 then dbms_output.put_line(n||'\n'); end if; end loop; END; Output : Input: Enter the lower and higher limit:1 10 Output: 2 3 5 7 DBMS SQL DBMS SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n10 May, 2020" }, { "code": null, "e": 63, "s": 28, "text": "Prerequisite – PL/SQL Introduction" }, { "code": null, "e": 273, "s": 63, "text": "In PL/SQL code groups of commands are arranged within a block. A block group related declarations or statements. In declare part, we declare variables and between begin and end part, we perform the operations." }, { "code": null, "e": 380, "s": 273, "text": "Problem :Write a script in PL/SQL to display all the prime numbers between any two positive whole numbers." }, { "code": null, "e": 628, "s": 380, "text": "Explanation :Here, all the prime numbers between any two numbers taken as input as the upper limit and the lower limit are returned.A prime number is a natural number greater than 1 that cannot be formed by multiplying two smaller natural numbers." }, { "code": null, "e": 840, "s": 628, "text": "In this implementation, the number of divisors of a number that occurs between the two limits is counted which should be 2 (1 and the number itself). If the number of divisors is 2, then that number is returned." }, { "code": null, "e": 957, "s": 840, "text": "For example, consider the number 5. It has only two divisors: 1 and the number 5 itself.Hence, it is a prime number." }, { "code": null, "e": 968, "s": 957, "text": "Examples :" }, { "code": null, "e": 1033, "s": 968, "text": "Input: 10 20\nOutput: 11 13 17 19\n\nInput: 20 30\nOutput: 23 29 " }, { "code": null, "e": 1063, "s": 1033, "text": "Below is the implementation :" }, { "code": " DECLARE--the upper limit and the lower limit are taken as user inputs. low number(2); high number(2); n number(2); m number(2); c number(20);BEGIN dbms_output.put_line('Enter the lower and higher limit:'); low:=&low; high:=&high;--The main operation happens in this loop for n IN low.. high loop c:=0; for m IN 1.. n loop if mod(n, m)=0 then c:=c+1; end if; end loop;--the number of divisors for each number in the range is counted and then checked. if c<=2 then dbms_output.put_line(n||'\\n'); end if; end loop; END;", "e": 1725, "s": 1063, "text": null }, { "code": null, "e": 1734, "s": 1725, "text": "Output :" }, { "code": null, "e": 1822, "s": 1734, "text": "Input: \nEnter the lower and higher limit:1 10\nOutput: 2\n 3\n 5\n 7 " }, { "code": null, "e": 1827, "s": 1822, "text": "DBMS" }, { "code": null, "e": 1831, "s": 1827, "text": "SQL" }, { "code": null, "e": 1836, "s": 1831, "text": "DBMS" }, { "code": null, "e": 1840, "s": 1836, "text": "SQL" } ]
volatile Keyword in Java
23 Jan, 2022 Using volatile is yet another way (like synchronized, atomic wrapper) of making class thread-safe. Thread-safe means that a method or class instance can be used by multiple threads at the same time without any problem. Consider the below example. class SharedObj { // Changes made to sharedVar in one thread // may not immediately reflect in other thread static int sharedVar = 6; } Suppose that two threads are working on SharedObj. If two threads run on different processors each thread may have its own local copy of sharedVariable. If one thread modifies its value the change might not reflect in the original one in the main memory instantly. This depends on the write policy of cache. Now the other thread is not aware of the modified value which leads to data inconsistency. The below diagram shows that if two threads are run on different processors, then the value of sharedVariable may be different in different threads. Note that writing of normal variables without any synchronization actions, might not be visible to any reading thread (this behavior is called sequential consistency). Although most modern hardware provides good cache coherence, therefore, most probably the changes in one cache are reflected in another but it’s not a good practice to rely on hardware to ‘fix’ a faulty application. class SharedObj { // volatile keyword here makes sure that // the changes made in one thread are // immediately reflect in other thread static volatile int sharedVar = 6; } Note that volatile should not be confused with the static modifier. static variables are class members that are shared among all objects. There is only one copy of them in the main memory. volatile vs synchronized: Before we move on let’s take a look at two important features of locks and synchronization. Mutual Exclusion: It means that only one thread or process can execute a block of code (critical section) at a time.Visibility: It means that changes made by one thread to shared data are visible to other threads. Mutual Exclusion: It means that only one thread or process can execute a block of code (critical section) at a time. Visibility: It means that changes made by one thread to shared data are visible to other threads. Java’s synchronized keyword guarantees both mutual exclusion and visibility. If we make the blocks of threads that modify the value of the shared variable synchronized only one thread can enter the block and changes made by it will be reflected in the main memory. All other threads trying to enter the block at the same time will be blocked and put to sleep. In some cases, we may only desire visibility and not atomicity. The use of synchronized in such a situation is overkill and may cause scalability problems. Here volatile comes to the rescue. Volatile variables have the visibility features of synchronized but not the atomicity features. The values of the volatile variable will never be cached and all writes and reads will be done to and from the main memory. However, the use of volatile is limited to a very restricted set of cases as most of the times atomicity is desired. For example, a simple increment statement such as x = x + 1; or x++ seems to be a single operation but is really a compound read-modify-write sequence of operations that must execute atomically. Java // Java Program to demonstrate the// use of Volatile Keyword in Java public class VolatileTest { private static final Logger LOGGER = MyLoggerFactory.getSimplestLogger(); private static volatile int MY_INT = 0; public static void main(String[] args) { new ChangeListener().start(); new ChangeMaker().start(); } static class ChangeListener extends Thread { @Override public void run() { int local_value = MY_INT; while (local_value < 5) { if (local_value != MY_INT) { LOGGER.log( Level.INFO, "Got Change for MY_INT : {0}", MY_INT); local_value = MY_INT; } } } } static class ChangeMaker extends Thread { @Override public void run() { int local_value = MY_INT; while (MY_INT < 5) { LOGGER.log(Level.INFO, "Incrementing MY_INT to {0}", local_value + 1); MY_INT = ++local_value; try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } } } }} Output (With the Volatile Keyword): Incrementing MY_INT to 1 Got Change for MY_INT : 1 Incrementing MY_INT to 2 Got Change for MY_INT : 2 Incrementing MY_INT to 3 Got Change for MY_INT : 3 Incrementing MY_INT to 4 Got Change for MY_INT : 4 Incrementing MY_INT to 5 Got Change for MY_INT : 5 Output (Without the Volatile Keyword) Incrementing MY_INT to 1 Incrementing MY_INT to 2 Incrementing MY_INT to 3 Incrementing MY_INT to 4 Incrementing MY_INT to 5 Volatile in Java is different from the “volatile” qualifier in C/C++. For Java, “volatile” tells the compiler that the value of a variable must never be cached as its value may change outside of the scope of the program itself. In C/C++, “volatile” is needed when developing embedded systems or device drivers, where you need to read or write a memory-mapped hardware device. The contents of a particular device register could change at any time, so you need the “volatile” keyword to ensure that such accesses aren’t optimized away by the compiler. This article is contributed by Sulabh Kumar. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above rajeev0719singh nishkarshgandhi Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n23 Jan, 2022" }, { "code": null, "e": 302, "s": 54, "text": "Using volatile is yet another way (like synchronized, atomic wrapper) of making class thread-safe. Thread-safe means that a method or class instance can be used by multiple threads at the same time without any problem. Consider the below example. " }, { "code": null, "e": 447, "s": 302, "text": "class SharedObj\n{\n // Changes made to sharedVar in one thread\n // may not immediately reflect in other thread\n static int sharedVar = 6;\n}" }, { "code": null, "e": 847, "s": 447, "text": "Suppose that two threads are working on SharedObj. If two threads run on different processors each thread may have its own local copy of sharedVariable. If one thread modifies its value the change might not reflect in the original one in the main memory instantly. This depends on the write policy of cache. Now the other thread is not aware of the modified value which leads to data inconsistency. " }, { "code": null, "e": 997, "s": 847, "text": "The below diagram shows that if two threads are run on different processors, then the value of sharedVariable may be different in different threads. " }, { "code": null, "e": 1382, "s": 997, "text": "Note that writing of normal variables without any synchronization actions, might not be visible to any reading thread (this behavior is called sequential consistency). Although most modern hardware provides good cache coherence, therefore, most probably the changes in one cache are reflected in another but it’s not a good practice to rely on hardware to ‘fix’ a faulty application. " }, { "code": null, "e": 1568, "s": 1382, "text": "class SharedObj\n{\n // volatile keyword here makes sure that\n // the changes made in one thread are \n // immediately reflect in other thread\n static volatile int sharedVar = 6;\n}" }, { "code": null, "e": 1758, "s": 1568, "text": "Note that volatile should not be confused with the static modifier. static variables are class members that are shared among all objects. There is only one copy of them in the main memory. " }, { "code": null, "e": 1877, "s": 1758, "text": "volatile vs synchronized: Before we move on let’s take a look at two important features of locks and synchronization. " }, { "code": null, "e": 2091, "s": 1877, "text": "Mutual Exclusion: It means that only one thread or process can execute a block of code (critical section) at a time.Visibility: It means that changes made by one thread to shared data are visible to other threads." }, { "code": null, "e": 2208, "s": 2091, "text": "Mutual Exclusion: It means that only one thread or process can execute a block of code (critical section) at a time." }, { "code": null, "e": 2306, "s": 2208, "text": "Visibility: It means that changes made by one thread to shared data are visible to other threads." }, { "code": null, "e": 2667, "s": 2306, "text": "Java’s synchronized keyword guarantees both mutual exclusion and visibility. If we make the blocks of threads that modify the value of the shared variable synchronized only one thread can enter the block and changes made by it will be reflected in the main memory. All other threads trying to enter the block at the same time will be blocked and put to sleep. " }, { "code": null, "e": 3391, "s": 2667, "text": "In some cases, we may only desire visibility and not atomicity. The use of synchronized in such a situation is overkill and may cause scalability problems. Here volatile comes to the rescue. Volatile variables have the visibility features of synchronized but not the atomicity features. The values of the volatile variable will never be cached and all writes and reads will be done to and from the main memory. However, the use of volatile is limited to a very restricted set of cases as most of the times atomicity is desired. For example, a simple increment statement such as x = x + 1; or x++ seems to be a single operation but is really a compound read-modify-write sequence of operations that must execute atomically. " }, { "code": null, "e": 3396, "s": 3391, "text": "Java" }, { "code": "// Java Program to demonstrate the// use of Volatile Keyword in Java public class VolatileTest { private static final Logger LOGGER = MyLoggerFactory.getSimplestLogger(); private static volatile int MY_INT = 0; public static void main(String[] args) { new ChangeListener().start(); new ChangeMaker().start(); } static class ChangeListener extends Thread { @Override public void run() { int local_value = MY_INT; while (local_value < 5) { if (local_value != MY_INT) { LOGGER.log( Level.INFO, \"Got Change for MY_INT : {0}\", MY_INT); local_value = MY_INT; } } } } static class ChangeMaker extends Thread { @Override public void run() { int local_value = MY_INT; while (MY_INT < 5) { LOGGER.log(Level.INFO, \"Incrementing MY_INT to {0}\", local_value + 1); MY_INT = ++local_value; try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } } } }}", "e": 4743, "s": 3396, "text": null }, { "code": null, "e": 4779, "s": 4743, "text": "Output (With the Volatile Keyword):" }, { "code": null, "e": 5034, "s": 4779, "text": "Incrementing MY_INT to 1\nGot Change for MY_INT : 1\nIncrementing MY_INT to 2\nGot Change for MY_INT : 2\nIncrementing MY_INT to 3\nGot Change for MY_INT : 3\nIncrementing MY_INT to 4\nGot Change for MY_INT : 4\nIncrementing MY_INT to 5\nGot Change for MY_INT : 5" }, { "code": null, "e": 5072, "s": 5034, "text": "Output (Without the Volatile Keyword)" }, { "code": null, "e": 5197, "s": 5072, "text": "Incrementing MY_INT to 1\nIncrementing MY_INT to 2\nIncrementing MY_INT to 3\nIncrementing MY_INT to 4\nIncrementing MY_INT to 5" }, { "code": null, "e": 5748, "s": 5197, "text": "Volatile in Java is different from the “volatile” qualifier in C/C++. For Java, “volatile” tells the compiler that the value of a variable must never be cached as its value may change outside of the scope of the program itself. In C/C++, “volatile” is needed when developing embedded systems or device drivers, where you need to read or write a memory-mapped hardware device. The contents of a particular device register could change at any time, so you need the “volatile” keyword to ensure that such accesses aren’t optimized away by the compiler. " }, { "code": null, "e": 5918, "s": 5748, "text": "This article is contributed by Sulabh Kumar. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 5934, "s": 5918, "text": "rajeev0719singh" }, { "code": null, "e": 5950, "s": 5934, "text": "nishkarshgandhi" }, { "code": null, "e": 5955, "s": 5950, "text": "Java" }, { "code": null, "e": 5960, "s": 5955, "text": "Java" } ]
EmberJS - Classes and Instances
Class is a template or blue print, that has a collection of variables and functions, where as instances are related to the object of that class. Creating and extending the Ember class on Ember.Object is the main property of the Ember object model. You can create new Ember class by using the Ember.Object's extend() method − const Demo = Ember.Object.extend ({ //code here }); The above code creates new Ember class called "Demo" which inherits the properties from initializers, computed properties, etc. After creating the class, you need to create instance of it by using the create() method as shown below − const state = Demo.create(); Using the above instance "state", access the properties by using the set and get accessor methods. console.log(state.get('stateOn')); You can change the "stateon" property by using the set method as shown below − state.set('stateOn', true); You can initialize the new instance by invoking the init() method. When declaring objects in the class, you need to initialize each instance with the init() method. The following example uses the above mentioned properties and displays an alert message when an Ember object is initialized − import Ember from 'ember'; //import ember module export default function() { //new ember object const Demo = Ember.Object.extend ({ init() { alert('The default property of stateOn is : ' + this.get('stateOn')); }, stateOn: false }); const state = Demo.create(); //new instance from object with create() method state.set('stateOn', true); console.log(state.get('stateOn')); } Now open the app.js file and add the following line on top of the file − import classinstance from './classinstance'; Where, classinstance is a name of the file specified as "classinstance.js" and created under the "app" folder. Now, call the inherited "classinstance" at the bottom, before the export. This executes the classinstance function which is created in the classinstance.js file − classinstance(); Run the ember server and you will receive the following output −
[ { "code": null, "e": 2280, "s": 2032, "text": "Class is a template or blue print, that has a collection of variables and functions, where as instances are related to the object of that class. Creating and extending the Ember class on Ember.Object is the main property of the Ember object model." }, { "code": null, "e": 2357, "s": 2280, "text": "You can create new Ember class by using the Ember.Object's extend() method −" }, { "code": null, "e": 2412, "s": 2357, "text": "const Demo = Ember.Object.extend ({\n //code here\n});" }, { "code": null, "e": 2646, "s": 2412, "text": "The above code creates new Ember class called \"Demo\" which inherits the properties from initializers, computed properties, etc. After creating the class, you need to create instance of it by using the create() method as shown below −" }, { "code": null, "e": 2676, "s": 2646, "text": "const state = Demo.create();\n" }, { "code": null, "e": 2775, "s": 2676, "text": "Using the above instance \"state\", access the properties by using the set and get accessor methods." }, { "code": null, "e": 2811, "s": 2775, "text": "console.log(state.get('stateOn'));\n" }, { "code": null, "e": 2890, "s": 2811, "text": "You can change the \"stateon\" property by using the set method as shown below −" }, { "code": null, "e": 2919, "s": 2890, "text": "state.set('stateOn', true);\n" }, { "code": null, "e": 3084, "s": 2919, "text": "You can initialize the new instance by invoking the init() method. When declaring objects in the class, you need to initialize each instance with the init() method." }, { "code": null, "e": 3210, "s": 3084, "text": "The following example uses the above mentioned properties and displays an alert message when an Ember object is initialized −" }, { "code": null, "e": 3639, "s": 3210, "text": "import Ember from 'ember'; //import ember module\nexport default function() {\n \n //new ember object\n const Demo = Ember.Object.extend ({\n init() {\n alert('The default property of stateOn is : ' + this.get('stateOn'));\n },\n stateOn: false\n });\n\n const state = Demo.create(); //new instance from object with create() method\n state.set('stateOn', true);\n console.log(state.get('stateOn'));\n}" }, { "code": null, "e": 3712, "s": 3639, "text": "Now open the app.js file and add the following line on top of the file −" }, { "code": null, "e": 3758, "s": 3712, "text": "import classinstance from './classinstance';\n" }, { "code": null, "e": 4032, "s": 3758, "text": "Where, classinstance is a name of the file specified as \"classinstance.js\" and created under the \"app\" folder. Now, call the inherited \"classinstance\" at the bottom, before the export. This executes the classinstance function which is created in the classinstance.js file −" }, { "code": null, "e": 4050, "s": 4032, "text": "classinstance();\n" } ]
How to make text input non-editable using CSS?
26 Feb, 2019 The read-only attribute in HTML is used to create a text input non-editable. But in case of CSS, the pointer-events property is used to stop the pointer events. Syntax: pointer-events: none; Example 1: This example shows two input text, in which one is non-editable. <!DOCTYPE html> <html> <head> <title> Disable Text Input field </title> <style> .inputClass { pointer-events: none; } </style> </head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> Non-editable:<input class="inputClass" name="input" value="GeeksForGeeks"> <br><br> Editable:<input class="inputClass2" name="input" value="GeeksForGeeks"> </body> </html> Output: Example 2: This example creates two input text, both of them are non-editable. <!DOCTYPE html> <html> <head> <title> Disable Text Input field </title> <style> .inputClass { pointer-events: none; } </style> </head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> Non-editable:<input class="inputClass" name="input" value="GeeksForGeeks"> <br><br> Non-Editable:<input class="inputClass" name="input" value="GeeksForGeeks"> </body></html> Output: CSS-Misc Picked Web-Programs CSS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Types of CSS (Cascading Style Sheet) Design a Tribute Page using HTML & CSS How to set space between the flexbox ? How to position a div at the bottom of its container using CSS? How to Upload Image into Database and Display it using PHP ? Installation of Node.js on Linux Difference between var, let and const keywords in JavaScript How to fetch data from an API in ReactJS ? Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array
[ { "code": null, "e": 28, "s": 0, "text": "\n26 Feb, 2019" }, { "code": null, "e": 189, "s": 28, "text": "The read-only attribute in HTML is used to create a text input non-editable. But in case of CSS, the pointer-events property is used to stop the pointer events." }, { "code": null, "e": 197, "s": 189, "text": "Syntax:" }, { "code": null, "e": 219, "s": 197, "text": "pointer-events: none;" }, { "code": null, "e": 295, "s": 219, "text": "Example 1: This example shows two input text, in which one is non-editable." }, { "code": "<!DOCTYPE html> <html> <head> <title> Disable Text Input field </title> <style> .inputClass { pointer-events: none; } </style> </head> <body style = \"text-align:center;\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> Non-editable:<input class=\"inputClass\" name=\"input\" value=\"GeeksForGeeks\"> <br><br> Editable:<input class=\"inputClass2\" name=\"input\" value=\"GeeksForGeeks\"> </body> </html> ", "e": 909, "s": 295, "text": null }, { "code": null, "e": 917, "s": 909, "text": "Output:" }, { "code": null, "e": 996, "s": 917, "text": "Example 2: This example creates two input text, both of them are non-editable." }, { "code": "<!DOCTYPE html> <html> <head> <title> Disable Text Input field </title> <style> .inputClass { pointer-events: none; } </style> </head> <body style = \"text-align:center;\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> Non-editable:<input class=\"inputClass\" name=\"input\" value=\"GeeksForGeeks\"> <br><br> Non-Editable:<input class=\"inputClass\" name=\"input\" value=\"GeeksForGeeks\"> </body></html>", "e": 1550, "s": 996, "text": null }, { "code": null, "e": 1558, "s": 1550, "text": "Output:" }, { "code": null, "e": 1567, "s": 1558, "text": "CSS-Misc" }, { "code": null, "e": 1574, "s": 1567, "text": "Picked" }, { "code": null, "e": 1587, "s": 1574, "text": "Web-Programs" }, { "code": null, "e": 1591, "s": 1587, "text": "CSS" }, { "code": null, "e": 1608, "s": 1591, "text": "Web Technologies" }, { "code": null, "e": 1706, "s": 1608, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1743, "s": 1706, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 1782, "s": 1743, "text": "Design a Tribute Page using HTML & CSS" }, { "code": null, "e": 1821, "s": 1782, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 1885, "s": 1821, "text": "How to position a div at the bottom of its container using CSS?" }, { "code": null, "e": 1946, "s": 1885, "text": "How to Upload Image into Database and Display it using PHP ?" }, { "code": null, "e": 1979, "s": 1946, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 2040, "s": 1979, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2083, "s": 2040, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 2155, "s": 2083, "text": "Differences between Functional Components and Class Components in React" } ]
How to use Table Component in ReactJS ? - GeeksforGeeks
05 Mar, 2021 Tables display sets of data. They can be fully customized. Material UI for React has this component available for us, and it is very easy to integrate. We can use the Table Component in ReactJS using the following approach. Creating React Application And Installing Module: Step 1: Create a React application using the following command. npx create-react-app foldername Step 2: After creating your project folder i.e. foldername, move to it using the following command. cd foldername Step 3: After creating the ReactJS application, Install the material-ui modules using the following command. npm install @material-ui/core Project Structure: It will look like the following. Project Structure Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code. App.js import React from "react";import TableContainer from "@material-ui/core/TableContainer";import Table from "@material-ui/core/Table";import TableBody from "@material-ui/core/TableBody";import TableRow from "@material-ui/core/TableRow";import Paper from "@material-ui/core/Paper";import TableHead from "@material-ui/core/TableHead";import TableCell from "@material-ui/core/TableCell"; function formatOurData(columnName, semOneMarks, semTwoMarks) { return { columnName, semOneMarks, semTwoMarks };} const SampleData = [ formatOurData("Maths", 55, 66), formatOurData("English", 44, 94), formatOurData("Hindi", 67, 85), formatOurData("Computer", 68, 95), formatOurData("Science", 56, 85),]; export default function App() { return ( <div style={{ display: "block", padding: 30 }}> <h4>How to use Table Component in ReactJS?</h4> <TableContainer component={Paper}> <Table style={{ width: 600, }} size="small" > <TableHead> <TableRow> <TableCell>Subject Name</TableCell> <TableCell align="right"> Sem-I Marks </TableCell> <TableCell align="right"> Sem-II Marks </TableCell> </TableRow> </TableHead> <TableBody> {SampleData.map((row) => ( <TableRow key={row.columnName}> <TableCell component="th" scope="row"> {row.columnName} </TableCell> <TableCell align="right"> {row.semOneMarks} </TableCell> <TableCell align="right"> {row.semTwoMarks} </TableCell> </TableRow> ))} </TableBody> </Table> </TableContainer> </div> );} Step to Run Application: Run the application using the following command from the root directory of the project. npm start Output: Now open your browser and go to http://localhost:3000/, you will see the following output. Reference: https://material-ui.com/components/tables/ Material-UI React-Questions ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to set background images in ReactJS ? How to create a table in ReactJS ? How to navigate on path by button click in react router ? How to create a multi-page website using React.js ? ReactJS useNavigate() Hook 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 insert spaces/tabs in text using HTML/CSS? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 24397, "s": 24369, "text": "\n05 Mar, 2021" }, { "code": null, "e": 24621, "s": 24397, "text": "Tables display sets of data. They can be fully customized. Material UI for React has this component available for us, and it is very easy to integrate. We can use the Table Component in ReactJS using the following approach." }, { "code": null, "e": 24671, "s": 24621, "text": "Creating React Application And Installing Module:" }, { "code": null, "e": 24735, "s": 24671, "text": "Step 1: Create a React application using the following command." }, { "code": null, "e": 24767, "s": 24735, "text": "npx create-react-app foldername" }, { "code": null, "e": 24867, "s": 24767, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command." }, { "code": null, "e": 24881, "s": 24867, "text": "cd foldername" }, { "code": null, "e": 24990, "s": 24881, "text": "Step 3: After creating the ReactJS application, Install the material-ui modules using the following command." }, { "code": null, "e": 25020, "s": 24990, "text": "npm install @material-ui/core" }, { "code": null, "e": 25072, "s": 25020, "text": "Project Structure: It will look like the following." }, { "code": null, "e": 25090, "s": 25072, "text": "Project Structure" }, { "code": null, "e": 25220, "s": 25090, "text": "Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code." }, { "code": null, "e": 25227, "s": 25220, "text": "App.js" }, { "code": "import React from \"react\";import TableContainer from \"@material-ui/core/TableContainer\";import Table from \"@material-ui/core/Table\";import TableBody from \"@material-ui/core/TableBody\";import TableRow from \"@material-ui/core/TableRow\";import Paper from \"@material-ui/core/Paper\";import TableHead from \"@material-ui/core/TableHead\";import TableCell from \"@material-ui/core/TableCell\"; function formatOurData(columnName, semOneMarks, semTwoMarks) { return { columnName, semOneMarks, semTwoMarks };} const SampleData = [ formatOurData(\"Maths\", 55, 66), formatOurData(\"English\", 44, 94), formatOurData(\"Hindi\", 67, 85), formatOurData(\"Computer\", 68, 95), formatOurData(\"Science\", 56, 85),]; export default function App() { return ( <div style={{ display: \"block\", padding: 30 }}> <h4>How to use Table Component in ReactJS?</h4> <TableContainer component={Paper}> <Table style={{ width: 600, }} size=\"small\" > <TableHead> <TableRow> <TableCell>Subject Name</TableCell> <TableCell align=\"right\"> Sem-I Marks </TableCell> <TableCell align=\"right\"> Sem-II Marks </TableCell> </TableRow> </TableHead> <TableBody> {SampleData.map((row) => ( <TableRow key={row.columnName}> <TableCell component=\"th\" scope=\"row\"> {row.columnName} </TableCell> <TableCell align=\"right\"> {row.semOneMarks} </TableCell> <TableCell align=\"right\"> {row.semTwoMarks} </TableCell> </TableRow> ))} </TableBody> </Table> </TableContainer> </div> );}", "e": 27080, "s": 25227, "text": null }, { "code": null, "e": 27193, "s": 27080, "text": "Step to Run Application: Run the application using the following command from the root directory of the project." }, { "code": null, "e": 27203, "s": 27193, "text": "npm start" }, { "code": null, "e": 27302, "s": 27203, "text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output." }, { "code": null, "e": 27356, "s": 27302, "text": "Reference: https://material-ui.com/components/tables/" }, { "code": null, "e": 27368, "s": 27356, "text": "Material-UI" }, { "code": null, "e": 27384, "s": 27368, "text": "React-Questions" }, { "code": null, "e": 27392, "s": 27384, "text": "ReactJS" }, { "code": null, "e": 27409, "s": 27392, "text": "Web Technologies" }, { "code": null, "e": 27507, "s": 27409, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27516, "s": 27507, "text": "Comments" }, { "code": null, "e": 27529, "s": 27516, "text": "Old Comments" }, { "code": null, "e": 27571, "s": 27529, "text": "How to set background images in ReactJS ?" }, { "code": null, "e": 27606, "s": 27571, "text": "How to create a table in ReactJS ?" }, { "code": null, "e": 27664, "s": 27606, "text": "How to navigate on path by button click in react router ?" }, { "code": null, "e": 27716, "s": 27664, "text": "How to create a multi-page website using React.js ?" }, { "code": null, "e": 27743, "s": 27716, "text": "ReactJS useNavigate() Hook" }, { "code": null, "e": 27799, "s": 27743, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 27832, "s": 27799, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 27894, "s": 27832, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 27944, "s": 27894, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
What is routing? Explain how it works in ASP.NET Core
In the context of web application frameworks, routing matches an incoming HTTP request to executable code. The executable code works as an endpoint that handles the request and returns a response. ASP.NET Core defines and configures the endpoints when the application starts. Routing also handles extracting the values from the request, building appropriate objects, and passing them to the methods that handle the request. Routing has been an important part of ASP.NET Core from the beginning. However, ASP.NET Core 3.0 introduced a new routing system called endpoint routing. It decouples routing from the MVC framework and makes it a more fundamental feature of ASP.NET Core. You can still use it to configure MVC routes, but in addition, the new routing system allows you to configure the routing using: Controllers Controllers Razor Pages Razor Pages SignalR SignalR gRPC Services gRPC Services Delegates and lambdas Delegates and lambdas You can also use routing in ASP.NET Core to map requests with multiple URLs to the same controllers or Razor Pages. When you generate a new ASP.NET Core application using the templates, it includes routing in the generated code. You register routing in the middleware pipeline, which is defined in the Configure() method on the Startup class. In the example below, the bolded code configures the routing for your application. public void Configure(IApplicationBuilder app, IWebHostEnvironment env){ if (env.IsDevelopment()){ app.UseDeveloperExceptionPage(); }else{ app.UseExceptionHandler("/Error"); // The default HSTS value is 30 days. You may want to change this for production app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints =>{ endpoints.MapRazorPages(); }); } UseRouting() method adds route matching to the middleware pipeline, which selects the best match for the request after inspecting the defined endpoints. UseRouting() method adds route matching to the middleware pipeline, which selects the best match for the request after inspecting the defined endpoints. UseEndPoints() adds endpoint execution to the middleware pipeline. UseEndPoints() adds endpoint execution to the middleware pipeline. You can configure routing using two different ways: Convention-based routing Convention-based routing Attribute-based routing Attribute-based routing Which routing strategy you choose depends upon which type of web application you are building, i.e., MVC or Razor Pages, and whether you are building an API or a web application with the user interface. Convention-based routing applies globally for your application, i.e., all the MVC controllers or Razor Pages can use it. You define your controllers, methods, or Razor Pages using well-defined ASP.NET Core conventions to map the requests to endpoints. Though this approach works well for most cases, it makes it challenging to create custom routes and endpoints. Using attribute-based routing, you can use the C# attributes such as [Route] on the controllers to map a given URL to a specific endpoint. Attribute-based routing provides more flexibility in terms of giving custom names to the routes and matching a request to the endpoints. You can explicitly define what the URL for each endpoint should be. Though it can be verbose, the additional flexibility can prove useful.
[ { "code": null, "e": 1259, "s": 1062, "text": "In the context of web application frameworks, routing matches an incoming HTTP request to executable code. The executable code works as an endpoint that handles the request and returns a response." }, { "code": null, "e": 1486, "s": 1259, "text": "ASP.NET Core defines and configures the endpoints when the application starts. Routing also handles extracting the values from the request, building appropriate objects, and passing them to the methods that handle the request." }, { "code": null, "e": 1870, "s": 1486, "text": "Routing has been an important part of ASP.NET Core from the beginning. However, ASP.NET Core 3.0 introduced a new routing system called endpoint routing. It decouples routing from the MVC framework and makes it a more fundamental feature of ASP.NET Core. You can still use it to configure MVC routes, but in addition, the new routing system allows you to configure the routing using:" }, { "code": null, "e": 1882, "s": 1870, "text": "Controllers" }, { "code": null, "e": 1894, "s": 1882, "text": "Controllers" }, { "code": null, "e": 1906, "s": 1894, "text": "Razor Pages" }, { "code": null, "e": 1918, "s": 1906, "text": "Razor Pages" }, { "code": null, "e": 1926, "s": 1918, "text": "SignalR" }, { "code": null, "e": 1934, "s": 1926, "text": "SignalR" }, { "code": null, "e": 1948, "s": 1934, "text": "gRPC Services" }, { "code": null, "e": 1962, "s": 1948, "text": "gRPC Services" }, { "code": null, "e": 1984, "s": 1962, "text": "Delegates and lambdas" }, { "code": null, "e": 2006, "s": 1984, "text": "Delegates and lambdas" }, { "code": null, "e": 2122, "s": 2006, "text": "You can also use routing in ASP.NET Core to map requests with multiple URLs to the same controllers or Razor Pages." }, { "code": null, "e": 2432, "s": 2122, "text": "When you generate a new ASP.NET Core application using the templates, it includes routing in the generated code. You register routing in the middleware pipeline, which is defined in the Configure() method on the Startup class. In the example below, the bolded code configures the routing for your application." }, { "code": null, "e": 2916, "s": 2432, "text": "public void Configure(IApplicationBuilder app, IWebHostEnvironment env){\n if (env.IsDevelopment()){\n app.UseDeveloperExceptionPage();\n }else{\n app.UseExceptionHandler(\"/Error\");\n // The default HSTS value is 30 days. You may want to change this for production\n app.UseHsts();\n }\n app.UseHttpsRedirection();\n app.UseStaticFiles();\n app.UseRouting();\n app.UseAuthorization();\n app.UseEndpoints(endpoints =>{\n endpoints.MapRazorPages();\n });\n}" }, { "code": null, "e": 3069, "s": 2916, "text": "UseRouting() method adds route matching to the middleware pipeline, which selects the best match for the request after inspecting the defined endpoints." }, { "code": null, "e": 3222, "s": 3069, "text": "UseRouting() method adds route matching to the middleware pipeline, which selects the best match for the request after inspecting the defined endpoints." }, { "code": null, "e": 3289, "s": 3222, "text": "UseEndPoints() adds endpoint execution to the middleware pipeline." }, { "code": null, "e": 3356, "s": 3289, "text": "UseEndPoints() adds endpoint execution to the middleware pipeline." }, { "code": null, "e": 3408, "s": 3356, "text": "You can configure routing using two different ways:" }, { "code": null, "e": 3433, "s": 3408, "text": "Convention-based routing" }, { "code": null, "e": 3458, "s": 3433, "text": "Convention-based routing" }, { "code": null, "e": 3482, "s": 3458, "text": "Attribute-based routing" }, { "code": null, "e": 3506, "s": 3482, "text": "Attribute-based routing" }, { "code": null, "e": 3709, "s": 3506, "text": "Which routing strategy you choose depends upon which type of web application you are building, i.e., MVC or Razor Pages, and whether you are building an API or a web application with the user interface." }, { "code": null, "e": 4072, "s": 3709, "text": "Convention-based routing applies globally for your application, i.e., all the MVC controllers or Razor Pages can use it. You define your controllers, methods, or Razor Pages using well-defined ASP.NET Core conventions to map the requests to endpoints. Though this approach works well for most cases, it makes it challenging to create custom routes and endpoints." }, { "code": null, "e": 4487, "s": 4072, "text": "Using attribute-based routing, you can use the C# attributes such as [Route] on the controllers to map a given URL to a specific endpoint. Attribute-based routing provides more flexibility in terms of giving custom names to the routes and matching a request to the endpoints. You can explicitly define what the URL for each endpoint should be. Though it can be verbose, the additional flexibility can prove useful." } ]
printf() function in PHP
The printf() function output a formatted string. It returns the length of the outputted string. printf (format, argument1, argument2, ... ) format − Specifies the string and how to format the variables in it. format − Specifies the string and how to format the variables in it. The following are the possible format values −%% - Returns a percent sign%b - Binary number%c - The character according to the ASCII value%d - Signed decimal number (negative, zero or positive)%e - Scientific notation using a lowercase (e.g. 1.2e+2)%E - Scientific notation using a uppercase (e.g. 1.2E+2)%u - Unsigned decimal number (equal to or greather than zero)%f - Floating-point number (local settings aware)%F - Floating-point number (not local settings aware)%g - shorter of %e and %f%G - shorter of %E and %f%o - Octal number%s - String%x - Hexadecimal number (lowercase letters)%X - Hexadecimal number (uppercase letters) The following are the possible format values − %% - Returns a percent sign %% - Returns a percent sign %b - Binary number %b - Binary number %c - The character according to the ASCII value %c - The character according to the ASCII value %d - Signed decimal number (negative, zero or positive) %d - Signed decimal number (negative, zero or positive) %e - Scientific notation using a lowercase (e.g. 1.2e+2) %e - Scientific notation using a lowercase (e.g. 1.2e+2) %E - Scientific notation using a uppercase (e.g. 1.2E+2) %E - Scientific notation using a uppercase (e.g. 1.2E+2) %u - Unsigned decimal number (equal to or greather than zero) %u - Unsigned decimal number (equal to or greather than zero) %f - Floating-point number (local settings aware) %f - Floating-point number (local settings aware) %F - Floating-point number (not local settings aware) %F - Floating-point number (not local settings aware) %g - shorter of %e and %f %g - shorter of %e and %f %G - shorter of %E and %f %G - shorter of %E and %f %o - Octal number %o - Octal number %s - String %s - String %x - Hexadecimal number (lowercase letters) %x - Hexadecimal number (lowercase letters) %X - Hexadecimal number (uppercase letters) %X - Hexadecimal number (uppercase letters) argument1 − The argument to be inserted at the first %-sign in the format string. argument1 − The argument to be inserted at the first %-sign in the format string. argument2 − The argument to be inserted at the second %-sign in the format string. argument2 − The argument to be inserted at the second %-sign in the format string. The printf() function returns the length of the outputted string. The following is an example − Live Demo <?php $val = 2976; printf("%f",$val); ?> The following is the output − 2976.000000 Let us see another example − Live Demo <?php $s = "Welcome"; printf("[%s]<b>",$s); ?> The following is the output − [Welcome]<br>
[ { "code": null, "e": 1158, "s": 1062, "text": "The printf() function output a formatted string. It returns the length of the outputted string." }, { "code": null, "e": 1202, "s": 1158, "text": "printf (format, argument1, argument2, ... )" }, { "code": null, "e": 1271, "s": 1202, "text": "format − Specifies the string and how to format the variables in it." }, { "code": null, "e": 1340, "s": 1271, "text": "format − Specifies the string and how to format the variables in it." }, { "code": null, "e": 1973, "s": 1340, "text": "The following are the possible format values −%% - Returns a percent sign%b - Binary number%c - The character according to the ASCII value%d - Signed decimal number (negative, zero or positive)%e - Scientific notation using a lowercase (e.g. 1.2e+2)%E - Scientific notation using a uppercase (e.g. 1.2E+2)%u - Unsigned decimal number (equal to or greather than zero)%f - Floating-point number (local settings aware)%F - Floating-point number (not local settings aware)%g - shorter of %e and %f%G - shorter of %E and %f%o - Octal number%s - String%x - Hexadecimal number (lowercase letters)%X - Hexadecimal number (uppercase letters)" }, { "code": null, "e": 2020, "s": 1973, "text": "The following are the possible format values −" }, { "code": null, "e": 2048, "s": 2020, "text": "%% - Returns a percent sign" }, { "code": null, "e": 2076, "s": 2048, "text": "%% - Returns a percent sign" }, { "code": null, "e": 2095, "s": 2076, "text": "%b - Binary number" }, { "code": null, "e": 2114, "s": 2095, "text": "%b - Binary number" }, { "code": null, "e": 2162, "s": 2114, "text": "%c - The character according to the ASCII value" }, { "code": null, "e": 2210, "s": 2162, "text": "%c - The character according to the ASCII value" }, { "code": null, "e": 2266, "s": 2210, "text": "%d - Signed decimal number (negative, zero or positive)" }, { "code": null, "e": 2322, "s": 2266, "text": "%d - Signed decimal number (negative, zero or positive)" }, { "code": null, "e": 2379, "s": 2322, "text": "%e - Scientific notation using a lowercase (e.g. 1.2e+2)" }, { "code": null, "e": 2436, "s": 2379, "text": "%e - Scientific notation using a lowercase (e.g. 1.2e+2)" }, { "code": null, "e": 2493, "s": 2436, "text": "%E - Scientific notation using a uppercase (e.g. 1.2E+2)" }, { "code": null, "e": 2550, "s": 2493, "text": "%E - Scientific notation using a uppercase (e.g. 1.2E+2)" }, { "code": null, "e": 2612, "s": 2550, "text": "%u - Unsigned decimal number (equal to or greather than zero)" }, { "code": null, "e": 2674, "s": 2612, "text": "%u - Unsigned decimal number (equal to or greather than zero)" }, { "code": null, "e": 2724, "s": 2674, "text": "%f - Floating-point number (local settings aware)" }, { "code": null, "e": 2774, "s": 2724, "text": "%f - Floating-point number (local settings aware)" }, { "code": null, "e": 2828, "s": 2774, "text": "%F - Floating-point number (not local settings aware)" }, { "code": null, "e": 2882, "s": 2828, "text": "%F - Floating-point number (not local settings aware)" }, { "code": null, "e": 2908, "s": 2882, "text": "%g - shorter of %e and %f" }, { "code": null, "e": 2934, "s": 2908, "text": "%g - shorter of %e and %f" }, { "code": null, "e": 2960, "s": 2934, "text": "%G - shorter of %E and %f" }, { "code": null, "e": 2986, "s": 2960, "text": "%G - shorter of %E and %f" }, { "code": null, "e": 3004, "s": 2986, "text": "%o - Octal number" }, { "code": null, "e": 3022, "s": 3004, "text": "%o - Octal number" }, { "code": null, "e": 3034, "s": 3022, "text": "%s - String" }, { "code": null, "e": 3046, "s": 3034, "text": "%s - String" }, { "code": null, "e": 3090, "s": 3046, "text": "%x - Hexadecimal number (lowercase letters)" }, { "code": null, "e": 3134, "s": 3090, "text": "%x - Hexadecimal number (lowercase letters)" }, { "code": null, "e": 3178, "s": 3134, "text": "%X - Hexadecimal number (uppercase letters)" }, { "code": null, "e": 3222, "s": 3178, "text": "%X - Hexadecimal number (uppercase letters)" }, { "code": null, "e": 3304, "s": 3222, "text": "argument1 − The argument to be inserted at the first %-sign in the format string." }, { "code": null, "e": 3386, "s": 3304, "text": "argument1 − The argument to be inserted at the first %-sign in the format string." }, { "code": null, "e": 3469, "s": 3386, "text": "argument2 − The argument to be inserted at the second %-sign in the format string." }, { "code": null, "e": 3552, "s": 3469, "text": "argument2 − The argument to be inserted at the second %-sign in the format string." }, { "code": null, "e": 3618, "s": 3552, "text": "The printf() function returns the length of the outputted string." }, { "code": null, "e": 3648, "s": 3618, "text": "The following is an example −" }, { "code": null, "e": 3659, "s": 3648, "text": " Live Demo" }, { "code": null, "e": 3706, "s": 3659, "text": "<?php\n $val = 2976;\n printf(\"%f\",$val);\n?>" }, { "code": null, "e": 3736, "s": 3706, "text": "The following is the output −" }, { "code": null, "e": 3748, "s": 3736, "text": "2976.000000" }, { "code": null, "e": 3777, "s": 3748, "text": "Let us see another example −" }, { "code": null, "e": 3788, "s": 3777, "text": " Live Demo" }, { "code": null, "e": 3841, "s": 3788, "text": "<?php\n $s = \"Welcome\";\n printf(\"[%s]<b>\",$s);\n?>" }, { "code": null, "e": 3871, "s": 3841, "text": "The following is the output −" }, { "code": null, "e": 3885, "s": 3871, "text": "[Welcome]<br>" } ]
Big Data Analytics - Time Series Analysis
Time series is a sequence of observations of categorical or numeric variables indexed by a date, or timestamp. A clear example of time series data is the time series of a stock price. In the following table, we can see the basic structure of time series data. In this case the observations are recorded every hour. Normally, the first step in time series analysis is to plot the series, this is normally done with a line chart. The most common application of time series analysis is forecasting future values of a numeric value using the temporal structure of the data. This means, the available observations are used to predict values from the future. The temporal ordering of the data, implies that traditional regression methods are not useful. In order to build robust forecast, we need models that take into account the temporal ordering of the data. The most widely used model for Time Series Analysis is called Autoregressive Moving Average (ARMA). The model consists of two parts, an autoregressive (AR) part and a moving average (MA) part. The model is usually then referred to as the ARMA(p, q) model where p is the order of the autoregressive part and q is the order of the moving average part. The AR(p) is read as an autoregressive model of order p. Mathematically it is written as − Xt=c+∑i=1PφiXt−i+εt where {φ1, ..., φp} are parameters to be estimated, c is a constant, and the random variable εt represents the white noise. Some constraints are necessary on the values of the parameters so that the model remains stationary. The notation MA(q) refers to the moving average model of order q − Xt=μ+εt+∑i=1qθiεt−i where the θ1, ..., θq are the parameters of the model, μ is the expectation of Xt, and the εt, εt − 1, ... are, white noise error terms. The ARMA(p, q) model combines p autoregressive terms and q moving-average terms. Mathematically the model is expressed with the following formula − Xt=c+εt+∑i=1PφiXt−1+∑i=1qθiεt−i We can see that the ARMA(p, q) model is a combination of AR(p) and MA(q) models. To give some intuition of the model consider that the AR part of the equation seeks to estimate parameters for Xt − i observations of in order to predict the value of the variable in Xt. It is in the end a weighted average of the past values. The MA section uses the same approach but with the error of previous observations, εt − i. So in the end, the result of the model is a weighted average. The following code snippet demonstrates how to implement an ARMA(p, q) in R. # install.packages("forecast") library("forecast") # Read the data data = scan('fancy.dat') ts_data <- ts(data, frequency = 12, start = c(1987,1)) ts_data plot.ts(ts_data) Plotting the data is normally the first step to find out if there is a temporal structure in the data. We can see from the plot that there are strong spikes at the end of each year. The following code fits an ARMA model to the data. It runs several combinations of models and selects the one that has less error. # Fit the ARMA model fit = auto.arima(ts_data) summary(fit) # Series: ts_data # ARIMA(1,1,1)(0,1,1)[12] # Coefficients: # ar1 ma1 sma1 # 0.2401 -0.9013 0.7499 # s.e. 0.1427 0.0709 0.1790 # # sigma^2 estimated as 15464184: log likelihood = -693.69 # AIC = 1395.38 AICc = 1395.98 BIC = 1404.43 # Training set error measures: # ME RMSE MAE MPE MAPE MASE ACF1 # Training set 328.301 3615.374 2171.002 -2.481166 15.97302 0.4905797 -0.02521172 65 Lectures 6 hours Arnab Chakraborty 18 Lectures 1.5 hours Pranjal Srivastava, Harshit Srivastava 23 Lectures 2 hours John Shea 18 Lectures 1.5 hours Pranjal Srivastava 46 Lectures 3.5 hours Pranjal Srivastava 37 Lectures 3.5 hours Pranjal Srivastava, Harshit Srivastava Print Add Notes Bookmark this page
[ { "code": null, "e": 2869, "s": 2554, "text": "Time series is a sequence of observations of categorical or numeric variables indexed by a date, or timestamp. A clear example of time series data is the time series of a stock price. In the following table, we can see the basic structure of time series data. In this case the observations are recorded every hour." }, { "code": null, "e": 2982, "s": 2869, "text": "Normally, the first step in time series analysis is to plot the series, this is normally done with a line chart." }, { "code": null, "e": 3207, "s": 2982, "text": "The most common application of time series analysis is forecasting future values of a numeric value using the temporal structure of the data. This means, the available observations are used to predict values from the future." }, { "code": null, "e": 3410, "s": 3207, "text": "The temporal ordering of the data, implies that traditional regression methods are not useful. In order to build robust forecast, we need models that take into account the temporal ordering of the data." }, { "code": null, "e": 3760, "s": 3410, "text": "The most widely used model for Time Series Analysis is called Autoregressive Moving Average (ARMA). The model consists of two parts, an autoregressive (AR) part and a moving average (MA) part. The model is usually then referred to as the ARMA(p, q) model where p is the order of the autoregressive part and q is the order of the moving average part." }, { "code": null, "e": 3851, "s": 3760, "text": "The AR(p) is read as an autoregressive model of order p. Mathematically it is written as −" }, { "code": null, "e": 3871, "s": 3851, "text": "Xt=c+∑i=1PφiXt−i+εt" }, { "code": null, "e": 4096, "s": 3871, "text": "where {φ1, ..., φp} are parameters to be estimated, c is a constant, and the random variable εt represents the white noise. Some constraints are necessary on the values of the parameters so that the model remains stationary." }, { "code": null, "e": 4163, "s": 4096, "text": "The notation MA(q) refers to the moving average model of order q −" }, { "code": null, "e": 4183, "s": 4163, "text": "Xt=μ+εt+∑i=1qθiεt−i" }, { "code": null, "e": 4320, "s": 4183, "text": "where the θ1, ..., θq are the parameters of the model, μ is the expectation of Xt, and the εt, εt − 1, ... are, white noise error terms." }, { "code": null, "e": 4468, "s": 4320, "text": "The ARMA(p, q) model combines p autoregressive terms and q moving-average terms. Mathematically the model is expressed with the following formula −" }, { "code": null, "e": 4500, "s": 4468, "text": "Xt=c+εt+∑i=1PφiXt−1+∑i=1qθiεt−i" }, { "code": null, "e": 4581, "s": 4500, "text": "We can see that the ARMA(p, q) model is a combination of AR(p) and MA(q) models." }, { "code": null, "e": 4977, "s": 4581, "text": "To give some intuition of the model consider that the AR part of the equation seeks to estimate parameters for Xt − i observations of in order to predict the value of the variable in Xt. It is in the end a weighted average of the past values. The MA section uses the same approach but with the error of previous observations, εt − i. So in the end, the result of the model is a weighted average." }, { "code": null, "e": 5054, "s": 4977, "text": "The following code snippet demonstrates how to implement an ARMA(p, q) in R." }, { "code": null, "e": 5235, "s": 5054, "text": "# install.packages(\"forecast\")\nlibrary(\"forecast\") \n\n# Read the data \ndata = scan('fancy.dat') \nts_data <- ts(data, frequency = 12, start = c(1987,1)) \nts_data \nplot.ts(ts_data)\n" }, { "code": null, "e": 5417, "s": 5235, "text": "Plotting the data is normally the first step to find out if there is a temporal structure in the data. We can see from the plot that there are strong spikes at the end of each year." }, { "code": null, "e": 5548, "s": 5417, "text": "The following code fits an ARMA model to the data. It runs several combinations of models and selects the one that has less error." }, { "code": null, "e": 6109, "s": 5548, "text": "# Fit the ARMA model\nfit = auto.arima(ts_data) \nsummary(fit) \n\n# Series: ts_data \n# ARIMA(1,1,1)(0,1,1)[12] \n# Coefficients: \n# ar1 ma1 sma1 \n# 0.2401 -0.9013 0.7499 \n# s.e. 0.1427 0.0709 0.1790 \n\n# \n# sigma^2 estimated as 15464184: log likelihood = -693.69 \n# AIC = 1395.38 AICc = 1395.98 BIC = 1404.43 \n\n# Training set error measures: \n# ME RMSE MAE MPE MAPE MASE ACF1 \n# Training set 328.301 3615.374 2171.002 -2.481166 15.97302 0.4905797 -0.02521172\n" }, { "code": null, "e": 6142, "s": 6109, "text": "\n 65 Lectures \n 6 hours \n" }, { "code": null, "e": 6161, "s": 6142, "text": " Arnab Chakraborty" }, { "code": null, "e": 6196, "s": 6161, "text": "\n 18 Lectures \n 1.5 hours \n" }, { "code": null, "e": 6236, "s": 6196, "text": " Pranjal Srivastava, Harshit Srivastava" }, { "code": null, "e": 6269, "s": 6236, "text": "\n 23 Lectures \n 2 hours \n" }, { "code": null, "e": 6280, "s": 6269, "text": " John Shea" }, { "code": null, "e": 6315, "s": 6280, "text": "\n 18 Lectures \n 1.5 hours \n" }, { "code": null, "e": 6335, "s": 6315, "text": " Pranjal Srivastava" }, { "code": null, "e": 6370, "s": 6335, "text": "\n 46 Lectures \n 3.5 hours \n" }, { "code": null, "e": 6390, "s": 6370, "text": " Pranjal Srivastava" }, { "code": null, "e": 6425, "s": 6390, "text": "\n 37 Lectures \n 3.5 hours \n" }, { "code": null, "e": 6465, "s": 6425, "text": " Pranjal Srivastava, Harshit Srivastava" }, { "code": null, "e": 6472, "s": 6465, "text": " Print" }, { "code": null, "e": 6483, "s": 6472, "text": " Add Notes" } ]
Make array elements equal in Minimum Steps
13 Sep, 2021 Given an array of N elements where the first element is a non zero positive number M, and the rest N – 1 elements are 0, the task is to calculate the minimum number of steps required to make the entire array equal while abiding by the following rules:1. The ith element can be increased by one if and only if i-1th element is strictly greater than the ith element 2. If the ith element is being increased by one then the i+1th cannot be increased at the same time.(i.e consecutive elements cannot be increased at the same time) 3. Multiple elements can be incremented simultaneously in a single step.Examples: Input : N = 3, M = 4 Output : 8 Explanation: array is 4 0 0 In 4 steps element at index 1 is increased, so the array becomes {4, 4, 0}. In the next 4 steps the element at index 3 is increased so array becomes {4, 4, 4} Thus, 4 + 4 = 8 operations are required to make all the array elements equalInput : N = 4, M = 4 Output : 9 Explanation: The steps are shown in the flowchart given below Refer to the flowchart given below. Approach: To maximise the Number of Increments per Step, more number of Unbalances are created (array[i]>array[i+1]),Step 1, element 0 >element 1 so element 1 is incremented, Step 2, element 1> element 2 so element 2 is incremented by 1Step 3, element 0 > element 1 and element 2> element 3 so element 1 &3 are incremented by 1Step 4, element 1 > element 2 element 3 > element 4 so element 2 & 4 are incrementedStep 5, element 0> element 1; element 2>element 3 ;element 4> element 5; so element 1, 3, &5 are incremented. and so on...Consider the following array, 5 0 0 0 0 01) 5 1 0 0 0 0 2) 5 1 1 0 0 0 3) 5 2 1 1 0 0 4) 5 2 2 1 1 0 5) 5 3 2 2 1 1 6) 5 3 3 2 2 1 7) 5 4 3 3 2 2 8) 5 4 4 3 3 2 9) 5 5 4 4 3 3 10) 5 5 5 4 4 3 11) 5 5 5 5 4 4 12) 5 5 5 5 5 4 13) 5 5 5 5 5 5Notice that after an unbalance is created (i.e array[i]>array[i+1]) the element gets incremented by one in alternate steps. In step 1 element 1 gets incremented to 1, in step 2 element 2 gets incremented to 1, in step 3 element 3 gets incremented to 1, so in step n-1, n-1th element will become 1. After that n-1th element is increased by 1 on alternate steps until it reaches the value at element 0. Then the entire array becomes equal.So the pattern followed by the last element is (0, 0, 0.., 0) till (N – 4)th element becomes 1 which is n-4 steps and after that, (0, 0, 1, 1, 2, 2, 3, 3, 4, 4, ... M – 1, M – 1, M) which is 2*m + 1 steps.So the Final Result becomes (N – 3) + 2 * MThere are a few corner cases which need to be handled, viz. When N = 1, array has only a single element, so the number of steps required = 0. and When N = 2, number of steps required equal to M C++ Java Python3 C# PHP Javascript // C++ program to make the array elements equal in minimum steps #include <bits/stdc++.h>using namespace std; // Returns the minimum steps required to make an array of N// elements equal, where the first array element equals Mint steps(int N, int M){ // Corner Case 1: When N = 1 if (N == 1) return 0; // Corner Case 2: When N = 2 else if (N == 2) // corner case 2 return M; return 2 * M + (N - 3);} // Driver Codeint main(){ int N = 4, M = 4; cout << steps(N, M); return 0;} // Java program to make the array elements// equal in minimum steps import java.io.*; class GFG { // Returns the minimum steps required // to make an array of N elements equal, // where the first array element equals M static int steps(int N, int M) { // Corner Case 1: When N = 1 if (N == 1) return 0; // Corner Case 2: When N = 2 else if (N == 2) // corner case 2 return M; return 2 * M + (N - 3); } // Driver Code public static void main (String[] args) { int N = 4, M = 4; System.out.print( steps(N, M)); }} // This code is contributed by anuj_67. # Python program to make# the array elements equal# in minimum steps # Returns the minimum steps# required to make an array# of N elements equal, where# the first array element# equals Mdef steps(N, M): # Corner Case 1: When N = 1 if (N == 1): return 0 # Corner Case 2: When N = 2 elif(N == 2): return M return 2 * M + (N - 3) # Driver CodeN = 4M = 4print(steps(N,M)) # This code is contributed# by Shivi_Aggarwal. // C# program to make the array// elements equal in minimum stepsusing System; class GFG{ // Returns the minimum steps // required to make an array // of N elements equal, where // the first array element // equals M static int steps(int N, int M) { // Corner Case 1: When N = 1 if (N == 1) return 0; // Corner Case 2: When N = 2 else if (N == 2) // corner case 2 return M; return 2 * M + (N - 3); } // Driver Code public static void Main () { int N = 4, M = 4; Console.WriteLine(steps(N, M)); }} // This code is contributed by anuj_67. <?php// PHP program to make the array// elements equal in minimum steps // Returns the minimum steps required// to make an array of N elements equal,// where the first array element equals Mfunction steps($N, $M){ // Corner Case 1: When N = 1 if ($N == 1) return 0; // Corner Case 2: When N = 2 else if ($N == 2) // corner case 2 return $M; return 2 * $M + ($N - 3);} // Driver Code$N = 4;$M = 4;echo steps($N, $M); // This code is contributed by ajit?> <script> // Javascript program to make the array // elements equal in minimum steps // Returns the minimum steps // required to make an array // of N elements equal, where // the first array element // equals M function steps(N, M) { // Corner Case 1: When N = 1 if (N == 1) return 0; // Corner Case 2: When N = 2 else if (N == 2) // corner case 2 return M; return 2 * M + (N - 3); } let N = 4, M = 4; document.write(steps(N, M)); // This code is contributed by suresh07.</script> 9 vt_m Shivi_Aggarwal jit_t suresh07 adnanirshad158 Greedy Pattern Searching Greedy Pattern Searching Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Policemen catch thieves K Centers Problem | Set 1 (Greedy Approximate Algorithm) Maximize difference between the Sum of the two halves of the Array after removal of N elements Minimize Cash Flow among a given set of friends who have borrowed money from each other Program for First Fit algorithm in Memory Management KMP Algorithm for Pattern Searching Rabin-Karp Algorithm for Pattern Searching Check if a string is substring of another Naive algorithm for Pattern Searching Boyer Moore Algorithm for Pattern Searching
[ { "code": null, "e": 28, "s": 0, "text": "\n13 Sep, 2021" }, { "code": null, "e": 640, "s": 28, "text": "Given an array of N elements where the first element is a non zero positive number M, and the rest N – 1 elements are 0, the task is to calculate the minimum number of steps required to make the entire array equal while abiding by the following rules:1. The ith element can be increased by one if and only if i-1th element is strictly greater than the ith element 2. If the ith element is being increased by one then the i+1th cannot be increased at the same time.(i.e consecutive elements cannot be increased at the same time) 3. Multiple elements can be incremented simultaneously in a single step.Examples: " }, { "code": null, "e": 1067, "s": 640, "text": "Input : N = 3, M = 4 Output : 8 Explanation: array is 4 0 0 In 4 steps element at index 1 is increased, so the array becomes {4, 4, 0}. In the next 4 steps the element at index 3 is increased so array becomes {4, 4, 4} Thus, 4 + 4 = 8 operations are required to make all the array elements equalInput : N = 4, M = 4 Output : 9 Explanation: The steps are shown in the flowchart given below Refer to the flowchart given below. " }, { "code": null, "e": 2724, "s": 1071, "text": "Approach: To maximise the Number of Increments per Step, more number of Unbalances are created (array[i]>array[i+1]),Step 1, element 0 >element 1 so element 1 is incremented, Step 2, element 1> element 2 so element 2 is incremented by 1Step 3, element 0 > element 1 and element 2> element 3 so element 1 &3 are incremented by 1Step 4, element 1 > element 2 element 3 > element 4 so element 2 & 4 are incrementedStep 5, element 0> element 1; element 2>element 3 ;element 4> element 5; so element 1, 3, &5 are incremented. and so on...Consider the following array, 5 0 0 0 0 01) 5 1 0 0 0 0 2) 5 1 1 0 0 0 3) 5 2 1 1 0 0 4) 5 2 2 1 1 0 5) 5 3 2 2 1 1 6) 5 3 3 2 2 1 7) 5 4 3 3 2 2 8) 5 4 4 3 3 2 9) 5 5 4 4 3 3 10) 5 5 5 4 4 3 11) 5 5 5 5 4 4 12) 5 5 5 5 5 4 13) 5 5 5 5 5 5Notice that after an unbalance is created (i.e array[i]>array[i+1]) the element gets incremented by one in alternate steps. In step 1 element 1 gets incremented to 1, in step 2 element 2 gets incremented to 1, in step 3 element 3 gets incremented to 1, so in step n-1, n-1th element will become 1. After that n-1th element is increased by 1 on alternate steps until it reaches the value at element 0. Then the entire array becomes equal.So the pattern followed by the last element is (0, 0, 0.., 0) till (N – 4)th element becomes 1 which is n-4 steps and after that, (0, 0, 1, 1, 2, 2, 3, 3, 4, 4, ... M – 1, M – 1, M) which is 2*m + 1 steps.So the Final Result becomes (N – 3) + 2 * MThere are a few corner cases which need to be handled, viz. When N = 1, array has only a single element, so the number of steps required = 0. and When N = 2, number of steps required equal to M " }, { "code": null, "e": 2728, "s": 2724, "text": "C++" }, { "code": null, "e": 2733, "s": 2728, "text": "Java" }, { "code": null, "e": 2741, "s": 2733, "text": "Python3" }, { "code": null, "e": 2744, "s": 2741, "text": "C#" }, { "code": null, "e": 2748, "s": 2744, "text": "PHP" }, { "code": null, "e": 2759, "s": 2748, "text": "Javascript" }, { "code": "// C++ program to make the array elements equal in minimum steps #include <bits/stdc++.h>using namespace std; // Returns the minimum steps required to make an array of N// elements equal, where the first array element equals Mint steps(int N, int M){ // Corner Case 1: When N = 1 if (N == 1) return 0; // Corner Case 2: When N = 2 else if (N == 2) // corner case 2 return M; return 2 * M + (N - 3);} // Driver Codeint main(){ int N = 4, M = 4; cout << steps(N, M); return 0;}", "e": 3275, "s": 2759, "text": null }, { "code": "// Java program to make the array elements// equal in minimum steps import java.io.*; class GFG { // Returns the minimum steps required // to make an array of N elements equal, // where the first array element equals M static int steps(int N, int M) { // Corner Case 1: When N = 1 if (N == 1) return 0; // Corner Case 2: When N = 2 else if (N == 2) // corner case 2 return M; return 2 * M + (N - 3); } // Driver Code public static void main (String[] args) { int N = 4, M = 4; System.out.print( steps(N, M)); }} // This code is contributed by anuj_67.", "e": 3944, "s": 3275, "text": null }, { "code": "# Python program to make# the array elements equal# in minimum steps # Returns the minimum steps# required to make an array# of N elements equal, where# the first array element# equals Mdef steps(N, M): # Corner Case 1: When N = 1 if (N == 1): return 0 # Corner Case 2: When N = 2 elif(N == 2): return M return 2 * M + (N - 3) # Driver CodeN = 4M = 4print(steps(N,M)) # This code is contributed# by Shivi_Aggarwal.", "e": 4391, "s": 3944, "text": null }, { "code": "// C# program to make the array// elements equal in minimum stepsusing System; class GFG{ // Returns the minimum steps // required to make an array // of N elements equal, where // the first array element // equals M static int steps(int N, int M) { // Corner Case 1: When N = 1 if (N == 1) return 0; // Corner Case 2: When N = 2 else if (N == 2) // corner case 2 return M; return 2 * M + (N - 3); } // Driver Code public static void Main () { int N = 4, M = 4; Console.WriteLine(steps(N, M)); }} // This code is contributed by anuj_67.", "e": 5052, "s": 4391, "text": null }, { "code": "<?php// PHP program to make the array// elements equal in minimum steps // Returns the minimum steps required// to make an array of N elements equal,// where the first array element equals Mfunction steps($N, $M){ // Corner Case 1: When N = 1 if ($N == 1) return 0; // Corner Case 2: When N = 2 else if ($N == 2) // corner case 2 return $M; return 2 * $M + ($N - 3);} // Driver Code$N = 4;$M = 4;echo steps($N, $M); // This code is contributed by ajit?>", "e": 5541, "s": 5052, "text": null }, { "code": "<script> // Javascript program to make the array // elements equal in minimum steps // Returns the minimum steps // required to make an array // of N elements equal, where // the first array element // equals M function steps(N, M) { // Corner Case 1: When N = 1 if (N == 1) return 0; // Corner Case 2: When N = 2 else if (N == 2) // corner case 2 return M; return 2 * M + (N - 3); } let N = 4, M = 4; document.write(steps(N, M)); // This code is contributed by suresh07.</script>", "e": 6148, "s": 5541, "text": null }, { "code": null, "e": 6150, "s": 6148, "text": "9" }, { "code": null, "e": 6157, "s": 6152, "text": "vt_m" }, { "code": null, "e": 6172, "s": 6157, "text": "Shivi_Aggarwal" }, { "code": null, "e": 6178, "s": 6172, "text": "jit_t" }, { "code": null, "e": 6187, "s": 6178, "text": "suresh07" }, { "code": null, "e": 6202, "s": 6187, "text": "adnanirshad158" }, { "code": null, "e": 6209, "s": 6202, "text": "Greedy" }, { "code": null, "e": 6227, "s": 6209, "text": "Pattern Searching" }, { "code": null, "e": 6234, "s": 6227, "text": "Greedy" }, { "code": null, "e": 6252, "s": 6234, "text": "Pattern Searching" }, { "code": null, "e": 6350, "s": 6252, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6374, "s": 6350, "text": "Policemen catch thieves" }, { "code": null, "e": 6431, "s": 6374, "text": "K Centers Problem | Set 1 (Greedy Approximate Algorithm)" }, { "code": null, "e": 6526, "s": 6431, "text": "Maximize difference between the Sum of the two halves of the Array after removal of N elements" }, { "code": null, "e": 6614, "s": 6526, "text": "Minimize Cash Flow among a given set of friends who have borrowed money from each other" }, { "code": null, "e": 6667, "s": 6614, "text": "Program for First Fit algorithm in Memory Management" }, { "code": null, "e": 6703, "s": 6667, "text": "KMP Algorithm for Pattern Searching" }, { "code": null, "e": 6746, "s": 6703, "text": "Rabin-Karp Algorithm for Pattern Searching" }, { "code": null, "e": 6788, "s": 6746, "text": "Check if a string is substring of another" }, { "code": null, "e": 6826, "s": 6788, "text": "Naive algorithm for Pattern Searching" } ]
Happy Number
14 Jun, 2022 A number is called happy if it leads to 1 after a sequence of steps wherein each step number is replaced by the sum of squares of its digit that is if we start with Happy Number and keep replacing it with digits square sum, we reach 1. Examples : Input: n = 19 Output: True 19 is Happy Number, 1^2 + 9^2 = 82 8^2 + 2^2 = 68 6^2 + 8^2 = 100 1^2 + 0^2 + 0^2 = 1 As we reached to 1, 19 is a Happy Number. Input: n = 20 Output: False A number will not be a Happy Number when it makes a loop in its sequence that is it touches a number in sequence which already been touched. So to check whether a number is happy or not, we can keep a set, if the same number occurs again we flag result as not happy. A simple function on the above approach can be written as below – C++ Java C# Javascript Python3 // method return true if n is Happy Number// numSquareSum method is given in below detailed code snippetint isHappyNumber(int n){ set<int> st; while (1) { n = numSquareSum(n); if (n == 1) return true; if (st.find(n) != st.end()) return false; st.insert(n); }} // method return true if n is Happy Number// numSquareSum method is given in below detailed code snippetstatic int isHappyNumber(int n){ HashSet<Integer> st = new HashSet<>(); while (1) { n = numSquareSum(n); if (n == 1) return true; if (st.contains(n)) return false; st.add(n); }} // This code is contributed by Princi Singh // Method return true if n is Happy Number// numSquareSum method is given in below// detailed code snippetstatic int isHappyNumber(int n){ HashSet<int> st = new HashSet<>(); while (1) { n = numSquareSum(n); if (n == 1) return true; if (st.Contains(n)) return false; st.Add(n); }} // This code is contributed by 29AjayKumar <script> // method return true if n is Happy Number// numSquareSum method is given in below detailed code snippet let st = new Set(); while (1) { n = numSquareSum(n); if (n == 1) return true; if (st.has(n)) return false; st.add(n); }} //This code is contributed by Mayank Tyagi</script> # method return true if n is Happy Number# numSquareSum method is given in below detailed code snippetdef isHappyNumber(n): st=set() while (1): n = numSquareSum(n) if (n == 1): return True if n not in st: return False st.insert(n) Complexity Analysis: Time Complexity: O(n*log(n)). Chapters descriptions off, selected captions settings, opens captions settings dialog captions off, selected English This is a modal window. Beginning of dialog window. Escape will cancel and close the window. End of dialog window. Auxiliary Space: O(n) since using extra set for storage We can solve this problem without using extra space and that technique can be used in some other similar problems also. If we treat every number as a node and replacement by square sum digit as a link, then this problem is same as finding a loop in a linklist : So as a proposed solution from the above link, we will keep two numbers slow and fast both initialize from a given number, slow is replaced one step at a time and fast is replaced two steps at a time. If they meet at 1, then the given number is Happy Number otherwise not. C++ C Java Python3 C# PHP Javascript // C++ program to check a number is a Happy number or not#include <bits/stdc++.h>using namespace std; // Utility method to return sum of square of digit of nint numSquareSum(int n){ int squareSum = 0; while (n) { squareSum += (n % 10) * (n % 10); n /= 10; } return squareSum;} // method return true if n is Happy numberbool isHappynumber(int n){ int slow, fast; // initialize slow and fast by n slow = fast = n; do { // move slow number by one iteration slow = numSquareSum(slow); // move fast number by two iteration fast = numSquareSum(numSquareSum(fast)); } while (slow != fast); // if both number meet at 1, then return true return (slow == 1);} // Driver code to test above methodsint main(){ int n = 13; if (isHappynumber(n)) cout << n << " is a Happy number\n"; else cout << n << " is not a Happy number\n";} // This code is contributed by Sania Kumari Gupta (kriSania804) // C program to check a number is a Happy number or not#include <stdbool.h>#include <stdio.h> // Utility method to return sum of square of digit of nint numSquareSum(int n){ int squareSum = 0; while (n) { squareSum += (n % 10) * (n % 10); n /= 10; } return squareSum;} // method return true if n is Happy numberbool isHappynumber(int n){ int slow, fast; // initialize slow and fast by n slow = fast = n; do { // move slow number by one iteration slow = numSquareSum(slow); // move fast number by two iteration fast = numSquareSum(numSquareSum(fast)); } while (slow != fast); // if both number meet at 1, then return true return (slow == 1);} // Driver code to test above methodsint main(){ int n = 13; if (isHappynumber(n)) printf("%d is a Happy number\n", n); else printf("%d is not a Happy number\n", n);} // This code is contributed by Sania Kumari Gupta// (kriSania804) // Java program to check a number is a Happy// number or not class GFG { // Utility method to return sum of square of// digit of nstatic int numSquareSum(int n){ int squareSum = 0; while (n!= 0) { squareSum += (n % 10) * (n % 10); n /= 10; } return squareSum;} // method return true if n is Happy numberstatic boolean isHappynumber(int n){ int slow, fast; // initialize slow and fast by n slow = fast = n; do { // move slow number // by one iteration slow = numSquareSum(slow); // move fast number // by two iteration fast = numSquareSum(numSquareSum(fast)); } while (slow != fast); // if both number meet at 1, // then return true return (slow == 1);} // Driver code to test above methodspublic static void main(String[] args){ int n = 13; if (isHappynumber(n)) System.out.println(n + " is a Happy number"); else System.out.println(n + " is not a Happy number");}} # Python3 program to check a number# is a Happy number or not # Utility method to return# sum of square of digit of ndef numSquareSum(n): squareSum = 0; while(n): squareSum += (n % 10) * (n % 10); n = int(n / 10); return squareSum; # method return true if# n is Happy numberdef isHappynumber(n): # initialize slow # and fast by n slow = n; fast = n; while(True): # move slow number # by one iteration slow = numSquareSum(slow); # move fast number # by two iteration fast = numSquareSum(numSquareSum(fast)); if(slow != fast): continue; else: break; # if both number meet at 1, # then return true return (slow == 1); # Driver Coden = 13;if (isHappynumber(n)): print(n , "is a Happy number");else: print(n , "is not a Happy number"); # This code is contributed by mits // C# program to check a number// is a Happy number or notusing System;class GFG { // Utility method to return// sum of square of digit of nstatic int numSquareSum(int n){ int squareSum = 0; while (n!= 0) { squareSum += (n % 10) * (n % 10); n /= 10; } return squareSum;} // method return true if// n is Happy numberstatic bool isHappynumber(int n){ int slow, fast; // initialize slow and // fast by n slow = fast = n; do { // move slow number // by one iteration slow = numSquareSum(slow); // move fast number // by two iteration fast = numSquareSum(numSquareSum(fast)); } while (slow != fast); // if both number meet at 1, // then return true return (slow == 1);} // Driver codepublic static void Main(){ int n = 13; if (isHappynumber(n)) Console.WriteLine(n + " is a Happy number"); else Console.WriteLine(n + " is not a Happy number");}} // This code is contributed by anuj_67. <?php// PHP program to check a number// is a Happy number or not // Utility method to return// sum of square of digit of nfunction numSquareSum( $n){ $squareSum = 0; while ($n) { $squareSum += ($n % 10) * ($n % 10); $n /= 10; } return $squareSum;} // method return true if// n is Happy numberfunction isHappynumber( $n){ $slow; $fast; // initialize slow // and fast by n $slow = $n; $fast = $n; do { // move slow number // by one iteration $slow = numSquareSum($slow); // move fast number // by two iteration $fast = numSquareSum(numSquareSum($fast)); } while ($slow != $fast); // if both number meet at 1, // then return true return ($slow == 1);} // Driver Code$n = 13;if (isHappynumber($n)) echo $n , " is a Happy number\n";else echo n , " is not a Happy number\n"; // This code is contributed by anuj_67.?> <script> // Javascript program to check a number is a Happy// number or not// Utility method to return sum of square of// digit of nfunction numSquareSum(n){ var squareSum = 0; while (n!= 0) { squareSum += (n % 10) * (n % 10); n = parseInt(n/10); } return squareSum;} // method return true if n is Happy numberfunction isHappynumber(n){ var slow, fast; // initialize slow and fast by n slow = fast = n; do { // move slow number // by one iteration slow = numSquareSum(slow); // move fast number // by two iteration fast = numSquareSum(numSquareSum(fast)); } while (slow != fast); // if both number meet at 1, // then return true return (slow == 1);} // Driver code to test above methodsvar n = 13;if (isHappynumber(n)) document.write(n + " is a Happy number");else document.write(n + " is not a Happy number"); // This code contributed by Princi Singh </script> Output : 13 is a Happy Number Complexity Analysis: Time Complexity: O(n*log(n)). Auxiliary Space: O(1). Another approach for solving this problem using no extra space.A number cannot be a happy number if, at any step, the sum of the square of digits obtained is a single-digit number except 1 or 7. This is because 1 and 7 are the only single-digit happy numbers. Using this information, we can develop an approach as shown in the code below – C++ Java Python3 C# Javascript // C++ program to check if a number// is a Happy number or not.#include <bits/stdc++.h>using namespace std; // Method - returns true if the input is// a happy number else returns falsebool isHappynumber(int n){ if (n == 1 || n == 7) return true; int sum = n, x = n; // This loop executes till the sum // of square of digits obtained is // not a single digit number while(sum > 9) { sum = 0; // This loop finds the sum of // square of digits while (x > 0) { int d = x % 10; sum += d * d; x /= 10; } if (sum == 1) return true; x = sum; } if (sum == 7) return true; return false;} int main(){ int n = 13; if (isHappynumber(n)) cout << n << " is a Happy number"; else cout << n << " is not a Happy number"; return 0;} // This code is contributed by divyeshrabadiya07. // This code is contributed by Vansh Sodhi.// Java program to check if a number is a Happy number or not. class GFG { // method - returns true if the input is a happy // number else returns false static boolean isHappynumber(int n) { if (n == 1 || n == 7) return true; int sum = n, x = n; // this loop executes till the sum of square of // digits obtained is not a single digit number while(sum > 9) { sum = 0; // this loop finds the sum of square of digits while (x > 0) { int d = x%10; sum += d*d; x/=10; } if (sum == 1) return true; x = sum; } if(sum == 7) return true; return false; } // Driver code public static void main(String[] args) { int n = 13; if (isHappynumber(n)) System.out.println(n + " is a Happy number"); else System.out.println(n + " is not a Happy number"); }} # Python3 program to check if a number is a Happy number or not. # Method - returns true if the input is# a happy number else returns falsedef isHappynumber(n): if n == 1 or n == 7: return True Sum, x = n, n # This loop executes till the sum # of square of digits obtained is # not a single digit number while Sum > 9: Sum = 0 # This loop finds the sum of # square of digits while x > 0: d = x % 10 Sum += d * d x = int(x / 10) if Sum == 1: return True x = Sum if Sum == 7: return True return False n = 13 if isHappynumber(n): print(n, "is a Happy number")else: print(n, "is not a Happy number") # This code is contributed by mukesh07. // C# program to check if a number// is a Happy number or not.using System; class GFG{ // Method - returns true if the input is// a happy number else returns falsestatic bool isHappynumber(int n){ if (n == 1 || n == 7) return true; int sum = n, x = n; // This loop executes till the sum // of square of digits obtained is // not a single digit number while(sum > 9) { sum = 0; // This loop finds the sum of // square of digits while (x > 0) { int d = x % 10; sum += d * d; x /= 10; } if (sum == 1) return true; x = sum; } if (sum == 7) return true; return false;} // Driver codepublic static void Main(String[] args){ int n = 13; if (isHappynumber(n)) Console.WriteLine(n + " is a Happy number"); else Console.WriteLine(n + " is not a Happy number");}} // This code is contributed by 29AjayKumar <script>// This code is contributed by Vansh Sodhi.// javascript program to check if a number is a Happy number or not. // method - returns true if the input is a happy // number else returns false function isHappynumber(n) { if (n == 1 || n == 7) return true; var sum = n, x = n; // this loop executes till the sum of square of // digits obtained is not a single digit number while(sum > 9) { sum = 0; // this loop finds the sum of square of digits while (x > 0) { var d = x % 10; sum += d * d; x /= 10; } if (sum == 1) return true; x = sum; } if(sum == 7) return true; return false;} // Driver code var n = 13; if (isHappynumber(n)) document.write(n + " is a Happy number"); else document.write(n + " is not a Happy number"); // This code is contributed by 29AjayKumar</script> 13 is a Happy number Complexity Analysis: Time Complexity: O(n*log(n)). Auxiliary Space: O(1). This article is contributed by Utkarsh Trivedi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks’ main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. vt_m Mithun Kumar Coolyo13605 princi singh 29AjayKumar mayanktyagi1709 divyeshrabadiya07 mukesh07 amartyaghoshgfg anandkumarshivam2266 krisania804 technophpfij Algorithms Mathematical Recursion Mathematical Recursion Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n14 Jun, 2022" }, { "code": null, "e": 291, "s": 54, "text": "A number is called happy if it leads to 1 after a sequence of steps wherein each step number is replaced by the sum of squares of its digit that is if we start with Happy Number and keep replacing it with digits square sum, we reach 1. " }, { "code": null, "e": 303, "s": 291, "text": "Examples : " }, { "code": null, "e": 487, "s": 303, "text": "Input: n = 19\nOutput: True\n19 is Happy Number,\n1^2 + 9^2 = 82\n8^2 + 2^2 = 68\n6^2 + 8^2 = 100\n1^2 + 0^2 + 0^2 = 1\nAs we reached to 1, 19 is a Happy Number.\n\nInput: n = 20\nOutput: False" }, { "code": null, "e": 822, "s": 487, "text": "A number will not be a Happy Number when it makes a loop in its sequence that is it touches a number in sequence which already been touched. So to check whether a number is happy or not, we can keep a set, if the same number occurs again we flag result as not happy. A simple function on the above approach can be written as below – " }, { "code": null, "e": 826, "s": 822, "text": "C++" }, { "code": null, "e": 831, "s": 826, "text": "Java" }, { "code": null, "e": 834, "s": 831, "text": "C#" }, { "code": null, "e": 845, "s": 834, "text": "Javascript" }, { "code": null, "e": 853, "s": 845, "text": "Python3" }, { "code": "// method return true if n is Happy Number// numSquareSum method is given in below detailed code snippetint isHappyNumber(int n){ set<int> st; while (1) { n = numSquareSum(n); if (n == 1) return true; if (st.find(n) != st.end()) return false; st.insert(n); }}", "e": 1177, "s": 853, "text": null }, { "code": "// method return true if n is Happy Number// numSquareSum method is given in below detailed code snippetstatic int isHappyNumber(int n){ HashSet<Integer> st = new HashSet<>(); while (1) { n = numSquareSum(n); if (n == 1) return true; if (st.contains(n)) return false; st.add(n); }} // This code is contributed by Princi Singh", "e": 1567, "s": 1177, "text": null }, { "code": "// Method return true if n is Happy Number// numSquareSum method is given in below// detailed code snippetstatic int isHappyNumber(int n){ HashSet<int> st = new HashSet<>(); while (1) { n = numSquareSum(n); if (n == 1) return true; if (st.Contains(n)) return false; st.Add(n); }} // This code is contributed by 29AjayKumar", "e": 1961, "s": 1567, "text": null }, { "code": "<script> // method return true if n is Happy Number// numSquareSum method is given in below detailed code snippet let st = new Set(); while (1) { n = numSquareSum(n); if (n == 1) return true; if (st.has(n)) return false; st.add(n); }} //This code is contributed by Mayank Tyagi</script>", "e": 2311, "s": 1961, "text": null }, { "code": "# method return true if n is Happy Number# numSquareSum method is given in below detailed code snippetdef isHappyNumber(n): st=set() while (1): n = numSquareSum(n) if (n == 1): return True if n not in st: return False st.insert(n)", "e": 2600, "s": 2311, "text": null }, { "code": null, "e": 2621, "s": 2600, "text": "Complexity Analysis:" }, { "code": null, "e": 2652, "s": 2621, "text": "Time Complexity: O(n*log(n)). " }, { "code": null, "e": 2661, "s": 2652, "text": "Chapters" }, { "code": null, "e": 2688, "s": 2661, "text": "descriptions off, selected" }, { "code": null, "e": 2738, "s": 2688, "text": "captions settings, opens captions settings dialog" }, { "code": null, "e": 2761, "s": 2738, "text": "captions off, selected" }, { "code": null, "e": 2769, "s": 2761, "text": "English" }, { "code": null, "e": 2793, "s": 2769, "text": "This is a modal window." }, { "code": null, "e": 2862, "s": 2793, "text": "Beginning of dialog window. Escape will cancel and close the window." }, { "code": null, "e": 2884, "s": 2862, "text": "End of dialog window." }, { "code": null, "e": 2940, "s": 2884, "text": "Auxiliary Space: O(n) since using extra set for storage" }, { "code": null, "e": 3203, "s": 2940, "text": "We can solve this problem without using extra space and that technique can be used in some other similar problems also. If we treat every number as a node and replacement by square sum digit as a link, then this problem is same as finding a loop in a linklist : " }, { "code": null, "e": 3478, "s": 3203, "text": "So as a proposed solution from the above link, we will keep two numbers slow and fast both initialize from a given number, slow is replaced one step at a time and fast is replaced two steps at a time. If they meet at 1, then the given number is Happy Number otherwise not. " }, { "code": null, "e": 3482, "s": 3478, "text": "C++" }, { "code": null, "e": 3484, "s": 3482, "text": "C" }, { "code": null, "e": 3489, "s": 3484, "text": "Java" }, { "code": null, "e": 3497, "s": 3489, "text": "Python3" }, { "code": null, "e": 3500, "s": 3497, "text": "C#" }, { "code": null, "e": 3504, "s": 3500, "text": "PHP" }, { "code": null, "e": 3515, "s": 3504, "text": "Javascript" }, { "code": "// C++ program to check a number is a Happy number or not#include <bits/stdc++.h>using namespace std; // Utility method to return sum of square of digit of nint numSquareSum(int n){ int squareSum = 0; while (n) { squareSum += (n % 10) * (n % 10); n /= 10; } return squareSum;} // method return true if n is Happy numberbool isHappynumber(int n){ int slow, fast; // initialize slow and fast by n slow = fast = n; do { // move slow number by one iteration slow = numSquareSum(slow); // move fast number by two iteration fast = numSquareSum(numSquareSum(fast)); } while (slow != fast); // if both number meet at 1, then return true return (slow == 1);} // Driver code to test above methodsint main(){ int n = 13; if (isHappynumber(n)) cout << n << \" is a Happy number\\n\"; else cout << n << \" is not a Happy number\\n\";} // This code is contributed by Sania Kumari Gupta (kriSania804)", "e": 4499, "s": 3515, "text": null }, { "code": "// C program to check a number is a Happy number or not#include <stdbool.h>#include <stdio.h> // Utility method to return sum of square of digit of nint numSquareSum(int n){ int squareSum = 0; while (n) { squareSum += (n % 10) * (n % 10); n /= 10; } return squareSum;} // method return true if n is Happy numberbool isHappynumber(int n){ int slow, fast; // initialize slow and fast by n slow = fast = n; do { // move slow number by one iteration slow = numSquareSum(slow); // move fast number by two iteration fast = numSquareSum(numSquareSum(fast)); } while (slow != fast); // if both number meet at 1, then return true return (slow == 1);} // Driver code to test above methodsint main(){ int n = 13; if (isHappynumber(n)) printf(\"%d is a Happy number\\n\", n); else printf(\"%d is not a Happy number\\n\", n);} // This code is contributed by Sania Kumari Gupta// (kriSania804)", "e": 5477, "s": 4499, "text": null }, { "code": "// Java program to check a number is a Happy// number or not class GFG { // Utility method to return sum of square of// digit of nstatic int numSquareSum(int n){ int squareSum = 0; while (n!= 0) { squareSum += (n % 10) * (n % 10); n /= 10; } return squareSum;} // method return true if n is Happy numberstatic boolean isHappynumber(int n){ int slow, fast; // initialize slow and fast by n slow = fast = n; do { // move slow number // by one iteration slow = numSquareSum(slow); // move fast number // by two iteration fast = numSquareSum(numSquareSum(fast)); } while (slow != fast); // if both number meet at 1, // then return true return (slow == 1);} // Driver code to test above methodspublic static void main(String[] args){ int n = 13; if (isHappynumber(n)) System.out.println(n + \" is a Happy number\"); else System.out.println(n + \" is not a Happy number\");}}", "e": 6500, "s": 5477, "text": null }, { "code": "# Python3 program to check a number# is a Happy number or not # Utility method to return# sum of square of digit of ndef numSquareSum(n): squareSum = 0; while(n): squareSum += (n % 10) * (n % 10); n = int(n / 10); return squareSum; # method return true if# n is Happy numberdef isHappynumber(n): # initialize slow # and fast by n slow = n; fast = n; while(True): # move slow number # by one iteration slow = numSquareSum(slow); # move fast number # by two iteration fast = numSquareSum(numSquareSum(fast)); if(slow != fast): continue; else: break; # if both number meet at 1, # then return true return (slow == 1); # Driver Coden = 13;if (isHappynumber(n)): print(n , \"is a Happy number\");else: print(n , \"is not a Happy number\"); # This code is contributed by mits", "e": 7409, "s": 6500, "text": null }, { "code": "// C# program to check a number// is a Happy number or notusing System;class GFG { // Utility method to return// sum of square of digit of nstatic int numSquareSum(int n){ int squareSum = 0; while (n!= 0) { squareSum += (n % 10) * (n % 10); n /= 10; } return squareSum;} // method return true if// n is Happy numberstatic bool isHappynumber(int n){ int slow, fast; // initialize slow and // fast by n slow = fast = n; do { // move slow number // by one iteration slow = numSquareSum(slow); // move fast number // by two iteration fast = numSquareSum(numSquareSum(fast)); } while (slow != fast); // if both number meet at 1, // then return true return (slow == 1);} // Driver codepublic static void Main(){ int n = 13; if (isHappynumber(n)) Console.WriteLine(n + \" is a Happy number\"); else Console.WriteLine(n + \" is not a Happy number\");}} // This code is contributed by anuj_67.", "e": 8464, "s": 7409, "text": null }, { "code": "<?php// PHP program to check a number// is a Happy number or not // Utility method to return// sum of square of digit of nfunction numSquareSum( $n){ $squareSum = 0; while ($n) { $squareSum += ($n % 10) * ($n % 10); $n /= 10; } return $squareSum;} // method return true if// n is Happy numberfunction isHappynumber( $n){ $slow; $fast; // initialize slow // and fast by n $slow = $n; $fast = $n; do { // move slow number // by one iteration $slow = numSquareSum($slow); // move fast number // by two iteration $fast = numSquareSum(numSquareSum($fast)); } while ($slow != $fast); // if both number meet at 1, // then return true return ($slow == 1);} // Driver Code$n = 13;if (isHappynumber($n)) echo $n , \" is a Happy number\\n\";else echo n , \" is not a Happy number\\n\"; // This code is contributed by anuj_67.?>", "e": 9413, "s": 8464, "text": null }, { "code": "<script> // Javascript program to check a number is a Happy// number or not// Utility method to return sum of square of// digit of nfunction numSquareSum(n){ var squareSum = 0; while (n!= 0) { squareSum += (n % 10) * (n % 10); n = parseInt(n/10); } return squareSum;} // method return true if n is Happy numberfunction isHappynumber(n){ var slow, fast; // initialize slow and fast by n slow = fast = n; do { // move slow number // by one iteration slow = numSquareSum(slow); // move fast number // by two iteration fast = numSquareSum(numSquareSum(fast)); } while (slow != fast); // if both number meet at 1, // then return true return (slow == 1);} // Driver code to test above methodsvar n = 13;if (isHappynumber(n)) document.write(n + \" is a Happy number\");else document.write(n + \" is not a Happy number\"); // This code contributed by Princi Singh </script>", "e": 10410, "s": 9413, "text": null }, { "code": null, "e": 10420, "s": 10410, "text": "Output : " }, { "code": null, "e": 10441, "s": 10420, "text": "13 is a Happy Number" }, { "code": null, "e": 10462, "s": 10441, "text": "Complexity Analysis:" }, { "code": null, "e": 10492, "s": 10462, "text": "Time Complexity: O(n*log(n))." }, { "code": null, "e": 10516, "s": 10492, "text": "Auxiliary Space: O(1). " }, { "code": null, "e": 10857, "s": 10516, "text": "Another approach for solving this problem using no extra space.A number cannot be a happy number if, at any step, the sum of the square of digits obtained is a single-digit number except 1 or 7. This is because 1 and 7 are the only single-digit happy numbers. Using this information, we can develop an approach as shown in the code below – " }, { "code": null, "e": 10861, "s": 10857, "text": "C++" }, { "code": null, "e": 10866, "s": 10861, "text": "Java" }, { "code": null, "e": 10874, "s": 10866, "text": "Python3" }, { "code": null, "e": 10877, "s": 10874, "text": "C#" }, { "code": null, "e": 10888, "s": 10877, "text": "Javascript" }, { "code": "// C++ program to check if a number// is a Happy number or not.#include <bits/stdc++.h>using namespace std; // Method - returns true if the input is// a happy number else returns falsebool isHappynumber(int n){ if (n == 1 || n == 7) return true; int sum = n, x = n; // This loop executes till the sum // of square of digits obtained is // not a single digit number while(sum > 9) { sum = 0; // This loop finds the sum of // square of digits while (x > 0) { int d = x % 10; sum += d * d; x /= 10; } if (sum == 1) return true; x = sum; } if (sum == 7) return true; return false;} int main(){ int n = 13; if (isHappynumber(n)) cout << n << \" is a Happy number\"; else cout << n << \" is not a Happy number\"; return 0;} // This code is contributed by divyeshrabadiya07.", "e": 11875, "s": 10888, "text": null }, { "code": "// This code is contributed by Vansh Sodhi.// Java program to check if a number is a Happy number or not. class GFG { // method - returns true if the input is a happy // number else returns false static boolean isHappynumber(int n) { if (n == 1 || n == 7) return true; int sum = n, x = n; // this loop executes till the sum of square of // digits obtained is not a single digit number while(sum > 9) { sum = 0; // this loop finds the sum of square of digits while (x > 0) { int d = x%10; sum += d*d; x/=10; } if (sum == 1) return true; x = sum; } if(sum == 7) return true; return false; } // Driver code public static void main(String[] args) { int n = 13; if (isHappynumber(n)) System.out.println(n + \" is a Happy number\"); else System.out.println(n + \" is not a Happy number\"); }}", "e": 12945, "s": 11875, "text": null }, { "code": "# Python3 program to check if a number is a Happy number or not. # Method - returns true if the input is# a happy number else returns falsedef isHappynumber(n): if n == 1 or n == 7: return True Sum, x = n, n # This loop executes till the sum # of square of digits obtained is # not a single digit number while Sum > 9: Sum = 0 # This loop finds the sum of # square of digits while x > 0: d = x % 10 Sum += d * d x = int(x / 10) if Sum == 1: return True x = Sum if Sum == 7: return True return False n = 13 if isHappynumber(n): print(n, \"is a Happy number\")else: print(n, \"is not a Happy number\") # This code is contributed by mukesh07.", "e": 13783, "s": 12945, "text": null }, { "code": "// C# program to check if a number// is a Happy number or not.using System; class GFG{ // Method - returns true if the input is// a happy number else returns falsestatic bool isHappynumber(int n){ if (n == 1 || n == 7) return true; int sum = n, x = n; // This loop executes till the sum // of square of digits obtained is // not a single digit number while(sum > 9) { sum = 0; // This loop finds the sum of // square of digits while (x > 0) { int d = x % 10; sum += d * d; x /= 10; } if (sum == 1) return true; x = sum; } if (sum == 7) return true; return false;} // Driver codepublic static void Main(String[] args){ int n = 13; if (isHappynumber(n)) Console.WriteLine(n + \" is a Happy number\"); else Console.WriteLine(n + \" is not a Happy number\");}} // This code is contributed by 29AjayKumar", "e": 14792, "s": 13783, "text": null }, { "code": "<script>// This code is contributed by Vansh Sodhi.// javascript program to check if a number is a Happy number or not. // method - returns true if the input is a happy // number else returns false function isHappynumber(n) { if (n == 1 || n == 7) return true; var sum = n, x = n; // this loop executes till the sum of square of // digits obtained is not a single digit number while(sum > 9) { sum = 0; // this loop finds the sum of square of digits while (x > 0) { var d = x % 10; sum += d * d; x /= 10; } if (sum == 1) return true; x = sum; } if(sum == 7) return true; return false;} // Driver code var n = 13; if (isHappynumber(n)) document.write(n + \" is a Happy number\"); else document.write(n + \" is not a Happy number\"); // This code is contributed by 29AjayKumar</script>", "e": 15741, "s": 14792, "text": null }, { "code": null, "e": 15762, "s": 15741, "text": "13 is a Happy number" }, { "code": null, "e": 15783, "s": 15762, "text": "Complexity Analysis:" }, { "code": null, "e": 15813, "s": 15783, "text": "Time Complexity: O(n*log(n))." }, { "code": null, "e": 15837, "s": 15813, "text": "Auxiliary Space: O(1). " }, { "code": null, "e": 16262, "s": 15837, "text": "This article is contributed by Utkarsh Trivedi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks’ main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 16267, "s": 16262, "text": "vt_m" }, { "code": null, "e": 16280, "s": 16267, "text": "Mithun Kumar" }, { "code": null, "e": 16292, "s": 16280, "text": "Coolyo13605" }, { "code": null, "e": 16305, "s": 16292, "text": "princi singh" }, { "code": null, "e": 16317, "s": 16305, "text": "29AjayKumar" }, { "code": null, "e": 16333, "s": 16317, "text": "mayanktyagi1709" }, { "code": null, "e": 16351, "s": 16333, "text": "divyeshrabadiya07" }, { "code": null, "e": 16360, "s": 16351, "text": "mukesh07" }, { "code": null, "e": 16376, "s": 16360, "text": "amartyaghoshgfg" }, { "code": null, "e": 16397, "s": 16376, "text": "anandkumarshivam2266" }, { "code": null, "e": 16409, "s": 16397, "text": "krisania804" }, { "code": null, "e": 16422, "s": 16409, "text": "technophpfij" }, { "code": null, "e": 16433, "s": 16422, "text": "Algorithms" }, { "code": null, "e": 16446, "s": 16433, "text": "Mathematical" }, { "code": null, "e": 16456, "s": 16446, "text": "Recursion" }, { "code": null, "e": 16469, "s": 16456, "text": "Mathematical" }, { "code": null, "e": 16479, "s": 16469, "text": "Recursion" }, { "code": null, "e": 16490, "s": 16479, "text": "Algorithms" } ]
Setting up the environment in C#
06 Jun, 2019 Prerequisite : Introduction to C#C# is a general-purpose, modern and object-oriented programming language pronounced as “C sharp”. It was developed by Microsoft led by Anders Hejlsberg and his team within the .Net initiative and was approved by the European Computer Manufacturers Association (ECMA) and International Standards Organization (ISO). C# is among the languages for Common Language Infrastructure and the current version of C# is version 7.2. C# is a lot similar to Java syntactically and is easy for the users who have knowledge of C, C++ or Java. Basic Components involved in process of Setting up the environment in C# .Net FrameworkThe .NET Framework is a platform for building, deploying, and running Web Services and applications. To run C# applications or any program, it requires installing a .NET Framework component on the system. .NET also supports a lot of programming languages like Visual Basic, Visual C++, etc. And C# is one of the common languages which is included in the .NET Framework. It is consist of two basic components:Common Language Runtime (CLR): The .NET Framework contains a run-time environment known as CLR which runs the codes. It provides services to make the development process easy.Framework Class Library(FCL): It is a library of classes, value types, interfaces that provide access to system functionality.In Windows Operating System, .NET Framework is installed by default. To know more about .NET Framework versions, click on .NET Framework Versions. of Microsoft Document.Visual Studio IDEMicrosoft has provided an IDE(Integrated Development Environment) tool named Visual Studio to develop applications using different programming languages such as C#, VB(Visual Basic) etc. To install and use Visual Studio for the commercial purpose it must buy a license from Microsoft. For learning (non-commercial) purpose, Microsoft provided a free Visual Studio Community Version. .Net FrameworkThe .NET Framework is a platform for building, deploying, and running Web Services and applications. To run C# applications or any program, it requires installing a .NET Framework component on the system. .NET also supports a lot of programming languages like Visual Basic, Visual C++, etc. And C# is one of the common languages which is included in the .NET Framework. It is consist of two basic components:Common Language Runtime (CLR): The .NET Framework contains a run-time environment known as CLR which runs the codes. It provides services to make the development process easy.Framework Class Library(FCL): It is a library of classes, value types, interfaces that provide access to system functionality.In Windows Operating System, .NET Framework is installed by default. To know more about .NET Framework versions, click on .NET Framework Versions. of Microsoft Document. Common Language Runtime (CLR): The .NET Framework contains a run-time environment known as CLR which runs the codes. It provides services to make the development process easy. Framework Class Library(FCL): It is a library of classes, value types, interfaces that provide access to system functionality. In Windows Operating System, .NET Framework is installed by default. To know more about .NET Framework versions, click on .NET Framework Versions. of Microsoft Document. Visual Studio IDEMicrosoft has provided an IDE(Integrated Development Environment) tool named Visual Studio to develop applications using different programming languages such as C#, VB(Visual Basic) etc. To install and use Visual Studio for the commercial purpose it must buy a license from Microsoft. For learning (non-commercial) purpose, Microsoft provided a free Visual Studio Community Version. Steps for Setting up C# Environment for Windows Step 1: Download the Visual Studio Community Version Step 2: Run the .exe file and follow the instructions to install Visual Studio Community Version on the system. Step 3: Select .Net Desktop Development from the options and click to install in bottom right corner as shown below : Step 4: Open it and it will be prompted to sign in for the first time. The sign-in step is optional so it can be skipped. Step 5: The dialog box will appear for first time only and ask to choose Development Settings and color theme. Once select required options, click on Start Visual Studio option like as shown below : . Step 6: To create a new console application using C#, Go to File –> New –>Project like as shown below Step 7: Choose Console App, write the name of the project and select location path to save project files and then click OK like as shown below. Step 8: After clicking OK a predefined template will come and start writing C# code. CSharp-Basics C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n06 Jun, 2019" }, { "code": null, "e": 613, "s": 52, "text": "Prerequisite : Introduction to C#C# is a general-purpose, modern and object-oriented programming language pronounced as “C sharp”. It was developed by Microsoft led by Anders Hejlsberg and his team within the .Net initiative and was approved by the European Computer Manufacturers Association (ECMA) and International Standards Organization (ISO). C# is among the languages for Common Language Infrastructure and the current version of C# is version 7.2. C# is a lot similar to Java syntactically and is easy for the users who have knowledge of C, C++ or Java." }, { "code": null, "e": 686, "s": 613, "text": "Basic Components involved in process of Setting up the environment in C#" }, { "code": null, "e": 1978, "s": 686, "text": ".Net FrameworkThe .NET Framework is a platform for building, deploying, and running Web Services and applications. To run C# applications or any program, it requires installing a .NET Framework component on the system. .NET also supports a lot of programming languages like Visual Basic, Visual C++, etc. And C# is one of the common languages which is included in the .NET Framework. It is consist of two basic components:Common Language Runtime (CLR): The .NET Framework contains a run-time environment known as CLR which runs the codes. It provides services to make the development process easy.Framework Class Library(FCL): It is a library of classes, value types, interfaces that provide access to system functionality.In Windows Operating System, .NET Framework is installed by default. To know more about .NET Framework versions, click on .NET Framework Versions. of Microsoft Document.Visual Studio IDEMicrosoft has provided an IDE(Integrated Development Environment) tool named Visual Studio to develop applications using different programming languages such as C#, VB(Visual Basic) etc. To install and use Visual Studio for the commercial purpose it must buy a license from Microsoft. For learning (non-commercial) purpose, Microsoft provided a free Visual Studio Community Version." }, { "code": null, "e": 2871, "s": 1978, "text": ".Net FrameworkThe .NET Framework is a platform for building, deploying, and running Web Services and applications. To run C# applications or any program, it requires installing a .NET Framework component on the system. .NET also supports a lot of programming languages like Visual Basic, Visual C++, etc. And C# is one of the common languages which is included in the .NET Framework. It is consist of two basic components:Common Language Runtime (CLR): The .NET Framework contains a run-time environment known as CLR which runs the codes. It provides services to make the development process easy.Framework Class Library(FCL): It is a library of classes, value types, interfaces that provide access to system functionality.In Windows Operating System, .NET Framework is installed by default. To know more about .NET Framework versions, click on .NET Framework Versions. of Microsoft Document." }, { "code": null, "e": 3047, "s": 2871, "text": "Common Language Runtime (CLR): The .NET Framework contains a run-time environment known as CLR which runs the codes. It provides services to make the development process easy." }, { "code": null, "e": 3174, "s": 3047, "text": "Framework Class Library(FCL): It is a library of classes, value types, interfaces that provide access to system functionality." }, { "code": null, "e": 3344, "s": 3174, "text": "In Windows Operating System, .NET Framework is installed by default. To know more about .NET Framework versions, click on .NET Framework Versions. of Microsoft Document." }, { "code": null, "e": 3744, "s": 3344, "text": "Visual Studio IDEMicrosoft has provided an IDE(Integrated Development Environment) tool named Visual Studio to develop applications using different programming languages such as C#, VB(Visual Basic) etc. To install and use Visual Studio for the commercial purpose it must buy a license from Microsoft. For learning (non-commercial) purpose, Microsoft provided a free Visual Studio Community Version." }, { "code": null, "e": 3792, "s": 3744, "text": "Steps for Setting up C# Environment for Windows" }, { "code": null, "e": 3845, "s": 3792, "text": "Step 1: Download the Visual Studio Community Version" }, { "code": null, "e": 3957, "s": 3845, "text": "Step 2: Run the .exe file and follow the instructions to install Visual Studio Community Version on the system." }, { "code": null, "e": 4075, "s": 3957, "text": "Step 3: Select .Net Desktop Development from the options and click to install in bottom right corner as shown below :" }, { "code": null, "e": 4197, "s": 4075, "text": "Step 4: Open it and it will be prompted to sign in for the first time. The sign-in step is optional so it can be skipped." }, { "code": null, "e": 4396, "s": 4197, "text": "Step 5: The dialog box will appear for first time only and ask to choose Development Settings and color theme. Once select required options, click on Start Visual Studio option like as shown below :" }, { "code": null, "e": 4398, "s": 4396, "text": "." }, { "code": null, "e": 4500, "s": 4398, "text": "Step 6: To create a new console application using C#, Go to File –> New –>Project like as shown below" }, { "code": null, "e": 4644, "s": 4500, "text": "Step 7: Choose Console App, write the name of the project and select location path to save project files and then click OK like as shown below." }, { "code": null, "e": 4729, "s": 4644, "text": "Step 8: After clicking OK a predefined template will come and start writing C# code." }, { "code": null, "e": 4743, "s": 4729, "text": "CSharp-Basics" }, { "code": null, "e": 4746, "s": 4743, "text": "C#" } ]
Count number of even and odd length elements in an Array
22 Mar, 2021 Given an array arr[] of integers of size N, the task is to find the number elements of the array having even and odd length.Examples: Input: arr[] = {14, 735, 3333, 223222} Output: Number of even length elements = 3 Number of odd length elements = 1 Input: arr[] = {1121, 322, 32, 14783, 44} Output: Number of even length elements = 3 Number of odd length elements = 2 Approach: To calculate the number of digits having even length or odd length, convert each number into a string. Then check if the length is odd or even. Finally, print the count of numbers having even length and odd length separately.Below is the implementation of the above approach: CPP Java Python3 C# Javascript // C++ program to find the count// number of even and odd// length elements in an Array #include <bits/stdc++.h>using namespace std; // Function to find the number elements of// the array having even length and odd.void EvenOddLength(int arr[], int n){ // Store numbers with even length int even = 0; for (int i = 0; i < n; i++) { // Conversion of integer to string string x = to_string(arr[i]); if (x.length() % 2 == 0) even++; } cout << "Number of even " << "length elements = " << even << endl; cout << "Number of odd " << "length elements = " << n - even << endl;} // Driver codeint main(){ int arr[] = { 12, 44, 213, 232, 3433 }; int n = sizeof(arr) / sizeof(arr[0]); // Function call EvenOddLength(arr, n); return 0;} // Java program to find the count// number of even and odd// length elements in an Arrayimport java.util.*;class GFG{ // Function to find the number elements of// the array having even length and odd. static void EvenOddLength(int arr[], int n) { // Store numbers with even length int even = 0; for (int i = 0; i < n; i++) { // Conversion of integer to string String x = Integer.toString(arr[i]); if (x.length() % 2 == 0) even++; } System.out.println("Number of even length elements = "+even); System.out.println("Number of odd length elements = "+(n - even)); } // Driver code public static void main(String args[]) { int arr[] = { 12, 44, 213, 232, 3433 }; int n = arr.length; // Function call EvenOddLength(arr, n); }} // This code is contributed by AbhiThakur # Python3 program to find the count# number of even and odd# length elements in an Array # Function to find the number elements of# the array having even length and odd.def EvenOddLength(arr, n): # Store numbers with even length even = 0 for i in range(n): # Conversion of integer to string x = str(arr[i]) if (len(x) % 2 == 0): even += 1 print( "Number of even length elements = ", even) print( "Number of odd length elements = ", n - even) # Driver codeif __name__ == '__main__': arr= [12, 44, 213, 232, 3433] n = len(arr) # Function call EvenOddLength(arr, n) # This code is contributed by mohit kumar 29 // C# program to find the count// number of even and odd// length elements in an Arrayusing System; class GFG{ // Function to find the number elements of// the array having even length and odd. static void EvenOddLength(int []arr, int n) { // Store numbers with even length int even = 0; for (int i = 0; i < n; i++) { // Conversion of integer to string String x = arr[i].ToString(); if (x.Length % 2 == 0) even++; } Console.WriteLine("Number of even length elements = "+even); Console.WriteLine("Number of odd length elements = "+(n - even)); } // Driver code public static void Main(String []args) { int []arr = { 12, 44, 213, 232, 3433 }; int n = arr.Length; // Function call EvenOddLength(arr, n); }} // This code is contributed by sapnasingh4991 <script> // Javascript program to find the count// number of even and odd// length elements in an Array // Function to find the number elements of// the array having even length and odd.function EvenOddLength(arr, n){ // Store numbers with even length let even = 0; for (let i = 0; i < n; i++) { // Conversion of integer to string let x = arr[i].toString(); if ((x.length) % 2 == 0) even++; } document.write("Number of even " + "length elements = " + even + "<br>"); document.write("Number of odd " + "length elements = "); document.write(n - even + "<br>");} // Driver code let arr = [ 12, 44, 213, 232, 3433 ]; let n = arr.length; // Function call EvenOddLength(arr, n); // This code is contributed by Mayank Tyagi</script> Number of even length elements = 3 Number of odd length elements = 2 mohit kumar 29 abhaysingh290895 sapnasingh4991 mayanktyagi1709 Arrays School Programming Arrays Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Maximum and minimum of an array using minimum number of comparisons Top 50 Array Coding Problems for Interviews Multidimensional Arrays in Java Stack Data Structure (Introduction and Program) Linear Search Python Dictionary Reverse a string in Java Introduction To PYTHON Interfaces in Java Inheritance in C++
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Mar, 2021" }, { "code": null, "e": 164, "s": 28, "text": "Given an array arr[] of integers of size N, the task is to find the number elements of the array having even and odd length.Examples: " }, { "code": null, "e": 401, "s": 164, "text": "Input: arr[] = {14, 735, 3333, 223222} Output: Number of even length elements = 3 Number of odd length elements = 1 Input: arr[] = {1121, 322, 32, 14783, 44} Output: Number of even length elements = 3 Number of odd length elements = 2 " }, { "code": null, "e": 691, "s": 403, "text": "Approach: To calculate the number of digits having even length or odd length, convert each number into a string. Then check if the length is odd or even. Finally, print the count of numbers having even length and odd length separately.Below is the implementation of the above approach: " }, { "code": null, "e": 695, "s": 691, "text": "CPP" }, { "code": null, "e": 700, "s": 695, "text": "Java" }, { "code": null, "e": 708, "s": 700, "text": "Python3" }, { "code": null, "e": 711, "s": 708, "text": "C#" }, { "code": null, "e": 722, "s": 711, "text": "Javascript" }, { "code": "// C++ program to find the count// number of even and odd// length elements in an Array #include <bits/stdc++.h>using namespace std; // Function to find the number elements of// the array having even length and odd.void EvenOddLength(int arr[], int n){ // Store numbers with even length int even = 0; for (int i = 0; i < n; i++) { // Conversion of integer to string string x = to_string(arr[i]); if (x.length() % 2 == 0) even++; } cout << \"Number of even \" << \"length elements = \" << even << endl; cout << \"Number of odd \" << \"length elements = \" << n - even << endl;} // Driver codeint main(){ int arr[] = { 12, 44, 213, 232, 3433 }; int n = sizeof(arr) / sizeof(arr[0]); // Function call EvenOddLength(arr, n); return 0;}", "e": 1549, "s": 722, "text": null }, { "code": "// Java program to find the count// number of even and odd// length elements in an Arrayimport java.util.*;class GFG{ // Function to find the number elements of// the array having even length and odd. static void EvenOddLength(int arr[], int n) { // Store numbers with even length int even = 0; for (int i = 0; i < n; i++) { // Conversion of integer to string String x = Integer.toString(arr[i]); if (x.length() % 2 == 0) even++; } System.out.println(\"Number of even length elements = \"+even); System.out.println(\"Number of odd length elements = \"+(n - even)); } // Driver code public static void main(String args[]) { int arr[] = { 12, 44, 213, 232, 3433 }; int n = arr.length; // Function call EvenOddLength(arr, n); }} // This code is contributed by AbhiThakur", "e": 2487, "s": 1549, "text": null }, { "code": "# Python3 program to find the count# number of even and odd# length elements in an Array # Function to find the number elements of# the array having even length and odd.def EvenOddLength(arr, n): # Store numbers with even length even = 0 for i in range(n): # Conversion of integer to string x = str(arr[i]) if (len(x) % 2 == 0): even += 1 print( \"Number of even length elements = \", even) print( \"Number of odd length elements = \", n - even) # Driver codeif __name__ == '__main__': arr= [12, 44, 213, 232, 3433] n = len(arr) # Function call EvenOddLength(arr, n) # This code is contributed by mohit kumar 29", "e": 3164, "s": 2487, "text": null }, { "code": "// C# program to find the count// number of even and odd// length elements in an Arrayusing System; class GFG{ // Function to find the number elements of// the array having even length and odd. static void EvenOddLength(int []arr, int n) { // Store numbers with even length int even = 0; for (int i = 0; i < n; i++) { // Conversion of integer to string String x = arr[i].ToString(); if (x.Length % 2 == 0) even++; } Console.WriteLine(\"Number of even length elements = \"+even); Console.WriteLine(\"Number of odd length elements = \"+(n - even)); } // Driver code public static void Main(String []args) { int []arr = { 12, 44, 213, 232, 3433 }; int n = arr.Length; // Function call EvenOddLength(arr, n); }} // This code is contributed by sapnasingh4991", "e": 4096, "s": 3164, "text": null }, { "code": "<script> // Javascript program to find the count// number of even and odd// length elements in an Array // Function to find the number elements of// the array having even length and odd.function EvenOddLength(arr, n){ // Store numbers with even length let even = 0; for (let i = 0; i < n; i++) { // Conversion of integer to string let x = arr[i].toString(); if ((x.length) % 2 == 0) even++; } document.write(\"Number of even \" + \"length elements = \" + even + \"<br>\"); document.write(\"Number of odd \" + \"length elements = \"); document.write(n - even + \"<br>\");} // Driver code let arr = [ 12, 44, 213, 232, 3433 ]; let n = arr.length; // Function call EvenOddLength(arr, n); // This code is contributed by Mayank Tyagi</script>", "e": 4917, "s": 4096, "text": null }, { "code": null, "e": 4986, "s": 4917, "text": "Number of even length elements = 3\nNumber of odd length elements = 2" }, { "code": null, "e": 5003, "s": 4988, "text": "mohit kumar 29" }, { "code": null, "e": 5020, "s": 5003, "text": "abhaysingh290895" }, { "code": null, "e": 5035, "s": 5020, "text": "sapnasingh4991" }, { "code": null, "e": 5051, "s": 5035, "text": "mayanktyagi1709" }, { "code": null, "e": 5058, "s": 5051, "text": "Arrays" }, { "code": null, "e": 5077, "s": 5058, "text": "School Programming" }, { "code": null, "e": 5084, "s": 5077, "text": "Arrays" }, { "code": null, "e": 5182, "s": 5084, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5250, "s": 5182, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 5294, "s": 5250, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 5326, "s": 5294, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 5374, "s": 5326, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 5388, "s": 5374, "text": "Linear Search" }, { "code": null, "e": 5406, "s": 5388, "text": "Python Dictionary" }, { "code": null, "e": 5431, "s": 5406, "text": "Reverse a string in Java" }, { "code": null, "e": 5454, "s": 5431, "text": "Introduction To PYTHON" }, { "code": null, "e": 5473, "s": 5454, "text": "Interfaces in Java" } ]
Python Pillow Tutorial
17 Jun, 2021 Digital Image processing means processing the image digitally with the help of a computer. Using image processing we can perform operations like enhancing the image, blurring the image, extracting text from images, and many more operations. There are various ways to process images digitally. Here we will discuss the Pillow module of Python. Python Pillow is built on the top of PIL (Python Image Library) and is considered as the fork for the same as PIL has been discontinued from 2011. Pillow supports many image file formats including BMP, PNG, JPEG, and TIFF. The library encourages adding support for newer formats in the library by creating new file decoders. This article aims at providing information about Python Pillow from basics to advance with the help of well-explained concepts and examples. So, let’s not waste any of the time and dive deep into the Pillow. Python Pillow does not come in-built with Python. To install it type the below command in the terminal. pip install pillow After installation let’s get started using the pillow module. The Pillow module provides the open() and show() function to read and display the image respectively. For displaying the image Pillow first converts the image to a .png format (on Windows OS) and stores it in a temporary buffer and then displays it. Therefore, due to the conversion of the image format to .png some properties of the original image file format might be lost (like animation). Therefore, it is advised to use this method only for test purposes. Example: Image Used for all the below Examples: Python3 from PIL import Image # Location of the imageimg = Image.open("geek.jpg") img.show() Output: Refer to the below articles to get detailed information about opening and displaying images. Python PIL | Image.open() method Python PIL | Image.show() method size attribute provides the size of the image. It returns a tuple that contains width and height. format attribute returns the format of the image file. Example: Python3 from PIL import Image # Location of the imageimg = Image.open("geek.jpg") # size of the imageprint(img.size) # format of the imageprint(img.format) Output: (287, 70) JPEG Refer to the below article to get detailed information about Getting the Size, and format of the Image Finding the Size Resolution of Image in Python How to find width and height of an image using Python? The mode attribute of the image tells the type and depth of the pixel in the image. A 1-bit pixel has a range of 0-1, and an 8-bit pixel has a range of 0-255. There are different modes provided by this module. A few of them are: Example: Python3 from PIL import Image # Location of the imageimg = Image.open("geek.jpg") # mode of the imageprint(img.mode) Output: RGB rotate() method of the Image class is used to rotate the image by a particular angle counterclockwise around its center. After rotating the image, the sections of the image having no pixel values are filled with black (for non-alpha images) and with completely transparent pixels (for images supporting transparency). Syntax: new_object = PIL.Image.Image.rotate(image_object, angle, resample=0, expand=0) OR new_object = image_object.rotate(angle, resample=0, expand=0) Example: Python3 # Importing Image module from# PIL packagefrom PIL import Imageimport PIL # creating a image object (main image)im1 = Image.open(r"geek.jpg") # rotating a image 90 deg counter clockwiseim1 = im1.rotate(90, PIL.Image.NEAREST, expand = 1) # to show specified imageim1.show() Output: Refer to the below articles to get detailed information about rotating the image. Python PIL | rotate() method How to rotate an image using Python? Image.transpose() is used to transpose the image (flip or rotate in 90 degree steps). Syntax: transpose(degree) Keywords FLIP_TOP_BOTTOM and FLIP_LEFT_RIGHT will be passed to transpose method to flip it. FLIP_TOP_BOTTOM – returns an original image flipped Vertically FLIP_LEFT_RIGHT – returns an original image flipped Horizontally Example: Python3 # importing PIL Modulefrom PIL import Image # open the original imageoriginal_img = Image.open("geek.jpg") # Flip the original image verticallyvertical_img = original_img.transpose(method=Image.FLIP_TOP_BOTTOM)vertical_img.save("vertical.png") vertical_img.show() # close all our files objectoriginal_img.close()vertical_img.close() Output: Refer to the below articles to get detailed information about flipping images. Python PIL | Image.transpose() method How to flip an image horizontally or vertically in Python? Image.resize() returns a resized copy of the image. Interpolation happens during the resize process, due to which the quality of image changes whether it is being upscaled (resized to a higher dimension than original) or downscaled (resized to a lower Image then original). Therefore resize() should be used cautiously and while providing suitable value for resampling argument. Syntax: Image.resize(size, resample=0) Example: Python3 # Importing Image class from PIL modulefrom PIL import Image # Opens a image in RGB modeim = Image.open(r"geek.jpg") # Size of the image in pixels# (size of original image)# (This is not mandatory)width, height = im.size # Setting the points for cropped imageleft = 4top = height / 5right = 154bottom = 3 * height / 5 # Cropped image of above dimension# (It will not change original image)im1 = im.crop((left, top, right, bottom))newsize = (300, 300)im1 = im1.resize(newsize) # Shows the image in image viewerim1.show() Output: Refer to the below article to get detailed information about resizing images. Python PIL | Image.resize() method Change the ratio between width and height of an image using Python – Pillow Image.save() saves the image under the given filename. If no format is specified, the format to use is determined from the filename extension, if possible. You can use a file object instead of a filename. In this case, you must always specify the format. The file object must implement the seek, tell, and write methods, and be opened in binary mode. Syntax: Image.save(fp, format=None, **params) Example: Python3 from PIL import Image size = (40, 40)img = Image.open(r"geek.jpg") print("Original size of the image")print(img.size) # resizing the imager_img = img.resize(size, resample = Image.BILINEAR) # resized_test.png => Destination_pathr_img.save("resized_test.jpg") # Opening the new imageimg = Image.open(r"resized_test.jpg") print("\nNew size of the image")print(img.size) Output: Original size of the image (287, 70) New size of the image (40, 40) Till now, we have learned the basics of pillow now let’s start with some complex operations like blurring the image of merging two images or even creating a thumbnail. So let’s get started by merging images. Image.merge() is used to merge a set of single band images into a new multiband image. Syntax: PIL.Image.merge(mode, bands) Parameters: mode – The mode to use for the output image. See: Modes. bands – A sequence containing one single-band image for each band in the output image. All bands must have the same size. Returns: An Image object. Note: We will be using Image.split() method to split the image into individual bands. Example: Python3 # importing Image class from PIL packagefrom PIL import Image # creating a objectimage = Image.open(r"geek.jpg")image.load() # Splitting the image into individual# bandsr, g, b, = image.split() # merge function usedim1 = Image.merge('RGB', (g, b, r))im1.show() Output: Using the merge() method we can also merge two or more images. We have to select two images of the same size or we can resize the image. Then using the new() function we will create a new image and will paste all the images there. See the below example for a better understanding. Example: Images Used: Python3 from PIL import Image img_01 = Image.open("digit-number-img-0.jpg")img_02 = Image.open("digit-number-img-1.jpg")img_03 = Image.open("digit-number-img-2.jpg")img_04 = Image.open("digit-number-img-3.jpg") img_01_size = img_01.sizeimg_02_size = img_02.sizeimg_03_size = img_02.sizeimg_02_size = img_02.size print('img 1 size: ', img_01_size)print('img 2 size: ', img_02_size)print('img 3 size: ', img_03_size)print('img 4 size: ', img_03_size) new_im = Image.new('RGB', (2*img_01_size[0],2*img_01_size[1]), (250,250,250)) new_im.paste(img_01, (0,0))new_im.paste(img_02, (img_01_size[0],0))new_im.paste(img_03, (0,img_01_size[1]))new_im.paste(img_04, (img_01_size[0],img_01_size[1])) new_im.save("merged_images.png", "PNG")new_im.show() Output: Refer to the below articles to get detailed information about merging images. Python PIL | Image.merge() method How to merge images with same size using the Python 3 module pillow? Python | Copy and Paste Images onto other Image using Pillow How to merge a transparent PNG image with another image using PIL? Image.thumbnail() convert the image into a thumbnail. This method modifies the image to contain a thumbnail version of itself, no larger than the given size. This method calculates an appropriate thumbnail size to preserve the aspect of the image, calls the draft() method to configure the file reader (where applicable), and finally resizes the image. Note: This function modifies the Image object in place. If you need to use the full resolution image as well, apply this method to a copy() of the original image. Example: Image Used: Python3 # importing Image class from PIL packagefrom PIL import Image # creating a objectimage = Image.open(r"image.jpg")MAX_SIZE = (100, 100) # Creating the thumbnailimage.thumbnail(MAX_SIZE) image.show() Output: Refer to the below articles to get detailed information about creating thumbnails. Python PIL | Image.thumbnail() Method Generate square or circular thumbnail image with Python – Pillow Cropping is the process of selecting only a part of the image. The crop() method is used to crop a rectangular portion of any image. Syntax: PIL.Image.crop(box = None) Parameters: box: a 4-tuple defining the left, upper, right, and lower pixel coordinate. Example: Python3 # Importing Image class from PIL modulefrom PIL import Image # Opens a image in RGB modeim = Image.open(r"geek.jpg") # Size of the image in pixels# (size of original image)# (This is not mandatory)width, height = im.size # Setting the points for cropped imageleft = 5top = height / 4right = 164bottom = 3 * height / 4 # Cropped image of above dimension# (It will not change original image)im1 = im.crop((left, top, right, bottom)) # Shows the image in image viewerim1.show() Output: Refer to the below articles to get detailed information about Cropping images. Crop image using pillow Cropping an Image in a circular way If a blurred image is observed carefully then a common thing to notice is that image is smooth meaning edges are not observed. A filter used for blurring is also called a low pass filter because it allows the low frequency to enter and stop high frequency. The ImageFilter class in the pillow library provides various filters that can be applied using the filter() method. Let’s see some of the blurring filters provided by the pillow. This method blurs the image using the kernel matrix or through the convolution matrix. It can be applied using the BLUR parameter. Syntax: filter(ImageFilter.BLUR) Note: For more information refer, What is Image Blurring Example: Python3 # Importing Image class from PIL modulefrom PIL import Image # Opens a image in RGB modeim = Image.open(r"geek.jpg") # Blurring the imageim1 = im.filter(ImageFilter.BLUR) # Shows the image in image viewerim1.show() Output: The Gaussian filter is implemented as an Odd sized Symmetric Kernel (DIP version of a Matrix) which is passed through each pixel of the Region of Interest to get the desired effect. The kernel is not hard towards drastic color changed (edges) due to the pixels towards the center of the kernel having more weightage towards the final value than the periphery. A Gaussian filter could be considered as an approximation of the Gaussian Function (mathematics). The Pillow module provides the predefined gaussianblur kernel that does the underlying maths for us. Syntax: ImageFilter.GaussianBlur(radius=2) Example: Python3 # Importing Image class from PIL modulefrom PIL import Image # Opens a image in RGB modeim = Image.open(r"geek.jpg") # Blurring the imageim1 = im.filter(ImageFilter.GaussianBlur(4)) # Shows the image in image viewerim1.show() Output: Box blur is also known as box linear filter. Box blurs are frequently used to approximate Gaussian blur. A box blur is generally implemented as an image effect that affects the whole screen. The blurred color of the current pixel is the average of the current pixel’s color and its 8 neighboring pixels. Pillow provides the BoxBlur() method to do the same. Syntax: ImageFilter.BoxBlur(radius) Example: Python3 # Importing Image class from PIL modulefrom PIL import Image # Opens a image in RGB modeim = Image.open(r"geek.jpg") # Blurring the imageim1 = im.filter(ImageFilter.BoxBlur(4)) # Shows the image in image viewerim1.show() Output: Refer to the below articles to get detailed information about blurring images. Python PIL | GaussianBlur() method Apply a Gauss filter to an image with Python Python PIL | BoxBlur() method Pillow provides the ImageDraw module that provides simple 2D graphics for Image objects. You can use this module to create new images, annotate or retouch existing images, and generate graphics on the fly for web use. Let’s see various figures or texts that we can draw on the image. Adding text to an image can sometimes be very necessary as it can be used to provide some useful information to the image or can also be used to add a digital signature to the image. With pillow, we can easily add a text to any image. Let’s see the below example. Python3 # import all the librariesfrom PIL import Imagefrom PIL import ImageFontfrom PIL import ImageDraw # image openingimage = Image.open("image.jpg") # creating a copy of original imagewatermark_image = image.copy() # Image is converted into editable form using# Draw function and assigned to drawdraw = ImageDraw.Draw(watermark_image) # ("font type",font size)font = ImageFont.truetype("DroidSans.ttf", 50) # Decide the text location, color and font# (255,255,255)-White color textdraw.text((0, 0), "GeeksforGeeks", (255, 255, 255), font=font) watermark_image.show() Output: Make the image editable using ImageDraw. Use ImageFont to specify font and font size. This step is optional. It is for those who want their text to look cool or stylish because someone won’t select any font style then the system takes the default font style. Create a Font using ImageFont module function truetype() as it needs two parameters that are (“font type”, size) Then used text() function of draw object and pass the four-parameters (Point of starting for text, “sample text”, Color, ImageFont object). Refer to the below articles to get detailed information about adding texts to the image. Python Pillow – Writing Text on Image Python PIL | ImageDraw.Draw.text() Adding Text on Image using Python – PIL ImageDraw.Draw.multiline_text() is used to draws the string at the given position. Syntax: ImageDraw.Draw.multiline_text(xy, text, fill=None, font=None, anchor=None, spacing=0, align=”left”) Example: Python3 # Importing Image and ImageFont, ImageDraw# module from PIL packagefrom PIL import Image, ImageFont, ImageDraw # creating a image objectimage = Image.open(r'geek.jpg') draw = ImageDraw.Draw(image) # specified font sizefont = ImageFont.truetype(r'DroidSans.ttf', 15) text = u"""\GeeksFOR \n Geeks""" # drawing text sizedraw.text((6, 8), text, fill ="red", font = font, align ="right") image.show() Output: ImageDraw.Draw.line() is used to draws a line between the coordinates in the xy list. Syntax: ImageDraw.Draw.line(xy, fill=None, width=0) Example: Python3 # importing image object from PILimport mathfrom PIL import Image, ImageDraw w, h = 220, 190shape = [(40, 40), (w - 10, h - 10)] # creating new Image objectimg = Image.new("RGB", (w, h)) # create line imageimg1 = ImageDraw.Draw(img)img1.line(shape, fill="none", width=0)img.show() Output: ImageDraw.Draw.rectangle() is used to draw a rectangle. Syntax: ImageDraw.Draw.rectangle(xy, fill=None, outline=None) Example: Python3 # importing image object from PILimport mathfrom PIL import Image, ImageDraw w, h = 220, 190shape = [(40, 40), (w - 10, h - 10)] # creating new Image objectimg = Image.new("RGB", (w, h)) # create rectangle imageimg1 = ImageDraw.Draw(img)img1.rectangle(shape, fill="# ffff33", outline="red")img.show() Output: ImageDraw.Draw.polygon() is used to draw a polygon. The polygon outline consists of straight lines between the given coordinates, plus a straight line between the last and the first coordinate. Syntax: ImageDraw.Draw.polygon(xy, fill=None, outline=None) Example: Python3 import mathfrom PIL import Image, ImageDrawfrom PIL import ImagePath side = 8xy = [ ((math.cos(th) + 1) * 90, (math.sin(th) + 1) * 60) for th in [i * (2 * math.pi) / side for i in range(side)]] image = ImagePath.Path(xy).getbbox()size = list(map(int, map(math.ceil, image[2:]))) img = Image.new("RGB", size, "# f9f9f9")img1 = ImageDraw.Draw(img)img1.polygon(xy, fill="# eeeeff", outline="blue")img.show() Output: Python Pillow provides the ImageEnhance module to adjust the color, brightness, contrast, and sharpness of the image. ImageEnhance.Color() and ImageEnhance.Contrast() methods are used to adjust the color and contrast of the image respectively. ImageEnhance.Color() is used to adjust the color balance of an image, in a manner similar to the controls on a color TV set. An enhancement factor of 0.0 gives a black and white image. A factor of 1.0 gives the original image. Syntax: ImageEnhance.Color(image) Example: Python3 # This will import Image and ImageEnhance modulesfrom PIL import Image, ImageEnhance # Opening Imageim = Image.open(r"geek.jpg") # Creating object of Color classim3 = ImageEnhance.Color(im) # showing resultant imageim3.enhance(5.0).show() Output: ImageEnhance.Contrast() is used to control the contrast of an image, similar to the contrast control on a TV set. An enhancement factor of 0.0 gives a solid grey image. A factor of 1.0 gives the original image. Syntax: obj = ImageEnhance.Contrast(image) obj.enhance(factor) Example: Python3 # This will import Image and ImageEnhance modulesfrom PIL import Image, ImageEnhance # Opening Imageim = Image.open(r"geek.jpg") # Creating object of Contrast classim3 = ImageEnhance.Contrast(im) # showing resultant imageim3.enhance(5.0).show() Output: Refer to the below articles to get detailed information about enhancing color and contrast. Python PIL | ImageEnhance.Color() and ImageEnhance.Contrast() method ImageEnhance.Brightness() and ImageEnhance.Sharpness() methods are used to adjust the brightness and sharpness of the image. ImageEnhance.Brightness() is used to control the brightness of an image. An enhancement factor of 0.0 gives a black image. A factor of 1.0 gives the original image. Syntax: obj = ImageEnhance.Brightness(image) obj.enhance(factor) Example: Python3 # This will import Image and ImageEnhance modulesfrom PIL import Image, ImageEnhance # Opening Imageim = Image.open(r"geek.jpg") # Creating object of Brightness classim3 = ImageEnhance.Brightness(im) # showing resultant imageim3.enhance(1.5).show() Output: ImageEnhance.Sharpness() is used to adjust the sharpness of an image. An enhancement factor of 0.0 gives a blurred image, a factor of 1.0 gives the original image, and a factor of 2.0 gives a sharpened image. Syntax: obj = ImageEnhance.Sharpness(image) obj.enhance(factor) Example: Python3 # This will import Image and ImageChops modulesfrom PIL import Image, ImageEnhance # Opening Imageim = Image.open(r"geek.jpg") # Creating object of Sharpness classim3 = ImageEnhance.Sharpness(im) # showing resultant imageim3.enhance(5.0).show() Output: Refer to the below articles to get detailed information about enhancing the brightness and sharpness of the image. Python PIL | ImageEnhance.Brightness() and ImageEnhance.Sharpness() method Convert the .GIF to .BMP and it’s vice-versa in Python Convert an image into jpg format using Pillow in Python Convert PNG to JPG using Python Convert files from jpg to png and vice versa using Python Convert the .PNG to .GIF and it’s vice-versa in Python Convert files from jpg to gif and vice versa using Python Convert OpenCV image to PIL image in Python Create transparent png image with Python – Pillow Add padding to the image with Python – Pillow Find most used colors in image using Python Python – Color Inversion using Pillow Overlay an image on another image in Python Change image resolution using Pillow in Python Spot the difference between two images using Python How to Extract Text from Images with Python? Create and save animated GIF with Python – Pillow How to compress images using Python and PIL? Python | Using PIL ImageGrab and PyTesseract Floodfill Image using Python-Pillow Python – Channel Drop using Pillow Loading Images in Tkinter using PIL Create Certificates using Python-PIL Python | OCR on All the Images present in a Folder Simultaneously Apply changes to all the images in given folder – Using Python PIL simranarora5sos Python-pil Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n17 Jun, 2021" }, { "code": null, "e": 696, "s": 28, "text": "Digital Image processing means processing the image digitally with the help of a computer. Using image processing we can perform operations like enhancing the image, blurring the image, extracting text from images, and many more operations. There are various ways to process images digitally. Here we will discuss the Pillow module of Python. Python Pillow is built on the top of PIL (Python Image Library) and is considered as the fork for the same as PIL has been discontinued from 2011. Pillow supports many image file formats including BMP, PNG, JPEG, and TIFF. The library encourages adding support for newer formats in the library by creating new file decoders." }, { "code": null, "e": 904, "s": 696, "text": "This article aims at providing information about Python Pillow from basics to advance with the help of well-explained concepts and examples. So, let’s not waste any of the time and dive deep into the Pillow." }, { "code": null, "e": 1008, "s": 904, "text": "Python Pillow does not come in-built with Python. To install it type the below command in the terminal." }, { "code": null, "e": 1027, "s": 1008, "text": "pip install pillow" }, { "code": null, "e": 1089, "s": 1027, "text": "After installation let’s get started using the pillow module." }, { "code": null, "e": 1550, "s": 1089, "text": "The Pillow module provides the open() and show() function to read and display the image respectively. For displaying the image Pillow first converts the image to a .png format (on Windows OS) and stores it in a temporary buffer and then displays it. Therefore, due to the conversion of the image format to .png some properties of the original image file format might be lost (like animation). Therefore, it is advised to use this method only for test purposes." }, { "code": null, "e": 1559, "s": 1550, "text": "Example:" }, { "code": null, "e": 1600, "s": 1561, "text": "Image Used for all the below Examples:" }, { "code": null, "e": 1608, "s": 1600, "text": "Python3" }, { "code": "from PIL import Image # Location of the imageimg = Image.open(\"geek.jpg\") img.show()", "e": 1694, "s": 1608, "text": null }, { "code": null, "e": 1706, "s": 1698, "text": "Output:" }, { "code": null, "e": 1803, "s": 1710, "text": "Refer to the below articles to get detailed information about opening and displaying images." }, { "code": null, "e": 1838, "s": 1805, "text": "Python PIL | Image.open() method" }, { "code": null, "e": 1871, "s": 1838, "text": "Python PIL | Image.show() method" }, { "code": null, "e": 1969, "s": 1871, "text": "size attribute provides the size of the image. It returns a tuple that contains width and height." }, { "code": null, "e": 2024, "s": 1969, "text": "format attribute returns the format of the image file." }, { "code": null, "e": 2033, "s": 2024, "text": "Example:" }, { "code": null, "e": 2043, "s": 2035, "text": "Python3" }, { "code": "from PIL import Image # Location of the imageimg = Image.open(\"geek.jpg\") # size of the imageprint(img.size) # format of the imageprint(img.format)", "e": 2192, "s": 2043, "text": null }, { "code": null, "e": 2204, "s": 2196, "text": "Output:" }, { "code": null, "e": 2221, "s": 2206, "text": "(287, 70)\nJPEG" }, { "code": null, "e": 2326, "s": 2223, "text": "Refer to the below article to get detailed information about Getting the Size, and format of the Image" }, { "code": null, "e": 2375, "s": 2328, "text": "Finding the Size Resolution of Image in Python" }, { "code": null, "e": 2430, "s": 2375, "text": "How to find width and height of an image using Python?" }, { "code": null, "e": 2661, "s": 2432, "text": "The mode attribute of the image tells the type and depth of the pixel in the image. A 1-bit pixel has a range of 0-1, and an 8-bit pixel has a range of 0-255. There are different modes provided by this module. A few of them are:" }, { "code": null, "e": 2674, "s": 2665, "text": "Example:" }, { "code": null, "e": 2684, "s": 2676, "text": "Python3" }, { "code": "from PIL import Image # Location of the imageimg = Image.open(\"geek.jpg\") # mode of the imageprint(img.mode)", "e": 2794, "s": 2684, "text": null }, { "code": null, "e": 2806, "s": 2798, "text": "Output:" }, { "code": null, "e": 2812, "s": 2808, "text": "RGB" }, { "code": null, "e": 3130, "s": 2812, "text": "rotate() method of the Image class is used to rotate the image by a particular angle counterclockwise around its center. After rotating the image, the sections of the image having no pixel values are filled with black (for non-alpha images) and with completely transparent pixels (for images supporting transparency)." }, { "code": null, "e": 3140, "s": 3132, "text": "Syntax:" }, { "code": null, "e": 3221, "s": 3142, "text": "new_object = PIL.Image.Image.rotate(image_object, angle, resample=0, expand=0)" }, { "code": null, "e": 3224, "s": 3221, "text": "OR" }, { "code": null, "e": 3286, "s": 3224, "text": "new_object = image_object.rotate(angle, resample=0, expand=0)" }, { "code": null, "e": 3297, "s": 3288, "text": "Example:" }, { "code": null, "e": 3307, "s": 3299, "text": "Python3" }, { "code": "# Importing Image module from# PIL packagefrom PIL import Imageimport PIL # creating a image object (main image)im1 = Image.open(r\"geek.jpg\") # rotating a image 90 deg counter clockwiseim1 = im1.rotate(90, PIL.Image.NEAREST, expand = 1) # to show specified imageim1.show()", "e": 3580, "s": 3307, "text": null }, { "code": null, "e": 3592, "s": 3584, "text": "Output:" }, { "code": null, "e": 3678, "s": 3596, "text": "Refer to the below articles to get detailed information about rotating the image." }, { "code": null, "e": 3709, "s": 3680, "text": "Python PIL | rotate() method" }, { "code": null, "e": 3746, "s": 3709, "text": "How to rotate an image using Python?" }, { "code": null, "e": 3833, "s": 3746, "text": "Image.transpose() is used to transpose the image (flip or rotate in 90 degree steps). " }, { "code": null, "e": 3843, "s": 3835, "text": "Syntax:" }, { "code": null, "e": 3863, "s": 3845, "text": "transpose(degree)" }, { "code": null, "e": 3957, "s": 3865, "text": "Keywords FLIP_TOP_BOTTOM and FLIP_LEFT_RIGHT will be passed to transpose method to flip it." }, { "code": null, "e": 4022, "s": 3959, "text": "FLIP_TOP_BOTTOM – returns an original image flipped Vertically" }, { "code": null, "e": 4087, "s": 4022, "text": "FLIP_LEFT_RIGHT – returns an original image flipped Horizontally" }, { "code": null, "e": 4098, "s": 4089, "text": "Example:" }, { "code": null, "e": 4108, "s": 4100, "text": "Python3" }, { "code": "# importing PIL Modulefrom PIL import Image # open the original imageoriginal_img = Image.open(\"geek.jpg\") # Flip the original image verticallyvertical_img = original_img.transpose(method=Image.FLIP_TOP_BOTTOM)vertical_img.save(\"vertical.png\") vertical_img.show() # close all our files objectoriginal_img.close()vertical_img.close()", "e": 4441, "s": 4108, "text": null }, { "code": null, "e": 4453, "s": 4445, "text": "Output:" }, { "code": null, "e": 4536, "s": 4457, "text": "Refer to the below articles to get detailed information about flipping images." }, { "code": null, "e": 4576, "s": 4538, "text": "Python PIL | Image.transpose() method" }, { "code": null, "e": 4635, "s": 4576, "text": "How to flip an image horizontally or vertically in Python?" }, { "code": null, "e": 5014, "s": 4635, "text": "Image.resize() returns a resized copy of the image. Interpolation happens during the resize process, due to which the quality of image changes whether it is being upscaled (resized to a higher dimension than original) or downscaled (resized to a lower Image then original). Therefore resize() should be used cautiously and while providing suitable value for resampling argument." }, { "code": null, "e": 5025, "s": 5016, "text": "Syntax: " }, { "code": null, "e": 5058, "s": 5027, "text": "Image.resize(size, resample=0)" }, { "code": null, "e": 5067, "s": 5058, "text": "Example:" }, { "code": null, "e": 5077, "s": 5069, "text": "Python3" }, { "code": "# Importing Image class from PIL modulefrom PIL import Image # Opens a image in RGB modeim = Image.open(r\"geek.jpg\") # Size of the image in pixels# (size of original image)# (This is not mandatory)width, height = im.size # Setting the points for cropped imageleft = 4top = height / 5right = 154bottom = 3 * height / 5 # Cropped image of above dimension# (It will not change original image)im1 = im.crop((left, top, right, bottom))newsize = (300, 300)im1 = im1.resize(newsize) # Shows the image in image viewerim1.show()", "e": 5597, "s": 5077, "text": null }, { "code": null, "e": 5605, "s": 5597, "text": "Output:" }, { "code": null, "e": 5683, "s": 5605, "text": "Refer to the below article to get detailed information about resizing images." }, { "code": null, "e": 5718, "s": 5683, "text": "Python PIL | Image.resize() method" }, { "code": null, "e": 5794, "s": 5718, "text": "Change the ratio between width and height of an image using Python – Pillow" }, { "code": null, "e": 6145, "s": 5794, "text": "Image.save() saves the image under the given filename. If no format is specified, the format to use is determined from the filename extension, if possible. You can use a file object instead of a filename. In this case, you must always specify the format. The file object must implement the seek, tell, and write methods, and be opened in binary mode." }, { "code": null, "e": 6154, "s": 6145, "text": "Syntax: " }, { "code": null, "e": 6192, "s": 6154, "text": "Image.save(fp, format=None, **params)" }, { "code": null, "e": 6201, "s": 6192, "text": "Example:" }, { "code": null, "e": 6209, "s": 6201, "text": "Python3" }, { "code": "from PIL import Image size = (40, 40)img = Image.open(r\"geek.jpg\") print(\"Original size of the image\")print(img.size) # resizing the imager_img = img.resize(size, resample = Image.BILINEAR) # resized_test.png => Destination_pathr_img.save(\"resized_test.jpg\") # Opening the new imageimg = Image.open(r\"resized_test.jpg\") print(\"\\nNew size of the image\")print(img.size)", "e": 6578, "s": 6209, "text": null }, { "code": null, "e": 6590, "s": 6582, "text": "Output:" }, { "code": null, "e": 6661, "s": 6592, "text": "Original size of the image\n(287, 70)\n\nNew size of the image\n(40, 40)" }, { "code": null, "e": 6871, "s": 6663, "text": "Till now, we have learned the basics of pillow now let’s start with some complex operations like blurring the image of merging two images or even creating a thumbnail. So let’s get started by merging images." }, { "code": null, "e": 6963, "s": 6875, "text": "Image.merge() is used to merge a set of single band images into a new multiband image. " }, { "code": null, "e": 6974, "s": 6965, "text": "Syntax: " }, { "code": null, "e": 7005, "s": 6976, "text": "PIL.Image.merge(mode, bands)" }, { "code": null, "e": 7017, "s": 7005, "text": "Parameters:" }, { "code": null, "e": 7074, "s": 7017, "text": "mode – The mode to use for the output image. See: Modes." }, { "code": null, "e": 7196, "s": 7074, "text": "bands – A sequence containing one single-band image for each band in the output image. All bands must have the same size." }, { "code": null, "e": 7222, "s": 7196, "text": "Returns: An Image object." }, { "code": null, "e": 7310, "s": 7224, "text": "Note: We will be using Image.split() method to split the image into individual bands." }, { "code": null, "e": 7321, "s": 7312, "text": "Example:" }, { "code": null, "e": 7331, "s": 7323, "text": "Python3" }, { "code": "# importing Image class from PIL packagefrom PIL import Image # creating a objectimage = Image.open(r\"geek.jpg\")image.load() # Splitting the image into individual# bandsr, g, b, = image.split() # merge function usedim1 = Image.merge('RGB', (g, b, r))im1.show()", "e": 7592, "s": 7331, "text": null }, { "code": null, "e": 7604, "s": 7596, "text": "Output:" }, { "code": null, "e": 7889, "s": 7608, "text": "Using the merge() method we can also merge two or more images. We have to select two images of the same size or we can resize the image. Then using the new() function we will create a new image and will paste all the images there. See the below example for a better understanding." }, { "code": null, "e": 7900, "s": 7891, "text": "Example:" }, { "code": null, "e": 7915, "s": 7902, "text": "Images Used:" }, { "code": null, "e": 7927, "s": 7919, "text": "Python3" }, { "code": "from PIL import Image img_01 = Image.open(\"digit-number-img-0.jpg\")img_02 = Image.open(\"digit-number-img-1.jpg\")img_03 = Image.open(\"digit-number-img-2.jpg\")img_04 = Image.open(\"digit-number-img-3.jpg\") img_01_size = img_01.sizeimg_02_size = img_02.sizeimg_03_size = img_02.sizeimg_02_size = img_02.size print('img 1 size: ', img_01_size)print('img 2 size: ', img_02_size)print('img 3 size: ', img_03_size)print('img 4 size: ', img_03_size) new_im = Image.new('RGB', (2*img_01_size[0],2*img_01_size[1]), (250,250,250)) new_im.paste(img_01, (0,0))new_im.paste(img_02, (img_01_size[0],0))new_im.paste(img_03, (0,img_01_size[1]))new_im.paste(img_04, (img_01_size[0],img_01_size[1])) new_im.save(\"merged_images.png\", \"PNG\")new_im.show()", "e": 8660, "s": 7927, "text": null }, { "code": null, "e": 8668, "s": 8660, "text": "Output:" }, { "code": null, "e": 8746, "s": 8668, "text": "Refer to the below articles to get detailed information about merging images." }, { "code": null, "e": 8780, "s": 8746, "text": "Python PIL | Image.merge() method" }, { "code": null, "e": 8849, "s": 8780, "text": "How to merge images with same size using the Python 3 module pillow?" }, { "code": null, "e": 8910, "s": 8849, "text": "Python | Copy and Paste Images onto other Image using Pillow" }, { "code": null, "e": 8977, "s": 8910, "text": "How to merge a transparent PNG image with another image using PIL?" }, { "code": null, "e": 9330, "s": 8977, "text": "Image.thumbnail() convert the image into a thumbnail. This method modifies the image to contain a thumbnail version of itself, no larger than the given size. This method calculates an appropriate thumbnail size to preserve the aspect of the image, calls the draft() method to configure the file reader (where applicable), and finally resizes the image." }, { "code": null, "e": 9493, "s": 9330, "text": "Note: This function modifies the Image object in place. If you need to use the full resolution image as well, apply this method to a copy() of the original image." }, { "code": null, "e": 9502, "s": 9493, "text": "Example:" }, { "code": null, "e": 9514, "s": 9502, "text": "Image Used:" }, { "code": null, "e": 9522, "s": 9514, "text": "Python3" }, { "code": "# importing Image class from PIL packagefrom PIL import Image # creating a objectimage = Image.open(r\"image.jpg\")MAX_SIZE = (100, 100) # Creating the thumbnailimage.thumbnail(MAX_SIZE) image.show()", "e": 9720, "s": 9522, "text": null }, { "code": null, "e": 9732, "s": 9724, "text": "Output:" }, { "code": null, "e": 9819, "s": 9736, "text": "Refer to the below articles to get detailed information about creating thumbnails." }, { "code": null, "e": 9859, "s": 9821, "text": "Python PIL | Image.thumbnail() Method" }, { "code": null, "e": 9924, "s": 9859, "text": "Generate square or circular thumbnail image with Python – Pillow" }, { "code": null, "e": 10057, "s": 9924, "text": "Cropping is the process of selecting only a part of the image. The crop() method is used to crop a rectangular portion of any image." }, { "code": null, "e": 10068, "s": 10059, "text": "Syntax: " }, { "code": null, "e": 10097, "s": 10070, "text": "PIL.Image.crop(box = None)" }, { "code": null, "e": 10109, "s": 10097, "text": "Parameters:" }, { "code": null, "e": 10185, "s": 10109, "text": "box: a 4-tuple defining the left, upper, right, and lower pixel coordinate." }, { "code": null, "e": 10196, "s": 10187, "text": "Example:" }, { "code": null, "e": 10206, "s": 10198, "text": "Python3" }, { "code": "# Importing Image class from PIL modulefrom PIL import Image # Opens a image in RGB modeim = Image.open(r\"geek.jpg\") # Size of the image in pixels# (size of original image)# (This is not mandatory)width, height = im.size # Setting the points for cropped imageleft = 5top = height / 4right = 164bottom = 3 * height / 4 # Cropped image of above dimension# (It will not change original image)im1 = im.crop((left, top, right, bottom)) # Shows the image in image viewerim1.show()", "e": 10681, "s": 10206, "text": null }, { "code": null, "e": 10689, "s": 10681, "text": "Output:" }, { "code": null, "e": 10768, "s": 10689, "text": "Refer to the below articles to get detailed information about Cropping images." }, { "code": null, "e": 10792, "s": 10768, "text": "Crop image using pillow" }, { "code": null, "e": 10828, "s": 10792, "text": "Cropping an Image in a circular way" }, { "code": null, "e": 11264, "s": 10828, "text": "If a blurred image is observed carefully then a common thing to notice is that image is smooth meaning edges are not observed. A filter used for blurring is also called a low pass filter because it allows the low frequency to enter and stop high frequency. The ImageFilter class in the pillow library provides various filters that can be applied using the filter() method. Let’s see some of the blurring filters provided by the pillow." }, { "code": null, "e": 11395, "s": 11264, "text": "This method blurs the image using the kernel matrix or through the convolution matrix. It can be applied using the BLUR parameter." }, { "code": null, "e": 11403, "s": 11395, "text": "Syntax:" }, { "code": null, "e": 11428, "s": 11403, "text": "filter(ImageFilter.BLUR)" }, { "code": null, "e": 11485, "s": 11428, "text": "Note: For more information refer, What is Image Blurring" }, { "code": null, "e": 11494, "s": 11485, "text": "Example:" }, { "code": null, "e": 11502, "s": 11494, "text": "Python3" }, { "code": "# Importing Image class from PIL modulefrom PIL import Image # Opens a image in RGB modeim = Image.open(r\"geek.jpg\") # Blurring the imageim1 = im.filter(ImageFilter.BLUR) # Shows the image in image viewerim1.show()", "e": 11717, "s": 11502, "text": null }, { "code": null, "e": 11725, "s": 11717, "text": "Output:" }, { "code": null, "e": 12284, "s": 11725, "text": "The Gaussian filter is implemented as an Odd sized Symmetric Kernel (DIP version of a Matrix) which is passed through each pixel of the Region of Interest to get the desired effect. The kernel is not hard towards drastic color changed (edges) due to the pixels towards the center of the kernel having more weightage towards the final value than the periphery. A Gaussian filter could be considered as an approximation of the Gaussian Function (mathematics). The Pillow module provides the predefined gaussianblur kernel that does the underlying maths for us." }, { "code": null, "e": 12292, "s": 12284, "text": "Syntax:" }, { "code": null, "e": 12327, "s": 12292, "text": "ImageFilter.GaussianBlur(radius=2)" }, { "code": null, "e": 12336, "s": 12327, "text": "Example:" }, { "code": null, "e": 12344, "s": 12336, "text": "Python3" }, { "code": "# Importing Image class from PIL modulefrom PIL import Image # Opens a image in RGB modeim = Image.open(r\"geek.jpg\") # Blurring the imageim1 = im.filter(ImageFilter.GaussianBlur(4)) # Shows the image in image viewerim1.show()", "e": 12570, "s": 12344, "text": null }, { "code": null, "e": 12578, "s": 12570, "text": "Output:" }, { "code": null, "e": 12935, "s": 12578, "text": "Box blur is also known as box linear filter. Box blurs are frequently used to approximate Gaussian blur. A box blur is generally implemented as an image effect that affects the whole screen. The blurred color of the current pixel is the average of the current pixel’s color and its 8 neighboring pixels. Pillow provides the BoxBlur() method to do the same." }, { "code": null, "e": 12943, "s": 12935, "text": "Syntax:" }, { "code": null, "e": 12971, "s": 12943, "text": "ImageFilter.BoxBlur(radius)" }, { "code": null, "e": 12980, "s": 12971, "text": "Example:" }, { "code": null, "e": 12988, "s": 12980, "text": "Python3" }, { "code": "# Importing Image class from PIL modulefrom PIL import Image # Opens a image in RGB modeim = Image.open(r\"geek.jpg\") # Blurring the imageim1 = im.filter(ImageFilter.BoxBlur(4)) # Shows the image in image viewerim1.show()", "e": 13209, "s": 12988, "text": null }, { "code": null, "e": 13221, "s": 13213, "text": "Output:" }, { "code": null, "e": 13304, "s": 13225, "text": "Refer to the below articles to get detailed information about blurring images." }, { "code": null, "e": 13341, "s": 13306, "text": "Python PIL | GaussianBlur() method" }, { "code": null, "e": 13386, "s": 13341, "text": "Apply a Gauss filter to an image with Python" }, { "code": null, "e": 13416, "s": 13386, "text": "Python PIL | BoxBlur() method" }, { "code": null, "e": 13700, "s": 13416, "text": "Pillow provides the ImageDraw module that provides simple 2D graphics for Image objects. You can use this module to create new images, annotate or retouch existing images, and generate graphics on the fly for web use. Let’s see various figures or texts that we can draw on the image." }, { "code": null, "e": 13966, "s": 13702, "text": "Adding text to an image can sometimes be very necessary as it can be used to provide some useful information to the image or can also be used to add a digital signature to the image. With pillow, we can easily add a text to any image. Let’s see the below example." }, { "code": null, "e": 13976, "s": 13968, "text": "Python3" }, { "code": "# import all the librariesfrom PIL import Imagefrom PIL import ImageFontfrom PIL import ImageDraw # image openingimage = Image.open(\"image.jpg\") # creating a copy of original imagewatermark_image = image.copy() # Image is converted into editable form using# Draw function and assigned to drawdraw = ImageDraw.Draw(watermark_image) # (\"font type\",font size)font = ImageFont.truetype(\"DroidSans.ttf\", 50) # Decide the text location, color and font# (255,255,255)-White color textdraw.text((0, 0), \"GeeksforGeeks\", (255, 255, 255), font=font) watermark_image.show()", "e": 14539, "s": 13976, "text": null }, { "code": null, "e": 14551, "s": 14543, "text": "Output:" }, { "code": null, "e": 14594, "s": 14553, "text": "Make the image editable using ImageDraw." }, { "code": null, "e": 14812, "s": 14594, "text": "Use ImageFont to specify font and font size. This step is optional. It is for those who want their text to look cool or stylish because someone won’t select any font style then the system takes the default font style." }, { "code": null, "e": 14925, "s": 14812, "text": "Create a Font using ImageFont module function truetype() as it needs two parameters that are (“font type”, size)" }, { "code": null, "e": 15065, "s": 14925, "text": "Then used text() function of draw object and pass the four-parameters (Point of starting for text, “sample text”, Color, ImageFont object)." }, { "code": null, "e": 15156, "s": 15067, "text": "Refer to the below articles to get detailed information about adding texts to the image." }, { "code": null, "e": 15196, "s": 15158, "text": "Python Pillow – Writing Text on Image" }, { "code": null, "e": 15231, "s": 15196, "text": "Python PIL | ImageDraw.Draw.text()" }, { "code": null, "e": 15271, "s": 15231, "text": "Adding Text on Image using Python – PIL" }, { "code": null, "e": 15356, "s": 15273, "text": "ImageDraw.Draw.multiline_text() is used to draws the string at the given position." }, { "code": null, "e": 15366, "s": 15358, "text": "Syntax:" }, { "code": null, "e": 15468, "s": 15368, "text": "ImageDraw.Draw.multiline_text(xy, text, fill=None, font=None, anchor=None, spacing=0, align=”left”)" }, { "code": null, "e": 15479, "s": 15470, "text": "Example:" }, { "code": null, "e": 15489, "s": 15481, "text": "Python3" }, { "code": "# Importing Image and ImageFont, ImageDraw# module from PIL packagefrom PIL import Image, ImageFont, ImageDraw # creating a image objectimage = Image.open(r'geek.jpg') draw = ImageDraw.Draw(image) # specified font sizefont = ImageFont.truetype(r'DroidSans.ttf', 15) text = u\"\"\"\\GeeksFOR \\n Geeks\"\"\" # drawing text sizedraw.text((6, 8), text, fill =\"red\", font = font, align =\"right\") image.show()", "e": 15886, "s": 15489, "text": null }, { "code": null, "e": 15894, "s": 15886, "text": "Output:" }, { "code": null, "e": 15980, "s": 15894, "text": "ImageDraw.Draw.line() is used to draws a line between the coordinates in the xy list." }, { "code": null, "e": 15989, "s": 15980, "text": "Syntax: " }, { "code": null, "e": 16033, "s": 15989, "text": "ImageDraw.Draw.line(xy, fill=None, width=0)" }, { "code": null, "e": 16042, "s": 16033, "text": "Example:" }, { "code": null, "e": 16050, "s": 16042, "text": "Python3" }, { "code": "# importing image object from PILimport mathfrom PIL import Image, ImageDraw w, h = 220, 190shape = [(40, 40), (w - 10, h - 10)] # creating new Image objectimg = Image.new(\"RGB\", (w, h)) # create line imageimg1 = ImageDraw.Draw(img)img1.line(shape, fill=\"none\", width=0)img.show()", "e": 16331, "s": 16050, "text": null }, { "code": null, "e": 16339, "s": 16331, "text": "Output:" }, { "code": null, "e": 16395, "s": 16339, "text": "ImageDraw.Draw.rectangle() is used to draw a rectangle." }, { "code": null, "e": 16404, "s": 16395, "text": "Syntax: " }, { "code": null, "e": 16458, "s": 16404, "text": "ImageDraw.Draw.rectangle(xy, fill=None, outline=None)" }, { "code": null, "e": 16467, "s": 16458, "text": "Example:" }, { "code": null, "e": 16475, "s": 16467, "text": "Python3" }, { "code": "# importing image object from PILimport mathfrom PIL import Image, ImageDraw w, h = 220, 190shape = [(40, 40), (w - 10, h - 10)] # creating new Image objectimg = Image.new(\"RGB\", (w, h)) # create rectangle imageimg1 = ImageDraw.Draw(img)img1.rectangle(shape, fill=\"# ffff33\", outline=\"red\")img.show()", "e": 16776, "s": 16475, "text": null }, { "code": null, "e": 16788, "s": 16780, "text": "Output:" }, { "code": null, "e": 16986, "s": 16792, "text": "ImageDraw.Draw.polygon() is used to draw a polygon. The polygon outline consists of straight lines between the given coordinates, plus a straight line between the last and the first coordinate." }, { "code": null, "e": 16996, "s": 16988, "text": "Syntax:" }, { "code": null, "e": 17050, "s": 16998, "text": "ImageDraw.Draw.polygon(xy, fill=None, outline=None)" }, { "code": null, "e": 17061, "s": 17052, "text": "Example:" }, { "code": null, "e": 17071, "s": 17063, "text": "Python3" }, { "code": "import mathfrom PIL import Image, ImageDrawfrom PIL import ImagePath side = 8xy = [ ((math.cos(th) + 1) * 90, (math.sin(th) + 1) * 60) for th in [i * (2 * math.pi) / side for i in range(side)]] image = ImagePath.Path(xy).getbbox()size = list(map(int, map(math.ceil, image[2:]))) img = Image.new(\"RGB\", size, \"# f9f9f9\")img1 = ImageDraw.Draw(img)img1.polygon(xy, fill=\"# eeeeff\", outline=\"blue\")img.show()", "e": 17486, "s": 17071, "text": null }, { "code": null, "e": 17494, "s": 17486, "text": "Output:" }, { "code": null, "e": 17612, "s": 17494, "text": "Python Pillow provides the ImageEnhance module to adjust the color, brightness, contrast, and sharpness of the image." }, { "code": null, "e": 17738, "s": 17612, "text": "ImageEnhance.Color() and ImageEnhance.Contrast() methods are used to adjust the color and contrast of the image respectively." }, { "code": null, "e": 17965, "s": 17738, "text": "ImageEnhance.Color() is used to adjust the color balance of an image, in a manner similar to the controls on a color TV set. An enhancement factor of 0.0 gives a black and white image. A factor of 1.0 gives the original image." }, { "code": null, "e": 17973, "s": 17965, "text": "Syntax:" }, { "code": null, "e": 17999, "s": 17973, "text": "ImageEnhance.Color(image)" }, { "code": null, "e": 18008, "s": 17999, "text": "Example:" }, { "code": null, "e": 18016, "s": 18008, "text": "Python3" }, { "code": "# This will import Image and ImageEnhance modulesfrom PIL import Image, ImageEnhance # Opening Imageim = Image.open(r\"geek.jpg\") # Creating object of Color classim3 = ImageEnhance.Color(im) # showing resultant imageim3.enhance(5.0).show()", "e": 18255, "s": 18016, "text": null }, { "code": null, "e": 18266, "s": 18258, "text": "Output:" }, { "code": null, "e": 18479, "s": 18268, "text": "ImageEnhance.Contrast() is used to control the contrast of an image, similar to the contrast control on a TV set. An enhancement factor of 0.0 gives a solid grey image. A factor of 1.0 gives the original image." }, { "code": null, "e": 18489, "s": 18481, "text": "Syntax:" }, { "code": null, "e": 18526, "s": 18491, "text": "obj = ImageEnhance.Contrast(image)" }, { "code": null, "e": 18546, "s": 18526, "text": "obj.enhance(factor)" }, { "code": null, "e": 18557, "s": 18548, "text": "Example:" }, { "code": null, "e": 18567, "s": 18559, "text": "Python3" }, { "code": "# This will import Image and ImageEnhance modulesfrom PIL import Image, ImageEnhance # Opening Imageim = Image.open(r\"geek.jpg\") # Creating object of Contrast classim3 = ImageEnhance.Contrast(im) # showing resultant imageim3.enhance(5.0).show()", "e": 18812, "s": 18567, "text": null }, { "code": null, "e": 18824, "s": 18816, "text": "Output:" }, { "code": null, "e": 18920, "s": 18828, "text": "Refer to the below articles to get detailed information about enhancing color and contrast." }, { "code": null, "e": 18991, "s": 18922, "text": "Python PIL | ImageEnhance.Color() and ImageEnhance.Contrast() method" }, { "code": null, "e": 19118, "s": 18993, "text": "ImageEnhance.Brightness() and ImageEnhance.Sharpness() methods are used to adjust the brightness and sharpness of the image." }, { "code": null, "e": 19286, "s": 19120, "text": " ImageEnhance.Brightness() is used to control the brightness of an image. An enhancement factor of 0.0 gives a black image. A factor of 1.0 gives the original image." }, { "code": null, "e": 19296, "s": 19288, "text": "Syntax:" }, { "code": null, "e": 19335, "s": 19298, "text": "obj = ImageEnhance.Brightness(image)" }, { "code": null, "e": 19355, "s": 19335, "text": "obj.enhance(factor)" }, { "code": null, "e": 19366, "s": 19357, "text": "Example:" }, { "code": null, "e": 19376, "s": 19368, "text": "Python3" }, { "code": "# This will import Image and ImageEnhance modulesfrom PIL import Image, ImageEnhance # Opening Imageim = Image.open(r\"geek.jpg\") # Creating object of Brightness classim3 = ImageEnhance.Brightness(im) # showing resultant imageim3.enhance(1.5).show()", "e": 19625, "s": 19376, "text": null }, { "code": null, "e": 19637, "s": 19629, "text": "Output:" }, { "code": null, "e": 19848, "s": 19639, "text": "ImageEnhance.Sharpness() is used to adjust the sharpness of an image. An enhancement factor of 0.0 gives a blurred image, a factor of 1.0 gives the original image, and a factor of 2.0 gives a sharpened image." }, { "code": null, "e": 19858, "s": 19850, "text": "Syntax:" }, { "code": null, "e": 19896, "s": 19860, "text": "obj = ImageEnhance.Sharpness(image)" }, { "code": null, "e": 19916, "s": 19896, "text": "obj.enhance(factor)" }, { "code": null, "e": 19927, "s": 19918, "text": "Example:" }, { "code": null, "e": 19937, "s": 19929, "text": "Python3" }, { "code": "# This will import Image and ImageChops modulesfrom PIL import Image, ImageEnhance # Opening Imageim = Image.open(r\"geek.jpg\") # Creating object of Sharpness classim3 = ImageEnhance.Sharpness(im) # showing resultant imageim3.enhance(5.0).show()", "e": 20182, "s": 19937, "text": null }, { "code": null, "e": 20194, "s": 20186, "text": "Output:" }, { "code": null, "e": 20313, "s": 20198, "text": "Refer to the below articles to get detailed information about enhancing the brightness and sharpness of the image." }, { "code": null, "e": 20390, "s": 20315, "text": "Python PIL | ImageEnhance.Brightness() and ImageEnhance.Sharpness() method" }, { "code": null, "e": 20445, "s": 20390, "text": "Convert the .GIF to .BMP and it’s vice-versa in Python" }, { "code": null, "e": 20501, "s": 20445, "text": "Convert an image into jpg format using Pillow in Python" }, { "code": null, "e": 20533, "s": 20501, "text": "Convert PNG to JPG using Python" }, { "code": null, "e": 20591, "s": 20533, "text": "Convert files from jpg to png and vice versa using Python" }, { "code": null, "e": 20646, "s": 20591, "text": "Convert the .PNG to .GIF and it’s vice-versa in Python" }, { "code": null, "e": 20704, "s": 20646, "text": "Convert files from jpg to gif and vice versa using Python" }, { "code": null, "e": 20748, "s": 20704, "text": "Convert OpenCV image to PIL image in Python" }, { "code": null, "e": 20798, "s": 20748, "text": "Create transparent png image with Python – Pillow" }, { "code": null, "e": 20844, "s": 20798, "text": "Add padding to the image with Python – Pillow" }, { "code": null, "e": 20888, "s": 20844, "text": "Find most used colors in image using Python" }, { "code": null, "e": 20926, "s": 20888, "text": "Python – Color Inversion using Pillow" }, { "code": null, "e": 20970, "s": 20926, "text": "Overlay an image on another image in Python" }, { "code": null, "e": 21017, "s": 20970, "text": "Change image resolution using Pillow in Python" }, { "code": null, "e": 21069, "s": 21017, "text": "Spot the difference between two images using Python" }, { "code": null, "e": 21114, "s": 21069, "text": "How to Extract Text from Images with Python?" }, { "code": null, "e": 21164, "s": 21114, "text": "Create and save animated GIF with Python – Pillow" }, { "code": null, "e": 21209, "s": 21164, "text": "How to compress images using Python and PIL?" }, { "code": null, "e": 21254, "s": 21209, "text": "Python | Using PIL ImageGrab and PyTesseract" }, { "code": null, "e": 21290, "s": 21254, "text": "Floodfill Image using Python-Pillow" }, { "code": null, "e": 21325, "s": 21290, "text": "Python – Channel Drop using Pillow" }, { "code": null, "e": 21361, "s": 21325, "text": "Loading Images in Tkinter using PIL" }, { "code": null, "e": 21398, "s": 21361, "text": "Create Certificates using Python-PIL" }, { "code": null, "e": 21464, "s": 21398, "text": "Python | OCR on All the Images present in a Folder Simultaneously" }, { "code": null, "e": 21531, "s": 21464, "text": "Apply changes to all the images in given folder – Using Python PIL" }, { "code": null, "e": 21549, "s": 21533, "text": "simranarora5sos" }, { "code": null, "e": 21560, "s": 21549, "text": "Python-pil" }, { "code": null, "e": 21567, "s": 21560, "text": "Python" } ]
Difference Between Fork/Join Framework and ExecutorService in Java
01 Jul, 2022 The Fork/Join framework provides fine-grained task execution framework with high performance for Java data parallelism. Its parallel computing engine is used by many higher-level frameworks. The fork/join framework supports a style of parallel programming that solves problems by “Divide and conquer”, in the following manner as shown below: Splitting a task into sub-tasks.Solving sub-tasks in parallelSub-tasks can run in parallel on different cores.Sub-tasks can also run concurrently in different threads on a single core.Waiting for them to completejoin() waits for a sub-task to finishMerging the results.A task uses calls to join() to merge the sub-task results together. Splitting a task into sub-tasks. Solving sub-tasks in parallelSub-tasks can run in parallel on different cores.Sub-tasks can also run concurrently in different threads on a single core. Sub-tasks can run in parallel on different cores. Sub-tasks can also run concurrently in different threads on a single core. Waiting for them to completejoin() waits for a sub-task to finish join() waits for a sub-task to finish Merging the results.A task uses calls to join() to merge the sub-task results together. A task uses calls to join() to merge the sub-task results together. Java Fork-Join Pool Computation Model If a task does not return a result then it just waits for its sub-tasks to complete. Below is a Java program to demonstrate the working of Fork/Join Framework : Java // Java program to demonstrate the working of Fork/Join// Framework // Importing required librariesimport java.io.*;import java.util.concurrent.ForkJoinPool;import java.util.concurrent.RecursiveTask; // Class 1// helper classclass SearchTask extends RecursiveTask<Integer> { // Global variables int array[]; int start, end; int searchElement; // Constructor for initialising globals public SearchTask(int array[], int start, int end, int searchElement) { // This keyword refers to current object itself this.array = array; this.start = start; this.end = end; this.searchElement = searchElement; } // Method // @Override protected Integer compute() { // Returns the count computed by processSearch return processSearch(); } // Method // To count the count of searched element private Integer processSearch() { // Initially count os set to zero int count = 0; // iterating using for loop for (int i = start; i <= end; i++) { // if element is present in array if (array[i] == searchElement) { // Increment the count count++; } } // Returning the count of searched element return count; }} // Class 2// Main classpublic class GFG { // main driver method public static void main(String args[]) { // Custom input array elements int array[] = { 1, 2, 6, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 6 }; // Custom element to be searched in array int searchElement = 6; // initializing starting and ending indices int start = 0; int end = array.length - 1; // Creating object of ForkJoinPool class ForkJoinPool pool = ForkJoinPool.commonPool(); // Now creating object of above class SearchTask task = new SearchTask(array, start, end, searchElement); int result = pool.invoke(task); // Print and display the searched element // If found do display out the number of times it is // found System.out.println(searchElement + " found " + result + " times "); }} 6 found 3 times Now dwelling onto The Java ExecutorService interface extends Executor so we get the one and only execute(Runnable) method defined by Executor. There are a lot more methods in Java ExecutorService compared to Java Executor. Some of the methods in the ExecutorService interface can be used to submit one or more tasks and returns something called a future(essentially a proxy to the result of a computation that runs concurrently and or asynchronously in the background). The ExecutorService works in the following manner as follows: Submit 1+ tasks and return futures for these tasks.Manage the lifecycle of tasks and executor service itself, e.g., interrupts worker threads in a pool.An ExecutorService instance can be in one of three statesRunning: After being created via a factory method.Shutting Down: After being shut down gracefully or abruptly.Terminated: After all, tasks have completed. Submit 1+ tasks and return futures for these tasks. Manage the lifecycle of tasks and executor service itself, e.g., interrupts worker threads in a pool. An ExecutorService instance can be in one of three statesRunning: After being created via a factory method.Shutting Down: After being shut down gracefully or abruptly.Terminated: After all, tasks have completed. Running: After being created via a factory method. Shutting Down: After being shut down gracefully or abruptly. Terminated: After all, tasks have completed. Implementation: Example Java // Java program to demonstrate the working of// ExecutorService // Importing required librariesimport java.io.*;import java.util.Date;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.TimeUnit; // Class 1// helper class extending Runnable interfaceclass Service implements Runnable { // member variable of this class int i; // Constructor of this class public Service(int i) { // Initializing the counter variable this.i = i; } // Method // @Override public void run() { // Printing the counter System.out.println(i + " "); // Try block to check for exceptions try { // Making thread to sleep for 1 second // using the sleep() method Thread.sleep(1000); } // Catch block to handle the exceptions catch (InterruptedException e) { // Print the line number and the corresponding // exception occurred e.printStackTrace(); } }} // Class 2// Main class// ExecutorUtilitypublic class GFG { // Main driver method public static void main(String[] args) { // Creating an object of ExecutorService class to // create fixed size thread pool ExecutorService es = Executors.newFixedThreadPool(5); // Print the time difference before completion System.out.println(new Date()); for (int i = 0; i < 25; i++) { // Executes the given command at some time in // the future es.execute(new Service(i)); } // Executor is shut down so that // its task can be considered complete es.shutdown(); // Print the time difference after completion System.out.println(new Date()); }} Output: Now finally let us conclude the differences between Fork/Join Framework and ExecutorService which ais as follows: gabaa406 surinderdawra388 adnanirshad158 sooda367 ruhelaa48 arorakashish0911 as5853535 simmytarika5 Picked Difference Between Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n01 Jul, 2022" }, { "code": null, "e": 370, "s": 28, "text": "The Fork/Join framework provides fine-grained task execution framework with high performance for Java data parallelism. Its parallel computing engine is used by many higher-level frameworks. The fork/join framework supports a style of parallel programming that solves problems by “Divide and conquer”, in the following manner as shown below:" }, { "code": null, "e": 707, "s": 370, "text": "Splitting a task into sub-tasks.Solving sub-tasks in parallelSub-tasks can run in parallel on different cores.Sub-tasks can also run concurrently in different threads on a single core.Waiting for them to completejoin() waits for a sub-task to finishMerging the results.A task uses calls to join() to merge the sub-task results together." }, { "code": null, "e": 740, "s": 707, "text": "Splitting a task into sub-tasks." }, { "code": null, "e": 893, "s": 740, "text": "Solving sub-tasks in parallelSub-tasks can run in parallel on different cores.Sub-tasks can also run concurrently in different threads on a single core." }, { "code": null, "e": 943, "s": 893, "text": "Sub-tasks can run in parallel on different cores." }, { "code": null, "e": 1018, "s": 943, "text": "Sub-tasks can also run concurrently in different threads on a single core." }, { "code": null, "e": 1084, "s": 1018, "text": "Waiting for them to completejoin() waits for a sub-task to finish" }, { "code": null, "e": 1122, "s": 1084, "text": "join() waits for a sub-task to finish" }, { "code": null, "e": 1210, "s": 1122, "text": "Merging the results.A task uses calls to join() to merge the sub-task results together." }, { "code": null, "e": 1278, "s": 1210, "text": "A task uses calls to join() to merge the sub-task results together." }, { "code": null, "e": 1316, "s": 1278, "text": "Java Fork-Join Pool Computation Model" }, { "code": null, "e": 1401, "s": 1316, "text": "If a task does not return a result then it just waits for its sub-tasks to complete." }, { "code": null, "e": 1477, "s": 1401, "text": "Below is a Java program to demonstrate the working of Fork/Join Framework :" }, { "code": null, "e": 1482, "s": 1477, "text": "Java" }, { "code": "// Java program to demonstrate the working of Fork/Join// Framework // Importing required librariesimport java.io.*;import java.util.concurrent.ForkJoinPool;import java.util.concurrent.RecursiveTask; // Class 1// helper classclass SearchTask extends RecursiveTask<Integer> { // Global variables int array[]; int start, end; int searchElement; // Constructor for initialising globals public SearchTask(int array[], int start, int end, int searchElement) { // This keyword refers to current object itself this.array = array; this.start = start; this.end = end; this.searchElement = searchElement; } // Method // @Override protected Integer compute() { // Returns the count computed by processSearch return processSearch(); } // Method // To count the count of searched element private Integer processSearch() { // Initially count os set to zero int count = 0; // iterating using for loop for (int i = start; i <= end; i++) { // if element is present in array if (array[i] == searchElement) { // Increment the count count++; } } // Returning the count of searched element return count; }} // Class 2// Main classpublic class GFG { // main driver method public static void main(String args[]) { // Custom input array elements int array[] = { 1, 2, 6, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 6 }; // Custom element to be searched in array int searchElement = 6; // initializing starting and ending indices int start = 0; int end = array.length - 1; // Creating object of ForkJoinPool class ForkJoinPool pool = ForkJoinPool.commonPool(); // Now creating object of above class SearchTask task = new SearchTask(array, start, end, searchElement); int result = pool.invoke(task); // Print and display the searched element // If found do display out the number of times it is // found System.out.println(searchElement + \" found \" + result + \" times \"); }}", "e": 3791, "s": 1482, "text": null }, { "code": null, "e": 3808, "s": 3791, "text": "6 found 3 times " }, { "code": null, "e": 4278, "s": 3808, "text": "Now dwelling onto The Java ExecutorService interface extends Executor so we get the one and only execute(Runnable) method defined by Executor. There are a lot more methods in Java ExecutorService compared to Java Executor. Some of the methods in the ExecutorService interface can be used to submit one or more tasks and returns something called a future(essentially a proxy to the result of a computation that runs concurrently and or asynchronously in the background)." }, { "code": null, "e": 4341, "s": 4278, "text": "The ExecutorService works in the following manner as follows: " }, { "code": null, "e": 4705, "s": 4341, "text": "Submit 1+ tasks and return futures for these tasks.Manage the lifecycle of tasks and executor service itself, e.g., interrupts worker threads in a pool.An ExecutorService instance can be in one of three statesRunning: After being created via a factory method.Shutting Down: After being shut down gracefully or abruptly.Terminated: After all, tasks have completed." }, { "code": null, "e": 4757, "s": 4705, "text": "Submit 1+ tasks and return futures for these tasks." }, { "code": null, "e": 4859, "s": 4757, "text": "Manage the lifecycle of tasks and executor service itself, e.g., interrupts worker threads in a pool." }, { "code": null, "e": 5071, "s": 4859, "text": "An ExecutorService instance can be in one of three statesRunning: After being created via a factory method.Shutting Down: After being shut down gracefully or abruptly.Terminated: After all, tasks have completed." }, { "code": null, "e": 5122, "s": 5071, "text": "Running: After being created via a factory method." }, { "code": null, "e": 5183, "s": 5122, "text": "Shutting Down: After being shut down gracefully or abruptly." }, { "code": null, "e": 5228, "s": 5183, "text": "Terminated: After all, tasks have completed." }, { "code": null, "e": 5244, "s": 5228, "text": "Implementation:" }, { "code": null, "e": 5253, "s": 5244, "text": "Example " }, { "code": null, "e": 5258, "s": 5253, "text": "Java" }, { "code": "// Java program to demonstrate the working of// ExecutorService // Importing required librariesimport java.io.*;import java.util.Date;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.TimeUnit; // Class 1// helper class extending Runnable interfaceclass Service implements Runnable { // member variable of this class int i; // Constructor of this class public Service(int i) { // Initializing the counter variable this.i = i; } // Method // @Override public void run() { // Printing the counter System.out.println(i + \" \"); // Try block to check for exceptions try { // Making thread to sleep for 1 second // using the sleep() method Thread.sleep(1000); } // Catch block to handle the exceptions catch (InterruptedException e) { // Print the line number and the corresponding // exception occurred e.printStackTrace(); } }} // Class 2// Main class// ExecutorUtilitypublic class GFG { // Main driver method public static void main(String[] args) { // Creating an object of ExecutorService class to // create fixed size thread pool ExecutorService es = Executors.newFixedThreadPool(5); // Print the time difference before completion System.out.println(new Date()); for (int i = 0; i < 25; i++) { // Executes the given command at some time in // the future es.execute(new Service(i)); } // Executor is shut down so that // its task can be considered complete es.shutdown(); // Print the time difference after completion System.out.println(new Date()); }}", "e": 7095, "s": 5258, "text": null }, { "code": null, "e": 7104, "s": 7095, "text": "Output: " }, { "code": null, "e": 7219, "s": 7104, "text": "Now finally let us conclude the differences between Fork/Join Framework and ExecutorService which ais as follows: " }, { "code": null, "e": 7230, "s": 7221, "text": "gabaa406" }, { "code": null, "e": 7247, "s": 7230, "text": "surinderdawra388" }, { "code": null, "e": 7262, "s": 7247, "text": "adnanirshad158" }, { "code": null, "e": 7271, "s": 7262, "text": "sooda367" }, { "code": null, "e": 7281, "s": 7271, "text": "ruhelaa48" }, { "code": null, "e": 7298, "s": 7281, "text": "arorakashish0911" }, { "code": null, "e": 7308, "s": 7298, "text": "as5853535" }, { "code": null, "e": 7321, "s": 7308, "text": "simmytarika5" }, { "code": null, "e": 7328, "s": 7321, "text": "Picked" }, { "code": null, "e": 7347, "s": 7328, "text": "Difference Between" }, { "code": null, "e": 7352, "s": 7347, "text": "Java" }, { "code": null, "e": 7357, "s": 7352, "text": "Java" } ]
Theming Material Design Buttons in Android with Examples
14 Oct, 2020 Material Design Components (MDC Android) offers designers and developers a way to implement Material Design in their Android application. Developed by a core team of engineers and UX designers at Google, these components enable a reliable development workflow to build beautiful and functional Android applications. If you like the way how the UI elements from Google Material Design Components for android which are designed by Google are pretty awesome, then here are some steps that need to be followed to get them, and one of them is Google Material Design Components (MDC) Buttons. A Button is a user interface that is used to perform some action when clicked or tapped. In the previous article Material Design Buttons in Android with Example, we have discussed four types of Buttons, Contained Button, Outlined Button, Text Button, and Toggle Button. So in this article, we are going to discuss another popular type of Button i.e Theming Material Design Buttons. At the end of this article, one can easily add icons to material design buttons and change or override the default theme of the material design buttons. A sample image is given below to get an idea about what types of Button we are going to create in this article. Step 1: Create a New Project To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Step 2: Add Material design dependency on the app level Gradle file Invoke the following line of code into the dependencies field. implementation ‘com.google.android.material:material:1.3.0-alpha02’ If unable to locate the app level Gradle file refer to the following image to get it under Project view. Go to app > src > main > res > values > styles.xml and change the base application theme. The MaterialComponents contains various action bar theme styles, one may invoke any of the MaterialComponents action bar theme styles, except AppCompat styles. Below is the code for the styles.xml file. XML <resources> <!-- Base application theme. --> <style name="AppTheme" parent="Theme.MaterialComponents.Light.DarkActionBar"> <!-- Customize your theme here. --> <item name="colorPrimary">@color/colorPrimary</item> <item name="colorPrimaryDark">@color/colorPrimaryDark</item> <item name="colorAccent">@color/colorAccent</item> </style> </resources> If unable to locate the styles.xml file refer to the following image. Step 4: Working with the activity_main.xml In this case, a typical 3 material design buttons are invoked. Those are the Contained Button, Outlined Button, Text Button. To know the usage and how to invoke them, one can read the Material Design Buttons in Android with Example article. Invoke the following code in the activity_main.xml file to implement all types of material design buttons. Comments are added inside the code to understand the code in more detail. XML <?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity" tools:ignore="HardcodedText"> <!--Contained Button--> <!--there is no style attribute for contained button--> <!--by default the button itself is a contained button--> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_marginTop="64dp" android:text="Contained Button" /> <!--Outlined Button--> <!--need to carefully invoke the style attribute--> <Button style="@style/Widget.MaterialComponents.Button.OutlinedButton.Icon" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_marginTop="64dp" android:text="Outlined Button" /> <!--Text Button--> <!--need to carefully invoke the style attribute--> <Button style="@style/Widget.MaterialComponents.Button.TextButton.Icon" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_marginTop="64dp" android:text="Text Button" /> </LinearLayout> Output: Run on Emulator Step 1: Import vector icon(s) to the drawable folder To import the vector icons to the drawable folder right click on the drawable folder > goto New > click on Vector Asset. Now select the desired vector from the pop-up window. One can refer to the following image to get a vector icon selector pop-up window. Click on the marked button in the below image, to select the desired vector icons. Step 2: Working with the activity_main.xml file By adding the app:icon attribute in each of the buttons and selecting the desired vector icon from the drawable folder, will add the icon to the material design buttons. So, invoke the following code. XML <?xml version="1.0" encoding="utf-8"?><!--there is need to invoke the app namespace to add icons to material design button--><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity" tools:ignore="HardcodedText"> <!--Contained Button--> <!--there is no style attribute for contained button--> <!--by default the button itself is a contained button--> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_marginTop="64dp" android:text="Contained Button" app:icon="@drawable/ic_add_black_24dp" /> <!--Outlined Button--> <!--need to carefully invoke the style attribute--> <Button style="@style/Widget.MaterialComponents.Button.OutlinedButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_marginTop="64dp" android:text="Outlined Button" app:icon="@drawable/ic_add_black_24dp" /> <!--Text Button--> <!--need to carefully invoke the style attribute--> <Button style="@style/Widget.MaterialComponents.Button.TextButton.Icon" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_marginTop="64dp" android:text="Text Button" app:icon="@drawable/ic_add_black_24dp" /> </LinearLayout> Output: Run on Emulator Here the icons are optional. So, in this case, the icon has been removed. However, the theme can be overridden with or without the icon. Method 1: This method of implementation will affect other material components, as well as material design buttons. Invoke the following code in the styles.xml file to override the default theme of the material design buttons. XML <resources> <!-- Base application theme. --> <style name="AppTheme" parent="Theme.MaterialComponents.Light.DarkActionBar"> <!-- Customize your theme here. --> <item name="colorPrimary">@color/colorPrimary</item> <item name="colorPrimaryDark">@color/colorPrimaryDark</item> <item name="colorAccent">@color/colorAccent</item> <!--this item is to override the fontFamily of the material design buttons--> <item name="textAppearanceButton">@style/TextAppearance.App.Button</item> <!--this item is to override the cornerFamily and cornerSize of the material design buttons--> <item name="shapeAppearanceSmallComponent">@style/ShapeAppearance.App.SmallComponent</item> </style> <!--This overrides the fontFamily and textSize of material design buttons--> <style name="TextAppearance.App.Button" parent="TextAppearance.MaterialComponents.Button"> <item name="fontFamily">sans-serif-black</item> <item name="android:fontFamily">sans-serif</item> <item name="android:textSize">18sp</item> </style> <!--This overrides the cornerFamily and cornerSize of the default material design button--> <style name="ShapeAppearance.App.SmallComponent" parent="ShapeAppearance.MaterialComponents.SmallComponent"> <item name="cornerFamily">cut</item> <item name="cornerSize">8dp</item> </style> </resources> Output: Run on Emulator One can notice the change in the corner cut of 8dp, similar in all the buttons. Note: By using this method if the application contains the material design floating action button, the default theme of those all floating action button overriden by same attributes invoke in above code. Method 2: This method of overriding the default theme of the material design button will affect each of the individual buttons. In this case, different attributes can be overridden for Contained Button, Outlined Button, and Text Button. Invoke the following code in the styles.xml file. XML <resources> <!-- Base application theme. --> <style name="AppTheme" parent="Theme.MaterialComponents.Light.DarkActionBar"> <!-- Customize your theme here. --> <item name="colorPrimary">@color/colorPrimary</item> <item name="colorPrimaryDark">@color/colorPrimaryDark</item> <item name="colorAccent">@color/colorAccent</item> <!--this item is invoked in app theme to override the contained material button--> <item name="materialButtonStyle">@style/myCustomContainedButton</item> <!--this item is invoked in app theme to override the outlined material button--> <item name="materialButtonOutlinedStyle">@style/myCustomOutlinedButton</item> </style> <!--Base application theme ends here--> <!--theming of contained button begins here--> <!--parent name is to be give carefully--> <style name="myCustomContainedButton" parent="Widget.MaterialComponents.Button"> <!--these all styles are implemented outside, because to get all the overridden attributes easily--> <item name="shapeAppearance">@style/customContainedButtonTheme</item> <item name="android:textAppearance">@style/myCustomTextForMaterialButtons</item> </style> <!--overriding cornerSize and cornerFamily of the contained button--> <style name="customContainedButtonTheme"> <item name="cornerFamily">rounded</item> <item name="cornerSize">24dp</item> </style> <!--theming of contained button ends here--> <!--theming of outlined button begins here--> <!--parent name is to be give carefully--> <style name="myCustomOutlinedButton" parent="Widget.MaterialComponents.Button.OutlinedButton"> <!--these all styles are implemented outside, because to get all the overridden attributes easily--> <item name="shapeAppearance">@style/customOutlinedButtonTheme</item> <item name="android:textAppearance">@style/myCustomTextForMaterialButtons</item> </style> <!--overriding cornerSize and cornerFamily of the outlined button--> <style name="customOutlinedButtonTheme"> <item name="cornerFamily">cut</item> <item name="cornerSize">12dp</item> </style> <!--theming of outlined button ends here--> <!--Font family and size of all the buttons in the entire application should be same--> <!--so this child is common for all the material buttons in entire application--> <style name="myCustomTextForMaterialButtons"> <item name="fontFamily">sans-serif-condensed-medium</item> <item name="android:textSize">18sp</item> <item name="android:fontFamily">sans-serif</item> </style> </resources> Note that here the default theme of the text button is not overridden, because it’s not much affected as it has no border and no background color. Only the text color and text font can be changed in the activity_main.xml file itself. After overriding the default theme of all buttons, there is a need to change the style attribute of the outline button in the activity_main.xml file. This needs to be changed because the outlined button is child class of material button, if not invoked the outlined button will be inheriting the style of the contained button. XML <?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity" tools:ignore="HardcodedText"> <!--Contained Button--> <!--there is no style attribute for contained button--> <!--by default the button itself is a contained button--> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_marginTop="64dp" android:text="Contained Button" /> <!--Outlined Button--> <!--need to carefully invoke the style attribute--> <Button style="@style/myCustomOutlinedButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_marginTop="64dp" android:text="Outlined Button" /> <!--Text Button--> <!--need to carefully invoke the style attribute--> <Button style="@style/Widget.MaterialComponents.Button.TextButton.Icon" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_marginTop="64dp" android:text="Text Button" /> </LinearLayout> Output: Run on Emulator android Android Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n14 Oct, 2020" }, { "code": null, "e": 1263, "s": 28, "text": "Material Design Components (MDC Android) offers designers and developers a way to implement Material Design in their Android application. Developed by a core team of engineers and UX designers at Google, these components enable a reliable development workflow to build beautiful and functional Android applications. If you like the way how the UI elements from Google Material Design Components for android which are designed by Google are pretty awesome, then here are some steps that need to be followed to get them, and one of them is Google Material Design Components (MDC) Buttons. A Button is a user interface that is used to perform some action when clicked or tapped. In the previous article Material Design Buttons in Android with Example, we have discussed four types of Buttons, Contained Button, Outlined Button, Text Button, and Toggle Button. So in this article, we are going to discuss another popular type of Button i.e Theming Material Design Buttons. At the end of this article, one can easily add icons to material design buttons and change or override the default theme of the material design buttons. A sample image is given below to get an idea about what types of Button we are going to create in this article. " }, { "code": null, "e": 1292, "s": 1263, "text": "Step 1: Create a New Project" }, { "code": null, "e": 1404, "s": 1292, "text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. " }, { "code": null, "e": 1472, "s": 1404, "text": "Step 2: Add Material design dependency on the app level Gradle file" }, { "code": null, "e": 1535, "s": 1472, "text": "Invoke the following line of code into the dependencies field." }, { "code": null, "e": 1603, "s": 1535, "text": "implementation ‘com.google.android.material:material:1.3.0-alpha02’" }, { "code": null, "e": 1708, "s": 1603, "text": "If unable to locate the app level Gradle file refer to the following image to get it under Project view." }, { "code": null, "e": 2001, "s": 1708, "text": "Go to app > src > main > res > values > styles.xml and change the base application theme. The MaterialComponents contains various action bar theme styles, one may invoke any of the MaterialComponents action bar theme styles, except AppCompat styles. Below is the code for the styles.xml file." }, { "code": null, "e": 2005, "s": 2001, "text": "XML" }, { "code": "<resources> <!-- Base application theme. --> <style name=\"AppTheme\" parent=\"Theme.MaterialComponents.Light.DarkActionBar\"> <!-- Customize your theme here. --> <item name=\"colorPrimary\">@color/colorPrimary</item> <item name=\"colorPrimaryDark\">@color/colorPrimaryDark</item> <item name=\"colorAccent\">@color/colorAccent</item> </style> </resources>", "e": 2391, "s": 2005, "text": null }, { "code": null, "e": 2461, "s": 2391, "text": "If unable to locate the styles.xml file refer to the following image." }, { "code": null, "e": 2504, "s": 2461, "text": "Step 4: Working with the activity_main.xml" }, { "code": null, "e": 2926, "s": 2504, "text": "In this case, a typical 3 material design buttons are invoked. Those are the Contained Button, Outlined Button, Text Button. To know the usage and how to invoke them, one can read the Material Design Buttons in Android with Example article. Invoke the following code in the activity_main.xml file to implement all types of material design buttons. Comments are added inside the code to understand the code in more detail." }, { "code": null, "e": 2930, "s": 2926, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:orientation=\"vertical\" tools:context=\".MainActivity\" tools:ignore=\"HardcodedText\"> <!--Contained Button--> <!--there is no style attribute for contained button--> <!--by default the button itself is a contained button--> <Button android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_gravity=\"center\" android:layout_marginTop=\"64dp\" android:text=\"Contained Button\" /> <!--Outlined Button--> <!--need to carefully invoke the style attribute--> <Button style=\"@style/Widget.MaterialComponents.Button.OutlinedButton.Icon\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_gravity=\"center\" android:layout_marginTop=\"64dp\" android:text=\"Outlined Button\" /> <!--Text Button--> <!--need to carefully invoke the style attribute--> <Button style=\"@style/Widget.MaterialComponents.Button.TextButton.Icon\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_gravity=\"center\" android:layout_marginTop=\"64dp\" android:text=\"Text Button\" /> </LinearLayout>", "e": 4396, "s": 2930, "text": null }, { "code": null, "e": 4420, "s": 4396, "text": "Output: Run on Emulator" }, { "code": null, "e": 4473, "s": 4420, "text": "Step 1: Import vector icon(s) to the drawable folder" }, { "code": null, "e": 4730, "s": 4473, "text": "To import the vector icons to the drawable folder right click on the drawable folder > goto New > click on Vector Asset. Now select the desired vector from the pop-up window. One can refer to the following image to get a vector icon selector pop-up window." }, { "code": null, "e": 4813, "s": 4730, "text": "Click on the marked button in the below image, to select the desired vector icons." }, { "code": null, "e": 4861, "s": 4813, "text": "Step 2: Working with the activity_main.xml file" }, { "code": null, "e": 5062, "s": 4861, "text": "By adding the app:icon attribute in each of the buttons and selecting the desired vector icon from the drawable folder, will add the icon to the material design buttons. So, invoke the following code." }, { "code": null, "e": 5066, "s": 5062, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><!--there is need to invoke the app namespace to add icons to material design button--><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:orientation=\"vertical\" tools:context=\".MainActivity\" tools:ignore=\"HardcodedText\"> <!--Contained Button--> <!--there is no style attribute for contained button--> <!--by default the button itself is a contained button--> <Button android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_gravity=\"center\" android:layout_marginTop=\"64dp\" android:text=\"Contained Button\" app:icon=\"@drawable/ic_add_black_24dp\" /> <!--Outlined Button--> <!--need to carefully invoke the style attribute--> <Button style=\"@style/Widget.MaterialComponents.Button.OutlinedButton\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_gravity=\"center\" android:layout_marginTop=\"64dp\" android:text=\"Outlined Button\" app:icon=\"@drawable/ic_add_black_24dp\" /> <!--Text Button--> <!--need to carefully invoke the style attribute--> <Button style=\"@style/Widget.MaterialComponents.Button.TextButton.Icon\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_gravity=\"center\" android:layout_marginTop=\"64dp\" android:text=\"Text Button\" app:icon=\"@drawable/ic_add_black_24dp\" /> </LinearLayout>", "e": 6853, "s": 5066, "text": null }, { "code": null, "e": 6877, "s": 6853, "text": "Output: Run on Emulator" }, { "code": null, "e": 7014, "s": 6877, "text": "Here the icons are optional. So, in this case, the icon has been removed. However, the theme can be overridden with or without the icon." }, { "code": null, "e": 7024, "s": 7014, "text": "Method 1:" }, { "code": null, "e": 7240, "s": 7024, "text": "This method of implementation will affect other material components, as well as material design buttons. Invoke the following code in the styles.xml file to override the default theme of the material design buttons." }, { "code": null, "e": 7244, "s": 7240, "text": "XML" }, { "code": "<resources> <!-- Base application theme. --> <style name=\"AppTheme\" parent=\"Theme.MaterialComponents.Light.DarkActionBar\"> <!-- Customize your theme here. --> <item name=\"colorPrimary\">@color/colorPrimary</item> <item name=\"colorPrimaryDark\">@color/colorPrimaryDark</item> <item name=\"colorAccent\">@color/colorAccent</item> <!--this item is to override the fontFamily of the material design buttons--> <item name=\"textAppearanceButton\">@style/TextAppearance.App.Button</item> <!--this item is to override the cornerFamily and cornerSize of the material design buttons--> <item name=\"shapeAppearanceSmallComponent\">@style/ShapeAppearance.App.SmallComponent</item> </style> <!--This overrides the fontFamily and textSize of material design buttons--> <style name=\"TextAppearance.App.Button\" parent=\"TextAppearance.MaterialComponents.Button\"> <item name=\"fontFamily\">sans-serif-black</item> <item name=\"android:fontFamily\">sans-serif</item> <item name=\"android:textSize\">18sp</item> </style> <!--This overrides the cornerFamily and cornerSize of the default material design button--> <style name=\"ShapeAppearance.App.SmallComponent\" parent=\"ShapeAppearance.MaterialComponents.SmallComponent\"> <item name=\"cornerFamily\">cut</item> <item name=\"cornerSize\">8dp</item> </style> </resources>", "e": 8659, "s": 7244, "text": null }, { "code": null, "e": 8683, "s": 8659, "text": "Output: Run on Emulator" }, { "code": null, "e": 8763, "s": 8683, "text": "One can notice the change in the corner cut of 8dp, similar in all the buttons." }, { "code": null, "e": 8967, "s": 8763, "text": "Note: By using this method if the application contains the material design floating action button, the default theme of those all floating action button overriden by same attributes invoke in above code." }, { "code": null, "e": 8977, "s": 8967, "text": "Method 2:" }, { "code": null, "e": 9254, "s": 8977, "text": "This method of overriding the default theme of the material design button will affect each of the individual buttons. In this case, different attributes can be overridden for Contained Button, Outlined Button, and Text Button. Invoke the following code in the styles.xml file." }, { "code": null, "e": 9258, "s": 9254, "text": "XML" }, { "code": "<resources> <!-- Base application theme. --> <style name=\"AppTheme\" parent=\"Theme.MaterialComponents.Light.DarkActionBar\"> <!-- Customize your theme here. --> <item name=\"colorPrimary\">@color/colorPrimary</item> <item name=\"colorPrimaryDark\">@color/colorPrimaryDark</item> <item name=\"colorAccent\">@color/colorAccent</item> <!--this item is invoked in app theme to override the contained material button--> <item name=\"materialButtonStyle\">@style/myCustomContainedButton</item> <!--this item is invoked in app theme to override the outlined material button--> <item name=\"materialButtonOutlinedStyle\">@style/myCustomOutlinedButton</item> </style> <!--Base application theme ends here--> <!--theming of contained button begins here--> <!--parent name is to be give carefully--> <style name=\"myCustomContainedButton\" parent=\"Widget.MaterialComponents.Button\"> <!--these all styles are implemented outside, because to get all the overridden attributes easily--> <item name=\"shapeAppearance\">@style/customContainedButtonTheme</item> <item name=\"android:textAppearance\">@style/myCustomTextForMaterialButtons</item> </style> <!--overriding cornerSize and cornerFamily of the contained button--> <style name=\"customContainedButtonTheme\"> <item name=\"cornerFamily\">rounded</item> <item name=\"cornerSize\">24dp</item> </style> <!--theming of contained button ends here--> <!--theming of outlined button begins here--> <!--parent name is to be give carefully--> <style name=\"myCustomOutlinedButton\" parent=\"Widget.MaterialComponents.Button.OutlinedButton\"> <!--these all styles are implemented outside, because to get all the overridden attributes easily--> <item name=\"shapeAppearance\">@style/customOutlinedButtonTheme</item> <item name=\"android:textAppearance\">@style/myCustomTextForMaterialButtons</item> </style> <!--overriding cornerSize and cornerFamily of the outlined button--> <style name=\"customOutlinedButtonTheme\"> <item name=\"cornerFamily\">cut</item> <item name=\"cornerSize\">12dp</item> </style> <!--theming of outlined button ends here--> <!--Font family and size of all the buttons in the entire application should be same--> <!--so this child is common for all the material buttons in entire application--> <style name=\"myCustomTextForMaterialButtons\"> <item name=\"fontFamily\">sans-serif-condensed-medium</item> <item name=\"android:textSize\">18sp</item> <item name=\"android:fontFamily\">sans-serif</item> </style> </resources>", "e": 11921, "s": 9258, "text": null }, { "code": null, "e": 12482, "s": 11921, "text": "Note that here the default theme of the text button is not overridden, because it’s not much affected as it has no border and no background color. Only the text color and text font can be changed in the activity_main.xml file itself. After overriding the default theme of all buttons, there is a need to change the style attribute of the outline button in the activity_main.xml file. This needs to be changed because the outlined button is child class of material button, if not invoked the outlined button will be inheriting the style of the contained button." }, { "code": null, "e": 12486, "s": 12482, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:orientation=\"vertical\" tools:context=\".MainActivity\" tools:ignore=\"HardcodedText\"> <!--Contained Button--> <!--there is no style attribute for contained button--> <!--by default the button itself is a contained button--> <Button android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_gravity=\"center\" android:layout_marginTop=\"64dp\" android:text=\"Contained Button\" /> <!--Outlined Button--> <!--need to carefully invoke the style attribute--> <Button style=\"@style/myCustomOutlinedButton\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_gravity=\"center\" android:layout_marginTop=\"64dp\" android:text=\"Outlined Button\" /> <!--Text Button--> <!--need to carefully invoke the style attribute--> <Button style=\"@style/Widget.MaterialComponents.Button.TextButton.Icon\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_gravity=\"center\" android:layout_marginTop=\"64dp\" android:text=\"Text Button\" /> </LinearLayout>", "e": 13922, "s": 12486, "text": null }, { "code": null, "e": 13946, "s": 13922, "text": "Output: Run on Emulator" }, { "code": null, "e": 13954, "s": 13946, "text": "android" }, { "code": null, "e": 13962, "s": 13954, "text": "Android" }, { "code": null, "e": 13970, "s": 13962, "text": "Android" } ]
Pandas – Find unique values from multiple columns
21 Oct, 2021 Prerequisite: Pandas In this article, we will discuss various methods to obtain unique values from multiple columns of Pandas DataFrame. Method 1: Using pandas Unique() and Concat() methods Pandas series aka columns has a unique() method that filters out only unique values from a column. The first output shows only unique FirstNames. We can extend this method using pandas concat() method and concat all the desired columns into 1 single column and then find the unique of the resultant column. Python3 import pandas as pdimport numpy as np # Creating a custom dataframe.df = pd.DataFrame({'FirstName': ['Arun', 'Navneet', 'Shilpa', 'Prateek', 'Pyare', 'Prateek'], 'LastName': ['Singh', 'Yadav', 'Yadav', 'Shukla', 'Lal', 'Mishra'], 'Age': [26, 25, 25, 27, 28, 30]}) # To get unique values in 1 series/columnprint(f"Unique FN: {df['FirstName'].unique()}") # Extending the idea from 1 column to multiple columnsprint(f"Unique Values from 3 Columns:\{pd.concat([df['FirstName'],df['LastName'],df['Age']]).unique()}") Output: Unique FN: [‘Arun’ ‘Navneet’ ‘Shilpa’ ‘Prateek’ ‘Pyare’] Unique Values from 3 Columns:[‘Arun’ ‘Navneet’ ‘Shilpa’ ‘Prateek’ ‘Pyare’ ‘Singh’ ‘Yadav’ ‘Shukla’ ‘Lal’ ‘Mishra’ 26 25 27 28 30] Method 2: Using Numpy.unique() method With the help of np.unique() method, we can get the unique values from an array given as parameter in np.unique() method. Note: This approach has one limitation i.e. we cannot combine str and numerical columns together, and therefore if such a situation arises where we need to club different datatypes columns together then go for Method 1. Python3 import pandas as pdimport numpy as np # Creating a custom dataframe.df = pd.DataFrame({'FirstName': ['Arun', 'Navneet', 'Shilpa', 'Prateek', 'Pyare', 'Prateek'], 'LastName': ['Singh', 'Yadav', 'Yadav', 'Shukla', 'Lal', 'Mishra'], 'Age': [26, 25, 25, 27, 28, 30]}) print(np.unique(df[['LastName', 'FirstName']].values)) # Will throw error as Age is numerical datatype# and LastName is str# print(np.unique(df[['LastName','Age']].values)) Output: [‘Arun’ ‘Lal’ ‘Mishra’ ‘Navneet’ ‘Prateek’ ‘Pyare’ ‘Shilpa’ ‘Shukla’ ‘Singh’ ‘Yadav’] Method 3: Using Sets in Python The Set has a property that only contains unique values and therefore we convert individual series into a Set object and then take the set union of them. Unlike Method 2 this also works for all datatype combinations. Python3 import pandas as pdimport numpy as np # Creating a custom dataframe.df = pd.DataFrame({'FirstName': ['Arun', 'Navneet', 'Shilpa', 'Prateek', 'Pyare', 'Prateek'], 'LastName': ['Singh', 'Yadav', 'Yadav', 'Shukla', 'Lal', 'Mishra'], 'Age': [26, 25, 25, 27, 28, 30]}) # Typecasting pandas series into set and then# taking set union (|)print(set(df.FirstName) | set(df.LastName) | set(df.Age)) Output: {‘Singh’, ‘Pyare’, ‘Mishra’, 27, ‘Navneet’, ‘Arun’, ‘Lal’, ‘Shukla’, 30, 25, 26, ‘Yadav’, 28, ‘Shilpa’, ‘Prateek’} sumitgumber28 kashishsoda Picked Python Pandas-exercise Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON Python | os.path.join() method How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Get unique values from a list Python | datetime.timedelta() function
[ { "code": null, "e": 28, "s": 0, "text": "\n21 Oct, 2021" }, { "code": null, "e": 50, "s": 28, "text": "Prerequisite: Pandas " }, { "code": null, "e": 166, "s": 50, "text": "In this article, we will discuss various methods to obtain unique values from multiple columns of Pandas DataFrame." }, { "code": null, "e": 219, "s": 166, "text": "Method 1: Using pandas Unique() and Concat() methods" }, { "code": null, "e": 526, "s": 219, "text": "Pandas series aka columns has a unique() method that filters out only unique values from a column. The first output shows only unique FirstNames. We can extend this method using pandas concat() method and concat all the desired columns into 1 single column and then find the unique of the resultant column." }, { "code": null, "e": 534, "s": 526, "text": "Python3" }, { "code": "import pandas as pdimport numpy as np # Creating a custom dataframe.df = pd.DataFrame({'FirstName': ['Arun', 'Navneet', 'Shilpa', 'Prateek', 'Pyare', 'Prateek'], 'LastName': ['Singh', 'Yadav', 'Yadav', 'Shukla', 'Lal', 'Mishra'], 'Age': [26, 25, 25, 27, 28, 30]}) # To get unique values in 1 series/columnprint(f\"Unique FN: {df['FirstName'].unique()}\") # Extending the idea from 1 column to multiple columnsprint(f\"Unique Values from 3 Columns:\\{pd.concat([df['FirstName'],df['LastName'],df['Age']]).unique()}\")", "e": 1185, "s": 534, "text": null }, { "code": null, "e": 1193, "s": 1185, "text": "Output:" }, { "code": null, "e": 1250, "s": 1193, "text": "Unique FN: [‘Arun’ ‘Navneet’ ‘Shilpa’ ‘Prateek’ ‘Pyare’]" }, { "code": null, "e": 1349, "s": 1250, "text": "Unique Values from 3 Columns:[‘Arun’ ‘Navneet’ ‘Shilpa’ ‘Prateek’ ‘Pyare’ ‘Singh’ ‘Yadav’ ‘Shukla’" }, { "code": null, "e": 1381, "s": 1349, "text": " ‘Lal’ ‘Mishra’ 26 25 27 28 30]" }, { "code": null, "e": 1419, "s": 1381, "text": "Method 2: Using Numpy.unique() method" }, { "code": null, "e": 1541, "s": 1419, "text": "With the help of np.unique() method, we can get the unique values from an array given as parameter in np.unique() method." }, { "code": null, "e": 1761, "s": 1541, "text": "Note: This approach has one limitation i.e. we cannot combine str and numerical columns together, and therefore if such a situation arises where we need to club different datatypes columns together then go for Method 1." }, { "code": null, "e": 1769, "s": 1761, "text": "Python3" }, { "code": "import pandas as pdimport numpy as np # Creating a custom dataframe.df = pd.DataFrame({'FirstName': ['Arun', 'Navneet', 'Shilpa', 'Prateek', 'Pyare', 'Prateek'], 'LastName': ['Singh', 'Yadav', 'Yadav', 'Shukla', 'Lal', 'Mishra'], 'Age': [26, 25, 25, 27, 28, 30]}) print(np.unique(df[['LastName', 'FirstName']].values)) # Will throw error as Age is numerical datatype# and LastName is str# print(np.unique(df[['LastName','Age']].values))", "e": 2345, "s": 1769, "text": null }, { "code": null, "e": 2354, "s": 2345, "text": "Output: " }, { "code": null, "e": 2423, "s": 2354, "text": "[‘Arun’ ‘Lal’ ‘Mishra’ ‘Navneet’ ‘Prateek’ ‘Pyare’ ‘Shilpa’ ‘Shukla’" }, { "code": null, "e": 2441, "s": 2423, "text": " ‘Singh’ ‘Yadav’]" }, { "code": null, "e": 2473, "s": 2441, "text": "Method 3: Using Sets in Python " }, { "code": null, "e": 2692, "s": 2473, "text": "The Set has a property that only contains unique values and therefore we convert individual series into a Set object and then take the set union of them. Unlike Method 2 this also works for all datatype combinations. " }, { "code": null, "e": 2700, "s": 2692, "text": "Python3" }, { "code": "import pandas as pdimport numpy as np # Creating a custom dataframe.df = pd.DataFrame({'FirstName': ['Arun', 'Navneet', 'Shilpa', 'Prateek', 'Pyare', 'Prateek'], 'LastName': ['Singh', 'Yadav', 'Yadav', 'Shukla', 'Lal', 'Mishra'], 'Age': [26, 25, 25, 27, 28, 30]}) # Typecasting pandas series into set and then# taking set union (|)print(set(df.FirstName) | set(df.LastName) | set(df.Age))", "e": 3229, "s": 2700, "text": null }, { "code": null, "e": 3238, "s": 3229, "text": "Output: " }, { "code": null, "e": 3353, "s": 3238, "text": "{‘Singh’, ‘Pyare’, ‘Mishra’, 27, ‘Navneet’, ‘Arun’, ‘Lal’, ‘Shukla’, 30, 25, 26, ‘Yadav’, 28, ‘Shilpa’, ‘Prateek’}" }, { "code": null, "e": 3369, "s": 3355, "text": "sumitgumber28" }, { "code": null, "e": 3381, "s": 3369, "text": "kashishsoda" }, { "code": null, "e": 3388, "s": 3381, "text": "Picked" }, { "code": null, "e": 3411, "s": 3388, "text": "Python Pandas-exercise" }, { "code": null, "e": 3425, "s": 3411, "text": "Python-pandas" }, { "code": null, "e": 3432, "s": 3425, "text": "Python" }, { "code": null, "e": 3530, "s": 3432, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3562, "s": 3530, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 3589, "s": 3562, "text": "Python Classes and Objects" }, { "code": null, "e": 3610, "s": 3589, "text": "Python OOPs Concepts" }, { "code": null, "e": 3633, "s": 3610, "text": "Introduction To PYTHON" }, { "code": null, "e": 3664, "s": 3633, "text": "Python | os.path.join() method" }, { "code": null, "e": 3720, "s": 3664, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 3762, "s": 3720, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 3804, "s": 3762, "text": "Check if element exists in list in Python" }, { "code": null, "e": 3843, "s": 3804, "text": "Python | Get unique values from a list" } ]
Introduction to Material Design in Android
27 Oct, 2020 Material Design Components (MDC Android) offers designers and developers a way to implement Material Design in their Android application. Developed by a core team of engineers and UX designers at Google, these components enable a reliable development workflow to build beautiful and functional Android applications. Material design in Android is one of the key features that attracts and engages the customer towards the application. This is a special type of design, which is guided by Google. So in this article, it has been introduced to the basic things that need to be considered before designing or developing any Materialistic Android Application. The topics covered in these articles are Color and themingTypography (Choosing the right font)Material design componentsShaping the material design components Color and theming Typography (Choosing the right font) Material design components Shaping the material design components By choosing the right kind of color combination reflects the application’s brand and style. For example, the application’s main or primary color is the Green, then in the whole application, the green color will be frequently shown. Choosing the color for the application, there are three types of colors to be chosen for developing the android application. Primary Color: This color should be chosen very cautiously because this color is frequently visible in the application components like high emphasis buttons or the button ripple color, and also the top and bottom navigation bar. Secondary Color: This color should be chosen only when there is a low complexity level of the application. This color will be applied to those elements which need a little color accent like the background color for the Floating Action Buttons (FAB), sliders, toggle buttons, chips (Active State), progress bars, etc. Light and Dark variants: These colors are the variants of the primary color. The dark variant of the primary color is set for the status bar and the light variant of the primary color is set for the Floating action button, outline for the edit texts, and where the elements need some color accents the light variant of the primary colors will be set for them. Have a look at the following image when only the primary color is set for the application theme looks like. But according to the complexity of the application, there are various types of color can be chosen. Have a look at the following image, having selected the primary color, with that the Complementary color can be chosen or Analogous color can be chosen or Triadic color can be chosen or Secondary color can be chosen to meet the required style. To make color swatches of their own can visit here. In android, however, the Roboto font meets all the requirements. But too, if the developer wants to customize the application more with the font, the font needs to be chosen where it has all its variants. The variants are the light face, regular face, medium face, and sometimes the dark face. Choosing the font from Google Font is recommended. As it offers a variety of font families, and almost all the fonts have contained all the variants. There are some guidelines that need to be followed by having the font chosen. In this case, the Roboto is chosen for demonstration purposes only. Looking at the following image which is the type scale chart for applying the styles of the fonts for various contexts. The various contexts include captions, Body, Subtitles, Button, captions, etc. In the below image left side column contains the font is chosen, font style, and the font size. The second column contains the preview of the selected context of the font. To select the right kind of font for the application can visit this. Material design components are the components that allow a lot of features for the users and easy to implement for the developers. Have a look at the following image on how material design components stand out in terms of the customization, styling, and look, from the normal UI components. The features offered by the material design components can be implemented in various contexts. One can notice in the above image how the normal button and edit text has adapted to the application’s theme and how the material design button has adapted to the application’s theme. These components can even adapt to the dark theme and change their styles when it is toggled by the user. Have look at the following image to differentiate the behaviors between the material design components and normal UI components. For step-by-step implementations of some of the material design components and their theming can be found in the following articles. Material Design Buttons in Android with ExampleTheming Material Design Buttons in Android with ExamplesFloating Action Button (FAB) in Android with ExampleExtended Floating Action Button in Android with ExampleTheming Floating Action Buttons in Android with ExampleMaterial Design Date Picker in AndroidMore Functionalities of Material Design Date Picker in AndroidMaterial Design EditText in Android with Examples Material Design Buttons in Android with Example Theming Material Design Buttons in Android with Examples Floating Action Button (FAB) in Android with Example Extended Floating Action Button in Android with Example Theming Floating Action Buttons in Android with Example Material Design Date Picker in Android More Functionalities of Material Design Date Picker in Android Material Design EditText in Android with Examples For various material design components can be found here. In material design, there are three types of shaping methods. Cut cornerRounded cornerTriangle edge Cut corner Rounded corner Triangle edge These methods are also can be applied for the material design buttons, text fields, chips, floating action buttons, cards, navigation bars, bottom sheets, etc. These features are available with the Material design components out of the proverbial box. Just need to add the dependency of the material design components and start implementing the styling for material design components. For more of the hard coding, customization refers to this. android Technical Scripter 2020 Android GBlog Technical Scripter Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n27 Oct, 2020" }, { "code": null, "e": 709, "s": 54, "text": "Material Design Components (MDC Android) offers designers and developers a way to implement Material Design in their Android application. Developed by a core team of engineers and UX designers at Google, these components enable a reliable development workflow to build beautiful and functional Android applications. Material design in Android is one of the key features that attracts and engages the customer towards the application. This is a special type of design, which is guided by Google. So in this article, it has been introduced to the basic things that need to be considered before designing or developing any Materialistic Android Application." }, { "code": null, "e": 750, "s": 709, "text": "The topics covered in these articles are" }, { "code": null, "e": 868, "s": 750, "text": "Color and themingTypography (Choosing the right font)Material design componentsShaping the material design components" }, { "code": null, "e": 886, "s": 868, "text": "Color and theming" }, { "code": null, "e": 923, "s": 886, "text": "Typography (Choosing the right font)" }, { "code": null, "e": 950, "s": 923, "text": "Material design components" }, { "code": null, "e": 989, "s": 950, "text": "Shaping the material design components" }, { "code": null, "e": 1346, "s": 989, "text": "By choosing the right kind of color combination reflects the application’s brand and style. For example, the application’s main or primary color is the Green, then in the whole application, the green color will be frequently shown. Choosing the color for the application, there are three types of colors to be chosen for developing the android application." }, { "code": null, "e": 1575, "s": 1346, "text": "Primary Color: This color should be chosen very cautiously because this color is frequently visible in the application components like high emphasis buttons or the button ripple color, and also the top and bottom navigation bar." }, { "code": null, "e": 1892, "s": 1575, "text": "Secondary Color: This color should be chosen only when there is a low complexity level of the application. This color will be applied to those elements which need a little color accent like the background color for the Floating Action Buttons (FAB), sliders, toggle buttons, chips (Active State), progress bars, etc." }, { "code": null, "e": 2360, "s": 1892, "text": "Light and Dark variants: These colors are the variants of the primary color. The dark variant of the primary color is set for the status bar and the light variant of the primary color is set for the Floating action button, outline for the edit texts, and where the elements need some color accents the light variant of the primary colors will be set for them. Have a look at the following image when only the primary color is set for the application theme looks like." }, { "code": null, "e": 2460, "s": 2360, "text": "But according to the complexity of the application, there are various types of color can be chosen." }, { "code": null, "e": 2704, "s": 2460, "text": "Have a look at the following image, having selected the primary color, with that the Complementary color can be chosen or Analogous color can be chosen or Triadic color can be chosen or Secondary color can be chosen to meet the required style." }, { "code": null, "e": 2756, "s": 2704, "text": "To make color swatches of their own can visit here." }, { "code": null, "e": 3050, "s": 2756, "text": "In android, however, the Roboto font meets all the requirements. But too, if the developer wants to customize the application more with the font, the font needs to be chosen where it has all its variants. The variants are the light face, regular face, medium face, and sometimes the dark face." }, { "code": null, "e": 3200, "s": 3050, "text": "Choosing the font from Google Font is recommended. As it offers a variety of font families, and almost all the fonts have contained all the variants." }, { "code": null, "e": 3466, "s": 3200, "text": "There are some guidelines that need to be followed by having the font chosen. In this case, the Roboto is chosen for demonstration purposes only. Looking at the following image which is the type scale chart for applying the styles of the fonts for various contexts." }, { "code": null, "e": 3545, "s": 3466, "text": "The various contexts include captions, Body, Subtitles, Button, captions, etc." }, { "code": null, "e": 3717, "s": 3545, "text": "In the below image left side column contains the font is chosen, font style, and the font size. The second column contains the preview of the selected context of the font." }, { "code": null, "e": 3786, "s": 3717, "text": "To select the right kind of font for the application can visit this." }, { "code": null, "e": 3917, "s": 3786, "text": "Material design components are the components that allow a lot of features for the users and easy to implement for the developers." }, { "code": null, "e": 4077, "s": 3917, "text": "Have a look at the following image on how material design components stand out in terms of the customization, styling, and look, from the normal UI components." }, { "code": null, "e": 4356, "s": 4077, "text": "The features offered by the material design components can be implemented in various contexts. One can notice in the above image how the normal button and edit text has adapted to the application’s theme and how the material design button has adapted to the application’s theme." }, { "code": null, "e": 4591, "s": 4356, "text": "These components can even adapt to the dark theme and change their styles when it is toggled by the user. Have look at the following image to differentiate the behaviors between the material design components and normal UI components." }, { "code": null, "e": 4724, "s": 4591, "text": "For step-by-step implementations of some of the material design components and their theming can be found in the following articles." }, { "code": null, "e": 5139, "s": 4724, "text": "Material Design Buttons in Android with ExampleTheming Material Design Buttons in Android with ExamplesFloating Action Button (FAB) in Android with ExampleExtended Floating Action Button in Android with ExampleTheming Floating Action Buttons in Android with ExampleMaterial Design Date Picker in AndroidMore Functionalities of Material Design Date Picker in AndroidMaterial Design EditText in Android with Examples" }, { "code": null, "e": 5187, "s": 5139, "text": "Material Design Buttons in Android with Example" }, { "code": null, "e": 5244, "s": 5187, "text": "Theming Material Design Buttons in Android with Examples" }, { "code": null, "e": 5297, "s": 5244, "text": "Floating Action Button (FAB) in Android with Example" }, { "code": null, "e": 5353, "s": 5297, "text": "Extended Floating Action Button in Android with Example" }, { "code": null, "e": 5409, "s": 5353, "text": "Theming Floating Action Buttons in Android with Example" }, { "code": null, "e": 5448, "s": 5409, "text": "Material Design Date Picker in Android" }, { "code": null, "e": 5511, "s": 5448, "text": "More Functionalities of Material Design Date Picker in Android" }, { "code": null, "e": 5561, "s": 5511, "text": "Material Design EditText in Android with Examples" }, { "code": null, "e": 5619, "s": 5561, "text": "For various material design components can be found here." }, { "code": null, "e": 5681, "s": 5619, "text": "In material design, there are three types of shaping methods." }, { "code": null, "e": 5719, "s": 5681, "text": "Cut cornerRounded cornerTriangle edge" }, { "code": null, "e": 5730, "s": 5719, "text": "Cut corner" }, { "code": null, "e": 5745, "s": 5730, "text": "Rounded corner" }, { "code": null, "e": 5759, "s": 5745, "text": "Triangle edge" }, { "code": null, "e": 5919, "s": 5759, "text": "These methods are also can be applied for the material design buttons, text fields, chips, floating action buttons, cards, navigation bars, bottom sheets, etc." }, { "code": null, "e": 6144, "s": 5919, "text": "These features are available with the Material design components out of the proverbial box. Just need to add the dependency of the material design components and start implementing the styling for material design components." }, { "code": null, "e": 6203, "s": 6144, "text": "For more of the hard coding, customization refers to this." }, { "code": null, "e": 6211, "s": 6203, "text": "android" }, { "code": null, "e": 6235, "s": 6211, "text": "Technical Scripter 2020" }, { "code": null, "e": 6243, "s": 6235, "text": "Android" }, { "code": null, "e": 6249, "s": 6243, "text": "GBlog" }, { "code": null, "e": 6268, "s": 6249, "text": "Technical Scripter" }, { "code": null, "e": 6276, "s": 6268, "text": "Android" } ]
Python | getattr() method
08 Oct, 2021 Python getattr() function is used to access the attribute value of an object and also gives an option of executing the default value in case of unavailability of the key. Syntax : getattr(obj, key, def) Parameters : obj : The object whose attributes need to be processed. key : The attribute of object def : The default value that need to be printed in case attribute is not found. Returns : Object value if value is available, default value in case attribute is not present and returns AttributeError in case attribute is not present and default value is not specified. Python3 # Python code to demonstrate# working of getattr() # declaring classclass GfG: name = "GeeksforGeeks" age = 24 # initializing object and# python getattr() function callobj = GfG() # use of getattrprint("The name is " + getattr(obj, 'name')) # use of getattr with defaultprint("Description is " + getattr(obj, 'description', 'CS Portal')) # use of getattr without defaultprint("Motto is " + getattr(obj, 'motto')) Output: The name is GeeksforGeeks Description is CS Portal Exception: AttributeError: GfG instance has no attribute 'motto' Python3 # Python code to demonstrate# working of getattr() # declaring classclass GfG: name = "GeeksforGeeks" age = 24 # initializing objectobj = GfG() # use of getattr without defaultprint("Gender is " + getattr(obj, 'gender')) Output: AttributeError: 'GfG' object has no attribute 'gender' Python3 # Python code to demonstrate# performance analysis of getattr()import time # declaring classclass GfG: name = "GeeksforGeeks" age = 24 # initializing objectobj = GfG() # use of getattr to print namestart_getattr = time.time()print("The name is " + getattr(obj, 'name'))print("Time to execute getattr " + str(time.time() - start_getattr)) # use of conventional method to print namestart_obj = time.time()print("The name is " + obj.name)print("Time to execute conventional method " + str(time.time() - start_obj)) Output: The name is GeeksforGeeks Time to execute getattr 5.0067901611328125e-06 The name is GeeksforGeeks Time to execute conventional method 1.1920928955078125e-06 Python3 # Python code to demonstrate# working of getattr() # declaring classclass GfG: name = "GeeksforGeeks" age = 24 # initializing objectobj = GfG() # use of getattr without defaultprint("Motto is " + getattr(obj, 'motto')) Output: AttributeError: 'GfG' object has no attribute 'motto' Python3 # Python code to demonstrate# working of getattr() # declaring classclass GfG: def __init__(self, name, age): self.name = name self.age = age def call(self, x): print(f"{self.name} called with parameters '{x}'") return # initializing objectobj = GfG("Vivek", 10)print(obj)print(GfG)print(getattr(obj,'call')) getattr(obj,'call')('arg') Output: <__main__.GfG object at 0x0000023C1ED92748> <class '__main__.GfG'> <bound method GfG.call of <__main__.GfG object at 0x0000023C1ED92748>> Vivek called with parameters 'arg' Result : Conventional method takes less time than getattr(), but when default values have to be used in case of missing attributes, getattr() is a good choice. Applications: The are many applications of getattr(), a few of them already mentioned in cases of absence of attributes of objects, in web developments where some of the form attributes are optional. Also useful in cases of Machine Learning feature collections in case some features sometimes go missing in data collection. kumar_satyam sagartomar9927 Python-Built-in-functions python-object Python-OOP Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n08 Oct, 2021" }, { "code": null, "e": 224, "s": 53, "text": "Python getattr() function is used to access the attribute value of an object and also gives an option of executing the default value in case of unavailability of the key." }, { "code": null, "e": 256, "s": 224, "text": "Syntax : getattr(obj, key, def)" }, { "code": null, "e": 270, "s": 256, "text": "Parameters : " }, { "code": null, "e": 326, "s": 270, "text": "obj : The object whose attributes need to be processed." }, { "code": null, "e": 356, "s": 326, "text": "key : The attribute of object" }, { "code": null, "e": 436, "s": 356, "text": "def : The default value that need to be printed in case attribute is not found." }, { "code": null, "e": 626, "s": 436, "text": "Returns : Object value if value is available, default value in case attribute is not present and returns AttributeError in case attribute is not present and default value is not specified. " }, { "code": null, "e": 634, "s": 626, "text": "Python3" }, { "code": "# Python code to demonstrate# working of getattr() # declaring classclass GfG: name = \"GeeksforGeeks\" age = 24 # initializing object and# python getattr() function callobj = GfG() # use of getattrprint(\"The name is \" + getattr(obj, 'name')) # use of getattr with defaultprint(\"Description is \" + getattr(obj, 'description', 'CS Portal')) # use of getattr without defaultprint(\"Motto is \" + getattr(obj, 'motto'))", "e": 1119, "s": 634, "text": null }, { "code": null, "e": 1128, "s": 1119, "text": "Output: " }, { "code": null, "e": 1179, "s": 1128, "text": "The name is GeeksforGeeks\nDescription is CS Portal" }, { "code": null, "e": 1191, "s": 1179, "text": "Exception: " }, { "code": null, "e": 1245, "s": 1191, "text": "AttributeError: GfG instance has no attribute 'motto'" }, { "code": null, "e": 1253, "s": 1245, "text": "Python3" }, { "code": "# Python code to demonstrate# working of getattr() # declaring classclass GfG: name = \"GeeksforGeeks\" age = 24 # initializing objectobj = GfG() # use of getattr without defaultprint(\"Gender is \" + getattr(obj, 'gender'))", "e": 1481, "s": 1253, "text": null }, { "code": null, "e": 1489, "s": 1481, "text": "Output:" }, { "code": null, "e": 1544, "s": 1489, "text": "AttributeError: 'GfG' object has no attribute 'gender'" }, { "code": null, "e": 1552, "s": 1544, "text": "Python3" }, { "code": "# Python code to demonstrate# performance analysis of getattr()import time # declaring classclass GfG: name = \"GeeksforGeeks\" age = 24 # initializing objectobj = GfG() # use of getattr to print namestart_getattr = time.time()print(\"The name is \" + getattr(obj, 'name'))print(\"Time to execute getattr \" + str(time.time() - start_getattr)) # use of conventional method to print namestart_obj = time.time()print(\"The name is \" + obj.name)print(\"Time to execute conventional method \" + str(time.time() - start_obj))", "e": 2070, "s": 1552, "text": null }, { "code": null, "e": 2079, "s": 2070, "text": "Output: " }, { "code": null, "e": 2237, "s": 2079, "text": "The name is GeeksforGeeks\nTime to execute getattr 5.0067901611328125e-06\nThe name is GeeksforGeeks\nTime to execute conventional method 1.1920928955078125e-06" }, { "code": null, "e": 2245, "s": 2237, "text": "Python3" }, { "code": "# Python code to demonstrate# working of getattr() # declaring classclass GfG: name = \"GeeksforGeeks\" age = 24 # initializing objectobj = GfG() # use of getattr without defaultprint(\"Motto is \" + getattr(obj, 'motto'))", "e": 2470, "s": 2245, "text": null }, { "code": null, "e": 2478, "s": 2470, "text": "Output:" }, { "code": null, "e": 2532, "s": 2478, "text": "AttributeError: 'GfG' object has no attribute 'motto'" }, { "code": null, "e": 2540, "s": 2532, "text": "Python3" }, { "code": "# Python code to demonstrate# working of getattr() # declaring classclass GfG: def __init__(self, name, age): self.name = name self.age = age def call(self, x): print(f\"{self.name} called with parameters '{x}'\") return # initializing objectobj = GfG(\"Vivek\", 10)print(obj)print(GfG)print(getattr(obj,'call')) getattr(obj,'call')('arg')", "e": 2916, "s": 2540, "text": null }, { "code": null, "e": 2924, "s": 2916, "text": "Output:" }, { "code": null, "e": 3097, "s": 2924, "text": "<__main__.GfG object at 0x0000023C1ED92748>\n<class '__main__.GfG'>\n<bound method GfG.call of <__main__.GfG object at 0x0000023C1ED92748>>\nVivek called with parameters 'arg'" }, { "code": null, "e": 3257, "s": 3097, "text": "Result : Conventional method takes less time than getattr(), but when default values have to be used in case of missing attributes, getattr() is a good choice." }, { "code": null, "e": 3581, "s": 3257, "text": "Applications: The are many applications of getattr(), a few of them already mentioned in cases of absence of attributes of objects, in web developments where some of the form attributes are optional. Also useful in cases of Machine Learning feature collections in case some features sometimes go missing in data collection." }, { "code": null, "e": 3594, "s": 3581, "text": "kumar_satyam" }, { "code": null, "e": 3609, "s": 3594, "text": "sagartomar9927" }, { "code": null, "e": 3635, "s": 3609, "text": "Python-Built-in-functions" }, { "code": null, "e": 3649, "s": 3635, "text": "python-object" }, { "code": null, "e": 3660, "s": 3649, "text": "Python-OOP" }, { "code": null, "e": 3667, "s": 3660, "text": "Python" } ]
Java.util.zip.InflaterInputStream class in Java
26 Jan, 2017 This class implements a stream filter for uncompressing data in the “deflate” compression format. It is also used as the basis for other decompression filters, such as GZIPInputStream.Constructors InflaterInputStream(InputStream in) : Creates a new input stream with a default decompressor and buffer size. InflaterInputStream(InputStream in, Inflater inf) : Creates a new input stream with the specified decompressor and a default buffer size. InflaterInputStream(InputStream in, Inflater inf, int size) : Creates a new input stream with the specified decompressor and buffer size. Methods: int available() : Returns 0 after EOF has been reached, otherwise always return 1.Syntax : public int available() throws IOException Returns: 1 before EOF and 0 after EOF. Throws: IOException Syntax : public int available() throws IOException Returns: 1 before EOF and 0 after EOF. Throws: IOException void close() : Closes this input stream and releases any system resources associated with the stream.Syntax : public void close() throws IOException Throws: IOException Syntax : public void close() throws IOException Throws: IOException protected void fill() : Fills input buffer with more data to decompress.Syntax : protected void fill() throws IOException Throws: IOException Syntax : protected void fill() throws IOException Throws: IOException void mark(int readlimit) : Marks the current position in this input stream.Syntax : public void mark(int readlimit) Parameters: readlimit - the maximum limit of bytes that can be read before the mark position becomes invalid. Syntax : public void mark(int readlimit) Parameters: readlimit - the maximum limit of bytes that can be read before the mark position becomes invalid. boolean markSupported() : Tests if this input stream supports the mark and reset methods.Syntax : public boolean markSupported() Returns: a boolean indicating if this stream type supports the mark and reset methods. Syntax : public boolean markSupported() Returns: a boolean indicating if this stream type supports the mark and reset methods. int read() : Reads a byte of uncompressed data.Syntax : public int read() throws IOException Returns: the byte read, or -1 if end of compressed input is reached Throws: IOException Syntax : public int read() throws IOException Returns: the byte read, or -1 if end of compressed input is reached Throws: IOException int read(byte[] b, int off, int len) : Reads uncompressed data into an array of bytes.Syntax : public int read(byte[] b, int off, int len) throws IOException Parameters: b - the buffer into which the data is read off - the start offset in the destination array b len - the maximum number of bytes read Returns: the actual number of bytes read, or -1 if the end of the compressed input is reached. Throws: NullPointerException IndexOutOfBoundsException ZipException IOException Syntax : public int read(byte[] b, int off, int len) throws IOException Parameters: b - the buffer into which the data is read off - the start offset in the destination array b len - the maximum number of bytes read Returns: the actual number of bytes read, or -1 if the end of the compressed input is reached. Throws: NullPointerException IndexOutOfBoundsException ZipException IOException void reset() : Repositions this stream to the position at the time the mark method was last called on this input stream.Syntax : public void reset() throws IOException Throws: IOException Syntax : public void reset() throws IOException Throws: IOException long skip(long n) : Skips specified number of bytes of uncompressed data.Syntax : public long skip(long n) throws IOException Parameters: n - the number of bytes to skip Returns: the actual number of bytes skipped. Throws: IOException IllegalArgumentException Syntax : public long skip(long n) throws IOException Parameters: n - the number of bytes to skip Returns: the actual number of bytes skipped. Throws: IOException IllegalArgumentException Program: //Java program to demonstrate InflaterInputStreamimport java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.util.zip.DeflaterOutputStream;import java.util.zip.InflaterInputStream; class InflaterInputStreamDemo{ public static void main(String[] args) throws IOException { FileOutputStream fos = new FileOutputStream("file.txt"); //Assign FileOutputStream to DeflaterOutputStream DeflaterOutputStream dos = new DeflaterOutputStream(fos); //write it into DeflaterOutputStream for (int i = 0; i < 10; i++) { dos.write(i); } dos.flush(); dos.close(); FileInputStream fis = new FileInputStream("file.txt"); InflaterInputStream iis = new InflaterInputStream(fis); //illustrating available() method System.out.println(iis.available()); //illustrating mark and markSupported() if (iis.markSupported()) iis.mark(15); else System.out.println(false); //illustrating skip() method iis.skip(3); //illustrating read() for (int i = 0; i <3 ; i++) { System.out.print(iis.read()); } //illustrating read(byte[] b,int off,int len) byte b[]=new byte[4]; for (int i = 0; i <4 ; i++) { iis.read(b,0,4); } for (int i = 0; i < 4; i++) { System.out.print(b[i]); } }} Output: 1 false 3456789 Next Article: Java.util.zip.InflaterOutputStream class in Java This article is contributed by Nishant Sharma. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Java-I/O Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n26 Jan, 2017" }, { "code": null, "e": 225, "s": 28, "text": "This class implements a stream filter for uncompressing data in the “deflate” compression format. It is also used as the basis for other decompression filters, such as GZIPInputStream.Constructors" }, { "code": null, "e": 335, "s": 225, "text": "InflaterInputStream(InputStream in) : Creates a new input stream with a default decompressor and buffer size." }, { "code": null, "e": 473, "s": 335, "text": "InflaterInputStream(InputStream in, Inflater inf) : Creates a new input stream with the specified decompressor and a default buffer size." }, { "code": null, "e": 611, "s": 473, "text": "InflaterInputStream(InputStream in, Inflater inf, int size) : Creates a new input stream with the specified decompressor and buffer size." }, { "code": null, "e": 620, "s": 611, "text": "Methods:" }, { "code": null, "e": 827, "s": 620, "text": "int available() : Returns 0 after EOF has been reached, otherwise always return 1.Syntax : public int available()\n throws IOException\nReturns:\n1 before EOF and 0 after EOF.\nThrows:\nIOException\n" }, { "code": null, "e": 952, "s": 827, "text": "Syntax : public int available()\n throws IOException\nReturns:\n1 before EOF and 0 after EOF.\nThrows:\nIOException\n" }, { "code": null, "e": 1134, "s": 952, "text": "void close() : Closes this input stream and releases any system resources associated with the stream.Syntax : public void close()\n throws IOException\nThrows:\nIOException \n" }, { "code": null, "e": 1215, "s": 1134, "text": "Syntax : public void close()\n throws IOException\nThrows:\nIOException \n" }, { "code": null, "e": 1371, "s": 1215, "text": "protected void fill() : Fills input buffer with more data to decompress.Syntax : protected void fill()\n throws IOException\nThrows:\nIOException\n" }, { "code": null, "e": 1455, "s": 1371, "text": "Syntax : protected void fill()\n throws IOException\nThrows:\nIOException\n" }, { "code": null, "e": 1681, "s": 1455, "text": "void mark(int readlimit) : Marks the current position in this input stream.Syntax : public void mark(int readlimit)\nParameters:\nreadlimit - the maximum limit of bytes that can be read\nbefore the mark position becomes invalid." }, { "code": null, "e": 1832, "s": 1681, "text": "Syntax : public void mark(int readlimit)\nParameters:\nreadlimit - the maximum limit of bytes that can be read\nbefore the mark position becomes invalid." }, { "code": null, "e": 2049, "s": 1832, "text": "boolean markSupported() : Tests if this input stream supports the mark and reset methods.Syntax : public boolean markSupported()\nReturns:\na boolean indicating if this stream type supports the mark and reset methods.\n" }, { "code": null, "e": 2177, "s": 2049, "text": "Syntax : public boolean markSupported()\nReturns:\na boolean indicating if this stream type supports the mark and reset methods.\n" }, { "code": null, "e": 2367, "s": 2177, "text": "int read() : Reads a byte of uncompressed data.Syntax : public int read()\n throws IOException\nReturns:\nthe byte read, or -1 if end of compressed input is reached\nThrows:\nIOException" }, { "code": null, "e": 2510, "s": 2367, "text": "Syntax : public int read()\n throws IOException\nReturns:\nthe byte read, or -1 if end of compressed input is reached\nThrows:\nIOException" }, { "code": null, "e": 3013, "s": 2510, "text": "int read(byte[] b, int off, int len) : Reads uncompressed data into an array of bytes.Syntax : public int read(byte[] b,\n int off,\n int len)\n throws IOException\nParameters:\nb - the buffer into which the data is read\noff - the start offset in the destination array b\nlen - the maximum number of bytes read\nReturns:\nthe actual number of bytes read, or -1 if the end of the compressed input is reached.\nThrows:\nNullPointerException \nIndexOutOfBoundsException \nZipException\nIOException\n" }, { "code": null, "e": 3430, "s": 3013, "text": "Syntax : public int read(byte[] b,\n int off,\n int len)\n throws IOException\nParameters:\nb - the buffer into which the data is read\noff - the start offset in the destination array b\nlen - the maximum number of bytes read\nReturns:\nthe actual number of bytes read, or -1 if the end of the compressed input is reached.\nThrows:\nNullPointerException \nIndexOutOfBoundsException \nZipException\nIOException\n" }, { "code": null, "e": 3630, "s": 3430, "text": "void reset() : Repositions this stream to the position at the time the mark method was last called on this input stream.Syntax : public void reset()\n throws IOException\nThrows:\nIOException\n" }, { "code": null, "e": 3710, "s": 3630, "text": "Syntax : public void reset()\n throws IOException\nThrows:\nIOException\n" }, { "code": null, "e": 3982, "s": 3710, "text": "long skip(long n) : Skips specified number of bytes of uncompressed data.Syntax : public long skip(long n)\n throws IOException\nParameters:\nn - the number of bytes to skip\nReturns:\nthe actual number of bytes skipped.\nThrows:\nIOException \nIllegalArgumentException " }, { "code": null, "e": 4181, "s": 3982, "text": "Syntax : public long skip(long n)\n throws IOException\nParameters:\nn - the number of bytes to skip\nReturns:\nthe actual number of bytes skipped.\nThrows:\nIOException \nIllegalArgumentException " }, { "code": null, "e": 4190, "s": 4181, "text": "Program:" }, { "code": "//Java program to demonstrate InflaterInputStreamimport java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.util.zip.DeflaterOutputStream;import java.util.zip.InflaterInputStream; class InflaterInputStreamDemo{ public static void main(String[] args) throws IOException { FileOutputStream fos = new FileOutputStream(\"file.txt\"); //Assign FileOutputStream to DeflaterOutputStream DeflaterOutputStream dos = new DeflaterOutputStream(fos); //write it into DeflaterOutputStream for (int i = 0; i < 10; i++) { dos.write(i); } dos.flush(); dos.close(); FileInputStream fis = new FileInputStream(\"file.txt\"); InflaterInputStream iis = new InflaterInputStream(fis); //illustrating available() method System.out.println(iis.available()); //illustrating mark and markSupported() if (iis.markSupported()) iis.mark(15); else System.out.println(false); //illustrating skip() method iis.skip(3); //illustrating read() for (int i = 0; i <3 ; i++) { System.out.print(iis.read()); } //illustrating read(byte[] b,int off,int len) byte b[]=new byte[4]; for (int i = 0; i <4 ; i++) { iis.read(b,0,4); } for (int i = 0; i < 4; i++) { System.out.print(b[i]); } }}", "e": 5709, "s": 4190, "text": null }, { "code": null, "e": 5717, "s": 5709, "text": "Output:" }, { "code": null, "e": 5733, "s": 5717, "text": "1\nfalse\n3456789" }, { "code": null, "e": 5796, "s": 5733, "text": "Next Article: Java.util.zip.InflaterOutputStream class in Java" }, { "code": null, "e": 6098, "s": 5796, "text": "This article is contributed by Nishant Sharma. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 6223, "s": 6098, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 6232, "s": 6223, "text": "Java-I/O" }, { "code": null, "e": 6237, "s": 6232, "text": "Java" }, { "code": null, "e": 6242, "s": 6237, "text": "Java" } ]
Sets union() function | Guava | Java
15 Nov, 2018 Guava’s Sets.union() returns an unmodifiable view of the union of two sets. The returned set contains all elements that are contained in either backing set. Iterating over the returned set iterates first over all the elements of set1, then over each element of set2, in order, that is not contained in set1. Syntax: public static <E> Sets.SetView<E> union(Set<? extends E> set1, Set<? extends E> set2) Return Value: This method returns an unmodifiable view of the union of two sets. Example 1: // Java code to show implementation// of Guava's Sets.union() method import com.google.common.collect.Sets;import java.util.Set; class GFG { // Driver's code public static void main(String[] args) { // Creating first set Set<Integer> set1 = Sets.newHashSet(1, 2, 3, 4, 5); // Creating second set Set<Integer> set2 = Sets.newHashSet(3, 5, 7, 9); // Using Guava's Sets.union() method Set<Integer> answer = Sets.union(set1, set2); // Displaying the union of set set1 and set2 System.out.println("Set 1: " + set1); System.out.println("Set 2: " + set2); System.out.println("Set 1 union Set 2: " + answer); }} Set 1: [1, 2, 3, 4, 5] Set 2: [9, 3, 5, 7] Set 1 union Set 2: [1, 2, 3, 4, 5, 9, 7] Example 2: // Java code to show implementation// of Guava's Sets.union() method import com.google.common.collect.Sets;import java.util.Set; class GFG { // Driver's code public static void main(String[] args) { // Creating first set Set<String> set1 = Sets.newHashSet("G", "e", "e", "k", "s"); // Creating second set Set<String> set2 = Sets.newHashSet("g", "f", "G", "e"); // Using Guava's Sets.union() method Set<String> answer = Sets.union(set1, set2); // Displaying the union of set set1 and set2 System.out.println("Set 1: " + set1); System.out.println("Set 2: " + set2); System.out.println("Set 1 union Set 2: " + answer); }} Set 1: [k, s, e, G] Set 2: [e, f, g, G] Set 1 union Set 2: [k, s, e, G, f, g] java-guava java-set Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n15 Nov, 2018" }, { "code": null, "e": 336, "s": 28, "text": "Guava’s Sets.union() returns an unmodifiable view of the union of two sets. The returned set contains all elements that are contained in either backing set. Iterating over the returned set iterates first over all the elements of set1, then over each element of set2, in order, that is not contained in set1." }, { "code": null, "e": 344, "s": 336, "text": "Syntax:" }, { "code": null, "e": 450, "s": 344, "text": "public static <E> \n Sets.SetView<E> \n union(Set<? extends E> set1, \n Set<? extends E> set2)\n" }, { "code": null, "e": 531, "s": 450, "text": "Return Value: This method returns an unmodifiable view of the union of two sets." }, { "code": null, "e": 542, "s": 531, "text": "Example 1:" }, { "code": "// Java code to show implementation// of Guava's Sets.union() method import com.google.common.collect.Sets;import java.util.Set; class GFG { // Driver's code public static void main(String[] args) { // Creating first set Set<Integer> set1 = Sets.newHashSet(1, 2, 3, 4, 5); // Creating second set Set<Integer> set2 = Sets.newHashSet(3, 5, 7, 9); // Using Guava's Sets.union() method Set<Integer> answer = Sets.union(set1, set2); // Displaying the union of set set1 and set2 System.out.println(\"Set 1: \" + set1); System.out.println(\"Set 2: \" + set2); System.out.println(\"Set 1 union Set 2: \" + answer); }}", "e": 1349, "s": 542, "text": null }, { "code": null, "e": 1434, "s": 1349, "text": "Set 1: [1, 2, 3, 4, 5]\nSet 2: [9, 3, 5, 7]\nSet 1 union Set 2: [1, 2, 3, 4, 5, 9, 7]\n" }, { "code": null, "e": 1445, "s": 1434, "text": "Example 2:" }, { "code": "// Java code to show implementation// of Guava's Sets.union() method import com.google.common.collect.Sets;import java.util.Set; class GFG { // Driver's code public static void main(String[] args) { // Creating first set Set<String> set1 = Sets.newHashSet(\"G\", \"e\", \"e\", \"k\", \"s\"); // Creating second set Set<String> set2 = Sets.newHashSet(\"g\", \"f\", \"G\", \"e\"); // Using Guava's Sets.union() method Set<String> answer = Sets.union(set1, set2); // Displaying the union of set set1 and set2 System.out.println(\"Set 1: \" + set1); System.out.println(\"Set 2: \" + set2); System.out.println(\"Set 1 union Set 2: \" + answer); }}", "e": 2267, "s": 1445, "text": null }, { "code": null, "e": 2346, "s": 2267, "text": "Set 1: [k, s, e, G]\nSet 2: [e, f, g, G]\nSet 1 union Set 2: [k, s, e, G, f, g]\n" }, { "code": null, "e": 2357, "s": 2346, "text": "java-guava" }, { "code": null, "e": 2366, "s": 2357, "text": "java-set" }, { "code": null, "e": 2371, "s": 2366, "text": "Java" }, { "code": null, "e": 2376, "s": 2371, "text": "Java" } ]
Heap Sort for decreasing order using min heap
20 Jun, 2022 Given an array of elements, sort the array in decreasing order using min heap. Examples: Input : arr[] = {5, 3, 10, 1} Output : arr[] = {10, 5, 3, 1} Input : arr[] = {1, 50, 100, 25} Output : arr[] = {100, 50, 25, 1} Prerequisite : Heap sort using min heap.Algorithm : 1. Build a min heap from the input data. 2. At this point, the smallest item is stored at the root of the heap. Replace it with the last item of the heap followed by reducing the size of heap by 1. Finally, heapify the root of tree. 3. Repeat above steps while size of heap is greater than 1.Note :Heap Sort using min heap sorts in descending order where as max heap sorts in ascending order C++ Java Python3 C# Javascript // C++ program for implementation of Heap Sort#include <bits/stdc++.h>using namespace std; // To heapify a subtree rooted with node i which is// an index in arr[]. n is size of heapvoid heapify(int arr[], int n, int i){ int smallest = i; // Initialize smallest as root int l = 2 * i + 1; // left = 2*i + 1 int r = 2 * i + 2; // right = 2*i + 2 // If left child is smaller than root if (l < n && arr[l] < arr[smallest]) smallest = l; // If right child is smaller than smallest so far if (r < n && arr[r] < arr[smallest]) smallest = r; // If smallest is not root if (smallest != i) { swap(arr[i], arr[smallest]); // Recursively heapify the affected sub-tree heapify(arr, n, smallest); }} // main function to do heap sortvoid heapSort(int arr[], int n){ // Build heap (rearrange array) for (int i = n / 2 - 1; i >= 0; i--) heapify(arr, n, i); // One by one extract an element from heap for (int i = n - 1; i >= 0; i--) { // Move current root to end swap(arr[0], arr[i]); // call min heapify on the reduced heap heapify(arr, i, 0); }} /* A utility function to print array of size n */void printArray(int arr[], int n){ for (int i = 0; i < n; ++i) cout << arr[i] << " "; cout << "\n";} // Driver programint main(){ int arr[] = { 4, 6, 3, 2, 9 }; int n = sizeof(arr) / sizeof(arr[0]); heapSort(arr, n); cout << "Sorted array is \n"; printArray(arr, n);} // Java program for implementation of Heap Sort import java.io.*; class GFG { // To heapify a subtree rooted with node i which is // an index in arr[]. n is size of heap static void heapify(int arr[], int n, int i) { int smallest = i; // Initialize smallest as root int l = 2 * i + 1; // left = 2*i + 1 int r = 2 * i + 2; // right = 2*i + 2 // If left child is smaller than root if (l < n && arr[l] < arr[smallest]) smallest = l; // If right child is smaller than smallest so far if (r < n && arr[r] < arr[smallest]) smallest = r; // If smallest is not root if (smallest != i) { int temp = arr[i]; arr[i] = arr[smallest]; arr[smallest] = temp; // Recursively heapify the affected sub-tree heapify(arr, n, smallest); } } // main function to do heap sort static void heapSort(int arr[], int n) { // Build heap (rearrange array) for (int i = n / 2 - 1; i >= 0; i--) heapify(arr, n, i); // One by one extract an element from heap for (int i = n - 1; i >= 0; i--) { // Move current root to end int temp = arr[0]; arr[0] = arr[i]; arr[i] = temp; // call min heapify on the reduced heap heapify(arr, i, 0); } } /* A utility function to print array of size n */ static void printArray(int arr[], int n) { for (int i = 0; i < n; ++i) System.out.print(arr[i] + " "); System.out.println(); } // Driver program public static void main(String[] args) { int arr[] = { 4, 6, 3, 2, 9 }; int n = arr.length; heapSort(arr, n); System.out.println("Sorted array is "); printArray(arr, n); }} // This code is contributed by vt_m. # Python3 program for implementation# of Heap Sort # To heapify a subtree rooted with# node i which is an index in arr[].# n is size of heapdef heapify(arr, n, i): smallest = i # Initialize smallest as root l = 2 * i + 1 # left = 2*i + 1 r = 2 * i + 2 # right = 2*i + 2 # If left child is smaller than root if l < n and arr[l] < arr[smallest]: smallest = l # If right child is smaller than # smallest so far if r < n and arr[r] < arr[smallest]: smallest = r # If smallest is not root if smallest != i: (arr[i], arr[smallest]) = (arr[smallest], arr[i]) # Recursively heapify the affected # sub-tree heapify(arr, n, smallest) # main function to do heap sortdef heapSort(arr, n): # Build heap (rearrange array) for i in range(int(n / 2) - 1, -1, -1): heapify(arr, n, i) # One by one extract an element # from heap for i in range(n-1, -1, -1): # Move current root to end # arr[0], arr[i] = arr[i], arr[0] # call min heapify on the reduced heap heapify(arr, i, 0) # A utility function to print# array of size ndef printArray(arr, n): for i in range(n): print(arr[i], end = " ") print() # Driver Codeif __name__ == '__main__': arr = [4, 6, 3, 2, 9] n = len(arr) heapSort(arr, n) print("Sorted array is ") printArray(arr, n) # This code is contributed by PranchalK // C# program for implementation of Heap Sortusing System; class GFG { // To heapify a subtree rooted with // node i which is an index in arr[], // n is size of heap static void heapify(int[] arr, int n, int i) { int smallest = i; // Initialize smallest as root int l = 2 * i + 1; // left = 2*i + 1 int r = 2 * i + 2; // right = 2*i + 2 // If left child is smaller than root if (l < n && arr[l] < arr[smallest]) smallest = l; // If right child is smaller than smallest so far if (r < n && arr[r] < arr[smallest]) smallest = r; // If smallest is not root if (smallest != i) { int temp = arr[i]; arr[i] = arr[smallest]; arr[smallest] = temp; // Recursively heapify the affected sub-tree heapify(arr, n, smallest); } } // main function to do heap sort static void heapSort(int[] arr, int n) { // Build heap (rearrange array) for (int i = n / 2 - 1; i >= 0; i--) heapify(arr, n, i); // One by one extract an element from heap for (int i = n - 1; i >= 0; i--) { // Move current root to end int temp = arr[0]; arr[0] = arr[i]; arr[i] = temp; // call min heapify on the reduced heap heapify(arr, i, 0); } } /* A utility function to print array of size n */ static void printArray(int[] arr, int n) { for (int i = 0; i < n; ++i) Console.Write(arr[i] + " "); Console.WriteLine(); } // Driver program public static void Main() { int[] arr = { 4, 6, 3, 2, 9 }; int n = arr.Length; heapSort(arr, n); Console.WriteLine("Sorted array is "); printArray(arr, n); }} // This code is contributed by vt_m. <script> // Javascript program for implementation of Heap Sort // To heapify a subtree rooted with node i which is// an index in arr[]. n is size of heapfunction heapify(arr, n, i){ var smallest = i; // Initialize smallest as root var l = 2 * i + 1; // left = 2*i + 1 var r = 2 * i + 2; // right = 2*i + 2 // If left child is smaller than root if (l < n && arr[l] < arr[smallest]) smallest = l; // If right child is smaller than smallest so far if (r < n && arr[r] < arr[smallest]) smallest = r; // If smallest is not root if (smallest != i) { [arr[i], arr[smallest]] = [arr[smallest], arr[i]] // Recursively heapify the affected sub-tree heapify(arr, n, smallest); }} // main function to do heap sortfunction heapSort(arr, n){ // Build heap (rearrange array) for (var i = parseInt(n / 2 - 1); i >= 0; i--) heapify(arr, n, i); // One by one extract an element from heap for (var i = n - 1; i >= 0; i--) { // Move current root to end [arr[0], arr[i]] = [arr[i], arr[0]] // call min heapify on the reduced heap heapify(arr, i, 0); }} /* A utility function to print array of size n */function printArray(arr, n){ for (var i = 0; i < n; ++i) document.write( arr[i] + " "); document.write("<br>");} // Driver programvar arr = [4, 6, 3, 2, 9];var n = arr.length;heapSort(arr, n);document.write( "Sorted array is <br>");printArray(arr, n); </script> Sorted array is 9 6 4 3 2 Time complexity:It takes O(logn) for heapify and O(n) for constructing a heap. Hence, the overall time complexity of heap sort using min heap or max heap is O(nlogn) Space complexity: O(n) for call stack PranchalKatiyar rrrtnx rajatkumargla19 simmytarika5 technophpfij Heap Sort Heap Sorting Sorting Heap Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n20 Jun, 2022" }, { "code": null, "e": 143, "s": 52, "text": "Given an array of elements, sort the array in decreasing order using min heap. Examples: " }, { "code": null, "e": 272, "s": 143, "text": "Input : arr[] = {5, 3, 10, 1}\nOutput : arr[] = {10, 5, 3, 1}\n\nInput : arr[] = {1, 50, 100, 25}\nOutput : arr[] = {100, 50, 25, 1}" }, { "code": null, "e": 719, "s": 274, "text": "Prerequisite : Heap sort using min heap.Algorithm : 1. Build a min heap from the input data. 2. At this point, the smallest item is stored at the root of the heap. Replace it with the last item of the heap followed by reducing the size of heap by 1. Finally, heapify the root of tree. 3. Repeat above steps while size of heap is greater than 1.Note :Heap Sort using min heap sorts in descending order where as max heap sorts in ascending order " }, { "code": null, "e": 723, "s": 719, "text": "C++" }, { "code": null, "e": 728, "s": 723, "text": "Java" }, { "code": null, "e": 736, "s": 728, "text": "Python3" }, { "code": null, "e": 739, "s": 736, "text": "C#" }, { "code": null, "e": 750, "s": 739, "text": "Javascript" }, { "code": "// C++ program for implementation of Heap Sort#include <bits/stdc++.h>using namespace std; // To heapify a subtree rooted with node i which is// an index in arr[]. n is size of heapvoid heapify(int arr[], int n, int i){ int smallest = i; // Initialize smallest as root int l = 2 * i + 1; // left = 2*i + 1 int r = 2 * i + 2; // right = 2*i + 2 // If left child is smaller than root if (l < n && arr[l] < arr[smallest]) smallest = l; // If right child is smaller than smallest so far if (r < n && arr[r] < arr[smallest]) smallest = r; // If smallest is not root if (smallest != i) { swap(arr[i], arr[smallest]); // Recursively heapify the affected sub-tree heapify(arr, n, smallest); }} // main function to do heap sortvoid heapSort(int arr[], int n){ // Build heap (rearrange array) for (int i = n / 2 - 1; i >= 0; i--) heapify(arr, n, i); // One by one extract an element from heap for (int i = n - 1; i >= 0; i--) { // Move current root to end swap(arr[0], arr[i]); // call min heapify on the reduced heap heapify(arr, i, 0); }} /* A utility function to print array of size n */void printArray(int arr[], int n){ for (int i = 0; i < n; ++i) cout << arr[i] << \" \"; cout << \"\\n\";} // Driver programint main(){ int arr[] = { 4, 6, 3, 2, 9 }; int n = sizeof(arr) / sizeof(arr[0]); heapSort(arr, n); cout << \"Sorted array is \\n\"; printArray(arr, n);}", "e": 2249, "s": 750, "text": null }, { "code": "// Java program for implementation of Heap Sort import java.io.*; class GFG { // To heapify a subtree rooted with node i which is // an index in arr[]. n is size of heap static void heapify(int arr[], int n, int i) { int smallest = i; // Initialize smallest as root int l = 2 * i + 1; // left = 2*i + 1 int r = 2 * i + 2; // right = 2*i + 2 // If left child is smaller than root if (l < n && arr[l] < arr[smallest]) smallest = l; // If right child is smaller than smallest so far if (r < n && arr[r] < arr[smallest]) smallest = r; // If smallest is not root if (smallest != i) { int temp = arr[i]; arr[i] = arr[smallest]; arr[smallest] = temp; // Recursively heapify the affected sub-tree heapify(arr, n, smallest); } } // main function to do heap sort static void heapSort(int arr[], int n) { // Build heap (rearrange array) for (int i = n / 2 - 1; i >= 0; i--) heapify(arr, n, i); // One by one extract an element from heap for (int i = n - 1; i >= 0; i--) { // Move current root to end int temp = arr[0]; arr[0] = arr[i]; arr[i] = temp; // call min heapify on the reduced heap heapify(arr, i, 0); } } /* A utility function to print array of size n */ static void printArray(int arr[], int n) { for (int i = 0; i < n; ++i) System.out.print(arr[i] + \" \"); System.out.println(); } // Driver program public static void main(String[] args) { int arr[] = { 4, 6, 3, 2, 9 }; int n = arr.length; heapSort(arr, n); System.out.println(\"Sorted array is \"); printArray(arr, n); }} // This code is contributed by vt_m.", "e": 4157, "s": 2249, "text": null }, { "code": "# Python3 program for implementation# of Heap Sort # To heapify a subtree rooted with# node i which is an index in arr[].# n is size of heapdef heapify(arr, n, i): smallest = i # Initialize smallest as root l = 2 * i + 1 # left = 2*i + 1 r = 2 * i + 2 # right = 2*i + 2 # If left child is smaller than root if l < n and arr[l] < arr[smallest]: smallest = l # If right child is smaller than # smallest so far if r < n and arr[r] < arr[smallest]: smallest = r # If smallest is not root if smallest != i: (arr[i], arr[smallest]) = (arr[smallest], arr[i]) # Recursively heapify the affected # sub-tree heapify(arr, n, smallest) # main function to do heap sortdef heapSort(arr, n): # Build heap (rearrange array) for i in range(int(n / 2) - 1, -1, -1): heapify(arr, n, i) # One by one extract an element # from heap for i in range(n-1, -1, -1): # Move current root to end # arr[0], arr[i] = arr[i], arr[0] # call min heapify on the reduced heap heapify(arr, i, 0) # A utility function to print# array of size ndef printArray(arr, n): for i in range(n): print(arr[i], end = \" \") print() # Driver Codeif __name__ == '__main__': arr = [4, 6, 3, 2, 9] n = len(arr) heapSort(arr, n) print(\"Sorted array is \") printArray(arr, n) # This code is contributed by PranchalK", "e": 5626, "s": 4157, "text": null }, { "code": "// C# program for implementation of Heap Sortusing System; class GFG { // To heapify a subtree rooted with // node i which is an index in arr[], // n is size of heap static void heapify(int[] arr, int n, int i) { int smallest = i; // Initialize smallest as root int l = 2 * i + 1; // left = 2*i + 1 int r = 2 * i + 2; // right = 2*i + 2 // If left child is smaller than root if (l < n && arr[l] < arr[smallest]) smallest = l; // If right child is smaller than smallest so far if (r < n && arr[r] < arr[smallest]) smallest = r; // If smallest is not root if (smallest != i) { int temp = arr[i]; arr[i] = arr[smallest]; arr[smallest] = temp; // Recursively heapify the affected sub-tree heapify(arr, n, smallest); } } // main function to do heap sort static void heapSort(int[] arr, int n) { // Build heap (rearrange array) for (int i = n / 2 - 1; i >= 0; i--) heapify(arr, n, i); // One by one extract an element from heap for (int i = n - 1; i >= 0; i--) { // Move current root to end int temp = arr[0]; arr[0] = arr[i]; arr[i] = temp; // call min heapify on the reduced heap heapify(arr, i, 0); } } /* A utility function to print array of size n */ static void printArray(int[] arr, int n) { for (int i = 0; i < n; ++i) Console.Write(arr[i] + \" \"); Console.WriteLine(); } // Driver program public static void Main() { int[] arr = { 4, 6, 3, 2, 9 }; int n = arr.Length; heapSort(arr, n); Console.WriteLine(\"Sorted array is \"); printArray(arr, n); }} // This code is contributed by vt_m.", "e": 7515, "s": 5626, "text": null }, { "code": "<script> // Javascript program for implementation of Heap Sort // To heapify a subtree rooted with node i which is// an index in arr[]. n is size of heapfunction heapify(arr, n, i){ var smallest = i; // Initialize smallest as root var l = 2 * i + 1; // left = 2*i + 1 var r = 2 * i + 2; // right = 2*i + 2 // If left child is smaller than root if (l < n && arr[l] < arr[smallest]) smallest = l; // If right child is smaller than smallest so far if (r < n && arr[r] < arr[smallest]) smallest = r; // If smallest is not root if (smallest != i) { [arr[i], arr[smallest]] = [arr[smallest], arr[i]] // Recursively heapify the affected sub-tree heapify(arr, n, smallest); }} // main function to do heap sortfunction heapSort(arr, n){ // Build heap (rearrange array) for (var i = parseInt(n / 2 - 1); i >= 0; i--) heapify(arr, n, i); // One by one extract an element from heap for (var i = n - 1; i >= 0; i--) { // Move current root to end [arr[0], arr[i]] = [arr[i], arr[0]] // call min heapify on the reduced heap heapify(arr, i, 0); }} /* A utility function to print array of size n */function printArray(arr, n){ for (var i = 0; i < n; ++i) document.write( arr[i] + \" \"); document.write(\"<br>\");} // Driver programvar arr = [4, 6, 3, 2, 9];var n = arr.length;heapSort(arr, n);document.write( \"Sorted array is <br>\");printArray(arr, n); </script>", "e": 8995, "s": 7515, "text": null }, { "code": null, "e": 9022, "s": 8995, "text": "Sorted array is \n9 6 4 3 2" }, { "code": null, "e": 9190, "s": 9024, "text": "Time complexity:It takes O(logn) for heapify and O(n) for constructing a heap. Hence, the overall time complexity of heap sort using min heap or max heap is O(nlogn)" }, { "code": null, "e": 9229, "s": 9190, "text": "Space complexity: O(n) for call stack " }, { "code": null, "e": 9245, "s": 9229, "text": "PranchalKatiyar" }, { "code": null, "e": 9252, "s": 9245, "text": "rrrtnx" }, { "code": null, "e": 9268, "s": 9252, "text": "rajatkumargla19" }, { "code": null, "e": 9281, "s": 9268, "text": "simmytarika5" }, { "code": null, "e": 9294, "s": 9281, "text": "technophpfij" }, { "code": null, "e": 9304, "s": 9294, "text": "Heap Sort" }, { "code": null, "e": 9309, "s": 9304, "text": "Heap" }, { "code": null, "e": 9317, "s": 9309, "text": "Sorting" }, { "code": null, "e": 9325, "s": 9317, "text": "Sorting" }, { "code": null, "e": 9330, "s": 9325, "text": "Heap" } ]
Hierholzer’s Algorithm for directed graph
06 Jul, 2022 Given a directed Eulerian graph, print an Euler circuit. Euler circuit is a path that traverses every edge of a graph, and the path ends on the starting vertex. Examples: Input : Adjacency list for the below graph Output : 0 -> 1 -> 2 -> 0 Input : Adjacency list for the below graph Output : 0 -> 6 -> 4 -> 5 -> 0 -> 1 -> 2 -> 3 -> 4 -> 2 -> 0 Explanation: In both the cases, we can trace the Euler circuit by following the edges as indicated in the output. We have discussed the problem of finding out whether a given graph is Eulerian or not. In this post, an algorithm to print the Eulerian trail or circuit is discussed. The same problem can be solved using Fleury’s Algorithm, however, its complexity is O(E*E). Using Hierholzer’s Algorithm, we can find the circuit/path in O(E), i.e., linear time. Below is the Algorithm: ref ( wiki ). Remember that a directed graph has a Eulerian cycle if the following conditions are true (1) All vertices with nonzero degrees belong to a single strongly connected component. (2) In degree and out-degree of every vertex is the same. The algorithm assumes that the given graph has a Eulerian Circuit. Choose any starting vertex v, and follow a trail of edges from that vertex until returning to v. It is not possible to get stuck at any vertex other than v, because indegree and outdegree of every vertex must be same, when the trail enters another vertex w there must be an unused edge leaving w. The tour formed in this way is a closed tour, but may not cover all the vertices and edges of the initial graph. As long as there exists a vertex u that belongs to the current tour, but that has adjacent edges not part of the tour, start another trail from u, following unused edges until returning to u, and join the tour formed in this way to the previous tour. Thus the idea is to keep following unused edges and removing them until we get stuck. Once we get stuck, we backtrack to the nearest vertex in our current path that has unused edges, and we repeat the process until all the edges have been used. We can use another container to maintain the final path. Let’s take an example: Let the initial directed graph be as below Let's start our path from 0. Thus, curr_path = {0} and circuit = {} Now let's use the edge 0->1 Now, curr_path = {0,1} and circuit = {} similarly we reach up to 2 and then to 0 again as Now, curr_path = {0,1,2} and circuit = {} Then we go to 0, now since 0 haven't got any unused edge we put 0 in circuit and back track till we find an edge We then have curr_path = {0,1,2} and circuit = {0} Similarly, when we backtrack to 2, we don't find any unused edge. Hence put 2 in the circuit and backtrack again. curr_path = {0,1} and circuit = {0,2} After reaching 1 we go to through unused edge 1->3 and then 3->4, 4->1 until all edges have been traversed. The contents of the two containers look as: curr_path = {0,1,3,4,1} and circuit = {0,2} now as all edges have been used, the curr_path is popped one by one into the circuit. Finally, we've circuit = {0,2,1,4,3,1,0} We print the circuit in reverse to obtain the path followed. i.e., 0->1->3->4->1->1->2->0 Below is the implementation for the above approach: C++ Python3 // A C++ program to print Eulerian circuit in given// directed graph using Hierholzer algorithm#include <bits/stdc++.h>using namespace std; void printCircuit(vector< vector<int> > adj){ // adj represents the adjacency list of // the directed graph // edge_count represents the number of edges // emerging from a vertex unordered_map<int,int> edge_count; for (int i=0; i<adj.size(); i++) { //find the count of edges to keep track //of unused edges edge_count[i] = adj[i].size(); } if (!adj.size()) return; //empty graph // Maintain a stack to keep vertices stack<int> curr_path; // vector to store final circuit vector<int> circuit; // start from any vertex curr_path.push(0); int curr_v = 0; // Current vertex while (!curr_path.empty()) { // If there's remaining edge if (edge_count[curr_v]) { // Push the vertex curr_path.push(curr_v); // Find the next vertex using an edge int next_v = adj[curr_v].back(); // and remove that edge edge_count[curr_v]--; adj[curr_v].pop_back(); // Move to next vertex curr_v = next_v; } // back-track to find remaining circuit else { circuit.push_back(curr_v); // Back-tracking curr_v = curr_path.top(); curr_path.pop(); } } // we've got the circuit, now print it in reverse for (int i=circuit.size()-1; i>=0; i--) { cout << circuit[i]; if (i) cout<<" -> "; }} // Driver program to check the above functionint main(){ vector< vector<int> > adj1, adj2; // Input Graph 1 adj1.resize(3); // Build the edges adj1[0].push_back(1); adj1[1].push_back(2); adj1[2].push_back(0); printCircuit(adj1); cout << endl; // Input Graph 2 adj2.resize(7); adj2[0].push_back(1); adj2[0].push_back(6); adj2[1].push_back(2); adj2[2].push_back(0); adj2[2].push_back(3); adj2[3].push_back(4); adj2[4].push_back(2); adj2[4].push_back(5); adj2[5].push_back(0); adj2[6].push_back(4); printCircuit(adj2); return 0;} # Python3 program to print Eulerian circuit in given# directed graph using Hierholzer algorithmdef printCircuit(adj): # adj represents the adjacency list of # the directed graph # edge_count represents the number of edges # emerging from a vertex edge_count = dict() for i in range(len(adj)): # find the count of edges to keep track # of unused edges edge_count[i] = len(adj[i]) if len(adj) == 0: return # empty graph # Maintain a stack to keep vertices curr_path = [] # vector to store final circuit circuit = [] # start from any vertex curr_path.append(0) curr_v = 0 # Current vertex while len(curr_path): # If there's remaining edge if edge_count[curr_v]: # Push the vertex curr_path.append(curr_v) # Find the next vertex using an edge next_v = adj[curr_v][-1] # and remove that edge edge_count[curr_v] -= 1 adj[curr_v].pop() # Move to next vertex curr_v = next_v # back-track to find remaining circuit else: circuit.append(curr_v) # Back-tracking curr_v = curr_path[-1] curr_path.pop() # we've got the circuit, now print it in reverse for i in range(len(circuit) - 1, -1, -1): print(circuit[i], end = "") if i: print(" -> ", end = "") # Driver Codeif __name__ == "__main__": # Input Graph 1 adj1 = [0] * 3 for i in range(3): adj1[i] = [] # Build the edges adj1[0].append(1) adj1[1].append(2) adj1[2].append(0) printCircuit(adj1) print() # Input Graph 2 adj2 = [0] * 7 for i in range(7): adj2[i] = [] adj2[0].append(1) adj2[0].append(6) adj2[1].append(2) adj2[2].append(0) adj2[2].append(3) adj2[3].append(4) adj2[4].append(2) adj2[4].append(5) adj2[5].append(0) adj2[6].append(4) printCircuit(adj2) print() # This code is contributed by# sanjeev2552 0 -> 1 -> 2 -> 0 0 -> 6 -> 4 -> 5 -> 0 -> 1 -> 2 -> 3 -> 4 -> 2 -> 0 Alternate Implementation: Below are the improvements made from the above code The above code kept a count of the number of edges for every vertex. This is unnecessary since we are already maintaining the adjacency list. We simply deleted the creation of edge_count array. In the algorithm we replaced `if edge_count[current_v]` with `if adj[current_v]` The above code pushes the initial node twice to the stack. Though the way he coded the result is correct, this approach is confusing and inefficient. We eliminated this by appending the next vertex to the stack, instead of the current one. In the main part, where the author tests the algorithm, the initialization of the adjacency lists `adj1` and `adj2`were a little weird. That potion is also improved. Python3 # Python3 program to print Eulerian circuit in given# directed graph using Hierholzer algorithmdef printCircuit(adj): # adj represents the adjacency list of # the directed graph if len(adj) == 0: return # empty graph # Maintain a stack to keep vertices # We can start from any vertex, here we start with 0 curr_path = [0] # list to store final circuit circuit = [] while curr_path: curr_v = curr_path[-1] # If there's remaining edge in adjacency list # of the current vertex if adj[curr_v]: # Find and remove the next vertex that is # adjacent to the current vertex next_v = adj[curr_v].pop() # Push the new vertex to the stack curr_path.append(next_v) # back-track to find remaining circuit else: # Remove the current vertex and # put it in the circuit circuit.append(curr_path.pop()) # we've got the circuit, now print it in reverse for i in range(len(circuit) - 1, -1, -1): print(circuit[i], end = "") if i: print(" -> ", end = "") # Driver Codeif __name__ == "__main__": # Input Graph 1 adj1 = [[] for _ in range(3)] # Build the edges adj1[0].append(1) adj1[1].append(2) adj1[2].append(0) printCircuit(adj1) print() # Input Graph 2 adj2 = [[] for _ in range(7)] adj2[0].append(1) adj2[0].append(6) adj2[1].append(2) adj2[2].append(0) adj2[2].append(3) adj2[3].append(4) adj2[4].append(2) adj2[4].append(5) adj2[5].append(0) adj2[6].append(4) printCircuit(adj2) print() 0 -> 1 -> 2 -> 0 0 -> 6 -> 4 -> 5 -> 0 -> 1 -> 2 -> 3 -> 4 -> 2 -> 0 Time Complexity : O(V+E). This article is contributed by Ashutosh Kumar. The article contains also inputs from Nitish Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. sanjeev2552 heruslu Code_Mech surinderdawra388 simmytarika5 hardikkoriintern Euler-Circuit Graph Graph 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": 225, "s": 54, "text": "Given a directed Eulerian graph, print an Euler circuit. Euler circuit is a path that traverses every edge of a graph, and the path ends on the starting vertex. Examples:" }, { "code": null, "e": 528, "s": 225, "text": "Input : Adjacency list for the below graph\n\nOutput : 0 -> 1 -> 2 -> 0 \n\nInput : Adjacency list for the below graph\n\nOutput : 0 -> 6 -> 4 -> 5 -> 0 -> 1 \n -> 2 -> 3 -> 4 -> 2 -> 0 \nExplanation:\nIn both the cases, we can trace the Euler circuit \nby following the edges as indicated in the output." }, { "code": null, "e": 1213, "s": 528, "text": "We have discussed the problem of finding out whether a given graph is Eulerian or not. In this post, an algorithm to print the Eulerian trail or circuit is discussed. The same problem can be solved using Fleury’s Algorithm, however, its complexity is O(E*E). Using Hierholzer’s Algorithm, we can find the circuit/path in O(E), i.e., linear time. Below is the Algorithm: ref ( wiki ). Remember that a directed graph has a Eulerian cycle if the following conditions are true (1) All vertices with nonzero degrees belong to a single strongly connected component. (2) In degree and out-degree of every vertex is the same. The algorithm assumes that the given graph has a Eulerian Circuit." }, { "code": null, "e": 1623, "s": 1213, "text": "Choose any starting vertex v, and follow a trail of edges from that vertex until returning to v. It is not possible to get stuck at any vertex other than v, because indegree and outdegree of every vertex must be same, when the trail enters another vertex w there must be an unused edge leaving w. The tour formed in this way is a closed tour, but may not cover all the vertices and edges of the initial graph." }, { "code": null, "e": 1874, "s": 1623, "text": "As long as there exists a vertex u that belongs to the current tour, but that has adjacent edges not part of the tour, start another trail from u, following unused edges until returning to u, and join the tour formed in this way to the previous tour." }, { "code": null, "e": 2199, "s": 1874, "text": "Thus the idea is to keep following unused edges and removing them until we get stuck. Once we get stuck, we backtrack to the nearest vertex in our current path that has unused edges, and we repeat the process until all the edges have been used. We can use another container to maintain the final path. Let’s take an example:" }, { "code": null, "e": 3215, "s": 2199, "text": "Let the initial directed graph be as below\n\n\nLet's start our path from 0.\nThus, curr_path = {0} and circuit = {}\nNow let's use the edge 0->1 \n\nNow, curr_path = {0,1} and circuit = {}\nsimilarly we reach up to 2 and then to 0 again as\n\nNow, curr_path = {0,1,2} and circuit = {}\nThen we go to 0, now since 0 haven't got any unused\nedge we put 0 in circuit and back track till we find\nan edge\n\nWe then have curr_path = {0,1,2} and circuit = {0}\nSimilarly, when we backtrack to 2, we don't find any \nunused edge. Hence put 2 in the circuit and backtrack \nagain.\n\ncurr_path = {0,1} and circuit = {0,2}\n\nAfter reaching 1 we go to through unused edge 1->3 and \nthen 3->4, 4->1 until all edges have been traversed.\n\nThe contents of the two containers look as:\ncurr_path = {0,1,3,4,1} and circuit = {0,2} \n\nnow as all edges have been used, the curr_path is \npopped one by one into the circuit.\nFinally, we've circuit = {0,2,1,4,3,1,0}\n\nWe print the circuit in reverse to obtain the path followed.\ni.e., 0->1->3->4->1->1->2->0" }, { "code": null, "e": 3268, "s": 3215, "text": "Below is the implementation for the above approach: " }, { "code": null, "e": 3272, "s": 3268, "text": "C++" }, { "code": null, "e": 3280, "s": 3272, "text": "Python3" }, { "code": "// A C++ program to print Eulerian circuit in given// directed graph using Hierholzer algorithm#include <bits/stdc++.h>using namespace std; void printCircuit(vector< vector<int> > adj){ // adj represents the adjacency list of // the directed graph // edge_count represents the number of edges // emerging from a vertex unordered_map<int,int> edge_count; for (int i=0; i<adj.size(); i++) { //find the count of edges to keep track //of unused edges edge_count[i] = adj[i].size(); } if (!adj.size()) return; //empty graph // Maintain a stack to keep vertices stack<int> curr_path; // vector to store final circuit vector<int> circuit; // start from any vertex curr_path.push(0); int curr_v = 0; // Current vertex while (!curr_path.empty()) { // If there's remaining edge if (edge_count[curr_v]) { // Push the vertex curr_path.push(curr_v); // Find the next vertex using an edge int next_v = adj[curr_v].back(); // and remove that edge edge_count[curr_v]--; adj[curr_v].pop_back(); // Move to next vertex curr_v = next_v; } // back-track to find remaining circuit else { circuit.push_back(curr_v); // Back-tracking curr_v = curr_path.top(); curr_path.pop(); } } // we've got the circuit, now print it in reverse for (int i=circuit.size()-1; i>=0; i--) { cout << circuit[i]; if (i) cout<<\" -> \"; }} // Driver program to check the above functionint main(){ vector< vector<int> > adj1, adj2; // Input Graph 1 adj1.resize(3); // Build the edges adj1[0].push_back(1); adj1[1].push_back(2); adj1[2].push_back(0); printCircuit(adj1); cout << endl; // Input Graph 2 adj2.resize(7); adj2[0].push_back(1); adj2[0].push_back(6); adj2[1].push_back(2); adj2[2].push_back(0); adj2[2].push_back(3); adj2[3].push_back(4); adj2[4].push_back(2); adj2[4].push_back(5); adj2[5].push_back(0); adj2[6].push_back(4); printCircuit(adj2); return 0;}", "e": 5506, "s": 3280, "text": null }, { "code": "# Python3 program to print Eulerian circuit in given# directed graph using Hierholzer algorithmdef printCircuit(adj): # adj represents the adjacency list of # the directed graph # edge_count represents the number of edges # emerging from a vertex edge_count = dict() for i in range(len(adj)): # find the count of edges to keep track # of unused edges edge_count[i] = len(adj[i]) if len(adj) == 0: return # empty graph # Maintain a stack to keep vertices curr_path = [] # vector to store final circuit circuit = [] # start from any vertex curr_path.append(0) curr_v = 0 # Current vertex while len(curr_path): # If there's remaining edge if edge_count[curr_v]: # Push the vertex curr_path.append(curr_v) # Find the next vertex using an edge next_v = adj[curr_v][-1] # and remove that edge edge_count[curr_v] -= 1 adj[curr_v].pop() # Move to next vertex curr_v = next_v # back-track to find remaining circuit else: circuit.append(curr_v) # Back-tracking curr_v = curr_path[-1] curr_path.pop() # we've got the circuit, now print it in reverse for i in range(len(circuit) - 1, -1, -1): print(circuit[i], end = \"\") if i: print(\" -> \", end = \"\") # Driver Codeif __name__ == \"__main__\": # Input Graph 1 adj1 = [0] * 3 for i in range(3): adj1[i] = [] # Build the edges adj1[0].append(1) adj1[1].append(2) adj1[2].append(0) printCircuit(adj1) print() # Input Graph 2 adj2 = [0] * 7 for i in range(7): adj2[i] = [] adj2[0].append(1) adj2[0].append(6) adj2[1].append(2) adj2[2].append(0) adj2[2].append(3) adj2[3].append(4) adj2[4].append(2) adj2[4].append(5) adj2[5].append(0) adj2[6].append(4) printCircuit(adj2) print() # This code is contributed by# sanjeev2552", "e": 7541, "s": 5506, "text": null }, { "code": null, "e": 7610, "s": 7541, "text": "0 -> 1 -> 2 -> 0\n0 -> 6 -> 4 -> 5 -> 0 -> 1 -> 2 -> 3 -> 4 -> 2 -> 0" }, { "code": null, "e": 7689, "s": 7610, "text": "Alternate Implementation: Below are the improvements made from the above code " }, { "code": null, "e": 7965, "s": 7689, "text": "The above code kept a count of the number of edges for every vertex. This is unnecessary since we are already maintaining the adjacency list. We simply deleted the creation of edge_count array. In the algorithm we replaced `if edge_count[current_v]` with `if adj[current_v]` " }, { "code": null, "e": 8206, "s": 7965, "text": "The above code pushes the initial node twice to the stack. Though the way he coded the result is correct, this approach is confusing and inefficient. We eliminated this by appending the next vertex to the stack, instead of the current one. " }, { "code": null, "e": 8373, "s": 8206, "text": "In the main part, where the author tests the algorithm, the initialization of the adjacency lists `adj1` and `adj2`were a little weird. That potion is also improved. " }, { "code": null, "e": 8381, "s": 8373, "text": "Python3" }, { "code": "# Python3 program to print Eulerian circuit in given# directed graph using Hierholzer algorithmdef printCircuit(adj): # adj represents the adjacency list of # the directed graph if len(adj) == 0: return # empty graph # Maintain a stack to keep vertices # We can start from any vertex, here we start with 0 curr_path = [0] # list to store final circuit circuit = [] while curr_path: curr_v = curr_path[-1] # If there's remaining edge in adjacency list # of the current vertex if adj[curr_v]: # Find and remove the next vertex that is # adjacent to the current vertex next_v = adj[curr_v].pop() # Push the new vertex to the stack curr_path.append(next_v) # back-track to find remaining circuit else: # Remove the current vertex and # put it in the circuit circuit.append(curr_path.pop()) # we've got the circuit, now print it in reverse for i in range(len(circuit) - 1, -1, -1): print(circuit[i], end = \"\") if i: print(\" -> \", end = \"\") # Driver Codeif __name__ == \"__main__\": # Input Graph 1 adj1 = [[] for _ in range(3)] # Build the edges adj1[0].append(1) adj1[1].append(2) adj1[2].append(0) printCircuit(adj1) print() # Input Graph 2 adj2 = [[] for _ in range(7)] adj2[0].append(1) adj2[0].append(6) adj2[1].append(2) adj2[2].append(0) adj2[2].append(3) adj2[3].append(4) adj2[4].append(2) adj2[4].append(5) adj2[5].append(0) adj2[6].append(4) printCircuit(adj2) print()", "e": 10059, "s": 8381, "text": null }, { "code": null, "e": 10128, "s": 10059, "text": "0 -> 1 -> 2 -> 0\n0 -> 6 -> 4 -> 5 -> 0 -> 1 -> 2 -> 3 -> 4 -> 2 -> 0" }, { "code": null, "e": 10154, "s": 10128, "text": "Time Complexity : O(V+E)." }, { "code": null, "e": 10504, "s": 10154, "text": "This article is contributed by Ashutosh Kumar. The article contains also inputs from Nitish Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 10516, "s": 10504, "text": "sanjeev2552" }, { "code": null, "e": 10524, "s": 10516, "text": "heruslu" }, { "code": null, "e": 10534, "s": 10524, "text": "Code_Mech" }, { "code": null, "e": 10551, "s": 10534, "text": "surinderdawra388" }, { "code": null, "e": 10564, "s": 10551, "text": "simmytarika5" }, { "code": null, "e": 10581, "s": 10564, "text": "hardikkoriintern" }, { "code": null, "e": 10595, "s": 10581, "text": "Euler-Circuit" }, { "code": null, "e": 10601, "s": 10595, "text": "Graph" }, { "code": null, "e": 10607, "s": 10601, "text": "Graph" } ]
Count pairs in array divisible by K | Practice | GeeksforGeeks
Given an array A[] and positive integer K, the task is to count total number of pairs in the array whose sum is divisible by K. Example 1: Input : A[] = {2, 2, 1, 7, 5, 3}, K = 4 Output : 5 Explanation : There are five pairs possible whose sum is divisible by '4' i.e., (2, 2), (1, 7), (7, 5), (1, 3) and (5, 3) Example 2: Input : A[] = {5, 9, 36, 74, 52, 31, 42}, K = 3 Output : 7 Explanation : There are seven pairs whose sum is divisible by 3, i.e, (9, 36), (9,42), (74, 52), (36, 42), (74, 31), (31, 5) and (5, 52). 0 shubhamkhuntia3 weeks ago class Solution { public static long countKdivPairs(int arr[], int n, int k) { HashMap<Integer, Integer> map = new HashMap<>(); for(int val:arr){ int rem = val%k; if(rem<0){ rem+=k; } map.put(rem,map.getOrDefault(rem,0)+1); } long ans = 0; for(int val: arr){ int rem = val%k; if(rem<0){ rem+=k; } if(rem==0){ long pair = (long)map.get(rem); ans += pair*((pair-1)/2); } else if(2*rem == k){ long pair = (long)map.get(rem); ans += pair*((pair-1)/2); } else { long pair = (long)map.get(rem); long pair2 = (long)map.get(k-rem); ans += pair*pair2; } } return ans; } } 0 ankitpahwa4 weeks ago long long countKdivPairs(int A[], int n, int k) { //code here if(k==1) return n*(n-1)/2; unordered_map<int,int>m; vector<int>remainders(n,0); for(int i=0; i<n; i++){ remainders[i] = A[i]%k; } long long ans = 0; for(int i=0; i<n; i++){ int myself = remainders[i]; int target1 = k-remainders[i]; int target2 = -1*remainders[i]; if(m.count(target1)==1 && m[target1]>0) ans += m[target1]; if(m.count(target2)==1 && m[target2]>0) ans += m[target2]; m[myself]++; } return ans; } 0 jayesh294 weeks ago Easy 5 line Java Code :) public static long countKdivPairs(int arr[], int n, int k){ HashMap<Integer,Integer> map = new HashMap<>(); long count = 0; for(int i=0;i<n;i++){ if(map.containsKey((k-(arr[i]%k))%k)) count+=(map.get((k-(arr[i]%k))%k)); map.put(arr[i]%k,map.getOrDefault((arr[i]%k),0)+1); } return count; } 0 zacharibarnes1 month ago Why doesnt my code work on testcase 71 and 72? Javascript: countKdivPairs(arr,n, k){ const remainderArr = new Array(k).fill(0); for(let x of arr){ remainderArr[x%k]++; } let totalCount = (remainderArr[0] * (remainderArr[0]-1))/2; for(let i=1; i<=k/2 && i !==(k-i); i++){ totalCount += remainderArr[k-i] * remainderArr[i]; } if(k%2 == 0) totalCount += (remainderArr[k/2] * (remainderArr[k/2]-1))/2; // console.log(remainderArr); return totalCount; } 0 imranwahid2 months ago C++ solution using hash 0 amruthack11012 months ago JAVA: class Solution { public static int countKdivPairs(int arr[], int n, int k) { HashMap<Integer,Integer> map=new HashMap<>(); int ans=0; for(int i=0;i<n;i++){ if(map.containsKey((k-(arr[i]%k))%k)) ans+=map.get((k-(arr[i]%k))%k); int cV=arr[i]%k; map.put(cV,map.getOrDefault(cV,0)+1 ); } //System.out.print(map); return ans; } } +1 patelneer4032 months ago //perfect sol int countKdivPairs(int A[], int n, int K) { unordered_map<int,int>map; int i,count=0; if(K==1) return n*(n-1)/2; for(i=0;i<n;i++) { map[A[i]%K]++; } for(i=1;i<=K/2;i++) { if(i!=K-i) count+= map[i]*map[K-i]; } if(K%2==0) count+= map[K/2]*(map[K/2]-1)/2; count+= map[0]*(map[0]-1)/2; return count; } +1 sknwd88643 months ago Time Complexity : O(N) Space Complexity : O(K) int countKdivPairs(int arr[], int n, int k) { unordered_map<int, int> mp; int count = 0; for(int i = 0; i < n; i++) { int rem = arr[i] % k; int curr = (k - rem) % k ; auto it = mp.find(curr); if(it != mp.end()) { count += mp[curr]; } mp[rem]++; } return count; } 0 nav575kaur3 months ago int countKdivPairs(int A[], int n, int K) { //code here vector<int> freq(K,0); int ans = 0; for(int i=0; i<n; i++){ //find complement int comp = (K-(A[i]%K))%K; ans = ans+freq[comp]; freq[A[i]%K]++; } return ans; } 0 deepakchill77333 months ago int countKdivPairs(int A[], int n, int K) {unordered_map<int,int> mp; int f=0; for(int i=0;i<n;i++){ if(A[i]%K!=0){ int g=K-(A[i]%K); if(mp[g]>=1){f+=mp[g];}} else{if(mp[0]>=1){f+=mp[0];}} mp[A[i]%K]++; } return f; //code here } We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 366, "s": 238, "text": "Given an array A[] and positive integer K, the task is to count total number of pairs in the array whose sum is divisible by K." }, { "code": null, "e": 377, "s": 366, "text": "Example 1:" }, { "code": null, "e": 553, "s": 377, "text": "Input : \nA[] = {2, 2, 1, 7, 5, 3}, K = 4\nOutput : 5\nExplanation : \nThere are five pairs possible whose sum\nis divisible by '4' i.e., (2, 2), \n(1, 7), (7, 5), (1, 3) and (5, 3)" }, { "code": null, "e": 564, "s": 553, "text": "Example 2:" }, { "code": null, "e": 767, "s": 564, "text": "Input : \nA[] = {5, 9, 36, 74, 52, 31, 42}, K = 3\nOutput : 7 \nExplanation : \nThere are seven pairs whose sum is divisible by 3, \ni.e, (9, 36), (9,42), (74, 52), (36, 42), (74, 31), \n(31, 5) and (5, 52).\n" }, { "code": null, "e": 769, "s": 767, "text": "0" }, { "code": null, "e": 795, "s": 769, "text": "shubhamkhuntia3 weeks ago" }, { "code": null, "e": 1496, "s": 795, "text": "class Solution\n{\n public static long countKdivPairs(int arr[], int n, int k)\n {\n HashMap<Integer, Integer> map = new HashMap<>();\n\t\tfor(int val:arr){\n\t\t\tint rem = val%k;\n\t\t\tif(rem<0){\n\t\t\t rem+=k;\n\t\t\t}\n\t\t\tmap.put(rem,map.getOrDefault(rem,0)+1);\n\t\t}\n\t\tlong ans = 0;\n\t\tfor(int val: arr){\n\t\t\tint rem = val%k; \n\t\t\tif(rem<0){\n\t\t\t rem+=k;\n\t\t\t}\n\t\t\tif(rem==0){\n\t\t\t\t\tlong pair = (long)map.get(rem);\n\t\t\t\t\tans += pair*((pair-1)/2);\n\t\t\t} else if(2*rem == k){\n\t\t\t\t\n\t\t\t\t\tlong pair = (long)map.get(rem);\n\t\t\t\t\tans += pair*((pair-1)/2);\n\t\t\t\t\n\t\t\t} else {\n\t\t\t\t\n\t\t\t\t\tlong pair = (long)map.get(rem);\n\t\t\t\t\tlong pair2 = (long)map.get(k-rem);\n\t\t\t\t\tans += pair*pair2;\n\t\t\t\t\n\t\t\t}\n\t\t\t\n\t\t}\n\t\treturn ans;\n }\n}" }, { "code": null, "e": 1498, "s": 1496, "text": "0" }, { "code": null, "e": 1520, "s": 1498, "text": "ankitpahwa4 weeks ago" }, { "code": null, "e": 2190, "s": 1520, "text": "long long countKdivPairs(int A[], int n, int k)\n {\n //code here\n if(k==1)\n return n*(n-1)/2;\n \n unordered_map<int,int>m;\n vector<int>remainders(n,0);\n for(int i=0; i<n; i++){\n remainders[i] = A[i]%k;\n }\n long long ans = 0;\n for(int i=0; i<n; i++){\n int myself = remainders[i];\n int target1 = k-remainders[i];\n int target2 = -1*remainders[i];\n if(m.count(target1)==1 && m[target1]>0) ans += m[target1];\n if(m.count(target2)==1 && m[target2]>0) ans += m[target2];\n m[myself]++;\n }\n return ans;\n }" }, { "code": null, "e": 2192, "s": 2190, "text": "0" }, { "code": null, "e": 2212, "s": 2192, "text": "jayesh294 weeks ago" }, { "code": null, "e": 2237, "s": 2212, "text": "Easy 5 line Java Code :)" }, { "code": null, "e": 2602, "s": 2237, "text": " public static long countKdivPairs(int arr[], int n, int k){\n HashMap<Integer,Integer> map = new HashMap<>();\n long count = 0;\n for(int i=0;i<n;i++){\n if(map.containsKey((k-(arr[i]%k))%k)) count+=(map.get((k-(arr[i]%k))%k));\n map.put(arr[i]%k,map.getOrDefault((arr[i]%k),0)+1);\n }\n return count;\n }" }, { "code": null, "e": 2604, "s": 2602, "text": "0" }, { "code": null, "e": 2629, "s": 2604, "text": "zacharibarnes1 month ago" }, { "code": null, "e": 2676, "s": 2629, "text": "Why doesnt my code work on testcase 71 and 72?" }, { "code": null, "e": 2688, "s": 2676, "text": "Javascript:" }, { "code": null, "e": 3193, "s": 2688, "text": "\n countKdivPairs(arr,n, k){\n\n const remainderArr = new Array(k).fill(0);\n for(let x of arr){\n remainderArr[x%k]++;\n }\n let totalCount = (remainderArr[0] * (remainderArr[0]-1))/2;\n\n for(let i=1; i<=k/2 && i !==(k-i); i++){\n totalCount += remainderArr[k-i] * remainderArr[i];\n }\n if(k%2 == 0)\n totalCount += (remainderArr[k/2] * (remainderArr[k/2]-1))/2;\n // console.log(remainderArr);\n return totalCount;\n }" }, { "code": null, "e": 3195, "s": 3193, "text": "0" }, { "code": null, "e": 3218, "s": 3195, "text": "imranwahid2 months ago" }, { "code": null, "e": 3242, "s": 3218, "text": "C++ solution using hash" }, { "code": null, "e": 3244, "s": 3242, "text": "0" }, { "code": null, "e": 3270, "s": 3244, "text": "amruthack11012 months ago" }, { "code": null, "e": 3731, "s": 3270, "text": "JAVA:\nclass Solution\n{\n public static int countKdivPairs(int arr[], int n, int k)\n {\n HashMap<Integer,Integer> map=new HashMap<>();\n int ans=0;\n for(int i=0;i<n;i++){ \n if(map.containsKey((k-(arr[i]%k))%k))\n ans+=map.get((k-(arr[i]%k))%k);\n \n int cV=arr[i]%k;\n map.put(cV,map.getOrDefault(cV,0)+1 );\n }\n //System.out.print(map);\n return ans;\n }\n}" }, { "code": null, "e": 3734, "s": 3731, "text": "+1" }, { "code": null, "e": 3759, "s": 3734, "text": "patelneer4032 months ago" }, { "code": null, "e": 3773, "s": 3759, "text": "//perfect sol" }, { "code": null, "e": 4213, "s": 3773, "text": "int countKdivPairs(int A[], int n, int K) { unordered_map<int,int>map; int i,count=0; if(K==1) return n*(n-1)/2; for(i=0;i<n;i++) { map[A[i]%K]++; } for(i=1;i<=K/2;i++) { if(i!=K-i) count+= map[i]*map[K-i]; } if(K%2==0) count+= map[K/2]*(map[K/2]-1)/2; count+= map[0]*(map[0]-1)/2; return count; }" }, { "code": null, "e": 4216, "s": 4213, "text": "+1" }, { "code": null, "e": 4238, "s": 4216, "text": "sknwd88643 months ago" }, { "code": null, "e": 4261, "s": 4238, "text": "Time Complexity : O(N)" }, { "code": null, "e": 4285, "s": 4261, "text": "Space Complexity : O(K)" }, { "code": null, "e": 4783, "s": 4285, "text": "int countKdivPairs(int arr[], int n, int k)\n {\n unordered_map<int, int> mp;\n \n int count = 0;\n \n for(int i = 0; i < n; i++)\n {\n int rem = arr[i] % k;\n \n int curr = (k - rem) % k ;\n \n auto it = mp.find(curr);\n \n if(it != mp.end())\n {\n count += mp[curr];\n }\n \n mp[rem]++;\n }\n \n return count;\n }" }, { "code": null, "e": 4785, "s": 4783, "text": "0" }, { "code": null, "e": 4808, "s": 4785, "text": "nav575kaur3 months ago" }, { "code": null, "e": 5127, "s": 4808, "text": "int countKdivPairs(int A[], int n, int K)\n {\n //code here\n vector<int> freq(K,0);\n int ans = 0;\n for(int i=0; i<n; i++){\n //find complement\n int comp = (K-(A[i]%K))%K;\n ans = ans+freq[comp];\n freq[A[i]%K]++;\n }\n return ans;\n }" }, { "code": null, "e": 5129, "s": 5127, "text": "0" }, { "code": null, "e": 5157, "s": 5129, "text": "deepakchill77333 months ago" }, { "code": null, "e": 5464, "s": 5157, "text": " int countKdivPairs(int A[], int n, int K)\n {unordered_map<int,int> mp;\n \n int f=0;\n for(int i=0;i<n;i++){\n if(A[i]%K!=0){\n int g=K-(A[i]%K);\n if(mp[g]>=1){f+=mp[g];}}\n else{if(mp[0]>=1){f+=mp[0];}}\n mp[A[i]%K]++;\n }\n return f;\n //code here\n }" }, { "code": null, "e": 5610, "s": 5464, "text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?" }, { "code": null, "e": 5646, "s": 5610, "text": " Login to access your submissions. " }, { "code": null, "e": 5656, "s": 5646, "text": "\nProblem\n" }, { "code": null, "e": 5666, "s": 5656, "text": "\nContest\n" }, { "code": null, "e": 5729, "s": 5666, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 5877, "s": 5729, "text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 6085, "s": 5877, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints." }, { "code": null, "e": 6191, "s": 6085, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Bead Sort | A Natural Sorting Algorithm - GeeksforGeeks
27 May, 2018 Also known as Gravity sort, this algorithm was inspired from natural phenomenons and was designed keeping in mind objects(or beads) falling under the influence of gravity. The Idea: Positive numbers are represented by a set of beads like those on an abacus. Sorting of {7, 2, 1, 4, 2} using Bead Sort. Beads fall down one by one if there is space below. Like in the image above the beads represent the following numbers from top to bottom : 7, 2, 1, 4, 2. Now, imagine that this is the position of the beads at time t = 0 and with every passing second the beads will fall down by one level provided there is no bead already present below them. In such a case, they just rest upon the bead below them.(Rods are numbered from left to right and levels are numbered from the bottom as 1, 2, .......... n.)Now, at time t = 1 the bottom 2 beads in the first two rods from the left stay at their positions while the second bead from the top from the second rod comes down by one level to rest upon the bead below it. The beads in the 3rd and 4th rod at level 2 come down to level 1. Simultaneously, the beads in the rods 3 to 7 come down by one level. Now, the numbers from top to bottom become: 2, 6, 2, 2, 4.This goes on till time t = 4 where we get the sorted sequence of numbers from top to bottom which is: 1, 2, 2, 4, 7. Like in the image above the beads represent the following numbers from top to bottom : 7, 2, 1, 4, 2. Now, imagine that this is the position of the beads at time t = 0 and with every passing second the beads will fall down by one level provided there is no bead already present below them. In such a case, they just rest upon the bead below them.(Rods are numbered from left to right and levels are numbered from the bottom as 1, 2, .......... n.) Now, at time t = 1 the bottom 2 beads in the first two rods from the left stay at their positions while the second bead from the top from the second rod comes down by one level to rest upon the bead below it. The beads in the 3rd and 4th rod at level 2 come down to level 1. Simultaneously, the beads in the rods 3 to 7 come down by one level. Now, the numbers from top to bottom become: 2, 6, 2, 2, 4. This goes on till time t = 4 where we get the sorted sequence of numbers from top to bottom which is: 1, 2, 2, 4, 7. Why is it called so? When one tries to visualize this algorithm it appears as if beads are falling down under the influence of gravity to the bottom-most level they can reach resulting the set of beads being arranged in a descending order from the ground up. If you are having trouble visualizing this visit this link Lets say that we have to sort the numbers 3, 4, 1, 2. The above algorithm would work like this. Bead Sort Working Below is the code, try to implement it yourself before looking at the code. The Code: // C++ program to implement gravity/bead sort#include <bits/stdc++.h>using namespace std; #define BEAD(i, j) beads[i * max + j] // function to perform the above algorithmvoid beadSort(int *a, int len){ // Find the maximum element int max = a[0]; for (int i = 1; i < len; i++) if (a[i] > max) max = a[i]; // allocating memory unsigned char beads[max*len]; memset(beads, 0, sizeof(beads)); // mark the beads for (int i = 0; i < len; i++) for (int j = 0; j < a[i]; j++) BEAD(i, j) = 1; for (int j = 0; j < max; j++) { // count how many beads are on each post int sum = 0; for (int i=0; i < len; i++) { sum += BEAD(i, j); BEAD(i, j) = 0; } // Move beads down for (int i = len - sum; i < len; i++) BEAD(i, j) = 1; } // Put sorted values in array using beads for (int i = 0; i < len; i++) { int j; for (j = 0; j < max && BEAD(i, j); j++); a[i] = j; }} // driver function to test the algorithmint main(){ int a[] = {5, 3, 1, 7, 4, 1, 1, 20}; int len = sizeof(a)/sizeof(a[0]); beadSort(a, len); for (int i = 0; i < len; i++) printf("%d ", a[i]); return 0;} Output: 1 1 1 3 4 5 7 20 Time Complexity:The algorithm’s run–time complexity ranges from O(1) to O(S) (S is the sum of the input integers) depending on the user’s perspective. Finally, three possible implementations are suggested. O(1) : Dropping all beads together as a single (simultaneous) operation. This complexity cannot be implemented in practice.O(): In a realistic physical model that uses gravity, the time it takes to let the beads fall is proportional to the square root of the maximum height, which is proportional to n.O(n) : Dropping the row of beads in the frame (representing a number) as a distinct operation since the number of rows is equal to n.O(S) : Dropping each and every bead’ as a separate operation since S is the sum of all the beads. O(1) : Dropping all beads together as a single (simultaneous) operation. This complexity cannot be implemented in practice. O(): In a realistic physical model that uses gravity, the time it takes to let the beads fall is proportional to the square root of the maximum height, which is proportional to n. O(n) : Dropping the row of beads in the frame (representing a number) as a distinct operation since the number of rows is equal to n. O(S) : Dropping each and every bead’ as a separate operation since S is the sum of all the beads. Like the Pigeonhole sort, bead sort is unusual in that in worst case it can perform faster than O(), the fastest performance possible for a comparison sort in worst case. This is possible because the key for a bead sort is always a positive integer and bead sort exploits its structure. Space Complexity: Bead sort is the record-holder as for waste. The costs for the extra memory exceed the costs for storing the array itself. Its memory complexity is O() References: https://www.wikiwand.com/en/Bead_sort https://kukuruku.co/post/bead-sort/ https://rosettacode.org/wiki/Sorting_algorithms/Bead_sort https://www.cs.auckland.ac.nz/~mjd/misc/BeadSort5.pdf This article is contributed by Palash Nigam . If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Pigeonhole Principle Sorting Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments C++ Program for QuickSort Stability in sorting algorithms Quickselect Algorithm Quick Sort vs Merge Sort QuickSort using Random Pivoting Sorting in Java Check if two arrays are equal or not Binary Insertion Sort Recursive Bubble Sort Sort a nearly sorted (or K sorted) array
[ { "code": null, "e": 24078, "s": 24050, "text": "\n27 May, 2018" }, { "code": null, "e": 24250, "s": 24078, "text": "Also known as Gravity sort, this algorithm was inspired from natural phenomenons and was designed keeping in mind objects(or beads) falling under the influence of gravity." }, { "code": null, "e": 24336, "s": 24250, "text": "The Idea: Positive numbers are represented by a set of beads like those on an abacus." }, { "code": null, "e": 24432, "s": 24336, "text": "Sorting of {7, 2, 1, 4, 2} using Bead Sort. Beads fall down one by one if there is space below." }, { "code": null, "e": 25398, "s": 24432, "text": "Like in the image above the beads represent the following numbers from top to bottom : 7, 2, 1, 4, 2. Now, imagine that this is the position of the beads at time t = 0 and with every passing second the beads will fall down by one level provided there is no bead already present below them. In such a case, they just rest upon the bead below them.(Rods are numbered from left to right and levels are numbered from the bottom as 1, 2, .......... n.)Now, at time t = 1 the bottom 2 beads in the first two rods from the left stay at their positions while the second bead from the top from the second rod comes down by one level to rest upon the bead below it. The beads in the 3rd and 4th rod at level 2 come down to level 1. Simultaneously, the beads in the rods 3 to 7 come down by one level. Now, the numbers from top to bottom become: 2, 6, 2, 2, 4.This goes on till time t = 4 where we get the sorted sequence of numbers from top to bottom which is: 1, 2, 2, 4, 7." }, { "code": null, "e": 25846, "s": 25398, "text": "Like in the image above the beads represent the following numbers from top to bottom : 7, 2, 1, 4, 2. Now, imagine that this is the position of the beads at time t = 0 and with every passing second the beads will fall down by one level provided there is no bead already present below them. In such a case, they just rest upon the bead below them.(Rods are numbered from left to right and levels are numbered from the bottom as 1, 2, .......... n.)" }, { "code": null, "e": 26249, "s": 25846, "text": "Now, at time t = 1 the bottom 2 beads in the first two rods from the left stay at their positions while the second bead from the top from the second rod comes down by one level to rest upon the bead below it. The beads in the 3rd and 4th rod at level 2 come down to level 1. Simultaneously, the beads in the rods 3 to 7 come down by one level. Now, the numbers from top to bottom become: 2, 6, 2, 2, 4." }, { "code": null, "e": 26366, "s": 26249, "text": "This goes on till time t = 4 where we get the sorted sequence of numbers from top to bottom which is: 1, 2, 2, 4, 7." }, { "code": null, "e": 26387, "s": 26366, "text": "Why is it called so?" }, { "code": null, "e": 26684, "s": 26387, "text": "When one tries to visualize this algorithm it appears as if beads are falling down under the influence of gravity to the bottom-most level they can reach resulting the set of beads being arranged in a descending order from the ground up. If you are having trouble visualizing this visit this link" }, { "code": null, "e": 26780, "s": 26684, "text": "Lets say that we have to sort the numbers 3, 4, 1, 2. The above algorithm would work like this." }, { "code": null, "e": 26798, "s": 26780, "text": "Bead Sort Working" }, { "code": null, "e": 26874, "s": 26798, "text": "Below is the code, try to implement it yourself before looking at the code." }, { "code": null, "e": 26884, "s": 26874, "text": "The Code:" }, { "code": "// C++ program to implement gravity/bead sort#include <bits/stdc++.h>using namespace std; #define BEAD(i, j) beads[i * max + j] // function to perform the above algorithmvoid beadSort(int *a, int len){ // Find the maximum element int max = a[0]; for (int i = 1; i < len; i++) if (a[i] > max) max = a[i]; // allocating memory unsigned char beads[max*len]; memset(beads, 0, sizeof(beads)); // mark the beads for (int i = 0; i < len; i++) for (int j = 0; j < a[i]; j++) BEAD(i, j) = 1; for (int j = 0; j < max; j++) { // count how many beads are on each post int sum = 0; for (int i=0; i < len; i++) { sum += BEAD(i, j); BEAD(i, j) = 0; } // Move beads down for (int i = len - sum; i < len; i++) BEAD(i, j) = 1; } // Put sorted values in array using beads for (int i = 0; i < len; i++) { int j; for (j = 0; j < max && BEAD(i, j); j++); a[i] = j; }} // driver function to test the algorithmint main(){ int a[] = {5, 3, 1, 7, 4, 1, 1, 20}; int len = sizeof(a)/sizeof(a[0]); beadSort(a, len); for (int i = 0; i < len; i++) printf(\"%d \", a[i]); return 0;}", "e": 28159, "s": 26884, "text": null }, { "code": null, "e": 28167, "s": 28159, "text": "Output:" }, { "code": null, "e": 28185, "s": 28167, "text": "1 1 1 3 4 5 7 20\n" }, { "code": null, "e": 28391, "s": 28185, "text": "Time Complexity:The algorithm’s run–time complexity ranges from O(1) to O(S) (S is the sum of the input integers) depending on the user’s perspective. Finally, three possible implementations are suggested." }, { "code": null, "e": 28924, "s": 28391, "text": "O(1) : Dropping all beads together as a single (simultaneous) operation. This complexity cannot be implemented in practice.O(): In a realistic physical model that uses gravity, the time it takes to let the beads fall is proportional to the square root of the maximum height, which is proportional to n.O(n) : Dropping the row of beads in the frame (representing a number) as a distinct operation since the number of rows is equal to n.O(S) : Dropping each and every bead’ as a separate operation since S is the sum of all the beads." }, { "code": null, "e": 29048, "s": 28924, "text": "O(1) : Dropping all beads together as a single (simultaneous) operation. This complexity cannot be implemented in practice." }, { "code": null, "e": 29228, "s": 29048, "text": "O(): In a realistic physical model that uses gravity, the time it takes to let the beads fall is proportional to the square root of the maximum height, which is proportional to n." }, { "code": null, "e": 29362, "s": 29228, "text": "O(n) : Dropping the row of beads in the frame (representing a number) as a distinct operation since the number of rows is equal to n." }, { "code": null, "e": 29460, "s": 29362, "text": "O(S) : Dropping each and every bead’ as a separate operation since S is the sum of all the beads." }, { "code": null, "e": 29747, "s": 29460, "text": "Like the Pigeonhole sort, bead sort is unusual in that in worst case it can perform faster than O(), the fastest performance possible for a comparison sort in worst case. This is possible because the key for a bead sort is always a positive integer and bead sort exploits its structure." }, { "code": null, "e": 29917, "s": 29747, "text": "Space Complexity: Bead sort is the record-holder as for waste. The costs for the extra memory exceed the costs for storing the array itself. Its memory complexity is O()" }, { "code": null, "e": 29929, "s": 29917, "text": "References:" }, { "code": null, "e": 29967, "s": 29929, "text": "https://www.wikiwand.com/en/Bead_sort" }, { "code": null, "e": 30003, "s": 29967, "text": "https://kukuruku.co/post/bead-sort/" }, { "code": null, "e": 30061, "s": 30003, "text": "https://rosettacode.org/wiki/Sorting_algorithms/Bead_sort" }, { "code": null, "e": 30115, "s": 30061, "text": "https://www.cs.auckland.ac.nz/~mjd/misc/BeadSort5.pdf" }, { "code": null, "e": 30416, "s": 30115, "text": "This article is contributed by Palash Nigam . If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 30541, "s": 30416, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 30562, "s": 30541, "text": "Pigeonhole Principle" }, { "code": null, "e": 30570, "s": 30562, "text": "Sorting" }, { "code": null, "e": 30578, "s": 30570, "text": "Sorting" }, { "code": null, "e": 30676, "s": 30578, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30685, "s": 30676, "text": "Comments" }, { "code": null, "e": 30698, "s": 30685, "text": "Old Comments" }, { "code": null, "e": 30724, "s": 30698, "text": "C++ Program for QuickSort" }, { "code": null, "e": 30756, "s": 30724, "text": "Stability in sorting algorithms" }, { "code": null, "e": 30778, "s": 30756, "text": "Quickselect Algorithm" }, { "code": null, "e": 30803, "s": 30778, "text": "Quick Sort vs Merge Sort" }, { "code": null, "e": 30835, "s": 30803, "text": "QuickSort using Random Pivoting" }, { "code": null, "e": 30851, "s": 30835, "text": "Sorting in Java" }, { "code": null, "e": 30888, "s": 30851, "text": "Check if two arrays are equal or not" }, { "code": null, "e": 30910, "s": 30888, "text": "Binary Insertion Sort" }, { "code": null, "e": 30932, "s": 30910, "text": "Recursive Bubble Sort" } ]
Regular Expressions and RegExp Object
A regular expression is an object that describes a pattern of characters. The JavaScript RegExp class represents regular expressions, and both String and RegExp define methods that use regular expressions to perform powerful pattern-matching and search-and-replace functions on text. A regular expression could be defined with the RegExp () constructor, as follows − var pattern = new RegExp(pattern, attributes); or simply var pattern = /pattern/attributes; Here is the description of the parameters − pattern − A string that specifies the pattern of the regular expression or another regular expression. pattern − A string that specifies the pattern of the regular expression or another regular expression. attributes − An optional string containing any of the "g", "i", and "m" attributes that specify global, case-insensitive, and multi-line matches, respectively. attributes − An optional string containing any of the "g", "i", and "m" attributes that specify global, case-insensitive, and multi-line matches, respectively. Brackets ([]) have a special meaning when used in the context of regular expressions. They are used to find a range of characters. [...] Any one character between the brackets. [^...] Any one character not between the brackets. [0-9] It matches any decimal digit from 0 through 9. [a-z] It matches any character from lowercase a through lowercase z. [A-Z] It matches any character from uppercase A through uppercase Z. [a-Z] It matches any character from lowercase a through uppercase Z. The ranges shown above are general; you could also use the range [0-3] to match any decimal digit ranging from 0 through 3, or the range [b-v] to match any lowercase character ranging from b through v. The frequency or position of bracketed character sequences and single characters can be denoted by a special character. Each special character has a specific connotation. The +, *, ?, and $ flags all follow a character sequence. p+ It matches any string containing one or more p's. p* It matches any string containing zero or more p's. p? It matches any string containing at most one p. p{N} It matches any string containing a sequence of N p's p{2,3} It matches any string containing a sequence of two or three p's. p{2, } It matches any string containing a sequence of at least two p's. p$ It matches any string with p at the end of it. ^p It matches any string with p at the beginning of it. Following examples explain more about matching characters. [^a-zA-Z] It matches any string not containing any of the characters ranging from a through z and A through Z. p.p It matches any string containing p, followed by any character, in turn followed by another p. ^.{2}$ It matches any string containing exactly two characters. <b>(.*)</b> It matches any string enclosed within <b> and </b>. p(hp)* It matches any string containing a p followed by zero or more instances of the sequence hp. Alphanumeric Itself \0 The NUL character (\u0000) \t Tab (\u0009 \n Newline (\u000A) \v Vertical tab (\u000B) \f Form feed (\u000C) \r Carriage return (\u000D) \xnn The Latin character specified by the hexadecimal number nn; for example, \x0A is the same as \n \uxxxx The Unicode character specified by the hexadecimal number xxxx; for example, \u0009 is the same as \t \cX The control character ^X; for example, \cJ is equivalent to the newline character \n A metacharacter is simply an alphabetical character preceded by a backslash that acts to give the combination a special meaning. For instance, you can search for a large sum of money using the '\d' metacharacter: /([\d]+)000/, Here \d will search for any string of numerical character. The following table lists a set of metacharacters which can be used in PERL Style Regular Expressions. . a single character \s a whitespace character (space, tab, newline) \S non-whitespace character \d a digit (0-9) \D a non-digit \w a word character (a-z, A-Z, 0-9, _) \W a non-word character [\b] a literal backspace (special case). [aeiou] matches a single character in the given set [^aeiou] matches a single character outside the given set (foo|bar|baz) matches any of the alternatives specified Several modifiers are available that can simplify the way you work with regexps, like case sensitivity, searching in multiple lines, etc. i Perform case-insensitive matching. m Specifies that if the string has newline or carriage return characters, the ^ and $ operators will now match against a newline boundary, instead of a string boundary g Performs a global matchthat is, find all matches rather than stopping after the first match. Here is a list of the properties associated with RegExp and their description. Specifies the function that creates an object's prototype. Specifies if the "g" modifier is set. Specifies if the "i" modifier is set. The index at which to start the next match. Specifies if the "m" modifier is set. The text of the pattern. In the following sections, we will have a few examples to demonstrate the usage of RegExp properties. Here is a list of the methods associated with RegExp along with their description. Executes a search for a match in its string parameter. Tests for a match in its string parameter. Returns an object literal representing the specified object; you can use this value to create a new object. Returns a string representing the specified object. In the following sections, we will have a few examples to demonstrate the usage of RegExp methods. 25 Lectures 2.5 hours Anadi Sharma 74 Lectures 10 hours Lets Kode It 72 Lectures 4.5 hours Frahaan Hussain 70 Lectures 4.5 hours Frahaan Hussain 46 Lectures 6 hours Eduonix Learning Solutions 88 Lectures 14 hours Eduonix Learning Solutions Print Add Notes Bookmark this page
[ { "code": null, "e": 2540, "s": 2466, "text": "A regular expression is an object that describes a pattern of characters." }, { "code": null, "e": 2750, "s": 2540, "text": "The JavaScript RegExp class represents regular expressions, and both String and RegExp define methods that use regular expressions to perform powerful pattern-matching and search-and-replace functions on text." }, { "code": null, "e": 2833, "s": 2750, "text": "A regular expression could be defined with the RegExp () constructor, as follows −" }, { "code": null, "e": 2926, "s": 2833, "text": "var pattern = new RegExp(pattern, attributes);\nor simply\nvar pattern = /pattern/attributes;\n" }, { "code": null, "e": 2970, "s": 2926, "text": "Here is the description of the parameters −" }, { "code": null, "e": 3073, "s": 2970, "text": "pattern − A string that specifies the pattern of the regular expression or another regular expression." }, { "code": null, "e": 3176, "s": 3073, "text": "pattern − A string that specifies the pattern of the regular expression or another regular expression." }, { "code": null, "e": 3336, "s": 3176, "text": "attributes − An optional string containing any of the \"g\", \"i\", and \"m\" attributes that specify global, case-insensitive, and multi-line matches, respectively." }, { "code": null, "e": 3496, "s": 3336, "text": "attributes − An optional string containing any of the \"g\", \"i\", and \"m\" attributes that specify global, case-insensitive, and multi-line matches, respectively." }, { "code": null, "e": 3627, "s": 3496, "text": "Brackets ([]) have a special meaning when used in the context of regular expressions. They are used to find a range of characters." }, { "code": null, "e": 3633, "s": 3627, "text": "[...]" }, { "code": null, "e": 3673, "s": 3633, "text": "Any one character between the brackets." }, { "code": null, "e": 3680, "s": 3673, "text": "[^...]" }, { "code": null, "e": 3724, "s": 3680, "text": "Any one character not between the brackets." }, { "code": null, "e": 3730, "s": 3724, "text": "[0-9]" }, { "code": null, "e": 3777, "s": 3730, "text": "It matches any decimal digit from 0 through 9." }, { "code": null, "e": 3783, "s": 3777, "text": "[a-z]" }, { "code": null, "e": 3846, "s": 3783, "text": "It matches any character from lowercase a through lowercase z." }, { "code": null, "e": 3852, "s": 3846, "text": "[A-Z]" }, { "code": null, "e": 3915, "s": 3852, "text": "It matches any character from uppercase A through uppercase Z." }, { "code": null, "e": 3921, "s": 3915, "text": "[a-Z]" }, { "code": null, "e": 3984, "s": 3921, "text": "It matches any character from lowercase a through uppercase Z." }, { "code": null, "e": 4186, "s": 3984, "text": "The ranges shown above are general; you could also use the range [0-3] to match any decimal digit ranging from 0 through 3, or the range [b-v] to match any lowercase character ranging from b through v." }, { "code": null, "e": 4415, "s": 4186, "text": "The frequency or position of bracketed character sequences and single characters can be denoted by a special character. Each special character has a specific connotation. The +, *, ?, and $ flags all follow a character sequence." }, { "code": null, "e": 4418, "s": 4415, "text": "p+" }, { "code": null, "e": 4468, "s": 4418, "text": "It matches any string containing one or more p's." }, { "code": null, "e": 4471, "s": 4468, "text": "p*" }, { "code": null, "e": 4522, "s": 4471, "text": "It matches any string containing zero or more p's." }, { "code": null, "e": 4525, "s": 4522, "text": "p?" }, { "code": null, "e": 4573, "s": 4525, "text": "It matches any string containing at most one p." }, { "code": null, "e": 4578, "s": 4573, "text": "p{N}" }, { "code": null, "e": 4631, "s": 4578, "text": "It matches any string containing a sequence of N p's" }, { "code": null, "e": 4638, "s": 4631, "text": "p{2,3}" }, { "code": null, "e": 4703, "s": 4638, "text": "It matches any string containing a sequence of two or three p's." }, { "code": null, "e": 4710, "s": 4703, "text": "p{2, }" }, { "code": null, "e": 4775, "s": 4710, "text": "It matches any string containing a sequence of at least two p's." }, { "code": null, "e": 4778, "s": 4775, "text": "p$" }, { "code": null, "e": 4826, "s": 4778, "text": "It matches any string with p at the end of it." }, { "code": null, "e": 4829, "s": 4826, "text": "^p" }, { "code": null, "e": 4882, "s": 4829, "text": "It matches any string with p at the beginning of it." }, { "code": null, "e": 4941, "s": 4882, "text": "Following examples explain more about matching characters." }, { "code": null, "e": 4951, "s": 4941, "text": "[^a-zA-Z]" }, { "code": null, "e": 5052, "s": 4951, "text": "It matches any string not containing any of the characters ranging from a through z and A through Z." }, { "code": null, "e": 5056, "s": 5052, "text": "p.p" }, { "code": null, "e": 5150, "s": 5056, "text": "It matches any string containing p, followed by any character, in turn followed by another p." }, { "code": null, "e": 5157, "s": 5150, "text": "^.{2}$" }, { "code": null, "e": 5214, "s": 5157, "text": "It matches any string containing exactly two characters." }, { "code": null, "e": 5226, "s": 5214, "text": "<b>(.*)</b>" }, { "code": null, "e": 5278, "s": 5226, "text": "It matches any string enclosed within <b> and </b>." }, { "code": null, "e": 5285, "s": 5278, "text": "p(hp)*" }, { "code": null, "e": 5377, "s": 5285, "text": "It matches any string containing a p followed by zero or more instances of the sequence hp." }, { "code": null, "e": 5390, "s": 5377, "text": "Alphanumeric" }, { "code": null, "e": 5397, "s": 5390, "text": "Itself" }, { "code": null, "e": 5400, "s": 5397, "text": "\\0" }, { "code": null, "e": 5427, "s": 5400, "text": "The NUL character (\\u0000)" }, { "code": null, "e": 5430, "s": 5427, "text": "\\t" }, { "code": null, "e": 5442, "s": 5430, "text": "Tab (\\u0009" }, { "code": null, "e": 5445, "s": 5442, "text": "\\n" }, { "code": null, "e": 5462, "s": 5445, "text": "Newline (\\u000A)" }, { "code": null, "e": 5465, "s": 5462, "text": "\\v" }, { "code": null, "e": 5487, "s": 5465, "text": "Vertical tab (\\u000B)" }, { "code": null, "e": 5490, "s": 5487, "text": "\\f" }, { "code": null, "e": 5509, "s": 5490, "text": "Form feed (\\u000C)" }, { "code": null, "e": 5512, "s": 5509, "text": "\\r" }, { "code": null, "e": 5537, "s": 5512, "text": "Carriage return (\\u000D)" }, { "code": null, "e": 5542, "s": 5537, "text": "\\xnn" }, { "code": null, "e": 5638, "s": 5542, "text": "The Latin character specified by the hexadecimal number nn; for example, \\x0A is the same as \\n" }, { "code": null, "e": 5645, "s": 5638, "text": "\\uxxxx" }, { "code": null, "e": 5747, "s": 5645, "text": "The Unicode character specified by the hexadecimal number xxxx; for example, \\u0009 is the same as \\t" }, { "code": null, "e": 5751, "s": 5747, "text": "\\cX" }, { "code": null, "e": 5836, "s": 5751, "text": "The control character ^X; for example, \\cJ is equivalent to the newline character \\n" }, { "code": null, "e": 5965, "s": 5836, "text": "A metacharacter is simply an alphabetical character preceded by a backslash that acts to give the combination a special meaning." }, { "code": null, "e": 6122, "s": 5965, "text": "For instance, you can search for a large sum of money using the '\\d' metacharacter: /([\\d]+)000/, Here \\d will search for any string of numerical character." }, { "code": null, "e": 6225, "s": 6122, "text": "The following table lists a set of metacharacters which can be used in PERL Style Regular Expressions." }, { "code": null, "e": 6227, "s": 6225, "text": "." }, { "code": null, "e": 6246, "s": 6227, "text": "a single character" }, { "code": null, "e": 6249, "s": 6246, "text": "\\s" }, { "code": null, "e": 6294, "s": 6249, "text": "a whitespace character (space, tab, newline)" }, { "code": null, "e": 6297, "s": 6294, "text": "\\S" }, { "code": null, "e": 6322, "s": 6297, "text": "non-whitespace character" }, { "code": null, "e": 6325, "s": 6322, "text": "\\d" }, { "code": null, "e": 6339, "s": 6325, "text": "a digit (0-9)" }, { "code": null, "e": 6342, "s": 6339, "text": "\\D" }, { "code": null, "e": 6354, "s": 6342, "text": "a non-digit" }, { "code": null, "e": 6357, "s": 6354, "text": "\\w" }, { "code": null, "e": 6393, "s": 6357, "text": "a word character (a-z, A-Z, 0-9, _)" }, { "code": null, "e": 6396, "s": 6393, "text": "\\W" }, { "code": null, "e": 6417, "s": 6396, "text": "a non-word character" }, { "code": null, "e": 6422, "s": 6417, "text": "[\\b]" }, { "code": null, "e": 6458, "s": 6422, "text": "a literal backspace (special case)." }, { "code": null, "e": 6466, "s": 6458, "text": "[aeiou]" }, { "code": null, "e": 6510, "s": 6466, "text": "matches a single character in the given set" }, { "code": null, "e": 6519, "s": 6510, "text": "[^aeiou]" }, { "code": null, "e": 6568, "s": 6519, "text": "matches a single character outside the given set" }, { "code": null, "e": 6582, "s": 6568, "text": "(foo|bar|baz)" }, { "code": null, "e": 6624, "s": 6582, "text": "matches any of the alternatives specified" }, { "code": null, "e": 6762, "s": 6624, "text": "Several modifiers are available that can simplify the way you work with regexps, like case sensitivity, searching in multiple lines, etc." }, { "code": null, "e": 6764, "s": 6762, "text": "i" }, { "code": null, "e": 6799, "s": 6764, "text": "Perform case-insensitive matching." }, { "code": null, "e": 6801, "s": 6799, "text": "m" }, { "code": null, "e": 6967, "s": 6801, "text": "Specifies that if the string has newline or carriage return characters, the ^ and $ operators will now match against a newline boundary, instead of a string boundary" }, { "code": null, "e": 6969, "s": 6967, "text": "g" }, { "code": null, "e": 7062, "s": 6969, "text": "Performs a global matchthat is, find all matches rather than stopping after the first match." }, { "code": null, "e": 7141, "s": 7062, "text": "Here is a list of the properties associated with RegExp and their description." }, { "code": null, "e": 7200, "s": 7141, "text": "Specifies the function that creates an object's prototype." }, { "code": null, "e": 7238, "s": 7200, "text": "Specifies if the \"g\" modifier is set." }, { "code": null, "e": 7276, "s": 7238, "text": "Specifies if the \"i\" modifier is set." }, { "code": null, "e": 7320, "s": 7276, "text": "The index at which to start the next match." }, { "code": null, "e": 7358, "s": 7320, "text": "Specifies if the \"m\" modifier is set." }, { "code": null, "e": 7383, "s": 7358, "text": "The text of the pattern." }, { "code": null, "e": 7485, "s": 7383, "text": "In the following sections, we will have a few examples to demonstrate the usage of RegExp properties." }, { "code": null, "e": 7568, "s": 7485, "text": "Here is a list of the methods associated with RegExp along with their description." }, { "code": null, "e": 7623, "s": 7568, "text": "Executes a search for a match in its string parameter." }, { "code": null, "e": 7666, "s": 7623, "text": "Tests for a match in its string parameter." }, { "code": null, "e": 7774, "s": 7666, "text": "Returns an object literal representing the specified object; you can use this value to create a new object." }, { "code": null, "e": 7826, "s": 7774, "text": "Returns a string representing the specified object." }, { "code": null, "e": 7925, "s": 7826, "text": "In the following sections, we will have a few examples to demonstrate the usage of RegExp methods." }, { "code": null, "e": 7960, "s": 7925, "text": "\n 25 Lectures \n 2.5 hours \n" }, { "code": null, "e": 7974, "s": 7960, "text": " Anadi Sharma" }, { "code": null, "e": 8008, "s": 7974, "text": "\n 74 Lectures \n 10 hours \n" }, { "code": null, "e": 8022, "s": 8008, "text": " Lets Kode It" }, { "code": null, "e": 8057, "s": 8022, "text": "\n 72 Lectures \n 4.5 hours \n" }, { "code": null, "e": 8074, "s": 8057, "text": " Frahaan Hussain" }, { "code": null, "e": 8109, "s": 8074, "text": "\n 70 Lectures \n 4.5 hours \n" }, { "code": null, "e": 8126, "s": 8109, "text": " Frahaan Hussain" }, { "code": null, "e": 8159, "s": 8126, "text": "\n 46 Lectures \n 6 hours \n" }, { "code": null, "e": 8187, "s": 8159, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 8221, "s": 8187, "text": "\n 88 Lectures \n 14 hours \n" }, { "code": null, "e": 8249, "s": 8221, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 8256, "s": 8249, "text": " Print" }, { "code": null, "e": 8267, "s": 8256, "text": " Add Notes" } ]
How To Configure and Install Redis on Ubuntu Linux
In this article we will learn how to configure Redis, Redis is an in-memory Key-value store which is popular for its flexibility, performance and used with wide language support. We will configure this on the Ubuntu Linux server. To do this demo we need a non-root user and we will set Sudo privileges to the user to perform. To get the latest version of Redis, we will get the latest source code and will compile and install the software. For that, we needed to install the dependencies for the software compiling. We also need to install build-essential meta-package from the Ubuntu repositories, and download ‘tcl’ packages which are used to test the binaries. # sudo apt-get update # sudo apt-get install build-essentials tcl Downloading the Source code and Extract. Create a folder in temp # mkdir /tmp/redis # cd /tmp/redis Download the latest stable version of Redis, thus we can get using the below command # curl -O http://download.redis.io/redis-stable.tar.gz # tar xzvf redis-stable.tar.gz # cd redis-stable We will compile and install the Redis binaries with the below command # make After the compilation of the source code, we will get binaries we run the below command to test the suit # make test We can install all the binaries on the system using the below command. # make install As we just installed the Redis, we can begin the configuration of Redis. We needed to create the directory /etc/redis # mkdir /etc/redis Copy the redis configuration files included in the Redis source archive # cp /tmp/redis/redis-stable/redis.conf /etc/redis Open the configuration file using an editor # vi /etc/redis/redis.conf In the configuration file, we will find a directive called ‘supervised’ which is set to no, as we are using systemd to init the system so that we can change this to systemd. # If you run Redis from upstart or systemd, Redis can interact with your # supervision tree. Options: # supervised no - no supervision interaction # supervised upstart - signal upstart by putting Redis into SIGSTOP mode # supervised systemd - signal systemd by writing READY=1 to $NOTIFY_SOCKET # supervised auto - detect upstart or systemd method based on # UPSTART_JOB or NOTIFY_SOCKET environment variables # Note: these supervision methods only signal "process is ready." # They do not enable continuous liveness pings back to your supervisor. supervised systemd Next, find the dir directive and change the dire directive to the /var/lib/redis, where this option is used to specify the directory that Redis will be used to dump the persistent data. This location has the write permission and is not viewable by normal users. # The working directory. # # The DB will be written inside this directory, with the filename specified # above using the 'dbfilename' configuration directive. # # The Append Only File will also be created inside this directory. # # Note that you must specify a directory here, not a file name. dir /var/lib/redis Save the changes and close the file We can create a systemd file so that init system can manage the process. # touch /etc/systemd/system/redis.service # vi /etc/systemd/system/redis.service We start with [Unit] section by adding the description and define a requirement that we needed networking to be the most available to start this service. [Unit] Description=Redis In-Memory Data Store After=network.target In [service] section we will specify the services behavior. For security reasons, we will not run the service as root user. We will dedicate a user and group which will call the Redis with simplicity. To start the services we need to call the redis-server binary which is pointed at our configuration. To stop the service we will use Redis shutdown command and which will be executed with redis-cli binary. [Unit] Description=Redis In-Memory Data Store After=network.target [Service] User=redis Group=redis ExecStart=/usr/local/bin/redis-server /etc/redis/redis.conf ExecStop=/usr/local/bin/redis-cli shutdown Restart=always [Install] section, we define the systemd to target the service to attach to enable (configured to start at boot time). [Unit] Description=Redis In-Memory Data Store After=network.target [Service] User=redis Group=redis ExecStart=/usr/local/bin/redis-server /etc/redis/redis.conf ExecStop=/usr/local/bin/redis-cli shutdown Restart=always [Install] WantedBy=multi-user.target # add users --system --group --no-create-home redis # mkdir /var/lib/redis # chown redis:redis /var/lib/redis # chmod 770 /var/lib/redis We are ready to start the Redis Server # systemctl start redis To check the services running with no errors we can run the below command – # systemctl status redis redis.service - Redis Server Loaded: loaded (/etc/systemd/system/redis.service; enabled; vendor preset: enabled) Active: active (running) since Wed 2016-05-13 11:42:00 EDT; 5min 03s ago Process: 7127 ExecStop=/usr/local/bin/redis-cli shutdown (code=exited, status=0/SUCCESS) Main PID: 7143 (redis-server) Tasks: 6 (limit: 512) Memory: 10864.0K CPU: 79ms CGroup: /system.slice/redis.service └─7143 /usr/local/bin/redis-server 127.0.0.1:6379 # sudo systemctl enable redis We should have a Redis instance installed and configured in our environment so that we can use it for in-memory data structure store and also used as a database, cache and as message broker.
[ { "code": null, "e": 1388, "s": 1062, "text": "In this article we will learn how to configure Redis, Redis is an in-memory Key-value store which is popular for its flexibility, performance and used with wide language support. We will configure this on the Ubuntu Linux server. To do this demo we need a non-root user and we will set Sudo privileges to the user to perform." }, { "code": null, "e": 1578, "s": 1388, "text": "To get the latest version of Redis, we will get the latest source code and will compile and install the software. For that, we needed to install the dependencies for the software compiling." }, { "code": null, "e": 1726, "s": 1578, "text": "We also need to install build-essential meta-package from the Ubuntu repositories, and download ‘tcl’ packages which are used to test the binaries." }, { "code": null, "e": 1792, "s": 1726, "text": "# sudo apt-get update\n# sudo apt-get install build-essentials tcl" }, { "code": null, "e": 1857, "s": 1792, "text": "Downloading the Source code and Extract. Create a folder in temp" }, { "code": null, "e": 1892, "s": 1857, "text": "# mkdir /tmp/redis\n# cd /tmp/redis" }, { "code": null, "e": 1977, "s": 1892, "text": "Download the latest stable version of Redis, thus we can get using the below command" }, { "code": null, "e": 2081, "s": 1977, "text": "# curl -O http://download.redis.io/redis-stable.tar.gz\n# tar xzvf redis-stable.tar.gz\n# cd redis-stable" }, { "code": null, "e": 2151, "s": 2081, "text": "We will compile and install the Redis binaries with the below command" }, { "code": null, "e": 2158, "s": 2151, "text": "# make" }, { "code": null, "e": 2263, "s": 2158, "text": "After the compilation of the source code, we will get binaries we run the below command to test the suit" }, { "code": null, "e": 2275, "s": 2263, "text": "# make test" }, { "code": null, "e": 2346, "s": 2275, "text": "We can install all the binaries on the system using the below command." }, { "code": null, "e": 2361, "s": 2346, "text": "# make install" }, { "code": null, "e": 2479, "s": 2361, "text": "As we just installed the Redis, we can begin the configuration of Redis. We needed to create the directory /etc/redis" }, { "code": null, "e": 2498, "s": 2479, "text": "# mkdir /etc/redis" }, { "code": null, "e": 2570, "s": 2498, "text": "Copy the redis configuration files included in the Redis source archive" }, { "code": null, "e": 2621, "s": 2570, "text": "# cp /tmp/redis/redis-stable/redis.conf /etc/redis" }, { "code": null, "e": 2665, "s": 2621, "text": "Open the configuration file using an editor" }, { "code": null, "e": 2692, "s": 2665, "text": "# vi /etc/redis/redis.conf" }, { "code": null, "e": 2866, "s": 2692, "text": "In the configuration file, we will find a directive called ‘supervised’ which is set to no, as we are using systemd to init the system so that we can change this to systemd." }, { "code": null, "e": 3477, "s": 2866, "text": "# If you run Redis from upstart or systemd, Redis can interact with your\n# supervision tree. Options:\n# supervised no - no supervision interaction\n# supervised upstart - signal upstart by putting Redis into SIGSTOP mode\n# supervised systemd - signal systemd by writing READY=1 to $NOTIFY_SOCKET\n# supervised auto - detect upstart or systemd method based on\n# UPSTART_JOB or NOTIFY_SOCKET environment variables\n# Note: these supervision methods only signal \"process is ready.\"\n# They do not enable continuous liveness pings back to your supervisor.\nsupervised systemd" }, { "code": null, "e": 3739, "s": 3477, "text": "Next, find the dir directive and change the dire directive to the /var/lib/redis, where this option is used to specify the directory that Redis will be used to dump the persistent data. This location has the write permission and is not viewable by normal users." }, { "code": null, "e": 4089, "s": 3739, "text": "# The working directory.\n#\n# The DB will be written inside this directory, with the filename specified\n# above using the 'dbfilename' configuration directive.\n#\n# The Append Only File will also be created inside this directory.\n#\n# Note that you must specify a directory here, not a file name.\ndir /var/lib/redis\n\nSave the changes and close the file" }, { "code": null, "e": 4162, "s": 4089, "text": "We can create a systemd file so that init system can manage the process." }, { "code": null, "e": 4243, "s": 4162, "text": "# touch /etc/systemd/system/redis.service\n# vi /etc/systemd/system/redis.service" }, { "code": null, "e": 4397, "s": 4243, "text": "We start with [Unit] section by adding the description and define a requirement that we needed networking to be the most available to start this service." }, { "code": null, "e": 4464, "s": 4397, "text": "[Unit] Description=Redis In-Memory Data Store After=network.target" }, { "code": null, "e": 4665, "s": 4464, "text": "In [service] section we will specify the services behavior. For security reasons, we will not run the service as root user. We will dedicate a user and group which will call the Redis with simplicity." }, { "code": null, "e": 4871, "s": 4665, "text": "To start the services we need to call the redis-server binary which is pointed at our configuration. To stop the service we will use Redis shutdown command and which will be executed with redis-cli binary." }, { "code": null, "e": 5463, "s": 4871, "text": "[Unit] Description=Redis In-Memory Data Store After=network.target [Service]\nUser=redis Group=redis ExecStart=/usr/local/bin/redis-server\n/etc/redis/redis.conf ExecStop=/usr/local/bin/redis-cli shutdown\nRestart=always\n[Install] section, we define the systemd to target the service to attach to\nenable (configured to start at boot time).\n[Unit] Description=Redis In-Memory Data Store After=network.target [Service]\nUser=redis Group=redis ExecStart=/usr/local/bin/redis-server\n/etc/redis/redis.conf ExecStop=/usr/local/bin/redis-cli shutdown\nRestart=always [Install] WantedBy=multi-user.target" }, { "code": null, "e": 5600, "s": 5463, "text": "# add users --system --group --no-create-home redis\n# mkdir /var/lib/redis\n# chown redis:redis /var/lib/redis\n# chmod 770 /var/lib/redis" }, { "code": null, "e": 5639, "s": 5600, "text": "We are ready to start the Redis Server" }, { "code": null, "e": 5663, "s": 5639, "text": "# systemctl start redis" }, { "code": null, "e": 5739, "s": 5663, "text": "To check the services running with no errors we can run the below command –" }, { "code": null, "e": 6204, "s": 5739, "text": "# systemctl status redis\nredis.service - Redis Server\nLoaded: loaded (/etc/systemd/system/redis.service; enabled; vendor preset: enabled)\nActive: active (running) since Wed 2016-05-13 11:42:00 EDT; 5min 03s ago\nProcess: 7127 ExecStop=/usr/local/bin/redis-cli shutdown (code=exited, status=0/SUCCESS)\nMain PID: 7143 (redis-server)\nTasks: 6 (limit: 512)\nMemory: 10864.0K\nCPU: 79ms\nCGroup: /system.slice/redis.service\n└─7143 /usr/local/bin/redis-server 127.0.0.1:6379" }, { "code": null, "e": 6234, "s": 6204, "text": "# sudo systemctl enable redis" }, { "code": null, "e": 6425, "s": 6234, "text": "We should have a Redis instance installed and configured in our environment so that we can use it for in-memory data structure store and also used as a database, cache and as message broker." } ]
Greenhouse gas (CO2) emissions and oil refining | by Ranganath Venkataraman | Towards Data Science
My previous posts have used Python visualizations to explore oil refining capacity across the United States. Further, we analyzed behavior of crude and fuel prices over the years. I’m going to explore something else in this article: carbon dioxide (CO2) emissions from oil refining. Source data for all work below is from the EPA’s Greenhouse Gas Reporting Program, whose data is publicly available here. This data is made up of self-reported emissions of CO2-equivalent in metric tons from 5,441 companies in 1,210 industries from 2011 through 2018. A point of education: CO2 equivalency is a way to measure emissions of any pollutant. For example, 1 ton CO2 equivalent means that amount of actual gas released would warm the earth by same amount as by release of 1 ton CO2. TL/DR: Power generation generates little more than 62% of the total emitted carbon dioxide to the atmosphere, with refining and chemicals comprising a distant second at 9.6%. Texas, Louisiana and California are key sources — and Illinois features as a key emitter for certain industries as well. Oil refining brings to the mind’s eye massive structures that belch clouds of smoke and steam. But — just how much CO2 do oil refineries emit compared to other major industries in the United States? And how do these numbers vary across states? Which industry offers the biggest reduction target in terms of current emissions? Let me preface by stating the well-known point that CO2 emissions are important to understand since CO2 in the atmosphere absorbs radiation and traps heat in the Earth’s atmosphere. The higher the CO2, the more heat is stored in the atmosphere, and the greater the increase in temperatures and general weather disruptions — also known as global warming or climate change. First, let’s use the code below to generate a bar plot to visualize the top CO2equiv-producing industries. fig = px.bar(ByIndustry, x='Latest Reported Industry Type (sectors)', y='%')fig.update_xaxes(tickangle=45, tickfont=dict(family='Rockwell', size=14))fig.update_layout(width=1000, height=500, title='% of emissions from various Industries')fig.add_annotation(x=31, y=62.38, font=dict(family="Courier New, monospace", size=18, color="black",), text="62.38% of emissions from Power Plants")fig.show() Interesting, power plants are responsible for little more than 62% of total emissions as measured from 2011 through 2018. Refining and chemicals, by contrast, are responsible for a combined 9.1% of emissions — 85% less! It’s fascinating to observe the role played by various industries in emitting CO2-equiv. How does this vary across states? Take a look at the dynamic choropleth below examining the contributions of different states in 2018 emissions for the industries specified in the list above: CO2-equiv from power plants was peak in Texas at 185 million tons. Florida and Indiana were distant second place-holders at 84 million and 81 million tons respectively. How about refineries and chemicals? Texas again leads the way with 38 million tons of CO2eq, with Louisiana running second at 28 million tons of CO2eq — this matches the message conveyed in the choropleth showing January 2019 refinery capacity in my Refinery capacity article. The industrial gases and minerals businesses provide food for thought. For context, minerals are unearthed as part of the mining business while industrial gases cover the manufacture of commonly-used gases for other businesses e.g. nitrogen, CO2, argon, hydrogen, and helium. Kentucky emits roughly 1 million tons annually creating industrial gases, while Louisiana and Indiana are close behind emitting slightly more than 700,000 tons per year. Meanwhile, Texas, Missouri, and Illinois are leading emitters in the minerals industry Bottom-line here is that many states and many industries play a role in emitting CO2 to the atmosphere, with power generation being the industry holding the greatest potential for emissions reduction. This conclusion holds steady across the years in which greenhouse gas data was collected by the EPA, 2011–2018. As observed in Figure 4 below, no particular year in that time frame changes the narrative above. Indeed, there simply isn’t a significant change in emissions profiles over those 7 years across any industry. Let’s start shifting tack to consider emissions reductions in refining. I had previously discussed the economics of oil refining that converts crude oil to gasoline, jet fuel, diesel etc. How exactly does a refinery accomplish this? It does so, through the use of various refining process units, chief among which are: Hydrocrackers, Fluid Catalytic Crackers (FCCs), Reformers, and Delayed Cokers. That’s a lot of new terminology and we’ll spend the next few articles diving into how machine learning algorithms can help optimize the balance between profitability and emissions for these different units. As always, I welcome any feedback or questions on this or other articles. The repo to support analysis for this article is here.
[ { "code": null, "e": 351, "s": 171, "text": "My previous posts have used Python visualizations to explore oil refining capacity across the United States. Further, we analyzed behavior of crude and fuel prices over the years." }, { "code": null, "e": 722, "s": 351, "text": "I’m going to explore something else in this article: carbon dioxide (CO2) emissions from oil refining. Source data for all work below is from the EPA’s Greenhouse Gas Reporting Program, whose data is publicly available here. This data is made up of self-reported emissions of CO2-equivalent in metric tons from 5,441 companies in 1,210 industries from 2011 through 2018." }, { "code": null, "e": 947, "s": 722, "text": "A point of education: CO2 equivalency is a way to measure emissions of any pollutant. For example, 1 ton CO2 equivalent means that amount of actual gas released would warm the earth by same amount as by release of 1 ton CO2." }, { "code": null, "e": 1243, "s": 947, "text": "TL/DR: Power generation generates little more than 62% of the total emitted carbon dioxide to the atmosphere, with refining and chemicals comprising a distant second at 9.6%. Texas, Louisiana and California are key sources — and Illinois features as a key emitter for certain industries as well." }, { "code": null, "e": 1569, "s": 1243, "text": "Oil refining brings to the mind’s eye massive structures that belch clouds of smoke and steam. But — just how much CO2 do oil refineries emit compared to other major industries in the United States? And how do these numbers vary across states? Which industry offers the biggest reduction target in terms of current emissions?" }, { "code": null, "e": 1941, "s": 1569, "text": "Let me preface by stating the well-known point that CO2 emissions are important to understand since CO2 in the atmosphere absorbs radiation and traps heat in the Earth’s atmosphere. The higher the CO2, the more heat is stored in the atmosphere, and the greater the increase in temperatures and general weather disruptions — also known as global warming or climate change." }, { "code": null, "e": 2048, "s": 1941, "text": "First, let’s use the code below to generate a bar plot to visualize the top CO2equiv-producing industries." }, { "code": null, "e": 2456, "s": 2048, "text": "fig = px.bar(ByIndustry, x='Latest Reported Industry Type (sectors)', y='%')fig.update_xaxes(tickangle=45, tickfont=dict(family='Rockwell', size=14))fig.update_layout(width=1000, height=500, title='% of emissions from various Industries')fig.add_annotation(x=31, y=62.38, font=dict(family=\"Courier New, monospace\", size=18, color=\"black\",), text=\"62.38% of emissions from Power Plants\")fig.show()" }, { "code": null, "e": 2676, "s": 2456, "text": "Interesting, power plants are responsible for little more than 62% of total emissions as measured from 2011 through 2018. Refining and chemicals, by contrast, are responsible for a combined 9.1% of emissions — 85% less!" }, { "code": null, "e": 2957, "s": 2676, "text": "It’s fascinating to observe the role played by various industries in emitting CO2-equiv. How does this vary across states? Take a look at the dynamic choropleth below examining the contributions of different states in 2018 emissions for the industries specified in the list above:" }, { "code": null, "e": 3126, "s": 2957, "text": "CO2-equiv from power plants was peak in Texas at 185 million tons. Florida and Indiana were distant second place-holders at 84 million and 81 million tons respectively." }, { "code": null, "e": 3403, "s": 3126, "text": "How about refineries and chemicals? Texas again leads the way with 38 million tons of CO2eq, with Louisiana running second at 28 million tons of CO2eq — this matches the message conveyed in the choropleth showing January 2019 refinery capacity in my Refinery capacity article." }, { "code": null, "e": 3679, "s": 3403, "text": "The industrial gases and minerals businesses provide food for thought. For context, minerals are unearthed as part of the mining business while industrial gases cover the manufacture of commonly-used gases for other businesses e.g. nitrogen, CO2, argon, hydrogen, and helium." }, { "code": null, "e": 3936, "s": 3679, "text": "Kentucky emits roughly 1 million tons annually creating industrial gases, while Louisiana and Indiana are close behind emitting slightly more than 700,000 tons per year. Meanwhile, Texas, Missouri, and Illinois are leading emitters in the minerals industry" }, { "code": null, "e": 4137, "s": 3936, "text": "Bottom-line here is that many states and many industries play a role in emitting CO2 to the atmosphere, with power generation being the industry holding the greatest potential for emissions reduction." }, { "code": null, "e": 4457, "s": 4137, "text": "This conclusion holds steady across the years in which greenhouse gas data was collected by the EPA, 2011–2018. As observed in Figure 4 below, no particular year in that time frame changes the narrative above. Indeed, there simply isn’t a significant change in emissions profiles over those 7 years across any industry." }, { "code": null, "e": 4529, "s": 4457, "text": "Let’s start shifting tack to consider emissions reductions in refining." }, { "code": null, "e": 4855, "s": 4529, "text": "I had previously discussed the economics of oil refining that converts crude oil to gasoline, jet fuel, diesel etc. How exactly does a refinery accomplish this? It does so, through the use of various refining process units, chief among which are: Hydrocrackers, Fluid Catalytic Crackers (FCCs), Reformers, and Delayed Cokers." }, { "code": null, "e": 5062, "s": 4855, "text": "That’s a lot of new terminology and we’ll spend the next few articles diving into how machine learning algorithms can help optimize the balance between profitability and emissions for these different units." } ]
JavaScript Objects
In real life, a car is an object. A car has properties like weight and color, and methods like start and stop: All cars have the same properties, but the property values differ from car to car. All cars have the same methods, but the methods are performed at different times. You have already learned that JavaScript variables are containers for data values. This code assigns a simple value (Fiat) to a variable named car: Objects are variables too. But objects can contain many values. This code assigns many values (Fiat, 500, white) to a variable named car: The values are written as name:value pairs (name and value separated by a colon). It is a common practice to declare objects with the const keyword. Learn more about using const with objects in the chapter: JS Const. You define (and create) a JavaScript object with an object literal: Spaces and line breaks are not important. An object definition can span multiple lines: The name:values pairs in JavaScript objects are called properties: You can access object properties in two ways: or JavaScript objects are containers for named values called properties. Objects can also have methods. Methods are actions that can be performed on objects. Methods are stored in properties as function definitions. A method is a function stored as a property. In the example above, this refers to the person object. I.E. this.firstName means the firstName property of this. I.E. this.firstName means the firstName property of person. In JavaScript, the this keyword refers to an object. Which object depends on how this is being invoked (used or called). The this keyword refers to different objects depending on how it is used: The JavaScript this Tutorial In a function definition, this refers to the "owner" of the function. In the example above, this is the person object that "owns" the fullName function. In other words, this.firstName means the firstName property of this object. Learn more about this in The JavaScript this Tutorial. You access an object method with the following syntax: If you access a method without the () parentheses, it will return the function definition: When a JavaScript variable is declared with the keyword "new", the variable is created as an object: Avoid String, Number, and Boolean objects. They complicate your code and slow down execution speed. You will learn more about objects later in this tutorial. Alert "John" by extracting information from the person object. const person = { firstName: "John", lastName: "Doe" }; alert(); Start the Exercise 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": 35, "s": 0, "text": "In real life, a car is an object. " }, { "code": null, "e": 112, "s": 35, "text": "A car has properties like weight and color, and methods like start and stop:" }, { "code": null, "e": 195, "s": 112, "text": "All cars have the same properties, but the property values differ from car to car." }, { "code": null, "e": 278, "s": 195, "text": "All cars have the same methods, but the methods are performed \nat different times." }, { "code": null, "e": 362, "s": 278, "text": "You have already learned that JavaScript variables are \ncontainers for data values." }, { "code": null, "e": 429, "s": 362, "text": "This code assigns a simple value (Fiat) to \na variable named car: " }, { "code": null, "e": 495, "s": 429, "text": "Objects are variables too. But objects can contain many \nvalues. " }, { "code": null, "e": 570, "s": 495, "text": "This code assigns many values (Fiat, 500, white) to a\nvariable \nnamed car:" }, { "code": null, "e": 653, "s": 570, "text": "The values are written as name:value pairs (name and value separated by a \ncolon)." }, { "code": null, "e": 720, "s": 653, "text": "It is a common practice to declare objects with the const keyword." }, { "code": null, "e": 788, "s": 720, "text": "Learn more about using const with objects in the chapter: JS Const." }, { "code": null, "e": 856, "s": 788, "text": "You define (and create) a JavaScript object with an object literal:" }, { "code": null, "e": 945, "s": 856, "text": "Spaces and line breaks are not important. An object definition can span multiple lines: " }, { "code": null, "e": 1012, "s": 945, "text": "The name:values pairs in JavaScript objects are called properties:" }, { "code": null, "e": 1059, "s": 1012, "text": "You can access object properties in two ways: " }, { "code": null, "e": 1062, "s": 1059, "text": "or" }, { "code": null, "e": 1132, "s": 1062, "text": "JavaScript objects are containers for named values called properties." }, { "code": null, "e": 1163, "s": 1132, "text": "Objects can also have methods." }, { "code": null, "e": 1217, "s": 1163, "text": "Methods are actions that can be performed on objects." }, { "code": null, "e": 1276, "s": 1217, "text": "Methods are stored in properties as function \ndefinitions." }, { "code": null, "e": 1321, "s": 1276, "text": "A method is a function stored as a property." }, { "code": null, "e": 1377, "s": 1321, "text": "In the example above, this refers to the person object." }, { "code": null, "e": 1435, "s": 1377, "text": "I.E. this.firstName means the firstName property of this." }, { "code": null, "e": 1495, "s": 1435, "text": "I.E. this.firstName means the firstName property of person." }, { "code": null, "e": 1548, "s": 1495, "text": "In JavaScript, the this keyword refers to an object." }, { "code": null, "e": 1616, "s": 1548, "text": "Which object depends on how this is being invoked (used or called)." }, { "code": null, "e": 1690, "s": 1616, "text": "The this keyword refers to different objects depending on how it is used:" }, { "code": null, "e": 1719, "s": 1690, "text": "The JavaScript this Tutorial" }, { "code": null, "e": 1789, "s": 1719, "text": "In a function definition, this refers to the \"owner\" of the function." }, { "code": null, "e": 1873, "s": 1789, "text": "In the example above, this is the person object that \"owns\" the \nfullName function." }, { "code": null, "e": 1949, "s": 1873, "text": "In other words, this.firstName means the firstName property of this object." }, { "code": null, "e": 2004, "s": 1949, "text": "Learn more about this in The JavaScript this Tutorial." }, { "code": null, "e": 2059, "s": 2004, "text": "You access an object method with the following syntax:" }, { "code": null, "e": 2151, "s": 2059, "text": "If you access a method without the () parentheses, it \nwill return the function definition:" }, { "code": null, "e": 2255, "s": 2151, "text": "When a JavaScript variable is declared with the keyword \"new\", the variable is \ncreated as \nan object: " }, { "code": null, "e": 2357, "s": 2255, "text": "Avoid String, Number, and Boolean objects. They complicate your code and slow down \nexecution speed." }, { "code": null, "e": 2415, "s": 2357, "text": "You will learn more about objects later in this tutorial." }, { "code": null, "e": 2478, "s": 2415, "text": "Alert \"John\" by extracting information from the person object." }, { "code": null, "e": 2548, "s": 2478, "text": "const person = {\n firstName: \"John\",\n lastName: \"Doe\"\n};\n\nalert();\n" }, { "code": null, "e": 2567, "s": 2548, "text": "Start the Exercise" }, { "code": null, "e": 2600, "s": 2567, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 2642, "s": 2600, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 2749, "s": 2642, "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": 2768, "s": 2749, "text": "help@w3schools.com" } ]
How to delete specific cache data in ReactJS ?
26 Apr, 2021 We can use the following approach in ReactJS to delete specific cache data in ReactJS. We can delete specific cache data from the browser as per the user requirement. Caching is a technique that helps us to stores a copy of a given resource into our browser and serves it back when requested. Approach: Follow these simple steps in order to delete specific cache data in ReactJS. We have created our deleteSpecificCache function which takes the cache name and deletes it from the browser cache. When we click on the button, the function is triggered, and the given cache gets deleted from the browser and, and we see an alert popup. Creating React Application: Step 1: Create a React application using the following command:npx create-react-app foldername Step 1: Create a React application using the following command: npx create-react-app foldername Step 2: After creating your project folder i.e. folder name, move to it using the following command:cd foldername Step 2: After creating your project folder i.e. folder name, move to it using the following command: cd foldername Project Structure: It will look like the following. Project Structure Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code. App.js import * as React from 'react'; export default function App() { // Function to delete our give cache const deleteSpecificCache = (cacheName) => { if ("caches" in window) { caches.delete(cacheName).then(function (res) { alert(cacheName) return res; }); }}; return ( <div style={{ height: 500, width: '80%' }}> <h4>How to delete specific cache data in ReactJS?</h4> <button onClick={()=>deleteSpecificCache('MyCache')} > Delete Specific Cache</button> </div> );} Step to Run Application: Run the application using the following command from the root directory of the project: npm start Output: Now open your browser and go to http://localhost:3000/, you will see the following output: React-Questions ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Axios in React: A Guide for Beginners ReactJS useNavigate() Hook How to install bootstrap in React.js ? How to create a multi-page website using React.js ? How to do crud operations in ReactJS ? Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? Differences between Functional Components and Class Components in React
[ { "code": null, "e": 28, "s": 0, "text": "\n26 Apr, 2021" }, { "code": null, "e": 321, "s": 28, "text": "We can use the following approach in ReactJS to delete specific cache data in ReactJS. We can delete specific cache data from the browser as per the user requirement. Caching is a technique that helps us to stores a copy of a given resource into our browser and serves it back when requested." }, { "code": null, "e": 661, "s": 321, "text": "Approach: Follow these simple steps in order to delete specific cache data in ReactJS. We have created our deleteSpecificCache function which takes the cache name and deletes it from the browser cache. When we click on the button, the function is triggered, and the given cache gets deleted from the browser and, and we see an alert popup." }, { "code": null, "e": 689, "s": 661, "text": "Creating React Application:" }, { "code": null, "e": 784, "s": 689, "text": "Step 1: Create a React application using the following command:npx create-react-app foldername" }, { "code": null, "e": 848, "s": 784, "text": "Step 1: Create a React application using the following command:" }, { "code": null, "e": 880, "s": 848, "text": "npx create-react-app foldername" }, { "code": null, "e": 994, "s": 880, "text": "Step 2: After creating your project folder i.e. folder name, move to it using the following command:cd foldername" }, { "code": null, "e": 1095, "s": 994, "text": "Step 2: After creating your project folder i.e. folder name, move to it using the following command:" }, { "code": null, "e": 1109, "s": 1095, "text": "cd foldername" }, { "code": null, "e": 1161, "s": 1109, "text": "Project Structure: It will look like the following." }, { "code": null, "e": 1179, "s": 1161, "text": "Project Structure" }, { "code": null, "e": 1309, "s": 1179, "text": "Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code." }, { "code": null, "e": 1316, "s": 1309, "text": "App.js" }, { "code": "import * as React from 'react'; export default function App() { // Function to delete our give cache const deleteSpecificCache = (cacheName) => { if (\"caches\" in window) { caches.delete(cacheName).then(function (res) { alert(cacheName) return res; }); }}; return ( <div style={{ height: 500, width: '80%' }}> <h4>How to delete specific cache data in ReactJS?</h4> <button onClick={()=>deleteSpecificCache('MyCache')} > Delete Specific Cache</button> </div> );}", "e": 1851, "s": 1316, "text": null }, { "code": null, "e": 1964, "s": 1851, "text": "Step to Run Application: Run the application using the following command from the root directory of the project:" }, { "code": null, "e": 1974, "s": 1964, "text": "npm start" }, { "code": null, "e": 2073, "s": 1974, "text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:" }, { "code": null, "e": 2089, "s": 2073, "text": "React-Questions" }, { "code": null, "e": 2097, "s": 2089, "text": "ReactJS" }, { "code": null, "e": 2114, "s": 2097, "text": "Web Technologies" }, { "code": null, "e": 2212, "s": 2114, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2250, "s": 2212, "text": "Axios in React: A Guide for Beginners" }, { "code": null, "e": 2277, "s": 2250, "text": "ReactJS useNavigate() Hook" }, { "code": null, "e": 2316, "s": 2277, "text": "How to install bootstrap in React.js ?" }, { "code": null, "e": 2368, "s": 2316, "text": "How to create a multi-page website using React.js ?" }, { "code": null, "e": 2407, "s": 2368, "text": "How to do crud operations in ReactJS ?" }, { "code": null, "e": 2440, "s": 2407, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 2502, "s": 2440, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 2563, "s": 2502, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2613, "s": 2563, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
How to Get Coordinate Of Screen in Python Turtle ?
21 Jun, 2022 Turtle is a special feature in python which contains a graphical library. In this article we will learn how to Get Coordinate Of Screen in Python Turtle. Turtle has many built in function to create this program we use following. import turtle –> This is the python library which allow us to access turtle library. Turtle()–> This Method is used to make object. onscreenclick(functionname,1) –> This is turtle function which sends the coordinate to function; 1 is for left click and 3 is for Right click speed()–> This is used to increase or decrease the speed of turtle pointer. listen()–> This allows the server to listen to incoming connections. done()–> This is used to hold the screen. Python3 # turtle libraryimport turtle #This to make turtle objecttess=turtle.Turtle() # self defined function to print coordinatedef buttonclick(x,y): print("You clicked at this coordinate({0},{1})".format(x,y)) #onscreen function to send coordinateturtle.onscreenclick(buttonclick,1)turtle.listen() # listen to incoming connectionsturtle.speed(10) # set the speedturtle.done() # hold the screen Above Output shows that coordinates are print where pointer clicks on the Screen varshagumber28 simmytarika5 Python-turtle Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() Python program to convert a list to string Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python Program for Fibonacci numbers
[ { "code": null, "e": 28, "s": 0, "text": "\n21 Jun, 2022" }, { "code": null, "e": 183, "s": 28, "text": "Turtle is a special feature in python which contains a graphical library. In this article we will learn how to Get Coordinate Of Screen in Python Turtle. " }, { "code": null, "e": 258, "s": 183, "text": "Turtle has many built in function to create this program we use following." }, { "code": null, "e": 343, "s": 258, "text": "import turtle –> This is the python library which allow us to access turtle library." }, { "code": null, "e": 390, "s": 343, "text": "Turtle()–> This Method is used to make object." }, { "code": null, "e": 533, "s": 390, "text": "onscreenclick(functionname,1) –> This is turtle function which sends the coordinate to function; 1 is for left click and 3 is for Right click" }, { "code": null, "e": 609, "s": 533, "text": "speed()–> This is used to increase or decrease the speed of turtle pointer." }, { "code": null, "e": 678, "s": 609, "text": "listen()–> This allows the server to listen to incoming connections." }, { "code": null, "e": 723, "s": 678, "text": "done()–> This is used to hold the screen. " }, { "code": null, "e": 733, "s": 725, "text": "Python3" }, { "code": "# turtle libraryimport turtle #This to make turtle objecttess=turtle.Turtle() # self defined function to print coordinatedef buttonclick(x,y): print(\"You clicked at this coordinate({0},{1})\".format(x,y)) #onscreen function to send coordinateturtle.onscreenclick(buttonclick,1)turtle.listen() # listen to incoming connectionsturtle.speed(10) # set the speedturtle.done() # hold the screen", "e": 1130, "s": 733, "text": null }, { "code": null, "e": 1211, "s": 1130, "text": "Above Output shows that coordinates are print where pointer clicks on the Screen" }, { "code": null, "e": 1226, "s": 1211, "text": "varshagumber28" }, { "code": null, "e": 1239, "s": 1226, "text": "simmytarika5" }, { "code": null, "e": 1253, "s": 1239, "text": "Python-turtle" }, { "code": null, "e": 1260, "s": 1253, "text": "Python" }, { "code": null, "e": 1276, "s": 1260, "text": "Python Programs" }, { "code": null, "e": 1374, "s": 1276, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1392, "s": 1374, "text": "Python Dictionary" }, { "code": null, "e": 1434, "s": 1392, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 1456, "s": 1434, "text": "Enumerate() in Python" }, { "code": null, "e": 1491, "s": 1456, "text": "Read a file line by line in Python" }, { "code": null, "e": 1517, "s": 1491, "text": "Python String | replace()" }, { "code": null, "e": 1560, "s": 1517, "text": "Python program to convert a list to string" }, { "code": null, "e": 1582, "s": 1560, "text": "Defaultdict in Python" }, { "code": null, "e": 1621, "s": 1582, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 1659, "s": 1621, "text": "Python | Convert a list to dictionary" } ]
How to show and hide widgets in Tkinter?
Tkinter is a Python library which is used to create and develop GUI-based applications.Let us suppose that we have to create an application such that we can show or hide the widgets. In order to display/show the widget, use pack() geometry manager To hide any widget from the application, use pack_forget() method. Let us take this example to understand how to show/hide widgets − # Import the required libraries from tkinter import * from tkinter import ttk # Create an instance of tkinter frame win = Tk() # Set the size of the tkinter window win.geometry("700x350") # Define the style for combobox widget style = ttk.Style() style.theme_use('xpnative') # Define a function to show/hide widget def show_widget(): label.pack() def hide_widget(): label.pack_forget() b1.configure(text="Show", command=show_widget) # Add a label widget label = ttk.Label(win, text="Eat, Sleep, Code and Repeat", font=('Aerial 11')) label.pack(pady=30) # Add a Button widget b1 = ttk.Button(win, text="Hide", command=hide_widget) b1.pack(pady=20) win.mainloop() Running the above code will open a window that will have a Button to show/hide the widgets from the application. Now, click the button to display/hide the label text from the window.
[ { "code": null, "e": 1370, "s": 1187, "text": "Tkinter is a Python library which is used to create and develop GUI-based applications.Let us suppose that we have to create an application such that we can show or hide the widgets." }, { "code": null, "e": 1435, "s": 1370, "text": "In order to display/show the widget, use pack() geometry manager" }, { "code": null, "e": 1502, "s": 1435, "text": "To hide any widget from the application, use pack_forget() method." }, { "code": null, "e": 1568, "s": 1502, "text": "Let us take this example to understand how to show/hide widgets −" }, { "code": null, "e": 2246, "s": 1568, "text": "# Import the required libraries\nfrom tkinter import *\nfrom tkinter import ttk\n\n# Create an instance of tkinter frame\nwin = Tk()\n\n# Set the size of the tkinter window\nwin.geometry(\"700x350\")\n\n# Define the style for combobox widget\nstyle = ttk.Style()\nstyle.theme_use('xpnative')\n\n# Define a function to show/hide widget\ndef show_widget():\n label.pack()\ndef hide_widget():\n label.pack_forget()\n b1.configure(text=\"Show\", command=show_widget)\n\n# Add a label widget\nlabel = ttk.Label(win, text=\"Eat, Sleep, Code and Repeat\", font=('Aerial 11'))\nlabel.pack(pady=30)\n\n# Add a Button widget\nb1 = ttk.Button(win, text=\"Hide\", command=hide_widget)\nb1.pack(pady=20)\n\nwin.mainloop()" }, { "code": null, "e": 2359, "s": 2246, "text": "Running the above code will open a window that will have a Button to show/hide the widgets from the application." }, { "code": null, "e": 2429, "s": 2359, "text": "Now, click the button to display/hide the label text from the window." } ]
Arduino - micros () function
The micros() function returns the number of microseconds from the time, the Arduino board begins running the current program. This number overflows i.e. goes back to zero after approximately 70 minutes. On 16 MHz Arduino boards (e.g. Duemilanove and Nano), this function has a resolution of four microseconds (i.e. the value returned is always a multiple of four). On 8 MHz Arduino boards (e.g. the LilyPad), this function has a resolution of eight microseconds. micros () ; This function returns number of microseconds since the program started (unsigned long) unsigned long time; void setup() { Serial.begin(9600); } void loop() { Serial.print("Time:"); time = micros(); //prints time since program started Serial.println(time); // wait a second so as not to send massive amounts of data delay(1000); } 65 Lectures 6.5 hours Amit Rana 43 Lectures 3 hours Amit Rana 20 Lectures 2 hours Ashraf Said 19 Lectures 1.5 hours Ashraf Said 11 Lectures 47 mins Ashraf Said 9 Lectures 41 mins Ashraf Said Print Add Notes Bookmark this page
[ { "code": null, "e": 3333, "s": 2870, "text": "The micros() function returns the number of microseconds from the time, the Arduino board begins running the current program. This number overflows i.e. goes back to zero after approximately 70 minutes. On 16 MHz Arduino boards (e.g. Duemilanove and Nano), this function has a resolution of four microseconds (i.e. the value returned is always a multiple of four). On 8 MHz Arduino boards (e.g. the LilyPad), this function has a resolution of eight microseconds." }, { "code": null, "e": 3346, "s": 3333, "text": "micros () ;\n" }, { "code": null, "e": 3433, "s": 3346, "text": "This function returns number of microseconds since the program started (unsigned long)" }, { "code": null, "e": 3697, "s": 3433, "text": "unsigned long time; void setup() { \n Serial.begin(9600); \n} \n\nvoid loop() { \n Serial.print(\"Time:\");\n time = micros(); //prints time since program started\n Serial.println(time); // wait a second so as not to send massive amounts of data\n delay(1000); \n}" }, { "code": null, "e": 3732, "s": 3697, "text": "\n 65 Lectures \n 6.5 hours \n" }, { "code": null, "e": 3743, "s": 3732, "text": " Amit Rana" }, { "code": null, "e": 3776, "s": 3743, "text": "\n 43 Lectures \n 3 hours \n" }, { "code": null, "e": 3787, "s": 3776, "text": " Amit Rana" }, { "code": null, "e": 3820, "s": 3787, "text": "\n 20 Lectures \n 2 hours \n" }, { "code": null, "e": 3833, "s": 3820, "text": " Ashraf Said" }, { "code": null, "e": 3868, "s": 3833, "text": "\n 19 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3881, "s": 3868, "text": " Ashraf Said" }, { "code": null, "e": 3913, "s": 3881, "text": "\n 11 Lectures \n 47 mins\n" }, { "code": null, "e": 3926, "s": 3913, "text": " Ashraf Said" }, { "code": null, "e": 3957, "s": 3926, "text": "\n 9 Lectures \n 41 mins\n" }, { "code": null, "e": 3970, "s": 3957, "text": " Ashraf Said" }, { "code": null, "e": 3977, "s": 3970, "text": " Print" }, { "code": null, "e": 3988, "s": 3977, "text": " Add Notes" } ]
What are runtime errors in JavaScript?
There are three types of errors in programming: (a) Syntax Errors, (b) Runtime Errors, and (c) Logical Errors. Runtime errors, also called exceptions, occur during execution (after compilation/interpretation). For example, the following line causes a runtime error because here the syntax is correct, but at runtime, it is trying to call a method that does not exist. <script> <!-- window.printme(); //--> </script> Exceptions also affect the thread in which they occur, allowing other JavaScript threads to continue normal execution.
[ { "code": null, "e": 1430, "s": 1062, "text": "There are three types of errors in programming: (a) Syntax Errors, (b) Runtime Errors, and (c) Logical Errors. Runtime errors, also called exceptions, occur during execution (after compilation/interpretation). For example, the following line causes a runtime error because here the syntax is correct, but at runtime, it is trying to call a method that does not exist." }, { "code": null, "e": 1490, "s": 1430, "text": "<script>\n <!--\n window.printme();\n //-->\n</script>" }, { "code": null, "e": 1609, "s": 1490, "text": "Exceptions also affect the thread in which they occur, allowing other JavaScript threads to continue normal execution." } ]
Creating a Path Graph Using Networkx in Python - GeeksforGeeks
29 Apr, 2021 A path graph is a connected graph denoted by Pn if it contains n nodes. Nodes are connected in form of a straight line in a path graph. Here we will discuss how networkx module can be used to generate one using its inbuilt path_graph() function. The number of nodes in a path graph(Pn) is N. The number of edges in a path graph(Pn) is N-1. The diameter of the path graph(Pn) i.e maximum distance between any pair of vertices is N-1 which is between 1st and last node. The chromatic number of Path Graph is 2. Nodes are assigned labels from 0 to N-1 Terminal vertices have degree 1 and every other vertex has degree 2. A path graph is a connected graph. Path graph contains no cycle in it. Although the path graph is connected but the removal of any edge will make it unconnected as no cycle is there in Path Graph. It is a Planar Graph. We will use the networkx module for realizing a Path graph. It comes with an inbuilt function networkx.path_graph() and can be illustrated using the networkx.draw() method. This method is straightforward method of creating a desired path graph using appropriate parameters. Syntax: path_graph(n, create_using=None) Parameter: n: Number of nodes we want in path graph. create_using: We can simply pass None or pass nx.DiGraph() as a value to this argument sending nx.Digraph() will lead to creation of a directed path graph. Approach: Import module Create path graph object using path_graph() function as mentioned above. Pass appropriate parameters to the functions Display plot Program: Python3 # import required moduleimport networkx as nx # create objectG = nx.path_graph(5, create_using=nx.DiGraph()) # illustrate graphnx.draw(G, node_color='green') Output: simmytarika5 Graph Python Graph Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2 Topological Sorting Bellman–Ford Algorithm | DP-23 Detect Cycle in a Directed Graph Floyd Warshall Algorithm | DP-16 Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe
[ { "code": null, "e": 25192, "s": 25164, "text": "\n29 Apr, 2021" }, { "code": null, "e": 25438, "s": 25192, "text": "A path graph is a connected graph denoted by Pn if it contains n nodes. Nodes are connected in form of a straight line in a path graph. Here we will discuss how networkx module can be used to generate one using its inbuilt path_graph() function." }, { "code": null, "e": 25484, "s": 25438, "text": "The number of nodes in a path graph(Pn) is N." }, { "code": null, "e": 25532, "s": 25484, "text": "The number of edges in a path graph(Pn) is N-1." }, { "code": null, "e": 25660, "s": 25532, "text": "The diameter of the path graph(Pn) i.e maximum distance between any pair of vertices is N-1 which is between 1st and last node." }, { "code": null, "e": 25701, "s": 25660, "text": "The chromatic number of Path Graph is 2." }, { "code": null, "e": 25741, "s": 25701, "text": "Nodes are assigned labels from 0 to N-1" }, { "code": null, "e": 25810, "s": 25741, "text": "Terminal vertices have degree 1 and every other vertex has degree 2." }, { "code": null, "e": 25845, "s": 25810, "text": "A path graph is a connected graph." }, { "code": null, "e": 25881, "s": 25845, "text": "Path graph contains no cycle in it." }, { "code": null, "e": 26007, "s": 25881, "text": "Although the path graph is connected but the removal of any edge will make it unconnected as no cycle is there in Path Graph." }, { "code": null, "e": 26029, "s": 26007, "text": "It is a Planar Graph." }, { "code": null, "e": 26304, "s": 26029, "text": "We will use the networkx module for realizing a Path graph. It comes with an inbuilt function networkx.path_graph() and can be illustrated using the networkx.draw() method. This method is straightforward method of creating a desired path graph using appropriate parameters. " }, { "code": null, "e": 26346, "s": 26304, "text": "Syntax: path_graph(n, create_using=None)" }, { "code": null, "e": 26357, "s": 26346, "text": "Parameter:" }, { "code": null, "e": 26399, "s": 26357, "text": "n: Number of nodes we want in path graph." }, { "code": null, "e": 26555, "s": 26399, "text": "create_using: We can simply pass None or pass nx.DiGraph() as a value to this argument sending nx.Digraph() will lead to creation of a directed path graph." }, { "code": null, "e": 26565, "s": 26555, "text": "Approach:" }, { "code": null, "e": 26579, "s": 26565, "text": "Import module" }, { "code": null, "e": 26652, "s": 26579, "text": "Create path graph object using path_graph() function as mentioned above." }, { "code": null, "e": 26697, "s": 26652, "text": "Pass appropriate parameters to the functions" }, { "code": null, "e": 26710, "s": 26697, "text": "Display plot" }, { "code": null, "e": 26719, "s": 26710, "text": "Program:" }, { "code": null, "e": 26727, "s": 26719, "text": "Python3" }, { "code": "# import required moduleimport networkx as nx # create objectG = nx.path_graph(5, create_using=nx.DiGraph()) # illustrate graphnx.draw(G, node_color='green')", "e": 26885, "s": 26727, "text": null }, { "code": null, "e": 26893, "s": 26885, "text": "Output:" }, { "code": null, "e": 26906, "s": 26893, "text": "simmytarika5" }, { "code": null, "e": 26912, "s": 26906, "text": "Graph" }, { "code": null, "e": 26919, "s": 26912, "text": "Python" }, { "code": null, "e": 26925, "s": 26919, "text": "Graph" }, { "code": null, "e": 27023, "s": 26925, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27081, "s": 27023, "text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2" }, { "code": null, "e": 27101, "s": 27081, "text": "Topological Sorting" }, { "code": null, "e": 27132, "s": 27101, "text": "Bellman–Ford Algorithm | DP-23" }, { "code": null, "e": 27165, "s": 27132, "text": "Detect Cycle in a Directed Graph" }, { "code": null, "e": 27198, "s": 27165, "text": "Floyd Warshall Algorithm | DP-16" }, { "code": null, "e": 27226, "s": 27198, "text": "Read JSON file using Python" }, { "code": null, "e": 27276, "s": 27226, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 27298, "s": 27276, "text": "Python map() function" } ]
Computer Vision: Instance Segmentation with Mask R-CNN | by Renu Khandelwal | Towards Data Science
This is the fourth part in the series on Computer vision journey. In this article we will explore Mask R-CNN to understand how instance segmentation works with Mask R-CNN and then predict the segmentation for an image with Mask R-CNN using Keras Part 1- CNN, R-CNN, Fast R-CNN, Faster R-CNN Part 2 — Understanding YOLO, YOLOv2, YOLO v3 Part 3- Object Detection with YOLOv3 using Keras What is instance segmentation and how is different from semantic segmentation? Semantic Segmentation detects all the objects present in an image at the pixel level. Outputs regions with different classes or objects Semantic segmentation groups pixels in a semantically meaningful way. Pixels belonging to a person, road, building, fence, bicycle, cars or trees are grouped separately. Instance Segmentation is identifying each object instance for every known object within an image. Instance segmentation assigns a label to each pixel of the image. It is used for tasks such as counting the number of objects Instance segmentation requires Object detection of all objects in an image . Here the goal is to classify individual objects and localize each object instance using a bounding box Segmenting each instance. Here the goal is to classify each pixel into a fixed set of categories without differentiating object instances Mask R-CNN extends Faster R-CNN. What’s different in Mask R-CNN and Faster R-CNN? Mask R-CNN has an additional branch for predicting segmentation masks on each Region of Interest (RoI) in a pixel-to pixel manner Faster R-CNN is not designed for pixel-to-pixel alignment between network inputs and outputs. Faster R-CNN has two outputs For each candidate object, a class label and a bounding-box offset; Mask R-CNN has three outputs For each candidate object, a class label and a bounding-box offset; Third output is the object mask What’s similar between Mask R-CNN and Faster R-CNN? -Both Mask R-CNN and Faster R-CNN have a branch for classification and bounding box regression. -Both use ResNet 101 architecture to extract features from image. -Both use Region Proposal Network(RPN) to generate Region of Interests(RoI) How does Mask R-CNN work? Mask R-CNN model is divided into two parts Region proposal network (RPN) to proposes candidate object bounding boxes. Binary mask classifier to generate mask for every class Image is run through the CNN to generate the feature maps. Region Proposal Network(RPN) uses a CNN to generate the multiple Region of Interest(RoI) using a lightweight binary classifier. It does this using 9 anchors boxes over the image. The classifier returns object/no-object scores. Non Max suppression is applied to Anchors with high objectness score The RoI Align network outputs multiple bounding boxes rather than a single definite one and warp them into a fixed dimension. Warped features are then fed into fully connected layers to make classification using softmax and boundary box prediction is further refined using the regression model Warped features are also fed into Mask classifier, which consists of two CNN’s to output a binary mask for each RoI. Mask Classifier allows the network to generate masks for every class without competition among classes Mask R-CNN uses anchor boxes to detect multiple objects, objects of different scales, and overlapping objects in an image. This improves the speed and efficiency for object detection. Anchor boxes are a set of predefined bounding boxes of a certain height and width. These boxes are defined to capture the scale and aspect ratio of specific object classes you want to detect. To predict multiple objects or multiple instances of objects in an image, Mask R-CNN makes thousands of predictions. Final object detection is done by removing anchor boxes that belong to the background class and the remaining ones are filtered by their confidence score. We find the anchor boxes with IoU greater than 0.5. Anchor boxes with the greatest confidence score are selected using Non-Max suppression explained below IoU computes intersection over the union of the two bounding boxes, the bounding box for the ground truth and the bounding box for the predicted box by algorithm When IoU is 1 that would imply that predicted and the ground-truth bounding boxes overlap perfectly. To detect an Object once in an image, Non-Max suppression considers all bounding boxes with IoU >0.5 What if I have multiple bounding boxes with IoU greater than 0.5? Non-Max Suppression will remove all bounding boxes where IoU is less than or equal to 0.5 Pick the bounding box with the highest value for IoU and suppress the other bounding boxes for identifying the same object For this we use MatterPort Mask R-CNN. The Mask R-CNN model used in this example is pre-trained on the COCO data set. Step 1: Clone the Mask R-CNN repository git clone https://github.com/matterport/Mask_RCNN.gitcd Mask_RCNN$ python setup.py install Step 2: Download the pre-trained weights for COCO model from MatterPort. Place the file in the Mask_RCNN folder with name “mask_rcnn_coco.h5” Step 3: Import the required libraries # import the necessary packagesfrom mrcnn.config import Configfrom mrcnn import model as modellibfrom mrcnn import visualizeimport mrcnnimport numpy as npimport colorsysimport argparseimport imutilsimport randomimport cv2import osfrom matplotlib import pyplotfrom matplotlib.patches import Rectangle%matplotlib inline Step 4: We Create a myMaskRCNNConfig class that inherits from Mask R-CNN Config class. As I am using CPU hence setting the GPU_COUNT=1 COCO dataset has 80 labels so we set the NUM_CLASSES to 80 + 1 (for background) class myMaskRCNNConfig(Config): # give the configuration a recognizable name NAME = “MaskRCNN_inference” # set the number of GPUs to use along with the number of images # per GPU GPU_COUNT = 1 IMAGES_PER_GPU = 1 # number of classes (we would normally add +1 for the background # but the background class is *already* included in the class # names) NUM_CLASSES = 1+80 Step 5: Create an instance of the myMaskRCNNConfig class config = myMaskRCNNConfig() Step 6 :Initialize Mask R-CNN model for “inference” using the Config instance that we created print(“loading weights for Mask R-CNN model...”)model = modellib.MaskRCNN(mode=”inference”, config=config, model_dir=’./’) Step 7: Load the weights for the Mask R-CNN. These are the pre-trained weights for COCO data set model.load_weights(‘mask_rcnn_coco.h5’, by_name=True) Step 8: Define 80 classes that the coco model and 1 for background(BG) class_names = [‘BG’, ‘person’, ‘bicycle’, ‘car’, ‘motorcycle’, ‘airplane’, ‘bus’, ‘train’, ‘truck’, ‘boat’, ‘traffic light’, ‘fire hydrant’, ‘stop sign’, ‘parking meter’, ‘bench’, ‘bird’, ‘cat’, ‘dog’, ‘horse’, ‘sheep’, ‘cow’, ‘elephant’, ‘bear’, ‘zebra’, ‘giraffe’, ‘backpack’, ‘umbrella’, ‘handbag’, ‘tie’, ‘suitcase’, ‘frisbee’, ‘skis’, ‘snowboard’, ‘sports ball’, ‘kite’, ‘baseball bat’, ‘baseball glove’, ‘skateboard’, ‘surfboard’, ‘tennis racket’, ‘bottle’, ‘wine glass’, ‘cup’, ‘fork’, ‘knife’, ‘spoon’, ‘bowl’, ‘banana’, ‘apple’, ‘sandwich’, ‘orange’, ‘broccoli’, ‘carrot’, ‘hot dog’, ‘pizza’, ‘donut’, ‘cake’, ‘chair’, ‘couch’, ‘potted plant’, ‘bed’, ‘dining table’, ‘toilet’, ‘tv’, ‘laptop’, ‘mouse’, ‘remote’, ‘keyboard’, ‘cell phone’, ‘microwave’, ‘oven’, ‘toaster’, ‘sink’, ‘refrigerator’, ‘book’, ‘clock’, ‘vase’, ‘scissors’, ‘teddy bear’, ‘hair drier’, ‘toothbrush’] Step 9: Function for drawing boxes for objected detected in the image # draw an image with detected objectsdef draw_image_with_boxes(filename, boxes_list): # load the image data = pyplot.imread(filename) # plot the image pyplot.imshow(data) # get the context for drawing boxes ax = pyplot.gca() # plot each box for box in boxes_list: # get coordinates y1, x1, y2, x2 = box # calculate width and height of the box width, height = x2 - x1, y2 - y1 # create the shape rect = Rectangle((x1, y1), width, height, fill=False, color='red', lw=5) # draw the box ax.add_patch(rect) # show the plot pyplot.show() Step 10: We finally make the prediction and draw bounding boxes around the detected objects Loading the image and then converting it to a numpy array from keras.preprocessing.image import load_imgfrom keras.preprocessing.image import img_to_arrayimg = load_img(‘donuts.jpg’)pyplot.imshow(img)img = img_to_array(img) we now make the prediction # make predictionresults = model.detect([img], verbose=0) Result is a dictionary for the image that we passed into the detect() function. Dictionary has keys for the bounding boxes, masks, class and the scores. Each key points to a list for multiple possible objects detected in the image. The keys of the dictionary are ‘rois‘: Regions-of-interest (ROI) for detected objects. ‘masks‘: Masks for the detected objects. ‘class_ids‘: Class integers for the detected objects. ‘scores‘: Confidence Probability for each predicted class. Step 11: Visualize the results by drawing bounding box around the region of interest(rois) # visualize the resultsdraw_image_with_boxes('donuts.jpg', results[0]['rois']) Drawing the mask # get dictionary for first predictionfrom mrcnn.visualize import display_instancesr = results[0]# show photo with bounding boxes, masks, class labels and scoresdisplay_instances(img, r[‘rois’], r[‘masks’], r[‘class_ids’], class_names, r[‘scores’]) To find the number of object and classes classes= r['class_ids']print("Total Objects found", len(classes))for i in range(len(classes)): print(class_names[classes[i]]) Code for prediction using Mask R-CNN available at github Mask R-CNN paper
[ { "code": null, "e": 418, "s": 172, "text": "This is the fourth part in the series on Computer vision journey. In this article we will explore Mask R-CNN to understand how instance segmentation works with Mask R-CNN and then predict the segmentation for an image with Mask R-CNN using Keras" }, { "code": null, "e": 463, "s": 418, "text": "Part 1- CNN, R-CNN, Fast R-CNN, Faster R-CNN" }, { "code": null, "e": 508, "s": 463, "text": "Part 2 — Understanding YOLO, YOLOv2, YOLO v3" }, { "code": null, "e": 557, "s": 508, "text": "Part 3- Object Detection with YOLOv3 using Keras" }, { "code": null, "e": 636, "s": 557, "text": "What is instance segmentation and how is different from semantic segmentation?" }, { "code": null, "e": 772, "s": 636, "text": "Semantic Segmentation detects all the objects present in an image at the pixel level. Outputs regions with different classes or objects" }, { "code": null, "e": 942, "s": 772, "text": "Semantic segmentation groups pixels in a semantically meaningful way. Pixels belonging to a person, road, building, fence, bicycle, cars or trees are grouped separately." }, { "code": null, "e": 1040, "s": 942, "text": "Instance Segmentation is identifying each object instance for every known object within an image." }, { "code": null, "e": 1166, "s": 1040, "text": "Instance segmentation assigns a label to each pixel of the image. It is used for tasks such as counting the number of objects" }, { "code": null, "e": 1197, "s": 1166, "text": "Instance segmentation requires" }, { "code": null, "e": 1346, "s": 1197, "text": "Object detection of all objects in an image . Here the goal is to classify individual objects and localize each object instance using a bounding box" }, { "code": null, "e": 1484, "s": 1346, "text": "Segmenting each instance. Here the goal is to classify each pixel into a fixed set of categories without differentiating object instances" }, { "code": null, "e": 1517, "s": 1484, "text": "Mask R-CNN extends Faster R-CNN." }, { "code": null, "e": 1566, "s": 1517, "text": "What’s different in Mask R-CNN and Faster R-CNN?" }, { "code": null, "e": 1696, "s": 1566, "text": "Mask R-CNN has an additional branch for predicting segmentation masks on each Region of Interest (RoI) in a pixel-to pixel manner" }, { "code": null, "e": 1790, "s": 1696, "text": "Faster R-CNN is not designed for pixel-to-pixel alignment between network inputs and outputs." }, { "code": null, "e": 1819, "s": 1790, "text": "Faster R-CNN has two outputs" }, { "code": null, "e": 1887, "s": 1819, "text": "For each candidate object, a class label and a bounding-box offset;" }, { "code": null, "e": 1916, "s": 1887, "text": "Mask R-CNN has three outputs" }, { "code": null, "e": 1984, "s": 1916, "text": "For each candidate object, a class label and a bounding-box offset;" }, { "code": null, "e": 2016, "s": 1984, "text": "Third output is the object mask" }, { "code": null, "e": 2068, "s": 2016, "text": "What’s similar between Mask R-CNN and Faster R-CNN?" }, { "code": null, "e": 2164, "s": 2068, "text": "-Both Mask R-CNN and Faster R-CNN have a branch for classification and bounding box regression." }, { "code": null, "e": 2230, "s": 2164, "text": "-Both use ResNet 101 architecture to extract features from image." }, { "code": null, "e": 2306, "s": 2230, "text": "-Both use Region Proposal Network(RPN) to generate Region of Interests(RoI)" }, { "code": null, "e": 2332, "s": 2306, "text": "How does Mask R-CNN work?" }, { "code": null, "e": 2375, "s": 2332, "text": "Mask R-CNN model is divided into two parts" }, { "code": null, "e": 2450, "s": 2375, "text": "Region proposal network (RPN) to proposes candidate object bounding boxes." }, { "code": null, "e": 2506, "s": 2450, "text": "Binary mask classifier to generate mask for every class" }, { "code": null, "e": 2565, "s": 2506, "text": "Image is run through the CNN to generate the feature maps." }, { "code": null, "e": 2861, "s": 2565, "text": "Region Proposal Network(RPN) uses a CNN to generate the multiple Region of Interest(RoI) using a lightweight binary classifier. It does this using 9 anchors boxes over the image. The classifier returns object/no-object scores. Non Max suppression is applied to Anchors with high objectness score" }, { "code": null, "e": 2987, "s": 2861, "text": "The RoI Align network outputs multiple bounding boxes rather than a single definite one and warp them into a fixed dimension." }, { "code": null, "e": 3155, "s": 2987, "text": "Warped features are then fed into fully connected layers to make classification using softmax and boundary box prediction is further refined using the regression model" }, { "code": null, "e": 3375, "s": 3155, "text": "Warped features are also fed into Mask classifier, which consists of two CNN’s to output a binary mask for each RoI. Mask Classifier allows the network to generate masks for every class without competition among classes" }, { "code": null, "e": 3559, "s": 3375, "text": "Mask R-CNN uses anchor boxes to detect multiple objects, objects of different scales, and overlapping objects in an image. This improves the speed and efficiency for object detection." }, { "code": null, "e": 3751, "s": 3559, "text": "Anchor boxes are a set of predefined bounding boxes of a certain height and width. These boxes are defined to capture the scale and aspect ratio of specific object classes you want to detect." }, { "code": null, "e": 4178, "s": 3751, "text": "To predict multiple objects or multiple instances of objects in an image, Mask R-CNN makes thousands of predictions. Final object detection is done by removing anchor boxes that belong to the background class and the remaining ones are filtered by their confidence score. We find the anchor boxes with IoU greater than 0.5. Anchor boxes with the greatest confidence score are selected using Non-Max suppression explained below" }, { "code": null, "e": 4340, "s": 4178, "text": "IoU computes intersection over the union of the two bounding boxes, the bounding box for the ground truth and the bounding box for the predicted box by algorithm" }, { "code": null, "e": 4441, "s": 4340, "text": "When IoU is 1 that would imply that predicted and the ground-truth bounding boxes overlap perfectly." }, { "code": null, "e": 4542, "s": 4441, "text": "To detect an Object once in an image, Non-Max suppression considers all bounding boxes with IoU >0.5" }, { "code": null, "e": 4608, "s": 4542, "text": "What if I have multiple bounding boxes with IoU greater than 0.5?" }, { "code": null, "e": 4698, "s": 4608, "text": "Non-Max Suppression will remove all bounding boxes where IoU is less than or equal to 0.5" }, { "code": null, "e": 4821, "s": 4698, "text": "Pick the bounding box with the highest value for IoU and suppress the other bounding boxes for identifying the same object" }, { "code": null, "e": 4939, "s": 4821, "text": "For this we use MatterPort Mask R-CNN. The Mask R-CNN model used in this example is pre-trained on the COCO data set." }, { "code": null, "e": 4979, "s": 4939, "text": "Step 1: Clone the Mask R-CNN repository" }, { "code": null, "e": 5070, "s": 4979, "text": "git clone https://github.com/matterport/Mask_RCNN.gitcd Mask_RCNN$ python setup.py install" }, { "code": null, "e": 5212, "s": 5070, "text": "Step 2: Download the pre-trained weights for COCO model from MatterPort. Place the file in the Mask_RCNN folder with name “mask_rcnn_coco.h5”" }, { "code": null, "e": 5250, "s": 5212, "text": "Step 3: Import the required libraries" }, { "code": null, "e": 5568, "s": 5250, "text": "# import the necessary packagesfrom mrcnn.config import Configfrom mrcnn import model as modellibfrom mrcnn import visualizeimport mrcnnimport numpy as npimport colorsysimport argparseimport imutilsimport randomimport cv2import osfrom matplotlib import pyplotfrom matplotlib.patches import Rectangle%matplotlib inline" }, { "code": null, "e": 5655, "s": 5568, "text": "Step 4: We Create a myMaskRCNNConfig class that inherits from Mask R-CNN Config class." }, { "code": null, "e": 5703, "s": 5655, "text": "As I am using CPU hence setting the GPU_COUNT=1" }, { "code": null, "e": 5783, "s": 5703, "text": "COCO dataset has 80 labels so we set the NUM_CLASSES to 80 + 1 (for background)" }, { "code": null, "e": 6152, "s": 5783, "text": "class myMaskRCNNConfig(Config): # give the configuration a recognizable name NAME = “MaskRCNN_inference” # set the number of GPUs to use along with the number of images # per GPU GPU_COUNT = 1 IMAGES_PER_GPU = 1 # number of classes (we would normally add +1 for the background # but the background class is *already* included in the class # names) NUM_CLASSES = 1+80" }, { "code": null, "e": 6209, "s": 6152, "text": "Step 5: Create an instance of the myMaskRCNNConfig class" }, { "code": null, "e": 6237, "s": 6209, "text": "config = myMaskRCNNConfig()" }, { "code": null, "e": 6331, "s": 6237, "text": "Step 6 :Initialize Mask R-CNN model for “inference” using the Config instance that we created" }, { "code": null, "e": 6455, "s": 6331, "text": "print(“loading weights for Mask R-CNN model...”)model = modellib.MaskRCNN(mode=”inference”, config=config, model_dir=’./’)" }, { "code": null, "e": 6552, "s": 6455, "text": "Step 7: Load the weights for the Mask R-CNN. These are the pre-trained weights for COCO data set" }, { "code": null, "e": 6606, "s": 6552, "text": "model.load_weights(‘mask_rcnn_coco.h5’, by_name=True)" }, { "code": null, "e": 6677, "s": 6606, "text": "Step 8: Define 80 classes that the coco model and 1 for background(BG)" }, { "code": null, "e": 7559, "s": 6677, "text": "class_names = [‘BG’, ‘person’, ‘bicycle’, ‘car’, ‘motorcycle’, ‘airplane’, ‘bus’, ‘train’, ‘truck’, ‘boat’, ‘traffic light’, ‘fire hydrant’, ‘stop sign’, ‘parking meter’, ‘bench’, ‘bird’, ‘cat’, ‘dog’, ‘horse’, ‘sheep’, ‘cow’, ‘elephant’, ‘bear’, ‘zebra’, ‘giraffe’, ‘backpack’, ‘umbrella’, ‘handbag’, ‘tie’, ‘suitcase’, ‘frisbee’, ‘skis’, ‘snowboard’, ‘sports ball’, ‘kite’, ‘baseball bat’, ‘baseball glove’, ‘skateboard’, ‘surfboard’, ‘tennis racket’, ‘bottle’, ‘wine glass’, ‘cup’, ‘fork’, ‘knife’, ‘spoon’, ‘bowl’, ‘banana’, ‘apple’, ‘sandwich’, ‘orange’, ‘broccoli’, ‘carrot’, ‘hot dog’, ‘pizza’, ‘donut’, ‘cake’, ‘chair’, ‘couch’, ‘potted plant’, ‘bed’, ‘dining table’, ‘toilet’, ‘tv’, ‘laptop’, ‘mouse’, ‘remote’, ‘keyboard’, ‘cell phone’, ‘microwave’, ‘oven’, ‘toaster’, ‘sink’, ‘refrigerator’, ‘book’, ‘clock’, ‘vase’, ‘scissors’, ‘teddy bear’, ‘hair drier’, ‘toothbrush’]" }, { "code": null, "e": 7629, "s": 7559, "text": "Step 9: Function for drawing boxes for objected detected in the image" }, { "code": null, "e": 8273, "s": 7629, "text": "# draw an image with detected objectsdef draw_image_with_boxes(filename, boxes_list): # load the image data = pyplot.imread(filename) # plot the image pyplot.imshow(data) # get the context for drawing boxes ax = pyplot.gca() # plot each box for box in boxes_list: # get coordinates y1, x1, y2, x2 = box # calculate width and height of the box width, height = x2 - x1, y2 - y1 # create the shape rect = Rectangle((x1, y1), width, height, fill=False, color='red', lw=5) # draw the box ax.add_patch(rect) # show the plot pyplot.show()" }, { "code": null, "e": 8365, "s": 8273, "text": "Step 10: We finally make the prediction and draw bounding boxes around the detected objects" }, { "code": null, "e": 8423, "s": 8365, "text": "Loading the image and then converting it to a numpy array" }, { "code": null, "e": 8589, "s": 8423, "text": "from keras.preprocessing.image import load_imgfrom keras.preprocessing.image import img_to_arrayimg = load_img(‘donuts.jpg’)pyplot.imshow(img)img = img_to_array(img)" }, { "code": null, "e": 8616, "s": 8589, "text": "we now make the prediction" }, { "code": null, "e": 8674, "s": 8616, "text": "# make predictionresults = model.detect([img], verbose=0)" }, { "code": null, "e": 8754, "s": 8674, "text": "Result is a dictionary for the image that we passed into the detect() function." }, { "code": null, "e": 8906, "s": 8754, "text": "Dictionary has keys for the bounding boxes, masks, class and the scores. Each key points to a list for multiple possible objects detected in the image." }, { "code": null, "e": 8937, "s": 8906, "text": "The keys of the dictionary are" }, { "code": null, "e": 8993, "s": 8937, "text": "‘rois‘: Regions-of-interest (ROI) for detected objects." }, { "code": null, "e": 9034, "s": 8993, "text": "‘masks‘: Masks for the detected objects." }, { "code": null, "e": 9088, "s": 9034, "text": "‘class_ids‘: Class integers for the detected objects." }, { "code": null, "e": 9147, "s": 9088, "text": "‘scores‘: Confidence Probability for each predicted class." }, { "code": null, "e": 9238, "s": 9147, "text": "Step 11: Visualize the results by drawing bounding box around the region of interest(rois)" }, { "code": null, "e": 9317, "s": 9238, "text": "# visualize the resultsdraw_image_with_boxes('donuts.jpg', results[0]['rois'])" }, { "code": null, "e": 9334, "s": 9317, "text": "Drawing the mask" }, { "code": null, "e": 9582, "s": 9334, "text": "# get dictionary for first predictionfrom mrcnn.visualize import display_instancesr = results[0]# show photo with bounding boxes, masks, class labels and scoresdisplay_instances(img, r[‘rois’], r[‘masks’], r[‘class_ids’], class_names, r[‘scores’])" }, { "code": null, "e": 9623, "s": 9582, "text": "To find the number of object and classes" }, { "code": null, "e": 9752, "s": 9623, "text": "classes= r['class_ids']print(\"Total Objects found\", len(classes))for i in range(len(classes)): print(class_names[classes[i]])" }, { "code": null, "e": 9809, "s": 9752, "text": "Code for prediction using Mask R-CNN available at github" } ]
int(5) vs. int(10) in MySQL?
The value in the parentheses is used to display only the width and sets the zerofill. The width is 5 for int(5), whereas 10 for int(10). Let us see another example with a different width value set for int. Let us first create a table. Here, we have set the int to int(11) and int(13). The following is the query to create a table − mysql> create table intVsIntAnyThingDemo −> ( −> Number1 int(11) unsigned zerofill, −> Number int(13) unsigned zerofill −> ); Query OK, 0 rows affected (1.17 sec) Now you can insert record in the table with the help of insert command. The query is as follows − mysql> insert into intVsIntAnyThingDemo values(12345,6789); Query OK, 1 row affected (0.44 sec) mysql> insert into intVsIntAnyThingDemo values(3,2); Query OK, 1 row affected (0.20 sec) mysql> insert into intVsIntAnyThingDemo values(12,89); Query OK, 1 row affected (0.15 sec) mysql> insert into intVsIntAnyThingDemo values(123,6789); Query OK, 1 row affected (0.17 sec) mysql> insert into intVsIntAnyThingDemo values(1234,6789); Query OK, 1 row affected (0.14 sec) Display all records with the help of select statement. The query is as follows − mysql> select *from intVsIntAnyThingDemo; The following is the output displaying zero fill for the total width set for int − +-------------+---------------+ | Number1 | Number | +-------------+---------------+ | 00000012345 | 0000000006789 | | 00000000003 | 0000000000002 | | 00000000012 | 0000000000089 | | 00000000123 | 0000000006789 | | 00000001234 | 0000000006789 | +-------------+---------------+ 5 rows in set (0.00 sec)
[ { "code": null, "e": 1268, "s": 1062, "text": "The value in the parentheses is used to display only the width and sets the zerofill. The width is 5 for int(5), whereas 10 for int(10). Let us see another example with a different width value set for int." }, { "code": null, "e": 1394, "s": 1268, "text": "Let us first create a table. Here, we have set the int to int(11) and int(13). The following is the query to create a table −" }, { "code": null, "e": 1557, "s": 1394, "text": "mysql> create table intVsIntAnyThingDemo\n−> (\n−> Number1 int(11) unsigned zerofill,\n−> Number int(13) unsigned zerofill\n−> );\nQuery OK, 0 rows affected (1.17 sec)" }, { "code": null, "e": 1655, "s": 1557, "text": "Now you can insert record in the table with the help of insert command. The query is as follows −" }, { "code": null, "e": 2124, "s": 1655, "text": "mysql> insert into intVsIntAnyThingDemo values(12345,6789);\nQuery OK, 1 row affected (0.44 sec)\n\nmysql> insert into intVsIntAnyThingDemo values(3,2);\nQuery OK, 1 row affected (0.20 sec)\n\nmysql> insert into intVsIntAnyThingDemo values(12,89);\nQuery OK, 1 row affected (0.15 sec)\n\nmysql> insert into intVsIntAnyThingDemo values(123,6789);\nQuery OK, 1 row affected (0.17 sec)\n\nmysql> insert into intVsIntAnyThingDemo values(1234,6789);\nQuery OK, 1 row affected (0.14 sec)" }, { "code": null, "e": 2205, "s": 2124, "text": "Display all records with the help of select statement. The query is as follows −" }, { "code": null, "e": 2247, "s": 2205, "text": "mysql> select *from intVsIntAnyThingDemo;" }, { "code": null, "e": 2330, "s": 2247, "text": "The following is the output displaying zero fill for the total width set for int −" }, { "code": null, "e": 2643, "s": 2330, "text": "+-------------+---------------+\n| Number1 | Number |\n+-------------+---------------+\n| 00000012345 | 0000000006789 |\n| 00000000003 | 0000000000002 |\n| 00000000012 | 0000000000089 |\n| 00000000123 | 0000000006789 |\n| 00000001234 | 0000000006789 |\n+-------------+---------------+\n5 rows in set (0.00 sec)" } ]
R Tutorial
R is a programming language. R is often used for statistical computing and graphical presentation to analyze and visualize data. With our "Try it Yourself" editor, you can edit R code and view the result. How to output some text, and how to do a simple calculation in R: Result: How you can use R to easily create a graph with numbers from 1 to 10 on both the x and y axis: Result: We recommend reading this tutorial, in the sequence listed in the left menu. Insert the missing part of the code below to output "Hello World". Hello World Start the Exercise Learn by examples! This tutorial supplements all explanations with clarifying examples. See All R Examples Learn by taking a quiz! This quiz will give you a signal of how much you know about R. Take the R Quiz 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": 29, "s": 0, "text": "R is a programming language." }, { "code": null, "e": 132, "s": 29, "text": "R is often used for statistical computing and graphical presentation to analyze \n and visualize data." }, { "code": null, "e": 208, "s": 132, "text": "With our \"Try it Yourself\" editor, you can edit R code and view the result." }, { "code": null, "e": 274, "s": 208, "text": "How to output some text, and how to do a simple calculation in R:" }, { "code": null, "e": 282, "s": 274, "text": "Result:" }, { "code": null, "e": 378, "s": 282, "text": "How you can use R to easily create a graph with \nnumbers from 1 to 10 on both the x and y axis:" }, { "code": null, "e": 386, "s": 378, "text": "Result:" }, { "code": null, "e": 463, "s": 386, "text": "We recommend reading this tutorial, in the sequence listed in the left menu." }, { "code": null, "e": 530, "s": 463, "text": "Insert the missing part of the code below to output \"Hello World\"." }, { "code": null, "e": 543, "s": 530, "text": "Hello World\n" }, { "code": null, "e": 562, "s": 543, "text": "Start the Exercise" }, { "code": null, "e": 650, "s": 562, "text": "Learn by examples! This tutorial supplements all explanations with clarifying examples." }, { "code": null, "e": 670, "s": 650, "text": "\nSee All R Examples" }, { "code": null, "e": 757, "s": 670, "text": "Learn by taking a quiz! This quiz will give you a signal of how much you know about R." }, { "code": null, "e": 773, "s": 757, "text": "Take the R Quiz" }, { "code": null, "e": 806, "s": 773, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 848, "s": 806, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 955, "s": 848, "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": 974, "s": 955, "text": "help@w3schools.com" } ]
How to put data of any size in the EEPROM using Arduino?
Arduino Uno has 1 kB of EEPROM storage. EEPROM is a type of non-volatile memory, i.e., its contents are preserved even after power-down. Therefore, it can be used to store data that you want to be unchanged across power cycles. Configurations or settings are examples of such data. In this article, we will see how to put data of any size (not just a byte) in the EEPROM. We will be walking through an inbuilt example in Arduino. The EEPROM examples can be accessed from: File → Examples → EEPROM. We will look at the eeprom_put example. The main function of interest is EEPROM.put(). It takes two arguments, the starting address from which to start writing/ updating data, and the data to be written (which can be of a primitive type, like float, or a custom struct). Examples of other primitive data types are short, int, long, char, double, etc. The .put() function behaves like the .update() function, i.e., it writes to the EEPROM only if the new value to be written is different from the existing value stored in that memory location. We begin with the inclusion of the library. #include <EEPROM.h> Next, we a struct is defined, which contains two floats, and a character array. struct MyObject { float field1; byte field2; char name[10]; }; Within the Setup, we first initialize Serial. Next, we initialize a float, and write it to the beginning of the EEPROM (address = 0). We then advance the address variable by the size of the float (using the sizeof() function), and store a struct (using the structure defined earlier). void setup() { Serial.begin(9600); while (!Serial) { ; // wait for serial port to connect. Needed for native USB port only } float f = 123.456f; //Variable to store in EEPROM. int eeAddress = 0; // Location we want the data to be put. // One simple call, with the address first and the object second. EEPROM.put(eeAddress, f); Serial.println("Written float data type!"); /** Put is designed for use with custom structures also. **/ // Data to store. MyObject customVar = { 3.14f, 65, "Working!" }; eeAddress += sizeof(float); // Move address to the next byte after float 'f'. EEPROM.put(eeAddress, customVar); Serial.print("Written custom data type! \n\nView the example sketch eeprom_get to see how you can retrieve the values!"); } Nothing happens in the loop. void loop() { /* Empty loop */ } This example is a precursor to the eeprom_get example. In other words, the eeprom_get example will assume that you've run this eeprom_put example on your Arduino once.
[ { "code": null, "e": 1344, "s": 1062, "text": "Arduino Uno has 1 kB of EEPROM storage. EEPROM is a type of non-volatile memory, i.e., its contents are preserved even after power-down. Therefore, it can be used to store data that you want to be unchanged across power cycles. Configurations or settings are examples of such data." }, { "code": null, "e": 1560, "s": 1344, "text": "In this article, we will see how to put data of any size (not just a byte) in the EEPROM. We will be walking through an inbuilt example in Arduino. The EEPROM examples can be accessed from: File → Examples → EEPROM." }, { "code": null, "e": 2103, "s": 1560, "text": "We will look at the eeprom_put example. The main function of interest is EEPROM.put(). It takes two arguments, the starting address from which to start writing/ updating data, and the data to be written (which can be of a primitive type, like float, or a custom struct). Examples of other primitive data types are short, int, long, char, double, etc. The .put() function behaves like the .update() function, i.e., it writes to the EEPROM only if the new value to be written is different from the existing value stored in that memory location." }, { "code": null, "e": 2147, "s": 2103, "text": "We begin with the inclusion of the library." }, { "code": null, "e": 2167, "s": 2147, "text": "#include <EEPROM.h>" }, { "code": null, "e": 2247, "s": 2167, "text": "Next, we a struct is defined, which contains two floats, and a character array." }, { "code": null, "e": 2319, "s": 2247, "text": "struct MyObject {\n float field1;\n byte field2;\n char name[10];\n};" }, { "code": null, "e": 2604, "s": 2319, "text": "Within the Setup, we first initialize Serial. Next, we initialize a float, and write it to the beginning of the EEPROM (address = 0). We then advance the address variable by the size of the float (using the sizeof() function), and store a struct (using the structure defined earlier)." }, { "code": null, "e": 3415, "s": 2604, "text": "void setup() {\n\n Serial.begin(9600);\n while (!Serial) {\n ; // wait for serial port to connect. Needed for native USB port only\n }\n\n float f = 123.456f; //Variable to store in EEPROM.\n int eeAddress = 0; // Location we want the data to be put.\n\n // One simple call, with the address first and the object second.\n EEPROM.put(eeAddress, f);\n\n Serial.println(\"Written float data type!\");\n\n /** Put is designed for use with custom structures also. **/\n\n // Data to store.\n MyObject customVar = {\n 3.14f,\n 65,\n \"Working!\"\n };\n\n eeAddress += sizeof(float); // Move address to the next byte after float 'f'.\n\n EEPROM.put(eeAddress, customVar);\n Serial.print(\"Written custom data type! \\n\\nView the example sketch eeprom_get to see how you can retrieve the values!\");\n}" }, { "code": null, "e": 3444, "s": 3415, "text": "Nothing happens in the loop." }, { "code": null, "e": 3480, "s": 3444, "text": "void loop() {\n /* Empty loop */\n}" }, { "code": null, "e": 3648, "s": 3480, "text": "This example is a precursor to the eeprom_get example. In other words, the eeprom_get example will assume that you've run this eeprom_put example on your Arduino once." } ]
QlikView - Master Calendar
In QlikView, many times we need to create a calendar reference object, which can be linked to any data set present in QlikView's memory. For example, you have a table that captures the sales amount and sales date but does not store the weekday or quarter, which corresponds to that date. In such a scenario, we create a Master Calendar which will supply the additional date fields like Quarter, Day etc. as required by any data set. Let us consider the following CSV data files, which are used as input for further illustrations. SalesDate,SalesVolume 3/28/2012,3152 3/30/2012,2458 3/31/2012,4105 4/8/2012,6245 4/10/2012,5816 4/11/2012,3522 We load the above input data using the script editor, which is invoked by pressing Control+E. Choose the option Table Files and browse for the Input file. Next, we load the above data to QlikView's memory and create a Table Box by using the menu Layout → New Sheet Objects → Table Box where we choose all the available fields to be displayed as shown below. Next, we create the Master Calendar by writing the following script in the script editor. Here we use the table DailySales as a resident table from which we capture the Maximum and Minimum dates. We load each of the dates within this range using the second load statement above the resident load. Finally, we have a third load statement, which extracts the year, quarter, month etc. from the SalesDate values. After creation of the complete load script along with the master calendar, we create a table box to view the data using the menu Layout → New Sheet Objects → Table Box The final output shows the table showing the Quarter and Month values, which are created using the Sales data and Master Calendar. 70 Lectures 5 hours Arthur Fong Print Add Notes Bookmark this page
[ { "code": null, "e": 3353, "s": 2920, "text": "In QlikView, many times we need to create a calendar reference object, which can be linked to any data set present in QlikView's memory. For example, you have a table that captures the sales amount and sales date but does not store the weekday or quarter, which corresponds to that date. In such a scenario, we create a Master Calendar which will supply the additional date fields like Quarter, Day etc. as required by any data set." }, { "code": null, "e": 3450, "s": 3353, "text": "Let us consider the following CSV data files, which are used as input for further illustrations." }, { "code": null, "e": 3562, "s": 3450, "text": "SalesDate,SalesVolume\n3/28/2012,3152\n3/30/2012,2458\n3/31/2012,4105\n4/8/2012,6245\n4/10/2012,5816\n4/11/2012,3522\n" }, { "code": null, "e": 3717, "s": 3562, "text": "We load the above input data using the script editor, which is invoked by pressing Control+E. Choose the option Table Files and browse for the Input file." }, { "code": null, "e": 3920, "s": 3717, "text": "Next, we load the above data to QlikView's memory and create a Table Box by using the menu Layout → New Sheet Objects → Table Box where we choose all the available fields to be displayed as shown below." }, { "code": null, "e": 4330, "s": 3920, "text": "Next, we create the Master Calendar by writing the following script in the script editor. Here we use the table DailySales as a resident table from which we capture the Maximum and Minimum dates. We load each of the dates within this range using the second load statement above the resident load. Finally, we have a third load statement, which extracts the year, quarter, month etc. from the SalesDate values." }, { "code": null, "e": 4498, "s": 4330, "text": "After creation of the complete load script along with the master calendar, we create a table box to view the data using the menu Layout → New Sheet Objects → Table Box" }, { "code": null, "e": 4629, "s": 4498, "text": "The final output shows the table showing the Quarter and Month values, which are created using the Sales data and Master Calendar." }, { "code": null, "e": 4662, "s": 4629, "text": "\n 70 Lectures \n 5 hours \n" }, { "code": null, "e": 4675, "s": 4662, "text": " Arthur Fong" }, { "code": null, "e": 4682, "s": 4675, "text": " Print" }, { "code": null, "e": 4693, "s": 4682, "text": " Add Notes" } ]
XML Functionalities in Oracle. An overview of implementation and... | by Gaurav Goel | Towards Data Science
There is always an extensive demand for exchanging data between different sources without worrying about how the receiver will use it or how it will be displayed. XML does that thing for us. It’s a W3C(World Wide Web Consortium) initiative that allows information to be encoded in meaningful structure and rules that humans and machines can understand easily. XML stands for eXtensible Markup Language. XML is not a replacement of HTML. While HTML is designed with focus on how to ‘display’ data, XML is designed how to ‘store’ and ‘transport’ it. XML, in itself, does not DO anything. Let’s look at a sample xml document: <message><to>Tom</to><from>Bill</from><body>Send me your phone number</body></message> The above XML document contains a message with a body having a sender and receiver information. But it does not do anything on its own. It has just structured and stored information. Someone has to write a software code to receive, send or display it. The tags like <from> or <to> are not predefined. They are written by the author of this XML document. Thus, in short, we can say that XML is a software and hardware independent tool or way to structure, store and carry information. An XML document has a tree structure that starts at the “root” element. An example is as follows: <?xml version=”1.0"?><Employees><Empl id=”1"><FirstName>Bill</FirstName><LastName>Watterson</LastName><Dept>Finance</Dept></Empl></Employees><Employees><Empl id=”1"><FirstName>Bill</FirstName><LastName>Watterson</LastName><Dept>Finance</Dept></Empl></Employees> The first line is the XML declaration. It defines the XML version. The next line declared the “root” element of this XML document. So, “Employees” is root element here. The other elements like “Empl”, “FirstName”, “lastName” and “Dept” are the child elements. Inside EMPL element, there is field id with value”1”. It is called attribute of that element. Attributes provide additional information about elements. Attribute values are always enclosed in quotes(single or double). A XML document with correct syntax is called “well-formed” XML. A Document Type definition (DTD) defines the legal building blocks of an XML document. It defines a document structure with a list of legal elements and attributes. A DTD document example is as follows: <?xml version=”1.0"?> <!DOCTYPE message [ <!ELEMENT message (to,from,body)> <!ELEMENT to (#PCDATA)> <!ELEMENT from (#PCDATA)> <!ELEMENT body (#PCDATA)> ]> The DTD above is interpreted like this: The DTD above is interpreted like this: !DOCTYPE note defines that the root element of this document is message.!ELEMENT note defines that the note element contains four elements: “to,from,body”.!ELEMENT to defines the to element to be of the type “#PCDATA”.!ELEMENT from defines the from element to be of the type “#PCDATA”.!ELEMENT body defines the body element to be of the type “#PCDATA”. The description (#PCDATA) specifies parsed character data. Parsed data is the text between the start tag and the end tag of an XML element. Parsed character data is text without child elements. An XML Schema Definition(XSD) document is an XML based alternative to DTD. A “Valid” XML document is a “well-formed” XML document which also conforms to the rules of DTD or XSD. As discussed, HTML tags are predefined. In HTML <table> defines a table and a browser already knows how to display it. However, in XML <table> can mean anything. XML is focused on structuring and storing the data. So, we need a mechanism to define how this data should be displayed in browsers, cellphones etc. XSL (eXtensible Style Language) is the language to do that. It defines the rules to interpret the elements of the XML document. Let's take an XML document “CDCatalog.xml” defined as follows: <?xml version=”1.0" encoding=”ISO-8859–1"?><?xml-stylesheet type=”text/xsl” href=”DisplayCD.xsl”?><catalog> <cd> <title>Empire Burlesque</title> <artist>Bob Dylan</artist> <country>USA</country> <company>Columbia</company> <price>10.90</price> <year>1985</year> </cd> <cd> <title>Hide your heart</title> <artist>Bonnie Tyler</artist> <country>UK</country> <company>CBS Records</company> <price>9.90</price> <year>1988</year> </cd></catalog> In the second line, it's referring to an XSL document DisplayCD.xsl This document can be defined as below: <?xml version=”1.0" encoding=”ISO-8859–1"?><xsl:stylesheet version=”1.0" xmlns:xsl=”http://www.w3.org/1999/XSL/Transform"><xsl:template match=”/”> <html> <body> <h2>Title</h2><xsl:for-each select=”catalog/cd”> <xsl:value-of select=”title”/> <br/></xsl:for-each> </body> </html></xsl:template></xsl:stylesheet> Let's understand DisplayCD.xsl , line by line. The first line <?xml version=”1.0" encoding=”ISO-8859–1"?>, defines the XML version and encoding used. The next line declared the XSL version and Namespace to be used. The xmlns:xsl=”http://www.w3.org/1999/XSL/Transform" points to the official W3C XSLT namespace. The <xsl:template> element defines a template. The match=”/” attribute associates the template with the root of the XML source document. The content inside the <xsl:template> element defines some HTML to write to the output. The <xsl:value-of> element can be used to extract the value of an XML element. The select attribute in the example above, contains an XPath expression. An XPath expression works like navigating a file system; a forward slash (/) selects subdirectories. The XSL <xsl:for-each> element can be used to select every XML element of a specified node-set. When CDCatalog.xml is opened in a web browser, it will display the data as follows, as defined in DisplayCD.xsl: Oracle uses a new datatype, XML Type, to facilitate handling of XML data in the database. To view the data of an existing table in XML format, you can write the query as follows: select XMLTYPE(cursor(select * from dept)) XML_Data from dual The output will be as follows: XML_Data==============<?xml version=”1.0"?><ROWSET> <ROW> <DEPTID>10</DEPTID> <DEPTNAME>ACCOUNTING</DEPTNAME> <LOC>NEW YORK</LOC> </ROW> <ROW> <DEPTID>20</DEPTID> <DEPTNAME>RESEARCH</DEPTNAME> <LOC>DALLAS</LOC> </ROW> <ROW> <DEPTID>30</DEPTID> <DEPTNAME>SALES</DEPTNAME> <LOC>CHICAGO</LOC> </ROW> <ROW> <DEPTID>40</DEPTID> <DEPTNAME>OPERATIONS</DEPTNAME> <LOC>BOSTON</LOC> </ROW></ROWSET> XMLType can accept a Ref Cursor as a parameter To insert the contents of an XML file into an Oracle table, follow the below steps: Create a table of type XMLTYPE e.g create table catalog of xmltypeCreate an Oracle directory which contains the XML file to be loaded. (An Oracle directory is a database object pointing to an operating system directory on the database server machine for reading and writing files.) e.g: Create a table of type XMLTYPE e.g create table catalog of xmltype Create an Oracle directory which contains the XML file to be loaded. (An Oracle directory is a database object pointing to an operating system directory on the database server machine for reading and writing files.) e.g: CREATE OR REPLACE DIRECTORY MYXMLDIR AS ‘D:\Gaurav\Trainings\Files’; 3. Execute the insert statement as follows: INSERT INTO catalog VALUES(XMLType(bfilename(‘MYXMLDIR’,’CDCatalog.xml’),nls_charset_id(‘AL32UTF8’))); The value passed to nls_charset_id indicates that the encoding for the file to be read is UTF-8. 4. This value can be selected using OBJECT_VALUE e.g select OBJECT_VALUE from catalog XMLELEMENT is a function that returns an XML Type. It accepts 2 arguments: the first argument is the name of the tag, the second argument is the value and could be string,XMLTYPE, number or a date. select empno, ename from emp where ename like ‘F%’; This will return the employee number and name of the employee whose name contains letter ‘S’ as follows: Using XMLELEMENT, we can add xmltype with a userdefined tag name and value as employee name e.g select empno, xmlelement(name,ename) namefromempwhere ename like ‘%S%’; It generates an XMLType with tag NAME and the employee name as value: XMLELEMENT can be nested and can contain attributes: select empno, xmlelement( emp, xmlattributes (empno, deptno), xmlelement(name, ename), xmlelement(job,job) emp ) from emp where ename like '%S%' EXTRACT and EXTRACTVALUE: The EXTRACT function takes 2 arguments: an XMLTYPE element and an XPATH string and returns an XMLTYPE instance e.g To select that data where country=”USA”, following query will be used on “catalog” table. select extract(OBJECT_VALUE,’/catalog/cd[country =”USA”]’) cd_usafromcatalog EXTRACTVALUE is used to extract the particular value under a node. E.g if we have to find the artist name where title=’Still got the blues’, the query will be written as below: select extractvalue(OBJECT_VALUE,’/catalog/cd[title =”Still got the blues”]//artist/text()’) artist_namefromcatalog The output: EXISTSNODE: EXISTSNODE checks the existence of an XPATH expression e.g if we want to know that whether the title “Still got the blues” is present in catalog or not, we can write the query as follows: select existsnode(OBJECT_VALUE,’/catalog/cd[title =”Still got the blues”]’) exist_flgfromcatalog The output 1 indicates that it exists while 0 indicates that it is not present. XMLAGG: XMLAGG is used to aggregate multiple rows in a single XML document. E.g to aggregate employees in each department, the query can be written as: selectxmlelement(emp,xmlagg(xmlelement(dept, xmlagg( xmlelement(name,ename) order by ename ) ) ) ) from empgroup by empno UPDATEXML: UPDATEXML searches for an XPATH expression and updates it. E.g UPDATE catalog SET object_value = UPDATEXML(object_value, ‘/catalog/cd/title/text()’,’changed’) This will update all the titles to “changed” in the table catalog. This article was aimed to give the reader, a basic understanding of XML and related technologies and how XML data is handled in Oracle database. For more detailed knowledge of XML capabilities of Oracle, please refer to the below link:
[ { "code": null, "e": 406, "s": 46, "text": "There is always an extensive demand for exchanging data between different sources without worrying about how the receiver will use it or how it will be displayed. XML does that thing for us. It’s a W3C(World Wide Web Consortium) initiative that allows information to be encoded in meaningful structure and rules that humans and machines can understand easily." }, { "code": null, "e": 483, "s": 406, "text": "XML stands for eXtensible Markup Language. XML is not a replacement of HTML." }, { "code": null, "e": 594, "s": 483, "text": "While HTML is designed with focus on how to ‘display’ data, XML is designed how to ‘store’ and ‘transport’ it." }, { "code": null, "e": 632, "s": 594, "text": "XML, in itself, does not DO anything." }, { "code": null, "e": 669, "s": 632, "text": "Let’s look at a sample xml document:" }, { "code": null, "e": 756, "s": 669, "text": "<message><to>Tom</to><from>Bill</from><body>Send me your phone number</body></message>" }, { "code": null, "e": 1008, "s": 756, "text": "The above XML document contains a message with a body having a sender and receiver information. But it does not do anything on its own. It has just structured and stored information. Someone has to write a software code to receive, send or display it." }, { "code": null, "e": 1110, "s": 1008, "text": "The tags like <from> or <to> are not predefined. They are written by the author of this XML document." }, { "code": null, "e": 1240, "s": 1110, "text": "Thus, in short, we can say that XML is a software and hardware independent tool or way to structure, store and carry information." }, { "code": null, "e": 1338, "s": 1240, "text": "An XML document has a tree structure that starts at the “root” element. An example is as follows:" }, { "code": null, "e": 1600, "s": 1338, "text": "<?xml version=”1.0\"?><Employees><Empl id=”1\"><FirstName>Bill</FirstName><LastName>Watterson</LastName><Dept>Finance</Dept></Empl></Employees><Employees><Empl id=”1\"><FirstName>Bill</FirstName><LastName>Watterson</LastName><Dept>Finance</Dept></Empl></Employees>" }, { "code": null, "e": 2142, "s": 1600, "text": "The first line is the XML declaration. It defines the XML version. The next line declared the “root” element of this XML document. So, “Employees” is root element here. The other elements like “Empl”, “FirstName”, “lastName” and “Dept” are the child elements. Inside EMPL element, there is field id with value”1”. It is called attribute of that element. Attributes provide additional information about elements. Attribute values are always enclosed in quotes(single or double). A XML document with correct syntax is called “well-formed” XML." }, { "code": null, "e": 2345, "s": 2142, "text": "A Document Type definition (DTD) defines the legal building blocks of an XML document. It defines a document structure with a list of legal elements and attributes. A DTD document example is as follows:" }, { "code": null, "e": 2503, "s": 2345, "text": "<?xml version=”1.0\"?> <!DOCTYPE message [ <!ELEMENT message (to,from,body)> <!ELEMENT to (#PCDATA)> <!ELEMENT from (#PCDATA)> <!ELEMENT body (#PCDATA)> ]>" }, { "code": null, "e": 2583, "s": 2503, "text": "The DTD above is interpreted like this: The DTD above is interpreted like this:" }, { "code": null, "e": 2936, "s": 2583, "text": "!DOCTYPE note defines that the root element of this document is message.!ELEMENT note defines that the note element contains four elements: “to,from,body”.!ELEMENT to defines the to element to be of the type “#PCDATA”.!ELEMENT from defines the from element to be of the type “#PCDATA”.!ELEMENT body defines the body element to be of the type “#PCDATA”." }, { "code": null, "e": 3130, "s": 2936, "text": "The description (#PCDATA) specifies parsed character data. Parsed data is the text between the start tag and the end tag of an XML element. Parsed character data is text without child elements." }, { "code": null, "e": 3205, "s": 3130, "text": "An XML Schema Definition(XSD) document is an XML based alternative to DTD." }, { "code": null, "e": 3308, "s": 3205, "text": "A “Valid” XML document is a “well-formed” XML document which also conforms to the rules of DTD or XSD." }, { "code": null, "e": 3747, "s": 3308, "text": "As discussed, HTML tags are predefined. In HTML <table> defines a table and a browser already knows how to display it. However, in XML <table> can mean anything. XML is focused on structuring and storing the data. So, we need a mechanism to define how this data should be displayed in browsers, cellphones etc. XSL (eXtensible Style Language) is the language to do that. It defines the rules to interpret the elements of the XML document." }, { "code": null, "e": 3810, "s": 3747, "text": "Let's take an XML document “CDCatalog.xml” defined as follows:" }, { "code": null, "e": 4251, "s": 3810, "text": "<?xml version=”1.0\" encoding=”ISO-8859–1\"?><?xml-stylesheet type=”text/xsl” href=”DisplayCD.xsl”?><catalog> <cd> <title>Empire Burlesque</title> <artist>Bob Dylan</artist> <country>USA</country> <company>Columbia</company> <price>10.90</price> <year>1985</year> </cd> <cd> <title>Hide your heart</title> <artist>Bonnie Tyler</artist> <country>UK</country> <company>CBS Records</company> <price>9.90</price> <year>1988</year> </cd></catalog>" }, { "code": null, "e": 4358, "s": 4251, "text": "In the second line, it's referring to an XSL document DisplayCD.xsl This document can be defined as below:" }, { "code": null, "e": 4668, "s": 4358, "text": "<?xml version=”1.0\" encoding=”ISO-8859–1\"?><xsl:stylesheet version=”1.0\" xmlns:xsl=”http://www.w3.org/1999/XSL/Transform\"><xsl:template match=”/”> <html> <body> <h2>Title</h2><xsl:for-each select=”catalog/cd”> <xsl:value-of select=”title”/> <br/></xsl:for-each> </body> </html></xsl:template></xsl:stylesheet>" }, { "code": null, "e": 4715, "s": 4668, "text": "Let's understand DisplayCD.xsl , line by line." }, { "code": null, "e": 4818, "s": 4715, "text": "The first line <?xml version=”1.0\" encoding=”ISO-8859–1\"?>, defines the XML version and encoding used." }, { "code": null, "e": 4979, "s": 4818, "text": "The next line declared the XSL version and Namespace to be used. The xmlns:xsl=”http://www.w3.org/1999/XSL/Transform\" points to the official W3C XSLT namespace." }, { "code": null, "e": 5116, "s": 4979, "text": "The <xsl:template> element defines a template. The match=”/” attribute associates the template with the root of the XML source document." }, { "code": null, "e": 5204, "s": 5116, "text": "The content inside the <xsl:template> element defines some HTML to write to the output." }, { "code": null, "e": 5553, "s": 5204, "text": "The <xsl:value-of> element can be used to extract the value of an XML element. The select attribute in the example above, contains an XPath expression. An XPath expression works like navigating a file system; a forward slash (/) selects subdirectories. The XSL <xsl:for-each> element can be used to select every XML element of a specified node-set." }, { "code": null, "e": 5666, "s": 5553, "text": "When CDCatalog.xml is opened in a web browser, it will display the data as follows, as defined in DisplayCD.xsl:" }, { "code": null, "e": 5845, "s": 5666, "text": "Oracle uses a new datatype, XML Type, to facilitate handling of XML data in the database. To view the data of an existing table in XML format, you can write the query as follows:" }, { "code": null, "e": 5907, "s": 5845, "text": "select XMLTYPE(cursor(select * from dept)) XML_Data from dual" }, { "code": null, "e": 5938, "s": 5907, "text": "The output will be as follows:" }, { "code": null, "e": 6327, "s": 5938, "text": "XML_Data==============<?xml version=”1.0\"?><ROWSET> <ROW> <DEPTID>10</DEPTID> <DEPTNAME>ACCOUNTING</DEPTNAME> <LOC>NEW YORK</LOC> </ROW> <ROW> <DEPTID>20</DEPTID> <DEPTNAME>RESEARCH</DEPTNAME> <LOC>DALLAS</LOC> </ROW> <ROW> <DEPTID>30</DEPTID> <DEPTNAME>SALES</DEPTNAME> <LOC>CHICAGO</LOC> </ROW> <ROW> <DEPTID>40</DEPTID> <DEPTNAME>OPERATIONS</DEPTNAME> <LOC>BOSTON</LOC> </ROW></ROWSET>" }, { "code": null, "e": 6374, "s": 6327, "text": "XMLType can accept a Ref Cursor as a parameter" }, { "code": null, "e": 6458, "s": 6374, "text": "To insert the contents of an XML file into an Oracle table, follow the below steps:" }, { "code": null, "e": 6745, "s": 6458, "text": "Create a table of type XMLTYPE e.g create table catalog of xmltypeCreate an Oracle directory which contains the XML file to be loaded. (An Oracle directory is a database object pointing to an operating system directory on the database server machine for reading and writing files.) e.g:" }, { "code": null, "e": 6812, "s": 6745, "text": "Create a table of type XMLTYPE e.g create table catalog of xmltype" }, { "code": null, "e": 7033, "s": 6812, "text": "Create an Oracle directory which contains the XML file to be loaded. (An Oracle directory is a database object pointing to an operating system directory on the database server machine for reading and writing files.) e.g:" }, { "code": null, "e": 7102, "s": 7033, "text": "CREATE OR REPLACE DIRECTORY MYXMLDIR AS ‘D:\\Gaurav\\Trainings\\Files’;" }, { "code": null, "e": 7146, "s": 7102, "text": "3. Execute the insert statement as follows:" }, { "code": null, "e": 7249, "s": 7146, "text": "INSERT INTO catalog VALUES(XMLType(bfilename(‘MYXMLDIR’,’CDCatalog.xml’),nls_charset_id(‘AL32UTF8’)));" }, { "code": null, "e": 7346, "s": 7249, "text": "The value passed to nls_charset_id indicates that the encoding for the file to be read is UTF-8." }, { "code": null, "e": 7399, "s": 7346, "text": "4. This value can be selected using OBJECT_VALUE e.g" }, { "code": null, "e": 7432, "s": 7399, "text": "select OBJECT_VALUE from catalog" }, { "code": null, "e": 7630, "s": 7432, "text": "XMLELEMENT is a function that returns an XML Type. It accepts 2 arguments: the first argument is the name of the tag, the second argument is the value and could be string,XMLTYPE, number or a date." }, { "code": null, "e": 7682, "s": 7630, "text": "select empno, ename from emp where ename like ‘F%’;" }, { "code": null, "e": 7787, "s": 7682, "text": "This will return the employee number and name of the employee whose name contains letter ‘S’ as follows:" }, { "code": null, "e": 7883, "s": 7787, "text": "Using XMLELEMENT, we can add xmltype with a userdefined tag name and value as employee name e.g" }, { "code": null, "e": 7955, "s": 7883, "text": "select empno, xmlelement(name,ename) namefromempwhere ename like ‘%S%’;" }, { "code": null, "e": 8025, "s": 7955, "text": "It generates an XMLType with tag NAME and the employee name as value:" }, { "code": null, "e": 8078, "s": 8025, "text": "XMLELEMENT can be nested and can contain attributes:" }, { "code": null, "e": 8416, "s": 8078, "text": "select empno, xmlelement( emp, xmlattributes (empno, deptno), xmlelement(name, ename), xmlelement(job,job) emp ) from emp where ename like '%S%'" }, { "code": null, "e": 8442, "s": 8416, "text": "EXTRACT and EXTRACTVALUE:" }, { "code": null, "e": 8557, "s": 8442, "text": "The EXTRACT function takes 2 arguments: an XMLTYPE element and an XPATH string and returns an XMLTYPE instance e.g" }, { "code": null, "e": 8647, "s": 8557, "text": "To select that data where country=”USA”, following query will be used on “catalog” table." }, { "code": null, "e": 8724, "s": 8647, "text": "select extract(OBJECT_VALUE,’/catalog/cd[country =”USA”]’) cd_usafromcatalog" }, { "code": null, "e": 8901, "s": 8724, "text": "EXTRACTVALUE is used to extract the particular value under a node. E.g if we have to find the artist name where title=’Still got the blues’, the query will be written as below:" }, { "code": null, "e": 9017, "s": 8901, "text": "select extractvalue(OBJECT_VALUE,’/catalog/cd[title =”Still got the blues”]//artist/text()’) artist_namefromcatalog" }, { "code": null, "e": 9029, "s": 9017, "text": "The output:" }, { "code": null, "e": 9041, "s": 9029, "text": "EXISTSNODE:" }, { "code": null, "e": 9229, "s": 9041, "text": "EXISTSNODE checks the existence of an XPATH expression e.g if we want to know that whether the title “Still got the blues” is present in catalog or not, we can write the query as follows:" }, { "code": null, "e": 9326, "s": 9229, "text": "select existsnode(OBJECT_VALUE,’/catalog/cd[title =”Still got the blues”]’) exist_flgfromcatalog" }, { "code": null, "e": 9406, "s": 9326, "text": "The output 1 indicates that it exists while 0 indicates that it is not present." }, { "code": null, "e": 9414, "s": 9406, "text": "XMLAGG:" }, { "code": null, "e": 9558, "s": 9414, "text": "XMLAGG is used to aggregate multiple rows in a single XML document. E.g to aggregate employees in each department, the query can be written as:" }, { "code": null, "e": 9682, "s": 9558, "text": "selectxmlelement(emp,xmlagg(xmlelement(dept, xmlagg( xmlelement(name,ename) order by ename ) ) ) ) from empgroup by empno" }, { "code": null, "e": 9693, "s": 9682, "text": "UPDATEXML:" }, { "code": null, "e": 9756, "s": 9693, "text": "UPDATEXML searches for an XPATH expression and updates it. E.g" }, { "code": null, "e": 9852, "s": 9756, "text": "UPDATE catalog SET object_value = UPDATEXML(object_value, ‘/catalog/cd/title/text()’,’changed’)" }, { "code": null, "e": 9919, "s": 9852, "text": "This will update all the titles to “changed” in the table catalog." } ]
Bank Institution Term Deposit Predictive Model | by Lotome John | Towards Data Science
The investment and portfolio department of the Bank of Portugal would want to be able to identify their customers who potentially would subscribe to their term deposits. As there has been heightened interest of marketing managers to carefully tune their directed campaigns to the rigorous selection of contacts, the task at hand is to find a model that can predict which future clients who would subscribe to the Bank’s term deposit.In this post, am going to talk about data exploration, data cleaning, feature extraction, and dealing with class imbalance and developing a robust machine learning algorithm for predicting which potential customers would subscribe to the term deposit using different Machine learning library. The Github repository containing all the code is available here. PACKAGES The following are the different machine learning and python packages used. Exploratory data analysis is usually the initial process of every data science project. It is usually critical to perform an initial investigation on data to identify patterns, outliers, imbalances and to test a prior hypothesis. Summary statistics and visualization are mainly used to perform exploratory data analysis. “There are no routine statistical questions, only questionable statistical routines.” Sir David Cox From the above output, some patterns of the data can be extracted. Grouping the data based on if the potential client subscribed to the term deposit or not indicates that the majority of clients did not subscribe to the term deposit, 88.7% decline while 11.3% accepted the subscription offer. This significant difference in the proportion of the class that we are trying to predict leads to imbalance data. The above output shows clusters of clients who subscribe to the term deposit and those who decline based on marital status. An outlier is a data point that differs significantly from the other observations which may be due to variability in the measurement or it may indicate experimental errors. The temptation of training a machine learning model without checking and dealing with outliers is usually a recipe for failure. Outliers in data can significantly impact the accuracy of the model, but simply removing outliers from your data without considering the impact on the results is a bad practice since outliers aren’t always a bad thing. “Outliers are not necessarily a bad thing. These are just observations that are not following the same pattern as the other ones. But it can be the case that an outlier is very interesting. For example, if in a biological experiment, a rat is not dead whereas all others are, then it would be very interesting to understand why. This could lead to new scientific discoveries. So, it is important to detect outliers.” Pierre Lafaye de Micheaux, Author, and Statistician. A common practice of detecting outliers is using box plots, histograms, and scatter plots. This methodology may not be efficient in large datasets. PyOD, a python library has different algorithms that can be used to detect and clean outliers. For this case, we use k-Nearest Neighbors Detectors. Datasets normally contain numerical and categorical variables but a machine learning algorithm only understands numbers and not text that is why we need to convert or transform the categorical variables, a process is known as categorical encoding. There two types of categorical encoding: Label Encoding One-Hot Encoding Label Encoding is useful where the categories in the categorical columns have data with some kind of order or hierarchy. One-Hot Encoding works by splitting the column to be encoded into multiple columns depending on the number of categories in that column. The categories are then replaced by 1s and 0s, depending on which column has what value.We also use StandardScaler to rescale all numerical columns. This is useful since some variables are often measured at different scales and would not contribute equally to model fitting which may lead the trained model to create some bias. Training a machine learning model on an imbalanced dataset may lead to inaccurate predictions. In this case, we use a random sampling technique to deal with the imbalanced data. Random oversampling works by randomly sampling data from the minority class and duplicates it to create more samples, this process is repeated until when the distribution is equal. One of the cons of the Random Sampling technique is that it can potentially lead to overfitting since it duplicates the existing minority data set. Dimensionality reduction is a technique that reduces the number of input variables or features in a dataset. More input features often make a predictive modeling task more challenging to a model, referred to as the curse of dimensionality. There are different dimensionality reduction techniques like AutoEncoder and t-SNE which is a probabilistic technique. For our case, we use Principal Component Analysis (PCA) for dimension reduction. PCA performs a linear mapping of the data to a lower-dimensional space in such a way that the variance of the data in the low dimensional representation is maximized.We only performed PCA on the features alone, without including the labels. The code snippet below shows a method that I used in comparing the different modelling algorithms. Four parameters are required when initializing the parameters Model type. For this case, I used XGBoost Classifier, Multi-layer Perceptron classifier, Logistic Regression and Support Vector Machine.Cross-Validation technique, that is either k-fold or Stratified k-foldX which is the dataset featuresy which is the label Model type. For this case, I used XGBoost Classifier, Multi-layer Perceptron classifier, Logistic Regression and Support Vector Machine. Cross-Validation technique, that is either k-fold or Stratified k-fold X which is the dataset features y which is the label Initialization of the different models In all the models selected even with hyperparameter tuning, XGBoost Classifier had higher accuracy scores. The figure below shows the different metric scores of the XGBoost model used. There was a slightly significant difference in the scores while using Stratified k-fold and k-fold cross-validation. Stratified k-fold had higher scores compared to k-fold. Accuracy scores of the model: 0.88 Classification report of the model-------------------------------------- precision recall f1-score support 0 0.89 0.87 0.88 3442 1 0.88 0.90 0.89 3537 accuracy 0.88 6979 macro avg 0.89 0.88 0.88 6979weighted avg 0.89 0.88 0.88 6979 Confusion Matrix of the model--------------------------------------[[2993 449] [ 354 3183]] Our model had an accuracy of 0.88 with precision and recall metrics above 0.87. The ROC plot when using k-fold cross validation indicates a score of 0.88. while using stratified k-fold, there was an increase in score by 0.01 Since the XGBoost had a higher precision, recall, and f1-score for the minority class which is a more important classification of whether a potential client was going to subscribe to the term deposit, the bank should use XGBoost model. With different hyperparameter tuning techniques, the model can lead to higher scores. Respect and gratitude to all my fellow learners and staff at 10Academy for their support in putting this together.
[ { "code": null, "e": 963, "s": 172, "text": "The investment and portfolio department of the Bank of Portugal would want to be able to identify their customers who potentially would subscribe to their term deposits. As there has been heightened interest of marketing managers to carefully tune their directed campaigns to the rigorous selection of contacts, the task at hand is to find a model that can predict which future clients who would subscribe to the Bank’s term deposit.In this post, am going to talk about data exploration, data cleaning, feature extraction, and dealing with class imbalance and developing a robust machine learning algorithm for predicting which potential customers would subscribe to the term deposit using different Machine learning library. The Github repository containing all the code is available here." }, { "code": null, "e": 972, "s": 963, "text": "PACKAGES" }, { "code": null, "e": 1047, "s": 972, "text": "The following are the different machine learning and python packages used." }, { "code": null, "e": 1368, "s": 1047, "text": "Exploratory data analysis is usually the initial process of every data science project. It is usually critical to perform an initial investigation on data to identify patterns, outliers, imbalances and to test a prior hypothesis. Summary statistics and visualization are mainly used to perform exploratory data analysis." }, { "code": null, "e": 1468, "s": 1368, "text": "“There are no routine statistical questions, only questionable statistical routines.” Sir David Cox" }, { "code": null, "e": 1875, "s": 1468, "text": "From the above output, some patterns of the data can be extracted. Grouping the data based on if the potential client subscribed to the term deposit or not indicates that the majority of clients did not subscribe to the term deposit, 88.7% decline while 11.3% accepted the subscription offer. This significant difference in the proportion of the class that we are trying to predict leads to imbalance data." }, { "code": null, "e": 1999, "s": 1875, "text": "The above output shows clusters of clients who subscribe to the term deposit and those who decline based on marital status." }, { "code": null, "e": 2519, "s": 1999, "text": "An outlier is a data point that differs significantly from the other observations which may be due to variability in the measurement or it may indicate experimental errors. The temptation of training a machine learning model without checking and dealing with outliers is usually a recipe for failure. Outliers in data can significantly impact the accuracy of the model, but simply removing outliers from your data without considering the impact on the results is a bad practice since outliers aren’t always a bad thing." }, { "code": null, "e": 2989, "s": 2519, "text": "“Outliers are not necessarily a bad thing. These are just observations that are not following the same pattern as the other ones. But it can be the case that an outlier is very interesting. For example, if in a biological experiment, a rat is not dead whereas all others are, then it would be very interesting to understand why. This could lead to new scientific discoveries. So, it is important to detect outliers.” Pierre Lafaye de Micheaux, Author, and Statistician." }, { "code": null, "e": 3285, "s": 2989, "text": "A common practice of detecting outliers is using box plots, histograms, and scatter plots. This methodology may not be efficient in large datasets. PyOD, a python library has different algorithms that can be used to detect and clean outliers. For this case, we use k-Nearest Neighbors Detectors." }, { "code": null, "e": 3574, "s": 3285, "text": "Datasets normally contain numerical and categorical variables but a machine learning algorithm only understands numbers and not text that is why we need to convert or transform the categorical variables, a process is known as categorical encoding. There two types of categorical encoding:" }, { "code": null, "e": 3589, "s": 3574, "text": "Label Encoding" }, { "code": null, "e": 3606, "s": 3589, "text": "One-Hot Encoding" }, { "code": null, "e": 4192, "s": 3606, "text": "Label Encoding is useful where the categories in the categorical columns have data with some kind of order or hierarchy. One-Hot Encoding works by splitting the column to be encoded into multiple columns depending on the number of categories in that column. The categories are then replaced by 1s and 0s, depending on which column has what value.We also use StandardScaler to rescale all numerical columns. This is useful since some variables are often measured at different scales and would not contribute equally to model fitting which may lead the trained model to create some bias." }, { "code": null, "e": 4699, "s": 4192, "text": "Training a machine learning model on an imbalanced dataset may lead to inaccurate predictions. In this case, we use a random sampling technique to deal with the imbalanced data. Random oversampling works by randomly sampling data from the minority class and duplicates it to create more samples, this process is repeated until when the distribution is equal. One of the cons of the Random Sampling technique is that it can potentially lead to overfitting since it duplicates the existing minority data set." }, { "code": null, "e": 5380, "s": 4699, "text": "Dimensionality reduction is a technique that reduces the number of input variables or features in a dataset. More input features often make a predictive modeling task more challenging to a model, referred to as the curse of dimensionality. There are different dimensionality reduction techniques like AutoEncoder and t-SNE which is a probabilistic technique. For our case, we use Principal Component Analysis (PCA) for dimension reduction. PCA performs a linear mapping of the data to a lower-dimensional space in such a way that the variance of the data in the low dimensional representation is maximized.We only performed PCA on the features alone, without including the labels." }, { "code": null, "e": 5541, "s": 5380, "text": "The code snippet below shows a method that I used in comparing the different modelling algorithms. Four parameters are required when initializing the parameters" }, { "code": null, "e": 5799, "s": 5541, "text": "Model type. For this case, I used XGBoost Classifier, Multi-layer Perceptron classifier, Logistic Regression and Support Vector Machine.Cross-Validation technique, that is either k-fold or Stratified k-foldX which is the dataset featuresy which is the label" }, { "code": null, "e": 5936, "s": 5799, "text": "Model type. For this case, I used XGBoost Classifier, Multi-layer Perceptron classifier, Logistic Regression and Support Vector Machine." }, { "code": null, "e": 6007, "s": 5936, "text": "Cross-Validation technique, that is either k-fold or Stratified k-fold" }, { "code": null, "e": 6039, "s": 6007, "text": "X which is the dataset features" }, { "code": null, "e": 6060, "s": 6039, "text": "y which is the label" }, { "code": null, "e": 6099, "s": 6060, "text": "Initialization of the different models" }, { "code": null, "e": 6457, "s": 6099, "text": "In all the models selected even with hyperparameter tuning, XGBoost Classifier had higher accuracy scores. The figure below shows the different metric scores of the XGBoost model used. There was a slightly significant difference in the scores while using Stratified k-fold and k-fold cross-validation. Stratified k-fold had higher scores compared to k-fold." }, { "code": null, "e": 6976, "s": 6457, "text": "Accuracy scores of the model: 0.88 Classification report of the model-------------------------------------- precision recall f1-score support 0 0.89 0.87 0.88 3442 1 0.88 0.90 0.89 3537 accuracy 0.88 6979 macro avg 0.89 0.88 0.88 6979weighted avg 0.89 0.88 0.88 6979 Confusion Matrix of the model--------------------------------------[[2993 449] [ 354 3183]]" }, { "code": null, "e": 7056, "s": 6976, "text": "Our model had an accuracy of 0.88 with precision and recall metrics above 0.87." }, { "code": null, "e": 7131, "s": 7056, "text": "The ROC plot when using k-fold cross validation indicates a score of 0.88." }, { "code": null, "e": 7201, "s": 7131, "text": "while using stratified k-fold, there was an increase in score by 0.01" }, { "code": null, "e": 7523, "s": 7201, "text": "Since the XGBoost had a higher precision, recall, and f1-score for the minority class which is a more important classification of whether a potential client was going to subscribe to the term deposit, the bank should use XGBoost model. With different hyperparameter tuning techniques, the model can lead to higher scores." } ]
How to count number of notification on an icon? - GeeksforGeeks
09 Aug, 2021 Bootstrap provides us with badges to display counts on an icon which can be used to show unread notifications/messages etc. We need to get the value of count on the icon badge and update that value accordingly. In this article, we will create a notification icon that can hold the counting like unread notification does. We will divide this into two different sections in the first section we will create the structure of the icon and in the second section, we will design the icon and make the icon responsive.Approach: We will proceed with the following steps to ensure that we can always get the notification number/badge count for the icon irrespective of the DOM structure. Wrapping the icon and badge under same element. Using jQuery find() function to extract the count. Increase/Decrease the count of the badge from the extracted value. Update the value. Creating Structure: Below is a sample code which we’ll be using as a template. Finally, we’ll apply jQuery as per the problem statement for the following. CDN links for the Icons from the Font Awesome: <script src=”https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.12.0/js/all.min.js”></script> HTML code: HTML <!-- Final Solution --><!DOCTYPE html><html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.12.0/js/all.min.js"> </script></head> <body> <div class="container-fluid"> <br> <br> <center> <h1>GeeksforGeeks</h1> <h4>Icon with count Badge: <!-- Wrapping the icon and badge --> <span id="group"> <button type="button" class="btn btn-info"> <i class="fa fa-envelope"></i> </button> <span class="badge badge-light">5</span> </span> </h4> <br> <br> <button class="btn btn-danger"> <i class="fas fa-minus"></i> Subtract </button> <button class="btn btn-success"> <i class="fas fa-plus"></i> Addition </button> </center> </div></body> </html> Designing Structure: In this section, we will design the structure and make the icon responsive as well. CSS code: CSS <style> h1 { color:green; } .badge { position: relative; top: -20px; left: -25px; border: 1px solid black; border-radius: 50%; } button { margin:5px; }</style> JavaScript code: The implementation of the approach is purely dependent on the developer and the DOM structure depends upon the use-case required. It is not necessary developer groups the badge in the same element as the icon. javascript <script> // Use find() function to extract the badge // count from '#group' container. $(document).ready(function() { $(".btn").click(function() { var val = parseInt($('#group').find('.badge').text()); // Check for the button clicked if ($(this).hasClass('btn-danger')) { $('#group').find('.badge').text(val - 1); } else if ($(this).hasClass('btn-success')) { $('#group').find('.badge').text(val + 1); } }); });</script> Note: Later we will group this by chaining to apply jQuery on the badge irrespective of the developer’s implementation for the same.Combining HTML, CSS and JavaScript Code: This is the final code that is the combination of the above two sections creating structure and designing structure. html <!-- Final Solution --><!DOCTYPE html><html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.12.0/js/all.min.js"> </script> <style> h1 { color:green; } .badge { position: relative; top: -20px; left: -25px; border: 1px solid black; border-radius: 50%; } button { margin:5px; } </style></head> <body> <div class="container-fluid"> <br> <br> <center> <h1>GeeksforGeeks</h1> <h4>Icon with count Badge: <!-- Wrapping the icon and badge --> <span id="group"> <button type="button" class="btn btn-info"> <i class="fa fa-envelope"></i> </button> <span class="badge badge-light">5</span> </span> </h4> <br> <br> <button class="btn btn-danger"> <i class="fas fa-minus"></i> Subtract </button> <button class="btn btn-success"> <i class="fas fa-plus"></i> Addition </button> </center> </div></body><script> // Use find() function to extract the badge // count from '#group' container. $(document).ready(function() { $(".btn").click(function() { var val = parseInt($('#group').find('.badge').text()); // Check for the button clicked if ($(this).hasClass('btn-danger')) { $('#group').find('.badge').text(val - 1); } else if ($(this).hasClass('btn-success')) { $('#group').find('.badge').text(val + 1); } }); });</script> </html> Output: 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. Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. anikakapoor Bootstrap-Misc CSS-Misc HTML-Misc JavaScript-Misc Picked Technical Scripter 2019 CSS HTML JQuery Technical Scripter Web Technologies Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to create footer to stay at the bottom of a Web page? Types of CSS (Cascading Style Sheet) Create a Responsive Navbar using ReactJS Design a web page using HTML and CSS How to position a div at the bottom of its container using CSS? How to set the default value for an HTML <select> element ? How to set input type date in dd-mm-yyyy format using HTML ? Hide or show elements in HTML using display property Types of CSS (Cascading Style Sheet) How to Insert Form Data into Database using PHP ?
[ { "code": null, "e": 24580, "s": 24552, "text": "\n09 Aug, 2021" }, { "code": null, "e": 25261, "s": 24580, "text": "Bootstrap provides us with badges to display counts on an icon which can be used to show unread notifications/messages etc. We need to get the value of count on the icon badge and update that value accordingly. In this article, we will create a notification icon that can hold the counting like unread notification does. We will divide this into two different sections in the first section we will create the structure of the icon and in the second section, we will design the icon and make the icon responsive.Approach: We will proceed with the following steps to ensure that we can always get the notification number/badge count for the icon irrespective of the DOM structure. " }, { "code": null, "e": 25309, "s": 25261, "text": "Wrapping the icon and badge under same element." }, { "code": null, "e": 25360, "s": 25309, "text": "Using jQuery find() function to extract the count." }, { "code": null, "e": 25427, "s": 25360, "text": "Increase/Decrease the count of the badge from the extracted value." }, { "code": null, "e": 25445, "s": 25427, "text": "Update the value." }, { "code": null, "e": 25602, "s": 25445, "text": "Creating Structure: Below is a sample code which we’ll be using as a template. Finally, we’ll apply jQuery as per the problem statement for the following. " }, { "code": null, "e": 25651, "s": 25602, "text": "CDN links for the Icons from the Font Awesome: " }, { "code": null, "e": 25750, "s": 25651, "text": "<script src=”https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.12.0/js/all.min.js”></script> " }, { "code": null, "e": 25763, "s": 25750, "text": "HTML code: " }, { "code": null, "e": 25768, "s": 25763, "text": "HTML" }, { "code": "<!-- Final Solution --><!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.12.0/js/all.min.js\"> </script></head> <body> <div class=\"container-fluid\"> <br> <br> <center> <h1>GeeksforGeeks</h1> <h4>Icon with count Badge: <!-- Wrapping the icon and badge --> <span id=\"group\"> <button type=\"button\" class=\"btn btn-info\"> <i class=\"fa fa-envelope\"></i> </button> <span class=\"badge badge-light\">5</span> </span> </h4> <br> <br> <button class=\"btn btn-danger\"> <i class=\"fas fa-minus\"></i> Subtract </button> <button class=\"btn btn-success\"> <i class=\"fas fa-plus\"></i> Addition </button> </center> </div></body> </html>", "e": 27253, "s": 25768, "text": null }, { "code": null, "e": 27360, "s": 27253, "text": "Designing Structure: In this section, we will design the structure and make the icon responsive as well. " }, { "code": null, "e": 27372, "s": 27360, "text": "CSS code: " }, { "code": null, "e": 27376, "s": 27372, "text": "CSS" }, { "code": "<style> h1 { color:green; } .badge { position: relative; top: -20px; left: -25px; border: 1px solid black; border-radius: 50%; } button { margin:5px; }</style>", "e": 27611, "s": 27376, "text": null }, { "code": null, "e": 27840, "s": 27611, "text": "JavaScript code: The implementation of the approach is purely dependent on the developer and the DOM structure depends upon the use-case required. It is not necessary developer groups the badge in the same element as the icon. " }, { "code": null, "e": 27851, "s": 27840, "text": "javascript" }, { "code": "<script> // Use find() function to extract the badge // count from '#group' container. $(document).ready(function() { $(\".btn\").click(function() { var val = parseInt($('#group').find('.badge').text()); // Check for the button clicked if ($(this).hasClass('btn-danger')) { $('#group').find('.badge').text(val - 1); } else if ($(this).hasClass('btn-success')) { $('#group').find('.badge').text(val + 1); } }); });</script>", "e": 28387, "s": 27851, "text": null }, { "code": null, "e": 28679, "s": 28387, "text": "Note: Later we will group this by chaining to apply jQuery on the badge irrespective of the developer’s implementation for the same.Combining HTML, CSS and JavaScript Code: This is the final code that is the combination of the above two sections creating structure and designing structure. " }, { "code": null, "e": 28684, "s": 28679, "text": "html" }, { "code": "<!-- Final Solution --><!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.12.0/js/all.min.js\"> </script> <style> h1 { color:green; } .badge { position: relative; top: -20px; left: -25px; border: 1px solid black; border-radius: 50%; } button { margin:5px; } </style></head> <body> <div class=\"container-fluid\"> <br> <br> <center> <h1>GeeksforGeeks</h1> <h4>Icon with count Badge: <!-- Wrapping the icon and badge --> <span id=\"group\"> <button type=\"button\" class=\"btn btn-info\"> <i class=\"fa fa-envelope\"></i> </button> <span class=\"badge badge-light\">5</span> </span> </h4> <br> <br> <button class=\"btn btn-danger\"> <i class=\"fas fa-minus\"></i> Subtract </button> <button class=\"btn btn-success\"> <i class=\"fas fa-plus\"></i> Addition </button> </center> </div></body><script> // Use find() function to extract the badge // count from '#group' container. $(document).ready(function() { $(\".btn\").click(function() { var val = parseInt($('#group').find('.badge').text()); // Check for the button clicked if ($(this).hasClass('btn-danger')) { $('#group').find('.badge').text(val - 1); } else if ($(this).hasClass('btn-success')) { $('#group').find('.badge').text(val + 1); } }); });</script> </html> ", "e": 31004, "s": 28684, "text": null }, { "code": null, "e": 31014, "s": 31004, "text": "Output: " }, { "code": null, "e": 31285, "s": 31016, "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": 31424, "s": 31287, "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": 31436, "s": 31424, "text": "anikakapoor" }, { "code": null, "e": 31451, "s": 31436, "text": "Bootstrap-Misc" }, { "code": null, "e": 31460, "s": 31451, "text": "CSS-Misc" }, { "code": null, "e": 31470, "s": 31460, "text": "HTML-Misc" }, { "code": null, "e": 31486, "s": 31470, "text": "JavaScript-Misc" }, { "code": null, "e": 31493, "s": 31486, "text": "Picked" }, { "code": null, "e": 31517, "s": 31493, "text": "Technical Scripter 2019" }, { "code": null, "e": 31521, "s": 31517, "text": "CSS" }, { "code": null, "e": 31526, "s": 31521, "text": "HTML" }, { "code": null, "e": 31533, "s": 31526, "text": "JQuery" }, { "code": null, "e": 31552, "s": 31533, "text": "Technical Scripter" }, { "code": null, "e": 31569, "s": 31552, "text": "Web Technologies" }, { "code": null, "e": 31596, "s": 31569, "text": "Web technologies Questions" }, { "code": null, "e": 31601, "s": 31596, "text": "HTML" }, { "code": null, "e": 31699, "s": 31601, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31708, "s": 31699, "text": "Comments" }, { "code": null, "e": 31721, "s": 31708, "text": "Old Comments" }, { "code": null, "e": 31779, "s": 31721, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 31816, "s": 31779, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 31857, "s": 31816, "text": "Create a Responsive Navbar using ReactJS" }, { "code": null, "e": 31894, "s": 31857, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 31958, "s": 31894, "text": "How to position a div at the bottom of its container using CSS?" }, { "code": null, "e": 32018, "s": 31958, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 32079, "s": 32018, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 32132, "s": 32079, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 32169, "s": 32132, "text": "Types of CSS (Cascading Style Sheet)" } ]
MySQL - UNLOCK TABLES Statement
A session releases all the tables locks with it at once. You can implicitly release the table locks. If the connection to the server terminates explicitly or implicitly all the locks will be released. You can release the locks of a table explicitly using the UNLOCK TABLES statement. Following is the syntax of the MySQL UNLOCK TABLES statement − UNLOCK TABLES Suppose we have created a table that contains the sales details along with the contact details of the customers as shown below − mysql> CREATE TABLE SalesDetails ( ID INT, ProductName VARCHAR(255), CustomerName VARCHAR(255), DispatchDate date, DeliveryTime time, Price INT, Location VARCHAR(255), CustomerAge INT, CustomrtPhone BIGINT, DispatchAddress VARCHAR(255), Email VARCHAR(50) ); Now, let’s insert 2 records into the above created table using the INSERT statement as − mysql> insert into SalesDetails values(1, 'Key-Board', 'Raja', DATE('2019-09-01'), TIME('11:00:00'), 7000, 'Hyderabad', 25, '9000012345', 'Hyderabad – Madhapur', 'pujasharma@gmail.com'); Query OK, 1 row affected (0.84 sec) mysql> insert into SalesDetails values(2, 'Mobile', 'Vanaja', DATE('2019-03-01'), TIME('10:10:52'), 9000, 'Chennai', 30, '90000123654', 'Chennai- TNagar', 'vanajarani@gmail.com'); Query OK, 1 row affected (1.84 sec) If we want another table with just the contact details of the customer create a table as − mysql> CREATE TABLE CustContactDetails ( ID INT, Name VARCHAR(255), Age INT, Phone BIGINT, Address VARCHAR(255), Email VARCHAR(50) ); Following queries insets records into the CustContactDetails table using the INSERT INTO SELECT statement. Here, we are trying to insert records from the SALES_DETAILS table to CustContactDetails table. Here before the transfer, we are acquiring the write lock on the table to which we are inserting records and acquiring read lock on the table from which we are inserting records. Finally, after the transfer we are releasing the records. LOCK TABLES SalesDetails READ, CustContactDetails WRITE; INSERT INTO CustContactDetails (ID, Name, Age, Phone, Address, Email) SELECT ID, CustomerName, CustomerAge, CustomrtPhone, DispatchAddress, Email FROM SalesDetails WHERE ID = 1 AND CustomerName = 'Raja'; INSERT INTO CustContactDetails (ID, Name, Age, Phone, Address, Email) SELECT ID, CustomerName, CustomerAge, CustomrtPhone, DispatchAddress, Email FROM SalesDetails WHERE ID = 2 AND CustomerName = 'Vanaja'; UNLOCK TABLES; You can verify the contents of the CustContactDetails table as shown below − mysql> SELECT * FROM CustContactDetails; +------+--------+------+-------------+----------------------+----------------------+ | ID | Name | Age | Phone | Address | Email | +------+--------+------+-------------+----------------------+----------------------+ | 1 | Raja | 25 | 9000012345 | Hyderabad – Madhapur | pujasharma@gmail.com | | 2 | Vanaja | 30 | 90000123654 | Chennai- TNagar | vanajarani@gmail.com | +------+--------+------+-------------+----------------------+----------------------+ 2 rows in set (0.00 sec) 31 Lectures 6 hours Eduonix Learning Solutions 84 Lectures 5.5 hours Frahaan Hussain 6 Lectures 3.5 hours DATAhill Solutions Srinivas Reddy 60 Lectures 10 hours Vijay Kumar Parvatha Reddy 10 Lectures 1 hours Harshit Srivastava 25 Lectures 4 hours Trevoir Williams Print Add Notes Bookmark this page
[ { "code": null, "e": 2534, "s": 2333, "text": "A session releases all the tables locks with it at once. You can implicitly release the table locks. If the connection to the server terminates explicitly or implicitly all the locks will be released." }, { "code": null, "e": 2617, "s": 2534, "text": "You can release the locks of a table explicitly using the UNLOCK TABLES statement." }, { "code": null, "e": 2680, "s": 2617, "text": "Following is the syntax of the MySQL UNLOCK TABLES statement −" }, { "code": null, "e": 2695, "s": 2680, "text": "UNLOCK TABLES\n" }, { "code": null, "e": 2824, "s": 2695, "text": "Suppose we have created a table that contains the sales details along with the contact details of the customers as shown below −" }, { "code": null, "e": 3115, "s": 2824, "text": "mysql> CREATE TABLE SalesDetails (\n ID INT,\n ProductName VARCHAR(255),\n CustomerName VARCHAR(255),\n DispatchDate date,\n DeliveryTime time,\n Price INT,\n Location VARCHAR(255),\n CustomerAge INT,\n CustomrtPhone BIGINT,\n DispatchAddress VARCHAR(255),\n Email VARCHAR(50)\n);" }, { "code": null, "e": 3204, "s": 3115, "text": "Now, let’s insert 2 records into the above created table using the INSERT statement as −" }, { "code": null, "e": 3644, "s": 3204, "text": "mysql> insert into SalesDetails values(1, 'Key-Board', 'Raja', DATE('2019-09-01'), TIME('11:00:00'), 7000, 'Hyderabad', 25, '9000012345', 'Hyderabad – Madhapur', 'pujasharma@gmail.com');\nQuery OK, 1 row affected (0.84 sec)\nmysql> insert into SalesDetails values(2, 'Mobile', 'Vanaja', DATE('2019-03-01'), TIME('10:10:52'), 9000, 'Chennai', 30, '90000123654', 'Chennai- TNagar', 'vanajarani@gmail.com'); \nQuery OK, 1 row affected (1.84 sec)" }, { "code": null, "e": 3735, "s": 3644, "text": "If we want another table with just the contact details of the customer create a table as −" }, { "code": null, "e": 3887, "s": 3735, "text": "mysql> CREATE TABLE CustContactDetails (\n ID INT,\n Name VARCHAR(255),\n Age INT,\n Phone BIGINT,\n Address VARCHAR(255),\n Email VARCHAR(50)\n);" }, { "code": null, "e": 4090, "s": 3887, "text": "Following queries insets records into the CustContactDetails table using the INSERT INTO SELECT statement. Here, we are trying to insert records from the SALES_DETAILS table to CustContactDetails table." }, { "code": null, "e": 4327, "s": 4090, "text": "Here before the transfer, we are acquiring the write lock on the table to which we are inserting records and acquiring read lock on the table from which we are inserting records. Finally, after the transfer we are releasing the records." }, { "code": null, "e": 4864, "s": 4327, "text": "LOCK TABLES SalesDetails READ, CustContactDetails WRITE;\nINSERT INTO CustContactDetails (ID, Name, Age, Phone, Address, Email)\n SELECT\n ID, CustomerName, CustomerAge, CustomrtPhone, DispatchAddress, Email\n FROM\n SalesDetails\n WHERE\n ID = 1 AND CustomerName = 'Raja';\n\nINSERT INTO CustContactDetails (ID, Name, Age, Phone, Address, Email)\n SELECT\n ID, CustomerName, CustomerAge, CustomrtPhone, DispatchAddress, Email\n FROM\n SalesDetails\n WHERE\n ID = 2 AND CustomerName = 'Vanaja';\nUNLOCK TABLES;" }, { "code": null, "e": 4941, "s": 4864, "text": "You can verify the contents of the CustContactDetails table as shown below −" }, { "code": null, "e": 5517, "s": 4941, "text": "mysql> SELECT * FROM CustContactDetails;\n+------+--------+------+-------------+----------------------+----------------------+\n| ID | Name | Age | Phone | Address | Email |\n+------+--------+------+-------------+----------------------+----------------------+\n| 1 | Raja | 25 | 9000012345 | Hyderabad – Madhapur | pujasharma@gmail.com |\n| 2 | Vanaja | 30 | 90000123654 | Chennai- TNagar | vanajarani@gmail.com |\n+------+--------+------+-------------+----------------------+----------------------+\n2 rows in set (0.00 sec)" }, { "code": null, "e": 5550, "s": 5517, "text": "\n 31 Lectures \n 6 hours \n" }, { "code": null, "e": 5578, "s": 5550, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 5613, "s": 5578, "text": "\n 84 Lectures \n 5.5 hours \n" }, { "code": null, "e": 5630, "s": 5613, "text": " Frahaan Hussain" }, { "code": null, "e": 5664, "s": 5630, "text": "\n 6 Lectures \n 3.5 hours \n" }, { "code": null, "e": 5699, "s": 5664, "text": " DATAhill Solutions Srinivas Reddy" }, { "code": null, "e": 5733, "s": 5699, "text": "\n 60 Lectures \n 10 hours \n" }, { "code": null, "e": 5761, "s": 5733, "text": " Vijay Kumar Parvatha Reddy" }, { "code": null, "e": 5794, "s": 5761, "text": "\n 10 Lectures \n 1 hours \n" }, { "code": null, "e": 5814, "s": 5794, "text": " Harshit Srivastava" }, { "code": null, "e": 5847, "s": 5814, "text": "\n 25 Lectures \n 4 hours \n" }, { "code": null, "e": 5865, "s": 5847, "text": " Trevoir Williams" }, { "code": null, "e": 5872, "s": 5865, "text": " Print" }, { "code": null, "e": 5883, "s": 5872, "text": " Add Notes" } ]
Kotlin - Constructors
A Kotlin constructor is a special member function in a class that is invoked when an object is instantiated. Whenever an object is created, the defined constructor is called automatically which is used to initialize the properties of the class. A Kotlin class can have following two type of constructors: Primary Constructor Primary Constructor Second Constructors Second Constructors A Kotlin class can have a primary constructor and one or more additional secondary constructors. The Kotlin primary constructor initializes the class, whereas the secondary constructor helps to include some extra logic while initializing the class. The primary constructor can be declared at class header level as shown in the following example. class Person constructor(val firstName: String, val age: Int) { // class body } The constructor keyword can be omitted if there is no annotations or access modifiers specified like public, private or protected.. class Person (val firstName: String, val age: Int) { // class body } In this example, we have declared properties through the val keyword to make them read-only. These properties could be defined using keyword var if you need to change their values at later point in time. The primary constructor cannot contain any code. Initialization code can be placed in initializer blocks prefixed with the init keyword. There could be more than one init blocks and during the initialization of an instance, the initializer blocks are executed in the same order as they appear in the class body, interleaved with the property initializers: Following is an example with a usage of initializer block: class Person (val _name: String, val _age: Int) { // Member Variables var name: String var age: Int // Initializer Block init { this.name = _name this.age = _age println("Name = $name") println("Age = $age") } } fun main(args: Array<String>) { val person = Person("Zara", 20) } When you run the above Kotlin program, it will generate the following output: Name = Zara Age = 20 Kotlin allows to initialize the constructor parameters with some default values. Following is a working example for the same: class Person (val _name: String, val _age: Int=20) { // Member Variables var name: String var age: Int // Initializer Block init { this.name = _name this.age = _age println("Name = $name") println("Age = $age") } } fun main(args: Array<String>) { val zara = Person("Zara") val nuha = Person("Nuha", 11) } When you run the above Kotlin program, it will generate the following output: Name = Zara Age = 20 Name = Nuha Age = 11 As mentioned earlier, Kotlin allows to create one or more secondary constructors for your class. This secondary constructor is created using the constructor keyword. It is required whenever you want to create more than one constructor in Kotlin or whenever you want to include more logic in the primary constructor and you cannot do that because the primary constructor may be called by some other class. Take a look at the following example, here we have created a secondary constructor to implement the above example once again: class Person{ // Member Variables var name: String var age: Int // Initializer Block init { println("Initializer Block") } // Secondary Constructor constructor ( _name: String, _age: Int) { this.name = _name this.age = _age println("Name = $name") println("Age = $age") } } fun main(args: Array<String>) { val zara = Person("Zara", 20) } When you run the above Kotlin program, it will generate the following output: Initializer Block Name = Zara Age = 20 Secondary constructor do not allow to use val or var with secondary constructor parameters. Now let's see one example with two secondary constructors: class Person{ // Member Variables var name: String var age: Int var salary:Double // First Secondary Constructor constructor ( _name: String, _age: Int) { this.name = _name this.age = _age this.salary = 0.00 println("Name = $name") println("Age = $age") } // Second Secondary Constructor constructor ( _name: String, _age: Int, _salary: Double) { this.name = _name this.age = _age this.salary = _salary println("Name = $name") println("Age = $age") println("Salary = $salary") } } fun main(args: Array<String>) { val nuha = Person("Nuha", 12) val zara = Person("Zara", 20, 2000.00) } When you run the above Kotlin program, it will generate the following output: Name = Nuha Age = 12 Name = Zara Age = 20 Salary = 2000.0 Q 1 - We can define N number of constructors in Kotlin program: A - Yes B - No Yes we can define a primary constructor and multiple number of secondary constructors in Kotlin program Q 2 - Which keyword is used to define a Kotlin constructor: A - init B - constructor C - Constructor D - All the bove Though the constructor keyword can be omitted if there is no annotations or access modifiers specified. Q 3 - Kotlin allows to set default values for the constructor parameters. A - True B - False Yes we can set a default value for any of the constructor parameters. Q 4 - Second constructor does not allow to use data types alongwith its parameters. A - True B - B We can not use data types alongwith secondary constructor parameters. 68 Lectures 4.5 hours Arnab Chakraborty 71 Lectures 5.5 hours Frahaan Hussain 18 Lectures 1.5 hours Mahmoud Ramadan 49 Lectures 6 hours Catalin Stefan 49 Lectures 2.5 hours Skillbakerystudios 22 Lectures 1 hours CLEMENT OCHIENG Print Add Notes Bookmark this page
[ { "code": null, "e": 2670, "s": 2425, "text": "A Kotlin constructor is a special member function in a class that is invoked when an object is instantiated. Whenever an object is created, the defined constructor is called automatically which is used to initialize the properties of the class." }, { "code": null, "e": 2730, "s": 2670, "text": "A Kotlin class can have following two type of constructors:" }, { "code": null, "e": 2750, "s": 2730, "text": "Primary Constructor" }, { "code": null, "e": 2770, "s": 2750, "text": "Primary Constructor" }, { "code": null, "e": 2790, "s": 2770, "text": "Second Constructors" }, { "code": null, "e": 2810, "s": 2790, "text": "Second Constructors" }, { "code": null, "e": 3059, "s": 2810, "text": "A Kotlin class can have a primary constructor and one or more additional secondary constructors. The Kotlin primary constructor initializes the class, whereas the secondary constructor helps to include some extra logic while initializing the class." }, { "code": null, "e": 3156, "s": 3059, "text": "The primary constructor can be declared at class header level as shown in the following example." }, { "code": null, "e": 3240, "s": 3156, "text": "class Person constructor(val firstName: String, val age: Int) {\n // class body\n}\n" }, { "code": null, "e": 3373, "s": 3240, "text": "The constructor keyword can be omitted if there is no annotations or access modifiers specified like public, private or protected.." }, { "code": null, "e": 3446, "s": 3373, "text": "class Person (val firstName: String, val age: Int) {\n // class body\n}\n" }, { "code": null, "e": 3650, "s": 3446, "text": "In this example, we have declared properties through the val keyword to make them read-only. These properties could be defined using keyword var if you need to change their values at later point in time." }, { "code": null, "e": 4006, "s": 3650, "text": "The primary constructor cannot contain any code. Initialization code can be placed in initializer blocks prefixed with the init keyword. There could be more than one init blocks and during the initialization of an instance, the initializer blocks are executed in the same order as they appear in the class body, interleaved with the property initializers:" }, { "code": null, "e": 4065, "s": 4006, "text": "Following is an example with a usage of initializer block:" }, { "code": null, "e": 4391, "s": 4065, "text": "class Person (val _name: String, val _age: Int) {\n // Member Variables\n var name: String\n var age: Int\n\n // Initializer Block\n init {\n this.name = _name\n this.age = _age\n println(\"Name = $name\")\n println(\"Age = $age\")\n }\n}\n\nfun main(args: Array<String>) {\n val person = Person(\"Zara\", 20)\n}\n" }, { "code": null, "e": 4469, "s": 4391, "text": "When you run the above Kotlin program, it will generate the following output:" }, { "code": null, "e": 4491, "s": 4469, "text": "Name = Zara\nAge = 20\n" }, { "code": null, "e": 4617, "s": 4491, "text": "Kotlin allows to initialize the constructor parameters with some default values. Following is a working example for the same:" }, { "code": null, "e": 4973, "s": 4617, "text": "class Person (val _name: String, val _age: Int=20) {\n // Member Variables\n var name: String\n var age: Int\n\n // Initializer Block\n init {\n this.name = _name\n this.age = _age\n println(\"Name = $name\")\n println(\"Age = $age\")\n }\n}\n\nfun main(args: Array<String>) {\n val zara = Person(\"Zara\")\n val nuha = Person(\"Nuha\", 11)\n}\n" }, { "code": null, "e": 5051, "s": 4973, "text": "When you run the above Kotlin program, it will generate the following output:" }, { "code": null, "e": 5094, "s": 5051, "text": "Name = Zara\nAge = 20\nName = Nuha\nAge = 11\n" }, { "code": null, "e": 5499, "s": 5094, "text": "As mentioned earlier, Kotlin allows to create one or more secondary constructors for your class. This secondary constructor is created using the constructor keyword. It is required whenever you want to create more than one constructor in Kotlin or whenever you want to include more logic in the primary constructor and you cannot do that because the primary constructor may be called by some other class." }, { "code": null, "e": 5625, "s": 5499, "text": "Take a look at the following example, here we have created a secondary constructor to implement the above example once again:" }, { "code": null, "e": 6027, "s": 5625, "text": "class Person{\n // Member Variables\n var name: String\n var age: Int\n\n // Initializer Block\n init {\n println(\"Initializer Block\")\n }\n\n // Secondary Constructor\n constructor ( _name: String, _age: Int) {\n this.name = _name\n this.age = _age\n println(\"Name = $name\")\n println(\"Age = $age\")\n }\n}\n\nfun main(args: Array<String>) {\n val zara = Person(\"Zara\", 20)\n}\n" }, { "code": null, "e": 6105, "s": 6027, "text": "When you run the above Kotlin program, it will generate the following output:" }, { "code": null, "e": 6145, "s": 6105, "text": "Initializer Block\nName = Zara\nAge = 20\n" }, { "code": null, "e": 6296, "s": 6145, "text": "Secondary constructor do not allow to use val or var with secondary constructor parameters. Now let's see one example with two secondary constructors:" }, { "code": null, "e": 6986, "s": 6296, "text": "class Person{\n // Member Variables\n var name: String\n var age: Int\n var salary:Double\n\n // First Secondary Constructor\n constructor ( _name: String, _age: Int) {\n this.name = _name\n this.age = _age\n this.salary = 0.00\n println(\"Name = $name\")\n println(\"Age = $age\")\n }\n\n // Second Secondary Constructor\n constructor ( _name: String, _age: Int, _salary: Double) {\n this.name = _name\n this.age = _age\n this.salary = _salary\n println(\"Name = $name\")\n println(\"Age = $age\")\n println(\"Salary = $salary\")\n }\n}\n\nfun main(args: Array<String>) {\n val nuha = Person(\"Nuha\", 12)\n val zara = Person(\"Zara\", 20, 2000.00)\n}\n" }, { "code": null, "e": 7064, "s": 6986, "text": "When you run the above Kotlin program, it will generate the following output:" }, { "code": null, "e": 7123, "s": 7064, "text": "Name = Nuha\nAge = 12\nName = Zara\nAge = 20\nSalary = 2000.0\n" }, { "code": null, "e": 7187, "s": 7123, "text": "Q 1 - We can define N number of constructors in Kotlin program:" }, { "code": null, "e": 7195, "s": 7187, "text": "A - Yes" }, { "code": null, "e": 7202, "s": 7195, "text": "B - No" }, { "code": null, "e": 7306, "s": 7202, "text": "Yes we can define a primary constructor and multiple number of secondary constructors in Kotlin program" }, { "code": null, "e": 7366, "s": 7306, "text": "Q 2 - Which keyword is used to define a Kotlin constructor:" }, { "code": null, "e": 7375, "s": 7366, "text": "A - init" }, { "code": null, "e": 7391, "s": 7375, "text": "B - constructor" }, { "code": null, "e": 7407, "s": 7391, "text": "C - Constructor" }, { "code": null, "e": 7424, "s": 7407, "text": "D - All the bove" }, { "code": null, "e": 7528, "s": 7424, "text": "Though the constructor keyword can be omitted if there is no annotations or access modifiers specified." }, { "code": null, "e": 7602, "s": 7528, "text": "Q 3 - Kotlin allows to set default values for the constructor parameters." }, { "code": null, "e": 7611, "s": 7602, "text": "A - True" }, { "code": null, "e": 7621, "s": 7611, "text": "B - False" }, { "code": null, "e": 7691, "s": 7621, "text": "Yes we can set a default value for any of the constructor parameters." }, { "code": null, "e": 7775, "s": 7691, "text": "Q 4 - Second constructor does not allow to use data types alongwith its parameters." }, { "code": null, "e": 7784, "s": 7775, "text": "A - True" }, { "code": null, "e": 7790, "s": 7784, "text": "B - B" }, { "code": null, "e": 7860, "s": 7790, "text": "We can not use data types alongwith secondary constructor parameters." }, { "code": null, "e": 7895, "s": 7860, "text": "\n 68 Lectures \n 4.5 hours \n" }, { "code": null, "e": 7914, "s": 7895, "text": " Arnab Chakraborty" }, { "code": null, "e": 7949, "s": 7914, "text": "\n 71 Lectures \n 5.5 hours \n" }, { "code": null, "e": 7966, "s": 7949, "text": " Frahaan Hussain" }, { "code": null, "e": 8001, "s": 7966, "text": "\n 18 Lectures \n 1.5 hours \n" }, { "code": null, "e": 8018, "s": 8001, "text": " Mahmoud Ramadan" }, { "code": null, "e": 8051, "s": 8018, "text": "\n 49 Lectures \n 6 hours \n" }, { "code": null, "e": 8067, "s": 8051, "text": " Catalin Stefan" }, { "code": null, "e": 8102, "s": 8067, "text": "\n 49 Lectures \n 2.5 hours \n" }, { "code": null, "e": 8122, "s": 8102, "text": " Skillbakerystudios" }, { "code": null, "e": 8155, "s": 8122, "text": "\n 22 Lectures \n 1 hours \n" }, { "code": null, "e": 8172, "s": 8155, "text": " CLEMENT OCHIENG" }, { "code": null, "e": 8179, "s": 8172, "text": " Print" }, { "code": null, "e": 8190, "s": 8179, "text": " Add Notes" } ]
Recommender System — singular value decomposition (SVD) & truncated SVD | by Denise Chen | Towards Data Science
The most common method for recommendation systems often comes with Collaborating Filtering (CF) where it relies on the past user and item dataset. Two popular approaches of CF are latent factor models, which extract features from user and item matrices and neighborhood models, which finds similarities between products or users. The neighborhood model is an item-oriented approach to discover the user preference based on the ratings given by the user for similar items. On the other hand, latent factor models such as Singular Value Decomposition (SVD) extract features and correlation from the user-item matrix. For example, when items are movies in different categories. SVD would generate factors when looking into the dimension space like action vs comedy, Hollywood vs Bollywood, or Marvel vs Disney. Mainly, we will focus on the latent factor model for the Singular Value Decomposition (SVD) approach. In this article, you will learn the singular value decomposition and truncated SVD of the recommender system: (1) Introduction to singular value decomposition (2) Introduction to truncated SVD (3) Hands-on experience of python code on matrix factorization When it comes to dimensionality reduction, the Singular Value Decomposition (SVD) is a popular method in linear algebra for matrix factorization in machine learning. Such a method shrinks the space dimension from N-dimension to K-dimension (where K<N) and reduces the number of features. SVD constructs a matrix with the row of users and columns of items and the elements are given by the users’ ratings. Singular value decomposition decomposes a matrix into three other matrices and extracts the factors from the factorization of a high-level (user-item-rating) matrix. Matrix U: singular matrix of (user*latent factors)Matrix S: diagonal matrix (shows the strength of each latent factor)Matrix U: singular matrix of (item*latent factors) From matrix factorization, the latent factors show the characteristics of the items. Finally, the utility matrix A is produced with shape m*n. The final output of the matrix A reduces the dimension through latent factors’ extraction. From the matrix A, it shows the relationships between users and items by mapping the user and item into r-dimensional latent space. Vector X_i is considered each item and vector Y_u is regarded as each user. The rating is given by a user on an item as R_ui = X^T_i * Y_u. The loss can be minimized by the square error difference between the product of R_ui and the expected rating. Regularization is used to avoid overfitting and generalize the dataset by adding the penalty. Here, we add a bias term to reduce the error of actual versus predicted value by the model. (u, i): user-item pairμ: the average rating of all itemsbi: average rating of item i minus μbu: the average rating given by user u minus μ The equation below adds the bias term and the regularization term: When it comes to matrix factorization technique, truncated Singular Value Decomposition (SVD) is a popular method to produce features that factors a matrix M into the three matrices U, Σ, and V. Another popular method is Principal Component Analysis (PCA). Truncated SVD shares similarity with PCA while SVD is produced from the data matrix and the factorization of PCA is generated from the covariance matrix. Unlike regular SVDs, truncated SVD produces a factorization where the number of columns can be specified for a number of truncation. For example, given an n x n matrix, truncated SVD generates the matrices with the specified number of columns, whereas SVD outputs n columns of matrices. Truncated SVD can deal with sparse matrix to generate features’ matrices, whereas PCA would operate on the entire matrix for the output of the covariance matrix. The metadata includes 45,000 movies listed in the Full MovieLens Dataset and movies are released before July 2017. Cast, crew, plot keywords, budget, revenue, posters, release dates, languages, production companies, countries, TMDB vote counts and vote averages are in the dataset. The scale of ratings is 1–5 and obtained from the official GroupLens website. The dataset is referred to from the Kaggle dataset. Singular value decomposition (SVD) is a collaborative filtering method for movie recommendation. The aim for the code implementation is to provide users with movies’ recommendation from the latent features of item-user matrices. The code would show you how to use the SVD latent factor model for matrix factorization. Random sample the rating dataset and generate the movie features with genres. Then, labelencode all the movies and users with respective unique ids. num of users: 1105num of movies: 3000 Through each run of the epoch, the rmse is reduced and the final output reaches rmse 0.57. The number of batch size would affect the number of input data fed into the model for each run. Batch size, learning rate, and regularization term are tunable to optimize the model performance. RMSE 2.1727233RMSE 2.101482RMSE 2.0310202RMSE 1.9610059RMSE 1.8911659RMSE 1.8213558RMSE 1.7515925RMSE 1.681992RMSE 1.612707RMSE 1.543902RMSE 1.4757496RMSE 1.408429RMSE 1.3421307RMSE 1.277059RMSE 1.2134355RMSE 1.1514966RMSE 1.0914934RMSE 1.0336862RMSE 0.9783424RMSE 0.9257237RMSE 0.87606686RMSE 0.82956517RMSE 0.7863303RMSE 0.7463626RMSE 0.7095342RMSE 0.67563176RMSE 0.6445249RMSE 0.6163493RMSE 0.5914116RMSE 0.5701855 The first 10 components of user x movie matrix s generated through truncated SVD. There are latent features in the reconstructed matrix showing a correlation with the user ratings for the rating prediction. Since the genres column is in the list of the dictionary format, The column is preprocessed and extracted with several genres’ names separated by | format. Take a 3000 random sample of users’ ratings from the dataset and create the pivot table with the index of Userid and columns of MovieID with the rating value. Then, the user matrix is generated with 2921x1739 users by the user matrix. Take 3000 random samples of movies from the dataset and create the pivot table with the index of MovieID and columns of Userid with the rating value. Then, the movie matrix is generated with 3000x1105 users by the movie matrix. From both user and rating matrix, 80% of data is used for training data and the rest 20% is for test data. For the train data, the reconstructed matrix is produced from 10 components of truncated SVD. The row*col length of matrices is movie_features.shape = (2400, 10) and user_features.shape = (2336, 10). TSNE Visualization TSNE transforms the high-dimensional space of data into a low-dimensional space of data and visualizes it. Perplexity is one of the tuneable features to take the balance of local and global data and suggest the number of close neighbors each point has. Take the perplexity of 5 and 2 components of the movie features and the plot is produced and shows the clusters of movies. The correlated movies are clustered by the latent features produced from the TSNE method. The label of the target data is the average users’ rating and round it to 1 decimal point. There are a total of 501 movies and 1108 users’ ratings. The size of the train and the target data are data.shape = (3000, 1105) and targets.shape = (3000,). Train the model of GradientBoostingRegressor with the learning rate of 0.1 and 200 estimators. The loss function is calculated through mean squared error. The final prediction is the average rating of each movie by all the ratings produced from the users. The final MSE is around 0.51, which is quite optimal for the average rating model. Iter Train Loss Remaining Time 1 0.3735 5.43s 2 0.3710 5.12s 3 0.3689 4.89s 4 0.3672 4.76s 5 0.3656 4.67s 6 0.3641 4.64s 7 0.3628 4.59s 8 0.3614 4.54s 9 0.3601 4.52s 10 0.3589 4.51s 20 0.3480 4.14s 30 0.3391 3.83s 40 0.3316 3.59s 50 0.3245 3.35s 60 0.3174 3.14s 70 0.3118 2.91s 80 0.3063 2.68s 90 0.3013 2.45s 100 0.2968 2.22s 200 0.2620 0.00sFinal MSE:0.5118555681581297 Singular value decomposition decomposes three matrices and the latent factors show the characteristics of the items. It reduces the dimension through latent factors’ extraction. By adding the regularization and bias term, it optimizes the model performance by minimizing the rmse error.Truncated SVD generates the matrices with the specified number of columns, whereas SVD outputs n columns of matrices. It decreases the number of output and better works on the sparse matrices for features output. Singular value decomposition decomposes three matrices and the latent factors show the characteristics of the items. It reduces the dimension through latent factors’ extraction. By adding the regularization and bias term, it optimizes the model performance by minimizing the rmse error. Truncated SVD generates the matrices with the specified number of columns, whereas SVD outputs n columns of matrices. It decreases the number of output and better works on the sparse matrices for features output. Using truncated SVD to reduce dimensionalityhttps://subscription.packtpub.com/book/big_data_and_business_intelligence/9781783989485/1/ch01lvl1sec21/using-truncated-svd-to-reduce-dimensionalityRecommending movies using Truncated SVDhttps://github.com/saurabhmathur96/movie-recommendations/blob/master/notebooks/Recommending%20movies%20using%20Truncated%20SVD.ipynb Using truncated SVD to reduce dimensionalityhttps://subscription.packtpub.com/book/big_data_and_business_intelligence/9781783989485/1/ch01lvl1sec21/using-truncated-svd-to-reduce-dimensionality Recommending movies using Truncated SVDhttps://github.com/saurabhmathur96/movie-recommendations/blob/master/notebooks/Recommending%20movies%20using%20Truncated%20SVD.ipynb 3. Singular Value Decomposition (SVD) & Its Application In Recommender Systemhttps://analyticsindiamag.com/singular-value-decomposition-svd-application-recommender-system/#:~:text=In%20the%20context%20of%20the,given%20to%20items%20by%20users. 4. Recommending movies using SVD Matrix Factorisationhttps://github.com/saurabhmathur96/movie-recommendations/blob/master/notebooks/Recommending%20movies%20using%20SVD%20Matrix%20Factorisation.ipynb
[ { "code": null, "e": 501, "s": 171, "text": "The most common method for recommendation systems often comes with Collaborating Filtering (CF) where it relies on the past user and item dataset. Two popular approaches of CF are latent factor models, which extract features from user and item matrices and neighborhood models, which finds similarities between products or users." }, { "code": null, "e": 1081, "s": 501, "text": "The neighborhood model is an item-oriented approach to discover the user preference based on the ratings given by the user for similar items. On the other hand, latent factor models such as Singular Value Decomposition (SVD) extract features and correlation from the user-item matrix. For example, when items are movies in different categories. SVD would generate factors when looking into the dimension space like action vs comedy, Hollywood vs Bollywood, or Marvel vs Disney. Mainly, we will focus on the latent factor model for the Singular Value Decomposition (SVD) approach." }, { "code": null, "e": 1191, "s": 1081, "text": "In this article, you will learn the singular value decomposition and truncated SVD of the recommender system:" }, { "code": null, "e": 1240, "s": 1191, "text": "(1) Introduction to singular value decomposition" }, { "code": null, "e": 1274, "s": 1240, "text": "(2) Introduction to truncated SVD" }, { "code": null, "e": 1337, "s": 1274, "text": "(3) Hands-on experience of python code on matrix factorization" }, { "code": null, "e": 1908, "s": 1337, "text": "When it comes to dimensionality reduction, the Singular Value Decomposition (SVD) is a popular method in linear algebra for matrix factorization in machine learning. Such a method shrinks the space dimension from N-dimension to K-dimension (where K<N) and reduces the number of features. SVD constructs a matrix with the row of users and columns of items and the elements are given by the users’ ratings. Singular value decomposition decomposes a matrix into three other matrices and extracts the factors from the factorization of a high-level (user-item-rating) matrix." }, { "code": null, "e": 2077, "s": 1908, "text": "Matrix U: singular matrix of (user*latent factors)Matrix S: diagonal matrix (shows the strength of each latent factor)Matrix U: singular matrix of (item*latent factors)" }, { "code": null, "e": 2693, "s": 2077, "text": "From matrix factorization, the latent factors show the characteristics of the items. Finally, the utility matrix A is produced with shape m*n. The final output of the matrix A reduces the dimension through latent factors’ extraction. From the matrix A, it shows the relationships between users and items by mapping the user and item into r-dimensional latent space. Vector X_i is considered each item and vector Y_u is regarded as each user. The rating is given by a user on an item as R_ui = X^T_i * Y_u. The loss can be minimized by the square error difference between the product of R_ui and the expected rating." }, { "code": null, "e": 2787, "s": 2693, "text": "Regularization is used to avoid overfitting and generalize the dataset by adding the penalty." }, { "code": null, "e": 2879, "s": 2787, "text": "Here, we add a bias term to reduce the error of actual versus predicted value by the model." }, { "code": null, "e": 3018, "s": 2879, "text": "(u, i): user-item pairμ: the average rating of all itemsbi: average rating of item i minus μbu: the average rating given by user u minus μ" }, { "code": null, "e": 3085, "s": 3018, "text": "The equation below adds the bias term and the regularization term:" }, { "code": null, "e": 3783, "s": 3085, "text": "When it comes to matrix factorization technique, truncated Singular Value Decomposition (SVD) is a popular method to produce features that factors a matrix M into the three matrices U, Σ, and V. Another popular method is Principal Component Analysis (PCA). Truncated SVD shares similarity with PCA while SVD is produced from the data matrix and the factorization of PCA is generated from the covariance matrix. Unlike regular SVDs, truncated SVD produces a factorization where the number of columns can be specified for a number of truncation. For example, given an n x n matrix, truncated SVD generates the matrices with the specified number of columns, whereas SVD outputs n columns of matrices." }, { "code": null, "e": 3945, "s": 3783, "text": "Truncated SVD can deal with sparse matrix to generate features’ matrices, whereas PCA would operate on the entire matrix for the output of the covariance matrix." }, { "code": null, "e": 4357, "s": 3945, "text": "The metadata includes 45,000 movies listed in the Full MovieLens Dataset and movies are released before July 2017. Cast, crew, plot keywords, budget, revenue, posters, release dates, languages, production companies, countries, TMDB vote counts and vote averages are in the dataset. The scale of ratings is 1–5 and obtained from the official GroupLens website. The dataset is referred to from the Kaggle dataset." }, { "code": null, "e": 4675, "s": 4357, "text": "Singular value decomposition (SVD) is a collaborative filtering method for movie recommendation. The aim for the code implementation is to provide users with movies’ recommendation from the latent features of item-user matrices. The code would show you how to use the SVD latent factor model for matrix factorization." }, { "code": null, "e": 4824, "s": 4675, "text": "Random sample the rating dataset and generate the movie features with genres. Then, labelencode all the movies and users with respective unique ids." }, { "code": null, "e": 4862, "s": 4824, "text": "num of users: 1105num of movies: 3000" }, { "code": null, "e": 5147, "s": 4862, "text": "Through each run of the epoch, the rmse is reduced and the final output reaches rmse 0.57. The number of batch size would affect the number of input data fed into the model for each run. Batch size, learning rate, and regularization term are tunable to optimize the model performance." }, { "code": null, "e": 5565, "s": 5147, "text": "RMSE 2.1727233RMSE 2.101482RMSE 2.0310202RMSE 1.9610059RMSE 1.8911659RMSE 1.8213558RMSE 1.7515925RMSE 1.681992RMSE 1.612707RMSE 1.543902RMSE 1.4757496RMSE 1.408429RMSE 1.3421307RMSE 1.277059RMSE 1.2134355RMSE 1.1514966RMSE 1.0914934RMSE 1.0336862RMSE 0.9783424RMSE 0.9257237RMSE 0.87606686RMSE 0.82956517RMSE 0.7863303RMSE 0.7463626RMSE 0.7095342RMSE 0.67563176RMSE 0.6445249RMSE 0.6163493RMSE 0.5914116RMSE 0.5701855" }, { "code": null, "e": 5772, "s": 5565, "text": "The first 10 components of user x movie matrix s generated through truncated SVD. There are latent features in the reconstructed matrix showing a correlation with the user ratings for the rating prediction." }, { "code": null, "e": 5928, "s": 5772, "text": "Since the genres column is in the list of the dictionary format, The column is preprocessed and extracted with several genres’ names separated by | format." }, { "code": null, "e": 6163, "s": 5928, "text": "Take a 3000 random sample of users’ ratings from the dataset and create the pivot table with the index of Userid and columns of MovieID with the rating value. Then, the user matrix is generated with 2921x1739 users by the user matrix." }, { "code": null, "e": 6391, "s": 6163, "text": "Take 3000 random samples of movies from the dataset and create the pivot table with the index of MovieID and columns of Userid with the rating value. Then, the movie matrix is generated with 3000x1105 users by the movie matrix." }, { "code": null, "e": 6698, "s": 6391, "text": "From both user and rating matrix, 80% of data is used for training data and the rest 20% is for test data. For the train data, the reconstructed matrix is produced from 10 components of truncated SVD. The row*col length of matrices is movie_features.shape = (2400, 10) and user_features.shape = (2336, 10)." }, { "code": null, "e": 6717, "s": 6698, "text": "TSNE Visualization" }, { "code": null, "e": 6970, "s": 6717, "text": "TSNE transforms the high-dimensional space of data into a low-dimensional space of data and visualizes it. Perplexity is one of the tuneable features to take the balance of local and global data and suggest the number of close neighbors each point has." }, { "code": null, "e": 7183, "s": 6970, "text": "Take the perplexity of 5 and 2 components of the movie features and the plot is produced and shows the clusters of movies. The correlated movies are clustered by the latent features produced from the TSNE method." }, { "code": null, "e": 7432, "s": 7183, "text": "The label of the target data is the average users’ rating and round it to 1 decimal point. There are a total of 501 movies and 1108 users’ ratings. The size of the train and the target data are data.shape = (3000, 1105) and targets.shape = (3000,)." }, { "code": null, "e": 7587, "s": 7432, "text": "Train the model of GradientBoostingRegressor with the learning rate of 0.1 and 200 estimators. The loss function is calculated through mean squared error." }, { "code": null, "e": 7771, "s": 7587, "text": "The final prediction is the average rating of each movie by all the ratings produced from the users. The final MSE is around 0.51, which is quite optimal for the average rating model." }, { "code": null, "e": 8726, "s": 7771, "text": " Iter Train Loss Remaining Time 1 0.3735 5.43s 2 0.3710 5.12s 3 0.3689 4.89s 4 0.3672 4.76s 5 0.3656 4.67s 6 0.3641 4.64s 7 0.3628 4.59s 8 0.3614 4.54s 9 0.3601 4.52s 10 0.3589 4.51s 20 0.3480 4.14s 30 0.3391 3.83s 40 0.3316 3.59s 50 0.3245 3.35s 60 0.3174 3.14s 70 0.3118 2.91s 80 0.3063 2.68s 90 0.3013 2.45s 100 0.2968 2.22s 200 0.2620 0.00sFinal MSE:0.5118555681581297" }, { "code": null, "e": 9225, "s": 8726, "text": "Singular value decomposition decomposes three matrices and the latent factors show the characteristics of the items. It reduces the dimension through latent factors’ extraction. By adding the regularization and bias term, it optimizes the model performance by minimizing the rmse error.Truncated SVD generates the matrices with the specified number of columns, whereas SVD outputs n columns of matrices. It decreases the number of output and better works on the sparse matrices for features output." }, { "code": null, "e": 9512, "s": 9225, "text": "Singular value decomposition decomposes three matrices and the latent factors show the characteristics of the items. It reduces the dimension through latent factors’ extraction. By adding the regularization and bias term, it optimizes the model performance by minimizing the rmse error." }, { "code": null, "e": 9725, "s": 9512, "text": "Truncated SVD generates the matrices with the specified number of columns, whereas SVD outputs n columns of matrices. It decreases the number of output and better works on the sparse matrices for features output." }, { "code": null, "e": 10089, "s": 9725, "text": "Using truncated SVD to reduce dimensionalityhttps://subscription.packtpub.com/book/big_data_and_business_intelligence/9781783989485/1/ch01lvl1sec21/using-truncated-svd-to-reduce-dimensionalityRecommending movies using Truncated SVDhttps://github.com/saurabhmathur96/movie-recommendations/blob/master/notebooks/Recommending%20movies%20using%20Truncated%20SVD.ipynb" }, { "code": null, "e": 10282, "s": 10089, "text": "Using truncated SVD to reduce dimensionalityhttps://subscription.packtpub.com/book/big_data_and_business_intelligence/9781783989485/1/ch01lvl1sec21/using-truncated-svd-to-reduce-dimensionality" }, { "code": null, "e": 10454, "s": 10282, "text": "Recommending movies using Truncated SVDhttps://github.com/saurabhmathur96/movie-recommendations/blob/master/notebooks/Recommending%20movies%20using%20Truncated%20SVD.ipynb" }, { "code": null, "e": 10697, "s": 10454, "text": "3. Singular Value Decomposition (SVD) & Its Application In Recommender Systemhttps://analyticsindiamag.com/singular-value-decomposition-svd-application-recommender-system/#:~:text=In%20the%20context%20of%20the,given%20to%20items%20by%20users." } ]
Primitive root of a prime number n modulo n in C++
In this problem, we are given a prime number N. our task is to print the primitive root of prime number N modulo N. Primitive root of prime number N is an integer x lying between [1, n-1] such that all values of xk (mod n) where k lies in [0, n-2] are unique. Let’s take an example to understand the problem, Input: 13 Output: 2 To solve this problem, we have to use mathematical function called Euler’s Totient Function. Euler’s Totient Function is the count of numbers from 1 to n which are relatively prime to the number n. A number i is relatively prime if GCD (i, n) = 1. In solution, if the multiplicative order of x modulo n is equal to Euler’s Totient Function, then the number is primitive root otherwise not. We will check for all relative primes. Note: Euler’s Totient Function of a prime number n=n-1 The below code will show the implementation of our solution, Live Demo #include<bits/stdc++.h> using namespace std; bool isPrimeNumber(int n) { if (n <= 1) return false; if (n <= 3) return true; if (n%2 == 0 || n%3 == 0) return false; for (int i=5; i*i<=n; i=i+6) if (n%i == 0 || n%(i+2) == 0) return false; return true; } int power(int x, unsigned int y, int p) { int res = 1; x = x % p; while (y > 0){ if (y & 1) res = (res*x) % p; y = y >> 1; x = (x*x) % p; } return res; } void GeneratePrimes(unordered_set<int> &s, int n) { while (n%2 == 0){ s.insert(2); n = n/2; } for (int i = 3; i <= sqrt(n); i = i+2){ while (n%i == 0){ s.insert(i); n = n/i; } } if (n > 2) s.insert(n); } int findPrimitiveRoot(int n) { unordered_set<int> s; if (isPrimeNumber(n)==false) return -1; int ETF = n-1; GeneratePrimes(s, ETF); for (int r=2; r<=ETF; r++){ bool flag = false; for (auto it = s.begin(); it != s.end(); it++){ if (power(r, ETF/(*it), n) == 1){ flag = true; break; } } if (flag == false) return r; } return -1; } int main() { int n= 13; cout<<" Smallest primitive root of "<<n<<" is "<<findPrimitiveRoot(n); return 0; } Smallest primitive root of 13 is 2
[ { "code": null, "e": 1178, "s": 1062, "text": "In this problem, we are given a prime number N. our task is to print the primitive root of prime number N modulo N." }, { "code": null, "e": 1322, "s": 1178, "text": "Primitive root of prime number N is an integer x lying between [1, n-1] such that all values of xk (mod n) where k lies in [0, n-2] are unique." }, { "code": null, "e": 1371, "s": 1322, "text": "Let’s take an example to understand the problem," }, { "code": null, "e": 1391, "s": 1371, "text": "Input: 13\nOutput: 2" }, { "code": null, "e": 1484, "s": 1391, "text": "To solve this problem, we have to use mathematical function called Euler’s Totient Function." }, { "code": null, "e": 1589, "s": 1484, "text": "Euler’s Totient Function is the count of numbers from 1 to n which are relatively prime to the number n." }, { "code": null, "e": 1639, "s": 1589, "text": "A number i is relatively prime if GCD (i, n) = 1." }, { "code": null, "e": 1820, "s": 1639, "text": "In solution, if the multiplicative order of x modulo n is equal to Euler’s Totient Function, then the number is primitive root otherwise not. We will check for all relative primes." }, { "code": null, "e": 1875, "s": 1820, "text": "Note: Euler’s Totient Function of a prime number n=n-1" }, { "code": null, "e": 1936, "s": 1875, "text": "The below code will show the implementation of our solution," }, { "code": null, "e": 1947, "s": 1936, "text": " Live Demo" }, { "code": null, "e": 3227, "s": 1947, "text": "#include<bits/stdc++.h>\nusing namespace std;\nbool isPrimeNumber(int n) {\n if (n <= 1) return false;\n if (n <= 3) return true;\n if (n%2 == 0 || n%3 == 0) return false;\n for (int i=5; i*i<=n; i=i+6)\n if (n%i == 0 || n%(i+2) == 0)\n return false;\n return true;\n}\nint power(int x, unsigned int y, int p) {\n int res = 1;\n x = x % p;\n while (y > 0){\n if (y & 1)\n res = (res*x) % p;\n y = y >> 1;\n x = (x*x) % p;\n }\n return res;\n}\nvoid GeneratePrimes(unordered_set<int> &s, int n) {\n while (n%2 == 0){\n s.insert(2);\n n = n/2;\n }\n for (int i = 3; i <= sqrt(n); i = i+2){\n while (n%i == 0){\n s.insert(i);\n n = n/i;\n }\n }\n if (n > 2)\n s.insert(n);\n}\nint findPrimitiveRoot(int n) {\n unordered_set<int> s;\n if (isPrimeNumber(n)==false)\n return -1;\n int ETF = n-1;\n GeneratePrimes(s, ETF);\n for (int r=2; r<=ETF; r++){\n bool flag = false;\n for (auto it = s.begin(); it != s.end(); it++){\n if (power(r, ETF/(*it), n) == 1){\n flag = true;\n break;\n }\n }\n if (flag == false)\n return r;\n }\n return -1;\n}\nint main() {\n int n= 13;\n cout<<\" Smallest primitive root of \"<<n<<\" is \"<<findPrimitiveRoot(n);\n return 0;\n}" }, { "code": null, "e": 3262, "s": 3227, "text": "Smallest primitive root of 13 is 2" } ]
Program to find Circumference of a Circle in C++
In this tutorial, we will be discussing a program to find circumference of a circle. For this we will be provided with the radius of the circle. Our task is to calculate and print the circumference of that circle. Live Demo #include<bits/stdc++.h> using namespace std; #define PI 3.1415 double circumference(double r){ double cir = 2*PI*r; return cir; } int main(){ double r = 5; cout << "Circumference : " << circumference(r); return 0; } Circumference : 31.415
[ { "code": null, "e": 1147, "s": 1062, "text": "In this tutorial, we will be discussing a program to find circumference of a circle." }, { "code": null, "e": 1276, "s": 1147, "text": "For this we will be provided with the radius of the circle. Our task is to calculate and print the circumference of that circle." }, { "code": null, "e": 1287, "s": 1276, "text": " Live Demo" }, { "code": null, "e": 1518, "s": 1287, "text": "#include<bits/stdc++.h>\nusing namespace std;\n#define PI 3.1415\ndouble circumference(double r){\n double cir = 2*PI*r;\n return cir;\n}\nint main(){\n double r = 5;\n cout << \"Circumference : \" << circumference(r);\n return 0;\n}" }, { "code": null, "e": 1541, "s": 1518, "text": "Circumference : 31.415" } ]
Java - isUpperCase() Method
This method determines whether the specified char value is uppercase. boolean isUpperCase(char ch) Here is the detail of parameters − ch − Primitive character type. ch − Primitive character type. This method returns true, if the passed character is really an uppercase. public class Test { public static void main(String args[]) { System.out.println(Character.isUpperCase('c')); System.out.println(Character.isUpperCase('C')); System.out.println(Character.isUpperCase('\n')); System.out.println(Character.isUpperCase('\t')); } } This will produce the following result − false true false false 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": 2447, "s": 2377, "text": "This method determines whether the specified char value is uppercase." }, { "code": null, "e": 2477, "s": 2447, "text": "boolean isUpperCase(char ch)\n" }, { "code": null, "e": 2512, "s": 2477, "text": "Here is the detail of parameters −" }, { "code": null, "e": 2543, "s": 2512, "text": "ch − Primitive character type." }, { "code": null, "e": 2574, "s": 2543, "text": "ch − Primitive character type." }, { "code": null, "e": 2648, "s": 2574, "text": "This method returns true, if the passed character is really an uppercase." }, { "code": null, "e": 2938, "s": 2648, "text": "public class Test {\n\n public static void main(String args[]) {\n System.out.println(Character.isUpperCase('c'));\n System.out.println(Character.isUpperCase('C'));\n System.out.println(Character.isUpperCase('\\n'));\n System.out.println(Character.isUpperCase('\\t'));\n }\n}" }, { "code": null, "e": 2979, "s": 2938, "text": "This will produce the following result −" }, { "code": null, "e": 3003, "s": 2979, "text": "false\ntrue\nfalse\nfalse\n" }, { "code": null, "e": 3036, "s": 3003, "text": "\n 16 Lectures \n 2 hours \n" }, { "code": null, "e": 3052, "s": 3036, "text": " Malhar Lathkar" }, { "code": null, "e": 3085, "s": 3052, "text": "\n 19 Lectures \n 5 hours \n" }, { "code": null, "e": 3101, "s": 3085, "text": " Malhar Lathkar" }, { "code": null, "e": 3136, "s": 3101, "text": "\n 25 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3150, "s": 3136, "text": " Anadi Sharma" }, { "code": null, "e": 3184, "s": 3150, "text": "\n 126 Lectures \n 7 hours \n" }, { "code": null, "e": 3198, "s": 3184, "text": " Tushar Kale" }, { "code": null, "e": 3235, "s": 3198, "text": "\n 119 Lectures \n 17.5 hours \n" }, { "code": null, "e": 3250, "s": 3235, "text": " Monica Mittal" }, { "code": null, "e": 3283, "s": 3250, "text": "\n 76 Lectures \n 7 hours \n" }, { "code": null, "e": 3302, "s": 3283, "text": " Arnab Chakraborty" }, { "code": null, "e": 3309, "s": 3302, "text": " Print" }, { "code": null, "e": 3320, "s": 3309, "text": " Add Notes" } ]
Kotlin For Loop
Often when you work with arrays, you need to loop through all of the elements. To loop through array elements, use the for loop together with the in operator: Output all elements in the cars array: val cars = arrayOf("Volvo", "BMW", "Ford", "Mazda") for (x in cars) { println(x) } You can loop through all kinds of arrays. In the example above, we used an array of strings. In the example below, we loop through an array of integers: val nums = arrayOf(1, 5, 10, 15, 20) for (x in nums) { println(x) } Unlike Java and other programming languages, there is no traditional for loop in Kotlin. In Kotlin, the for loop is used to loop through arrays, ranges, and other things that contains a countable number of values. You will learn more about ranges in the next chapter - which will create a range of values. 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": 80, "s": 0, "text": "Often when you work with arrays, you need to loop through all of the \nelements." }, { "code": null, "e": 161, "s": 80, "text": "To loop through array elements, use the for \nloop together with the in operator:" }, { "code": null, "e": 200, "s": 161, "text": "Output all elements in the cars array:" }, { "code": null, "e": 286, "s": 200, "text": "val cars = arrayOf(\"Volvo\", \"BMW\", \"Ford\", \"Mazda\")\nfor (x in cars) {\n println(x)\n}\n" }, { "code": null, "e": 380, "s": 286, "text": "You can loop through all kinds of arrays. In the example above, we used an array of strings. " }, { "code": null, "e": 440, "s": 380, "text": "In the example below, we loop through an array of integers:" }, { "code": null, "e": 510, "s": 440, "text": "val nums = arrayOf(1, 5, 10, 15, 20)\nfor (x in nums) {\n println(x)\n}" }, { "code": null, "e": 600, "s": 510, "text": "Unlike Java and other programming languages, there is no traditional for loop \nin Kotlin." }, { "code": null, "e": 727, "s": 600, "text": "In Kotlin, the for loop is used to loop through arrays, ranges, and other \nthings that contains a \ncountable number of values." }, { "code": null, "e": 820, "s": 727, "text": "You will learn more about ranges in the next chapter - which \nwill create a range of values." }, { "code": null, "e": 853, "s": 820, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 895, "s": 853, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 1002, "s": 895, "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": 1021, "s": 1002, "text": "help@w3schools.com" } ]
Instruction type ORA R in 8085 Microprocessor
In 8085 Instruction set, ORA is a mnemonic, which stands for “OR Accumulator” and “R” stands for any of the following registers, or memory location M pointed by HL pair. R = A, B, C, D, E, H, L, or M This instruction is used to OR contents of R with the Accumulator. The result of OR operation will be stored back in the Accumulator. As R can have any of the eight values, there are eight opcodes for this type of instruction. It occupies only 1-Byte in memory. Let us consider the instruction ORA E as an example instruction of this category. As it is a 1-Byte instruction so it will occupy a single Byte in the memory. Let us consider that the initial contents of Accumulator and E register are ABH and CDH. The result of execution of this instruction has been shown in the following tracing table. (E) (A) (F) The internal calculation has been done as shown below − (A) ABH ---> 1010 1011 (E) CDH ---> 1100 1101 --------- ORA E ---> 1110 1111 (EFH) The timing diagram against this instruction ORA E execution is as follows − Summary − So this instruction ORA E requires 1-Byte, 1-Machine Cycle (Opcode Fetch) and 4 T-States for execution as shown in the timing diagram.
[ { "code": null, "e": 1232, "s": 1062, "text": "In 8085 Instruction set, ORA is a mnemonic, which stands for “OR Accumulator” and “R” stands for any of the following registers, or memory location M pointed by HL pair." }, { "code": null, "e": 1263, "s": 1232, "text": "R = A, B, C, D, E, H, L, or M\n" }, { "code": null, "e": 1525, "s": 1263, "text": "This instruction is used to OR contents of R with the Accumulator. The result of OR operation will be stored back in the Accumulator. As R can have any of the eight values, there are eight opcodes for this type of instruction. It occupies only 1-Byte in memory." }, { "code": null, "e": 1864, "s": 1525, "text": "Let us consider the instruction ORA E as an example instruction of this category. As it is a 1-Byte instruction so it will occupy a single Byte in the memory. Let us consider that the initial contents of Accumulator and E register are ABH and CDH. The result of execution of this instruction has been shown in the following tracing table." }, { "code": null, "e": 1868, "s": 1864, "text": "(E)" }, { "code": null, "e": 1872, "s": 1868, "text": "(A)" }, { "code": null, "e": 1876, "s": 1872, "text": "(F)" }, { "code": null, "e": 1932, "s": 1876, "text": "The internal calculation has been done as shown below −" }, { "code": null, "e": 2036, "s": 1932, "text": "(A) ABH ---> 1010 1011\n(E) CDH ---> 1100 1101\n ---------\n ORA E ---> 1110 1111 (EFH)\n" }, { "code": null, "e": 2112, "s": 2036, "text": "The timing diagram against this instruction ORA E execution is as follows −" }, { "code": null, "e": 2257, "s": 2112, "text": "Summary − So this instruction ORA E requires 1-Byte, 1-Machine Cycle (Opcode Fetch) and 4 T-States for execution as shown in the timing diagram." } ]
Find the maximum length of the prefix | Set-2 - GeeksforGeeks
15 Jul, 2021 Given an array arr[] of N integers, the task is to find the maximum prefix length of the array such that removing exactly one element from the prefix will make the frequency of the remaining prefix elements the same. Examples: Input: arr[] = {1, 1, 1, 2, 2, 2} Output: 5 Explanation: The following prefixes satisfy the given conditions: The prefix over the range [0, 0]. Removing the only element in the prefix will become empty.The prefix over the range [0, 1]. Removing either of the element from the prefix, frequency of every element will becomes equal in the prefix.The prefix over the range [0, 2]. Removing any of the element from the prefix, frequency of every element will becomes equal in the prefix.The prefix over the range [0, 3]. Removing the element at index 3 from the prefix, frequency of every element will becomes equal in the prefix.The prefix over the range [0, 4]. Removing any element in the range [0, 2] from the prefix, frequency of every element will becomes equal in the prefix. The prefix over the range [0, 0]. Removing the only element in the prefix will become empty. The prefix over the range [0, 1]. Removing either of the element from the prefix, frequency of every element will becomes equal in the prefix. The prefix over the range [0, 2]. Removing any of the element from the prefix, frequency of every element will becomes equal in the prefix. The prefix over the range [0, 3]. Removing the element at index 3 from the prefix, frequency of every element will becomes equal in the prefix. The prefix over the range [0, 4]. Removing any element in the range [0, 2] from the prefix, frequency of every element will becomes equal in the prefix. Therefore, the maximum length of prefix satisfying the conditions is 5. Input: arr[] = {1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5} Output: 13 The Hashing and sorting-based approach has been discussed in Set 1 of this article. Approach: The idea is to use two Maps to keep track of the frequencies of elements and use the following four conditions to check for valid prefixes. Frequencies of all the elements of the prefix are equal to 1.All the elements in the prefix window are the same.There exist only two distinct frequencies of the elements in the prefix and the difference between them is equal to 1 and the count of the frequency with a larger value is 1.There exists a single element with frequency 1 and except that all elements have the same frequency. Frequencies of all the elements of the prefix are equal to 1. All the elements in the prefix window are the same. There exist only two distinct frequencies of the elements in the prefix and the difference between them is equal to 1 and the count of the frequency with a larger value is 1. There exists a single element with frequency 1 and except that all elements have the same frequency. Follow the steps below to solve the problem: Initialize two Maps say mp1 and mp2 to store the frequency of elements in the prefix and to store the frequency of the frequencies of the elements respectively. Also, Initialize a variable say ans as 0 to store the maximum length of the prefix. Traverse over the range [0, N-1] using the variable i and follow the below steps:If the count of arr[i] is not equal to 0, then decrement the count of that frequency from the map mp2 and if it becomes 0 then erase the value from map mp2.Increment the count of arr[i] in the map mp1 by 1 and then increment the count of the new frequency of arr[i] i.e mp1[arr[i]] in Map mp2 by 1.If the count of the current element is equal to its prefix length i.e (i+1) or every element occurred once in the prefix then update the value of ans to max(ans, i+1).Now, if the size of mp2 is equal to 2 then perform the following steps,Store the frequencies of the array element i.e key of the map mp2 in variables say freq1 and freq2 respectively.Store the counts of frequencies of freq1 and freq2 in variables say count1 and count2.Check if the difference between freq2 and freq1 is equal to 1 and the value of count2 is equal to 1 then update the ans to max(ans, i+1).Else, if the difference between freq1 and freq2 is equal to 1 and the value of count1 is equal to 1 then update the ans to max(ans, i+1).Else if freq2 and count2 are equal to 1 or freq1 and count1 are equal to 1 then update the ans to max(ans, i+1). If the count of arr[i] is not equal to 0, then decrement the count of that frequency from the map mp2 and if it becomes 0 then erase the value from map mp2. Increment the count of arr[i] in the map mp1 by 1 and then increment the count of the new frequency of arr[i] i.e mp1[arr[i]] in Map mp2 by 1. If the count of the current element is equal to its prefix length i.e (i+1) or every element occurred once in the prefix then update the value of ans to max(ans, i+1). Now, if the size of mp2 is equal to 2 then perform the following steps,Store the frequencies of the array element i.e key of the map mp2 in variables say freq1 and freq2 respectively.Store the counts of frequencies of freq1 and freq2 in variables say count1 and count2.Check if the difference between freq2 and freq1 is equal to 1 and the value of count2 is equal to 1 then update the ans to max(ans, i+1).Else, if the difference between freq1 and freq2 is equal to 1 and the value of count1 is equal to 1 then update the ans to max(ans, i+1).Else if freq2 and count2 are equal to 1 or freq1 and count1 are equal to 1 then update the ans to max(ans, i+1). Store the frequencies of the array element i.e key of the map mp2 in variables say freq1 and freq2 respectively. Store the counts of frequencies of freq1 and freq2 in variables say count1 and count2. Check if the difference between freq2 and freq1 is equal to 1 and the value of count2 is equal to 1 then update the ans to max(ans, i+1). Else, if the difference between freq1 and freq2 is equal to 1 and the value of count1 is equal to 1 then update the ans to max(ans, i+1). Else if freq2 and count2 are equal to 1 or freq1 and count1 are equal to 1 then update the ans to max(ans, i+1). Finally, after completing the above steps print the value of ans. Below is the implementation of the above approach: C++ Java Python3 Javascript // C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find the maximum// length of the required prefixint maxPrefixLen(int arr[], int N){ // Stores the frequency of // elements unordered_map<int, int> a, b; // Stores the maximum length // of the prefix satisfying // the conditions int ans = 1; // Traverse the array arr[] for (int i = 0; i < N; i++) { // Stores the count of // current element int curr = a[arr[i]]; // If curr is not // equal to 0 if (curr != 0) { // Decrement b[curr] // by 1 b[curr]--; // If b[curr] is 0 if (b[curr] == 0) { // Remove b[curr] // from the b b.erase(curr); } } // Update a[arr[i]]++; b[curr + 1]++; // If all elements in the // prefix are same or if // all elements have frequency // 1 if (a[arr[i]] == i + 1 or (b.find(1) != b.end() and b[1] == i + 1)) { // Update the value of ans ans = max(ans, i + 1); } // Else if the size of b // is 2 else if (b.size() == 2) { auto p = b.begin(); auto q = p; // Increment q by 1 q++; int freq1 = p->first; int freq2 = q->first; int count1 = p->second; int count2 = q->second; // If difference between // freq2 and freq1 is // equal to 1 and if // count2 is equal to 1 if (freq2 - freq1 == 1 and count2 == 1) { // Update the value // of ans ans = max(ans, i + 1); } // If difference between // freq1 and freq2 is // equal to 1 and if // count1 is equal to 1 else if (freq1 - freq2 == 1 and count1 == 1) { // Update the value // of ans ans = max(ans, i + 1); } // If freq2 and count2 is 1 // or freq1 and count1 is 1 if ((freq2 == 1 and count2 == 1) or (freq1 == 1 and count1 == 1)) { // Update the value of // ans ans = max(ans, i + 1); } } } // Return ans return ans;} // Driver Codeint main(){ int arr[] = { 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5 }; int N = sizeof(arr) / sizeof(arr[0]); cout << maxPrefixLen(arr, N);} // Java program for the above approachimport java.util.HashMap;class GFG { // Function to find the maximum // length of the required prefix public static int maxPrefixLen(int arr[], int N) { // Stores the frequency of // elements HashMap<Integer, Integer> a = new HashMap<Integer, Integer>(); HashMap<Integer, Integer> b = new HashMap<Integer, Integer>(); // Stores the maximum length // of the prefix satisfying // the conditions int ans = 1; // Traverse the array arr[] for (int i = 0; i < N; i++) { // Stores the count of // current element int curr = !a.containsKey(arr[i]) ? 0 : a.get(arr[i]); // If curr is not // equal to 0 if (curr != 0) { // Decrement b[curr] // by 1 b.put(curr, b.get(curr) - 1); // If b[curr] is 0 if (b.get(curr) == 0) { // Remove b[curr] // from the b b.remove(curr); } } // Update if (a.containsKey(arr[i])) { a.put(arr[i], a.get(arr[i]) + 1); } else { a.put(arr[i], 1); } if (b.containsKey(curr + 1)) { b.put(curr + 1, b.get(curr + 1) + 1); } else { b.put(curr + 1, 1); } // If all elements in the // prefix are same or if // all elements have frequency // 1 if (a.get(arr[i]) == i + 1 || (b.containsKey(1) && b.get(1) == i + 1)) { // Update the value of ans ans = Math.max(ans, i + 1); } else if (b.size() == 2) { int p = b.keySet().toArray()[0].hashCode(); int q = b.keySet().toArray()[1].hashCode(); // Increment q by 1 int freq1 = p; int freq2 = q; int count1 = b.get(p); int count2 = b.get(q); // If difference between // freq2 and freq1 is // equal to 1 and if // count2 is equal to 1 if ((freq2 - freq1) == 1 && count2 == 1) { // Update the value // of ans ans = Math.max(ans, i + 1); } // If difference between // freq1 and freq2 is // equal to 1 and if // count1 is equal to 1 else if (freq1 - freq2 == 1 && count1 == 1) { // Update the value // of ans ans = Math.max(ans, i + 1); } // If freq2 and count2 is 1 // or freq1 and count1 is 1 if ((freq2 == 1 && count2 == 1) || (freq1 == 1 && count1 == 1)) { // Update the value of // ans ans = Math.max(ans, i + 1); } } } // Return ans return ans; } // Driver Code public static void main(String args[]) { int arr[] = { 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5 }; int N = arr.length; System.out.println(maxPrefixLen(arr, N)); }} // This code is contributed by gfgking. # Python3 program for the above approach # Function to find the maximum# length of the required prefixdef maxPrefixLen(arr, N): # Stores the frequency of # elements a, b = {}, {} # Stores the maximum length # of the prefix satisfying # the conditions ans = 1 # Traverse the array arr[] for i in range(N): # Stores the count of # current element curr = 0 if (arr[i] not in a) else a[arr[i]] # If curr is not # equal to 0 if (curr != 0): # Decrement b[curr] # by 1 b[curr] -= 1 # If b[curr] is 0 if (b[curr] == 0): # Remove b[curr] # from the b del b[curr] # Update a[arr[i]] = a.get(arr[i], 0) + 1 b[curr + 1] = b.get(curr + 1, 0) + 1 # If all elements in the # prefix are same or if # all elements have frequency # 1 if (a[arr[i]] == i + 1 or (1 in b) and b[1] == i + 1): # Update the value of ans ans = max(ans, i + 1) # Else if the size of b # is 2 elif (len(b) == 2): p = list(b.keys())[0] q = list(b.keys())[1] freq1 = p freq2 = q count1 = b[p] count2 = b[q] # If difference between # freq2 and freq1 is # equal to 1 and if # count2 is equal to 1 if (freq2 - freq1 == 1 and count2 == 1): # Update the value # of ans ans = max(ans, i + 1) # If difference between # freq1 and freq2 is # equal to 1 and if # count1 is equal to 1 elif (freq1 - freq2 == 1 and count1 == 1): # Update the value # of ans ans = max(ans, i + 1) # If freq2 and count2 is 1 # or freq1 and count1 is 1 if ((freq2 == 1 and count2 == 1) or (freq1 == 1 and count1 == 1)): # Update the value of # ans ans = max(ans, i + 1) # Return ans return ans # Driver Codeif __name__ == '__main__': arr = [ 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5 ] N = len(arr) print(maxPrefixLen(arr, N)) # This code is contributed by mohit kumar 29 <script>// Javascript program for the above approach // Function to find the maximum// length of the required prefixfunction maxPrefixLen(arr, N) { // Stores the frequency of // elements let a = new Map(); let b = new Map(); // Stores the maximum length // of the prefix satisfying // the conditions let ans = 1 // Traverse the array arr[] for (let i = 0; i < N; i++) { // Stores the count of // current element let curr = !(a.has(arr[i])) ? 0 : a.get(arr[i]) // If curr is not // equal to 0 if (curr != 0) { // Decrement b[curr] // by 1 b.set(curr, b.get(curr) - 1) // If b[curr] is 0 if (b.get(curr) == 0) { // Remove b[curr] // from the b b.delete(curr) } } // Update if (a.has(arr[i])) { a.set(arr[i], a.get(arr[i]) + 1) } else { a.set(arr[i], 1) } if (b.has(curr + 1)) { b.set(curr + 1, b.get(curr + 1) + 1) } else { b.set(curr + 1, 1) } // If all elements in the // prefix are same or if // all elements have frequency // 1 if (a.get(arr[i]) == i + 1 || (b.has(1)) && b.get(1) == i + 1) { // Update the value of ans ans = Math.max(ans, i + 1) // Else if the size of b // is 2 } else if (b.size == 2) { let p = [...b.keys()][0] let q = [...b.keys()][1] let freq1 = p let freq2 = q let count1 = b.get(p) let count2 = b.get(q) // If difference between // freq2 and freq1 is // equal to 1 and if // count2 is equal to 1 if (freq2 - freq1 == 1 && count2 == 1) { // Update the value // of ans ans = Math.max(ans, i + 1) } // If difference between // freq1 and freq2 is // equal to 1 and if // count1 is equal to 1 else if (freq1 - freq2 == 1 && count1 == 1) { // Update the value // of ans ans = Math.max(ans, i + 1) } // If freq2 and count2 is 1 // or freq1 and count1 is 1 if ((freq2 == 1 && count2 == 1) || (freq1 == 1 && count1 == 1)) { // Update the value of // ans ans = Math.max(ans, i + 1) } } } // Return ans return ans } // Driver Code let arr = [1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5]N = arr.length document.write(maxPrefixLen(arr, N)) // This code is contributed by gfgking</script> 13 Time Complexity: O(N)Auxiliary Space: O(N) mohit kumar 29 gfgking cpp-map frequency-counting prefix Arrays Arrays Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Window Sliding Technique Building Heap from Array Trapping Rain Water Program to find sum of elements in a given array Reversal algorithm for array rotation Move all negative numbers to beginning and positive to end with constant extra space Find duplicates in O(n) time and O(1) extra space | Set 1 Count pairs with given sum Next Greater Element Remove duplicates from sorted array
[ { "code": null, "e": 24796, "s": 24768, "text": "\n15 Jul, 2021" }, { "code": null, "e": 25013, "s": 24796, "text": "Given an array arr[] of N integers, the task is to find the maximum prefix length of the array such that removing exactly one element from the prefix will make the frequency of the remaining prefix elements the same." }, { "code": null, "e": 25025, "s": 25013, "text": "Examples: " }, { "code": null, "e": 25137, "s": 25025, "text": "Input: arr[] = {1, 1, 1, 2, 2, 2} Output: 5 Explanation: The following prefixes satisfy the given conditions:" }, { "code": null, "e": 25806, "s": 25137, "text": "The prefix over the range [0, 0]. Removing the only element in the prefix will become empty.The prefix over the range [0, 1]. Removing either of the element from the prefix, frequency of every element will becomes equal in the prefix.The prefix over the range [0, 2]. Removing any of the element from the prefix, frequency of every element will becomes equal in the prefix.The prefix over the range [0, 3]. Removing the element at index 3 from the prefix, frequency of every element will becomes equal in the prefix.The prefix over the range [0, 4]. Removing any element in the range [0, 2] from the prefix, frequency of every element will becomes equal in the prefix." }, { "code": null, "e": 25899, "s": 25806, "text": "The prefix over the range [0, 0]. Removing the only element in the prefix will become empty." }, { "code": null, "e": 26042, "s": 25899, "text": "The prefix over the range [0, 1]. Removing either of the element from the prefix, frequency of every element will becomes equal in the prefix." }, { "code": null, "e": 26182, "s": 26042, "text": "The prefix over the range [0, 2]. Removing any of the element from the prefix, frequency of every element will becomes equal in the prefix." }, { "code": null, "e": 26326, "s": 26182, "text": "The prefix over the range [0, 3]. Removing the element at index 3 from the prefix, frequency of every element will becomes equal in the prefix." }, { "code": null, "e": 26479, "s": 26326, "text": "The prefix over the range [0, 4]. Removing any element in the range [0, 2] from the prefix, frequency of every element will becomes equal in the prefix." }, { "code": null, "e": 26551, "s": 26479, "text": "Therefore, the maximum length of prefix satisfying the conditions is 5." }, { "code": null, "e": 26619, "s": 26551, "text": "Input: arr[] = {1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5} Output: 13 " }, { "code": null, "e": 26703, "s": 26619, "text": "The Hashing and sorting-based approach has been discussed in Set 1 of this article." }, { "code": null, "e": 26853, "s": 26703, "text": "Approach: The idea is to use two Maps to keep track of the frequencies of elements and use the following four conditions to check for valid prefixes." }, { "code": null, "e": 27240, "s": 26853, "text": "Frequencies of all the elements of the prefix are equal to 1.All the elements in the prefix window are the same.There exist only two distinct frequencies of the elements in the prefix and the difference between them is equal to 1 and the count of the frequency with a larger value is 1.There exists a single element with frequency 1 and except that all elements have the same frequency." }, { "code": null, "e": 27302, "s": 27240, "text": "Frequencies of all the elements of the prefix are equal to 1." }, { "code": null, "e": 27354, "s": 27302, "text": "All the elements in the prefix window are the same." }, { "code": null, "e": 27529, "s": 27354, "text": "There exist only two distinct frequencies of the elements in the prefix and the difference between them is equal to 1 and the count of the frequency with a larger value is 1." }, { "code": null, "e": 27630, "s": 27529, "text": "There exists a single element with frequency 1 and except that all elements have the same frequency." }, { "code": null, "e": 27675, "s": 27630, "text": "Follow the steps below to solve the problem:" }, { "code": null, "e": 27836, "s": 27675, "text": "Initialize two Maps say mp1 and mp2 to store the frequency of elements in the prefix and to store the frequency of the frequencies of the elements respectively." }, { "code": null, "e": 27920, "s": 27836, "text": "Also, Initialize a variable say ans as 0 to store the maximum length of the prefix." }, { "code": null, "e": 29122, "s": 27920, "text": "Traverse over the range [0, N-1] using the variable i and follow the below steps:If the count of arr[i] is not equal to 0, then decrement the count of that frequency from the map mp2 and if it becomes 0 then erase the value from map mp2.Increment the count of arr[i] in the map mp1 by 1 and then increment the count of the new frequency of arr[i] i.e mp1[arr[i]] in Map mp2 by 1.If the count of the current element is equal to its prefix length i.e (i+1) or every element occurred once in the prefix then update the value of ans to max(ans, i+1).Now, if the size of mp2 is equal to 2 then perform the following steps,Store the frequencies of the array element i.e key of the map mp2 in variables say freq1 and freq2 respectively.Store the counts of frequencies of freq1 and freq2 in variables say count1 and count2.Check if the difference between freq2 and freq1 is equal to 1 and the value of count2 is equal to 1 then update the ans to max(ans, i+1).Else, if the difference between freq1 and freq2 is equal to 1 and the value of count1 is equal to 1 then update the ans to max(ans, i+1).Else if freq2 and count2 are equal to 1 or freq1 and count1 are equal to 1 then update the ans to max(ans, i+1)." }, { "code": null, "e": 29279, "s": 29122, "text": "If the count of arr[i] is not equal to 0, then decrement the count of that frequency from the map mp2 and if it becomes 0 then erase the value from map mp2." }, { "code": null, "e": 29422, "s": 29279, "text": "Increment the count of arr[i] in the map mp1 by 1 and then increment the count of the new frequency of arr[i] i.e mp1[arr[i]] in Map mp2 by 1." }, { "code": null, "e": 29590, "s": 29422, "text": "If the count of the current element is equal to its prefix length i.e (i+1) or every element occurred once in the prefix then update the value of ans to max(ans, i+1)." }, { "code": null, "e": 30246, "s": 29590, "text": "Now, if the size of mp2 is equal to 2 then perform the following steps,Store the frequencies of the array element i.e key of the map mp2 in variables say freq1 and freq2 respectively.Store the counts of frequencies of freq1 and freq2 in variables say count1 and count2.Check if the difference between freq2 and freq1 is equal to 1 and the value of count2 is equal to 1 then update the ans to max(ans, i+1).Else, if the difference between freq1 and freq2 is equal to 1 and the value of count1 is equal to 1 then update the ans to max(ans, i+1).Else if freq2 and count2 are equal to 1 or freq1 and count1 are equal to 1 then update the ans to max(ans, i+1)." }, { "code": null, "e": 30359, "s": 30246, "text": "Store the frequencies of the array element i.e key of the map mp2 in variables say freq1 and freq2 respectively." }, { "code": null, "e": 30446, "s": 30359, "text": "Store the counts of frequencies of freq1 and freq2 in variables say count1 and count2." }, { "code": null, "e": 30584, "s": 30446, "text": "Check if the difference between freq2 and freq1 is equal to 1 and the value of count2 is equal to 1 then update the ans to max(ans, i+1)." }, { "code": null, "e": 30722, "s": 30584, "text": "Else, if the difference between freq1 and freq2 is equal to 1 and the value of count1 is equal to 1 then update the ans to max(ans, i+1)." }, { "code": null, "e": 30835, "s": 30722, "text": "Else if freq2 and count2 are equal to 1 or freq1 and count1 are equal to 1 then update the ans to max(ans, i+1)." }, { "code": null, "e": 30901, "s": 30835, "text": "Finally, after completing the above steps print the value of ans." }, { "code": null, "e": 30952, "s": 30901, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 30956, "s": 30952, "text": "C++" }, { "code": null, "e": 30961, "s": 30956, "text": "Java" }, { "code": null, "e": 30969, "s": 30961, "text": "Python3" }, { "code": null, "e": 30980, "s": 30969, "text": "Javascript" }, { "code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find the maximum// length of the required prefixint maxPrefixLen(int arr[], int N){ // Stores the frequency of // elements unordered_map<int, int> a, b; // Stores the maximum length // of the prefix satisfying // the conditions int ans = 1; // Traverse the array arr[] for (int i = 0; i < N; i++) { // Stores the count of // current element int curr = a[arr[i]]; // If curr is not // equal to 0 if (curr != 0) { // Decrement b[curr] // by 1 b[curr]--; // If b[curr] is 0 if (b[curr] == 0) { // Remove b[curr] // from the b b.erase(curr); } } // Update a[arr[i]]++; b[curr + 1]++; // If all elements in the // prefix are same or if // all elements have frequency // 1 if (a[arr[i]] == i + 1 or (b.find(1) != b.end() and b[1] == i + 1)) { // Update the value of ans ans = max(ans, i + 1); } // Else if the size of b // is 2 else if (b.size() == 2) { auto p = b.begin(); auto q = p; // Increment q by 1 q++; int freq1 = p->first; int freq2 = q->first; int count1 = p->second; int count2 = q->second; // If difference between // freq2 and freq1 is // equal to 1 and if // count2 is equal to 1 if (freq2 - freq1 == 1 and count2 == 1) { // Update the value // of ans ans = max(ans, i + 1); } // If difference between // freq1 and freq2 is // equal to 1 and if // count1 is equal to 1 else if (freq1 - freq2 == 1 and count1 == 1) { // Update the value // of ans ans = max(ans, i + 1); } // If freq2 and count2 is 1 // or freq1 and count1 is 1 if ((freq2 == 1 and count2 == 1) or (freq1 == 1 and count1 == 1)) { // Update the value of // ans ans = max(ans, i + 1); } } } // Return ans return ans;} // Driver Codeint main(){ int arr[] = { 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5 }; int N = sizeof(arr) / sizeof(arr[0]); cout << maxPrefixLen(arr, N);}", "e": 33579, "s": 30980, "text": null }, { "code": "// Java program for the above approachimport java.util.HashMap;class GFG { // Function to find the maximum // length of the required prefix public static int maxPrefixLen(int arr[], int N) { // Stores the frequency of // elements HashMap<Integer, Integer> a = new HashMap<Integer, Integer>(); HashMap<Integer, Integer> b = new HashMap<Integer, Integer>(); // Stores the maximum length // of the prefix satisfying // the conditions int ans = 1; // Traverse the array arr[] for (int i = 0; i < N; i++) { // Stores the count of // current element int curr = !a.containsKey(arr[i]) ? 0 : a.get(arr[i]); // If curr is not // equal to 0 if (curr != 0) { // Decrement b[curr] // by 1 b.put(curr, b.get(curr) - 1); // If b[curr] is 0 if (b.get(curr) == 0) { // Remove b[curr] // from the b b.remove(curr); } } // Update if (a.containsKey(arr[i])) { a.put(arr[i], a.get(arr[i]) + 1); } else { a.put(arr[i], 1); } if (b.containsKey(curr + 1)) { b.put(curr + 1, b.get(curr + 1) + 1); } else { b.put(curr + 1, 1); } // If all elements in the // prefix are same or if // all elements have frequency // 1 if (a.get(arr[i]) == i + 1 || (b.containsKey(1) && b.get(1) == i + 1)) { // Update the value of ans ans = Math.max(ans, i + 1); } else if (b.size() == 2) { int p = b.keySet().toArray()[0].hashCode(); int q = b.keySet().toArray()[1].hashCode(); // Increment q by 1 int freq1 = p; int freq2 = q; int count1 = b.get(p); int count2 = b.get(q); // If difference between // freq2 and freq1 is // equal to 1 and if // count2 is equal to 1 if ((freq2 - freq1) == 1 && count2 == 1) { // Update the value // of ans ans = Math.max(ans, i + 1); } // If difference between // freq1 and freq2 is // equal to 1 and if // count1 is equal to 1 else if (freq1 - freq2 == 1 && count1 == 1) { // Update the value // of ans ans = Math.max(ans, i + 1); } // If freq2 and count2 is 1 // or freq1 and count1 is 1 if ((freq2 == 1 && count2 == 1) || (freq1 == 1 && count1 == 1)) { // Update the value of // ans ans = Math.max(ans, i + 1); } } } // Return ans return ans; } // Driver Code public static void main(String args[]) { int arr[] = { 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5 }; int N = arr.length; System.out.println(maxPrefixLen(arr, N)); }} // This code is contributed by gfgking.", "e": 37154, "s": 33579, "text": null }, { "code": "# Python3 program for the above approach # Function to find the maximum# length of the required prefixdef maxPrefixLen(arr, N): # Stores the frequency of # elements a, b = {}, {} # Stores the maximum length # of the prefix satisfying # the conditions ans = 1 # Traverse the array arr[] for i in range(N): # Stores the count of # current element curr = 0 if (arr[i] not in a) else a[arr[i]] # If curr is not # equal to 0 if (curr != 0): # Decrement b[curr] # by 1 b[curr] -= 1 # If b[curr] is 0 if (b[curr] == 0): # Remove b[curr] # from the b del b[curr] # Update a[arr[i]] = a.get(arr[i], 0) + 1 b[curr + 1] = b.get(curr + 1, 0) + 1 # If all elements in the # prefix are same or if # all elements have frequency # 1 if (a[arr[i]] == i + 1 or (1 in b) and b[1] == i + 1): # Update the value of ans ans = max(ans, i + 1) # Else if the size of b # is 2 elif (len(b) == 2): p = list(b.keys())[0] q = list(b.keys())[1] freq1 = p freq2 = q count1 = b[p] count2 = b[q] # If difference between # freq2 and freq1 is # equal to 1 and if # count2 is equal to 1 if (freq2 - freq1 == 1 and count2 == 1): # Update the value # of ans ans = max(ans, i + 1) # If difference between # freq1 and freq2 is # equal to 1 and if # count1 is equal to 1 elif (freq1 - freq2 == 1 and count1 == 1): # Update the value # of ans ans = max(ans, i + 1) # If freq2 and count2 is 1 # or freq1 and count1 is 1 if ((freq2 == 1 and count2 == 1) or (freq1 == 1 and count1 == 1)): # Update the value of # ans ans = max(ans, i + 1) # Return ans return ans # Driver Codeif __name__ == '__main__': arr = [ 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5 ] N = len(arr) print(maxPrefixLen(arr, N)) # This code is contributed by mohit kumar 29", "e": 39680, "s": 37154, "text": null }, { "code": "<script>// Javascript program for the above approach // Function to find the maximum// length of the required prefixfunction maxPrefixLen(arr, N) { // Stores the frequency of // elements let a = new Map(); let b = new Map(); // Stores the maximum length // of the prefix satisfying // the conditions let ans = 1 // Traverse the array arr[] for (let i = 0; i < N; i++) { // Stores the count of // current element let curr = !(a.has(arr[i])) ? 0 : a.get(arr[i]) // If curr is not // equal to 0 if (curr != 0) { // Decrement b[curr] // by 1 b.set(curr, b.get(curr) - 1) // If b[curr] is 0 if (b.get(curr) == 0) { // Remove b[curr] // from the b b.delete(curr) } } // Update if (a.has(arr[i])) { a.set(arr[i], a.get(arr[i]) + 1) } else { a.set(arr[i], 1) } if (b.has(curr + 1)) { b.set(curr + 1, b.get(curr + 1) + 1) } else { b.set(curr + 1, 1) } // If all elements in the // prefix are same or if // all elements have frequency // 1 if (a.get(arr[i]) == i + 1 || (b.has(1)) && b.get(1) == i + 1) { // Update the value of ans ans = Math.max(ans, i + 1) // Else if the size of b // is 2 } else if (b.size == 2) { let p = [...b.keys()][0] let q = [...b.keys()][1] let freq1 = p let freq2 = q let count1 = b.get(p) let count2 = b.get(q) // If difference between // freq2 and freq1 is // equal to 1 and if // count2 is equal to 1 if (freq2 - freq1 == 1 && count2 == 1) { // Update the value // of ans ans = Math.max(ans, i + 1) } // If difference between // freq1 and freq2 is // equal to 1 and if // count1 is equal to 1 else if (freq1 - freq2 == 1 && count1 == 1) { // Update the value // of ans ans = Math.max(ans, i + 1) } // If freq2 and count2 is 1 // or freq1 and count1 is 1 if ((freq2 == 1 && count2 == 1) || (freq1 == 1 && count1 == 1)) { // Update the value of // ans ans = Math.max(ans, i + 1) } } } // Return ans return ans } // Driver Code let arr = [1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5]N = arr.length document.write(maxPrefixLen(arr, N)) // This code is contributed by gfgking</script>", "e": 42494, "s": 39680, "text": null }, { "code": null, "e": 42497, "s": 42494, "text": "13" }, { "code": null, "e": 42542, "s": 42499, "text": "Time Complexity: O(N)Auxiliary Space: O(N)" }, { "code": null, "e": 42559, "s": 42544, "text": "mohit kumar 29" }, { "code": null, "e": 42567, "s": 42559, "text": "gfgking" }, { "code": null, "e": 42575, "s": 42567, "text": "cpp-map" }, { "code": null, "e": 42594, "s": 42575, "text": "frequency-counting" }, { "code": null, "e": 42601, "s": 42594, "text": "prefix" }, { "code": null, "e": 42608, "s": 42601, "text": "Arrays" }, { "code": null, "e": 42615, "s": 42608, "text": "Arrays" }, { "code": null, "e": 42713, "s": 42615, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 42738, "s": 42713, "text": "Window Sliding Technique" }, { "code": null, "e": 42763, "s": 42738, "text": "Building Heap from Array" }, { "code": null, "e": 42783, "s": 42763, "text": "Trapping Rain Water" }, { "code": null, "e": 42832, "s": 42783, "text": "Program to find sum of elements in a given array" }, { "code": null, "e": 42870, "s": 42832, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 42955, "s": 42870, "text": "Move all negative numbers to beginning and positive to end with constant extra space" }, { "code": null, "e": 43013, "s": 42955, "text": "Find duplicates in O(n) time and O(1) extra space | Set 1" }, { "code": null, "e": 43040, "s": 43013, "text": "Count pairs with given sum" }, { "code": null, "e": 43061, "s": 43040, "text": "Next Greater Element" } ]
How to Compress files with ZIPFILE module in Python.
You want to create a compress files in python. ZIP files can hold the compressed contents of many other files. Compressing a file reduces its size on disk, which is useful when transferring it over the internet or between the systems using Control-m AFT or Connect direct or even scp. Python programs creates ZIP files using functions in the zipfile module. 1. We will be using zipfile and io packages. Install them with pip if any of the packages are missing on your system. If you are unsure, use pip freeze command to validate the packages. 2. We will write a function to write sample data to a file. The function write_data_to_files below takes data as input and creates a file in the current directory name. # Function : write_data_to_files def write_data_to_files(inp_data, file_name): """ function : create a csv file with the data passed to this code args : inp_data : data to be written to the target file file_name : target file name to store the data return : none assumption : File to be created and this code are in same directory. """ print(f" *** Writing the data to - {file_name}") throwaway_storage = io.StringIO(inp_data) with open(file_name, 'w') as f: for line in throwaway_storage: f.write(line) 3. We will now write a function file_compress to zip the files created in above step. This function accepts list of files, go through them and compress it to a zip file. Detailed explanation of each step is provided in comments. To create your own compressed ZIP files, you must open the ZipFile object in write mode by passing 'w' as the second argument. When you pass a path to the write() method of a ZipFile object, Python will compress the file at that path and add it into the ZIP file. The first argument for write() method is a string of the filename to add. The second argument is the compression type parameter - which tells the computer what algorithm it should use to compress the files. # Function : file_compress def file_compress(inp_file_names, out_zip_file): """ function : file_compress args : inp_file_names : list of filenames to be zipped out_zip_file : output zip file return : none assumption : Input file paths and this code is in same directory. """ # Select the compression mode ZIP_DEFLATED for compression # or zipfile.ZIP_STORED to just store the file compression = zipfile.ZIP_DEFLATED print(f" *** Input File name passed for zipping - {inp_file_names}") # create the zip file first parameter path/name, second mode print(f' *** out_zip_file is - {out_zip_file}') zf = zipfile.ZipFile(out_zip_file, mode="w") try: for file_to_write in inp_file_names: # Add file to the zip file # first parameter file to zip, second filename in zip print(f' *** Processing file {file_to_write}') zf.write(file_to_write, file_to_write, compress_type=compression) except FileNotFoundError as e: print(f' *** Exception occurred during zip process - {e}') finally: # Don't forget to close the file! zf.close() 4. We will call the functions to create two csv files and then zip them. We will use tennis players data who won more than 1 grandslam titles to one file - temporary_file1_for_zip.csv and tennis players who won less than or equal to 1 grandslam in another file temporary_file1_for_zip.csv. We will then zip both these files to temporary.zip file. import zipfile import io import pandas as pd file_name1 = "temporary_file1_for_zip.csv" file_name2 = "temporary_file2_for_zip.csv" file_name_list = [file_name1, file_name2] zip_file_name = "temporary.zip" # data for file 1 file_data_1 = """ player,titles Federer,20 Nadal,20 Djokovic,17 Murray,3 """ # data for file 2 file_data_2 = """ player,titles Theim,1 Zverev,0 Medvedev,0 Rublev,0 """ # write the file_data to file_name write_data_to_files(file_data_1, file_name1) write_data_to_files(file_data_2, file_name2) # zip the file_name to zip_file_name file_compress(file_name_list, zip_file_name) 5.Putting everything together discussed in above steps. # Define the data # let us create a zip file with a single file import zipfile import io import pandas as pd # Function : write_data_to_files def write_data_to_files(inp_data, file_name): """ function : create a csv file with the data passed to this code args : inp_data : data to be written to the target file file_name : target file name to store the data return : none assumption : File to be created and this code are in same directory. """ print(f" *** Writing the data to - {file_name}") throwaway_storage = io.StringIO(inp_data) with open(file_name, 'w') as f: for line in throwaway_storage: f.write(line) # Function : file_compress def file_compress(inp_file_names, out_zip_file): """ function : file_compress args : inp_file_names : list of filenames to be zipped out_zip_file : output zip file return : none assumption : Input file paths and this code is in same directory. """ # Select the compression mode ZIP_DEFLATED for compression # or zipfile.ZIP_STORED to just store the file compression = zipfile.ZIP_DEFLATED print(f" *** Input File name passed for zipping - {inp_file_names}") # create the zip file first parameter path/name, second mode print(f' *** out_zip_file is - {out_zip_file}') zf = zipfile.ZipFile(out_zip_file, mode="w") try: for file_to_write in inp_file_names: # Add file to the zip file # first parameter file to zip, second filename in zip print(f' *** Processing file {file_to_write}') zf.write(file_to_write, file_to_write, compress_type=compression) except FileNotFoundError as e: print(f' *** Exception occurred during zip process - {e}') finally: # Don't forget to close the file! zf.close() # __main__ program if __name__ == '__main__': # Define your file name and data file_name1 = "temporary_file1_for_zip.csv" file_name2 = "temporary_file2_for_zip.csv" file_name_list = [file_name1, file_name2] zip_file_name = "temporary.zip" file_data_1 = """ player,titles Federer,20 Nadal,20 Djokovic,17 Murray,3 """ file_data_2 = """ player,titles Theim,1 Zverev,0 Medvedev,0 Rublev,0 """ # write the file_data to file_name write_data_to_files(file_data_1, file_name1) write_data_to_files(file_data_2, file_name2) # zip the file_name to zip_file_name file_compress(file_name_list, zip_file_name) *** Writing the data to - temporary_file1_for_zip.csv *** Writing the data to - temporary_file2_for_zip.csv *** Input File name passed for zipping - ['temporary_file1_for_zip.csv', 'temporary_file2_for_zip.csv'] *** out_zip_file is - temporary.zip *** Processing file temporary_file1_for_zip.csv *** Processing file temporary_file2_for_zip.csv When the above code is executed, the output is temporary_file1_for_zip.csv created in current directory. temporary_file1_for_zip.csv created in current directory. temporary_file2_for_zip.csv created in current directory. temporary_file2_for_zip.csv created in current directory. temporary.zip file is created in current directory. temporary.zip file is created in current directory.
[ { "code": null, "e": 1109, "s": 1062, "text": "You want to create a compress files in python." }, { "code": null, "e": 1347, "s": 1109, "text": "ZIP files can hold the compressed contents of many other files. Compressing a file reduces its size on disk, which is useful when transferring it over the internet or between the systems using Control-m AFT or Connect direct or even scp." }, { "code": null, "e": 1420, "s": 1347, "text": "Python programs creates ZIP files using functions in the zipfile module." }, { "code": null, "e": 1606, "s": 1420, "text": "1. We will be using zipfile and io packages. Install them with pip if any of the packages are missing on your system. If you are unsure, use pip freeze command to validate the packages." }, { "code": null, "e": 1775, "s": 1606, "text": "2. We will write a function to write sample data to a file. The function write_data_to_files below takes data as input and creates a file in the current directory name." }, { "code": null, "e": 2279, "s": 1775, "text": "# Function : write_data_to_files\ndef write_data_to_files(inp_data, file_name):\n\"\"\"\nfunction : create a csv file with the data passed to this code\nargs : inp_data : data to be written to the target file\nfile_name : target file name to store the data\nreturn : none\nassumption : File to be created and this code are in same directory.\n\"\"\"\nprint(f\" *** Writing the data to - {file_name}\")\nthrowaway_storage = io.StringIO(inp_data)\nwith open(file_name, 'w') as f:\nfor line in throwaway_storage:\nf.write(line)" }, { "code": null, "e": 2508, "s": 2279, "text": "3. We will now write a function file_compress to zip the files created in above step. This function accepts list of files, go through them and compress it to a zip file. Detailed explanation of each step is provided in comments." }, { "code": null, "e": 2635, "s": 2508, "text": "To create your own compressed ZIP files, you must open the ZipFile object in write mode by passing 'w' as the second argument." }, { "code": null, "e": 2772, "s": 2635, "text": "When you pass a path to the write() method of a ZipFile object, Python will compress the file at that path and add it into the ZIP file." }, { "code": null, "e": 2846, "s": 2772, "text": "The first argument for write() method is a string of the filename to add." }, { "code": null, "e": 2979, "s": 2846, "text": "The second argument is the compression type parameter - which tells the computer what algorithm it should use to compress the files." }, { "code": null, "e": 4001, "s": 2979, "text": "# Function : file_compress\ndef file_compress(inp_file_names, out_zip_file):\n\"\"\"\nfunction : file_compress\nargs : inp_file_names : list of filenames to be zipped\nout_zip_file : output zip file\nreturn : none\nassumption : Input file paths and this code is in same directory.\n\"\"\"\n# Select the compression mode ZIP_DEFLATED for compression\n# or zipfile.ZIP_STORED to just store the file\ncompression = zipfile.ZIP_DEFLATED\nprint(f\" *** Input File name passed for zipping - {inp_file_names}\")\n\n# create the zip file first parameter path/name, second mode\nprint(f' *** out_zip_file is - {out_zip_file}')\nzf = zipfile.ZipFile(out_zip_file, mode=\"w\")\n\ntry:\nfor file_to_write in inp_file_names:\n# Add file to the zip file\n# first parameter file to zip, second filename in zip\nprint(f' *** Processing file {file_to_write}')\nzf.write(file_to_write, file_to_write, compress_type=compression)\n\nexcept FileNotFoundError as e:\nprint(f' *** Exception occurred during zip process - {e}')\nfinally:\n# Don't forget to close the file!\nzf.close()" }, { "code": null, "e": 4348, "s": 4001, "text": "4. We will call the functions to create two csv files and then zip them. We will use tennis players data who won more than 1 grandslam titles to one file - temporary_file1_for_zip.csv and tennis players who won less than or equal to 1 grandslam in another file temporary_file1_for_zip.csv. We will then zip both these files to temporary.zip file." }, { "code": null, "e": 4952, "s": 4348, "text": "import zipfile\nimport io\nimport pandas as pd\n\nfile_name1 = \"temporary_file1_for_zip.csv\"\nfile_name2 = \"temporary_file2_for_zip.csv\"\nfile_name_list = [file_name1, file_name2]\nzip_file_name = \"temporary.zip\"\n\n# data for file 1\nfile_data_1 = \"\"\"\nplayer,titles\nFederer,20\nNadal,20\nDjokovic,17\nMurray,3\n\"\"\"\n\n# data for file 2\n\nfile_data_2 = \"\"\"\nplayer,titles\nTheim,1\nZverev,0\nMedvedev,0\nRublev,0\n\"\"\"\n\n# write the file_data to file_name\nwrite_data_to_files(file_data_1, file_name1)\nwrite_data_to_files(file_data_2, file_name2)\n\n# zip the file_name to zip_file_name\nfile_compress(file_name_list, zip_file_name)" }, { "code": null, "e": 5008, "s": 4952, "text": "5.Putting everything together discussed in above steps." }, { "code": null, "e": 7246, "s": 5008, "text": "# Define the data\n# let us create a zip file with a single file\n\nimport zipfile\nimport io\nimport pandas as pd\n\n# Function : write_data_to_files\ndef write_data_to_files(inp_data, file_name):\n\"\"\"\nfunction : create a csv file with the data passed to this code\nargs : inp_data : data to be written to the target file\nfile_name : target file name to store the data\nreturn : none\nassumption : File to be created and this code are in same directory.\n\"\"\"\nprint(f\" *** Writing the data to - {file_name}\")\nthrowaway_storage = io.StringIO(inp_data)\nwith open(file_name, 'w') as f:\nfor line in throwaway_storage:\nf.write(line)\n\n# Function : file_compress\ndef file_compress(inp_file_names, out_zip_file):\n\"\"\"\nfunction : file_compress\nargs : inp_file_names : list of filenames to be zipped\nout_zip_file : output zip file\nreturn : none\nassumption : Input file paths and this code is in same directory.\n\"\"\"\n# Select the compression mode ZIP_DEFLATED for compression\n# or zipfile.ZIP_STORED to just store the file\ncompression = zipfile.ZIP_DEFLATED\nprint(f\" *** Input File name passed for zipping - {inp_file_names}\")\n\n# create the zip file first parameter path/name, second mode\nprint(f' *** out_zip_file is - {out_zip_file}')\nzf = zipfile.ZipFile(out_zip_file, mode=\"w\")\n\ntry:\nfor file_to_write in inp_file_names:\n# Add file to the zip file\n# first parameter file to zip, second filename in zip\nprint(f' *** Processing file {file_to_write}')\nzf.write(file_to_write, file_to_write, compress_type=compression)\n\nexcept FileNotFoundError as e:\nprint(f' *** Exception occurred during zip process - {e}')\nfinally:\n# Don't forget to close the file!\nzf.close()\n\n# __main__ program\nif __name__ == '__main__':\n# Define your file name and data\nfile_name1 = \"temporary_file1_for_zip.csv\"\nfile_name2 = \"temporary_file2_for_zip.csv\"\n\nfile_name_list = [file_name1, file_name2]\nzip_file_name = \"temporary.zip\"\nfile_data_1 = \"\"\"\nplayer,titles\nFederer,20\nNadal,20\nDjokovic,17\nMurray,3\n\"\"\"\n\nfile_data_2 = \"\"\"\nplayer,titles\nTheim,1\nZverev,0\nMedvedev,0\nRublev,0\n\"\"\"\n# write the file_data to file_name\nwrite_data_to_files(file_data_1, file_name1)\nwrite_data_to_files(file_data_2, file_name2)\n\n# zip the file_name to zip_file_name\nfile_compress(file_name_list, zip_file_name)" }, { "code": null, "e": 7590, "s": 7246, "text": "*** Writing the data to - temporary_file1_for_zip.csv\n*** Writing the data to - temporary_file2_for_zip.csv\n*** Input File name passed for zipping - ['temporary_file1_for_zip.csv', 'temporary_file2_for_zip.csv']\n*** out_zip_file is - temporary.zip\n*** Processing file temporary_file1_for_zip.csv\n*** Processing file temporary_file2_for_zip.csv" }, { "code": null, "e": 7637, "s": 7590, "text": "When the above code is executed, the output is" }, { "code": null, "e": 7695, "s": 7637, "text": "temporary_file1_for_zip.csv created in current directory." }, { "code": null, "e": 7753, "s": 7695, "text": "temporary_file1_for_zip.csv created in current directory." }, { "code": null, "e": 7811, "s": 7753, "text": "temporary_file2_for_zip.csv created in current directory." }, { "code": null, "e": 7869, "s": 7811, "text": "temporary_file2_for_zip.csv created in current directory." }, { "code": null, "e": 7921, "s": 7869, "text": "temporary.zip file is created in current directory." }, { "code": null, "e": 7973, "s": 7921, "text": "temporary.zip file is created in current directory." } ]
How to read file content into istringstream in C++?
Here is a C++ program to read file content into isstringstream in C++. #include <fstream> #include <sstream> #include<iostream> using namespace std; int main() { ifstream is("a.txt", ios::binary ); // get length of file: is.seekg (0, std::ios::end); long length = is.tellg(); is.seekg (0, std::ios::beg); // allocate memory: char *buffer = new char [length]; // read data as a block: is.read (buffer,length); // create string stream of memory contents istringstream iss( string( buffer ) ); cout<<buffer; // delete temporary buffer delete [] buffer; // close filestream is.close(); } hi tutorialspoint
[ { "code": null, "e": 1133, "s": 1062, "text": "Here is a C++ program to read file content into isstringstream in C++." }, { "code": null, "e": 1694, "s": 1133, "text": "#include <fstream>\n#include <sstream>\n#include<iostream>\nusing namespace std;\nint main() {\n ifstream is(\"a.txt\", ios::binary );\n // get length of file:\n is.seekg (0, std::ios::end);\n long length = is.tellg();\n is.seekg (0, std::ios::beg);\n // allocate memory:\n char *buffer = new char [length];\n // read data as a block:\n is.read (buffer,length);\n // create string stream of memory contents\n istringstream iss( string( buffer ) );\n cout<<buffer;\n // delete temporary buffer\n delete [] buffer;\n // close filestream\n is.close();\n}" }, { "code": null, "e": 1712, "s": 1694, "text": "hi tutorialspoint" } ]
“Digital Twin” with Python: A hands-on example | by Tirthajyoti Sarkar | Towards Data Science
IBM defines a digital twin as follows “A digital twin is a virtual model designed to accurately reflect a physical object”. They go on to describe how the main enabling factors for creating a digital twin are the sensors that gather data and the processing system that inserts the data in some particular format/model into the digital copy of the object. Further, IBM says “Once informed with such data, the virtual model can be used to run simulations, study performance issues and generate possible improvements”. So, we can draw this mental model, can’t we? So, how do we use our favorite language Python to create a digital twin? Why do we even think it will work? The answer is deceptively simple. Just look at the figure above and then at the one below to see the equivalency between a Digital Twin model and a classic Python object. We can emulate the sensors and data processors with suitable methods/functions, store the gathered data in a database or internal variables, and encapsulate everything into a Python class. Once we accomplish that, we can also hope that the Python object can be used in suitable simulation programs, can be probed for data, and can even be subject to optimization routines for enhancing suitable internal parameters. We can, of course, add virtually infinite layers of complexity to this scheme and make the object a truly complex digital construct. But, following Occam’s Razor principle, we should start simple, and add sophistication as we go along. ...main enabling factors for creating a digital twin are the sensors that gather data and the processing system... In this article, we will take a simple step-by-step approach to creating a digital twin object out of a single semiconductor device (the physical object). For the sake of simplicity, we will not even get into modeling sensors, but emulate them as simple terminal voltages on the semiconductor device. There are a select few physical objects around us that define and embody the march of modern civilization quite spectacularly. An incomplete list may look like the following, internal combustion engine — embodies all mobility printing press — embodies all knowledge electrical motor — embodies all industrial motion a semiconductor-based transistor — embodies all electronics/internet I have worked in the semiconductor industry for more than a decade before joining the world of data science. Naturally, I would be attracted towards using a related example for this digital twin demo, won’t I? Although the first semiconductor transistors were so-called ‘Bipolar Junction Device”, almost all modern transistors are of the form called MOSFET. It is an acronym that stands for “Metal-Oxide-Semiconductor Field-Effect-Transistor”. Basically, it is a device made of metal and semiconductor (e.g., silicon or germanium) layers that sandwich a thin oxide (or another electrical insulator) material layer in between. This is a historical image of one of the earliest MOSFET patents, We can simplify the internal structure by adopting a device model (also called a circuit model) with three terminals — Drain, Source, and Gate. This is one of the first considerations while building a digital twin — what characteristics we want to model in our digital object. This determines the complexity and data structure choice for the twin. For instance, although we can model all kinds of complex physics phenomena with the MOSFET structure, we may choose to restrict ourselves to modeling only the most basic characteristic viz. the drain-source current and voltage relationships in their simplest form. Now, we don’t have the bandwidth to explain all these characteristics (and their underlying physics) in detail in this article. Interested readers can refer to excellent online materials, https://www.electronics-tutorials.ws/transistor/tran_6.html The most succinct way to remember the behavior of a MOSFET is to imagine it as a digital switch. Here is how it works, If the voltage between Gate and Source is below a certain threshold, then the switch is OFF and no current (or information) flows between the Drain and Source. This is shown in the bottom-right image of the figure above. When the Gate to Source voltage is above this threshold, the switch is ON. The Drain to Source current is also determined by the voltage between them. This is shown in the top-right image of the figure above. So, the fundamental utility of a MOSFET is as a voltage-controlled switch i.e. we can control the amount of current (or information) between two of its terminals by controlling the voltage on the third terminal. What characteristics do we want to model in our digital object? This determines the complexity and data structure choice for the digital twin With this in mind, the only thing to remember for creating a digital twin, are three important parameters of a generic MOSFET, Vth: It is the threshold voltage (between Gate and Source) above which the switch is ON. gm: It is the ‘ease’ with which a MOSFET can carry current between Drain and Source once it is ON. The higher this number is, the more is the current. It can be thought of as an inverse quantity to resistance (which represents the resistance to the flow of current for a given voltage). BV: This is called the “Breakdown voltage”. This was not discussed in the ideal switch description and will not be modeled in the digital twin. This represents a limit on how much voltage the MOSFET can hold between its Drain and Source while it is in the OFF state. Above this limit, the MOSFET starts conducting again but not in a controlled manner i.e. we cannot control the current flow and it is essentially useless. However, this parameter is important to design and model as it limits the choice of a particular device in a particular application. fundamental utility of a MOSFET is as a voltage-controlled switch... The boilerplate code for this demo is here in my Github repo. For brevity, I will only show partial code snippets in this article. We define the main MOSFET class with a choice for the user to also define some parameters and the terminal voltages. Partial code is shown below, class MOSFET: def __init__(self,params=None,terminals=None): # Params if params is None: self._params_ = {'BV':20, 'Vth':1.0, 'gm':1e-2} else: self._params_ = params # Terminals if terminals is None: self._terminals_ = {'source':0.0, 'drain':0.0, 'gate':0.0} else: self._terminals_ = terminals In this code, we can observe the familiar terminals and parameters that we discussed at length before. There are some default parameters. We can also have a __repr__ method to describe the object in one line, def __repr__(self): return "Digital Twin of a MOSFET" We can easily translate the MOSFET characteristic of a digital switch (ON/OFF) into a programming logic by defining a method within the class. def determine_state(self,vgs=None): """ """ if vgs is None: vgs = self._terminals_['gate'] - self._terminals_['source'] else: vgs = vgs if vgs > self._params_['Vth']: return 'ON' else: return 'OFF' In the __init__ method, we can have the state determined from the instantiation of the object. # Determine state self._state_ = self.determine_state() You are getting a hang of defining a Digital Twin with its characteristics and behavior, aren’t you? Before going deeper into other characteristics, let’s see the behavior of this digital twin as defined so far. mosfet = MOSFET() In Jupyter notebook, we type this for testing the one-line description, mosfet>> Digital Twin of a MOSFET We test the state of the mosfet object. mosfet._state_>> 'OFF' We get the default parameters’ dictionary back in this way, mosfet._params_>> {'BV': 20, 'Vth': 1.0, 'gm': 0.01} Now, if we explicitly define an object with some terminal and parameters value, mosfet = MOSFET(terminals={'source':0.0, 'drain':0.0, 'gate':2.0}, params={'BV':20, 'Vth':1.0, 'gm':1e-2}) What do you think the state of this object is? Let’s check, mosfet._state_>> 'ON' The MOSFET (or its Digital Twin) is ON because the voltage between Gate and Source is larger than the parameter Vth as defined in the instance. I repeat the code snippet again with highlighted portion of interest, terminals={'source':0.0, 'drain':0.0, 'gate':2.0} and params={'BV':20, 'Vth':1.0, 'gm':1e-2}) Next, we define a method to calculate the Drain-to-Source current for the ON-state MOSFET using a simple, first-order analytical model. The code and equation are contained in the Notebook, and I only show a partial code snippet here, def id_vd(self,vgs=None,vds=None,rounding=True): """ Calculates drain-source current from terminal voltages and gm """ <code> if state=='ON': if vds <= vgs - vth: ids = self._params_['gm']*(vgs - vth - (vds/2))*vds else: ids = (self._params_['gm']/2)*(vgs-vth)**2 <more code...> What will be more interesting is that checking if the Digital Twin can generate current-voltage characteristics similar to a physical device. We can calculate a series of Drain-Source currents for a range of Drain-Source voltage. ids = []mosfet = MOSFET()vds_vals = [0.01*i for i in range(1,501)]for v in vds_vals: ids.append(mosfet.id_vd(vgs=3.0,vds=v,rounding=False)) The result looks beautifully matched to a generic, ideal MOSFET characteristic. Here Vds (x-axis) represents Drain-Source voltage and Ids (y-axis) represent Drain-Source current. The analytical model involves Gate-Source voltage (Vgs) too, and therefore, we can calculate Ids vs. Vds curves for a range of Vgs. That result looks like, Digital twin modeling does not necessarily need tools from data science or machine learning. However, in the modern world, dominated by data-driven models, it is prudent to use such modeling techniques wherever applicable and suitable. This does not mean that you should eliminate all analytical models from your digital twins and start throwing deep learning models at every characteristic. As a domain expert (or with the help of one if you are not the domain expert), you must determine a balanced mix of analytical and machine-learning models (or even discrete simulation models), to embed inside the Digital Twin object for representing the real-world characteristics of the physical asset. Digital twin modeling does not necessarily need tools from data science or machine learning So, where should we apply a suitable ML technique in our digital twin object? It turns out that calculating (or predicting with an ML estimator) the so-called “Sub-threshold leakage” will be a good candidate. What is this “Sub-threshold leakage”? As we discussed earlier, the MOSFET is in the OFF state when the Vgs is below Vth. So, the ideal behavior for it is to carry zero current between Drain and Source. However, due to the wonderful whimsical nature of quantum mechanics (the details of which we don’t need to know), a real MOSFET carries a small amount of ‘leakage’ current even in the OFF state. We can attempt to calculate this using an ML model — specifically a deep neural network (DNN). So, why did we choose an analytical equation for modeling the Ids-Vds in the ON-state and a DNN for leakage current? There is no right or wrong answer to this question. It depends on a few factors, the type, and nature of the data you have the nature and complexity of the physical process that you are trying to model the trade-off between performance and accuracy of the Digital Twin model In this case, the measurement of the leakage current is often noisy. The actual value is also somewhat stochastic, being a strong function of the natural variability in the material properties and manufacturing processes that created the physical MOSFET. The physics also dictates that it is a nonlinear function of the terminal voltage and a few other internal parameters. All of these make an ML approach suitable for modeling this characteristic. For every digital twin you create, you have to investigate deeply and make the choice based on your judgment. However, the beauty of a digital twin is that it allows you to swap out an analytical model with an ML model (and vice versa) anytime you fancy. you must determine a balanced mix of analytical and machine-learning models (or even discrete simulation models), to embed inside the Digital Twin object The choice of the model training and prediction interface is entirely flexible. In this example, we have separate training and prediction methods. The code snippet for the training method looks like the following. def train_leakage(self,data=None, batch_size=5, epochs=20, learning_rate=2e-5, verbose=1): """ Trains the digital twin for leakage current model with experimental data Args: data: The training data, expected as a Pandas DataFrame batch_size (int): Training batch size epochs (int): Number of epochs for training learning_rate (float): Learning rate for training verbose (0 or 1): Verbosity of display while training """ Note the inclusion of parameters like batch_size, epochs, and learning_rate — familiar to anybody knowledgeable about building a deep learning model. As the main input, all you have to supply is the data which is expected to be a Pandas DataFrame. Internally, the code builds a Tensorflow Keras model, compiles and trains it, and saves the trained model as an internal property (self.leakage_model) of the Digital Twin. # Deep-learning modelmodel = build_model(num_layers=3, architecture=[32,32,32], input_dim=3)# Compile and trainmodel_trained = compile_train_model(model, X_train_scaled, y_train_scaled, batch_size=batch_size, epochs=epochs, learning_rate=learning_rate, verbose=verbose)self.leakage_model = model_trained Hyperparameters like the number of hidden layers and the activation function are pre-fixed in this implementation, but they can be exposed easily to the developer who is using the Digital Twin in the real-world application. beauty of a digital twin is that it allows you to swap out an analytical model with an ML model (and vice versa) anytime you fancy For this demo, we created some synthetic data using a special helper function (included in the Notebook) to train the DNN. This helper included random variables to mimic the variability and noise in the manufacturing and measurement, mentioned earlier. However, in real life, the semiconductor plant/ fab will run physical test suites (using other machines) on millions of MOSFETs and record their leakage current for various Vgs bias voltages. It will also record the Vth of those MOSFETs in the test. All these data will flow into the Digital Twin and the model will be continuously trained and updated. With this arrangement, we just write one line of code to train the model with the training data supplied as df DataFrame, mosfet.train_leakage(df) and the familiar training starts, We write a separate leakage method to predict the sub-Vth leakage for any combination of transconductance, Vgs, and Vth as input. def leakage(self, w_l=1e-2, vgs=None, vth=None): """ Calculates leakage current using the deep learning model """ if not self._leakage_: return "Leakage model is not trained yet" # Vgs if vgs is None: vgs = self._terminals_['gate'] - self._terminals_['source'] else: vgs = vgs # Vth if vth is None: vth = self._params_['Vth'] else: vth = vth # Predict x = np.array([w_l,vgs,vth]) ip = x.reshape(-1,3) result = float(10**(-self.leakage_model.predict(ip))) return result The exponentiation in the code (raising to the power of 10) is due to the fact that we supplied the negative 10-logarithm of actual leakage values as training targets to the DNN model. This was done to achieve faster convergence and higher accuracy. Digital Twins welcome friends with their open arms. On both sides of the aisle, too. Basically, they are particularly amenable to connecting to industrial systems — upstream and downstream — and exploit that connection for the optimal behavior of the whole plant/industrial system. This is important to keep in mind while designing Digital Twin with a programming language, or any other modern data-oriented tool for that matter. Connection. Communication. Co-work. These are the keys to making a successful and well-liked Digital Twin. So, the designer must carefully evaluate the choice of data structures, programming platforms, and AI/ML methods to make sure they play well with that design philosophy. In this article, we just peeled the upper layers of a Digital Twin design by showing you some simple steps with Python programmatic framework. It is up to you — the readers — to take the concepts forward and add more sophisticated layers of programming, logic, and data science layers to the system/asset of your choice and design powerful digital twins. The Industry 4.0/ Smart factory is already here and ready to take advantage of all the progress in Digital Transformation, Artificial Intelligence, and Machine Learning. Digital twins are a vital co-component of that journey. Connection. Communication. Co-work. These are the keys to making a successful and well-liked Digital Twin Loved the article? Become a Medium member to continue learning without limits. I’ll receive a portion of your membership fee if you use the following link, with no extra cost to you.
[ { "code": null, "e": 296, "s": 172, "text": "IBM defines a digital twin as follows “A digital twin is a virtual model designed to accurately reflect a physical object”." }, { "code": null, "e": 527, "s": 296, "text": "They go on to describe how the main enabling factors for creating a digital twin are the sensors that gather data and the processing system that inserts the data in some particular format/model into the digital copy of the object." }, { "code": null, "e": 688, "s": 527, "text": "Further, IBM says “Once informed with such data, the virtual model can be used to run simulations, study performance issues and generate possible improvements”." }, { "code": null, "e": 733, "s": 688, "text": "So, we can draw this mental model, can’t we?" }, { "code": null, "e": 841, "s": 733, "text": "So, how do we use our favorite language Python to create a digital twin? Why do we even think it will work?" }, { "code": null, "e": 1201, "s": 841, "text": "The answer is deceptively simple. Just look at the figure above and then at the one below to see the equivalency between a Digital Twin model and a classic Python object. We can emulate the sensors and data processors with suitable methods/functions, store the gathered data in a database or internal variables, and encapsulate everything into a Python class." }, { "code": null, "e": 1266, "s": 1201, "text": "Once we accomplish that, we can also hope that the Python object" }, { "code": null, "e": 1311, "s": 1266, "text": "can be used in suitable simulation programs," }, { "code": null, "e": 1339, "s": 1311, "text": "can be probed for data, and" }, { "code": null, "e": 1428, "s": 1339, "text": "can even be subject to optimization routines for enhancing suitable internal parameters." }, { "code": null, "e": 1664, "s": 1428, "text": "We can, of course, add virtually infinite layers of complexity to this scheme and make the object a truly complex digital construct. But, following Occam’s Razor principle, we should start simple, and add sophistication as we go along." }, { "code": null, "e": 1779, "s": 1664, "text": "...main enabling factors for creating a digital twin are the sensors that gather data and the processing system..." }, { "code": null, "e": 2080, "s": 1779, "text": "In this article, we will take a simple step-by-step approach to creating a digital twin object out of a single semiconductor device (the physical object). For the sake of simplicity, we will not even get into modeling sensors, but emulate them as simple terminal voltages on the semiconductor device." }, { "code": null, "e": 2255, "s": 2080, "text": "There are a select few physical objects around us that define and embody the march of modern civilization quite spectacularly. An incomplete list may look like the following," }, { "code": null, "e": 2306, "s": 2255, "text": "internal combustion engine — embodies all mobility" }, { "code": null, "e": 2346, "s": 2306, "text": "printing press — embodies all knowledge" }, { "code": null, "e": 2396, "s": 2346, "text": "electrical motor — embodies all industrial motion" }, { "code": null, "e": 2465, "s": 2396, "text": "a semiconductor-based transistor — embodies all electronics/internet" }, { "code": null, "e": 2675, "s": 2465, "text": "I have worked in the semiconductor industry for more than a decade before joining the world of data science. Naturally, I would be attracted towards using a related example for this digital twin demo, won’t I?" }, { "code": null, "e": 2909, "s": 2675, "text": "Although the first semiconductor transistors were so-called ‘Bipolar Junction Device”, almost all modern transistors are of the form called MOSFET. It is an acronym that stands for “Metal-Oxide-Semiconductor Field-Effect-Transistor”." }, { "code": null, "e": 3091, "s": 2909, "text": "Basically, it is a device made of metal and semiconductor (e.g., silicon or germanium) layers that sandwich a thin oxide (or another electrical insulator) material layer in between." }, { "code": null, "e": 3157, "s": 3091, "text": "This is a historical image of one of the earliest MOSFET patents," }, { "code": null, "e": 3301, "s": 3157, "text": "We can simplify the internal structure by adopting a device model (also called a circuit model) with three terminals — Drain, Source, and Gate." }, { "code": null, "e": 3505, "s": 3301, "text": "This is one of the first considerations while building a digital twin — what characteristics we want to model in our digital object. This determines the complexity and data structure choice for the twin." }, { "code": null, "e": 3770, "s": 3505, "text": "For instance, although we can model all kinds of complex physics phenomena with the MOSFET structure, we may choose to restrict ourselves to modeling only the most basic characteristic viz. the drain-source current and voltage relationships in their simplest form." }, { "code": null, "e": 3958, "s": 3770, "text": "Now, we don’t have the bandwidth to explain all these characteristics (and their underlying physics) in detail in this article. Interested readers can refer to excellent online materials," }, { "code": null, "e": 4018, "s": 3958, "text": "https://www.electronics-tutorials.ws/transistor/tran_6.html" }, { "code": null, "e": 4137, "s": 4018, "text": "The most succinct way to remember the behavior of a MOSFET is to imagine it as a digital switch. Here is how it works," }, { "code": null, "e": 4358, "s": 4137, "text": "If the voltage between Gate and Source is below a certain threshold, then the switch is OFF and no current (or information) flows between the Drain and Source. This is shown in the bottom-right image of the figure above." }, { "code": null, "e": 4567, "s": 4358, "text": "When the Gate to Source voltage is above this threshold, the switch is ON. The Drain to Source current is also determined by the voltage between them. This is shown in the top-right image of the figure above." }, { "code": null, "e": 4779, "s": 4567, "text": "So, the fundamental utility of a MOSFET is as a voltage-controlled switch i.e. we can control the amount of current (or information) between two of its terminals by controlling the voltage on the third terminal." }, { "code": null, "e": 4921, "s": 4779, "text": "What characteristics do we want to model in our digital object? This determines the complexity and data structure choice for the digital twin" }, { "code": null, "e": 5048, "s": 4921, "text": "With this in mind, the only thing to remember for creating a digital twin, are three important parameters of a generic MOSFET," }, { "code": null, "e": 5137, "s": 5048, "text": "Vth: It is the threshold voltage (between Gate and Source) above which the switch is ON." }, { "code": null, "e": 5424, "s": 5137, "text": "gm: It is the ‘ease’ with which a MOSFET can carry current between Drain and Source once it is ON. The higher this number is, the more is the current. It can be thought of as an inverse quantity to resistance (which represents the resistance to the flow of current for a given voltage)." }, { "code": null, "e": 5979, "s": 5424, "text": "BV: This is called the “Breakdown voltage”. This was not discussed in the ideal switch description and will not be modeled in the digital twin. This represents a limit on how much voltage the MOSFET can hold between its Drain and Source while it is in the OFF state. Above this limit, the MOSFET starts conducting again but not in a controlled manner i.e. we cannot control the current flow and it is essentially useless. However, this parameter is important to design and model as it limits the choice of a particular device in a particular application." }, { "code": null, "e": 6048, "s": 5979, "text": "fundamental utility of a MOSFET is as a voltage-controlled switch..." }, { "code": null, "e": 6179, "s": 6048, "text": "The boilerplate code for this demo is here in my Github repo. For brevity, I will only show partial code snippets in this article." }, { "code": null, "e": 6325, "s": 6179, "text": "We define the main MOSFET class with a choice for the user to also define some parameters and the terminal voltages. Partial code is shown below," }, { "code": null, "e": 6826, "s": 6325, "text": "class MOSFET: def __init__(self,params=None,terminals=None): # Params if params is None: self._params_ = {'BV':20, 'Vth':1.0, 'gm':1e-2} else: self._params_ = params # Terminals if terminals is None: self._terminals_ = {'source':0.0, 'drain':0.0, 'gate':0.0} else: self._terminals_ = terminals" }, { "code": null, "e": 6964, "s": 6826, "text": "In this code, we can observe the familiar terminals and parameters that we discussed at length before. There are some default parameters." }, { "code": null, "e": 7035, "s": 6964, "text": "We can also have a __repr__ method to describe the object in one line," }, { "code": null, "e": 7096, "s": 7035, "text": "def __repr__(self): return \"Digital Twin of a MOSFET\"" }, { "code": null, "e": 7239, "s": 7096, "text": "We can easily translate the MOSFET characteristic of a digital switch (ON/OFF) into a programming logic by defining a method within the class." }, { "code": null, "e": 7523, "s": 7239, "text": "def determine_state(self,vgs=None): \"\"\" \"\"\" if vgs is None: vgs = self._terminals_['gate'] - self._terminals_['source'] else: vgs = vgs if vgs > self._params_['Vth']: return 'ON' else: return 'OFF'" }, { "code": null, "e": 7618, "s": 7523, "text": "In the __init__ method, we can have the state determined from the instantiation of the object." }, { "code": null, "e": 7675, "s": 7618, "text": "# Determine state self._state_ = self.determine_state()" }, { "code": null, "e": 7776, "s": 7675, "text": "You are getting a hang of defining a Digital Twin with its characteristics and behavior, aren’t you?" }, { "code": null, "e": 7887, "s": 7776, "text": "Before going deeper into other characteristics, let’s see the behavior of this digital twin as defined so far." }, { "code": null, "e": 7905, "s": 7887, "text": "mosfet = MOSFET()" }, { "code": null, "e": 7977, "s": 7905, "text": "In Jupyter notebook, we type this for testing the one-line description," }, { "code": null, "e": 8011, "s": 7977, "text": "mosfet>> Digital Twin of a MOSFET" }, { "code": null, "e": 8051, "s": 8011, "text": "We test the state of the mosfet object." }, { "code": null, "e": 8074, "s": 8051, "text": "mosfet._state_>> 'OFF'" }, { "code": null, "e": 8134, "s": 8074, "text": "We get the default parameters’ dictionary back in this way," }, { "code": null, "e": 8187, "s": 8134, "text": "mosfet._params_>> {'BV': 20, 'Vth': 1.0, 'gm': 0.01}" }, { "code": null, "e": 8267, "s": 8187, "text": "Now, if we explicitly define an object with some terminal and parameters value," }, { "code": null, "e": 8443, "s": 8267, "text": "mosfet = MOSFET(terminals={'source':0.0, 'drain':0.0, 'gate':2.0}, params={'BV':20, 'Vth':1.0, 'gm':1e-2})" }, { "code": null, "e": 8503, "s": 8443, "text": "What do you think the state of this object is? Let’s check," }, { "code": null, "e": 8525, "s": 8503, "text": "mosfet._state_>> 'ON'" }, { "code": null, "e": 8739, "s": 8525, "text": "The MOSFET (or its Digital Twin) is ON because the voltage between Gate and Source is larger than the parameter Vth as defined in the instance. I repeat the code snippet again with highlighted portion of interest," }, { "code": null, "e": 8811, "s": 8739, "text": "terminals={'source':0.0, 'drain':0.0, 'gate':2.0}" }, { "code": null, "e": 8815, "s": 8811, "text": "and" }, { "code": null, "e": 8869, "s": 8815, "text": "params={'BV':20, 'Vth':1.0, 'gm':1e-2})" }, { "code": null, "e": 9103, "s": 8869, "text": "Next, we define a method to calculate the Drain-to-Source current for the ON-state MOSFET using a simple, first-order analytical model. The code and equation are contained in the Notebook, and I only show a partial code snippet here," }, { "code": null, "e": 9493, "s": 9103, "text": "def id_vd(self,vgs=None,vds=None,rounding=True): \"\"\" Calculates drain-source current from terminal voltages and gm \"\"\" <code> if state=='ON': if vds <= vgs - vth: ids = self._params_['gm']*(vgs - vth - (vds/2))*vds else: ids = (self._params_['gm']/2)*(vgs-vth)**2 <more code...>" }, { "code": null, "e": 9723, "s": 9493, "text": "What will be more interesting is that checking if the Digital Twin can generate current-voltage characteristics similar to a physical device. We can calculate a series of Drain-Source currents for a range of Drain-Source voltage." }, { "code": null, "e": 9866, "s": 9723, "text": "ids = []mosfet = MOSFET()vds_vals = [0.01*i for i in range(1,501)]for v in vds_vals: ids.append(mosfet.id_vd(vgs=3.0,vds=v,rounding=False))" }, { "code": null, "e": 10045, "s": 9866, "text": "The result looks beautifully matched to a generic, ideal MOSFET characteristic. Here Vds (x-axis) represents Drain-Source voltage and Ids (y-axis) represent Drain-Source current." }, { "code": null, "e": 10201, "s": 10045, "text": "The analytical model involves Gate-Source voltage (Vgs) too, and therefore, we can calculate Ids vs. Vds curves for a range of Vgs. That result looks like," }, { "code": null, "e": 10437, "s": 10201, "text": "Digital twin modeling does not necessarily need tools from data science or machine learning. However, in the modern world, dominated by data-driven models, it is prudent to use such modeling techniques wherever applicable and suitable." }, { "code": null, "e": 10897, "s": 10437, "text": "This does not mean that you should eliminate all analytical models from your digital twins and start throwing deep learning models at every characteristic. As a domain expert (or with the help of one if you are not the domain expert), you must determine a balanced mix of analytical and machine-learning models (or even discrete simulation models), to embed inside the Digital Twin object for representing the real-world characteristics of the physical asset." }, { "code": null, "e": 10989, "s": 10897, "text": "Digital twin modeling does not necessarily need tools from data science or machine learning" }, { "code": null, "e": 11198, "s": 10989, "text": "So, where should we apply a suitable ML technique in our digital twin object? It turns out that calculating (or predicting with an ML estimator) the so-called “Sub-threshold leakage” will be a good candidate." }, { "code": null, "e": 11236, "s": 11198, "text": "What is this “Sub-threshold leakage”?" }, { "code": null, "e": 11690, "s": 11236, "text": "As we discussed earlier, the MOSFET is in the OFF state when the Vgs is below Vth. So, the ideal behavior for it is to carry zero current between Drain and Source. However, due to the wonderful whimsical nature of quantum mechanics (the details of which we don’t need to know), a real MOSFET carries a small amount of ‘leakage’ current even in the OFF state. We can attempt to calculate this using an ML model — specifically a deep neural network (DNN)." }, { "code": null, "e": 11807, "s": 11690, "text": "So, why did we choose an analytical equation for modeling the Ids-Vds in the ON-state and a DNN for leakage current?" }, { "code": null, "e": 11888, "s": 11807, "text": "There is no right or wrong answer to this question. It depends on a few factors," }, { "code": null, "e": 11930, "s": 11888, "text": "the type, and nature of the data you have" }, { "code": null, "e": 12009, "s": 11930, "text": "the nature and complexity of the physical process that you are trying to model" }, { "code": null, "e": 12082, "s": 12009, "text": "the trade-off between performance and accuracy of the Digital Twin model" }, { "code": null, "e": 12532, "s": 12082, "text": "In this case, the measurement of the leakage current is often noisy. The actual value is also somewhat stochastic, being a strong function of the natural variability in the material properties and manufacturing processes that created the physical MOSFET. The physics also dictates that it is a nonlinear function of the terminal voltage and a few other internal parameters. All of these make an ML approach suitable for modeling this characteristic." }, { "code": null, "e": 12787, "s": 12532, "text": "For every digital twin you create, you have to investigate deeply and make the choice based on your judgment. However, the beauty of a digital twin is that it allows you to swap out an analytical model with an ML model (and vice versa) anytime you fancy." }, { "code": null, "e": 12941, "s": 12787, "text": "you must determine a balanced mix of analytical and machine-learning models (or even discrete simulation models), to embed inside the Digital Twin object" }, { "code": null, "e": 13155, "s": 12941, "text": "The choice of the model training and prediction interface is entirely flexible. In this example, we have separate training and prediction methods. The code snippet for the training method looks like the following." }, { "code": null, "e": 13742, "s": 13155, "text": "def train_leakage(self,data=None, batch_size=5, epochs=20, learning_rate=2e-5, verbose=1): \"\"\" Trains the digital twin for leakage current model with experimental data Args: data: The training data, expected as a Pandas DataFrame batch_size (int): Training batch size epochs (int): Number of epochs for training learning_rate (float): Learning rate for training verbose (0 or 1): Verbosity of display while training \"\"\"" }, { "code": null, "e": 13990, "s": 13742, "text": "Note the inclusion of parameters like batch_size, epochs, and learning_rate — familiar to anybody knowledgeable about building a deep learning model. As the main input, all you have to supply is the data which is expected to be a Pandas DataFrame." }, { "code": null, "e": 14162, "s": 13990, "text": "Internally, the code builds a Tensorflow Keras model, compiles and trains it, and saves the trained model as an internal property (self.leakage_model) of the Digital Twin." }, { "code": null, "e": 14714, "s": 14162, "text": "# Deep-learning modelmodel = build_model(num_layers=3, architecture=[32,32,32], input_dim=3)# Compile and trainmodel_trained = compile_train_model(model, X_train_scaled, y_train_scaled, batch_size=batch_size, epochs=epochs, learning_rate=learning_rate, verbose=verbose)self.leakage_model = model_trained" }, { "code": null, "e": 14938, "s": 14714, "text": "Hyperparameters like the number of hidden layers and the activation function are pre-fixed in this implementation, but they can be exposed easily to the developer who is using the Digital Twin in the real-world application." }, { "code": null, "e": 15069, "s": 14938, "text": "beauty of a digital twin is that it allows you to swap out an analytical model with an ML model (and vice versa) anytime you fancy" }, { "code": null, "e": 15322, "s": 15069, "text": "For this demo, we created some synthetic data using a special helper function (included in the Notebook) to train the DNN. This helper included random variables to mimic the variability and noise in the manufacturing and measurement, mentioned earlier." }, { "code": null, "e": 15675, "s": 15322, "text": "However, in real life, the semiconductor plant/ fab will run physical test suites (using other machines) on millions of MOSFETs and record their leakage current for various Vgs bias voltages. It will also record the Vth of those MOSFETs in the test. All these data will flow into the Digital Twin and the model will be continuously trained and updated." }, { "code": null, "e": 15797, "s": 15675, "text": "With this arrangement, we just write one line of code to train the model with the training data supplied as df DataFrame," }, { "code": null, "e": 15822, "s": 15797, "text": "mosfet.train_leakage(df)" }, { "code": null, "e": 15856, "s": 15822, "text": "and the familiar training starts," }, { "code": null, "e": 15986, "s": 15856, "text": "We write a separate leakage method to predict the sub-Vth leakage for any combination of transconductance, Vgs, and Vth as input." }, { "code": null, "e": 16676, "s": 15986, "text": "def leakage(self, w_l=1e-2, vgs=None, vth=None): \"\"\" Calculates leakage current using the deep learning model \"\"\" if not self._leakage_: return \"Leakage model is not trained yet\" # Vgs if vgs is None: vgs = self._terminals_['gate'] - self._terminals_['source'] else: vgs = vgs # Vth if vth is None: vth = self._params_['Vth'] else: vth = vth # Predict x = np.array([w_l,vgs,vth]) ip = x.reshape(-1,3) result = float(10**(-self.leakage_model.predict(ip))) return result" }, { "code": null, "e": 16926, "s": 16676, "text": "The exponentiation in the code (raising to the power of 10) is due to the fact that we supplied the negative 10-logarithm of actual leakage values as training targets to the DNN model. This was done to achieve faster convergence and higher accuracy." }, { "code": null, "e": 17011, "s": 16926, "text": "Digital Twins welcome friends with their open arms. On both sides of the aisle, too." }, { "code": null, "e": 17356, "s": 17011, "text": "Basically, they are particularly amenable to connecting to industrial systems — upstream and downstream — and exploit that connection for the optimal behavior of the whole plant/industrial system. This is important to keep in mind while designing Digital Twin with a programming language, or any other modern data-oriented tool for that matter." }, { "code": null, "e": 17633, "s": 17356, "text": "Connection. Communication. Co-work. These are the keys to making a successful and well-liked Digital Twin. So, the designer must carefully evaluate the choice of data structures, programming platforms, and AI/ML methods to make sure they play well with that design philosophy." }, { "code": null, "e": 17988, "s": 17633, "text": "In this article, we just peeled the upper layers of a Digital Twin design by showing you some simple steps with Python programmatic framework. It is up to you — the readers — to take the concepts forward and add more sophisticated layers of programming, logic, and data science layers to the system/asset of your choice and design powerful digital twins." }, { "code": null, "e": 18214, "s": 17988, "text": "The Industry 4.0/ Smart factory is already here and ready to take advantage of all the progress in Digital Transformation, Artificial Intelligence, and Machine Learning. Digital twins are a vital co-component of that journey." }, { "code": null, "e": 18320, "s": 18214, "text": "Connection. Communication. Co-work. These are the keys to making a successful and well-liked Digital Twin" } ]
Using useState hook in React.js
Hooks allows the functional component in react to get the features available in class based component in make them more powerful. useState we will import from react. Import {useState} from ‘react’; This helps us in creating local state variables for functional component and provides method to update that variable. State in class is an object, but with useState we can create simple primitive data types and object if we want. const test=()=>{ const [age, setAge] = useState(25); return ( <div> <p>Age: {age}</p> <button onClick={()=>setAge(age+1)}>Increase Age</button> </div> ); } In the above example we created a state variable age which is initialized with 25. useState also provided us setAge method which we used on button click to increment age by 1. The useState provides us an array with two elements 1. Current value 2. Function to update that value The order of elements from useState is fixed that means first element is current value and second is set function. Similarly we can create multiple state variable but these useState should be the first statement in your function body. This is introduced in React 16.8 and its backward compatible that means we can convert the classes into functional components. The useState initialize the variable only once in life of that component and maintains its value between multiple renders. We can define an empty array. const myList= useState([]); we can pass previous value and process it in set function setAge(preAge=>preAge+1); while updating the value make sure to return a new object to trigger re-render else react assumes it as same object and wont re-render as explained below. onClick={(e)=>{ age.birthYear=e.target.value; setAge(age); }} It won’t trigger the re-render as we just mutated the current object and object remains the same. Instead of this we should create new object. onClick={(e)=>{ const newAge={birthYear: e.target.value}; setAge(newAge); }} The above way react sees the creation of new object and it will re-render on value change. This approach clearly shows us that useState does not merge the updates but replaces them with new value. And setState in class based components merges them automatically . To avoid the other properties of the object from getting lost we can use the spread operator setAge((prev)=>{ return {...prev, birthYear:newValue}; }); The spread operator will preserve the remaining properties the object from getting lost and also updates the other property. Please note that all these hooks only works in functional component and never work in class based component. These hooks does not work in non react JavaScript functions. These hooks should not be used in conditional statements or in loops but should be declared at the start of the function body in simple statements. If you are more interested, analyzing code in class ReactFiberHooks of react library can be helpful where we can see the implementation of hooks. Providing a initial value to local state variable is not necessary. Updates work in asynchronous way and does not block the UI from rendering. Probably this the way the new modern react code will be written instead of writing classes.
[ { "code": null, "e": 1192, "s": 1062, "text": "Hooks allows the functional component in react to get the features available in class based component in make them more powerful." }, { "code": null, "e": 1378, "s": 1192, "text": "useState we will import from react. Import {useState} from ‘react’; This helps us in creating local state variables for functional component and provides method to update that variable." }, { "code": null, "e": 1490, "s": 1378, "text": "State in class is an object, but with useState we can create simple primitive data types and object if we want." }, { "code": null, "e": 1685, "s": 1490, "text": "const test=()=>{\n const [age, setAge] = useState(25);\n return (\n <div>\n <p>Age: {age}</p>\n <button onClick={()=>setAge(age+1)}>Increase Age</button>\n </div>\n );\n}" }, { "code": null, "e": 1861, "s": 1685, "text": "In the above example we created a state variable age which is initialized with 25. useState also provided us setAge method which we used on button click to increment age by 1." }, { "code": null, "e": 1963, "s": 1861, "text": "The useState provides us an array with two elements 1. Current value 2. Function to update that value" }, { "code": null, "e": 2078, "s": 1963, "text": "The order of elements from useState is fixed that means first element is current value and second is set function." }, { "code": null, "e": 2198, "s": 2078, "text": "Similarly we can create multiple state variable but these useState should be the first statement in your function body." }, { "code": null, "e": 2325, "s": 2198, "text": "This is introduced in React 16.8 and its backward compatible that means we can convert the classes into functional components." }, { "code": null, "e": 2448, "s": 2325, "text": "The useState initialize the variable only once in life of that component and maintains its value between multiple renders." }, { "code": null, "e": 2478, "s": 2448, "text": "We can define an empty array." }, { "code": null, "e": 2506, "s": 2478, "text": "const myList= useState([]);" }, { "code": null, "e": 2564, "s": 2506, "text": "we can pass previous value and process it in set function" }, { "code": null, "e": 2590, "s": 2564, "text": "setAge(preAge=>preAge+1);" }, { "code": null, "e": 2745, "s": 2590, "text": "while updating the value make sure to return a new object to trigger re-render else react assumes it as same object and wont re-render as explained below." }, { "code": null, "e": 2813, "s": 2745, "text": "onClick={(e)=>{\n age.birthYear=e.target.value;\n setAge(age);\n}}" }, { "code": null, "e": 2911, "s": 2813, "text": "It won’t trigger the re-render as we just mutated the current object and object remains the same." }, { "code": null, "e": 2956, "s": 2911, "text": "Instead of this we should create new object." }, { "code": null, "e": 3039, "s": 2956, "text": "onClick={(e)=>{\n const newAge={birthYear: e.target.value};\n setAge(newAge);\n}}" }, { "code": null, "e": 3130, "s": 3039, "text": "The above way react sees the creation of new object and it will re-render on value change." }, { "code": null, "e": 3303, "s": 3130, "text": "This approach clearly shows us that useState does not merge the updates but replaces them with new value. And setState in class based components merges them automatically ." }, { "code": null, "e": 3396, "s": 3303, "text": "To avoid the other properties of the object from getting lost we can use the spread operator" }, { "code": null, "e": 3458, "s": 3396, "text": "setAge((prev)=>{\n return {...prev, birthYear:newValue};\n});" }, { "code": null, "e": 3583, "s": 3458, "text": "The spread operator will preserve the remaining properties the object from getting lost and also updates the other property." }, { "code": null, "e": 3753, "s": 3583, "text": "Please note that all these hooks only works in functional component and never work in class based component. These hooks does not work in non react JavaScript functions." }, { "code": null, "e": 3901, "s": 3753, "text": "These hooks should not be used in conditional statements or in loops but should be declared at the start of the function body in simple statements." }, { "code": null, "e": 4047, "s": 3901, "text": "If you are more interested, analyzing code in class ReactFiberHooks of react library can be helpful where we can see the implementation of hooks." }, { "code": null, "e": 4190, "s": 4047, "text": "Providing a initial value to local state variable is not necessary. Updates work in asynchronous way and does not block the UI from rendering." }, { "code": null, "e": 4282, "s": 4190, "text": "Probably this the way the new modern react code will be written instead of writing classes." } ]
Bulma | Input - GeeksforGeeks
15 Jul, 2020 Bulma is a free, open-source CSS framework based on Flexbox. It is component rich, compatible, and well documented. It is highly responsive in nature. It uses classes to implement its design. The ‘input’ component of a form is not that attractive in look. Using Bulma we can design input elements of the form in a far better way just by adding some simple Bulma classes. Bulma input elements are available in different colors, different styles, different sizes, and different states. Example 1: This Example illustrates simple Bulma input. <!DOCTYPE html><html> <head> <title>Bulma Input</title> <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.5/css/bulma.css'> <!-- custom css --> <style> div.columns { margin-top: 80px; } </style> </head> <body> <div class='container'> <div class='columns is-mobile is-centered'> <div class='column is-5'> <div class="field"> <div class="control"> <input class="input" type="text" placeholder='Normal Input'> </div> </div> </div> </div> </div> </body></html> Output: Example 2: This example illustrates coloured form input. <!DOCTYPE html><html> <head> <title>Bulma Input</title> <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.5/css/bulma.css'> <!-- custom css --> <style> div.columns{ margin-top: 80px; } </style> </head> <body> <div class='container'> <div class='columns is-mobile is-centered'> <div class='column is-5'> <div class="field"> <div class="control"> <input class="input is-primary" type="text" placeholder='Primary color Input'> </div> </div> <div class="field"> <div class="control"> <input class="input is-link" type="text" placeholder='Link color Input'> </div> </div> <div class="field"> <div class="control"> <input class="input is-info" type="text" placeholder='Info color Input'> </div> </div> <div class="field"> <div class="control"> <input class="input is-success" type="text" placeholder='success color Input'> </div> </div> <div class="field"> <div class="control"> <input class="input is-warning" type="text" placeholder='Warning color Input'> </div> </div> <div class="field"> <div class="control"> <input class="input is-danger" type="text" placeholder='Danger color Input'> </div> </div> </div> </div> </div> </body></html> Output: Example 3: This example illustrates different size form input. <!DOCTYPE html><html> <head> <title>Bulma Input</title> <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.5/css/bulma.css'> <!-- custom css --> <style> div.columns{ margin-top: 80px; } </style> </head> <body> <div class='container'> <div class='columns is-mobile is-centered'> <div class='column is-5'> <div class="field"> <div class="control"> <input class="input is-small" type="text" placeholder='Small input'> </div> </div> <div class="field"> <div class="control"> <input class="input" type="text" placeholder='Normal Input'> </div> </div> <div class="field"> <div class="control"> <input class="input is-medium" type="text" placeholder='Medium Input'> </div> </div> <div class="field"> <div class="control"> <input class="input is-large" type="text" placeholder='Large Input'> </div> </div> </div> </div> </div> </body></html> Output: Example 4: This example illustrates different states of form input. <!DOCTYPE html><html> <head> <title>Bulma Input</title> <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.5/css/bulma.css'> <!-- custom css --> <style> div.columns{ margin-top: 80px; } </style> </head> <body> <div class='container'> <div class='columns is-mobile is-centered'> <div class='column is-5'> <div class="field"> <div class="control"> <input class="input" type="text" placeholder='Normal Input'> </div> </div> <div class="field"> <div class="control"> <input class="input is-hovered" type="text" placeholder='Hovered Input'> </div> </div> <div class="field"> <div class="control"> <input class="input is-focused" type="text" placeholder='Focused Input'> </div> </div> <div class="field"> <div class="control is-loading"> <input class="input" type="text" placeholder="Loading input"> </div> </div> </div> </div> </div> </body></html> Output: Example 5: This example illustrates form input with font awesome icons. <!DOCTYPE html><html> <head> <title>Bulma Input</title> <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.5/css/bulma.css'> <!-- custom css --> <style> div.columns{ margin-top: 80px; } </style> </head> <body> <!-- font-awesome cdn --> <script src='https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.12.0-2/js/all.min.js'> </script> <div class='container'> <div class='columns is-mobile is-centered'> <div class='column is-5'> <div class="field"> <div class="control has-icons-left"> <input class="input" type="text" placeholder="Username"> <span class="icon is-small is-left"> <i class="fas fa-user"></i> </span> </div> </div> <div class="field"> <div class="control has-icons-left"> <input class="input" type="password" placeholder="Password"> <span class="icon is-small is-left"> <i class="fas fa-lock"></i> </span> </div> </div> </div> </div> </div> </body></html> Output: Example 6: This example illustrates rounded type of form inputs. <!DOCTYPE html><html> <head> <title>Bulma Input</title> <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.5/css/bulma.css'> <!-- custom css --> <style> div.columns{ margin-top: 80px; } </style> </head> <body> <!-- font-awesome cdn --> <script src='https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.12.0-2/js/all.min.js'> </script> <div class='container'> <div class='columns is-mobile is-centered'> <div class='column is-5'> <div class="field"> <div class="control has-icons-left"> <input class="input is-rounded" type="text" placeholder="Username"> <span class="icon is-small is-left"> <i class="fas fa-user"></i> </span> </div> </div> <div class="field"> <div class="control has-icons-left"> <input class="input is-rounded" type="password" placeholder="Password"> <span class="icon is-small is-left"> <i class="fas fa-lock"></i> </span> </div> </div> </div> </div> </div> </body></html> Output : Bulma CSS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? How to create footer to stay at the bottom of a Web page? How to update Node.js and NPM to next version ? CSS to put icon inside an input element in a form Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 26108, "s": 26080, "text": "\n15 Jul, 2020" }, { "code": null, "e": 26300, "s": 26108, "text": "Bulma is a free, open-source CSS framework based on Flexbox. It is component rich, compatible, and well documented. It is highly responsive in nature. It uses classes to implement its design." }, { "code": null, "e": 26592, "s": 26300, "text": "The ‘input’ component of a form is not that attractive in look. Using Bulma we can design input elements of the form in a far better way just by adding some simple Bulma classes. Bulma input elements are available in different colors, different styles, different sizes, and different states." }, { "code": null, "e": 26648, "s": 26592, "text": "Example 1: This Example illustrates simple Bulma input." }, { "code": "<!DOCTYPE html><html> <head> <title>Bulma Input</title> <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.5/css/bulma.css'> <!-- custom css --> <style> div.columns { margin-top: 80px; } </style> </head> <body> <div class='container'> <div class='columns is-mobile is-centered'> <div class='column is-5'> <div class=\"field\"> <div class=\"control\"> <input class=\"input\" type=\"text\" placeholder='Normal Input'> </div> </div> </div> </div> </div> </body></html>", "e": 27303, "s": 26648, "text": null }, { "code": null, "e": 27311, "s": 27303, "text": "Output:" }, { "code": null, "e": 27368, "s": 27311, "text": "Example 2: This example illustrates coloured form input." }, { "code": "<!DOCTYPE html><html> <head> <title>Bulma Input</title> <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.5/css/bulma.css'> <!-- custom css --> <style> div.columns{ margin-top: 80px; } </style> </head> <body> <div class='container'> <div class='columns is-mobile is-centered'> <div class='column is-5'> <div class=\"field\"> <div class=\"control\"> <input class=\"input is-primary\" type=\"text\" placeholder='Primary color Input'> </div> </div> <div class=\"field\"> <div class=\"control\"> <input class=\"input is-link\" type=\"text\" placeholder='Link color Input'> </div> </div> <div class=\"field\"> <div class=\"control\"> <input class=\"input is-info\" type=\"text\" placeholder='Info color Input'> </div> </div> <div class=\"field\"> <div class=\"control\"> <input class=\"input is-success\" type=\"text\" placeholder='success color Input'> </div> </div> <div class=\"field\"> <div class=\"control\"> <input class=\"input is-warning\" type=\"text\" placeholder='Warning color Input'> </div> </div> <div class=\"field\"> <div class=\"control\"> <input class=\"input is-danger\" type=\"text\" placeholder='Danger color Input'> </div> </div> </div> </div> </div> </body></html>", "e": 29172, "s": 27368, "text": null }, { "code": null, "e": 29180, "s": 29172, "text": "Output:" }, { "code": null, "e": 29243, "s": 29180, "text": "Example 3: This example illustrates different size form input." }, { "code": "<!DOCTYPE html><html> <head> <title>Bulma Input</title> <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.5/css/bulma.css'> <!-- custom css --> <style> div.columns{ margin-top: 80px; } </style> </head> <body> <div class='container'> <div class='columns is-mobile is-centered'> <div class='column is-5'> <div class=\"field\"> <div class=\"control\"> <input class=\"input is-small\" type=\"text\" placeholder='Small input'> </div> </div> <div class=\"field\"> <div class=\"control\"> <input class=\"input\" type=\"text\" placeholder='Normal Input'> </div> </div> <div class=\"field\"> <div class=\"control\"> <input class=\"input is-medium\" type=\"text\" placeholder='Medium Input'> </div> </div> <div class=\"field\"> <div class=\"control\"> <input class=\"input is-large\" type=\"text\" placeholder='Large Input'> </div> </div> </div> </div> </div> </body></html>", "e": 30549, "s": 29243, "text": null }, { "code": null, "e": 30557, "s": 30549, "text": "Output:" }, { "code": null, "e": 30625, "s": 30557, "text": "Example 4: This example illustrates different states of form input." }, { "code": "<!DOCTYPE html><html> <head> <title>Bulma Input</title> <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.5/css/bulma.css'> <!-- custom css --> <style> div.columns{ margin-top: 80px; } </style> </head> <body> <div class='container'> <div class='columns is-mobile is-centered'> <div class='column is-5'> <div class=\"field\"> <div class=\"control\"> <input class=\"input\" type=\"text\" placeholder='Normal Input'> </div> </div> <div class=\"field\"> <div class=\"control\"> <input class=\"input is-hovered\" type=\"text\" placeholder='Hovered Input'> </div> </div> <div class=\"field\"> <div class=\"control\"> <input class=\"input is-focused\" type=\"text\" placeholder='Focused Input'> </div> </div> <div class=\"field\"> <div class=\"control is-loading\"> <input class=\"input\" type=\"text\" placeholder=\"Loading input\"> </div> </div> </div> </div> </div> </body></html>", "e": 31904, "s": 30625, "text": null }, { "code": null, "e": 31912, "s": 31904, "text": "Output:" }, { "code": null, "e": 31984, "s": 31912, "text": "Example 5: This example illustrates form input with font awesome icons." }, { "code": "<!DOCTYPE html><html> <head> <title>Bulma Input</title> <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.5/css/bulma.css'> <!-- custom css --> <style> div.columns{ margin-top: 80px; } </style> </head> <body> <!-- font-awesome cdn --> <script src='https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.12.0-2/js/all.min.js'> </script> <div class='container'> <div class='columns is-mobile is-centered'> <div class='column is-5'> <div class=\"field\"> <div class=\"control has-icons-left\"> <input class=\"input\" type=\"text\" placeholder=\"Username\"> <span class=\"icon is-small is-left\"> <i class=\"fas fa-user\"></i> </span> </div> </div> <div class=\"field\"> <div class=\"control has-icons-left\"> <input class=\"input\" type=\"password\" placeholder=\"Password\"> <span class=\"icon is-small is-left\"> <i class=\"fas fa-lock\"></i> </span> </div> </div> </div> </div> </div> </body></html>", "e": 33231, "s": 31984, "text": null }, { "code": null, "e": 33239, "s": 33231, "text": "Output:" }, { "code": null, "e": 33304, "s": 33239, "text": "Example 6: This example illustrates rounded type of form inputs." }, { "code": "<!DOCTYPE html><html> <head> <title>Bulma Input</title> <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.5/css/bulma.css'> <!-- custom css --> <style> div.columns{ margin-top: 80px; } </style> </head> <body> <!-- font-awesome cdn --> <script src='https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.12.0-2/js/all.min.js'> </script> <div class='container'> <div class='columns is-mobile is-centered'> <div class='column is-5'> <div class=\"field\"> <div class=\"control has-icons-left\"> <input class=\"input is-rounded\" type=\"text\" placeholder=\"Username\"> <span class=\"icon is-small is-left\"> <i class=\"fas fa-user\"></i> </span> </div> </div> <div class=\"field\"> <div class=\"control has-icons-left\"> <input class=\"input is-rounded\" type=\"password\" placeholder=\"Password\"> <span class=\"icon is-small is-left\"> <i class=\"fas fa-lock\"></i> </span> </div> </div> </div> </div> </div> </body></html>", "e": 34576, "s": 33304, "text": null }, { "code": null, "e": 34585, "s": 34576, "text": "Output :" }, { "code": null, "e": 34591, "s": 34585, "text": "Bulma" }, { "code": null, "e": 34595, "s": 34591, "text": "CSS" }, { "code": null, "e": 34612, "s": 34595, "text": "Web Technologies" }, { "code": null, "e": 34710, "s": 34612, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34772, "s": 34710, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 34822, "s": 34772, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 34880, "s": 34822, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 34928, "s": 34880, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 34978, "s": 34928, "text": "CSS to put icon inside an input element in a form" }, { "code": null, "e": 35020, "s": 34978, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 35053, "s": 35020, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 35096, "s": 35053, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 35158, "s": 35096, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" } ]
Check if the given two matrices are mirror images of one another - GeeksforGeeks
23 Apr, 2021 Given two matrices mat1[][] and mat2[][] of size NxN. The task is to find if the given two matrices are mirror images of one another. Print “Yes” if the given two matrices are mirror images, otherwise print “No”. Two matrices mat1 and mat2 of size N*N are said to be mirror images of one another if for any valid index (i, j) of the matrix: mat1[i][j] = mat2[i][N-j-1] Examples: Input: mat1[][] = {{1, 2, 3}, {3, 4, 5}, {6, 7, 8}}, mat2[][] = {{3, 2, 1}, {5, 4, 3}, {8, 7, 6}} Output: Yes Input: mat1 = {{1, 2, 3}, {5, 4, 1}, {6, 7, 2}}; mat2 = {{3, 2, 1}, {5, 4, 1}, {2, 7, 6}}; Output: No Approach: The approach is based on the observation that a matrix is a mirror image of another only if the elements of each row of the first matrix are equal to the reversed row of elements of the other matrix. Follow the steps below : Traverse over the matrix mat1[][] row-wise from start to end and over mat2[][] row-wise from end to start. While traversing, if any element of mat1[][] is found to be not equal to the element at mat2[][], then print “No” After traversing both the matrices, if all the elements are found to be equal, print “Yes”. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation of// the above approach#include <bits/stdc++.h>using namespace std; // Function to check whether the// two matrices are mirror// of each othervoid mirrorMatrix(int mat1[][4], int mat2[][4], int N){ // Initialising row and column of // second matrix int row = 0; int col = 0; bool isMirrorImage = true; // Iterating over the matrices for (int i = 0; i < N; i++) { // Check row of first matrix with // reversed row of second matrix for (int j = N - 1; j >= 0; j--) { // If the element is not equal if (mat2[row][col] != mat1[i][j]) { isMirrorImage = false; } // Increment column col++; } // Reset column to 0 // for new row col = 0; // Increment row row++; } if (isMirrorImage) cout << "Yes"; else cout << "No";} // Driver codeint main(){ // Given 2 matrices int N = 4; int mat1[][4] = { { 1, 2, 3, 4 }, { 0, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; int mat2[][4] = { { 4, 3, 2, 1 }, { 8, 7, 6, 0 }, { 12, 11, 10, 9 }, { 16, 15, 14, 13 } }; // Function Call mirrorMatrix(mat1, mat2, N);} // Java implementation of// the above approachimport java.util.*;class GFG{ // Function to check whether the// two matrices are mirror// of each otherstatic void mirrorMatrix(int mat1[][], int mat2[][], int N){ // Initialising row and column of // second matrix int row = 0; int col = 0; boolean isMirrorImage = true; // Iterating over the matrices for (int i = 0; i < N; i++) { // Check row of first matrix with // reversed row of second matrix for (int j = N - 1; j >= 0; j--) { // If the element is not equal if (mat2[row][col] != mat1[i][j]) { isMirrorImage = false; } // Increment column col++; } // Reset column to 0 // for new row col = 0; // Increment row row++; } if (isMirrorImage) System.out.print("Yes"); else System.out.print("No");} // Driver codepublic static void main(String[] args){ // Given 2 matrices int N = 4; int mat1[][] = {{1, 2, 3, 4}, {0, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}}; int mat2[][] = {{4, 3, 2, 1}, {8, 7, 6, 0}, {12, 11, 10, 9}, {16, 15, 14, 13}}; // Function Call mirrorMatrix(mat1, mat2, N);}} // This code is contributed by 29AjayKumar # Python3 implementation of# the above approach # Function to check whether the# two matrices are mirror# of each otherdef mirrorMatrix(mat1, mat2, N): # Initialising row and column of # second matrix row = 0 col = 0 isMirrorImage = True # Iterating over the matrices for i in range(N): # Check row of first matrix with # reversed row of second matrix for j in range(N - 1, -1, -1): # If the element is not equal if (mat2[row][col] != mat1[i][j]): isMirrorImage = False # Increment column col += 1 # Reset column to 0 # for new row col = 0 # Increment row row += 1 if (isMirrorImage): print("Yes") else: print("No") # Driver codeif __name__ == '__main__': # Given 2 matrices N = 4 mat1 = [ [ 1, 2, 3, 4 ], [ 0, 6, 7, 8 ], [ 9, 10, 11, 12 ], [ 13, 14, 15, 16 ] ] mat2 = [ [ 4, 3, 2, 1 ], [ 8, 7, 6, 0 ], [ 12, 11, 10, 9 ], [ 16, 15, 14, 13 ] ] # Function call mirrorMatrix(mat1, mat2, N) # This code is contributed by mohit kumar 29 // C# implementation of// the above approachusing System;class GFG{ // Function to check whether the// two matrices are mirror// of each otherstatic void mirrorMatrix(int[,] mat1, int [,]mat2, int N){ // Initialising row and column of // second matrix int row = 0; int col = 0; bool isMirrorImage = true; // Iterating over the matrices for (int i = 0; i < N; i++) { // Check row of first matrix with // reversed row of second matrix for (int j = N - 1; j >= 0; j--) { // If the element is not equal if (mat2[row, col] != mat1[i, j]) { isMirrorImage = false; } // Increment column col++; } // Reset column to 0 // for new row col = 0; // Increment row row++; } if (isMirrorImage) Console.Write("Yes"); else Console.Write("No");} // Driver codepublic static void Main(String[] args){ // Given 2 matrices int N = 4; int [,]mat1 = {{1, 2, 3, 4}, {0, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}}; int [,]mat2 = {{4, 3, 2, 1}, {8, 7, 6, 0}, {12, 11, 10, 9}, {16, 15, 14, 13}}; // Function Call mirrorMatrix(mat1, mat2, N);}} // This code is contributed by shikhasingrajput <script> // Javascript implementation of// the above approach // Function to check whether the// two matrices are mirror// of each otherfunction mirrorMatrix(mat1, mat2, N){ // Initialising row and column of // second matrix let row = 0; let col = 0; let isMirrorImage = true; // Iterating over the matrices for (let i = 0; i < N; i++) { // Check row of first matrix with // reversed row of second matrix for (let j = N - 1; j >= 0; j--) { // If the element is not equal if (mat2[row][col] != mat1[i][j]) { isMirrorImage = false; } // Increment column col++; } // Reset column to 0 // for new row col = 0; // Increment row row++; } if (isMirrorImage) document.write("Yes"); else document.write("No");} // Driver code // Given 2 matrices let N = 4; let mat1 = [ [ 1, 2, 3, 4 ], [ 0, 6, 7, 8 ], [ 9, 10, 11, 12 ], [ 13, 14, 15, 16 ] ]; let mat2 = [ [ 4, 3, 2, 1 ], [ 8, 7, 6, 0 ], [ 12, 11, 10, 9 ], [ 16, 15, 14, 13 ] ]; // Function Call mirrorMatrix(mat1, mat2, N); </script> Yes Time complexity: O(N2) Auxiliary Space: O(1) mohit kumar 29 29AjayKumar shikhasingrajput rishavmahato348 Convert to Mirror Matrix Searching Searching Matrix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Flood fill Algorithm - how to implement fill() in paint? Breadth First Traversal ( BFS ) on a 2D array Program to find the Sum of each Row and each Column of a Matrix Python program to add two Matrices Mathematics | L U Decomposition of a System of Linear Equations Binary Search Maximum and minimum of an array using minimum number of comparisons Linear Search Find the Missing Number K'th Smallest/Largest Element in Unsorted Array | Set 1
[ { "code": null, "e": 24922, "s": 24894, "text": "\n23 Apr, 2021" }, { "code": null, "e": 25135, "s": 24922, "text": "Given two matrices mat1[][] and mat2[][] of size NxN. The task is to find if the given two matrices are mirror images of one another. Print “Yes” if the given two matrices are mirror images, otherwise print “No”." }, { "code": null, "e": 25265, "s": 25135, "text": "Two matrices mat1 and mat2 of size N*N are said to be mirror images of one another if for any valid index (i, j) of the matrix: " }, { "code": null, "e": 25293, "s": 25265, "text": "mat1[i][j] = mat2[i][N-j-1]" }, { "code": null, "e": 25307, "s": 25295, "text": "Examples: " }, { "code": null, "e": 25419, "s": 25307, "text": "Input: mat1[][] = {{1, 2, 3}, {3, 4, 5}, {6, 7, 8}}, mat2[][] = {{3, 2, 1}, {5, 4, 3}, {8, 7, 6}} Output: Yes " }, { "code": null, "e": 25523, "s": 25419, "text": "Input: mat1 = {{1, 2, 3}, {5, 4, 1}, {6, 7, 2}}; mat2 = {{3, 2, 1}, {5, 4, 1}, {2, 7, 6}}; Output: No " }, { "code": null, "e": 25760, "s": 25523, "text": "Approach: The approach is based on the observation that a matrix is a mirror image of another only if the elements of each row of the first matrix are equal to the reversed row of elements of the other matrix. Follow the steps below : " }, { "code": null, "e": 25867, "s": 25760, "text": "Traverse over the matrix mat1[][] row-wise from start to end and over mat2[][] row-wise from end to start." }, { "code": null, "e": 25981, "s": 25867, "text": "While traversing, if any element of mat1[][] is found to be not equal to the element at mat2[][], then print “No”" }, { "code": null, "e": 26073, "s": 25981, "text": "After traversing both the matrices, if all the elements are found to be equal, print “Yes”." }, { "code": null, "e": 26126, "s": 26073, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 26130, "s": 26126, "text": "C++" }, { "code": null, "e": 26135, "s": 26130, "text": "Java" }, { "code": null, "e": 26143, "s": 26135, "text": "Python3" }, { "code": null, "e": 26146, "s": 26143, "text": "C#" }, { "code": null, "e": 26157, "s": 26146, "text": "Javascript" }, { "code": "// C++ implementation of// the above approach#include <bits/stdc++.h>using namespace std; // Function to check whether the// two matrices are mirror// of each othervoid mirrorMatrix(int mat1[][4], int mat2[][4], int N){ // Initialising row and column of // second matrix int row = 0; int col = 0; bool isMirrorImage = true; // Iterating over the matrices for (int i = 0; i < N; i++) { // Check row of first matrix with // reversed row of second matrix for (int j = N - 1; j >= 0; j--) { // If the element is not equal if (mat2[row][col] != mat1[i][j]) { isMirrorImage = false; } // Increment column col++; } // Reset column to 0 // for new row col = 0; // Increment row row++; } if (isMirrorImage) cout << \"Yes\"; else cout << \"No\";} // Driver codeint main(){ // Given 2 matrices int N = 4; int mat1[][4] = { { 1, 2, 3, 4 }, { 0, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; int mat2[][4] = { { 4, 3, 2, 1 }, { 8, 7, 6, 0 }, { 12, 11, 10, 9 }, { 16, 15, 14, 13 } }; // Function Call mirrorMatrix(mat1, mat2, N);}", "e": 27524, "s": 26157, "text": null }, { "code": "// Java implementation of// the above approachimport java.util.*;class GFG{ // Function to check whether the// two matrices are mirror// of each otherstatic void mirrorMatrix(int mat1[][], int mat2[][], int N){ // Initialising row and column of // second matrix int row = 0; int col = 0; boolean isMirrorImage = true; // Iterating over the matrices for (int i = 0; i < N; i++) { // Check row of first matrix with // reversed row of second matrix for (int j = N - 1; j >= 0; j--) { // If the element is not equal if (mat2[row][col] != mat1[i][j]) { isMirrorImage = false; } // Increment column col++; } // Reset column to 0 // for new row col = 0; // Increment row row++; } if (isMirrorImage) System.out.print(\"Yes\"); else System.out.print(\"No\");} // Driver codepublic static void main(String[] args){ // Given 2 matrices int N = 4; int mat1[][] = {{1, 2, 3, 4}, {0, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}}; int mat2[][] = {{4, 3, 2, 1}, {8, 7, 6, 0}, {12, 11, 10, 9}, {16, 15, 14, 13}}; // Function Call mirrorMatrix(mat1, mat2, N);}} // This code is contributed by 29AjayKumar", "e": 28831, "s": 27524, "text": null }, { "code": "# Python3 implementation of# the above approach # Function to check whether the# two matrices are mirror# of each otherdef mirrorMatrix(mat1, mat2, N): # Initialising row and column of # second matrix row = 0 col = 0 isMirrorImage = True # Iterating over the matrices for i in range(N): # Check row of first matrix with # reversed row of second matrix for j in range(N - 1, -1, -1): # If the element is not equal if (mat2[row][col] != mat1[i][j]): isMirrorImage = False # Increment column col += 1 # Reset column to 0 # for new row col = 0 # Increment row row += 1 if (isMirrorImage): print(\"Yes\") else: print(\"No\") # Driver codeif __name__ == '__main__': # Given 2 matrices N = 4 mat1 = [ [ 1, 2, 3, 4 ], [ 0, 6, 7, 8 ], [ 9, 10, 11, 12 ], [ 13, 14, 15, 16 ] ] mat2 = [ [ 4, 3, 2, 1 ], [ 8, 7, 6, 0 ], [ 12, 11, 10, 9 ], [ 16, 15, 14, 13 ] ] # Function call mirrorMatrix(mat1, mat2, N) # This code is contributed by mohit kumar 29", "e": 30025, "s": 28831, "text": null }, { "code": "// C# implementation of// the above approachusing System;class GFG{ // Function to check whether the// two matrices are mirror// of each otherstatic void mirrorMatrix(int[,] mat1, int [,]mat2, int N){ // Initialising row and column of // second matrix int row = 0; int col = 0; bool isMirrorImage = true; // Iterating over the matrices for (int i = 0; i < N; i++) { // Check row of first matrix with // reversed row of second matrix for (int j = N - 1; j >= 0; j--) { // If the element is not equal if (mat2[row, col] != mat1[i, j]) { isMirrorImage = false; } // Increment column col++; } // Reset column to 0 // for new row col = 0; // Increment row row++; } if (isMirrorImage) Console.Write(\"Yes\"); else Console.Write(\"No\");} // Driver codepublic static void Main(String[] args){ // Given 2 matrices int N = 4; int [,]mat1 = {{1, 2, 3, 4}, {0, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}}; int [,]mat2 = {{4, 3, 2, 1}, {8, 7, 6, 0}, {12, 11, 10, 9}, {16, 15, 14, 13}}; // Function Call mirrorMatrix(mat1, mat2, N);}} // This code is contributed by shikhasingrajput", "e": 31310, "s": 30025, "text": null }, { "code": "<script> // Javascript implementation of// the above approach // Function to check whether the// two matrices are mirror// of each otherfunction mirrorMatrix(mat1, mat2, N){ // Initialising row and column of // second matrix let row = 0; let col = 0; let isMirrorImage = true; // Iterating over the matrices for (let i = 0; i < N; i++) { // Check row of first matrix with // reversed row of second matrix for (let j = N - 1; j >= 0; j--) { // If the element is not equal if (mat2[row][col] != mat1[i][j]) { isMirrorImage = false; } // Increment column col++; } // Reset column to 0 // for new row col = 0; // Increment row row++; } if (isMirrorImage) document.write(\"Yes\"); else document.write(\"No\");} // Driver code // Given 2 matrices let N = 4; let mat1 = [ [ 1, 2, 3, 4 ], [ 0, 6, 7, 8 ], [ 9, 10, 11, 12 ], [ 13, 14, 15, 16 ] ]; let mat2 = [ [ 4, 3, 2, 1 ], [ 8, 7, 6, 0 ], [ 12, 11, 10, 9 ], [ 16, 15, 14, 13 ] ]; // Function Call mirrorMatrix(mat1, mat2, N); </script>", "e": 32617, "s": 31310, "text": null }, { "code": null, "e": 32621, "s": 32617, "text": "Yes" }, { "code": null, "e": 32669, "s": 32623, "text": "Time complexity: O(N2) Auxiliary Space: O(1) " }, { "code": null, "e": 32684, "s": 32669, "text": "mohit kumar 29" }, { "code": null, "e": 32696, "s": 32684, "text": "29AjayKumar" }, { "code": null, "e": 32713, "s": 32696, "text": "shikhasingrajput" }, { "code": null, "e": 32729, "s": 32713, "text": "rishavmahato348" }, { "code": null, "e": 32747, "s": 32729, "text": "Convert to Mirror" }, { "code": null, "e": 32754, "s": 32747, "text": "Matrix" }, { "code": null, "e": 32764, "s": 32754, "text": "Searching" }, { "code": null, "e": 32774, "s": 32764, "text": "Searching" }, { "code": null, "e": 32781, "s": 32774, "text": "Matrix" }, { "code": null, "e": 32879, "s": 32781, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32936, "s": 32879, "text": "Flood fill Algorithm - how to implement fill() in paint?" }, { "code": null, "e": 32982, "s": 32936, "text": "Breadth First Traversal ( BFS ) on a 2D array" }, { "code": null, "e": 33046, "s": 32982, "text": "Program to find the Sum of each Row and each Column of a Matrix" }, { "code": null, "e": 33081, "s": 33046, "text": "Python program to add two Matrices" }, { "code": null, "e": 33145, "s": 33081, "text": "Mathematics | L U Decomposition of a System of Linear Equations" }, { "code": null, "e": 33159, "s": 33145, "text": "Binary Search" }, { "code": null, "e": 33227, "s": 33159, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 33241, "s": 33227, "text": "Linear Search" }, { "code": null, "e": 33265, "s": 33241, "text": "Find the Missing Number" } ]
Write an example program on structure using C language
The structure is a collection of different datatype variables, grouped together under a single name Syntax. The general form of structure declaration is as follows − datatype member1; struct tagname{ datatype member2; datatype member n; }; Here, struct - keyword tagname - specifies name of structure member1, member2 - specifies the data items that makeup structure. struct book{ int pages; char author [30]; float price; }; There are three ways of declaring structure variables. They are as follows − 1) struct book{ int pages; char author[30]; float price; }b; 2) struct{ int pages; char author[30]; float price; }b; 3) struct book{ int pages; char author[30]; float price; }; struct book b; The link between a member and a structure variable is established using the member operator (or) dot operator. The link between a member and a structure variable is established using the member operator (or) dot operator. Initialization can be done in the following ways − Initialization can be done in the following ways − struct book{ int pages; char author[30]; float price; } b = {100, “balu", 325.75}; struct book{ int pages; char author[30]; float price; }; struct book b = {100, “balu", 325.75}; struct book{ int pages; char author[30]; float price; } ; struct book b; b. pages = 100; strcpy (b.author, “balu"); b.price = 325.75; struct book{ int pages; char author[30]; float price; } ; struct book b; scanf (“%d", &b.pages); scanf (“%s", b.author); scanf (“%f", &b. price); We can print the contents of either of the above structures in the main method as shown below − main ( ){ struct book b; clrscr ( ); printf ( "enter no of pages, author, price of book"); scanf ("%d%s%f", &b.pages, b.author, &b.price); printf("Details of book are"); printf("pages =%d, author = %s, price = %f", b.pages, b.author, b.price); getch(); } Following is another example of structures − Live Demo #include<stdio.h> struct aaa{ struct aaa *prev; int i; struct aaa *next; }; main(){ struct aaa abc,def,ghi,jkl; int x=100; abc.i=0; abc.prev=&jkl; abc.next=&def; def.i=1; def.prev=&abc; def.next=&ghi; ghi.i=2;ghi.prev=&def; ghi.next=&jkl; jkl.i=3; jkl.prev=&ghi; jkl.next=&abc; x=abc.next->next->prev->next->i; printf("%d",x); } 2
[ { "code": null, "e": 1170, "s": 1062, "text": "The structure is a collection of different datatype variables, grouped together under a single name Syntax." }, { "code": null, "e": 1228, "s": 1170, "text": "The general form of structure declaration is as follows −" }, { "code": null, "e": 1308, "s": 1228, "text": "datatype member1;\nstruct tagname{\n datatype member2;\n datatype member n;\n};" }, { "code": null, "e": 1331, "s": 1308, "text": "Here, struct - keyword" }, { "code": null, "e": 1378, "s": 1331, "text": " tagname - specifies name of structure" }, { "code": null, "e": 1454, "s": 1378, "text": " member1, member2 - specifies the data items that makeup structure." }, { "code": null, "e": 1521, "s": 1454, "text": "struct book{\n int pages;\n char author [30];\n float price;\n};" }, { "code": null, "e": 1598, "s": 1521, "text": "There are three ways of declaring structure variables. They are as follows −" }, { "code": null, "e": 1817, "s": 1598, "text": "1) struct book{\n int pages;\n char author[30];\n float price;\n}b;\n2) struct{\n int pages;\n char author[30];\n float price;\n}b;\n3) struct book{\n int pages;\n char author[30];\n float price;\n};\nstruct book b;" }, { "code": null, "e": 1928, "s": 1817, "text": "The link between a member and a structure variable is established using the member operator (or) dot operator." }, { "code": null, "e": 2039, "s": 1928, "text": "The link between a member and a structure variable is established using the member operator (or) dot operator." }, { "code": null, "e": 2090, "s": 2039, "text": "Initialization can be done in the following ways −" }, { "code": null, "e": 2141, "s": 2090, "text": "Initialization can be done in the following ways −" }, { "code": null, "e": 2233, "s": 2141, "text": "struct book{\n int pages;\n char author[30];\n float price;\n} b = {100, “balu\", 325.75};" }, { "code": null, "e": 2338, "s": 2233, "text": "struct book{\n int pages;\n char author[30];\n float price;\n};\nstruct book b = {100, “balu\", 325.75};" }, { "code": null, "e": 2490, "s": 2338, "text": "struct book{\n int pages;\n char author[30];\n float price;\n} ;\nstruct book b;\n b. pages = 100;\n strcpy (b.author, “balu\");\n b.price = 325.75;" }, { "code": null, "e": 2654, "s": 2490, "text": "struct book{\n int pages;\n char author[30];\n float price;\n} ;\nstruct book b;\n scanf (“%d\", &b.pages);\n scanf (“%s\", b.author);\n scanf (“%f\", &b. price);" }, { "code": null, "e": 2750, "s": 2654, "text": "We can print the contents of either of the above structures in the main method as shown below −" }, { "code": null, "e": 3026, "s": 2750, "text": "main ( ){\n struct book b;\n clrscr ( );\n printf ( \"enter no of pages, author, price of book\");\n scanf (\"%d%s%f\", &b.pages, b.author, &b.price);\n printf(\"Details of book are\");\n printf(\"pages =%d, author = %s, price = %f\", b.pages, b.author, b.price);\n getch();\n}" }, { "code": null, "e": 3071, "s": 3026, "text": "Following is another example of structures −" }, { "code": null, "e": 3082, "s": 3071, "text": " Live Demo" }, { "code": null, "e": 3465, "s": 3082, "text": "#include<stdio.h>\nstruct aaa{\n struct aaa *prev;\n int i;\n struct aaa *next;\n};\nmain(){\n struct aaa abc,def,ghi,jkl;\n int x=100;\n abc.i=0;\n abc.prev=&jkl;\n abc.next=&def;\n def.i=1;\n def.prev=&abc;\n def.next=&ghi;\n ghi.i=2;ghi.prev=&def;\n ghi.next=&jkl;\n jkl.i=3;\n jkl.prev=&ghi;\n jkl.next=&abc;\n x=abc.next->next->prev->next->i;\n printf(\"%d\",x);\n}" }, { "code": null, "e": 3467, "s": 3465, "text": "2" } ]
How to find the sum of column values of an R dataframe? - GeeksforGeeks
30 May, 2021 In this article, we are going to find the sum of the column values of a dataframe in R with the use of sum() function. Syntax: sum(dataframe$column_name) A dataframe can be created with the use of data.frame() function that is pre-defined in the R library. This function accepts the elements and the number of rows and columns that are required for the dataframe to be created. Following is an R Program for the creation of dataframe: R # R Program to create a dataframe # Creating a Data Framedf<-data.frame(row1 = 0:2, row2 = 3:5, row3 = 6:8)print(df) Output: row1 row2 row3 1 0 3 6 2 1 4 7 3 2 5 8 R language provides an in-built function sum() to compute the mean of a dataframe. Following is an R program for the implementation of sum(). R # Computing sum of column values # Using sum() functionsum(df$row1)sum(df$row2) Output: 3 12 Example 2: R # R program to illustrate dataframe Roll_num = c(01, 02, 03)Age = c(22, 25, 45)Marks = c(70, 80, 90) # To create dataframe use data.frame command and # then pass each of the vectors # we have created as arguments # to the function data.frame() df = data.frame(Roll_num, Age, Marks) print(df) # Computing Sum using sum() functionsum(df$Roll_num)sum(df$Age)sum(df$Marks) Output: 6 92 240 Example 3: R # R program to illustrate dataframe ID = c(01, 02, 03)Age = c(25, 30, 70)Salary = c(70000, 85000, 40000) # To create dataframe use data.frame command and # then pass each of the vectors # we have created as arguments # to the function data.frame() df = data.frame(ID, Age, Salary) # Computing total salarycat("Total Salary =", sum(df$Salary)) Output: 195000 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 May, 2021" }, { "code": null, "e": 25361, "s": 25242, "text": "In this article, we are going to find the sum of the column values of a dataframe in R with the use of sum() function." }, { "code": null, "e": 25369, "s": 25361, "text": "Syntax:" }, { "code": null, "e": 25396, "s": 25369, "text": "sum(dataframe$column_name)" }, { "code": null, "e": 25620, "s": 25396, "text": "A dataframe can be created with the use of data.frame() function that is pre-defined in the R library. This function accepts the elements and the number of rows and columns that are required for the dataframe to be created." }, { "code": null, "e": 25677, "s": 25620, "text": "Following is an R Program for the creation of dataframe:" }, { "code": null, "e": 25679, "s": 25677, "text": "R" }, { "code": "# R Program to create a dataframe # Creating a Data Framedf<-data.frame(row1 = 0:2, row2 = 3:5, row3 = 6:8)print(df)", "e": 25797, "s": 25679, "text": null }, { "code": null, "e": 25805, "s": 25797, "text": "Output:" }, { "code": null, "e": 25873, "s": 25805, "text": " row1 row2 row3\n1 0 3 6\n2 1 4 7\n3 2 5 8" }, { "code": null, "e": 26015, "s": 25873, "text": "R language provides an in-built function sum() to compute the mean of a dataframe. Following is an R program for the implementation of sum()." }, { "code": null, "e": 26017, "s": 26015, "text": "R" }, { "code": "# Computing sum of column values # Using sum() functionsum(df$row1)sum(df$row2)", "e": 26098, "s": 26017, "text": null }, { "code": null, "e": 26106, "s": 26098, "text": "Output:" }, { "code": null, "e": 26111, "s": 26106, "text": "3\n12" }, { "code": null, "e": 26122, "s": 26111, "text": "Example 2:" }, { "code": null, "e": 26124, "s": 26122, "text": "R" }, { "code": "# R program to illustrate dataframe Roll_num = c(01, 02, 03)Age = c(22, 25, 45)Marks = c(70, 80, 90) # To create dataframe use data.frame command and # then pass each of the vectors # we have created as arguments # to the function data.frame() df = data.frame(Roll_num, Age, Marks) print(df) # Computing Sum using sum() functionsum(df$Roll_num)sum(df$Age)sum(df$Marks)", "e": 26498, "s": 26124, "text": null }, { "code": null, "e": 26506, "s": 26498, "text": "Output:" }, { "code": null, "e": 26515, "s": 26506, "text": "6\n92\n240" }, { "code": null, "e": 26526, "s": 26515, "text": "Example 3:" }, { "code": null, "e": 26528, "s": 26526, "text": "R" }, { "code": "# R program to illustrate dataframe ID = c(01, 02, 03)Age = c(25, 30, 70)Salary = c(70000, 85000, 40000) # To create dataframe use data.frame command and # then pass each of the vectors # we have created as arguments # to the function data.frame() df = data.frame(ID, Age, Salary) # Computing total salarycat(\"Total Salary =\", sum(df$Salary))", "e": 26877, "s": 26528, "text": null }, { "code": null, "e": 26885, "s": 26877, "text": "Output:" }, { "code": null, "e": 26892, "s": 26885, "text": "195000" }, { "code": null, "e": 26899, "s": 26892, "text": "Picked" }, { "code": null, "e": 26920, "s": 26899, "text": "R DataFrame-Programs" }, { "code": null, "e": 26932, "s": 26920, "text": "R-DataFrame" }, { "code": null, "e": 26943, "s": 26932, "text": "R Language" }, { "code": null, "e": 26954, "s": 26943, "text": "R Programs" }, { "code": null, "e": 27052, "s": 26954, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27104, "s": 27052, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 27142, "s": 27104, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 27177, "s": 27142, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 27235, "s": 27177, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 27284, "s": 27235, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 27342, "s": 27284, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 27391, "s": 27342, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 27441, "s": 27391, "text": "How to filter R dataframe by multiple conditions?" }, { "code": null, "e": 27484, "s": 27441, "text": "Replace Specific Characters in String in R" } ]
Calculate n + nn + nnn + ... + n(m times) in Python program
We are going to write a program that calculates the following series in Python. Examine the example inputs and outputs for the program that we are going to write. Input: 34 3 + 33 + 333 + 3333 Output: 3702 Input: 5 5 5 + 55 + 555 + 5555 + 55555 Output: 61725 So, we will have two numbers, and we have to calculate the sum of the series generated as above. Follow the below steps to achieve the output. 1. Initialize the number let's say n and m. 2. Initialize a variable with the value n let's say change. 3. Intialize a variable s to zero. 4. Write a loop which iterates m times. 4.1. Add change to the s. 4.2. Update the value of change to get next number in the series. 5. Print the sum at the end of the program. You have to create a general formula to generate numbers in the series. Try to get it as your own. If you stuck at the logic, see the code below. ## intializing n and m n, m = 3, 4 ## initializing change variable to n change = n ## initializing sum to 0 s = 0 ## loop for i in range(m): ## adding change to s s += change ## updating the value of change change = change * 10 + n ## printing the s print(s) If you run the above program, you will get the following output. 3702 Let's see another example with different values as we discussed in the examples. ## intializing n and m n, m = 5, 5 ## initializing change variable to n change = n ## initializing sum to 0 s = 0 ## loop for i in range(m): ## adding change to s s += change ## updating the value of change change = change * 10 + n ## printing the s print(s) If you run the above program, you will get the following output. 61725 If you have any doubts regarding the tutorial, mention them in the comment section.
[ { "code": null, "e": 1225, "s": 1062, "text": "We are going to write a program that calculates the following series in Python. Examine the example inputs and outputs for the program that we are going to write." }, { "code": null, "e": 1268, "s": 1225, "text": "Input:\n34\n3 + 33 + 333 + 3333\nOutput:\n3702" }, { "code": null, "e": 1321, "s": 1268, "text": "Input:\n5 5 5 + 55 + 555 + 5555 + 55555\nOutput:\n61725" }, { "code": null, "e": 1464, "s": 1321, "text": "So, we will have two numbers, and we have to calculate the sum of the series generated as above. Follow the below steps to achieve the output." }, { "code": null, "e": 1785, "s": 1464, "text": "1. Initialize the number let's say n and m.\n2. Initialize a variable with the value n let's say change.\n3. Intialize a variable s to zero.\n4. Write a loop which iterates m times.\n 4.1. Add change to the s.\n 4.2. Update the value of change to get next number in the series.\n5. Print the sum at the end of the program." }, { "code": null, "e": 1931, "s": 1785, "text": "You have to create a general formula to generate numbers in the series. Try to get it as your own. If you stuck at the logic, see the code below." }, { "code": null, "e": 2202, "s": 1931, "text": "## intializing n and m\nn, m = 3, 4\n## initializing change variable to n\nchange = n\n## initializing sum to 0\ns = 0\n## loop\nfor i in range(m):\n ## adding change to s\n s += change\n ## updating the value of change\n change = change * 10 + n\n## printing the s\nprint(s)" }, { "code": null, "e": 2267, "s": 2202, "text": "If you run the above program, you will get the following output." }, { "code": null, "e": 2272, "s": 2267, "text": "3702" }, { "code": null, "e": 2353, "s": 2272, "text": "Let's see another example with different values as we discussed in the examples." }, { "code": null, "e": 2624, "s": 2353, "text": "## intializing n and m\nn, m = 5, 5\n## initializing change variable to n\nchange = n\n## initializing sum to 0\ns = 0\n## loop\nfor i in range(m):\n ## adding change to s\n s += change\n ## updating the value of change\n change = change * 10 + n\n## printing the s\nprint(s)" }, { "code": null, "e": 2689, "s": 2624, "text": "If you run the above program, you will get the following output." }, { "code": null, "e": 2695, "s": 2689, "text": "61725" }, { "code": null, "e": 2779, "s": 2695, "text": "If you have any doubts regarding the tutorial, mention them in the comment section." } ]
How to install Python on Linux? - GeeksforGeeks
22 Jan, 2020 Prerequisite: Python Language Introduction Before we start with how to install Python3 on Linux, let’s first go through the basic introduction to Python. Python is a widely-used general-purpose, high-level programming language. Python is a programming language that lets you work quickly and integrate systems more efficiently. There are two major Python versions- Python 2 and Python 3. Both are quite different. Python is a lot easier to code and learn. Python programs can be written on any plain text editor like notepad, notepad++, or anything of that sort. One can also use an online IDE for writing Python codes or can even install one on their system to make it more feasible to write these codes because IDEs provide a lot of features like intuitive code editor, debugger, compiler, etc.To begin with, writing Python Codes and performing various intriguing and useful operations, one must have Python installed on their System. This can be done by following the step by step instructions provided below: Most of the Linux OS has Python pre-installed. To check if your device is pre-installed with Python or not, just go to terminal using Ctrl+Alt+T Now run the following command:For Python2 python --version For Python3.x python3.x --version If Python is already installed, it will generate a message with the Python version available. Before starting with the installation process, you need to download it. For that all versions of Python for Linux are available on python.org. Download the required version and follow the further instructions for the installation process. Beginning the installation. For almost every Linux system, the following command could be used to install Python directly: $ sudo apt-get install python3.8 Getting Started: Assigning DiskSpace: Fetching and Installing Packages: Getting through the installation process: Finished Installation: To verify the installation enter the following commands in your Terminal. python3.8 Let’s consider a simple Hello World Program. # Python program to print# Hello World print("Hello World") python-basics 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 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 Create a Pandas DataFrame from Lists sum() function in Python
[ { "code": null, "e": 24386, "s": 24358, "text": "\n22 Jan, 2020" }, { "code": null, "e": 24800, "s": 24386, "text": "Prerequisite: Python Language Introduction Before we start with how to install Python3 on Linux, let’s first go through the basic introduction to Python. Python is a widely-used general-purpose, high-level programming language. Python is a programming language that lets you work quickly and integrate systems more efficiently. There are two major Python versions- Python 2 and Python 3. Both are quite different." }, { "code": null, "e": 25399, "s": 24800, "text": "Python is a lot easier to code and learn. Python programs can be written on any plain text editor like notepad, notepad++, or anything of that sort. One can also use an online IDE for writing Python codes or can even install one on their system to make it more feasible to write these codes because IDEs provide a lot of features like intuitive code editor, debugger, compiler, etc.To begin with, writing Python Codes and performing various intriguing and useful operations, one must have Python installed on their System. This can be done by following the step by step instructions provided below:" }, { "code": null, "e": 25544, "s": 25399, "text": "Most of the Linux OS has Python pre-installed. To check if your device is pre-installed with Python or not, just go to terminal using Ctrl+Alt+T" }, { "code": null, "e": 25586, "s": 25544, "text": "Now run the following command:For Python2" }, { "code": null, "e": 25604, "s": 25586, "text": "python --version\n" }, { "code": null, "e": 25618, "s": 25604, "text": "For Python3.x" }, { "code": null, "e": 25639, "s": 25618, "text": "python3.x --version\n" }, { "code": null, "e": 25733, "s": 25639, "text": "If Python is already installed, it will generate a message with the Python version available." }, { "code": null, "e": 25876, "s": 25733, "text": "Before starting with the installation process, you need to download it. For that all versions of Python for Linux are available on python.org." }, { "code": null, "e": 25972, "s": 25876, "text": "Download the required version and follow the further instructions for the installation process." }, { "code": null, "e": 26000, "s": 25972, "text": "Beginning the installation." }, { "code": null, "e": 26095, "s": 26000, "text": "For almost every Linux system, the following command could be used to install Python directly:" }, { "code": null, "e": 26129, "s": 26095, "text": "$ sudo apt-get install python3.8\n" }, { "code": null, "e": 26146, "s": 26129, "text": "Getting Started:" }, { "code": null, "e": 26167, "s": 26146, "text": "Assigning DiskSpace:" }, { "code": null, "e": 26201, "s": 26167, "text": "Fetching and Installing Packages:" }, { "code": null, "e": 26243, "s": 26201, "text": "Getting through the installation process:" }, { "code": null, "e": 26266, "s": 26243, "text": "Finished Installation:" }, { "code": null, "e": 26340, "s": 26266, "text": "To verify the installation enter the following commands in your Terminal." }, { "code": null, "e": 26351, "s": 26340, "text": "python3.8\n" }, { "code": null, "e": 26396, "s": 26351, "text": "Let’s consider a simple Hello World Program." }, { "code": "# Python program to print# Hello World print(\"Hello World\")", "e": 26457, "s": 26396, "text": null }, { "code": null, "e": 26471, "s": 26457, "text": "python-basics" }, { "code": null, "e": 26478, "s": 26471, "text": "Python" }, { "code": null, "e": 26576, "s": 26478, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26585, "s": 26576, "text": "Comments" }, { "code": null, "e": 26598, "s": 26585, "text": "Old Comments" }, { "code": null, "e": 26616, "s": 26598, "text": "Python Dictionary" }, { "code": null, "e": 26651, "s": 26616, "text": "Read a file line by line in Python" }, { "code": null, "e": 26673, "s": 26651, "text": "Enumerate() in Python" }, { "code": null, "e": 26703, "s": 26673, "text": "Iterate over a list in Python" }, { "code": null, "e": 26745, "s": 26703, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 26771, "s": 26745, "text": "Python String | replace()" }, { "code": null, "e": 26814, "s": 26771, "text": "Python program to convert a list to string" }, { "code": null, "e": 26858, "s": 26814, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 26895, "s": 26858, "text": "Create a Pandas DataFrame from Lists" } ]