title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
How to get the width of device screen in JavaScript ? - GeeksforGeeks
28 Jun, 2019 Given an HTML document which is running on a device. The task is to find the width of the working screen device using JavaScript. Example 1: This example uses window.innerWidth to get the width of device screen. The innerWidth property is used to return the width of the device. <!DOCTYPE HTML> <html> <head> <title> How to get the device screen width in JavaScript ? </title> </head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <p id = "GFG_UP" style = "font-size: 19px; font-weight: bold;"> </p> <button onclick = "GFG_Fun()"> click here </button> <p id = "GFG_DOWN" style = "color: green; font-size: 24px; font-weight: bold;"> </p> <!-- Script to display the device screen width --> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); el_up.innerHTML = "Click on the button to get the" + " width of the device's screen"; function GFG_Fun() { var width = window.innerWidth; el_down.innerHTML = width + " pixels"; } </script> </body> </html> Output: Before clicking on the button: After clicking on the button: Example 2: This example uses document.documentElement.clientWidth method to get the width of device screen. <!DOCTYPE HTML> <html> <head> <title> How to get the device screen width in JavaScript ? </title> </head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <p id = "GFG_UP" style = "font-size: 19px; font-weight: bold;"> </p> <button onclick = "GFG_Fun()"> click here </button> <p id = "GFG_DOWN" style = "color: green; font-size: 24px; font-weight: bold;"> </p> <!-- Script to display the device screen width --> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); el_up.innerHTML = "Click on the button to get the" + " width of the device's screen"; function GFG_Fun() { el_down.innerHTML = document.documentElement.clientWidth + " pixels"; } </script> </body> </html> Output: Before clicking on the button: After clicking on the button: JavaScript-Misc JavaScript Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Difference between var, let and const keywords in JavaScript Difference Between PUT and PATCH Request JavaScript | Promises How to get character array from string in JavaScript? Remove elements from a JavaScript Array Installation of Node.js on Linux How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 26545, "s": 26517, "text": "\n28 Jun, 2019" }, { "code": null, "e": 26675, "s": 26545, "text": "Given an HTML document which is running on a device. The task is to find the width of the working screen device using JavaScript." }, { "code": null, "e": 26824, "s": 26675, "text": "Example 1: This example uses window.innerWidth to get the width of device screen. The innerWidth property is used to return the width of the device." }, { "code": "<!DOCTYPE HTML> <html> <head> <title> How to get the device screen width in JavaScript ? </title> </head> <body style = \"text-align:center;\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <p id = \"GFG_UP\" style = \"font-size: 19px; font-weight: bold;\"> </p> <button onclick = \"GFG_Fun()\"> click here </button> <p id = \"GFG_DOWN\" style = \"color: green; font-size: 24px; font-weight: bold;\"> </p> <!-- Script to display the device screen width --> <script> var el_up = document.getElementById(\"GFG_UP\"); var el_down = document.getElementById(\"GFG_DOWN\"); el_up.innerHTML = \"Click on the button to get the\" + \" width of the device's screen\"; function GFG_Fun() { var width = window.innerWidth; el_down.innerHTML = width + \" pixels\"; } </script> </body> </html> ", "e": 27951, "s": 26824, "text": null }, { "code": null, "e": 27959, "s": 27951, "text": "Output:" }, { "code": null, "e": 27990, "s": 27959, "text": "Before clicking on the button:" }, { "code": null, "e": 28020, "s": 27990, "text": "After clicking on the button:" }, { "code": null, "e": 28128, "s": 28020, "text": "Example 2: This example uses document.documentElement.clientWidth method to get the width of device screen." }, { "code": "<!DOCTYPE HTML> <html> <head> <title> How to get the device screen width in JavaScript ? </title> </head> <body style = \"text-align:center;\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <p id = \"GFG_UP\" style = \"font-size: 19px; font-weight: bold;\"> </p> <button onclick = \"GFG_Fun()\"> click here </button> <p id = \"GFG_DOWN\" style = \"color: green; font-size: 24px; font-weight: bold;\"> </p> <!-- Script to display the device screen width --> <script> var el_up = document.getElementById(\"GFG_UP\"); var el_down = document.getElementById(\"GFG_DOWN\"); el_up.innerHTML = \"Click on the button to get the\" + \" width of the device's screen\"; function GFG_Fun() { el_down.innerHTML = document.documentElement.clientWidth + \" pixels\"; } </script> </body> </html>", "e": 29239, "s": 28128, "text": null }, { "code": null, "e": 29247, "s": 29239, "text": "Output:" }, { "code": null, "e": 29278, "s": 29247, "text": "Before clicking on the button:" }, { "code": null, "e": 29308, "s": 29278, "text": "After clicking on the button:" }, { "code": null, "e": 29324, "s": 29308, "text": "JavaScript-Misc" }, { "code": null, "e": 29335, "s": 29324, "text": "JavaScript" }, { "code": null, "e": 29352, "s": 29335, "text": "Web Technologies" }, { "code": null, "e": 29379, "s": 29352, "text": "Web technologies Questions" }, { "code": null, "e": 29477, "s": 29379, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29517, "s": 29477, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 29578, "s": 29517, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 29619, "s": 29578, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 29641, "s": 29619, "text": "JavaScript | Promises" }, { "code": null, "e": 29695, "s": 29641, "text": "How to get character array from string in JavaScript?" }, { "code": null, "e": 29735, "s": 29695, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 29768, "s": 29735, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 29811, "s": 29768, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 29861, "s": 29811, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Check if the Object is a Matrix in R Programming - is.matrix() Function - GeeksforGeeks
12 Jun, 2020 is.matrix() function in R Language is used to return TRUE if the specified data is in the form of matrix else return FALSE. Syntax: is.matrix(x) Parameters:x: specified matrix Example 1: # R program to illustrate# is.matrix function # Specifying some different types of arraysA <- matrix(c(1:5))B <- matrix(c(1:12), nrow = 4, byrow = TRUE)C <- matrix(c(1:12), nrow = 4, byrow = FALSE) # Calling is.matrix() functionis.matrix(A)is.matrix(B)is.matrix(C) Output: [1] TRUE [1] TRUE [1] TRUE Example 2: # R program to illustrate# is.matrix function # Specifying Biochemical oxygen demand datax <- BOD # Calling is.matrix() functionis.matrix(x) # Calling is.matrix() function# over different types of datais.matrix(4)is.matrix("2")is.matrix("a") Output: [1] FALSE [1] FALSE [1] FALSE [1] FALSE R Matrix-Function R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Filter data by multiple conditions in R using Dplyr Loops in R (for, while, repeat) Change Color of Bars in Barchart using ggplot2 in R How to change Row Names of DataFrame in R ? Group by function in R using Dplyr How to Change Axis Scales in R Plots? How to Split Column Into Multiple Columns in R DataFrame? K-Means Clustering in R Programming Replace Specific Characters in String in R Remove rows with NA in one column of R DataFrame
[ { "code": null, "e": 26103, "s": 26075, "text": "\n12 Jun, 2020" }, { "code": null, "e": 26227, "s": 26103, "text": "is.matrix() function in R Language is used to return TRUE if the specified data is in the form of matrix else return FALSE." }, { "code": null, "e": 26248, "s": 26227, "text": "Syntax: is.matrix(x)" }, { "code": null, "e": 26279, "s": 26248, "text": "Parameters:x: specified matrix" }, { "code": null, "e": 26290, "s": 26279, "text": "Example 1:" }, { "code": "# R program to illustrate# is.matrix function # Specifying some different types of arraysA <- matrix(c(1:5))B <- matrix(c(1:12), nrow = 4, byrow = TRUE)C <- matrix(c(1:12), nrow = 4, byrow = FALSE) # Calling is.matrix() functionis.matrix(A)is.matrix(B)is.matrix(C)", "e": 26557, "s": 26290, "text": null }, { "code": null, "e": 26565, "s": 26557, "text": "Output:" }, { "code": null, "e": 26593, "s": 26565, "text": "[1] TRUE\n[1] TRUE\n[1] TRUE\n" }, { "code": null, "e": 26604, "s": 26593, "text": "Example 2:" }, { "code": "# R program to illustrate# is.matrix function # Specifying Biochemical oxygen demand datax <- BOD # Calling is.matrix() functionis.matrix(x) # Calling is.matrix() function# over different types of datais.matrix(4)is.matrix(\"2\")is.matrix(\"a\")", "e": 26849, "s": 26604, "text": null }, { "code": null, "e": 26857, "s": 26849, "text": "Output:" }, { "code": null, "e": 26898, "s": 26857, "text": "[1] FALSE\n[1] FALSE\n[1] FALSE\n[1] FALSE\n" }, { "code": null, "e": 26916, "s": 26898, "text": "R Matrix-Function" }, { "code": null, "e": 26927, "s": 26916, "text": "R Language" }, { "code": null, "e": 27025, "s": 26927, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27077, "s": 27025, "text": "Filter data by multiple conditions in R using Dplyr" }, { "code": null, "e": 27109, "s": 27077, "text": "Loops in R (for, while, repeat)" }, { "code": null, "e": 27161, "s": 27109, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 27205, "s": 27161, "text": "How to change Row Names of DataFrame in R ?" }, { "code": null, "e": 27240, "s": 27205, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 27278, "s": 27240, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 27336, "s": 27278, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 27372, "s": 27336, "text": "K-Means Clustering in R Programming" }, { "code": null, "e": 27415, "s": 27372, "text": "Replace Specific Characters in String in R" } ]
Python OpenCV - Depth map from Stereo Images - GeeksforGeeks
12 Dec, 2021 OpenCV is the huge open-source library for the computer vision, machine learning, and image processing and now it plays a major role in real-time operation which is very important in today’s systems.Note: For more information, refer to Introduction to OpenCV Depth Map : A depth map is a picture where every pixel has depth information(rather than RGB) and it normally represented as a grayscale picture. Depth information means the distance of surface of scene objects from a viewpoint. An example of pixel value depth map can be found here : Pixel Value Depth Map using Histograms Stereo Images : Two images with slight offset. For example, take a picture of an object from the center. Move your camera to your right by 6cms while keeping the object at the center of the image. Look for the same thing in both pictures and infer depth from the difference in position. This is called stereo matching. To have best results, avoid distortions. Approach Collect or take stereo images. Import OpenCV and matplotlib libraries. Read both left and right images. Calculate disparity using stereo.compute. Example :Sample Images: Left Right Python3 # import OpenCV and pyplotimport cv2 as cvfrom matplotlib import pyplot as plt # read left and right imagesimgR = cv.imread('right.png', 0)imgL = cv.imread('left.png', 0) # creates StereoBm objectstereo = cv.StereoBM_create(numDisparities = 16, blockSize = 15) # computes disparitydisparity = stereo.compute(imgL, imgR) # displays image as grayscale and plottedplt.imshow(disparity, 'gray')plt.show() Output: Disparity Map Output adnanirshad158 Python-OpenCV Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | os.path.join() method Python | Get unique values from a list Create a directory in Python Defaultdict in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n12 Dec, 2021" }, { "code": null, "e": 25796, "s": 25537, "text": "OpenCV is the huge open-source library for the computer vision, machine learning, and image processing and now it plays a major role in real-time operation which is very important in today’s systems.Note: For more information, refer to Introduction to OpenCV" }, { "code": null, "e": 26120, "s": 25796, "text": "Depth Map : A depth map is a picture where every pixel has depth information(rather than RGB) and it normally represented as a grayscale picture. Depth information means the distance of surface of scene objects from a viewpoint. An example of pixel value depth map can be found here : Pixel Value Depth Map using Histograms" }, { "code": null, "e": 26480, "s": 26120, "text": "Stereo Images : Two images with slight offset. For example, take a picture of an object from the center. Move your camera to your right by 6cms while keeping the object at the center of the image. Look for the same thing in both pictures and infer depth from the difference in position. This is called stereo matching. To have best results, avoid distortions." }, { "code": null, "e": 26491, "s": 26480, "text": "Approach " }, { "code": null, "e": 26522, "s": 26491, "text": "Collect or take stereo images." }, { "code": null, "e": 26562, "s": 26522, "text": "Import OpenCV and matplotlib libraries." }, { "code": null, "e": 26595, "s": 26562, "text": "Read both left and right images." }, { "code": null, "e": 26637, "s": 26595, "text": "Calculate disparity using stereo.compute." }, { "code": null, "e": 26662, "s": 26637, "text": "Example :Sample Images: " }, { "code": null, "e": 26667, "s": 26662, "text": "Left" }, { "code": null, "e": 26675, "s": 26669, "text": "Right" }, { "code": null, "e": 26685, "s": 26677, "text": "Python3" }, { "code": "# import OpenCV and pyplotimport cv2 as cvfrom matplotlib import pyplot as plt # read left and right imagesimgR = cv.imread('right.png', 0)imgL = cv.imread('left.png', 0) # creates StereoBm objectstereo = cv.StereoBM_create(numDisparities = 16, blockSize = 15) # computes disparitydisparity = stereo.compute(imgL, imgR) # displays image as grayscale and plottedplt.imshow(disparity, 'gray')plt.show()", "e": 27113, "s": 26685, "text": null }, { "code": null, "e": 27122, "s": 27113, "text": "Output: " }, { "code": null, "e": 27143, "s": 27122, "text": "Disparity Map Output" }, { "code": null, "e": 27160, "s": 27145, "text": "adnanirshad158" }, { "code": null, "e": 27174, "s": 27160, "text": "Python-OpenCV" }, { "code": null, "e": 27181, "s": 27174, "text": "Python" }, { "code": null, "e": 27279, "s": 27181, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27311, "s": 27279, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27353, "s": 27311, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27395, "s": 27353, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27451, "s": 27395, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27478, "s": 27451, "text": "Python Classes and Objects" }, { "code": null, "e": 27509, "s": 27478, "text": "Python | os.path.join() method" }, { "code": null, "e": 27548, "s": 27509, "text": "Python | Get unique values from a list" }, { "code": null, "e": 27577, "s": 27548, "text": "Create a directory in Python" }, { "code": null, "e": 27599, "s": 27577, "text": "Defaultdict in Python" } ]
Cache Hits in Memory Organization - GeeksforGeeks
01 May, 2022 The user has a memory machine. It has one layer for data storage and another layer for the cache. The user has stored an array with length N in the first layer. When the CPU needs data, it immediately checks in cache memory whether it has data or not. If data is present it results in CACHE HITS, else CACHE MISS, i.e., data is not in cache memory so it retrieves data from main memory and inserts a block of data into the cache layer. The question that arises is: How many times machine will need to load a block into the cache layer, i.e. determine the number of CACHE MISS? Example Let us assume an array and denote its elements by A0, A1, ..., AN? Now user wants to load some elements of this array into the cache. Machine loads array in blocks with size B:Assume block size is 4. 1 2 3 4 comes in Block 1, 5 6 7 8 comes in Block 2 and 9,10 comes in Block 3. A0, A1, ..., AB? 1 form a block; AB, AB+1, ... , A2B? 1 form another block, and so on. The last block may contain less than B elements of user’s array.Cache may only contain at most one block at a time. Whenever user tries to access an element Ai, machine checks if block where Ai is located is already in cache, and if it is not, loads this block into cache layer, so that it can quickly access any data in it.However, as soon as user tries to access an element that is outside currently loaded block in cache, block that was previously loaded into cache is removed from cache, since machine loads a new block containing element that is being accessed. Example – User has a sequence of elements Ax1, Ax2, ..., AxM which he wants to access, in this order. Initially, cache is empty. We need to find out how many times machine will need to load a block into cache layer. Input Format : First line of each test case contains three space-separated integers N, B and M. Second line contains M space-separated integers x1, x2, ..., xM. Input : 5 3 3 0 3 4 Output : 2 Explanation : Machine stores elements [A0, A1, A2] in one block and [A3, A4] in another block. When accessing A0, block [A0, A1, A2] is loaded. Then, accessing A3 removes previous block from cache and loads block [A3, A4]. Finally, when user accesses A4, a new block is not loaded, since block containing A4 is currently loaded in cache. Approach : Initially cache miss occurs because cache layer is empty and we find next multiplier and starting element. Obtain user value and find next multiplier number which is divisible by block size. Find starting elements of current block. If user value is greater than next multiplier and lesser than starting element then cache miss occurs. Implementation : C++ Java Python3 C# Javascript // C++ program to implement Cache Hits#include <iostream>using namespace std; // Function to find the next multiplierint findnextmultiplier(int i, int b){ for (int j = i; j <= i * b; j++) { if (j % b == 0) return j; }} // Function to find the cache hitsint ans(int n, int b, int m, int user[]){ // Initially cache miss occurs int start, cacheMiss = 1, nextmultiplier; // Find next multiplier for ith user and start nextmultiplier= findnextmultiplier(user[0] + 1, b); start = nextmultiplier - b + 1; for (int i = 1; i < m; i++) { // If ith user is greater than nextmultiplier or lesser // than start then cache miss occurs if (user[i] + 1 > nextmultiplier || user[i] + 1 < start) { cacheMiss++; nextmultiplier= findnextmultiplier(user[i] + 1, b); start = nextmultiplier - b + 1; } } // Printing cache hits cout << cacheMiss << endl; return 0;} // Driver codeint main(){ int n=5, b=3, m=3; int user[3] = {0, 3, 4}; ans(n, b, m, user); return 0;} // Java program to implement Cache Hitspublic class Main{ // Function to find the next multiplier public static int findnextmultiplier(int i, int b) { for (int j = i; j <= i * b; j++) { if (j % b == 0) return j; } return 0; } // Function to find the cache hits public static int ans(int n, int b, int m, int user[]) { // Initially cache miss occurs int start, ch = 1, nextmultiplier; // Find next multiplier for ith user and start nextmultiplier= findnextmultiplier(user[0] + 1, b); start = nextmultiplier - b + 1; for (int i = 1; i < m; i++) { // If ith user is greater than nextmultiplier or lesser // than start then cache hit occurs if (user[i] + 1 > nextmultiplier || user[i] + 1 < start) { ch++; nextmultiplier= findnextmultiplier(user[i] + 1, b); start = nextmultiplier - b + 1; } } // Printing cache hits System.out.println(ch); return 0; } public static void main(String[] args) { int n=5, b=3, m=3; int user[] = {0, 3, 4}; ans(n, b, m, user); }} // This code is contributed by divyeshrabadiya07 # Python3 program to implement Cache Hits # Function to find the next multiplierdef findnextmultiplier(i, b): for j in range(i, (i * b) + 1): if (j % b == 0): return j # Function to find the cache hitsdef ans(n, b, m, user): # Initially cache hit occurs ch = 1 # Find next multiplier for ith user and start nextmultiplier = findnextmultiplier(user[0] + 1, b) start = nextmultiplier - b + 1 for i in range(1, m): # If ith user is greater than nextmultiplier # or lesser than start then cache hit occurs if (user[i] + 1 > nextmultiplier or user[i] + 1 < start): ch += 1 nextmultiplier = findnextmultiplier( user[i] + 1, b) start = nextmultiplier - b + 1 # Printing cache hits print(ch) # Driver coden = 5b = 3m = 3 user = [ 0, 3, 4 ]ans(n, b, m, user) # This code is contributed by rag2127 // C# program to implement Cache Hitsusing System; class GFG{ // Function to find the next multiplierstatic int findnextmultiplier(int i, int b){ for(int j = i; j <= i * b; j++) { if (j % b == 0) return j; } return 0;} // Function to find the cache hitsstatic int ans(int n, int b, int m, int[] user){ // Initially cache hit occurs int start, ch = 1, nextmultiplier; // Find next multiplier for ith user and start nextmultiplier = findnextmultiplier( user[0] + 1, b); start = nextmultiplier - b + 1; for(int i = 1; i < m; i++) { // If ith user is greater than nextmultiplier // or lesser than start then cache hit occurs if (user[i] + 1 > nextmultiplier || user[i] + 1 < start) { ch++; nextmultiplier = findnextmultiplier( user[i] + 1, b); start = nextmultiplier - b + 1; } } // Printing cache hits Console.WriteLine(ch); return 0;} // Driver Code static void Main(){ int n = 5, b = 3, m = 3; int[] user = { 0, 3, 4 }; ans(n, b, m, user);}} // This code is contributed by divyesh072019 <script> // Javascript program to implement // Cache Hits // Function to find the next multiplier function findnextmultiplier(i, b) { for(let j = i; j <= i * b; j++) { if (j % b == 0) return j; } return 0; } // Function to find the cache hits function ans(n, b, m, user) { // Initially cache hit occurs let start, ch = 1, nextmultiplier; // Find next multiplier for ith user and start nextmultiplier = findnextmultiplier(user[0] + 1, b); start = nextmultiplier - b + 1; for(let i = 1; i < m; i++) { // If ith user is greater than nextmultiplier // or lesser than start then cache hit occurs if (user[i] + 1 > nextmultiplier || user[i] + 1 < start) { ch++; nextmultiplier = findnextmultiplier(user[i] + 1, b); start = nextmultiplier - b + 1; } } // Printing cache hits document.write(ch + "</br>"); return 0; } let n = 5, b = 3, m = 3; let user = [ 0, 3, 4 ]; ans(n, b, m, user); </script> Output : 2 Time Complexity : O(m) Auxiliary Space : O(1) divyeshrabadiya07 divyesh072019 rag2127 heypriyankahere decode2207 RiyaJain6 memory-management Computer Organization & Architecture Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Direct Access Media (DMA) Controller in Computer Architecture Computer Organization and Architecture | Pipelining | Set 2 (Dependencies and Data Hazard) Architecture of 8085 microprocessor Pin diagram of 8086 microprocessor I2C Communication Protocol Memory mapped I/O and Isolated I/O Difference between Hardwired and Micro-programmed Control Unit | Set 2 Computer Architecture | Flynn's taxonomy Computer Organization | Different Instruction Cycles Introduction of Assembler
[ { "code": null, "e": 26051, "s": 26023, "text": "\n01 May, 2022" }, { "code": null, "e": 26489, "s": 26051, "text": "The user has a memory machine. It has one layer for data storage and another layer for the cache. The user has stored an array with length N in the first layer. When the CPU needs data, it immediately checks in cache memory whether it has data or not. If data is present it results in CACHE HITS, else CACHE MISS, i.e., data is not in cache memory so it retrieves data from main memory and inserts a block of data into the cache layer. " }, { "code": null, "e": 26631, "s": 26489, "text": "The question that arises is: How many times machine will need to load a block into the cache layer, i.e. determine the number of CACHE MISS? " }, { "code": null, "e": 26639, "s": 26631, "text": "Example" }, { "code": null, "e": 26775, "s": 26639, "text": "Let us assume an array and denote its elements by A0, A1, ..., AN? Now user wants to load some elements of this array into the cache. " }, { "code": null, "e": 26920, "s": 26775, "text": "Machine loads array in blocks with size B:Assume block size is 4. 1 2 3 4 comes in Block 1, 5 6 7 8 comes in Block 2 and 9,10 comes in Block 3. " }, { "code": null, "e": 27574, "s": 26920, "text": "A0, A1, ..., AB? 1 form a block; AB, AB+1, ... , A2B? 1 form another block, and so on. The last block may contain less than B elements of user’s array.Cache may only contain at most one block at a time. Whenever user tries to access an element Ai, machine checks if block where Ai is located is already in cache, and if it is not, loads this block into cache layer, so that it can quickly access any data in it.However, as soon as user tries to access an element that is outside currently loaded block in cache, block that was previously loaded into cache is removed from cache, since machine loads a new block containing element that is being accessed." }, { "code": null, "e": 27791, "s": 27574, "text": "Example – User has a sequence of elements Ax1, Ax2, ..., AxM which he wants to access, in this order. Initially, cache is empty. We need to find out how many times machine will need to load a block into cache layer. " }, { "code": null, "e": 27808, "s": 27791, "text": "Input Format : " }, { "code": null, "e": 27889, "s": 27808, "text": "First line of each test case contains three space-separated integers N, B and M." }, { "code": null, "e": 27954, "s": 27889, "text": "Second line contains M space-separated integers x1, x2, ..., xM." }, { "code": null, "e": 27963, "s": 27954, "text": "Input : " }, { "code": null, "e": 27975, "s": 27963, "text": "5 3 3\n0 3 4" }, { "code": null, "e": 27986, "s": 27975, "text": "Output : " }, { "code": null, "e": 27988, "s": 27986, "text": "2" }, { "code": null, "e": 28326, "s": 27988, "text": "Explanation : Machine stores elements [A0, A1, A2] in one block and [A3, A4] in another block. When accessing A0, block [A0, A1, A2] is loaded. Then, accessing A3 removes previous block from cache and loads block [A3, A4]. Finally, when user accesses A4, a new block is not loaded, since block containing A4 is currently loaded in cache." }, { "code": null, "e": 28339, "s": 28326, "text": "Approach : " }, { "code": null, "e": 28446, "s": 28339, "text": "Initially cache miss occurs because cache layer is empty and we find next multiplier and starting element." }, { "code": null, "e": 28530, "s": 28446, "text": "Obtain user value and find next multiplier number which is divisible by block size." }, { "code": null, "e": 28571, "s": 28530, "text": "Find starting elements of current block." }, { "code": null, "e": 28674, "s": 28571, "text": "If user value is greater than next multiplier and lesser than starting element then cache miss occurs." }, { "code": null, "e": 28691, "s": 28674, "text": "Implementation :" }, { "code": null, "e": 28695, "s": 28691, "text": "C++" }, { "code": null, "e": 28700, "s": 28695, "text": "Java" }, { "code": null, "e": 28708, "s": 28700, "text": "Python3" }, { "code": null, "e": 28711, "s": 28708, "text": "C#" }, { "code": null, "e": 28722, "s": 28711, "text": "Javascript" }, { "code": "// C++ program to implement Cache Hits#include <iostream>using namespace std; // Function to find the next multiplierint findnextmultiplier(int i, int b){ for (int j = i; j <= i * b; j++) { if (j % b == 0) return j; }} // Function to find the cache hitsint ans(int n, int b, int m, int user[]){ // Initially cache miss occurs int start, cacheMiss = 1, nextmultiplier; // Find next multiplier for ith user and start nextmultiplier= findnextmultiplier(user[0] + 1, b); start = nextmultiplier - b + 1; for (int i = 1; i < m; i++) { // If ith user is greater than nextmultiplier or lesser // than start then cache miss occurs if (user[i] + 1 > nextmultiplier || user[i] + 1 < start) { cacheMiss++; nextmultiplier= findnextmultiplier(user[i] + 1, b); start = nextmultiplier - b + 1; } } // Printing cache hits cout << cacheMiss << endl; return 0;} // Driver codeint main(){ int n=5, b=3, m=3; int user[3] = {0, 3, 4}; ans(n, b, m, user); return 0;}", "e": 29791, "s": 28722, "text": null }, { "code": "// Java program to implement Cache Hitspublic class Main{ // Function to find the next multiplier public static int findnextmultiplier(int i, int b) { for (int j = i; j <= i * b; j++) { if (j % b == 0) return j; } return 0; } // Function to find the cache hits public static int ans(int n, int b, int m, int user[]) { // Initially cache miss occurs int start, ch = 1, nextmultiplier; // Find next multiplier for ith user and start nextmultiplier= findnextmultiplier(user[0] + 1, b); start = nextmultiplier - b + 1; for (int i = 1; i < m; i++) { // If ith user is greater than nextmultiplier or lesser // than start then cache hit occurs if (user[i] + 1 > nextmultiplier || user[i] + 1 < start) { ch++; nextmultiplier= findnextmultiplier(user[i] + 1, b); start = nextmultiplier - b + 1; } } // Printing cache hits System.out.println(ch); return 0; } public static void main(String[] args) { int n=5, b=3, m=3; int user[] = {0, 3, 4}; ans(n, b, m, user); }} // This code is contributed by divyeshrabadiya07", "e": 31134, "s": 29791, "text": null }, { "code": "# Python3 program to implement Cache Hits # Function to find the next multiplierdef findnextmultiplier(i, b): for j in range(i, (i * b) + 1): if (j % b == 0): return j # Function to find the cache hitsdef ans(n, b, m, user): # Initially cache hit occurs ch = 1 # Find next multiplier for ith user and start nextmultiplier = findnextmultiplier(user[0] + 1, b) start = nextmultiplier - b + 1 for i in range(1, m): # If ith user is greater than nextmultiplier # or lesser than start then cache hit occurs if (user[i] + 1 > nextmultiplier or user[i] + 1 < start): ch += 1 nextmultiplier = findnextmultiplier( user[i] + 1, b) start = nextmultiplier - b + 1 # Printing cache hits print(ch) # Driver coden = 5b = 3m = 3 user = [ 0, 3, 4 ]ans(n, b, m, user) # This code is contributed by rag2127", "e": 32069, "s": 31134, "text": null }, { "code": "// C# program to implement Cache Hitsusing System; class GFG{ // Function to find the next multiplierstatic int findnextmultiplier(int i, int b){ for(int j = i; j <= i * b; j++) { if (j % b == 0) return j; } return 0;} // Function to find the cache hitsstatic int ans(int n, int b, int m, int[] user){ // Initially cache hit occurs int start, ch = 1, nextmultiplier; // Find next multiplier for ith user and start nextmultiplier = findnextmultiplier( user[0] + 1, b); start = nextmultiplier - b + 1; for(int i = 1; i < m; i++) { // If ith user is greater than nextmultiplier // or lesser than start then cache hit occurs if (user[i] + 1 > nextmultiplier || user[i] + 1 < start) { ch++; nextmultiplier = findnextmultiplier( user[i] + 1, b); start = nextmultiplier - b + 1; } } // Printing cache hits Console.WriteLine(ch); return 0;} // Driver Code static void Main(){ int n = 5, b = 3, m = 3; int[] user = { 0, 3, 4 }; ans(n, b, m, user);}} // This code is contributed by divyesh072019", "e": 33291, "s": 32069, "text": null }, { "code": "<script> // Javascript program to implement // Cache Hits // Function to find the next multiplier function findnextmultiplier(i, b) { for(let j = i; j <= i * b; j++) { if (j % b == 0) return j; } return 0; } // Function to find the cache hits function ans(n, b, m, user) { // Initially cache hit occurs let start, ch = 1, nextmultiplier; // Find next multiplier for ith user and start nextmultiplier = findnextmultiplier(user[0] + 1, b); start = nextmultiplier - b + 1; for(let i = 1; i < m; i++) { // If ith user is greater than nextmultiplier // or lesser than start then cache hit occurs if (user[i] + 1 > nextmultiplier || user[i] + 1 < start) { ch++; nextmultiplier = findnextmultiplier(user[i] + 1, b); start = nextmultiplier - b + 1; } } // Printing cache hits document.write(ch + \"</br>\"); return 0; } let n = 5, b = 3, m = 3; let user = [ 0, 3, 4 ]; ans(n, b, m, user); </script>", "e": 34514, "s": 33291, "text": null }, { "code": null, "e": 34524, "s": 34514, "text": "Output : " }, { "code": null, "e": 34526, "s": 34524, "text": "2" }, { "code": null, "e": 34573, "s": 34526, "text": "Time Complexity : O(m) Auxiliary Space : O(1) " }, { "code": null, "e": 34591, "s": 34573, "text": "divyeshrabadiya07" }, { "code": null, "e": 34605, "s": 34591, "text": "divyesh072019" }, { "code": null, "e": 34613, "s": 34605, "text": "rag2127" }, { "code": null, "e": 34629, "s": 34613, "text": "heypriyankahere" }, { "code": null, "e": 34640, "s": 34629, "text": "decode2207" }, { "code": null, "e": 34650, "s": 34640, "text": "RiyaJain6" }, { "code": null, "e": 34668, "s": 34650, "text": "memory-management" }, { "code": null, "e": 34705, "s": 34668, "text": "Computer Organization & Architecture" }, { "code": null, "e": 34803, "s": 34705, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34865, "s": 34803, "text": "Direct Access Media (DMA) Controller in Computer Architecture" }, { "code": null, "e": 34956, "s": 34865, "text": "Computer Organization and Architecture | Pipelining | Set 2 (Dependencies and Data Hazard)" }, { "code": null, "e": 34992, "s": 34956, "text": "Architecture of 8085 microprocessor" }, { "code": null, "e": 35027, "s": 34992, "text": "Pin diagram of 8086 microprocessor" }, { "code": null, "e": 35054, "s": 35027, "text": "I2C Communication Protocol" }, { "code": null, "e": 35089, "s": 35054, "text": "Memory mapped I/O and Isolated I/O" }, { "code": null, "e": 35160, "s": 35089, "text": "Difference between Hardwired and Micro-programmed Control Unit | Set 2" }, { "code": null, "e": 35201, "s": 35160, "text": "Computer Architecture | Flynn's taxonomy" }, { "code": null, "e": 35254, "s": 35201, "text": "Computer Organization | Different Instruction Cycles" } ]
Exception Handling in C++ - GeeksforGeeks
07 Jul, 2021 One of the advantages of C++ over C is Exception Handling. Exceptions are run-time anomalies or abnormal conditions that a program encounters during its execution. There are two types of exceptions: a)Synchronous, b)Asynchronous(Ex:which are beyond the program’s control, Disc failure etc). C++ provides following specialized keywords for this purpose.try: represents a block of code that can throw an exception.catch: represents a block of code that is executed when a particular exception is thrown.throw: Used to throw an exception. Also used to list the exceptions that a function throws, but doesn’t handle itself. Why Exception Handling? Following are main advantages of exception handling over traditional error handling. 1) Separation of Error Handling code from Normal Code: In traditional error handling codes, there are always if else conditions to handle errors. These conditions and the code to handle errors get mixed up with the normal flow. This makes the code less readable and maintainable. With try catch blocks, the code for error handling becomes separate from the normal flow. 2) Functions/Methods can handle any exceptions they choose: A function can throw many exceptions, but may choose to handle some of them. The other exceptions which are thrown, but not caught can be handled by caller. If the caller chooses not to catch them, then the exceptions are handled by caller of the caller. In C++, a function can specify the exceptions that it throws using the throw keyword. The caller of this function must handle the exception in some way (either by specifying it again or catching it) 3) Grouping of Error Types: In C++, both basic types and objects can be thrown as exception. We can create a hierarchy of exception objects, group exceptions in namespaces or classes, categorize them according to types. C++ Exceptions: When executing C++ code, different errors can occur: coding errors made by the programmer, errors due to wrong input, or other unforeseeable things. When an error occurs, C++ will normally stop and generate an error message. The technical term for this is: C++ will throw an exception (throw an error). C++ try and catch: Exception handling in C++ consists of three keywords: try, throw and catch: The try statement allows you to define a block of code to be tested for errors while it is being executed. The throw keyword throws an exception when a problem is detected, which lets us create a custom error. The catch statement allows you to define a block of code to be executed, if an error occurs in the try block. The try and catch keywords come in pairs: We use the try block to test some code: If the age variable is less than 18, we will throw an exception, and handle it in our catch block. In the catch block, we catch the error and do something about it. The catch statement takes a parameter: in our example we use an int variable (myNum) (because we are throwing an exception of int type in the try block (age)), to output the value of age. If no error occurs (e.g. if age is 20 instead of 15, meaning it will be be greater than 18), the catch block is skipped: Exception Handling in C++ 1) Following is a simple example to show exception handling in C++. The output of program explains flow of execution of try/catch blocks. CPP #include <iostream>using namespace std; int main(){ int x = -1; // Some code cout << "Before try \n"; try { cout << "Inside try \n"; if (x < 0) { throw x; cout << "After throw (Never executed) \n"; } } catch (int x ) { cout << "Exception Caught \n"; } cout << "After catch (Will be executed) \n"; return 0;} Output: Before try Inside try Exception Caught After catch (Will be executed) 2) There is a special catch block called ‘catch all’ catch(...) that can be used to catch all types of exceptions. For example, in the following program, an int is thrown as an exception, but there is no catch block for int, so catch(...) block will be executed. CPP #include <iostream>using namespace std; int main(){ try { throw 10; } catch (char *excp) { cout << "Caught " << excp; } catch (...) { cout << "Default Exception\n"; } return 0;} Output: Default Exception 3) Implicit type conversion doesn’t happen for primitive types. For example, in the following program ‘a’ is not implicitly converted to int CPP #include <iostream>using namespace std; int main(){ try { throw 'a'; } catch (int x) { cout << "Caught " << x; } catch (...) { cout << "Default Exception\n"; } return 0;} Output: Default Exception 4) If an exception is thrown and not caught anywhere, the program terminates abnormally. For example, in the following program, a char is thrown, but there is no catch block to catch a char. CPP #include <iostream>using namespace std; int main(){ try { throw 'a'; } catch (int x) { cout << "Caught "; } return 0;} Output: terminate called after throwing an instance of 'char' This application has requested the Runtime to terminate it in an unusual way. Please contact the application's support team for more information. We can change this abnormal termination behavior by writing our own unexpected function.5) A derived class exception should be caught before a base class exception. See this for more details.6) Like Java, C++ library has a standard exception class which is base class for all standard exceptions. All objects thrown by components of the standard library are derived from this class. Therefore, all standard exceptions can be caught by catching this type7) Unlike Java, in C++, all exceptions are unchecked. Compiler doesn’t check whether an exception is caught or not (See this for details). For example, in C++, it is not necessary to specify all uncaught exceptions in a function declaration. Although it’s a recommended practice to do so. For example, the following program compiles fine, but ideally signature of fun() should list unchecked exceptions. CPP #include <iostream>using namespace std; // This function signature is fine by the compiler, but not recommended.// Ideally, the function should specify all uncaught exceptions and function// signature should be "void fun(int *ptr, int x) throw (int *, int)"void fun(int *ptr, int x){ if (ptr == NULL) throw ptr; if (x == 0) throw x; /* Some functionality */} int main(){ try { fun(NULL, 0); } catch(...) { cout << "Caught exception from fun()"; } return 0;} Output: Caught exception from fun() A better way to write above code CPP #include <iostream>using namespace std; // Here we specify the exceptions that this function// throws.void fun(int *ptr, int x) throw (int *, int) // Dynamic Exception specification{ if (ptr == NULL) throw ptr; if (x == 0) throw x; /* Some functionality */} int main(){ try { fun(NULL, 0); } catch(...) { cout << "Caught exception from fun()"; } return 0;} (Note : The use of Dynamic Exception Specification has been deprecated after C++11, one of the reason maybe because it can randomly abort your program. This can happen when you throw an exception of an another type which is not mentioned in the dynamic exception specification, your program will abort itself, because in that scenario program calls(indrectly) terminate(), and which is by default call abort()). Output: Caught exception from fun() 8) In C++, try-catch blocks can be nested. Also, an exception can be re-thrown using “throw; ” CPP #include <iostream>using namespace std; int main(){ try { try { throw 20; } catch (int n) { cout << "Handle Partially "; throw; // Re-throwing an exception } } catch (int n) { cout << "Handle remaining "; } return 0;} Output: Handle Partially Handle remaining A function can also re-throw a function using same “throw; “. A function can handle a part and can ask the caller to handle remaining.9) When an exception is thrown, all objects created inside the enclosing try block are destructed before the control is transferred to catch block. CPP #include <iostream>using namespace std; class Test {public: Test() { cout << "Constructor of Test " << endl; } ~Test() { cout << "Destructor of Test " << endl; }}; int main(){ try { Test t1; throw 10; } catch (int i) { cout << "Caught " << i << endl; }} Output: Constructor of Test Destructor of Test Caught 10 10) You may like to try Quiz on Exception Handling in C++.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. slodha95 pritiprajapati314 crawler akgrd140 cpp-exception C Language C++ School Programming CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc() std::sort() in C++ STL Bitwise Operators in C/C++ Substring in C++ Left Shift and Right Shift Operators in C/C++ Vector in C++ STL Initialize a vector in C++ (6 different ways) std::sort() in C++ STL Bitwise Operators in C/C++ Virtual Function in C++
[ { "code": null, "e": 28207, "s": 28179, "text": "\n07 Jul, 2021" }, { "code": null, "e": 28827, "s": 28207, "text": "One of the advantages of C++ over C is Exception Handling. Exceptions are run-time anomalies or abnormal conditions that a program encounters during its execution. There are two types of exceptions: a)Synchronous, b)Asynchronous(Ex:which are beyond the program’s control, Disc failure etc). C++ provides following specialized keywords for this purpose.try: represents a block of code that can throw an exception.catch: represents a block of code that is executed when a particular exception is thrown.throw: Used to throw an exception. Also used to list the exceptions that a function throws, but doesn’t handle itself." }, { "code": null, "e": 28936, "s": 28827, "text": "Why Exception Handling? Following are main advantages of exception handling over traditional error handling." }, { "code": null, "e": 29306, "s": 28936, "text": "1) Separation of Error Handling code from Normal Code: In traditional error handling codes, there are always if else conditions to handle errors. These conditions and the code to handle errors get mixed up with the normal flow. This makes the code less readable and maintainable. With try catch blocks, the code for error handling becomes separate from the normal flow." }, { "code": null, "e": 29820, "s": 29306, "text": "2) Functions/Methods can handle any exceptions they choose: A function can throw many exceptions, but may choose to handle some of them. The other exceptions which are thrown, but not caught can be handled by caller. If the caller chooses not to catch them, then the exceptions are handled by caller of the caller. In C++, a function can specify the exceptions that it throws using the throw keyword. The caller of this function must handle the exception in some way (either by specifying it again or catching it)" }, { "code": null, "e": 30041, "s": 29820, "text": "3) Grouping of Error Types: In C++, both basic types and objects can be thrown as exception. We can create a hierarchy of exception objects, group exceptions in namespaces or classes, categorize them according to types. " }, { "code": null, "e": 30057, "s": 30041, "text": "C++ Exceptions:" }, { "code": null, "e": 30206, "s": 30057, "text": "When executing C++ code, different errors can occur: coding errors made by the programmer, errors due to wrong input, or other unforeseeable things." }, { "code": null, "e": 30360, "s": 30206, "text": "When an error occurs, C++ will normally stop and generate an error message. The technical term for this is: C++ will throw an exception (throw an error)." }, { "code": null, "e": 30379, "s": 30360, "text": "C++ try and catch:" }, { "code": null, "e": 30455, "s": 30379, "text": "Exception handling in C++ consists of three keywords: try, throw and catch:" }, { "code": null, "e": 30562, "s": 30455, "text": "The try statement allows you to define a block of code to be tested for errors while it is being executed." }, { "code": null, "e": 30665, "s": 30562, "text": "The throw keyword throws an exception when a problem is detected, which lets us create a custom error." }, { "code": null, "e": 30775, "s": 30665, "text": "The catch statement allows you to define a block of code to be executed, if an error occurs in the try block." }, { "code": null, "e": 30817, "s": 30775, "text": "The try and catch keywords come in pairs:" }, { "code": null, "e": 30956, "s": 30817, "text": "We use the try block to test some code: If the age variable is less than 18, we will throw an exception, and handle it in our catch block." }, { "code": null, "e": 31210, "s": 30956, "text": "In the catch block, we catch the error and do something about it. The catch statement takes a parameter: in our example we use an int variable (myNum) (because we are throwing an exception of int type in the try block (age)), to output the value of age." }, { "code": null, "e": 31331, "s": 31210, "text": "If no error occurs (e.g. if age is 20 instead of 15, meaning it will be be greater than 18), the catch block is skipped:" }, { "code": null, "e": 31357, "s": 31331, "text": "Exception Handling in C++" }, { "code": null, "e": 31496, "s": 31357, "text": "1) Following is a simple example to show exception handling in C++. The output of program explains flow of execution of try/catch blocks. " }, { "code": null, "e": 31500, "s": 31496, "text": "CPP" }, { "code": "#include <iostream>using namespace std; int main(){ int x = -1; // Some code cout << \"Before try \\n\"; try { cout << \"Inside try \\n\"; if (x < 0) { throw x; cout << \"After throw (Never executed) \\n\"; } } catch (int x ) { cout << \"Exception Caught \\n\"; } cout << \"After catch (Will be executed) \\n\"; return 0;}", "e": 31869, "s": 31500, "text": null }, { "code": null, "e": 31878, "s": 31869, "text": "Output: " }, { "code": null, "e": 31948, "s": 31878, "text": "Before try\nInside try\nException Caught\nAfter catch (Will be executed)" }, { "code": null, "e": 32212, "s": 31948, "text": "2) There is a special catch block called ‘catch all’ catch(...) that can be used to catch all types of exceptions. For example, in the following program, an int is thrown as an exception, but there is no catch block for int, so catch(...) block will be executed. " }, { "code": null, "e": 32216, "s": 32212, "text": "CPP" }, { "code": "#include <iostream>using namespace std; int main(){ try { throw 10; } catch (char *excp) { cout << \"Caught \" << excp; } catch (...) { cout << \"Default Exception\\n\"; } return 0;}", "e": 32438, "s": 32216, "text": null }, { "code": null, "e": 32447, "s": 32438, "text": "Output: " }, { "code": null, "e": 32465, "s": 32447, "text": "Default Exception" }, { "code": null, "e": 32607, "s": 32465, "text": "3) Implicit type conversion doesn’t happen for primitive types. For example, in the following program ‘a’ is not implicitly converted to int " }, { "code": null, "e": 32611, "s": 32607, "text": "CPP" }, { "code": "#include <iostream>using namespace std; int main(){ try { throw 'a'; } catch (int x) { cout << \"Caught \" << x; } catch (...) { cout << \"Default Exception\\n\"; } return 0;}", "e": 32826, "s": 32611, "text": null }, { "code": null, "e": 32835, "s": 32826, "text": "Output: " }, { "code": null, "e": 32853, "s": 32835, "text": "Default Exception" }, { "code": null, "e": 33046, "s": 32853, "text": "4) If an exception is thrown and not caught anywhere, the program terminates abnormally. For example, in the following program, a char is thrown, but there is no catch block to catch a char. " }, { "code": null, "e": 33050, "s": 33046, "text": "CPP" }, { "code": "#include <iostream>using namespace std; int main(){ try { throw 'a'; } catch (int x) { cout << \"Caught \"; } return 0;}", "e": 33199, "s": 33050, "text": null }, { "code": null, "e": 33208, "s": 33199, "text": "Output: " }, { "code": null, "e": 33411, "s": 33208, "text": "terminate called after throwing an instance of 'char'\n\nThis application has requested the Runtime to terminate it in an \nunusual way. Please contact the application's support team for \nmore information." }, { "code": null, "e": 34269, "s": 33411, "text": "We can change this abnormal termination behavior by writing our own unexpected function.5) A derived class exception should be caught before a base class exception. See this for more details.6) Like Java, C++ library has a standard exception class which is base class for all standard exceptions. All objects thrown by components of the standard library are derived from this class. Therefore, all standard exceptions can be caught by catching this type7) Unlike Java, in C++, all exceptions are unchecked. Compiler doesn’t check whether an exception is caught or not (See this for details). For example, in C++, it is not necessary to specify all uncaught exceptions in a function declaration. Although it’s a recommended practice to do so. For example, the following program compiles fine, but ideally signature of fun() should list unchecked exceptions. " }, { "code": null, "e": 34273, "s": 34269, "text": "CPP" }, { "code": "#include <iostream>using namespace std; // This function signature is fine by the compiler, but not recommended.// Ideally, the function should specify all uncaught exceptions and function// signature should be \"void fun(int *ptr, int x) throw (int *, int)\"void fun(int *ptr, int x){ if (ptr == NULL) throw ptr; if (x == 0) throw x; /* Some functionality */} int main(){ try { fun(NULL, 0); } catch(...) { cout << \"Caught exception from fun()\"; } return 0;}", "e": 34782, "s": 34273, "text": null }, { "code": null, "e": 34791, "s": 34782, "text": "Output: " }, { "code": null, "e": 34819, "s": 34791, "text": "Caught exception from fun()" }, { "code": null, "e": 34853, "s": 34819, "text": "A better way to write above code " }, { "code": null, "e": 34857, "s": 34853, "text": "CPP" }, { "code": "#include <iostream>using namespace std; // Here we specify the exceptions that this function// throws.void fun(int *ptr, int x) throw (int *, int) // Dynamic Exception specification{ if (ptr == NULL) throw ptr; if (x == 0) throw x; /* Some functionality */} int main(){ try { fun(NULL, 0); } catch(...) { cout << \"Caught exception from fun()\"; } return 0;}", "e": 35265, "s": 34857, "text": null }, { "code": null, "e": 35677, "s": 35265, "text": "(Note : The use of Dynamic Exception Specification has been deprecated after C++11, one of the reason maybe because it can randomly abort your program. This can happen when you throw an exception of an another type which is not mentioned in the dynamic exception specification, your program will abort itself, because in that scenario program calls(indrectly) terminate(), and which is by default call abort())." }, { "code": null, "e": 35686, "s": 35677, "text": "Output: " }, { "code": null, "e": 35714, "s": 35686, "text": "Caught exception from fun()" }, { "code": null, "e": 35810, "s": 35714, "text": "8) In C++, try-catch blocks can be nested. Also, an exception can be re-thrown using “throw; ” " }, { "code": null, "e": 35814, "s": 35810, "text": "CPP" }, { "code": "#include <iostream>using namespace std; int main(){ try { try { throw 20; } catch (int n) { cout << \"Handle Partially \"; throw; // Re-throwing an exception } } catch (int n) { cout << \"Handle remaining \"; } return 0;}", "e": 36115, "s": 35814, "text": null }, { "code": null, "e": 36124, "s": 36115, "text": "Output: " }, { "code": null, "e": 36158, "s": 36124, "text": "Handle Partially Handle remaining" }, { "code": null, "e": 36440, "s": 36158, "text": "A function can also re-throw a function using same “throw; “. A function can handle a part and can ask the caller to handle remaining.9) When an exception is thrown, all objects created inside the enclosing try block are destructed before the control is transferred to catch block." }, { "code": null, "e": 36444, "s": 36440, "text": "CPP" }, { "code": "#include <iostream>using namespace std; class Test {public: Test() { cout << \"Constructor of Test \" << endl; } ~Test() { cout << \"Destructor of Test \" << endl; }}; int main(){ try { Test t1; throw 10; } catch (int i) { cout << \"Caught \" << i << endl; }}", "e": 36737, "s": 36444, "text": null }, { "code": null, "e": 36746, "s": 36737, "text": "Output: " }, { "code": null, "e": 36795, "s": 36746, "text": "Constructor of Test\nDestructor of Test\nCaught 10" }, { "code": null, "e": 36979, "s": 36795, "text": "10) You may like to try Quiz on Exception Handling in C++.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 36988, "s": 36979, "text": "slodha95" }, { "code": null, "e": 37006, "s": 36988, "text": "pritiprajapati314" }, { "code": null, "e": 37014, "s": 37006, "text": "crawler" }, { "code": null, "e": 37023, "s": 37014, "text": "akgrd140" }, { "code": null, "e": 37037, "s": 37023, "text": "cpp-exception" }, { "code": null, "e": 37048, "s": 37037, "text": "C Language" }, { "code": null, "e": 37052, "s": 37048, "text": "C++" }, { "code": null, "e": 37071, "s": 37052, "text": "School Programming" }, { "code": null, "e": 37075, "s": 37071, "text": "CPP" }, { "code": null, "e": 37173, "s": 37075, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 37251, "s": 37173, "text": "Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc()" }, { "code": null, "e": 37274, "s": 37251, "text": "std::sort() in C++ STL" }, { "code": null, "e": 37301, "s": 37274, "text": "Bitwise Operators in C/C++" }, { "code": null, "e": 37318, "s": 37301, "text": "Substring in C++" }, { "code": null, "e": 37364, "s": 37318, "text": "Left Shift and Right Shift Operators in C/C++" }, { "code": null, "e": 37382, "s": 37364, "text": "Vector in C++ STL" }, { "code": null, "e": 37428, "s": 37382, "text": "Initialize a vector in C++ (6 different ways)" }, { "code": null, "e": 37451, "s": 37428, "text": "std::sort() in C++ STL" }, { "code": null, "e": 37478, "s": 37451, "text": "Bitwise Operators in C/C++" } ]
Sort a Pandas Series in Python - GeeksforGeeks
05 Jul, 2021 Series is a one-dimensional labeled array capable of holding data of the type integer, string, float, python objects, etc. The axis labels are collectively called index. Now, Let’s see a program to sort a Pandas Series. For sorting a pandas series the Series.sort_values() method is used. Syntax: Series.sort_values(axis=0, ascending=True, inplace=False, kind=’quicksort’, na_position=’last’)Sorted Returns: Sorted series Examples 1: Sorting a numeric series in ascending order. Python3 # importing pandas as pdimport pandas as pd # define a numeric seriess = pd.Series([100, 200, 54.67, 300.12, 400]) # print the unsorted seriess Output: Now we will use Series.sort_values() method to sort a numeric series in ascending order. Python3 # sorting series s with# s.sort_value() method in# ascending ordersorted_series = s.sort_values(ascending = True)# print the sorted seriessorted_series Output: From the output, we can see that the numeric series is sorted in ascending order. Example 2: Sorting a numeric series in descending order. Python3 # importing pandas as pdimport pandas as pd # define a numeric seriess = pd.Series([100, 200, 54.67, 300.12, 400]) # print the unsorted seriess Output: Now we will use Series.sort_values() method to sort a numeric series in descending order. Python3 # sorting the series s with# s.sort_values() method# in descending ordersorted_series = s.sort_values(ascending = False)# printing the sorted seriessorted_series Output: From the output, we can see that the numeric series is sorted in descending order. Example 3: Sorting a series of strings. Python3 # importing pandas as pdimport pandas as pd #d efine a string series ss = pd.Series(["OS","DBMS","DAA", "TOC","ML"]) # print the unsorted seriess Output: Now we will use Series.sort_values() method to sort a series of strings. Python3 # sorting the series s with# s.sort_values() method# in ascending ordersorted_series = s.sort_values(ascending = True)# printing the sorted seriessorted_series Output: From the output, we can see that the string series is sorted in a lexicographically ascending order. Example 4: Sorting values inplace. Python3 # importing numpy as npimport numpy as np # importing pandas as pdimport pandas as pd # define a numeric series# s with a NaNs = pd.Series([np.nan, 1, 3, 10, 5]) # print the unsorted seriess Output: Now we will use Series.sort_values() method to sort values inplace Python3 # sorting the series s with# s.sort_values() method in# descending order and inplaces.sort_values(ascending = False, inplace = True) # printing the sorted seriess Output: The output shows that the inplace sorting in the Pandas Series. Example 5: Sorting values in the series by putting NaN first. Python3 # importing numpy as npimport numpy as np # importing pandas as pdimport pandas as pd # define a numeric series# s with a NaNs = pd.Series([np.nan, 1, 3, 10, 5]) # print the unsorted seriess Output: Now we will use Series.sort_values() method to sort values in the series by putting NaN first. Python3 # sorting the series s with# s.sort_values() method in# ascending order with na# position at firstsorted_series = s.sort_values(na_position = 'first') # printing the sorted seriessorted_series Output: The output shows that the NaN (not a number) value is given the first place in the sorted series. sweetyty Python pandas-series Python-pandas 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": 26177, "s": 26149, "text": "\n05 Jul, 2021" }, { "code": null, "e": 26348, "s": 26177, "text": "Series is a one-dimensional labeled array capable of holding data of the type integer, string, float, python objects, etc. The axis labels are collectively called index. " }, { "code": null, "e": 26398, "s": 26348, "text": "Now, Let’s see a program to sort a Pandas Series." }, { "code": null, "e": 26467, "s": 26398, "text": "For sorting a pandas series the Series.sort_values() method is used." }, { "code": null, "e": 26577, "s": 26467, "text": "Syntax: Series.sort_values(axis=0, ascending=True, inplace=False, kind=’quicksort’, na_position=’last’)Sorted" }, { "code": null, "e": 26600, "s": 26577, "text": "Returns: Sorted series" }, { "code": null, "e": 26657, "s": 26600, "text": "Examples 1: Sorting a numeric series in ascending order." }, { "code": null, "e": 26665, "s": 26657, "text": "Python3" }, { "code": "# importing pandas as pdimport pandas as pd # define a numeric seriess = pd.Series([100, 200, 54.67, 300.12, 400]) # print the unsorted seriess", "e": 26823, "s": 26665, "text": null }, { "code": null, "e": 26835, "s": 26827, "text": "Output:" }, { "code": null, "e": 26928, "s": 26839, "text": "Now we will use Series.sort_values() method to sort a numeric series in ascending order." }, { "code": null, "e": 26938, "s": 26930, "text": "Python3" }, { "code": "# sorting series s with# s.sort_value() method in# ascending ordersorted_series = s.sort_values(ascending = True)# print the sorted seriessorted_series", "e": 27119, "s": 26938, "text": null }, { "code": null, "e": 27127, "s": 27119, "text": "Output:" }, { "code": null, "e": 27209, "s": 27127, "text": "From the output, we can see that the numeric series is sorted in ascending order." }, { "code": null, "e": 27267, "s": 27209, "text": "Example 2: Sorting a numeric series in descending order." }, { "code": null, "e": 27275, "s": 27267, "text": "Python3" }, { "code": "# importing pandas as pdimport pandas as pd # define a numeric seriess = pd.Series([100, 200, 54.67, 300.12, 400]) # print the unsorted seriess", "e": 27433, "s": 27275, "text": null }, { "code": null, "e": 27445, "s": 27437, "text": "Output:" }, { "code": null, "e": 27539, "s": 27449, "text": "Now we will use Series.sort_values() method to sort a numeric series in descending order." }, { "code": null, "e": 27549, "s": 27541, "text": "Python3" }, { "code": "# sorting the series s with# s.sort_values() method# in descending ordersorted_series = s.sort_values(ascending = False)# printing the sorted seriessorted_series", "e": 27740, "s": 27549, "text": null }, { "code": null, "e": 27748, "s": 27740, "text": "Output:" }, { "code": null, "e": 27831, "s": 27748, "text": "From the output, we can see that the numeric series is sorted in descending order." }, { "code": null, "e": 27871, "s": 27831, "text": "Example 3: Sorting a series of strings." }, { "code": null, "e": 27879, "s": 27871, "text": "Python3" }, { "code": "# importing pandas as pdimport pandas as pd #d efine a string series ss = pd.Series([\"OS\",\"DBMS\",\"DAA\", \"TOC\",\"ML\"]) # print the unsorted seriess", "e": 28039, "s": 27879, "text": null }, { "code": null, "e": 28047, "s": 28039, "text": "Output:" }, { "code": null, "e": 28120, "s": 28047, "text": "Now we will use Series.sort_values() method to sort a series of strings." }, { "code": null, "e": 28128, "s": 28120, "text": "Python3" }, { "code": "# sorting the series s with# s.sort_values() method# in ascending ordersorted_series = s.sort_values(ascending = True)# printing the sorted seriessorted_series", "e": 28317, "s": 28128, "text": null }, { "code": null, "e": 28325, "s": 28317, "text": "Output:" }, { "code": null, "e": 28426, "s": 28325, "text": "From the output, we can see that the string series is sorted in a lexicographically ascending order." }, { "code": null, "e": 28461, "s": 28426, "text": "Example 4: Sorting values inplace." }, { "code": null, "e": 28469, "s": 28461, "text": "Python3" }, { "code": "# importing numpy as npimport numpy as np # importing pandas as pdimport pandas as pd # define a numeric series# s with a NaNs = pd.Series([np.nan, 1, 3, 10, 5]) # print the unsorted seriess", "e": 28674, "s": 28469, "text": null }, { "code": null, "e": 28682, "s": 28674, "text": "Output:" }, { "code": null, "e": 28749, "s": 28682, "text": "Now we will use Series.sort_values() method to sort values inplace" }, { "code": null, "e": 28757, "s": 28749, "text": "Python3" }, { "code": "# sorting the series s with# s.sort_values() method in# descending order and inplaces.sort_values(ascending = False, inplace = True) # printing the sorted seriess", "e": 28950, "s": 28757, "text": null }, { "code": null, "e": 28962, "s": 28954, "text": "Output:" }, { "code": null, "e": 29030, "s": 28966, "text": "The output shows that the inplace sorting in the Pandas Series." }, { "code": null, "e": 29094, "s": 29032, "text": "Example 5: Sorting values in the series by putting NaN first." }, { "code": null, "e": 29104, "s": 29096, "text": "Python3" }, { "code": "# importing numpy as npimport numpy as np # importing pandas as pdimport pandas as pd # define a numeric series# s with a NaNs = pd.Series([np.nan, 1, 3, 10, 5]) # print the unsorted seriess", "e": 29310, "s": 29104, "text": null }, { "code": null, "e": 29323, "s": 29314, "text": "Output: " }, { "code": null, "e": 29422, "s": 29327, "text": "Now we will use Series.sort_values() method to sort values in the series by putting NaN first." }, { "code": null, "e": 29432, "s": 29424, "text": "Python3" }, { "code": "# sorting the series s with# s.sort_values() method in# ascending order with na# position at firstsorted_series = s.sort_values(na_position = 'first') # printing the sorted seriessorted_series", "e": 29654, "s": 29432, "text": null }, { "code": null, "e": 29666, "s": 29658, "text": "Output:" }, { "code": null, "e": 29768, "s": 29670, "text": "The output shows that the NaN (not a number) value is given the first place in the sorted series." }, { "code": null, "e": 29779, "s": 29770, "text": "sweetyty" }, { "code": null, "e": 29800, "s": 29779, "text": "Python pandas-series" }, { "code": null, "e": 29814, "s": 29800, "text": "Python-pandas" }, { "code": null, "e": 29821, "s": 29814, "text": "Python" }, { "code": null, "e": 29919, "s": 29821, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29937, "s": 29919, "text": "Python Dictionary" }, { "code": null, "e": 29972, "s": 29937, "text": "Read a file line by line in Python" }, { "code": null, "e": 30004, "s": 29972, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 30026, "s": 30004, "text": "Enumerate() in Python" }, { "code": null, "e": 30068, "s": 30026, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 30098, "s": 30068, "text": "Iterate over a list in Python" }, { "code": null, "e": 30124, "s": 30098, "text": "Python String | replace()" }, { "code": null, "e": 30153, "s": 30124, "text": "*args and **kwargs in Python" }, { "code": null, "e": 30197, "s": 30153, "text": "Reading and Writing to text files in Python" } ]
How to create Music Player UI Controls Component in ReactJS? - GeeksforGeeks
16 Sep, 2021 We can create a music-player basic UI in ReactJS using the following logic which is very simple and easy to implement. Material UI for React has this component available for us, and it is very easy to integrate. We can create it 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 npm install @material-ui/icons 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 CardContent from "@material-ui/core/CardContent";import SkipPreviousIcon from "@material-ui/icons/SkipPrevious";import SkipNextIcon from "@material-ui/icons/SkipNext";import { useTheme } from "@material-ui/core/styles";import Typography from "@material-ui/core/Typography";import IconButton from "@material-ui/core/IconButton";import CardMedia from "@material-ui/core/CardMedia";import PlayArrowIcon from "@material-ui/icons/PlayArrow";import Card from "@material-ui/core/Card"; export default function App() { const playAudio = () => { const audioEl = document.getElementsByClassName("audio-element")[0]; audioEl.play(); }; return ( <div style={{}}> <h4>How to create Music Player UI in ReactJS?</h4> <Card style={{ width: 400, display: "flex", backgroundColor: "whitesmoke", boxShadow: "4px 4px 4px gray", }} > <div style={{ display: "flex", flexDirection: "column", }} > <CardContent style={{ flex: "1 0 auto", }} > <Typography component="h5" variant="h5"> Music Title </Typography> <Typography variant="subtitle1" color="textSecondary"> Singer Name </Typography> </CardContent> <div style={{ display: "flex", alignItems: "center", paddingLeft: 1, paddingBottom: 1, }} > <IconButton aria-label="previous"> {useTheme().direction !== "rtl" ? ( <SkipPreviousIcon /> ) : ( <SkipNextIcon /> )} </IconButton> <IconButton aria-label="play/pause"> <PlayArrowIcon style={{ height: 38, width: 38, }} onClick={playAudio} /> </IconButton> <IconButton aria-label="next"> {useTheme().direction !== "rtl" ? ( <SkipNextIcon /> ) : ( <SkipPreviousIcon /> )} </IconButton> </div> </div> <CardMedia style={{ width: 151, }} image="https://write.geeksforgeeks.org/static/media/Group%20210.08204759.svg" /> <audio className="audio-element"> <source src="https://assets.coderrocketfuel.com/pomodoro-times-up.mp3"> </source> </audio> </Card> </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/cards/#ui-controls sooda367 Material-UI React-Questions ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. ReactJS useNavigate() Hook How to set background images in ReactJS ? Axios in React: A Guide for Beginners How to create a table in ReactJS ? How to navigate on path by button click in react router ? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to insert spaces/tabs in text using HTML/CSS? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 26071, "s": 26043, "text": "\n16 Sep, 2021" }, { "code": null, "e": 26341, "s": 26071, "text": "We can create a music-player basic UI in ReactJS using the following logic which is very simple and easy to implement. Material UI for React has this component available for us, and it is very easy to integrate. We can create it in ReactJS using the following approach." }, { "code": null, "e": 26391, "s": 26341, "text": "Creating React Application And Installing Module:" }, { "code": null, "e": 26455, "s": 26391, "text": "Step 1: Create a React application using the following command." }, { "code": null, "e": 26487, "s": 26455, "text": "npx create-react-app foldername" }, { "code": null, "e": 26587, "s": 26487, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command." }, { "code": null, "e": 26601, "s": 26587, "text": "cd foldername" }, { "code": null, "e": 26710, "s": 26601, "text": "Step 3: After creating the ReactJS application, Install the material-ui modules using the following command." }, { "code": null, "e": 26771, "s": 26710, "text": "npm install @material-ui/core\nnpm install @material-ui/icons" }, { "code": null, "e": 26823, "s": 26771, "text": "Project Structure: It will look like the following." }, { "code": null, "e": 26841, "s": 26823, "text": "Project Structure" }, { "code": null, "e": 26971, "s": 26841, "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": 26978, "s": 26971, "text": "App.js" }, { "code": "import React from \"react\";import CardContent from \"@material-ui/core/CardContent\";import SkipPreviousIcon from \"@material-ui/icons/SkipPrevious\";import SkipNextIcon from \"@material-ui/icons/SkipNext\";import { useTheme } from \"@material-ui/core/styles\";import Typography from \"@material-ui/core/Typography\";import IconButton from \"@material-ui/core/IconButton\";import CardMedia from \"@material-ui/core/CardMedia\";import PlayArrowIcon from \"@material-ui/icons/PlayArrow\";import Card from \"@material-ui/core/Card\"; export default function App() { const playAudio = () => { const audioEl = document.getElementsByClassName(\"audio-element\")[0]; audioEl.play(); }; return ( <div style={{}}> <h4>How to create Music Player UI in ReactJS?</h4> <Card style={{ width: 400, display: \"flex\", backgroundColor: \"whitesmoke\", boxShadow: \"4px 4px 4px gray\", }} > <div style={{ display: \"flex\", flexDirection: \"column\", }} > <CardContent style={{ flex: \"1 0 auto\", }} > <Typography component=\"h5\" variant=\"h5\"> Music Title </Typography> <Typography variant=\"subtitle1\" color=\"textSecondary\"> Singer Name </Typography> </CardContent> <div style={{ display: \"flex\", alignItems: \"center\", paddingLeft: 1, paddingBottom: 1, }} > <IconButton aria-label=\"previous\"> {useTheme().direction !== \"rtl\" ? ( <SkipPreviousIcon /> ) : ( <SkipNextIcon /> )} </IconButton> <IconButton aria-label=\"play/pause\"> <PlayArrowIcon style={{ height: 38, width: 38, }} onClick={playAudio} /> </IconButton> <IconButton aria-label=\"next\"> {useTheme().direction !== \"rtl\" ? ( <SkipNextIcon /> ) : ( <SkipPreviousIcon /> )} </IconButton> </div> </div> <CardMedia style={{ width: 151, }} image=\"https://write.geeksforgeeks.org/static/media/Group%20210.08204759.svg\" /> <audio className=\"audio-element\"> <source src=\"https://assets.coderrocketfuel.com/pomodoro-times-up.mp3\"> </source> </audio> </Card> </div> );}", "e": 29619, "s": 26978, "text": null }, { "code": null, "e": 29732, "s": 29619, "text": "Step to Run Application: Run the application using the following command from the root directory of the project." }, { "code": null, "e": 29742, "s": 29732, "text": "npm start" }, { "code": null, "e": 29841, "s": 29742, "text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output." }, { "code": null, "e": 29906, "s": 29841, "text": "Reference: https://material-ui.com/components/cards/#ui-controls" }, { "code": null, "e": 29915, "s": 29906, "text": "sooda367" }, { "code": null, "e": 29927, "s": 29915, "text": "Material-UI" }, { "code": null, "e": 29943, "s": 29927, "text": "React-Questions" }, { "code": null, "e": 29951, "s": 29943, "text": "ReactJS" }, { "code": null, "e": 29968, "s": 29951, "text": "Web Technologies" }, { "code": null, "e": 30066, "s": 29968, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30093, "s": 30066, "text": "ReactJS useNavigate() Hook" }, { "code": null, "e": 30135, "s": 30093, "text": "How to set background images in ReactJS ?" }, { "code": null, "e": 30173, "s": 30135, "text": "Axios in React: A Guide for Beginners" }, { "code": null, "e": 30208, "s": 30173, "text": "How to create a table in ReactJS ?" }, { "code": null, "e": 30266, "s": 30208, "text": "How to navigate on path by button click in react router ?" }, { "code": null, "e": 30306, "s": 30266, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 30339, "s": 30306, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 30384, "s": 30339, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 30434, "s": 30384, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
MongoDB - Logical Query Operators - GeeksforGeeks
10 May, 2020 MongoDB supports logical query operators. These operators are used for filtering the data and getting precise results based on the given conditions. The following table contains the comparison query operators: In the following examples, we are working with: Database: GeeksforGeeks Collection: contributor Document: three documents that contain the details of the contributors in the form of field-value pairs. In this example, we are retrieving only those employee’s documents whose branch is CSE and joiningYear is 2018. db.contributor.find({$and: [{branch: "CSE"}, {joiningYear: 2018}]}).pretty() In this example, we are retrieving only those employee’s documents whose salary is not 3000 and whose branch is not ECE. db.contributor.find({$nor: [{salary: 3000}, {branch: "ECE"}]}).pretty() In this example, we are retrieving only those employee’s documents whose branch is ECE or joiningYear is 2017. db.contributor.find({$or: [{branch: "ECE"}, {joiningYear: 2017}]}).pretty() In this example, we are retrieving only those employee’s documents whose salary is not greater than 2000. db.contributor.find({salary: {$not: {$gt: 2000}}}).pretty() MongoDB MongoDB-operators MongoDB Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to connect MongoDB with ReactJS ? MongoDB - limit() Method MongoDB - Distinct() Method MongoDB - FindOne() Method Create user and add role in MongoDB Export data from MongoDB MongoDB - sort() Method MongoDB - Regex MongoDB updateOne() Method - db.Collection.updateOne() MongoDB insertMany() Method - db.Collection.insertMany()
[ { "code": null, "e": 25589, "s": 25561, "text": "\n10 May, 2020" }, { "code": null, "e": 25799, "s": 25589, "text": "MongoDB supports logical query operators. These operators are used for filtering the data and getting precise results based on the given conditions. The following table contains the comparison query operators:" }, { "code": null, "e": 25847, "s": 25799, "text": "In the following examples, we are working with:" }, { "code": null, "e": 26000, "s": 25847, "text": "Database: GeeksforGeeks\nCollection: contributor\nDocument: three documents that contain the details of the contributors in the form of field-value pairs." }, { "code": null, "e": 26112, "s": 26000, "text": "In this example, we are retrieving only those employee’s documents whose branch is CSE and joiningYear is 2018." }, { "code": "db.contributor.find({$and: [{branch: \"CSE\"}, {joiningYear: 2018}]}).pretty()", "e": 26189, "s": 26112, "text": null }, { "code": null, "e": 26310, "s": 26189, "text": "In this example, we are retrieving only those employee’s documents whose salary is not 3000 and whose branch is not ECE." }, { "code": "db.contributor.find({$nor: [{salary: 3000}, {branch: \"ECE\"}]}).pretty()", "e": 26382, "s": 26310, "text": null }, { "code": null, "e": 26493, "s": 26382, "text": "In this example, we are retrieving only those employee’s documents whose branch is ECE or joiningYear is 2017." }, { "code": "db.contributor.find({$or: [{branch: \"ECE\"}, {joiningYear: 2017}]}).pretty()", "e": 26569, "s": 26493, "text": null }, { "code": null, "e": 26675, "s": 26569, "text": "In this example, we are retrieving only those employee’s documents whose salary is not greater than 2000." }, { "code": "db.contributor.find({salary: {$not: {$gt: 2000}}}).pretty()", "e": 26735, "s": 26675, "text": null }, { "code": null, "e": 26743, "s": 26735, "text": "MongoDB" }, { "code": null, "e": 26761, "s": 26743, "text": "MongoDB-operators" }, { "code": null, "e": 26769, "s": 26761, "text": "MongoDB" }, { "code": null, "e": 26867, "s": 26769, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26905, "s": 26867, "text": "How to connect MongoDB with ReactJS ?" }, { "code": null, "e": 26930, "s": 26905, "text": "MongoDB - limit() Method" }, { "code": null, "e": 26958, "s": 26930, "text": "MongoDB - Distinct() Method" }, { "code": null, "e": 26985, "s": 26958, "text": "MongoDB - FindOne() Method" }, { "code": null, "e": 27021, "s": 26985, "text": "Create user and add role in MongoDB" }, { "code": null, "e": 27046, "s": 27021, "text": "Export data from MongoDB" }, { "code": null, "e": 27070, "s": 27046, "text": "MongoDB - sort() Method" }, { "code": null, "e": 27086, "s": 27070, "text": "MongoDB - Regex" }, { "code": null, "e": 27141, "s": 27086, "text": "MongoDB updateOne() Method - db.Collection.updateOne()" } ]
Create an n x n square matrix, where all the sub-matrix have the sum of opposite corner elements as even - GeeksforGeeks
04 Aug, 2021 Given an integer N. The task is to generate a square matrix of ( n x n ) having the elements ranging from 1 to n^2 with the following condition: The elements of the matrix should be distinct i.e used only once Numbers ranging from 1 to n^2 Every sub-matrix you choose should have the sum of opposite corner elements as even i.e sum of top left and bottom right should be even and the sum of top right and bottom left element should be even This property should apply to all the submatrices of the matrix. You need to generate an Even Sub-Matrix Examples: Input: 2 Output: 1 2 4 3 Explanation: Here sum of 1+3=4 is even and 2+4=6 is even Input: 4 Output: 1 2 3 4 5 6 7 8 9 Explanation: The sub matrix [1 2 4 5], [2 3 5 6], [4 5 7 8], [5 6 8 9], [1 2 3 4 5 6 7 8 9] satisfies the condition of opposite corner elements having even sum Approach: As we know for any two elements sum to be even it can be Sum of ODD and ODD or Sum of EVEN and EVEN. In either of the two cases for the corner elements sum to be even we need to ensure that the diagonal pattern arranged elements should be either odd or even. So we make the 2d array having diagonals as all odds or all evens to find any submatrix having corner elements sum even. The below approach can be followed for the same. When n is odd the diagonals are already in all odd or even elements, so we need not modify and generate a simple 2d array When n is even the matrix generated does not satisfy the property having an even sum of opposite corner elements of the sub-matrices, so we reverse the alternate row elements so that diagonals of every submatrix are either all odd or all even. Below is the implementation. C++ Java Python3 C# // C++ program for// the above approach#include <bits/stdc++.h>using namespace std; void sub_mat_even(int N){ // Counter to initialize // the values in 2-D array int K = 1; // To create a 2-D array // from to 1 to N*2 int A[N][N]; for(int i = 0; i < N; i++) { for(int j = 0; j < N; j++) { A[i][j] = K; K++; } } // If found even we reverse // the alternate row elements // to get all diagonal elements // as all even or all odd if(N % 2 == 0) { for(int i = 0; i < N; i++) { if(i % 2 == 1) { int s = 0; int l = N - 1; // Reverse the row while(s < l) { swap(A[i][s], A[i][l]); s++; l--; } } } } // Print the formed array for(int i = 0; i < N; i++) { for(int j = 0; j < N; j++) { cout << A[i][j] << " "; } cout << endl; }} // Driver codeint main(){ int N = 4; // Function call sub_mat_even(N);} // This code is contributed by mishrapriyanshu557 // Java program for// the above approachimport java.io.*; class GFG{ static void sub_mat_even(int N){ // Counter to initialize // the values in 2-D array int K = 1; // To create a 2-D array // from to 1 to N*2 int[][] A = new int[N][N]; for(int i = 0; i < N; i++) { for(int j = 0; j < N; j++) { A[i][j] = K; K++; } } // If found even we reverse // the alternate row elements // to get all diagonal elements // as all even or all odd if (N % 2 == 0) { for(int i = 0; i < N; i++) { if (i % 2 == 1) { int s = 0; int l = N - 1; // Reverse the row while (s < l) { swap(A[i], s, l); s++; l--; } } } } // Print the formed array for(int i = 0; i < N; i++) { for(int j = 0; j < N; j++) { System.out.print(A[i][j] + " "); } System.out.println(); }} private static void swap(int[] A, int s, int l){ int temp = A[s]; A[s] = A[l]; A[l] = temp;} // Driver codepublic static void main(String[] args){ int N = 4; // Function call sub_mat_even(N);}} // This code is contributed by jithin # Python3 program for# the above approachimport itertools def sub_mat_even(n): temp = itertools.count(1) # create a 2d array ranging # from 1 to n^2 l = [[next(temp)for i in range(n)]for i in range(n)] # If found even we reverse the alternate # row elements to get all diagonal elements # as all even or all odd if n%2 == 0: for i in range(0,len(l)): if i%2 == 1: l[i][:] = l[i][::-1] # Printing the array formed for i in range(n): for j in range(n): print(l[i][j],end=" ") print() n = 4sub_mat_even(n) // C# program for// the above approachusing System;class GFG { static void sub_mat_even(int N) { // Counter to initialize // the values in 2-D array int K = 1; // To create a 2-D array // from to 1 to N*2 int[,] A = new int[N, N]; for(int i = 0; i < N; i++) { for(int j = 0; j < N; j++) { A[i, j] = K; K++; } } // If found even we reverse // the alternate row elements // to get all diagonal elements // as all even or all odd if (N % 2 == 0) { for(int i = 0; i < N; i++) { if (i % 2 == 1) { int s = 0; int l = N - 1; // Reverse the row while (s < l) { int temp = A[i, s]; A[i, s] = A[i, l]; A[i, l] = temp; s++; l--; } } } } // Print the formed array for(int i = 0; i < N; i++) { for(int j = 0; j < N; j++) { Console.Write(A[i, j] + " "); } Console.WriteLine(); } } static void Main() { int N = 4; // Function call sub_mat_even(N); }} // This code is contributed by divyeshrabadiya07 Output: 1 2 3 4 8 7 6 5 9 10 11 12 16 15 14 13 This approach takes O(n*2) time complexity. mishrapriyanshu557 jithin divyeshrabadiya07 gabaa406 Python matrix-program Python-Matrix 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": 26031, "s": 26003, "text": "\n04 Aug, 2021" }, { "code": null, "e": 26176, "s": 26031, "text": "Given an integer N. The task is to generate a square matrix of ( n x n ) having the elements ranging from 1 to n^2 with the following condition:" }, { "code": null, "e": 26241, "s": 26176, "text": "The elements of the matrix should be distinct i.e used only once" }, { "code": null, "e": 26271, "s": 26241, "text": "Numbers ranging from 1 to n^2" }, { "code": null, "e": 26471, "s": 26271, "text": "Every sub-matrix you choose should have the sum of opposite corner elements as even i.e sum of top left and bottom right should be even and the sum of top right and bottom left element should be even" }, { "code": null, "e": 26576, "s": 26471, "text": "This property should apply to all the submatrices of the matrix. You need to generate an Even Sub-Matrix" }, { "code": null, "e": 26586, "s": 26576, "text": "Examples:" }, { "code": null, "e": 26668, "s": 26586, "text": "Input: 2 Output: 1 2 4 3 Explanation: Here sum of 1+3=4 is even and 2+4=6 is even" }, { "code": null, "e": 26865, "s": 26668, "text": "Input: 4 Output: 1 2 3 4 5 6 7 8 9 Explanation: The sub matrix [1 2 4 5], [2 3 5 6], [4 5 7 8], [5 6 8 9], [1 2 3 4 5 6 7 8 9] satisfies the condition of opposite corner elements having even sum " }, { "code": null, "e": 26875, "s": 26865, "text": "Approach:" }, { "code": null, "e": 27304, "s": 26875, "text": "As we know for any two elements sum to be even it can be Sum of ODD and ODD or Sum of EVEN and EVEN. In either of the two cases for the corner elements sum to be even we need to ensure that the diagonal pattern arranged elements should be either odd or even. So we make the 2d array having diagonals as all odds or all evens to find any submatrix having corner elements sum even. The below approach can be followed for the same." }, { "code": null, "e": 27427, "s": 27304, "text": "When n is odd the diagonals are already in all odd or even elements, so we need not modify and generate a simple 2d array" }, { "code": null, "e": 27671, "s": 27427, "text": "When n is even the matrix generated does not satisfy the property having an even sum of opposite corner elements of the sub-matrices, so we reverse the alternate row elements so that diagonals of every submatrix are either all odd or all even." }, { "code": null, "e": 27700, "s": 27671, "text": "Below is the implementation." }, { "code": null, "e": 27704, "s": 27700, "text": "C++" }, { "code": null, "e": 27709, "s": 27704, "text": "Java" }, { "code": null, "e": 27717, "s": 27709, "text": "Python3" }, { "code": null, "e": 27720, "s": 27717, "text": "C#" }, { "code": "// C++ program for// the above approach#include <bits/stdc++.h>using namespace std; void sub_mat_even(int N){ // Counter to initialize // the values in 2-D array int K = 1; // To create a 2-D array // from to 1 to N*2 int A[N][N]; for(int i = 0; i < N; i++) { for(int j = 0; j < N; j++) { A[i][j] = K; K++; } } // If found even we reverse // the alternate row elements // to get all diagonal elements // as all even or all odd if(N % 2 == 0) { for(int i = 0; i < N; i++) { if(i % 2 == 1) { int s = 0; int l = N - 1; // Reverse the row while(s < l) { swap(A[i][s], A[i][l]); s++; l--; } } } } // Print the formed array for(int i = 0; i < N; i++) { for(int j = 0; j < N; j++) { cout << A[i][j] << \" \"; } cout << endl; }} // Driver codeint main(){ int N = 4; // Function call sub_mat_even(N);} // This code is contributed by mishrapriyanshu557", "e": 28753, "s": 27720, "text": null }, { "code": "// Java program for// the above approachimport java.io.*; class GFG{ static void sub_mat_even(int N){ // Counter to initialize // the values in 2-D array int K = 1; // To create a 2-D array // from to 1 to N*2 int[][] A = new int[N][N]; for(int i = 0; i < N; i++) { for(int j = 0; j < N; j++) { A[i][j] = K; K++; } } // If found even we reverse // the alternate row elements // to get all diagonal elements // as all even or all odd if (N % 2 == 0) { for(int i = 0; i < N; i++) { if (i % 2 == 1) { int s = 0; int l = N - 1; // Reverse the row while (s < l) { swap(A[i], s, l); s++; l--; } } } } // Print the formed array for(int i = 0; i < N; i++) { for(int j = 0; j < N; j++) { System.out.print(A[i][j] + \" \"); } System.out.println(); }} private static void swap(int[] A, int s, int l){ int temp = A[s]; A[s] = A[l]; A[l] = temp;} // Driver codepublic static void main(String[] args){ int N = 4; // Function call sub_mat_even(N);}} // This code is contributed by jithin", "e": 30096, "s": 28753, "text": null }, { "code": "# Python3 program for# the above approachimport itertools def sub_mat_even(n): temp = itertools.count(1) # create a 2d array ranging # from 1 to n^2 l = [[next(temp)for i in range(n)]for i in range(n)] # If found even we reverse the alternate # row elements to get all diagonal elements # as all even or all odd if n%2 == 0: for i in range(0,len(l)): if i%2 == 1: l[i][:] = l[i][::-1] # Printing the array formed for i in range(n): for j in range(n): print(l[i][j],end=\" \") print() n = 4sub_mat_even(n)", "e": 30708, "s": 30096, "text": null }, { "code": "// C# program for// the above approachusing System;class GFG { static void sub_mat_even(int N) { // Counter to initialize // the values in 2-D array int K = 1; // To create a 2-D array // from to 1 to N*2 int[,] A = new int[N, N]; for(int i = 0; i < N; i++) { for(int j = 0; j < N; j++) { A[i, j] = K; K++; } } // If found even we reverse // the alternate row elements // to get all diagonal elements // as all even or all odd if (N % 2 == 0) { for(int i = 0; i < N; i++) { if (i % 2 == 1) { int s = 0; int l = N - 1; // Reverse the row while (s < l) { int temp = A[i, s]; A[i, s] = A[i, l]; A[i, l] = temp; s++; l--; } } } } // Print the formed array for(int i = 0; i < N; i++) { for(int j = 0; j < N; j++) { Console.Write(A[i, j] + \" \"); } Console.WriteLine(); } } static void Main() { int N = 4; // Function call sub_mat_even(N); }} // This code is contributed by divyeshrabadiya07", "e": 32237, "s": 30708, "text": null }, { "code": null, "e": 32245, "s": 32237, "text": "Output:" }, { "code": null, "e": 32284, "s": 32245, "text": "1 2 3 4\n8 7 6 5\n9 10 11 12\n16 15 14 13" }, { "code": null, "e": 32328, "s": 32284, "text": "This approach takes O(n*2) time complexity." }, { "code": null, "e": 32347, "s": 32328, "text": "mishrapriyanshu557" }, { "code": null, "e": 32354, "s": 32347, "text": "jithin" }, { "code": null, "e": 32372, "s": 32354, "text": "divyeshrabadiya07" }, { "code": null, "e": 32381, "s": 32372, "text": "gabaa406" }, { "code": null, "e": 32403, "s": 32381, "text": "Python matrix-program" }, { "code": null, "e": 32417, "s": 32403, "text": "Python-Matrix" }, { "code": null, "e": 32424, "s": 32417, "text": "Python" }, { "code": null, "e": 32522, "s": 32424, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32540, "s": 32522, "text": "Python Dictionary" }, { "code": null, "e": 32575, "s": 32540, "text": "Read a file line by line in Python" }, { "code": null, "e": 32607, "s": 32575, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 32629, "s": 32607, "text": "Enumerate() in Python" }, { "code": null, "e": 32671, "s": 32629, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 32701, "s": 32671, "text": "Iterate over a list in Python" }, { "code": null, "e": 32727, "s": 32701, "text": "Python String | replace()" }, { "code": null, "e": 32756, "s": 32727, "text": "*args and **kwargs in Python" }, { "code": null, "e": 32800, "s": 32756, "text": "Reading and Writing to text files in Python" } ]
Python | sympy.atan2() method - GeeksforGeeks
24 Dec, 2021 In simpy, atan2() method is an inverse tangent function. Using the atan2(x, y) method in simpy module, we can computes the two-argument arctangent. This function is defined for real x and y only. Syntax : sympy.atan(x) Return : Returns the arc tangent of x Code #1: Below is the example using atan() method to find inverse tangent function. Python3 # importing sympy libraryfrom sympy import * # calling atan2() method on expressiongeek1 = atan2(1, 1)geek2 = atan2(1, -1) print(geek1)print(geek2) Output: pi/4 3*pi/4 Code #2: Python3 # importing sympy libraryfrom sympy import atan2 # calling atan2() method on expressiongeek = atan2(-1, -1)print(geek) Output: -3*pi/4 surindertarika1234 SymPy 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": "\n24 Dec, 2021" }, { "code": null, "e": 25734, "s": 25537, "text": "In simpy, atan2() method is an inverse tangent function. Using the atan2(x, y) method in simpy module, we can computes the two-argument arctangent. This function is defined for real x and y only. " }, { "code": null, "e": 25797, "s": 25734, "text": "Syntax : sympy.atan(x)\n\nReturn : Returns the arc tangent of x " }, { "code": null, "e": 25883, "s": 25797, "text": "Code #1: Below is the example using atan() method to find inverse tangent function. " }, { "code": null, "e": 25891, "s": 25883, "text": "Python3" }, { "code": "# importing sympy libraryfrom sympy import * # calling atan2() method on expressiongeek1 = atan2(1, 1)geek2 = atan2(1, -1) print(geek1)print(geek2)", "e": 26039, "s": 25891, "text": null }, { "code": null, "e": 26049, "s": 26039, "text": "Output: " }, { "code": null, "e": 26061, "s": 26049, "text": "pi/4\n3*pi/4" }, { "code": null, "e": 26074, "s": 26061, "text": " Code #2: " }, { "code": null, "e": 26082, "s": 26074, "text": "Python3" }, { "code": "# importing sympy libraryfrom sympy import atan2 # calling atan2() method on expressiongeek = atan2(-1, -1)print(geek)", "e": 26202, "s": 26082, "text": null }, { "code": null, "e": 26212, "s": 26202, "text": "Output: " }, { "code": null, "e": 26220, "s": 26212, "text": "-3*pi/4" }, { "code": null, "e": 26241, "s": 26222, "text": "surindertarika1234" }, { "code": null, "e": 26247, "s": 26241, "text": "SymPy" }, { "code": null, "e": 26254, "s": 26247, "text": "Python" }, { "code": null, "e": 26352, "s": 26254, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26384, "s": 26352, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26426, "s": 26384, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26468, "s": 26426, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 26524, "s": 26468, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26551, "s": 26524, "text": "Python Classes and Objects" }, { "code": null, "e": 26590, "s": 26551, "text": "Python | Get unique values from a list" }, { "code": null, "e": 26621, "s": 26590, "text": "Python | os.path.join() method" }, { "code": null, "e": 26650, "s": 26621, "text": "Create a directory in Python" }, { "code": null, "e": 26672, "s": 26650, "text": "Defaultdict in Python" } ]
How To Create a Plotly Visualization And Embed It On Websites | by Elizabeth Ter Sahakyan | Towards Data Science
Plotly is an open-source, simple-to-use charting library for python. Plotly.express was built as a wrapper for Plotly.py to make creating interactive visualizations as easy as writing one line of python ✨ plotly.express is to plotly what seaborn is to matplotlib There are so many cool interactive visualizations that can be created with Plotly Express — like this one using a dataset from Airbnb: Interactive visualizations created with Plotly express can be rendered and displayed by most notebooks and IDE’s. Embedding them elsewhere is a different story. If you’ve been running into trouble with embedding your interactive plotly visualizations you’re in the right place! In this article, I’ll go over how to create a basic interactive visualization with plotly express and generate the iframe embed code to display it on any website. The steps are as follows: create plotly visualization host visualization (either on plotly or github pages) get iframe embed code If you haven’t already, install plotly into your environment using !pip install plotly and import plotly using import plotly.express as px. Run the following code to create a basic visualization: gapminder = px.data.gapminder()fig = px.scatter(gapminder.query("year==2007"), x="gdpPercap", y="lifeExp", size="pop", color="continent", hover_name="country", log_x=True, size_max=60)fig.show() The figure below should appear in your notebook: Now that you have an interactive visualization to work with...let’s host it somewhere! If your dataset is small enough you’ll be able to upload your visualization to plotly on a free account— and if it’s not, it’ll give you an error when you try the part below. I’ll explain in the next section how to get around it if you run into the error. To upload the visualization to your plotly account, install chart studio using !pip install chart_studio and then import it using import chart_studio. You’ll need your username and api key from your plotly account to connect to it from your notebook. To get your api key, just click your username in the top right corner of your profile and click settings, then regenerate a new api key. Now you can set your credentials: username = '' # your usernameapi_key = '' # your api key - go to profile > settings > regenerate keychart_studio.tools.set_credentials_file(username=username, api_key=api_key) Push your visualiztion to your account using the following lines of code: import chart_studio.plotly as pypy.plot(fig, filename = 'gdp_per_cap', auto_open=True) If done correctly, this code should open a new window with your visualization on your account and return the link in your notebook. You can use that same link to then embed on websites that support embedding with embed.ly, like Medium. Note: while you’re drafting a post on Medium your visualization will not be interactive, but once you publish it it will work. Here is the interactive visualization we created that I embedded in Medium just by pasting the link ...easy. If uploading your visualization to plotly worked for you — great. You can skip over to the next section where I’ll show you how to generate the iframe embed code. When the dataset you’re working with is too big, you will get an error from plotly that you can’t upload the visualization unless you upgrade your account. So to get around this we are going to write our plotly visualization to HTML. First, let’s create a visualization with a large data set. I’m going to use data from Airbnb, which can be found in this github repo. You can download the csv if you want to follow along. Below is the code to create the dataframe that I’ll be using: And here is the code to create the visualization: fig = px.scatter(df, x='Neighborhood', y='Price (US Dollars)' ,size='Accommodates' , hover_data=['Bedrooms', 'Wifi', 'Cable TV', 'Kitchen', 'Washer', 'Number of Reviews'] ,color= 'Room Type')fig.update_layout(template='plotly_white')fig.update_layout(title='How much should you charge in a Berlin neighborhood?')fig.show() The output will look like this: And now if you try uploading this to your plotly account using py.plot(fig, filename='airbnb', auto_open=True), you will get this error: PlotlyRequestError: This file is too big! Your current subscription is limited to 524.288 KB uploads. For more information, please visit: https://go.plot.ly/get-pricing. So instead, we’re going to write our visualization to HTML and host it on github pages. To generate the HTML file for the plotly visualization, use: import plotly.io as piopio.write_html(fig, file=’index.html’, auto_open=True) If done correctly, this code will open up the local HTML file in your browser and you should see the visualization. Publishing to github pages is super simple. You can follow the instructions documented by github here or follow my brief overview. Create a new github repo and initialize with a README.md. Upload the index.html file we just created and commit it to the master branch. Now, click settings, and scroll down to the github pages section and under ‘Source’ select ‘master branch’ . You should now be able to view your visualization using this link structure http://username.github.io/repository And the one I just made can be found here https://elizabethts.github.io/publish-plotly-website/. Now that we have the link to our plotly visualization (either hosted on plotly or github pages) we can generate an iframe code for the visualization. If you were able to upload your visualization to plotly, generating the iframe embed code can be done with this line of code: import chart_studio.tools as tlstls.get_embed('https://plot.ly/~elizabethts/9/') #change to your url This will give you the output: <iframe id="igraph" scrolling="no" style="border:none;" seamless="seamless" src="https://plot.ly/~elizabethts/9.embed" height="525" width="100%"></iframe> If you went the github pages route, you will need to modify the iframe code above yourself. Just replace the plotly url with the github url! Finally, you can place this iframe embed code into your site and your visualization will appear! Note: you might have to modify the height and width if you are using the github link. Ironically, you can’t embed your interactive visualization on Medium if your dataset was too large and you had to host it on github, that I know of. To get around this, I highly recommend using CloudApp to screen record gifs that you can easily drag and drop into your Medium article, which is what I did in this one. And there you go — you can now create an interactive plotly visualization and generate the iframe embed code to display it on any website! Find me on twitter @elizabethets!
[ { "code": null, "e": 376, "s": 171, "text": "Plotly is an open-source, simple-to-use charting library for python. Plotly.express was built as a wrapper for Plotly.py to make creating interactive visualizations as easy as writing one line of python ✨" }, { "code": null, "e": 434, "s": 376, "text": "plotly.express is to plotly what seaborn is to matplotlib" }, { "code": null, "e": 569, "s": 434, "text": "There are so many cool interactive visualizations that can be created with Plotly Express — like this one using a dataset from Airbnb:" }, { "code": null, "e": 847, "s": 569, "text": "Interactive visualizations created with Plotly express can be rendered and displayed by most notebooks and IDE’s. Embedding them elsewhere is a different story. If you’ve been running into trouble with embedding your interactive plotly visualizations you’re in the right place!" }, { "code": null, "e": 1010, "s": 847, "text": "In this article, I’ll go over how to create a basic interactive visualization with plotly express and generate the iframe embed code to display it on any website." }, { "code": null, "e": 1036, "s": 1010, "text": "The steps are as follows:" }, { "code": null, "e": 1064, "s": 1036, "text": "create plotly visualization" }, { "code": null, "e": 1118, "s": 1064, "text": "host visualization (either on plotly or github pages)" }, { "code": null, "e": 1140, "s": 1118, "text": "get iframe embed code" }, { "code": null, "e": 1280, "s": 1140, "text": "If you haven’t already, install plotly into your environment using !pip install plotly and import plotly using import plotly.express as px." }, { "code": null, "e": 1336, "s": 1280, "text": "Run the following code to create a basic visualization:" }, { "code": null, "e": 1541, "s": 1336, "text": "gapminder = px.data.gapminder()fig = px.scatter(gapminder.query(\"year==2007\"), x=\"gdpPercap\", y=\"lifeExp\", size=\"pop\", color=\"continent\", hover_name=\"country\", log_x=True, size_max=60)fig.show()" }, { "code": null, "e": 1590, "s": 1541, "text": "The figure below should appear in your notebook:" }, { "code": null, "e": 1677, "s": 1590, "text": "Now that you have an interactive visualization to work with...let’s host it somewhere!" }, { "code": null, "e": 1933, "s": 1677, "text": "If your dataset is small enough you’ll be able to upload your visualization to plotly on a free account— and if it’s not, it’ll give you an error when you try the part below. I’ll explain in the next section how to get around it if you run into the error." }, { "code": null, "e": 2084, "s": 1933, "text": "To upload the visualization to your plotly account, install chart studio using !pip install chart_studio and then import it using import chart_studio." }, { "code": null, "e": 2355, "s": 2084, "text": "You’ll need your username and api key from your plotly account to connect to it from your notebook. To get your api key, just click your username in the top right corner of your profile and click settings, then regenerate a new api key. Now you can set your credentials:" }, { "code": null, "e": 2531, "s": 2355, "text": "username = '' # your usernameapi_key = '' # your api key - go to profile > settings > regenerate keychart_studio.tools.set_credentials_file(username=username, api_key=api_key)" }, { "code": null, "e": 2605, "s": 2531, "text": "Push your visualiztion to your account using the following lines of code:" }, { "code": null, "e": 2692, "s": 2605, "text": "import chart_studio.plotly as pypy.plot(fig, filename = 'gdp_per_cap', auto_open=True)" }, { "code": null, "e": 3055, "s": 2692, "text": "If done correctly, this code should open a new window with your visualization on your account and return the link in your notebook. You can use that same link to then embed on websites that support embedding with embed.ly, like Medium. Note: while you’re drafting a post on Medium your visualization will not be interactive, but once you publish it it will work." }, { "code": null, "e": 3164, "s": 3055, "text": "Here is the interactive visualization we created that I embedded in Medium just by pasting the link ...easy." }, { "code": null, "e": 3327, "s": 3164, "text": "If uploading your visualization to plotly worked for you — great. You can skip over to the next section where I’ll show you how to generate the iframe embed code." }, { "code": null, "e": 3561, "s": 3327, "text": "When the dataset you’re working with is too big, you will get an error from plotly that you can’t upload the visualization unless you upgrade your account. So to get around this we are going to write our plotly visualization to HTML." }, { "code": null, "e": 3749, "s": 3561, "text": "First, let’s create a visualization with a large data set. I’m going to use data from Airbnb, which can be found in this github repo. You can download the csv if you want to follow along." }, { "code": null, "e": 3811, "s": 3749, "text": "Below is the code to create the dataframe that I’ll be using:" }, { "code": null, "e": 3861, "s": 3811, "text": "And here is the code to create the visualization:" }, { "code": null, "e": 4232, "s": 3861, "text": "fig = px.scatter(df, x='Neighborhood', y='Price (US Dollars)' ,size='Accommodates' , hover_data=['Bedrooms', 'Wifi', 'Cable TV', 'Kitchen', 'Washer', 'Number of Reviews'] ,color= 'Room Type')fig.update_layout(template='plotly_white')fig.update_layout(title='How much should you charge in a Berlin neighborhood?')fig.show()" }, { "code": null, "e": 4264, "s": 4232, "text": "The output will look like this:" }, { "code": null, "e": 4401, "s": 4264, "text": "And now if you try uploading this to your plotly account using py.plot(fig, filename='airbnb', auto_open=True), you will get this error:" }, { "code": null, "e": 4571, "s": 4401, "text": "PlotlyRequestError: This file is too big! Your current subscription is limited to 524.288 KB uploads. For more information, please visit: https://go.plot.ly/get-pricing." }, { "code": null, "e": 4659, "s": 4571, "text": "So instead, we’re going to write our visualization to HTML and host it on github pages." }, { "code": null, "e": 4720, "s": 4659, "text": "To generate the HTML file for the plotly visualization, use:" }, { "code": null, "e": 4798, "s": 4720, "text": "import plotly.io as piopio.write_html(fig, file=’index.html’, auto_open=True)" }, { "code": null, "e": 4914, "s": 4798, "text": "If done correctly, this code will open up the local HTML file in your browser and you should see the visualization." }, { "code": null, "e": 5045, "s": 4914, "text": "Publishing to github pages is super simple. You can follow the instructions documented by github here or follow my brief overview." }, { "code": null, "e": 5291, "s": 5045, "text": "Create a new github repo and initialize with a README.md. Upload the index.html file we just created and commit it to the master branch. Now, click settings, and scroll down to the github pages section and under ‘Source’ select ‘master branch’ ." }, { "code": null, "e": 5404, "s": 5291, "text": "You should now be able to view your visualization using this link structure http://username.github.io/repository" }, { "code": null, "e": 5501, "s": 5404, "text": "And the one I just made can be found here https://elizabethts.github.io/publish-plotly-website/." }, { "code": null, "e": 5777, "s": 5501, "text": "Now that we have the link to our plotly visualization (either hosted on plotly or github pages) we can generate an iframe code for the visualization. If you were able to upload your visualization to plotly, generating the iframe embed code can be done with this line of code:" }, { "code": null, "e": 5878, "s": 5777, "text": "import chart_studio.tools as tlstls.get_embed('https://plot.ly/~elizabethts/9/') #change to your url" }, { "code": null, "e": 5909, "s": 5878, "text": "This will give you the output:" }, { "code": null, "e": 6064, "s": 5909, "text": "<iframe id=\"igraph\" scrolling=\"no\" style=\"border:none;\" seamless=\"seamless\" src=\"https://plot.ly/~elizabethts/9.embed\" height=\"525\" width=\"100%\"></iframe>" }, { "code": null, "e": 6205, "s": 6064, "text": "If you went the github pages route, you will need to modify the iframe code above yourself. Just replace the plotly url with the github url!" }, { "code": null, "e": 6388, "s": 6205, "text": "Finally, you can place this iframe embed code into your site and your visualization will appear! Note: you might have to modify the height and width if you are using the github link." }, { "code": null, "e": 6706, "s": 6388, "text": "Ironically, you can’t embed your interactive visualization on Medium if your dataset was too large and you had to host it on github, that I know of. To get around this, I highly recommend using CloudApp to screen record gifs that you can easily drag and drop into your Medium article, which is what I did in this one." }, { "code": null, "e": 6845, "s": 6706, "text": "And there you go — you can now create an interactive plotly visualization and generate the iframe embed code to display it on any website!" } ]
Align text and select boxes to the same width with HTML and CSS
When we set the width and height of an element in CSS then often the element appears bigger than the actual size. This is because by default, the padding and border are added to the element’s width and height and then the element is displayed. The box sizing property includes the padding and border of an element with actual width and height so that the element does not appear bigger than the actual size. The format to use this property is “box-sizing: box-border” You can try to run the following code to align text and select boxes to the same width − <html> <head> <style> input, select { width: 250px; border: 2px solid #000; padding: 0; margin: 0; height: 22px; -moz-box-sizing: border-box; -webkit-box-sizing: border-box; box-sizing: border-box; } input { text-indent: 3px; } </style> </head> <body> <input type = "text" value = "Name of Candidate"><br> <select> <option>Select Choice</option> <option>Student</option> <option>Teachers</option> <option>Head</option> </select> </body> </html>
[ { "code": null, "e": 1306, "s": 1062, "text": "When we set the width and height of an element in CSS then often the element appears bigger than the actual size. This is because by default, the padding and border are added to the element’s width and height and then the element is displayed." }, { "code": null, "e": 1530, "s": 1306, "text": "The box sizing property includes the padding and border of an element with actual width and height so that the element does not appear bigger than the actual size. The format to use this property is “box-sizing: box-border”" }, { "code": null, "e": 1619, "s": 1530, "text": "You can try to run the following code to align text and select boxes to the same width −" }, { "code": null, "e": 2286, "s": 1619, "text": "<html>\n <head>\n <style>\n input, select {\n width: 250px;\n border: 2px solid #000;\n padding: 0;\n margin: 0;\n height: 22px;\n -moz-box-sizing: border-box;\n -webkit-box-sizing: border-box;\n box-sizing: border-box;\n }\n input {\n text-indent: 3px;\n }\n </style>\n </head>\n <body>\n <input type = \"text\" value = \"Name of Candidate\"><br>\n <select>\n <option>Select Choice</option>\n <option>Student</option>\n <option>Teachers</option>\n <option>Head</option>\n </select>\n </body>\n</html>" } ]
GAN — Ways to improve GAN performance | by Jonathan Hui | Towards Data Science
GAN models can suffer badly in the following areas comparing to other deep networks. Non-convergence: the models do not converge and worse they become unstable. Mode collapse: the generator produces limited modes, and Slow training: the gradient to train the generator vanished. As part of the GAN series, this article looks into ways on how to improve GAN. In particular, Change the cost function for a better optimization goal. Add additional penalties to the cost function to enforce constraints. Avoid overconfidence and overfitting. Better ways of optimizing the model. Add labels. But be aware that this is a dynamic topic as research remains highly active. The generator tries to find the best image to fool the discriminator. The “best” image keeps changing when both networks counteract their opponent. However, the optimization can turn too greedy and fall it into a never-ending cat-and-mouse game. This is one of the scenarios that the model does not converge and mode collapses. Feature matching changes the cost function for the generator to minimizing the statistical difference between the features of the real images and the generated images. Often, we measure the L2-distance between the means of their feature vectors. Therefore, feature matching expands the goal from beating the opponent to matching features in real images. Here is the new objective function: where f(x) is the feature vector extracted in an immediate layer by the discriminator. The means of the real image features are computed per minibatch which fluctuate on every batch. It is good news in mitigating the mode collapse. It introduces randomness that makes the discriminator harder to overfit itself. Feature matching is effective when the GAN model is unstable during training. When mode collapses, all images created looks similar. To mitigate the problem, we feed real images and generated images into the discriminator separately in different batches and compute the similarity of the image x with images in the same batch. We append the similarity o(x) in one of the dense layers in the discriminator to classify whether this image is real or generated. If the mode starts to collapse, the similarity of generated images increases. The discriminator can use this score to detect generated images and penalize the generator if mode is collapsing. The similarity o(xi) between the image xi and other images in the same batch is computed by a transformation matrix T. The equations are a little bit hard to trace but the concept is pretty simple. But feel free to skip to next section if you want. In the figure above, xi is the input image and xj is the rest of the images in the same batch. We use a transformation matrix T to transform the features xi to Mi which is a B×C matrix. We derive the similarity c(xi, xj) between image i and j using the L1-norm and the following equation. The similarity o(xi) between image xi and the rest of images in the batch is Here is the recap: As a quote from the paper “Improved Techniques for Training GANs” Minibatch discrimination allows us to generate visually appealing samples very quickly, and in this regard it is superior to feature matching. Deep networks may suffer from overconfidence. For example, it uses very few features to classify an object. To mitigate the problem, deep learning uses regulation and dropout to avoid overconfidence. In GAN, if the discriminator depends on a small set of features to detect real images, the generator may just produce these features only to exploit the discriminator. The optimization may turn too greedy and produces no long term benefit. In GAN, overconfidence hurts badly. To avoid the problem, we penalize the discriminator when the prediction for any real images go beyond 0.9 (D(real image)>0.9). This is done by setting our target label value to be 0.9 instead of 1.0. Here is the pseudo code: p = tf.placeholder(tf.float32, shape=[None, 10])# Use 0.9 instead of 1.0.feed_dict = { p: [[0, 0, 0, 0.9, 0, 0, 0, 0, 0, 0]] # Image with label "3"}# logits_real_image is the logits calculated by # the discriminator for real images.d_real_loss = tf.nn.sigmoid_cross_entropy_with_logits( labels=p, logits=logits_real_image) In historical averaging, we keep track of the model parameters for the last t models. Alternatively, we update a running average of the model parameters if we need to keep a long sequence of models. We add an L2 cost below to the cost function to penalize model different from the historical average. For GANs with non-convex object function, historical averaging may stop models circle around the equilibrium point and act as a damping force to converge the model. The model optimization can be too greedy in defeating what the generator is currently generating. To address this problem, experience replay maintains the most recent generated images from the past optimization iterations. Instead of fitting the models with current generated images only, we feed the discriminator with all recent generated images also. Hence, the discriminator will not be overfitted for a particular time instance of the generator. Many datasets come with labels for the object type of their samples. Training GAN is already hard. So any extra help in guiding the GAN training can improve the performance a lot. Adding the label as part of the latent space z helps the GAN training. Below is the data flow used in CGAN to take advantage of the labels in the samples. Do cost functions matter? It must be otherwise all those research efforts will be a waste. But if you hear about a 2017 Google Brain paper, you will definitely have doubts. But pushing image quality is still a top priority. Likely, we will see researchers trying different cost functions before we have a definite answer for the merit. The following figure lists the cost functions for some common GAN models. We decide not to detail these cost functions in this article. Here are the articles that covers some common cost functions in details: WGAN/WGAN-GP, EBGAN/BEGAN, LSGAN, RGAN and RaGAN. At the end of this article, we list an article that studies all these cost functions in more details. Since cost function is one major research area in GAN, we do encourage you to read that article later. Here is some of the FID score (the lower the better) on some of the datasets. This is one reference point but be warned that it is still too early to make any conclusion on what cost functions perform the best. Indeed, there is no single cost function that performs the best among all different datasets yet. (MM GAN is the GAN cost function in the original paper. NS GAN is the alternative cost functions addressing the vanishing gradients in the same paper.) But no model performs well without good hyperparameters and tuning GANs takes time. Be patient in the hyperparameters optimization before randomly testing different cost functions. Some researchers had suggested that tunning the hyperparameters may ripe a better return than changing the cost functions. A carefully tunned learning rate may mitigate some serious GAN’s problems like mode collapse. In specific, lower the learning rate and redo the training when mode collapse happens. We can also experiment with different learning rates for the generator and the discriminator. For example, the following graph use the learning rate of 0.0003 for the discriminator and 0.0001 for the generator in the WGAN-GP training. Scale the image pixel value between -1 and 1. Use tanh as the output layer for the generator. Experiment sampling z with Gaussian distributions. Batch normalization often stabilizes training. Use PixelShuffle and transpose convolution for upsampling. Avoid max pooling for downsampling. Use convolution stride. Adam optimizer usually works better than other methods. Add noise to the real and generated images before feeding them into the discriminator. The dynamics of the GAN models are not well understood yet. So some of the tips are just suggestions and the mileage may vary. For example, the LSGAN paper reports RMSProp has more stable training in their experiments. This is kind of rare but demonstrates the challenges of making generic recommendations. The discriminator and the generator are constantly competing with others. Be prepared that the cost function value may go up and down. Don’t stop the training pre-maturely even the cost may seem to trend up. Monitor the results visually to verify the progress of the training. Batch normalization BM becomes a de facto standard in many deep network design. The mean and the variance of BM is derived from the current minibatch. However, it creates a dependency between samples. The generated images are not independent of each other. This is reflected in experiments which generated images show color tint in the same batch. Originally, we sample z from a random distribution that gives us independent samples. However, the bias created by the batch normalization overwhelm the randomness of z. Virtual batch normalization (VBN) samples a reference batch before the training. In the forward pass, we can preselect a reference batch to compute the normalization parameters (μ and σ) for the BN. However, we will overfit the model with this reference batch since we use the same batch over the whole training. To mitigate that, we can combine a reference batch with the current batch to compute the normalization parameters. The random seeds used to initialize the model parameters impact the performance of GAN. As shown below, the FID scores in measuring the GAN performance vary in 50 individual runs (training). But the range is relatively small and likely to be done in later fine tuning only. A Google Brain paper indicates LSGAN occasionally fails or collapses in some dataset, and training needs to be restarted with another random seed. DGCAN strongly recommends adding BM into the network design. The use of BM also become a general practice in many deep network model. However, there will be exceptions. The following figure demonstrates the impact of BN on different dataset. The y-axis is the FID score which the lower the better. As suggested by the WGAN-GP paper, BN should be off when it is used. We suggest readers to check the cost function used and the corresponding FID performance on BN, and verify the setting with experiments. Spectral Normalization is a weight normalization that stabilizes the training of the discriminator. It controls the Lipschitz constant of the discriminator to mitigate the exploding gradient problem and the mode collapse problem. The concept is based heavily on maths but conceptually, it restricts the weight changes in each iteration and not over depending on a small set of features in distinguishing images by the discriminator. This approach will be computationally light compared with WGAN-GP and achieve good mode coverage that haunts many GAN methods. Mode collapse may not be all bad. The image quality often improves when mode collapses. In fact, we may collect the best model for each mode and use them to recreate different modes of images. The discriminator and generator are always in a tug of war to undercut each other. Mode collapse and gradient diminishing are often explained as an imbalance between the discriminator and the generator. We can improve GAN by turning our attention in balancing the loss between the generator and the discriminator. Unfortunately, the solution seems elusive. We can maintain a static ratio between the number of gradient descent iterations on the discriminator and the generator. Even this seems appealing but many doubt its benefit. Often, we maintain a one-to-one ratio. But some researchers also test out a ratio of 5 discriminator iterations per generator update. Balancing both networks with dynamic mechanics is also proposed. But not until recent years, we get some traction on it. On the other hand, some researchers challenge the feasibility and desirability of balancing these networks. A well-trained discriminator gives quality feedback to the generator anyway. Also, it is not easy to train the generator to always catch up with the discriminator. Instead, we may turn the attention into finding a cost function that does not have a close-to-zero gradient when the generator is not performing well. Nevertheless, issues remain. Many cost function proposals are made and the debates on what is the best remain. The model for the discriminator is usually more complex than the generator (more filters and more layers) and a good discriminator gives quality information. In many GAN applications, we may run into bottlenecks where increasing generator capacity shows no quality improvement. Until we identify the bottlenecks and resolve them, increasing generator capacity does not seem to be a priority for many partitioners. BigGAN was published in 2018 with the goal of pulling together some practices for GAN in generating the best images at that time. In this section, we will study some of the practices that not yet covered. Larger batch size Increase the batch size can have a significant drop in FID as shown above. With a bigger batch size, more modes are covered and provide better gradients for both networks to learn. But yet, BigGAN reports the model reaches better performance in fewer iterations, but become unstable and even collapse afterward. So, save the model constantly. Truncation Trick Low probability density region in the latent space z may not have enough training data to learn it accurately. So when generating images, we can avoid those regions to improve the image quality at the cost of the variation. i.e. the quality of images will increase but those generated images will have lower variance in style. There are different techniques to truncate the input latent space z. The general principle is when values fall outside a range, it will be resampled or squeeze to the higher-probability region. Increase model capacity During tuning, consider increasing the capacity of the model, in particular for layers with high-spatial resolutions. Many models show improvement when double the traditional capacity used at the time. But don’t do it too early without proofing the model design and implementation first. Moving averages of Generator weights The weights used by the generator are computed from an exponential moving average of the weights of the generator. Orthogonal regularization The condition of the weight matrix is a heavy studied topic. This is a study on how sensitive a function output is to changes in its input. It has a large impact on training stability. A matrix Q is orthogonal if If we multiply x with an orthogonal matrix, the changes in x will not be magnified. This behavior is very desirable for maintaining numerical stability. With other properties, maintain the orthogonal properties of the weight matrix can be appealing in deep learning. We can add an orthogonal regularization to encourage such properties during training. It penalizes the system if Q deviates from being an orthogonal matrix. Nevertheless, this is known to be too limiting and therefore BigGAN uses a modified term: The orthogonal regularization also allows the truncation trick to be more successful across different models. Orthogonal weight initialization The model weight is initialized to be a random orthogonal matrix. Skip-z connection In the vanilla GAN, the latent factor z is input to the first layer only. With skip-z connection, direct skip connections (skip-z) from the latent factor z is connected to multiple layers of the generator rather than just the first layer. In this article, we do not detail the improvement through the cost function. This is an important topic and we recommend readers to read the article below: medium.com To know more cool applications of GANs: medium.com All the articles in this series. medium.com Improved Techniques for Training GANs
[ { "code": null, "e": 257, "s": 172, "text": "GAN models can suffer badly in the following areas comparing to other deep networks." }, { "code": null, "e": 333, "s": 257, "text": "Non-convergence: the models do not converge and worse they become unstable." }, { "code": null, "e": 390, "s": 333, "text": "Mode collapse: the generator produces limited modes, and" }, { "code": null, "e": 451, "s": 390, "text": "Slow training: the gradient to train the generator vanished." }, { "code": null, "e": 545, "s": 451, "text": "As part of the GAN series, this article looks into ways on how to improve GAN. In particular," }, { "code": null, "e": 602, "s": 545, "text": "Change the cost function for a better optimization goal." }, { "code": null, "e": 672, "s": 602, "text": "Add additional penalties to the cost function to enforce constraints." }, { "code": null, "e": 710, "s": 672, "text": "Avoid overconfidence and overfitting." }, { "code": null, "e": 747, "s": 710, "text": "Better ways of optimizing the model." }, { "code": null, "e": 759, "s": 747, "text": "Add labels." }, { "code": null, "e": 836, "s": 759, "text": "But be aware that this is a dynamic topic as research remains highly active." }, { "code": null, "e": 1164, "s": 836, "text": "The generator tries to find the best image to fool the discriminator. The “best” image keeps changing when both networks counteract their opponent. However, the optimization can turn too greedy and fall it into a never-ending cat-and-mouse game. This is one of the scenarios that the model does not converge and mode collapses." }, { "code": null, "e": 1554, "s": 1164, "text": "Feature matching changes the cost function for the generator to minimizing the statistical difference between the features of the real images and the generated images. Often, we measure the L2-distance between the means of their feature vectors. Therefore, feature matching expands the goal from beating the opponent to matching features in real images. Here is the new objective function:" }, { "code": null, "e": 1641, "s": 1554, "text": "where f(x) is the feature vector extracted in an immediate layer by the discriminator." }, { "code": null, "e": 1866, "s": 1641, "text": "The means of the real image features are computed per minibatch which fluctuate on every batch. It is good news in mitigating the mode collapse. It introduces randomness that makes the discriminator harder to overfit itself." }, { "code": null, "e": 1944, "s": 1866, "text": "Feature matching is effective when the GAN model is unstable during training." }, { "code": null, "e": 2324, "s": 1944, "text": "When mode collapses, all images created looks similar. To mitigate the problem, we feed real images and generated images into the discriminator separately in different batches and compute the similarity of the image x with images in the same batch. We append the similarity o(x) in one of the dense layers in the discriminator to classify whether this image is real or generated." }, { "code": null, "e": 2516, "s": 2324, "text": "If the mode starts to collapse, the similarity of generated images increases. The discriminator can use this score to detect generated images and penalize the generator if mode is collapsing." }, { "code": null, "e": 2765, "s": 2516, "text": "The similarity o(xi) between the image xi and other images in the same batch is computed by a transformation matrix T. The equations are a little bit hard to trace but the concept is pretty simple. But feel free to skip to next section if you want." }, { "code": null, "e": 2951, "s": 2765, "text": "In the figure above, xi is the input image and xj is the rest of the images in the same batch. We use a transformation matrix T to transform the features xi to Mi which is a B×C matrix." }, { "code": null, "e": 3054, "s": 2951, "text": "We derive the similarity c(xi, xj) between image i and j using the L1-norm and the following equation." }, { "code": null, "e": 3131, "s": 3054, "text": "The similarity o(xi) between image xi and the rest of images in the batch is" }, { "code": null, "e": 3150, "s": 3131, "text": "Here is the recap:" }, { "code": null, "e": 3216, "s": 3150, "text": "As a quote from the paper “Improved Techniques for Training GANs”" }, { "code": null, "e": 3359, "s": 3216, "text": "Minibatch discrimination allows us to generate visually appealing samples very quickly, and in this regard it is superior to feature matching." }, { "code": null, "e": 3559, "s": 3359, "text": "Deep networks may suffer from overconfidence. For example, it uses very few features to classify an object. To mitigate the problem, deep learning uses regulation and dropout to avoid overconfidence." }, { "code": null, "e": 4060, "s": 3559, "text": "In GAN, if the discriminator depends on a small set of features to detect real images, the generator may just produce these features only to exploit the discriminator. The optimization may turn too greedy and produces no long term benefit. In GAN, overconfidence hurts badly. To avoid the problem, we penalize the discriminator when the prediction for any real images go beyond 0.9 (D(real image)>0.9). This is done by setting our target label value to be 0.9 instead of 1.0. Here is the pseudo code:" }, { "code": null, "e": 4403, "s": 4060, "text": "p = tf.placeholder(tf.float32, shape=[None, 10])# Use 0.9 instead of 1.0.feed_dict = { p: [[0, 0, 0, 0.9, 0, 0, 0, 0, 0, 0]] # Image with label \"3\"}# logits_real_image is the logits calculated by # the discriminator for real images.d_real_loss = tf.nn.sigmoid_cross_entropy_with_logits( labels=p, logits=logits_real_image)" }, { "code": null, "e": 4602, "s": 4403, "text": "In historical averaging, we keep track of the model parameters for the last t models. Alternatively, we update a running average of the model parameters if we need to keep a long sequence of models." }, { "code": null, "e": 4704, "s": 4602, "text": "We add an L2 cost below to the cost function to penalize model different from the historical average." }, { "code": null, "e": 4869, "s": 4704, "text": "For GANs with non-convex object function, historical averaging may stop models circle around the equilibrium point and act as a damping force to converge the model." }, { "code": null, "e": 5320, "s": 4869, "text": "The model optimization can be too greedy in defeating what the generator is currently generating. To address this problem, experience replay maintains the most recent generated images from the past optimization iterations. Instead of fitting the models with current generated images only, we feed the discriminator with all recent generated images also. Hence, the discriminator will not be overfitted for a particular time instance of the generator." }, { "code": null, "e": 5655, "s": 5320, "text": "Many datasets come with labels for the object type of their samples. Training GAN is already hard. So any extra help in guiding the GAN training can improve the performance a lot. Adding the label as part of the latent space z helps the GAN training. Below is the data flow used in CGAN to take advantage of the labels in the samples." }, { "code": null, "e": 5991, "s": 5655, "text": "Do cost functions matter? It must be otherwise all those research efforts will be a waste. But if you hear about a 2017 Google Brain paper, you will definitely have doubts. But pushing image quality is still a top priority. Likely, we will see researchers trying different cost functions before we have a definite answer for the merit." }, { "code": null, "e": 6065, "s": 5991, "text": "The following figure lists the cost functions for some common GAN models." }, { "code": null, "e": 6455, "s": 6065, "text": "We decide not to detail these cost functions in this article. Here are the articles that covers some common cost functions in details: WGAN/WGAN-GP, EBGAN/BEGAN, LSGAN, RGAN and RaGAN. At the end of this article, we list an article that studies all these cost functions in more details. Since cost function is one major research area in GAN, we do encourage you to read that article later." }, { "code": null, "e": 6764, "s": 6455, "text": "Here is some of the FID score (the lower the better) on some of the datasets. This is one reference point but be warned that it is still too early to make any conclusion on what cost functions perform the best. Indeed, there is no single cost function that performs the best among all different datasets yet." }, { "code": null, "e": 6916, "s": 6764, "text": "(MM GAN is the GAN cost function in the original paper. NS GAN is the alternative cost functions addressing the vanishing gradients in the same paper.)" }, { "code": null, "e": 7401, "s": 6916, "text": "But no model performs well without good hyperparameters and tuning GANs takes time. Be patient in the hyperparameters optimization before randomly testing different cost functions. Some researchers had suggested that tunning the hyperparameters may ripe a better return than changing the cost functions. A carefully tunned learning rate may mitigate some serious GAN’s problems like mode collapse. In specific, lower the learning rate and redo the training when mode collapse happens." }, { "code": null, "e": 7636, "s": 7401, "text": "We can also experiment with different learning rates for the generator and the discriminator. For example, the following graph use the learning rate of 0.0003 for the discriminator and 0.0001 for the generator in the WGAN-GP training." }, { "code": null, "e": 7730, "s": 7636, "text": "Scale the image pixel value between -1 and 1. Use tanh as the output layer for the generator." }, { "code": null, "e": 7781, "s": 7730, "text": "Experiment sampling z with Gaussian distributions." }, { "code": null, "e": 7828, "s": 7781, "text": "Batch normalization often stabilizes training." }, { "code": null, "e": 7887, "s": 7828, "text": "Use PixelShuffle and transpose convolution for upsampling." }, { "code": null, "e": 7947, "s": 7887, "text": "Avoid max pooling for downsampling. Use convolution stride." }, { "code": null, "e": 8003, "s": 7947, "text": "Adam optimizer usually works better than other methods." }, { "code": null, "e": 8090, "s": 8003, "text": "Add noise to the real and generated images before feeding them into the discriminator." }, { "code": null, "e": 8397, "s": 8090, "text": "The dynamics of the GAN models are not well understood yet. So some of the tips are just suggestions and the mileage may vary. For example, the LSGAN paper reports RMSProp has more stable training in their experiments. This is kind of rare but demonstrates the challenges of making generic recommendations." }, { "code": null, "e": 8674, "s": 8397, "text": "The discriminator and the generator are constantly competing with others. Be prepared that the cost function value may go up and down. Don’t stop the training pre-maturely even the cost may seem to trend up. Monitor the results visually to verify the progress of the training." }, { "code": null, "e": 8931, "s": 8674, "text": "Batch normalization BM becomes a de facto standard in many deep network design. The mean and the variance of BM is derived from the current minibatch. However, it creates a dependency between samples. The generated images are not independent of each other." }, { "code": null, "e": 9022, "s": 8931, "text": "This is reflected in experiments which generated images show color tint in the same batch." }, { "code": null, "e": 9192, "s": 9022, "text": "Originally, we sample z from a random distribution that gives us independent samples. However, the bias created by the batch normalization overwhelm the randomness of z." }, { "code": null, "e": 9620, "s": 9192, "text": "Virtual batch normalization (VBN) samples a reference batch before the training. In the forward pass, we can preselect a reference batch to compute the normalization parameters (μ and σ) for the BN. However, we will overfit the model with this reference batch since we use the same batch over the whole training. To mitigate that, we can combine a reference batch with the current batch to compute the normalization parameters." }, { "code": null, "e": 9894, "s": 9620, "text": "The random seeds used to initialize the model parameters impact the performance of GAN. As shown below, the FID scores in measuring the GAN performance vary in 50 individual runs (training). But the range is relatively small and likely to be done in later fine tuning only." }, { "code": null, "e": 10041, "s": 9894, "text": "A Google Brain paper indicates LSGAN occasionally fails or collapses in some dataset, and training needs to be restarted with another random seed." }, { "code": null, "e": 10545, "s": 10041, "text": "DGCAN strongly recommends adding BM into the network design. The use of BM also become a general practice in many deep network model. However, there will be exceptions. The following figure demonstrates the impact of BN on different dataset. The y-axis is the FID score which the lower the better. As suggested by the WGAN-GP paper, BN should be off when it is used. We suggest readers to check the cost function used and the corresponding FID performance on BN, and verify the setting with experiments." }, { "code": null, "e": 11105, "s": 10545, "text": "Spectral Normalization is a weight normalization that stabilizes the training of the discriminator. It controls the Lipschitz constant of the discriminator to mitigate the exploding gradient problem and the mode collapse problem. The concept is based heavily on maths but conceptually, it restricts the weight changes in each iteration and not over depending on a small set of features in distinguishing images by the discriminator. This approach will be computationally light compared with WGAN-GP and achieve good mode coverage that haunts many GAN methods." }, { "code": null, "e": 11298, "s": 11105, "text": "Mode collapse may not be all bad. The image quality often improves when mode collapses. In fact, we may collect the best model for each mode and use them to recreate different modes of images." }, { "code": null, "e": 12085, "s": 11298, "text": "The discriminator and generator are always in a tug of war to undercut each other. Mode collapse and gradient diminishing are often explained as an imbalance between the discriminator and the generator. We can improve GAN by turning our attention in balancing the loss between the generator and the discriminator. Unfortunately, the solution seems elusive. We can maintain a static ratio between the number of gradient descent iterations on the discriminator and the generator. Even this seems appealing but many doubt its benefit. Often, we maintain a one-to-one ratio. But some researchers also test out a ratio of 5 discriminator iterations per generator update. Balancing both networks with dynamic mechanics is also proposed. But not until recent years, we get some traction on it." }, { "code": null, "e": 12508, "s": 12085, "text": "On the other hand, some researchers challenge the feasibility and desirability of balancing these networks. A well-trained discriminator gives quality feedback to the generator anyway. Also, it is not easy to train the generator to always catch up with the discriminator. Instead, we may turn the attention into finding a cost function that does not have a close-to-zero gradient when the generator is not performing well." }, { "code": null, "e": 12619, "s": 12508, "text": "Nevertheless, issues remain. Many cost function proposals are made and the debates on what is the best remain." }, { "code": null, "e": 13033, "s": 12619, "text": "The model for the discriminator is usually more complex than the generator (more filters and more layers) and a good discriminator gives quality information. In many GAN applications, we may run into bottlenecks where increasing generator capacity shows no quality improvement. Until we identify the bottlenecks and resolve them, increasing generator capacity does not seem to be a priority for many partitioners." }, { "code": null, "e": 13238, "s": 13033, "text": "BigGAN was published in 2018 with the goal of pulling together some practices for GAN in generating the best images at that time. In this section, we will study some of the practices that not yet covered." }, { "code": null, "e": 13256, "s": 13238, "text": "Larger batch size" }, { "code": null, "e": 13599, "s": 13256, "text": "Increase the batch size can have a significant drop in FID as shown above. With a bigger batch size, more modes are covered and provide better gradients for both networks to learn. But yet, BigGAN reports the model reaches better performance in fewer iterations, but become unstable and even collapse afterward. So, save the model constantly." }, { "code": null, "e": 13616, "s": 13599, "text": "Truncation Trick" }, { "code": null, "e": 14137, "s": 13616, "text": "Low probability density region in the latent space z may not have enough training data to learn it accurately. So when generating images, we can avoid those regions to improve the image quality at the cost of the variation. i.e. the quality of images will increase but those generated images will have lower variance in style. There are different techniques to truncate the input latent space z. The general principle is when values fall outside a range, it will be resampled or squeeze to the higher-probability region." }, { "code": null, "e": 14161, "s": 14137, "text": "Increase model capacity" }, { "code": null, "e": 14449, "s": 14161, "text": "During tuning, consider increasing the capacity of the model, in particular for layers with high-spatial resolutions. Many models show improvement when double the traditional capacity used at the time. But don’t do it too early without proofing the model design and implementation first." }, { "code": null, "e": 14486, "s": 14449, "text": "Moving averages of Generator weights" }, { "code": null, "e": 14601, "s": 14486, "text": "The weights used by the generator are computed from an exponential moving average of the weights of the generator." }, { "code": null, "e": 14627, "s": 14601, "text": "Orthogonal regularization" }, { "code": null, "e": 14840, "s": 14627, "text": "The condition of the weight matrix is a heavy studied topic. This is a study on how sensitive a function output is to changes in its input. It has a large impact on training stability. A matrix Q is orthogonal if" }, { "code": null, "e": 14993, "s": 14840, "text": "If we multiply x with an orthogonal matrix, the changes in x will not be magnified. This behavior is very desirable for maintaining numerical stability." }, { "code": null, "e": 15264, "s": 14993, "text": "With other properties, maintain the orthogonal properties of the weight matrix can be appealing in deep learning. We can add an orthogonal regularization to encourage such properties during training. It penalizes the system if Q deviates from being an orthogonal matrix." }, { "code": null, "e": 15354, "s": 15264, "text": "Nevertheless, this is known to be too limiting and therefore BigGAN uses a modified term:" }, { "code": null, "e": 15464, "s": 15354, "text": "The orthogonal regularization also allows the truncation trick to be more successful across different models." }, { "code": null, "e": 15497, "s": 15464, "text": "Orthogonal weight initialization" }, { "code": null, "e": 15563, "s": 15497, "text": "The model weight is initialized to be a random orthogonal matrix." }, { "code": null, "e": 15581, "s": 15563, "text": "Skip-z connection" }, { "code": null, "e": 15820, "s": 15581, "text": "In the vanilla GAN, the latent factor z is input to the first layer only. With skip-z connection, direct skip connections (skip-z) from the latent factor z is connected to multiple layers of the generator rather than just the first layer." }, { "code": null, "e": 15976, "s": 15820, "text": "In this article, we do not detail the improvement through the cost function. This is an important topic and we recommend readers to read the article below:" }, { "code": null, "e": 15987, "s": 15976, "text": "medium.com" }, { "code": null, "e": 16027, "s": 15987, "text": "To know more cool applications of GANs:" }, { "code": null, "e": 16038, "s": 16027, "text": "medium.com" }, { "code": null, "e": 16071, "s": 16038, "text": "All the articles in this series." }, { "code": null, "e": 16082, "s": 16071, "text": "medium.com" } ]
Democratising Machine learning with H2O | by Parul Pandey | Towards Data Science
It is important to make AI accessible to everyone for the sake of social and economic stability. Kaggle days is a two-day event where data science enthusiasts can talk to each other face to face, exchange knowledge, and compete together. Kaggle days San Francisco just concluded and as is customary, Kaggle also organised a hackathon for the participants. I had been following Kaggle days on Twitter and the following tweet from Erin LeDell (Chief Machine Learning Scientist at H2O.ai) caught my eye. I have been experimenting with H2O for quite some time and found it really seamless and intuitive for solving ML problems. Seeing it perform so well on Leaderboard, I thought it was time that I wrote an article on the same to make it easy for others to make a transition into the world of H2O. H2O.ai is based in Mountain View, California and offers a suite of Machine Learning platforms. H2O’s core strength is its high-performing ML components, which are tightly integrated. H2O.ai is a Visionary in the Gartner Magic Quadrant for Data Science Platforms in its report released in Jan’2019. Let’s take a brief look at the offerings of H2O.ai: H2O is an open-source, distributed in-memory machine learning platform with linear scalability. H2O supports the most widely used statistical & machine learning algorithms and also has an AutoML functionality. H2O’s core code is written in Java and its REST API allows access to all the capabilities of H2O from an external program or script. The platform includes interfaces for R, Python, Scala, Java, JSON and CoffeeScript/JavaScript, along with a built-in web interface, Flow, Since the main focus of this article is about H2O, we shall get to know more about it later in the article. Sparkling Water allows users to combine the fast, scalable machine learning algorithms of H2O with the capabilities of Spark. Sparkling Water is ideal for H2O users who need to manage large clusters for their data processing needs and want to transfer data from Spark to H2O (or vice versa). H2O4GPU is an open-source, GPU-accelerated machine learning package with APIs in Python and R that allows anyone to take advantage of GPUs to build advanced machine learning models. H2O Driverless AI is H2O.ai’s flagship product for automatic machine learning. It fully automates some of the most challenging and productive tasks in applied data science such as feature engineering, model tuning, model ensembling and model deployment. With Driverless AI, data scientists of all proficiency levels can train and deploy modelling pipelines with just a few clicks from the GUI. Driverless AI is a commercially licensed product with a 21-day free trial version. The latest version called H2O-3 is the third incarnation of H2O. H2O uses familiar interfaces like R, Python, Scala, Java, JSON and the Flow notebook/web interface, and works seamlessly with big data technologies like Hadoop and Spark. H2O can easily and quickly derive insights from the data through faster and better predictive modelling. H2O makes it possible to import data from multiple sources and has a fast, Scalable & Distributed Compute Engine Written in Java. Here is a high-level overview of the platform. H2O supports a lot of commonly used algorithms of Machine Learning. H2O offers an R package that can be installed from CRAN and a python package that can be installed from PyPI. In this article, I shall be working with only the Python implementation. Also, you may want to look at the documentation for complete details. Python Java 7 or later, which you can get at the Java download page. To build H2O or run H2O tests, the 64-bit JDK is required. To run the H2O binary using either the command line, R or Python packages, only 64-bit JRE is required. pip install requestspip install tabulatepip install "colorama>=0.3.8"pip install future pip install pip install -f http://h2o-release.s3.amazonaws.com/h2o/latest_stable_Py.html h2o conda conda install -c h2oai h2o=3.22.1.2 Note: When installing H2O from pip in OS X El Capitan, users must include the --user flag. For example - pip install -f http://h2o-release.s3.amazonaws.com/h2o/latest_stable_Py.html h2o --user For R installation please refer to the official documentation here. Every new python session begins by initializing a connection between the python client and the H2O cluster. A cluster is a group of H2O nodes that work together; when a job is submitted to a cluster, all the nodes in the cluster work on a portion of the job. To check if everything is in place, open your Jupyter Notebooks and type in the following: import h2oh2o.init() This is a local H2O cluster. On executing the cell, some information will be printed on the screen in a tabular format displaying amongst other things, the number of nodes, total memory, Python version etc. In case you need to report a bug, make sure you include all this information. Also, the h2o.init() makes sure that no prior instance of H2O is running. By default, H2O instance uses all the cores and about 25% of the system’s memory. However, in case you wish to allocate it a fixed chunk of memory, you can specify it in the init function. Let’s say we want to give the H2O instance 4GB of memory and it should only use 2 cores.#Allocate resourcesh2o.init(nthreads=2,max_mem_size=4) Now our H2O instance is using only 2 cores and around 4GB of memory. However, we will go with the default method. After the installation is successful, it’s time to get our hands dirty by working on a real-world dataset. We will be working on a Regression problem using the famous wine dataset. The task here is to predict the quality of white wine on a scale of 0–10 given a set of features as inputs. Here is a link to the Github Repository in case you want to follow along or you can view it on my binder by clicking the image below. The data belongs to the white variants of the Portuguese “Vinho Verde” wine. Source: https://archive.ics.uci.edu/ml/datasets/Wine+Quality CSV FIle : (https://archive.ics.uci.edu/ml/machine-learning-databases/wine-quality/winequality-white.csv) Importing data from a local CSV file. The command is very similar to pandas.read_csv and the data is stored in memory as a H2OFrame. wine_data = h2o.import_file("winequality-white.csv")wine_data.head(5)# The default head() command displays the first 10 rows. Let us explore the dataset to get some insights. wine_data.describe() All the features here are numbers and there aren’t any categorical variables. Now let us also look at the correlation of the individual features. import matplotlib.pyplot as pltimport seaborn as snsplt.figure(figsize=(10,10))corr = wine_data.cor().as_data_frame()corr.index = wine_data.columnssns.heatmap(corr, annot = True, cmap='RdYlGn', vmin=-1, vmax=1)plt.title("Correlation Heatmap", fontsize=16)plt.show() We shall build a regression model to predict the Quality of the wine. There are a lot of algorithms available in the H2O module both for Classification as well as Regression problems. Since we have only one dataset, let’s split it into training and Testing part, so that we can evaluate the model’s performance. We shall use the split_frame() function. wine_split = wine_data.split_frame(ratios = [0.8], seed = 1234)wine_train = wine_split[0] # using 80% for trainingwine_test = wine_split[1] #rest 20% for testingprint(wine_train.shape, wine_test.shape)(3932, 12) (966, 12) predictors = list(wine_data.columns) predictors.remove('quality') # Since we need to predict qualitypredictors We shall build a Generalized Linear Model (GLM) with default settings. Generalized Linear Models (GLM) estimate regression models for outcomes following exponential distributions. In addition to the Gaussian (i.e. normal) distribution, these include Poisson, binomial, and gamma distributions. You can read more about GLM in the documentation. # Import the function for GLMfrom h2o.estimators.glm import H2OGeneralizedLinearEstimator# Set up GLM for regressionglm = H2OGeneralizedLinearEstimator(family = 'gaussian', model_id = 'glm_default')# Use .train() to build the modelglm.train(x = predictors, y = 'quality', training_frame = wine_train)print(glm) Now, let’s check the model’s performance on the test dataset glm.model_performance(wine_test) Using the GLM model to make predictions in the test dataset. predictions = glm.predict(wine_test)predictions.head(5) Similarly, you could use other supervised algorithms like Distributed Random Forest, Gradient Boosting Machines, and even Deep Learning.you could also tune in the hyperparameters. Automated machine learning (AutoML) is the process of automating the end-to-end process of applying machine learning to real-world problems. AutoML makes machine learning available in a true sense, even to people with no major expertise in this field. H2O’s AutoML tends to automate the training and the tuning part of the models. In this section, we shall be using the AutoML capabilities of H2O to work on the same regression problem of predicting wine quality. from h2o.automl import H2OAutoMLaml = H2OAutoML(max_models = 20, max_runtime_secs=100, seed = 1) Here AutoML will run for 20 base models for 100 seconds. The default runtime is 1 Hour. aml.train(x=predictors, y='quality', training_frame=wine_train, validation_frame=wine_test) Now let us look at the automl leaderboard. print(aml.leaderboard) The leaderboard displays the top 10 models built by AutoML with their parameters. The best model is placed on the top is a Stacked Ensemble. The leader model is stored as aml.leader Let us look at the contribution of the individual models for this meta-learner. metalearner = h2o.get_model(aml.leader.metalearner()['name'])metalearner.std_coef_plot() XRT( Extremely Randomized Trees) has the maximum contribution followed by Distributed Random Forests. preds = aml.leader.predict(wine_test) The code above is the quickest way to get started, however, to learn more about H2O AutoML it is worth taking a look at the in-depth AutoML tutorial (available in R and Python). h2o.shutdown() In the final leg of this article, let us have a quick overview of H2O’s open source Web UI called Flow. FLow is a web-based interactive computational environment where you can combine code execution, text, mathematics, plots and rich media into a single document, much like Jupyter Notebooks. Once H2O is up and running all you need to do is point your browser to http://localhost:54321 and you’ll see our very nice user interface called Flow. Here is a quick glance over the flow interface. You can read more about using and working with it here. Flow is designed to help data scientists rapidly and easily create models, import files, split data frames and do all the things that would normally require quite a bit of typing in other environments. Let’s work through our same wine example but this time with Flow. The following video explains the model building and prediction using flow and it is kind of self-explanatory. For a deep dive into FLow and it’s capabilities, refer to the article below: towardsdatascience.com H2O is a powerful tool and given its capabilities, it can really transform the Data Science process for good. The capabilities and advantages of AI should be made available to everybody and not a select few. This is the real essence of Democratisation and Democratising Data Science should is essential for resolving Real problems threatening our planet.
[ { "code": null, "e": 269, "s": 172, "text": "It is important to make AI accessible to everyone for the sake of social and economic stability." }, { "code": null, "e": 673, "s": 269, "text": "Kaggle days is a two-day event where data science enthusiasts can talk to each other face to face, exchange knowledge, and compete together. Kaggle days San Francisco just concluded and as is customary, Kaggle also organised a hackathon for the participants. I had been following Kaggle days on Twitter and the following tweet from Erin LeDell (Chief Machine Learning Scientist at H2O.ai) caught my eye." }, { "code": null, "e": 967, "s": 673, "text": "I have been experimenting with H2O for quite some time and found it really seamless and intuitive for solving ML problems. Seeing it perform so well on Leaderboard, I thought it was time that I wrote an article on the same to make it easy for others to make a transition into the world of H2O." }, { "code": null, "e": 1265, "s": 967, "text": "H2O.ai is based in Mountain View, California and offers a suite of Machine Learning platforms. H2O’s core strength is its high-performing ML components, which are tightly integrated. H2O.ai is a Visionary in the Gartner Magic Quadrant for Data Science Platforms in its report released in Jan’2019." }, { "code": null, "e": 1317, "s": 1265, "text": "Let’s take a brief look at the offerings of H2O.ai:" }, { "code": null, "e": 1798, "s": 1317, "text": "H2O is an open-source, distributed in-memory machine learning platform with linear scalability. H2O supports the most widely used statistical & machine learning algorithms and also has an AutoML functionality. H2O’s core code is written in Java and its REST API allows access to all the capabilities of H2O from an external program or script. The platform includes interfaces for R, Python, Scala, Java, JSON and CoffeeScript/JavaScript, along with a built-in web interface, Flow," }, { "code": null, "e": 1906, "s": 1798, "text": "Since the main focus of this article is about H2O, we shall get to know more about it later in the article." }, { "code": null, "e": 2198, "s": 1906, "text": "Sparkling Water allows users to combine the fast, scalable machine learning algorithms of H2O with the capabilities of Spark. Sparkling Water is ideal for H2O users who need to manage large clusters for their data processing needs and want to transfer data from Spark to H2O (or vice versa)." }, { "code": null, "e": 2380, "s": 2198, "text": "H2O4GPU is an open-source, GPU-accelerated machine learning package with APIs in Python and R that allows anyone to take advantage of GPUs to build advanced machine learning models." }, { "code": null, "e": 2857, "s": 2380, "text": "H2O Driverless AI is H2O.ai’s flagship product for automatic machine learning. It fully automates some of the most challenging and productive tasks in applied data science such as feature engineering, model tuning, model ensembling and model deployment. With Driverless AI, data scientists of all proficiency levels can train and deploy modelling pipelines with just a few clicks from the GUI. Driverless AI is a commercially licensed product with a 21-day free trial version." }, { "code": null, "e": 3198, "s": 2857, "text": "The latest version called H2O-3 is the third incarnation of H2O. H2O uses familiar interfaces like R, Python, Scala, Java, JSON and the Flow notebook/web interface, and works seamlessly with big data technologies like Hadoop and Spark. H2O can easily and quickly derive insights from the data through faster and better predictive modelling." }, { "code": null, "e": 3375, "s": 3198, "text": "H2O makes it possible to import data from multiple sources and has a fast, Scalable & Distributed Compute Engine Written in Java. Here is a high-level overview of the platform." }, { "code": null, "e": 3443, "s": 3375, "text": "H2O supports a lot of commonly used algorithms of Machine Learning." }, { "code": null, "e": 3696, "s": 3443, "text": "H2O offers an R package that can be installed from CRAN and a python package that can be installed from PyPI. In this article, I shall be working with only the Python implementation. Also, you may want to look at the documentation for complete details." }, { "code": null, "e": 3703, "s": 3696, "text": "Python" }, { "code": null, "e": 3928, "s": 3703, "text": "Java 7 or later, which you can get at the Java download page. To build H2O or run H2O tests, the 64-bit JDK is required. To run the H2O binary using either the command line, R or Python packages, only 64-bit JRE is required." }, { "code": null, "e": 4016, "s": 3928, "text": "pip install requestspip install tabulatepip install \"colorama>=0.3.8\"pip install future" }, { "code": null, "e": 4028, "s": 4016, "text": "pip install" }, { "code": null, "e": 4109, "s": 4028, "text": "pip install -f http://h2o-release.s3.amazonaws.com/h2o/latest_stable_Py.html h2o" }, { "code": null, "e": 4115, "s": 4109, "text": "conda" }, { "code": null, "e": 4151, "s": 4115, "text": "conda install -c h2oai h2o=3.22.1.2" }, { "code": null, "e": 4256, "s": 4151, "text": "Note: When installing H2O from pip in OS X El Capitan, users must include the --user flag. For example -" }, { "code": null, "e": 4344, "s": 4256, "text": "pip install -f http://h2o-release.s3.amazonaws.com/h2o/latest_stable_Py.html h2o --user" }, { "code": null, "e": 4412, "s": 4344, "text": "For R installation please refer to the official documentation here." }, { "code": null, "e": 4671, "s": 4412, "text": "Every new python session begins by initializing a connection between the python client and the H2O cluster. A cluster is a group of H2O nodes that work together; when a job is submitted to a cluster, all the nodes in the cluster work on a portion of the job." }, { "code": null, "e": 4762, "s": 4671, "text": "To check if everything is in place, open your Jupyter Notebooks and type in the following:" }, { "code": null, "e": 4783, "s": 4762, "text": "import h2oh2o.init()" }, { "code": null, "e": 5142, "s": 4783, "text": "This is a local H2O cluster. On executing the cell, some information will be printed on the screen in a tabular format displaying amongst other things, the number of nodes, total memory, Python version etc. In case you need to report a bug, make sure you include all this information. Also, the h2o.init() makes sure that no prior instance of H2O is running." }, { "code": null, "e": 5474, "s": 5142, "text": "By default, H2O instance uses all the cores and about 25% of the system’s memory. However, in case you wish to allocate it a fixed chunk of memory, you can specify it in the init function. Let’s say we want to give the H2O instance 4GB of memory and it should only use 2 cores.#Allocate resourcesh2o.init(nthreads=2,max_mem_size=4)" }, { "code": null, "e": 5588, "s": 5474, "text": "Now our H2O instance is using only 2 cores and around 4GB of memory. However, we will go with the default method." }, { "code": null, "e": 5877, "s": 5588, "text": "After the installation is successful, it’s time to get our hands dirty by working on a real-world dataset. We will be working on a Regression problem using the famous wine dataset. The task here is to predict the quality of white wine on a scale of 0–10 given a set of features as inputs." }, { "code": null, "e": 6011, "s": 5877, "text": "Here is a link to the Github Repository in case you want to follow along or you can view it on my binder by clicking the image below." }, { "code": null, "e": 6088, "s": 6011, "text": "The data belongs to the white variants of the Portuguese “Vinho Verde” wine." }, { "code": null, "e": 6149, "s": 6088, "text": "Source: https://archive.ics.uci.edu/ml/datasets/Wine+Quality" }, { "code": null, "e": 6255, "s": 6149, "text": "CSV FIle : (https://archive.ics.uci.edu/ml/machine-learning-databases/wine-quality/winequality-white.csv)" }, { "code": null, "e": 6388, "s": 6255, "text": "Importing data from a local CSV file. The command is very similar to pandas.read_csv and the data is stored in memory as a H2OFrame." }, { "code": null, "e": 6514, "s": 6388, "text": "wine_data = h2o.import_file(\"winequality-white.csv\")wine_data.head(5)# The default head() command displays the first 10 rows." }, { "code": null, "e": 6563, "s": 6514, "text": "Let us explore the dataset to get some insights." }, { "code": null, "e": 6584, "s": 6563, "text": "wine_data.describe()" }, { "code": null, "e": 6730, "s": 6584, "text": "All the features here are numbers and there aren’t any categorical variables. Now let us also look at the correlation of the individual features." }, { "code": null, "e": 6996, "s": 6730, "text": "import matplotlib.pyplot as pltimport seaborn as snsplt.figure(figsize=(10,10))corr = wine_data.cor().as_data_frame()corr.index = wine_data.columnssns.heatmap(corr, annot = True, cmap='RdYlGn', vmin=-1, vmax=1)plt.title(\"Correlation Heatmap\", fontsize=16)plt.show()" }, { "code": null, "e": 7180, "s": 6996, "text": "We shall build a regression model to predict the Quality of the wine. There are a lot of algorithms available in the H2O module both for Classification as well as Regression problems." }, { "code": null, "e": 7349, "s": 7180, "text": "Since we have only one dataset, let’s split it into training and Testing part, so that we can evaluate the model’s performance. We shall use the split_frame() function." }, { "code": null, "e": 7571, "s": 7349, "text": "wine_split = wine_data.split_frame(ratios = [0.8], seed = 1234)wine_train = wine_split[0] # using 80% for trainingwine_test = wine_split[1] #rest 20% for testingprint(wine_train.shape, wine_test.shape)(3932, 12) (966, 12)" }, { "code": null, "e": 7683, "s": 7571, "text": "predictors = list(wine_data.columns) predictors.remove('quality') # Since we need to predict qualitypredictors" }, { "code": null, "e": 8027, "s": 7683, "text": "We shall build a Generalized Linear Model (GLM) with default settings. Generalized Linear Models (GLM) estimate regression models for outcomes following exponential distributions. In addition to the Gaussian (i.e. normal) distribution, these include Poisson, binomial, and gamma distributions. You can read more about GLM in the documentation." }, { "code": null, "e": 8374, "s": 8027, "text": "# Import the function for GLMfrom h2o.estimators.glm import H2OGeneralizedLinearEstimator# Set up GLM for regressionglm = H2OGeneralizedLinearEstimator(family = 'gaussian', model_id = 'glm_default')# Use .train() to build the modelglm.train(x = predictors, y = 'quality', training_frame = wine_train)print(glm)" }, { "code": null, "e": 8435, "s": 8374, "text": "Now, let’s check the model’s performance on the test dataset" }, { "code": null, "e": 8468, "s": 8435, "text": "glm.model_performance(wine_test)" }, { "code": null, "e": 8529, "s": 8468, "text": "Using the GLM model to make predictions in the test dataset." }, { "code": null, "e": 8585, "s": 8529, "text": "predictions = glm.predict(wine_test)predictions.head(5)" }, { "code": null, "e": 8765, "s": 8585, "text": "Similarly, you could use other supervised algorithms like Distributed Random Forest, Gradient Boosting Machines, and even Deep Learning.you could also tune in the hyperparameters." }, { "code": null, "e": 9096, "s": 8765, "text": "Automated machine learning (AutoML) is the process of automating the end-to-end process of applying machine learning to real-world problems. AutoML makes machine learning available in a true sense, even to people with no major expertise in this field. H2O’s AutoML tends to automate the training and the tuning part of the models." }, { "code": null, "e": 9229, "s": 9096, "text": "In this section, we shall be using the AutoML capabilities of H2O to work on the same regression problem of predicting wine quality." }, { "code": null, "e": 9326, "s": 9229, "text": "from h2o.automl import H2OAutoMLaml = H2OAutoML(max_models = 20, max_runtime_secs=100, seed = 1)" }, { "code": null, "e": 9414, "s": 9326, "text": "Here AutoML will run for 20 base models for 100 seconds. The default runtime is 1 Hour." }, { "code": null, "e": 9506, "s": 9414, "text": "aml.train(x=predictors, y='quality', training_frame=wine_train, validation_frame=wine_test)" }, { "code": null, "e": 9549, "s": 9506, "text": "Now let us look at the automl leaderboard." }, { "code": null, "e": 9572, "s": 9549, "text": "print(aml.leaderboard)" }, { "code": null, "e": 9713, "s": 9572, "text": "The leaderboard displays the top 10 models built by AutoML with their parameters. The best model is placed on the top is a Stacked Ensemble." }, { "code": null, "e": 9754, "s": 9713, "text": "The leader model is stored as aml.leader" }, { "code": null, "e": 9834, "s": 9754, "text": "Let us look at the contribution of the individual models for this meta-learner." }, { "code": null, "e": 9923, "s": 9834, "text": "metalearner = h2o.get_model(aml.leader.metalearner()['name'])metalearner.std_coef_plot()" }, { "code": null, "e": 10025, "s": 9923, "text": "XRT( Extremely Randomized Trees) has the maximum contribution followed by Distributed Random Forests." }, { "code": null, "e": 10063, "s": 10025, "text": "preds = aml.leader.predict(wine_test)" }, { "code": null, "e": 10241, "s": 10063, "text": "The code above is the quickest way to get started, however, to learn more about H2O AutoML it is worth taking a look at the in-depth AutoML tutorial (available in R and Python)." }, { "code": null, "e": 10256, "s": 10241, "text": "h2o.shutdown()" }, { "code": null, "e": 10549, "s": 10256, "text": "In the final leg of this article, let us have a quick overview of H2O’s open source Web UI called Flow. FLow is a web-based interactive computational environment where you can combine code execution, text, mathematics, plots and rich media into a single document, much like Jupyter Notebooks." }, { "code": null, "e": 10700, "s": 10549, "text": "Once H2O is up and running all you need to do is point your browser to http://localhost:54321 and you’ll see our very nice user interface called Flow." }, { "code": null, "e": 10804, "s": 10700, "text": "Here is a quick glance over the flow interface. You can read more about using and working with it here." }, { "code": null, "e": 11006, "s": 10804, "text": "Flow is designed to help data scientists rapidly and easily create models, import files, split data frames and do all the things that would normally require quite a bit of typing in other environments." }, { "code": null, "e": 11182, "s": 11006, "text": "Let’s work through our same wine example but this time with Flow. The following video explains the model building and prediction using flow and it is kind of self-explanatory." }, { "code": null, "e": 11259, "s": 11182, "text": "For a deep dive into FLow and it’s capabilities, refer to the article below:" }, { "code": null, "e": 11282, "s": 11259, "text": "towardsdatascience.com" } ]
C++ Date and Time
The C++ standard library does not provide a proper date type. C++ inherits the structs and functions for date and time manipulation from C. To access date and time related functions and structures, you would need to include <ctime> header file in your C++ program. There are four time-related types: clock_t, time_t, size_t, and tm. The types - clock_t, size_t and time_t are capable of representing the system time and date as some sort of integer. The structure type tm holds the date and time in the form of a C structure having the following elements − struct tm { int tm_sec; // seconds of minutes from 0 to 61 int tm_min; // minutes of hour from 0 to 59 int tm_hour; // hours of day from 0 to 24 int tm_mday; // day of month from 1 to 31 int tm_mon; // month of year from 0 to 11 int tm_year; // year since 1900 int tm_wday; // days since sunday int tm_yday; // days since January 1st int tm_isdst; // hours of daylight savings time } Following are the important functions, which we use while working with date and time in C or C++. All these functions are part of standard C and C++ library and you can check their detail using reference to C++ standard library given below. time_t time(time_t *time); This returns the current calendar time of the system in number of seconds elapsed since January 1, 1970. If the system has no time, .1 is returned. char *ctime(const time_t *time); This returns a pointer to a string of the form day month year hours:minutes:seconds year\n\0. struct tm *localtime(const time_t *time); This returns a pointer to the tm structure representing local time. clock_t clock(void); This returns a value that approximates the amount of time the calling program has been running. A value of .1 is returned if the time is not available. char * asctime ( const struct tm * time ); This returns a pointer to a string that contains the information stored in the structure pointed to by time converted into the form: day month date hours:minutes:seconds year\n\0 struct tm *gmtime(const time_t *time); This returns a pointer to the time in the form of a tm structure. The time is represented in Coordinated Universal Time (UTC), which is essentially Greenwich Mean Time (GMT). time_t mktime(struct tm *time); This returns the calendar-time equivalent of the time found in the structure pointed to by time. double difftime ( time_t time2, time_t time1 ); This function calculates the difference in seconds between time1 and time2. size_t strftime(); This function can be used to format date and time in a specific format. Suppose you want to retrieve the current system date and time, either as a local time or as a Coordinated Universal Time (UTC). Following is the example to achieve the same − #include <iostream> #include <ctime> using namespace std; int main() { // current date/time based on current system time_t now = time(0); // convert now to string form char* dt = ctime(&now); cout << "The local date and time is: " << dt << endl; // convert now to tm struct for UTC tm *gmtm = gmtime(&now); dt = asctime(gmtm); cout << "The UTC date and time is:"<< dt << endl; } When the above code is compiled and executed, it produces the following result − The local date and time is: Sat Jan 8 20:07:41 2011 The UTC date and time is:Sun Jan 9 03:07:41 2011 The tm structure is very important while working with date and time in either C or C++. This structure holds the date and time in the form of a C structure as mentioned above. Most of the time related functions makes use of tm structure. Following is an example which makes use of various date and time related functions and tm structure − While using structure in this chapter, I'm making an assumption that you have basic understanding on C structure and how to access structure members using arrow -> operator. #include <iostream> #include <ctime> using namespace std; int main() { // current date/time based on current system time_t now = time(0); cout << "Number of sec since January 1,1970 is:: " << now << endl; tm *ltm = localtime(&now); // print various components of tm structure. cout << "Year:" << 1900 + ltm->tm_year<<endl; cout << "Month: "<< 1 + ltm->tm_mon<< endl; cout << "Day: "<< ltm->tm_mday << endl; cout << "Time: "<< 5+ltm->tm_hour << ":"; cout << 30+ltm->tm_min << ":"; cout << ltm->tm_sec << endl; } When the above code is compiled and executed, it produces the following result − Number of sec since January 1,1970 is:: 1588485717 Year:2020 Month: 5 Day: 3 Time: 11:31:57 154 Lectures 11.5 hours Arnab Chakraborty 14 Lectures 57 mins Kaushik Roy Chowdhury 30 Lectures 12.5 hours Frahaan Hussain 54 Lectures 3.5 hours Frahaan Hussain 77 Lectures 5.5 hours Frahaan Hussain 12 Lectures 3.5 hours Frahaan Hussain Print Add Notes Bookmark this page
[ { "code": null, "e": 2583, "s": 2318, "text": "The C++ standard library does not provide a proper date type. C++ inherits the structs and functions for date and time manipulation from C. To access date and time related functions and structures, you would need to include <ctime> header file in your C++ program." }, { "code": null, "e": 2768, "s": 2583, "text": "There are four time-related types: clock_t, time_t, size_t, and tm. The types - clock_t, size_t and time_t are capable of representing the system time and date as some sort of integer." }, { "code": null, "e": 2875, "s": 2768, "text": "The structure type tm holds the date and time in the form of a C structure having the following elements −" }, { "code": null, "e": 3298, "s": 2875, "text": "struct tm {\n int tm_sec; // seconds of minutes from 0 to 61\n int tm_min; // minutes of hour from 0 to 59\n int tm_hour; // hours of day from 0 to 24\n int tm_mday; // day of month from 1 to 31\n int tm_mon; // month of year from 0 to 11\n int tm_year; // year since 1900\n int tm_wday; // days since sunday\n int tm_yday; // days since January 1st\n int tm_isdst; // hours of daylight savings time\n}\n" }, { "code": null, "e": 3539, "s": 3298, "text": "Following are the important functions, which we use while working with date and time in C or C++. All these functions are part of standard C and C++ library and you can check their detail using reference to C++ standard library given below." }, { "code": null, "e": 3566, "s": 3539, "text": "time_t time(time_t *time);" }, { "code": null, "e": 3714, "s": 3566, "text": "This returns the current calendar time of the system in number of seconds elapsed since January 1, 1970. If the system has no time, .1 is returned." }, { "code": null, "e": 3747, "s": 3714, "text": "char *ctime(const time_t *time);" }, { "code": null, "e": 3841, "s": 3747, "text": "This returns a pointer to a string of the form day month year hours:minutes:seconds year\\n\\0." }, { "code": null, "e": 3883, "s": 3841, "text": "struct tm *localtime(const time_t *time);" }, { "code": null, "e": 3951, "s": 3883, "text": "This returns a pointer to the tm structure representing local time." }, { "code": null, "e": 3972, "s": 3951, "text": "clock_t clock(void);" }, { "code": null, "e": 4124, "s": 3972, "text": "This returns a value that approximates the amount of time the calling program has been running. A value of .1 is returned if the time is not available." }, { "code": null, "e": 4167, "s": 4124, "text": "char * asctime ( const struct tm * time );" }, { "code": null, "e": 4346, "s": 4167, "text": "This returns a pointer to a string that contains the information stored in the structure pointed to by time converted into the form: day month date hours:minutes:seconds year\\n\\0" }, { "code": null, "e": 4385, "s": 4346, "text": "struct tm *gmtime(const time_t *time);" }, { "code": null, "e": 4560, "s": 4385, "text": "This returns a pointer to the time in the form of a tm structure. The time is represented in Coordinated Universal Time (UTC), which is essentially Greenwich Mean Time (GMT)." }, { "code": null, "e": 4592, "s": 4560, "text": "time_t mktime(struct tm *time);" }, { "code": null, "e": 4689, "s": 4592, "text": "This returns the calendar-time equivalent of the time found in the structure pointed to by time." }, { "code": null, "e": 4737, "s": 4689, "text": "double difftime ( time_t time2, time_t time1 );" }, { "code": null, "e": 4813, "s": 4737, "text": "This function calculates the difference in seconds between time1 and time2." }, { "code": null, "e": 4832, "s": 4813, "text": "size_t strftime();" }, { "code": null, "e": 4904, "s": 4832, "text": "This function can be used to format date and time in a specific format." }, { "code": null, "e": 5079, "s": 4904, "text": "Suppose you want to retrieve the current system date and time, either as a local time or as a Coordinated Universal Time (UTC). Following is the example to achieve the same −" }, { "code": null, "e": 5493, "s": 5079, "text": "#include <iostream>\n#include <ctime>\n\nusing namespace std;\n\nint main() {\n // current date/time based on current system\n time_t now = time(0);\n \n // convert now to string form\n char* dt = ctime(&now);\n\n cout << \"The local date and time is: \" << dt << endl;\n\n // convert now to tm struct for UTC\n tm *gmtm = gmtime(&now);\n dt = asctime(gmtm);\n cout << \"The UTC date and time is:\"<< dt << endl;\n}" }, { "code": null, "e": 5574, "s": 5493, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 5679, "s": 5574, "text": "The local date and time is: Sat Jan 8 20:07:41 2011\n\nThe UTC date and time is:Sun Jan 9 03:07:41 2011\n" }, { "code": null, "e": 6019, "s": 5679, "text": "The tm structure is very important while working with date and time in either C or C++. This structure holds the date and time in the form of a C structure as mentioned above. Most of the time related functions makes use of tm structure. Following is an example which makes use of various date and time related functions and tm structure −" }, { "code": null, "e": 6193, "s": 6019, "text": "While using structure in this chapter, I'm making an assumption that you have basic understanding on C structure and how to access structure members using arrow -> operator." }, { "code": null, "e": 6742, "s": 6193, "text": "#include <iostream>\n#include <ctime>\n\nusing namespace std;\n\nint main() {\n // current date/time based on current system\n time_t now = time(0);\n\n cout << \"Number of sec since January 1,1970 is:: \" << now << endl;\n\n tm *ltm = localtime(&now);\n\n // print various components of tm structure.\n cout << \"Year:\" << 1900 + ltm->tm_year<<endl;\n cout << \"Month: \"<< 1 + ltm->tm_mon<< endl;\n cout << \"Day: \"<< ltm->tm_mday << endl;\n cout << \"Time: \"<< 5+ltm->tm_hour << \":\";\n cout << 30+ltm->tm_min << \":\";\n cout << ltm->tm_sec << endl;\n}" }, { "code": null, "e": 6823, "s": 6742, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 6916, "s": 6823, "text": "Number of sec since January 1,1970 is:: 1588485717\nYear:2020\nMonth: 5\nDay: 3\nTime: 11:31:57\n" }, { "code": null, "e": 6953, "s": 6916, "text": "\n 154 Lectures \n 11.5 hours \n" }, { "code": null, "e": 6972, "s": 6953, "text": " Arnab Chakraborty" }, { "code": null, "e": 7004, "s": 6972, "text": "\n 14 Lectures \n 57 mins\n" }, { "code": null, "e": 7027, "s": 7004, "text": " Kaushik Roy Chowdhury" }, { "code": null, "e": 7063, "s": 7027, "text": "\n 30 Lectures \n 12.5 hours \n" }, { "code": null, "e": 7080, "s": 7063, "text": " Frahaan Hussain" }, { "code": null, "e": 7115, "s": 7080, "text": "\n 54 Lectures \n 3.5 hours \n" }, { "code": null, "e": 7132, "s": 7115, "text": " Frahaan Hussain" }, { "code": null, "e": 7167, "s": 7132, "text": "\n 77 Lectures \n 5.5 hours \n" }, { "code": null, "e": 7184, "s": 7167, "text": " Frahaan Hussain" }, { "code": null, "e": 7219, "s": 7184, "text": "\n 12 Lectures \n 3.5 hours \n" }, { "code": null, "e": 7236, "s": 7219, "text": " Frahaan Hussain" }, { "code": null, "e": 7243, "s": 7236, "text": " Print" }, { "code": null, "e": 7254, "s": 7243, "text": " Add Notes" } ]
Exception Handling in Node.js - GeeksforGeeks
16 Feb, 2022 The exception handling refers to the mechanism by which the exceptions occurring in a code while an application is running is handled. Node.js supports several mechanisms for propagating and handling errors. This are the different methods which can be used for exception handling in Node.js: Exception handling in synchronous code:If an error occurs in a synchronous code, return the error. Example: javascript // Write Javascript code here// Define divider as a synchronous functionvar divideSync = function(x, y) { // if error condition? if ( y === 0 ) { // "throw" the error safely by returning it return new Error("Can't divide by zero") } else { // no error occurred, continue on return x/y }} // Divide 9/3var result = divideSync(9, 3)// did an error occur?if ( result instanceof Error ) { // handle the error safely console.log("9/3=err", result)}else { // no error occurred, continue on console.log("9/3="+result)} // Divide 9/0result = divideSync(9, 0)// did an error occur?if ( result instanceof Error ) { // handle the error safely console.log("9/0=err", result)}else { // no error occurred, continue on console.log("9/0="+result)} Output: Exception handling in callback-based( asynchronous) code: In callback-based code, the one of the argument of the callback is err. If an error happens err is the error, if an error doesn’t happen then err is null. The err argument can be followed any number of other arguments. Example: javascript // Write Javascript code herevar divide = function(x, y, next) { // if error condition? if ( y === 0 ) { // "throw" the error safely by calling the completion callback // with the first argument being the error next(new Error("Can't divide by zero")) } else { // no error occurred, continue on next(null, x/y) }} divide(9, 3, function(err, result){ // did an error occur? if ( err ) { // handle the error safely console.log("9/3=err", err) } else { // no error occurred, continue on console.log("9/3="+result) }}) divide(9, 0, function(err, result){ // did an error occur? if ( err ) { // handle the error safely console.log("9/0=err", err) } else { // no error occurred, continue on console.log("9/0="+result) }}) Output: Exception handling in eventful code:In an eventful code, the error may happen anywhere. So instead of throwing the error, fire the error event instead. Example: javascript // Write Javascript code here// Definite our Divider Event Emittervar events = require("events")var Divider = function(){ events.EventEmitter.call(this)}require('util').inherits(Divider, events.EventEmitter) // Add the divide functionDivider.prototype.divide = function(x, y){ // if error condition? if ( y === 0 ) { // "throw" the error safely by emitting it var err = new Error("Can't divide by zero") this.emit("error", err) } else { // no error occurred, continue on this.emit("divided", x, y, x/y) } // Chain return this;} // Create our divider and listen for errorsvar divider = new Divider()divider.on('error', function(err){ // handle the error safely console.log(err)})divider.on('divided', function(x, y, result){ console.log(x+"/"+y+"="+result)}) // Dividedivider.divide(9, 3).divide(9, 0) Output: Akanksha_Rai sagar0719kumar Picked Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Node.js fs.writeFile() Method How to install the previous version of node.js and npm ? Difference between promise and async await in Node.js How to use an ES6 import in Node.js? Express.js res.sendFile() Function Top 10 Front End Developer Skills That You Need in 2022 Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 24035, "s": 24007, "text": "\n16 Feb, 2022" }, { "code": null, "e": 24329, "s": 24035, "text": "The exception handling refers to the mechanism by which the exceptions occurring in a code while an application is running is handled. Node.js supports several mechanisms for propagating and handling errors. This are the different methods which can be used for exception handling in Node.js: " }, { "code": null, "e": 24439, "s": 24329, "text": "Exception handling in synchronous code:If an error occurs in a synchronous code, return the error. Example: " }, { "code": null, "e": 24450, "s": 24439, "text": "javascript" }, { "code": "// Write Javascript code here// Define divider as a synchronous functionvar divideSync = function(x, y) { // if error condition? if ( y === 0 ) { // \"throw\" the error safely by returning it return new Error(\"Can't divide by zero\") } else { // no error occurred, continue on return x/y }} // Divide 9/3var result = divideSync(9, 3)// did an error occur?if ( result instanceof Error ) { // handle the error safely console.log(\"9/3=err\", result)}else { // no error occurred, continue on console.log(\"9/3=\"+result)} // Divide 9/0result = divideSync(9, 0)// did an error occur?if ( result instanceof Error ) { // handle the error safely console.log(\"9/0=err\", result)}else { // no error occurred, continue on console.log(\"9/0=\"+result)}", "e": 25249, "s": 24450, "text": null }, { "code": null, "e": 25259, "s": 25249, "text": "Output: " }, { "code": null, "e": 25547, "s": 25259, "text": "Exception handling in callback-based( asynchronous) code: In callback-based code, the one of the argument of the callback is err. If an error happens err is the error, if an error doesn’t happen then err is null. The err argument can be followed any number of other arguments. Example: " }, { "code": null, "e": 25558, "s": 25547, "text": "javascript" }, { "code": "// Write Javascript code herevar divide = function(x, y, next) { // if error condition? if ( y === 0 ) { // \"throw\" the error safely by calling the completion callback // with the first argument being the error next(new Error(\"Can't divide by zero\")) } else { // no error occurred, continue on next(null, x/y) }} divide(9, 3, function(err, result){ // did an error occur? if ( err ) { // handle the error safely console.log(\"9/3=err\", err) } else { // no error occurred, continue on console.log(\"9/3=\"+result) }}) divide(9, 0, function(err, result){ // did an error occur? if ( err ) { // handle the error safely console.log(\"9/0=err\", err) } else { // no error occurred, continue on console.log(\"9/0=\"+result) }})", "e": 26409, "s": 25558, "text": null }, { "code": null, "e": 26419, "s": 26409, "text": "Output: " }, { "code": null, "e": 26582, "s": 26419, "text": "Exception handling in eventful code:In an eventful code, the error may happen anywhere. So instead of throwing the error, fire the error event instead. Example: " }, { "code": null, "e": 26593, "s": 26582, "text": "javascript" }, { "code": "// Write Javascript code here// Definite our Divider Event Emittervar events = require(\"events\")var Divider = function(){ events.EventEmitter.call(this)}require('util').inherits(Divider, events.EventEmitter) // Add the divide functionDivider.prototype.divide = function(x, y){ // if error condition? if ( y === 0 ) { // \"throw\" the error safely by emitting it var err = new Error(\"Can't divide by zero\") this.emit(\"error\", err) } else { // no error occurred, continue on this.emit(\"divided\", x, y, x/y) } // Chain return this;} // Create our divider and listen for errorsvar divider = new Divider()divider.on('error', function(err){ // handle the error safely console.log(err)})divider.on('divided', function(x, y, result){ console.log(x+\"/\"+y+\"=\"+result)}) // Dividedivider.divide(9, 3).divide(9, 0)", "e": 27463, "s": 26593, "text": null }, { "code": null, "e": 27473, "s": 27463, "text": "Output: " }, { "code": null, "e": 27488, "s": 27475, "text": "Akanksha_Rai" }, { "code": null, "e": 27503, "s": 27488, "text": "sagar0719kumar" }, { "code": null, "e": 27510, "s": 27503, "text": "Picked" }, { "code": null, "e": 27518, "s": 27510, "text": "Node.js" }, { "code": null, "e": 27535, "s": 27518, "text": "Web Technologies" }, { "code": null, "e": 27633, "s": 27535, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27642, "s": 27633, "text": "Comments" }, { "code": null, "e": 27655, "s": 27642, "text": "Old Comments" }, { "code": null, "e": 27685, "s": 27655, "text": "Node.js fs.writeFile() Method" }, { "code": null, "e": 27742, "s": 27685, "text": "How to install the previous version of node.js and npm ?" }, { "code": null, "e": 27796, "s": 27742, "text": "Difference between promise and async await in Node.js" }, { "code": null, "e": 27833, "s": 27796, "text": "How to use an ES6 import in Node.js?" }, { "code": null, "e": 27868, "s": 27833, "text": "Express.js res.sendFile() Function" }, { "code": null, "e": 27924, "s": 27868, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 27986, "s": 27924, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 28029, "s": 27986, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 28079, "s": 28029, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Unix / Linux - Shell Arithmetic Operators Example
The following arithmetic operators are supported by Bourne Shell. Assume variable a holds 10 and variable b holds 20 then − It is very important to understand that all the conditional expressions should be inside square braces with spaces around them, for example [ $a == $b ] is correct whereas, [$a==$b] is incorrect. All the arithmetical calculations are done using long integers. Here is an example which uses all the arithmetic operators − #!/bin/sh a=10 b=20 val=`expr $a + $b` echo "a + b : $val" val=`expr $a - $b` echo "a - b : $val" val=`expr $a \* $b` echo "a * b : $val" val=`expr $b / $a` echo "b / a : $val" val=`expr $b % $a` echo "b % a : $val" if [ $a == $b ] then echo "a is equal to b" fi if [ $a != $b ] then echo "a is not equal to b" fi The above script will produce the following result − a + b : 30 a - b : -10 a * b : 200 b / a : 2 b % a : 0 a is not equal to b The following points need to be considered when using the Arithmetic Operators − There must be spaces between the operators and the expressions. For example, 2+2 is not correct; it should be written as 2 + 2. There must be spaces between the operators and the expressions. For example, 2+2 is not correct; it should be written as 2 + 2. Complete expression should be enclosed between ‘ ‘, called the inverted commas. Complete expression should be enclosed between ‘ ‘, called the inverted commas. You should use \ on the * symbol for multiplication. You should use \ on the * symbol for multiplication. if...then...fi statement is a decision-making statement which has been explained in the next chapter. if...then...fi statement is a decision-making statement which has been explained in the next chapter. 129 Lectures 23 hours Eduonix Learning Solutions 5 Lectures 4.5 hours Frahaan Hussain 35 Lectures 2 hours Pradeep D 41 Lectures 2.5 hours Musab Zayadneh 46 Lectures 4 hours GUHARAJANM 6 Lectures 4 hours Uplatz Print Add Notes Bookmark this page
[ { "code": null, "e": 2813, "s": 2747, "text": "The following arithmetic operators are supported by Bourne Shell." }, { "code": null, "e": 2871, "s": 2813, "text": "Assume variable a holds 10 and variable b holds 20 then −" }, { "code": null, "e": 3067, "s": 2871, "text": "It is very important to understand that all the conditional expressions should be inside square braces with spaces around them, for example [ $a == $b ] is correct whereas, [$a==$b] is incorrect." }, { "code": null, "e": 3131, "s": 3067, "text": "All the arithmetical calculations are done using long integers." }, { "code": null, "e": 3192, "s": 3131, "text": "Here is an example which uses all the arithmetic operators −" }, { "code": null, "e": 3520, "s": 3192, "text": "#!/bin/sh\n\na=10\nb=20\n\nval=`expr $a + $b`\necho \"a + b : $val\"\n\nval=`expr $a - $b`\necho \"a - b : $val\"\n\nval=`expr $a \\* $b`\necho \"a * b : $val\"\n\nval=`expr $b / $a`\necho \"b / a : $val\"\n\nval=`expr $b % $a`\necho \"b % a : $val\"\n\nif [ $a == $b ]\nthen\n echo \"a is equal to b\"\nfi\n\nif [ $a != $b ]\nthen\n echo \"a is not equal to b\"\nfi" }, { "code": null, "e": 3573, "s": 3520, "text": "The above script will produce the following result −" }, { "code": null, "e": 3649, "s": 3573, "text": "a + b : 30\na - b : -10\na * b : 200\nb / a : 2\nb % a : 0\na is not equal to b\n" }, { "code": null, "e": 3730, "s": 3649, "text": "The following points need to be considered when using the Arithmetic Operators −" }, { "code": null, "e": 3858, "s": 3730, "text": "There must be spaces between the operators and the expressions. For example, 2+2 is not correct; it should be written as 2 + 2." }, { "code": null, "e": 3986, "s": 3858, "text": "There must be spaces between the operators and the expressions. For example, 2+2 is not correct; it should be written as 2 + 2." }, { "code": null, "e": 4066, "s": 3986, "text": "Complete expression should be enclosed between ‘ ‘, called the inverted commas." }, { "code": null, "e": 4146, "s": 4066, "text": "Complete expression should be enclosed between ‘ ‘, called the inverted commas." }, { "code": null, "e": 4199, "s": 4146, "text": "You should use \\ on the * symbol for multiplication." }, { "code": null, "e": 4252, "s": 4199, "text": "You should use \\ on the * symbol for multiplication." }, { "code": null, "e": 4354, "s": 4252, "text": "if...then...fi statement is a decision-making statement which has been explained in the next chapter." }, { "code": null, "e": 4456, "s": 4354, "text": "if...then...fi statement is a decision-making statement which has been explained in the next chapter." }, { "code": null, "e": 4491, "s": 4456, "text": "\n 129 Lectures \n 23 hours \n" }, { "code": null, "e": 4519, "s": 4491, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 4553, "s": 4519, "text": "\n 5 Lectures \n 4.5 hours \n" }, { "code": null, "e": 4570, "s": 4553, "text": " Frahaan Hussain" }, { "code": null, "e": 4603, "s": 4570, "text": "\n 35 Lectures \n 2 hours \n" }, { "code": null, "e": 4614, "s": 4603, "text": " Pradeep D" }, { "code": null, "e": 4649, "s": 4614, "text": "\n 41 Lectures \n 2.5 hours \n" }, { "code": null, "e": 4665, "s": 4649, "text": " Musab Zayadneh" }, { "code": null, "e": 4698, "s": 4665, "text": "\n 46 Lectures \n 4 hours \n" }, { "code": null, "e": 4710, "s": 4698, "text": " GUHARAJANM" }, { "code": null, "e": 4742, "s": 4710, "text": "\n 6 Lectures \n 4 hours \n" }, { "code": null, "e": 4750, "s": 4742, "text": " Uplatz" }, { "code": null, "e": 4757, "s": 4750, "text": " Print" }, { "code": null, "e": 4768, "s": 4757, "text": " Add Notes" } ]
jQuery | on() with Examples
16 Apr, 2020 The on() is an inbuilt method in jQuery which is used to attach one or more event handlers for the selected elements and child elements in the DOM tree. The DOM (Document Object Model) is a World Wide Web Consortium standard. This defines for accessing elements in the DOM tree.Syntax: $(selector).on(event, childSelector, data, function) Parameter: It accepts some parameters which are specified below- event: This specifies the events that are attached to the selected element. childSelector: This is optional and this specify the specific child to which given event handler can be used. data: This is optional and this specifies additional data to be passed along with the function. function: This specifies the function to run when the event occurs. Return Value: This returns all the event handler that are attached to selected element. jQuery code to show the working of on() method:Code #1:In the code below child specifier and data is not passed. <html> <head> <script src="https://ajax.googleapis.com/ajax/ libs/jquery/3.3.1/jquery.min.js"></script> <script> <!--jQuery code to show on method --> $(document).ready(function() { $("p").on("click", function() { document.getElementById("p1").innerHTML = "Paragraph changed!"; }); }); </script> <style> #p1 { font-size: 30px; width: 400px; padding: 20px; border: 2px solid green; } </style></head> <body> <!--click on this paragraph --> <p id="p1">Click Here !!!</p></body> </html> Output:Before clicking on generated output-After clicking on generated output- Code #2:In the below code data and message both are being passed to the function. <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/ jquery/3.3.1/jquery.min.js"></script> <script> <!--jQuery code to show on method --> function handlerName(event) { var t = event.data.msg; document.getElementById("p1").innerHTML = t; } $(document).ready(function() { $("p").on("click", { msg: "You just clicked the given paragraph !" }, handlerName) }); </script> <style> #p1 { font-size: 30px; width: 470px; padding: 20px; border: 2px solid green; } </style></head> <body> <!--click on this paragraph --> <p id="p1">Click Me!</p></body> </html> Output :Before clicking the generated output-After clicking the generated output- frikishaan jQuery-Events JavaScript JQuery Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Remove elements from a JavaScript Array Difference Between PUT and PATCH Request Roadmap to Learn JavaScript For Beginners JavaScript | Promises JQuery | Set the value of an input text field How to change selected value of a drop-down list using jQuery? Form validation using jQuery How to add options to a select element using jQuery? jQuery | children() with Examples
[ { "code": null, "e": 28, "s": 0, "text": "\n16 Apr, 2020" }, { "code": null, "e": 314, "s": 28, "text": "The on() is an inbuilt method in jQuery which is used to attach one or more event handlers for the selected elements and child elements in the DOM tree. The DOM (Document Object Model) is a World Wide Web Consortium standard. This defines for accessing elements in the DOM tree.Syntax:" }, { "code": null, "e": 368, "s": 314, "text": "$(selector).on(event, childSelector, data, function)\n" }, { "code": null, "e": 433, "s": 368, "text": "Parameter: It accepts some parameters which are specified below-" }, { "code": null, "e": 509, "s": 433, "text": "event: This specifies the events that are attached to the selected element." }, { "code": null, "e": 619, "s": 509, "text": "childSelector: This is optional and this specify the specific child to which given event handler can be used." }, { "code": null, "e": 715, "s": 619, "text": "data: This is optional and this specifies additional data to be passed along with the function." }, { "code": null, "e": 783, "s": 715, "text": "function: This specifies the function to run when the event occurs." }, { "code": null, "e": 871, "s": 783, "text": "Return Value: This returns all the event handler that are attached to selected element." }, { "code": null, "e": 984, "s": 871, "text": "jQuery code to show the working of on() method:Code #1:In the code below child specifier and data is not passed." }, { "code": "<html> <head> <script src=\"https://ajax.googleapis.com/ajax/ libs/jquery/3.3.1/jquery.min.js\"></script> <script> <!--jQuery code to show on method --> $(document).ready(function() { $(\"p\").on(\"click\", function() { document.getElementById(\"p1\").innerHTML = \"Paragraph changed!\"; }); }); </script> <style> #p1 { font-size: 30px; width: 400px; padding: 20px; border: 2px solid green; } </style></head> <body> <!--click on this paragraph --> <p id=\"p1\">Click Here !!!</p></body> </html>", "e": 1619, "s": 984, "text": null }, { "code": null, "e": 1698, "s": 1619, "text": "Output:Before clicking on generated output-After clicking on generated output-" }, { "code": null, "e": 1780, "s": 1698, "text": "Code #2:In the below code data and message both are being passed to the function." }, { "code": "<html> <head> <script src=\"https://ajax.googleapis.com/ajax/libs/ jquery/3.3.1/jquery.min.js\"></script> <script> <!--jQuery code to show on method --> function handlerName(event) { var t = event.data.msg; document.getElementById(\"p1\").innerHTML = t; } $(document).ready(function() { $(\"p\").on(\"click\", { msg: \"You just clicked the given paragraph !\" }, handlerName) }); </script> <style> #p1 { font-size: 30px; width: 470px; padding: 20px; border: 2px solid green; } </style></head> <body> <!--click on this paragraph --> <p id=\"p1\">Click Me!</p></body> </html>", "e": 2535, "s": 1780, "text": null }, { "code": null, "e": 2617, "s": 2535, "text": "Output :Before clicking the generated output-After clicking the generated output-" }, { "code": null, "e": 2628, "s": 2617, "text": "frikishaan" }, { "code": null, "e": 2642, "s": 2628, "text": "jQuery-Events" }, { "code": null, "e": 2653, "s": 2642, "text": "JavaScript" }, { "code": null, "e": 2660, "s": 2653, "text": "JQuery" }, { "code": null, "e": 2758, "s": 2660, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2819, "s": 2758, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2859, "s": 2819, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 2900, "s": 2859, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 2942, "s": 2900, "text": "Roadmap to Learn JavaScript For Beginners" }, { "code": null, "e": 2964, "s": 2942, "text": "JavaScript | Promises" }, { "code": null, "e": 3010, "s": 2964, "text": "JQuery | Set the value of an input text field" }, { "code": null, "e": 3073, "s": 3010, "text": "How to change selected value of a drop-down list using jQuery?" }, { "code": null, "e": 3102, "s": 3073, "text": "Form validation using jQuery" }, { "code": null, "e": 3155, "s": 3102, "text": "How to add options to a select element using jQuery?" } ]
Text to text Transfer Transformer in Data Augmentation
22 Jan, 2021 Do you want to achieve ‘the-state-of-the-art’ results in your next NLP project? Is your data insufficient for training the machine learning model? Do you want to improve the accuracy of your machine learning model with some extra data? If yes, all you need is Data Augmentation. Whether you are building text classification, summarization, question answering, or any other machine learning model. Data Augmentation will help to improve the performance of your model. There are five data augmentation techniques: Word EmbeddingsBERTBack TranslationText to Text Transfer TransformerEnsemble Approach. Word Embeddings BERT Back Translation Text to Text Transfer Transformer Ensemble Approach. Data augmentation using Text to Text Transfer Transformer (T5) is a large transformer model trained on the Colossal Clean Crawled Corpus (C4) dataset. Google open-sourced a pre-trained T5 model that is capable of doing multiple tasks like translation, summarization, question answering, and classification. T5 reframes every NLP task into text to text format. Example 1: The T5 model can be trained for English German translation with Input translate text English to German, English text, and German text as output. Example 2: To train the model for sentiment classification input can be sentiment classification, input text, and Output can be the sentiment. The same model can be trained for multiple tasks by specifying different tasks. Specific prefix string in input training data. T5 achieved state-of-the-art results on a variety of NLP tasks. This can be done in multiple ways. In Back Translation, we used pre-trained models out of the box. If we want to use T5 out of the box, we can make use of its text summarization capabilities for data augmentation. T5 can take input in the format, summarize, input text, and generate a summary of the input. T5 is an abstractive summarization algorithm. T5 can rephrase sentences or use new words to generate the summary. T5 data augmentation technique is useful for NLP tasks involving long text documents. For a short text, it may not give very good results. Another approach to use T5 for data augmentation is to make use of the transfer learning technique and use the knowledge stored inside T5 to generate synthetic data. This can be done in multiple ways. 1) One way is to fine-tune T5 on a masked word prediction task, the same on which BERT is trained on. Fine Tuning Data on Masked word Prediction Task We can use the same C4 dataset on which T5 is pre-trained to further fine-tune it for masked word prediction. So the input to the model will start with some prefix like predict mask followed by an input sentence having a masked word and the output will be the original sentence without a mask. We can also mask multiple words in the same sentence and train T5 to predict the span of words. If we mask a single word, the model will not be able to generate new data that has variations in sentence structure. But if we mask multiple words, the model can learn to generate data with slight variations in sentence structure as well. This way, our data augmentation approach will be very similar to the BERT based approach. 2) Another way to use T5 for data augmentation is to fine-tune it on paraphrased generation task. Fine Tuning T5 for Paraphrase Generation using PAWS Dataset Paraphrasing means generating an output sentence that has the same meaning as that of input, but a different sentence structure and keyword. This is exactly what we need for data augmentation. We are going to use the PAWS dataset to find tune T5 for paraphrase generation. PAWS stands for paraphrase adversaries from word scrambling. This dataset contains thousands of paraphrases and is available in six languages other than English. So, Our data augmentation approach using T5 will be as follows: Step 1: Involve some data preprocessing and which will convert the PAWS dataset into the format required for training T5. Step 2: The next step will be to fine-tune, T5. For fine-tuning, Our input to the model will be in the format, generate paraphrased input text and output will be a paraphrase of the input text. Once we have a fine-tuned model, we can use it to generate paraphrases of any input text. We can provide input with the prefix generate paraphrase and the model will output its paraphrase. The model can be configured to output multiple paraphrases. This way we can very easily create our own paraphrase generation model for the data augmentation. The pre-trained T5 model is available in five different sizes. T5 Small (60M Params)T5 Base (220 Params)T5 Large (770 Params)T5 3 B (3 B Params)T5 11 B (11 B Params) T5 Small (60M Params) T5 Base (220 Params) T5 Large (770 Params) T5 3 B (3 B Params) T5 11 B (11 B Params) The larger model gives better results, but also requires more computing power and takes a lot of time to train. But it’s a one-time process. Once you have a good quality fine-tuned paraphrase generation model trained on an appropriate dataset, it can be used for the data augmentation in several NLP tasks. We are going to implement Data Augmentation using a Text to Text Transfer Transformer using the simple transformers library. This library is based on the Hugging face transformers Library. It makes it simple to fine-tune transformer-based models. Step 1: We’re going to upload PAWS data set (paraphrase adversaries from word scrambling) that we need for fine-tuning. Step 2: We need to prepare the dataset for training so that, we can start Fine-tuning the model. Step 3: We will create and save the fine-tuned model on Google Drive. Step 4: Finally, we will load the saved model and generate paraphrases that can be used for data augmentation Python3 !pip install simpletransformers import pandas as pdfrom simpletransformers.t5 import T5Modelfrom pprint import pprintimport logging You can download the dataset from this link PAWS wiki labelled dataset. It has three files train, dev, and test.tsv. We are only going to use train and dev files. This dataset has three columns, sentence one, sentence two, and label. The label is one of two sentences are paraphrases and zero otherwise. Python df = pd.read_csv('train.tsv',sep='\t')df.head(5) When comparable rates of flow can be maintained, the results are high. The corresponding sentence2 shows that the results are high when comparable flow rates can be maintained. These two sentences are paraphrases, so the label is one. We’re going to fine-tune T5 for paraphrase generation. So we need only paraphrases from this dataset. This means only the samples that have labeled one are useful for our task. Python df.describe() The size of this dataset is 49401. Let’s keep only the pairs that have label one. Python paraphrase_train = df[df['label']==1]paraphrase_train.head(5)paraphrase_train.describe() Now the size is reduced to almost half. T5 can be trained for multiple tasks. So when giving input to the model, we need to add some task-specific prefix. For that, We are adding a new column prefix in our data frame with the value generated paraphrase. We need to rename sentence one and sentence two-column also. Note that rename should be “input_text” and “target_text” otherwise it will show runtime error. Python paraphrase_train["prefix"] = "Generate Paraphrase for this line"paraphrase_train= paraphrase_train.rename( columns={"sentence1": "input_text", "sentence2": "target_text"}) Same steps, We need to apply to dev.tsv. Python df = pd.read_csv('dev.tsv',sep='\t')paraphrase_dev = df[df['label']==1]paraphrase_dev["prefix"] = "Generate Paraphrase for this line"paraphrase_dev = paraphrase_dev.rename( columns={"sentence1": "input_text", "sentence2": "target_text"}) First, we need to decide some configuration parameters. You can go through Simple Transformer’s documentation to understand all these parameters. The last parameter is to determine how many paraphrases to generate for every input. The paraphrases are generated using a combination of top-k sampling and top-p nucleus sampling. To create an object of the T5 model class, we need to pass configuration parameters and the type of T5 model. T5 is available in multiple sizes, we’re going to use the T5 small version. Python model_args = { "reprocess_input_data": True, "overwrite_output_dir": True, "max_seq_length": 128, "train_batch_size": 16, "num_train_epochs": 10, "num_beams": None, "do_sample": True, "max_length": 20, "top_k": 50, "top_p": 0.95, "use_multiprocessing": False, "save_steps": -1, "save_eval_checkpoints": True, "evaluate_during_training": True, "evaluate_during_training_verbose": True, "num_return_sequences": 5} Python model = T5Model("t5","t5-small", args=model_args)model.train_model(paraphrase_train, eval_data=paraphrase_dev) Python //import drivefrom google.colab import drivedrive.mount('/content/gdrive') //copy path of best_model!cp -r /content/outputs/best_model/ /content/gdrive/'My Drive'/T5/ //load modelpre_trained_model = T5Model("/content/gdrive/My Drive/T5/best_model", model_args) In some cases, it may not give good results, but there is a lot of scopes to improve the model instead of using the T5 small version. If we use a larger version and fine-tune it on a larger dataset, we can get much better results. Also, you can go to the hugging face model repository and search for T5 there. You may find some T5 model fine-tuned on paraphrase generation. You can also try out these models or further fine-tune them on your domain-specific dataset. This is the advantage of this data augmentation technique. Natural-language-processing Technical Scripter 2020 Machine Learning Technical Scripter Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n22 Jan, 2021" }, { "code": null, "e": 132, "s": 52, "text": "Do you want to achieve ‘the-state-of-the-art’ results in your next NLP project?" }, { "code": null, "e": 199, "s": 132, "text": "Is your data insufficient for training the machine learning model?" }, { "code": null, "e": 288, "s": 199, "text": "Do you want to improve the accuracy of your machine learning model with some extra data?" }, { "code": null, "e": 519, "s": 288, "text": "If yes, all you need is Data Augmentation. Whether you are building text classification, summarization, question answering, or any other machine learning model. Data Augmentation will help to improve the performance of your model." }, { "code": null, "e": 564, "s": 519, "text": "There are five data augmentation techniques:" }, { "code": null, "e": 651, "s": 564, "text": "Word EmbeddingsBERTBack TranslationText to Text Transfer TransformerEnsemble Approach." }, { "code": null, "e": 667, "s": 651, "text": "Word Embeddings" }, { "code": null, "e": 672, "s": 667, "text": "BERT" }, { "code": null, "e": 689, "s": 672, "text": "Back Translation" }, { "code": null, "e": 723, "s": 689, "text": "Text to Text Transfer Transformer" }, { "code": null, "e": 742, "s": 723, "text": "Ensemble Approach." }, { "code": null, "e": 1050, "s": 742, "text": "Data augmentation using Text to Text Transfer Transformer (T5) is a large transformer model trained on the Colossal Clean Crawled Corpus (C4) dataset. Google open-sourced a pre-trained T5 model that is capable of doing multiple tasks like translation, summarization, question answering, and classification." }, { "code": null, "e": 1103, "s": 1050, "text": "T5 reframes every NLP task into text to text format." }, { "code": null, "e": 1260, "s": 1103, "text": "Example 1: The T5 model can be trained for English German translation with Input translate text English to German, English text, and German text as output. " }, { "code": null, "e": 1403, "s": 1260, "text": "Example 2: To train the model for sentiment classification input can be sentiment classification, input text, and Output can be the sentiment." }, { "code": null, "e": 1594, "s": 1403, "text": "The same model can be trained for multiple tasks by specifying different tasks. Specific prefix string in input training data. T5 achieved state-of-the-art results on a variety of NLP tasks." }, { "code": null, "e": 1629, "s": 1594, "text": "This can be done in multiple ways." }, { "code": null, "e": 1808, "s": 1629, "text": "In Back Translation, we used pre-trained models out of the box. If we want to use T5 out of the box, we can make use of its text summarization capabilities for data augmentation." }, { "code": null, "e": 1901, "s": 1808, "text": "T5 can take input in the format, summarize, input text, and generate a summary of the input." }, { "code": null, "e": 1947, "s": 1901, "text": "T5 is an abstractive summarization algorithm." }, { "code": null, "e": 2015, "s": 1947, "text": "T5 can rephrase sentences or use new words to generate the summary." }, { "code": null, "e": 2101, "s": 2015, "text": "T5 data augmentation technique is useful for NLP tasks involving long text documents." }, { "code": null, "e": 2154, "s": 2101, "text": "For a short text, it may not give very good results." }, { "code": null, "e": 2355, "s": 2154, "text": "Another approach to use T5 for data augmentation is to make use of the transfer learning technique and use the knowledge stored inside T5 to generate synthetic data. This can be done in multiple ways." }, { "code": null, "e": 2458, "s": 2355, "text": "1) One way is to fine-tune T5 on a masked word prediction task, the same on which BERT is trained on. " }, { "code": null, "e": 2506, "s": 2458, "text": "Fine Tuning Data on Masked word Prediction Task" }, { "code": null, "e": 2800, "s": 2506, "text": "We can use the same C4 dataset on which T5 is pre-trained to further fine-tune it for masked word prediction. So the input to the model will start with some prefix like predict mask followed by an input sentence having a masked word and the output will be the original sentence without a mask." }, { "code": null, "e": 3225, "s": 2800, "text": "We can also mask multiple words in the same sentence and train T5 to predict the span of words. If we mask a single word, the model will not be able to generate new data that has variations in sentence structure. But if we mask multiple words, the model can learn to generate data with slight variations in sentence structure as well. This way, our data augmentation approach will be very similar to the BERT based approach." }, { "code": null, "e": 3323, "s": 3225, "text": "2) Another way to use T5 for data augmentation is to fine-tune it on paraphrased generation task." }, { "code": null, "e": 3383, "s": 3323, "text": "Fine Tuning T5 for Paraphrase Generation using PAWS Dataset" }, { "code": null, "e": 3576, "s": 3383, "text": "Paraphrasing means generating an output sentence that has the same meaning as that of input, but a different sentence structure and keyword. This is exactly what we need for data augmentation." }, { "code": null, "e": 3818, "s": 3576, "text": "We are going to use the PAWS dataset to find tune T5 for paraphrase generation. PAWS stands for paraphrase adversaries from word scrambling. This dataset contains thousands of paraphrases and is available in six languages other than English." }, { "code": null, "e": 3882, "s": 3818, "text": "So, Our data augmentation approach using T5 will be as follows:" }, { "code": null, "e": 4004, "s": 3882, "text": "Step 1: Involve some data preprocessing and which will convert the PAWS dataset into the format required for training T5." }, { "code": null, "e": 4198, "s": 4004, "text": "Step 2: The next step will be to fine-tune, T5. For fine-tuning, Our input to the model will be in the format, generate paraphrased input text and output will be a paraphrase of the input text." }, { "code": null, "e": 4387, "s": 4198, "text": "Once we have a fine-tuned model, we can use it to generate paraphrases of any input text. We can provide input with the prefix generate paraphrase and the model will output its paraphrase." }, { "code": null, "e": 4545, "s": 4387, "text": "The model can be configured to output multiple paraphrases. This way we can very easily create our own paraphrase generation model for the data augmentation." }, { "code": null, "e": 4608, "s": 4545, "text": "The pre-trained T5 model is available in five different sizes." }, { "code": null, "e": 4711, "s": 4608, "text": "T5 Small (60M Params)T5 Base (220 Params)T5 Large (770 Params)T5 3 B (3 B Params)T5 11 B (11 B Params)" }, { "code": null, "e": 4733, "s": 4711, "text": "T5 Small (60M Params)" }, { "code": null, "e": 4754, "s": 4733, "text": "T5 Base (220 Params)" }, { "code": null, "e": 4776, "s": 4754, "text": "T5 Large (770 Params)" }, { "code": null, "e": 4796, "s": 4776, "text": "T5 3 B (3 B Params)" }, { "code": null, "e": 4818, "s": 4796, "text": "T5 11 B (11 B Params)" }, { "code": null, "e": 5125, "s": 4818, "text": "The larger model gives better results, but also requires more computing power and takes a lot of time to train. But it’s a one-time process. Once you have a good quality fine-tuned paraphrase generation model trained on an appropriate dataset, it can be used for the data augmentation in several NLP tasks." }, { "code": null, "e": 5372, "s": 5125, "text": "We are going to implement Data Augmentation using a Text to Text Transfer Transformer using the simple transformers library. This library is based on the Hugging face transformers Library. It makes it simple to fine-tune transformer-based models." }, { "code": null, "e": 5492, "s": 5372, "text": "Step 1: We’re going to upload PAWS data set (paraphrase adversaries from word scrambling) that we need for fine-tuning." }, { "code": null, "e": 5589, "s": 5492, "text": "Step 2: We need to prepare the dataset for training so that, we can start Fine-tuning the model." }, { "code": null, "e": 5659, "s": 5589, "text": "Step 3: We will create and save the fine-tuned model on Google Drive." }, { "code": null, "e": 5769, "s": 5659, "text": "Step 4: Finally, we will load the saved model and generate paraphrases that can be used for data augmentation" }, { "code": null, "e": 5777, "s": 5769, "text": "Python3" }, { "code": "!pip install simpletransformers import pandas as pdfrom simpletransformers.t5 import T5Modelfrom pprint import pprintimport logging", "e": 5910, "s": 5777, "text": null }, { "code": null, "e": 6214, "s": 5910, "text": "You can download the dataset from this link PAWS wiki labelled dataset. It has three files train, dev, and test.tsv. We are only going to use train and dev files. This dataset has three columns, sentence one, sentence two, and label. The label is one of two sentences are paraphrases and zero otherwise." }, { "code": null, "e": 6221, "s": 6214, "text": "Python" }, { "code": "df = pd.read_csv('train.tsv',sep='\\t')df.head(5)", "e": 6270, "s": 6221, "text": null }, { "code": null, "e": 6505, "s": 6270, "text": "When comparable rates of flow can be maintained, the results are high. The corresponding sentence2 shows that the results are high when comparable flow rates can be maintained. These two sentences are paraphrases, so the label is one." }, { "code": null, "e": 6682, "s": 6505, "text": "We’re going to fine-tune T5 for paraphrase generation. So we need only paraphrases from this dataset. This means only the samples that have labeled one are useful for our task." }, { "code": null, "e": 6689, "s": 6682, "text": "Python" }, { "code": "df.describe()", "e": 6703, "s": 6689, "text": null }, { "code": null, "e": 6738, "s": 6703, "text": "The size of this dataset is 49401." }, { "code": null, "e": 6785, "s": 6738, "text": "Let’s keep only the pairs that have label one." }, { "code": null, "e": 6792, "s": 6785, "text": "Python" }, { "code": "paraphrase_train = df[df['label']==1]paraphrase_train.head(5)paraphrase_train.describe()", "e": 6881, "s": 6792, "text": null }, { "code": null, "e": 7135, "s": 6881, "text": "Now the size is reduced to almost half. T5 can be trained for multiple tasks. So when giving input to the model, we need to add some task-specific prefix. For that, We are adding a new column prefix in our data frame with the value generated paraphrase." }, { "code": null, "e": 7292, "s": 7135, "text": "We need to rename sentence one and sentence two-column also. Note that rename should be “input_text” and “target_text” otherwise it will show runtime error." }, { "code": null, "e": 7299, "s": 7292, "text": "Python" }, { "code": "paraphrase_train[\"prefix\"] = \"Generate Paraphrase for this line\"paraphrase_train= paraphrase_train.rename( columns={\"sentence1\": \"input_text\", \"sentence2\": \"target_text\"})", "e": 7472, "s": 7299, "text": null }, { "code": null, "e": 7513, "s": 7472, "text": "Same steps, We need to apply to dev.tsv." }, { "code": null, "e": 7520, "s": 7513, "text": "Python" }, { "code": "df = pd.read_csv('dev.tsv',sep='\\t')paraphrase_dev = df[df['label']==1]paraphrase_dev[\"prefix\"] = \"Generate Paraphrase for this line\"paraphrase_dev = paraphrase_dev.rename( columns={\"sentence1\": \"input_text\", \"sentence2\": \"target_text\"})", "e": 7759, "s": 7520, "text": null }, { "code": null, "e": 7905, "s": 7759, "text": "First, we need to decide some configuration parameters. You can go through Simple Transformer’s documentation to understand all these parameters." }, { "code": null, "e": 8086, "s": 7905, "text": "The last parameter is to determine how many paraphrases to generate for every input. The paraphrases are generated using a combination of top-k sampling and top-p nucleus sampling." }, { "code": null, "e": 8272, "s": 8086, "text": "To create an object of the T5 model class, we need to pass configuration parameters and the type of T5 model. T5 is available in multiple sizes, we’re going to use the T5 small version." }, { "code": null, "e": 8279, "s": 8272, "text": "Python" }, { "code": "model_args = { \"reprocess_input_data\": True, \"overwrite_output_dir\": True, \"max_seq_length\": 128, \"train_batch_size\": 16, \"num_train_epochs\": 10, \"num_beams\": None, \"do_sample\": True, \"max_length\": 20, \"top_k\": 50, \"top_p\": 0.95, \"use_multiprocessing\": False, \"save_steps\": -1, \"save_eval_checkpoints\": True, \"evaluate_during_training\": True, \"evaluate_during_training_verbose\": True, \"num_return_sequences\": 5}", "e": 8739, "s": 8279, "text": null }, { "code": null, "e": 8746, "s": 8739, "text": "Python" }, { "code": "model = T5Model(\"t5\",\"t5-small\", args=model_args)model.train_model(paraphrase_train, eval_data=paraphrase_dev)", "e": 8857, "s": 8746, "text": null }, { "code": null, "e": 8864, "s": 8857, "text": "Python" }, { "code": "//import drivefrom google.colab import drivedrive.mount('/content/gdrive') //copy path of best_model!cp -r /content/outputs/best_model/ /content/gdrive/'My Drive'/T5/ //load modelpre_trained_model = T5Model(\"/content/gdrive/My Drive/T5/best_model\", model_args)", "e": 9127, "s": 8864, "text": null }, { "code": null, "e": 9358, "s": 9127, "text": "In some cases, it may not give good results, but there is a lot of scopes to improve the model instead of using the T5 small version. If we use a larger version and fine-tune it on a larger dataset, we can get much better results." }, { "code": null, "e": 9594, "s": 9358, "text": "Also, you can go to the hugging face model repository and search for T5 there. You may find some T5 model fine-tuned on paraphrase generation. You can also try out these models or further fine-tune them on your domain-specific dataset." }, { "code": null, "e": 9653, "s": 9594, "text": "This is the advantage of this data augmentation technique." }, { "code": null, "e": 9681, "s": 9653, "text": "Natural-language-processing" }, { "code": null, "e": 9705, "s": 9681, "text": "Technical Scripter 2020" }, { "code": null, "e": 9722, "s": 9705, "text": "Machine Learning" }, { "code": null, "e": 9741, "s": 9722, "text": "Technical Scripter" }, { "code": null, "e": 9758, "s": 9741, "text": "Machine Learning" } ]
Stream.distinct() in Java
06 Dec, 2018 distinct() returns a stream consisting of distinct elements in a stream. distinct() is the method of Stream interface. This method uses hashCode() and equals() methods to get distinct elements. In case of ordered streams, the selection of distinct elements is stable. But, in case of unordered streams, the selection of distinct elements is not necessarily stable and can change. distinct() performs stateful intermediate operation i.e, it maintains some state internally to accomplish the operation. Syntax : Stream<T> distinct() Where, Stream is an interface and the function returns a stream consisting of the distinct elements. Below given are some examples to understand the implementation of the function in a better way.Example 1 : // Implementation of Stream.distinct()// to get the distinct elements in the Listimport java.util.*; class GFG { // Driver code public static void main(String[] args) { // Creating a list of integers List<Integer> list = Arrays.asList(1, 1, 2, 3, 3, 4, 5, 5); System.out.println("The distinct elements are :"); // Displaying the distinct elements in the list // using Stream.distinct() method list.stream().distinct().forEach(System.out::println); }} Output : The distinct elements are : 1 2 3 4 5 Example 2 : // Implementation of Stream.distinct()// to get the distinct elements in the Listimport java.util.*; class GFG { // Driver code public static void main(String[] args) { // Creating a list of strings List<String> list = Arrays.asList("Geeks", "for", "Geeks", "GeeksQuiz", "for", "GeeksforGeeks"); System.out.println("The distinct elements are :"); // Displaying the distinct elements in the list // using Stream.distinct() method list.stream().distinct().forEach(System.out::println); }} Output : The distinct elements are : Geeks for GeeksQuiz GeeksforGeeks Example 3 : // Implementation of Stream.distinct()// to get the count of distinct elements// in the Listimport java.util.*; class GFG { // Driver code public static void main(String[] args) { // Creating a list of strings List<String> list = Arrays.asList("Geeks", "for", "Geeks", "GeeksQuiz", "for", "GeeksforGeeks"); // Storing the count of distinct elements // in the list using Stream.distinct() method long Count = list.stream().distinct().count(); // Displaying the count of distinct elements System.out.println("The count of distinct elements is : " + Count); }} Output : The count of distinct elements is : 4 Java - util package Java-Functions java-stream Java-Stream interface Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java How to iterate any Map in Java Interfaces in Java HashMap in Java with Examples ArrayList in Java Collections in Java Singleton Class in Java Multidimensional Arrays in Java Set in Java Stack Class in Java
[ { "code": null, "e": 54, "s": 26, "text": "\n06 Dec, 2018" }, { "code": null, "e": 555, "s": 54, "text": "distinct() returns a stream consisting of distinct elements in a stream. distinct() is the method of Stream interface. This method uses hashCode() and equals() methods to get distinct elements. In case of ordered streams, the selection of distinct elements is stable. But, in case of unordered streams, the selection of distinct elements is not necessarily stable and can change. distinct() performs stateful intermediate operation i.e, it maintains some state internally to accomplish the operation." }, { "code": null, "e": 564, "s": 555, "text": "Syntax :" }, { "code": null, "e": 689, "s": 564, "text": "Stream<T> distinct()\n\nWhere, Stream is an interface and the function\nreturns a stream consisting of the distinct \nelements.\n" }, { "code": null, "e": 796, "s": 689, "text": "Below given are some examples to understand the implementation of the function in a better way.Example 1 :" }, { "code": "// Implementation of Stream.distinct()// to get the distinct elements in the Listimport java.util.*; class GFG { // Driver code public static void main(String[] args) { // Creating a list of integers List<Integer> list = Arrays.asList(1, 1, 2, 3, 3, 4, 5, 5); System.out.println(\"The distinct elements are :\"); // Displaying the distinct elements in the list // using Stream.distinct() method list.stream().distinct().forEach(System.out::println); }}", "e": 1310, "s": 796, "text": null }, { "code": null, "e": 1319, "s": 1310, "text": "Output :" }, { "code": null, "e": 1358, "s": 1319, "text": "The distinct elements are :\n1\n2\n3\n4\n5\n" }, { "code": null, "e": 1370, "s": 1358, "text": "Example 2 :" }, { "code": "// Implementation of Stream.distinct()// to get the distinct elements in the Listimport java.util.*; class GFG { // Driver code public static void main(String[] args) { // Creating a list of strings List<String> list = Arrays.asList(\"Geeks\", \"for\", \"Geeks\", \"GeeksQuiz\", \"for\", \"GeeksforGeeks\"); System.out.println(\"The distinct elements are :\"); // Displaying the distinct elements in the list // using Stream.distinct() method list.stream().distinct().forEach(System.out::println); }}", "e": 1961, "s": 1370, "text": null }, { "code": null, "e": 1970, "s": 1961, "text": "Output :" }, { "code": null, "e": 2033, "s": 1970, "text": "The distinct elements are :\nGeeks\nfor\nGeeksQuiz\nGeeksforGeeks\n" }, { "code": null, "e": 2045, "s": 2033, "text": "Example 3 :" }, { "code": "// Implementation of Stream.distinct()// to get the count of distinct elements// in the Listimport java.util.*; class GFG { // Driver code public static void main(String[] args) { // Creating a list of strings List<String> list = Arrays.asList(\"Geeks\", \"for\", \"Geeks\", \"GeeksQuiz\", \"for\", \"GeeksforGeeks\"); // Storing the count of distinct elements // in the list using Stream.distinct() method long Count = list.stream().distinct().count(); // Displaying the count of distinct elements System.out.println(\"The count of distinct elements is : \" + Count); }}", "e": 2714, "s": 2045, "text": null }, { "code": null, "e": 2723, "s": 2714, "text": "Output :" }, { "code": null, "e": 2762, "s": 2723, "text": "The count of distinct elements is : 4\n" }, { "code": null, "e": 2782, "s": 2762, "text": "Java - util package" }, { "code": null, "e": 2797, "s": 2782, "text": "Java-Functions" }, { "code": null, "e": 2809, "s": 2797, "text": "java-stream" }, { "code": null, "e": 2831, "s": 2809, "text": "Java-Stream interface" }, { "code": null, "e": 2836, "s": 2831, "text": "Java" }, { "code": null, "e": 2841, "s": 2836, "text": "Java" }, { "code": null, "e": 2939, "s": 2841, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2990, "s": 2939, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 3021, "s": 2990, "text": "How to iterate any Map in Java" }, { "code": null, "e": 3040, "s": 3021, "text": "Interfaces in Java" }, { "code": null, "e": 3070, "s": 3040, "text": "HashMap in Java with Examples" }, { "code": null, "e": 3088, "s": 3070, "text": "ArrayList in Java" }, { "code": null, "e": 3108, "s": 3088, "text": "Collections in Java" }, { "code": null, "e": 3132, "s": 3108, "text": "Singleton Class in Java" }, { "code": null, "e": 3164, "s": 3132, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 3176, "s": 3164, "text": "Set in Java" } ]
Average Cells Based On Multiple Criteria in Excel
23 Jun, 2021 Average a number expressing the central or typical value in a set of data, in particular the mode, median, or (most commonly) the mean, which is calculated by dividing the sum of the values in the set by their number. The basic formula for the average of n numbers x1,x2,......xn is A = (x1 + x2 ........xn)/ n In Excel, there is an average function for this purpose, but it can be calculated manually also using SUM and COUNT functions like this = SUM(D1:D5)/COUNT(D1:D5) Here SUM: This function is used to find the sum of values in the required range of cells.COUNT: This function is used to get the count of the required range of cells containing numeric values. SUM: This function is used to find the sum of values in the required range of cells. COUNT: This function is used to get the count of the required range of cells containing numeric values. Excel provides a direct function named AVERAGE to calculate the average (or mean) of the numbers in the range specified in the function’s argument. In this function, maximum of 255 arguments can be given (numbers / cell references/ ranges/ arrays or constants). Syntax: = AVERAGE(Num1, [Num2], ...) Here Num1 [Required]: Provide range, cell references, or the first number for calculating the average.Num2, ... [Optional]: Provide additional numbers or range of cell references for calculating the average. Num1 [Required]: Provide range, cell references, or the first number for calculating the average. Num2, ... [Optional]: Provide additional numbers or range of cell references for calculating the average. Example: AVERAGE(C1:C5) This will give the average of numeric values in the range C1 to C5. Note: In the above-mentioned methods, any criteria for calculating the average cannot be mentioned. For this excel provide another function called AVERAGEIF. Excel provides a direct function named AVERAGEIF to calculate the average (or mean) of the numbers in the range specified that meets particular criteria specified in the function’s argument. Syntax: = AVERAGEIF(Range_Cells_For_Criteria, Criteria, [Range_Cells_For_Average]) Here Range_Cells_For_Criteria [Required]: Give the range of cells on which criteria are to be tested.Criteria [Required]: This is the condition on which to decide the cells to average. The criteria can be given in the form of an expression(logical), text-value or number, or reference to a cell, e.g. 100 or “>100” or “Apple” or A7.Range_Cells_For_Average [Optional]: Specify the cells on which the average needs to be calculated. Range_Cells_For_Criteria is used to find the average if it is not included. Range_Cells_For_Criteria [Required]: Give the range of cells on which criteria are to be tested. Criteria [Required]: This is the condition on which to decide the cells to average. The criteria can be given in the form of an expression(logical), text-value or number, or reference to a cell, e.g. 100 or “>100” or “Apple” or A7. Range_Cells_For_Average [Optional]: Specify the cells on which the average needs to be calculated. Range_Cells_For_Criteria is used to find the average if it is not included. Note: An empty cell in average_range is ignored here.Cells in the range that contain TRUE or FALSE are ignored here.If the range is blank, return the #DIV0! Error value.Empty cell in the criteria is treated as 0. An empty cell in average_range is ignored here. Cells in the range that contain TRUE or FALSE are ignored here. If the range is blank, return the #DIV0! Error value. Empty cell in the criteria is treated as 0. In Excel, the text values are surrounded by double quotations (“”), but integers are not, in general. But when numbers are used in criteria(s) with a logical operator, the number and operator must also be wrapped in quotes. Examples: 1. To calculate the average of only positive numbers excluding 0 in the range A2 to A6= AVERAGEIF(A2:A6,”>0′′) is correct.= AVERAGEIF(A2:A6,>0) is incorrect as the logical operator should be included in double-quotes. 2. To get the average age (AGE is in column C) of the employees living in the city having id = 1 (CityId is in column D)= AVERAGEIF(D2:D10, “=1”, C2:C10) is correct= AVERAGEIF(D2:D10, 1, C2:C10) is also correct as here also D2 to D10 cells will be checked for value 1. 3. To get the average age (AGE is in column C) of the employees living in a city named Mumbai (City is in column B)= AVERAGEIF(B2:B10, “Mumbai”, C2:C10) is correct = AVERAGEIF(B2:B10, Mumbai, C2:C10) is incorrect as text should be included in double-quotes. Example 1: To calculate the average of only positive numbers excluding 0 in the range A2 to A6. Solution: In this example, a single criterion is given- “>0′′. So all the numbers in the range that are greater than 0 come in the criteria. The average will be calculated as (12.7 + 87.2 + 100) / 3 = 66.66666667 So, the average formula for the above example is AVERAGEIF(A2:A6,">0") Example 2: To get the average age (AGE is in column C) of the employees living in a city named Mumbai (City is in column B). Solution: Let’s break the example into different parts so that the individual parts can then be substituted in the AVERAGEIF function Criteria: “Mumbai”. Cells for criteria: B2 to B6. Cells for average: C2 to C6 that meet the criteria. The average age of the employees living in Mumbai = (65 + 45) /2 = 55 So, the average formula for this example is AVERAGEIF(B2:B6,"Mumbai",C2:C6) Excel provides a direct function named AVERAGEIFS to calculate the average (or mean) of the numbers in the range specified that meets multiple criteria specified in the function’s argument. Syntax: AVERAGEIFS(RangeForAverage,RangeForCriteria1,Criteria1, [RangeForCriteria2, Criteria2],..) Here RangeForAverage [Required]: Provide the cell range on which average needs to be computed.RangeForCriteria1: Range on which criteria1 is applied.Criteria1: The first criteria to apply on the RangeForCriteria1. RangeForAverage [Required]: Provide the cell range on which average needs to be computed. RangeForCriteria1: Range on which criteria1 is applied. Criteria1: The first criteria to apply on the RangeForCriteria1. Note: All ranges are required along with their criteria.Criteria1 is required, the rest are optional. All ranges are required along with their criteria. Criteria1 is required, the rest are optional. Example 1: To calculate the average age of the employees living in Mumbai whose ages are > 50. Solution: The following criteria are used to solve the problem RangeForAverage: C2 to C8. Criteria 1: “Mumbai”. RangeForCriteria1: B2 to B8. Criteria 2: “>50”. RangeForCriteria1: C2 to C8. Here, the average is calculated on basis of two criteria- Employees living in Mumbai and employees whose Age > 50 AVERAGEIFS(C2:C8,B2:B8,"Mumbai",C2:C8,">50") Example 2: To get the average price of the product with Category ID 1 and having a Price greater than Rs 500/-. Solution: The following criteria will be used for the AVERAGEIF function RangeForAverage: C2 to C11. Criteria 1: “=1”. RangeForCriteria1: B2 to B11. Criteria 2: “>500”. RangeForCriteria2: C2 to C11. Here, the average is calculated on the basis of two criteria- Product having Category ID 1 and Price greater than 500 AVERAGEIFSC2:C11,B2:B11,"=1",C2:C11,">500") The concatenation of text can be used to use the value from another cell. Concatenation is the process of connecting two or more values to form a text string. There are two ways for concatenation of the strings in Excel Logical & operator can be used.Concatenate function in Excel for concatenation of two texts. Logical & operator can be used. Concatenate function in Excel for concatenation of two texts. Example: To get average marks (marks are in column B) of passed students having minimum passing marks value contained in cell D2. Solution: In this example, the logical & operator will be used to concatenate the two conditions for finding the result Marks greater than 0. Minimum passing marks i.e. 10. Here, D2 has a value of 10, so the minimum pass marks are 10, the following criteria will be used- “>=”&D2. This will concat “>=” & value contained in cell D2, i.e. 10. After concatenation, the criteria will become “>=10”. So, in this example RangeForAverage- B2 to B12. Criteria1- Marks greater than 0. RangeForCriteria1- B2 to B12. The following formula will be used to calculate the average =AVERAGEIFS(B2:B12,B2:B12,">=0"&D2) Excel provides wildcard characters that can be used in the criteria. Some wild cards are * (asterisk): This symbol can be used to represent any number of characters.? (question mark): This symbol can be used to represent a single character.~ (tilde): This symbol is used before the above two wild cards and also tilde itself so that when there is a need to match a text containing * or? Or ~, Excel does not treat them as a wildcard. To treat them as normal characters in Excel criteria, the tilde is used before them. * (asterisk): This symbol can be used to represent any number of characters. ? (question mark): This symbol can be used to represent a single character. ~ (tilde): This symbol is used before the above two wild cards and also tilde itself so that when there is a need to match a text containing * or? Or ~, Excel does not treat them as a wildcard. To treat them as normal characters in Excel criteria, the tilde is used before them. Examples: There are the product names in column A (From A1 to A10) and their respective price in column C. AVERAGEIFS(C2:C11, A:A11, “*a*”): To find the average price of all the products who have character ‘a’ anywhere in their name.AVERAGEIFS(C2:C11, A:A11, “?a*”): To find the average price of all the products that have the second character ‘a’ in their name.AVERAGEIFS(C2:C11, A:A11, “?aree”): To find the average price of all the products that have a single character before ‘aree’ in their name.AVERAGEIFS(C2:C11, A:A11, ” ~*Saree “): To find the average price of all the products that have a name is *Saree. AVERAGEIFS(C2:C11, A:A11, “*a*”): To find the average price of all the products who have character ‘a’ anywhere in their name. AVERAGEIFS(C2:C11, A:A11, “?a*”): To find the average price of all the products that have the second character ‘a’ in their name. AVERAGEIFS(C2:C11, A:A11, “?aree”): To find the average price of all the products that have a single character before ‘aree’ in their name. AVERAGEIFS(C2:C11, A:A11, ” ~*Saree “): To find the average price of all the products that have a name is *Saree. Example: To find the average price of all the products that have character ‘a’ anywhere in their name. Solution: In this example Product Saree, Nail Paint, Jeans, and Lehenga contains the character ‘a’ in them.The average prices for these products will be Product Saree, Nail Paint, Jeans, and Lehenga contains the character ‘a’ in them. The average prices for these products will be = (1200+ 100+ 1000+ 5000)/4 = 7300/4 = 1825 So, the complete formula for calculating the average is as follows AVERAGEIFS(C2:C11,A2:A11,"*a") Using AVERAGE, it is possible to find average without any criteria. Using AVERAGEIF, the average can be calculated with particular criteria and using AVERAGEIFS, the average can be computed with multiple criteria(s). Excel-functions Picked Excel Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Delete Blank Columns in Excel? How to Get Length of Array in Excel VBA? How to Normalize Data in Excel? How to Find the Last Used Row and Column in Excel VBA? How to Use Solver in Excel? Introduction to Excel Spreadsheet How to make a 3 Axis Graph using Excel? Macros in Excel How to Show Percentages in Stacked Column Chart in Excel? How to Extract the Last Word From a Cell in Excel?
[ { "code": null, "e": 28, "s": 0, "text": "\n23 Jun, 2021" }, { "code": null, "e": 311, "s": 28, "text": "Average a number expressing the central or typical value in a set of data, in particular the mode, median, or (most commonly) the mean, which is calculated by dividing the sum of the values in the set by their number. The basic formula for the average of n numbers x1,x2,......xn is" }, { "code": null, "e": 339, "s": 311, "text": "A = (x1 + x2 ........xn)/ n" }, { "code": null, "e": 475, "s": 339, "text": "In Excel, there is an average function for this purpose, but it can be calculated manually also using SUM and COUNT functions like this" }, { "code": null, "e": 502, "s": 475, "text": "= SUM(D1:D5)/COUNT(D1:D5) " }, { "code": null, "e": 507, "s": 502, "text": "Here" }, { "code": null, "e": 695, "s": 507, "text": "SUM: This function is used to find the sum of values in the required range of cells.COUNT: This function is used to get the count of the required range of cells containing numeric values." }, { "code": null, "e": 780, "s": 695, "text": "SUM: This function is used to find the sum of values in the required range of cells." }, { "code": null, "e": 884, "s": 780, "text": "COUNT: This function is used to get the count of the required range of cells containing numeric values." }, { "code": null, "e": 1146, "s": 884, "text": "Excel provides a direct function named AVERAGE to calculate the average (or mean) of the numbers in the range specified in the function’s argument. In this function, maximum of 255 arguments can be given (numbers / cell references/ ranges/ arrays or constants)." }, { "code": null, "e": 1154, "s": 1146, "text": "Syntax:" }, { "code": null, "e": 1183, "s": 1154, "text": "= AVERAGE(Num1, [Num2], ...)" }, { "code": null, "e": 1188, "s": 1183, "text": "Here" }, { "code": null, "e": 1391, "s": 1188, "text": "Num1 [Required]: Provide range, cell references, or the first number for calculating the average.Num2, ... [Optional]: Provide additional numbers or range of cell references for calculating the average." }, { "code": null, "e": 1489, "s": 1391, "text": "Num1 [Required]: Provide range, cell references, or the first number for calculating the average." }, { "code": null, "e": 1595, "s": 1489, "text": "Num2, ... [Optional]: Provide additional numbers or range of cell references for calculating the average." }, { "code": null, "e": 1604, "s": 1595, "text": "Example:" }, { "code": null, "e": 1620, "s": 1604, "text": "AVERAGE(C1:C5) " }, { "code": null, "e": 1688, "s": 1620, "text": "This will give the average of numeric values in the range C1 to C5." }, { "code": null, "e": 1846, "s": 1688, "text": "Note: In the above-mentioned methods, any criteria for calculating the average cannot be mentioned. For this excel provide another function called AVERAGEIF." }, { "code": null, "e": 2037, "s": 1846, "text": "Excel provides a direct function named AVERAGEIF to calculate the average (or mean) of the numbers in the range specified that meets particular criteria specified in the function’s argument." }, { "code": null, "e": 2045, "s": 2037, "text": "Syntax:" }, { "code": null, "e": 2120, "s": 2045, "text": "= AVERAGEIF(Range_Cells_For_Criteria, Criteria, [Range_Cells_For_Average])" }, { "code": null, "e": 2125, "s": 2120, "text": "Here" }, { "code": null, "e": 2627, "s": 2125, "text": "Range_Cells_For_Criteria [Required]: Give the range of cells on which criteria are to be tested.Criteria [Required]: This is the condition on which to decide the cells to average. The criteria can be given in the form of an expression(logical), text-value or number, or reference to a cell, e.g. 100 or “>100” or “Apple” or A7.Range_Cells_For_Average [Optional]: Specify the cells on which the average needs to be calculated. Range_Cells_For_Criteria is used to find the average if it is not included." }, { "code": null, "e": 2724, "s": 2627, "text": "Range_Cells_For_Criteria [Required]: Give the range of cells on which criteria are to be tested." }, { "code": null, "e": 2956, "s": 2724, "text": "Criteria [Required]: This is the condition on which to decide the cells to average. The criteria can be given in the form of an expression(logical), text-value or number, or reference to a cell, e.g. 100 or “>100” or “Apple” or A7." }, { "code": null, "e": 3131, "s": 2956, "text": "Range_Cells_For_Average [Optional]: Specify the cells on which the average needs to be calculated. Range_Cells_For_Criteria is used to find the average if it is not included." }, { "code": null, "e": 3137, "s": 3131, "text": "Note:" }, { "code": null, "e": 3344, "s": 3137, "text": "An empty cell in average_range is ignored here.Cells in the range that contain TRUE or FALSE are ignored here.If the range is blank, return the #DIV0! Error value.Empty cell in the criteria is treated as 0." }, { "code": null, "e": 3392, "s": 3344, "text": "An empty cell in average_range is ignored here." }, { "code": null, "e": 3456, "s": 3392, "text": "Cells in the range that contain TRUE or FALSE are ignored here." }, { "code": null, "e": 3510, "s": 3456, "text": "If the range is blank, return the #DIV0! Error value." }, { "code": null, "e": 3554, "s": 3510, "text": "Empty cell in the criteria is treated as 0." }, { "code": null, "e": 3779, "s": 3554, "text": "In Excel, the text values are surrounded by double quotations (“”), but integers are not, in general. But when numbers are used in criteria(s) with a logical operator, the number and operator must also be wrapped in quotes. " }, { "code": null, "e": 3789, "s": 3779, "text": "Examples:" }, { "code": null, "e": 4007, "s": 3789, "text": "1. To calculate the average of only positive numbers excluding 0 in the range A2 to A6= AVERAGEIF(A2:A6,”>0′′) is correct.= AVERAGEIF(A2:A6,>0) is incorrect as the logical operator should be included in double-quotes." }, { "code": null, "e": 4276, "s": 4007, "text": "2. To get the average age (AGE is in column C) of the employees living in the city having id = 1 (CityId is in column D)= AVERAGEIF(D2:D10, “=1”, C2:C10) is correct= AVERAGEIF(D2:D10, 1, C2:C10) is also correct as here also D2 to D10 cells will be checked for value 1." }, { "code": null, "e": 4534, "s": 4276, "text": "3. To get the average age (AGE is in column C) of the employees living in a city named Mumbai (City is in column B)= AVERAGEIF(B2:B10, “Mumbai”, C2:C10) is correct = AVERAGEIF(B2:B10, Mumbai, C2:C10) is incorrect as text should be included in double-quotes." }, { "code": null, "e": 4630, "s": 4534, "text": "Example 1: To calculate the average of only positive numbers excluding 0 in the range A2 to A6." }, { "code": null, "e": 4805, "s": 4630, "text": "Solution: In this example, a single criterion is given- “>0′′. So all the numbers in the range that are greater than 0 come in the criteria. The average will be calculated as" }, { "code": null, "e": 4843, "s": 4805, "text": "(12.7 + 87.2 + 100) / 3 = 66.66666667" }, { "code": null, "e": 4892, "s": 4843, "text": "So, the average formula for the above example is" }, { "code": null, "e": 4914, "s": 4892, "text": "AVERAGEIF(A2:A6,\">0\")" }, { "code": null, "e": 5039, "s": 4914, "text": "Example 2: To get the average age (AGE is in column C) of the employees living in a city named Mumbai (City is in column B)." }, { "code": null, "e": 5173, "s": 5039, "text": "Solution: Let’s break the example into different parts so that the individual parts can then be substituted in the AVERAGEIF function" }, { "code": null, "e": 5193, "s": 5173, "text": "Criteria: “Mumbai”." }, { "code": null, "e": 5223, "s": 5193, "text": "Cells for criteria: B2 to B6." }, { "code": null, "e": 5275, "s": 5223, "text": "Cells for average: C2 to C6 that meet the criteria." }, { "code": null, "e": 5325, "s": 5275, "text": "The average age of the employees living in Mumbai" }, { "code": null, "e": 5345, "s": 5325, "text": "= (65 + 45) /2 = 55" }, { "code": null, "e": 5389, "s": 5345, "text": "So, the average formula for this example is" }, { "code": null, "e": 5421, "s": 5389, "text": "AVERAGEIF(B2:B6,\"Mumbai\",C2:C6)" }, { "code": null, "e": 5611, "s": 5421, "text": "Excel provides a direct function named AVERAGEIFS to calculate the average (or mean) of the numbers in the range specified that meets multiple criteria specified in the function’s argument." }, { "code": null, "e": 5619, "s": 5611, "text": "Syntax:" }, { "code": null, "e": 5721, "s": 5619, "text": "AVERAGEIFS(RangeForAverage,RangeForCriteria1,Criteria1,\n [RangeForCriteria2, Criteria2],..)" }, { "code": null, "e": 5726, "s": 5721, "text": "Here" }, { "code": null, "e": 5935, "s": 5726, "text": "RangeForAverage [Required]: Provide the cell range on which average needs to be computed.RangeForCriteria1: Range on which criteria1 is applied.Criteria1: The first criteria to apply on the RangeForCriteria1." }, { "code": null, "e": 6025, "s": 5935, "text": "RangeForAverage [Required]: Provide the cell range on which average needs to be computed." }, { "code": null, "e": 6081, "s": 6025, "text": "RangeForCriteria1: Range on which criteria1 is applied." }, { "code": null, "e": 6146, "s": 6081, "text": "Criteria1: The first criteria to apply on the RangeForCriteria1." }, { "code": null, "e": 6152, "s": 6146, "text": "Note:" }, { "code": null, "e": 6248, "s": 6152, "text": "All ranges are required along with their criteria.Criteria1 is required, the rest are optional." }, { "code": null, "e": 6299, "s": 6248, "text": "All ranges are required along with their criteria." }, { "code": null, "e": 6345, "s": 6299, "text": "Criteria1 is required, the rest are optional." }, { "code": null, "e": 6440, "s": 6345, "text": "Example 1: To calculate the average age of the employees living in Mumbai whose ages are > 50." }, { "code": null, "e": 6503, "s": 6440, "text": "Solution: The following criteria are used to solve the problem" }, { "code": null, "e": 6530, "s": 6503, "text": "RangeForAverage: C2 to C8." }, { "code": null, "e": 6552, "s": 6530, "text": "Criteria 1: “Mumbai”." }, { "code": null, "e": 6581, "s": 6552, "text": "RangeForCriteria1: B2 to B8." }, { "code": null, "e": 6600, "s": 6581, "text": "Criteria 2: “>50”." }, { "code": null, "e": 6629, "s": 6600, "text": "RangeForCriteria1: C2 to C8." }, { "code": null, "e": 6743, "s": 6629, "text": "Here, the average is calculated on basis of two criteria- Employees living in Mumbai and employees whose Age > 50" }, { "code": null, "e": 6788, "s": 6743, "text": "AVERAGEIFS(C2:C8,B2:B8,\"Mumbai\",C2:C8,\">50\")" }, { "code": null, "e": 6900, "s": 6788, "text": "Example 2: To get the average price of the product with Category ID 1 and having a Price greater than Rs 500/-." }, { "code": null, "e": 6973, "s": 6900, "text": "Solution: The following criteria will be used for the AVERAGEIF function" }, { "code": null, "e": 7001, "s": 6973, "text": "RangeForAverage: C2 to C11." }, { "code": null, "e": 7019, "s": 7001, "text": "Criteria 1: “=1”." }, { "code": null, "e": 7049, "s": 7019, "text": "RangeForCriteria1: B2 to B11." }, { "code": null, "e": 7069, "s": 7049, "text": "Criteria 2: “>500”." }, { "code": null, "e": 7099, "s": 7069, "text": "RangeForCriteria2: C2 to C11." }, { "code": null, "e": 7217, "s": 7099, "text": "Here, the average is calculated on the basis of two criteria- Product having Category ID 1 and Price greater than 500" }, { "code": null, "e": 7261, "s": 7217, "text": "AVERAGEIFSC2:C11,B2:B11,\"=1\",C2:C11,\">500\")" }, { "code": null, "e": 7481, "s": 7261, "text": "The concatenation of text can be used to use the value from another cell. Concatenation is the process of connecting two or more values to form a text string. There are two ways for concatenation of the strings in Excel" }, { "code": null, "e": 7574, "s": 7481, "text": "Logical & operator can be used.Concatenate function in Excel for concatenation of two texts." }, { "code": null, "e": 7606, "s": 7574, "text": "Logical & operator can be used." }, { "code": null, "e": 7668, "s": 7606, "text": "Concatenate function in Excel for concatenation of two texts." }, { "code": null, "e": 7798, "s": 7668, "text": "Example: To get average marks (marks are in column B) of passed students having minimum passing marks value contained in cell D2." }, { "code": null, "e": 7918, "s": 7798, "text": "Solution: In this example, the logical & operator will be used to concatenate the two conditions for finding the result" }, { "code": null, "e": 7940, "s": 7918, "text": "Marks greater than 0." }, { "code": null, "e": 7971, "s": 7940, "text": "Minimum passing marks i.e. 10." }, { "code": null, "e": 8194, "s": 7971, "text": "Here, D2 has a value of 10, so the minimum pass marks are 10, the following criteria will be used- “>=”&D2. This will concat “>=” & value contained in cell D2, i.e. 10. After concatenation, the criteria will become “>=10”." }, { "code": null, "e": 8214, "s": 8194, "text": "So, in this example" }, { "code": null, "e": 8242, "s": 8214, "text": "RangeForAverage- B2 to B12." }, { "code": null, "e": 8275, "s": 8242, "text": "Criteria1- Marks greater than 0." }, { "code": null, "e": 8305, "s": 8275, "text": "RangeForCriteria1- B2 to B12." }, { "code": null, "e": 8365, "s": 8305, "text": "The following formula will be used to calculate the average" }, { "code": null, "e": 8401, "s": 8365, "text": "=AVERAGEIFS(B2:B12,B2:B12,\">=0\"&D2)" }, { "code": null, "e": 8490, "s": 8401, "text": "Excel provides wildcard characters that can be used in the criteria. Some wild cards are" }, { "code": null, "e": 8920, "s": 8490, "text": "* (asterisk): This symbol can be used to represent any number of characters.? (question mark): This symbol can be used to represent a single character.~ (tilde): This symbol is used before the above two wild cards and also tilde itself so that when there is a need to match a text containing * or? Or ~, Excel does not treat them as a wildcard. To treat them as normal characters in Excel criteria, the tilde is used before them." }, { "code": null, "e": 8997, "s": 8920, "text": "* (asterisk): This symbol can be used to represent any number of characters." }, { "code": null, "e": 9073, "s": 8997, "text": "? (question mark): This symbol can be used to represent a single character." }, { "code": null, "e": 9352, "s": 9073, "text": "~ (tilde): This symbol is used before the above two wild cards and also tilde itself so that when there is a need to match a text containing * or? Or ~, Excel does not treat them as a wildcard. To treat them as normal characters in Excel criteria, the tilde is used before them." }, { "code": null, "e": 9459, "s": 9352, "text": "Examples: There are the product names in column A (From A1 to A10) and their respective price in column C." }, { "code": null, "e": 9967, "s": 9459, "text": "AVERAGEIFS(C2:C11, A:A11, “*a*”): To find the average price of all the products who have character ‘a’ anywhere in their name.AVERAGEIFS(C2:C11, A:A11, “?a*”): To find the average price of all the products that have the second character ‘a’ in their name.AVERAGEIFS(C2:C11, A:A11, “?aree”): To find the average price of all the products that have a single character before ‘aree’ in their name.AVERAGEIFS(C2:C11, A:A11, ” ~*Saree “): To find the average price of all the products that have a name is *Saree." }, { "code": null, "e": 10094, "s": 9967, "text": "AVERAGEIFS(C2:C11, A:A11, “*a*”): To find the average price of all the products who have character ‘a’ anywhere in their name." }, { "code": null, "e": 10224, "s": 10094, "text": "AVERAGEIFS(C2:C11, A:A11, “?a*”): To find the average price of all the products that have the second character ‘a’ in their name." }, { "code": null, "e": 10364, "s": 10224, "text": "AVERAGEIFS(C2:C11, A:A11, “?aree”): To find the average price of all the products that have a single character before ‘aree’ in their name." }, { "code": null, "e": 10478, "s": 10364, "text": "AVERAGEIFS(C2:C11, A:A11, ” ~*Saree “): To find the average price of all the products that have a name is *Saree." }, { "code": null, "e": 10581, "s": 10478, "text": "Example: To find the average price of all the products that have character ‘a’ anywhere in their name." }, { "code": null, "e": 10607, "s": 10581, "text": "Solution: In this example" }, { "code": null, "e": 10734, "s": 10607, "text": "Product Saree, Nail Paint, Jeans, and Lehenga contains the character ‘a’ in them.The average prices for these products will be" }, { "code": null, "e": 10816, "s": 10734, "text": "Product Saree, Nail Paint, Jeans, and Lehenga contains the character ‘a’ in them." }, { "code": null, "e": 10862, "s": 10816, "text": "The average prices for these products will be" }, { "code": null, "e": 10907, "s": 10862, "text": "= (1200+ 100+ 1000+ 5000)/4 = 7300/4 = 1825 " }, { "code": null, "e": 10974, "s": 10907, "text": "So, the complete formula for calculating the average is as follows" }, { "code": null, "e": 11005, "s": 10974, "text": "AVERAGEIFS(C2:C11,A2:A11,\"*a\")" }, { "code": null, "e": 11222, "s": 11005, "text": "Using AVERAGE, it is possible to find average without any criteria. Using AVERAGEIF, the average can be calculated with particular criteria and using AVERAGEIFS, the average can be computed with multiple criteria(s)." }, { "code": null, "e": 11238, "s": 11222, "text": "Excel-functions" }, { "code": null, "e": 11245, "s": 11238, "text": "Picked" }, { "code": null, "e": 11251, "s": 11245, "text": "Excel" }, { "code": null, "e": 11349, "s": 11251, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 11387, "s": 11349, "text": "How to Delete Blank Columns in Excel?" }, { "code": null, "e": 11428, "s": 11387, "text": "How to Get Length of Array in Excel VBA?" }, { "code": null, "e": 11460, "s": 11428, "text": "How to Normalize Data in Excel?" }, { "code": null, "e": 11515, "s": 11460, "text": "How to Find the Last Used Row and Column in Excel VBA?" }, { "code": null, "e": 11543, "s": 11515, "text": "How to Use Solver in Excel?" }, { "code": null, "e": 11577, "s": 11543, "text": "Introduction to Excel Spreadsheet" }, { "code": null, "e": 11617, "s": 11577, "text": "How to make a 3 Axis Graph using Excel?" }, { "code": null, "e": 11633, "s": 11617, "text": "Macros in Excel" }, { "code": null, "e": 11691, "s": 11633, "text": "How to Show Percentages in Stacked Column Chart in Excel?" } ]
strftime() function in C/C++
The function strftime() is used to format the time and date as a string. It is declared in “time.h” header file in C language. It returns the total number of characters copied to the string, if string fits in less than size characters otherwise, returns zero. Here is the syntax of strftime() in C language, size_t strftime(char *string, size_t size, const char *format, const struct tm *time_pointer) Here, string − Pointer to the destination array. size − Maximum number of characters to be copied. format − Some special format specifiers to represent the time in tm. time_pointer − Pointer to tm structure that contains the calendar time structure. Here is an example of strftime() in C language, Live Demo #include <stdio.h> #include <time.h> int main () { time_t tim; struct tm *detl; char buf[80]; time( &tim ); detl = localtime( &tim ); strftime(buf, 20, "%x - %I:%M%p", detl); printf("Date & time after formatting : %s", buf ); return(0); } Date & time after formatting : 10/23/18 - 10:33AM In the above program, three variables of multiple data types are declared. The function localtime() is storing the current date and time. The function strftime() is copying the string and formatting it in some special structure by using some special specifiers. detl = localtime( &tim ); strftime(buf, 20, "%x - %I:%M%p", detl);
[ { "code": null, "e": 1322, "s": 1062, "text": "The function strftime() is used to format the time and date as a string. It is declared in “time.h” header file in C language. It returns the total number of characters copied to the string, if string fits in less than size characters otherwise, returns zero." }, { "code": null, "e": 1370, "s": 1322, "text": "Here is the syntax of strftime() in C language," }, { "code": null, "e": 1464, "s": 1370, "text": "size_t strftime(char *string, size_t size, const char *format, const struct tm *time_pointer)" }, { "code": null, "e": 1470, "s": 1464, "text": "Here," }, { "code": null, "e": 1513, "s": 1470, "text": "string − Pointer to the destination array." }, { "code": null, "e": 1563, "s": 1513, "text": "size − Maximum number of characters to be copied." }, { "code": null, "e": 1632, "s": 1563, "text": "format − Some special format specifiers to represent the time in tm." }, { "code": null, "e": 1714, "s": 1632, "text": "time_pointer − Pointer to tm structure that contains the calendar time structure." }, { "code": null, "e": 1762, "s": 1714, "text": "Here is an example of strftime() in C language," }, { "code": null, "e": 1773, "s": 1762, "text": " Live Demo" }, { "code": null, "e": 2036, "s": 1773, "text": "#include <stdio.h>\n#include <time.h>\nint main () {\n time_t tim;\n struct tm *detl;\n char buf[80];\n time( &tim );\n detl = localtime( &tim );\n strftime(buf, 20, \"%x - %I:%M%p\", detl);\n printf(\"Date & time after formatting : %s\", buf );\n return(0);\n}" }, { "code": null, "e": 2086, "s": 2036, "text": "Date & time after formatting : 10/23/18 - 10:33AM" }, { "code": null, "e": 2348, "s": 2086, "text": "In the above program, three variables of multiple data types are declared. The function localtime() is storing the current date and time. The function strftime() is copying the string and formatting it in some special structure by using some special specifiers." }, { "code": null, "e": 2415, "s": 2348, "text": "detl = localtime( &tim );\nstrftime(buf, 20, \"%x - %I:%M%p\", detl);" } ]
PyQt5 - Introduction
PyQt is a GUI widgets toolkit. It is a Python interface for Qt, one of the most powerful, and popular cross-platform GUI library. PyQt was developed by RiverBank Computing Ltd. The latest version of PyQt can be downloaded from its official website − riverbankcomputing.com PyQt API is a set of modules containing a large number of classes and functions. While QtCore module contains non-GUI functionality for working with file and directory etc., QtGui module contains all the graphical controls. In addition, there are modules for working with XML (QtXml), SVG (QtSvg), and SQL (QtSql), etc. A list of frequently used modules is given below − QtCore − Core non-GUI classes used by other modules QtCore − Core non-GUI classes used by other modules QtGui − Graphical user interface components QtGui − Graphical user interface components QtMultimedia − Classes for low-level multimedia programming QtMultimedia − Classes for low-level multimedia programming QtNetwork − Classes for network programming QtNetwork − Classes for network programming QtOpenGL − OpenGL support classes QtOpenGL − OpenGL support classes QtScript − Classes for evaluating Qt Scripts QtScript − Classes for evaluating Qt Scripts QtSql − Classes for database integration using SQL QtSql − Classes for database integration using SQL QtSvg − Classes for displaying the contents of SVG files QtSvg − Classes for displaying the contents of SVG files QtWebKit − Classes for rendering and editing HTML QtWebKit − Classes for rendering and editing HTML QtXml − Classes for handling XML QtXml − Classes for handling XML QtWidgets − Classes for creating classic desktop-style UIs QtWidgets − Classes for creating classic desktop-style UIs QtDesigner − Classes for extending Qt Designer QtDesigner − Classes for extending Qt Designer PyQt is compatible with all the popular operating systems including Windows, Linux, and Mac OS. It is dual licensed, available under GPL as well as commercial license. The latest stable version is PyQt5-5.13.2. Wheels for 32-bit or 64-bit architecture are provided that are compatible with Python version 3.5 or later. The recommended way to install is using PIP utility − pip3 install PyQt5 To install development tools such as Qt Designer to support PyQt5 wheels, following is the command − pip3 install pyqt5-tools You can also build PyQt5 on Linux/macOS from the source code www.riverbankcomputing.com/static/Downloads/PyQt5 146 Lectures 22.5 hours ALAA EID Print Add Notes Bookmark this page
[ { "code": null, "e": 2236, "s": 1963, "text": "PyQt is a GUI widgets toolkit. It is a Python interface for Qt, one of the most powerful, and popular cross-platform GUI library. PyQt was developed by RiverBank Computing Ltd. The latest version of PyQt can be downloaded from its official website − riverbankcomputing.com" }, { "code": null, "e": 2556, "s": 2236, "text": "PyQt API is a set of modules containing a large number of classes and functions. While QtCore module contains non-GUI functionality for working with file and directory etc., QtGui module contains all the graphical controls. In addition, there are modules for working with XML (QtXml), SVG (QtSvg), and SQL (QtSql), etc." }, { "code": null, "e": 2607, "s": 2556, "text": "A list of frequently used modules is given below −" }, { "code": null, "e": 2659, "s": 2607, "text": "QtCore − Core non-GUI classes used by other modules" }, { "code": null, "e": 2711, "s": 2659, "text": "QtCore − Core non-GUI classes used by other modules" }, { "code": null, "e": 2755, "s": 2711, "text": "QtGui − Graphical user interface components" }, { "code": null, "e": 2799, "s": 2755, "text": "QtGui − Graphical user interface components" }, { "code": null, "e": 2859, "s": 2799, "text": "QtMultimedia − Classes for low-level multimedia programming" }, { "code": null, "e": 2919, "s": 2859, "text": "QtMultimedia − Classes for low-level multimedia programming" }, { "code": null, "e": 2963, "s": 2919, "text": "QtNetwork − Classes for network programming" }, { "code": null, "e": 3007, "s": 2963, "text": "QtNetwork − Classes for network programming" }, { "code": null, "e": 3041, "s": 3007, "text": "QtOpenGL − OpenGL support classes" }, { "code": null, "e": 3075, "s": 3041, "text": "QtOpenGL − OpenGL support classes" }, { "code": null, "e": 3120, "s": 3075, "text": "QtScript − Classes for evaluating Qt Scripts" }, { "code": null, "e": 3165, "s": 3120, "text": "QtScript − Classes for evaluating Qt Scripts" }, { "code": null, "e": 3216, "s": 3165, "text": "QtSql − Classes for database integration using SQL" }, { "code": null, "e": 3267, "s": 3216, "text": "QtSql − Classes for database integration using SQL" }, { "code": null, "e": 3324, "s": 3267, "text": "QtSvg − Classes for displaying the contents of SVG files" }, { "code": null, "e": 3381, "s": 3324, "text": "QtSvg − Classes for displaying the contents of SVG files" }, { "code": null, "e": 3431, "s": 3381, "text": "QtWebKit − Classes for rendering and editing HTML" }, { "code": null, "e": 3481, "s": 3431, "text": "QtWebKit − Classes for rendering and editing HTML" }, { "code": null, "e": 3514, "s": 3481, "text": "QtXml − Classes for handling XML" }, { "code": null, "e": 3547, "s": 3514, "text": "QtXml − Classes for handling XML" }, { "code": null, "e": 3606, "s": 3547, "text": "QtWidgets − Classes for creating classic desktop-style UIs" }, { "code": null, "e": 3665, "s": 3606, "text": "QtWidgets − Classes for creating classic desktop-style UIs" }, { "code": null, "e": 3712, "s": 3665, "text": "QtDesigner − Classes for extending Qt Designer" }, { "code": null, "e": 3759, "s": 3712, "text": "QtDesigner − Classes for extending Qt Designer" }, { "code": null, "e": 3970, "s": 3759, "text": "PyQt is compatible with all the popular operating systems including Windows, Linux, and Mac OS. It is dual licensed, available under GPL as well as commercial license. The latest stable version is PyQt5-5.13.2." }, { "code": null, "e": 4132, "s": 3970, "text": "Wheels for 32-bit or 64-bit architecture are provided that are compatible with Python version 3.5 or later. The recommended way to install is using PIP utility −" }, { "code": null, "e": 4152, "s": 4132, "text": "pip3 install PyQt5\n" }, { "code": null, "e": 4253, "s": 4152, "text": "To install development tools such as Qt Designer to support PyQt5 wheels, following is the command −" }, { "code": null, "e": 4279, "s": 4253, "text": "pip3 install pyqt5-tools\n" }, { "code": null, "e": 4390, "s": 4279, "text": "You can also build PyQt5 on Linux/macOS from the source code www.riverbankcomputing.com/static/Downloads/PyQt5" }, { "code": null, "e": 4427, "s": 4390, "text": "\n 146 Lectures \n 22.5 hours \n" }, { "code": null, "e": 4437, "s": 4427, "text": " ALAA EID" }, { "code": null, "e": 4444, "s": 4437, "text": " Print" }, { "code": null, "e": 4455, "s": 4444, "text": " Add Notes" } ]
Find right sibling of a binary tree with parent pointers - GeeksforGeeks
14 Mar, 2022 Given a binary tree with parent pointers, find the right sibling of a given node(pointer to the node will be given), if it doesn’t exist return null. Do it in O(1) space and O(n) time?Examples: 1 / \ 2 3 / \ \ 4 6 5 / \ \ 7 9 8 / \ 10 12 Input : Given above tree with parent pointer and node 10 Output : 12 Approach: The idea is to find out the first right child of the nearest ancestor which is neither the current node nor the parent of the current node, keep track of the level in those while going up. then, iterate through that node first left child, if the left is not there then, right child and if the level becomes 0, then, this is the next right sibling of the given node.In the above case, if the given node is 7, we will end up with 6 to find the right child which doesn’t have any child.In this case, we need to recursively call for the right sibling with the current level, so that we case reach 8. C++ Java Python3 C# Javascript // C program to print right sibling of a node#include <bits/stdc++.h> // A Binary Tree Nodestruct Node { int data; Node *left, *right, *parent;}; // A utility function to create a new Binary// Tree NodeNode* newNode(int item, Node* parent){ Node* temp = new Node; temp->data = item; temp->left = temp->right = NULL; temp->parent = parent; return temp;} // Method to find right siblingNode* findRightSibling(Node* node, int level){ if (node == NULL || node->parent == NULL) return NULL; // GET Parent pointer whose right child is not // a parent or itself of this node. There might // be case when parent has no right child, but, // current node is left child of the parent // (second condition is for that). while (node->parent->right == node || (node->parent->right == NULL && node->parent->left == node)) { if (node->parent == NULL || node->parent->parent == NULL) return NULL; node = node->parent; level--; } // Move to the required child, where right sibling // can be present node = node->parent->right; if (node == NULL) return NULL; // find right sibling in the given subtree(from current // node), when level will be 0 while (level < 0) { // Iterate through subtree if (node->left != NULL) node = node->left; else if (node->right != NULL) node = node->right; else // if no child are there, we cannot have right // sibling in this path break; level++; } if (level == 0) return node; // This is the case when we reach 9 node in the tree, // where we need to again recursively find the right // sibling return findRightSibling(node, level);} // Driver Program to test above functionsint main(){ Node* root = newNode(1, NULL); root->left = newNode(2, root); root->right = newNode(3, root); root->left->left = newNode(4, root->left); root->left->right = newNode(6, root->left); root->left->left->left = newNode(7, root->left->left); root->left->left->left->left = newNode(10, root->left->left->left); root->left->right->right = newNode(9, root->left->right); root->right->right = newNode(5, root->right); root->right->right->right = newNode(8, root->right->right); root->right->right->right->right = newNode(12, root->right->right->right); // passing 10 Node* res = findRightSibling(root->left->left->left->left, 0); if (res == NULL) printf("No right sibling"); else printf("%d", res->data); return 0;} // Java program to print right sibling of a nodepublic class Right_Sibling { // A Binary Tree Node static class Node { int data; Node left, right, parent; // Constructor public Node(int data, Node parent) { this.data = data; left = null; right = null; this.parent = parent; } }; // Method to find right sibling static Node findRightSibling(Node node, int level) { if (node == null || node.parent == null) return null; // GET Parent pointer whose right child is not // a parent or itself of this node. There might // be case when parent has no right child, but, // current node is left child of the parent // (second condition is for that). while (node.parent.right == node || (node.parent.right == null && node.parent.left == node)) { if (node.parent == null) return null; node = node.parent; level--; } // Move to the required child, where right sibling // can be present node = node.parent.right; // find right sibling in the given subtree(from current // node), when level will be 0 while (level < 0) { // Iterate through subtree if (node.left != null) node = node.left; else if (node.right != null) node = node.right; else // if no child are there, we cannot have right // sibling in this path break; level++; } if (level == 0) return node; // This is the case when we reach 9 node in the tree, // where we need to again recursively find the right // sibling return findRightSibling(node, level); } // Driver Program to test above functions public static void main(String args[]) { Node root = new Node(1, null); root.left = new Node(2, root); root.right = new Node(3, root); root.left.left = new Node(4, root.left); root.left.right = new Node(6, root.left); root.left.left.left = new Node(7, root.left.left); root.left.left.left.left = new Node(10, root.left.left.left); root.left.right.right = new Node(9, root.left.right); root.right.right = new Node(5, root.right); root.right.right.right = new Node(8, root.right.right); root.right.right.right.right = new Node(12, root.right.right.right); // passing 10 System.out.println(findRightSibling(root.left.left.left.left, 0).data); }}// This code is contributed by Sumit Ghosh # Python3 program to print right sibling# of a node # A class to create a new Binary# Tree Nodeclass newNode: def __init__(self, item, parent): self.data = item self.left = self.right = None self.parent = parent # Method to find right siblingdef findRightSibling(node, level): if (node == None or node.parent == None): return None # GET Parent pointer whose right child is not # a parent or itself of this node. There might # be case when parent has no right child, but, # current node is left child of the parent # (second condition is for that). while (node.parent.right == node or (node.parent.right == None and node.parent.left == node)): if (node.parent == None): return None node = node.parent level -= 1 # Move to the required child, where # right sibling can be present node = node.parent.right # find right sibling in the given subtree # (from current node), when level will be 0 while (level < 0): # Iterate through subtree if (node.left != None): node = node.left else if (node.right != None): node = node.right else: # if no child are there, we cannot # have right sibling in this path break level += 1 if (level == 0): return node # This is the case when we reach 9 node # in the tree, where we need to again # recursively find the right sibling return findRightSibling(node, level) # Driver Codeif __name__ == '__main__': root = newNode(1, None) root.left = newNode(2, root) root.right = newNode(3, root) root.left.left = newNode(4, root.left) root.left.right = newNode(6, root.left) root.left.left.left = newNode(7, root.left.left) root.left.left.left.left = newNode(10, root.left.left.left) root.left.right.right = newNode(9, root.left.right) root.right.right = newNode(5, root.right) root.right.right.right = newNode(8, root.right.right) root.right.right.right.right = newNode(12, root.right.right.right) # passing 10 res = findRightSibling(root.left.left.left.left, 0) if (res == None): print("No right sibling") else: print(res.data) # This code is contributed by PranchalK using System; // C# program to print right sibling of a nodepublic class Right_Sibling { // A Binary Tree Node public class Node { public int data; public Node left, right, parent; // Constructor public Node(int data, Node parent) { this.data = data; left = null; right = null; this.parent = parent; } } // Method to find right sibling public static Node findRightSibling(Node node, int level) { if (node == null || node.parent == null) { return null; } // GET Parent pointer whose right child is not // a parent or itself of this node. There might // be case when parent has no right child, but, // current node is left child of the parent // (second condition is for that). while (node.parent.right == node || (node.parent.right == null && node.parent.left == node)) { if (node.parent == null || node.parent.parent == null) { return null; } node = node.parent; level--; } // Move to the required child, where right sibling // can be present node = node.parent.right; // find right sibling in the given subtree(from current // node), when level will be 0 while (level < 0) { // Iterate through subtree if (node.left != null) { node = node.left; } else if (node.right != null) { node = node.right; } else { // if no child are there, we cannot have right // sibling in this path break; } level++; } if (level == 0) { return node; } // This is the case when we reach 9 node in the tree, // where we need to again recursively find the right // sibling return findRightSibling(node, level); } // Driver Program to test above functions public static void Main(string[] args) { Node root = new Node(1, null); root.left = new Node(2, root); root.right = new Node(3, root); root.left.left = new Node(4, root.left); root.left.right = new Node(6, root.left); root.left.left.left = new Node(7, root.left.left); root.left.left.left.left = new Node(10, root.left.left.left); root.left.right.right = new Node(9, root.left.right); root.right.right = new Node(5, root.right); root.right.right.right = new Node(8, root.right.right); root.right.right.right.right = new Node(12, root.right.right.right); // passing 10 Console.WriteLine(findRightSibling(root.left.left.left.left, 0).data); }} // This code is contributed by Shrikant13 <script> // Javascript program to print right sibling of a node // A Binary Tree Node class Node { constructor(data, parent) { this.left = null; this.right = null; this.data = data; this.parent = parent; } } // Method to find right sibling function findRightSibling(node, level) { if (node == null || node.parent == null) return null; // GET Parent pointer whose right child is not // a parent or itself of this node. There might // be case when parent has no right child, but, // current node is left child of the parent // (second condition is for that). while (node.parent.right == node || (node.parent.right == null && node.parent.left == node)) { if (node.parent == null) return null; node = node.parent; level--; } // Move to the required child, where right sibling // can be present node = node.parent.right; // find right sibling in the given subtree(from current // node), when level will be 0 while (level < 0) { // Iterate through subtree if (node.left != null) node = node.left; else if (node.right != null) node = node.right; else // if no child are there, we cannot have right // sibling in this path break; level++; } if (level == 0) return node; // This is the case when we reach 9 node in the tree, // where we need to again recursively find the right // sibling return findRightSibling(node, level); } let root = new Node(1, null); root.left = new Node(2, root); root.right = new Node(3, root); root.left.left = new Node(4, root.left); root.left.right = new Node(6, root.left); root.left.left.left = new Node(7, root.left.left); root.left.left.left.left = new Node(10, root.left.left.left); root.left.right.right = new Node(9, root.left.right); root.right.right = new Node(5, root.right); root.right.right.right = new Node(8, root.right.right); root.right.right.right.right = new Node(12, root.right.right.right); // passing 10 document.write(findRightSibling(root.left.left.left.left, 0).data); // This code is contributed by divyesh072019.</script> Output: 12 Time Complexity: O(N) Auxiliary Space: O(1) This article is contributed by Krishna 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 [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. shrikanth13 PranchalKatiyar AbdulG rohitsingh07052 divyesh072019 surinderdawra388 Tree Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Tree Traversals (Inorder, Preorder and Postorder) Binary Tree | Set 1 (Introduction) Level Order Binary Tree Traversal AVL Tree | Set 1 (Insertion) Inorder Tree Traversal without Recursion Binary Tree | Set 3 (Types of Binary Tree) Write a Program to Find the Maximum Depth or Height of a Tree Binary Tree | Set 2 (Properties) A program to check if a binary tree is BST or not
[ { "code": null, "e": 35846, "s": 35818, "text": "\n14 Mar, 2022" }, { "code": null, "e": 36041, "s": 35846, "text": "Given a binary tree with parent pointers, find the right sibling of a given node(pointer to the node will be given), if it doesn’t exist return null. Do it in O(1) space and O(n) time?Examples: " }, { "code": null, "e": 36276, "s": 36041, "text": " 1\n / \\\n 2 3\n / \\ \\\n 4 6 5\n / \\ \\\n 7 9 8\n / \\\n 10 12\nInput : Given above tree with parent pointer and node 10\nOutput : 12 " }, { "code": null, "e": 36883, "s": 36276, "text": "Approach: The idea is to find out the first right child of the nearest ancestor which is neither the current node nor the parent of the current node, keep track of the level in those while going up. then, iterate through that node first left child, if the left is not there then, right child and if the level becomes 0, then, this is the next right sibling of the given node.In the above case, if the given node is 7, we will end up with 6 to find the right child which doesn’t have any child.In this case, we need to recursively call for the right sibling with the current level, so that we case reach 8. " }, { "code": null, "e": 36887, "s": 36883, "text": "C++" }, { "code": null, "e": 36892, "s": 36887, "text": "Java" }, { "code": null, "e": 36900, "s": 36892, "text": "Python3" }, { "code": null, "e": 36903, "s": 36900, "text": "C#" }, { "code": null, "e": 36914, "s": 36903, "text": "Javascript" }, { "code": "// C program to print right sibling of a node#include <bits/stdc++.h> // A Binary Tree Nodestruct Node { int data; Node *left, *right, *parent;}; // A utility function to create a new Binary// Tree NodeNode* newNode(int item, Node* parent){ Node* temp = new Node; temp->data = item; temp->left = temp->right = NULL; temp->parent = parent; return temp;} // Method to find right siblingNode* findRightSibling(Node* node, int level){ if (node == NULL || node->parent == NULL) return NULL; // GET Parent pointer whose right child is not // a parent or itself of this node. There might // be case when parent has no right child, but, // current node is left child of the parent // (second condition is for that). while (node->parent->right == node || (node->parent->right == NULL && node->parent->left == node)) { if (node->parent == NULL || node->parent->parent == NULL) return NULL; node = node->parent; level--; } // Move to the required child, where right sibling // can be present node = node->parent->right; if (node == NULL) return NULL; // find right sibling in the given subtree(from current // node), when level will be 0 while (level < 0) { // Iterate through subtree if (node->left != NULL) node = node->left; else if (node->right != NULL) node = node->right; else // if no child are there, we cannot have right // sibling in this path break; level++; } if (level == 0) return node; // This is the case when we reach 9 node in the tree, // where we need to again recursively find the right // sibling return findRightSibling(node, level);} // Driver Program to test above functionsint main(){ Node* root = newNode(1, NULL); root->left = newNode(2, root); root->right = newNode(3, root); root->left->left = newNode(4, root->left); root->left->right = newNode(6, root->left); root->left->left->left = newNode(7, root->left->left); root->left->left->left->left = newNode(10, root->left->left->left); root->left->right->right = newNode(9, root->left->right); root->right->right = newNode(5, root->right); root->right->right->right = newNode(8, root->right->right); root->right->right->right->right = newNode(12, root->right->right->right); // passing 10 Node* res = findRightSibling(root->left->left->left->left, 0); if (res == NULL) printf(\"No right sibling\"); else printf(\"%d\", res->data); return 0;}", "e": 39555, "s": 36914, "text": null }, { "code": "// Java program to print right sibling of a nodepublic class Right_Sibling { // A Binary Tree Node static class Node { int data; Node left, right, parent; // Constructor public Node(int data, Node parent) { this.data = data; left = null; right = null; this.parent = parent; } }; // Method to find right sibling static Node findRightSibling(Node node, int level) { if (node == null || node.parent == null) return null; // GET Parent pointer whose right child is not // a parent or itself of this node. There might // be case when parent has no right child, but, // current node is left child of the parent // (second condition is for that). while (node.parent.right == node || (node.parent.right == null && node.parent.left == node)) { if (node.parent == null) return null; node = node.parent; level--; } // Move to the required child, where right sibling // can be present node = node.parent.right; // find right sibling in the given subtree(from current // node), when level will be 0 while (level < 0) { // Iterate through subtree if (node.left != null) node = node.left; else if (node.right != null) node = node.right; else // if no child are there, we cannot have right // sibling in this path break; level++; } if (level == 0) return node; // This is the case when we reach 9 node in the tree, // where we need to again recursively find the right // sibling return findRightSibling(node, level); } // Driver Program to test above functions public static void main(String args[]) { Node root = new Node(1, null); root.left = new Node(2, root); root.right = new Node(3, root); root.left.left = new Node(4, root.left); root.left.right = new Node(6, root.left); root.left.left.left = new Node(7, root.left.left); root.left.left.left.left = new Node(10, root.left.left.left); root.left.right.right = new Node(9, root.left.right); root.right.right = new Node(5, root.right); root.right.right.right = new Node(8, root.right.right); root.right.right.right.right = new Node(12, root.right.right.right); // passing 10 System.out.println(findRightSibling(root.left.left.left.left, 0).data); }}// This code is contributed by Sumit Ghosh", "e": 42281, "s": 39555, "text": null }, { "code": "# Python3 program to print right sibling# of a node # A class to create a new Binary# Tree Nodeclass newNode: def __init__(self, item, parent): self.data = item self.left = self.right = None self.parent = parent # Method to find right siblingdef findRightSibling(node, level): if (node == None or node.parent == None): return None # GET Parent pointer whose right child is not # a parent or itself of this node. There might # be case when parent has no right child, but, # current node is left child of the parent # (second condition is for that). while (node.parent.right == node or (node.parent.right == None and node.parent.left == node)): if (node.parent == None): return None node = node.parent level -= 1 # Move to the required child, where # right sibling can be present node = node.parent.right # find right sibling in the given subtree # (from current node), when level will be 0 while (level < 0): # Iterate through subtree if (node.left != None): node = node.left else if (node.right != None): node = node.right else: # if no child are there, we cannot # have right sibling in this path break level += 1 if (level == 0): return node # This is the case when we reach 9 node # in the tree, where we need to again # recursively find the right sibling return findRightSibling(node, level) # Driver Codeif __name__ == '__main__': root = newNode(1, None) root.left = newNode(2, root) root.right = newNode(3, root) root.left.left = newNode(4, root.left) root.left.right = newNode(6, root.left) root.left.left.left = newNode(7, root.left.left) root.left.left.left.left = newNode(10, root.left.left.left) root.left.right.right = newNode(9, root.left.right) root.right.right = newNode(5, root.right) root.right.right.right = newNode(8, root.right.right) root.right.right.right.right = newNode(12, root.right.right.right) # passing 10 res = findRightSibling(root.left.left.left.left, 0) if (res == None): print(\"No right sibling\") else: print(res.data) # This code is contributed by PranchalK", "e": 44591, "s": 42281, "text": null }, { "code": "using System; // C# program to print right sibling of a nodepublic class Right_Sibling { // A Binary Tree Node public class Node { public int data; public Node left, right, parent; // Constructor public Node(int data, Node parent) { this.data = data; left = null; right = null; this.parent = parent; } } // Method to find right sibling public static Node findRightSibling(Node node, int level) { if (node == null || node.parent == null) { return null; } // GET Parent pointer whose right child is not // a parent or itself of this node. There might // be case when parent has no right child, but, // current node is left child of the parent // (second condition is for that). while (node.parent.right == node || (node.parent.right == null && node.parent.left == node)) { if (node.parent == null || node.parent.parent == null) { return null; } node = node.parent; level--; } // Move to the required child, where right sibling // can be present node = node.parent.right; // find right sibling in the given subtree(from current // node), when level will be 0 while (level < 0) { // Iterate through subtree if (node.left != null) { node = node.left; } else if (node.right != null) { node = node.right; } else { // if no child are there, we cannot have right // sibling in this path break; } level++; } if (level == 0) { return node; } // This is the case when we reach 9 node in the tree, // where we need to again recursively find the right // sibling return findRightSibling(node, level); } // Driver Program to test above functions public static void Main(string[] args) { Node root = new Node(1, null); root.left = new Node(2, root); root.right = new Node(3, root); root.left.left = new Node(4, root.left); root.left.right = new Node(6, root.left); root.left.left.left = new Node(7, root.left.left); root.left.left.left.left = new Node(10, root.left.left.left); root.left.right.right = new Node(9, root.left.right); root.right.right = new Node(5, root.right); root.right.right.right = new Node(8, root.right.right); root.right.right.right.right = new Node(12, root.right.right.right); // passing 10 Console.WriteLine(findRightSibling(root.left.left.left.left, 0).data); }} // This code is contributed by Shrikant13", "e": 47475, "s": 44591, "text": null }, { "code": "<script> // Javascript program to print right sibling of a node // A Binary Tree Node class Node { constructor(data, parent) { this.left = null; this.right = null; this.data = data; this.parent = parent; } } // Method to find right sibling function findRightSibling(node, level) { if (node == null || node.parent == null) return null; // GET Parent pointer whose right child is not // a parent or itself of this node. There might // be case when parent has no right child, but, // current node is left child of the parent // (second condition is for that). while (node.parent.right == node || (node.parent.right == null && node.parent.left == node)) { if (node.parent == null) return null; node = node.parent; level--; } // Move to the required child, where right sibling // can be present node = node.parent.right; // find right sibling in the given subtree(from current // node), when level will be 0 while (level < 0) { // Iterate through subtree if (node.left != null) node = node.left; else if (node.right != null) node = node.right; else // if no child are there, we cannot have right // sibling in this path break; level++; } if (level == 0) return node; // This is the case when we reach 9 node in the tree, // where we need to again recursively find the right // sibling return findRightSibling(node, level); } let root = new Node(1, null); root.left = new Node(2, root); root.right = new Node(3, root); root.left.left = new Node(4, root.left); root.left.right = new Node(6, root.left); root.left.left.left = new Node(7, root.left.left); root.left.left.left.left = new Node(10, root.left.left.left); root.left.right.right = new Node(9, root.left.right); root.right.right = new Node(5, root.right); root.right.right.right = new Node(8, root.right.right); root.right.right.right.right = new Node(12, root.right.right.right); // passing 10 document.write(findRightSibling(root.left.left.left.left, 0).data); // This code is contributed by divyesh072019.</script>", "e": 49976, "s": 47475, "text": null }, { "code": null, "e": 49985, "s": 49976, "text": "Output: " }, { "code": null, "e": 49988, "s": 49985, "text": "12" }, { "code": null, "e": 50010, "s": 49988, "text": "Time Complexity: O(N)" }, { "code": null, "e": 50032, "s": 50010, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 50454, "s": 50032, "text": "This article is contributed by Krishna 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 [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 50466, "s": 50454, "text": "shrikanth13" }, { "code": null, "e": 50482, "s": 50466, "text": "PranchalKatiyar" }, { "code": null, "e": 50489, "s": 50482, "text": "AbdulG" }, { "code": null, "e": 50505, "s": 50489, "text": "rohitsingh07052" }, { "code": null, "e": 50519, "s": 50505, "text": "divyesh072019" }, { "code": null, "e": 50536, "s": 50519, "text": "surinderdawra388" }, { "code": null, "e": 50541, "s": 50536, "text": "Tree" }, { "code": null, "e": 50546, "s": 50541, "text": "Tree" }, { "code": null, "e": 50644, "s": 50546, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 50653, "s": 50644, "text": "Comments" }, { "code": null, "e": 50666, "s": 50653, "text": "Old Comments" }, { "code": null, "e": 50716, "s": 50666, "text": "Tree Traversals (Inorder, Preorder and Postorder)" }, { "code": null, "e": 50751, "s": 50716, "text": "Binary Tree | Set 1 (Introduction)" }, { "code": null, "e": 50785, "s": 50751, "text": "Level Order Binary Tree Traversal" }, { "code": null, "e": 50814, "s": 50785, "text": "AVL Tree | Set 1 (Insertion)" }, { "code": null, "e": 50855, "s": 50814, "text": "Inorder Tree Traversal without Recursion" }, { "code": null, "e": 50898, "s": 50855, "text": "Binary Tree | Set 3 (Types of Binary Tree)" }, { "code": null, "e": 50960, "s": 50898, "text": "Write a Program to Find the Maximum Depth or Height of a Tree" }, { "code": null, "e": 50993, "s": 50960, "text": "Binary Tree | Set 2 (Properties)" } ]
What are the rules need to follow when overriding a method that throws an exception in Java?
We need to follow some rules when we overriding a method that throws an Exception. When the parent class method doesn’t throw any exceptions, the child class method can’t throw any checked exception, but it may throw any unchecked exceptions. class Parent { void doSomething() { // ... } } class Child extends Parent { void doSomething() throws IllegalArgumentException { // ... } } When the parent class method throws one or more checked exceptions, the child class method can throw any unchecked exception. class Parent { void doSomething() throws IOException, ParseException { // ... } void doSomethingElse() throws IOException { // ... } } class Child extends Parent { void doSomething() throws IOException { // ... } void doSomethingElse() throws FileNotFoundException, EOFException { // ... } } When the parent class method has a throws clause with an unchecked exception, the child class method can throw none or any number of unchecked exceptions, even though they are not related. class Parent { void doSomething() throws IllegalArgumentException { // ... } } class Child extends Parent { void doSomething() throws ArithmeticException, BufferOverflowException { // ... } } Live Demo import java.io.*; class SuperClassTest{ public void test() throws IOException { System.out.println("SuperClassTest.test() method"); } } class SubClassTest extends SuperClassTest { public void test() { System.out.println("SubClassTest.test() method"); } } public class OverridingExceptionTest { public static void main(String[] args) { SuperClassTest sct = new SubClassTest(); try { sct.test(); } catch(IOException ioe) { ioe.printStackTrace(); } } } SubClassTest.test() method
[ { "code": null, "e": 1145, "s": 1062, "text": "We need to follow some rules when we overriding a method that throws an Exception." }, { "code": null, "e": 1305, "s": 1145, "text": "When the parent class method doesn’t throw any exceptions, the child class method can’t throw any checked exception, but it may throw any unchecked exceptions." }, { "code": null, "e": 1469, "s": 1305, "text": "class Parent {\n void doSomething() {\n // ...\n }\n}\nclass Child extends Parent {\n void doSomething() throws IllegalArgumentException {\n // ...\n }\n}" }, { "code": null, "e": 1595, "s": 1469, "text": "When the parent class method throws one or more checked exceptions, the child class method can throw any unchecked exception." }, { "code": null, "e": 1935, "s": 1595, "text": "class Parent {\n void doSomething() throws IOException, ParseException {\n // ...\n }\n void doSomethingElse() throws IOException {\n // ...\n }\n}\nclass Child extends Parent {\n void doSomething() throws IOException {\n // ...\n }\n void doSomethingElse() throws FileNotFoundException, EOFException {\n // ...\n }\n}" }, { "code": null, "e": 2124, "s": 1935, "text": "When the parent class method has a throws clause with an unchecked exception, the child class method can throw none or any number of unchecked exceptions, even though they are not related." }, { "code": null, "e": 2340, "s": 2124, "text": "class Parent {\n void doSomething() throws IllegalArgumentException {\n // ...\n }\n}\nclass Child extends Parent {\n void doSomething() throws ArithmeticException, BufferOverflowException {\n // ...\n }\n}" }, { "code": null, "e": 2350, "s": 2340, "text": "Live Demo" }, { "code": null, "e": 2872, "s": 2350, "text": "import java.io.*;\nclass SuperClassTest{\n public void test() throws IOException {\n System.out.println(\"SuperClassTest.test() method\");\n }\n}\nclass SubClassTest extends SuperClassTest {\n public void test() {\n System.out.println(\"SubClassTest.test() method\");\n }\n}\npublic class OverridingExceptionTest {\n public static void main(String[] args) {\n SuperClassTest sct = new SubClassTest();\n try {\n sct.test();\n } catch(IOException ioe) {\n ioe.printStackTrace();\n }\n }\n}" }, { "code": null, "e": 2899, "s": 2872, "text": "SubClassTest.test() method" } ]
File canWrite() method in Java with examples - GeeksforGeeks
13 Dec, 2021 The canWrite()function is a part of File class in Java . This function determines whether the program can write the file denoted by the abstract path name.The function returns true if the abstract file path exists and the application is allowed to write the file. Function signature: public boolean canWrite() Syntax: file.canWrite() Parameters: This method does not accept any parameter. Return Value: The function returns boolean value representing whether the application is allowed to write the file or not. Exception: This method throws Security Exception if the write access to the file is denied Below programs illustrates the use of canWrite() function: Example 1: The file “F:\\program.txt” is writable Java // Java program to demonstrate// canWrite() method of File Class import java.io.*; public class solution { public static void main(String args[]) { // Get the file File f = new File("F:\\program.txt"); // Check if the specified file // can be written or not if (f.canWrite()) System.out.println("Can be written"); else System.out.println("Cannot be written"); }} Can be written Example 2: The file “F:\\program1.txt” is writable Java // Java program to demonstrate// canWrite() method of File Class import java.io.*; public class solution { public static void main(String args[]) { // Get the file File f = new File("F:\\program1.txt"); // Check if the specified file // can be written or not if (f.canWrite()) System.out.println("Can be written"); else System.out.println("Cannot be written"); }} Cannot be written Note: The programs might not run in an online IDE. Please use an offline IDE and set the path of the file. sagar0719kumar Java-File Class Java-Functions Java-IO package Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Different ways of Reading a text file in Java Constructors in Java Stream In Java Generics in Java Exceptions in Java Functional Interfaces in Java Comparator Interface in Java with Examples HashMap get() Method in Java Strings in Java StringBuilder Class in Java with Examples
[ { "code": null, "e": 23948, "s": 23920, "text": "\n13 Dec, 2021" }, { "code": null, "e": 24212, "s": 23948, "text": "The canWrite()function is a part of File class in Java . This function determines whether the program can write the file denoted by the abstract path name.The function returns true if the abstract file path exists and the application is allowed to write the file." }, { "code": null, "e": 24232, "s": 24212, "text": "Function signature:" }, { "code": null, "e": 24258, "s": 24232, "text": "public boolean canWrite()" }, { "code": null, "e": 24266, "s": 24258, "text": "Syntax:" }, { "code": null, "e": 24282, "s": 24266, "text": "file.canWrite()" }, { "code": null, "e": 24337, "s": 24282, "text": "Parameters: This method does not accept any parameter." }, { "code": null, "e": 24460, "s": 24337, "text": "Return Value: The function returns boolean value representing whether the application is allowed to write the file or not." }, { "code": null, "e": 24551, "s": 24460, "text": "Exception: This method throws Security Exception if the write access to the file is denied" }, { "code": null, "e": 24610, "s": 24551, "text": "Below programs illustrates the use of canWrite() function:" }, { "code": null, "e": 24660, "s": 24610, "text": "Example 1: The file “F:\\\\program.txt” is writable" }, { "code": null, "e": 24665, "s": 24660, "text": "Java" }, { "code": "// Java program to demonstrate// canWrite() method of File Class import java.io.*; public class solution { public static void main(String args[]) { // Get the file File f = new File(\"F:\\\\program.txt\"); // Check if the specified file // can be written or not if (f.canWrite()) System.out.println(\"Can be written\"); else System.out.println(\"Cannot be written\"); }}", "e": 25107, "s": 24665, "text": null }, { "code": null, "e": 25122, "s": 25107, "text": "Can be written" }, { "code": null, "e": 25173, "s": 25122, "text": "Example 2: The file “F:\\\\program1.txt” is writable" }, { "code": null, "e": 25178, "s": 25173, "text": "Java" }, { "code": "// Java program to demonstrate// canWrite() method of File Class import java.io.*; public class solution { public static void main(String args[]) { // Get the file File f = new File(\"F:\\\\program1.txt\"); // Check if the specified file // can be written or not if (f.canWrite()) System.out.println(\"Can be written\"); else System.out.println(\"Cannot be written\"); }}", "e": 25621, "s": 25178, "text": null }, { "code": null, "e": 25639, "s": 25621, "text": "Cannot be written" }, { "code": null, "e": 25746, "s": 25639, "text": "Note: The programs might not run in an online IDE. Please use an offline IDE and set the path of the file." }, { "code": null, "e": 25761, "s": 25746, "text": "sagar0719kumar" }, { "code": null, "e": 25777, "s": 25761, "text": "Java-File Class" }, { "code": null, "e": 25792, "s": 25777, "text": "Java-Functions" }, { "code": null, "e": 25808, "s": 25792, "text": "Java-IO package" }, { "code": null, "e": 25813, "s": 25808, "text": "Java" }, { "code": null, "e": 25818, "s": 25813, "text": "Java" }, { "code": null, "e": 25916, "s": 25818, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25925, "s": 25916, "text": "Comments" }, { "code": null, "e": 25938, "s": 25925, "text": "Old Comments" }, { "code": null, "e": 25984, "s": 25938, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 26005, "s": 25984, "text": "Constructors in Java" }, { "code": null, "e": 26020, "s": 26005, "text": "Stream In Java" }, { "code": null, "e": 26037, "s": 26020, "text": "Generics in Java" }, { "code": null, "e": 26056, "s": 26037, "text": "Exceptions in Java" }, { "code": null, "e": 26086, "s": 26056, "text": "Functional Interfaces in Java" }, { "code": null, "e": 26129, "s": 26086, "text": "Comparator Interface in Java with Examples" }, { "code": null, "e": 26158, "s": 26129, "text": "HashMap get() Method in Java" }, { "code": null, "e": 26174, "s": 26158, "text": "Strings in Java" } ]
MoviePy – Creating Image Sequence Clip - GeeksforGeeks
18 Aug, 2020 In this article we will see how we can create a image sequence clip in MoviePy. MoviePy is a Python module for video editing, which can be used for basic operations on videos and GIF’s. Video is formed by the frames, combination of frames creates a video each frame is an individual image. Image sequence clip is the clip which is formed by combining images one by one to form a sequence i.e video. In order to do this we will use ImageSequenceClip method Syntax : ImageSequenceClip([‘image_file1.jpeg’, ...], fps=24) Argument : It takes image file names and fps as argument Return : It returns ImageSequenceClip object Below is the implementation # importing editor from movie pyfrom moviepy.editor import * # creating a Image sequence clip with fps = 1clip = ImageSequenceClip(['frame1.png', 'frame2.png', 'frame1.png', 'frame2.png'], fps = 1) # showing clip clip.ipython_display(width = 360) Output : Moviepy - Building video __temp__.mp4. Moviepy - Writing video __temp__.mp4 Moviepy - Done ! Moviepy - video ready __temp__.mp4 Another example # importing editor from movie pyfrom moviepy.editor import * # creating a Image sequence clip with fps = 3clip = ImageSequenceClip(['frame1.png', 'frame1.png', 'frame2.png', 'frame1.png', 'frame1.png', 'frame2.png', 'frame1.png', 'frame1.png', 'frame2.png'], fps = 3) # showing clip clip.ipython_display(width = 360) Output : Moviepy - Building video __temp__.mp4. Moviepy - Writing video __temp__.mp4 Moviepy - Done ! Moviepy - video ready __temp__.mp4 Python-MoviePy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python Different ways to create Pandas Dataframe Python String | replace() Create a Pandas DataFrame from Lists Python program to convert a list to string Reading and Writing to text files in Python
[ { "code": null, "e": 24456, "s": 24428, "text": "\n18 Aug, 2020" }, { "code": null, "e": 24855, "s": 24456, "text": "In this article we will see how we can create a image sequence clip in MoviePy. MoviePy is a Python module for video editing, which can be used for basic operations on videos and GIF’s. Video is formed by the frames, combination of frames creates a video each frame is an individual image. Image sequence clip is the clip which is formed by combining images one by one to form a sequence i.e video." }, { "code": null, "e": 24912, "s": 24855, "text": "In order to do this we will use ImageSequenceClip method" }, { "code": null, "e": 24974, "s": 24912, "text": "Syntax : ImageSequenceClip([‘image_file1.jpeg’, ...], fps=24)" }, { "code": null, "e": 25031, "s": 24974, "text": "Argument : It takes image file names and fps as argument" }, { "code": null, "e": 25076, "s": 25031, "text": "Return : It returns ImageSequenceClip object" }, { "code": null, "e": 25104, "s": 25076, "text": "Below is the implementation" }, { "code": "# importing editor from movie pyfrom moviepy.editor import * # creating a Image sequence clip with fps = 1clip = ImageSequenceClip(['frame1.png', 'frame2.png', 'frame1.png', 'frame2.png'], fps = 1) # showing clip clip.ipython_display(width = 360) ", "e": 25355, "s": 25104, "text": null }, { "code": null, "e": 25364, "s": 25355, "text": "Output :" }, { "code": null, "e": 25614, "s": 25364, "text": "Moviepy - Building video __temp__.mp4.\nMoviepy - Writing video __temp__.mp4\n\n \nMoviepy - Done !\nMoviepy - video ready __temp__.mp4\n" }, { "code": null, "e": 25630, "s": 25614, "text": "Another example" }, { "code": "# importing editor from movie pyfrom moviepy.editor import * # creating a Image sequence clip with fps = 3clip = ImageSequenceClip(['frame1.png', 'frame1.png', 'frame2.png', 'frame1.png', 'frame1.png', 'frame2.png', 'frame1.png', 'frame1.png', 'frame2.png'], fps = 3) # showing clip clip.ipython_display(width = 360) ", "e": 26001, "s": 25630, "text": null }, { "code": null, "e": 26010, "s": 26001, "text": "Output :" }, { "code": null, "e": 26260, "s": 26010, "text": "Moviepy - Building video __temp__.mp4.\nMoviepy - Writing video __temp__.mp4\n\n \nMoviepy - Done !\nMoviepy - video ready __temp__.mp4\n" }, { "code": null, "e": 26275, "s": 26260, "text": "Python-MoviePy" }, { "code": null, "e": 26282, "s": 26275, "text": "Python" }, { "code": null, "e": 26380, "s": 26282, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26398, "s": 26380, "text": "Python Dictionary" }, { "code": null, "e": 26433, "s": 26398, "text": "Read a file line by line in Python" }, { "code": null, "e": 26455, "s": 26433, "text": "Enumerate() in Python" }, { "code": null, "e": 26487, "s": 26455, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26517, "s": 26487, "text": "Iterate over a list in Python" }, { "code": null, "e": 26559, "s": 26517, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 26585, "s": 26559, "text": "Python String | replace()" }, { "code": null, "e": 26622, "s": 26585, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 26665, "s": 26622, "text": "Python program to convert a list to string" } ]
Predictor-Corrector or Modified-Euler method for solving Differential equation - GeeksforGeeks
28 Dec, 2021 For a given differential equation with initial condition find the approximate solution using Predictor-Corrector method.Predictor-Corrector Method : The predictor-corrector method is also known as Modified-Euler method. In the Euler method, the tangent is drawn at a point and slope is calculated for a given step size. Thus this method works best with linear functions, but for other cases, there remains a truncation error. To solve this problem the Modified Euler method is introduced. In this method instead of a point, the arithmetic average of the slope over an interval is used.Thus in the Predictor-Corrector method for each step the predicted value of is calculated first using Euler’s method and then the slopes at the points and is calculated and the arithmetic average of these slopes are added to to calculate the corrected value of .So, Step – 1 : First the value is predicted for a step(here t+1) : , here h is step size for each increment Step – 2 : Then the predicted value is corrected : Step – 3 : The incrementation is done : Step – 4 : Check for continuation, if then go to step – 1. Step – 5 : Terminate the process. As, in this method, the average slope is used, so the error is reduced significantly. Also, we can repeat the process of correction for convergence. Thus at every step, we are reducing the error thus by improving the value of y.Examples: Input : eq = , y(0) = 0.5, step size(h) = 0.2 To find: y(1) Output: y(1) = 2.18147Explanation: The final value of y at x = 1 is y=2.18147 Implementation: Here we are considering the differential equation: C++ Java Python3 C# PHP Javascript // C++ code for solving the differential equation// using Predictor-Corrector or Modified-Euler method// with the given conditions, y(0) = 0.5, step size(h) = 0.2// to find y(1) #include <bits/stdc++.h>using namespace std; // consider the differential equation// for a given x and y, return vdouble f(double x, double y){ double v = y - 2 * x * x + 1; return v;} // predicts the next value for a given (x, y)// and step size h using Euler methoddouble predict(double x, double y, double h){ // value of next y(predicted) is returned double y1p = y + h * f(x, y); return y1p;} // corrects the predicted value// using Modified Euler methoddouble correct(double x, double y, double x1, double y1, double h){ // (x, y) are of previous step // and x1 is the increased x for next step // and y1 is predicted y for next step double e = 0.00001; double y1c = y1; do { y1 = y1c; y1c = y + 0.5 * h * (f(x, y) + f(x1, y1)); } while (fabs(y1c - y1) > e); // every iteration is correcting the value // of y using average slope return y1c;} void printFinalValues(double x, double xn, double y, double h){ while (x < xn) { double x1 = x + h; double y1p = predict(x, y, h); double y1c = correct(x, y, x1, y1p, h); x = x1; y = y1c; } // at every iteration first the value // of for next step is first predicted // and then corrected. cout << "The final value of y at x = " << x << " is : " << y << endl;} int main(){ // here x and y are the initial // given condition, so x=0 and y=0.5 double x = 0, y = 0.5; // final value of x for which y is needed double xn = 1; // step size double h = 0.2; printFinalValues(x, xn, y, h); return 0;} // Java code for solving the differential// equation using Predictor-Corrector// or Modified-Euler method with the// given conditions, y(0) = 0.5, step// size(h) = 0.2 to find y(1)import java.text.*; class GFG{ // consider the differential equation// for a given x and y, return vstatic double f(double x, double y){ double v = y - 2 * x * x + 1; return v;} // predicts the next value for a given (x, y)// and step size h using Euler methodstatic double predict(double x, double y, double h){ // value of next y(predicted) is returned double y1p = y + h * f(x, y); return y1p;} // corrects the predicted value// using Modified Euler methodstatic double correct(double x, double y, double x1, double y1, double h){ // (x, y) are of previous step // and x1 is the increased x for next step // and y1 is predicted y for next step double e = 0.00001; double y1c = y1; do { y1 = y1c; y1c = y + 0.5 * h * (f(x, y) + f(x1, y1)); } while (Math.abs(y1c - y1) > e); // every iteration is correcting the value // of y using average slope return y1c;} static void printFinalValues(double x, double xn, double y, double h){ while (x < xn) { double x1 = x + h; double y1p = predict(x, y, h); double y1c = correct(x, y, x1, y1p, h); x = x1; y = y1c; } // at every iteration first the value // of for next step is first predicted // and then corrected. DecimalFormat df = new DecimalFormat("#.#####"); System.out.println("The final value of y at x = "+ x + " is : "+df.format(y));} // Driver codepublic static void main (String[] args){ // here x and y are the initial // given condition, so x=0 and y=0.5 double x = 0, y = 0.5; // final value of x for which y is needed double xn = 1; // step size double h = 0.2; printFinalValues(x, xn, y, h);}} // This code is contributed by mits # Python3 code for solving the differential equation# using Predictor-Corrector or Modified-Euler method# with the given conditions, y(0) = 0.5, step size(h) = 0.2# to find y(1) # consider the differential equation# for a given x and y, return vdef f(x, y): v = y - 2 * x * x + 1; return v; # predicts the next value for a given (x, y)# and step size h using Euler methoddef predict(x, y, h): # value of next y(predicted) is returned y1p = y + h * f(x, y); return y1p; # corrects the predicted value# using Modified Euler methoddef correct(x, y, x1, y1, h): # (x, y) are of previous step # and x1 is the increased x for next step # and y1 is predicted y for next step e = 0.00001; y1c = y1; while (abs(y1c - y1) > e + 1): y1 = y1c; y1c = y + 0.5 * h * (f(x, y) + f(x1, y1)); # every iteration is correcting the value # of y using average slope return y1c; def printFinalValues(x, xn, y, h): while (x < xn): x1 = x + h; y1p = predict(x, y, h); y1c = correct(x, y, x1, y1p, h); x = x1; y = y1c; # at every iteration first the value # of for next step is first predicted # and then corrected. print("The final value of y at x =", int(x), "is :", y); # Driver Codeif __name__ == '__main__': # here x and y are the initial # given condition, so x=0 and y=0.5 x = 0; y = 0.5; # final value of x for which y is needed xn = 1; # step size h = 0.2; printFinalValues(x, xn, y, h); # This code is contributed by Rajput-Ji // C# code for solving the differential// equation using Predictor-Corrector// or Modified-Euler method with the// given conditions, y(0) = 0.5, step// size(h) = 0.2 to find y(1)using System; class GFG{ // consider the differential equation// for a given x and y, return vstatic double f(double x, double y){ double v = y - 2 * x * x + 1; return v;} // predicts the next value for a given (x, y)// and step size h using Euler methodstatic double predict(double x, double y, double h){ // value of next y(predicted) is returned double y1p = y + h * f(x, y); return y1p;} // corrects the predicted value// using Modified Euler methodstatic double correct(double x, double y, double x1, double y1, double h){ // (x, y) are of previous step // and x1 is the increased x for next step // and y1 is predicted y for next step double e = 0.00001; double y1c = y1; do { y1 = y1c; y1c = y + 0.5 * h * (f(x, y) + f(x1, y1)); } while (Math.Abs(y1c - y1) > e); // every iteration is correcting the value // of y using average slope return y1c;} static void printFinalValues(double x, double xn, double y, double h){ while (x < xn) { double x1 = x + h; double y1p = predict(x, y, h); double y1c = correct(x, y, x1, y1p, h); x = x1; y = y1c; } // at every iteration first the value // of for next step is first predicted // and then corrected. Console.WriteLine("The final value of y at x = "+ x + " is : " + Math.Round(y, 5));} // Driver codestatic void Main(){ // here x and y are the initial // given condition, so x=0 and y=0.5 double x = 0, y = 0.5; // final value of x for which y is needed double xn = 1; // step size double h = 0.2; printFinalValues(x, xn, y, h);}} // This code is contributed by mits <?php// PHP code for solving the differential equation// using Predictor-Corrector or Modified-Euler// method with the given conditions, y(0) = 0.5,// step size(h) = 0.2 to find y(1) // consider the differential equation// for a given x and y, return vfunction f($x, $y){ $v = $y - 2 * $x * $x + 1; return $v;} // predicts the next value for a given (x, y)// and step size h using Euler methodfunction predict($x, $y, $h){ // value of next y(predicted) is returned $y1p = $y + $h * f($x, $y); return $y1p;} // corrects the predicted value// using Modified Euler methodfunction correct($x, $y, $x1, $y1, $h){ // (x, y) are of previous step and // x1 is the increased x for next step // and y1 is predicted y for next step $e = 0.00001; $y1c = $y1; do { $y1 = $y1c; $y1c = $y + 0.5 * $h * (f($x, $y) + f($x1, $y1)); } while (abs($y1c - $y1) > $e); // every iteration is correcting the // value of y using average slope return $y1c;} function printFinalValues($x, $xn, $y, $h){ while ($x < $xn) { $x1 = $x + $h; $y1p = predict($x, $y, $h); $y1c = correct($x, $y, $x1, $y1p, $h); $x = $x1; $y = $y1c; } // at every iteration first the value // of for next step is first predicted // and then corrected. echo "The final value of y at x = " . $x . " is : " . round($y, 5) . "\n";} // here x and y are the initial // given condition, so x=0 and y=0.5 $x = 0; $y = 0.5; // final value of x for which y is needed $xn = 1; // step size $h = 0.2; printFinalValues($x, $xn, $y, $h); // This code is contributed by mits?> <script>// javascript code for solving the differential// equation using Predictor-Corrector// or Modified-Euler method with the// given conditions, y(0) = 0.5, step// size(h) = 0.2 to find y(1) // consider the differential equation // for a given x and y, return v function f(x , y) { var v = y - 2 * x * x + 1; return v; } // predicts the next value for a given (x, y) // and step size h using Euler method function predict(x , y , h) { // value of next y(predicted) is returned var y1p = y + h * f(x, y); return y1p; } // corrects the predicted value // using Modified Euler method function correct(x , y , x1 , y1 , h) { // (x, y) are of previous step // and x1 is the increased x for next step // and y1 is predicted y for next step var e = 0.00001; var y1c = y1; do { y1 = y1c; y1c = y + 0.5 * h * (f(x, y) + f(x1, y1)); } while (Math.abs(y1c - y1) > e); // every iteration is correcting the value // of y using average slope return y1c; } function printFinalValues(x , xn , y , h) { while (x < xn) { var x1 = x + h; var y1p = predict(x, y, h); var y1c = correct(x, y, x1, y1p, h); x = x1; y = y1c; } // at every iteration first the value // of for next step is first predicted // and then corrected. document.write("The final value of y at x = " + x + " is : " + y.toFixed(5)); } // Driver code // here x and y are the initial // given condition, so x=0 and y=0.5 var x = 0, y = 0.5; // final value of x for which y is needed var xn = 1; // step size var h = 0.2; printFinalValues(x, xn, y, h); // This code is contributed by Rajput-Ji</script> The final value of y at x = 1 is : 2.18147 Mithun Kumar Rajput-Ji Algebra Mathematical Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Merge two sorted arrays Modulo Operator (%) in C/C++ with Examples Program to find sum of elements in a given array Program for factorial of a number Operators in C / C++ Euclidean algorithms (Basic and Extended) The Knight's tour problem | Backtracking-1 Efficient program to print all prime factors of a given number Find minimum number of coins that make a given value Minimum number of jumps to reach end
[ { "code": null, "e": 24900, "s": 24872, "text": "\n28 Dec, 2021" }, { "code": null, "e": 25753, "s": 24900, "text": "For a given differential equation with initial condition find the approximate solution using Predictor-Corrector method.Predictor-Corrector Method : The predictor-corrector method is also known as Modified-Euler method. In the Euler method, the tangent is drawn at a point and slope is calculated for a given step size. Thus this method works best with linear functions, but for other cases, there remains a truncation error. To solve this problem the Modified Euler method is introduced. In this method instead of a point, the arithmetic average of the slope over an interval is used.Thus in the Predictor-Corrector method for each step the predicted value of is calculated first using Euler’s method and then the slopes at the points and is calculated and the arithmetic average of these slopes are added to to calculate the corrected value of .So, " }, { "code": null, "e": 25857, "s": 25753, "text": "Step – 1 : First the value is predicted for a step(here t+1) : , here h is step size for each increment" }, { "code": null, "e": 25911, "s": 25859, "text": "Step – 2 : Then the predicted value is corrected : " }, { "code": null, "e": 25954, "s": 25913, "text": "Step – 3 : The incrementation is done : " }, { "code": null, "e": 26015, "s": 25956, "text": "Step – 4 : Check for continuation, if then go to step – 1." }, { "code": null, "e": 26051, "s": 26017, "text": "Step – 5 : Terminate the process." }, { "code": null, "e": 26291, "s": 26051, "text": "As, in this method, the average slope is used, so the error is reduced significantly. Also, we can repeat the process of correction for convergence. Thus at every step, we are reducing the error thus by improving the value of y.Examples: " }, { "code": null, "e": 26431, "s": 26291, "text": "Input : eq = , y(0) = 0.5, step size(h) = 0.2 To find: y(1) Output: y(1) = 2.18147Explanation: The final value of y at x = 1 is y=2.18147 " }, { "code": null, "e": 26500, "s": 26431, "text": "Implementation: Here we are considering the differential equation: " }, { "code": null, "e": 26504, "s": 26500, "text": "C++" }, { "code": null, "e": 26509, "s": 26504, "text": "Java" }, { "code": null, "e": 26517, "s": 26509, "text": "Python3" }, { "code": null, "e": 26520, "s": 26517, "text": "C#" }, { "code": null, "e": 26524, "s": 26520, "text": "PHP" }, { "code": null, "e": 26535, "s": 26524, "text": "Javascript" }, { "code": "// C++ code for solving the differential equation// using Predictor-Corrector or Modified-Euler method// with the given conditions, y(0) = 0.5, step size(h) = 0.2// to find y(1) #include <bits/stdc++.h>using namespace std; // consider the differential equation// for a given x and y, return vdouble f(double x, double y){ double v = y - 2 * x * x + 1; return v;} // predicts the next value for a given (x, y)// and step size h using Euler methoddouble predict(double x, double y, double h){ // value of next y(predicted) is returned double y1p = y + h * f(x, y); return y1p;} // corrects the predicted value// using Modified Euler methoddouble correct(double x, double y, double x1, double y1, double h){ // (x, y) are of previous step // and x1 is the increased x for next step // and y1 is predicted y for next step double e = 0.00001; double y1c = y1; do { y1 = y1c; y1c = y + 0.5 * h * (f(x, y) + f(x1, y1)); } while (fabs(y1c - y1) > e); // every iteration is correcting the value // of y using average slope return y1c;} void printFinalValues(double x, double xn, double y, double h){ while (x < xn) { double x1 = x + h; double y1p = predict(x, y, h); double y1c = correct(x, y, x1, y1p, h); x = x1; y = y1c; } // at every iteration first the value // of for next step is first predicted // and then corrected. cout << \"The final value of y at x = \" << x << \" is : \" << y << endl;} int main(){ // here x and y are the initial // given condition, so x=0 and y=0.5 double x = 0, y = 0.5; // final value of x for which y is needed double xn = 1; // step size double h = 0.2; printFinalValues(x, xn, y, h); return 0;}", "e": 28359, "s": 26535, "text": null }, { "code": "// Java code for solving the differential// equation using Predictor-Corrector// or Modified-Euler method with the// given conditions, y(0) = 0.5, step// size(h) = 0.2 to find y(1)import java.text.*; class GFG{ // consider the differential equation// for a given x and y, return vstatic double f(double x, double y){ double v = y - 2 * x * x + 1; return v;} // predicts the next value for a given (x, y)// and step size h using Euler methodstatic double predict(double x, double y, double h){ // value of next y(predicted) is returned double y1p = y + h * f(x, y); return y1p;} // corrects the predicted value// using Modified Euler methodstatic double correct(double x, double y, double x1, double y1, double h){ // (x, y) are of previous step // and x1 is the increased x for next step // and y1 is predicted y for next step double e = 0.00001; double y1c = y1; do { y1 = y1c; y1c = y + 0.5 * h * (f(x, y) + f(x1, y1)); } while (Math.abs(y1c - y1) > e); // every iteration is correcting the value // of y using average slope return y1c;} static void printFinalValues(double x, double xn, double y, double h){ while (x < xn) { double x1 = x + h; double y1p = predict(x, y, h); double y1c = correct(x, y, x1, y1p, h); x = x1; y = y1c; } // at every iteration first the value // of for next step is first predicted // and then corrected. DecimalFormat df = new DecimalFormat(\"#.#####\"); System.out.println(\"The final value of y at x = \"+ x + \" is : \"+df.format(y));} // Driver codepublic static void main (String[] args){ // here x and y are the initial // given condition, so x=0 and y=0.5 double x = 0, y = 0.5; // final value of x for which y is needed double xn = 1; // step size double h = 0.2; printFinalValues(x, xn, y, h);}} // This code is contributed by mits", "e": 30366, "s": 28359, "text": null }, { "code": "# Python3 code for solving the differential equation# using Predictor-Corrector or Modified-Euler method# with the given conditions, y(0) = 0.5, step size(h) = 0.2# to find y(1) # consider the differential equation# for a given x and y, return vdef f(x, y): v = y - 2 * x * x + 1; return v; # predicts the next value for a given (x, y)# and step size h using Euler methoddef predict(x, y, h): # value of next y(predicted) is returned y1p = y + h * f(x, y); return y1p; # corrects the predicted value# using Modified Euler methoddef correct(x, y, x1, y1, h): # (x, y) are of previous step # and x1 is the increased x for next step # and y1 is predicted y for next step e = 0.00001; y1c = y1; while (abs(y1c - y1) > e + 1): y1 = y1c; y1c = y + 0.5 * h * (f(x, y) + f(x1, y1)); # every iteration is correcting the value # of y using average slope return y1c; def printFinalValues(x, xn, y, h): while (x < xn): x1 = x + h; y1p = predict(x, y, h); y1c = correct(x, y, x1, y1p, h); x = x1; y = y1c; # at every iteration first the value # of for next step is first predicted # and then corrected. print(\"The final value of y at x =\", int(x), \"is :\", y); # Driver Codeif __name__ == '__main__': # here x and y are the initial # given condition, so x=0 and y=0.5 x = 0; y = 0.5; # final value of x for which y is needed xn = 1; # step size h = 0.2; printFinalValues(x, xn, y, h); # This code is contributed by Rajput-Ji", "e": 31948, "s": 30366, "text": null }, { "code": "// C# code for solving the differential// equation using Predictor-Corrector// or Modified-Euler method with the// given conditions, y(0) = 0.5, step// size(h) = 0.2 to find y(1)using System; class GFG{ // consider the differential equation// for a given x and y, return vstatic double f(double x, double y){ double v = y - 2 * x * x + 1; return v;} // predicts the next value for a given (x, y)// and step size h using Euler methodstatic double predict(double x, double y, double h){ // value of next y(predicted) is returned double y1p = y + h * f(x, y); return y1p;} // corrects the predicted value// using Modified Euler methodstatic double correct(double x, double y, double x1, double y1, double h){ // (x, y) are of previous step // and x1 is the increased x for next step // and y1 is predicted y for next step double e = 0.00001; double y1c = y1; do { y1 = y1c; y1c = y + 0.5 * h * (f(x, y) + f(x1, y1)); } while (Math.Abs(y1c - y1) > e); // every iteration is correcting the value // of y using average slope return y1c;} static void printFinalValues(double x, double xn, double y, double h){ while (x < xn) { double x1 = x + h; double y1p = predict(x, y, h); double y1c = correct(x, y, x1, y1p, h); x = x1; y = y1c; } // at every iteration first the value // of for next step is first predicted // and then corrected. Console.WriteLine(\"The final value of y at x = \"+ x + \" is : \" + Math.Round(y, 5));} // Driver codestatic void Main(){ // here x and y are the initial // given condition, so x=0 and y=0.5 double x = 0, y = 0.5; // final value of x for which y is needed double xn = 1; // step size double h = 0.2; printFinalValues(x, xn, y, h);}} // This code is contributed by mits", "e": 33863, "s": 31948, "text": null }, { "code": "<?php// PHP code for solving the differential equation// using Predictor-Corrector or Modified-Euler// method with the given conditions, y(0) = 0.5,// step size(h) = 0.2 to find y(1) // consider the differential equation// for a given x and y, return vfunction f($x, $y){ $v = $y - 2 * $x * $x + 1; return $v;} // predicts the next value for a given (x, y)// and step size h using Euler methodfunction predict($x, $y, $h){ // value of next y(predicted) is returned $y1p = $y + $h * f($x, $y); return $y1p;} // corrects the predicted value// using Modified Euler methodfunction correct($x, $y, $x1, $y1, $h){ // (x, y) are of previous step and // x1 is the increased x for next step // and y1 is predicted y for next step $e = 0.00001; $y1c = $y1; do { $y1 = $y1c; $y1c = $y + 0.5 * $h * (f($x, $y) + f($x1, $y1)); } while (abs($y1c - $y1) > $e); // every iteration is correcting the // value of y using average slope return $y1c;} function printFinalValues($x, $xn, $y, $h){ while ($x < $xn) { $x1 = $x + $h; $y1p = predict($x, $y, $h); $y1c = correct($x, $y, $x1, $y1p, $h); $x = $x1; $y = $y1c; } // at every iteration first the value // of for next step is first predicted // and then corrected. echo \"The final value of y at x = \" . $x . \" is : \" . round($y, 5) . \"\\n\";} // here x and y are the initial // given condition, so x=0 and y=0.5 $x = 0; $y = 0.5; // final value of x for which y is needed $xn = 1; // step size $h = 0.2; printFinalValues($x, $xn, $y, $h); // This code is contributed by mits?>", "e": 35574, "s": 33863, "text": null }, { "code": "<script>// javascript code for solving the differential// equation using Predictor-Corrector// or Modified-Euler method with the// given conditions, y(0) = 0.5, step// size(h) = 0.2 to find y(1) // consider the differential equation // for a given x and y, return v function f(x , y) { var v = y - 2 * x * x + 1; return v; } // predicts the next value for a given (x, y) // and step size h using Euler method function predict(x , y , h) { // value of next y(predicted) is returned var y1p = y + h * f(x, y); return y1p; } // corrects the predicted value // using Modified Euler method function correct(x , y , x1 , y1 , h) { // (x, y) are of previous step // and x1 is the increased x for next step // and y1 is predicted y for next step var e = 0.00001; var y1c = y1; do { y1 = y1c; y1c = y + 0.5 * h * (f(x, y) + f(x1, y1)); } while (Math.abs(y1c - y1) > e); // every iteration is correcting the value // of y using average slope return y1c; } function printFinalValues(x , xn , y , h) { while (x < xn) { var x1 = x + h; var y1p = predict(x, y, h); var y1c = correct(x, y, x1, y1p, h); x = x1; y = y1c; } // at every iteration first the value // of for next step is first predicted // and then corrected. document.write(\"The final value of y at x = \" + x + \" is : \" + y.toFixed(5)); } // Driver code // here x and y are the initial // given condition, so x=0 and y=0.5 var x = 0, y = 0.5; // final value of x for which y is needed var xn = 1; // step size var h = 0.2; printFinalValues(x, xn, y, h); // This code is contributed by Rajput-Ji</script>", "e": 37468, "s": 35574, "text": null }, { "code": null, "e": 37511, "s": 37468, "text": "The final value of y at x = 1 is : 2.18147" }, { "code": null, "e": 37526, "s": 37513, "text": "Mithun Kumar" }, { "code": null, "e": 37536, "s": 37526, "text": "Rajput-Ji" }, { "code": null, "e": 37544, "s": 37536, "text": "Algebra" }, { "code": null, "e": 37557, "s": 37544, "text": "Mathematical" }, { "code": null, "e": 37570, "s": 37557, "text": "Mathematical" }, { "code": null, "e": 37668, "s": 37570, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 37692, "s": 37668, "text": "Merge two sorted arrays" }, { "code": null, "e": 37735, "s": 37692, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 37784, "s": 37735, "text": "Program to find sum of elements in a given array" }, { "code": null, "e": 37818, "s": 37784, "text": "Program for factorial of a number" }, { "code": null, "e": 37839, "s": 37818, "text": "Operators in C / C++" }, { "code": null, "e": 37881, "s": 37839, "text": "Euclidean algorithms (Basic and Extended)" }, { "code": null, "e": 37924, "s": 37881, "text": "The Knight's tour problem | Backtracking-1" }, { "code": null, "e": 37987, "s": 37924, "text": "Efficient program to print all prime factors of a given number" }, { "code": null, "e": 38040, "s": 37987, "text": "Find minimum number of coins that make a given value" } ]
VBA - WeekDay Name
The WeekDayName function returns the name of the weekday for the specified day. WeekdayName(weekday[,abbreviate[,firstdayofweek]]) Weekday − A required parameter. The number of the weekday. Weekday − A required parameter. The number of the weekday. Toabbreviate − An optional parameter. A Boolean value that indicates if the month name is to be abbreviated. If left blank, the default value would be taken as False. Toabbreviate − An optional parameter. A Boolean value that indicates if the month name is to be abbreviated. If left blank, the default value would be taken as False. Firstdayofweek − An optional parameter. Specifies the first day of the week. 0 = vbUseSystemDayOfWeek - Use National Language Support (NLS) API setting 1 = vbSunday - Sunday 2 = vbMonday - Monday 3 = vbTuesday - Tuesday 4 = vbWednesday - Wednesday 5 = vbThursday - Thursday 6 = vbFriday - Friday 7 = vbSaturday - Saturday Firstdayofweek − An optional parameter. Specifies the first day of the week. 0 = vbUseSystemDayOfWeek - Use National Language Support (NLS) API setting 0 = vbUseSystemDayOfWeek - Use National Language Support (NLS) API setting 1 = vbSunday - Sunday 1 = vbSunday - Sunday 2 = vbMonday - Monday 2 = vbMonday - Monday 3 = vbTuesday - Tuesday 3 = vbTuesday - Tuesday 4 = vbWednesday - Wednesday 4 = vbWednesday - Wednesday 5 = vbThursday - Thursday 5 = vbThursday - Thursday 6 = vbFriday - Friday 6 = vbFriday - Friday 7 = vbSaturday - Saturday 7 = vbSaturday - Saturday Add a button and add the following function. Private Sub Constant_demo_Click() msgbox("Line 1 : " &WeekdayName(3)) msgbox("Line 2 : " &WeekdayName(2,True)) msgbox("Line 3 : " &WeekdayName(1,False)) msgbox("Line 4 : " &WeekdayName(2,True,0)) msgbox("Line 5 : " &WeekdayName(1,False,1)) End Sub When you execute the above function, it produces the following output. Line 1 : Tuesday Line 2 : Mon Line 3 : Sunday Line 4 : Tue Line 5 : Sunday 101 Lectures 6 hours Pavan Lalwani 41 Lectures 3 hours Arnold Higuit 80 Lectures 5.5 hours Prashant Panchal 25 Lectures 2 hours Prashant Panchal 26 Lectures 2 hours Arnold Higuit 92 Lectures 10.5 hours Vijay Kumar Parvatha Reddy Print Add Notes Bookmark this page
[ { "code": null, "e": 2015, "s": 1935, "text": "The WeekDayName function returns the name of the weekday for the specified day." }, { "code": null, "e": 2068, "s": 2015, "text": "WeekdayName(weekday[,abbreviate[,firstdayofweek]]) \n" }, { "code": null, "e": 2127, "s": 2068, "text": "Weekday − A required parameter. The number of the weekday." }, { "code": null, "e": 2186, "s": 2127, "text": "Weekday − A required parameter. The number of the weekday." }, { "code": null, "e": 2353, "s": 2186, "text": "Toabbreviate − An optional parameter. A Boolean value that indicates if the month name is to be abbreviated. If left blank, the default value would be taken as False." }, { "code": null, "e": 2520, "s": 2353, "text": "Toabbreviate − An optional parameter. A Boolean value that indicates if the month name is to be abbreviated. If left blank, the default value would be taken as False." }, { "code": null, "e": 2845, "s": 2520, "text": "Firstdayofweek − An optional parameter. Specifies the first day of the week.\n\n0 = vbUseSystemDayOfWeek - Use National Language Support (NLS) API setting\n1 = vbSunday - Sunday\n2 = vbMonday - Monday\n3 = vbTuesday - Tuesday\n4 = vbWednesday - Wednesday\n5 = vbThursday - Thursday\n6 = vbFriday - Friday\n7 = vbSaturday - Saturday\n\n" }, { "code": null, "e": 2922, "s": 2845, "text": "Firstdayofweek − An optional parameter. Specifies the first day of the week." }, { "code": null, "e": 2997, "s": 2922, "text": "0 = vbUseSystemDayOfWeek - Use National Language Support (NLS) API setting" }, { "code": null, "e": 3072, "s": 2997, "text": "0 = vbUseSystemDayOfWeek - Use National Language Support (NLS) API setting" }, { "code": null, "e": 3094, "s": 3072, "text": "1 = vbSunday - Sunday" }, { "code": null, "e": 3116, "s": 3094, "text": "1 = vbSunday - Sunday" }, { "code": null, "e": 3138, "s": 3116, "text": "2 = vbMonday - Monday" }, { "code": null, "e": 3160, "s": 3138, "text": "2 = vbMonday - Monday" }, { "code": null, "e": 3184, "s": 3160, "text": "3 = vbTuesday - Tuesday" }, { "code": null, "e": 3208, "s": 3184, "text": "3 = vbTuesday - Tuesday" }, { "code": null, "e": 3236, "s": 3208, "text": "4 = vbWednesday - Wednesday" }, { "code": null, "e": 3264, "s": 3236, "text": "4 = vbWednesday - Wednesday" }, { "code": null, "e": 3290, "s": 3264, "text": "5 = vbThursday - Thursday" }, { "code": null, "e": 3316, "s": 3290, "text": "5 = vbThursday - Thursday" }, { "code": null, "e": 3338, "s": 3316, "text": "6 = vbFriday - Friday" }, { "code": null, "e": 3360, "s": 3338, "text": "6 = vbFriday - Friday" }, { "code": null, "e": 3386, "s": 3360, "text": "7 = vbSaturday - Saturday" }, { "code": null, "e": 3412, "s": 3386, "text": "7 = vbSaturday - Saturday" }, { "code": null, "e": 3457, "s": 3412, "text": "Add a button and add the following function." }, { "code": null, "e": 3720, "s": 3457, "text": "Private Sub Constant_demo_Click()\n msgbox(\"Line 1 : \" &WeekdayName(3))\n msgbox(\"Line 2 : \" &WeekdayName(2,True))\n msgbox(\"Line 3 : \" &WeekdayName(1,False))\n msgbox(\"Line 4 : \" &WeekdayName(2,True,0))\n msgbox(\"Line 5 : \" &WeekdayName(1,False,1))\nEnd Sub" }, { "code": null, "e": 3791, "s": 3720, "text": "When you execute the above function, it produces the following output." }, { "code": null, "e": 3867, "s": 3791, "text": "Line 1 : Tuesday\nLine 2 : Mon\nLine 3 : Sunday\nLine 4 : Tue\nLine 5 : Sunday\n" }, { "code": null, "e": 3901, "s": 3867, "text": "\n 101 Lectures \n 6 hours \n" }, { "code": null, "e": 3916, "s": 3901, "text": " Pavan Lalwani" }, { "code": null, "e": 3949, "s": 3916, "text": "\n 41 Lectures \n 3 hours \n" }, { "code": null, "e": 3964, "s": 3949, "text": " Arnold Higuit" }, { "code": null, "e": 3999, "s": 3964, "text": "\n 80 Lectures \n 5.5 hours \n" }, { "code": null, "e": 4017, "s": 3999, "text": " Prashant Panchal" }, { "code": null, "e": 4050, "s": 4017, "text": "\n 25 Lectures \n 2 hours \n" }, { "code": null, "e": 4068, "s": 4050, "text": " Prashant Panchal" }, { "code": null, "e": 4101, "s": 4068, "text": "\n 26 Lectures \n 2 hours \n" }, { "code": null, "e": 4116, "s": 4101, "text": " Arnold Higuit" }, { "code": null, "e": 4152, "s": 4116, "text": "\n 92 Lectures \n 10.5 hours \n" }, { "code": null, "e": 4180, "s": 4152, "text": " Vijay Kumar Parvatha Reddy" }, { "code": null, "e": 4187, "s": 4180, "text": " Print" }, { "code": null, "e": 4198, "s": 4187, "text": " Add Notes" } ]
Parallel Algorithm - Matrix Multiplication
A matrix is a set of numerical and non-numerical data arranged in a fixed number of rows and column. Matrix multiplication is an important multiplication design in parallel computation. Here, we will discuss the implementation of matrix multiplication on various communication networks like mesh and hypercube. Mesh and hypercube have higher network connectivity, so they allow faster algorithm than other networks like ring network. A topology where a set of nodes form a p-dimensional grid is called a mesh topology. Here, all the edges are parallel to the grid axis and all the adjacent nodes can communicate among themselves. Total number of nodes = (number of nodes in row) × (number of nodes in column) A mesh network can be evaluated using the following factors − Diameter Bisection width Diameter − In a mesh network, the longest distance between two nodes is its diameter. A p-dimensional mesh network having kP nodes has a diameter of p(k–1). Bisection width − Bisection width is the minimum number of edges needed to be removed from a network to divide the mesh network into two halves. We have considered a 2D mesh network SIMD model having wraparound connections. We will design an algorithm to multiply two n × n arrays using n2 processors in a particular amount of time. Matrices A and B have elements aij and bij respectively. Processing element PEij represents aij and bij. Arrange the matrices A and B in such a way that every processor has a pair of elements to multiply. The elements of matrix A will move in left direction and the elements of matrix B will move in upward direction. These changes in the position of the elements in matrix A and B present each processing element, PE, a new pair of values to multiply. Stagger two matrices. Calculate all products, aik × bkj Calculate sums when step 2 is complete. Procedure MatrixMulti Begin for k = 1 to n-1 for all Pij; where i and j ranges from 1 to n ifi is greater than k then rotate a in left direction end if if j is greater than k then rotate b in the upward direction end if for all Pij ; where i and j lies between 1 and n compute the product of a and b and store it in c for k= 1 to n-1 step 1 for all Pi;j where i and j ranges from 1 to n rotate a in left direction rotate b in the upward direction c=c+aXb End A hypercube is an n-dimensional construct where edges are perpendicular among themselves and are of same length. An n-dimensional hypercube is also known as an n-cube or an n-dimensional cube. Diameter = k Bisection width = 2k–1 Number of edges = k General specification of Hypercube networks − Let N = 2m be the total number of processors. Let the processors be P0, P1.....PN-1. Let N = 2m be the total number of processors. Let the processors be P0, P1.....PN-1. Let i and ib be two integers, 0 < i,ib < N-1 and its binary representation differ only in position b, 0 < b < k–1. Let i and ib be two integers, 0 < i,ib < N-1 and its binary representation differ only in position b, 0 < b < k–1. Let us consider two n × n matrices, matrix A and matrix B. Let us consider two n × n matrices, matrix A and matrix B. Step 1 − The elements of matrix A and matrix B are assigned to the n3 processors such that the processor in position i, j, k will have aji and bik. Step 1 − The elements of matrix A and matrix B are assigned to the n3 processors such that the processor in position i, j, k will have aji and bik. Step 2 − All the processor in position (i,j,k) computes the product C(i,j,k) = A(i,j,k) × B(i,j,k) Step 2 − All the processor in position (i,j,k) computes the product C(i,j,k) = A(i,j,k) × B(i,j,k) Step 3 − The sum C(0,j,k) = ΣC(i,j,k) for 0 ≤ i ≤ n-1, where 0 ≤ j, k < n–1. Step 3 − The sum C(0,j,k) = ΣC(i,j,k) for 0 ≤ i ≤ n-1, where 0 ≤ j, k < n–1. Block Matrix or partitioned matrix is a matrix where each element itself represents an individual matrix. These individual sections are known as a block or sub-matrix. In Figure (a), X is a block matrix where A, B, C, D are matrix themselves. Figure (f) shows the total matrix. When two block matrices are square matrices, then they are multiplied just the way we perform simple matrix multiplication. For example, 19 Lectures 1.5 hours Megha Aggarwal 22 Lectures 2.5 hours Vancho Dimitrov Print Add Notes Bookmark this page
[ { "code": null, "e": 2337, "s": 1903, "text": "A matrix is a set of numerical and non-numerical data arranged in a fixed number of rows and column. Matrix multiplication is an important multiplication design in parallel computation. Here, we will discuss the implementation of matrix multiplication on various communication networks like mesh and hypercube. Mesh and hypercube have higher network connectivity, so they allow faster algorithm than other networks like ring network." }, { "code": null, "e": 2533, "s": 2337, "text": "A topology where a set of nodes form a p-dimensional grid is called a mesh topology. Here, all the edges are parallel to the grid axis and all the adjacent nodes can communicate among themselves." }, { "code": null, "e": 2612, "s": 2533, "text": "Total number of nodes = (number of nodes in row) × (number of nodes in column)" }, { "code": null, "e": 2674, "s": 2612, "text": "A mesh network can be evaluated using the following factors −" }, { "code": null, "e": 2683, "s": 2674, "text": "Diameter" }, { "code": null, "e": 2699, "s": 2683, "text": "Bisection width" }, { "code": null, "e": 2856, "s": 2699, "text": "Diameter − In a mesh network, the longest distance between two nodes is its diameter. A p-dimensional mesh network having kP nodes has a diameter of p(k–1)." }, { "code": null, "e": 3001, "s": 2856, "text": "Bisection width − Bisection width is the minimum number of edges needed to be removed from a network to divide the mesh network into two halves." }, { "code": null, "e": 3189, "s": 3001, "text": "We have considered a 2D mesh network SIMD model having wraparound connections. We will design an algorithm to multiply two n × n arrays using n2 processors in a particular amount of time." }, { "code": null, "e": 3642, "s": 3189, "text": "Matrices A and B have elements aij and bij respectively. Processing element PEij represents aij and bij. Arrange the matrices A and B in such a way that every processor has a pair of elements to multiply. The elements of matrix A will move in left direction and the elements of matrix B will move in upward direction. These changes in the position of the elements in matrix A and B present each processing element, PE, a new pair of values to multiply." }, { "code": null, "e": 3664, "s": 3642, "text": "Stagger two matrices." }, { "code": null, "e": 3698, "s": 3664, "text": "Calculate all products, aik × bkj" }, { "code": null, "e": 3738, "s": 3698, "text": "Calculate sums when step 2 is complete." }, { "code": null, "e": 4277, "s": 3738, "text": "Procedure MatrixMulti\n\nBegin\n for k = 1 to n-1\n\t\n for all Pij; where i and j ranges from 1 to n\n ifi is greater than k then\n rotate a in left direction\n end if\n\t\t\n if j is greater than k then\n rotate b in the upward direction\n end if\n\t\n for all Pij ; where i and j lies between 1 and n\n compute the product of a and b and store it in c\n for k= 1 to n-1 step 1\n for all Pi;j where i and j ranges from 1 to n\n rotate a in left direction\n rotate b in the upward direction\n c=c+aXb\nEnd" }, { "code": null, "e": 4470, "s": 4277, "text": "A hypercube is an n-dimensional construct where edges are perpendicular among themselves and are of same length. An n-dimensional hypercube is also known as an n-cube or an n-dimensional cube." }, { "code": null, "e": 4483, "s": 4470, "text": "Diameter = k" }, { "code": null, "e": 4506, "s": 4483, "text": "Bisection width = 2k–1" }, { "code": null, "e": 4526, "s": 4506, "text": "Number of edges = k" }, { "code": null, "e": 4572, "s": 4526, "text": "General specification of Hypercube networks −" }, { "code": null, "e": 4657, "s": 4572, "text": "Let N = 2m be the total number of processors. Let the processors be P0, P1.....PN-1." }, { "code": null, "e": 4742, "s": 4657, "text": "Let N = 2m be the total number of processors. Let the processors be P0, P1.....PN-1." }, { "code": null, "e": 4857, "s": 4742, "text": "Let i and ib be two integers, 0 < i,ib < N-1 and its binary representation differ only in position b, 0 < b < k–1." }, { "code": null, "e": 4972, "s": 4857, "text": "Let i and ib be two integers, 0 < i,ib < N-1 and its binary representation differ only in position b, 0 < b < k–1." }, { "code": null, "e": 5031, "s": 4972, "text": "Let us consider two n × n matrices, matrix A and matrix B." }, { "code": null, "e": 5090, "s": 5031, "text": "Let us consider two n × n matrices, matrix A and matrix B." }, { "code": null, "e": 5238, "s": 5090, "text": "Step 1 − The elements of matrix A and matrix B are assigned to the n3 processors such that the processor in position i, j, k will have aji and bik." }, { "code": null, "e": 5386, "s": 5238, "text": "Step 1 − The elements of matrix A and matrix B are assigned to the n3 processors such that the processor in position i, j, k will have aji and bik." }, { "code": null, "e": 5485, "s": 5386, "text": "Step 2 − All the processor in position (i,j,k) computes the product\nC(i,j,k) = A(i,j,k) × B(i,j,k)" }, { "code": null, "e": 5553, "s": 5485, "text": "Step 2 − All the processor in position (i,j,k) computes the product" }, { "code": null, "e": 5584, "s": 5553, "text": "C(i,j,k) = A(i,j,k) × B(i,j,k)" }, { "code": null, "e": 5661, "s": 5584, "text": "Step 3 − The sum C(0,j,k) = ΣC(i,j,k) for 0 ≤ i ≤ n-1, where 0 ≤ j, k < n–1." }, { "code": null, "e": 5738, "s": 5661, "text": "Step 3 − The sum C(0,j,k) = ΣC(i,j,k) for 0 ≤ i ≤ n-1, where 0 ≤ j, k < n–1." }, { "code": null, "e": 5906, "s": 5738, "text": "Block Matrix or partitioned matrix is a matrix where each element itself represents an individual matrix. These individual sections are known as a block or sub-matrix." }, { "code": null, "e": 6016, "s": 5906, "text": "In Figure (a), X is a block matrix where A, B, C, D are matrix themselves. Figure (f) shows the total matrix." }, { "code": null, "e": 6153, "s": 6016, "text": "When two block matrices are square matrices, then they are multiplied just the way we perform simple matrix multiplication. For example," }, { "code": null, "e": 6188, "s": 6153, "text": "\n 19 Lectures \n 1.5 hours \n" }, { "code": null, "e": 6204, "s": 6188, "text": " Megha Aggarwal" }, { "code": null, "e": 6239, "s": 6204, "text": "\n 22 Lectures \n 2.5 hours \n" }, { "code": null, "e": 6256, "s": 6239, "text": " Vancho Dimitrov" }, { "code": null, "e": 6263, "s": 6256, "text": " Print" }, { "code": null, "e": 6274, "s": 6263, "text": " Add Notes" } ]
How To Structure Your PyTorch Project | by Branislav Holländer | Towards Data Science
Ever since I started to train deep neural networks, I was wondering what would be the structure for all my Python code. Ideally, a good structure should support extensive experimenting with the model, allow for implementing various different models in a single compact framework and be easily understood by everybody reading the code. You have to be able to use data from different data sources by coding and reusing various data loaders. Additionally, it would be nice if the models supported combining multiple networks in one model (such as is the case for GANs or the original R-CNN). The framework should also have enough flexibility to allow for complex visualizations (it is one of my core beliefs in data science that visualization makes everything MUCH easier, especially in the case of computer vision tasks). The detailed implementation of a deep learning framework will of course be dependent on the underlying library you are using, whether it be TensorFlow, PyTorch or CNTK. In this post I will present my approach based on PyTorch. However, I think that the general structure applies equally to whatever libraries you are using. You can find the whole repository at https://github.com/branislav1991/PyTorchProjectFramework. On the image above (taken from VS code, my Python editor of choice), you can see the general folder structure that I created for my framework. The framework consists of some startup scripts (train.py, validate.py, hyperopt.py) as well as the libraries hiding inside the folders. The datasets folder contains classes and methods for loading various types of data for training. The losses folder may contain additional loss functions or validation metrics. If you do not require any custom loss functions for your project, you probably won’t need this folder. The models folder is the most important: it contains the actual models. The optimizers folder includes code for custom optimizers. As with the losses folder, if you do not have any custom optimizers, you may as well omit this folder. Finally, the utils folder contains various utilities used all over the framework, most notably the visualizer. You will also notice the config_segmentation.json file in the root folder of the project. This file contains all the configuration options required for training. As you may have guessed, training is launched by calling the train.py script. This script is called with the appropriate configuration file as a command line argument. It takes care of all the high-level training stuff such as loading the training and validation datasets and the model, setting up the visualization, running the training loop and exporting the trained model at the end. Validation is used similarly by calling the appropriate scripts and passing the configuration files as arguments. On the image above you can see the structure of the dataset folder. It includes the __init__.py module which includes some necessary functions to find and create the right dataset as well as a custom data loader which forwards the data to the training pipeline (for more information on this, please have a look at the PyTorch API documentation). The base_dataset.py, as the name suggests, defines the abstract base class for each dataset you define in the framework. For every custom dataset you define, you will have to implement the __getitem__ and __len__ methods so that PyTorch may iterate over it. You won’t have to deal with the DataLoader anymore since that is defined in datasets/__init__.py already. You may also define custom callbacks for the dataset to be called before and after every epoch. This could be useful if you want to use some warmup method that feeds different data to the model during the first few epochs and switches to a more complex dataset afterwards. To instantiate the dataset, the train.py script calls the following code: print(‘Initializing dataset...’)train_dataset = create_dataset(configuration[‘train_dataset_params’])train_dataset_size = len(train_dataset)print(‘The number of training samples = {0}’.format(train_dataset_size)) This calls the create_dataset function which looks at the configuration file and chooses the correct dataset based on its name. It is important to follow the convention <datasetname>_dataset.py when naming the dataset since that is how the script is able to find your dataset based on the string in the configuration file. Finally, the script above calls the len() function on the dataset to inform you about its size. Models in the framework work in the same way as the datasets: the __init__.py module includes functions to find and create the right model according to its module name and the string defined in the configuration file. The model class itself inherits from the abstract BaseModel class and has to implement two methods: forward(self) to run the forward prediction, and optimize_parameters(self) to modify the weights of the network(s) after a training pass. All other methods may either be overridden or you may use the default BaseClass implementation. Functions you may want to override include pre_epoch_callback and post_epoch_callback (called before and after each epoch) or test (called during validation). In order to use the framework correctly, it is important to know how to use the networks, the optimizers and the losses in the model. Since there may be multiple networks in a model using different optimizers as well as multiple different losses (for instance, you could want to display the bounding box classification and regression losses for a semantic localization model), the interface is a bit more involved. Specifically, you provide the names of your losses and your networks together with the optimizers for the BaseModel class to know how to train your model. In the provided code I included an example of a 2D segmentation model together with an example dataset for you to see how the framework is supposed to be used. Take a look at the __init__() function of the provided 2D segmentation model: class Segmentation2DModel(BaseModel): def __init__(self, configuration): super().__init__(configuration) self.loss_names = [‘segmentation’] self.network_names = [‘unet’] self.netunet = UNet(1, 2) self.netunet = self.netunet.to(self.device) if self.is_train: # only defined during training time self.criterion_loss = torch.nn.CrossEntropyLoss() self.optimizer = torch.optim.Adam(self.netunet.parameters(), lr=configuration[‘lr’]) self.optimizers = [self.optimizer] This is what is happening here: first, we read the model configuration. Then, we define the ‘segmentation’ loss and put it in the self.loss_names list. The name of the loss is important since we use the variable self.loss_segmentation for the loss. By knowing the name, the BaseModel can look up the loss and print it in the console or visualize it (more about visualization in the next section). Similarly, we define the name of the network. This makes sure that BaseModel knows how to train the model without us having to explicitly define it. Next, we initialize the network (in this case a U-Net) and move it to the GPU. If we are in training mode, we also define the loss criterion and instantiate the optimizer (in this case Adam). Lastly, we put the optimizer into the self.optimizers list. This list is again used in the BaseModel class to update the learning rate or to resume training from a given checkpoint. Let us also take a look at the forward() and optimize_parameters() functions: def forward(self): self.output = self.netunet(self.input)def backward(self): self.loss_segmentation = self.criterion_loss(self.output, self.label)def optimize_parameters(self): self.loss_segmentation.backward() # calculate gradients self.optimizer.step() self.optimizer.zero_grad() As you can see, this is standard PyTorch code: its only responsibility is to call forward() on the network itself, to step the optimizer after the gradients have been calculated and to zero them again. It should be easy to implement this for your own model. Visualization can be found in the Visualizer class. This class is responsible for printing out loss information to the terminal as well as visualizing various results using the visdom library. It is initialized at the beginning of the training script (which loads up the visdom server). The training script also calls its plot_current_losses() and print_current_losses() functions to visualize and write out the training loss. It also contains functions like plot_current_validation_metrics(), plot_roc_curve() and show_validation_images() which are not called automatically but may be called from the model in the post_epoch_callback() to do some useful visualization upon validation. I tried to keep the visualizer fairly general. Certainly you can expand the functionality of the visualizer yourself to make it more useful for you. I presented an approach to writing a general deep learning framework that can be used in all areas of deep learning. By using this structure, you will obtain a clear and flexible codebase for further development. Of course there are many alternative ways how to approach the problem. Let me know in the comments if you have other suggestions!
[ { "code": null, "e": 867, "s": 47, "text": "Ever since I started to train deep neural networks, I was wondering what would be the structure for all my Python code. Ideally, a good structure should support extensive experimenting with the model, allow for implementing various different models in a single compact framework and be easily understood by everybody reading the code. You have to be able to use data from different data sources by coding and reusing various data loaders. Additionally, it would be nice if the models supported combining multiple networks in one model (such as is the case for GANs or the original R-CNN). The framework should also have enough flexibility to allow for complex visualizations (it is one of my core beliefs in data science that visualization makes everything MUCH easier, especially in the case of computer vision tasks)." }, { "code": null, "e": 1286, "s": 867, "text": "The detailed implementation of a deep learning framework will of course be dependent on the underlying library you are using, whether it be TensorFlow, PyTorch or CNTK. In this post I will present my approach based on PyTorch. However, I think that the general structure applies equally to whatever libraries you are using. You can find the whole repository at https://github.com/branislav1991/PyTorchProjectFramework." }, { "code": null, "e": 2351, "s": 1286, "text": "On the image above (taken from VS code, my Python editor of choice), you can see the general folder structure that I created for my framework. The framework consists of some startup scripts (train.py, validate.py, hyperopt.py) as well as the libraries hiding inside the folders. The datasets folder contains classes and methods for loading various types of data for training. The losses folder may contain additional loss functions or validation metrics. If you do not require any custom loss functions for your project, you probably won’t need this folder. The models folder is the most important: it contains the actual models. The optimizers folder includes code for custom optimizers. As with the losses folder, if you do not have any custom optimizers, you may as well omit this folder. Finally, the utils folder contains various utilities used all over the framework, most notably the visualizer. You will also notice the config_segmentation.json file in the root folder of the project. This file contains all the configuration options required for training." }, { "code": null, "e": 2738, "s": 2351, "text": "As you may have guessed, training is launched by calling the train.py script. This script is called with the appropriate configuration file as a command line argument. It takes care of all the high-level training stuff such as loading the training and validation datasets and the model, setting up the visualization, running the training loop and exporting the trained model at the end." }, { "code": null, "e": 2852, "s": 2738, "text": "Validation is used similarly by calling the appropriate scripts and passing the configuration files as arguments." }, { "code": null, "e": 3319, "s": 2852, "text": "On the image above you can see the structure of the dataset folder. It includes the __init__.py module which includes some necessary functions to find and create the right dataset as well as a custom data loader which forwards the data to the training pipeline (for more information on this, please have a look at the PyTorch API documentation). The base_dataset.py, as the name suggests, defines the abstract base class for each dataset you define in the framework." }, { "code": null, "e": 3835, "s": 3319, "text": "For every custom dataset you define, you will have to implement the __getitem__ and __len__ methods so that PyTorch may iterate over it. You won’t have to deal with the DataLoader anymore since that is defined in datasets/__init__.py already. You may also define custom callbacks for the dataset to be called before and after every epoch. This could be useful if you want to use some warmup method that feeds different data to the model during the first few epochs and switches to a more complex dataset afterwards." }, { "code": null, "e": 3909, "s": 3835, "text": "To instantiate the dataset, the train.py script calls the following code:" }, { "code": null, "e": 4124, "s": 3909, "text": "print(‘Initializing dataset...’)train_dataset = create_dataset(configuration[‘train_dataset_params’])train_dataset_size = len(train_dataset)print(‘The number of training samples = {0}’.format(train_dataset_size))" }, { "code": null, "e": 4543, "s": 4124, "text": "This calls the create_dataset function which looks at the configuration file and chooses the correct dataset based on its name. It is important to follow the convention <datasetname>_dataset.py when naming the dataset since that is how the script is able to find your dataset based on the string in the configuration file. Finally, the script above calls the len() function on the dataset to inform you about its size." }, { "code": null, "e": 4861, "s": 4543, "text": "Models in the framework work in the same way as the datasets: the __init__.py module includes functions to find and create the right model according to its module name and the string defined in the configuration file. The model class itself inherits from the abstract BaseModel class and has to implement two methods:" }, { "code": null, "e": 4910, "s": 4861, "text": "forward(self) to run the forward prediction, and" }, { "code": null, "e": 4999, "s": 4910, "text": "optimize_parameters(self) to modify the weights of the network(s) after a training pass." }, { "code": null, "e": 5254, "s": 4999, "text": "All other methods may either be overridden or you may use the default BaseClass implementation. Functions you may want to override include pre_epoch_callback and post_epoch_callback (called before and after each epoch) or test (called during validation)." }, { "code": null, "e": 5984, "s": 5254, "text": "In order to use the framework correctly, it is important to know how to use the networks, the optimizers and the losses in the model. Since there may be multiple networks in a model using different optimizers as well as multiple different losses (for instance, you could want to display the bounding box classification and regression losses for a semantic localization model), the interface is a bit more involved. Specifically, you provide the names of your losses and your networks together with the optimizers for the BaseModel class to know how to train your model. In the provided code I included an example of a 2D segmentation model together with an example dataset for you to see how the framework is supposed to be used." }, { "code": null, "e": 6062, "s": 5984, "text": "Take a look at the __init__() function of the provided 2D segmentation model:" }, { "code": null, "e": 6582, "s": 6062, "text": "class Segmentation2DModel(BaseModel): def __init__(self, configuration): super().__init__(configuration) self.loss_names = [‘segmentation’] self.network_names = [‘unet’] self.netunet = UNet(1, 2) self.netunet = self.netunet.to(self.device) if self.is_train: # only defined during training time self.criterion_loss = torch.nn.CrossEntropyLoss() self.optimizer = torch.optim.Adam(self.netunet.parameters(), lr=configuration[‘lr’]) self.optimizers = [self.optimizer]" }, { "code": null, "e": 7502, "s": 6582, "text": "This is what is happening here: first, we read the model configuration. Then, we define the ‘segmentation’ loss and put it in the self.loss_names list. The name of the loss is important since we use the variable self.loss_segmentation for the loss. By knowing the name, the BaseModel can look up the loss and print it in the console or visualize it (more about visualization in the next section). Similarly, we define the name of the network. This makes sure that BaseModel knows how to train the model without us having to explicitly define it. Next, we initialize the network (in this case a U-Net) and move it to the GPU. If we are in training mode, we also define the loss criterion and instantiate the optimizer (in this case Adam). Lastly, we put the optimizer into the self.optimizers list. This list is again used in the BaseModel class to update the learning rate or to resume training from a given checkpoint." }, { "code": null, "e": 7580, "s": 7502, "text": "Let us also take a look at the forward() and optimize_parameters() functions:" }, { "code": null, "e": 7872, "s": 7580, "text": "def forward(self): self.output = self.netunet(self.input)def backward(self): self.loss_segmentation = self.criterion_loss(self.output, self.label)def optimize_parameters(self): self.loss_segmentation.backward() # calculate gradients self.optimizer.step() self.optimizer.zero_grad()" }, { "code": null, "e": 8130, "s": 7872, "text": "As you can see, this is standard PyTorch code: its only responsibility is to call forward() on the network itself, to step the optimizer after the gradients have been calculated and to zero them again. It should be easy to implement this for your own model." }, { "code": null, "e": 8965, "s": 8130, "text": "Visualization can be found in the Visualizer class. This class is responsible for printing out loss information to the terminal as well as visualizing various results using the visdom library. It is initialized at the beginning of the training script (which loads up the visdom server). The training script also calls its plot_current_losses() and print_current_losses() functions to visualize and write out the training loss. It also contains functions like plot_current_validation_metrics(), plot_roc_curve() and show_validation_images() which are not called automatically but may be called from the model in the post_epoch_callback() to do some useful visualization upon validation. I tried to keep the visualizer fairly general. Certainly you can expand the functionality of the visualizer yourself to make it more useful for you." } ]
Redis - String Append Command
Redis APPEND command is used to add some value in a key. Integer reply, the length of the string after the append operation. Following is the basic syntax of Redis APPEND command. redis 127.0.0.1:6379> APPEND KEY_NAME NEW_VALUE redis 127.0.0.1:6379> SET mykey "hello" OK redis 127.0.0.1:6379> APPEND mykey " tutorialspoint" (integer) 20 redis 127.0.0.1:6379> GET mykey "hello tutorialspoint" 22 Lectures 40 mins Skillbakerystudios Print Add Notes Bookmark this page
[ { "code": null, "e": 2102, "s": 2045, "text": "Redis APPEND command is used to add some value in a key." }, { "code": null, "e": 2170, "s": 2102, "text": "Integer reply, the length of the string after the append operation." }, { "code": null, "e": 2225, "s": 2170, "text": "Following is the basic syntax of Redis APPEND command." }, { "code": null, "e": 2274, "s": 2225, "text": "redis 127.0.0.1:6379> APPEND KEY_NAME NEW_VALUE\n" }, { "code": null, "e": 2445, "s": 2274, "text": "redis 127.0.0.1:6379> SET mykey \"hello\" \nOK \nredis 127.0.0.1:6379> APPEND mykey \" tutorialspoint\" \n(integer) 20 \nredis 127.0.0.1:6379> GET mykey \n\"hello tutorialspoint\"\n" }, { "code": null, "e": 2477, "s": 2445, "text": "\n 22 Lectures \n 40 mins\n" }, { "code": null, "e": 2497, "s": 2477, "text": " Skillbakerystudios" }, { "code": null, "e": 2504, "s": 2497, "text": " Print" }, { "code": null, "e": 2515, "s": 2504, "text": " Add Notes" } ]
How can we ENABLE AND DISABLE a particular MySQL event?
With the help of ALTER EVENT statement along with the ENABLE and DISABLE keyword, we can ENABLE and DISABLE the event. To illustrate it we are having the following example − mysql> ALTER EVENT hello DISABLE; Query OK, 0 rows affected (0.00 sec) The above query will DISABLE the event named ‘Hello’ and the query below will enable it. mysql> ALTER EVENT hello ENABLE; Query OK, 0 rows affected (0.00 sec)
[ { "code": null, "e": 1236, "s": 1062, "text": "With the help of ALTER EVENT statement along with the ENABLE and DISABLE keyword, we can ENABLE and DISABLE the event. To illustrate it we are having the following example −" }, { "code": null, "e": 1307, "s": 1236, "text": "mysql> ALTER EVENT hello DISABLE;\nQuery OK, 0 rows affected (0.00 sec)" }, { "code": null, "e": 1396, "s": 1307, "text": "The above query will DISABLE the event named ‘Hello’ and the query below will enable it." }, { "code": null, "e": 1466, "s": 1396, "text": "mysql> ALTER EVENT hello ENABLE;\nQuery OK, 0 rows affected (0.00 sec)" } ]
Run and share deep learning web application on Google Colab | Towards Data Science
In my previous work, I built a deep learning model using Fastai to colorize black and white photos and built a web app prototype using Streamlit. I wish to share it with my colleagues and friends to get some feedback, so I tried to deploy the web app to AWS and Heroku. towardsdatascience.com I was able to deploy my app to these cloud service providers and run it, however, the free tier accounts of them do not provide enough memory for my app, it crashed all the time. To have at least something running online, I had to make the size of the photos small, resulting in very poor quality. I do not want to spend a lot of money on upgrading the account at this early stage. I just want a quick prototype running with full functionality so I can test it and get some feedback. Since then, I have been looking for other solutions to deploy and share the app. One solution I found is to run the app on Google Colab, using its free and powerful computation service. In this short post, I will describe how I run the web app on Colab. In case you are not familiar with Stremlit, it is a powerful tool to create simple web applications in Python. It is very convenient for people without web development background and skills like me. They offer a nice tutorial for beginners. github.com I also documented my work building the web app using Stremlit in this post: towardsdatascience.com Once you have the web app running locally successfully, you can try to run it on Google Colab First, clone the app to colab and enter the directory. !git clone http://github.com/xxx/xxxxx.git colorcd color then install the requirements !pip install -r requirements_colab.txt In my case, it contains stremlit, opencv, fastai, and scikit_image. then we need to install pyngrok. !pip install pyngrok To run and share the app by a public URL on Colab, we need to use ngrok, which is a secure tunneling solution. You can find the details here. After the installation, we can run the app in the background. !streamlit run run.py &>/dev/null& then create the public URL using ngrok. from pyngrok import ngrok# Setup a tunnel to the streamlit port 8501public_url = ngrok.connect(port='8501')public_url you should get an URL like this “http://ea41c43860d1.ngrok.io”. That is it! Really simple steps. Now the web app is available online utilizing the powerful Google Colab for free. The advantage of running a web app on Colab is that the app is not limited by the limited computation of free tier accounts, you can even have a runtime with GPU. However, the major drawback of it is the URL is only temporary, once the Colab is disconnected, the URL will be disabled. So you can only share the link for a short period (<12hrs). But I think it is still a good approach to quickly deploy, test, and share a web app prototype. Thanks for reading. Suggestions and comments are welcome.
[ { "code": null, "e": 442, "s": 172, "text": "In my previous work, I built a deep learning model using Fastai to colorize black and white photos and built a web app prototype using Streamlit. I wish to share it with my colleagues and friends to get some feedback, so I tried to deploy the web app to AWS and Heroku." }, { "code": null, "e": 465, "s": 442, "text": "towardsdatascience.com" }, { "code": null, "e": 949, "s": 465, "text": "I was able to deploy my app to these cloud service providers and run it, however, the free tier accounts of them do not provide enough memory for my app, it crashed all the time. To have at least something running online, I had to make the size of the photos small, resulting in very poor quality. I do not want to spend a lot of money on upgrading the account at this early stage. I just want a quick prototype running with full functionality so I can test it and get some feedback." }, { "code": null, "e": 1203, "s": 949, "text": "Since then, I have been looking for other solutions to deploy and share the app. One solution I found is to run the app on Google Colab, using its free and powerful computation service. In this short post, I will describe how I run the web app on Colab." }, { "code": null, "e": 1402, "s": 1203, "text": "In case you are not familiar with Stremlit, it is a powerful tool to create simple web applications in Python. It is very convenient for people without web development background and skills like me." }, { "code": null, "e": 1444, "s": 1402, "text": "They offer a nice tutorial for beginners." }, { "code": null, "e": 1455, "s": 1444, "text": "github.com" }, { "code": null, "e": 1531, "s": 1455, "text": "I also documented my work building the web app using Stremlit in this post:" }, { "code": null, "e": 1554, "s": 1531, "text": "towardsdatascience.com" }, { "code": null, "e": 1648, "s": 1554, "text": "Once you have the web app running locally successfully, you can try to run it on Google Colab" }, { "code": null, "e": 1703, "s": 1648, "text": "First, clone the app to colab and enter the directory." }, { "code": null, "e": 1760, "s": 1703, "text": "!git clone http://github.com/xxx/xxxxx.git colorcd color" }, { "code": null, "e": 1790, "s": 1760, "text": "then install the requirements" }, { "code": null, "e": 1829, "s": 1790, "text": "!pip install -r requirements_colab.txt" }, { "code": null, "e": 1897, "s": 1829, "text": "In my case, it contains stremlit, opencv, fastai, and scikit_image." }, { "code": null, "e": 1930, "s": 1897, "text": "then we need to install pyngrok." }, { "code": null, "e": 1951, "s": 1930, "text": "!pip install pyngrok" }, { "code": null, "e": 2093, "s": 1951, "text": "To run and share the app by a public URL on Colab, we need to use ngrok, which is a secure tunneling solution. You can find the details here." }, { "code": null, "e": 2155, "s": 2093, "text": "After the installation, we can run the app in the background." }, { "code": null, "e": 2190, "s": 2155, "text": "!streamlit run run.py &>/dev/null&" }, { "code": null, "e": 2230, "s": 2190, "text": "then create the public URL using ngrok." }, { "code": null, "e": 2348, "s": 2230, "text": "from pyngrok import ngrok# Setup a tunnel to the streamlit port 8501public_url = ngrok.connect(port='8501')public_url" }, { "code": null, "e": 2412, "s": 2348, "text": "you should get an URL like this “http://ea41c43860d1.ngrok.io”." }, { "code": null, "e": 2527, "s": 2412, "text": "That is it! Really simple steps. Now the web app is available online utilizing the powerful Google Colab for free." }, { "code": null, "e": 2968, "s": 2527, "text": "The advantage of running a web app on Colab is that the app is not limited by the limited computation of free tier accounts, you can even have a runtime with GPU. However, the major drawback of it is the URL is only temporary, once the Colab is disconnected, the URL will be disabled. So you can only share the link for a short period (<12hrs). But I think it is still a good approach to quickly deploy, test, and share a web app prototype." } ]
How YOLOV5 solved an ambiguity encountered by YOLOv3 | Towards Data Science
To the ones who not might be knowing, a new version of YOLO (You Only Look Once) is here, namely YOLO v5. Many thanks to Ultralytics for putting this repository together. You only look once (YOLO) is a state-of-the-art, real-time object detection system. On a Pascal Titan X it processes images at 30 FPS and has a mAP of 57.9% on COCO test-dev. YOLOv3 is extremely fast and accurate. In mAP measured at .5 IOU YOLOv3 is on par with Focal Loss but about 4x faster. Moreover, you can easily tradeoff between speed and accuracy simply by changing the size of the model, no retraining required! YOLOv3 has a problem though, despite being so accurate, it is biased. The bias is towards the size of the object in the image. If encountered with bigger objects while training, it cannot detect the same object of a smaller scale perfectly. YOLOv3 detects features in images and learn how to recognize objects with this information. Layers near the start detecting really simple features like edges and layers that are deeper can detect more complex features like eyes, noses, or an entire face. It then uses all of these features which it has learned, to make a final prediction. Herein lies the flaws of this system — there is no spatial that is used anywhere in a CNN and the pooling function that is used to connect layers is rendered inefficient. YOLOv5 YOLOv5 consists of three parts : Model BackboneModel headModel neck Model Backbone Model head Model neck The model head helps in the process of feature extraction. The model backbone consists of CSP Nets which help extract essential features from tensor passed through the model head. CSPNets enable quicker inference as well. The tensor from the model backbone is passed through the model neck which has feature pyramids, which try to eliminate bias with respect to size of objects. To know more about feature pyramids, check this out arxiv.org To know more about YOLOv5, check this out. blog.roboflow.ai Check out the YOLO v5 repository at github.com For our use case, I have created a similar repository at github.com git clone https://github.com/sid0312/anpr_yolov5cd anpr_yolov5 To detect a license plate in the car image, save it in the sample_cars folder of the directory. Name it as example.jpg python detect.py --source sample_cars/example.jpg --weights weights/best.pt --conf 0.4 Get the final image in the inference/output directory . To get an intuition of the detection process, check out the following notebook !git clone https://github.com/sid0312/anpr_yolov5 Cloning into 'anpr_yolov5'... remote: Enumerating objects: 42, done. remote: Counting objects: 100% (42/42), done. remote: Compressing objects: 100% (39/39), done. remote: Total 611 (delta 19), reused 15 (delta 3), pack-reused 569 Receiving objects: 100% (611/611), 63.42 MiB | 25.97 MiB/s, done. Resolving deltas: 100% (46/46), done. %cd anpr_yolov5/ /content/anpr_yolov5 !python detect.py --source sample_cars/ --weights weights/last.pt --conf 0.4 Namespace(agnostic_nms=False, augment=False, classes=None, conf_thres=0.4, device='', fourcc='mp4v', img_size=640, iou_thres=0.5, output='inference/output', save_txt=False, source='sample_cars/', view_img=False, weights='weights/last.pt') Using CUDA device0 _CudaDeviceProperties(name='Tesla K80', total_memory=11441MB) image 1/5 sample_cars/car_0.jpg: 448x640 1 license_plates, Done. (0.056s) image 2/5 sample_cars/car_1.jpg: 384x640 Done. (0.025s) image 3/5 sample_cars/car_2.jpg: 512x640 1 license_plates, Done. (0.028s) image 4/5 sample_cars/car_3.jpg: 448x640 1 license_plates, Done. (0.027s) image 5/5 sample_cars/car_4.jpg: 512x640 2 license_plates, Done. (0.028s) Results saved to /content/anpr_yolov5/inference/output Done. (0.785s) import os print(os.listdir('/content/anpr_yolov5/inference/output')) ['car_0.jpg', 'car_1.jpg', 'car_3.jpg', 'car_2.jpg', 'car_4.jpg'] from google.colab import files for img in os.listdir('/content/anpr_yolov5/inference/output'): path = os.path.join('/content/anpr_yolov5/inference/output',img) files.download(path) Here are some results This repository included the following changes to the original utlralytics repository Created data/license_plate.yaml Data Preparation Step 1- Download the starter dataset in JSON format from www.kaggle.com This serves as our starting dataset. Upload the JSON file to your Google Drive Step 2- Conversion of the JSON starter dataset to YOLO format from google.colab import drive drive.mount('/content/drive') Drive already mounted at /content/drive; to attempt to forcibly remount, call drive.mount("/content/drive", force_remount=True). import pandas as pd import numpy as np import urllib import matplotlib.pyplot as plt import cv2 import glob,os,time from PIL import Image json_path = '/content/drive/My Drive/Indian_Number_plates.json' data = pd.read_json(json_path,lines=True) data.head() os.mkdir('License Plates') data['annotation'][0] [{'imageHeight': 466, 'imageWidth': 806, 'label': ['number_plate'], 'notes': '', 'points': [{'x': 0.722084367245657, 'y': 0.5879828326180251}, {'x': 0.8684863523573201, 'y': 0.688841201716738}]}] print(len(data)) 237 dataset = {} vals = ['name','height','width','top_x','top_y','bottom_x','bottom_y'] for i in vals: dataset[i] = list() count = 0 for idx,row in data.iterrows(): img = urllib.request.urlopen(row["content"]) img = Image.open(img) img = img.convert('RGB') img.save("/content/License Plates/car_{}.jpeg".format(count),'JPEG') dataset['name'].append('car_{}'.format(count)) annotation = row['annotation'] dataset['height'].append(annotation[0]['imageHeight']) dataset['width'].append(annotation[0]['imageWidth']) dataset['top_x'].append(annotation[0]['points'][0]['x']) dataset['top_y'].append(annotation[0]['points'][0]['y']) dataset['bottom_x'].append(annotation[0]['points'][1]['x']) dataset['bottom_y'].append(annotation[0]['points'][1]['y']) count =count+1 if count%10==0: print('Downloaded.. {}/{}'.format(count,len(data))) if count%len(data)==0: print('Loading last image.. {}/{}'.format(count,len(data))) print('{} images downloaded'.format(count)) Downloaded.. 10/237 Downloaded.. 20/237 Downloaded.. 30/237 Downloaded.. 40/237 Downloaded.. 50/237 Downloaded.. 60/237 Downloaded.. 70/237 Downloaded.. 80/237 Downloaded.. 90/237 Downloaded.. 100/237 Downloaded.. 110/237 Downloaded.. 120/237 Downloaded.. 130/237 Downloaded.. 140/237 Downloaded.. 150/237 Downloaded.. 160/237 Downloaded.. 170/237 Downloaded.. 180/237 Downloaded.. 190/237 Downloaded.. 200/237 Downloaded.. 210/237 Downloaded.. 220/237 Downloaded.. 230/237 Loading last image.. 237/237 237 images downloaded df = pd.DataFrame(dataset) df.head() df.to_csv('license_plates.csv',index=False) csv_path = '/content/license_plates.csv' licenses = pd.read_csv(csv_path) licenses.tail() licenses['name'] = licenses['name'] + '.jpeg' licenses.head() licenses.drop(columns=['height','width'],inplace=True) licenses.head() widths,heights =[],[] center_x,center_y=[],[] for i in range(len(licenses)): widths.append(licenses['bottom_x'][i]- licenses['top_x'][i]) heights.append(licenses['bottom_y'][i]- licenses['top_y'][i]) center_x.append((licenses['bottom_x'][i] + licenses['top_x'][i])/2) center_y.append((licenses['bottom_y'][i] + licenses['top_y'][i])/2) lic = pd.DataFrame(columns=['x','y','w','h']) lic['w'] = widths lic['h'] = heights lic['x'] = center_x lic['y'] = center_y lic.head() for i in range(len(lic)): f = open('/content/License Plates/car_{}.txt'.format(i),'w+') f.write('{} {} {} {} {}'.format(0,lic['x'][i],lic['y'][i],lic['w'][i],lic['h'][i])) f.close() !zip -r /content/file.zip /content/License\ Plates from google.colab import files files.download("/content/file.zip") adding: content/License Plates/ (stored 0%) adding: content/License Plates/car_86.jpeg (deflated 1%) adding: content/License Plates/car_83.txt (deflated 27%) adding: content/License Plates/car_64.txt (deflated 28%) adding: content/License Plates/car_154.jpeg (deflated 1%) adding: content/License Plates/car_21.jpeg (deflated 1%) adding: content/License Plates/car_209.jpeg (deflated 1%) adding: content/License Plates/car_217.txt (deflated 37%) adding: content/License Plates/car_190.jpeg (deflated 2%) adding: content/License Plates/car_91.jpeg (deflated 1%) adding: content/License Plates/car_23.jpeg (deflated 0%) adding: content/License Plates/car_102.txt (deflated 29%) adding: content/License Plates/car_228.jpeg (deflated 1%) adding: content/License Plates/car_231.jpeg (deflated 2%) adding: content/License Plates/car_46.txt (deflated 27%) adding: content/License Plates/car_199.jpeg (deflated 0%) adding: content/License Plates/car_163.jpeg (deflated 1%) adding: content/License Plates/car_40.jpeg (deflated 0%) adding: content/License Plates/car_43.txt (deflated 29%) adding: content/License Plates/car_38.jpeg (deflated 1%) adding: content/License Plates/car_93.jpeg (deflated 1%) adding: content/License Plates/car_227.jpeg (deflated 1%) adding: content/License Plates/car_204.txt (deflated 38%) adding: content/License Plates/car_106.jpeg (deflated 1%) adding: content/License Plates/car_152.txt (deflated 32%) adding: content/License Plates/car_221.jpeg (deflated 0%) adding: content/License Plates/car_212.txt (deflated 37%) adding: content/License Plates/car_60.jpeg (deflated 1%) adding: content/License Plates/car_39.txt (deflated 56%) adding: content/License Plates/car_126.jpeg (deflated 0%) adding: content/License Plates/car_213.txt (deflated 30%) adding: content/License Plates/car_181.txt (deflated 34%) adding: content/License Plates/car_198.txt (deflated 36%) adding: content/License Plates/car_156.jpeg (deflated 0%) adding: content/License Plates/car_178.txt (deflated 30%) adding: content/License Plates/car_68.txt (deflated 32%) adding: content/License Plates/car_82.jpeg (deflated 1%) adding: content/License Plates/car_217.jpeg (deflated 1%) adding: content/License Plates/car_224.jpeg (deflated 3%) adding: content/License Plates/car_216.jpeg (deflated 0%) adding: content/License Plates/car_141.txt (deflated 33%) adding: content/License Plates/car_101.txt (deflated 32%) adding: content/License Plates/car_174.txt (deflated 47%) adding: content/License Plates/car_2.txt (deflated 29%) adding: content/License Plates/car_39.jpeg (deflated 2%) adding: content/License Plates/car_220.jpeg (deflated 1%) adding: content/License Plates/car_26.jpeg (deflated 2%) adding: content/License Plates/car_200.txt (deflated 30%) adding: content/License Plates/car_129.txt (deflated 45%) adding: content/License Plates/car_202.txt (deflated 52%) adding: content/License Plates/car_186.jpeg (deflated 1%) adding: content/License Plates/car_27.jpeg (deflated 1%) adding: content/License Plates/car_19.txt (deflated 27%) adding: content/License Plates/car_110.txt (deflated 53%) adding: content/License Plates/car_196.txt (deflated 22%) adding: content/License Plates/car_20.jpeg (deflated 1%) adding: content/License Plates/car_145.txt (deflated 45%) adding: content/License Plates/car_164.jpeg (deflated 0%) adding: content/License Plates/car_14.jpeg (deflated 1%) adding: content/License Plates/car_142.jpeg (deflated 1%) adding: content/License Plates/car_86.txt (deflated 31%) adding: content/License Plates/car_190.txt (deflated 32%) adding: content/License Plates/car_146.jpeg (deflated 1%) adding: content/License Plates/car_139.jpeg (deflated 1%) adding: content/License Plates/car_91.txt (deflated 36%) adding: content/License Plates/car_59.jpeg (deflated 2%) adding: content/License Plates/car_155.txt (deflated 42%) adding: content/License Plates/car_116.jpeg (deflated 1%) adding: content/License Plates/car_192.txt (deflated 27%) adding: content/License Plates/car_34.jpeg (deflated 0%) adding: content/License Plates/car_36.txt (deflated 47%) adding: content/License Plates/car_31.jpeg (deflated 2%) adding: content/License Plates/car_122.jpeg (deflated 2%) adding: content/License Plates/car_120.txt (deflated 33%) adding: content/License Plates/car_59.txt (deflated 29%) adding: content/License Plates/car_150.txt (deflated 28%) adding: content/License Plates/car_69.txt (deflated 32%) adding: content/License Plates/car_51.jpeg (deflated 0%) adding: content/License Plates/car_90.jpeg (deflated 1%) adding: content/License Plates/car_44.jpeg (deflated 1%) adding: content/License Plates/car_128.txt (deflated 28%) adding: content/License Plates/car_199.txt (deflated 47%) adding: content/License Plates/car_87.txt (deflated 29%) adding: content/License Plates/car_186.txt (deflated 38%) adding: content/License Plates/car_99.txt (deflated 27%) adding: content/License Plates/car_97.jpeg (deflated 2%) adding: content/License Plates/car_37.jpeg (deflated 1%) adding: content/License Plates/car_193.txt (deflated 46%) adding: content/License Plates/car_117.txt (deflated 56%) adding: content/License Plates/car_124.jpeg (deflated 1%) adding: content/License Plates/car_73.txt (deflated 29%) adding: content/License Plates/car_121.txt (deflated 28%) adding: content/License Plates/car_33.jpeg (deflated 0%) adding: content/License Plates/car_100.txt (deflated 27%) adding: content/License Plates/car_109.txt (deflated 28%) adding: content/License Plates/car_90.txt (deflated 33%) adding: content/License Plates/car_157.txt (deflated 28%) adding: content/License Plates/car_65.jpeg (deflated 2%) adding: content/License Plates/car_111.jpeg (deflated 0%) adding: content/License Plates/car_211.txt (deflated 13%) adding: content/License Plates/car_134.jpeg (deflated 1%) adding: content/License Plates/car_20.txt (deflated 35%) adding: content/License Plates/car_197.txt (deflated 49%) adding: content/License Plates/car_25.jpeg (deflated 0%) adding: content/License Plates/car_219.jpeg (deflated 1%) adding: content/License Plates/car_29.txt (deflated 34%) adding: content/License Plates/car_152.jpeg (deflated 1%) adding: content/License Plates/car_167.jpeg (deflated 0%) adding: content/License Plates/car_89.txt (deflated 29%) adding: content/License Plates/car_62.jpeg (deflated 2%) adding: content/License Plates/car_58.txt (deflated 34%) adding: content/License Plates/car_0.txt (deflated 30%) adding: content/License Plates/car_105.txt (deflated 38%) adding: content/License Plates/car_60.txt (deflated 29%) adding: content/License Plates/car_235.jpeg (deflated 0%) adding: content/License Plates/car_177.jpeg (deflated 1%) adding: content/License Plates/car_2.jpeg (deflated 1%) adding: content/License Plates/car_131.jpeg (deflated 1%) adding: content/License Plates/car_15.txt (deflated 29%) adding: content/License Plates/car_70.jpeg (deflated 1%) adding: content/License Plates/car_97.txt (deflated 40%) adding: content/License Plates/car_95.txt (deflated 28%) adding: content/License Plates/car_146.txt (deflated 35%) adding: content/License Plates/car_8.txt (deflated 29%) adding: content/License Plates/car_173.jpeg (deflated 1%) adding: content/License Plates/car_42.txt (deflated 38%) adding: content/License Plates/car_175.jpeg (deflated 6%) adding: content/License Plates/car_114.jpeg (deflated 4%) adding: content/License Plates/car_77.txt (deflated 28%) adding: content/License Plates/car_140.txt (deflated 31%) adding: content/License Plates/car_11.jpeg (deflated 0%) adding: content/License Plates/car_10.jpeg (deflated 0%) adding: content/License Plates/car_123.jpeg (deflated 0%) adding: content/License Plates/car_28.jpeg (deflated 0%) adding: content/License Plates/car_115.txt (deflated 53%) adding: content/License Plates/car_183.txt (deflated 37%) adding: content/License Plates/car_114.txt (deflated 34%) adding: content/License Plates/car_168.jpeg (deflated 1%) adding: content/License Plates/car_7.jpeg (deflated 0%) adding: content/License Plates/car_10.txt (deflated 37%) adding: content/License Plates/car_167.txt (deflated 38%) adding: content/License Plates/car_76.jpeg (deflated 0%) adding: content/License Plates/car_185.txt (deflated 30%) adding: content/License Plates/car_57.txt (deflated 30%) adding: content/License Plates/car_179.jpeg (deflated 1%) adding: content/License Plates/car_76.txt (deflated 43%) adding: content/License Plates/car_180.jpeg (deflated 1%) adding: content/License Plates/car_209.txt (deflated 29%) adding: content/License Plates/car_192.jpeg (deflated 1%) adding: content/License Plates/car_107.txt (deflated 31%) adding: content/License Plates/car_22.jpeg (deflated 0%) adding: content/License Plates/car_206.txt (deflated 27%) adding: content/License Plates/car_131.txt (deflated 42%) adding: content/License Plates/car_14.txt (deflated 16%) adding: content/License Plates/car_129.jpeg (deflated 1%) adding: content/License Plates/car_66.jpeg (deflated 1%) adding: content/License Plates/car_117.jpeg (deflated 0%) adding: content/License Plates/car_188.jpeg (deflated 1%) adding: content/License Plates/car_211.jpeg (deflated 1%) adding: content/License Plates/car_48.txt (deflated 28%) adding: content/License Plates/car_234.jpeg (deflated 0%) adding: content/License Plates/car_162.jpeg (deflated 3%) adding: content/License Plates/car_230.txt (deflated 29%) adding: content/License Plates/car_105.jpeg (deflated 2%) adding: content/License Plates/car_118.txt (deflated 43%) adding: content/License Plates/car_34.txt (deflated 28%) adding: content/License Plates/car_127.txt (deflated 29%) adding: content/License Plates/car_33.txt (deflated 30%) adding: content/License Plates/car_172.txt (deflated 24%) adding: content/License Plates/car_71.txt (deflated 28%) adding: content/License Plates/car_132.jpeg (deflated 1%) adding: content/License Plates/car_25.txt (deflated 40%) adding: content/License Plates/car_77.jpeg (deflated 1%) adding: content/License Plates/car_84.jpeg (deflated 1%) adding: content/License Plates/car_38.txt (deflated 33%) adding: content/License Plates/car_103.txt (deflated 29%) adding: content/License Plates/car_180.txt (deflated 29%) adding: content/License Plates/car_66.txt (deflated 29%) adding: content/License Plates/car_193.jpeg (deflated 1%) adding: content/License Plates/car_126.txt (deflated 39%) adding: content/License Plates/car_123.txt (deflated 38%) adding: content/License Plates/car_24.txt (deflated 34%) adding: content/License Plates/car_181.jpeg (deflated 0%) adding: content/License Plates/car_161.jpeg (deflated 0%) adding: content/License Plates/car_15.jpeg (deflated 1%) adding: content/License Plates/car_48.jpeg (deflated 1%) adding: content/License Plates/car_32.jpeg (deflated 0%) adding: content/License Plates/car_158.jpeg (deflated 1%) adding: content/License Plates/car_26.txt (deflated 39%) adding: content/License Plates/car_195.txt (deflated 29%) adding: content/License Plates/car_41.txt (deflated 37%) adding: content/License Plates/car_173.txt (deflated 16%) adding: content/License Plates/car_89.jpeg (deflated 1%) adding: content/License Plates/car_74.jpeg (deflated 1%) adding: content/License Plates/car_16.jpeg (deflated 0%) adding: content/License Plates/car_113.jpeg (deflated 1%) adding: content/License Plates/car_84.txt (deflated 33%) adding: content/License Plates/car_45.jpeg (deflated 1%) adding: content/License Plates/car_140.jpeg (deflated 1%) adding: content/License Plates/car_116.txt (deflated 60%) adding: content/License Plates/car_145.jpeg (deflated 0%) adding: content/License Plates/car_168.txt (deflated 32%) adding: content/License Plates/car_177.txt (deflated 49%) adding: content/License Plates/car_175.txt (deflated 39%) adding: content/License Plates/car_159.txt (deflated 29%) adding: content/License Plates/car_174.jpeg (deflated 1%) adding: content/License Plates/car_41.jpeg (deflated 1%) adding: content/License Plates/car_72.jpeg (deflated 2%) adding: content/License Plates/car_232.jpeg (deflated 1%) adding: content/License Plates/car_234.txt (deflated 28%) adding: content/License Plates/car_69.jpeg (deflated 1%) adding: content/License Plates/car_205.txt (deflated 28%) adding: content/License Plates/car_235.txt (deflated 29%) adding: content/License Plates/car_13.jpeg (deflated 0%) adding: content/License Plates/car_125.txt (deflated 53%) adding: content/License Plates/car_9.txt (deflated 22%) adding: content/License Plates/car_5.txt (deflated 29%) adding: content/License Plates/car_169.txt (deflated 43%) adding: content/License Plates/car_187.jpeg (deflated 1%) adding: content/License Plates/car_137.txt (deflated 38%) adding: content/License Plates/car_6.txt (deflated 31%) adding: content/License Plates/car_122.txt (deflated 15%) adding: content/License Plates/car_75.txt (deflated 36%) adding: content/License Plates/car_18.txt (deflated 32%) adding: content/License Plates/car_17.txt (deflated 29%) adding: content/License Plates/car_148.jpeg (deflated 1%) adding: content/License Plates/car_83.jpeg (deflated 1%) adding: content/License Plates/car_207.txt (deflated 28%) adding: content/License Plates/car_31.txt (deflated 28%) adding: content/License Plates/car_119.jpeg (deflated 3%) adding: content/License Plates/car_54.txt (deflated 16%) adding: content/License Plates/car_171.jpeg (deflated 3%) adding: content/License Plates/car_80.jpeg (deflated 1%) adding: content/License Plates/car_191.txt (deflated 42%) adding: content/License Plates/car_103.jpeg (deflated 6%) adding: content/License Plates/car_118.jpeg (deflated 8%) adding: content/License Plates/car_160.txt (deflated 28%) adding: content/License Plates/car_12.txt (deflated 33%) adding: content/License Plates/car_187.txt (deflated 52%) adding: content/License Plates/car_183.jpeg (deflated 0%) adding: content/License Plates/car_191.jpeg (deflated 0%) adding: content/License Plates/car_143.jpeg (deflated 1%) adding: content/License Plates/car_7.txt (deflated 36%) adding: content/License Plates/car_11.txt (deflated 23%) adding: content/License Plates/car_149.jpeg (deflated 1%) adding: content/License Plates/car_158.txt (deflated 14%) adding: content/License Plates/car_138.jpeg (deflated 1%) adding: content/License Plates/car_92.jpeg (deflated 1%) adding: content/License Plates/car_13.txt (deflated 37%) adding: content/License Plates/car_47.jpeg (deflated 0%) adding: content/License Plates/car_35.jpeg (deflated 0%) adding: content/License Plates/car_94.txt (deflated 36%) adding: content/License Plates/car_135.jpeg (deflated 0%) adding: content/License Plates/car_223.jpeg (deflated 1%) adding: content/License Plates/car_137.jpeg (deflated 0%) adding: content/License Plates/car_214.jpeg (deflated 1%) adding: content/License Plates/car_63.jpeg (deflated 1%) adding: content/License Plates/car_87.jpeg (deflated 1%) adding: content/License Plates/car_57.jpeg (deflated 0%) adding: content/License Plates/car_220.txt (deflated 37%) adding: content/License Plates/car_6.jpeg (deflated 1%) adding: content/License Plates/car_144.jpeg (deflated 1%) adding: content/License Plates/car_156.txt (deflated 30%) adding: content/License Plates/car_82.txt (deflated 29%) adding: content/License Plates/car_229.txt (deflated 35%) adding: content/License Plates/car_204.jpeg (deflated 2%) adding: content/License Plates/car_176.txt (deflated 53%) adding: content/License Plates/car_43.jpeg (deflated 2%) adding: content/License Plates/car_3.jpeg (deflated 0%) adding: content/License Plates/car_228.txt (deflated 29%) adding: content/License Plates/car_73.jpeg (deflated 1%) adding: content/License Plates/car_100.jpeg (deflated 3%) adding: content/License Plates/car_148.txt (deflated 38%) adding: content/License Plates/car_225.txt (deflated 16%) adding: content/License Plates/car_81.jpeg (deflated 1%) adding: content/License Plates/car_94.jpeg (deflated 1%) adding: content/License Plates/car_112.jpeg (deflated 1%) adding: content/License Plates/car_157.jpeg (deflated 1%) adding: content/License Plates/car_74.txt (deflated 25%) adding: content/License Plates/car_143.txt (deflated 32%) adding: content/License Plates/car_80.txt (deflated 29%) adding: content/License Plates/car_207.jpeg (deflated 2%) adding: content/License Plates/car_95.jpeg (deflated 1%) adding: content/License Plates/car_18.jpeg (deflated 1%) adding: content/License Plates/car_50.txt (deflated 42%) adding: content/License Plates/car_218.txt (deflated 19%) adding: content/License Plates/car_201.jpeg (deflated 1%) adding: content/License Plates/car_216.txt (deflated 47%) adding: content/License Plates/car_111.txt (deflated 48%) adding: content/License Plates/car_49.jpeg (deflated 1%) adding: content/License Plates/car_144.txt (deflated 38%) adding: content/License Plates/car_134.txt (deflated 28%) adding: content/License Plates/car_232.txt (deflated 36%) adding: content/License Plates/car_130.jpeg (deflated 8%) adding: content/License Plates/car_96.jpeg (deflated 12%) adding: content/License Plates/car_222.txt (deflated 59%) adding: content/License Plates/car_22.txt (deflated 28%) adding: content/License Plates/car_159.jpeg (deflated 0%) adding: content/License Plates/car_30.txt (deflated 29%) adding: content/License Plates/car_55.jpeg (deflated 1%) adding: content/License Plates/car_182.txt (deflated 29%) adding: content/License Plates/car_160.jpeg (deflated 0%) adding: content/License Plates/car_9.jpeg (deflated 0%) adding: content/License Plates/car_170.txt (deflated 34%) adding: content/License Plates/car_1.txt (deflated 28%) adding: content/License Plates/car_213.jpeg (deflated 2%) adding: content/License Plates/car_112.txt (deflated 35%) adding: content/License Plates/car_98.txt (deflated 28%) adding: content/License Plates/car_210.jpeg (deflated 1%) adding: content/License Plates/car_230.jpeg (deflated 1%) adding: content/License Plates/car_128.jpeg (deflated 1%) adding: content/License Plates/car_233.jpeg (deflated 1%) adding: content/License Plates/car_61.txt (deflated 37%) adding: content/License Plates/car_21.txt (deflated 32%) adding: content/License Plates/car_166.txt (deflated 48%) adding: content/License Plates/car_104.jpeg (deflated 1%) adding: content/License Plates/car_16.txt (deflated 31%) adding: content/License Plates/car_4.txt (deflated 29%) adding: content/License Plates/car_37.txt (deflated 32%) adding: content/License Plates/car_210.txt (deflated 28%) adding: content/License Plates/car_102.jpeg (deflated 1%) adding: content/License Plates/car_61.jpeg (deflated 1%) adding: content/License Plates/car_227.txt (deflated 30%) adding: content/License Plates/car_50.jpeg (deflated 0%) adding: content/License Plates/car_0.jpeg (deflated 0%) adding: content/License Plates/car_224.txt (deflated 34%) adding: content/License Plates/car_219.txt (deflated 30%) adding: content/License Plates/car_182.jpeg (deflated 0%) adding: content/License Plates/car_45.txt (deflated 31%) adding: content/License Plates/car_51.txt (deflated 27%) adding: content/License Plates/car_153.txt (deflated 30%) adding: content/License Plates/car_56.jpeg (deflated 1%) adding: content/License Plates/car_108.txt (deflated 33%) adding: content/License Plates/car_147.txt (deflated 14%) adding: content/License Plates/car_189.jpeg (deflated 10%) adding: content/License Plates/car_104.txt (deflated 37%) adding: content/License Plates/car_154.txt (deflated 29%) adding: content/License Plates/car_55.txt (deflated 27%) adding: content/License Plates/car_223.txt (deflated 38%) adding: content/License Plates/car_19.jpeg (deflated 3%) adding: content/License Plates/car_231.txt (deflated 30%) adding: content/License Plates/car_1.jpeg (deflated 1%) adding: content/License Plates/car_172.jpeg (deflated 2%) adding: content/License Plates/car_233.txt (deflated 42%) adding: content/License Plates/car_135.txt (deflated 35%) adding: content/License Plates/car_47.txt (deflated 30%) adding: content/License Plates/car_62.txt (deflated 14%) adding: content/License Plates/car_203.jpeg (deflated 0%) adding: content/License Plates/car_70.txt (deflated 32%) adding: content/License Plates/car_162.txt (deflated 49%) adding: content/License Plates/car_147.jpeg (deflated 1%) adding: content/License Plates/car_46.jpeg (deflated 1%) adding: content/License Plates/car_205.jpeg (deflated 1%) adding: content/License Plates/car_29.jpeg (deflated 8%) adding: content/License Plates/car_165.jpeg (deflated 1%) adding: content/License Plates/car_53.jpeg (deflated 1%) adding: content/License Plates/car_215.jpeg (deflated 1%) adding: content/License Plates/car_40.txt (deflated 30%) adding: content/License Plates/car_138.txt (deflated 37%) adding: content/License Plates/car_24.jpeg (deflated 1%) adding: content/License Plates/car_127.jpeg (deflated 1%) adding: content/License Plates/car_178.jpeg (deflated 0%) adding: content/License Plates/car_151.jpeg (deflated 2%) adding: content/License Plates/car_58.jpeg (deflated 0%) adding: content/License Plates/car_109.jpeg (deflated 2%) adding: content/License Plates/car_208.jpeg (deflated 1%) adding: content/License Plates/car_8.jpeg (deflated 0%) adding: content/License Plates/car_42.jpeg (deflated 1%) adding: content/License Plates/car_52.txt (deflated 29%) adding: content/License Plates/car_215.txt (deflated 29%) adding: content/License Plates/car_214.txt (deflated 27%) adding: content/License Plates/car_165.txt (deflated 44%) adding: content/License Plates/car_85.txt (deflated 16%) adding: content/License Plates/car_81.txt (deflated 44%) adding: content/License Plates/car_5.jpeg (deflated 1%) adding: content/License Plates/car_194.txt (deflated 53%) adding: content/License Plates/car_169.jpeg (deflated 1%) adding: content/License Plates/car_113.txt (deflated 25%) adding: content/License Plates/car_44.txt (deflated 45%) adding: content/License Plates/car_188.txt (deflated 29%) adding: content/License Plates/car_164.txt (deflated 32%) adding: content/License Plates/car_75.jpeg (deflated 1%) adding: content/License Plates/car_206.jpeg (deflated 0%) adding: content/License Plates/car_141.jpeg (deflated 1%) adding: content/License Plates/car_32.txt (deflated 28%) adding: content/License Plates/car_49.txt (deflated 24%) adding: content/License Plates/car_125.jpeg (deflated 1%) adding: content/License Plates/car_71.jpeg (deflated 1%) adding: content/License Plates/car_65.txt (deflated 13%) adding: content/License Plates/car_56.txt (deflated 22%) adding: content/License Plates/car_106.txt (deflated 49%) adding: content/License Plates/car_236.jpeg (deflated 2%) adding: content/License Plates/car_52.jpeg (deflated 0%) adding: content/License Plates/car_170.jpeg (deflated 0%) adding: content/License Plates/car_236.txt (deflated 29%) adding: content/License Plates/car_36.jpeg (deflated 1%) adding: content/License Plates/car_185.jpeg (deflated 0%) adding: content/License Plates/car_119.txt (deflated 50%) adding: content/License Plates/car_35.txt (deflated 32%) adding: content/License Plates/car_27.txt (deflated 12%) adding: content/License Plates/car_132.txt (deflated 35%) adding: content/License Plates/car_226.txt (deflated 28%) adding: content/License Plates/car_161.txt (deflated 34%) adding: content/License Plates/car_23.txt (deflated 26%) adding: content/License Plates/car_78.txt (deflated 33%) adding: content/License Plates/car_149.txt (deflated 34%) adding: content/License Plates/car_163.txt (deflated 35%) adding: content/License Plates/car_221.txt (deflated 46%) adding: content/License Plates/car_79.txt (deflated 20%) adding: content/License Plates/car_179.txt (deflated 30%) adding: content/License Plates/car_96.txt (deflated 47%) adding: content/License Plates/car_12.jpeg (deflated 1%) adding: content/License Plates/car_195.jpeg (deflated 2%) adding: content/License Plates/car_68.jpeg (deflated 1%) adding: content/License Plates/car_30.jpeg (deflated 1%) adding: content/License Plates/car_88.jpeg (deflated 1%) adding: content/License Plates/car_189.txt (deflated 28%) adding: content/License Plates/car_198.jpeg (deflated 0%) adding: content/License Plates/car_155.jpeg (deflated 1%) adding: content/License Plates/car_67.txt (deflated 26%) adding: content/License Plates/car_107.jpeg (deflated 24%) adding: content/License Plates/car_184.jpeg (deflated 1%) adding: content/License Plates/car_28.txt (deflated 29%) adding: content/License Plates/car_136.txt (deflated 25%) adding: content/License Plates/car_153.jpeg (deflated 1%) adding: content/License Plates/car_98.jpeg (deflated 4%) adding: content/License Plates/car_63.txt (deflated 50%) adding: content/License Plates/car_88.txt (deflated 30%) adding: content/License Plates/car_222.jpeg (deflated 1%) adding: content/License Plates/car_218.jpeg (deflated 1%) adding: content/License Plates/car_171.txt (deflated 29%) adding: content/License Plates/car_200.jpeg (deflated 0%) adding: content/License Plates/car_85.jpeg (deflated 1%) adding: content/License Plates/car_133.jpeg (deflated 0%) adding: content/License Plates/car_93.txt (deflated 32%) adding: content/License Plates/car_67.jpeg (deflated 3%) adding: content/License Plates/car_17.jpeg (deflated 1%) adding: content/License Plates/car_225.jpeg (deflated 2%) adding: content/License Plates/car_115.jpeg (deflated 0%) adding: content/License Plates/car_54.jpeg (deflated 1%) adding: content/License Plates/car_184.txt (deflated 39%) adding: content/License Plates/car_92.txt (deflated 31%) adding: content/License Plates/car_226.jpeg (deflated 1%) adding: content/License Plates/car_150.jpeg (deflated 1%) adding: content/License Plates/car_139.txt (deflated 31%) adding: content/License Plates/car_4.jpeg (deflated 1%) adding: content/License Plates/car_121.jpeg (deflated 1%) adding: content/License Plates/car_108.jpeg (deflated 5%) adding: content/License Plates/car_110.jpeg (deflated 0%) adding: content/License Plates/car_79.jpeg (deflated 1%) adding: content/License Plates/car_53.txt (deflated 35%) adding: content/License Plates/car_124.txt (deflated 47%) adding: content/License Plates/car_78.jpeg (deflated 1%) adding: content/License Plates/car_201.txt (deflated 31%) adding: content/License Plates/car_176.jpeg (deflated 2%) adding: content/License Plates/car_101.jpeg (deflated 3%) adding: content/License Plates/car_208.txt (deflated 15%) adding: content/License Plates/car_64.jpeg (deflated 1%) adding: content/License Plates/car_196.jpeg (deflated 0%) adding: content/License Plates/car_202.jpeg (deflated 2%) adding: content/License Plates/car_133.txt (deflated 26%) adding: content/License Plates/car_151.txt (deflated 38%) adding: content/License Plates/car_194.jpeg (deflated 1%) adding: content/License Plates/car_212.jpeg (deflated 1%) adding: content/License Plates/car_203.txt (deflated 40%) adding: content/License Plates/car_130.txt (deflated 16%) adding: content/License Plates/car_120.jpeg (deflated 1%) adding: content/License Plates/car_166.jpeg (deflated 2%) adding: content/License Plates/car_99.jpeg (deflated 0%) adding: content/License Plates/car_72.txt (deflated 37%) adding: content/License Plates/car_229.jpeg (deflated 1%) adding: content/License Plates/car_142.txt (deflated 32%) adding: content/License Plates/car_136.jpeg (deflated 1%) adding: content/License Plates/car_197.jpeg (deflated 1%) adding: content/License Plates/car_3.txt (deflated 16%) os.getcwd() '/root/darknet' cd ~ /root cd /content /content import random x = list(licenses['name']) random.shuffle(x) f = open('./train.txt','w+') y = open('./val.txt','w+') for i in range(len(x)): if i % 10 ==0: y.write('/darknet/data/obj/'+x[i]+'\n') else: f.write('/darknet/data/obj/'+x[i]+'\n') y.close() f.close() files.download('./train.txt') files.download('./val.txt') The following repository is an end to end detection and recognition of Indian license plates using YOLO v3 Darknet and Pytesseract. It serves as a precursor for our project. This is a fun individual project on its own! Creating folder structure In the data/images folder ,create two folder namely, train and valid The train folder consists of 201 images obtained from Step 2. These are to be used for training The valid folder consists of 36 images obtained from Step 2, which are to be used for validation Only images won’t do for detection as we need labels for bounding boxes and classes for each image. The YOLO format for a single class bounding box label is as follows: class_number x y width height The labels are already obtained from Step 2. The labels folder consists of a train and valid folder consisting of labels for training and validation images respectively. A sample label Next, we create the data/train.txt file To get the contents of this file, simply write the following in command prompt or terminal. Make sure you are in the anpr_yolov5 directory D:>git clone https://github.com/sid0312/anpr_yolov5cd anpr_yolov5python>>import os>>for image in os.list('data/images/train'): path = 'D:/anpr_yolov5/data/images/train' print(path+'/'+image) You will get the following output Copy the output to a file data/train.txt Do the same for valid.txt If you intend to train Yolo v5 on Google Colab, commit the repository in its present state without copying the contents above. Commit and push the current state of your repository to GitHub. git add . git commit -m"some msg"git push Now follow the following notebook and copy the contents of the print logs to the files data/train.txt and data/val.txt respectively Change the nc parameter in yolov5s.yaml to 1 Repeat the git add,commit,push process again Check out the following notebook for the training process github.com Note: You can use yolo5s.pt weights too. I have used randomly initialized weights and trained the model for 100 epochs. After running for 100 epochs, we get Precision as 0.659 Recall as 0.972 [email protected] as 0.978 [email protected] with 95% confidence as 0.471 https://blog.roboflow.ai https://github.com/ultralyitcs/yolov5 In case, you have skipped the training part and jumped right to the conclusion, I have something more for you. After finding the region of interest of the license plate, we can use it for character recognition using pytesseract I have done it for a previous project. You can check it out at: github.com If you’re into reading more about Object Detection Algorithms and Libraries, I highly recommend this blog by neptune.ai neptune.ai If you’re into my articles, check these out! towardsdatascience.com towardsdatascience.com towardsdatascience.com If you wish to connect with me on Linkedin, here’s my profile www.linkedin.com Happy Computer Vision and Happy Deep Learning ❤.
[ { "code": null, "e": 343, "s": 172, "text": "To the ones who not might be knowing, a new version of YOLO (You Only Look Once) is here, namely YOLO v5. Many thanks to Ultralytics for putting this repository together." }, { "code": null, "e": 518, "s": 343, "text": "You only look once (YOLO) is a state-of-the-art, real-time object detection system. On a Pascal Titan X it processes images at 30 FPS and has a mAP of 57.9% on COCO test-dev." }, { "code": null, "e": 764, "s": 518, "text": "YOLOv3 is extremely fast and accurate. In mAP measured at .5 IOU YOLOv3 is on par with Focal Loss but about 4x faster. Moreover, you can easily tradeoff between speed and accuracy simply by changing the size of the model, no retraining required!" }, { "code": null, "e": 1005, "s": 764, "text": "YOLOv3 has a problem though, despite being so accurate, it is biased. The bias is towards the size of the object in the image. If encountered with bigger objects while training, it cannot detect the same object of a smaller scale perfectly." }, { "code": null, "e": 1516, "s": 1005, "text": "YOLOv3 detects features in images and learn how to recognize objects with this information. Layers near the start detecting really simple features like edges and layers that are deeper can detect more complex features like eyes, noses, or an entire face. It then uses all of these features which it has learned, to make a final prediction. Herein lies the flaws of this system — there is no spatial that is used anywhere in a CNN and the pooling function that is used to connect layers is rendered inefficient." }, { "code": null, "e": 1523, "s": 1516, "text": "YOLOv5" }, { "code": null, "e": 1556, "s": 1523, "text": "YOLOv5 consists of three parts :" }, { "code": null, "e": 1591, "s": 1556, "text": "Model BackboneModel headModel neck" }, { "code": null, "e": 1606, "s": 1591, "text": "Model Backbone" }, { "code": null, "e": 1617, "s": 1606, "text": "Model head" }, { "code": null, "e": 1628, "s": 1617, "text": "Model neck" }, { "code": null, "e": 2007, "s": 1628, "text": "The model head helps in the process of feature extraction. The model backbone consists of CSP Nets which help extract essential features from tensor passed through the model head. CSPNets enable quicker inference as well. The tensor from the model backbone is passed through the model neck which has feature pyramids, which try to eliminate bias with respect to size of objects." }, { "code": null, "e": 2059, "s": 2007, "text": "To know more about feature pyramids, check this out" }, { "code": null, "e": 2069, "s": 2059, "text": "arxiv.org" }, { "code": null, "e": 2112, "s": 2069, "text": "To know more about YOLOv5, check this out." }, { "code": null, "e": 2129, "s": 2112, "text": "blog.roboflow.ai" }, { "code": null, "e": 2165, "s": 2129, "text": "Check out the YOLO v5 repository at" }, { "code": null, "e": 2176, "s": 2165, "text": "github.com" }, { "code": null, "e": 2233, "s": 2176, "text": "For our use case, I have created a similar repository at" }, { "code": null, "e": 2244, "s": 2233, "text": "github.com" }, { "code": null, "e": 2307, "s": 2244, "text": "git clone https://github.com/sid0312/anpr_yolov5cd anpr_yolov5" }, { "code": null, "e": 2426, "s": 2307, "text": "To detect a license plate in the car image, save it in the sample_cars folder of the directory. Name it as example.jpg" }, { "code": null, "e": 2514, "s": 2426, "text": "python detect.py --source sample_cars/example.jpg --weights weights/best.pt --conf 0.4" }, { "code": null, "e": 2649, "s": 2514, "text": "Get the final image in the inference/output directory . To get an intuition of the detection process, check out the following notebook" }, { "code": null, "e": 2700, "s": 2649, "text": "!git clone https://github.com/sid0312/anpr_yolov5\n" }, { "code": null, "e": 3036, "s": 2700, "text": "Cloning into 'anpr_yolov5'...\nremote: Enumerating objects: 42, done.\nremote: Counting objects: 100% (42/42), done.\nremote: Compressing objects: 100% (39/39), done.\nremote: Total 611 (delta 19), reused 15 (delta 3), pack-reused 569\nReceiving objects: 100% (611/611), 63.42 MiB | 25.97 MiB/s, done.\nResolving deltas: 100% (46/46), done.\n" }, { "code": null, "e": 3054, "s": 3036, "text": "%cd anpr_yolov5/\n" }, { "code": null, "e": 3076, "s": 3054, "text": "/content/anpr_yolov5\n" }, { "code": null, "e": 3155, "s": 3076, "text": "!python detect.py --source sample_cars/ --weights weights/last.pt --conf 0.4\n" }, { "code": null, "e": 3899, "s": 3155, "text": "Namespace(agnostic_nms=False, augment=False, classes=None, conf_thres=0.4, device='', fourcc='mp4v', img_size=640, iou_thres=0.5, output='inference/output', save_txt=False, source='sample_cars/', view_img=False, weights='weights/last.pt')\nUsing CUDA device0 _CudaDeviceProperties(name='Tesla K80', total_memory=11441MB)\n\nimage 1/5 sample_cars/car_0.jpg: 448x640 1 license_plates, Done. (0.056s)\nimage 2/5 sample_cars/car_1.jpg: 384x640 Done. (0.025s)\nimage 3/5 sample_cars/car_2.jpg: 512x640 1 license_plates, Done. (0.028s)\nimage 4/5 sample_cars/car_3.jpg: 448x640 1 license_plates, Done. (0.027s)\nimage 5/5 sample_cars/car_4.jpg: 512x640 2 license_plates, Done. (0.028s)\nResults saved to /content/anpr_yolov5/inference/output\nDone. (0.785s)\n" }, { "code": null, "e": 3969, "s": 3899, "text": "import os\nprint(os.listdir('/content/anpr_yolov5/inference/output'))\n" }, { "code": null, "e": 4036, "s": 3969, "text": "['car_0.jpg', 'car_1.jpg', 'car_3.jpg', 'car_2.jpg', 'car_4.jpg']\n" }, { "code": null, "e": 4068, "s": 4036, "text": "from google.colab import files\n" }, { "code": null, "e": 4223, "s": 4068, "text": "for img in os.listdir('/content/anpr_yolov5/inference/output'):\n path = os.path.join('/content/anpr_yolov5/inference/output',img)\n files.download(path)\n" }, { "code": null, "e": 4248, "s": 4226, "text": "Here are some results" }, { "code": null, "e": 4334, "s": 4248, "text": "This repository included the following changes to the original utlralytics repository" }, { "code": null, "e": 4366, "s": 4334, "text": "Created data/license_plate.yaml" }, { "code": null, "e": 4383, "s": 4366, "text": "Data Preparation" }, { "code": null, "e": 4440, "s": 4383, "text": "Step 1- Download the starter dataset in JSON format from" }, { "code": null, "e": 4455, "s": 4440, "text": "www.kaggle.com" }, { "code": null, "e": 4534, "s": 4455, "text": "This serves as our starting dataset. Upload the JSON file to your Google Drive" }, { "code": null, "e": 4596, "s": 4534, "text": "Step 2- Conversion of the JSON starter dataset to YOLO format" }, { "code": null, "e": 4658, "s": 4596, "text": "from google.colab import drive\ndrive.mount('/content/drive')\n" }, { "code": null, "e": 4788, "s": 4658, "text": "Drive already mounted at /content/drive; to attempt to forcibly remount, call drive.mount(\"/content/drive\", force_remount=True).\n" }, { "code": null, "e": 4927, "s": 4788, "text": "import pandas as pd\nimport numpy as np\nimport urllib\nimport matplotlib.pyplot as plt\nimport cv2\nimport glob,os,time\nfrom PIL import Image\n" }, { "code": null, "e": 4992, "s": 4927, "text": "json_path = '/content/drive/My Drive/Indian_Number_plates.json'\n" }, { "code": null, "e": 5035, "s": 4992, "text": "data = pd.read_json(json_path,lines=True)\n" }, { "code": null, "e": 5048, "s": 5035, "text": "data.head()\n" }, { "code": null, "e": 5076, "s": 5048, "text": "os.mkdir('License Plates')\n" }, { "code": null, "e": 5099, "s": 5076, "text": "data['annotation'][0]\n" }, { "code": null, "e": 5306, "s": 5099, "text": "[{'imageHeight': 466,\n 'imageWidth': 806,\n 'label': ['number_plate'],\n 'notes': '',\n 'points': [{'x': 0.722084367245657, 'y': 0.5879828326180251},\n {'x': 0.8684863523573201, 'y': 0.688841201716738}]}]" }, { "code": null, "e": 5324, "s": 5306, "text": "print(len(data))\n" }, { "code": null, "e": 5329, "s": 5324, "text": "237\n" }, { "code": null, "e": 6373, "s": 5329, "text": "dataset = {}\nvals = ['name','height','width','top_x','top_y','bottom_x','bottom_y']\nfor i in vals:\n dataset[i] = list()\ncount = 0\nfor idx,row in data.iterrows():\n img = urllib.request.urlopen(row[\"content\"])\n img = Image.open(img)\n img = img.convert('RGB')\n img.save(\"/content/License Plates/car_{}.jpeg\".format(count),'JPEG')\n dataset['name'].append('car_{}'.format(count))\n annotation = row['annotation']\n dataset['height'].append(annotation[0]['imageHeight'])\n dataset['width'].append(annotation[0]['imageWidth'])\n dataset['top_x'].append(annotation[0]['points'][0]['x'])\n dataset['top_y'].append(annotation[0]['points'][0]['y'])\n dataset['bottom_x'].append(annotation[0]['points'][1]['x'])\n dataset['bottom_y'].append(annotation[0]['points'][1]['y']) \n count =count+1\n if count%10==0:\n print('Downloaded.. {}/{}'.format(count,len(data))) \n if count%len(data)==0:\n print('Loading last image.. {}/{}'.format(count,len(data))) \nprint('{} images downloaded'.format(count)) \n" }, { "code": null, "e": 6899, "s": 6373, "text": "Downloaded.. 10/237\nDownloaded.. 20/237\nDownloaded.. 30/237\nDownloaded.. 40/237\nDownloaded.. 50/237\nDownloaded.. 60/237\nDownloaded.. 70/237\nDownloaded.. 80/237\nDownloaded.. 90/237\nDownloaded.. 100/237\nDownloaded.. 110/237\nDownloaded.. 120/237\nDownloaded.. 130/237\nDownloaded.. 140/237\nDownloaded.. 150/237\nDownloaded.. 160/237\nDownloaded.. 170/237\nDownloaded.. 180/237\nDownloaded.. 190/237\nDownloaded.. 200/237\nDownloaded.. 210/237\nDownloaded.. 220/237\nDownloaded.. 230/237\nLoading last image.. 237/237\n237 images downloaded\n" }, { "code": null, "e": 6927, "s": 6899, "text": "df = pd.DataFrame(dataset)\n" }, { "code": null, "e": 6938, "s": 6927, "text": "df.head()\n" }, { "code": null, "e": 6983, "s": 6938, "text": "df.to_csv('license_plates.csv',index=False)\n" }, { "code": null, "e": 7025, "s": 6983, "text": "csv_path = '/content/license_plates.csv'\n" }, { "code": null, "e": 7075, "s": 7025, "text": "licenses = pd.read_csv(csv_path)\nlicenses.tail()\n" }, { "code": null, "e": 7122, "s": 7075, "text": "licenses['name'] = licenses['name'] + '.jpeg'\n" }, { "code": null, "e": 7139, "s": 7122, "text": "licenses.head()\n" }, { "code": null, "e": 7195, "s": 7139, "text": "licenses.drop(columns=['height','width'],inplace=True)\n" }, { "code": null, "e": 7212, "s": 7195, "text": "licenses.head()\n" }, { "code": null, "e": 7680, "s": 7212, "text": "widths,heights =[],[]\ncenter_x,center_y=[],[]\nfor i in range(len(licenses)):\n widths.append(licenses['bottom_x'][i]- licenses['top_x'][i])\n heights.append(licenses['bottom_y'][i]- licenses['top_y'][i])\n center_x.append((licenses['bottom_x'][i] + licenses['top_x'][i])/2)\n center_y.append((licenses['bottom_y'][i] + licenses['top_y'][i])/2)\nlic = pd.DataFrame(columns=['x','y','w','h'])\nlic['w'] = widths\nlic['h'] = heights\nlic['x'] = center_x\nlic['y'] = center_y\n" }, { "code": null, "e": 7692, "s": 7680, "text": "lic.head()\n" }, { "code": null, "e": 7881, "s": 7692, "text": "for i in range(len(lic)):\n f = open('/content/License Plates/car_{}.txt'.format(i),'w+')\n f.write('{} {} {} {} {}'.format(0,lic['x'][i],lic['y'][i],lic['w'][i],lic['h'][i]))\n f.close()\n" }, { "code": null, "e": 8003, "s": 7884, "text": "!zip -r /content/file.zip /content/License\\ Plates\nfrom google.colab import files\nfiles.download(\"/content/file.zip\")\n" }, { "code": null, "e": 36273, "s": 8003, "text": " adding: content/License Plates/ (stored 0%)\n adding: content/License Plates/car_86.jpeg (deflated 1%)\n adding: content/License Plates/car_83.txt (deflated 27%)\n adding: content/License Plates/car_64.txt (deflated 28%)\n adding: content/License Plates/car_154.jpeg (deflated 1%)\n adding: content/License Plates/car_21.jpeg (deflated 1%)\n adding: content/License Plates/car_209.jpeg (deflated 1%)\n adding: content/License Plates/car_217.txt (deflated 37%)\n adding: content/License Plates/car_190.jpeg (deflated 2%)\n adding: content/License Plates/car_91.jpeg (deflated 1%)\n adding: content/License Plates/car_23.jpeg (deflated 0%)\n adding: content/License Plates/car_102.txt (deflated 29%)\n adding: content/License Plates/car_228.jpeg (deflated 1%)\n adding: content/License Plates/car_231.jpeg (deflated 2%)\n adding: content/License Plates/car_46.txt (deflated 27%)\n adding: content/License Plates/car_199.jpeg (deflated 0%)\n adding: content/License Plates/car_163.jpeg (deflated 1%)\n adding: content/License Plates/car_40.jpeg (deflated 0%)\n adding: content/License Plates/car_43.txt (deflated 29%)\n adding: content/License Plates/car_38.jpeg (deflated 1%)\n adding: content/License Plates/car_93.jpeg (deflated 1%)\n adding: content/License Plates/car_227.jpeg (deflated 1%)\n adding: content/License Plates/car_204.txt (deflated 38%)\n adding: content/License Plates/car_106.jpeg (deflated 1%)\n adding: content/License Plates/car_152.txt (deflated 32%)\n adding: content/License Plates/car_221.jpeg (deflated 0%)\n adding: content/License Plates/car_212.txt (deflated 37%)\n adding: content/License Plates/car_60.jpeg (deflated 1%)\n adding: content/License Plates/car_39.txt (deflated 56%)\n adding: content/License Plates/car_126.jpeg (deflated 0%)\n adding: content/License Plates/car_213.txt (deflated 30%)\n adding: content/License Plates/car_181.txt (deflated 34%)\n adding: content/License Plates/car_198.txt (deflated 36%)\n adding: content/License Plates/car_156.jpeg (deflated 0%)\n adding: content/License Plates/car_178.txt (deflated 30%)\n adding: content/License Plates/car_68.txt (deflated 32%)\n adding: content/License Plates/car_82.jpeg (deflated 1%)\n adding: content/License Plates/car_217.jpeg (deflated 1%)\n adding: content/License Plates/car_224.jpeg (deflated 3%)\n adding: content/License Plates/car_216.jpeg (deflated 0%)\n adding: content/License Plates/car_141.txt (deflated 33%)\n adding: content/License Plates/car_101.txt (deflated 32%)\n adding: content/License Plates/car_174.txt (deflated 47%)\n adding: content/License Plates/car_2.txt (deflated 29%)\n adding: content/License Plates/car_39.jpeg (deflated 2%)\n adding: content/License Plates/car_220.jpeg (deflated 1%)\n adding: content/License Plates/car_26.jpeg (deflated 2%)\n adding: content/License Plates/car_200.txt (deflated 30%)\n adding: content/License Plates/car_129.txt (deflated 45%)\n adding: content/License Plates/car_202.txt (deflated 52%)\n adding: content/License Plates/car_186.jpeg (deflated 1%)\n adding: content/License Plates/car_27.jpeg (deflated 1%)\n adding: content/License Plates/car_19.txt (deflated 27%)\n adding: content/License Plates/car_110.txt (deflated 53%)\n adding: content/License Plates/car_196.txt (deflated 22%)\n adding: content/License Plates/car_20.jpeg (deflated 1%)\n adding: content/License Plates/car_145.txt (deflated 45%)\n adding: content/License Plates/car_164.jpeg (deflated 0%)\n adding: content/License Plates/car_14.jpeg (deflated 1%)\n adding: content/License Plates/car_142.jpeg (deflated 1%)\n adding: content/License Plates/car_86.txt (deflated 31%)\n adding: content/License Plates/car_190.txt (deflated 32%)\n adding: content/License Plates/car_146.jpeg (deflated 1%)\n adding: content/License Plates/car_139.jpeg (deflated 1%)\n adding: content/License Plates/car_91.txt (deflated 36%)\n adding: content/License Plates/car_59.jpeg (deflated 2%)\n adding: content/License Plates/car_155.txt (deflated 42%)\n adding: content/License Plates/car_116.jpeg (deflated 1%)\n adding: content/License Plates/car_192.txt (deflated 27%)\n adding: content/License Plates/car_34.jpeg (deflated 0%)\n adding: content/License Plates/car_36.txt (deflated 47%)\n adding: content/License Plates/car_31.jpeg (deflated 2%)\n adding: content/License Plates/car_122.jpeg (deflated 2%)\n adding: content/License Plates/car_120.txt (deflated 33%)\n adding: content/License Plates/car_59.txt (deflated 29%)\n adding: content/License Plates/car_150.txt (deflated 28%)\n adding: content/License Plates/car_69.txt (deflated 32%)\n adding: content/License Plates/car_51.jpeg (deflated 0%)\n adding: content/License Plates/car_90.jpeg (deflated 1%)\n adding: content/License Plates/car_44.jpeg (deflated 1%)\n adding: content/License Plates/car_128.txt (deflated 28%)\n adding: content/License Plates/car_199.txt (deflated 47%)\n adding: content/License Plates/car_87.txt (deflated 29%)\n adding: content/License Plates/car_186.txt (deflated 38%)\n adding: content/License Plates/car_99.txt (deflated 27%)\n adding: content/License Plates/car_97.jpeg (deflated 2%)\n adding: content/License Plates/car_37.jpeg (deflated 1%)\n adding: content/License Plates/car_193.txt (deflated 46%)\n adding: content/License Plates/car_117.txt (deflated 56%)\n adding: content/License Plates/car_124.jpeg (deflated 1%)\n adding: content/License Plates/car_73.txt (deflated 29%)\n adding: content/License Plates/car_121.txt (deflated 28%)\n adding: content/License Plates/car_33.jpeg (deflated 0%)\n adding: content/License Plates/car_100.txt (deflated 27%)\n adding: content/License Plates/car_109.txt (deflated 28%)\n adding: content/License Plates/car_90.txt (deflated 33%)\n adding: content/License Plates/car_157.txt (deflated 28%)\n adding: content/License Plates/car_65.jpeg (deflated 2%)\n adding: content/License Plates/car_111.jpeg (deflated 0%)\n adding: content/License Plates/car_211.txt (deflated 13%)\n adding: content/License Plates/car_134.jpeg (deflated 1%)\n adding: content/License Plates/car_20.txt (deflated 35%)\n adding: content/License Plates/car_197.txt (deflated 49%)\n adding: content/License Plates/car_25.jpeg (deflated 0%)\n adding: content/License Plates/car_219.jpeg (deflated 1%)\n adding: content/License Plates/car_29.txt (deflated 34%)\n adding: content/License Plates/car_152.jpeg (deflated 1%)\n adding: content/License Plates/car_167.jpeg (deflated 0%)\n adding: content/License Plates/car_89.txt (deflated 29%)\n adding: content/License Plates/car_62.jpeg (deflated 2%)\n adding: content/License Plates/car_58.txt (deflated 34%)\n adding: content/License Plates/car_0.txt (deflated 30%)\n adding: content/License Plates/car_105.txt (deflated 38%)\n adding: content/License Plates/car_60.txt (deflated 29%)\n adding: content/License Plates/car_235.jpeg (deflated 0%)\n adding: content/License Plates/car_177.jpeg (deflated 1%)\n adding: content/License Plates/car_2.jpeg (deflated 1%)\n adding: content/License Plates/car_131.jpeg (deflated 1%)\n adding: content/License Plates/car_15.txt (deflated 29%)\n adding: content/License Plates/car_70.jpeg (deflated 1%)\n adding: content/License Plates/car_97.txt (deflated 40%)\n adding: content/License Plates/car_95.txt (deflated 28%)\n adding: content/License Plates/car_146.txt (deflated 35%)\n adding: content/License Plates/car_8.txt (deflated 29%)\n adding: content/License Plates/car_173.jpeg (deflated 1%)\n adding: content/License Plates/car_42.txt (deflated 38%)\n adding: content/License Plates/car_175.jpeg (deflated 6%)\n adding: content/License Plates/car_114.jpeg (deflated 4%)\n adding: content/License Plates/car_77.txt (deflated 28%)\n adding: content/License Plates/car_140.txt (deflated 31%)\n adding: content/License Plates/car_11.jpeg (deflated 0%)\n adding: content/License Plates/car_10.jpeg (deflated 0%)\n adding: content/License Plates/car_123.jpeg (deflated 0%)\n adding: content/License Plates/car_28.jpeg (deflated 0%)\n adding: content/License Plates/car_115.txt (deflated 53%)\n adding: content/License Plates/car_183.txt (deflated 37%)\n adding: content/License Plates/car_114.txt (deflated 34%)\n adding: content/License Plates/car_168.jpeg (deflated 1%)\n adding: content/License Plates/car_7.jpeg (deflated 0%)\n adding: content/License Plates/car_10.txt (deflated 37%)\n adding: content/License Plates/car_167.txt (deflated 38%)\n adding: content/License Plates/car_76.jpeg (deflated 0%)\n adding: content/License Plates/car_185.txt (deflated 30%)\n adding: content/License Plates/car_57.txt (deflated 30%)\n adding: content/License Plates/car_179.jpeg (deflated 1%)\n adding: content/License Plates/car_76.txt (deflated 43%)\n adding: content/License Plates/car_180.jpeg (deflated 1%)\n adding: content/License Plates/car_209.txt (deflated 29%)\n adding: content/License Plates/car_192.jpeg (deflated 1%)\n adding: content/License Plates/car_107.txt (deflated 31%)\n adding: content/License Plates/car_22.jpeg (deflated 0%)\n adding: content/License Plates/car_206.txt (deflated 27%)\n adding: content/License Plates/car_131.txt (deflated 42%)\n adding: content/License Plates/car_14.txt (deflated 16%)\n adding: content/License Plates/car_129.jpeg (deflated 1%)\n adding: content/License Plates/car_66.jpeg (deflated 1%)\n adding: content/License Plates/car_117.jpeg (deflated 0%)\n adding: content/License Plates/car_188.jpeg (deflated 1%)\n adding: content/License Plates/car_211.jpeg (deflated 1%)\n adding: content/License Plates/car_48.txt (deflated 28%)\n adding: content/License Plates/car_234.jpeg (deflated 0%)\n adding: content/License Plates/car_162.jpeg (deflated 3%)\n adding: content/License Plates/car_230.txt (deflated 29%)\n adding: content/License Plates/car_105.jpeg (deflated 2%)\n adding: content/License Plates/car_118.txt (deflated 43%)\n adding: content/License Plates/car_34.txt (deflated 28%)\n adding: content/License Plates/car_127.txt (deflated 29%)\n adding: content/License Plates/car_33.txt (deflated 30%)\n adding: content/License Plates/car_172.txt (deflated 24%)\n adding: content/License Plates/car_71.txt (deflated 28%)\n adding: content/License Plates/car_132.jpeg (deflated 1%)\n adding: content/License Plates/car_25.txt (deflated 40%)\n adding: content/License Plates/car_77.jpeg (deflated 1%)\n adding: content/License Plates/car_84.jpeg (deflated 1%)\n adding: content/License Plates/car_38.txt (deflated 33%)\n adding: content/License Plates/car_103.txt (deflated 29%)\n adding: content/License Plates/car_180.txt (deflated 29%)\n adding: content/License Plates/car_66.txt (deflated 29%)\n adding: content/License Plates/car_193.jpeg (deflated 1%)\n adding: content/License Plates/car_126.txt (deflated 39%)\n adding: content/License Plates/car_123.txt (deflated 38%)\n adding: content/License Plates/car_24.txt (deflated 34%)\n adding: content/License Plates/car_181.jpeg (deflated 0%)\n adding: content/License Plates/car_161.jpeg (deflated 0%)\n adding: content/License Plates/car_15.jpeg (deflated 1%)\n adding: content/License Plates/car_48.jpeg (deflated 1%)\n adding: content/License Plates/car_32.jpeg (deflated 0%)\n adding: content/License Plates/car_158.jpeg (deflated 1%)\n adding: content/License Plates/car_26.txt (deflated 39%)\n adding: content/License Plates/car_195.txt (deflated 29%)\n adding: content/License Plates/car_41.txt (deflated 37%)\n adding: content/License Plates/car_173.txt (deflated 16%)\n adding: content/License Plates/car_89.jpeg (deflated 1%)\n adding: content/License Plates/car_74.jpeg (deflated 1%)\n adding: content/License Plates/car_16.jpeg (deflated 0%)\n adding: content/License Plates/car_113.jpeg (deflated 1%)\n adding: content/License Plates/car_84.txt (deflated 33%)\n adding: content/License Plates/car_45.jpeg (deflated 1%)\n adding: content/License Plates/car_140.jpeg (deflated 1%)\n adding: content/License Plates/car_116.txt (deflated 60%)\n adding: content/License Plates/car_145.jpeg (deflated 0%)\n adding: content/License Plates/car_168.txt (deflated 32%)\n adding: content/License Plates/car_177.txt (deflated 49%)\n adding: content/License Plates/car_175.txt (deflated 39%)\n adding: content/License Plates/car_159.txt (deflated 29%)\n adding: content/License Plates/car_174.jpeg (deflated 1%)\n adding: content/License Plates/car_41.jpeg (deflated 1%)\n adding: content/License Plates/car_72.jpeg (deflated 2%)\n adding: content/License Plates/car_232.jpeg (deflated 1%)\n adding: content/License Plates/car_234.txt (deflated 28%)\n adding: content/License Plates/car_69.jpeg (deflated 1%)\n adding: content/License Plates/car_205.txt (deflated 28%)\n adding: content/License Plates/car_235.txt (deflated 29%)\n adding: content/License Plates/car_13.jpeg (deflated 0%)\n adding: content/License Plates/car_125.txt (deflated 53%)\n adding: content/License Plates/car_9.txt (deflated 22%)\n adding: content/License Plates/car_5.txt (deflated 29%)\n adding: content/License Plates/car_169.txt (deflated 43%)\n adding: content/License Plates/car_187.jpeg (deflated 1%)\n adding: content/License Plates/car_137.txt (deflated 38%)\n adding: content/License Plates/car_6.txt (deflated 31%)\n adding: content/License Plates/car_122.txt (deflated 15%)\n adding: content/License Plates/car_75.txt (deflated 36%)\n adding: content/License Plates/car_18.txt (deflated 32%)\n adding: content/License Plates/car_17.txt (deflated 29%)\n adding: content/License Plates/car_148.jpeg (deflated 1%)\n adding: content/License Plates/car_83.jpeg (deflated 1%)\n adding: content/License Plates/car_207.txt (deflated 28%)\n adding: content/License Plates/car_31.txt (deflated 28%)\n adding: content/License Plates/car_119.jpeg (deflated 3%)\n adding: content/License Plates/car_54.txt (deflated 16%)\n adding: content/License Plates/car_171.jpeg (deflated 3%)\n adding: content/License Plates/car_80.jpeg (deflated 1%)\n adding: content/License Plates/car_191.txt (deflated 42%)\n adding: content/License Plates/car_103.jpeg (deflated 6%)\n adding: content/License Plates/car_118.jpeg (deflated 8%)\n adding: content/License Plates/car_160.txt (deflated 28%)\n adding: content/License Plates/car_12.txt (deflated 33%)\n adding: content/License Plates/car_187.txt (deflated 52%)\n adding: content/License Plates/car_183.jpeg (deflated 0%)\n adding: content/License Plates/car_191.jpeg (deflated 0%)\n adding: content/License Plates/car_143.jpeg (deflated 1%)\n adding: content/License Plates/car_7.txt (deflated 36%)\n adding: content/License Plates/car_11.txt (deflated 23%)\n adding: content/License Plates/car_149.jpeg (deflated 1%)\n adding: content/License Plates/car_158.txt (deflated 14%)\n adding: content/License Plates/car_138.jpeg (deflated 1%)\n adding: content/License Plates/car_92.jpeg (deflated 1%)\n adding: content/License Plates/car_13.txt (deflated 37%)\n adding: content/License Plates/car_47.jpeg (deflated 0%)\n adding: content/License Plates/car_35.jpeg (deflated 0%)\n adding: content/License Plates/car_94.txt (deflated 36%)\n adding: content/License Plates/car_135.jpeg (deflated 0%)\n adding: content/License Plates/car_223.jpeg (deflated 1%)\n adding: content/License Plates/car_137.jpeg (deflated 0%)\n adding: content/License Plates/car_214.jpeg (deflated 1%)\n adding: content/License Plates/car_63.jpeg (deflated 1%)\n adding: content/License Plates/car_87.jpeg (deflated 1%)\n adding: content/License Plates/car_57.jpeg (deflated 0%)\n adding: content/License Plates/car_220.txt (deflated 37%)\n adding: content/License Plates/car_6.jpeg (deflated 1%)\n adding: content/License Plates/car_144.jpeg (deflated 1%)\n adding: content/License Plates/car_156.txt (deflated 30%)\n adding: content/License Plates/car_82.txt (deflated 29%)\n adding: content/License Plates/car_229.txt (deflated 35%)\n adding: content/License Plates/car_204.jpeg (deflated 2%)\n adding: content/License Plates/car_176.txt (deflated 53%)\n adding: content/License Plates/car_43.jpeg (deflated 2%)\n adding: content/License Plates/car_3.jpeg (deflated 0%)\n adding: content/License Plates/car_228.txt (deflated 29%)\n adding: content/License Plates/car_73.jpeg (deflated 1%)\n adding: content/License Plates/car_100.jpeg (deflated 3%)\n adding: content/License Plates/car_148.txt (deflated 38%)\n adding: content/License Plates/car_225.txt (deflated 16%)\n adding: content/License Plates/car_81.jpeg (deflated 1%)\n adding: content/License Plates/car_94.jpeg (deflated 1%)\n adding: content/License Plates/car_112.jpeg (deflated 1%)\n adding: content/License Plates/car_157.jpeg (deflated 1%)\n adding: content/License Plates/car_74.txt (deflated 25%)\n adding: content/License Plates/car_143.txt (deflated 32%)\n adding: content/License Plates/car_80.txt (deflated 29%)\n adding: content/License Plates/car_207.jpeg (deflated 2%)\n adding: content/License Plates/car_95.jpeg (deflated 1%)\n adding: content/License Plates/car_18.jpeg (deflated 1%)\n adding: content/License Plates/car_50.txt (deflated 42%)\n adding: content/License Plates/car_218.txt (deflated 19%)\n adding: content/License Plates/car_201.jpeg (deflated 1%)\n adding: content/License Plates/car_216.txt (deflated 47%)\n adding: content/License Plates/car_111.txt (deflated 48%)\n adding: content/License Plates/car_49.jpeg (deflated 1%)\n adding: content/License Plates/car_144.txt (deflated 38%)\n adding: content/License Plates/car_134.txt (deflated 28%)\n adding: content/License Plates/car_232.txt (deflated 36%)\n adding: content/License Plates/car_130.jpeg (deflated 8%)\n adding: content/License Plates/car_96.jpeg (deflated 12%)\n adding: content/License Plates/car_222.txt (deflated 59%)\n adding: content/License Plates/car_22.txt (deflated 28%)\n adding: content/License Plates/car_159.jpeg (deflated 0%)\n adding: content/License Plates/car_30.txt (deflated 29%)\n adding: content/License Plates/car_55.jpeg (deflated 1%)\n adding: content/License Plates/car_182.txt (deflated 29%)\n adding: content/License Plates/car_160.jpeg (deflated 0%)\n adding: content/License Plates/car_9.jpeg (deflated 0%)\n adding: content/License Plates/car_170.txt (deflated 34%)\n adding: content/License Plates/car_1.txt (deflated 28%)\n adding: content/License Plates/car_213.jpeg (deflated 2%)\n adding: content/License Plates/car_112.txt (deflated 35%)\n adding: content/License Plates/car_98.txt (deflated 28%)\n adding: content/License Plates/car_210.jpeg (deflated 1%)\n adding: content/License Plates/car_230.jpeg (deflated 1%)\n adding: content/License Plates/car_128.jpeg (deflated 1%)\n adding: content/License Plates/car_233.jpeg (deflated 1%)\n adding: content/License Plates/car_61.txt (deflated 37%)\n adding: content/License Plates/car_21.txt (deflated 32%)\n adding: content/License Plates/car_166.txt (deflated 48%)\n adding: content/License Plates/car_104.jpeg (deflated 1%)\n adding: content/License Plates/car_16.txt (deflated 31%)\n adding: content/License Plates/car_4.txt (deflated 29%)\n adding: content/License Plates/car_37.txt (deflated 32%)\n adding: content/License Plates/car_210.txt (deflated 28%)\n adding: content/License Plates/car_102.jpeg (deflated 1%)\n adding: content/License Plates/car_61.jpeg (deflated 1%)\n adding: content/License Plates/car_227.txt (deflated 30%)\n adding: content/License Plates/car_50.jpeg (deflated 0%)\n adding: content/License Plates/car_0.jpeg (deflated 0%)\n adding: content/License Plates/car_224.txt (deflated 34%)\n adding: content/License Plates/car_219.txt (deflated 30%)\n adding: content/License Plates/car_182.jpeg (deflated 0%)\n adding: content/License Plates/car_45.txt (deflated 31%)\n adding: content/License Plates/car_51.txt (deflated 27%)\n adding: content/License Plates/car_153.txt (deflated 30%)\n adding: content/License Plates/car_56.jpeg (deflated 1%)\n adding: content/License Plates/car_108.txt (deflated 33%)\n adding: content/License Plates/car_147.txt (deflated 14%)\n adding: content/License Plates/car_189.jpeg (deflated 10%)\n adding: content/License Plates/car_104.txt (deflated 37%)\n adding: content/License Plates/car_154.txt (deflated 29%)\n adding: content/License Plates/car_55.txt (deflated 27%)\n adding: content/License Plates/car_223.txt (deflated 38%)\n adding: content/License Plates/car_19.jpeg (deflated 3%)\n adding: content/License Plates/car_231.txt (deflated 30%)\n adding: content/License Plates/car_1.jpeg (deflated 1%)\n adding: content/License Plates/car_172.jpeg (deflated 2%)\n adding: content/License Plates/car_233.txt (deflated 42%)\n adding: content/License Plates/car_135.txt (deflated 35%)\n adding: content/License Plates/car_47.txt (deflated 30%)\n adding: content/License Plates/car_62.txt (deflated 14%)\n adding: content/License Plates/car_203.jpeg (deflated 0%)\n adding: content/License Plates/car_70.txt (deflated 32%)\n adding: content/License Plates/car_162.txt (deflated 49%)\n adding: content/License Plates/car_147.jpeg (deflated 1%)\n adding: content/License Plates/car_46.jpeg (deflated 1%)\n adding: content/License Plates/car_205.jpeg (deflated 1%)\n adding: content/License Plates/car_29.jpeg (deflated 8%)\n adding: content/License Plates/car_165.jpeg (deflated 1%)\n adding: content/License Plates/car_53.jpeg (deflated 1%)\n adding: content/License Plates/car_215.jpeg (deflated 1%)\n adding: content/License Plates/car_40.txt (deflated 30%)\n adding: content/License Plates/car_138.txt (deflated 37%)\n adding: content/License Plates/car_24.jpeg (deflated 1%)\n adding: content/License Plates/car_127.jpeg (deflated 1%)\n adding: content/License Plates/car_178.jpeg (deflated 0%)\n adding: content/License Plates/car_151.jpeg (deflated 2%)\n adding: content/License Plates/car_58.jpeg (deflated 0%)\n adding: content/License Plates/car_109.jpeg (deflated 2%)\n adding: content/License Plates/car_208.jpeg (deflated 1%)\n adding: content/License Plates/car_8.jpeg (deflated 0%)\n adding: content/License Plates/car_42.jpeg (deflated 1%)\n adding: content/License Plates/car_52.txt (deflated 29%)\n adding: content/License Plates/car_215.txt (deflated 29%)\n adding: content/License Plates/car_214.txt (deflated 27%)\n adding: content/License Plates/car_165.txt (deflated 44%)\n adding: content/License Plates/car_85.txt (deflated 16%)\n adding: content/License Plates/car_81.txt (deflated 44%)\n adding: content/License Plates/car_5.jpeg (deflated 1%)\n adding: content/License Plates/car_194.txt (deflated 53%)\n adding: content/License Plates/car_169.jpeg (deflated 1%)\n adding: content/License Plates/car_113.txt (deflated 25%)\n adding: content/License Plates/car_44.txt (deflated 45%)\n adding: content/License Plates/car_188.txt (deflated 29%)\n adding: content/License Plates/car_164.txt (deflated 32%)\n adding: content/License Plates/car_75.jpeg (deflated 1%)\n adding: content/License Plates/car_206.jpeg (deflated 0%)\n adding: content/License Plates/car_141.jpeg (deflated 1%)\n adding: content/License Plates/car_32.txt (deflated 28%)\n adding: content/License Plates/car_49.txt (deflated 24%)\n adding: content/License Plates/car_125.jpeg (deflated 1%)\n adding: content/License Plates/car_71.jpeg (deflated 1%)\n adding: content/License Plates/car_65.txt (deflated 13%)\n adding: content/License Plates/car_56.txt (deflated 22%)\n adding: content/License Plates/car_106.txt (deflated 49%)\n adding: content/License Plates/car_236.jpeg (deflated 2%)\n adding: content/License Plates/car_52.jpeg (deflated 0%)\n adding: content/License Plates/car_170.jpeg (deflated 0%)\n adding: content/License Plates/car_236.txt (deflated 29%)\n adding: content/License Plates/car_36.jpeg (deflated 1%)\n adding: content/License Plates/car_185.jpeg (deflated 0%)\n adding: content/License Plates/car_119.txt (deflated 50%)\n adding: content/License Plates/car_35.txt (deflated 32%)\n adding: content/License Plates/car_27.txt (deflated 12%)\n adding: content/License Plates/car_132.txt (deflated 35%)\n adding: content/License Plates/car_226.txt (deflated 28%)\n adding: content/License Plates/car_161.txt (deflated 34%)\n adding: content/License Plates/car_23.txt (deflated 26%)\n adding: content/License Plates/car_78.txt (deflated 33%)\n adding: content/License Plates/car_149.txt (deflated 34%)\n adding: content/License Plates/car_163.txt (deflated 35%)\n adding: content/License Plates/car_221.txt (deflated 46%)\n adding: content/License Plates/car_79.txt (deflated 20%)\n adding: content/License Plates/car_179.txt (deflated 30%)\n adding: content/License Plates/car_96.txt (deflated 47%)\n adding: content/License Plates/car_12.jpeg (deflated 1%)\n adding: content/License Plates/car_195.jpeg (deflated 2%)\n adding: content/License Plates/car_68.jpeg (deflated 1%)\n adding: content/License Plates/car_30.jpeg (deflated 1%)\n adding: content/License Plates/car_88.jpeg (deflated 1%)\n adding: content/License Plates/car_189.txt (deflated 28%)\n adding: content/License Plates/car_198.jpeg (deflated 0%)\n adding: content/License Plates/car_155.jpeg (deflated 1%)\n adding: content/License Plates/car_67.txt (deflated 26%)\n adding: content/License Plates/car_107.jpeg (deflated 24%)\n adding: content/License Plates/car_184.jpeg (deflated 1%)\n adding: content/License Plates/car_28.txt (deflated 29%)\n adding: content/License Plates/car_136.txt (deflated 25%)\n adding: content/License Plates/car_153.jpeg (deflated 1%)\n adding: content/License Plates/car_98.jpeg (deflated 4%)\n adding: content/License Plates/car_63.txt (deflated 50%)\n adding: content/License Plates/car_88.txt (deflated 30%)\n adding: content/License Plates/car_222.jpeg (deflated 1%)\n adding: content/License Plates/car_218.jpeg (deflated 1%)\n adding: content/License Plates/car_171.txt (deflated 29%)\n adding: content/License Plates/car_200.jpeg (deflated 0%)\n adding: content/License Plates/car_85.jpeg (deflated 1%)\n adding: content/License Plates/car_133.jpeg (deflated 0%)\n adding: content/License Plates/car_93.txt (deflated 32%)\n adding: content/License Plates/car_67.jpeg (deflated 3%)\n adding: content/License Plates/car_17.jpeg (deflated 1%)\n adding: content/License Plates/car_225.jpeg (deflated 2%)\n adding: content/License Plates/car_115.jpeg (deflated 0%)\n adding: content/License Plates/car_54.jpeg (deflated 1%)\n adding: content/License Plates/car_184.txt (deflated 39%)\n adding: content/License Plates/car_92.txt (deflated 31%)\n adding: content/License Plates/car_226.jpeg (deflated 1%)\n adding: content/License Plates/car_150.jpeg (deflated 1%)\n adding: content/License Plates/car_139.txt (deflated 31%)\n adding: content/License Plates/car_4.jpeg (deflated 1%)\n adding: content/License Plates/car_121.jpeg (deflated 1%)\n adding: content/License Plates/car_108.jpeg (deflated 5%)\n adding: content/License Plates/car_110.jpeg (deflated 0%)\n adding: content/License Plates/car_79.jpeg (deflated 1%)\n adding: content/License Plates/car_53.txt (deflated 35%)\n adding: content/License Plates/car_124.txt (deflated 47%)\n adding: content/License Plates/car_78.jpeg (deflated 1%)\n adding: content/License Plates/car_201.txt (deflated 31%)\n adding: content/License Plates/car_176.jpeg (deflated 2%)\n adding: content/License Plates/car_101.jpeg (deflated 3%)\n adding: content/License Plates/car_208.txt (deflated 15%)\n adding: content/License Plates/car_64.jpeg (deflated 1%)\n adding: content/License Plates/car_196.jpeg (deflated 0%)\n adding: content/License Plates/car_202.jpeg (deflated 2%)\n adding: content/License Plates/car_133.txt (deflated 26%)\n adding: content/License Plates/car_151.txt (deflated 38%)\n adding: content/License Plates/car_194.jpeg (deflated 1%)\n adding: content/License Plates/car_212.jpeg (deflated 1%)\n adding: content/License Plates/car_203.txt (deflated 40%)\n adding: content/License Plates/car_130.txt (deflated 16%)\n adding: content/License Plates/car_120.jpeg (deflated 1%)\n adding: content/License Plates/car_166.jpeg (deflated 2%)\n adding: content/License Plates/car_99.jpeg (deflated 0%)\n adding: content/License Plates/car_72.txt (deflated 37%)\n adding: content/License Plates/car_229.jpeg (deflated 1%)\n adding: content/License Plates/car_142.txt (deflated 32%)\n adding: content/License Plates/car_136.jpeg (deflated 1%)\n adding: content/License Plates/car_197.jpeg (deflated 1%)\n adding: content/License Plates/car_3.txt (deflated 16%)\n" }, { "code": null, "e": 36286, "s": 36273, "text": "os.getcwd()\n" }, { "code": null, "e": 36302, "s": 36286, "text": "'/root/darknet'" }, { "code": null, "e": 36308, "s": 36302, "text": "cd ~\n" }, { "code": null, "e": 36315, "s": 36308, "text": "/root\n" }, { "code": null, "e": 36328, "s": 36315, "text": "cd /content\n" }, { "code": null, "e": 36338, "s": 36328, "text": "/content\n" }, { "code": null, "e": 36614, "s": 36338, "text": "import random\n\nx = list(licenses['name'])\n\nrandom.shuffle(x)\nf = open('./train.txt','w+')\ny = open('./val.txt','w+')\n\nfor i in range(len(x)):\n if i % 10 ==0:\n y.write('/darknet/data/obj/'+x[i]+'\\n')\n else:\n f.write('/darknet/data/obj/'+x[i]+'\\n')\ny.close()\nf.close()\n" }, { "code": null, "e": 36673, "s": 36614, "text": "files.download('./train.txt')\nfiles.download('./val.txt')\n" }, { "code": null, "e": 36895, "s": 36676, "text": "The following repository is an end to end detection and recognition of Indian license plates using YOLO v3 Darknet and Pytesseract. It serves as a precursor for our project. This is a fun individual project on its own!" }, { "code": null, "e": 36921, "s": 36895, "text": "Creating folder structure" }, { "code": null, "e": 36990, "s": 36921, "text": "In the data/images folder ,create two folder namely, train and valid" }, { "code": null, "e": 37086, "s": 36990, "text": "The train folder consists of 201 images obtained from Step 2. These are to be used for training" }, { "code": null, "e": 37183, "s": 37086, "text": "The valid folder consists of 36 images obtained from Step 2, which are to be used for validation" }, { "code": null, "e": 37283, "s": 37183, "text": "Only images won’t do for detection as we need labels for bounding boxes and classes for each image." }, { "code": null, "e": 37352, "s": 37283, "text": "The YOLO format for a single class bounding box label is as follows:" }, { "code": null, "e": 37382, "s": 37352, "text": "class_number x y width height" }, { "code": null, "e": 37427, "s": 37382, "text": "The labels are already obtained from Step 2." }, { "code": null, "e": 37552, "s": 37427, "text": "The labels folder consists of a train and valid folder consisting of labels for training and validation images respectively." }, { "code": null, "e": 37567, "s": 37552, "text": "A sample label" }, { "code": null, "e": 37607, "s": 37567, "text": "Next, we create the data/train.txt file" }, { "code": null, "e": 37746, "s": 37607, "text": "To get the contents of this file, simply write the following in command prompt or terminal. Make sure you are in the anpr_yolov5 directory" }, { "code": null, "e": 37945, "s": 37746, "text": "D:>git clone https://github.com/sid0312/anpr_yolov5cd anpr_yolov5python>>import os>>for image in os.list('data/images/train'): path = 'D:/anpr_yolov5/data/images/train' print(path+'/'+image)" }, { "code": null, "e": 37979, "s": 37945, "text": "You will get the following output" }, { "code": null, "e": 38020, "s": 37979, "text": "Copy the output to a file data/train.txt" }, { "code": null, "e": 38046, "s": 38020, "text": "Do the same for valid.txt" }, { "code": null, "e": 38237, "s": 38046, "text": "If you intend to train Yolo v5 on Google Colab, commit the repository in its present state without copying the contents above. Commit and push the current state of your repository to GitHub." }, { "code": null, "e": 38279, "s": 38237, "text": "git add . git commit -m\"some msg\"git push" }, { "code": null, "e": 38411, "s": 38279, "text": "Now follow the following notebook and copy the contents of the print logs to the files data/train.txt and data/val.txt respectively" }, { "code": null, "e": 38456, "s": 38411, "text": "Change the nc parameter in yolov5s.yaml to 1" }, { "code": null, "e": 38501, "s": 38456, "text": "Repeat the git add,commit,push process again" }, { "code": null, "e": 38559, "s": 38501, "text": "Check out the following notebook for the training process" }, { "code": null, "e": 38570, "s": 38559, "text": "github.com" }, { "code": null, "e": 38690, "s": 38570, "text": "Note: You can use yolo5s.pt weights too. I have used randomly initialized weights and trained the model for 100 epochs." }, { "code": null, "e": 38727, "s": 38690, "text": "After running for 100 epochs, we get" }, { "code": null, "e": 38746, "s": 38727, "text": "Precision as 0.659" }, { "code": null, "e": 38762, "s": 38746, "text": "Recall as 0.972" }, { "code": null, "e": 38779, "s": 38762, "text": "[email protected] as 0.978" }, { "code": null, "e": 38816, "s": 38779, "text": "[email protected] with 95% confidence as 0.471" }, { "code": null, "e": 38841, "s": 38816, "text": "https://blog.roboflow.ai" }, { "code": null, "e": 38879, "s": 38841, "text": "https://github.com/ultralyitcs/yolov5" }, { "code": null, "e": 39107, "s": 38879, "text": "In case, you have skipped the training part and jumped right to the conclusion, I have something more for you. After finding the region of interest of the license plate, we can use it for character recognition using pytesseract" }, { "code": null, "e": 39171, "s": 39107, "text": "I have done it for a previous project. You can check it out at:" }, { "code": null, "e": 39182, "s": 39171, "text": "github.com" }, { "code": null, "e": 39302, "s": 39182, "text": "If you’re into reading more about Object Detection Algorithms and Libraries, I highly recommend this blog by neptune.ai" }, { "code": null, "e": 39313, "s": 39302, "text": "neptune.ai" }, { "code": null, "e": 39358, "s": 39313, "text": "If you’re into my articles, check these out!" }, { "code": null, "e": 39381, "s": 39358, "text": "towardsdatascience.com" }, { "code": null, "e": 39404, "s": 39381, "text": "towardsdatascience.com" }, { "code": null, "e": 39427, "s": 39404, "text": "towardsdatascience.com" }, { "code": null, "e": 39489, "s": 39427, "text": "If you wish to connect with me on Linkedin, here’s my profile" }, { "code": null, "e": 39506, "s": 39489, "text": "www.linkedin.com" } ]
C Program to Sort an array of names or strings - GeeksforGeeks
18 Jan, 2019 Given an array of strings in which all characters are of the same case, write a C function to sort them alphabetically. The idea is to use qsort() in C and write a comparison function that uses strcmp() to compare two strings. #include <stdio.h>#include <stdlib.h>#include <string.h> // Defining comparator function as per the requirementstatic int myCompare(const void* a, const void* b){ // setting up rules for comparison return strcmp(*(const char**)a, *(const char**)b);} // Function to sort the arrayvoid sort(const char* arr[], int n){ // calling qsort function to sort the array // with the help of Comparator qsort(arr, n, sizeof(const char*), myCompare);} int main(){ // Get the array of names to be sorted const char* arr[] = { "geeksforgeeks", "geeksquiz", "clanguage" }; int n = sizeof(arr) / sizeof(arr[0]); int i; // Print the given names printf("Given array is\n"); for (i = 0; i < n; i++) printf("%d: %s \n", i, arr[i]); // Sort the given names sort(arr, n); // Print the sorted names printf("\nSorted array is\n"); for (i = 0; i < n; i++) printf("%d: %s \n", i, arr[i]); return 0;} Given array is 0: geeksforgeeks 1: geeksquiz 2: clanguage Sorted array is 0: clanguage 1: geeksforgeeks 2: geeksquiz Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above Sorting Strings Strings Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments HeapSort Time Complexities of all Sorting Algorithms Radix Sort std::sort() in C++ STL sort() in Python Longest Common Subsequence | DP-4 Write a program to print all permutations of a given string Reverse a string in Java KMP Algorithm for Pattern Searching C++ Data Types
[ { "code": null, "e": 24381, "s": 24353, "text": "\n18 Jan, 2019" }, { "code": null, "e": 24501, "s": 24381, "text": "Given an array of strings in which all characters are of the same case, write a C function to sort them alphabetically." }, { "code": null, "e": 24608, "s": 24501, "text": "The idea is to use qsort() in C and write a comparison function that uses strcmp() to compare two strings." }, { "code": "#include <stdio.h>#include <stdlib.h>#include <string.h> // Defining comparator function as per the requirementstatic int myCompare(const void* a, const void* b){ // setting up rules for comparison return strcmp(*(const char**)a, *(const char**)b);} // Function to sort the arrayvoid sort(const char* arr[], int n){ // calling qsort function to sort the array // with the help of Comparator qsort(arr, n, sizeof(const char*), myCompare);} int main(){ // Get the array of names to be sorted const char* arr[] = { \"geeksforgeeks\", \"geeksquiz\", \"clanguage\" }; int n = sizeof(arr) / sizeof(arr[0]); int i; // Print the given names printf(\"Given array is\\n\"); for (i = 0; i < n; i++) printf(\"%d: %s \\n\", i, arr[i]); // Sort the given names sort(arr, n); // Print the sorted names printf(\"\\nSorted array is\\n\"); for (i = 0; i < n; i++) printf(\"%d: %s \\n\", i, arr[i]); return 0;}", "e": 25573, "s": 24608, "text": null }, { "code": null, "e": 25697, "s": 25573, "text": "Given array is\n0: geeksforgeeks \n1: geeksquiz \n2: clanguage \n\nSorted array is\n0: clanguage \n1: geeksforgeeks \n2: geeksquiz\n" }, { "code": null, "e": 25821, "s": 25697, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above" }, { "code": null, "e": 25829, "s": 25821, "text": "Sorting" }, { "code": null, "e": 25837, "s": 25829, "text": "Strings" }, { "code": null, "e": 25845, "s": 25837, "text": "Strings" }, { "code": null, "e": 25853, "s": 25845, "text": "Sorting" }, { "code": null, "e": 25951, "s": 25853, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25960, "s": 25951, "text": "Comments" }, { "code": null, "e": 25973, "s": 25960, "text": "Old Comments" }, { "code": null, "e": 25982, "s": 25973, "text": "HeapSort" }, { "code": null, "e": 26026, "s": 25982, "text": "Time Complexities of all Sorting Algorithms" }, { "code": null, "e": 26037, "s": 26026, "text": "Radix Sort" }, { "code": null, "e": 26060, "s": 26037, "text": "std::sort() in C++ STL" }, { "code": null, "e": 26077, "s": 26060, "text": "sort() in Python" }, { "code": null, "e": 26111, "s": 26077, "text": "Longest Common Subsequence | DP-4" }, { "code": null, "e": 26171, "s": 26111, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 26196, "s": 26171, "text": "Reverse a string in Java" }, { "code": null, "e": 26232, "s": 26196, "text": "KMP Algorithm for Pattern Searching" } ]
ADO.NET
ADO.NET provides a bridge between the front end controls and the back end database. The ADO.NET objects encapsulate all the data access operations and the controls interact with these objects to display data, thus hiding the details of movement of data. The following figure shows the ADO.NET objects at a glance: The dataset represents a subset of the database. It does not have a continuous connection to the database. To update the database a reconnection is required. The DataSet contains DataTable objects and DataRelation objects. The DataRelation objects represent the relationship between two tables. Following table shows some important properties of the DataSet class: The following table shows some important methods of the DataSet class: The DataTable class represents the tables in the database. It has the following important properties; most of these properties are read only properties except the PrimaryKey property: The following table shows some important methods of the DataTable class: The DataRow object represents a row in a table. It has the following important properties: The following table shows some important methods of the DataRow class: The DataAdapter object acts as a mediator between the DataSet object and the database. This helps the Dataset to contain data from multiple databases or other data source. The DataReader object is an alternative to the DataSet and DataAdapter combination. This object provides a connection oriented access to the data records in the database. These objects are suitable for read-only access, such as populating a list and then breaking the connection. The DbConnection object represents a connection to the data source. The connection could be shared among different command objects. The DbCommand object represents the command or a stored procedure sent to the database from retrieving or manipulating data. So far, we have used tables and databases already existing in our computer. In this example, we will create a table, add column, rows and data into it and display the table using a GridView object. The source file code is as given: <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="createdatabase._Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title> Untitled Page </title> </head> <body> <form id="form1" runat="server"> <div> <asp:GridView ID="GridView1" runat="server"> </asp:GridView> </div> </form> </body> </html> The code behind file is as given: namespace createdatabase { public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { DataSet ds = CreateDataSet(); GridView1.DataSource = ds.Tables["Student"]; GridView1.DataBind(); } } private DataSet CreateDataSet() { //creating a DataSet object for tables DataSet dataset = new DataSet(); // creating the student table DataTable Students = CreateStudentTable(); dataset.Tables.Add(Students); return dataset; } private DataTable CreateStudentTable() { DataTable Students = new DataTable("Student"); // adding columns AddNewColumn(Students, "System.Int32", "StudentID"); AddNewColumn(Students, "System.String", "StudentName"); AddNewColumn(Students, "System.String", "StudentCity"); // adding rows AddNewRow(Students, 1, "M H Kabir", "Kolkata"); AddNewRow(Students, 1, "Shreya Sharma", "Delhi"); AddNewRow(Students, 1, "Rini Mukherjee", "Hyderabad"); AddNewRow(Students, 1, "Sunil Dubey", "Bikaner"); AddNewRow(Students, 1, "Rajat Mishra", "Patna"); return Students; } private void AddNewColumn(DataTable table, string columnType, string columnName) { DataColumn column = table.Columns.Add(columnName, Type.GetType(columnType)); } //adding data into the table private void AddNewRow(DataTable table, int id, string name, string city) { DataRow newrow = table.NewRow(); newrow["StudentID"] = id; newrow["StudentName"] = name; newrow["StudentCity"] = city; table.Rows.Add(newrow); } } } When you execute the program, observe the following: The application first creates a data set and binds it with the grid view control using the DataBind() method of the GridView control. The application first creates a data set and binds it with the grid view control using the DataBind() method of the GridView control. The Createdataset() method is a user defined function, which creates a new DataSet object and then calls another user defined method CreateStudentTable() to create the table and add it to the Tables collection of the data set. The Createdataset() method is a user defined function, which creates a new DataSet object and then calls another user defined method CreateStudentTable() to create the table and add it to the Tables collection of the data set. The CreateStudentTable() method calls the user defined methods AddNewColumn() and AddNewRow() to create the columns and rows of the table as well as to add data to the rows. The CreateStudentTable() method calls the user defined methods AddNewColumn() and AddNewRow() to create the columns and rows of the table as well as to add data to the rows. When the page is executed, it returns the rows of the table as shown: 51 Lectures 5.5 hours Anadi Sharma 44 Lectures 4.5 hours Kaushik Roy Chowdhury 42 Lectures 18 hours SHIVPRASAD KOIRALA 57 Lectures 3.5 hours University Code 40 Lectures 2.5 hours University Code 138 Lectures 9 hours Bhrugen Patel Print Add Notes Bookmark this page
[ { "code": null, "e": 2601, "s": 2347, "text": "ADO.NET provides a bridge between the front end controls and the back end database. The ADO.NET objects encapsulate all the data access operations and the controls interact with these objects to display data, thus hiding the details of movement of data." }, { "code": null, "e": 2661, "s": 2601, "text": "The following figure shows the ADO.NET objects at a glance:" }, { "code": null, "e": 2956, "s": 2661, "text": "The dataset represents a subset of the database. It does not have a continuous connection to the database. To update the database a reconnection is required. The DataSet contains DataTable objects and DataRelation objects. The DataRelation objects represent the relationship between two tables." }, { "code": null, "e": 3026, "s": 2956, "text": "Following table shows some important properties of the DataSet class:" }, { "code": null, "e": 3097, "s": 3026, "text": "The following table shows some important methods of the DataSet class:" }, { "code": null, "e": 3281, "s": 3097, "text": "The DataTable class represents the tables in the database. It has the following important properties; most of these properties are read only properties except the PrimaryKey property:" }, { "code": null, "e": 3354, "s": 3281, "text": "The following table shows some important methods of the DataTable class:" }, { "code": null, "e": 3445, "s": 3354, "text": "The DataRow object represents a row in a table. It has the following important properties:" }, { "code": null, "e": 3516, "s": 3445, "text": "The following table shows some important methods of the DataRow class:" }, { "code": null, "e": 3688, "s": 3516, "text": "The DataAdapter object acts as a mediator between the DataSet object and the database. This helps the Dataset to contain data from multiple databases or other data source." }, { "code": null, "e": 3968, "s": 3688, "text": "The DataReader object is an alternative to the DataSet and DataAdapter combination. This object provides a connection oriented access to the data records in the database. These objects are suitable for read-only access, such as populating a list and then breaking the connection." }, { "code": null, "e": 4100, "s": 3968, "text": "The DbConnection object represents a connection to the data source. The connection could be shared among different command objects." }, { "code": null, "e": 4225, "s": 4100, "text": "The DbCommand object represents the command or a stored procedure sent to the database from retrieving or manipulating data." }, { "code": null, "e": 4423, "s": 4225, "text": "So far, we have used tables and databases already existing in our computer. In this example, we will create a table, add column, rows and data into it and display the table using a GridView object." }, { "code": null, "e": 4457, "s": 4423, "text": "The source file code is as given:" }, { "code": null, "e": 5051, "s": 4457, "text": "<%@ Page Language=\"C#\" AutoEventWireup=\"true\" CodeBehind=\"Default.aspx.cs\" Inherits=\"createdatabase._Default\" %>\n\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n\n<html xmlns=\"http://www.w3.org/1999/xhtml\" >\n\n <head runat=\"server\">\n <title>\n Untitled Page\n </title>\n </head>\n \n <body>\n <form id=\"form1\" runat=\"server\">\n \n <div>\n <asp:GridView ID=\"GridView1\" runat=\"server\">\n </asp:GridView>\n </div>\n \n </form>\n </body>\n \n</html>" }, { "code": null, "e": 5085, "s": 5051, "text": "The code behind file is as given:" }, { "code": null, "e": 6946, "s": 5085, "text": "namespace createdatabase\n{\n public partial class _Default : System.Web.UI.Page\n {\n protected void Page_Load(object sender, EventArgs e)\n {\n if (!IsPostBack)\n {\n DataSet ds = CreateDataSet();\n GridView1.DataSource = ds.Tables[\"Student\"];\n GridView1.DataBind();\n }\n }\n \n private DataSet CreateDataSet()\n {\n //creating a DataSet object for tables\n DataSet dataset = new DataSet();\n\n // creating the student table\n DataTable Students = CreateStudentTable();\n dataset.Tables.Add(Students);\n return dataset;\n }\n \n private DataTable CreateStudentTable()\n {\n DataTable Students = new DataTable(\"Student\");\n\n // adding columns\n AddNewColumn(Students, \"System.Int32\", \"StudentID\");\n AddNewColumn(Students, \"System.String\", \"StudentName\");\n AddNewColumn(Students, \"System.String\", \"StudentCity\");\n\n // adding rows\n AddNewRow(Students, 1, \"M H Kabir\", \"Kolkata\");\n AddNewRow(Students, 1, \"Shreya Sharma\", \"Delhi\");\n AddNewRow(Students, 1, \"Rini Mukherjee\", \"Hyderabad\");\n AddNewRow(Students, 1, \"Sunil Dubey\", \"Bikaner\");\n AddNewRow(Students, 1, \"Rajat Mishra\", \"Patna\");\n\n return Students;\n }\n\n private void AddNewColumn(DataTable table, string columnType, string columnName)\n {\n DataColumn column = table.Columns.Add(columnName, Type.GetType(columnType));\n }\n\n //adding data into the table\n private void AddNewRow(DataTable table, int id, string name, string city)\n {\n DataRow newrow = table.NewRow();\n newrow[\"StudentID\"] = id;\n newrow[\"StudentName\"] = name;\n newrow[\"StudentCity\"] = city;\n table.Rows.Add(newrow);\n }\n }\n}" }, { "code": null, "e": 6999, "s": 6946, "text": "When you execute the program, observe the following:" }, { "code": null, "e": 7133, "s": 6999, "text": "The application first creates a data set and binds it with the grid view control using the DataBind() method of the GridView control." }, { "code": null, "e": 7267, "s": 7133, "text": "The application first creates a data set and binds it with the grid view control using the DataBind() method of the GridView control." }, { "code": null, "e": 7494, "s": 7267, "text": "The Createdataset() method is a user defined function, which creates a new DataSet object and then calls another user defined method CreateStudentTable() to create the table and add it to the Tables collection of the data set." }, { "code": null, "e": 7721, "s": 7494, "text": "The Createdataset() method is a user defined function, which creates a new DataSet object and then calls another user defined method CreateStudentTable() to create the table and add it to the Tables collection of the data set." }, { "code": null, "e": 7895, "s": 7721, "text": "The CreateStudentTable() method calls the user defined methods AddNewColumn() and AddNewRow() to create the columns and rows of the table as well as to add data to the rows." }, { "code": null, "e": 8069, "s": 7895, "text": "The CreateStudentTable() method calls the user defined methods AddNewColumn() and AddNewRow() to create the columns and rows of the table as well as to add data to the rows." }, { "code": null, "e": 8139, "s": 8069, "text": "When the page is executed, it returns the rows of the table as shown:" }, { "code": null, "e": 8174, "s": 8139, "text": "\n 51 Lectures \n 5.5 hours \n" }, { "code": null, "e": 8188, "s": 8174, "text": " Anadi Sharma" }, { "code": null, "e": 8223, "s": 8188, "text": "\n 44 Lectures \n 4.5 hours \n" }, { "code": null, "e": 8246, "s": 8223, "text": " Kaushik Roy Chowdhury" }, { "code": null, "e": 8280, "s": 8246, "text": "\n 42 Lectures \n 18 hours \n" }, { "code": null, "e": 8300, "s": 8280, "text": " SHIVPRASAD KOIRALA" }, { "code": null, "e": 8335, "s": 8300, "text": "\n 57 Lectures \n 3.5 hours \n" }, { "code": null, "e": 8352, "s": 8335, "text": " University Code" }, { "code": null, "e": 8387, "s": 8352, "text": "\n 40 Lectures \n 2.5 hours \n" }, { "code": null, "e": 8404, "s": 8387, "text": " University Code" }, { "code": null, "e": 8438, "s": 8404, "text": "\n 138 Lectures \n 9 hours \n" }, { "code": null, "e": 8453, "s": 8438, "text": " Bhrugen Patel" }, { "code": null, "e": 8460, "s": 8453, "text": " Print" }, { "code": null, "e": 8471, "s": 8460, "text": " Add Notes" } ]
Scala Set toMap() method with example - GeeksforGeeks
18 Oct, 2019 The toMap() method is utilized to return a map consisting of all the elements of the set. Method Definition: def toMap[T, U]: Map[T, U] Return Type: It returns a map consisting of all the elements of the set. Example #1: // Scala program of toMap() // method // Creating object object GfG { // Main method def main(args:Array[String]) { // Creating a set val s1 = Set((1, 2), (3, 4), (5, 6)) // Applying toMap method val result = s1.toMap // Display output println(result) } } Map(1 -> 2, 3 -> 4, 5 -> 6) Example #2: // Scala program of toMap() // method // Creating object object GfG { // Main method def main(args:Array[String]) { // Creating a set val s1 = Set((12, 2), (13, 4), (15, 6)) // Applying toMap method val result = s1.toMap // Display output println(result) } } Map(12 -> 2, 13 -> 4, 15 -> 6) Scala scala-collection Scala-Method Scala-Set Scala Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Scala Lists Scala Tutorial – Learn Scala with Step By Step Guide Class and Object in Scala Type Casting in Scala Operators in Scala Inheritance in Scala Throw Keyword in Scala Hello World in Scala Scala String substring() method with example
[ { "code": null, "e": 23926, "s": 23898, "text": "\n18 Oct, 2019" }, { "code": null, "e": 24016, "s": 23926, "text": "The toMap() method is utilized to return a map consisting of all the elements of the set." }, { "code": null, "e": 24062, "s": 24016, "text": "Method Definition: def toMap[T, U]: Map[T, U]" }, { "code": null, "e": 24135, "s": 24062, "text": "Return Type: It returns a map consisting of all the elements of the set." }, { "code": null, "e": 24147, "s": 24135, "text": "Example #1:" }, { "code": "// Scala program of toMap() // method // Creating object object GfG { // Main method def main(args:Array[String]) { // Creating a set val s1 = Set((1, 2), (3, 4), (5, 6)) // Applying toMap method val result = s1.toMap // Display output println(result) } } ", "e": 24503, "s": 24147, "text": null }, { "code": null, "e": 24532, "s": 24503, "text": "Map(1 -> 2, 3 -> 4, 5 -> 6)\n" }, { "code": null, "e": 24544, "s": 24532, "text": "Example #2:" }, { "code": "// Scala program of toMap() // method // Creating object object GfG { // Main method def main(args:Array[String]) { // Creating a set val s1 = Set((12, 2), (13, 4), (15, 6)) // Applying toMap method val result = s1.toMap // Display output println(result) } } ", "e": 24903, "s": 24544, "text": null }, { "code": null, "e": 24935, "s": 24903, "text": "Map(12 -> 2, 13 -> 4, 15 -> 6)\n" }, { "code": null, "e": 24941, "s": 24935, "text": "Scala" }, { "code": null, "e": 24958, "s": 24941, "text": "scala-collection" }, { "code": null, "e": 24971, "s": 24958, "text": "Scala-Method" }, { "code": null, "e": 24981, "s": 24971, "text": "Scala-Set" }, { "code": null, "e": 24987, "s": 24981, "text": "Scala" }, { "code": null, "e": 25085, "s": 24987, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25094, "s": 25085, "text": "Comments" }, { "code": null, "e": 25107, "s": 25094, "text": "Old Comments" }, { "code": null, "e": 25119, "s": 25107, "text": "Scala Lists" }, { "code": null, "e": 25172, "s": 25119, "text": "Scala Tutorial – Learn Scala with Step By Step Guide" }, { "code": null, "e": 25198, "s": 25172, "text": "Class and Object in Scala" }, { "code": null, "e": 25220, "s": 25198, "text": "Type Casting in Scala" }, { "code": null, "e": 25239, "s": 25220, "text": "Operators in Scala" }, { "code": null, "e": 25260, "s": 25239, "text": "Inheritance in Scala" }, { "code": null, "e": 25283, "s": 25260, "text": "Throw Keyword in Scala" }, { "code": null, "e": 25304, "s": 25283, "text": "Hello World in Scala" } ]
Deploy a Production-Ready On-Premise Kubernetes Cluster | by Joshua Yeung | Towards Data Science
Last year during the pandemic, I had a chance to deploy an on-premise Kubernetes myself. In this article, I would like to mark a few things to remind me and also tell you all that you should know when deploying an on-premise Kubernetes. Kubespray uses Ansible playbooks as an inventory and provisioning tool to help us to deploy generic Kubernetes clusters. It also handles our configuration management tasks. It automates all the difficult stuff for you to deploy Kubernetes. All you need is just modifying the YAML file config provided by Kubespray. The following guide is copied from the documentation of Kubespray, you may check that out here: github.com First, you need to git clone the repository and install the Python requirements using pip. git clone https://github.com/kubernetes-sigs/kubespray.git# Install dependencies from ``requirements.txt``sudo pip3 install -r requirements.txt If you cannot install Ansible, check out this link: docs.ansible.com There is a sample inventory in the inventory folder. You need to copy that and name your whole cluster (e.g. mycluster). The repository has already provided you the inventory builder to update the Ansible inventory file. # Copy ``inventory/sample`` as ``inventory/mycluster``cp -rfp inventory/sample inventory/mycluster# Update Ansible inventory file with inventory builderdeclare -a IPS=(10.10.1.3 10.10.1.4 10.10.1.5)CONFIG_FILE=inventory/mycluster/hosts.yaml python3 contrib/inventory_builder/inventory.py ${IPS[@]} Next, you have to modify inventory/mycluster/hosts.yml. Below is an example, it sets three nodes to be masters and three other nodes to be workers. The etcd are located in the same nodes as the masters. all: hosts: node1: ansible_host: 192.168.0.2 ip: 192.168.0.2 access_ip: 192.168.0.2 node2: ansible_host: 192.168.0.3 ip: 192.168.0.3 access_ip: 192.168.0.3 node3: ansible_host: 192.168.0.4 ip: 192.168.0.4 access_ip: 192.168.0.4 node4: ansible_host: 192.168.0.5 ip: 192.168.0.5 access_ip: 192.168.0.5 node5: ansible_host: 192.168.0.6 ip: 192.168.0.6 access_ip: 192.168.0.6 node6: ansible_host: 192.168.0.7 ip: 192.168.0.7 access_ip: 192.168.0.7 children: kube-master: hosts: node1: node2: node3: kube-node: hosts: node4: node5: node6: etcd: hosts: node1: node2: node3: k8s-cluster: children: kube-master: kube-node: calico-rr: hosts: {} Because Ansible will make an SSH connection to your hosts, your SSH key of the Ansible host must be copied to all the servers or hosts in your inventory. What you need to do is the following: Generate an SSH Key with ssh-keygenCopy the key to a server using ssh-copy-id -i ~/.ssh/mykey user@host Generate an SSH Key with ssh-keygen Copy the key to a server using ssh-copy-id -i ~/.ssh/mykey user@host Now you need to review and change the parameters of your cluster. There are some aspects you should consider. # Review and change parameters under ``inventory/mycluster/group_vars``cat inventory/mycluster/group_vars/all/all.ymlcat inventory/mycluster/group_vars/k8s-cluster/k8s-cluster.yml The first one is to set up a load balancer for the high availability of your API servers. Load Balancer is used to prevent service failure when one of our master nodes is not working. Normally we would set up at least three masters. You may find more details in the HA endpoints for K8s section in the documentation. github.com For a production ready Kubernetes cluster, we need to use an external loadbalancer (LB) instead of internal LB. An external LB provides access for external clients, while the internal LB accepts client connections only to the localhost. I used HAProxy + keepalived to configure a highly available load balancer. Two VMs are set up to perform the load balancer functionality. The reference I was referring to is from this site: www.digitalocean.com Although the article is a bit old, the concept is the same and the procedure is quite similar. Given a frontend VIP address and IP1, IP2 addresses of backends, here is an example configuration for a HAProxy service acting as an external LB: #/etc/haproxy/haproxy.cfglisten kubernetes-apiserver-httpsbind <VIP>:8383mode tcpoption log-health-checkstimeout client 3htimeout server 3hserver master1 <IP1>:6443 check check-ssl verify none inter 10000server master2 <IP2>:6443 check check-ssl verify none inter 10000balance roundrobin And then you need to change the external load balancer config. Again, the config is copied from the HA endpoints for the K8s section in the documentation. #kubespray/inventory/mycluster/group_vars/all/all.yml## External LB example config## apiserver_loadbalancer_domain_name: "elb.some.domain"# loadbalancer_apiserver:# address: <VIP># port: 8383 If your cluster cannot access the Internet directly and is behind a corporate proxy like mine, you will experience pain in the deployment process... Make sure you add your proxy setting in kubespray/inventory/mycluster/group_vars/all/all.yml Add your proxy to http_proxy and the domain/IP that you don’t want your cluster to access through the proxy in additional_no_proxy section. (IMPORTANT!) If your master VMs have two network interfaces and you need to access Kubernetes from another interface other than the one used by Kubernetes, you will need to add supplementary addresses in the config file: ## Supplementary addresses that can be added in kubernetes ssl keys.## That can be useful for example to setup a keepalived virtual IPsupplementary_addresses_in_ssl_keys: [10.0.0.1, 10.0.0.2, 10.0.0.3] In order to let your user access your service which was deployed in Kubernetes, you need to expose your service. There are three ways to access from outside the cluster: Ingress, Load Balancer, and NodePort. To implement services of type LoadBalancer on-premise, we chose MetalLB to handle network load balancing functionality for us. MetalLB is a load-balancer implementation for bare metal Kubernetes clusters, using standard routing protocols. It is quite easy to install MetalLB with Kubespray. You just need to modify the addons YAML file and also the k8s-cluster YAML file. Note that the IP range you assigned to MetalLB must be prepared by yourself beforehand. # kubespray/inventory/mycluster/group_vars/k8s-cluster/addons.ymlmetallb_enabled: truemetallb_ip_range: - “10.5.0.50–10.5.0.99” Remember to set parameter kube_proxy_strict_arp to be true. # kubespray/inventory/mycluster/group_vars/k8s-cluster/k8s-cluster.yml# must be set to true for MetalLB to workkube_proxy_strict_arp: true Finally, you can deploy Kubespray with Ansible Playbook! Depending on your cluster size and network throughput, it takes around 15–30 minutes for a cluster to be ready. After that, you can now use your Kubernetes cluster! # Deploy Kubespray with Ansible Playbook - run the playbook as root# The option `--become` is required, as for example writing SSL keys in /etc/,# installing packages and interacting with various systemd daemons.# Without --become the playbook will fail to run!ansible-playbook -i inventory/mycluster/hosts.yaml --become --become-user=root cluster.yml We still have a ways to go before we are able to deploy our application to the Kubernetes cluster. Helm is a package manager for Kubernetes. From the official website of Helm, it states Helm is the best way to find, share, and use software built for Kubernetes. Helm helps you manage Kubernetes applications — Helm Charts help you define, install, and upgrade even the most complex Kubernetes application. To install Helm, the easiest method is to install by the script: $ curl -fsSL -o get_helm.sh https://raw.githubusercontent.com/helm/helm/master/scripts/get-helm-3$ chmod 700 get_helm.sh$ ./get_helm.sh You can fetch that script and then execute it locally. It's well documented so that you can read through it and understand what it is doing before you run it. helm.sh In order to let your user access your service which was deployed in Kubernetes, you need to expose your service. There are three ways to access from outside the cluster: Ingress, Load Balancer, and NodePort. In production, NodePort is not recommended since it lacks availability. For Load Balancer, we have already implemented using MetalLB. Now we are going to implement Ingress. Please check the details of Ingress on this site: kubernetes.io From the description of the official Kubernetes documentation, Ingress exposes HTTP and HTTPS routes from outside the cluster to services within the cluster. Traffic routing is controlled by rules defined on the Ingress resource. An Ingress Controller controls the Ingress resource. The one I used is called the NGINX ingress controller. You may install it easily using Helm. docs.nginx.com helm repo add nginx-stable https://helm.nginx.com/stablehelm repo updatehelm install my-release nginx-stable/nginx-ingress Data in the pod is ephemeral, if you want your data to be persisted, you store your data in a Persistent Volume. From the description of the official Kubernetes documentation, a PersistentVolume (PV) is a piece of storage in the cluster that has been provisioned by an administrator or dynamically provisioned using Storage Classes. kubernetes.io Each StorageClass has a provisioner that handles the volume assignment. The one I chose is Longhorn. From the description of the official Longhorn documentation, it states that longhorn.io Longhorn is a lightweight, reliable, and powerful distributed block storage system for Kubernetes. Longhorn implements distributed block storage using containers and microservices. It creates a dedicated storage controller for each block device volume and synchronously replicates the volume across multiple replicas stored on multiple nodes. The storage controller and replicas are themselves orchestrated using Kubernetes. This makes our storage has no single point of failure. It has an intuitive GUI dashboard too, you can view all the details of volumes in it. The below installation guide is copied from the official Longhorn documentation: To Install Longhorn 1. Add the Longhorn Helm repository: helm repo add longhorn https://charts.longhorn.io 2. Fetch the latest charts from the repository: helm repo update 3. Install Longhorn in the longhorn-system namespace. kubectl create namespace longhorn-systemhelm install longhorn longhorn/longhorn --namespace longhorn-system 4. To confirm that the deployment succeeded, run: kubectl -n longhorn-system get pod You should see all pods are running if it is ready. You need a registry to store your developed docker image. One of the open-source choices is Harbor. goharbor.io Again, you can easily install harbor with Helm chart. The one I used is maintained by bitnami: github.com To conclude, I walk you through the whole installation process of an on-premise Kubernetes cluster. Let’s make a simple checklist: KubesprayAnsible configurationMaster Node HA API Server Load Balancer (HAProxy + keepalived)Proxy settingConfigure kubectl access from outside the clusterService Exposure: Load Balancer and IngressPackage management: HelmStorage: LonghornInternal Image Repository: Registry Kubespray Ansible configuration Master Node HA API Server Load Balancer (HAProxy + keepalived) Proxy setting Configure kubectl access from outside the cluster Service Exposure: Load Balancer and Ingress Package management: Helm Storage: Longhorn Internal Image Repository: Registry It still only covers a part of a production-ready Kubernetes cluster and I am still exploring. Other important aspects are still missing in this article such as monitoring (like Prometheus & Grafana), security (RBAC/User management), CICD (Argo), etc... Welcome to the world of Kubernetes! If you want to know how to prepare for the Certified Kubernetes Application Developer (CKAD) examination, check out this article: towardsdatascience.com You may also want to check the affiliated link below.
[ { "code": null, "e": 408, "s": 171, "text": "Last year during the pandemic, I had a chance to deploy an on-premise Kubernetes myself. In this article, I would like to mark a few things to remind me and also tell you all that you should know when deploying an on-premise Kubernetes." }, { "code": null, "e": 819, "s": 408, "text": "Kubespray uses Ansible playbooks as an inventory and provisioning tool to help us to deploy generic Kubernetes clusters. It also handles our configuration management tasks. It automates all the difficult stuff for you to deploy Kubernetes. All you need is just modifying the YAML file config provided by Kubespray. The following guide is copied from the documentation of Kubespray, you may check that out here:" }, { "code": null, "e": 830, "s": 819, "text": "github.com" }, { "code": null, "e": 921, "s": 830, "text": "First, you need to git clone the repository and install the Python requirements using pip." }, { "code": null, "e": 1065, "s": 921, "text": "git clone https://github.com/kubernetes-sigs/kubespray.git# Install dependencies from ``requirements.txt``sudo pip3 install -r requirements.txt" }, { "code": null, "e": 1117, "s": 1065, "text": "If you cannot install Ansible, check out this link:" }, { "code": null, "e": 1134, "s": 1117, "text": "docs.ansible.com" }, { "code": null, "e": 1355, "s": 1134, "text": "There is a sample inventory in the inventory folder. You need to copy that and name your whole cluster (e.g. mycluster). The repository has already provided you the inventory builder to update the Ansible inventory file." }, { "code": null, "e": 1653, "s": 1355, "text": "# Copy ``inventory/sample`` as ``inventory/mycluster``cp -rfp inventory/sample inventory/mycluster# Update Ansible inventory file with inventory builderdeclare -a IPS=(10.10.1.3 10.10.1.4 10.10.1.5)CONFIG_FILE=inventory/mycluster/hosts.yaml python3 contrib/inventory_builder/inventory.py ${IPS[@]}" }, { "code": null, "e": 1856, "s": 1653, "text": "Next, you have to modify inventory/mycluster/hosts.yml. Below is an example, it sets three nodes to be masters and three other nodes to be workers. The etcd are located in the same nodes as the masters." }, { "code": null, "e": 2719, "s": 1856, "text": "all: hosts: node1: ansible_host: 192.168.0.2 ip: 192.168.0.2 access_ip: 192.168.0.2 node2: ansible_host: 192.168.0.3 ip: 192.168.0.3 access_ip: 192.168.0.3 node3: ansible_host: 192.168.0.4 ip: 192.168.0.4 access_ip: 192.168.0.4 node4: ansible_host: 192.168.0.5 ip: 192.168.0.5 access_ip: 192.168.0.5 node5: ansible_host: 192.168.0.6 ip: 192.168.0.6 access_ip: 192.168.0.6 node6: ansible_host: 192.168.0.7 ip: 192.168.0.7 access_ip: 192.168.0.7 children: kube-master: hosts: node1: node2: node3: kube-node: hosts: node4: node5: node6: etcd: hosts: node1: node2: node3: k8s-cluster: children: kube-master: kube-node: calico-rr: hosts: {}" }, { "code": null, "e": 2911, "s": 2719, "text": "Because Ansible will make an SSH connection to your hosts, your SSH key of the Ansible host must be copied to all the servers or hosts in your inventory. What you need to do is the following:" }, { "code": null, "e": 3015, "s": 2911, "text": "Generate an SSH Key with ssh-keygenCopy the key to a server using ssh-copy-id -i ~/.ssh/mykey user@host" }, { "code": null, "e": 3051, "s": 3015, "text": "Generate an SSH Key with ssh-keygen" }, { "code": null, "e": 3120, "s": 3051, "text": "Copy the key to a server using ssh-copy-id -i ~/.ssh/mykey user@host" }, { "code": null, "e": 3230, "s": 3120, "text": "Now you need to review and change the parameters of your cluster. There are some aspects you should consider." }, { "code": null, "e": 3410, "s": 3230, "text": "# Review and change parameters under ``inventory/mycluster/group_vars``cat inventory/mycluster/group_vars/all/all.ymlcat inventory/mycluster/group_vars/k8s-cluster/k8s-cluster.yml" }, { "code": null, "e": 3727, "s": 3410, "text": "The first one is to set up a load balancer for the high availability of your API servers. Load Balancer is used to prevent service failure when one of our master nodes is not working. Normally we would set up at least three masters. You may find more details in the HA endpoints for K8s section in the documentation." }, { "code": null, "e": 3738, "s": 3727, "text": "github.com" }, { "code": null, "e": 3975, "s": 3738, "text": "For a production ready Kubernetes cluster, we need to use an external loadbalancer (LB) instead of internal LB. An external LB provides access for external clients, while the internal LB accepts client connections only to the localhost." }, { "code": null, "e": 4165, "s": 3975, "text": "I used HAProxy + keepalived to configure a highly available load balancer. Two VMs are set up to perform the load balancer functionality. The reference I was referring to is from this site:" }, { "code": null, "e": 4186, "s": 4165, "text": "www.digitalocean.com" }, { "code": null, "e": 4281, "s": 4186, "text": "Although the article is a bit old, the concept is the same and the procedure is quite similar." }, { "code": null, "e": 4427, "s": 4281, "text": "Given a frontend VIP address and IP1, IP2 addresses of backends, here is an example configuration for a HAProxy service acting as an external LB:" }, { "code": null, "e": 4715, "s": 4427, "text": "#/etc/haproxy/haproxy.cfglisten kubernetes-apiserver-httpsbind <VIP>:8383mode tcpoption log-health-checkstimeout client 3htimeout server 3hserver master1 <IP1>:6443 check check-ssl verify none inter 10000server master2 <IP2>:6443 check check-ssl verify none inter 10000balance roundrobin" }, { "code": null, "e": 4870, "s": 4715, "text": "And then you need to change the external load balancer config. Again, the config is copied from the HA endpoints for the K8s section in the documentation." }, { "code": null, "e": 5072, "s": 4870, "text": "#kubespray/inventory/mycluster/group_vars/all/all.yml## External LB example config## apiserver_loadbalancer_domain_name: \"elb.some.domain\"# loadbalancer_apiserver:# address: <VIP># port: 8383" }, { "code": null, "e": 5314, "s": 5072, "text": "If your cluster cannot access the Internet directly and is behind a corporate proxy like mine, you will experience pain in the deployment process... Make sure you add your proxy setting in kubespray/inventory/mycluster/group_vars/all/all.yml" }, { "code": null, "e": 5467, "s": 5314, "text": "Add your proxy to http_proxy and the domain/IP that you don’t want your cluster to access through the proxy in additional_no_proxy section. (IMPORTANT!)" }, { "code": null, "e": 5675, "s": 5467, "text": "If your master VMs have two network interfaces and you need to access Kubernetes from another interface other than the one used by Kubernetes, you will need to add supplementary addresses in the config file:" }, { "code": null, "e": 5877, "s": 5675, "text": "## Supplementary addresses that can be added in kubernetes ssl keys.## That can be useful for example to setup a keepalived virtual IPsupplementary_addresses_in_ssl_keys: [10.0.0.1, 10.0.0.2, 10.0.0.3]" }, { "code": null, "e": 6324, "s": 5877, "text": "In order to let your user access your service which was deployed in Kubernetes, you need to expose your service. There are three ways to access from outside the cluster: Ingress, Load Balancer, and NodePort. To implement services of type LoadBalancer on-premise, we chose MetalLB to handle network load balancing functionality for us. MetalLB is a load-balancer implementation for bare metal Kubernetes clusters, using standard routing protocols." }, { "code": null, "e": 6545, "s": 6324, "text": "It is quite easy to install MetalLB with Kubespray. You just need to modify the addons YAML file and also the k8s-cluster YAML file. Note that the IP range you assigned to MetalLB must be prepared by yourself beforehand." }, { "code": null, "e": 6673, "s": 6545, "text": "# kubespray/inventory/mycluster/group_vars/k8s-cluster/addons.ymlmetallb_enabled: truemetallb_ip_range: - “10.5.0.50–10.5.0.99”" }, { "code": null, "e": 6733, "s": 6673, "text": "Remember to set parameter kube_proxy_strict_arp to be true." }, { "code": null, "e": 6872, "s": 6733, "text": "# kubespray/inventory/mycluster/group_vars/k8s-cluster/k8s-cluster.yml# must be set to true for MetalLB to workkube_proxy_strict_arp: true" }, { "code": null, "e": 7094, "s": 6872, "text": "Finally, you can deploy Kubespray with Ansible Playbook! Depending on your cluster size and network throughput, it takes around 15–30 minutes for a cluster to be ready. After that, you can now use your Kubernetes cluster!" }, { "code": null, "e": 7447, "s": 7094, "text": "# Deploy Kubespray with Ansible Playbook - run the playbook as root# The option `--become` is required, as for example writing SSL keys in /etc/,# installing packages and interacting with various systemd daemons.# Without --become the playbook will fail to run!ansible-playbook -i inventory/mycluster/hosts.yaml --become --become-user=root cluster.yml" }, { "code": null, "e": 7546, "s": 7447, "text": "We still have a ways to go before we are able to deploy our application to the Kubernetes cluster." }, { "code": null, "e": 7633, "s": 7546, "text": "Helm is a package manager for Kubernetes. From the official website of Helm, it states" }, { "code": null, "e": 7853, "s": 7633, "text": "Helm is the best way to find, share, and use software built for Kubernetes. Helm helps you manage Kubernetes applications — Helm Charts help you define, install, and upgrade even the most complex Kubernetes application." }, { "code": null, "e": 7918, "s": 7853, "text": "To install Helm, the easiest method is to install by the script:" }, { "code": null, "e": 8054, "s": 7918, "text": "$ curl -fsSL -o get_helm.sh https://raw.githubusercontent.com/helm/helm/master/scripts/get-helm-3$ chmod 700 get_helm.sh$ ./get_helm.sh" }, { "code": null, "e": 8213, "s": 8054, "text": "You can fetch that script and then execute it locally. It's well documented so that you can read through it and understand what it is doing before you run it." }, { "code": null, "e": 8221, "s": 8213, "text": "helm.sh" }, { "code": null, "e": 8652, "s": 8221, "text": "In order to let your user access your service which was deployed in Kubernetes, you need to expose your service. There are three ways to access from outside the cluster: Ingress, Load Balancer, and NodePort. In production, NodePort is not recommended since it lacks availability. For Load Balancer, we have already implemented using MetalLB. Now we are going to implement Ingress. Please check the details of Ingress on this site:" }, { "code": null, "e": 8666, "s": 8652, "text": "kubernetes.io" }, { "code": null, "e": 9042, "s": 8666, "text": "From the description of the official Kubernetes documentation, Ingress exposes HTTP and HTTPS routes from outside the cluster to services within the cluster. Traffic routing is controlled by rules defined on the Ingress resource. An Ingress Controller controls the Ingress resource. The one I used is called the NGINX ingress controller. You may install it easily using Helm." }, { "code": null, "e": 9057, "s": 9042, "text": "docs.nginx.com" }, { "code": null, "e": 9180, "s": 9057, "text": "helm repo add nginx-stable https://helm.nginx.com/stablehelm repo updatehelm install my-release nginx-stable/nginx-ingress" }, { "code": null, "e": 9513, "s": 9180, "text": "Data in the pod is ephemeral, if you want your data to be persisted, you store your data in a Persistent Volume. From the description of the official Kubernetes documentation, a PersistentVolume (PV) is a piece of storage in the cluster that has been provisioned by an administrator or dynamically provisioned using Storage Classes." }, { "code": null, "e": 9527, "s": 9513, "text": "kubernetes.io" }, { "code": null, "e": 9704, "s": 9527, "text": "Each StorageClass has a provisioner that handles the volume assignment. The one I chose is Longhorn. From the description of the official Longhorn documentation, it states that" }, { "code": null, "e": 9716, "s": 9704, "text": "longhorn.io" }, { "code": null, "e": 10141, "s": 9716, "text": "Longhorn is a lightweight, reliable, and powerful distributed block storage system for Kubernetes. Longhorn implements distributed block storage using containers and microservices. It creates a dedicated storage controller for each block device volume and synchronously replicates the volume across multiple replicas stored on multiple nodes. The storage controller and replicas are themselves orchestrated using Kubernetes." }, { "code": null, "e": 10282, "s": 10141, "text": "This makes our storage has no single point of failure. It has an intuitive GUI dashboard too, you can view all the details of volumes in it." }, { "code": null, "e": 10363, "s": 10282, "text": "The below installation guide is copied from the official Longhorn documentation:" }, { "code": null, "e": 10383, "s": 10363, "text": "To Install Longhorn" }, { "code": null, "e": 10420, "s": 10383, "text": "1. Add the Longhorn Helm repository:" }, { "code": null, "e": 10470, "s": 10420, "text": "helm repo add longhorn https://charts.longhorn.io" }, { "code": null, "e": 10518, "s": 10470, "text": "2. Fetch the latest charts from the repository:" }, { "code": null, "e": 10535, "s": 10518, "text": "helm repo update" }, { "code": null, "e": 10589, "s": 10535, "text": "3. Install Longhorn in the longhorn-system namespace." }, { "code": null, "e": 10697, "s": 10589, "text": "kubectl create namespace longhorn-systemhelm install longhorn longhorn/longhorn --namespace longhorn-system" }, { "code": null, "e": 10747, "s": 10697, "text": "4. To confirm that the deployment succeeded, run:" }, { "code": null, "e": 10782, "s": 10747, "text": "kubectl -n longhorn-system get pod" }, { "code": null, "e": 10834, "s": 10782, "text": "You should see all pods are running if it is ready." }, { "code": null, "e": 10934, "s": 10834, "text": "You need a registry to store your developed docker image. One of the open-source choices is Harbor." }, { "code": null, "e": 10946, "s": 10934, "text": "goharbor.io" }, { "code": null, "e": 11041, "s": 10946, "text": "Again, you can easily install harbor with Helm chart. The one I used is maintained by bitnami:" }, { "code": null, "e": 11052, "s": 11041, "text": "github.com" }, { "code": null, "e": 11183, "s": 11052, "text": "To conclude, I walk you through the whole installation process of an on-premise Kubernetes cluster. Let’s make a simple checklist:" }, { "code": null, "e": 11457, "s": 11183, "text": "KubesprayAnsible configurationMaster Node HA API Server Load Balancer (HAProxy + keepalived)Proxy settingConfigure kubectl access from outside the clusterService Exposure: Load Balancer and IngressPackage management: HelmStorage: LonghornInternal Image Repository: Registry" }, { "code": null, "e": 11467, "s": 11457, "text": "Kubespray" }, { "code": null, "e": 11489, "s": 11467, "text": "Ansible configuration" }, { "code": null, "e": 11552, "s": 11489, "text": "Master Node HA API Server Load Balancer (HAProxy + keepalived)" }, { "code": null, "e": 11566, "s": 11552, "text": "Proxy setting" }, { "code": null, "e": 11616, "s": 11566, "text": "Configure kubectl access from outside the cluster" }, { "code": null, "e": 11660, "s": 11616, "text": "Service Exposure: Load Balancer and Ingress" }, { "code": null, "e": 11685, "s": 11660, "text": "Package management: Helm" }, { "code": null, "e": 11703, "s": 11685, "text": "Storage: Longhorn" }, { "code": null, "e": 11739, "s": 11703, "text": "Internal Image Repository: Registry" }, { "code": null, "e": 11993, "s": 11739, "text": "It still only covers a part of a production-ready Kubernetes cluster and I am still exploring. Other important aspects are still missing in this article such as monitoring (like Prometheus & Grafana), security (RBAC/User management), CICD (Argo), etc..." }, { "code": null, "e": 12029, "s": 11993, "text": "Welcome to the world of Kubernetes!" }, { "code": null, "e": 12159, "s": 12029, "text": "If you want to know how to prepare for the Certified Kubernetes Application Developer (CKAD) examination, check out this article:" }, { "code": null, "e": 12182, "s": 12159, "text": "towardsdatascience.com" } ]
Conditionally change object property with JavaScript?
To conditionally change object property, use the logical AND operator ( &&). If both the operands are non-zero, then the condition becomes true in JavaScript’s logical AND operator. let marksDetails = { Mark1: 33, Mark2: 89 },isBacklog = false; console.log("Result when backlog is set to false==="); console.log({ ...marksDetails, ...isBacklog === true && { Mark1: 33 }}); isBacklog = true; console.log("Result when backlog is set to true==="); console.log({ ...marksDetails, ...isBacklog === true && { Mark1: 93 }}); To run the above program, you need to use the following command − node fileName.js. Here, my file name is demo77.js. This will produce the following output − PS C:\Users\Amit\JavaScript-code> node demo77.js Result when backlog is set to false=== { Mark1: 33, Mark2: 89 } Result when backlog is set to true=== { Mark1: 93, Mark2: 89 }
[ { "code": null, "e": 1139, "s": 1062, "text": "To conditionally change object property, use the logical AND operator ( &&)." }, { "code": null, "e": 1244, "s": 1139, "text": "If both the operands are non-zero, then the condition becomes true in JavaScript’s logical AND\noperator." }, { "code": null, "e": 1580, "s": 1244, "text": "let marksDetails = { Mark1: 33, Mark2: 89 },isBacklog = false;\nconsole.log(\"Result when backlog is set to false===\");\nconsole.log({ ...marksDetails, ...isBacklog === true && { Mark1: 33 }});\nisBacklog = true;\nconsole.log(\"Result when backlog is set to true===\");\nconsole.log({ ...marksDetails, ...isBacklog === true && { Mark1: 93 }});" }, { "code": null, "e": 1646, "s": 1580, "text": "To run the above program, you need to use the following command −" }, { "code": null, "e": 1664, "s": 1646, "text": "node fileName.js." }, { "code": null, "e": 1697, "s": 1664, "text": "Here, my file name is demo77.js." }, { "code": null, "e": 1738, "s": 1697, "text": "This will produce the following output −" }, { "code": null, "e": 1914, "s": 1738, "text": "PS C:\\Users\\Amit\\JavaScript-code> node demo77.js\nResult when backlog is set to false===\n{ Mark1: 33, Mark2: 89 }\nResult when backlog is set to true===\n{ Mark1: 93, Mark2: 89 }" } ]
How can we disable the cell editing inside a JTable in Java?
A JTable is a subclass of JComponent for displaying complex data structures. A JTable can follow the Model View Controller (MVC) design pattern for displaying the data in rows and columns. A JTable can fire TableModelListener, TableColumnModelListener, ListSelectionListener, CellEditorListener and RowSorterListener interfaces. By default, we can edit the text and modify it inside a JTable cell. We can also disable the cell editing inside a table by calling the editCellAt() method of JTable class and it must return false. import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.table.*; public final class DisableJTableMouseClickTest extends JFrame { private JTable table; private JScrollPane scrollPane; public DisableJTableMouseClickTest() { setTitle("DisableJTableMouseClick Test"); String[] columnNames = {"Country", "Rank"}; Object[][] data = {{"England", "1"}, {"India", "2"}, {"New Zealand", "3"}, {"Australia", "4"}, {"South Africa","5"}, {"Pakistan","6"}}; table = new JTable(data, columnNames) { public boolean editCellAt(int row, int column, java.util.EventObject e) { return false; } }; table.setRowSelectionAllowed(false); scrollPane= new JScrollPane(table); add(scrollPane); setSize(400, 275); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLocationRelativeTo(null); setVisible(true); } public static void main(String[] args) { new DisableJTableMouseClickTest(); } }
[ { "code": null, "e": 1589, "s": 1062, "text": "A JTable is a subclass of JComponent for displaying complex data structures. A JTable can follow the Model View Controller (MVC) design pattern for displaying the data in rows and columns. A JTable can fire TableModelListener, TableColumnModelListener, ListSelectionListener, CellEditorListener and RowSorterListener interfaces. By default, we can edit the text and modify it inside a JTable cell. We can also disable the cell editing inside a table by calling the editCellAt() method of JTable class and it must return false." }, { "code": null, "e": 2613, "s": 1589, "text": "import java.awt.*;\nimport java.awt.event.*;\nimport javax.swing.*;\nimport javax.swing.table.*;\npublic final class DisableJTableMouseClickTest extends JFrame {\n private JTable table;\n private JScrollPane scrollPane;\n public DisableJTableMouseClickTest() {\n setTitle(\"DisableJTableMouseClick Test\");\n String[] columnNames = {\"Country\", \"Rank\"};\n Object[][] data = {{\"England\", \"1\"}, {\"India\", \"2\"}, {\"New Zealand\", \"3\"}, {\"Australia\", \"4\"}, {\"South Africa\",\"5\"}, {\"Pakistan\",\"6\"}};\n table = new JTable(data, columnNames) {\n public boolean editCellAt(int row, int column, java.util.EventObject e) {\n return false;\n }\n };\n table.setRowSelectionAllowed(false);\n scrollPane= new JScrollPane(table);\n add(scrollPane);\n setSize(400, 275);\n setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n setLocationRelativeTo(null);\n setVisible(true);\n }\n public static void main(String[] args) {\n new DisableJTableMouseClickTest();\n }\n}" } ]
Print next greater number of Q queries
30 Jun, 2022 Given an array of n elements and q queries, for each query that has index i, find the next greater element and print its value. If there is no such greater element to its right then print -1. Examples: Input : arr[] = {3, 4, 2, 7, 5, 8, 10, 6} query indexes = {3, 6, 1} Output: 8 -1 7 Explanation : For the 1st query index is 3, element is 7 and the next greater element at its right is 8 For the 2nd query index is 6, element is 10 and there is no element greater than 10 at right, so print -1. For the 3rd query index is 1, element is 4 and the next greater element at its right is 7. Normal Approach: A normal approach will be for every query to move in a loop from index to n and find out the next greater element and print it, but this in worst case will take n iterations, which is a lot if the number of queries are high. Time Complexity: O(n^2) Auxiliary Space>: O(1)Efficient Approach: An efficient approach is based on next greater element. We store the index of the next greater element in an array and for every query process, answer the query in O(1) that will make it more efficient. But to find out the next greater element for every index in array there are two ways. One will take o(n^2) and O(n) space which will be to iterate from I+1 to n for each element at index I and find out the next greater element and store it.But the more efficient one will be to use stack, where we use indexes to compare and store in next[] the next greater element index.1) Push the first index to stack. 2) Pick rest of the indexes one by one and follow following steps in loop. ....a) Mark the current element as i. ....b) If stack is not empty, then pop an index from stack and compare a[index] with a[I]. ....c) If a[I] is greater than the a[index], then a[I] is the next greater element for the a[index]. ....d) Keep popping from the stack while the popped index element is smaller than a[I]. a[I] becomes the next greater element for all such popped elements ....g) If a[I] is smaller than the popped index element, then push the popped index back.3) After the loop in step 2 is over, pop all the index from stack and print -1 as next index for them. C++ Java Python3 C# Javascript // C++ program to print// next greater number// of Q queries#include <bits/stdc++.h>using namespace std; // array to store the next// greater element indexvoid next_greatest(int next[], int a[], int n){ // use of stl // stack in c++ stack<int> s; // push the 0th // index to the stack s.push(0); // traverse in the // loop from 1-nth index for (int i = 1; i < n; i++) { // iterate till loop is empty while (!s.empty()) { // get the topmost // index in the stack int cur = s.top(); // if the current element is // greater than the top indexth // element, then this will be // the next greatest index // of the top indexth element if (a[cur] < a[i]) { // initialise the cur // index position's // next greatest as index next[cur] = i; // pop the cur index // as its greater // element has been found s.pop(); } // if not greater // then break else break; } // push the i index so that its // next greatest can be found s.push(i); } // iterate for all other // index left inside stack while (!s.empty()) { int cur = s.top(); // mark it as -1 as no // element in greater // then it in right next[cur] = -1; s.pop(); }} // answers all// queries in O(1)int answer_query(int a[], int next[], int n, int index){ // stores the next greater // element positions int position = next[index]; // if position is -1 then no // greater element is at right. if (position == -1) return -1; // if there is a index that // has greater element // at right then return its // value as a[position] else return a[position];} // Driver Codeint main(){ int a[] = {3, 4, 2, 7, 5, 8, 10, 6 }; int n = sizeof(a) / sizeof(a[0]); // initializes the // next array as 0 int next[n] = { 0 }; // calls the function // to pre-calculate // the next greatest // element indexes next_greatest(next, a, n); // query 1 answered cout << answer_query(a, next, n, 3) << " "; // query 2 answered cout << answer_query(a, next, n, 6) << " "; // query 3 answered cout << answer_query(a, next, n, 1) << " ";} // Java program to print// next greater number// of Q queriesimport java.util.*; class GFG{public static int[] query(int arr[], int query[]){ int ans[] = new int[arr.length];// this array contains // the next greatest // elements of all the elements Stack<Integer> s = new Stack<>(); // push the 0th index // to the stack s.push(arr[0]); int j = 0; //traverse rest // of the array for(int i = 1; i < arr.length; i++) { int next = arr[i]; if(!s.isEmpty()) { // get the topmost // element in the stack int element = s.pop(); /* If the popped element is smaller than next, then a) store the pair b) keep popping while elements are smaller and stack is not empty */ while(next > element) { ans[j] = next; j++; if(s.isEmpty()) break; element = s.pop(); } /* If element is greater than next, then push the element back */ if (element > next) s.push(element); } /* push next to stack so that we can find next greater for it */ s.push(next); } /* After iterating over the loop, the remaining elements in stack do not have the next greater element, so -1 for them */ while(!s.isEmpty()) { int element = s.pop(); ans[j] = -1; j++; } // return the next // greatest array return ans;} // Driver Code public static void main(String[] args){ int arr[] = {3, 4, 2, 7, 5, 8, 10, 6}; int query[] = {3, 6, 1}; int ans[] = query(arr,query); // getting output array // with next greatest elements for(int i = 0; i < query.length; i++) { // displaying the next greater // element for given set of queries System.out.print(ans[query[i]] + " "); }}} // This code was contributed// by Harshit Sood # Python3 program to print# next greater number# of Q queries # array to store the next# greater element indexdef next_greatest(next, a, n): # use of stl # stack in c++ s = [] # push the 0th # index to the stack s.append(0); # traverse in the # loop from 1-nth index for i in range(1, n): # iterate till loop is empty while (len(s) != 0): # get the topmost # index in the stack cur = s[-1] # if the current element is # greater then the top indexth # element, then this will be # the next greatest index # of the top indexth element if (a[cur] < a[i]): # initialise the cur # index position's # next greatest as index next[cur] = i; # pop the cur index # as its greater # element has been found s.pop(); # if not greater # then break else: break; # push the i index so that its # next greatest can be found s.append(i); # iterate for all other # index left inside stack while(len(s) != 0): cur = s[-1] # mark it as -1 as no # element in greater # then it in right next[cur] = -1; s.pop(); # answers all# queries in O(1)def answer_query(a, next, n, index): # stores the next greater # element positions position = next[index]; # if position is -1 then no # greater element is at right. if(position == -1): return -1; # if there is a index that # has greater element # at right then return its # value as a[position] else: return a[position]; # Driver Codeif __name__=='__main__': a = [3, 4, 2, 7, 5, 8, 10, 6 ] n = len(a) # initializes the # next array as 0 next=[0 for i in range(n)] # calls the function # to pre-calculate # the next greatest # element indexes next_greatest(next, a, n); # query 1 answered print(answer_query(a, next, n, 3), end = ' ') # query 2 answered print(answer_query(a, next, n, 6), end = ' ') # query 3 answered print(answer_query(a, next, n, 1), end = ' ') # This code is contributed by rutvik_56. // C# program to print next greater// number of Q queriesusing System;using System.Collections.Generic; class GFG{public static int[] query(int[] arr, int[] query){ int[] ans = new int[arr.Length]; // this array contains // the next greatest // elements of all the elements Stack<int> s = new Stack<int>(); // push the 0th index to the stack s.Push(arr[0]); int j = 0; // traverse rest of the array for (int i = 1; i < arr.Length; i++) { int next = arr[i]; if (s.Count > 0) { // get the topmost element in the stack int element = s.Pop(); /* If the popped element is smaller than next, then a) store the pair b) keep popping while elements are smaller and stack is not empty */ while (next > element) { ans[j] = next; j++; if (s.Count == 0) { break; } element = s.Pop(); } /* If element is greater than next, then push the element back */ if (element > next) { s.Push(element); } } /* push next to stack so that we can find next greater for it */ s.Push(next); } /* After iterating over the loop, the remaining elements in stack do not have the next greater element, so -1 for them */ while (s.Count > 0) { int element = s.Pop(); ans[j] = -1; j++; } // return the next greatest array return ans;} // Driver Code public static void Main(string[] args){ int[] arr = new int[] {3, 4, 2, 7, 5, 8, 10, 6}; int[] query = new int[] {3, 6, 1}; int[] ans = GFG.query(arr, query); // getting output array // with next greatest elements for (int i = 0; i < query.Length; i++) { // displaying the next greater // element for given set of queries Console.Write(ans[query[i]] + " "); }}} // This code is contributed by Shrikant13 <script> // JavaScript program to print// next greater number// of Q queries // array to store the next// greater element indexfunction next_greatest(next, a, n){ // use of stl // stack in c++ var s = []; // push the 0th // index to the stack s.push(0); // traverse in the // loop from 1-nth index for (var i = 1; i < n; i++) { // iterate till loop is empty while (s.length!=0) { // get the topmost // index in the stack var cur = s[s.length-1]; // if the current element is // greater then the top indexth // element, then this will be // the next greatest index // of the top indexth element if (a[cur] < a[i]) { // initialise the cur // index position's // next greatest as index next[cur] = i; // pop the cur index // as its greater // element has been found s.pop(); } // if not greater // then break else break; } // push the i index so that its // next greatest can be found s.push(i); } // iterate for all other // index left inside stack while (s.length!=0) { var cur = s[s.length-1]; // mark it as -1 as no // element in greater // then it in right next[cur] = -1; s.pop(); }} // answers all// queries in O(1)function answer_query(a, next, n, index){ // stores the next greater // element positions var position = next[index]; // if position is -1 then no // greater element is at right. if (position == -1) return -1; // if there is a index that // has greater element // at right then return its // value as a[position] else return a[position];} // Driver Codevar a = [3, 4, 2, 7, 5, 8, 10, 6];var n = a.length;// initializes the// next array as 0var next = Array(n).fill(0);// calls the function// to pre-calculate// the next greatest// element indexesnext_greatest(next, a, n);// query 1 answereddocument.write( answer_query(a, next, n, 3) + " ");// query 2 answereddocument.write( answer_query(a, next, n, 6) + " ");// query 3 answereddocument.write( answer_query(a, next, n, 1) + " "); </script> Output: 8 -1 7 Time complexity: max(O(n), O(q)), O(n) for pre-processing the next[] array and O(1) for every query.Auxiliary Space: O(n)This article is contributed by Raja Vikramaditya(raj). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. HarshitSood1 shrikanth13 rutvik_56 itsok simmytarika5 mitalibhola94 Arrays Stack Arrays Stack Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n30 Jun, 2022" }, { "code": null, "e": 256, "s": 52, "text": "Given an array of n elements and q queries, for each query that has index i, find the next greater element and print its value. If there is no such greater element to its right then print -1. Examples: " }, { "code": null, "e": 658, "s": 256, "text": "Input : arr[] = {3, 4, 2, 7, 5, 8, 10, 6} \n query indexes = {3, 6, 1}\nOutput: 8 -1 7 \nExplanation : \nFor the 1st query index is 3, element is 7 and \nthe next greater element at its right is 8 \n\nFor the 2nd query index is 6, element is 10 and \nthere is no element greater than 10 at right, \nso print -1.\n\nFor the 3rd query index is 1, element is 4 and\nthe next greater element at its right is 7." }, { "code": null, "e": 2230, "s": 660, "text": "Normal Approach: A normal approach will be for every query to move in a loop from index to n and find out the next greater element and print it, but this in worst case will take n iterations, which is a lot if the number of queries are high. Time Complexity: O(n^2) Auxiliary Space>: O(1)Efficient Approach: An efficient approach is based on next greater element. We store the index of the next greater element in an array and for every query process, answer the query in O(1) that will make it more efficient. But to find out the next greater element for every index in array there are two ways. One will take o(n^2) and O(n) space which will be to iterate from I+1 to n for each element at index I and find out the next greater element and store it.But the more efficient one will be to use stack, where we use indexes to compare and store in next[] the next greater element index.1) Push the first index to stack. 2) Pick rest of the indexes one by one and follow following steps in loop. ....a) Mark the current element as i. ....b) If stack is not empty, then pop an index from stack and compare a[index] with a[I]. ....c) If a[I] is greater than the a[index], then a[I] is the next greater element for the a[index]. ....d) Keep popping from the stack while the popped index element is smaller than a[I]. a[I] becomes the next greater element for all such popped elements ....g) If a[I] is smaller than the popped index element, then push the popped index back.3) After the loop in step 2 is over, pop all the index from stack and print -1 as next index for them. " }, { "code": null, "e": 2234, "s": 2230, "text": "C++" }, { "code": null, "e": 2239, "s": 2234, "text": "Java" }, { "code": null, "e": 2247, "s": 2239, "text": "Python3" }, { "code": null, "e": 2250, "s": 2247, "text": "C#" }, { "code": null, "e": 2261, "s": 2250, "text": "Javascript" }, { "code": "// C++ program to print// next greater number// of Q queries#include <bits/stdc++.h>using namespace std; // array to store the next// greater element indexvoid next_greatest(int next[], int a[], int n){ // use of stl // stack in c++ stack<int> s; // push the 0th // index to the stack s.push(0); // traverse in the // loop from 1-nth index for (int i = 1; i < n; i++) { // iterate till loop is empty while (!s.empty()) { // get the topmost // index in the stack int cur = s.top(); // if the current element is // greater than the top indexth // element, then this will be // the next greatest index // of the top indexth element if (a[cur] < a[i]) { // initialise the cur // index position's // next greatest as index next[cur] = i; // pop the cur index // as its greater // element has been found s.pop(); } // if not greater // then break else break; } // push the i index so that its // next greatest can be found s.push(i); } // iterate for all other // index left inside stack while (!s.empty()) { int cur = s.top(); // mark it as -1 as no // element in greater // then it in right next[cur] = -1; s.pop(); }} // answers all// queries in O(1)int answer_query(int a[], int next[], int n, int index){ // stores the next greater // element positions int position = next[index]; // if position is -1 then no // greater element is at right. if (position == -1) return -1; // if there is a index that // has greater element // at right then return its // value as a[position] else return a[position];} // Driver Codeint main(){ int a[] = {3, 4, 2, 7, 5, 8, 10, 6 }; int n = sizeof(a) / sizeof(a[0]); // initializes the // next array as 0 int next[n] = { 0 }; // calls the function // to pre-calculate // the next greatest // element indexes next_greatest(next, a, n); // query 1 answered cout << answer_query(a, next, n, 3) << \" \"; // query 2 answered cout << answer_query(a, next, n, 6) << \" \"; // query 3 answered cout << answer_query(a, next, n, 1) << \" \";}", "e": 4822, "s": 2261, "text": null }, { "code": "// Java program to print// next greater number// of Q queriesimport java.util.*; class GFG{public static int[] query(int arr[], int query[]){ int ans[] = new int[arr.length];// this array contains // the next greatest // elements of all the elements Stack<Integer> s = new Stack<>(); // push the 0th index // to the stack s.push(arr[0]); int j = 0; //traverse rest // of the array for(int i = 1; i < arr.length; i++) { int next = arr[i]; if(!s.isEmpty()) { // get the topmost // element in the stack int element = s.pop(); /* If the popped element is smaller than next, then a) store the pair b) keep popping while elements are smaller and stack is not empty */ while(next > element) { ans[j] = next; j++; if(s.isEmpty()) break; element = s.pop(); } /* If element is greater than next, then push the element back */ if (element > next) s.push(element); } /* push next to stack so that we can find next greater for it */ s.push(next); } /* After iterating over the loop, the remaining elements in stack do not have the next greater element, so -1 for them */ while(!s.isEmpty()) { int element = s.pop(); ans[j] = -1; j++; } // return the next // greatest array return ans;} // Driver Code public static void main(String[] args){ int arr[] = {3, 4, 2, 7, 5, 8, 10, 6}; int query[] = {3, 6, 1}; int ans[] = query(arr,query); // getting output array // with next greatest elements for(int i = 0; i < query.length; i++) { // displaying the next greater // element for given set of queries System.out.print(ans[query[i]] + \" \"); }}} // This code was contributed// by Harshit Sood", "e": 7009, "s": 4822, "text": null }, { "code": "# Python3 program to print# next greater number# of Q queries # array to store the next# greater element indexdef next_greatest(next, a, n): # use of stl # stack in c++ s = [] # push the 0th # index to the stack s.append(0); # traverse in the # loop from 1-nth index for i in range(1, n): # iterate till loop is empty while (len(s) != 0): # get the topmost # index in the stack cur = s[-1] # if the current element is # greater then the top indexth # element, then this will be # the next greatest index # of the top indexth element if (a[cur] < a[i]): # initialise the cur # index position's # next greatest as index next[cur] = i; # pop the cur index # as its greater # element has been found s.pop(); # if not greater # then break else: break; # push the i index so that its # next greatest can be found s.append(i); # iterate for all other # index left inside stack while(len(s) != 0): cur = s[-1] # mark it as -1 as no # element in greater # then it in right next[cur] = -1; s.pop(); # answers all# queries in O(1)def answer_query(a, next, n, index): # stores the next greater # element positions position = next[index]; # if position is -1 then no # greater element is at right. if(position == -1): return -1; # if there is a index that # has greater element # at right then return its # value as a[position] else: return a[position]; # Driver Codeif __name__=='__main__': a = [3, 4, 2, 7, 5, 8, 10, 6 ] n = len(a) # initializes the # next array as 0 next=[0 for i in range(n)] # calls the function # to pre-calculate # the next greatest # element indexes next_greatest(next, a, n); # query 1 answered print(answer_query(a, next, n, 3), end = ' ') # query 2 answered print(answer_query(a, next, n, 6), end = ' ') # query 3 answered print(answer_query(a, next, n, 1), end = ' ') # This code is contributed by rutvik_56.", "e": 9360, "s": 7009, "text": null }, { "code": "// C# program to print next greater// number of Q queriesusing System;using System.Collections.Generic; class GFG{public static int[] query(int[] arr, int[] query){ int[] ans = new int[arr.Length]; // this array contains // the next greatest // elements of all the elements Stack<int> s = new Stack<int>(); // push the 0th index to the stack s.Push(arr[0]); int j = 0; // traverse rest of the array for (int i = 1; i < arr.Length; i++) { int next = arr[i]; if (s.Count > 0) { // get the topmost element in the stack int element = s.Pop(); /* If the popped element is smaller than next, then a) store the pair b) keep popping while elements are smaller and stack is not empty */ while (next > element) { ans[j] = next; j++; if (s.Count == 0) { break; } element = s.Pop(); } /* If element is greater than next, then push the element back */ if (element > next) { s.Push(element); } } /* push next to stack so that we can find next greater for it */ s.Push(next); } /* After iterating over the loop, the remaining elements in stack do not have the next greater element, so -1 for them */ while (s.Count > 0) { int element = s.Pop(); ans[j] = -1; j++; } // return the next greatest array return ans;} // Driver Code public static void Main(string[] args){ int[] arr = new int[] {3, 4, 2, 7, 5, 8, 10, 6}; int[] query = new int[] {3, 6, 1}; int[] ans = GFG.query(arr, query); // getting output array // with next greatest elements for (int i = 0; i < query.Length; i++) { // displaying the next greater // element for given set of queries Console.Write(ans[query[i]] + \" \"); }}} // This code is contributed by Shrikant13", "e": 11576, "s": 9360, "text": null }, { "code": "<script> // JavaScript program to print// next greater number// of Q queries // array to store the next// greater element indexfunction next_greatest(next, a, n){ // use of stl // stack in c++ var s = []; // push the 0th // index to the stack s.push(0); // traverse in the // loop from 1-nth index for (var i = 1; i < n; i++) { // iterate till loop is empty while (s.length!=0) { // get the topmost // index in the stack var cur = s[s.length-1]; // if the current element is // greater then the top indexth // element, then this will be // the next greatest index // of the top indexth element if (a[cur] < a[i]) { // initialise the cur // index position's // next greatest as index next[cur] = i; // pop the cur index // as its greater // element has been found s.pop(); } // if not greater // then break else break; } // push the i index so that its // next greatest can be found s.push(i); } // iterate for all other // index left inside stack while (s.length!=0) { var cur = s[s.length-1]; // mark it as -1 as no // element in greater // then it in right next[cur] = -1; s.pop(); }} // answers all// queries in O(1)function answer_query(a, next, n, index){ // stores the next greater // element positions var position = next[index]; // if position is -1 then no // greater element is at right. if (position == -1) return -1; // if there is a index that // has greater element // at right then return its // value as a[position] else return a[position];} // Driver Codevar a = [3, 4, 2, 7, 5, 8, 10, 6];var n = a.length;// initializes the// next array as 0var next = Array(n).fill(0);// calls the function// to pre-calculate// the next greatest// element indexesnext_greatest(next, a, n);// query 1 answereddocument.write( answer_query(a, next, n, 3) + \" \");// query 2 answereddocument.write( answer_query(a, next, n, 6) + \" \");// query 3 answereddocument.write( answer_query(a, next, n, 1) + \" \"); </script>", "e": 13998, "s": 11576, "text": null }, { "code": null, "e": 14008, "s": 13998, "text": "Output: " }, { "code": null, "e": 14016, "s": 14008, "text": "8 -1 7 " }, { "code": null, "e": 14568, "s": 14016, "text": "Time complexity: max(O(n), O(q)), O(n) for pre-processing the next[] array and O(1) for every query.Auxiliary Space: O(n)This article is contributed by Raja Vikramaditya(raj). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 14581, "s": 14568, "text": "HarshitSood1" }, { "code": null, "e": 14593, "s": 14581, "text": "shrikanth13" }, { "code": null, "e": 14603, "s": 14593, "text": "rutvik_56" }, { "code": null, "e": 14609, "s": 14603, "text": "itsok" }, { "code": null, "e": 14622, "s": 14609, "text": "simmytarika5" }, { "code": null, "e": 14636, "s": 14622, "text": "mitalibhola94" }, { "code": null, "e": 14643, "s": 14636, "text": "Arrays" }, { "code": null, "e": 14649, "s": 14643, "text": "Stack" }, { "code": null, "e": 14656, "s": 14649, "text": "Arrays" }, { "code": null, "e": 14662, "s": 14656, "text": "Stack" } ]
Kotlin Coroutines on Android
04 Sep, 2020 Asynchronous programming is very important and it’s now a common part of modern application. It increases the amount of work that your app can perform in parallel. This allows running heavy tasks away from UI Thread in the background, which ultimately gives a smooth and better experience to the user of the app. The Kotlin team defines coroutines as “lightweight threads”. They are sort of tasks that the actual threads can execute. Coroutines were added to Kotlin in version 1.3 and are based on established concepts from other languages. Kotlin coroutines introduce a new style of concurrency that can be used on Android to simplify async code. The official documentation says that coroutines are lightweight threads. By lightweight, it means that creating coroutines doesn’t allocate new threads. Instead, they use predefined thread pools and smart scheduling for the purpose of which task to execute next and which tasks later. Coroutines are basically of two types: Stackless Stackful Kotlin implements stackless coroutines, it means that the coroutines don’t have their own stack, so they don’t map on the native thread. As we know android developers today have many async tools in hand. These include RxJava, AsyncTasks, Jobs, Threads. So why there is a need to learn something new? While Using Rx, it requires a lot of effort to get it enough, to use it safely. On the Other hand, AsyncTasks and threads can easily introduce leaks and memory overhead. Even using these tools after so many disadvantages, the code can suffer from callbacks, which can introduce tons of extra code. Not only that, but the code also becomes unreadable as it has many callbacks which ultimately slow down or hang the device leading to poor user experience. Android is a single thread platform, By default, everything runs on the main thread. In Android, almost every application needs to perform some non UI operations like (Network call, I/O operations), so when coroutines concept is not introduced, what is done is that programmer dedicate this task to different threads, each thread executes the task given to it, when the task is completed, they return the result to UI thread to update the changes required. Though In android there is a detailed procedure given, about how to perform this task in an effective way using best practices using threads, this procedure includes lots of callbacks for passing the result among threads, which ultimately introduce tons of code in our application and the waiting time to get the result back to increases. On Android, Every app has a main thread (which handles all the UI operations like drawing views and other user interactions. If there is too much work happening on this main thread, like network calls (eg fetching a web page), the apps will appear to hang or slow down leading to poor user experience. Coroutines is the recommended solution for asynchronous programming on Android. Some highlighted features of coroutines are given below. Lightweight: One can run many coroutines on a single thread due to support for suspension, which doesn’t block the thread where the coroutine is running. Suspending frees memory over blocking while supporting multiple concurrent operations. Built-in cancellation support: Cancellation is generated automatically through the running coroutine hierarchy. Fewer memory leaks: It uses structured concurrency to run operations within a scope. Jetpack integration: Many Jetpack libraries include extensions that provide full coroutines support. Some libraries also provide their own coroutine scope that one can use for structured concurrency. Fetching the data from one thread and passing it to another thread takes a lot of time. It also introduces lots of callbacks, leading to less readability of code. On the other hand, coroutines eliminate callbacks. Creating and stopping a thread is an expensive job, as it involves creating their own stacks.,whereas creating coroutines is very cheap when compared to the performance it offers. coroutines do not have their own stack. Threads are blocking, whereas coroutines are suspendable. By blocking it means that when a thread sleeps for some duration, the entire threads get blocked, it cannot do any other operation, whereas since coroutines are suspendable, so when they are delayed for some seconds, they can perform any other work. Coroutines offer a very high level of concurrency as compared to threads, as multiple threads involve blocking and context switching. Context switching with threads is slower as compared to coroutines, as with threads context can only be switched when the job of 1 thread gets over, but with coroutines, they can change context any time, as they are suspendable. Coroutines are light and super fast. Coroutines are faster than threads, as threads are managed by Operating System, whereas coroutines are managed by users. Having thousands of coroutines working together are much better than having tens of threads working together. Add these dependencies in build.gradle app-level file. Kotlin // dependencies to import in project dependencies { implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:x.x.x" implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:x.x.x"} Note: x.x.x is the version of the coroutine. Let’s say we want to fetch some users from the database and show it on the screen. For fetching the data from the database we have to perform the network call, fetch the user from the database, and show it on the screen. Fetching the user can be done by using either by using callbacks or coroutines. Using Callbacks: Kotlin // pseudo kotlin code for demonstration// involves a series of callbacks from fetchAndShowUser // to fetchUser and then to showUserfun fetchAndShowUser() { fetchUser { user -> showUser(user) }} Using Coroutines: Kotlin //pseudo kotlin code for demonstrationsuspend fun fetchAndShowUser() { // fetch on IO thread val user = fetchUser() // back on UI thread showUser(user)} As discussed above using callbacks will decrease the code readability, so using coroutines is much better to use in terms of readability and performance as well. As discussed above Coroutines has many advantages apart from not having callbacks, like they are nonblocking, easy, and nonexpensive to create. android Android Kotlin Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n04 Sep, 2020" }, { "code": null, "e": 367, "s": 54, "text": "Asynchronous programming is very important and it’s now a common part of modern application. It increases the amount of work that your app can perform in parallel. This allows running heavy tasks away from UI Thread in the background, which ultimately gives a smooth and better experience to the user of the app." }, { "code": null, "e": 702, "s": 367, "text": "The Kotlin team defines coroutines as “lightweight threads”. They are sort of tasks that the actual threads can execute. Coroutines were added to Kotlin in version 1.3 and are based on established concepts from other languages. Kotlin coroutines introduce a new style of concurrency that can be used on Android to simplify async code." }, { "code": null, "e": 987, "s": 702, "text": "The official documentation says that coroutines are lightweight threads. By lightweight, it means that creating coroutines doesn’t allocate new threads. Instead, they use predefined thread pools and smart scheduling for the purpose of which task to execute next and which tasks later." }, { "code": null, "e": 1026, "s": 987, "text": "Coroutines are basically of two types:" }, { "code": null, "e": 1036, "s": 1026, "text": "Stackless" }, { "code": null, "e": 1045, "s": 1036, "text": "Stackful" }, { "code": null, "e": 1182, "s": 1045, "text": "Kotlin implements stackless coroutines, it means that the coroutines don’t have their own stack, so they don’t map on the native thread." }, { "code": null, "e": 1345, "s": 1182, "text": "As we know android developers today have many async tools in hand. These include RxJava, AsyncTasks, Jobs, Threads. So why there is a need to learn something new?" }, { "code": null, "e": 1799, "s": 1345, "text": "While Using Rx, it requires a lot of effort to get it enough, to use it safely. On the Other hand, AsyncTasks and threads can easily introduce leaks and memory overhead. Even using these tools after so many disadvantages, the code can suffer from callbacks, which can introduce tons of extra code. Not only that, but the code also becomes unreadable as it has many callbacks which ultimately slow down or hang the device leading to poor user experience." }, { "code": null, "e": 2595, "s": 1799, "text": "Android is a single thread platform, By default, everything runs on the main thread. In Android, almost every application needs to perform some non UI operations like (Network call, I/O operations), so when coroutines concept is not introduced, what is done is that programmer dedicate this task to different threads, each thread executes the task given to it, when the task is completed, they return the result to UI thread to update the changes required. Though In android there is a detailed procedure given, about how to perform this task in an effective way using best practices using threads, this procedure includes lots of callbacks for passing the result among threads, which ultimately introduce tons of code in our application and the waiting time to get the result back to increases." }, { "code": null, "e": 2897, "s": 2595, "text": "On Android, Every app has a main thread (which handles all the UI operations like drawing views and other user interactions. If there is too much work happening on this main thread, like network calls (eg fetching a web page), the apps will appear to hang or slow down leading to poor user experience." }, { "code": null, "e": 3034, "s": 2897, "text": "Coroutines is the recommended solution for asynchronous programming on Android. Some highlighted features of coroutines are given below." }, { "code": null, "e": 3275, "s": 3034, "text": "Lightweight: One can run many coroutines on a single thread due to support for suspension, which doesn’t block the thread where the coroutine is running. Suspending frees memory over blocking while supporting multiple concurrent operations." }, { "code": null, "e": 3387, "s": 3275, "text": "Built-in cancellation support: Cancellation is generated automatically through the running coroutine hierarchy." }, { "code": null, "e": 3472, "s": 3387, "text": "Fewer memory leaks: It uses structured concurrency to run operations within a scope." }, { "code": null, "e": 3672, "s": 3472, "text": "Jetpack integration: Many Jetpack libraries include extensions that provide full coroutines support. Some libraries also provide their own coroutine scope that one can use for structured concurrency." }, { "code": null, "e": 3886, "s": 3672, "text": "Fetching the data from one thread and passing it to another thread takes a lot of time. It also introduces lots of callbacks, leading to less readability of code. On the other hand, coroutines eliminate callbacks." }, { "code": null, "e": 4106, "s": 3886, "text": "Creating and stopping a thread is an expensive job, as it involves creating their own stacks.,whereas creating coroutines is very cheap when compared to the performance it offers. coroutines do not have their own stack." }, { "code": null, "e": 4414, "s": 4106, "text": "Threads are blocking, whereas coroutines are suspendable. By blocking it means that when a thread sleeps for some duration, the entire threads get blocked, it cannot do any other operation, whereas since coroutines are suspendable, so when they are delayed for some seconds, they can perform any other work." }, { "code": null, "e": 4777, "s": 4414, "text": "Coroutines offer a very high level of concurrency as compared to threads, as multiple threads involve blocking and context switching. Context switching with threads is slower as compared to coroutines, as with threads context can only be switched when the job of 1 thread gets over, but with coroutines, they can change context any time, as they are suspendable." }, { "code": null, "e": 5045, "s": 4777, "text": "Coroutines are light and super fast. Coroutines are faster than threads, as threads are managed by Operating System, whereas coroutines are managed by users. Having thousands of coroutines working together are much better than having tens of threads working together." }, { "code": null, "e": 5100, "s": 5045, "text": "Add these dependencies in build.gradle app-level file." }, { "code": null, "e": 5107, "s": 5100, "text": "Kotlin" }, { "code": "// dependencies to import in project dependencies { implementation \"org.jetbrains.kotlinx:kotlinx-coroutines-core:x.x.x\" implementation \"org.jetbrains.kotlinx:kotlinx-coroutines-android:x.x.x\"}", "e": 5303, "s": 5107, "text": null }, { "code": null, "e": 5348, "s": 5303, "text": "Note: x.x.x is the version of the coroutine." }, { "code": null, "e": 5649, "s": 5348, "text": "Let’s say we want to fetch some users from the database and show it on the screen. For fetching the data from the database we have to perform the network call, fetch the user from the database, and show it on the screen. Fetching the user can be done by using either by using callbacks or coroutines." }, { "code": null, "e": 5666, "s": 5649, "text": "Using Callbacks:" }, { "code": null, "e": 5673, "s": 5666, "text": "Kotlin" }, { "code": "// pseudo kotlin code for demonstration// involves a series of callbacks from fetchAndShowUser // to fetchUser and then to showUserfun fetchAndShowUser() { fetchUser { user -> showUser(user) }}", "e": 5874, "s": 5673, "text": null }, { "code": null, "e": 5892, "s": 5874, "text": "Using Coroutines:" }, { "code": null, "e": 5899, "s": 5892, "text": "Kotlin" }, { "code": "//pseudo kotlin code for demonstrationsuspend fun fetchAndShowUser() { // fetch on IO thread val user = fetchUser() // back on UI thread showUser(user)}", "e": 6057, "s": 5899, "text": null }, { "code": null, "e": 6370, "s": 6057, "text": "As discussed above using callbacks will decrease the code readability, so using coroutines is much better to use in terms of readability and performance as well. As discussed above Coroutines has many advantages apart from not having callbacks, like they are nonblocking, easy, and nonexpensive to create. " }, { "code": null, "e": 6378, "s": 6370, "text": "android" }, { "code": null, "e": 6386, "s": 6378, "text": "Android" }, { "code": null, "e": 6393, "s": 6386, "text": "Kotlin" }, { "code": null, "e": 6401, "s": 6393, "text": "Android" } ]
time.Sleep() Function in Golang With Examples
01 Apr, 2020 In Go language, time packages supplies functionality for determining as well as viewing time.The Sleep() function in Go language is used to stop the latest go-routine for at least the stated duration d. And a negative or zero duration of sleep will cause this method to return instantly. Moreover, this function is defined under the time package. Here, you need to import the “time” package to use these functions. Syntax: func Sleep(d Duration) Here, d is the duration of time in seconds to sleep. Return Value: It pauses the latest go-routine for the stated duration then returns the output of any operation after the sleep is over. Example 1: // Golang program to illustrate the usage of// Sleep() function // Including main packagepackage main // Importing fmt and timeimport ( "fmt" "time") // Main functionfunc main() { // Calling Sleep method time.Sleep(8 * time.Second) // Printed after sleep is over fmt.Println("Sleep Over.....")} Output: Sleep Over..... Here, after running the above code when the main function is called then due to Sleep method the stated operation is stopped for the given duration then the result is printed. Example 2: // Golang program to illustrate the usage of// Sleep() function // Including main packagepackage main // Importing time and fmtimport ( "fmt" "time") // Main functionfunc main() { // Creating channel using // make keyword mychan1 := make(chan string, 2) // Calling Sleep function of go go func() { time.Sleep(2 * time.Second) // Displayed after sleep overs mychan1 <- "output1" }() // Select statement select { // Case statement case out := <-mychan1: fmt.Println(out) // Calling After method case <-time.After(3 * time.Second): fmt.Println("timeout....1") } // Again Creating channel using // make keyword mychan2 := make(chan string, 2) // Calling Sleep method of go go func() { time.Sleep(6 * time.Second) // Printed after sleep overs mychan2 <- "output2" }() // Select statement select { // Case statement case out := <-mychan2: fmt.Println(out) // Calling After method case <-time.After(3 * time.Second): fmt.Println("timeout....2") }} Output: output1 timeout....2 Here, in the above code “output1” is printed as the duration of timeout(in After() method) is greater than the sleep time(in Sleep() method) so, the output is printed before the timeout is displayed but after that, the below case has timeout duration less than the sleep time so, before printing the output the timeout is displayed hence, “timeout....2” is printed. GoLang-time Go Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n01 Apr, 2020" }, { "code": null, "e": 467, "s": 52, "text": "In Go language, time packages supplies functionality for determining as well as viewing time.The Sleep() function in Go language is used to stop the latest go-routine for at least the stated duration d. And a negative or zero duration of sleep will cause this method to return instantly. Moreover, this function is defined under the time package. Here, you need to import the “time” package to use these functions." }, { "code": null, "e": 475, "s": 467, "text": "Syntax:" }, { "code": null, "e": 499, "s": 475, "text": "func Sleep(d Duration)\n" }, { "code": null, "e": 552, "s": 499, "text": "Here, d is the duration of time in seconds to sleep." }, { "code": null, "e": 688, "s": 552, "text": "Return Value: It pauses the latest go-routine for the stated duration then returns the output of any operation after the sleep is over." }, { "code": null, "e": 699, "s": 688, "text": "Example 1:" }, { "code": "// Golang program to illustrate the usage of// Sleep() function // Including main packagepackage main // Importing fmt and timeimport ( \"fmt\" \"time\") // Main functionfunc main() { // Calling Sleep method time.Sleep(8 * time.Second) // Printed after sleep is over fmt.Println(\"Sleep Over.....\")}", "e": 1019, "s": 699, "text": null }, { "code": null, "e": 1027, "s": 1019, "text": "Output:" }, { "code": null, "e": 1044, "s": 1027, "text": "Sleep Over.....\n" }, { "code": null, "e": 1220, "s": 1044, "text": "Here, after running the above code when the main function is called then due to Sleep method the stated operation is stopped for the given duration then the result is printed." }, { "code": null, "e": 1231, "s": 1220, "text": "Example 2:" }, { "code": "// Golang program to illustrate the usage of// Sleep() function // Including main packagepackage main // Importing time and fmtimport ( \"fmt\" \"time\") // Main functionfunc main() { // Creating channel using // make keyword mychan1 := make(chan string, 2) // Calling Sleep function of go go func() { time.Sleep(2 * time.Second) // Displayed after sleep overs mychan1 <- \"output1\" }() // Select statement select { // Case statement case out := <-mychan1: fmt.Println(out) // Calling After method case <-time.After(3 * time.Second): fmt.Println(\"timeout....1\") } // Again Creating channel using // make keyword mychan2 := make(chan string, 2) // Calling Sleep method of go go func() { time.Sleep(6 * time.Second) // Printed after sleep overs mychan2 <- \"output2\" }() // Select statement select { // Case statement case out := <-mychan2: fmt.Println(out) // Calling After method case <-time.After(3 * time.Second): fmt.Println(\"timeout....2\") }}", "e": 2353, "s": 1231, "text": null }, { "code": null, "e": 2361, "s": 2353, "text": "Output:" }, { "code": null, "e": 2383, "s": 2361, "text": "output1\ntimeout....2\n" }, { "code": null, "e": 2749, "s": 2383, "text": "Here, in the above code “output1” is printed as the duration of timeout(in After() method) is greater than the sleep time(in Sleep() method) so, the output is printed before the timeout is displayed but after that, the below case has timeout duration less than the sleep time so, before printing the output the timeout is displayed hence, “timeout....2” is printed." }, { "code": null, "e": 2761, "s": 2749, "text": "GoLang-time" }, { "code": null, "e": 2773, "s": 2761, "text": "Go Language" } ]
Happens-Before Relationship in Java
18 Apr, 2022 Prerequisite: Threading, Synchronized Block, and volatile Keyword Happens-before is a concept, a phenomenon, or simply a set of rules that define the basis for reordering of instructions by a compiler or CPU. Happens-before is not any keyword or object in the Java language, it is simply a discipline put into place so that in a multi-threading environment the reordering of the surrounding instructions does not result in a code that produces incorrect output. The definition might seem a bit overwhelming if this is the first time that you have come across this concept. To understand it let’s first learn where does the need for it originates from. The Java Memory Model which is also referred to as the JMM model defines how the storage and exchange of data take place between threads and the hardware in a single or multithreaded environment. Some points to keep in mind are as follows: Every CPU core has its own set of registers. Every CPU core can execute more than one thread at a time. Every CPU core has its own set of cache. A thread executes on a CPU core but its data is stored and accessed from RAM where the local variables lie inside the “Thread Stack” and the objects lie inside the “Heap.” The Java Memory Model The local variables and the references to objects inside a thread are stored in the Thread Stack, whereas the objects themselves are stored inside the Heap. The request for a variable by the thread running on the CPU follows this route RAM -> Cache -> CPU Registers. Similarly, when some processing happens on the variable and its value is updated, the changes go through CPU Register -> Cache -> RAM. Thus while working with multiple threads that share a variable, when one thread updates a shared variable’s value, the update has to be done to the register, then cache, and finally the RAM. And when another thread requires to read that shared variable, it reads the value present in the RAM which travels through the cache and registers. If you look at it at the basic level, if the read-write operations are delayed in such a way that the correct value is not stored in memory before another read-write is performed then it can result in memory consistency errors. When working with multiple threads, this procedure of storage and retrieval may pose some problems such as: Race Condition: The condition where two threads sharing some variable, read and write on it but do not do so in a synchronized manner, resulting in inconsistent values. Update Visibility: where the updates made by one thread to a shared variable may not be visible to the other thread because the value has not yet been updated to the RAM. These problems are solved by the use of synchronized block and volatile variables. Instruction Reordering During compilation or during processing, the compiler or the CPU might reorder the instructions to run them in parallel to increase throughput and performance. For example, we have 3 instructions: FullName = FirstName + LastName // Statement 1 UniqueId = FullName + TokenNo // Statement 2 Age = CurrentYear - BirthYear // Statement 3 The compiler cannot run 1 and 2 in parallel because 2 needs the output of 1, but 1 and 3 can run in parallel because they are independent of each other. So the compiler or the CPU can reorder these instructions in this way: FullName = FirstName + LastName // Statement 1 Age = CurrentYear - BirthYear // Statement 3 UniqueId = FullName + TokenNo // Statement 2 However, if reordering is performed in a multi-threaded application where threads share some variables then it may cost us the correctness of our program. Now recall the two problems we talked about in the previous section, the race condition, and the updated visibility. Java provides us with some solutions to handle these types of situations. We are gonna learn what they are, and finally happens-before will be introduced in that section. Volatile For a field/variable declared as volatile, private volatile count; Every write to the field will be written/flushed directly to the main memory (i.e. bypassing the cache.) Every read of that field is read directly from the main memory. This means that the shared variable count, whenever written-to or read-by a thread, it will always correspond to its most recently written value. This will prevent race condition because now the threads will always use the correct value of a shared variable. Also, the updates to the shared variable will also be visible to all the threads reading it, thus preventing the update visibility problem. There are some more important points that the volatile dictates: At the time you write to a volatile variable, all the non-volatile variables that are visible to that thread will also get written/flushed to the main memory, i.e. their most recent values will be stored in the RAM along with the volatile variable. At the time you read a volatile variable, all the non-volatile variables that are visible to that thread will also get refreshed from the main memory, i.e. their most recent values will be assigned to them. This is called the visibility guarantee of a volatile variable. All of this looks and works fine, unless the CPU decides to reorder your instructions, resulting in incorrect execution of your application. Lets understand what we mean. Consider this piece of a program: Implementation: The below code in the illustration depicts as conveyed in simpler words is as follows: Inputs a fresh assignment submitted by a student And then collects that fresh assignment. Our goal is that each time “only a freshly prepared assignment is collected. So proposing the sample code for the same as follows: illustration: // Sample class class ClassRoom { // Declaring and initializing variables // of this class private int numOfAssgnSubmitted = 0; private int numOfAssgnCollected = 0; private Assignment assgn = null; // Volatile shared variable private volatile boolean newAssignment = false; // Methods of this class // Method 1 // Used by Thread 1 public void submitAssignment(Assignment assgn) { // This keyword refers to current instance itself // 1 this.assgn = assgn; // 2 this.numOfAssgnSubmitted++; // 3 this.newAssignment = true; } // Method 2 // Used by Thread 2 public Assignment collectAssignment() { while (!newAssignment) { // Wait until a new assignment is submitted } Assignment collectedAssgn = this.assgn; this.numOfAssgnCollected++; this.newAssignment = false; return collectedAssgn; } } The method submitAssignment() is used by a thread Thread1, which accepts an assignment submitted by a student in the field assign, then increases the count of assignments submitted, and then flips the newAssignment variable to true. The method collectAssignment() is used by a thread Thread2, which waits until a new assignment has been submitted, when the value of newAssignment becomes true, it stores the submitted assignment into a variable ‘collectedAssgn’, increasing the count of assignments collected and flips the newAssignment to false, since no pending assignments are left. Finally, it returns the collected assignment. Now, the volatile variable newAssignment acts as a shared variable between Thread1 and Thread2 which are running concurrently. And since all the other variables are visible to each of the threads along with newAssignment itself, the read-write operations will be done directly using the main memory. If we focus on the submitAssignment() method, statements 1, 2, and 3 are independent of each other, since no statement makes use of the other statement, hence your CPU might think “Why not reorder them?” for whatever reasons that it may provide better performance. So let us assume the CPU reordered the three statements in this way: this.newAssignment = true; // 3 this.assgn = assgn; // 1 this.numOfAssgnSubmitted++; // 2 Now think for a second, what our goal was, it was to collect a new fresh assignment each time, but now due to statement 3 updating the newAssignment to true even before the new assgn has been stored in the assgn, the while loop in the Thread2 will now be exited and there is a possibility that Thread2’s instructions execute before the remaining instructions of Thread1, resulting in an older value object of Assignment being submitted. Even though the values are being retrieved directly from the main memory, it is useless if the instructions are executed in the wrong order in this case. This is the point where even though the visibility of the variables is guaranteed, the reordering of the instructions may lead to incorrect execution. And therefore, Java introduced the happens-before guarantee, with regards to the visibility of volatile variables. Happens-Before in Volatile Happens-Before states about reordering. It is as follows: When reordering any write to a variable that happened before a write to a volatile, will remain before the write to the volatile variable. When reordering any read of a volatile variable that is located before read of some non-volatile or volatile variable, is guaranteed to happen before any of the subsequent reads. In context to the above example, the first point is relevant. Any write to a variable (Statements 1 and 2) that happened before a write to a volatile (Statement 3), will remain before the write to the volatile variable. This means that reordering of Statement 3 before 1 and 2 is prohibited. This in turn guarantees that newAssignment is only set to true once the new value of Assignment is assigned to ‘assgn’. This is called happens-before visibility guarantee of volatile. Also, statements 1 and 2 may be reordered among themselves as long as they are not being reordered after statement 3. Synchronization Block In the case of a synchronization block in Java: When a thread enters a synchronization block, the thread will refresh the values of all variables that are visible to the thread at that time from the main memory. When a thread exits a synchronization block, the values of all those variables will be written to the main memory. Happens-Before in Synchronization Block In case of synchronization block, happens before states that for reordering: Any write to a variable that happens before the exit of a synchronization block is guaranteed to remain before the exit of a synchronization block. Entrance to a synchronization block that happens before a read of a variable, is guaranteed to remain before any of the reads to the variables that follow the entrance of a synchronized block. Now getting deeper to the roots of the happens-before relationship in java. Let us consider a scenario to understand it in better terms. Illustration: If one action ‘x’ is visible to and ordered before another action ‘y’, then there is a happens-before relationship between the two actions indicated by hb(x, y). If x and y are actions of the same thread and x comes before y in program order, then hb(x, y). There is a happens-before edge from the end of a constructor of an object to the start of a finalizer for that object. If an action x synchronizes with the following action y, then we also have hb(x, y). If hb(x, y) and hb(y, z), then hb(x, z). Note: It is important to know that if we have hb(x, y) then it does not necessarily mean that x always occurs in the implementation before y, as long as the execution produces correct results, reordering of such actions is legal. Some more rules laid out regarding synchronization state that are as follows: An unlock on a monitor happens-before every subsequent lock on that monitor. A write to a volatile field happens-before every subsequent read of that field. A call to start() on a thread happens-before any actions in the started thread. All actions in a thread happen-before any other thread successfully return from a join() on that thread. The default initialization of any object happens-before any other actions (other than default-writes) of a program. When a statement invokes Thread.start, every statement that has a happens-before relationship with that statement also has a happens-before relationship with every statement executed by the new thread. The effects of the code that led up to the creation of the new thread are visible to the new thread. When a thread terminates and causes a Thread.join in another thread to return, then all the statements executed by the terminated thread have a happens-before relationship with all the statements following the successful join. The effects of the code in the thread are now visible to the thread that performed the join. mayanknehru Java-Object Oriented Picked 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": "\n18 Apr, 2022" }, { "code": null, "e": 121, "s": 54, "text": "Prerequisite: Threading, Synchronized Block, and volatile Keyword" }, { "code": null, "e": 517, "s": 121, "text": "Happens-before is a concept, a phenomenon, or simply a set of rules that define the basis for reordering of instructions by a compiler or CPU. Happens-before is not any keyword or object in the Java language, it is simply a discipline put into place so that in a multi-threading environment the reordering of the surrounding instructions does not result in a code that produces incorrect output." }, { "code": null, "e": 707, "s": 517, "text": "The definition might seem a bit overwhelming if this is the first time that you have come across this concept. To understand it let’s first learn where does the need for it originates from." }, { "code": null, "e": 903, "s": 707, "text": "The Java Memory Model which is also referred to as the JMM model defines how the storage and exchange of data take place between threads and the hardware in a single or multithreaded environment." }, { "code": null, "e": 947, "s": 903, "text": "Some points to keep in mind are as follows:" }, { "code": null, "e": 992, "s": 947, "text": "Every CPU core has its own set of registers." }, { "code": null, "e": 1051, "s": 992, "text": "Every CPU core can execute more than one thread at a time." }, { "code": null, "e": 1092, "s": 1051, "text": "Every CPU core has its own set of cache." }, { "code": null, "e": 1264, "s": 1092, "text": "A thread executes on a CPU core but its data is stored and accessed from RAM where the local variables lie inside the “Thread Stack” and the objects lie inside the “Heap.”" }, { "code": null, "e": 1286, "s": 1264, "text": "The Java Memory Model" }, { "code": null, "e": 2255, "s": 1286, "text": "The local variables and the references to objects inside a thread are stored in the Thread Stack, whereas the objects themselves are stored inside the Heap. The request for a variable by the thread running on the CPU follows this route RAM -> Cache -> CPU Registers. Similarly, when some processing happens on the variable and its value is updated, the changes go through CPU Register -> Cache -> RAM. Thus while working with multiple threads that share a variable, when one thread updates a shared variable’s value, the update has to be done to the register, then cache, and finally the RAM. And when another thread requires to read that shared variable, it reads the value present in the RAM which travels through the cache and registers. If you look at it at the basic level, if the read-write operations are delayed in such a way that the correct value is not stored in memory before another read-write is performed then it can result in memory consistency errors." }, { "code": null, "e": 2363, "s": 2255, "text": "When working with multiple threads, this procedure of storage and retrieval may pose some problems such as:" }, { "code": null, "e": 2532, "s": 2363, "text": "Race Condition: The condition where two threads sharing some variable, read and write on it but do not do so in a synchronized manner, resulting in inconsistent values." }, { "code": null, "e": 2703, "s": 2532, "text": "Update Visibility: where the updates made by one thread to a shared variable may not be visible to the other thread because the value has not yet been updated to the RAM." }, { "code": null, "e": 2786, "s": 2703, "text": "These problems are solved by the use of synchronized block and volatile variables." }, { "code": null, "e": 2809, "s": 2786, "text": "Instruction Reordering" }, { "code": null, "e": 3006, "s": 2809, "text": "During compilation or during processing, the compiler or the CPU might reorder the instructions to run them in parallel to increase throughput and performance. For example, we have 3 instructions:" }, { "code": null, "e": 3167, "s": 3006, "text": "FullName = FirstName + LastName // Statement 1\nUniqueId = FullName + TokenNo // Statement 2\n \nAge = CurrentYear - BirthYear // Statement 3" }, { "code": null, "e": 3391, "s": 3167, "text": "The compiler cannot run 1 and 2 in parallel because 2 needs the output of 1, but 1 and 3 can run in parallel because they are independent of each other. So the compiler or the CPU can reorder these instructions in this way:" }, { "code": null, "e": 3547, "s": 3391, "text": "FullName = FirstName + LastName // Statement 1\nAge = CurrentYear - BirthYear // Statement 3\n\nUniqueId = FullName + TokenNo // Statement 2" }, { "code": null, "e": 3702, "s": 3547, "text": "However, if reordering is performed in a multi-threaded application where threads share some variables then it may cost us the correctness of our program." }, { "code": null, "e": 3990, "s": 3702, "text": "Now recall the two problems we talked about in the previous section, the race condition, and the updated visibility. Java provides us with some solutions to handle these types of situations. We are gonna learn what they are, and finally happens-before will be introduced in that section." }, { "code": null, "e": 4000, "s": 3990, "text": "Volatile " }, { "code": null, "e": 4044, "s": 4000, "text": "For a field/variable declared as volatile, " }, { "code": null, "e": 4068, "s": 4044, "text": "private volatile count;" }, { "code": null, "e": 4173, "s": 4068, "text": "Every write to the field will be written/flushed directly to the main memory (i.e. bypassing the cache.)" }, { "code": null, "e": 4237, "s": 4173, "text": "Every read of that field is read directly from the main memory." }, { "code": null, "e": 4636, "s": 4237, "text": "This means that the shared variable count, whenever written-to or read-by a thread, it will always correspond to its most recently written value. This will prevent race condition because now the threads will always use the correct value of a shared variable. Also, the updates to the shared variable will also be visible to all the threads reading it, thus preventing the update visibility problem." }, { "code": null, "e": 4701, "s": 4636, "text": "There are some more important points that the volatile dictates:" }, { "code": null, "e": 4950, "s": 4701, "text": "At the time you write to a volatile variable, all the non-volatile variables that are visible to that thread will also get written/flushed to the main memory, i.e. their most recent values will be stored in the RAM along with the volatile variable." }, { "code": null, "e": 5157, "s": 4950, "text": "At the time you read a volatile variable, all the non-volatile variables that are visible to that thread will also get refreshed from the main memory, i.e. their most recent values will be assigned to them." }, { "code": null, "e": 5221, "s": 5157, "text": "This is called the visibility guarantee of a volatile variable." }, { "code": null, "e": 5426, "s": 5221, "text": "All of this looks and works fine, unless the CPU decides to reorder your instructions, resulting in incorrect execution of your application. Lets understand what we mean. Consider this piece of a program:" }, { "code": null, "e": 5442, "s": 5426, "text": "Implementation:" }, { "code": null, "e": 5529, "s": 5442, "text": "The below code in the illustration depicts as conveyed in simpler words is as follows:" }, { "code": null, "e": 5578, "s": 5529, "text": "Inputs a fresh assignment submitted by a student" }, { "code": null, "e": 5619, "s": 5578, "text": "And then collects that fresh assignment." }, { "code": null, "e": 5750, "s": 5619, "text": "Our goal is that each time “only a freshly prepared assignment is collected. So proposing the sample code for the same as follows:" }, { "code": null, "e": 5764, "s": 5750, "text": "illustration:" }, { "code": null, "e": 6749, "s": 5764, "text": "// Sample class\nclass ClassRoom {\n\n // Declaring and initializing variables\n // of this class\n private int numOfAssgnSubmitted = 0;\n private int numOfAssgnCollected = 0;\n private Assignment assgn = null;\n // Volatile shared variable\n private volatile boolean newAssignment = false;\n\n // Methods of this class\n\n // Method 1\n // Used by Thread 1\n public void submitAssignment(Assignment assgn)\n {\n\n // This keyword refers to current instance itself\n // 1\n this.assgn = assgn;\n // 2\n this.numOfAssgnSubmitted++;\n // 3\n this.newAssignment = true;\n }\n\n // Method 2\n // Used by Thread 2\n public Assignment collectAssignment()\n {\n while (!newAssignment) {\n\n // Wait until a new assignment is submitted\n }\n\n Assignment collectedAssgn = this.assgn;\n\n this.numOfAssgnCollected++;\n this.newAssignment = false;\n\n return collectedAssgn;\n }\n}" }, { "code": null, "e": 6982, "s": 6749, "text": "The method submitAssignment() is used by a thread Thread1, which accepts an assignment submitted by a student in the field assign, then increases the count of assignments submitted, and then flips the newAssignment variable to true." }, { "code": null, "e": 7381, "s": 6982, "text": "The method collectAssignment() is used by a thread Thread2, which waits until a new assignment has been submitted, when the value of newAssignment becomes true, it stores the submitted assignment into a variable ‘collectedAssgn’, increasing the count of assignments collected and flips the newAssignment to false, since no pending assignments are left. Finally, it returns the collected assignment." }, { "code": null, "e": 7681, "s": 7381, "text": "Now, the volatile variable newAssignment acts as a shared variable between Thread1 and Thread2 which are running concurrently. And since all the other variables are visible to each of the threads along with newAssignment itself, the read-write operations will be done directly using the main memory." }, { "code": null, "e": 8016, "s": 7681, "text": "If we focus on the submitAssignment() method, statements 1, 2, and 3 are independent of each other, since no statement makes use of the other statement, hence your CPU might think “Why not reorder them?” for whatever reasons that it may provide better performance. So let us assume the CPU reordered the three statements in this way:" }, { "code": null, "e": 8108, "s": 8016, "text": "this.newAssignment = true; // 3\nthis.assgn = assgn; // 1\nthis.numOfAssgnSubmitted++; // 2" }, { "code": null, "e": 8699, "s": 8108, "text": "Now think for a second, what our goal was, it was to collect a new fresh assignment each time, but now due to statement 3 updating the newAssignment to true even before the new assgn has been stored in the assgn, the while loop in the Thread2 will now be exited and there is a possibility that Thread2’s instructions execute before the remaining instructions of Thread1, resulting in an older value object of Assignment being submitted. Even though the values are being retrieved directly from the main memory, it is useless if the instructions are executed in the wrong order in this case." }, { "code": null, "e": 8965, "s": 8699, "text": "This is the point where even though the visibility of the variables is guaranteed, the reordering of the instructions may lead to incorrect execution. And therefore, Java introduced the happens-before guarantee, with regards to the visibility of volatile variables." }, { "code": null, "e": 8992, "s": 8965, "text": "Happens-Before in Volatile" }, { "code": null, "e": 9050, "s": 8992, "text": "Happens-Before states about reordering. It is as follows:" }, { "code": null, "e": 9189, "s": 9050, "text": "When reordering any write to a variable that happened before a write to a volatile, will remain before the write to the volatile variable." }, { "code": null, "e": 9368, "s": 9189, "text": "When reordering any read of a volatile variable that is located before read of some non-volatile or volatile variable, is guaranteed to happen before any of the subsequent reads." }, { "code": null, "e": 9962, "s": 9368, "text": "In context to the above example, the first point is relevant. Any write to a variable (Statements 1 and 2) that happened before a write to a volatile (Statement 3), will remain before the write to the volatile variable. This means that reordering of Statement 3 before 1 and 2 is prohibited. This in turn guarantees that newAssignment is only set to true once the new value of Assignment is assigned to ‘assgn’. This is called happens-before visibility guarantee of volatile. Also, statements 1 and 2 may be reordered among themselves as long as they are not being reordered after statement 3." }, { "code": null, "e": 9984, "s": 9962, "text": "Synchronization Block" }, { "code": null, "e": 10032, "s": 9984, "text": "In the case of a synchronization block in Java:" }, { "code": null, "e": 10196, "s": 10032, "text": "When a thread enters a synchronization block, the thread will refresh the values of all variables that are visible to the thread at that time from the main memory." }, { "code": null, "e": 10311, "s": 10196, "text": "When a thread exits a synchronization block, the values of all those variables will be written to the main memory." }, { "code": null, "e": 10351, "s": 10311, "text": "Happens-Before in Synchronization Block" }, { "code": null, "e": 10428, "s": 10351, "text": "In case of synchronization block, happens before states that for reordering:" }, { "code": null, "e": 10576, "s": 10428, "text": "Any write to a variable that happens before the exit of a synchronization block is guaranteed to remain before the exit of a synchronization block." }, { "code": null, "e": 10769, "s": 10576, "text": "Entrance to a synchronization block that happens before a read of a variable, is guaranteed to remain before any of the reads to the variables that follow the entrance of a synchronized block." }, { "code": null, "e": 10906, "s": 10769, "text": "Now getting deeper to the roots of the happens-before relationship in java. Let us consider a scenario to understand it in better terms." }, { "code": null, "e": 10921, "s": 10906, "text": "Illustration: " }, { "code": null, "e": 11083, "s": 10921, "text": "If one action ‘x’ is visible to and ordered before another action ‘y’, then there is a happens-before relationship between the two actions indicated by hb(x, y)." }, { "code": null, "e": 11179, "s": 11083, "text": "If x and y are actions of the same thread and x comes before y in program order, then hb(x, y)." }, { "code": null, "e": 11298, "s": 11179, "text": "There is a happens-before edge from the end of a constructor of an object to the start of a finalizer for that object." }, { "code": null, "e": 11383, "s": 11298, "text": "If an action x synchronizes with the following action y, then we also have hb(x, y)." }, { "code": null, "e": 11424, "s": 11383, "text": "If hb(x, y) and hb(y, z), then hb(x, z)." }, { "code": null, "e": 11654, "s": 11424, "text": "Note: It is important to know that if we have hb(x, y) then it does not necessarily mean that x always occurs in the implementation before y, as long as the execution produces correct results, reordering of such actions is legal." }, { "code": null, "e": 11732, "s": 11654, "text": "Some more rules laid out regarding synchronization state that are as follows:" }, { "code": null, "e": 11809, "s": 11732, "text": "An unlock on a monitor happens-before every subsequent lock on that monitor." }, { "code": null, "e": 11889, "s": 11809, "text": "A write to a volatile field happens-before every subsequent read of that field." }, { "code": null, "e": 11969, "s": 11889, "text": "A call to start() on a thread happens-before any actions in the started thread." }, { "code": null, "e": 12074, "s": 11969, "text": "All actions in a thread happen-before any other thread successfully return from a join() on that thread." }, { "code": null, "e": 12190, "s": 12074, "text": "The default initialization of any object happens-before any other actions (other than default-writes) of a program." }, { "code": null, "e": 12493, "s": 12190, "text": "When a statement invokes Thread.start, every statement that has a happens-before relationship with that statement also has a happens-before relationship with every statement executed by the new thread. The effects of the code that led up to the creation of the new thread are visible to the new thread." }, { "code": null, "e": 12813, "s": 12493, "text": "When a thread terminates and causes a Thread.join in another thread to return, then all the statements executed by the terminated thread have a happens-before relationship with all the statements following the successful join. The effects of the code in the thread are now visible to the thread that performed the join." }, { "code": null, "e": 12825, "s": 12813, "text": "mayanknehru" }, { "code": null, "e": 12846, "s": 12825, "text": "Java-Object Oriented" }, { "code": null, "e": 12853, "s": 12846, "text": "Picked" }, { "code": null, "e": 12858, "s": 12853, "text": "Java" }, { "code": null, "e": 12863, "s": 12858, "text": "Java" } ]
Remove duplicates from unsorted array using Set data structure
03 Sep, 2021 Given an unsorted array of integers, print the array after removing the duplicate elements from it. We need to print distinct array elements according to their first occurrence. Examples: Input: arr[] = { 1, 2, 5, 1, 7, 2, 4, 2} Output: 1 2 5 7 4 Explanation: {1, 2} appear more than one time. Input: arr[] = { 3, 3, 4, 1, 1} Output: 3 4 1 Approach: Take a Set Insert all array element in the Set. Set does not allow duplicates and sets like LinkedHashSet maintains the order of insertion so it will remove duplicates and elements will be printed in the same order in which it is inserted. Convert the formed set into array. Print elements of Set. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // CPP program to remove duplicates// from unsorted array#include <bits/stdc++.h>using namespace std; // Function to remove duplicate from arrayvoid removeDuplicates(int arr[], int n){ unordered_set<int> s; // adding elements to LinkedHashSet for (int i = 0; i < n; i++) s.insert(arr[i]); // Print the elements of LinkedHashSet cout << "[ "; for (auto x : s) cout << x << " "; cout << "]";} // Driver codeint main(){ int arr[] = { 1, 2, 5, 1, 7, 2, 4, 2 }; int n = sizeof(arr) / sizeof(arr[0]); // Function call removeDuplicates(arr, n);} // This code is contributed// by Surendra_Gangwar // Java program to remove duplicates// from unsorted array import java.util.*; class GFG { // Function to remove duplicate from array public static void removeDuplicates(int[] arr) { LinkedHashSet<Integer> set = new LinkedHashSet<Integer>(); // adding elements to LinkedHashSet for (int i = 0; i < arr.length; i++) set.add(arr[i]); // Print the elements of LinkedHashSet System.out.print(set); } // Driver code public static void main(String[] args) { int arr[] = { 1, 2, 5, 1, 7, 2, 4, 2 }; // Function call removeDuplicates(arr); }} # Python3 program to remove duplicatesdef removeDulipcates(arr): # convert the arr into set and then into list return list(set(arr)) # Driver Codearr = [1, 2, 5, 1, 7, 2, 4, 2] # Function callprint(removeDulipcates(arr)) # This code is contributed# by Mohit Kumar // C# program to remove duplicates// from unsorted arrayusing System;using System.Collections.Generic; class GFG{ // Function to remove duplicate from array public static void removeDuplicates(int[] arr) { HashSet<int> set = new HashSet<int>(); // adding elements to LinkedHashSet for (int i = 0; i < arr.Length; i++) set.Add(arr[i]); // Print the elements of HashSet foreach(int item in set) Console.Write(item + ", "); } // Driver code public static void Main(String[] args) { int[] arr = { 1, 2, 5, 1, 7, 2, 4, 2 }; // Function call removeDuplicates(arr); }} // This code is contributed by 29AjayKumar <script> // Javascript program to remove duplicates// from unsorted array // Function to remove duplicate from arrayfunction removeDuplicates(arr){ let set = new Set(); // Adding elements to LinkedHashSet for(let i = 0; i < arr.length; i++) set.add(arr[i]); // Print the elements of LinkedHashSet document.write("[" + Array.from(set).join(", ") + "]");} // Driver codelet arr = [ 1, 2, 5, 1, 7, 2, 4, 2 ]; // Function callremoveDuplicates(arr); // This code is contributed by patel2127 </script> [ 4 7 5 1 2 ] Time Complexity: O(N) mohit kumar 29 29AjayKumar SURENDRA_GANGWAR surangatco santanupatra47 patel2127 simmytarika5 java-LinkedHashSet Arrays Arrays Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n03 Sep, 2021" }, { "code": null, "e": 230, "s": 52, "text": "Given an unsorted array of integers, print the array after removing the duplicate elements from it. We need to print distinct array elements according to their first occurrence." }, { "code": null, "e": 241, "s": 230, "text": "Examples: " }, { "code": null, "e": 394, "s": 241, "text": "Input: arr[] = { 1, 2, 5, 1, 7, 2, 4, 2}\nOutput: 1 2 5 7 4\nExplanation: {1, 2} appear more than one time.\n\nInput: arr[] = { 3, 3, 4, 1, 1}\nOutput: 3 4 1" }, { "code": null, "e": 405, "s": 394, "text": "Approach: " }, { "code": null, "e": 416, "s": 405, "text": "Take a Set" }, { "code": null, "e": 645, "s": 416, "text": "Insert all array element in the Set. Set does not allow duplicates and sets like LinkedHashSet maintains the order of insertion so it will remove duplicates and elements will be printed in the same order in which it is inserted." }, { "code": null, "e": 680, "s": 645, "text": "Convert the formed set into array." }, { "code": null, "e": 703, "s": 680, "text": "Print elements of Set." }, { "code": null, "e": 754, "s": 703, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 758, "s": 754, "text": "C++" }, { "code": null, "e": 763, "s": 758, "text": "Java" }, { "code": null, "e": 771, "s": 763, "text": "Python3" }, { "code": null, "e": 774, "s": 771, "text": "C#" }, { "code": null, "e": 785, "s": 774, "text": "Javascript" }, { "code": "// CPP program to remove duplicates// from unsorted array#include <bits/stdc++.h>using namespace std; // Function to remove duplicate from arrayvoid removeDuplicates(int arr[], int n){ unordered_set<int> s; // adding elements to LinkedHashSet for (int i = 0; i < n; i++) s.insert(arr[i]); // Print the elements of LinkedHashSet cout << \"[ \"; for (auto x : s) cout << x << \" \"; cout << \"]\";} // Driver codeint main(){ int arr[] = { 1, 2, 5, 1, 7, 2, 4, 2 }; int n = sizeof(arr) / sizeof(arr[0]); // Function call removeDuplicates(arr, n);} // This code is contributed// by Surendra_Gangwar", "e": 1426, "s": 785, "text": null }, { "code": "// Java program to remove duplicates// from unsorted array import java.util.*; class GFG { // Function to remove duplicate from array public static void removeDuplicates(int[] arr) { LinkedHashSet<Integer> set = new LinkedHashSet<Integer>(); // adding elements to LinkedHashSet for (int i = 0; i < arr.length; i++) set.add(arr[i]); // Print the elements of LinkedHashSet System.out.print(set); } // Driver code public static void main(String[] args) { int arr[] = { 1, 2, 5, 1, 7, 2, 4, 2 }; // Function call removeDuplicates(arr); }}", "e": 2074, "s": 1426, "text": null }, { "code": "# Python3 program to remove duplicatesdef removeDulipcates(arr): # convert the arr into set and then into list return list(set(arr)) # Driver Codearr = [1, 2, 5, 1, 7, 2, 4, 2] # Function callprint(removeDulipcates(arr)) # This code is contributed# by Mohit Kumar", "e": 2348, "s": 2074, "text": null }, { "code": "// C# program to remove duplicates// from unsorted arrayusing System;using System.Collections.Generic; class GFG{ // Function to remove duplicate from array public static void removeDuplicates(int[] arr) { HashSet<int> set = new HashSet<int>(); // adding elements to LinkedHashSet for (int i = 0; i < arr.Length; i++) set.Add(arr[i]); // Print the elements of HashSet foreach(int item in set) Console.Write(item + \", \"); } // Driver code public static void Main(String[] args) { int[] arr = { 1, 2, 5, 1, 7, 2, 4, 2 }; // Function call removeDuplicates(arr); }} // This code is contributed by 29AjayKumar", "e": 3054, "s": 2348, "text": null }, { "code": "<script> // Javascript program to remove duplicates// from unsorted array // Function to remove duplicate from arrayfunction removeDuplicates(arr){ let set = new Set(); // Adding elements to LinkedHashSet for(let i = 0; i < arr.length; i++) set.add(arr[i]); // Print the elements of LinkedHashSet document.write(\"[\" + Array.from(set).join(\", \") + \"]\");} // Driver codelet arr = [ 1, 2, 5, 1, 7, 2, 4, 2 ]; // Function callremoveDuplicates(arr); // This code is contributed by patel2127 </script>", "e": 3583, "s": 3054, "text": null }, { "code": null, "e": 3597, "s": 3583, "text": "[ 4 7 5 1 2 ]" }, { "code": null, "e": 3619, "s": 3597, "text": "Time Complexity: O(N)" }, { "code": null, "e": 3634, "s": 3619, "text": "mohit kumar 29" }, { "code": null, "e": 3646, "s": 3634, "text": "29AjayKumar" }, { "code": null, "e": 3663, "s": 3646, "text": "SURENDRA_GANGWAR" }, { "code": null, "e": 3674, "s": 3663, "text": "surangatco" }, { "code": null, "e": 3689, "s": 3674, "text": "santanupatra47" }, { "code": null, "e": 3699, "s": 3689, "text": "patel2127" }, { "code": null, "e": 3712, "s": 3699, "text": "simmytarika5" }, { "code": null, "e": 3731, "s": 3712, "text": "java-LinkedHashSet" }, { "code": null, "e": 3738, "s": 3731, "text": "Arrays" }, { "code": null, "e": 3745, "s": 3738, "text": "Arrays" } ]
Sum of cousins of a given node in a Binary Tree
17 Jan, 2022 Given a binary tree and data value of a node. The task is to find the sum of cousin nodes of given node. If given node has no cousins then return -1. Note: It is given that all nodes have distinct values and the given node exists in the tree. Examples: Input: 1 / \ 3 7 / \ / \ 6 5 4 13 / / \ 10 17 15 key = 13 Output: 11 Cousin nodes are 5 and 6 which gives sum 11. Input: 1 / \ 3 7 / \ / \ 6 5 4 13 / / \ 10 17 15 key = 7 Output: -1 No cousin nodes of node having value 7. Approach: The approach is to do a level order traversal of the tree. While performing level order traversal, find the sum of child nodes of next level. Add a child node’s value to the sum and check if either of the children nodes is the target node or not. If yes, then do not add the value of either child to the sum. After traversing current level if the target node is present in next level, then end the level order traversal and sum found is the sum of cousin nodes. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // CPP program to find sum of cousins// of given node in binary tree.#include <bits/stdc++.h>using namespace std; // A Binary Tree Nodestruct Node { int data; struct Node *left, *right;}; // A utility function to create a new// Binary Tree Nodestruct Node* newNode(int item){ struct Node* temp = new Node(); temp->data = item; temp->left = temp->right = NULL; return temp;} // Function to find sum of cousins of// a given node.int findCousinSum(Node* root, int key){ if (root == NULL) return -1; // Root node has no cousins so return -1. if (root->data == key) { return -1; } // To store sum of cousins. int currSum = 0; // To store size of current level. int size; // To perform level order traversal. queue<Node*> q; q.push(root); // To represent that target node is // found. bool found = false; while (!q.empty()) { // If target node is present at // current level, then return // sum of cousins stored in currSum. if (found == true) { return currSum; } // Find size of current level and // traverse entire level. size = q.size(); currSum = 0; while (size) { root = q.front(); q.pop(); // Check if either of the existing // children of given node is target // node or not. If yes then set // found equal to true. if ((root->left && root->left->data == key) || (root->right && root->right->data == key)) { found = true; } // If target node is not children of // current node, then its children can be cousin // of target node, so add their value to sum. else { if (root->left) { currSum += root->left->data; q.push(root->left); } if (root->right) { currSum += root->right->data; q.push(root->right); } } size--; } } return -1;} // Driver Codeint main(){ /* 1 / \ 3 7 / \ / \ 6 5 4 13 / / \ 10 17 15 */ struct Node* root = newNode(1); root->left = newNode(3); root->right = newNode(7); root->left->left = newNode(6); root->left->right = newNode(5); root->left->right->left = newNode(10); root->right->left = newNode(4); root->right->right = newNode(13); root->right->left->left = newNode(17); root->right->left->right = newNode(15); cout << findCousinSum(root, 13) << "\n"; cout << findCousinSum(root, 7) << "\n"; return 0;} // Java program to find sum of cousins// of given node in binary tree.import java.util.*;class Sol{ // A Binary Tree Nodestatic class Node{ int data; Node left, right;}; // A utility function to create a new// Binary Tree Nodestatic Node newNode(int item){ Node temp = new Node(); temp.data = item; temp.left = temp.right = null; return temp;} // Function to find sum of cousins of// a given node.static int findCousinSum(Node root, int key){ if (root == null) return -1; // Root node has no cousins so return -1. if (root.data == key) { return -1; } // To store sum of cousins. int currSum = 0; // To store size of current level. int size; // To perform level order traversal. Queue<Node> q=new LinkedList<Node>(); q.add(root); // To represent that target node is // found. boolean found = false; while (q.size() > 0) { // If target node is present at // current level, then return // sum of cousins stored in currSum. if (found == true) { return currSum; } // Find size of current level and // traverse entire level. size = q.size(); currSum = 0; while (size > 0) { root = q.peek(); q.remove(); // Check if either of the existing // children of given node is target // node or not. If yes then set // found equal to true. if ((root.left!=null && root.left.data == key) || (root.right!=null && root.right.data == key)) { found = true; } // If target node is not children of // current node, then its children can be cousin // of target node, so add their value to sum. else { if (root.left != null) { currSum += root.left.data; q.add(root.left); } if (root.right != null) { currSum += root.right.data; q.add(root.right); } } size--; } } return -1;} // Driver Codepublic static void main(String args[]){ /* 1 / \ 3 7 / \ / \ 6 5 4 13 / / \ 10 17 15 */ Node root = newNode(1); root.left = newNode(3); root.right = newNode(7); root.left.left = newNode(6); root.left.right = newNode(5); root.left.right.left = newNode(10); root.right.left = newNode(4); root.right.right = newNode(13); root.right.left.left = newNode(17); root.right.left.right = newNode(15); System.out.print( findCousinSum(root, 13) + "\n"); System.out.print( findCousinSum(root, 7) + "\n");}} // This code is contributed by Arnab Kundu """ Python3 program to find sum of cousinsof given node in binary tree """ # A Binary Tree Node# Utility function to create a new tree nodeclass newNode: # Constructor to create a newNode def __init__(self, data): self.data = data self.left = None self.right = None # Function to find sum of cousins of# a given node.def findCousinSum( root, key): if (root == None): return -1 # Root node has no cousins so return -1. if (root.data == key): return -1 # To store sum of cousins. currSum = 0 # To store size of current level. size = 0 # To perform level order traversal. q = [] q.append(root) # To represent that target node is # found. found = False while (len(q)): # If target node is present at # current level, then return # sum of cousins stored in currSum. if (found == True): return currSum # Find size of current level and # traverse entire level. size = len(q) currSum = 0 while (size): root = q[0] q.pop(0) # Check if either of the existing # children of given node is target # node or not. If yes then set # found equal to true. if ((root.left and root.left.data == key) or (root.right and root.right.data == key)) : found = True # If target node is not children of current # node, then its children can be cousin # of target node, so add their value to sum. else: if (root.left): currSum += root.left.data q.append(root.left) if (root.right) : currSum += root.right.data q.append(root.right) size -= 1 return -1 # Driver Codeif __name__ == '__main__': """ 1 / \ 3 7 / \ / \ 6 5 4 13 / / \ 10 17 15 """ root = newNode(1) root.left = newNode(3) root.right = newNode(7) root.left.left = newNode(6) root.left.right = newNode(5) root.left.right.left = newNode(10) root.right.left = newNode(4) root.right.right = newNode(13) root.right.left.left = newNode(17) root.right.left.right = newNode(15) print(findCousinSum(root, 13)) print(findCousinSum(root, 7)) # This code is contributed by# SHUBHAMSINGH10 // C# program to find sum of cousins// of given node in binary tree.using System;using System.Collections.Generic; class Sol{ // A Binary Tree Nodepublic class Node{ public int data; public Node left, right;}; // A utility function to create a new// Binary Tree Nodestatic Node newNode(int item){ Node temp = new Node(); temp.data = item; temp.left = temp.right = null; return temp;} // Function to find sum of cousins of// a given node.static int findCousinSum(Node root, int key){ if (root == null) return -1; // Root node has no cousins so return -1. if (root.data == key) { return -1; } // To store sum of cousins. int currSum = 0; // To store size of current level. int size; // To perform level order traversal. Queue<Node> q = new Queue<Node>(); q.Enqueue(root); // To represent that target node is // found. bool found = false; while (q.Count > 0) { // If target node is present at // current level, then return // sum of cousins stored in currSum. if (found == true) { return currSum; } // Find size of current level and // traverse entire level. size = q.Count; currSum = 0; while (size > 0) { root = q.Peek(); q.Dequeue(); // Check if either of the existing // children of given node is target // node or not. If yes then set // found equal to true. if ((root.left != null && root.left.data == key) || (root.right != null && root.right.data == key)) { found = true; } // If target node is not children of // current node, then its children can be cousin // of target node, so add their value to sum. else { if (root.left != null) { currSum += root.left.data; q.Enqueue(root.left); } if (root.right != null) { currSum += root.right.data; q.Enqueue(root.right); } } size--; } } return -1;} // Driver Codepublic static void Main(String []args){ /* 1 / \ 3 7 / \ / \ 6 5 4 13 / / \ 10 17 15 */ Node root = newNode(1); root.left = newNode(3); root.right = newNode(7); root.left.left = newNode(6); root.left.right = newNode(5); root.left.right.left = newNode(10); root.right.left = newNode(4); root.right.right = newNode(13); root.right.left.left = newNode(17); root.right.left.right = newNode(15); Console.Write( findCousinSum(root, 13) + "\n"); Console.Write( findCousinSum(root, 7) + "\n");}} // This code is contributed by Princi Singh <script> // JavaScript program to find sum of cousins// of given node in binary tree. // A Binary Tree Nodeclass Node{ constructor() { this.data = 0; this.left = null; this.right = null; }}; // A utility function to create a new// Binary Tree Nodefunction newNode(item){ var temp = new Node(); temp.data = item; temp.left = temp.right = null; return temp;} // Function to find sum of cousins of// a given node.function findCousinSum(root, key){ if (root == null) return -1; // Root node has no cousins so return -1. if (root.data == key) { return -1; } // To store sum of cousins. var currSum = 0; // To store size of current level. var size; // To perform level order traversal. var q = []; q.push(root); // To represent that target node is // found. var found = false; while (q.length > 0) { // If target node is present at // current level, then return // sum of cousins stored in currSum. if (found == true) { return currSum; } // Find size of current level and // traverse entire level. size = q.length; currSum = 0; while (size > 0) { root = q[0]; q.shift(); // Check if either of the existing // children of given node is target // node or not. If yes then set // found equal to true. if ((root.left != null && root.left.data == key) || (root.right != null && root.right.data == key)) { found = true; } // If target node is not children of // current node, then its children can be cousin // of target node, so add their value to sum. else { if (root.left != null) { currSum += root.left.data; q.push(root.left); } if (root.right != null) { currSum += root.right.data; q.push(root.right); } } size--; } } return -1;} // Driver Code/* 1 / \ 3 7 / \ / \ 6 5 4 13 / / \ 10 17 15*/var root = newNode(1);root.left = newNode(3);root.right = newNode(7);root.left.left = newNode(6);root.left.right = newNode(5);root.left.right.left = newNode(10);root.right.left = newNode(4);root.right.right = newNode(13);root.right.left.left = newNode(17);root.right.left.right = newNode(15);document.write( findCousinSum(root, 13) + "<br>");document.write( findCousinSum(root, 7) + "<br>"); </script> 11 -1 Time Complexity: O(N) Auxiliary Space: O(N) SHUBHAMSINGH10 andrew1234 princi singh itsok ashutoshsinghgeeksforgeeks surinderdawra388 Binary Tree cpp-queue tree-level-order Data Structures Data Structures Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n17 Jan, 2022" }, { "code": null, "e": 309, "s": 54, "text": "Given a binary tree and data value of a node. The task is to find the sum of cousin nodes of given node. If given node has no cousins then return -1. Note: It is given that all nodes have distinct values and the given node exists in the tree. Examples: " }, { "code": null, "e": 754, "s": 309, "text": "Input: \n 1\n / \\\n 3 7\n / \\ / \\\n 6 5 4 13\n / / \\\n 10 17 15\n key = 13\nOutput: 11\nCousin nodes are 5 and 6 which gives sum 11. \n\nInput:\n 1\n / \\\n 3 7\n / \\ / \\\n 6 5 4 13\n / / \\\n 10 17 15\n key = 7\nOutput: -1\nNo cousin nodes of node having value 7." }, { "code": null, "e": 1281, "s": 756, "text": "Approach: The approach is to do a level order traversal of the tree. While performing level order traversal, find the sum of child nodes of next level. Add a child node’s value to the sum and check if either of the children nodes is the target node or not. If yes, then do not add the value of either child to the sum. After traversing current level if the target node is present in next level, then end the level order traversal and sum found is the sum of cousin nodes. Below is the implementation of the above approach: " }, { "code": null, "e": 1285, "s": 1281, "text": "C++" }, { "code": null, "e": 1290, "s": 1285, "text": "Java" }, { "code": null, "e": 1298, "s": 1290, "text": "Python3" }, { "code": null, "e": 1301, "s": 1298, "text": "C#" }, { "code": null, "e": 1312, "s": 1301, "text": "Javascript" }, { "code": "// CPP program to find sum of cousins// of given node in binary tree.#include <bits/stdc++.h>using namespace std; // A Binary Tree Nodestruct Node { int data; struct Node *left, *right;}; // A utility function to create a new// Binary Tree Nodestruct Node* newNode(int item){ struct Node* temp = new Node(); temp->data = item; temp->left = temp->right = NULL; return temp;} // Function to find sum of cousins of// a given node.int findCousinSum(Node* root, int key){ if (root == NULL) return -1; // Root node has no cousins so return -1. if (root->data == key) { return -1; } // To store sum of cousins. int currSum = 0; // To store size of current level. int size; // To perform level order traversal. queue<Node*> q; q.push(root); // To represent that target node is // found. bool found = false; while (!q.empty()) { // If target node is present at // current level, then return // sum of cousins stored in currSum. if (found == true) { return currSum; } // Find size of current level and // traverse entire level. size = q.size(); currSum = 0; while (size) { root = q.front(); q.pop(); // Check if either of the existing // children of given node is target // node or not. If yes then set // found equal to true. if ((root->left && root->left->data == key) || (root->right && root->right->data == key)) { found = true; } // If target node is not children of // current node, then its children can be cousin // of target node, so add their value to sum. else { if (root->left) { currSum += root->left->data; q.push(root->left); } if (root->right) { currSum += root->right->data; q.push(root->right); } } size--; } } return -1;} // Driver Codeint main(){ /* 1 / \\ 3 7 / \\ / \\ 6 5 4 13 / / \\ 10 17 15 */ struct Node* root = newNode(1); root->left = newNode(3); root->right = newNode(7); root->left->left = newNode(6); root->left->right = newNode(5); root->left->right->left = newNode(10); root->right->left = newNode(4); root->right->right = newNode(13); root->right->left->left = newNode(17); root->right->left->right = newNode(15); cout << findCousinSum(root, 13) << \"\\n\"; cout << findCousinSum(root, 7) << \"\\n\"; return 0;}", "e": 4085, "s": 1312, "text": null }, { "code": "// Java program to find sum of cousins// of given node in binary tree.import java.util.*;class Sol{ // A Binary Tree Nodestatic class Node{ int data; Node left, right;}; // A utility function to create a new// Binary Tree Nodestatic Node newNode(int item){ Node temp = new Node(); temp.data = item; temp.left = temp.right = null; return temp;} // Function to find sum of cousins of// a given node.static int findCousinSum(Node root, int key){ if (root == null) return -1; // Root node has no cousins so return -1. if (root.data == key) { return -1; } // To store sum of cousins. int currSum = 0; // To store size of current level. int size; // To perform level order traversal. Queue<Node> q=new LinkedList<Node>(); q.add(root); // To represent that target node is // found. boolean found = false; while (q.size() > 0) { // If target node is present at // current level, then return // sum of cousins stored in currSum. if (found == true) { return currSum; } // Find size of current level and // traverse entire level. size = q.size(); currSum = 0; while (size > 0) { root = q.peek(); q.remove(); // Check if either of the existing // children of given node is target // node or not. If yes then set // found equal to true. if ((root.left!=null && root.left.data == key) || (root.right!=null && root.right.data == key)) { found = true; } // If target node is not children of // current node, then its children can be cousin // of target node, so add their value to sum. else { if (root.left != null) { currSum += root.left.data; q.add(root.left); } if (root.right != null) { currSum += root.right.data; q.add(root.right); } } size--; } } return -1;} // Driver Codepublic static void main(String args[]){ /* 1 / \\ 3 7 / \\ / \\ 6 5 4 13 / / \\ 10 17 15 */ Node root = newNode(1); root.left = newNode(3); root.right = newNode(7); root.left.left = newNode(6); root.left.right = newNode(5); root.left.right.left = newNode(10); root.right.left = newNode(4); root.right.right = newNode(13); root.right.left.left = newNode(17); root.right.left.right = newNode(15); System.out.print( findCousinSum(root, 13) + \"\\n\"); System.out.print( findCousinSum(root, 7) + \"\\n\");}} // This code is contributed by Arnab Kundu", "e": 6985, "s": 4085, "text": null }, { "code": "\"\"\" Python3 program to find sum of cousinsof given node in binary tree \"\"\" # A Binary Tree Node# Utility function to create a new tree nodeclass newNode: # Constructor to create a newNode def __init__(self, data): self.data = data self.left = None self.right = None # Function to find sum of cousins of# a given node.def findCousinSum( root, key): if (root == None): return -1 # Root node has no cousins so return -1. if (root.data == key): return -1 # To store sum of cousins. currSum = 0 # To store size of current level. size = 0 # To perform level order traversal. q = [] q.append(root) # To represent that target node is # found. found = False while (len(q)): # If target node is present at # current level, then return # sum of cousins stored in currSum. if (found == True): return currSum # Find size of current level and # traverse entire level. size = len(q) currSum = 0 while (size): root = q[0] q.pop(0) # Check if either of the existing # children of given node is target # node or not. If yes then set # found equal to true. if ((root.left and root.left.data == key) or (root.right and root.right.data == key)) : found = True # If target node is not children of current # node, then its children can be cousin # of target node, so add their value to sum. else: if (root.left): currSum += root.left.data q.append(root.left) if (root.right) : currSum += root.right.data q.append(root.right) size -= 1 return -1 # Driver Codeif __name__ == '__main__': \"\"\" 1 / \\ 3 7 / \\ / \\ 6 5 4 13 / / \\ 10 17 15 \"\"\" root = newNode(1) root.left = newNode(3) root.right = newNode(7) root.left.left = newNode(6) root.left.right = newNode(5) root.left.right.left = newNode(10) root.right.left = newNode(4) root.right.right = newNode(13) root.right.left.left = newNode(17) root.right.left.right = newNode(15) print(findCousinSum(root, 13)) print(findCousinSum(root, 7)) # This code is contributed by# SHUBHAMSINGH10", "e": 9518, "s": 6985, "text": null }, { "code": "// C# program to find sum of cousins// of given node in binary tree.using System;using System.Collections.Generic; class Sol{ // A Binary Tree Nodepublic class Node{ public int data; public Node left, right;}; // A utility function to create a new// Binary Tree Nodestatic Node newNode(int item){ Node temp = new Node(); temp.data = item; temp.left = temp.right = null; return temp;} // Function to find sum of cousins of// a given node.static int findCousinSum(Node root, int key){ if (root == null) return -1; // Root node has no cousins so return -1. if (root.data == key) { return -1; } // To store sum of cousins. int currSum = 0; // To store size of current level. int size; // To perform level order traversal. Queue<Node> q = new Queue<Node>(); q.Enqueue(root); // To represent that target node is // found. bool found = false; while (q.Count > 0) { // If target node is present at // current level, then return // sum of cousins stored in currSum. if (found == true) { return currSum; } // Find size of current level and // traverse entire level. size = q.Count; currSum = 0; while (size > 0) { root = q.Peek(); q.Dequeue(); // Check if either of the existing // children of given node is target // node or not. If yes then set // found equal to true. if ((root.left != null && root.left.data == key) || (root.right != null && root.right.data == key)) { found = true; } // If target node is not children of // current node, then its children can be cousin // of target node, so add their value to sum. else { if (root.left != null) { currSum += root.left.data; q.Enqueue(root.left); } if (root.right != null) { currSum += root.right.data; q.Enqueue(root.right); } } size--; } } return -1;} // Driver Codepublic static void Main(String []args){ /* 1 / \\ 3 7 / \\ / \\ 6 5 4 13 / / \\ 10 17 15 */ Node root = newNode(1); root.left = newNode(3); root.right = newNode(7); root.left.left = newNode(6); root.left.right = newNode(5); root.left.right.left = newNode(10); root.right.left = newNode(4); root.right.right = newNode(13); root.right.left.left = newNode(17); root.right.left.right = newNode(15); Console.Write( findCousinSum(root, 13) + \"\\n\"); Console.Write( findCousinSum(root, 7) + \"\\n\");}} // This code is contributed by Princi Singh", "e": 12462, "s": 9518, "text": null }, { "code": "<script> // JavaScript program to find sum of cousins// of given node in binary tree. // A Binary Tree Nodeclass Node{ constructor() { this.data = 0; this.left = null; this.right = null; }}; // A utility function to create a new// Binary Tree Nodefunction newNode(item){ var temp = new Node(); temp.data = item; temp.left = temp.right = null; return temp;} // Function to find sum of cousins of// a given node.function findCousinSum(root, key){ if (root == null) return -1; // Root node has no cousins so return -1. if (root.data == key) { return -1; } // To store sum of cousins. var currSum = 0; // To store size of current level. var size; // To perform level order traversal. var q = []; q.push(root); // To represent that target node is // found. var found = false; while (q.length > 0) { // If target node is present at // current level, then return // sum of cousins stored in currSum. if (found == true) { return currSum; } // Find size of current level and // traverse entire level. size = q.length; currSum = 0; while (size > 0) { root = q[0]; q.shift(); // Check if either of the existing // children of given node is target // node or not. If yes then set // found equal to true. if ((root.left != null && root.left.data == key) || (root.right != null && root.right.data == key)) { found = true; } // If target node is not children of // current node, then its children can be cousin // of target node, so add their value to sum. else { if (root.left != null) { currSum += root.left.data; q.push(root.left); } if (root.right != null) { currSum += root.right.data; q.push(root.right); } } size--; } } return -1;} // Driver Code/* 1 / \\ 3 7 / \\ / \\ 6 5 4 13 / / \\ 10 17 15*/var root = newNode(1);root.left = newNode(3);root.right = newNode(7);root.left.left = newNode(6);root.left.right = newNode(5);root.left.right.left = newNode(10);root.right.left = newNode(4);root.right.right = newNode(13);root.right.left.left = newNode(17);root.right.left.right = newNode(15);document.write( findCousinSum(root, 13) + \"<br>\");document.write( findCousinSum(root, 7) + \"<br>\"); </script>", "e": 15176, "s": 12462, "text": null }, { "code": null, "e": 15182, "s": 15176, "text": "11\n-1" }, { "code": null, "e": 15229, "s": 15184, "text": "Time Complexity: O(N) Auxiliary Space: O(N) " }, { "code": null, "e": 15244, "s": 15229, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 15255, "s": 15244, "text": "andrew1234" }, { "code": null, "e": 15268, "s": 15255, "text": "princi singh" }, { "code": null, "e": 15274, "s": 15268, "text": "itsok" }, { "code": null, "e": 15301, "s": 15274, "text": "ashutoshsinghgeeksforgeeks" }, { "code": null, "e": 15318, "s": 15301, "text": "surinderdawra388" }, { "code": null, "e": 15330, "s": 15318, "text": "Binary Tree" }, { "code": null, "e": 15340, "s": 15330, "text": "cpp-queue" }, { "code": null, "e": 15357, "s": 15340, "text": "tree-level-order" }, { "code": null, "e": 15373, "s": 15357, "text": "Data Structures" }, { "code": null, "e": 15389, "s": 15373, "text": "Data Structures" } ]
How to pass optional parameters to a function in Python?
04 Sep, 2021 In Python, when we define functions with default values for certain parameters, it is said to have its arguments set as an option for the user. Users can either pass their values or can pretend the function to use theirs default values which are specified. In this way, the user can call the function by either passing those optional parameters or just passing the required parameters. There are two main ways to pass optional parameters in python Without using keyword arguments. By using keyword arguments. Some main point to be taken care while passing without using keyword arguments is : The order of parameters should be maintained i.e. the order in which parameters are defined in function should be maintained while calling the function. The values for the non-optional parameters should be passed otherwise it will throw an error. The value of the default arguments can be either passed or ignored. Below are some codes which explain this concept. Example 1: Python3 # Here b is predefined and hence is optional.def func(a, b=1098): return a+b print(func(2, 2)) # this 1 is represented as 'a' in the function and# function uses the default value of bprint(func(1)) Output: 4 1099 Example 2: we can also pass strings. Python3 # Here string2 is the default string useddef fun2(string1, string2="Geeks"): print(string1 + string2) # calling the function using default valuefun2('GeeksFor') # calling without default value.fun2('GeeksFor', "Geeks") Output: GeeksForGeeks GeeksForGeeks When functions are defined then the parameters are written in the form “datatype keyword-name”. So python provides a mechanism to call the function using the keyword name for passing the values. This helps the programmer by relieving them not to learn the sequence or the order in which the parameters are to be passed. Some important points we need to remember are as follows: In this case, we are not required to maintain the order of passing the values. There should be no difference between the passed and declared keyword names. Below is the code for its implementation. Python3 # Here string2 is the default string useddef fun2(string1, string2="Geeks"): print(string1 + string2) # Thiscan be a way where no order is needed.fun2(string2='GeeksFor', string1="Geeks") # since we are not mentioning the non-default argument# so it will give error.fun2(string2='GeeksFor') Output: As we can see that we don’t require any order to be maintained in the above example. Also, we can see that when we try to pass only the optional parameters then it raises an error. This happens since optional parameters can be omitted as they have a default with them, but we cannot omit required parameters (string1 in the above case.) Hence, it shows an error with the flag: “missing 1 required argument”. This example will give a more insight idea of above topic: Python3 def func(a, b, c='geeks'): print(a, "type is", type(a)) print(b, "type is", type(b)) print(c, "type is", type(c)) # The optional parameters will not decide# the type of parameter passed.# also the order is maintainedprint("first call")func(2, 'z', 2.0) # below call uses the default# mentioned value of cprint("second call")func(2, 1) # The below call (in comments) will give an error# since other required parameter is not passed.# func('a')print("third call")func(c=2, b=3, a='geeks') Output: first call 2 type is <class 'int'> z type is <class 'str'> 2.0 type is <class 'float'> second call 2 type is <class 'int'> 1 type is <class 'int'> geeks type is <class 'str'> third call geeks type is <class 'str'> 3 type is <class 'int'> 2 type is <class 'int'> So basically python functional calls checks only if the required number of functional parameters are passed or not. Below shows the case where a user tries to pass arguments in both ways discussed above along with the precaution given: Python3 def comp(a, b=2): if(a < b): print("first parameter is smaller") if(a > b): print("second parameter is smaller") if(a == b): print("both are of equal value.") print("first call")comp(1)print("second call")comp(2, 1)print("third call")comp(b=1, a=-1)print("fourth call")comp(-1, b=0) Output: first call first parameter is smaller second call second parameter is smaller third call first parameter is smaller fourth call first parameter is smaller So one thing we should remember that the keyword argument should used after all positional arguments are passed. Hence this is an important thing we must keep in mind while passing parameters in both ways to same function. saeedy2007 simmytarika5 Picked Python-Functions Technical Scripter 2020 Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n04 Sep, 2021" }, { "code": null, "e": 285, "s": 28, "text": "In Python, when we define functions with default values for certain parameters, it is said to have its arguments set as an option for the user. Users can either pass their values or can pretend the function to use theirs default values which are specified." }, { "code": null, "e": 415, "s": 285, "text": "In this way, the user can call the function by either passing those optional parameters or just passing the required parameters. " }, { "code": null, "e": 478, "s": 415, "text": "There are two main ways to pass optional parameters in python " }, { "code": null, "e": 511, "s": 478, "text": "Without using keyword arguments." }, { "code": null, "e": 539, "s": 511, "text": "By using keyword arguments." }, { "code": null, "e": 623, "s": 539, "text": "Some main point to be taken care while passing without using keyword arguments is :" }, { "code": null, "e": 776, "s": 623, "text": "The order of parameters should be maintained i.e. the order in which parameters are defined in function should be maintained while calling the function." }, { "code": null, "e": 870, "s": 776, "text": "The values for the non-optional parameters should be passed otherwise it will throw an error." }, { "code": null, "e": 938, "s": 870, "text": "The value of the default arguments can be either passed or ignored." }, { "code": null, "e": 987, "s": 938, "text": "Below are some codes which explain this concept." }, { "code": null, "e": 998, "s": 987, "text": "Example 1:" }, { "code": null, "e": 1006, "s": 998, "text": "Python3" }, { "code": "# Here b is predefined and hence is optional.def func(a, b=1098): return a+b print(func(2, 2)) # this 1 is represented as 'a' in the function and# function uses the default value of bprint(func(1))", "e": 1208, "s": 1006, "text": null }, { "code": null, "e": 1216, "s": 1208, "text": "Output:" }, { "code": null, "e": 1223, "s": 1216, "text": "4\n1099" }, { "code": null, "e": 1260, "s": 1223, "text": "Example 2: we can also pass strings." }, { "code": null, "e": 1268, "s": 1260, "text": "Python3" }, { "code": "# Here string2 is the default string useddef fun2(string1, string2=\"Geeks\"): print(string1 + string2) # calling the function using default valuefun2('GeeksFor') # calling without default value.fun2('GeeksFor', \"Geeks\")", "e": 1491, "s": 1268, "text": null }, { "code": null, "e": 1499, "s": 1491, "text": "Output:" }, { "code": null, "e": 1527, "s": 1499, "text": "GeeksForGeeks\nGeeksForGeeks" }, { "code": null, "e": 1847, "s": 1527, "text": "When functions are defined then the parameters are written in the form “datatype keyword-name”. So python provides a mechanism to call the function using the keyword name for passing the values. This helps the programmer by relieving them not to learn the sequence or the order in which the parameters are to be passed." }, { "code": null, "e": 1905, "s": 1847, "text": "Some important points we need to remember are as follows:" }, { "code": null, "e": 1984, "s": 1905, "text": "In this case, we are not required to maintain the order of passing the values." }, { "code": null, "e": 2061, "s": 1984, "text": "There should be no difference between the passed and declared keyword names." }, { "code": null, "e": 2103, "s": 2061, "text": "Below is the code for its implementation." }, { "code": null, "e": 2111, "s": 2103, "text": "Python3" }, { "code": "# Here string2 is the default string useddef fun2(string1, string2=\"Geeks\"): print(string1 + string2) # Thiscan be a way where no order is needed.fun2(string2='GeeksFor', string1=\"Geeks\") # since we are not mentioning the non-default argument# so it will give error.fun2(string2='GeeksFor')", "e": 2406, "s": 2111, "text": null }, { "code": null, "e": 2414, "s": 2406, "text": "Output:" }, { "code": null, "e": 2822, "s": 2414, "text": "As we can see that we don’t require any order to be maintained in the above example. Also, we can see that when we try to pass only the optional parameters then it raises an error. This happens since optional parameters can be omitted as they have a default with them, but we cannot omit required parameters (string1 in the above case.) Hence, it shows an error with the flag: “missing 1 required argument”." }, { "code": null, "e": 2881, "s": 2822, "text": "This example will give a more insight idea of above topic:" }, { "code": null, "e": 2889, "s": 2881, "text": "Python3" }, { "code": "def func(a, b, c='geeks'): print(a, \"type is\", type(a)) print(b, \"type is\", type(b)) print(c, \"type is\", type(c)) # The optional parameters will not decide# the type of parameter passed.# also the order is maintainedprint(\"first call\")func(2, 'z', 2.0) # below call uses the default# mentioned value of cprint(\"second call\")func(2, 1) # The below call (in comments) will give an error# since other required parameter is not passed.# func('a')print(\"third call\")func(c=2, b=3, a='geeks')", "e": 3386, "s": 2889, "text": null }, { "code": null, "e": 3394, "s": 3386, "text": "Output:" }, { "code": null, "e": 3656, "s": 3394, "text": "first call\n2 type is <class 'int'>\nz type is <class 'str'>\n2.0 type is <class 'float'>\nsecond call\n2 type is <class 'int'>\n1 type is <class 'int'>\ngeeks type is <class 'str'>\nthird call\ngeeks type is <class 'str'>\n3 type is <class 'int'>\n2 type is <class 'int'>" }, { "code": null, "e": 3772, "s": 3656, "text": "So basically python functional calls checks only if the required number of functional parameters are passed or not." }, { "code": null, "e": 3892, "s": 3772, "text": "Below shows the case where a user tries to pass arguments in both ways discussed above along with the precaution given:" }, { "code": null, "e": 3900, "s": 3892, "text": "Python3" }, { "code": "def comp(a, b=2): if(a < b): print(\"first parameter is smaller\") if(a > b): print(\"second parameter is smaller\") if(a == b): print(\"both are of equal value.\") print(\"first call\")comp(1)print(\"second call\")comp(2, 1)print(\"third call\")comp(b=1, a=-1)print(\"fourth call\")comp(-1, b=0)", "e": 4214, "s": 3900, "text": null }, { "code": null, "e": 4222, "s": 4214, "text": "Output:" }, { "code": null, "e": 4377, "s": 4222, "text": "first call\nfirst parameter is smaller\nsecond call\nsecond parameter is smaller\nthird call\nfirst parameter is smaller\nfourth call\nfirst parameter is smaller" }, { "code": null, "e": 4600, "s": 4377, "text": "So one thing we should remember that the keyword argument should used after all positional arguments are passed. Hence this is an important thing we must keep in mind while passing parameters in both ways to same function." }, { "code": null, "e": 4611, "s": 4600, "text": "saeedy2007" }, { "code": null, "e": 4624, "s": 4611, "text": "simmytarika5" }, { "code": null, "e": 4631, "s": 4624, "text": "Picked" }, { "code": null, "e": 4648, "s": 4631, "text": "Python-Functions" }, { "code": null, "e": 4672, "s": 4648, "text": "Technical Scripter 2020" }, { "code": null, "e": 4679, "s": 4672, "text": "Python" }, { "code": null, "e": 4698, "s": 4679, "text": "Technical Scripter" } ]
Longest Prefix Matching in Routers
15 Jun, 2022 What is Forwarding? Forwarding is moving incoming packets to the appropriate interface. Routers use a forwarding table to decide which incoming packet should be forwarded to which next hop. What is an IP prefix? IP prefix is a prefix of IP address. All computers on one network have the same IP prefix. For example, in 192.24.0.0/18, 18 is the length of the prefix and prefix is the first 18 bits of the address. How does forwarding work? Routers basically look at the destination address’s IP prefix, searches the forwarding table for a match, and forward the packet to the corresponding next hop in the forwarding table. What happens if the prefixes overlap? Since prefixes might overlap (this is possible as classless addressing is used everywhere), an incoming IP’s prefix may match multiple IP entries in a table. For example, consider the below forwarding table In the above table, addresses from 192.24.12.0 to 192.24.15.255 overlap, i.e., match with both entries of the table. To handle the above situation, routers use the Longest Prefix Matching rule. The rule is to find the entry in a table which has the longest prefix matching with the incoming packet’s destination IP and forward the packet to the corresponding next hope. In the above example, all packets in overlapping range (192.24.12.0 to 192.24.15.255) are forwarded to next hop B as B has a longer prefix (22 bits). Example 1: Routers forward a packet using forwarding table entries. The network address of the incoming packet may match multiple entries. How do routers resolve this? (A) Forward it to the router whose entry matches with the longest prefix of the incoming packet (B) Forward the packet to all routers whose network addresses match. (C) Discard the packet. (D) Forward it the router whose entry matches with the longest suffix of an incoming packet Answer: (A) The network addresses of different entries may overlap in the forwarding table. Routers forward the incoming packet to the router which hashes the longest prefix matching with the incoming packet. Example 2: Classless Inter-domain Routing (CIDR) receives a packet with address 131.23.151.76. The router’s routing table has the following entries: (GATE CS 2015) Prefix Output Interface Identifier 131.16.0.0/12 3 131.28.0.0/14 5 131.19.0.0/16 2 131.22.0.0/15 1 The identifier of the output interface on which this packet will be forwarded is ______. Answer: “1”. We need to first find out matching table entries for an incoming packets with address “131.23.151.76”. The address matches with two entries “131.16.0.0/12” and “131.22.0.0/15” (We found this by matching the first 12 and 15 bits respectively). So should the packet go to interface 3 or 1? We use Longest Prefix Matching to decide among the two. The most specific of the matching table entries is used as the interface. Since “131.22.0.0/15” is most specific, the packet goes to interface 1. Exercise Consider the following routing table of a router. Consider the following three IP addresses. 192.24.6.0192.24.14.32192.24.54.0 192.24.6.0 192.24.14.32 192.24.54.0 Akanksha_Rai singhsawai531 tanwarsinghvaibhav pall58183 Network Layer Computer Networks Computer Networks Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n15 Jun, 2022" }, { "code": null, "e": 245, "s": 54, "text": "What is Forwarding? Forwarding is moving incoming packets to the appropriate interface. Routers use a forwarding table to decide which incoming packet should be forwarded to which next hop. " }, { "code": null, "e": 469, "s": 245, "text": "What is an IP prefix? IP prefix is a prefix of IP address. All computers on one network have the same IP prefix. For example, in 192.24.0.0/18, 18 is the length of the prefix and prefix is the first 18 bits of the address. " }, { "code": null, "e": 680, "s": 469, "text": "How does forwarding work? Routers basically look at the destination address’s IP prefix, searches the forwarding table for a match, and forward the packet to the corresponding next hop in the forwarding table. " }, { "code": null, "e": 926, "s": 680, "text": "What happens if the prefixes overlap? Since prefixes might overlap (this is possible as classless addressing is used everywhere), an incoming IP’s prefix may match multiple IP entries in a table. For example, consider the below forwarding table " }, { "code": null, "e": 1450, "s": 928, "text": "In the above table, addresses from 192.24.12.0 to 192.24.15.255 overlap, i.e., match with both entries of the table. To handle the above situation, routers use the Longest Prefix Matching rule. The rule is to find the entry in a table which has the longest prefix matching with the incoming packet’s destination IP and forward the packet to the corresponding next hope. In the above example, all packets in overlapping range (192.24.12.0 to 192.24.15.255) are forwarded to next hop B as B has a longer prefix (22 bits). " }, { "code": null, "e": 1901, "s": 1450, "text": "Example 1: Routers forward a packet using forwarding table entries. The network address of the incoming packet may match multiple entries. How do routers resolve this? (A) Forward it to the router whose entry matches with the longest prefix of the incoming packet (B) Forward the packet to all routers whose network addresses match. (C) Discard the packet. (D) Forward it the router whose entry matches with the longest suffix of an incoming packet " }, { "code": null, "e": 2111, "s": 1901, "text": "Answer: (A) The network addresses of different entries may overlap in the forwarding table. Routers forward the incoming packet to the router which hashes the longest prefix matching with the incoming packet. " }, { "code": null, "e": 2278, "s": 2111, "text": " Example 2: Classless Inter-domain Routing (CIDR) receives a packet with address 131.23.151.76. The router’s routing table has the following entries: (GATE CS 2015) " }, { "code": null, "e": 2440, "s": 2278, "text": "Prefix Output Interface Identifier\n131.16.0.0/12 3\n131.28.0.0/14 5\n131.19.0.0/16 2\n131.22.0.0/15 1 " }, { "code": null, "e": 2530, "s": 2440, "text": "The identifier of the output interface on which this packet will be forwarded is ______. " }, { "code": null, "e": 3034, "s": 2530, "text": "Answer: “1”. We need to first find out matching table entries for an incoming packets with address “131.23.151.76”. The address matches with two entries “131.16.0.0/12” and “131.22.0.0/15” (We found this by matching the first 12 and 15 bits respectively). So should the packet go to interface 3 or 1? We use Longest Prefix Matching to decide among the two. The most specific of the matching table entries is used as the interface. Since “131.22.0.0/15” is most specific, the packet goes to interface 1. " }, { "code": null, "e": 3097, "s": 3034, "text": " Exercise Consider the following routing table of a router. " }, { "code": null, "e": 3141, "s": 3097, "text": "Consider the following three IP addresses. " }, { "code": null, "e": 3175, "s": 3141, "text": "192.24.6.0192.24.14.32192.24.54.0" }, { "code": null, "e": 3186, "s": 3175, "text": "192.24.6.0" }, { "code": null, "e": 3199, "s": 3186, "text": "192.24.14.32" }, { "code": null, "e": 3211, "s": 3199, "text": "192.24.54.0" }, { "code": null, "e": 3224, "s": 3211, "text": "Akanksha_Rai" }, { "code": null, "e": 3238, "s": 3224, "text": "singhsawai531" }, { "code": null, "e": 3257, "s": 3238, "text": "tanwarsinghvaibhav" }, { "code": null, "e": 3267, "s": 3257, "text": "pall58183" }, { "code": null, "e": 3281, "s": 3267, "text": "Network Layer" }, { "code": null, "e": 3299, "s": 3281, "text": "Computer Networks" }, { "code": null, "e": 3317, "s": 3299, "text": "Computer Networks" } ]
Tailwind CSS Line Height
23 Mar, 2022 This class accepts lots of value in tailwind CSS in which all the properties are covered as in class form. It is the alternative to the CSS Line Height property. This class is used to set the amount of space used for lines, such as in the text. Negative values are not allowed. Line Height classes: leading-3: This class set the line-height at .75rem. leading-4: This class set the line-height at 1rem. leading-5: This class set the line-height at 1.25rem. leading-6: This class set the line-height at 1.5rem. leading-7: This class set the line-height at 1.75rem. leading-8: This class set the line-height at 2rem. leading-9: This class set the line-height at 2.25rem. leading-10: This class set the line-height at 2.5rem. leading-none: This class set the line-height at 1. leading-tight: This class set the line-height at 1.25. leading-snug: This class set the line-height at 1.375. leading-normal: This class set the line-height at 1.5. leading-relaxed: This class set the line-height at 1.625. leading-loose: This class set the line-height at 2. Syntax: <element class="leading-{height}">...</element> Example: In this example, we will use three classes leading-none, leading-normal and leading-loose. You can change the class name according to your need. HTML <!DOCTYPE html> <head> <link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet"></head> <body class="text-center mx-4 space-y-2"> <h1 class="text-green-600 text-5xl font-bold"> GeeksforGeeks </h1> <b>Tailwind CSS Line Height Class</b> <div class="mx-24 bg-green-200 text-justify"> <p class="p-2">leading-none:<br> <span class="leading-none"> How many times were you frustrated while looking out for a good collection of programming/algorithm /interview questions? What did you expect and what did you get? GeeksforGeeks. </span> </p> <p class="p-2">leading-normal:<br> <span class="leading-normal"> How many times were you frustrated while looking out for a good collection of programming/algorithm /interview questions? What did you expect and what did you get? GeeksforGeeks. </span> </p> <p class="p-2">leading-loose:<br> <span class="leading-loose"> How many times were you frustrated while looking out for a good collection of programming/algorithm /interview questions? What did you expect and what did you get? GeeksforGeeks. </span> </p> </div></body> </html> Output: Line height classes Tailwind CSS Tailwind-Typography CSS 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": "\n23 Mar, 2022" }, { "code": null, "e": 307, "s": 28, "text": "This class accepts lots of value in tailwind CSS in which all the properties are covered as in class form. It is the alternative to the CSS Line Height property. This class is used to set the amount of space used for lines, such as in the text. Negative values are not allowed." }, { "code": null, "e": 328, "s": 307, "text": "Line Height classes:" }, { "code": null, "e": 381, "s": 328, "text": "leading-3: This class set the line-height at .75rem." }, { "code": null, "e": 432, "s": 381, "text": "leading-4: This class set the line-height at 1rem." }, { "code": null, "e": 487, "s": 432, "text": "leading-5: This class set the line-height at 1.25rem. " }, { "code": null, "e": 540, "s": 487, "text": "leading-6: This class set the line-height at 1.5rem." }, { "code": null, "e": 594, "s": 540, "text": "leading-7: This class set the line-height at 1.75rem." }, { "code": null, "e": 645, "s": 594, "text": "leading-8: This class set the line-height at 2rem." }, { "code": null, "e": 699, "s": 645, "text": "leading-9: This class set the line-height at 2.25rem." }, { "code": null, "e": 753, "s": 699, "text": "leading-10: This class set the line-height at 2.5rem." }, { "code": null, "e": 804, "s": 753, "text": "leading-none: This class set the line-height at 1." }, { "code": null, "e": 859, "s": 804, "text": "leading-tight: This class set the line-height at 1.25." }, { "code": null, "e": 914, "s": 859, "text": "leading-snug: This class set the line-height at 1.375." }, { "code": null, "e": 969, "s": 914, "text": "leading-normal: This class set the line-height at 1.5." }, { "code": null, "e": 1027, "s": 969, "text": "leading-relaxed: This class set the line-height at 1.625." }, { "code": null, "e": 1079, "s": 1027, "text": "leading-loose: This class set the line-height at 2." }, { "code": null, "e": 1087, "s": 1079, "text": "Syntax:" }, { "code": null, "e": 1135, "s": 1087, "text": "<element class=\"leading-{height}\">...</element>" }, { "code": null, "e": 1289, "s": 1135, "text": "Example: In this example, we will use three classes leading-none, leading-normal and leading-loose. You can change the class name according to your need." }, { "code": null, "e": 1294, "s": 1289, "text": "HTML" }, { "code": "<!DOCTYPE html> <head> <link href=\"https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css\" rel=\"stylesheet\"></head> <body class=\"text-center mx-4 space-y-2\"> <h1 class=\"text-green-600 text-5xl font-bold\"> GeeksforGeeks </h1> <b>Tailwind CSS Line Height Class</b> <div class=\"mx-24 bg-green-200 text-justify\"> <p class=\"p-2\">leading-none:<br> <span class=\"leading-none\"> How many times were you frustrated while looking out for a good collection of programming/algorithm /interview questions? What did you expect and what did you get? GeeksforGeeks. </span> </p> <p class=\"p-2\">leading-normal:<br> <span class=\"leading-normal\"> How many times were you frustrated while looking out for a good collection of programming/algorithm /interview questions? What did you expect and what did you get? GeeksforGeeks. </span> </p> <p class=\"p-2\">leading-loose:<br> <span class=\"leading-loose\"> How many times were you frustrated while looking out for a good collection of programming/algorithm /interview questions? What did you expect and what did you get? GeeksforGeeks. </span> </p> </div></body> </html>", "e": 2826, "s": 1294, "text": null }, { "code": null, "e": 2834, "s": 2826, "text": "Output:" }, { "code": null, "e": 2854, "s": 2834, "text": "Line height classes" }, { "code": null, "e": 2867, "s": 2854, "text": "Tailwind CSS" }, { "code": null, "e": 2887, "s": 2867, "text": "Tailwind-Typography" }, { "code": null, "e": 2891, "s": 2887, "text": "CSS" }, { "code": null, "e": 2908, "s": 2891, "text": "Web Technologies" } ]
JavaScript - RegExp ignoreCase Property
ignoreCase is a read-only boolean property of RegExp objects. It specifies whether a particular regular expression performs case-insensitive matching, i.e., whether it was created with the "i" attribute. Its syntax is as follows − RegExpObject.ignoreCase Returns "TRUE" if the "i" modifier is set, "FALSE" otherwise. Try the following example program. <html> <head> <title>JavaScript RegExp ignoreCase Property</title> </head> <body> <script type = "text/javascript"> var re = new RegExp( "string" ); if ( re.ignoreCase ) { document.write("Test1-ignoreCase property is set"); } else { document.write("Test1-ignoreCase property is not set"); } re = new RegExp( "string", "i" ); if ( re.ignoreCase ) { document.write("<br/>Test2-ignoreCase property is set"); } else { document.write("<br/>Test2-ignoreCase property is not set"); } </script> </body> </html> Test1 - ignoreCase property is not set Test2 - ignoreCase property is set 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": 2670, "s": 2466, "text": "ignoreCase is a read-only boolean property of RegExp objects. It specifies whether a particular regular expression performs case-insensitive matching, i.e., whether it was created with the \"i\" attribute." }, { "code": null, "e": 2697, "s": 2670, "text": "Its syntax is as follows −" }, { "code": null, "e": 2722, "s": 2697, "text": "RegExpObject.ignoreCase\n" }, { "code": null, "e": 2784, "s": 2722, "text": "Returns \"TRUE\" if the \"i\" modifier is set, \"FALSE\" otherwise." }, { "code": null, "e": 2819, "s": 2784, "text": "Try the following example program." }, { "code": null, "e": 3507, "s": 2819, "text": "<html> \n <head>\n <title>JavaScript RegExp ignoreCase Property</title>\n </head>\n \n <body>\n <script type = \"text/javascript\">\n var re = new RegExp( \"string\" );\n \n if ( re.ignoreCase ) {\n document.write(\"Test1-ignoreCase property is set\"); \n } else {\n document.write(\"Test1-ignoreCase property is not set\"); \n }\n re = new RegExp( \"string\", \"i\" );\n \n if ( re.ignoreCase ) {\n document.write(\"<br/>Test2-ignoreCase property is set\"); \n } else {\n document.write(\"<br/>Test2-ignoreCase property is not set\"); \n }\n </script> \n </body>\n</html>" }, { "code": null, "e": 3583, "s": 3507, "text": "Test1 - ignoreCase property is not set\nTest2 - ignoreCase property is set \n" }, { "code": null, "e": 3618, "s": 3583, "text": "\n 25 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3632, "s": 3618, "text": " Anadi Sharma" }, { "code": null, "e": 3666, "s": 3632, "text": "\n 74 Lectures \n 10 hours \n" }, { "code": null, "e": 3680, "s": 3666, "text": " Lets Kode It" }, { "code": null, "e": 3715, "s": 3680, "text": "\n 72 Lectures \n 4.5 hours \n" }, { "code": null, "e": 3732, "s": 3715, "text": " Frahaan Hussain" }, { "code": null, "e": 3767, "s": 3732, "text": "\n 70 Lectures \n 4.5 hours \n" }, { "code": null, "e": 3784, "s": 3767, "text": " Frahaan Hussain" }, { "code": null, "e": 3817, "s": 3784, "text": "\n 46 Lectures \n 6 hours \n" }, { "code": null, "e": 3845, "s": 3817, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 3879, "s": 3845, "text": "\n 88 Lectures \n 14 hours \n" }, { "code": null, "e": 3907, "s": 3879, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 3914, "s": 3907, "text": " Print" }, { "code": null, "e": 3925, "s": 3914, "text": " Add Notes" } ]
Report Scriptlets
We have seen in our previous chapters, data displayed on the report is usually fetched from report parameters and report fields. This data can be processed using the report variables and their expressions. There are situations when a complex functionality cannot be achieved easily using report expressions or variables. Examples of this may be complex String manipulations, building of Maps, or Lists of objects in memory or manipulations of dates using 3rd party Java APIs. For such situations, JasperReports provides us with a simple and powerful means of doing this with Scriptlets. Scriptlets are sequences of Java code that are executed every time a report event occurs. Values of report variables can be affected through scriptlets. We can declare a scriptlet in two ways − Using <scriptlet> element. This element has name attribute and class attribute. The class attribute should specify the name of the class, which extends JRAbstractScriptlet class. The class must be available in the classpath at report filling time and must have an empty constructor, so that the engine can instantiate it on the fly. Using <scriptlet> element. This element has name attribute and class attribute. The class attribute should specify the name of the class, which extends JRAbstractScriptlet class. The class must be available in the classpath at report filling time and must have an empty constructor, so that the engine can instantiate it on the fly. Using the attribute scriptletClass of the element <jasperReport>, in the report template (JRXML). By setting this attribute with fully qualified name of scriptlet (including the entire package name), we indicate that we want to use a scriptlet. The scriptlet instance, created with this attribute, acts like the first scriptlet in the list of scriptlets and has the predefined name REPORT. Using the attribute scriptletClass of the element <jasperReport>, in the report template (JRXML). By setting this attribute with fully qualified name of scriptlet (including the entire package name), we indicate that we want to use a scriptlet. The scriptlet instance, created with this attribute, acts like the first scriptlet in the list of scriptlets and has the predefined name REPORT. A scriptlet is a java class, which must extend either of the following classes − net.sf.jasperreports.engine.JRAbstractScriptlet − This class contains a number of abstract methods that must be overridden in every implementation. These methods are called automatically by JasperReports at the appropriate moment. Developer must implement all the abstract methods. net.sf.jasperreports.engine.JRAbstractScriptlet − This class contains a number of abstract methods that must be overridden in every implementation. These methods are called automatically by JasperReports at the appropriate moment. Developer must implement all the abstract methods. net.sf.jasperreports.engine.JRDefaultScriptlet − This class contains default empty implementations of every method in JRAbstractScriptlet. A developer is only required to implement those methods he/she needs for his/her project. net.sf.jasperreports.engine.JRDefaultScriptlet − This class contains default empty implementations of every method in JRAbstractScriptlet. A developer is only required to implement those methods he/she needs for his/her project. The following table lists the methods in the above class. These methods will be called by the report engine at the appropriate time, during report filling phase. public void beforeReportInit() Called before report initialization. public void afterReportInit() Called after report initialization. public void beforePageInit() Called before each page is initialized. public void afterPageInit() Called after each page is initialized. public void beforeColumnInit() Called before each column is initialized. public void afterColumnInit() Called after each column is initialized. public void beforeGroupInit(String groupName) Called before the group specified in the parameter is initialized. public void afterGroupInit(String groupName) Called after the group specified in the parameter is initialized. public void beforeDetailEval() Called before each record in the detail section of the report is evaluated. public void afterDetailEval() Called after each record in the detail section of the report is evaluated. Any number of scriptlets can be specified per report. If no scriptlet is specified for a report, the engine still creates a single JRDefaultScriptlet instance and registers it with the built-in REPORT_SCRIPTLET parameter. We can add any additional methods that we need to our scriptlets. Reports can call these methods by using the built-in parameter REPORT_SCRIPTLET. We can associate scriptlets in another way to reports, which is by declaring the scriptlets globally. This makes the scriptlets apply to all reports being filled in the given JasperReports deployment. This is made easy by the fact that scriptlets can be added to JasperReports as extensions. The scriptlet extension point is represented by the net.sf.jasperreports.engine.scriptlets.ScriptletFactory interface. JasperReports will load all scriptlet factories available through extensions at runtime. Then, it will ask each one of them for the list of scriptlets instances that they want to apply to the current report that is being run. When asking for the list of scriptlet instances, the engine gives some context information that the factory could use in order to decide, which scriptlets actually apply to the current report. Governors are just an extension of global scriptlets that enable us to tackle a problem of report engine entering infinite loop at runtime, while generating reports. Invalid report templates cannot be detected at design time, because most of the time, the conditions for entering the infinite loops depend on the actual data that is fed into the engine at runtime. Report Governors help in deciding whether a certain report has entered an infinite loop and they can stop it. This prevents resource exhaustion for the machine that runs the report. JasperReports has two simple report governors that would stop a report execution based on a specified maximum number of pages or a specified timeout interval. They are − net.sf.jasperreports.governors.MaxPagesGovernor − This is a global scriptlet that is looking for two configuration properties to decide if it applies or not to the report currently being run. The configuration properties are − net.sf.jasperreports.governor.max.pages.enabled=[true|false] net.sf.jasperreports.governor.max.pages=[integer] net.sf.jasperreports.governors.MaxPagesGovernor − This is a global scriptlet that is looking for two configuration properties to decide if it applies or not to the report currently being run. The configuration properties are − net.sf.jasperreports.governor.max.pages.enabled=[true|false] net.sf.jasperreports.governor.max.pages.enabled=[true|false] net.sf.jasperreports.governor.max.pages=[integer] net.sf.jasperreports.governor.max.pages=[integer] net.sf.jasperreports.governors.TimeoutGovernor− This is also a global scriptlet that is looking for the following two configuration properties to decide if it applies or not. The configuration properties are − net.sf.jasperreports.governor.timeout.enabled=[true|false] net.sf.jasperreports.governor.timeout=[milliseconds] net.sf.jasperreports.governors.TimeoutGovernor− This is also a global scriptlet that is looking for the following two configuration properties to decide if it applies or not. The configuration properties are − net.sf.jasperreports.governor.timeout.enabled=[true|false] net.sf.jasperreports.governor.timeout.enabled=[true|false] net.sf.jasperreports.governor.timeout=[milliseconds] net.sf.jasperreports.governor.timeout=[milliseconds] The properties for both governors can be set globally, in the jasperreports.properties file, or at report level, as custom report properties. This is useful because different reports can have different estimated size or timeout limits and also because you might want turn on the governors for all reports, while turning it off for some, or vice-versa. Let's write a scriptlet class (MyScriptlet). The contents of file C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint\MyScriptlet.java are as follows − package com.tutorialspoint; import net.sf.jasperreports.engine.JRDefaultScriptlet; import net.sf.jasperreports.engine.JRScriptletException; public class MyScriptlet extends JRDefaultScriptlet { public void afterReportInit() throws JRScriptletException{ System.out.println("call afterReportInit()"); // this.setVariableValue("AllCountries", sbuffer.toString()); this.setVariableValue("someVar", new String("This variable value was modified by the scriptlet.")); } public String hello() throws JRScriptletException { return "Hello! I'm the report's scriptlet object."; } } Details of the above scriptlet class are as follows − In the afterReportInit method, we set a value to the variable "someVar" this.setVariableValue("someVar", new String("This variable value was modified by the scriptlet.")). In the afterReportInit method, we set a value to the variable "someVar" this.setVariableValue("someVar", new String("This variable value was modified by the scriptlet.")). At the end of the class, an extra method called 'hello' has been defined. This is an example of a method that can be added to the Scriptlet that actually returns a value, rather than setting a Variable. At the end of the class, an extra method called 'hello' has been defined. This is an example of a method that can be added to the Scriptlet that actually returns a value, rather than setting a Variable. Next, we will add the scriptlet class reference in our existing report template (Chapter Report Designs). The revised report template (jasper_report_template.jrxml) are as follows. Save it to C:\tools\jasperreports-5.0.1\test directory − <?xml version = "1.0"?> <!DOCTYPE jasperReport PUBLIC "//JasperReports//DTD Report Design//EN" "http://jasperreports.sourceforge.net/dtds/jasperreport.dtd"> <jasperReport xmlns = "http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation = "http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name = "jasper_report_template" pageWidth = "595" pageHeight = "842" columnWidth = "515" leftMargin = "40" rightMargin = "40" topMargin = "50" bottomMargin = "50" scriptletClass = "com.tutorialspoint.MyScriptlet"> <style name = "alternateStyle" fontName = "Arial" forecolor = "red"> <conditionalStyle> <conditionExpression> <![CDATA[new Boolean($V{countNumber}.intValue() % 2 == 0)]]> </conditionExpression> <style forecolor = "blue" isBold = "true"/> </conditionalStyle> </style> <parameter name = "ReportTitle" class = "java.lang.String"/> <parameter name = "Author" class = "java.lang.String"/> <queryString> <![CDATA[]]> </queryString> <field name = "country" class = "java.lang.String"> <fieldDescription> <![CDATA[country]]> </fieldDescription> </field> <field name = "name" class = "java.lang.String"> <fieldDescription> <![CDATA[name]]> </fieldDescription> </field> <variable name = "countNumber" class = "java.lang.Integer" calculation = "Count"> <variableExpression>< ![CDATA[Boolean.TRUE]]> </variableExpression> </variable> <variable name = "someVar" class = "java.lang.String"> <initialValueExpression> <![CDATA["This is the initial variable value."]]> </initialValueExpression> </variable> <title> <band height = "100"> <line> <reportElement x = "0" y = "0" width = "515" height = "1"/> </line> <textField isBlankWhenNull = "true" bookmarkLevel = "1"> <reportElement x = "0" y = "10" width = "515" height = "30"/> <textElement textAlignment = "Center"> <font size = "22"/> </textElement> <textFieldExpression class = "java.lang.String"> <![CDATA[$P{ReportTitle}]]> </textFieldExpression> <anchorNameExpression> <![CDATA["Title"]]> </anchorNameExpression> </textField> <textField isBlankWhenNull = "true"> <reportElement x = "0" y = "40" width = "515" height = "20"/> <textElement textAlignment = "Center"> <font size = "10"/> </textElement> <textFieldExpression class = "java.lang.String"> <![CDATA[$P{Author}]]> </textFieldExpression> </textField> <textField isBlankWhenNull = "true"> <reportElement x = "0" y = "50" width = "515" height = "30" forecolor = "#993300"/> <textElement textAlignment = "Center"> <font size = "10"/> </textElement> <textFieldExpression class = "java.lang.String"> <![CDATA[$V{someVar}]]> </textFieldExpression> </textField> </band> </title> <columnHeader> <band height = "23"> <staticText> <reportElement mode = "Opaque" x = "0" y = "3" width = "535" height = "15" backcolor = "#70A9A9" /> <box> <bottomPen lineWidth = "1.0" lineColor = "#CCCCCC" /> </box> <textElement /> <text> <![CDATA[]]> </text> </staticText> <staticText> <reportElement x = "414" y = "3" width = "121" height = "15" /> <textElement textAlignment = "Center" verticalAlignment = "Middle"> <font isBold = "true" /> </textElement> <text><![CDATA[Country]]></text> </staticText> <staticText> <reportElement x = "0" y = "3" width = "136" height = "15" /> <textElement textAlignment = "Center" verticalAlignment = "Middle"> <font isBold = "true" /> </textElement> <text><![CDATA[Name]]></text> </staticText> </band> </columnHeader> <detail> <band height = "16"> <staticText> <reportElement mode = "Opaque" x = "0" y = "0" width = "535" height = "14" backcolor = "#E5ECF9" /> <box> <bottomPen lineWidth = "0.25" lineColor = "#CCCCCC" /> </box> <textElement /> <text> <![CDATA[]]> </text> </staticText> <textField> <reportElement style = "alternateStyle" x="414" y = "0" width = "121" height = "15" /> <textElement textAlignment = "Center" verticalAlignment = "Middle"> <font size = "9" /> </textElement> <textFieldExpression class = "java.lang.String"> <![CDATA[$F{country}]]> </textFieldExpression> </textField> <textField> <reportElement x = "0" y = "0" width = "136" height = "15" /> <textElement textAlignment = "Center" verticalAlignment = "Middle" /> <textFieldExpression class = "java.lang.String"> <![CDATA[$F{name}]]> </textFieldExpression> </textField> </band> </detail> <summary> <band height = "45"> <textField isStretchWithOverflow = "true"> <reportElement x = "0" y = "10" width = "515" height = "15" /> <textElement textAlignment = "Center"/> <textFieldExpression class = "java.lang.String"> <![CDATA["There are " + String.valueOf($V{REPORT_COUNT}) + " records on this report."]]> </textFieldExpression> </textField> <textField isStretchWithOverflow = "true"> <reportElement positionType = "Float" x = "0" y = "30" width = "515" height = "15" forecolor = "# 993300" /> <textElement textAlignment = "Center"> <font size = "10"/> </textElement> <textFieldExpression class = "java.lang.String"> <![CDATA[$P{REPORT_SCRIPTLET}.hello()]]> </textFieldExpression> </textField> </band> </summary> </jasperReport> The details of the revised report template is given below − We have referenced the MyScriptlet class in the attribute scriptletClass of <jasperReport> element. We have referenced the MyScriptlet class in the attribute scriptletClass of <jasperReport> element. Scriptlets can only access, but not modify the report fields and parameters. However, scriptlets can modify report variable values. This can be accomplished by calling the setVariableValue() method. This method is defined in JRAbstractScriptlet class, which is always the parent class of any scriptlet. Here, we have defined a variable someVar, which will be modified by the MyScriptlet to have the value This value was modified by the scriptlet. Scriptlets can only access, but not modify the report fields and parameters. However, scriptlets can modify report variable values. This can be accomplished by calling the setVariableValue() method. This method is defined in JRAbstractScriptlet class, which is always the parent class of any scriptlet. Here, we have defined a variable someVar, which will be modified by the MyScriptlet to have the value This value was modified by the scriptlet. The above report template has a method call in the Summary band that illustrates how to write new methods (in scriptlets) and use them in the report template. ($P{REPORT_SCRIPTLET}.hello()) The above report template has a method call in the Summary band that illustrates how to write new methods (in scriptlets) and use them in the report template. ($P{REPORT_SCRIPTLET}.hello()) The java codes for report filling remain unchanged. The contents of the file C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint\JasperReportFill.java are as given below − package com.tutorialspoint; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import net.sf.jasperreports.engine.JRException; import net.sf.jasperreports.engine.JasperFillManager; import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource; public class JasperReportFill { @SuppressWarnings("unchecked") public static void main(String[] args) { String sourceFileName = "C://tools/jasperreports-5.0.1/test/jasper_report_template.jasper"; DataBeanList DataBeanList = new DataBeanList(); ArrayList<DataBean> dataList = DataBeanList.getDataBeanList(); JRBeanCollectionDataSource beanColDataSource = new JRBeanCollectionDataSource(dataList); Map parameters = new HashMap(); /** * Passing ReportTitle and Author as parameters */ parameters.put("ReportTitle", "List of Contacts"); parameters.put("Author", "Prepared By Manisha"); try { JasperFillManager.fillReportToFile( sourceFileName, parameters, beanColDataSource); } catch (JRException e) { e.printStackTrace(); } } } The contents of the POJO file C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint\DataBean.java are as given below − package com.tutorialspoint; public class DataBean { private String name; private String country; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } } The contents of the file C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint\DataBeanList.java are as given below − package com.tutorialspoint; import java.util.ArrayList; public class DataBeanList { public ArrayList<DataBean> getDataBeanList() { ArrayList<DataBean> dataBeanList = new ArrayList<DataBean>(); dataBeanList.add(produce("Manisha", "India")); dataBeanList.add(produce("Dennis Ritchie", "USA")); dataBeanList.add(produce("V.Anand", "India")); dataBeanList.add(produce("Shrinath", "California")); return dataBeanList; } /** * This method returns a DataBean object, * with name and country set in it. */ private DataBean produce(String name, String country) { DataBean dataBean = new DataBean(); dataBean.setName(name); dataBean.setCountry(country); return dataBean; } } We will compile and execute the above file using our regular ANT build process. The contents of the file build.xml (saved under directory C:\tools\jasperreports-5.0.1\test) are as given below. The import file - baseBuild.xml is picked up from the chapter Environment Setup and should be placed in the same directory as the build.xml. <?xml version = "1.0" encoding = "UTF-8"?> <project name = "JasperReportTest" default = "viewFillReport" basedir = "."> <import file = "baseBuild.xml" /> <target name = "viewFillReport" depends = "compile,compilereportdesing,run" description = "Launches the report viewer to preview the report stored in the .JRprint file."> <java classname = "net.sf.jasperreports.view.JasperViewer" fork = "true"> <arg value = "-F${file.name}.JRprint" /> <classpath refid = "classpath" /> </java> </target> <target name = "compilereportdesing" description = "Compiles the JXML file and produces the .jasper file."> <taskdef name = "jrc" classname = "net.sf.jasperreports.ant.JRAntCompileTask"> <classpath refid = "classpath" /> </taskdef> <jrc destdir = "."> <src> <fileset dir = "."> <include name = "*.jrxml" /> </fileset> </src> <classpath refid = "classpath" /> </jrc> </target> </project> Next, let's open command line window and go to the directory where build.xml is placed. Finally, execute the command ant -Dmain-class=com.tutorialspoint.JasperReportFill (viewFullReport is the default target) as − C:\tools\jasperreports-5.0.1\test>ant -Dmain-class=com.tutorialspoint.JasperReportFill Buildfile: C:\tools\jasperreports-5.0.1\test\build.xml clean-sample: [delete] Deleting directory C:\tools\jasperreports-5.0.1\test\classes [delete] Deleting: C:\tools\jasperreports-5.0.1\test\jasper_report_template.jasper [delete] Deleting: C:\tools\jasperreports-5.0.1\test\jasper_report_template.jrprint compile: [mkdir] Created dir: C:\tools\jasperreports-5.0.1\test\classes [javac] C:\tools\jasperreports-5.0.1\test\baseBuild.xml:28: warning: 'includeantruntime' was not set, defaulting to bu [javac] Compiling 4 source files to C:\tools\jasperreports-5.0.1\test\classes compilereportdesing: [jrc] Compiling 1 report design files. [jrc] log4j:WARN No appenders could be found for logger (net.sf.jasperreports.engine.xml.JRXmlDigesterFactory). [jrc] log4j:WARN Please initialize the log4j system properly. [jrc] log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info. [jrc] File : C:\tools\jasperreports-5.0.1\test\jasper_report_template.jrxml ... OK. run: [echo] Runnin class : com.tutorialspoint.JasperReportFill [java] log4j:WARN No appenders could be found for logger (net.sf.jasperreports.extensions.ExtensionsEnvironment). [java] log4j:WARN Please initialize the log4j system properly. [java] call afterReportInit() [java] call afterReportInit() viewFillReport: [java] log4j:WARN No appenders could be found for logger (net.sf.jasperreports.extensions.ExtensionsEnvironment). [java] log4j:WARN Please initialize the log4j system properly. BUILD SUCCESSFUL Total time: 18 minutes 49 seconds As a result of above compilation, a JasperViewer window opens up as shown in the screen given below − Here we see two messages are displayed from MyScriptlet class − In title section − This variable value was modified by the scriptlet At the bottom − Hello! I'm the report's scriptlet object. Print Add Notes Bookmark this page
[ { "code": null, "e": 2841, "s": 2254, "text": "We have seen in our previous chapters, data displayed on the report is usually fetched from report parameters and report fields. This data can be processed using the report variables and their expressions. There are situations when a complex functionality cannot be achieved easily using report expressions or variables. Examples of this may be complex String manipulations, building of Maps, or Lists of objects in memory or manipulations of dates using 3rd party Java APIs. For such situations, JasperReports provides us with a simple and powerful means of doing this with Scriptlets." }, { "code": null, "e": 2994, "s": 2841, "text": "Scriptlets are sequences of Java code that are executed every time a report event occurs. Values of report variables can be affected through scriptlets." }, { "code": null, "e": 3035, "s": 2994, "text": "We can declare a scriptlet in two ways −" }, { "code": null, "e": 3368, "s": 3035, "text": "Using <scriptlet> element. This element has name attribute and class attribute. The class attribute should specify the name of the class, which extends JRAbstractScriptlet class. The class must be available in the classpath at report filling time and must have an empty constructor, so that the engine can instantiate it on the fly." }, { "code": null, "e": 3701, "s": 3368, "text": "Using <scriptlet> element. This element has name attribute and class attribute. The class attribute should specify the name of the class, which extends JRAbstractScriptlet class. The class must be available in the classpath at report filling time and must have an empty constructor, so that the engine can instantiate it on the fly." }, { "code": null, "e": 4092, "s": 3701, "text": "Using the attribute scriptletClass of the element <jasperReport>, in the report template (JRXML). By setting this attribute with fully qualified name of scriptlet (including the entire package name), we indicate that we want to use a scriptlet. The scriptlet instance, created with this attribute, acts like the first scriptlet in the list of scriptlets and has the\npredefined name REPORT." }, { "code": null, "e": 4483, "s": 4092, "text": "Using the attribute scriptletClass of the element <jasperReport>, in the report template (JRXML). By setting this attribute with fully qualified name of scriptlet (including the entire package name), we indicate that we want to use a scriptlet. The scriptlet instance, created with this attribute, acts like the first scriptlet in the list of scriptlets and has the\npredefined name REPORT." }, { "code": null, "e": 4564, "s": 4483, "text": "A scriptlet is a java class, which must extend either of the following classes −" }, { "code": null, "e": 4846, "s": 4564, "text": "net.sf.jasperreports.engine.JRAbstractScriptlet − This class contains a number of abstract methods that must be overridden in every implementation. These methods are called automatically by JasperReports at the appropriate moment. Developer must implement all the abstract methods." }, { "code": null, "e": 5128, "s": 4846, "text": "net.sf.jasperreports.engine.JRAbstractScriptlet − This class contains a number of abstract methods that must be overridden in every implementation. These methods are called automatically by JasperReports at the appropriate moment. Developer must implement all the abstract methods." }, { "code": null, "e": 5358, "s": 5128, "text": "net.sf.jasperreports.engine.JRDefaultScriptlet − This class contains default empty implementations of every method in JRAbstractScriptlet. A developer is only required to implement those methods he/she needs for his/her project.\n" }, { "code": null, "e": 5588, "s": 5358, "text": "net.sf.jasperreports.engine.JRDefaultScriptlet − This class contains default empty implementations of every method in JRAbstractScriptlet. A developer is only required to implement those methods he/she needs for his/her project.\n" }, { "code": null, "e": 5750, "s": 5588, "text": "The following table lists the methods in the above class. These methods will be called by the report engine at the appropriate time, during report filling phase." }, { "code": null, "e": 5781, "s": 5750, "text": "public void beforeReportInit()" }, { "code": null, "e": 5818, "s": 5781, "text": "Called before report initialization." }, { "code": null, "e": 5848, "s": 5818, "text": "public void afterReportInit()" }, { "code": null, "e": 5884, "s": 5848, "text": "Called after report initialization." }, { "code": null, "e": 5913, "s": 5884, "text": "public void beforePageInit()" }, { "code": null, "e": 5953, "s": 5913, "text": "Called before each page is initialized." }, { "code": null, "e": 5981, "s": 5953, "text": "public void afterPageInit()" }, { "code": null, "e": 6020, "s": 5981, "text": "Called after each page is initialized." }, { "code": null, "e": 6051, "s": 6020, "text": "public void beforeColumnInit()" }, { "code": null, "e": 6093, "s": 6051, "text": "Called before each column is initialized." }, { "code": null, "e": 6123, "s": 6093, "text": "public void afterColumnInit()" }, { "code": null, "e": 6164, "s": 6123, "text": "Called after each column is initialized." }, { "code": null, "e": 6210, "s": 6164, "text": "public void beforeGroupInit(String groupName)" }, { "code": null, "e": 6277, "s": 6210, "text": "Called before the group specified in the parameter is initialized." }, { "code": null, "e": 6322, "s": 6277, "text": "public void afterGroupInit(String groupName)" }, { "code": null, "e": 6388, "s": 6322, "text": "Called after the group specified in the parameter is initialized." }, { "code": null, "e": 6419, "s": 6388, "text": "public void beforeDetailEval()" }, { "code": null, "e": 6495, "s": 6419, "text": "Called before each record in the detail section of the report is evaluated." }, { "code": null, "e": 6525, "s": 6495, "text": "public void afterDetailEval()" }, { "code": null, "e": 6600, "s": 6525, "text": "Called after each record in the detail section of the report is evaluated." }, { "code": null, "e": 6822, "s": 6600, "text": "Any number of scriptlets can be specified per report. If no scriptlet is specified for a report, the engine still creates a single JRDefaultScriptlet instance and registers it with the built-in REPORT_SCRIPTLET parameter." }, { "code": null, "e": 6969, "s": 6822, "text": "We can add any additional methods that we need to our scriptlets. Reports can call these methods by using the built-in parameter REPORT_SCRIPTLET." }, { "code": null, "e": 7799, "s": 6969, "text": "We can associate scriptlets in another way to reports, which is by declaring the scriptlets globally. This makes the scriptlets apply to all reports being filled in the given JasperReports deployment. This is made easy by the fact that scriptlets can be added to JasperReports as extensions. The scriptlet extension point is represented by the net.sf.jasperreports.engine.scriptlets.ScriptletFactory interface. JasperReports will load all scriptlet factories available through extensions at runtime. Then, it will ask each one of them for the list of scriptlets instances that they want to apply to the current report that is being run. When asking for the list of scriptlet instances, the engine gives some context information that the factory could use in order to decide, which scriptlets actually apply to the current report." }, { "code": null, "e": 8346, "s": 7799, "text": "Governors are just an extension of global scriptlets that enable us to tackle a problem of report engine entering infinite loop at runtime, while generating reports. Invalid report templates cannot be detected at design time, because most of the time, the conditions for entering the infinite loops depend on the actual data that is fed into the engine at runtime. Report Governors help in deciding whether a certain report has entered an infinite loop and they can stop it. This prevents resource exhaustion for the machine that runs the report." }, { "code": null, "e": 8516, "s": 8346, "text": "JasperReports has two simple report governors that would stop a report execution based on a specified maximum number of pages or a specified timeout interval. They are −" }, { "code": null, "e": 8857, "s": 8516, "text": "net.sf.jasperreports.governors.MaxPagesGovernor − This is a global scriptlet that is looking for two configuration properties to decide if it applies or not to the report currently being run. The configuration properties are −\n\nnet.sf.jasperreports.governor.max.pages.enabled=[true|false]\nnet.sf.jasperreports.governor.max.pages=[integer]\n\n" }, { "code": null, "e": 9084, "s": 8857, "text": "net.sf.jasperreports.governors.MaxPagesGovernor − This is a global scriptlet that is looking for two configuration properties to decide if it applies or not to the report currently being run. The configuration properties are −" }, { "code": null, "e": 9145, "s": 9084, "text": "net.sf.jasperreports.governor.max.pages.enabled=[true|false]" }, { "code": null, "e": 9206, "s": 9145, "text": "net.sf.jasperreports.governor.max.pages.enabled=[true|false]" }, { "code": null, "e": 9256, "s": 9206, "text": "net.sf.jasperreports.governor.max.pages=[integer]" }, { "code": null, "e": 9306, "s": 9256, "text": "net.sf.jasperreports.governor.max.pages=[integer]" }, { "code": null, "e": 9631, "s": 9306, "text": "net.sf.jasperreports.governors.TimeoutGovernor− This is also a global scriptlet that is looking for the following two configuration properties to decide if it applies or not.\nThe configuration properties are −\n\nnet.sf.jasperreports.governor.timeout.enabled=[true|false]\nnet.sf.jasperreports.governor.timeout=[milliseconds]\n\n" }, { "code": null, "e": 9806, "s": 9631, "text": "net.sf.jasperreports.governors.TimeoutGovernor− This is also a global scriptlet that is looking for the following two configuration properties to decide if it applies or not." }, { "code": null, "e": 9841, "s": 9806, "text": "The configuration properties are −" }, { "code": null, "e": 9900, "s": 9841, "text": "net.sf.jasperreports.governor.timeout.enabled=[true|false]" }, { "code": null, "e": 9959, "s": 9900, "text": "net.sf.jasperreports.governor.timeout.enabled=[true|false]" }, { "code": null, "e": 10012, "s": 9959, "text": "net.sf.jasperreports.governor.timeout=[milliseconds]" }, { "code": null, "e": 10065, "s": 10012, "text": "net.sf.jasperreports.governor.timeout=[milliseconds]" }, { "code": null, "e": 10417, "s": 10065, "text": "The properties for both governors can be set globally, in the jasperreports.properties file, or at report level, as custom report properties. This is useful because different reports can have different estimated size or timeout limits and also because you might want turn on the governors for all reports, while turning it off for some, or vice-versa." }, { "code": null, "e": 10574, "s": 10417, "text": "Let's write a scriptlet class (MyScriptlet). The contents of file C:\\tools\\jasperreports-5.0.1\\test\\src\\com\\tutorialspoint\\MyScriptlet.java are as follows −" }, { "code": null, "e": 11197, "s": 10574, "text": "package com.tutorialspoint;\n\nimport net.sf.jasperreports.engine.JRDefaultScriptlet;\nimport net.sf.jasperreports.engine.JRScriptletException;\n\n\npublic class MyScriptlet extends JRDefaultScriptlet {\n\n public void afterReportInit() throws JRScriptletException{\n System.out.println(\"call afterReportInit()\");\n // this.setVariableValue(\"AllCountries\", sbuffer.toString());\n this.setVariableValue(\"someVar\", new String(\"This variable value \n was modified by the scriptlet.\"));\n }\n\n public String hello() throws JRScriptletException {\n return \"Hello! I'm the report's scriptlet object.\";\n }\n\n}" }, { "code": null, "e": 11251, "s": 11197, "text": "Details of the above scriptlet class are as follows −" }, { "code": null, "e": 11423, "s": 11251, "text": "In the afterReportInit method, we set a value to the variable \"someVar\" this.setVariableValue(\"someVar\", new String(\"This variable value was modified by the scriptlet.\"))." }, { "code": null, "e": 11595, "s": 11423, "text": "In the afterReportInit method, we set a value to the variable \"someVar\" this.setVariableValue(\"someVar\", new String(\"This variable value was modified by the scriptlet.\"))." }, { "code": null, "e": 11798, "s": 11595, "text": "At the end of the class, an extra method called 'hello' has been defined. This is an example of a method that can be added to the Scriptlet that actually returns a value, rather than setting a Variable." }, { "code": null, "e": 12001, "s": 11798, "text": "At the end of the class, an extra method called 'hello' has been defined. This is an example of a method that can be added to the Scriptlet that actually returns a value, rather than setting a Variable." }, { "code": null, "e": 12239, "s": 12001, "text": "Next, we will add the scriptlet class reference in our existing report template (Chapter Report Designs). The revised report template (jasper_report_template.jrxml) are as follows. Save it to C:\\tools\\jasperreports-5.0.1\\test directory −" }, { "code": null, "e": 19346, "s": 12239, "text": "<?xml version = \"1.0\"?>\n<!DOCTYPE jasperReport PUBLIC\n \"//JasperReports//DTD Report Design//EN\"\n \"http://jasperreports.sourceforge.net/dtds/jasperreport.dtd\">\n\n<jasperReport xmlns = \"http://jasperreports.sourceforge.net/jasperreports\"\n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation = \"http://jasperreports.sourceforge.net/jasperreports\n http://jasperreports.sourceforge.net/xsd/jasperreport.xsd\"\n name = \"jasper_report_template\" pageWidth = \"595\"\n pageHeight = \"842\" columnWidth = \"515\"\n leftMargin = \"40\" rightMargin = \"40\" topMargin = \"50\" bottomMargin = \"50\"\n scriptletClass = \"com.tutorialspoint.MyScriptlet\">\n\t\n <style name = \"alternateStyle\" fontName = \"Arial\" forecolor = \"red\">\n \n <conditionalStyle>\n <conditionExpression>\n <![CDATA[new Boolean($V{countNumber}.intValue() % 2 == 0)]]>\n </conditionExpression>\n\t\t\t\n <style forecolor = \"blue\" isBold = \"true\"/>\n </conditionalStyle>\n </style>\n \n <parameter name = \"ReportTitle\" class = \"java.lang.String\"/>\n <parameter name = \"Author\" class = \"java.lang.String\"/>\n\n <queryString>\n <![CDATA[]]>\n </queryString>\n\n <field name = \"country\" class = \"java.lang.String\">\n <fieldDescription>\n <![CDATA[country]]>\n </fieldDescription>\n </field>\n\n <field name = \"name\" class = \"java.lang.String\">\n <fieldDescription>\n <![CDATA[name]]>\n </fieldDescription>\n </field>\n\n <variable name = \"countNumber\" class = \"java.lang.Integer\" \n calculation = \"Count\">\n <variableExpression><\n ![CDATA[Boolean.TRUE]]>\n </variableExpression>\n </variable>\n\n <variable name = \"someVar\" class = \"java.lang.String\">\n <initialValueExpression>\n <![CDATA[\"This is the initial variable value.\"]]>\n </initialValueExpression>\n </variable>\n\n <title>\n <band height = \"100\">\n \n <line>\n <reportElement x = \"0\" y = \"0\" width = \"515\" height = \"1\"/>\n </line>\n \n <textField isBlankWhenNull = \"true\" bookmarkLevel = \"1\">\n <reportElement x = \"0\" y = \"10\" width = \"515\" height = \"30\"/>\n \n <textElement textAlignment = \"Center\">\n <font size = \"22\"/>\n </textElement>\n \n <textFieldExpression class = \"java.lang.String\">\n <![CDATA[$P{ReportTitle}]]>\n </textFieldExpression>\n\t\t\t\t\n <anchorNameExpression>\n <![CDATA[\"Title\"]]>\n </anchorNameExpression>\n </textField>\n \n <textField isBlankWhenNull = \"true\">\n <reportElement x = \"0\" y = \"40\" width = \"515\" height = \"20\"/>\n \n <textElement textAlignment = \"Center\">\n <font size = \"10\"/>\n </textElement>\n \n <textFieldExpression class = \"java.lang.String\">\n <![CDATA[$P{Author}]]>\n </textFieldExpression>\n </textField>\n \n <textField isBlankWhenNull = \"true\">\n <reportElement x = \"0\" y = \"50\" width = \"515\" \n height = \"30\" forecolor = \"#993300\"/>\n \n <textElement textAlignment = \"Center\">\n <font size = \"10\"/>\n </textElement>\n \n <textFieldExpression class = \"java.lang.String\">\n <![CDATA[$V{someVar}]]>\n </textFieldExpression>\n\t\t\t\t\n </textField>\n\n </band>\n </title>\n\n <columnHeader>\n <band height = \"23\">\n \n <staticText>\n <reportElement mode = \"Opaque\" x = \"0\" y = \"3\" \n width = \"535\" height = \"15\"\n backcolor = \"#70A9A9\" />\n \n <box>\n <bottomPen lineWidth = \"1.0\" lineColor = \"#CCCCCC\" />\n </box>\n\t\t\t\t\n <textElement />\n\t\t\t\t\n <text>\n <![CDATA[]]>\n </text>\n\t\t\t\t\n </staticText>\n \n <staticText>\n <reportElement x = \"414\" y = \"3\" width = \"121\" height = \"15\" />\n \n <textElement textAlignment = \"Center\" verticalAlignment = \"Middle\">\n <font isBold = \"true\" />\n </textElement>\n \n <text><![CDATA[Country]]></text>\n </staticText>\n \n <staticText>\n <reportElement x = \"0\" y = \"3\" width = \"136\" height = \"15\" />\n \n <textElement textAlignment = \"Center\" verticalAlignment = \"Middle\">\n <font isBold = \"true\" />\n </textElement>\n\t\t\t\t\n <text><![CDATA[Name]]></text>\n </staticText>\n \n </band>\n </columnHeader>\n\n <detail>\n <band height = \"16\">\n \n <staticText>\n <reportElement mode = \"Opaque\" x = \"0\" y = \"0\" \n width = \"535\"\theight = \"14\"\n backcolor = \"#E5ECF9\" />\n \n <box>\n <bottomPen lineWidth = \"0.25\" lineColor = \"#CCCCCC\" />\n </box>\n\t\t\t\t\n <textElement />\n\t\t\t\t\n <text>\n <![CDATA[]]>\n </text>\n </staticText>\n \n <textField>\n <reportElement style = \"alternateStyle\" x=\"414\" y = \"0\" \n width = \"121\" height = \"15\" />\n \n <textElement textAlignment = \"Center\" verticalAlignment = \"Middle\">\n <font size = \"9\" />\n </textElement>\n \n\t\t\t\t\n <textFieldExpression class = \"java.lang.String\">\n <![CDATA[$F{country}]]>\n </textFieldExpression>\n </textField>\n \n <textField>\n <reportElement x = \"0\" y = \"0\" width = \"136\" height = \"15\" />\n <textElement textAlignment = \"Center\" verticalAlignment = \"Middle\" />\n \n <textFieldExpression class = \"java.lang.String\">\n <![CDATA[$F{name}]]>\n </textFieldExpression>\n </textField>\n \n </band>\n </detail>\n \n <summary>\n <band height = \"45\">\n \n <textField isStretchWithOverflow = \"true\">\n <reportElement x = \"0\" y = \"10\" width = \"515\" height = \"15\" />\n <textElement textAlignment = \"Center\"/>\n \n <textFieldExpression class = \"java.lang.String\">\n <![CDATA[\"There are \" + String.valueOf($V{REPORT_COUNT}) +\n \" records on this report.\"]]>\n </textFieldExpression>\n </textField>\n \n <textField isStretchWithOverflow = \"true\">\n <reportElement positionType = \"Float\" x = \"0\" y = \"30\" width = \"515\"\n height = \"15\" forecolor = \"# 993300\" />\n \n <textElement textAlignment = \"Center\">\n <font size = \"10\"/>\n </textElement>\n \n <textFieldExpression class = \"java.lang.String\">\n <![CDATA[$P{REPORT_SCRIPTLET}.hello()]]>\n </textFieldExpression>\n \n </textField>\n \n </band>\n </summary>\n\t\n</jasperReport>" }, { "code": null, "e": 19406, "s": 19346, "text": "The details of the revised report template is given below −" }, { "code": null, "e": 19507, "s": 19406, "text": "We have referenced the MyScriptlet class in the attribute scriptletClass of <jasperReport> element. " }, { "code": null, "e": 19608, "s": 19507, "text": "We have referenced the MyScriptlet class in the attribute scriptletClass of <jasperReport> element. " }, { "code": null, "e": 20055, "s": 19608, "text": "Scriptlets can only access, but not modify the report fields and parameters. However, scriptlets can modify report variable values. This can be accomplished by calling the setVariableValue() method. This method is defined in JRAbstractScriptlet class, which is always the parent class of any scriptlet. Here, we have defined a variable someVar, which will be modified by the MyScriptlet to have the value This value was modified by the scriptlet." }, { "code": null, "e": 20502, "s": 20055, "text": "Scriptlets can only access, but not modify the report fields and parameters. However, scriptlets can modify report variable values. This can be accomplished by calling the setVariableValue() method. This method is defined in JRAbstractScriptlet class, which is always the parent class of any scriptlet. Here, we have defined a variable someVar, which will be modified by the MyScriptlet to have the value This value was modified by the scriptlet." }, { "code": null, "e": 20692, "s": 20502, "text": "The above report template has a method call in the Summary band that illustrates how to write new methods (in scriptlets) and use them in the report template. ($P{REPORT_SCRIPTLET}.hello())" }, { "code": null, "e": 20882, "s": 20692, "text": "The above report template has a method call in the Summary band that illustrates how to write new methods (in scriptlets) and use them in the report template. ($P{REPORT_SCRIPTLET}.hello())" }, { "code": null, "e": 21059, "s": 20882, "text": "The java codes for report filling remain unchanged. The contents of the file C:\\tools\\jasperreports-5.0.1\\test\\src\\com\\tutorialspoint\\JasperReportFill.java are as given below −" }, { "code": null, "e": 22201, "s": 21059, "text": "package com.tutorialspoint;\n\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.Map;\n\nimport net.sf.jasperreports.engine.JRException;\nimport net.sf.jasperreports.engine.JasperFillManager;\nimport net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;\n\npublic class JasperReportFill {\n @SuppressWarnings(\"unchecked\")\n public static void main(String[] args) {\n String sourceFileName = \n \"C://tools/jasperreports-5.0.1/test/jasper_report_template.jasper\";\n\n DataBeanList DataBeanList = new DataBeanList();\n ArrayList<DataBean> dataList = DataBeanList.getDataBeanList();\n\n JRBeanCollectionDataSource beanColDataSource = new \n JRBeanCollectionDataSource(dataList);\n\n Map parameters = new HashMap();\n /**\n * Passing ReportTitle and Author as parameters\n */\n parameters.put(\"ReportTitle\", \"List of Contacts\");\n parameters.put(\"Author\", \"Prepared By Manisha\");\n\n try {\n JasperFillManager.fillReportToFile(\n sourceFileName, parameters, beanColDataSource);\n } catch (JRException e) {\n e.printStackTrace();\n }\n }\n}" }, { "code": null, "e": 22323, "s": 22201, "text": "The contents of the POJO file C:\\tools\\jasperreports-5.0.1\\test\\src\\com\\tutorialspoint\\DataBean.java are as given below −" }, { "code": null, "e": 22691, "s": 22323, "text": "package com.tutorialspoint;\n\npublic class DataBean {\n private String name;\n private String country;\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public String getCountry() {\n return country;\n }\n\n public void setCountry(String country) {\n this.country = country;\n }\n}" }, { "code": null, "e": 22812, "s": 22691, "text": "The contents of the file C:\\tools\\jasperreports-5.0.1\\test\\src\\com\\tutorialspoint\\DataBeanList.java are as given below −" }, { "code": null, "e": 23576, "s": 22812, "text": "package com.tutorialspoint;\n\nimport java.util.ArrayList;\n\npublic class DataBeanList {\n public ArrayList<DataBean> getDataBeanList() {\n ArrayList<DataBean> dataBeanList = new ArrayList<DataBean>();\n\n dataBeanList.add(produce(\"Manisha\", \"India\"));\n dataBeanList.add(produce(\"Dennis Ritchie\", \"USA\"));\n dataBeanList.add(produce(\"V.Anand\", \"India\"));\n dataBeanList.add(produce(\"Shrinath\", \"California\"));\n\n return dataBeanList;\n }\n\n /**\n * This method returns a DataBean object,\n * with name and country set in it.\n */\n private DataBean produce(String name, String country) {\n DataBean dataBean = new DataBean();\n dataBean.setName(name);\n dataBean.setCountry(country);\n \n return dataBean;\n }\n}" }, { "code": null, "e": 23769, "s": 23576, "text": "We will compile and execute the above file using our regular ANT build process. The contents of the file build.xml (saved under directory C:\\tools\\jasperreports-5.0.1\\test) are as given below." }, { "code": null, "e": 23910, "s": 23769, "text": "The import file - baseBuild.xml is picked up from the chapter Environment Setup and should be placed in the same directory as the build.xml." }, { "code": null, "e": 24986, "s": 23910, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<project name = \"JasperReportTest\" default = \"viewFillReport\" basedir = \".\">\n <import file = \"baseBuild.xml\" />\n \n <target name = \"viewFillReport\" depends = \"compile,compilereportdesing,run\"\n description = \"Launches the report viewer to preview \n the report stored in the .JRprint file.\">\n \n <java classname = \"net.sf.jasperreports.view.JasperViewer\" fork = \"true\">\n <arg value = \"-F${file.name}.JRprint\" />\n <classpath refid = \"classpath\" />\n </java>\n </target>\n \n <target name = \"compilereportdesing\" description = \"Compiles the JXML file and\n produces the .jasper file.\">\n \n <taskdef name = \"jrc\" classname = \"net.sf.jasperreports.ant.JRAntCompileTask\">\n <classpath refid = \"classpath\" />\n </taskdef>\n \n <jrc destdir = \".\">\n <src>\n <fileset dir = \".\">\n <include name = \"*.jrxml\" />\n </fileset>\n </src>\n <classpath refid = \"classpath\" />\n </jrc>\n \n </target>\n\n</project>" }, { "code": null, "e": 25200, "s": 24986, "text": "Next, let's open command line window and go to the directory where build.xml is placed. Finally, execute the command ant -Dmain-class=com.tutorialspoint.JasperReportFill (viewFullReport is the default target) as −" }, { "code": null, "e": 26887, "s": 25200, "text": "C:\\tools\\jasperreports-5.0.1\\test>ant -Dmain-class=com.tutorialspoint.JasperReportFill\nBuildfile: C:\\tools\\jasperreports-5.0.1\\test\\build.xml\n\nclean-sample:\n [delete] Deleting directory C:\\tools\\jasperreports-5.0.1\\test\\classes\n [delete] Deleting: C:\\tools\\jasperreports-5.0.1\\test\\jasper_report_template.jasper\n [delete] Deleting: C:\\tools\\jasperreports-5.0.1\\test\\jasper_report_template.jrprint\n\ncompile:\n [mkdir] Created dir: C:\\tools\\jasperreports-5.0.1\\test\\classes\n [javac] C:\\tools\\jasperreports-5.0.1\\test\\baseBuild.xml:28:\n warning: 'includeantruntime' was not set, defaulting to bu\n [javac] Compiling 4 source files to C:\\tools\\jasperreports-5.0.1\\test\\classes\n\ncompilereportdesing:\n [jrc] Compiling 1 report design files.\n [jrc] log4j:WARN No appenders could be found for logger\n (net.sf.jasperreports.engine.xml.JRXmlDigesterFactory).\n [jrc] log4j:WARN Please initialize the log4j system properly.\n [jrc] log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.\n [jrc] File : C:\\tools\\jasperreports-5.0.1\\test\\jasper_report_template.jrxml ... OK.\n\nrun:\n [echo] Runnin class : com.tutorialspoint.JasperReportFill\n [java] log4j:WARN No appenders could be found for logger\n (net.sf.jasperreports.extensions.ExtensionsEnvironment).\n [java] log4j:WARN Please initialize the log4j system properly.\n [java] call afterReportInit()\n [java] call afterReportInit()\n\nviewFillReport:\n [java] log4j:WARN No appenders could be found for logger\n (net.sf.jasperreports.extensions.ExtensionsEnvironment).\n [java] log4j:WARN Please initialize the log4j system properly.\n\nBUILD SUCCESSFUL\nTotal time: 18 minutes 49 seconds\n" }, { "code": null, "e": 26989, "s": 26887, "text": "As a result of above compilation, a JasperViewer window opens up as shown in the screen given below −" }, { "code": null, "e": 27053, "s": 26989, "text": "Here we see two messages are displayed from MyScriptlet class −" }, { "code": null, "e": 27122, "s": 27053, "text": "In title section − This variable value was modified by the scriptlet" }, { "code": null, "e": 27180, "s": 27122, "text": "At the bottom − Hello! I'm the report's scriptlet object." }, { "code": null, "e": 27187, "s": 27180, "text": " Print" }, { "code": null, "e": 27198, "s": 27187, "text": " Add Notes" } ]
Count of distinct permutations of length N having Bitwise AND as zero - GeeksforGeeks
19 Nov, 2021 Given an integer N., The task is to find the number of distinct permutations of length N, such that the bitwise AND value of each permutation is zero. Examples: Input: N = 1Output: 0 Explanation: There is only one permutation of length 1: [1] and it’s bitwise AND is 1 . Input: N = 3 Output: 6 Explanation: Permutations of length N having bitwise AND as 0 are : [1, 2, 3], [1, 3, 2], [2, 1, 3], [3, 1, 2], [2, 3, 1], [3, 2, 1] . Approach: The task can be solved using observations. One can observe that if a number is a power of 2, let’s say ‘x‘, bitwise AND of x & (x-1) is always zero. All permutations of length greater than 1, have bitwise AND as zero, and for N = 1, the count of distinct permutations is 0. Therefore, the required count is equal to the number of possible permutations i.e N! Below is the implementation of the above approach – C++ Java Python3 C# Javascript // C++ program for the// above approach#include <bits/stdc++.h>using namespace std; // Function to calculate factorial// of a numberlong long int fact(long long N){ long long int ans = 1; for (int i = 2; i <= N; i++) ans *= i; return ans;} // Function to find distinct no of// permutations having bitwise and (&)// equals to 0long long permutation_count(long long n){ // corner case if (n == 1) return 0; return fact(n);} // Driver codeint main(){ long long N = 3; cout << permutation_count(N); return 0;} // Java program for the above approachimport java.io.*; class GFG{ // Function to calculate factorial// of a numberstatic long fact( long N){ long ans = 1; for (int i = 2; i <= N; i++) ans *= i; return ans;} // Function to find distinct no of// permutations having bitwise and (&)// equals to 0static long permutation_count(long n){ // corner case if (n == 1) return 0; return fact(n);} public static void main (String[] args) { long N = 3; System.out.println(permutation_count(N)); }} // This code is contributed by Potta Lokesh # Python 3 program for the# above approach # Function to calculate factorial# of a numberdef fact(N): ans = 1 for i in range(2, N + 1): ans *= i return ans # Function to find distinct no of# permutations having bitwise and (&)# equals to 0def permutation_count(n): # corner case if (n == 1): return 0 return fact(n) # Driver codeif __name__ == "__main__": N = 3 print(permutation_count(N)) # This code is contributed by ukasp. // C# program for the// above approachusing System; class GFG{// Function to calculate factorial// of a numberstatic long fact(long N){ long ans = 1; for (int i = 2; i <= N; i++) ans *= i; return ans;} // Function to find distinct no of// permutations having bitwise and (&)// equals to 0static long permutation_count(long n){ // corner case if (n == 1) return 0; return fact(n);} // Driver codepublic static void Main(){ long N = 3; Console.Write(permutation_count(N));}} // This code is contributed by Samim Hossain Mondal. <script>// Javascript program for the// above approach // Function to calculate factorial// of a numberfunction fact(N){ let ans = 1; for (let i = 2; i <= N; i++) ans *= i; return ans;} // Function to find distinct no of// permutations having bitwise and (&)// equals to 0function permutation_count(n){ // corner case if (n == 1) return 0; return fact(n);} // Driver codelet N = 3;document.write(permutation_count(N)); // This code is contributed by Samim Hossain Mondal.</script> 6 Time complexity: O(N) Auxiliary Space: O(1) ukasp lokeshpotta20 samim2000 Bitwise-AND permutation Bit Magic Combinatorial Mathematical Mathematical Bit Magic permutation Combinatorial Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Set, Clear and Toggle a given bit of a number in C Check whether K-th bit is set or not Write an Efficient Method to Check if a Number is Multiple of 3 Reverse actual bits of the given number Program to find parity Write a program to print all permutations of a given string Permutation and Combination in Python itertools.combinations() module in Python to print all possible combinations Factorial of a large number Program to calculate value of nCr
[ { "code": null, "e": 24597, "s": 24569, "text": "\n19 Nov, 2021" }, { "code": null, "e": 24749, "s": 24597, "text": "Given an integer N., The task is to find the number of distinct permutations of length N, such that the bitwise AND value of each permutation is zero. " }, { "code": null, "e": 24759, "s": 24749, "text": "Examples:" }, { "code": null, "e": 24871, "s": 24759, "text": "Input: N = 1Output: 0 Explanation: There is only one permutation of length 1: [1] and it’s bitwise AND is 1 . " }, { "code": null, "e": 25030, "s": 24871, "text": "Input: N = 3 Output: 6 Explanation: Permutations of length N having bitwise AND as 0 are : [1, 2, 3], [1, 3, 2], [2, 1, 3], [3, 1, 2], [2, 3, 1], [3, 2, 1] . " }, { "code": null, "e": 25400, "s": 25030, "text": "Approach: The task can be solved using observations. One can observe that if a number is a power of 2, let’s say ‘x‘, bitwise AND of x & (x-1) is always zero. All permutations of length greater than 1, have bitwise AND as zero, and for N = 1, the count of distinct permutations is 0. Therefore, the required count is equal to the number of possible permutations i.e N!" }, { "code": null, "e": 25453, "s": 25400, "text": "Below is the implementation of the above approach – " }, { "code": null, "e": 25457, "s": 25453, "text": "C++" }, { "code": null, "e": 25462, "s": 25457, "text": "Java" }, { "code": null, "e": 25470, "s": 25462, "text": "Python3" }, { "code": null, "e": 25473, "s": 25470, "text": "C#" }, { "code": null, "e": 25484, "s": 25473, "text": "Javascript" }, { "code": "// C++ program for the// above approach#include <bits/stdc++.h>using namespace std; // Function to calculate factorial// of a numberlong long int fact(long long N){ long long int ans = 1; for (int i = 2; i <= N; i++) ans *= i; return ans;} // Function to find distinct no of// permutations having bitwise and (&)// equals to 0long long permutation_count(long long n){ // corner case if (n == 1) return 0; return fact(n);} // Driver codeint main(){ long long N = 3; cout << permutation_count(N); return 0;}", "e": 26034, "s": 25484, "text": null }, { "code": "// Java program for the above approachimport java.io.*; class GFG{ // Function to calculate factorial// of a numberstatic long fact( long N){ long ans = 1; for (int i = 2; i <= N; i++) ans *= i; return ans;} // Function to find distinct no of// permutations having bitwise and (&)// equals to 0static long permutation_count(long n){ // corner case if (n == 1) return 0; return fact(n);} public static void main (String[] args) { long N = 3; System.out.println(permutation_count(N)); }} // This code is contributed by Potta Lokesh", "e": 26624, "s": 26034, "text": null }, { "code": "# Python 3 program for the# above approach # Function to calculate factorial# of a numberdef fact(N): ans = 1 for i in range(2, N + 1): ans *= i return ans # Function to find distinct no of# permutations having bitwise and (&)# equals to 0def permutation_count(n): # corner case if (n == 1): return 0 return fact(n) # Driver codeif __name__ == \"__main__\": N = 3 print(permutation_count(N)) # This code is contributed by ukasp.", "e": 27099, "s": 26624, "text": null }, { "code": "// C# program for the// above approachusing System; class GFG{// Function to calculate factorial// of a numberstatic long fact(long N){ long ans = 1; for (int i = 2; i <= N; i++) ans *= i; return ans;} // Function to find distinct no of// permutations having bitwise and (&)// equals to 0static long permutation_count(long n){ // corner case if (n == 1) return 0; return fact(n);} // Driver codepublic static void Main(){ long N = 3; Console.Write(permutation_count(N));}} // This code is contributed by Samim Hossain Mondal.", "e": 27666, "s": 27099, "text": null }, { "code": "<script>// Javascript program for the// above approach // Function to calculate factorial// of a numberfunction fact(N){ let ans = 1; for (let i = 2; i <= N; i++) ans *= i; return ans;} // Function to find distinct no of// permutations having bitwise and (&)// equals to 0function permutation_count(n){ // corner case if (n == 1) return 0; return fact(n);} // Driver codelet N = 3;document.write(permutation_count(N)); // This code is contributed by Samim Hossain Mondal.</script>", "e": 28181, "s": 27666, "text": null }, { "code": null, "e": 28183, "s": 28181, "text": "6" }, { "code": null, "e": 28227, "s": 28183, "text": "Time complexity: O(N) Auxiliary Space: O(1)" }, { "code": null, "e": 28233, "s": 28227, "text": "ukasp" }, { "code": null, "e": 28247, "s": 28233, "text": "lokeshpotta20" }, { "code": null, "e": 28257, "s": 28247, "text": "samim2000" }, { "code": null, "e": 28269, "s": 28257, "text": "Bitwise-AND" }, { "code": null, "e": 28281, "s": 28269, "text": "permutation" }, { "code": null, "e": 28291, "s": 28281, "text": "Bit Magic" }, { "code": null, "e": 28305, "s": 28291, "text": "Combinatorial" }, { "code": null, "e": 28318, "s": 28305, "text": "Mathematical" }, { "code": null, "e": 28331, "s": 28318, "text": "Mathematical" }, { "code": null, "e": 28341, "s": 28331, "text": "Bit Magic" }, { "code": null, "e": 28353, "s": 28341, "text": "permutation" }, { "code": null, "e": 28367, "s": 28353, "text": "Combinatorial" }, { "code": null, "e": 28465, "s": 28367, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28474, "s": 28465, "text": "Comments" }, { "code": null, "e": 28487, "s": 28474, "text": "Old Comments" }, { "code": null, "e": 28538, "s": 28487, "text": "Set, Clear and Toggle a given bit of a number in C" }, { "code": null, "e": 28575, "s": 28538, "text": "Check whether K-th bit is set or not" }, { "code": null, "e": 28639, "s": 28575, "text": "Write an Efficient Method to Check if a Number is Multiple of 3" }, { "code": null, "e": 28679, "s": 28639, "text": "Reverse actual bits of the given number" }, { "code": null, "e": 28702, "s": 28679, "text": "Program to find parity" }, { "code": null, "e": 28762, "s": 28702, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 28800, "s": 28762, "text": "Permutation and Combination in Python" }, { "code": null, "e": 28877, "s": 28800, "text": "itertools.combinations() module in Python to print all possible combinations" }, { "code": null, "e": 28905, "s": 28877, "text": "Factorial of a large number" } ]
DIV() Function in MySQL - GeeksforGeeks
10 Dec, 2020 DIV() function :This function in MySQL is used to return a quotient (integer) value when integer division is done. For example, when 7 is divided by 3, then 2 will be returned. Syntax : SELECT x DIV y; Parameter :This method accepts two parameters as given below as follows. x – Specified dividend which will be divided by y. y – Specified divisor which will divide x. Returns :It returns a quotient (integer) value when integer division is done. Example-1 :Getting quotient 2 when 7 is divided by 3. SELECT 7 DIV 3; Output : 2 Example-2 :Getting quotient 1 when 4 is divided by 4. SELECT 4 DIV 4; Output : 1 Example-3 :Getting quotient 0 when 2 is divided by 4. Here dividend is less than divisor that is why 0 is returned. SELECT 2 DIV 4; Output : 0 Application :This function is used to return a quotient (integer) value when integer division is done. DBMS-SQL mysql SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Update Multiple Columns in Single Update Statement in SQL? How to Create a Table With Multiple Foreign Keys in SQL? What is Temporary Table in SQL? SQL Query to Convert VARCHAR to INT SQL | Subquery SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter SQL using Python How to Select Data Between Two Dates and Times in SQL Server? How to Write a SQL Query For a Specific Date Range and Date Time? SQL Query to Compare Two Dates
[ { "code": null, "e": 24366, "s": 24338, "text": "\n10 Dec, 2020" }, { "code": null, "e": 24543, "s": 24366, "text": "DIV() function :This function in MySQL is used to return a quotient (integer) value when integer division is done. For example, when 7 is divided by 3, then 2 will be returned." }, { "code": null, "e": 24552, "s": 24543, "text": "Syntax :" }, { "code": null, "e": 24568, "s": 24552, "text": "SELECT x DIV y;" }, { "code": null, "e": 24641, "s": 24568, "text": "Parameter :This method accepts two parameters as given below as follows." }, { "code": null, "e": 24692, "s": 24641, "text": "x – Specified dividend which will be divided by y." }, { "code": null, "e": 24735, "s": 24692, "text": "y – Specified divisor which will divide x." }, { "code": null, "e": 24813, "s": 24735, "text": "Returns :It returns a quotient (integer) value when integer division is done." }, { "code": null, "e": 24867, "s": 24813, "text": "Example-1 :Getting quotient 2 when 7 is divided by 3." }, { "code": null, "e": 24883, "s": 24867, "text": "SELECT 7 DIV 3;" }, { "code": null, "e": 24892, "s": 24883, "text": "Output :" }, { "code": null, "e": 24894, "s": 24892, "text": "2" }, { "code": null, "e": 24948, "s": 24894, "text": "Example-2 :Getting quotient 1 when 4 is divided by 4." }, { "code": null, "e": 24964, "s": 24948, "text": "SELECT 4 DIV 4;" }, { "code": null, "e": 24973, "s": 24964, "text": "Output :" }, { "code": null, "e": 24975, "s": 24973, "text": "1" }, { "code": null, "e": 25091, "s": 24975, "text": "Example-3 :Getting quotient 0 when 2 is divided by 4. Here dividend is less than divisor that is why 0 is returned." }, { "code": null, "e": 25107, "s": 25091, "text": "SELECT 2 DIV 4;" }, { "code": null, "e": 25116, "s": 25107, "text": "Output :" }, { "code": null, "e": 25118, "s": 25116, "text": "0" }, { "code": null, "e": 25221, "s": 25118, "text": "Application :This function is used to return a quotient (integer) value when integer division is done." }, { "code": null, "e": 25230, "s": 25221, "text": "DBMS-SQL" }, { "code": null, "e": 25236, "s": 25230, "text": "mysql" }, { "code": null, "e": 25240, "s": 25236, "text": "SQL" }, { "code": null, "e": 25244, "s": 25240, "text": "SQL" }, { "code": null, "e": 25342, "s": 25244, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25408, "s": 25342, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 25465, "s": 25408, "text": "How to Create a Table With Multiple Foreign Keys in SQL?" }, { "code": null, "e": 25497, "s": 25465, "text": "What is Temporary Table in SQL?" }, { "code": null, "e": 25533, "s": 25497, "text": "SQL Query to Convert VARCHAR to INT" }, { "code": null, "e": 25548, "s": 25533, "text": "SQL | Subquery" }, { "code": null, "e": 25626, "s": 25548, "text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter" }, { "code": null, "e": 25643, "s": 25626, "text": "SQL using Python" }, { "code": null, "e": 25705, "s": 25643, "text": "How to Select Data Between Two Dates and Times in SQL Server?" }, { "code": null, "e": 25771, "s": 25705, "text": "How to Write a SQL Query For a Specific Date Range and Date Time?" } ]
GATE | GATE CS 2018 | Question 30 - GeeksforGeeks
25 Feb, 2018 Consider a system with 3 processes that share 4 instances of the same resource type. Each process can request a maximum of K instances. Resource instances can be requested and released only one at a time. The largest value of K that will always avoid deadlock is _______ . Note – This was Numerical Type question. (A) 1(B) 2(C) 3(D) 4Answer: (B)Explanation: Given,Number of processes (P) = 3Number of resources (R) = 4 Since deadlock-free condition is: R ≥ P(N − 1) + 1 Where R is total number of resources,P is the number of processes, andN is the max need for each resource. 4 ≥ 3(N − 1) + 1 3 ≥ 3(N − 1) 1 ≥ (N − 1) N ≤ 2 Therefore, the largest value of K that will always avoid deadlock is 2.Option (B) is correct.Quiz of this Question GATE CS 2018 GATE-GATE CS 2018 GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. GATE | Gate IT 2007 | Question 25 GATE | GATE-CS-2000 | Question 41 GATE | GATE-CS-2001 | Question 39 GATE | GATE-CS-2005 | Question 6 GATE | GATE MOCK 2017 | Question 21 GATE | GATE-CS-2006 | Question 47 GATE | GATE MOCK 2017 | Question 24 GATE | Gate IT 2008 | Question 43 GATE | GATE-CS-2009 | Question 38 GATE | GATE-CS-2003 | Question 90
[ { "code": null, "e": 25847, "s": 25819, "text": "\n25 Feb, 2018" }, { "code": null, "e": 26120, "s": 25847, "text": "Consider a system with 3 processes that share 4 instances of the same resource type. Each process can request a maximum of K instances. Resource instances can be requested and released only one at a time. The largest value of K that will always avoid deadlock is _______ ." }, { "code": null, "e": 26161, "s": 26120, "text": "Note – This was Numerical Type question." }, { "code": null, "e": 26205, "s": 26161, "text": "(A) 1(B) 2(C) 3(D) 4Answer: (B)Explanation:" }, { "code": null, "e": 26266, "s": 26205, "text": "Given,Number of processes (P) = 3Number of resources (R) = 4" }, { "code": null, "e": 26300, "s": 26266, "text": "Since deadlock-free condition is:" }, { "code": null, "e": 26318, "s": 26300, "text": "R ≥ P(N − 1) + 1\n" }, { "code": null, "e": 26425, "s": 26318, "text": "Where R is total number of resources,P is the number of processes, andN is the max need for each resource." }, { "code": null, "e": 26474, "s": 26425, "text": "4 ≥ 3(N − 1) + 1\n3 ≥ 3(N − 1)\n1 ≥ (N − 1)\nN ≤ 2\n" }, { "code": null, "e": 26589, "s": 26474, "text": "Therefore, the largest value of K that will always avoid deadlock is 2.Option (B) is correct.Quiz of this Question" }, { "code": null, "e": 26602, "s": 26589, "text": "GATE CS 2018" }, { "code": null, "e": 26620, "s": 26602, "text": "GATE-GATE CS 2018" }, { "code": null, "e": 26625, "s": 26620, "text": "GATE" }, { "code": null, "e": 26723, "s": 26625, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26757, "s": 26723, "text": "GATE | Gate IT 2007 | Question 25" }, { "code": null, "e": 26791, "s": 26757, "text": "GATE | GATE-CS-2000 | Question 41" }, { "code": null, "e": 26825, "s": 26791, "text": "GATE | GATE-CS-2001 | Question 39" }, { "code": null, "e": 26858, "s": 26825, "text": "GATE | GATE-CS-2005 | Question 6" }, { "code": null, "e": 26894, "s": 26858, "text": "GATE | GATE MOCK 2017 | Question 21" }, { "code": null, "e": 26928, "s": 26894, "text": "GATE | GATE-CS-2006 | Question 47" }, { "code": null, "e": 26964, "s": 26928, "text": "GATE | GATE MOCK 2017 | Question 24" }, { "code": null, "e": 26998, "s": 26964, "text": "GATE | Gate IT 2008 | Question 43" }, { "code": null, "e": 27032, "s": 26998, "text": "GATE | GATE-CS-2009 | Question 38" } ]
Faulty Keyboard | Practice | GeeksforGeeks
Geek has a unique keyboard containing only the numpad keys. ie - 1,2,3,4,5,6,7,8,9,0. But the keyboard is damaged and can only process M keys. Geek is supposed to use the keyboard to type as many natural numbers as possible starting from 1. What will be the greatest natural number he will type? Example 1: Input: M = 5 Output: 5 Explaination: Geek can only press 5 keys. He will type 1,2,3,4,5. The greatest number is 5. Example 2: Input: M = 15 Output: 12 Explaination: 1 key each from 1 to 9. 2 keys each from 10 to 12. Total keys pressed = 15. Your Task: You do not need to read input or print anything. Your task is to complete the function maxNatural() which takes M as input parameter and returns the maximum natural number possible to get after pressing M keys. Expected Time Complexity: O(logN) Expected Auxiliary Space: O(1) Constraints: 1 ≤ M ≤ 38890 +1 amanpandey30072 months ago int maxNatural(int M) { if(M<=9) return M; M-=9; if(M<=180) { M=M/2; return 9+M; } M-=180; if(M<=2700) { M=M/3; return 99+M; } M-=2700; if(M<=36000) { M=M/4; return 999+M; } M-=36000; if(M<=38890) { M=M/5; return 9999+M; } return 0; } -2 Vineet Kumar5 years ago Vineet Kumar java implementation http://code.geeksforgeeks.o...works fine. let me know if it can be optimised further 0 LALIT6 years ago LALIT easy 0 Arpit Varshneya6 years ago Arpit Varshneya Java Implementationhttp://ideone.com/OEOhg1 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": 536, "s": 238, "text": "Geek has a unique keyboard containing only the numpad keys. ie - 1,2,3,4,5,6,7,8,9,0. But the keyboard is damaged and can only process M keys. Geek is supposed to use the keyboard to type as many natural numbers as possible starting from 1. What will be the greatest natural number he will type? " }, { "code": null, "e": 548, "s": 536, "text": "\nExample 1:" }, { "code": null, "e": 665, "s": 548, "text": "Input: \nM = 5\nOutput: 5\nExplaination: \nGeek can only press 5 keys. He will type\n1,2,3,4,5. The greatest number is 5." }, { "code": null, "e": 677, "s": 665, "text": "\nExample 2:" }, { "code": null, "e": 795, "s": 677, "text": "Input: \nM = 15\nOutput: 12\nExplaination: \n1 key each from 1 to 9. \n2 keys each from 10 to 12.\nTotal keys pressed = 15." }, { "code": null, "e": 1018, "s": 795, "text": "\nYour Task:\nYou do not need to read input or print anything. Your task is to complete the function maxNatural() which takes M as input parameter and returns the maximum natural number possible to get after pressing M keys." }, { "code": null, "e": 1084, "s": 1018, "text": "\nExpected Time Complexity: O(logN)\nExpected Auxiliary Space: O(1)" }, { "code": null, "e": 1112, "s": 1084, "text": "\nConstraints:\n1 ≤ M ≤ 38890" }, { "code": null, "e": 1115, "s": 1112, "text": "+1" }, { "code": null, "e": 1142, "s": 1115, "text": "amanpandey30072 months ago" }, { "code": null, "e": 1580, "s": 1142, "text": "int maxNatural(int M) { if(M<=9) return M; M-=9; if(M<=180) { M=M/2; return 9+M; } M-=180; if(M<=2700) { M=M/3; return 99+M; } M-=2700; if(M<=36000) { M=M/4; return 999+M; } M-=36000; if(M<=38890) { M=M/5; return 9999+M; } return 0; }" }, { "code": null, "e": 1583, "s": 1580, "text": "-2" }, { "code": null, "e": 1607, "s": 1583, "text": "Vineet Kumar5 years ago" }, { "code": null, "e": 1620, "s": 1607, "text": "Vineet Kumar" }, { "code": null, "e": 1725, "s": 1620, "text": "java implementation http://code.geeksforgeeks.o...works fine. let me know if it can be optimised further" }, { "code": null, "e": 1727, "s": 1725, "text": "0" }, { "code": null, "e": 1744, "s": 1727, "text": "LALIT6 years ago" }, { "code": null, "e": 1750, "s": 1744, "text": "LALIT" }, { "code": null, "e": 1755, "s": 1750, "text": "easy" }, { "code": null, "e": 1757, "s": 1755, "text": "0" }, { "code": null, "e": 1784, "s": 1757, "text": "Arpit Varshneya6 years ago" }, { "code": null, "e": 1800, "s": 1784, "text": "Arpit Varshneya" }, { "code": null, "e": 1844, "s": 1800, "text": "Java Implementationhttp://ideone.com/OEOhg1" }, { "code": null, "e": 1990, "s": 1844, "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": 2026, "s": 1990, "text": " Login to access your submissions. " }, { "code": null, "e": 2036, "s": 2026, "text": "\nProblem\n" }, { "code": null, "e": 2046, "s": 2036, "text": "\nContest\n" }, { "code": null, "e": 2109, "s": 2046, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 2257, "s": 2109, "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": 2465, "s": 2257, "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": 2571, "s": 2465, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
How do I check if raw input is integer in Python 3?
There is a method called isdigit() in String class that returns true if all characters in the string are digits and there is at least one character, false otherwise. Even if you input a float, it'll return false. You can call it as follows: >>> x = raw_input() 12345 >>> x.isdigit() True You can also use regexes for the same result. For matching only digits, we can call the re.match(regex, string) using the regex: "^[0-9]+$". For example, >>> x = raw_input() 123abc >>> bool(re.match('^[0-9]+$', x)) False re.match returns an object, to check if it exists or not, we need to convert it to a boolean using bool().
[ { "code": null, "e": 1303, "s": 1062, "text": "There is a method called isdigit() in String class that returns true if all characters in the string are digits and there is at least one character, false otherwise. Even if you input a float, it'll return false. You can call it as follows:" }, { "code": null, "e": 1350, "s": 1303, "text": ">>> x = raw_input()\n12345\n>>> x.isdigit()\nTrue" }, { "code": null, "e": 1504, "s": 1350, "text": "You can also use regexes for the same result. For matching only digits, we can call the re.match(regex, string) using the regex: \"^[0-9]+$\". For example," }, { "code": null, "e": 1571, "s": 1504, "text": ">>> x = raw_input()\n123abc\n>>> bool(re.match('^[0-9]+$', x))\nFalse" }, { "code": null, "e": 1678, "s": 1571, "text": "re.match returns an object, to check if it exists or not, we need to convert it to a boolean using bool()." } ]
Python | sympy.euler() method - GeeksforGeeks
14 Jul, 2019 With the help of sympy.euler() method, we can find the Euler number and Euler polynomial in SymPy. Syntax: euler(n) Parameter:n – It denotes the nth Euler number. Returns: Returns the nth Euler number. Example #1: # import sympy from sympy import * n = 4print("Value of n = {}".format(n)) # Use sympy.euler() method nth_euler = euler(n) print("Value of nth euler number : {}".format(nth_euler)) Output: Value of n = 4 Value of nth euler number : 5 Syntax: euler(n, k) Parameter:n – It denotes the order of the Euler polynomial.k – It denotes the variable in the Euler polynomial. Returns: Returns the expression of the Euler polynomial or its value. Example #2: # import sympy from sympy import * n = 5k = symbols('x')print("Value of n = {} and k = {}".format(n, k)) # Use sympy.euler() method nth_euler_poly = euler(n, k) print("The nth euler polynomial : {}".format(nth_euler_poly)) Output: Value of n = 5 and k = x The nth euler polynomial : x**5 - 5*x**4/2 + 5*x**2/2 - 1/2 Example #3: # import sympy from sympy import * n = 4k = 3print("Value of n = {} and k = {}".format(n, k)) # Use sympy.euler() method nth_euler_poly = euler(n, k) print("The nth euler polynomial value : {}".format(nth_euler_poly)) Output: Value of n = 4 and k = 3 The nth euler polynomial value : 30 SymPy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | Get unique values from a list Python | os.path.join() method Defaultdict in Python Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n14 Jul, 2019" }, { "code": null, "e": 25636, "s": 25537, "text": "With the help of sympy.euler() method, we can find the Euler number and Euler polynomial in SymPy." }, { "code": null, "e": 25653, "s": 25636, "text": "Syntax: euler(n)" }, { "code": null, "e": 25700, "s": 25653, "text": "Parameter:n – It denotes the nth Euler number." }, { "code": null, "e": 25739, "s": 25700, "text": "Returns: Returns the nth Euler number." }, { "code": null, "e": 25751, "s": 25739, "text": "Example #1:" }, { "code": "# import sympy from sympy import * n = 4print(\"Value of n = {}\".format(n)) # Use sympy.euler() method nth_euler = euler(n) print(\"Value of nth euler number : {}\".format(nth_euler)) ", "e": 25943, "s": 25751, "text": null }, { "code": null, "e": 25951, "s": 25943, "text": "Output:" }, { "code": null, "e": 25997, "s": 25951, "text": "Value of n = 4\nValue of nth euler number : 5\n" }, { "code": null, "e": 26017, "s": 25997, "text": "Syntax: euler(n, k)" }, { "code": null, "e": 26129, "s": 26017, "text": "Parameter:n – It denotes the order of the Euler polynomial.k – It denotes the variable in the Euler polynomial." }, { "code": null, "e": 26199, "s": 26129, "text": "Returns: Returns the expression of the Euler polynomial or its value." }, { "code": null, "e": 26211, "s": 26199, "text": "Example #2:" }, { "code": "# import sympy from sympy import * n = 5k = symbols('x')print(\"Value of n = {} and k = {}\".format(n, k)) # Use sympy.euler() method nth_euler_poly = euler(n, k) print(\"The nth euler polynomial : {}\".format(nth_euler_poly)) ", "e": 26445, "s": 26211, "text": null }, { "code": null, "e": 26453, "s": 26445, "text": "Output:" }, { "code": null, "e": 26539, "s": 26453, "text": "Value of n = 5 and k = x\nThe nth euler polynomial : x**5 - 5*x**4/2 + 5*x**2/2 - 1/2\n" }, { "code": null, "e": 26551, "s": 26539, "text": "Example #3:" }, { "code": "# import sympy from sympy import * n = 4k = 3print(\"Value of n = {} and k = {}\".format(n, k)) # Use sympy.euler() method nth_euler_poly = euler(n, k) print(\"The nth euler polynomial value : {}\".format(nth_euler_poly)) ", "e": 26780, "s": 26551, "text": null }, { "code": null, "e": 26788, "s": 26780, "text": "Output:" }, { "code": null, "e": 26850, "s": 26788, "text": "Value of n = 4 and k = 3\nThe nth euler polynomial value : 30\n" }, { "code": null, "e": 26856, "s": 26850, "text": "SymPy" }, { "code": null, "e": 26863, "s": 26856, "text": "Python" }, { "code": null, "e": 26961, "s": 26863, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26993, "s": 26961, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27035, "s": 26993, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27077, "s": 27035, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27133, "s": 27077, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27160, "s": 27133, "text": "Python Classes and Objects" }, { "code": null, "e": 27199, "s": 27160, "text": "Python | Get unique values from a list" }, { "code": null, "e": 27230, "s": 27199, "text": "Python | os.path.join() method" }, { "code": null, "e": 27252, "s": 27230, "text": "Defaultdict in Python" }, { "code": null, "e": 27281, "s": 27252, "text": "Create a directory in Python" } ]
Multimap of pairs in C++ with Examples - GeeksforGeeks
27 Dec, 2021 What is a multimap? In C++, a multimap is an associative container that is used to store elements in a mapped fashion. Internally, a multimap is implemented as a red-black tree. Each element of a multimap is treated as a pair. The first value is referred to as key and the second value is referred to as value. Multimap is quite similar to a map but in the case of a multimap, we can have multiple same keys. Also, we cannot use square brackets ([]) to access the value mapped with a key. Like a map, keys of the multimap are sorted in ascending order by default. Functions associated with multimap: begin(): Returns an iterator to the first element in the multimap end(): Returns an iterator to the theoretical element that follows the last element in the multimap size(): Returns the number of elements in the multimap max_size(): Returns the maximum number of elements that the multimap can hold empty(): Returns whether the multimap is empty insert(key, value): Adds a new element or pair to the multimap erase(iterator position): Removes the element at the position pointed by the iterator erase(const x): Removes the key-value ‘x’ from the multimap clear(): Removes all the elements from the multimap What is a pair? Utility header in C++ provides us pair container. A pair consists of two data elements or objects. The first element is referenced as ‘first’ and the second element as ‘second’ and the order is fixed (first, second). Pair is used to combine together two values that may be different in type. Pair provides a way to store two heterogeneous objects as a single unit. Pair can be assigned, copied, and compared. The array of objects allocated in a map or hash_map is of type ‘pair’ by default in which all the ‘first’ elements are unique keys associated with their ‘second’ value objects. To access the elements, we use variable name followed by dot operator followed by the keyword first or second. How to access a pair? The elements of a pair can be accessed by using the dot (.) operator. Syntax: auto fistElement = myPair.first; auto fistElement = myPair.second; Multimap of pairs A multimap of pairs is a multimap in which either of the key or value is a pair itself. Two pairs are considered to be equal if the corresponding first and second elements of pairs are equal. Now if there is a need to store more than one copy of a pair along with other elements that too in a sorted or particular order, in such cases multiset of pairs comes in handy. Syntax: multimap<pair<dataType1, dataType2>> myMultimap; Here, dataType1 and dataType2 can be similar or dissimilar data types. Example 1: Below is the C++ program to demonstrate the working of a multimap of pairs. C++ // C++ program to demonstrate// the working of a multimap of// pairs.#include <bits/stdc++.h>using namespace std; // Function to print multimap elementsvoid print(multimap<pair<int, int>, bool>& myContainer){ cout << "Key(pair of integers)" << " " << "Value(boolean)\n\n"; for (auto pr : myContainer) { pair<int, int> myPair = pr.first; // pr points to current pair of myContainer cout << '[' << myPair.first << " , " << myPair.second << ']' << " " << pr.second << '\n'; }} // Driver codeint main(){ // Declaring a multimap // Key is of pair<int, int> type // Value is of bool type multimap<pair<int, int>, bool> myContainer; // Creating some pairs to be used // as keys pair<int, int> pair1; pair1 = make_pair(100, 200); pair<int, int> pair2; pair2 = make_pair(200, 300); pair<int, int> pair3; pair3 = make_pair(300, 400); pair<int, int> pair4; pair4 = make_pair(100, 200); // Since each element is a pair on // its own in a multimap. So, we // are inserting a pair // Note that [] operator doesn't working // in case of a multimap myContainer.insert(pair<pair<int, int>, bool>(pair1, true)); myContainer.insert(pair<pair<int, int>, bool>(pair2, false)); myContainer.insert(pair<pair<int, int>, bool>(pair3, true)); myContainer.insert(pair<pair<int, int>, bool>(pair4, false)); // Calling print function print(myContainer); return 0;} Key(pair of integers) Value(boolean) [100, 200] 1[100, 200] 0[200, 300] 0[300, 400] 1 Example 2: Below is the C++ program to demonstrate the working of a multimap of pairs. C++ // C++ program to demonstrate// the working of a multimap of// pairs.#include <bits/stdc++.h>using namespace std; // Function to print multimap elementsvoid print(multimap<pair<string, int>, bool>& myContainer){ cout << "Key(pair of integers)" << " " << "Value(boolean)\n\n"; for (auto pr : myContainer) { pair<string, int> myPair = pr.first; // pr points to current pair of myContainer cout << '[' << myPair.first << " , " << myPair.second << ']' << " " << " " << pr.second << '\n'; }} // Driver codeint main(){ // Declaring a multimap // Key is of pair<int, int> type // Value is of bool type multimap<pair<string, int>, bool> myContainer; // Creating some pairs to be used // as keys pair<string, int> pair1; pair1 = make_pair("GFG", 100); pair<string, int> pair2; pair2 = make_pair("C++", 200); pair<string, int> pair3; pair3 = make_pair("CSS", 300); pair<string, int> pair4; pair4 = make_pair("GFG", 400); // Since each element is a pair on its // own in a multimap. So, we are // inserting a pair // Note that [] operator doesn't working // in case of a multimap myContainer.insert(pair<pair<string, int>, bool>(pair1, true)); myContainer.insert(pair<pair<string, int>, bool>(pair2, false)); myContainer.insert(pair<pair<string, int>, bool>(pair3, true)); myContainer.insert(pair<pair<string, int>, bool>(pair4, false)); // Calling print function print(myContainer); return 0;} Key(pair of integers) Value(boolean) [C++, 200] 0[CSS, 300] 1[GFG, 100] 1[GFG, 400] 0 cpp-multimap cpp-pair STL C++ STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Operator Overloading in C++ Polymorphism in C++ Sorting a vector in C++ Friend class and function in C++ Pair in C++ Standard Template Library (STL) std::string class in C++ Queue in C++ Standard Template Library (STL) Inline Functions in C++ Array of Strings in C++ (5 Different Ways to Create) Convert string to char array in C++
[ { "code": null, "e": 25343, "s": 25315, "text": "\n27 Dec, 2021" }, { "code": null, "e": 25363, "s": 25343, "text": "What is a multimap?" }, { "code": null, "e": 25907, "s": 25363, "text": "In C++, a multimap is an associative container that is used to store elements in a mapped fashion. Internally, a multimap is implemented as a red-black tree. Each element of a multimap is treated as a pair. The first value is referred to as key and the second value is referred to as value. Multimap is quite similar to a map but in the case of a multimap, we can have multiple same keys. Also, we cannot use square brackets ([]) to access the value mapped with a key. Like a map, keys of the multimap are sorted in ascending order by default." }, { "code": null, "e": 25943, "s": 25907, "text": "Functions associated with multimap:" }, { "code": null, "e": 26009, "s": 25943, "text": "begin(): Returns an iterator to the first element in the multimap" }, { "code": null, "e": 26109, "s": 26009, "text": "end(): Returns an iterator to the theoretical element that follows the last element in the multimap" }, { "code": null, "e": 26164, "s": 26109, "text": "size(): Returns the number of elements in the multimap" }, { "code": null, "e": 26242, "s": 26164, "text": "max_size(): Returns the maximum number of elements that the multimap can hold" }, { "code": null, "e": 26289, "s": 26242, "text": "empty(): Returns whether the multimap is empty" }, { "code": null, "e": 26352, "s": 26289, "text": "insert(key, value): Adds a new element or pair to the multimap" }, { "code": null, "e": 26438, "s": 26352, "text": "erase(iterator position): Removes the element at the position pointed by the iterator" }, { "code": null, "e": 26498, "s": 26438, "text": "erase(const x): Removes the key-value ‘x’ from the multimap" }, { "code": null, "e": 26550, "s": 26498, "text": "clear(): Removes all the elements from the multimap" }, { "code": null, "e": 26566, "s": 26550, "text": "What is a pair?" }, { "code": null, "e": 26665, "s": 26566, "text": "Utility header in C++ provides us pair container. A pair consists of two data elements or objects." }, { "code": null, "e": 26783, "s": 26665, "text": "The first element is referenced as ‘first’ and the second element as ‘second’ and the order is fixed (first, second)." }, { "code": null, "e": 26931, "s": 26783, "text": "Pair is used to combine together two values that may be different in type. Pair provides a way to store two heterogeneous objects as a single unit." }, { "code": null, "e": 27152, "s": 26931, "text": "Pair can be assigned, copied, and compared. The array of objects allocated in a map or hash_map is of type ‘pair’ by default in which all the ‘first’ elements are unique keys associated with their ‘second’ value objects." }, { "code": null, "e": 27263, "s": 27152, "text": "To access the elements, we use variable name followed by dot operator followed by the keyword first or second." }, { "code": null, "e": 27285, "s": 27263, "text": "How to access a pair?" }, { "code": null, "e": 27355, "s": 27285, "text": "The elements of a pair can be accessed by using the dot (.) operator." }, { "code": null, "e": 27363, "s": 27355, "text": "Syntax:" }, { "code": null, "e": 27396, "s": 27363, "text": "auto fistElement = myPair.first;" }, { "code": null, "e": 27430, "s": 27396, "text": "auto fistElement = myPair.second;" }, { "code": null, "e": 27448, "s": 27430, "text": "Multimap of pairs" }, { "code": null, "e": 27817, "s": 27448, "text": "A multimap of pairs is a multimap in which either of the key or value is a pair itself. Two pairs are considered to be equal if the corresponding first and second elements of pairs are equal. Now if there is a need to store more than one copy of a pair along with other elements that too in a sorted or particular order, in such cases multiset of pairs comes in handy." }, { "code": null, "e": 27825, "s": 27817, "text": "Syntax:" }, { "code": null, "e": 27874, "s": 27825, "text": "multimap<pair<dataType1, dataType2>> myMultimap;" }, { "code": null, "e": 27880, "s": 27874, "text": "Here," }, { "code": null, "e": 27945, "s": 27880, "text": "dataType1 and dataType2 can be similar or dissimilar data types." }, { "code": null, "e": 28033, "s": 27945, "text": "Example 1: Below is the C++ program to demonstrate the working of a multimap of pairs. " }, { "code": null, "e": 28037, "s": 28033, "text": "C++" }, { "code": "// C++ program to demonstrate// the working of a multimap of// pairs.#include <bits/stdc++.h>using namespace std; // Function to print multimap elementsvoid print(multimap<pair<int, int>, bool>& myContainer){ cout << \"Key(pair of integers)\" << \" \" << \"Value(boolean)\\n\\n\"; for (auto pr : myContainer) { pair<int, int> myPair = pr.first; // pr points to current pair of myContainer cout << '[' << myPair.first << \" , \" << myPair.second << ']' << \" \" << pr.second << '\\n'; }} // Driver codeint main(){ // Declaring a multimap // Key is of pair<int, int> type // Value is of bool type multimap<pair<int, int>, bool> myContainer; // Creating some pairs to be used // as keys pair<int, int> pair1; pair1 = make_pair(100, 200); pair<int, int> pair2; pair2 = make_pair(200, 300); pair<int, int> pair3; pair3 = make_pair(300, 400); pair<int, int> pair4; pair4 = make_pair(100, 200); // Since each element is a pair on // its own in a multimap. So, we // are inserting a pair // Note that [] operator doesn't working // in case of a multimap myContainer.insert(pair<pair<int, int>, bool>(pair1, true)); myContainer.insert(pair<pair<int, int>, bool>(pair2, false)); myContainer.insert(pair<pair<int, int>, bool>(pair3, true)); myContainer.insert(pair<pair<int, int>, bool>(pair4, false)); // Calling print function print(myContainer); return 0;}", "e": 29727, "s": 28037, "text": null }, { "code": null, "e": 29764, "s": 29727, "text": "Key(pair of integers) Value(boolean)" }, { "code": null, "e": 29813, "s": 29764, "text": "[100, 200] 1[100, 200] 0[200, 300] 0[300, 400] 1" }, { "code": null, "e": 29900, "s": 29813, "text": "Example 2: Below is the C++ program to demonstrate the working of a multimap of pairs." }, { "code": null, "e": 29904, "s": 29900, "text": "C++" }, { "code": "// C++ program to demonstrate// the working of a multimap of// pairs.#include <bits/stdc++.h>using namespace std; // Function to print multimap elementsvoid print(multimap<pair<string, int>, bool>& myContainer){ cout << \"Key(pair of integers)\" << \" \" << \"Value(boolean)\\n\\n\"; for (auto pr : myContainer) { pair<string, int> myPair = pr.first; // pr points to current pair of myContainer cout << '[' << myPair.first << \" , \" << myPair.second << ']' << \" \" << \" \" << pr.second << '\\n'; }} // Driver codeint main(){ // Declaring a multimap // Key is of pair<int, int> type // Value is of bool type multimap<pair<string, int>, bool> myContainer; // Creating some pairs to be used // as keys pair<string, int> pair1; pair1 = make_pair(\"GFG\", 100); pair<string, int> pair2; pair2 = make_pair(\"C++\", 200); pair<string, int> pair3; pair3 = make_pair(\"CSS\", 300); pair<string, int> pair4; pair4 = make_pair(\"GFG\", 400); // Since each element is a pair on its // own in a multimap. So, we are // inserting a pair // Note that [] operator doesn't working // in case of a multimap myContainer.insert(pair<pair<string, int>, bool>(pair1, true)); myContainer.insert(pair<pair<string, int>, bool>(pair2, false)); myContainer.insert(pair<pair<string, int>, bool>(pair3, true)); myContainer.insert(pair<pair<string, int>, bool>(pair4, false)); // Calling print function print(myContainer); return 0;}", "e": 31656, "s": 29904, "text": null }, { "code": null, "e": 31693, "s": 31656, "text": "Key(pair of integers) Value(boolean)" }, { "code": null, "e": 31742, "s": 31693, "text": "[C++, 200] 0[CSS, 300] 1[GFG, 100] 1[GFG, 400] 0" }, { "code": null, "e": 31755, "s": 31742, "text": "cpp-multimap" }, { "code": null, "e": 31764, "s": 31755, "text": "cpp-pair" }, { "code": null, "e": 31768, "s": 31764, "text": "STL" }, { "code": null, "e": 31772, "s": 31768, "text": "C++" }, { "code": null, "e": 31776, "s": 31772, "text": "STL" }, { "code": null, "e": 31780, "s": 31776, "text": "CPP" }, { "code": null, "e": 31878, "s": 31780, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31906, "s": 31878, "text": "Operator Overloading in C++" }, { "code": null, "e": 31926, "s": 31906, "text": "Polymorphism in C++" }, { "code": null, "e": 31950, "s": 31926, "text": "Sorting a vector in C++" }, { "code": null, "e": 31983, "s": 31950, "text": "Friend class and function in C++" }, { "code": null, "e": 32027, "s": 31983, "text": "Pair in C++ Standard Template Library (STL)" }, { "code": null, "e": 32052, "s": 32027, "text": "std::string class in C++" }, { "code": null, "e": 32097, "s": 32052, "text": "Queue in C++ Standard Template Library (STL)" }, { "code": null, "e": 32121, "s": 32097, "text": "Inline Functions in C++" }, { "code": null, "e": 32174, "s": 32121, "text": "Array of Strings in C++ (5 Different Ways to Create)" } ]
Associate user to its upload (post) in Django - GeeksforGeeks
27 Feb, 2020 Django provides built-in facilities of ForeignKey, ManytoManyField for associating one model to other model. To associate a user model to a post model, one can use various options. This article revolves around how to associate a user to its post (post model). This tutorial uses the concept of foreign keys in Django and at the end, one will be able to create application of post upload and also profile app which contains all the past uploads of the user. Prerequisites – Creation of Django projectCreation of application which can register login and logout the userMake migrations in application and add database Creation of Django project Creation of application which can register login and logout the user Make migrations in application and add database We have already created a user application for registration and so we will create a new app that can be named as userblog (blog upload from the user) .To do this create an app in main project file by writing this code in your PowerShell or terminal django-admin startapp userblog Now this application is available in your project file and you should first add this application to settings.py file in the project and add this application to INSTALLED_APPS Now make migrations in your project and add this application to your project python manage.py makemigrations python manage.py migrate Now we have to use models in this application so that Django can create a table for the information which we are going to store in our database and the user can input the information. We have to create a class in the models.py file of userblog application which is named as Snippet. We will use a ForeignKey class which will hold the id value of the user and it holds one to many relationship and so you can use this class to associate the user to any other activities where there is user involvement. from django.db import modelsfrom django.conf import settings User = settings.AUTH_USER_MODEL # Create your models here.class Snippet(models.Model): user = models.ForeignKey(User, default = 1, null = True, on_delete = models.SET_NULL ) blogname = models.CharField(max_length = 100) blogauth = models.CharField(max_length = 100) blogdes = models.TextField(max_length = 400) img = models.ImageField(upload_to ='pics') def __str__(self): return self.blogname Also create a python file named as forms.py and create a ModelForm for the same to input data from user. from django import formsfrom .models import Snippet class SnippetForm(forms.ModelForm): class Meta: model = Snippet fields = ['blogname', 'img', 'blogauth', 'blogdes' ] We need to migrate the class model of Snippet so that Django administration creates a database for the post upload and details so makemigrations of the class Snippet and you will see this in django administration –Here User is a foreign key which will show all the users and it will store the key number of last instance of post upload by a user by default it is set to superuserNow we will go to views.py file of application and add the main code which will be storing the information in database using model form object. usblog – This will display all the posts in our homepage snippet_detail – This will get the data from the user in the form ad it will associate blog to user from django.shortcuts import renderfrom django.http import HttpResponsefrom .forms import SnippetFormfrom .models import Snippetfrom django.contrib import messages# Create your views here.def usblog(request): snipps = Snippet.objects.all() return render(request, 'indexg.html', {'snipps' : snipps}) def snippet_detail(request): form = SnippetForm(request.POST or None, request.FILES or None) if request.method =='POST': if form.is_valid(): obj = form.save(commit = False) obj.user = request.user; obj.save() form = SnippetForm() messages.success(request, "Successfully created") return render(request, 'form.html', {'form':form}) So by now the Django administration has created the database of Snippet class and you can see it by visiting Django administration. Now we have to create a simple form.html file which we will contain a form from where user can enter the queries which we have stated in the class. Here comes the beauty of Django that since we have used model forms for our application Django has created HTML code of form which will have all those queries which we needed. So simply create an HTML file in your templates file(form.html). <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Your Blog</title></head> <body> <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{form.as_p}} <button type="submit">Submit</button> </form></body> </html> Now we will need a homepage where we will see all the posts of the users so create another HTML file indexg.html and import the objects of function which we have created in views.py file. (Placed image of only body part of html to show the python code you can make your own indexg with features ) <body> <h1>Post play<h4>Only for geeks</h4> </h1> <div class="topnav"> {% if user.is_authenticated %} <a href="#">Hi {{user.username}}</a> <a href="accounts/logout">Logout</a> <a href="snippet_detail">Write post</a> {% else %} <a href="accounts/register">Register</a> <a href="accounts/login">Login</a> {% endif %} </div> <p> {% for snips in snipps %} <img src="{{snips.img.url}}" alt="Image" class="img-fluid"> <h2 class="font-size-regular"><a href="#">{{snips.blogname}}</a></h2> <h3>{{snips.user}}</h3> {% if user.is_authenticated %} <p>{{snips.blogdes}}</p> {% else %} <p>Register/Login to know more</p> {% endif %} {% endfor %} </p> </div></body> Let us go to our main urls file where we will have an account app and now make the userblog application as default and add the URLs of your application. Also in your userblog application add urls.py and add the links of 2 functions which are form.html and homepage(indexg.html).Main Urls from django.contrib import adminfrom django.urls import path, includefrom django.conf import settingsfrom django.conf.urls.static import staticurlpatterns = [ path('', include('userblog.urls')), path('admin/', admin.site.urls), path('accounts/', include('accounts.urls')) ] userblog urls – from django.urls import path from . import viewsurlpatterns = [ path("snippet_detail", views.snippet_detail), path('', views.usblog, name ='usblog')] Start the application and register the user to your application and make a post python manage.py runserver Your browser does not support playing video GITHUB LINK – Github Repo Technical Scripter 2019 Python Technical Scripter Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python Classes and Objects How to drop one or multiple columns in Pandas Dataframe Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 25564, "s": 25536, "text": "\n27 Feb, 2020" }, { "code": null, "e": 26021, "s": 25564, "text": "Django provides built-in facilities of ForeignKey, ManytoManyField for associating one model to other model. To associate a user model to a post model, one can use various options. This article revolves around how to associate a user to its post (post model). This tutorial uses the concept of foreign keys in Django and at the end, one will be able to create application of post upload and also profile app which contains all the past uploads of the user." }, { "code": null, "e": 26037, "s": 26021, "text": "Prerequisites –" }, { "code": null, "e": 26179, "s": 26037, "text": "Creation of Django projectCreation of application which can register login and logout the userMake migrations in application and add database" }, { "code": null, "e": 26206, "s": 26179, "text": "Creation of Django project" }, { "code": null, "e": 26275, "s": 26206, "text": "Creation of application which can register login and logout the user" }, { "code": null, "e": 26323, "s": 26275, "text": "Make migrations in application and add database" }, { "code": null, "e": 26572, "s": 26323, "text": "We have already created a user application for registration and so we will create a new app that can be named as userblog (blog upload from the user) .To do this create an app in main project file by writing this code in your PowerShell or terminal" }, { "code": null, "e": 26604, "s": 26572, "text": "django-admin startapp userblog\n" }, { "code": null, "e": 26779, "s": 26604, "text": "Now this application is available in your project file and you should first add this application to settings.py file in the project and add this application to INSTALLED_APPS" }, { "code": null, "e": 26856, "s": 26779, "text": "Now make migrations in your project and add this application to your project" }, { "code": null, "e": 26914, "s": 26856, "text": "python manage.py makemigrations\npython manage.py migrate\n" }, { "code": null, "e": 27416, "s": 26914, "text": "Now we have to use models in this application so that Django can create a table for the information which we are going to store in our database and the user can input the information. We have to create a class in the models.py file of userblog application which is named as Snippet. We will use a ForeignKey class which will hold the id value of the user and it holds one to many relationship and so you can use this class to associate the user to any other activities where there is user involvement." }, { "code": "from django.db import modelsfrom django.conf import settings User = settings.AUTH_USER_MODEL # Create your models here.class Snippet(models.Model): user = models.ForeignKey(User, default = 1, null = True, on_delete = models.SET_NULL ) blogname = models.CharField(max_length = 100) blogauth = models.CharField(max_length = 100) blogdes = models.TextField(max_length = 400) img = models.ImageField(upload_to ='pics') def __str__(self): return self.blogname", "e": 27993, "s": 27416, "text": null }, { "code": null, "e": 28098, "s": 27993, "text": "Also create a python file named as forms.py and create a ModelForm for the same to input data from user." }, { "code": "from django import formsfrom .models import Snippet class SnippetForm(forms.ModelForm): class Meta: model = Snippet fields = ['blogname', 'img', 'blogauth', 'blogdes' ]", "e": 28313, "s": 28098, "text": null }, { "code": null, "e": 28836, "s": 28313, "text": "We need to migrate the class model of Snippet so that Django administration creates a database for the post upload and details so makemigrations of the class Snippet and you will see this in django administration –Here User is a foreign key which will show all the users and it will store the key number of last instance of post upload by a user by default it is set to superuserNow we will go to views.py file of application and add the main code which will be storing the information in database using model form object." }, { "code": null, "e": 28893, "s": 28836, "text": "usblog – This will display all the posts in our homepage" }, { "code": null, "e": 28993, "s": 28893, "text": "snippet_detail – This will get the data from the user in the form ad it will associate blog to user" }, { "code": "from django.shortcuts import renderfrom django.http import HttpResponsefrom .forms import SnippetFormfrom .models import Snippetfrom django.contrib import messages# Create your views here.def usblog(request): snipps = Snippet.objects.all() return render(request, 'indexg.html', {'snipps' : snipps}) def snippet_detail(request): form = SnippetForm(request.POST or None, request.FILES or None) if request.method =='POST': if form.is_valid(): obj = form.save(commit = False) obj.user = request.user; obj.save() form = SnippetForm() messages.success(request, \"Successfully created\") return render(request, 'form.html', {'form':form})", "e": 29737, "s": 28993, "text": null }, { "code": null, "e": 30258, "s": 29737, "text": "So by now the Django administration has created the database of Snippet class and you can see it by visiting Django administration. Now we have to create a simple form.html file which we will contain a form from where user can enter the queries which we have stated in the class. Here comes the beauty of Django that since we have used model forms for our application Django has created HTML code of form which will have all those queries which we needed. So simply create an HTML file in your templates file(form.html)." }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> <meta http-equiv=\"X-UA-Compatible\" content=\"ie=edge\"> <title>Your Blog</title></head> <body> <form method=\"post\" enctype=\"multipart/form-data\"> {% csrf_token %} {{form.as_p}} <button type=\"submit\">Submit</button> </form></body> </html>", "e": 30669, "s": 30258, "text": null }, { "code": null, "e": 30966, "s": 30669, "text": "Now we will need a homepage where we will see all the posts of the users so create another HTML file indexg.html and import the objects of function which we have created in views.py file. (Placed image of only body part of html to show the python code you can make your own indexg with features )" }, { "code": "<body> <h1>Post play<h4>Only for geeks</h4> </h1> <div class=\"topnav\"> {% if user.is_authenticated %} <a href=\"#\">Hi {{user.username}}</a> <a href=\"accounts/logout\">Logout</a> <a href=\"snippet_detail\">Write post</a> {% else %} <a href=\"accounts/register\">Register</a> <a href=\"accounts/login\">Login</a> {% endif %} </div> <p> {% for snips in snipps %} <img src=\"{{snips.img.url}}\" alt=\"Image\" class=\"img-fluid\"> <h2 class=\"font-size-regular\"><a href=\"#\">{{snips.blogname}}</a></h2> <h3>{{snips.user}}</h3> {% if user.is_authenticated %} <p>{{snips.blogdes}}</p> {% else %} <p>Register/Login to know more</p> {% endif %} {% endfor %} </p> </div></body>", "e": 31775, "s": 30966, "text": null }, { "code": null, "e": 32063, "s": 31775, "text": "Let us go to our main urls file where we will have an account app and now make the userblog application as default and add the URLs of your application. Also in your userblog application add urls.py and add the links of 2 functions which are form.html and homepage(indexg.html).Main Urls" }, { "code": "from django.contrib import adminfrom django.urls import path, includefrom django.conf import settingsfrom django.conf.urls.static import staticurlpatterns = [ path('', include('userblog.urls')), path('admin/', admin.site.urls), path('accounts/', include('accounts.urls')) ]", "e": 32355, "s": 32063, "text": null }, { "code": null, "e": 32371, "s": 32355, "text": "userblog urls –" }, { "code": "from django.urls import path from . import viewsurlpatterns = [ path(\"snippet_detail\", views.snippet_detail), path('', views.usblog, name ='usblog')]", "e": 32534, "s": 32371, "text": null }, { "code": null, "e": 32614, "s": 32534, "text": "Start the application and register the user to your application and make a post" }, { "code": null, "e": 32642, "s": 32614, "text": "python manage.py runserver\n" }, { "code": null, "e": 32686, "s": 32642, "text": "Your browser does not support playing video" }, { "code": null, "e": 32712, "s": 32686, "text": "GITHUB LINK – Github Repo" }, { "code": null, "e": 32736, "s": 32712, "text": "Technical Scripter 2019" }, { "code": null, "e": 32743, "s": 32736, "text": "Python" }, { "code": null, "e": 32762, "s": 32743, "text": "Technical Scripter" }, { "code": null, "e": 32779, "s": 32762, "text": "Web Technologies" }, { "code": null, "e": 32877, "s": 32779, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32909, "s": 32877, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 32951, "s": 32909, "text": "Check if element exists in list in Python" }, { "code": null, "e": 32993, "s": 32951, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 33020, "s": 32993, "text": "Python Classes and Objects" }, { "code": null, "e": 33076, "s": 33020, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 33116, "s": 33076, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 33149, "s": 33116, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 33194, "s": 33149, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 33237, "s": 33194, "text": "How to fetch data from an API in ReactJS ?" } ]
Check whether a given number N is a Nude Number or not - GeeksforGeeks
03 Mar, 2021 Given an integer N, the task is to check whether N is a Nude number or not. A Nude number is a number that is divisible by all of its digits (which should be nonzero). Example: Input: N = 672 Output: Yes Explanation: Since, 672 is divisible by all of its three digits 6, 7 and 2. Therefore the output is Yes.Input: N = 450 Output: No Explanation: Since, 450 is not divisible by 0 (Also it gives exception). Therefore the output is No. Approach: Extract digits from number one by one and check these two conditions: The digit must be non-zero, to avoid exceptionAnd the digit must divide the number N The digit must be non-zero, to avoid exception And the digit must divide the number N When both these condition is satisfied by all digits of N, then the number is called Nude number.Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program to check if the// number if Nude number or not #include <iostream>using namespace std; // Check if all digits// of num divide numbool checkDivisbility(int num){ // array to store all digits // of the given number int digit; int N = num; while (num != 0) { digit = num % 10; num = num / 10; // If any of the condition // is true for any digit // Then N is not a nude number if (digit == 0 || N % digit != 0) return false; } return true;} // Driver codeint main(){ int N = 128; bool result = checkDivisbility(N); if (result) cout << "Yes"; else cout << "No"; return 0;} // Java program to check if the// number if Nude number or notimport java.util.*;class GFG{ // Check if all digits// of num divide numstatic boolean checkDivisbility(int num){ // array to store all digits // of the given number int digit; int N = num; while (num != 0) { digit = num % 10; num = num / 10; // If any of the condition // is true for any digit // Then N is not a nude number if (digit == 0 || N % digit != 0) return false; } return true;} // Driver codepublic static void main(String[] args){ int N = 128; boolean result = checkDivisbility(N); if (result) System.out.print("Yes"); else System.out.print("No");}} // This code is contributed by 29AjayKumar # Python3 program to check if the# number if nude number or not # Check if all digits# of num divide numdef checkDivisbility(num): # Array to store all digits # of the given number digit = 0 N = num while (num != 0): digit = num % 10 num = num // 10 # If any of the condition # is true for any digit # then N is not a nude number if (digit == 0 or N % digit != 0): return False return True # Driver codeif __name__ == '__main__': N = 128 result = checkDivisbility(N) if (result): print("Yes") else: print("No") # This code is contributed by mohit kumar 29 // C# program to check if the// number if Nude number or notusing System;class GFG{ // Check if all digits// of num divide numstatic bool checkDivisbility(int num){ // array to store all digits // of the given number int digit; int N = num; while (num != 0) { digit = num % 10; num = num / 10; // If any of the condition // is true for any digit // Then N is not a nude number if (digit == 0 || N % digit != 0) return false; } return true;} // Driver codepublic static void Main(){ int N = 128; bool result = checkDivisbility(N); if (result) Console.Write("Yes"); else Console.Write("No");}} // This code is contributed by Nidhi_biet <script> // Javascript program to check if the// number if Nude number or not // Check if all digits// of num divide numfunction checkDivisbility(num){ // array to store all digits // of the given number let digit; let N = num; while (num != 0) { digit = num % 10; num = Math.floor(num / 10); // If any of the condition // is true for any digit // Then N is not a nude number if (digit == 0 || N % digit != 0) return false; } return true;} // Driver code let N = 128; let result = checkDivisbility(N); if (result) document.write("Yes"); else document.write("No"); // This code is contributed by Mayank Tyagi </script> Yes Time complexity: O( length of N ) mohit kumar 29 29AjayKumar nidhi_biet mayanktyagi1709 Number Divisibility number-digits Numbers Mathematical School Programming Write From Home Mathematical Numbers Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Merge two sorted arrays Modulo Operator (%) in C/C++ with Examples Prime Numbers Program to find GCD or HCF of two numbers Print all possible combinations of r elements in a given array of size n Python Dictionary Arrays in C/C++ Inheritance in C++ Reverse a string in Java C++ Classes and Objects
[ { "code": null, "e": 26191, "s": 26163, "text": "\n03 Mar, 2021" }, { "code": null, "e": 26268, "s": 26191, "text": "Given an integer N, the task is to check whether N is a Nude number or not. " }, { "code": null, "e": 26362, "s": 26268, "text": "A Nude number is a number that is divisible by all of its digits (which should be nonzero). " }, { "code": null, "e": 26373, "s": 26362, "text": "Example: " }, { "code": null, "e": 26633, "s": 26373, "text": "Input: N = 672 Output: Yes Explanation: Since, 672 is divisible by all of its three digits 6, 7 and 2. Therefore the output is Yes.Input: N = 450 Output: No Explanation: Since, 450 is not divisible by 0 (Also it gives exception). Therefore the output is No. " }, { "code": null, "e": 26717, "s": 26635, "text": "Approach: Extract digits from number one by one and check these two conditions: " }, { "code": null, "e": 26802, "s": 26717, "text": "The digit must be non-zero, to avoid exceptionAnd the digit must divide the number N" }, { "code": null, "e": 26849, "s": 26802, "text": "The digit must be non-zero, to avoid exception" }, { "code": null, "e": 26888, "s": 26849, "text": "And the digit must divide the number N" }, { "code": null, "e": 27037, "s": 26888, "text": "When both these condition is satisfied by all digits of N, then the number is called Nude number.Below is the implementation of the above approach: " }, { "code": null, "e": 27041, "s": 27037, "text": "C++" }, { "code": null, "e": 27046, "s": 27041, "text": "Java" }, { "code": null, "e": 27054, "s": 27046, "text": "Python3" }, { "code": null, "e": 27057, "s": 27054, "text": "C#" }, { "code": null, "e": 27068, "s": 27057, "text": "Javascript" }, { "code": "// C++ program to check if the// number if Nude number or not #include <iostream>using namespace std; // Check if all digits// of num divide numbool checkDivisbility(int num){ // array to store all digits // of the given number int digit; int N = num; while (num != 0) { digit = num % 10; num = num / 10; // If any of the condition // is true for any digit // Then N is not a nude number if (digit == 0 || N % digit != 0) return false; } return true;} // Driver codeint main(){ int N = 128; bool result = checkDivisbility(N); if (result) cout << \"Yes\"; else cout << \"No\"; return 0;}", "e": 27758, "s": 27068, "text": null }, { "code": "// Java program to check if the// number if Nude number or notimport java.util.*;class GFG{ // Check if all digits// of num divide numstatic boolean checkDivisbility(int num){ // array to store all digits // of the given number int digit; int N = num; while (num != 0) { digit = num % 10; num = num / 10; // If any of the condition // is true for any digit // Then N is not a nude number if (digit == 0 || N % digit != 0) return false; } return true;} // Driver codepublic static void main(String[] args){ int N = 128; boolean result = checkDivisbility(N); if (result) System.out.print(\"Yes\"); else System.out.print(\"No\");}} // This code is contributed by 29AjayKumar", "e": 28531, "s": 27758, "text": null }, { "code": "# Python3 program to check if the# number if nude number or not # Check if all digits# of num divide numdef checkDivisbility(num): # Array to store all digits # of the given number digit = 0 N = num while (num != 0): digit = num % 10 num = num // 10 # If any of the condition # is true for any digit # then N is not a nude number if (digit == 0 or N % digit != 0): return False return True # Driver codeif __name__ == '__main__': N = 128 result = checkDivisbility(N) if (result): print(\"Yes\") else: print(\"No\") # This code is contributed by mohit kumar 29", "e": 29202, "s": 28531, "text": null }, { "code": "// C# program to check if the// number if Nude number or notusing System;class GFG{ // Check if all digits// of num divide numstatic bool checkDivisbility(int num){ // array to store all digits // of the given number int digit; int N = num; while (num != 0) { digit = num % 10; num = num / 10; // If any of the condition // is true for any digit // Then N is not a nude number if (digit == 0 || N % digit != 0) return false; } return true;} // Driver codepublic static void Main(){ int N = 128; bool result = checkDivisbility(N); if (result) Console.Write(\"Yes\"); else Console.Write(\"No\");}} // This code is contributed by Nidhi_biet", "e": 29941, "s": 29202, "text": null }, { "code": "<script> // Javascript program to check if the// number if Nude number or not // Check if all digits// of num divide numfunction checkDivisbility(num){ // array to store all digits // of the given number let digit; let N = num; while (num != 0) { digit = num % 10; num = Math.floor(num / 10); // If any of the condition // is true for any digit // Then N is not a nude number if (digit == 0 || N % digit != 0) return false; } return true;} // Driver code let N = 128; let result = checkDivisbility(N); if (result) document.write(\"Yes\"); else document.write(\"No\"); // This code is contributed by Mayank Tyagi </script>", "e": 30664, "s": 29941, "text": null }, { "code": null, "e": 30668, "s": 30664, "text": "Yes" }, { "code": null, "e": 30705, "s": 30670, "text": "Time complexity: O( length of N ) " }, { "code": null, "e": 30720, "s": 30705, "text": "mohit kumar 29" }, { "code": null, "e": 30732, "s": 30720, "text": "29AjayKumar" }, { "code": null, "e": 30743, "s": 30732, "text": "nidhi_biet" }, { "code": null, "e": 30759, "s": 30743, "text": "mayanktyagi1709" }, { "code": null, "e": 30779, "s": 30759, "text": "Number Divisibility" }, { "code": null, "e": 30793, "s": 30779, "text": "number-digits" }, { "code": null, "e": 30801, "s": 30793, "text": "Numbers" }, { "code": null, "e": 30814, "s": 30801, "text": "Mathematical" }, { "code": null, "e": 30833, "s": 30814, "text": "School Programming" }, { "code": null, "e": 30849, "s": 30833, "text": "Write From Home" }, { "code": null, "e": 30862, "s": 30849, "text": "Mathematical" }, { "code": null, "e": 30870, "s": 30862, "text": "Numbers" }, { "code": null, "e": 30968, "s": 30870, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30992, "s": 30968, "text": "Merge two sorted arrays" }, { "code": null, "e": 31035, "s": 30992, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 31049, "s": 31035, "text": "Prime Numbers" }, { "code": null, "e": 31091, "s": 31049, "text": "Program to find GCD or HCF of two numbers" }, { "code": null, "e": 31164, "s": 31091, "text": "Print all possible combinations of r elements in a given array of size n" }, { "code": null, "e": 31182, "s": 31164, "text": "Python Dictionary" }, { "code": null, "e": 31198, "s": 31182, "text": "Arrays in C/C++" }, { "code": null, "e": 31217, "s": 31198, "text": "Inheritance in C++" }, { "code": null, "e": 31242, "s": 31217, "text": "Reverse a string in Java" } ]
BigDecimal Class in Java - GeeksforGeeks
04 Dec, 2018 The BigDecimal class provides operations on double numbers for arithmetic, scale handling, rounding, comparison, format conversion and hashing. It can handle very large and very small floating point numbers with great precision but compensating with the time complexity a bit.A BigDecimal consists of a random precision integer unscaled value and a 32-bit integer scale. If greater than or equal to zero, the scale is the number of digits to the right of the decimal point. If less than zero, the unscaled value of the number is multiplied by 10^(-scale). Examples: Input : double a=0.03; double b=0.04; double c=b-a; System.out.println(c); Output :0.009999999999999998 Input : BigDecimal _a = new BigDecimal("0.03"); BigDecimal _b = new BigDecimal("0.04"); BigDecimal _c = _b.subtract(_a); System.out.println(_c); Output :0.01 Need Of BigDecimal The two java primitive types(double and float) are floating point numbers, which is stored as a binary representation of a fraction and a exponent. Other primitive types(except boolean) are fixed-point numbers. Unlike fixed point numbers, floating point numbers will most of the times return an answer with a small error (around 10^-19) This is the reason why we end up with 0.009999999999999998 as the result of 0.04-0.03 in the above example. But BigDecimal provides us with the exact answer. // Java Program to illustrate BigDecimal Class import java.math.BigDecimal;public class BigDecimalExample{ public static void main(String[] args) { // Create two new BigDecimals BigDecimal bd1 = new BigDecimal("124567890.0987654321"); BigDecimal bd2 = new BigDecimal("987654321.123456789"); // Addition of two BigDecimals bd1 = bd1.add(bd2); System.out.println("BigDecimal1 = " + bd1); // Multiplication of two BigDecimals bd1 = bd1.multiply(bd2); System.out.println("BigDecimal1 = " + bd1); // Subtraction of two BigDecimals bd1 = bd1.subtract(bd2); System.out.println("BigDecimal1 = " + bd1); // Division of two BigDecimals bd1 = bd1.divide(bd2); System.out.println("BigDecimal1 = " + bd1); // BigDecima1 raised to the power of 2 bd1 = bd1.pow(2); System.out.println("BigDecimal1 = " + bd1); // Negate value of BigDecimal1 bd1 = bd1.negate(); System.out.println("BigDecimal1 = " + bd1); } } Output:- BigDecimal1 = 1112222211.2222222211 BigDecimal1 = 1098491072963113850.7436076939614540479 BigDecimal1 = 1098491071975459529.6201509049614540479 BigDecimal1 = 1112222210.2222222211 BigDecimal1 = 1237038244911605079.77528397755061728521 BigDecimal1 = -1237038244911605079.77528397755061728521 Declaration double a, b; BigDecimal A, B; Initialization: a = 5.4; b = 2.3; A = BigDecimal.valueOf(5.4); B = BigDecimal.valueOf(2.3); If you are given a String representation of a double number then you can initialize in the following manner: A = new BigDecimal(“5.4”); B = new BigDecimal(“1238126387123.1234”); For ease of initialization BigDecimal class has some pre-defined constants: A = BigDecimal.ONE; // Other than this, available constants // are BigDecimal.ZERO and BigDecimal.TEN Mathematical operations: int c = a + b; BigDecimal C = A.add(B); Other similar function are subtract() , multiply(), divide(), pow() But all these functions, except pow() which takes integer as its argument, take BigDecimal as their argument so if we want these operation with decimals or string convert them to BigDecimal before passing them to functions as shown below: String str = “123456789.123456789”; BigDecimal C = A.add(new BigBigDecimal(str)); double val = 123456789.123456789; BigDecimal C = A.add(BigDecimal.valueOf(val)); Extraction of value from BigDecimal: // value should be in limit of double x double x = A.doubleValue(); // To get string representation of BigDecimal A String z = A.toString(); Comparison: if (a < b) {} // For primitive double if (A.compareTo(B) < 0) {} // For BigDecimal Actually compareTo returns -1(less than), 0(Equal), 1(greater than) according to values. For equality we can also use: if (A.equals(B)) {} // A is equal to B Methods of BigDecimal Class: BigDecimal abs​(): This method returns a BigDecimal whose value is the absolute value of this BigDecimal, and whose scale is this.scale().BigDecimal abs​(MathContext mc): This method returns a BigDecimal whose value is the absolute value of this BigDecimal, with rounding according to the context settings.BigDecimal add​(BigDecimal augend): This method returns a BigDecimal whose value is (this + augend), and whose scale is max(this.scale(), augend.scale()).BigDecimal add​(BigDecimal augend, MathContext mc): This method returns a BigDecimal whose value is (this + augend), with rounding according to the context settings.byte byteValueExact​(): This method converts this BigDecimal to a byte, checking for lost information.int compareTo​(BigDecimal val): This method compares this BigDecimal with the specified BigDecimal.BigDecimal divide​(BigDecimal divisor): This method returns a BigDecimal whose value is (this / divisor), and whose preferred scale is (this.scale() – divisor.scale()); if the exact quotient cannot be represented (because it has a non-terminating decimal expansion) an ArithmeticException is thrown.BigDecimal divide​(BigDecimal divisor, int scale, RoundingMode roundingMode): This method returns a BigDecimal whose value is (this / divisor), and whose scale is as specified.BigDecimal divide​(BigDecimal divisor, MathContext mc): This method returns a BigDecimal whose value is (this / divisor), with rounding according to the context settings.BigDecimal divide​(BigDecimal divisor, RoundingMode roundingMode): This method returns a BigDecimal whose value is (this / divisor), and whose scale is this.scale().BigDecimal[] divideAndRemainder​(BigDecimal divisor): This method returns a two-element BigDecimal array containing the result of divideToIntegralValue followed by the result of remainder on the two operands.BigDecimal[] divideAndRemainder​(BigDecimal divisor, MathContext mc): This method returns a two-element BigDecimal array containing the result of divideToIntegralValue followed by the result of remainder on the two operands calculated with rounding according to the context settings.BigDecimal divideToIntegralValue​(BigDecimal divisor): This method returns a BigDecimal whose value is the integer part of the quotient (this / divisor) rounded down.BigDecimal divideToIntegralValue​(BigDecimal divisor, MathContext mc): This method returns a BigDecimal whose value is the integer part of (this / divisor).double doubleValue​(): This method converts this BigDecimal to a double.boolean equals​(Object x): This method compares this BigDecimal with the specified Object for equality.float floatValue​(): This method converts this BigDecimal to a float.int hashCode​(): This method returns the hash code for this BigDecimal.int intValue​(): This method converts this BigDecimal to an int.int intValueExact​(): This method converts this BigDecimal to an int, checking for lost information.long longValue​(): This method converts this BigDecimal to a long.long longValueExact​(): This method converts this BigDecimal to a long, checking for lost information.BigDecimal max​(BigDecimal val): This method returns the maximum of this BigDecimal and val.BigDecimal min​(BigDecimal val): This method returns the minimum of this BigDecimal and val.BigDecimal movePointLeft​(int n): This method returns a BigDecimal which is equivalent to this one with the decimal point moved n places to the left.BigDecimal movePointRight​(int n): This method returns a BigDecimal which is equivalent to this one with the decimal point moved n places to the right.BigDecimal multiply​(BigDecimal multiplicand): This method returns a BigDecimal whose value is (this × multiplicand), and whose scale is (this.scale() + multiplicand.scale()).BigDecimal multiply​(BigDecimal multiplicand, MathContext mc): This method returns a BigDecimal whose value is (this × multiplicand), with rounding according to the context settings.BigDecimal negate​(): This method returns a BigDecimal whose value is (-this), and whose scale is this.scale().BigDecimal negate​(MathContext mc): This method returns a BigDecimal whose value is (-this), with rounding according to the context settings.BigDecimal plus​(): This method returns a BigDecimal whose value is (+this), and whose scale is this.scale().BigDecimal plus​(MathContext mc): This method returns a BigDecimal whose value is (+this), with rounding according to the context settings.BigDecimal pow​(int n): This method returns a BigDecimal whose value is (thisn), The power is computed exactly, to unlimited precision.BigDecimal pow​(int n, MathContext mc): This method returns a BigDecimal whose value is (thisn).int precision​(): This method returns the precision of this BigDecimal.BigDecimal remainder​(BigDecimal divisor): This method returns a BigDecimal whose value is (this % divisor).BigDecimal remainder​(BigDecimal divisor, MathContext mc): This method returns a BigDecimal whose value is (this % divisor), with rounding according to the context settings.BigDecimal round​(MathContext mc): This method returns a BigDecimal rounded according to the MathContext settings.int scale​(): This method returns the scale of this BigDecimal.BigDecimal scaleByPowerOfTen​(int n): This method returns a BigDecimal whose numerical value is equal to (this * 10n).BigDecimal setScale​(int newScale): This method returns a BigDecimal whose scale is the specified value, and whose value is numerically equal to this BigDecimal’s.BigDecimal setScale​(int newScale, RoundingMode roundingMode): This method returns a BigDecimal whose scale is the specified value, and whose unscaled value is determined by multiplying or dividing this BigDecimal’s unscaled value by the appropriate power of ten to maintain its overall value.short shortValueExact​(): This method converts this BigDecimal to a short, checking for lost information.int signum​(): This method returns the signum function of this BigDecimal.BigDecimal sqrt​(MathContext mc): This method returns an approximation to the square root of this with rounding according to the context settings.BigDecimal stripTrailingZeros​(): This method returns a BigDecimal which is numerically equal to this one but with any trailing zeros removed from the representation.BigDecimal subtract​(BigDecimal subtrahend): This method returns a BigDecimal whose value is (this – subtrahend), and whose scale is max(this.scale(), subtrahend.scale()).BigDecimal subtract​(BigDecimal subtrahend, MathContext mc): This method returns a BigDecimal whose value is (this – subtrahend), with rounding according to the context settings.BigInteger toBigInteger​(): This method converts this BigDecimal to a BigInteger.BigInteger toBigIntegerExact​(): This method converts this BigDecimal to a BigInteger, checking for lost information.String toEngineeringString​(): This method returns a string representation of this BigDecimal, using engineering notation if an exponent is needed.String toPlainString​(): This method returns a string representation of this BigDecimal without an exponent field.String toString​(): This method returns the string representation of this BigDecimal, using scientific notation if an exponent is needed.BigDecimal ulp​(): This method returns the size of an ulp, a unit in the last place, of this BigDecimal.BigInteger unscaledValue​(): This method returns a BigInteger whose value is the unscaled value of this BigDecimal.static BigDecimal valueOf​(double val): This method translates a double into a BigDecimal, using the double’s canonical string representation provided by the Double.toString(double) method.static BigDecimal valueOf​(long val): This method translates a long value into a BigDecimal with a scale of zero.static BigDecimal valueOf​(long unscaledVal, int scale): This method translates a long unscaled value and an int scale into a BigDecimal. BigDecimal abs​(): This method returns a BigDecimal whose value is the absolute value of this BigDecimal, and whose scale is this.scale(). BigDecimal abs​(MathContext mc): This method returns a BigDecimal whose value is the absolute value of this BigDecimal, with rounding according to the context settings. BigDecimal add​(BigDecimal augend): This method returns a BigDecimal whose value is (this + augend), and whose scale is max(this.scale(), augend.scale()). BigDecimal add​(BigDecimal augend, MathContext mc): This method returns a BigDecimal whose value is (this + augend), with rounding according to the context settings. byte byteValueExact​(): This method converts this BigDecimal to a byte, checking for lost information. int compareTo​(BigDecimal val): This method compares this BigDecimal with the specified BigDecimal. BigDecimal divide​(BigDecimal divisor): This method returns a BigDecimal whose value is (this / divisor), and whose preferred scale is (this.scale() – divisor.scale()); if the exact quotient cannot be represented (because it has a non-terminating decimal expansion) an ArithmeticException is thrown. BigDecimal divide​(BigDecimal divisor, int scale, RoundingMode roundingMode): This method returns a BigDecimal whose value is (this / divisor), and whose scale is as specified. BigDecimal divide​(BigDecimal divisor, MathContext mc): This method returns a BigDecimal whose value is (this / divisor), with rounding according to the context settings. BigDecimal divide​(BigDecimal divisor, RoundingMode roundingMode): This method returns a BigDecimal whose value is (this / divisor), and whose scale is this.scale(). BigDecimal[] divideAndRemainder​(BigDecimal divisor): This method returns a two-element BigDecimal array containing the result of divideToIntegralValue followed by the result of remainder on the two operands. BigDecimal[] divideAndRemainder​(BigDecimal divisor, MathContext mc): This method returns a two-element BigDecimal array containing the result of divideToIntegralValue followed by the result of remainder on the two operands calculated with rounding according to the context settings. BigDecimal divideToIntegralValue​(BigDecimal divisor): This method returns a BigDecimal whose value is the integer part of the quotient (this / divisor) rounded down. BigDecimal divideToIntegralValue​(BigDecimal divisor, MathContext mc): This method returns a BigDecimal whose value is the integer part of (this / divisor). double doubleValue​(): This method converts this BigDecimal to a double. boolean equals​(Object x): This method compares this BigDecimal with the specified Object for equality. float floatValue​(): This method converts this BigDecimal to a float. int hashCode​(): This method returns the hash code for this BigDecimal. int intValue​(): This method converts this BigDecimal to an int. int intValueExact​(): This method converts this BigDecimal to an int, checking for lost information. long longValue​(): This method converts this BigDecimal to a long. long longValueExact​(): This method converts this BigDecimal to a long, checking for lost information. BigDecimal max​(BigDecimal val): This method returns the maximum of this BigDecimal and val. BigDecimal min​(BigDecimal val): This method returns the minimum of this BigDecimal and val. BigDecimal movePointLeft​(int n): This method returns a BigDecimal which is equivalent to this one with the decimal point moved n places to the left. BigDecimal movePointRight​(int n): This method returns a BigDecimal which is equivalent to this one with the decimal point moved n places to the right. BigDecimal multiply​(BigDecimal multiplicand): This method returns a BigDecimal whose value is (this × multiplicand), and whose scale is (this.scale() + multiplicand.scale()). BigDecimal multiply​(BigDecimal multiplicand, MathContext mc): This method returns a BigDecimal whose value is (this × multiplicand), with rounding according to the context settings. BigDecimal negate​(): This method returns a BigDecimal whose value is (-this), and whose scale is this.scale(). BigDecimal negate​(MathContext mc): This method returns a BigDecimal whose value is (-this), with rounding according to the context settings. BigDecimal plus​(): This method returns a BigDecimal whose value is (+this), and whose scale is this.scale(). BigDecimal plus​(MathContext mc): This method returns a BigDecimal whose value is (+this), with rounding according to the context settings. BigDecimal pow​(int n): This method returns a BigDecimal whose value is (thisn), The power is computed exactly, to unlimited precision. BigDecimal pow​(int n, MathContext mc): This method returns a BigDecimal whose value is (thisn). int precision​(): This method returns the precision of this BigDecimal. BigDecimal remainder​(BigDecimal divisor): This method returns a BigDecimal whose value is (this % divisor). BigDecimal remainder​(BigDecimal divisor, MathContext mc): This method returns a BigDecimal whose value is (this % divisor), with rounding according to the context settings. BigDecimal round​(MathContext mc): This method returns a BigDecimal rounded according to the MathContext settings. int scale​(): This method returns the scale of this BigDecimal. BigDecimal scaleByPowerOfTen​(int n): This method returns a BigDecimal whose numerical value is equal to (this * 10n). BigDecimal setScale​(int newScale): This method returns a BigDecimal whose scale is the specified value, and whose value is numerically equal to this BigDecimal’s. BigDecimal setScale​(int newScale, RoundingMode roundingMode): This method returns a BigDecimal whose scale is the specified value, and whose unscaled value is determined by multiplying or dividing this BigDecimal’s unscaled value by the appropriate power of ten to maintain its overall value. short shortValueExact​(): This method converts this BigDecimal to a short, checking for lost information. int signum​(): This method returns the signum function of this BigDecimal. BigDecimal sqrt​(MathContext mc): This method returns an approximation to the square root of this with rounding according to the context settings. BigDecimal stripTrailingZeros​(): This method returns a BigDecimal which is numerically equal to this one but with any trailing zeros removed from the representation. BigDecimal subtract​(BigDecimal subtrahend): This method returns a BigDecimal whose value is (this – subtrahend), and whose scale is max(this.scale(), subtrahend.scale()). BigDecimal subtract​(BigDecimal subtrahend, MathContext mc): This method returns a BigDecimal whose value is (this – subtrahend), with rounding according to the context settings. BigInteger toBigInteger​(): This method converts this BigDecimal to a BigInteger. BigInteger toBigIntegerExact​(): This method converts this BigDecimal to a BigInteger, checking for lost information. String toEngineeringString​(): This method returns a string representation of this BigDecimal, using engineering notation if an exponent is needed. String toPlainString​(): This method returns a string representation of this BigDecimal without an exponent field. String toString​(): This method returns the string representation of this BigDecimal, using scientific notation if an exponent is needed. BigDecimal ulp​(): This method returns the size of an ulp, a unit in the last place, of this BigDecimal. BigInteger unscaledValue​(): This method returns a BigInteger whose value is the unscaled value of this BigDecimal. static BigDecimal valueOf​(double val): This method translates a double into a BigDecimal, using the double’s canonical string representation provided by the Double.toString(double) method. static BigDecimal valueOf​(long val): This method translates a long value into a BigDecimal with a scale of zero. static BigDecimal valueOf​(long unscaledVal, int scale): This method translates a long unscaled value and an int scale into a BigDecimal. For more examples visit Java BigDecimal ExamplesRelated Articles: Using BigDecimal in Java to calculate PI number up to 200 decimal digits Make cents with BigDecimalFor more functions and details refer Class BigDecimalMy Personal Notes arrow_drop_upSave For more functions and details refer Class BigDecimal Java-BigDecimal Java-Data Types Java-Functions Java-math-package Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Interfaces in Java Singleton Class in Java Set in Java Multithreading in Java Collections in Java Queue Interface In Java Initializing a List in Java Overriding in Java LinkedList in Java
[ { "code": null, "e": 25689, "s": 25661, "text": "\n04 Dec, 2018" }, { "code": null, "e": 26245, "s": 25689, "text": "The BigDecimal class provides operations on double numbers for arithmetic, scale handling, rounding, comparison, format conversion and hashing. It can handle very large and very small floating point numbers with great precision but compensating with the time complexity a bit.A BigDecimal consists of a random precision integer unscaled value and a 32-bit integer scale. If greater than or equal to zero, the scale is the number of digits to the right of the decimal point. If less than zero, the unscaled value of the number is multiplied by 10^(-scale)." }, { "code": null, "e": 26255, "s": 26245, "text": "Examples:" }, { "code": null, "e": 26568, "s": 26255, "text": "Input : double a=0.03;\n double b=0.04;\n double c=b-a;\n System.out.println(c);\nOutput :0.009999999999999998\n\nInput : BigDecimal _a = new BigDecimal(\"0.03\");\n BigDecimal _b = new BigDecimal(\"0.04\");\n BigDecimal _c = _b.subtract(_a);\n System.out.println(_c);\nOutput :0.01\n\n" }, { "code": null, "e": 26587, "s": 26568, "text": "Need Of BigDecimal" }, { "code": null, "e": 26735, "s": 26587, "text": "The two java primitive types(double and float) are floating point numbers, which is stored as a binary representation of a fraction and a exponent." }, { "code": null, "e": 27032, "s": 26735, "text": "Other primitive types(except boolean) are fixed-point numbers. Unlike fixed point numbers, floating point numbers will most of the times return an answer with a small error (around 10^-19) This is the reason why we end up with 0.009999999999999998 as the result of 0.04-0.03 in the above example." }, { "code": null, "e": 27082, "s": 27032, "text": "But BigDecimal provides us with the exact answer." }, { "code": "// Java Program to illustrate BigDecimal Class import java.math.BigDecimal;public class BigDecimalExample{ public static void main(String[] args) { // Create two new BigDecimals BigDecimal bd1 = new BigDecimal(\"124567890.0987654321\"); BigDecimal bd2 = new BigDecimal(\"987654321.123456789\"); // Addition of two BigDecimals bd1 = bd1.add(bd2); System.out.println(\"BigDecimal1 = \" + bd1); // Multiplication of two BigDecimals bd1 = bd1.multiply(bd2); System.out.println(\"BigDecimal1 = \" + bd1); // Subtraction of two BigDecimals bd1 = bd1.subtract(bd2); System.out.println(\"BigDecimal1 = \" + bd1); // Division of two BigDecimals bd1 = bd1.divide(bd2); System.out.println(\"BigDecimal1 = \" + bd1); // BigDecima1 raised to the power of 2 bd1 = bd1.pow(2); System.out.println(\"BigDecimal1 = \" + bd1); // Negate value of BigDecimal1 bd1 = bd1.negate(); System.out.println(\"BigDecimal1 = \" + bd1); } } ", "e": 28194, "s": 27082, "text": null }, { "code": null, "e": 28203, "s": 28194, "text": "Output:-" }, { "code": null, "e": 28495, "s": 28203, "text": "BigDecimal1 = 1112222211.2222222211\nBigDecimal1 = 1098491072963113850.7436076939614540479\nBigDecimal1 = 1098491071975459529.6201509049614540479\nBigDecimal1 = 1112222210.2222222211\nBigDecimal1 = 1237038244911605079.77528397755061728521\nBigDecimal1 = -1237038244911605079.77528397755061728521\n" }, { "code": null, "e": 28507, "s": 28495, "text": "Declaration" }, { "code": null, "e": 28555, "s": 28507, "text": "double a, b; \nBigDecimal A, B; \n" }, { "code": null, "e": 28571, "s": 28555, "text": "Initialization:" }, { "code": null, "e": 28651, "s": 28571, "text": "a = 5.4;\nb = 2.3;\nA = BigDecimal.valueOf(5.4);\nB = BigDecimal.valueOf(2.3); \n" }, { "code": null, "e": 28760, "s": 28651, "text": "If you are given a String representation of a double number then you can initialize in the following manner:" }, { "code": null, "e": 28833, "s": 28760, "text": "A = new BigDecimal(“5.4”);\nB = new BigDecimal(“1238126387123.1234”); \n" }, { "code": null, "e": 28909, "s": 28833, "text": "For ease of initialization BigDecimal class has some pre-defined constants:" }, { "code": null, "e": 29013, "s": 28909, "text": "A = BigDecimal.ONE;\n// Other than this, available constants\n// are BigDecimal.ZERO and BigDecimal.TEN \n" }, { "code": null, "e": 29038, "s": 29013, "text": "Mathematical operations:" }, { "code": null, "e": 29148, "s": 29038, "text": "int c = a + b;\nBigDecimal C = A.add(B); \nOther similar function are subtract() , multiply(), divide(), pow()\n" }, { "code": null, "e": 29387, "s": 29148, "text": "But all these functions, except pow() which takes integer as its argument, take BigDecimal as their argument so if we want these operation with decimals or string convert them to BigDecimal before passing them to functions as shown below:" }, { "code": null, "e": 29553, "s": 29387, "text": "String str = “123456789.123456789”;\nBigDecimal C = A.add(new BigBigDecimal(str));\ndouble val = 123456789.123456789;\nBigDecimal C = A.add(BigDecimal.valueOf(val)); \n" }, { "code": null, "e": 29590, "s": 29553, "text": "Extraction of value from BigDecimal:" }, { "code": null, "e": 29746, "s": 29590, "text": "// value should be in limit of double x\ndouble x = A.doubleValue(); \n\n// To get string representation of BigDecimal A\nString z = A.toString(); \n" }, { "code": null, "e": 29758, "s": 29746, "text": "Comparison:" }, { "code": null, "e": 29851, "s": 29758, "text": "if (a < b) {} // For primitive double\nif (A.compareTo(B) < 0) {} // For BigDecimal\n" }, { "code": null, "e": 29940, "s": 29851, "text": "Actually compareTo returns -1(less than), 0(Equal), 1(greater than) according to values." }, { "code": null, "e": 29970, "s": 29940, "text": "For equality we can also use:" }, { "code": null, "e": 30012, "s": 29970, "text": "if (A.equals(B)) {} // A is equal to B \n" }, { "code": null, "e": 30041, "s": 30012, "text": "Methods of BigDecimal Class:" }, { "code": null, "e": 37907, "s": 30041, "text": "BigDecimal abs​(): This method returns a BigDecimal whose value is the absolute value of this BigDecimal, and whose scale is this.scale().BigDecimal abs​(MathContext mc): This method returns a BigDecimal whose value is the absolute value of this BigDecimal, with rounding according to the context settings.BigDecimal add​(BigDecimal augend): This method returns a BigDecimal whose value is (this + augend), and whose scale is max(this.scale(), augend.scale()).BigDecimal add​(BigDecimal augend, MathContext mc): This method returns a BigDecimal whose value is (this + augend), with rounding according to the context settings.byte byteValueExact​(): This method converts this BigDecimal to a byte, checking for lost information.int compareTo​(BigDecimal val): This method compares this BigDecimal with the specified BigDecimal.BigDecimal divide​(BigDecimal divisor): This method returns a BigDecimal whose value is (this / divisor), and whose preferred scale is (this.scale() – divisor.scale()); if the exact quotient cannot be represented (because it has a non-terminating decimal expansion) an ArithmeticException is thrown.BigDecimal divide​(BigDecimal divisor, int scale, RoundingMode roundingMode): This method returns a BigDecimal whose value is (this / divisor), and whose scale is as specified.BigDecimal divide​(BigDecimal divisor, MathContext mc): This method returns a BigDecimal whose value is (this / divisor), with rounding according to the context settings.BigDecimal divide​(BigDecimal divisor, RoundingMode roundingMode): This method returns a BigDecimal whose value is (this / divisor), and whose scale is this.scale().BigDecimal[] divideAndRemainder​(BigDecimal divisor): This method returns a two-element BigDecimal array containing the result of divideToIntegralValue followed by the result of remainder on the two operands.BigDecimal[] divideAndRemainder​(BigDecimal divisor, MathContext mc): This method returns a two-element BigDecimal array containing the result of divideToIntegralValue followed by the result of remainder on the two operands calculated with rounding according to the context settings.BigDecimal divideToIntegralValue​(BigDecimal divisor): This method returns a BigDecimal whose value is the integer part of the quotient (this / divisor) rounded down.BigDecimal divideToIntegralValue​(BigDecimal divisor, MathContext mc): This method returns a BigDecimal whose value is the integer part of (this / divisor).double doubleValue​(): This method converts this BigDecimal to a double.boolean equals​(Object x): This method compares this BigDecimal with the specified Object for equality.float floatValue​(): This method converts this BigDecimal to a float.int hashCode​(): This method returns the hash code for this BigDecimal.int intValue​(): This method converts this BigDecimal to an int.int intValueExact​(): This method converts this BigDecimal to an int, checking for lost information.long longValue​(): This method converts this BigDecimal to a long.long longValueExact​(): This method converts this BigDecimal to a long, checking for lost information.BigDecimal max​(BigDecimal val): This method returns the maximum of this BigDecimal and val.BigDecimal min​(BigDecimal val): This method returns the minimum of this BigDecimal and val.BigDecimal movePointLeft​(int n): This method returns a BigDecimal which is equivalent to this one with the decimal point moved n places to the left.BigDecimal movePointRight​(int n): This method returns a BigDecimal which is equivalent to this one with the decimal point moved n places to the right.BigDecimal multiply​(BigDecimal multiplicand): This method returns a BigDecimal whose value is (this × multiplicand), and whose scale is (this.scale() + multiplicand.scale()).BigDecimal multiply​(BigDecimal multiplicand, MathContext mc): This method returns a BigDecimal whose value is (this × multiplicand), with rounding according to the context settings.BigDecimal negate​(): This method returns a BigDecimal whose value is (-this), and whose scale is this.scale().BigDecimal negate​(MathContext mc): This method returns a BigDecimal whose value is (-this), with rounding according to the context settings.BigDecimal plus​(): This method returns a BigDecimal whose value is (+this), and whose scale is this.scale().BigDecimal plus​(MathContext mc): This method returns a BigDecimal whose value is (+this), with rounding according to the context settings.BigDecimal pow​(int n): This method returns a BigDecimal whose value is (thisn), The power is computed exactly, to unlimited precision.BigDecimal pow​(int n, MathContext mc): This method returns a BigDecimal whose value is (thisn).int precision​(): This method returns the precision of this BigDecimal.BigDecimal remainder​(BigDecimal divisor): This method returns a BigDecimal whose value is (this % divisor).BigDecimal remainder​(BigDecimal divisor, MathContext mc): This method returns a BigDecimal whose value is (this % divisor), with rounding according to the context settings.BigDecimal round​(MathContext mc): This method returns a BigDecimal rounded according to the MathContext settings.int scale​(): This method returns the scale of this BigDecimal.BigDecimal scaleByPowerOfTen​(int n): This method returns a BigDecimal whose numerical value is equal to (this * 10n).BigDecimal setScale​(int newScale): This method returns a BigDecimal whose scale is the specified value, and whose value is numerically equal to this BigDecimal’s.BigDecimal setScale​(int newScale, RoundingMode roundingMode): This method returns a BigDecimal whose scale is the specified value, and whose unscaled value is determined by multiplying or dividing this BigDecimal’s unscaled value by the appropriate power of ten to maintain its overall value.short shortValueExact​(): This method converts this BigDecimal to a short, checking for lost information.int signum​(): This method returns the signum function of this BigDecimal.BigDecimal sqrt​(MathContext mc): This method returns an approximation to the square root of this with rounding according to the context settings.BigDecimal stripTrailingZeros​(): This method returns a BigDecimal which is numerically equal to this one but with any trailing zeros removed from the representation.BigDecimal subtract​(BigDecimal subtrahend): This method returns a BigDecimal whose value is (this – subtrahend), and whose scale is max(this.scale(), subtrahend.scale()).BigDecimal subtract​(BigDecimal subtrahend, MathContext mc): This method returns a BigDecimal whose value is (this – subtrahend), with rounding according to the context settings.BigInteger toBigInteger​(): This method converts this BigDecimal to a BigInteger.BigInteger toBigIntegerExact​(): This method converts this BigDecimal to a BigInteger, checking for lost information.String toEngineeringString​(): This method returns a string representation of this BigDecimal, using engineering notation if an exponent is needed.String toPlainString​(): This method returns a string representation of this BigDecimal without an exponent field.String toString​(): This method returns the string representation of this BigDecimal, using scientific notation if an exponent is needed.BigDecimal ulp​(): This method returns the size of an ulp, a unit in the last place, of this BigDecimal.BigInteger unscaledValue​(): This method returns a BigInteger whose value is the unscaled value of this BigDecimal.static BigDecimal valueOf​(double val): This method translates a double into a BigDecimal, using the double’s canonical string representation provided by the Double.toString(double) method.static BigDecimal valueOf​(long val): This method translates a long value into a BigDecimal with a scale of zero.static BigDecimal valueOf​(long unscaledVal, int scale): This method translates a long unscaled value and an int scale into a BigDecimal." }, { "code": null, "e": 38046, "s": 37907, "text": "BigDecimal abs​(): This method returns a BigDecimal whose value is the absolute value of this BigDecimal, and whose scale is this.scale()." }, { "code": null, "e": 38215, "s": 38046, "text": "BigDecimal abs​(MathContext mc): This method returns a BigDecimal whose value is the absolute value of this BigDecimal, with rounding according to the context settings." }, { "code": null, "e": 38370, "s": 38215, "text": "BigDecimal add​(BigDecimal augend): This method returns a BigDecimal whose value is (this + augend), and whose scale is max(this.scale(), augend.scale())." }, { "code": null, "e": 38536, "s": 38370, "text": "BigDecimal add​(BigDecimal augend, MathContext mc): This method returns a BigDecimal whose value is (this + augend), with rounding according to the context settings." }, { "code": null, "e": 38639, "s": 38536, "text": "byte byteValueExact​(): This method converts this BigDecimal to a byte, checking for lost information." }, { "code": null, "e": 38739, "s": 38639, "text": "int compareTo​(BigDecimal val): This method compares this BigDecimal with the specified BigDecimal." }, { "code": null, "e": 39039, "s": 38739, "text": "BigDecimal divide​(BigDecimal divisor): This method returns a BigDecimal whose value is (this / divisor), and whose preferred scale is (this.scale() – divisor.scale()); if the exact quotient cannot be represented (because it has a non-terminating decimal expansion) an ArithmeticException is thrown." }, { "code": null, "e": 39216, "s": 39039, "text": "BigDecimal divide​(BigDecimal divisor, int scale, RoundingMode roundingMode): This method returns a BigDecimal whose value is (this / divisor), and whose scale is as specified." }, { "code": null, "e": 39387, "s": 39216, "text": "BigDecimal divide​(BigDecimal divisor, MathContext mc): This method returns a BigDecimal whose value is (this / divisor), with rounding according to the context settings." }, { "code": null, "e": 39553, "s": 39387, "text": "BigDecimal divide​(BigDecimal divisor, RoundingMode roundingMode): This method returns a BigDecimal whose value is (this / divisor), and whose scale is this.scale()." }, { "code": null, "e": 39762, "s": 39553, "text": "BigDecimal[] divideAndRemainder​(BigDecimal divisor): This method returns a two-element BigDecimal array containing the result of divideToIntegralValue followed by the result of remainder on the two operands." }, { "code": null, "e": 40046, "s": 39762, "text": "BigDecimal[] divideAndRemainder​(BigDecimal divisor, MathContext mc): This method returns a two-element BigDecimal array containing the result of divideToIntegralValue followed by the result of remainder on the two operands calculated with rounding according to the context settings." }, { "code": null, "e": 40213, "s": 40046, "text": "BigDecimal divideToIntegralValue​(BigDecimal divisor): This method returns a BigDecimal whose value is the integer part of the quotient (this / divisor) rounded down." }, { "code": null, "e": 40370, "s": 40213, "text": "BigDecimal divideToIntegralValue​(BigDecimal divisor, MathContext mc): This method returns a BigDecimal whose value is the integer part of (this / divisor)." }, { "code": null, "e": 40443, "s": 40370, "text": "double doubleValue​(): This method converts this BigDecimal to a double." }, { "code": null, "e": 40547, "s": 40443, "text": "boolean equals​(Object x): This method compares this BigDecimal with the specified Object for equality." }, { "code": null, "e": 40617, "s": 40547, "text": "float floatValue​(): This method converts this BigDecimal to a float." }, { "code": null, "e": 40689, "s": 40617, "text": "int hashCode​(): This method returns the hash code for this BigDecimal." }, { "code": null, "e": 40754, "s": 40689, "text": "int intValue​(): This method converts this BigDecimal to an int." }, { "code": null, "e": 40855, "s": 40754, "text": "int intValueExact​(): This method converts this BigDecimal to an int, checking for lost information." }, { "code": null, "e": 40922, "s": 40855, "text": "long longValue​(): This method converts this BigDecimal to a long." }, { "code": null, "e": 41025, "s": 40922, "text": "long longValueExact​(): This method converts this BigDecimal to a long, checking for lost information." }, { "code": null, "e": 41118, "s": 41025, "text": "BigDecimal max​(BigDecimal val): This method returns the maximum of this BigDecimal and val." }, { "code": null, "e": 41211, "s": 41118, "text": "BigDecimal min​(BigDecimal val): This method returns the minimum of this BigDecimal and val." }, { "code": null, "e": 41361, "s": 41211, "text": "BigDecimal movePointLeft​(int n): This method returns a BigDecimal which is equivalent to this one with the decimal point moved n places to the left." }, { "code": null, "e": 41513, "s": 41361, "text": "BigDecimal movePointRight​(int n): This method returns a BigDecimal which is equivalent to this one with the decimal point moved n places to the right." }, { "code": null, "e": 41689, "s": 41513, "text": "BigDecimal multiply​(BigDecimal multiplicand): This method returns a BigDecimal whose value is (this × multiplicand), and whose scale is (this.scale() + multiplicand.scale())." }, { "code": null, "e": 41872, "s": 41689, "text": "BigDecimal multiply​(BigDecimal multiplicand, MathContext mc): This method returns a BigDecimal whose value is (this × multiplicand), with rounding according to the context settings." }, { "code": null, "e": 41984, "s": 41872, "text": "BigDecimal negate​(): This method returns a BigDecimal whose value is (-this), and whose scale is this.scale()." }, { "code": null, "e": 42126, "s": 41984, "text": "BigDecimal negate​(MathContext mc): This method returns a BigDecimal whose value is (-this), with rounding according to the context settings." }, { "code": null, "e": 42236, "s": 42126, "text": "BigDecimal plus​(): This method returns a BigDecimal whose value is (+this), and whose scale is this.scale()." }, { "code": null, "e": 42376, "s": 42236, "text": "BigDecimal plus​(MathContext mc): This method returns a BigDecimal whose value is (+this), with rounding according to the context settings." }, { "code": null, "e": 42512, "s": 42376, "text": "BigDecimal pow​(int n): This method returns a BigDecimal whose value is (thisn), The power is computed exactly, to unlimited precision." }, { "code": null, "e": 42609, "s": 42512, "text": "BigDecimal pow​(int n, MathContext mc): This method returns a BigDecimal whose value is (thisn)." }, { "code": null, "e": 42681, "s": 42609, "text": "int precision​(): This method returns the precision of this BigDecimal." }, { "code": null, "e": 42790, "s": 42681, "text": "BigDecimal remainder​(BigDecimal divisor): This method returns a BigDecimal whose value is (this % divisor)." }, { "code": null, "e": 42964, "s": 42790, "text": "BigDecimal remainder​(BigDecimal divisor, MathContext mc): This method returns a BigDecimal whose value is (this % divisor), with rounding according to the context settings." }, { "code": null, "e": 43079, "s": 42964, "text": "BigDecimal round​(MathContext mc): This method returns a BigDecimal rounded according to the MathContext settings." }, { "code": null, "e": 43143, "s": 43079, "text": "int scale​(): This method returns the scale of this BigDecimal." }, { "code": null, "e": 43262, "s": 43143, "text": "BigDecimal scaleByPowerOfTen​(int n): This method returns a BigDecimal whose numerical value is equal to (this * 10n)." }, { "code": null, "e": 43426, "s": 43262, "text": "BigDecimal setScale​(int newScale): This method returns a BigDecimal whose scale is the specified value, and whose value is numerically equal to this BigDecimal’s." }, { "code": null, "e": 43720, "s": 43426, "text": "BigDecimal setScale​(int newScale, RoundingMode roundingMode): This method returns a BigDecimal whose scale is the specified value, and whose unscaled value is determined by multiplying or dividing this BigDecimal’s unscaled value by the appropriate power of ten to maintain its overall value." }, { "code": null, "e": 43826, "s": 43720, "text": "short shortValueExact​(): This method converts this BigDecimal to a short, checking for lost information." }, { "code": null, "e": 43901, "s": 43826, "text": "int signum​(): This method returns the signum function of this BigDecimal." }, { "code": null, "e": 44048, "s": 43901, "text": "BigDecimal sqrt​(MathContext mc): This method returns an approximation to the square root of this with rounding according to the context settings." }, { "code": null, "e": 44215, "s": 44048, "text": "BigDecimal stripTrailingZeros​(): This method returns a BigDecimal which is numerically equal to this one but with any trailing zeros removed from the representation." }, { "code": null, "e": 44387, "s": 44215, "text": "BigDecimal subtract​(BigDecimal subtrahend): This method returns a BigDecimal whose value is (this – subtrahend), and whose scale is max(this.scale(), subtrahend.scale())." }, { "code": null, "e": 44566, "s": 44387, "text": "BigDecimal subtract​(BigDecimal subtrahend, MathContext mc): This method returns a BigDecimal whose value is (this – subtrahend), with rounding according to the context settings." }, { "code": null, "e": 44648, "s": 44566, "text": "BigInteger toBigInteger​(): This method converts this BigDecimal to a BigInteger." }, { "code": null, "e": 44766, "s": 44648, "text": "BigInteger toBigIntegerExact​(): This method converts this BigDecimal to a BigInteger, checking for lost information." }, { "code": null, "e": 44914, "s": 44766, "text": "String toEngineeringString​(): This method returns a string representation of this BigDecimal, using engineering notation if an exponent is needed." }, { "code": null, "e": 45029, "s": 44914, "text": "String toPlainString​(): This method returns a string representation of this BigDecimal without an exponent field." }, { "code": null, "e": 45167, "s": 45029, "text": "String toString​(): This method returns the string representation of this BigDecimal, using scientific notation if an exponent is needed." }, { "code": null, "e": 45272, "s": 45167, "text": "BigDecimal ulp​(): This method returns the size of an ulp, a unit in the last place, of this BigDecimal." }, { "code": null, "e": 45388, "s": 45272, "text": "BigInteger unscaledValue​(): This method returns a BigInteger whose value is the unscaled value of this BigDecimal." }, { "code": null, "e": 45578, "s": 45388, "text": "static BigDecimal valueOf​(double val): This method translates a double into a BigDecimal, using the double’s canonical string representation provided by the Double.toString(double) method." }, { "code": null, "e": 45692, "s": 45578, "text": "static BigDecimal valueOf​(long val): This method translates a long value into a BigDecimal with a scale of zero." }, { "code": null, "e": 45830, "s": 45692, "text": "static BigDecimal valueOf​(long unscaledVal, int scale): This method translates a long unscaled value and an int scale into a BigDecimal." }, { "code": null, "e": 45896, "s": 45830, "text": "For more examples visit Java BigDecimal ExamplesRelated Articles:" }, { "code": null, "e": 45969, "s": 45896, "text": "Using BigDecimal in Java to calculate PI number up to 200 decimal digits" }, { "code": null, "e": 46084, "s": 45969, "text": "Make cents with BigDecimalFor more functions and details refer Class BigDecimalMy Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 46138, "s": 46084, "text": "For more functions and details refer Class BigDecimal" }, { "code": null, "e": 46154, "s": 46138, "text": "Java-BigDecimal" }, { "code": null, "e": 46170, "s": 46154, "text": "Java-Data Types" }, { "code": null, "e": 46185, "s": 46170, "text": "Java-Functions" }, { "code": null, "e": 46203, "s": 46185, "text": "Java-math-package" }, { "code": null, "e": 46208, "s": 46203, "text": "Java" }, { "code": null, "e": 46213, "s": 46208, "text": "Java" }, { "code": null, "e": 46311, "s": 46213, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 46326, "s": 46311, "text": "Stream In Java" }, { "code": null, "e": 46345, "s": 46326, "text": "Interfaces in Java" }, { "code": null, "e": 46369, "s": 46345, "text": "Singleton Class in Java" }, { "code": null, "e": 46381, "s": 46369, "text": "Set in Java" }, { "code": null, "e": 46404, "s": 46381, "text": "Multithreading in Java" }, { "code": null, "e": 46424, "s": 46404, "text": "Collections in Java" }, { "code": null, "e": 46448, "s": 46424, "text": "Queue Interface In Java" }, { "code": null, "e": 46476, "s": 46448, "text": "Initializing a List in Java" }, { "code": null, "e": 46495, "s": 46476, "text": "Overriding in Java" } ]
Overview of Room in Android Architecture Components - GeeksforGeeks
09 May, 2021 Room is one of the Jetpack Architecture Components in Android. This provides an abstract layer over the SQLite Database to save and perform the operations on persistent data locally. This is recommended by Google over SQLite Database although the SQLite APIs are more powerful they are fairly low-level, which requires a lot of time and effort to use. But Room makes everything easy and clear to create a Database and perform the operations on it. Cache the relevant pieces of the data so that when the user’s device is offline, they can still browse and view the content offline. Compile-time SQLite query verification preserves the application from crashing. The annotations which it provides minimizes the boilerplate code. This also provides easy integration with the other Architecture Components like LiveData, LifecycleObserver, etc., You can take codelab provided by Google here. Room SQLite Database Class: This provides the main access point to the underlying connection for the application’s persisted data. And this is annotated with @Database.Data Entities: This Represents all the tables from the existing database. And annotated with @Entity.DAO (Data Access Objects): This contains methods to perform the operations on the database. And annotated with @Dao. Database Class: This provides the main access point to the underlying connection for the application’s persisted data. And this is annotated with @Database. Data Entities: This Represents all the tables from the existing database. And annotated with @Entity. DAO (Data Access Objects): This contains methods to perform the operations on the database. And annotated with @Dao. From the image below we can conclude the working of the Room database as The application first gets the Data Access Objects (DAOs) associated with the existing Room Database. After getting DAOs, through DAOs it accesses the entities from the Database Tables. And then it can perform the operations on those entities and persist back the changes to the Database. Step 1: Create an Empty Activity project Create an empty activity Android Studio project. Refer to Android | How to Create/Start a New Project in Android Studio?, to how to create an empty activity Android Studio project. And select Kotlin as language. Step 2: Adding the required dependencies Add the following dependencies to the app-level gradle file. By going to ProjectName -> src -> build.gradle. // room_version may vary def room_version = “2.3.0” implementation “androidx.room:room-runtime:$room_version” kapt “androidx.room:room-compiler:$room_version” implementation “androidx.room:room-ktx:$room_version” testImplementation “androidx.room:room-testing:$room_version” Now creating the components of Room one by one: Note: Here the entities for every interface and classes created are important and to be taken care of. Step 3: Creating Data Entity Create a sample Data class naming User.kt. And invoke the following code which contains entities User as an entity, which represents a row and first_name, last_name, age represents column names of the table. Kotlin import androidx.room.ColumnInfoimport androidx.room.Entityimport androidx.room.PrimaryKey @Entitydata class User( @PrimaryKey(autoGenerate = true) val uid: Int, @ColumnInfo(name = "name") val firstName: String?, @ColumnInfo(name = "city") val lastName: String?) Step 4: Creating Data Access Objects (DAOs): Now create an interface named as UserDao.kt. And invoke the following code which provides various methods which are used by the application to interact with the user. Kotlin import androidx.room.Daoimport androidx.room.Deleteimport androidx.room.Insertimport androidx.room.Query @Daointerface UserDao { @Query("SELECT * FROM user") fun getAll(): List<User> @Query("SELECT * FROM user WHERE uid IN (:userIds)") fun loadAllByIds(userIds: IntArray): List<User> @Insert fun insertAll(vararg users: User) @Delete fun delete(user: User)} Step 5: Creating the Database Now creating the Database which defines the actual application’s database, which is the main access point to the application’s persisted data. This class must satisfy: The class must be abstract.The class should be annotated with @Database.Database class must define an abstract method with zero arguments and returns an instance of DAO. The class must be abstract. The class should be annotated with @Database. Database class must define an abstract method with zero arguments and returns an instance of DAO. Now invoke the following code inside the AppDatabase.kt file. Kotlin import androidx.room.Databaseimport androidx.room.RoomDatabase @Database(entities = arrayOf(User::class), version = 1)abstract class UserDatabase : RoomDatabase() { abstract fun userDao(): UserDao} Step 6: Usage of the Room database Inside the MainActivity.kt file we can create a database, by providing custom names for the database. Kotlin import android.os.Bundleimport androidx.appcompat.app.AppCompatActivityimport androidx.room.Room class MainActivity : AppCompatActivity() { // application's Database name private val DATABASE_NAME: String = "USER_DATABASE" override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // get the instance of the application's database val db = Room.databaseBuilder( applicationContext, UserDatabase::class.java, DATABASE_NAME ).build() // create instance of DAO to access the entities val userDao = db.userDao() // using the same DAO perform the Database operations val users: List<User> = userDao.getAll() }} Note: By using this basic knowledge about Room Database one can build a basic CRUD application using Room Database by referring to How to Perform CRUD Operations in Room Database in Android?. Android-Jetpack Picked Android Kotlin Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Resource Raw Folder in Android Studio Flutter - Custom Bottom Navigation Bar How to Read Data from SQLite Database in Android? How to Post Data to API using Retrofit in Android? Retrofit with Kotlin Coroutine in Android Android UI Layouts Kotlin Array Retrofit with Kotlin Coroutine in Android How to Get Current Location in Android? Kotlin Setters and Getters
[ { "code": null, "e": 26405, "s": 26377, "text": "\n09 May, 2021" }, { "code": null, "e": 26853, "s": 26405, "text": "Room is one of the Jetpack Architecture Components in Android. This provides an abstract layer over the SQLite Database to save and perform the operations on persistent data locally. This is recommended by Google over SQLite Database although the SQLite APIs are more powerful they are fairly low-level, which requires a lot of time and effort to use. But Room makes everything easy and clear to create a Database and perform the operations on it." }, { "code": null, "e": 26986, "s": 26853, "text": "Cache the relevant pieces of the data so that when the user’s device is offline, they can still browse and view the content offline." }, { "code": null, "e": 27066, "s": 26986, "text": "Compile-time SQLite query verification preserves the application from crashing." }, { "code": null, "e": 27132, "s": 27066, "text": "The annotations which it provides minimizes the boilerplate code." }, { "code": null, "e": 27293, "s": 27132, "text": "This also provides easy integration with the other Architecture Components like LiveData, LifecycleObserver, etc., You can take codelab provided by Google here." }, { "code": null, "e": 27298, "s": 27293, "text": "Room" }, { "code": null, "e": 27306, "s": 27298, "text": "SQLite " }, { "code": null, "e": 27680, "s": 27306, "text": "Database Class: This provides the main access point to the underlying connection for the application’s persisted data. And this is annotated with @Database.Data Entities: This Represents all the tables from the existing database. And annotated with @Entity.DAO (Data Access Objects): This contains methods to perform the operations on the database. And annotated with @Dao." }, { "code": null, "e": 27837, "s": 27680, "text": "Database Class: This provides the main access point to the underlying connection for the application’s persisted data. And this is annotated with @Database." }, { "code": null, "e": 27939, "s": 27837, "text": "Data Entities: This Represents all the tables from the existing database. And annotated with @Entity." }, { "code": null, "e": 28056, "s": 27939, "text": "DAO (Data Access Objects): This contains methods to perform the operations on the database. And annotated with @Dao." }, { "code": null, "e": 28418, "s": 28056, "text": "From the image below we can conclude the working of the Room database as The application first gets the Data Access Objects (DAOs) associated with the existing Room Database. After getting DAOs, through DAOs it accesses the entities from the Database Tables. And then it can perform the operations on those entities and persist back the changes to the Database." }, { "code": null, "e": 28459, "s": 28418, "text": "Step 1: Create an Empty Activity project" }, { "code": null, "e": 28640, "s": 28459, "text": "Create an empty activity Android Studio project. Refer to Android | How to Create/Start a New Project in Android Studio?, to how to create an empty activity Android Studio project." }, { "code": null, "e": 28671, "s": 28640, "text": "And select Kotlin as language." }, { "code": null, "e": 28712, "s": 28671, "text": "Step 2: Adding the required dependencies" }, { "code": null, "e": 28821, "s": 28712, "text": "Add the following dependencies to the app-level gradle file. By going to ProjectName -> src -> build.gradle." }, { "code": null, "e": 28846, "s": 28821, "text": "// room_version may vary" }, { "code": null, "e": 28873, "s": 28846, "text": "def room_version = “2.3.0”" }, { "code": null, "e": 28931, "s": 28873, "text": "implementation “androidx.room:room-runtime:$room_version”" }, { "code": null, "e": 28980, "s": 28931, "text": "kapt “androidx.room:room-compiler:$room_version”" }, { "code": null, "e": 29034, "s": 28980, "text": "implementation “androidx.room:room-ktx:$room_version”" }, { "code": null, "e": 29096, "s": 29034, "text": "testImplementation “androidx.room:room-testing:$room_version”" }, { "code": null, "e": 29144, "s": 29096, "text": "Now creating the components of Room one by one:" }, { "code": null, "e": 29247, "s": 29144, "text": "Note: Here the entities for every interface and classes created are important and to be taken care of." }, { "code": null, "e": 29276, "s": 29247, "text": "Step 3: Creating Data Entity" }, { "code": null, "e": 29319, "s": 29276, "text": "Create a sample Data class naming User.kt." }, { "code": null, "e": 29484, "s": 29319, "text": "And invoke the following code which contains entities User as an entity, which represents a row and first_name, last_name, age represents column names of the table." }, { "code": null, "e": 29491, "s": 29484, "text": "Kotlin" }, { "code": "import androidx.room.ColumnInfoimport androidx.room.Entityimport androidx.room.PrimaryKey @Entitydata class User( @PrimaryKey(autoGenerate = true) val uid: Int, @ColumnInfo(name = \"name\") val firstName: String?, @ColumnInfo(name = \"city\") val lastName: String?)", "e": 29763, "s": 29491, "text": null }, { "code": null, "e": 29808, "s": 29763, "text": "Step 4: Creating Data Access Objects (DAOs):" }, { "code": null, "e": 29853, "s": 29808, "text": "Now create an interface named as UserDao.kt." }, { "code": null, "e": 29975, "s": 29853, "text": "And invoke the following code which provides various methods which are used by the application to interact with the user." }, { "code": null, "e": 29982, "s": 29975, "text": "Kotlin" }, { "code": "import androidx.room.Daoimport androidx.room.Deleteimport androidx.room.Insertimport androidx.room.Query @Daointerface UserDao { @Query(\"SELECT * FROM user\") fun getAll(): List<User> @Query(\"SELECT * FROM user WHERE uid IN (:userIds)\") fun loadAllByIds(userIds: IntArray): List<User> @Insert fun insertAll(vararg users: User) @Delete fun delete(user: User)}", "e": 30371, "s": 29982, "text": null }, { "code": null, "e": 30401, "s": 30371, "text": "Step 5: Creating the Database" }, { "code": null, "e": 30569, "s": 30401, "text": "Now creating the Database which defines the actual application’s database, which is the main access point to the application’s persisted data. This class must satisfy:" }, { "code": null, "e": 30739, "s": 30569, "text": "The class must be abstract.The class should be annotated with @Database.Database class must define an abstract method with zero arguments and returns an instance of DAO." }, { "code": null, "e": 30767, "s": 30739, "text": "The class must be abstract." }, { "code": null, "e": 30813, "s": 30767, "text": "The class should be annotated with @Database." }, { "code": null, "e": 30911, "s": 30813, "text": "Database class must define an abstract method with zero arguments and returns an instance of DAO." }, { "code": null, "e": 30973, "s": 30911, "text": "Now invoke the following code inside the AppDatabase.kt file." }, { "code": null, "e": 30980, "s": 30973, "text": "Kotlin" }, { "code": "import androidx.room.Databaseimport androidx.room.RoomDatabase @Database(entities = arrayOf(User::class), version = 1)abstract class UserDatabase : RoomDatabase() { abstract fun userDao(): UserDao}", "e": 31182, "s": 30980, "text": null }, { "code": null, "e": 31217, "s": 31182, "text": "Step 6: Usage of the Room database" }, { "code": null, "e": 31319, "s": 31217, "text": "Inside the MainActivity.kt file we can create a database, by providing custom names for the database." }, { "code": null, "e": 31326, "s": 31319, "text": "Kotlin" }, { "code": "import android.os.Bundleimport androidx.appcompat.app.AppCompatActivityimport androidx.room.Room class MainActivity : AppCompatActivity() { // application's Database name private val DATABASE_NAME: String = \"USER_DATABASE\" override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // get the instance of the application's database val db = Room.databaseBuilder( applicationContext, UserDatabase::class.java, DATABASE_NAME ).build() // create instance of DAO to access the entities val userDao = db.userDao() // using the same DAO perform the Database operations val users: List<User> = userDao.getAll() }}", "e": 32098, "s": 31326, "text": null }, { "code": null, "e": 32290, "s": 32098, "text": "Note: By using this basic knowledge about Room Database one can build a basic CRUD application using Room Database by referring to How to Perform CRUD Operations in Room Database in Android?." }, { "code": null, "e": 32306, "s": 32290, "text": "Android-Jetpack" }, { "code": null, "e": 32313, "s": 32306, "text": "Picked" }, { "code": null, "e": 32321, "s": 32313, "text": "Android" }, { "code": null, "e": 32328, "s": 32321, "text": "Kotlin" }, { "code": null, "e": 32336, "s": 32328, "text": "Android" }, { "code": null, "e": 32434, "s": 32336, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32472, "s": 32434, "text": "Resource Raw Folder in Android Studio" }, { "code": null, "e": 32511, "s": 32472, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 32561, "s": 32511, "text": "How to Read Data from SQLite Database in Android?" }, { "code": null, "e": 32612, "s": 32561, "text": "How to Post Data to API using Retrofit in Android?" }, { "code": null, "e": 32654, "s": 32612, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 32673, "s": 32654, "text": "Android UI Layouts" }, { "code": null, "e": 32686, "s": 32673, "text": "Kotlin Array" }, { "code": null, "e": 32728, "s": 32686, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 32768, "s": 32728, "text": "How to Get Current Location in Android?" } ]
batch command in Linux with Examples - GeeksforGeeks
15 May, 2019 batch command is used to read commands from standard input or a specified file and execute them when system load levels permit i.e. when the load average drops below 1.5. Syntax: batch It is important to note that batch does not accepts any parameters. Other Similar Commands: atq: Used to display the queue of pending jobs(this is because at and batch both uses the same job queue). atrm: Used to remove the specified job from job queue. Example: Working with the batch command.top top Executing some commands using batch.See the average load is lower than 1.5 that’s why the job queue is empty and command executed instantly.Use ctrl +d when done giving commands to batch. See the average load is lower than 1.5 that’s why the job queue is empty and command executed instantly. Use ctrl +d when done giving commands to batch. Linux-batch-commands linux-command Picked Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. scp command in Linux with Examples mv command in Linux with examples Docker - COPY Instruction SED command in Linux | Set 2 chown command in Linux with Examples nohup Command in Linux with Examples Named Pipe or FIFO with example C program Thread functions in C/C++ uniq Command in LINUX with examples Start/Stop/Restart Services Using Systemctl in Linux
[ { "code": null, "e": 25651, "s": 25623, "text": "\n15 May, 2019" }, { "code": null, "e": 25822, "s": 25651, "text": "batch command is used to read commands from standard input or a specified file and execute them when system load levels permit i.e. when the load average drops below 1.5." }, { "code": null, "e": 25830, "s": 25822, "text": "Syntax:" }, { "code": null, "e": 25836, "s": 25830, "text": "batch" }, { "code": null, "e": 25904, "s": 25836, "text": "It is important to note that batch does not accepts any parameters." }, { "code": null, "e": 25928, "s": 25904, "text": "Other Similar Commands:" }, { "code": null, "e": 26035, "s": 25928, "text": "atq: Used to display the queue of pending jobs(this is because at and batch both uses the same job queue)." }, { "code": null, "e": 26090, "s": 26035, "text": "atrm: Used to remove the specified job from job queue." }, { "code": null, "e": 26099, "s": 26090, "text": "Example:" }, { "code": null, "e": 26134, "s": 26099, "text": "Working with the batch command.top" }, { "code": null, "e": 26138, "s": 26134, "text": "top" }, { "code": null, "e": 26326, "s": 26138, "text": "Executing some commands using batch.See the average load is lower than 1.5 that’s why the job queue is empty and command executed instantly.Use ctrl +d when done giving commands to batch." }, { "code": null, "e": 26431, "s": 26326, "text": "See the average load is lower than 1.5 that’s why the job queue is empty and command executed instantly." }, { "code": null, "e": 26479, "s": 26431, "text": "Use ctrl +d when done giving commands to batch." }, { "code": null, "e": 26500, "s": 26479, "text": "Linux-batch-commands" }, { "code": null, "e": 26514, "s": 26500, "text": "linux-command" }, { "code": null, "e": 26521, "s": 26514, "text": "Picked" }, { "code": null, "e": 26532, "s": 26521, "text": "Linux-Unix" }, { "code": null, "e": 26630, "s": 26532, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26665, "s": 26630, "text": "scp command in Linux with Examples" }, { "code": null, "e": 26699, "s": 26665, "text": "mv command in Linux with examples" }, { "code": null, "e": 26725, "s": 26699, "text": "Docker - COPY Instruction" }, { "code": null, "e": 26754, "s": 26725, "text": "SED command in Linux | Set 2" }, { "code": null, "e": 26791, "s": 26754, "text": "chown command in Linux with Examples" }, { "code": null, "e": 26828, "s": 26791, "text": "nohup Command in Linux with Examples" }, { "code": null, "e": 26870, "s": 26828, "text": "Named Pipe or FIFO with example C program" }, { "code": null, "e": 26896, "s": 26870, "text": "Thread functions in C/C++" }, { "code": null, "e": 26932, "s": 26896, "text": "uniq Command in LINUX with examples" } ]
Generate QR code using AngularJS - GeeksforGeeks
10 Mar, 2021 In this article, we will see how to generate and display QR codes in our Angular apps. A QR code is a matrix of black and white squares that can be read by a camera or a smartphone. A QR code can store information and URLs that make it easy to read for a bot or smartphone user. In a business scenario, QR codes can be used to share contact information, send emails, download apps, share URLs and location. Hence, we need to know how to generate one for our apps to keep up with the market. Prerequisites: NPM must be installed Environment Setup: Install angular CLI and create a new angular project. npm i -g @angular/cli ng new <project-name> cd <project-name> Now, verify the installation by serving the app on localhost: ng serve -o You should see the landing page of angular, and you are good to go. Now we need to install and register an additional package: npm install @techiediaries/ngx-qrcode Register it in app.module.ts. Make changes or copy the code below in app.module.ts file in app folder. app.module.ts import { NgModule } from '@angular/core';import { BrowserModule } from '@angular/platform-browser';import { AppRoutingModule } from './app-routing.module';import { AppComponent } from './app.component'; // Import this module import {NgxQRCodeModule} from '@techiediaries/ngx-qrcode' @NgModule({ declarations: [ AppComponent, ], imports: [ BrowserModule, AppRoutingModule, NgxQRCodeModule // Register the module ], providers: [], bootstrap: [AppComponent]})export class AppModule { } Now lets create a new component to display the QR code with the required data. ng generate component qrcode This will generate 4 new files. Additionally, it will update the file app.module.ts by registering the component automatically. Now add the following code in qrcode.component.ts : qrcode.component.ts import { Component, OnInit } from '@angular/core';@Component({ selector: 'app-qrcode', templateUrl: './qrcode.component.html', styleUrls: ['./qrcode.component.css']})export class QrcodeComponent{ elementType = 'url'; data = 'https://geeksforgeeks.org/';} Here elementType can be ‘url’, ‘img’ or ‘canvas’. The url type can encode string type data. The data variable stores the data we want to encode. Now add the following code to qrcode.component.html: qrcode.component.html <ngx-qrcode [elementType]="elementType" [value]="data"></ngx-qrcode> We have used the ngx-qrcode tag to place a component. It takes the previous data as input. Now add this component in app.component.html : app.component.html <div> <app-qrcode></app-qrcode></div> We can check it by starting the app : ng serve -o Open http://localhost:4200/ on your browser. You should see the following output. You can validate it by scanning the code using any app. Encoding the JSON data: We can also embed JSON data into the QR code. First we need to create object that we want to embed. Note that we can only embed string data when using ‘url’ elementType. So we can create a string of this object using JSON.stringify(). See the code below for qrcode.component.ts to understand better: qrcode.component.ts import { Component, OnInit } from '@angular/core';@Component({ selector: 'app-qrcode', templateUrl: './qrcode.component.html', styleUrls: ['./qrcode.component.css']})export class QrcodeComponent{ elementType = 'url'; obj = { cellTowers: [ { cellId: 170402199, locationAreaCode: 35632, mobileCountryCode: 310, mobileNetworkCode: 410, age: 0, signalStrength: -60, timingAdvance: 15 } ] } data = JSON.stringify(this.obj);} Output: AngularJS-Questions AngularJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Angular PrimeNG Dropdown Component Angular PrimeNG Calendar Component Angular 10 (blur) Event Angular PrimeNG Messages Component How to make a Bootstrap Modal Popup in Angular 9/8 ? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills
[ { "code": null, "e": 26378, "s": 26350, "text": "\n10 Mar, 2021" }, { "code": null, "e": 26869, "s": 26378, "text": "In this article, we will see how to generate and display QR codes in our Angular apps. A QR code is a matrix of black and white squares that can be read by a camera or a smartphone. A QR code can store information and URLs that make it easy to read for a bot or smartphone user. In a business scenario, QR codes can be used to share contact information, send emails, download apps, share URLs and location. Hence, we need to know how to generate one for our apps to keep up with the market." }, { "code": null, "e": 26906, "s": 26869, "text": "Prerequisites: NPM must be installed" }, { "code": null, "e": 26925, "s": 26906, "text": "Environment Setup:" }, { "code": null, "e": 26979, "s": 26925, "text": "Install angular CLI and create a new angular project." }, { "code": null, "e": 27041, "s": 26979, "text": "npm i -g @angular/cli\nng new <project-name>\ncd <project-name>" }, { "code": null, "e": 27103, "s": 27041, "text": "Now, verify the installation by serving the app on localhost:" }, { "code": null, "e": 27115, "s": 27103, "text": "ng serve -o" }, { "code": null, "e": 27242, "s": 27115, "text": "You should see the landing page of angular, and you are good to go. Now we need to install and register an additional package:" }, { "code": null, "e": 27280, "s": 27242, "text": "npm install @techiediaries/ngx-qrcode" }, { "code": null, "e": 27383, "s": 27280, "text": "Register it in app.module.ts. Make changes or copy the code below in app.module.ts file in app folder." }, { "code": null, "e": 27397, "s": 27383, "text": "app.module.ts" }, { "code": "import { NgModule } from '@angular/core';import { BrowserModule } from '@angular/platform-browser';import { AppRoutingModule } from './app-routing.module';import { AppComponent } from './app.component'; // Import this module import {NgxQRCodeModule} from '@techiediaries/ngx-qrcode' @NgModule({ declarations: [ AppComponent, ], imports: [ BrowserModule, AppRoutingModule, NgxQRCodeModule // Register the module ], providers: [], bootstrap: [AppComponent]})export class AppModule { }", "e": 27903, "s": 27397, "text": null }, { "code": null, "e": 27982, "s": 27903, "text": "Now lets create a new component to display the QR code with the required data." }, { "code": null, "e": 28011, "s": 27982, "text": "ng generate component qrcode" }, { "code": null, "e": 28191, "s": 28011, "text": "This will generate 4 new files. Additionally, it will update the file app.module.ts by registering the component automatically. Now add the following code in qrcode.component.ts :" }, { "code": null, "e": 28211, "s": 28191, "text": "qrcode.component.ts" }, { "code": "import { Component, OnInit } from '@angular/core';@Component({ selector: 'app-qrcode', templateUrl: './qrcode.component.html', styleUrls: ['./qrcode.component.css']})export class QrcodeComponent{ elementType = 'url'; data = 'https://geeksforgeeks.org/';}", "e": 28472, "s": 28211, "text": null }, { "code": null, "e": 28670, "s": 28472, "text": "Here elementType can be ‘url’, ‘img’ or ‘canvas’. The url type can encode string type data. The data variable stores the data we want to encode. Now add the following code to qrcode.component.html:" }, { "code": null, "e": 28692, "s": 28670, "text": "qrcode.component.html" }, { "code": "<ngx-qrcode [elementType]=\"elementType\" [value]=\"data\"></ngx-qrcode>", "e": 28763, "s": 28692, "text": null }, { "code": null, "e": 28901, "s": 28763, "text": "We have used the ngx-qrcode tag to place a component. It takes the previous data as input. Now add this component in app.component.html :" }, { "code": null, "e": 28920, "s": 28901, "text": "app.component.html" }, { "code": "<div> <app-qrcode></app-qrcode></div>", "e": 28959, "s": 28920, "text": null }, { "code": null, "e": 28997, "s": 28959, "text": "We can check it by starting the app :" }, { "code": null, "e": 29009, "s": 28997, "text": "ng serve -o" }, { "code": null, "e": 29147, "s": 29009, "text": "Open http://localhost:4200/ on your browser. You should see the following output. You can validate it by scanning the code using any app." }, { "code": null, "e": 29471, "s": 29147, "text": "Encoding the JSON data: We can also embed JSON data into the QR code. First we need to create object that we want to embed. Note that we can only embed string data when using ‘url’ elementType. So we can create a string of this object using JSON.stringify(). See the code below for qrcode.component.ts to understand better:" }, { "code": null, "e": 29491, "s": 29471, "text": "qrcode.component.ts" }, { "code": "import { Component, OnInit } from '@angular/core';@Component({ selector: 'app-qrcode', templateUrl: './qrcode.component.html', styleUrls: ['./qrcode.component.css']})export class QrcodeComponent{ elementType = 'url'; obj = { cellTowers: [ { cellId: 170402199, locationAreaCode: 35632, mobileCountryCode: 310, mobileNetworkCode: 410, age: 0, signalStrength: -60, timingAdvance: 15 } ] } data = JSON.stringify(this.obj);}", "e": 29984, "s": 29491, "text": null }, { "code": null, "e": 29992, "s": 29984, "text": "Output:" }, { "code": null, "e": 30014, "s": 29994, "text": "AngularJS-Questions" }, { "code": null, "e": 30024, "s": 30014, "text": "AngularJS" }, { "code": null, "e": 30041, "s": 30024, "text": "Web Technologies" }, { "code": null, "e": 30139, "s": 30041, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30174, "s": 30139, "text": "Angular PrimeNG Dropdown Component" }, { "code": null, "e": 30209, "s": 30174, "text": "Angular PrimeNG Calendar Component" }, { "code": null, "e": 30233, "s": 30209, "text": "Angular 10 (blur) Event" }, { "code": null, "e": 30268, "s": 30233, "text": "Angular PrimeNG Messages Component" }, { "code": null, "e": 30321, "s": 30268, "text": "How to make a Bootstrap Modal Popup in Angular 9/8 ?" }, { "code": null, "e": 30361, "s": 30321, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 30394, "s": 30361, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 30439, "s": 30394, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 30482, "s": 30439, "text": "How to fetch data from an API in ReactJS ?" } ]
HTTP status codes | Client Error Responses - GeeksforGeeks
19 Jul, 2020 The browser and the site server have a conversation in the form of HTTP status codes. The server gives responses to the browser’s request in the form of a three-digit code known as HTTP status codes. The categorization of HTTP status codes is done in five sections which are listed below. Informational responses (100–199)Successful responses (200–299)Redirects (300–399)Client errors (400–499)Server errors (500–599) Informational responses (100–199) Successful responses (200–299) Redirects (300–399) Client errors (400–499) Server errors (500–599) Client Error Responses: 400 Bad Request: This response code occurs when the server could not understand the request because an invalid syntax is used.Status:400 Bad Request 400 Bad Request 401 Unauthorized: This response code occurs when the server refuses to respond to the request because the request lacks client authentication to get the resources.Status:401 Unauthorized 401 Unauthorized 402 Payment Required: The response code 404 is reserved for future use. The aim of creating this response code is for the digital payment system.Status:402 Payment Required 402 Payment Required 403 Forbidden: This response code occurs when the client wants to access the content but it does not have the right to access the content as it is unauthorized.Status:403 Forbidden 403 Forbidden 404 Not Found: This response code occurs when the server cannot find the resources requested by the client. This code can also be sent by the server instead of error 403 to hide the resources from the unauthorized client. Error 404 is one of the most famous response codes on the web.Status:404 Not Found 404 Not Found 405 Method Not Allowed: This response code occurs when the server knows the method of the request but currently it has been disabled by the server.Status:405 Method Not Allowed 405 Method Not Allowed 406 Not Acceptable: This response code occurs when the server does not find the content mentioned in the client request.Status:406 Not Acceptable 406 Not Acceptable 407 Proxy Authentication Required: This response code occurs when it is necessary for the client to authenticate itself with the proxy.Status:407 Proxy Authentication Required 407 Proxy Authentication Required 408 Request Timeout: This response code occurs when the webserver did not receive the required response within the time that it was prepared to wait.Status:408 Request Timeout 408 Request Timeout 409 Conflict: This response code occurs when the server could not complete the request due to conflict in the target resource. The client can resubmit the request by resolving the conflict.Status:409 Conflict 409 Conflict 410 Gone: This response code occurs when the requested resource is permanently deleted from the server and is no longer available.Status:410 Gone 410 Gone 411 Length Required: This response code occurs when the server rejects the request as the request did not have a defined “Content-Length”.Status:411 Length Required 411 Length Required 412 Precondition Failed: This response code occurs when the server evaluates the preconditions given in the request header as false.Status:412 Precondition Failed 412 Precondition Failed 413 Request Entity Too Large: This response code occurs when the server refuses to process the request because the request entity is larger than the server’s ability to process the data.Status:413 Request Entity Too Large 413 Request Entity Too Large 414 Request-URI Too Long: This response code occurs when the client’s requested URI is longer than the ability of the server to interpret the URI.Status:414 Request-URI Too Long 414 Request-URI Too Long 415 Unsupported Media Type: This response code occurs when the server rejects the requested resource because the media format of the requested resource is not supported by the server.Status:415 Unsupported Media Type 415 Unsupported Media Type 416 Requested Range Not Satisfiable: Response code occurs when the request cannot be completed because of the range specified in the Range Header. The range can also be outside the target URI’s data.Status:416 Requested Range Not Satisfiable 416 Requested Range Not Satisfiable 417 Expectation Failed: This response code occurs when the server can’t meet the expectation indicated by the Expect request-header field.Status:416 Requested Range Not Satisfiable 416 Requested Range Not Satisfiable Supported Browsers: The browsers compatible with the HTTP status code Client Error Responses are listed below: Google Chrome Internet Explorer Firefox Safari Opera HTTP- response-status-codes Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React How to create footer to stay at the bottom of a Web page? Node.js fs.readFileSync() Method How to set the default value for an HTML <select> element ? File uploading in React.js How to apply style to parent if it has child with CSS?
[ { "code": null, "e": 26191, "s": 26163, "text": "\n19 Jul, 2020" }, { "code": null, "e": 26480, "s": 26191, "text": "The browser and the site server have a conversation in the form of HTTP status codes. The server gives responses to the browser’s request in the form of a three-digit code known as HTTP status codes. The categorization of HTTP status codes is done in five sections which are listed below." }, { "code": null, "e": 26609, "s": 26480, "text": "Informational responses (100–199)Successful responses (200–299)Redirects (300–399)Client errors (400–499)Server errors (500–599)" }, { "code": null, "e": 26643, "s": 26609, "text": "Informational responses (100–199)" }, { "code": null, "e": 26674, "s": 26643, "text": "Successful responses (200–299)" }, { "code": null, "e": 26694, "s": 26674, "text": "Redirects (300–399)" }, { "code": null, "e": 26718, "s": 26694, "text": "Client errors (400–499)" }, { "code": null, "e": 26742, "s": 26718, "text": "Server errors (500–599)" }, { "code": null, "e": 26766, "s": 26742, "text": "Client Error Responses:" }, { "code": null, "e": 26915, "s": 26766, "text": "400 Bad Request: This response code occurs when the server could not understand the request because an invalid syntax is used.Status:400 Bad Request" }, { "code": null, "e": 26931, "s": 26915, "text": "400 Bad Request" }, { "code": null, "e": 27118, "s": 26931, "text": "401 Unauthorized: This response code occurs when the server refuses to respond to the request because the request lacks client authentication to get the resources.Status:401 Unauthorized" }, { "code": null, "e": 27135, "s": 27118, "text": "401 Unauthorized" }, { "code": null, "e": 27308, "s": 27135, "text": "402 Payment Required: The response code 404 is reserved for future use. The aim of creating this response code is for the digital payment system.Status:402 Payment Required" }, { "code": null, "e": 27329, "s": 27308, "text": "402 Payment Required" }, { "code": null, "e": 27510, "s": 27329, "text": "403 Forbidden: This response code occurs when the client wants to access the content but it does not have the right to access the content as it is unauthorized.Status:403 Forbidden" }, { "code": null, "e": 27524, "s": 27510, "text": "403 Forbidden" }, { "code": null, "e": 27829, "s": 27524, "text": "404 Not Found: This response code occurs when the server cannot find the resources requested by the client. This code can also be sent by the server instead of error 403 to hide the resources from the unauthorized client. Error 404 is one of the most famous response codes on the web.Status:404 Not Found" }, { "code": null, "e": 27843, "s": 27829, "text": "404 Not Found" }, { "code": null, "e": 28020, "s": 27843, "text": "405 Method Not Allowed: This response code occurs when the server knows the method of the request but currently it has been disabled by the server.Status:405 Method Not Allowed" }, { "code": null, "e": 28043, "s": 28020, "text": "405 Method Not Allowed" }, { "code": null, "e": 28189, "s": 28043, "text": "406 Not Acceptable: This response code occurs when the server does not find the content mentioned in the client request.Status:406 Not Acceptable" }, { "code": null, "e": 28208, "s": 28189, "text": "406 Not Acceptable" }, { "code": null, "e": 28384, "s": 28208, "text": "407 Proxy Authentication Required: This response code occurs when it is necessary for the client to authenticate itself with the proxy.Status:407 Proxy Authentication Required" }, { "code": null, "e": 28418, "s": 28384, "text": "407 Proxy Authentication Required" }, { "code": null, "e": 28594, "s": 28418, "text": "408 Request Timeout: This response code occurs when the webserver did not receive the required response within the time that it was prepared to wait.Status:408 Request Timeout" }, { "code": null, "e": 28614, "s": 28594, "text": "408 Request Timeout" }, { "code": null, "e": 28823, "s": 28614, "text": "409 Conflict: This response code occurs when the server could not complete the request due to conflict in the target resource. The client can resubmit the request by resolving the conflict.Status:409 Conflict" }, { "code": null, "e": 28836, "s": 28823, "text": "409 Conflict" }, { "code": null, "e": 28982, "s": 28836, "text": "410 Gone: This response code occurs when the requested resource is permanently deleted from the server and is no longer available.Status:410 Gone" }, { "code": null, "e": 28991, "s": 28982, "text": "410 Gone" }, { "code": null, "e": 29156, "s": 28991, "text": "411 Length Required: This response code occurs when the server rejects the request as the request did not have a defined “Content-Length”.Status:411 Length Required" }, { "code": null, "e": 29176, "s": 29156, "text": "411 Length Required" }, { "code": null, "e": 29339, "s": 29176, "text": "412 Precondition Failed: This response code occurs when the server evaluates the preconditions given in the request header as false.Status:412 Precondition Failed" }, { "code": null, "e": 29363, "s": 29339, "text": "412 Precondition Failed" }, { "code": null, "e": 29585, "s": 29363, "text": "413 Request Entity Too Large: This response code occurs when the server refuses to process the request because the request entity is larger than the server’s ability to process the data.Status:413 Request Entity Too Large" }, { "code": null, "e": 29614, "s": 29585, "text": "413 Request Entity Too Large" }, { "code": null, "e": 29792, "s": 29614, "text": "414 Request-URI Too Long: This response code occurs when the client’s requested URI is longer than the ability of the server to interpret the URI.Status:414 Request-URI Too Long" }, { "code": null, "e": 29817, "s": 29792, "text": "414 Request-URI Too Long" }, { "code": null, "e": 30034, "s": 29817, "text": "415 Unsupported Media Type: This response code occurs when the server rejects the requested resource because the media format of the requested resource is not supported by the server.Status:415 Unsupported Media Type" }, { "code": null, "e": 30061, "s": 30034, "text": "415 Unsupported Media Type" }, { "code": null, "e": 30303, "s": 30061, "text": "416 Requested Range Not Satisfiable: Response code occurs when the request cannot be completed because of the range specified in the Range Header. The range can also be outside the target URI’s data.Status:416 Requested Range Not Satisfiable" }, { "code": null, "e": 30339, "s": 30303, "text": "416 Requested Range Not Satisfiable" }, { "code": null, "e": 30520, "s": 30339, "text": "417 Expectation Failed: This response code occurs when the server can’t meet the expectation indicated by the Expect request-header field.Status:416 Requested Range Not Satisfiable" }, { "code": null, "e": 30556, "s": 30520, "text": "416 Requested Range Not Satisfiable" }, { "code": null, "e": 30667, "s": 30556, "text": "Supported Browsers: The browsers compatible with the HTTP status code Client Error Responses are listed below:" }, { "code": null, "e": 30681, "s": 30667, "text": "Google Chrome" }, { "code": null, "e": 30699, "s": 30681, "text": "Internet Explorer" }, { "code": null, "e": 30707, "s": 30699, "text": "Firefox" }, { "code": null, "e": 30714, "s": 30707, "text": "Safari" }, { "code": null, "e": 30720, "s": 30714, "text": "Opera" }, { "code": null, "e": 30748, "s": 30720, "text": "HTTP- response-status-codes" }, { "code": null, "e": 30765, "s": 30748, "text": "Web Technologies" }, { "code": null, "e": 30863, "s": 30765, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30903, "s": 30863, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 30948, "s": 30903, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 30991, "s": 30948, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 31052, "s": 30991, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 31124, "s": 31052, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 31182, "s": 31124, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 31215, "s": 31182, "text": "Node.js fs.readFileSync() Method" }, { "code": null, "e": 31275, "s": 31215, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 31302, "s": 31275, "text": "File uploading in React.js" } ]
Hashcat Tool in Kali Linux - GeeksforGeeks
25 Jan, 2021 Hashcat is famous as the fastest password cracker and password recovery utility. Hashcat is designed to break or crack even the most complex passwords in a very less amount of time. Features of hashcat: The 90+ Algorithm can be implemented with performance and optimization in mind. The number of threads can be configured. Hashcat is a multi-algorithm based ( MD5, MD4, MySQL, SHA1, NTLM, DCC, etc.). All attacks can be extended by specialized rules. It is multi-hash and multi-OS based (Windows and Linux). It supports both hex-charset and hex-salt files. Installation: Usually Hashcat tool comes pre-installed with Kali Linux but if we need to install it write down the given command in the terminal. sudo apt-get install hashcat Now, you can find the hashcat Tool in Password Cracking Tools : We are going to perform Dictionary Attack to crack Password in this article. 1. Creating Hash Entries These entries will then be outputted to a file called “Dictionary_hashes”. -n: This option removes the new line added to the end of entries as we don’t want the newline characters to be hashed with our entries. tr -d: This option removes any characters that are a space or hyphen from the output. 2. Checking the stored Hashes We can check the stored hashes with the help of the below command : cat Dictionary_hashes.txt Some password hashes that can be cracked with hashcat can be seen below : 3. Choose the wordlists We are going to use the “rockyou” wordlist. 4. Cracking the Hashes Now we can crack the hashes that we stored in Dictionary_hashes.txt and we will store the result in the Done.txt file. 5. Results Now we can see the results stored in the Done.txt file by the below command: cat Done.txt Kali-Linux Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. tar command in Linux with examples curl command in Linux with Examples Conditional Statements | Shell Script 'crontab' in Linux with Examples diff command in Linux with examples Tail command in Linux with examples UDP Server-Client implementation in C Cat command in Linux with examples touch command in Linux with Examples scp command in Linux with Examples
[ { "code": null, "e": 25785, "s": 25757, "text": "\n25 Jan, 2021" }, { "code": null, "e": 25967, "s": 25785, "text": "Hashcat is famous as the fastest password cracker and password recovery utility. Hashcat is designed to break or crack even the most complex passwords in a very less amount of time." }, { "code": null, "e": 25988, "s": 25967, "text": "Features of hashcat:" }, { "code": null, "e": 26068, "s": 25988, "text": "The 90+ Algorithm can be implemented with performance and optimization in mind." }, { "code": null, "e": 26109, "s": 26068, "text": "The number of threads can be configured." }, { "code": null, "e": 26187, "s": 26109, "text": "Hashcat is a multi-algorithm based ( MD5, MD4, MySQL, SHA1, NTLM, DCC, etc.)." }, { "code": null, "e": 26237, "s": 26187, "text": "All attacks can be extended by specialized rules." }, { "code": null, "e": 26294, "s": 26237, "text": "It is multi-hash and multi-OS based (Windows and Linux)." }, { "code": null, "e": 26343, "s": 26294, "text": "It supports both hex-charset and hex-salt files." }, { "code": null, "e": 26489, "s": 26343, "text": "Installation: Usually Hashcat tool comes pre-installed with Kali Linux but if we need to install it write down the given command in the terminal." }, { "code": null, "e": 26518, "s": 26489, "text": "sudo apt-get install hashcat" }, { "code": null, "e": 26582, "s": 26518, "text": "Now, you can find the hashcat Tool in Password Cracking Tools :" }, { "code": null, "e": 26659, "s": 26582, "text": "We are going to perform Dictionary Attack to crack Password in this article." }, { "code": null, "e": 26684, "s": 26659, "text": "1. Creating Hash Entries" }, { "code": null, "e": 26760, "s": 26684, "text": "These entries will then be outputted to a file called “Dictionary_hashes”. " }, { "code": null, "e": 26896, "s": 26760, "text": "-n: This option removes the new line added to the end of entries as we don’t want the newline characters to be hashed with our entries." }, { "code": null, "e": 26982, "s": 26896, "text": "tr -d: This option removes any characters that are a space or hyphen from the output." }, { "code": null, "e": 27012, "s": 26982, "text": "2. Checking the stored Hashes" }, { "code": null, "e": 27080, "s": 27012, "text": "We can check the stored hashes with the help of the below command :" }, { "code": null, "e": 27106, "s": 27080, "text": "cat Dictionary_hashes.txt" }, { "code": null, "e": 27180, "s": 27106, "text": "Some password hashes that can be cracked with hashcat can be seen below :" }, { "code": null, "e": 27205, "s": 27180, "text": "3. Choose the wordlists" }, { "code": null, "e": 27249, "s": 27205, "text": "We are going to use the “rockyou” wordlist." }, { "code": null, "e": 27272, "s": 27249, "text": "4. Cracking the Hashes" }, { "code": null, "e": 27391, "s": 27272, "text": "Now we can crack the hashes that we stored in Dictionary_hashes.txt and we will store the result in the Done.txt file." }, { "code": null, "e": 27402, "s": 27391, "text": "5. Results" }, { "code": null, "e": 27479, "s": 27402, "text": "Now we can see the results stored in the Done.txt file by the below command:" }, { "code": null, "e": 27492, "s": 27479, "text": "cat Done.txt" }, { "code": null, "e": 27503, "s": 27492, "text": "Kali-Linux" }, { "code": null, "e": 27514, "s": 27503, "text": "Linux-Unix" }, { "code": null, "e": 27612, "s": 27514, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27647, "s": 27612, "text": "tar command in Linux with examples" }, { "code": null, "e": 27683, "s": 27647, "text": "curl command in Linux with Examples" }, { "code": null, "e": 27721, "s": 27683, "text": "Conditional Statements | Shell Script" }, { "code": null, "e": 27754, "s": 27721, "text": "'crontab' in Linux with Examples" }, { "code": null, "e": 27790, "s": 27754, "text": "diff command in Linux with examples" }, { "code": null, "e": 27826, "s": 27790, "text": "Tail command in Linux with examples" }, { "code": null, "e": 27864, "s": 27826, "text": "UDP Server-Client implementation in C" }, { "code": null, "e": 27899, "s": 27864, "text": "Cat command in Linux with examples" }, { "code": null, "e": 27936, "s": 27899, "text": "touch command in Linux with Examples" } ]
Python Program to Count Words in Text File - GeeksforGeeks
15 Dec, 2021 In this article, we are going to see how to count words in Text Files using Python. First, we create a text file of which we want to count the number of words. Let this file be SampleFile.txt with the following contents: Python3 # creating variable to store the# number of wordsnumber_of_words = 0 # Opening our text file in read only# mode using the open() functionwith open(r'SampleFile.txt','r') as file: # Reading the content of the file # using the read() function and storing # them in a new variable data = file.read() # Splitting the data into separate lines # using the split() function lines = data.split() # Adding the length of the # lines in our number_of_words # variable number_of_words += len(lines) # Printing total number of wordsprint(number_of_words) Output: 7 Explanation: Creating a new variable to store the total number of words in the text file. And then open the text file in read-only mode using the open() function. Read the content of the file using the read() function and storing them in a new variable. And then split the data stored in the data variable into separate lines using the split() function and then storing them in a new variable. And add the length of the lines in our number_of_words variable. File for demonstration: Below is the implementation: Python3 # creating variable to store the# number of wordsnumber_of_words = 0 # Opening our text file in read only# mode using the open() functionwith open(r'SampleFile.txt','r') as file: # Reading the content of the file # using the read() function and storing # them in a new variable data = file.read() # Splitting the data into separate lines # using the split() function lines = data.split() # Iterating over every word in # lines for word in lines: # checking if the word is numeric or not if not word.isnumeric(): # Adding the length of the # lines in our number_of_words # variable number_of_words += 1 # Printing total number of wordsprint(number_of_words) Output: 11 Explanation: Create a new variable to store the total number of words in the text file and then open the text file in read-only mode using the open() function. Read the content of the file using the read() function and storing them in a new variable and then split the data stored in the data variable into separate lines using the split() function and then storing them in a new variable, Iterating over every word in lines using the for loop and check if the word is numeric or not using the isnumeric() function then add 1 in our number_of_words variable. simranarora5sos Picked Python file-handling-programs Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | Get unique values from a list Python | os.path.join() method Defaultdict in Python Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25563, "s": 25535, "text": "\n15 Dec, 2021" }, { "code": null, "e": 25647, "s": 25563, "text": "In this article, we are going to see how to count words in Text Files using Python." }, { "code": null, "e": 25784, "s": 25647, "text": "First, we create a text file of which we want to count the number of words. Let this file be SampleFile.txt with the following contents:" }, { "code": null, "e": 25792, "s": 25784, "text": "Python3" }, { "code": "# creating variable to store the# number of wordsnumber_of_words = 0 # Opening our text file in read only# mode using the open() functionwith open(r'SampleFile.txt','r') as file: # Reading the content of the file # using the read() function and storing # them in a new variable data = file.read() # Splitting the data into separate lines # using the split() function lines = data.split() # Adding the length of the # lines in our number_of_words # variable number_of_words += len(lines) # Printing total number of wordsprint(number_of_words)", "e": 26371, "s": 25792, "text": null }, { "code": null, "e": 26380, "s": 26371, "text": "Output: " }, { "code": null, "e": 26382, "s": 26380, "text": "7" }, { "code": null, "e": 26396, "s": 26382, "text": "Explanation: " }, { "code": null, "e": 26546, "s": 26396, "text": "Creating a new variable to store the total number of words in the text file. And then open the text file in read-only mode using the open() function." }, { "code": null, "e": 26842, "s": 26546, "text": "Read the content of the file using the read() function and storing them in a new variable. And then split the data stored in the data variable into separate lines using the split() function and then storing them in a new variable. And add the length of the lines in our number_of_words variable." }, { "code": null, "e": 26867, "s": 26842, "text": "File for demonstration: " }, { "code": null, "e": 26897, "s": 26867, "text": "Below is the implementation: " }, { "code": null, "e": 26905, "s": 26897, "text": "Python3" }, { "code": "# creating variable to store the# number of wordsnumber_of_words = 0 # Opening our text file in read only# mode using the open() functionwith open(r'SampleFile.txt','r') as file: # Reading the content of the file # using the read() function and storing # them in a new variable data = file.read() # Splitting the data into separate lines # using the split() function lines = data.split() # Iterating over every word in # lines for word in lines: # checking if the word is numeric or not if not word.isnumeric(): # Adding the length of the # lines in our number_of_words # variable number_of_words += 1 # Printing total number of wordsprint(number_of_words)", "e": 27664, "s": 26905, "text": null }, { "code": null, "e": 27672, "s": 27664, "text": "Output:" }, { "code": null, "e": 27675, "s": 27672, "text": "11" }, { "code": null, "e": 28234, "s": 27675, "text": "Explanation: Create a new variable to store the total number of words in the text file and then open the text file in read-only mode using the open() function. Read the content of the file using the read() function and storing them in a new variable and then split the data stored in the data variable into separate lines using the split() function and then storing them in a new variable, Iterating over every word in lines using the for loop and check if the word is numeric or not using the isnumeric() function then add 1 in our number_of_words variable." }, { "code": null, "e": 28250, "s": 28234, "text": "simranarora5sos" }, { "code": null, "e": 28257, "s": 28250, "text": "Picked" }, { "code": null, "e": 28287, "s": 28257, "text": "Python file-handling-programs" }, { "code": null, "e": 28294, "s": 28287, "text": "Python" }, { "code": null, "e": 28392, "s": 28294, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28424, "s": 28392, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28466, "s": 28424, "text": "Check if element exists in list in Python" }, { "code": null, "e": 28508, "s": 28466, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 28564, "s": 28508, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28591, "s": 28564, "text": "Python Classes and Objects" }, { "code": null, "e": 28630, "s": 28591, "text": "Python | Get unique values from a list" }, { "code": null, "e": 28661, "s": 28630, "text": "Python | os.path.join() method" }, { "code": null, "e": 28683, "s": 28661, "text": "Defaultdict in Python" }, { "code": null, "e": 28712, "s": 28683, "text": "Create a directory in Python" } ]
Bitwise Operations on Digits of a Number - GeeksforGeeks
14 Aug, 2021 Given a number N, the task is to perform the bitwise operations on digits of the given number N. The bitwise operations include: Finding the XOR of all digits of the given number N Finding the OR of all digits of the given number N Finding the AND of all digits of the given number N Examples: Input: N = 486 Output: XOR = 10 OR = 14 AND = 0 Input: N = 123456 Output: XOR = 10 OR = 14 AND = 0 Approach: Get the number Find the digits of the number and store it in an array for computation purpose. Now perform the various bitwise operations (XOR, OR, and AND) on this array one by one. Get the number Find the digits of the number and store it in an array for computation purpose. Now perform the various bitwise operations (XOR, OR, and AND) on this array one by one. Below is the implementation of the above approach: C++ Java Python 3 C# Javascript // C++ implementation of the approach #include <bits/stdc++.h>using namespace std; int digit[100000]; // Function to find the digitsint findDigits(int n){ int count = 0; while (n != 0) { digit[count] = n % 10; n = n / 10; ++count; } return count;} // Function to Find OR// of all digits of a numberint OR_of_Digits(int n, int count){ int ans = 0; for (int i = 0; i < count; i++) { // Find OR of all digits ans = ans | digit[i]; } // return OR of digits return ans;} // Function to Find AND// of all digits of a numberint AND_of_Digits(int n, int count){ int ans = 0; for (int i = 0; i < count; i++) { // Find AND of all digits ans = ans & digit[i]; } // return AND of digits return ans;} // Function to Find XOR// of all digits of a numberint XOR_of_Digits(int n, int count){ int ans = 0; for (int i = 0; i < count; i++) { // Find XOR of all digits ans = ans ^ digit[i]; } // return XOR of digits return ans;} // Driver codevoid bitwise_operation(int N){ // Find and store all digits int countOfDigit = findDigits(N); // Find XOR of digits cout << "XOR = " << XOR_of_Digits(N, countOfDigit) << endl; // Find OR of digits cout << "OR = " << OR_of_Digits(N, countOfDigit) << endl; // Find AND of digits cout << "AND = " << AND_of_Digits(N, countOfDigit) << endl;} // Driver codeint main(){ int N = 123456; bitwise_operation(N); return 0;} // Java implementation of the approachimport java.util.*; class GFG{ static int []digit = new int[100000]; // Function to find the digitsstatic int findDigits(int n){ int count = 0; while (n != 0) { digit[count] = n % 10; n = n / 10; ++count; } return count;} // Function to Find OR// of all digits of a numberstatic int OR_of_Digits(int n, int count){ int ans = 0; for (int i = 0; i < count; i++) { // Find OR of all digits ans = ans | digit[i]; } // return OR of digits return ans;} // Function to Find AND// of all digits of a numberstatic int AND_of_Digits(int n, int count){ int ans = 0; for (int i = 0; i < count; i++) { // Find AND of all digits ans = ans & digit[i]; } // return AND of digits return ans;} // Function to Find XOR// of all digits of a numberstatic int XOR_of_Digits(int n, int count){ int ans = 0; for (int i = 0; i < count; i++) { // Find XOR of all digits ans = ans ^ digit[i]; } // return XOR of digits return ans;} // Driver codestatic void bitwise_operation(int N){ // Find and store all digits int countOfDigit = findDigits(N); // Find XOR of digits System.out.print("XOR = " + XOR_of_Digits(N, countOfDigit) +"\n"); // Find OR of digits System.out.print("OR = " + OR_of_Digits(N, countOfDigit) +"\n"); // Find AND of digits System.out.print("AND = " + AND_of_Digits(N, countOfDigit) +"\n");} // Driver codepublic static void main(String[] args){ int N = 123456; bitwise_operation(N);}} // This code is contributed by sapnasingh4991 # Python 3 implementation of the approachdigit = [0]*(100000) # Function to find the digitsdef findDigits(n): count = 0 while (n != 0): digit[count] = n % 10; n = n // 10; count += 1 return count # Function to Find OR# of all digits of a numberdef OR_of_Digits( n,count): ans = 0 for i in range(count): # Find OR of all digits ans = ans | digit[i] # return OR of digits return ans # Function to Find AND# of all digits of a numberdef AND_of_Digits(n, count): ans = 0 for i in range(count): # Find AND of all digits ans = ans & digit[i] # return AND of digits return ans # Function to Find XOR# of all digits of a numberdef XOR_of_Digits(n, count): ans = 0 for i in range(count): # Find XOR of all digits ans = ans ^ digit[i] # return XOR of digits return ans # Driver codedef bitwise_operation( N): # Find and store all digits countOfDigit = findDigits(N) # Find XOR of digits print("XOR = ",XOR_of_Digits(N, countOfDigit)) # Find OR of digits print("OR = ",OR_of_Digits(N, countOfDigit)) # Find AND of digits print("AND = ",AND_of_Digits(N, countOfDigit)) # Driver codeN = 123456;bitwise_operation(N) # This code is contributed by apurva raj // C# implementation of the approachusing System; class GFG{ static int []digit = new int[100000]; // Function to find the digitsstatic int findDigits(int n){ int count = 0; while (n != 0) { digit[count] = n % 10; n = n / 10; ++count; } return count;} // Function to Find OR// of all digits of a numberstatic int OR_of_Digits(int n, int count){ int ans = 0; for (int i = 0; i < count; i++) { // Find OR of all digits ans = ans | digit[i]; } // return OR of digits return ans;} // Function to Find AND// of all digits of a numberstatic int AND_of_Digits(int n, int count){ int ans = 0; for (int i = 0; i < count; i++) { // Find AND of all digits ans = ans & digit[i]; } // return AND of digits return ans;} // Function to Find XOR// of all digits of a numberstatic int XOR_of_Digits(int n, int count){ int ans = 0; for (int i = 0; i < count; i++) { // Find XOR of all digits ans = ans ^ digit[i]; } // return XOR of digits return ans;} // Driver codestatic void bitwise_operation(int N){ // Find and store all digits int countOfDigit = findDigits(N); // Find XOR of digits Console.Write("XOR = " + XOR_of_Digits(N, countOfDigit) +"\n"); // Find OR of digits Console.Write("OR = " + OR_of_Digits(N, countOfDigit) +"\n"); // Find AND of digits Console.Write("AND = " + AND_of_Digits(N, countOfDigit) +"\n");} // Driver codepublic static void Main(String[] args){ int N = 123456; bitwise_operation(N);}} // This code is contributed by 29AjayKumar <script> // Javascript implementation of the approach let digit = []; // Function to find the digitsfunction findDigits(n){ let count = 0; while (n != 0) { digit[count] = n % 10; n = n / 10; ++count; } return count;} // Function to Find OR// of all digits of a numberfunction OR_of_Digits(n, count){ let ans = 0; for (let i = 0; i < count; i++) { // Find OR of all digits ans = ans | digit[i]; } // return OR of digits return ans;} // Function to Find AND// of all digits of a numberfunction AND_of_Digits(n, count){ let ans = 0; for (let i = 0; i < count; i++) { // Find AND of all digits ans = ans & digit[i]; } // return AND of digits return ans;} // Function to Find XOR// of all digits of a numberfunction XOR_of_Digits(n, count){ let ans = 0; for (let i = 0; i < count; i++) { // Find XOR of all digits ans = ans ^ digit[i]; } // return XOR of digits return ans;} // Driver codefunction bitwise_operation(N){ // Find and store all digits let countOfDigit = findDigits(N); // Find XOR of digits document.write("XOR = " + XOR_of_Digits(N, countOfDigit) + "<br/>"); // Find OR of digits document.write("OR = " + OR_of_Digits(N, countOfDigit) + "<br/>"); // Find AND of digits document.write("AND = " + AND_of_Digits(N, countOfDigit) + "<br/>");} // Driver Code let N = 123456; bitwise_operation(N); </script> XOR = 7 OR = 7 AND = 0 Time Complexity: O(logN)Auxiliary Space: O(logN) ApurvaRaj sapnasingh4991 29AjayKumar chinmoy1997pal pankajsharmagfg Algorithms-Bit Algorithms Bitwise-AND Bitwise-OR Bitwise-XOR Algorithms Mathematical School Programming Write From Home Mathematical Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. DSA Sheet by Love Babbar How to Start Learning DSA? Difference between Algorithm, Pseudocode and Program K means Clustering - Introduction Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete Program for Fibonacci numbers Write a program to print all permutations of a given string C++ Data Types Set in C++ Standard Template Library (STL) Coin Change | DP-7
[ { "code": null, "e": 25917, "s": 25889, "text": "\n14 Aug, 2021" }, { "code": null, "e": 26048, "s": 25917, "text": "Given a number N, the task is to perform the bitwise operations on digits of the given number N. The bitwise operations include: " }, { "code": null, "e": 26100, "s": 26048, "text": "Finding the XOR of all digits of the given number N" }, { "code": null, "e": 26151, "s": 26100, "text": "Finding the OR of all digits of the given number N" }, { "code": null, "e": 26203, "s": 26151, "text": "Finding the AND of all digits of the given number N" }, { "code": null, "e": 26215, "s": 26203, "text": "Examples: " }, { "code": null, "e": 26317, "s": 26215, "text": "Input: N = 486\nOutput: \nXOR = 10\nOR = 14\nAND = 0\n\nInput: N = 123456\nOutput: \nXOR = 10\nOR = 14\nAND = 0" }, { "code": null, "e": 26330, "s": 26319, "text": "Approach: " }, { "code": null, "e": 26515, "s": 26330, "text": "Get the number Find the digits of the number and store it in an array for computation purpose. Now perform the various bitwise operations (XOR, OR, and AND) on this array one by one." }, { "code": null, "e": 26532, "s": 26515, "text": "Get the number " }, { "code": null, "e": 26614, "s": 26532, "text": "Find the digits of the number and store it in an array for computation purpose. " }, { "code": null, "e": 26702, "s": 26614, "text": "Now perform the various bitwise operations (XOR, OR, and AND) on this array one by one." }, { "code": null, "e": 26755, "s": 26702, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 26759, "s": 26755, "text": "C++" }, { "code": null, "e": 26764, "s": 26759, "text": "Java" }, { "code": null, "e": 26773, "s": 26764, "text": "Python 3" }, { "code": null, "e": 26776, "s": 26773, "text": "C#" }, { "code": null, "e": 26787, "s": 26776, "text": "Javascript" }, { "code": "// C++ implementation of the approach #include <bits/stdc++.h>using namespace std; int digit[100000]; // Function to find the digitsint findDigits(int n){ int count = 0; while (n != 0) { digit[count] = n % 10; n = n / 10; ++count; } return count;} // Function to Find OR// of all digits of a numberint OR_of_Digits(int n, int count){ int ans = 0; for (int i = 0; i < count; i++) { // Find OR of all digits ans = ans | digit[i]; } // return OR of digits return ans;} // Function to Find AND// of all digits of a numberint AND_of_Digits(int n, int count){ int ans = 0; for (int i = 0; i < count; i++) { // Find AND of all digits ans = ans & digit[i]; } // return AND of digits return ans;} // Function to Find XOR// of all digits of a numberint XOR_of_Digits(int n, int count){ int ans = 0; for (int i = 0; i < count; i++) { // Find XOR of all digits ans = ans ^ digit[i]; } // return XOR of digits return ans;} // Driver codevoid bitwise_operation(int N){ // Find and store all digits int countOfDigit = findDigits(N); // Find XOR of digits cout << \"XOR = \" << XOR_of_Digits(N, countOfDigit) << endl; // Find OR of digits cout << \"OR = \" << OR_of_Digits(N, countOfDigit) << endl; // Find AND of digits cout << \"AND = \" << AND_of_Digits(N, countOfDigit) << endl;} // Driver codeint main(){ int N = 123456; bitwise_operation(N); return 0;}", "e": 28344, "s": 26787, "text": null }, { "code": "// Java implementation of the approachimport java.util.*; class GFG{ static int []digit = new int[100000]; // Function to find the digitsstatic int findDigits(int n){ int count = 0; while (n != 0) { digit[count] = n % 10; n = n / 10; ++count; } return count;} // Function to Find OR// of all digits of a numberstatic int OR_of_Digits(int n, int count){ int ans = 0; for (int i = 0; i < count; i++) { // Find OR of all digits ans = ans | digit[i]; } // return OR of digits return ans;} // Function to Find AND// of all digits of a numberstatic int AND_of_Digits(int n, int count){ int ans = 0; for (int i = 0; i < count; i++) { // Find AND of all digits ans = ans & digit[i]; } // return AND of digits return ans;} // Function to Find XOR// of all digits of a numberstatic int XOR_of_Digits(int n, int count){ int ans = 0; for (int i = 0; i < count; i++) { // Find XOR of all digits ans = ans ^ digit[i]; } // return XOR of digits return ans;} // Driver codestatic void bitwise_operation(int N){ // Find and store all digits int countOfDigit = findDigits(N); // Find XOR of digits System.out.print(\"XOR = \" + XOR_of_Digits(N, countOfDigit) +\"\\n\"); // Find OR of digits System.out.print(\"OR = \" + OR_of_Digits(N, countOfDigit) +\"\\n\"); // Find AND of digits System.out.print(\"AND = \" + AND_of_Digits(N, countOfDigit) +\"\\n\");} // Driver codepublic static void main(String[] args){ int N = 123456; bitwise_operation(N);}} // This code is contributed by sapnasingh4991", "e": 30044, "s": 28344, "text": null }, { "code": "# Python 3 implementation of the approachdigit = [0]*(100000) # Function to find the digitsdef findDigits(n): count = 0 while (n != 0): digit[count] = n % 10; n = n // 10; count += 1 return count # Function to Find OR# of all digits of a numberdef OR_of_Digits( n,count): ans = 0 for i in range(count): # Find OR of all digits ans = ans | digit[i] # return OR of digits return ans # Function to Find AND# of all digits of a numberdef AND_of_Digits(n, count): ans = 0 for i in range(count): # Find AND of all digits ans = ans & digit[i] # return AND of digits return ans # Function to Find XOR# of all digits of a numberdef XOR_of_Digits(n, count): ans = 0 for i in range(count): # Find XOR of all digits ans = ans ^ digit[i] # return XOR of digits return ans # Driver codedef bitwise_operation( N): # Find and store all digits countOfDigit = findDigits(N) # Find XOR of digits print(\"XOR = \",XOR_of_Digits(N, countOfDigit)) # Find OR of digits print(\"OR = \",OR_of_Digits(N, countOfDigit)) # Find AND of digits print(\"AND = \",AND_of_Digits(N, countOfDigit)) # Driver codeN = 123456;bitwise_operation(N) # This code is contributed by apurva raj", "e": 31361, "s": 30044, "text": null }, { "code": "// C# implementation of the approachusing System; class GFG{ static int []digit = new int[100000]; // Function to find the digitsstatic int findDigits(int n){ int count = 0; while (n != 0) { digit[count] = n % 10; n = n / 10; ++count; } return count;} // Function to Find OR// of all digits of a numberstatic int OR_of_Digits(int n, int count){ int ans = 0; for (int i = 0; i < count; i++) { // Find OR of all digits ans = ans | digit[i]; } // return OR of digits return ans;} // Function to Find AND// of all digits of a numberstatic int AND_of_Digits(int n, int count){ int ans = 0; for (int i = 0; i < count; i++) { // Find AND of all digits ans = ans & digit[i]; } // return AND of digits return ans;} // Function to Find XOR// of all digits of a numberstatic int XOR_of_Digits(int n, int count){ int ans = 0; for (int i = 0; i < count; i++) { // Find XOR of all digits ans = ans ^ digit[i]; } // return XOR of digits return ans;} // Driver codestatic void bitwise_operation(int N){ // Find and store all digits int countOfDigit = findDigits(N); // Find XOR of digits Console.Write(\"XOR = \" + XOR_of_Digits(N, countOfDigit) +\"\\n\"); // Find OR of digits Console.Write(\"OR = \" + OR_of_Digits(N, countOfDigit) +\"\\n\"); // Find AND of digits Console.Write(\"AND = \" + AND_of_Digits(N, countOfDigit) +\"\\n\");} // Driver codepublic static void Main(String[] args){ int N = 123456; bitwise_operation(N);}} // This code is contributed by 29AjayKumar", "e": 33069, "s": 31361, "text": null }, { "code": "<script> // Javascript implementation of the approach let digit = []; // Function to find the digitsfunction findDigits(n){ let count = 0; while (n != 0) { digit[count] = n % 10; n = n / 10; ++count; } return count;} // Function to Find OR// of all digits of a numberfunction OR_of_Digits(n, count){ let ans = 0; for (let i = 0; i < count; i++) { // Find OR of all digits ans = ans | digit[i]; } // return OR of digits return ans;} // Function to Find AND// of all digits of a numberfunction AND_of_Digits(n, count){ let ans = 0; for (let i = 0; i < count; i++) { // Find AND of all digits ans = ans & digit[i]; } // return AND of digits return ans;} // Function to Find XOR// of all digits of a numberfunction XOR_of_Digits(n, count){ let ans = 0; for (let i = 0; i < count; i++) { // Find XOR of all digits ans = ans ^ digit[i]; } // return XOR of digits return ans;} // Driver codefunction bitwise_operation(N){ // Find and store all digits let countOfDigit = findDigits(N); // Find XOR of digits document.write(\"XOR = \" + XOR_of_Digits(N, countOfDigit) + \"<br/>\"); // Find OR of digits document.write(\"OR = \" + OR_of_Digits(N, countOfDigit) + \"<br/>\"); // Find AND of digits document.write(\"AND = \" + AND_of_Digits(N, countOfDigit) + \"<br/>\");} // Driver Code let N = 123456; bitwise_operation(N); </script>", "e": 34669, "s": 33069, "text": null }, { "code": null, "e": 34692, "s": 34669, "text": "XOR = 7\nOR = 7\nAND = 0" }, { "code": null, "e": 34743, "s": 34694, "text": "Time Complexity: O(logN)Auxiliary Space: O(logN)" }, { "code": null, "e": 34753, "s": 34743, "text": "ApurvaRaj" }, { "code": null, "e": 34768, "s": 34753, "text": "sapnasingh4991" }, { "code": null, "e": 34780, "s": 34768, "text": "29AjayKumar" }, { "code": null, "e": 34795, "s": 34780, "text": "chinmoy1997pal" }, { "code": null, "e": 34811, "s": 34795, "text": "pankajsharmagfg" }, { "code": null, "e": 34837, "s": 34811, "text": "Algorithms-Bit Algorithms" }, { "code": null, "e": 34849, "s": 34837, "text": "Bitwise-AND" }, { "code": null, "e": 34860, "s": 34849, "text": "Bitwise-OR" }, { "code": null, "e": 34872, "s": 34860, "text": "Bitwise-XOR" }, { "code": null, "e": 34883, "s": 34872, "text": "Algorithms" }, { "code": null, "e": 34896, "s": 34883, "text": "Mathematical" }, { "code": null, "e": 34915, "s": 34896, "text": "School Programming" }, { "code": null, "e": 34931, "s": 34915, "text": "Write From Home" }, { "code": null, "e": 34944, "s": 34931, "text": "Mathematical" }, { "code": null, "e": 34955, "s": 34944, "text": "Algorithms" }, { "code": null, "e": 35053, "s": 34955, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35078, "s": 35053, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 35105, "s": 35078, "text": "How to Start Learning DSA?" }, { "code": null, "e": 35158, "s": 35105, "text": "Difference between Algorithm, Pseudocode and Program" }, { "code": null, "e": 35192, "s": 35158, "text": "K means Clustering - Introduction" }, { "code": null, "e": 35259, "s": 35192, "text": "Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete" }, { "code": null, "e": 35289, "s": 35259, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 35349, "s": 35289, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 35364, "s": 35349, "text": "C++ Data Types" }, { "code": null, "e": 35407, "s": 35364, "text": "Set in C++ Standard Template Library (STL)" } ]
Pyspark - Split multiple array columns into rows - GeeksforGeeks
16 May, 2021 Suppose we have a DataFrame that contains columns having different types of values like string, integer, etc., and sometimes the column data is in array format also. Working with the array is sometimes difficult and to remove the difficulty we wanted to split those array data into rows. To split multiple array column data into rows pyspark provides a function called explode(). Using explode, we will get a new row for each element in the array. When an array is passed to this function, it creates a new default column, and it contains all array elements as its rows and the null values present in the array will be ignored. This is a built-in function is available in pyspark.sql.functions module. Syntax: pyspark.sql.functions.explode(col) Parameters: col is an array column name which we want to split into rows. Note: It takes only one positional argument i.e. at a time only one column can be split. Example: Split array column using explode() In this example we will create a dataframe containing three columns, one column is ‘Name’ contains the name of students, the other column is ‘Age’ contains the age of students, and the last and third column ‘Courses_enrolled’ contains the courses enrolled by these students. The first two columns contain simple data of string type, but the third column contains data in an array format. We will split the column ‘Courses_enrolled’ containing data in array format into rows. Python3 # importing pysparkimport pyspark # importing sparksessiofrom pyspark.sql import SparkSession # importing all from pyspark.sql.functions # like Row, array, explode etc.from pyspark.sql.functions import * # creating a sparksession object and# providing appName spark=SparkSession.builder.appName("sparkdf").getOrCreate() # now creating dataframe# creating the row data and giving array# values for dataframedata = [('Jaya', '20', ['SQL','Data Science']), ('Milan', '21', ['ML','AI']), ('Rohit', '19', ['Programming', 'DSA']), ('Maria', '20', ['DBMS', 'Networking']), ('Jay', '22', ['Data Analytics','ML'])] # column names for dataframecolumns = ['Name', 'Age', 'Courses_enrolled'] # creating dataframe with createDataFrame()df = spark.createDataFrame(data, columns) # printing dataframe schemadf.printSchema() # show dataframedf.show() Output: In the schema of the dataframe we can see that the first two columns have string type data and the third column has array data. Now, we will split the array column into rows using explode(). Python3 # using select function applying # explode on array columndf2 = df.select(df.Name,explode(df.Courses_enrolled)) # printing the schema of the df2df2.printSchema() # show df2df2.show() Output: In this output, we can see that the array column is split into rows. The explode() function created a default column ‘col’ for array column, each array element is converted into a row, and also the type of the column is changed to string, earlier its type was array as mentioned in above df output. There are three ways to explode an array column: explode_outer() posexplode() posexplode_outer() Let’s understand each of them with an example. For this, we will create a dataframe that contains some null arrays also and will split the array column into rows using different types of explode. Python3 # creating the row data and giving array # values for dataframe along with null valuesdata = [('Jaya', '20', ['SQL', 'Data Science']), ('Milan', '21', ['ML', 'AI']), ('Rohit', '19', None), ('Maria', '20', ['DBMS', 'Networking']), ('Jay', '22', None)] # column names for dataframecolumns = ['Name', 'Age', 'Courses_enrolled'] # creating dataframe with createDataFrame()df = spark.createDataFrame(data, columns) # printing dataframe schemadf.printSchema() # show dataframedf.show() Output: 1. explode_outer(): The explode_outer function splits the array column into a row for each element of the array element whether it contains a null value or not. Whereas the simple explode() ignores the null value present in the column. Python3 # now using select function applying# explode_outer on array columndf4 = df.select(df.Name, explode_outer(df.Courses_enrolled)) # printing the schema of the df4df4.printSchema() # show df2df4.show() Output: As we have defined above that explode_outer() doesn’t ignore null values of the array column. Clearly, we can see that the null values are also displayed as rows of dataframe. 2. posexplode(): The posexplode() splits the array column into rows for each element in the array and also provides the position of the elements in the array. It creates two columns “pos’ to carry the position of the array element and the ‘col’ to carry the particular array elements and ignores null values. Now, we will apply posexplode() on the array column ‘Courses_enrolled’. Python3 # using select function applying # explode on array columndf2 = df.select(df.Name, posexplode(df.Courses_enrolled)) # printing the schema of the df2df2.printSchema() # show df2df2.show() Output: As the posexplode() splits the arrays into rows and also provides the position of array elements and in this output, we have got the positions of array elements in the ‘pos’ column. And it ignored null values present in the array column. 3. posexplode_outer(): The posexplode_outer() splits the array column into rows for each element in the array and also provides the position of the elements in the array. It creates two columns “pos’ to carry the position of the array element and the ‘col’ to carry the particular array elements whether it contains a null value also. That means posexplode_outer() has the functionality of both the explode_outer() and posexplode() functions. Let’s see this in example: Now, we will apply posexplode_outer() on array column ‘Courses_enrolled’. Python3 # using select function applying # explode on array columndf2 = df.select(df.Name, posexplode_outer(df.Courses_enrolled)) # printing the schema of the df2df2.printSchema() # show df2df2.show() Output: As, posexplode_outer() provides functionalities of both the explode functions explode_outer() and posexplode(). In the output, clearly, we can see that we have got the rows and position values of all array elements including null values also in the ‘pos’ and ‘col’ column. Picked Python-Pyspark 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() Reading and Writing to text files in Python *args and **kwargs in Python Convert integer to string in Python
[ { "code": null, "e": 26353, "s": 26325, "text": "\n16 May, 2021" }, { "code": null, "e": 26642, "s": 26353, "text": "Suppose we have a DataFrame that contains columns having different types of values like string, integer, etc., and sometimes the column data is in array format also. Working with the array is sometimes difficult and to remove the difficulty we wanted to split those array data into rows. " }, { "code": null, "e": 27057, "s": 26642, "text": "To split multiple array column data into rows pyspark provides a function called explode(). Using explode, we will get a new row for each element in the array. When an array is passed to this function, it creates a new default column, and it contains all array elements as its rows and the null values present in the array will be ignored. This is a built-in function is available in pyspark.sql.functions module. " }, { "code": null, "e": 27100, "s": 27057, "text": "Syntax: pyspark.sql.functions.explode(col)" }, { "code": null, "e": 27112, "s": 27100, "text": "Parameters:" }, { "code": null, "e": 27174, "s": 27112, "text": "col is an array column name which we want to split into rows." }, { "code": null, "e": 27263, "s": 27174, "text": "Note: It takes only one positional argument i.e. at a time only one column can be split." }, { "code": null, "e": 27307, "s": 27263, "text": "Example: Split array column using explode()" }, { "code": null, "e": 27782, "s": 27307, "text": "In this example we will create a dataframe containing three columns, one column is ‘Name’ contains the name of students, the other column is ‘Age’ contains the age of students, and the last and third column ‘Courses_enrolled’ contains the courses enrolled by these students. The first two columns contain simple data of string type, but the third column contains data in an array format. We will split the column ‘Courses_enrolled’ containing data in array format into rows." }, { "code": null, "e": 27790, "s": 27782, "text": "Python3" }, { "code": "# importing pysparkimport pyspark # importing sparksessiofrom pyspark.sql import SparkSession # importing all from pyspark.sql.functions # like Row, array, explode etc.from pyspark.sql.functions import * # creating a sparksession object and# providing appName spark=SparkSession.builder.appName(\"sparkdf\").getOrCreate() # now creating dataframe# creating the row data and giving array# values for dataframedata = [('Jaya', '20', ['SQL','Data Science']), ('Milan', '21', ['ML','AI']), ('Rohit', '19', ['Programming', 'DSA']), ('Maria', '20', ['DBMS', 'Networking']), ('Jay', '22', ['Data Analytics','ML'])] # column names for dataframecolumns = ['Name', 'Age', 'Courses_enrolled'] # creating dataframe with createDataFrame()df = spark.createDataFrame(data, columns) # printing dataframe schemadf.printSchema() # show dataframedf.show()", "e": 28661, "s": 27790, "text": null }, { "code": null, "e": 28669, "s": 28661, "text": "Output:" }, { "code": null, "e": 28860, "s": 28669, "text": "In the schema of the dataframe we can see that the first two columns have string type data and the third column has array data. Now, we will split the array column into rows using explode()." }, { "code": null, "e": 28868, "s": 28860, "text": "Python3" }, { "code": "# using select function applying # explode on array columndf2 = df.select(df.Name,explode(df.Courses_enrolled)) # printing the schema of the df2df2.printSchema() # show df2df2.show()", "e": 29053, "s": 28868, "text": null }, { "code": null, "e": 29061, "s": 29053, "text": "Output:" }, { "code": null, "e": 29361, "s": 29061, "text": "In this output, we can see that the array column is split into rows. The explode() function created a default column ‘col’ for array column, each array element is converted into a row, and also the type of the column is changed to string, earlier its type was array as mentioned in above df output. " }, { "code": null, "e": 29410, "s": 29361, "text": "There are three ways to explode an array column:" }, { "code": null, "e": 29426, "s": 29410, "text": "explode_outer()" }, { "code": null, "e": 29439, "s": 29426, "text": "posexplode()" }, { "code": null, "e": 29458, "s": 29439, "text": "posexplode_outer()" }, { "code": null, "e": 29654, "s": 29458, "text": "Let’s understand each of them with an example. For this, we will create a dataframe that contains some null arrays also and will split the array column into rows using different types of explode." }, { "code": null, "e": 29662, "s": 29654, "text": "Python3" }, { "code": "# creating the row data and giving array # values for dataframe along with null valuesdata = [('Jaya', '20', ['SQL', 'Data Science']), ('Milan', '21', ['ML', 'AI']), ('Rohit', '19', None), ('Maria', '20', ['DBMS', 'Networking']), ('Jay', '22', None)] # column names for dataframecolumns = ['Name', 'Age', 'Courses_enrolled'] # creating dataframe with createDataFrame()df = spark.createDataFrame(data, columns) # printing dataframe schemadf.printSchema() # show dataframedf.show()", "e": 30174, "s": 29662, "text": null }, { "code": null, "e": 30182, "s": 30174, "text": "Output:" }, { "code": null, "e": 30418, "s": 30182, "text": "1. explode_outer(): The explode_outer function splits the array column into a row for each element of the array element whether it contains a null value or not. Whereas the simple explode() ignores the null value present in the column." }, { "code": null, "e": 30426, "s": 30418, "text": "Python3" }, { "code": "# now using select function applying# explode_outer on array columndf4 = df.select(df.Name, explode_outer(df.Courses_enrolled)) # printing the schema of the df4df4.printSchema() # show df2df4.show()", "e": 30627, "s": 30426, "text": null }, { "code": null, "e": 30635, "s": 30627, "text": "Output:" }, { "code": null, "e": 30811, "s": 30635, "text": "As we have defined above that explode_outer() doesn’t ignore null values of the array column. Clearly, we can see that the null values are also displayed as rows of dataframe." }, { "code": null, "e": 31193, "s": 30811, "text": "2. posexplode(): The posexplode() splits the array column into rows for each element in the array and also provides the position of the elements in the array. It creates two columns “pos’ to carry the position of the array element and the ‘col’ to carry the particular array elements and ignores null values. Now, we will apply posexplode() on the array column ‘Courses_enrolled’." }, { "code": null, "e": 31201, "s": 31193, "text": "Python3" }, { "code": "# using select function applying # explode on array columndf2 = df.select(df.Name, posexplode(df.Courses_enrolled)) # printing the schema of the df2df2.printSchema() # show df2df2.show()", "e": 31390, "s": 31201, "text": null }, { "code": null, "e": 31398, "s": 31390, "text": "Output:" }, { "code": null, "e": 31636, "s": 31398, "text": "As the posexplode() splits the arrays into rows and also provides the position of array elements and in this output, we have got the positions of array elements in the ‘pos’ column. And it ignored null values present in the array column." }, { "code": null, "e": 32107, "s": 31636, "text": "3. posexplode_outer(): The posexplode_outer() splits the array column into rows for each element in the array and also provides the position of the elements in the array. It creates two columns “pos’ to carry the position of the array element and the ‘col’ to carry the particular array elements whether it contains a null value also. That means posexplode_outer() has the functionality of both the explode_outer() and posexplode() functions. Let’s see this in example:" }, { "code": null, "e": 32181, "s": 32107, "text": "Now, we will apply posexplode_outer() on array column ‘Courses_enrolled’." }, { "code": null, "e": 32189, "s": 32181, "text": "Python3" }, { "code": "# using select function applying # explode on array columndf2 = df.select(df.Name, posexplode_outer(df.Courses_enrolled)) # printing the schema of the df2df2.printSchema() # show df2df2.show()", "e": 32384, "s": 32189, "text": null }, { "code": null, "e": 32392, "s": 32384, "text": "Output:" }, { "code": null, "e": 32665, "s": 32392, "text": "As, posexplode_outer() provides functionalities of both the explode functions explode_outer() and posexplode(). In the output, clearly, we can see that we have got the rows and position values of all array elements including null values also in the ‘pos’ and ‘col’ column." }, { "code": null, "e": 32672, "s": 32665, "text": "Picked" }, { "code": null, "e": 32687, "s": 32672, "text": "Python-Pyspark" }, { "code": null, "e": 32694, "s": 32687, "text": "Python" }, { "code": null, "e": 32792, "s": 32694, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32810, "s": 32792, "text": "Python Dictionary" }, { "code": null, "e": 32845, "s": 32810, "text": "Read a file line by line in Python" }, { "code": null, "e": 32877, "s": 32845, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 32899, "s": 32877, "text": "Enumerate() in Python" }, { "code": null, "e": 32941, "s": 32899, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 32971, "s": 32941, "text": "Iterate over a list in Python" }, { "code": null, "e": 32997, "s": 32971, "text": "Python String | replace()" }, { "code": null, "e": 33041, "s": 32997, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 33070, "s": 33041, "text": "*args and **kwargs in Python" } ]
Python | Gender Identification by name using NLTK - GeeksforGeeks
20 Jan, 2022 Natural Language Toolkit (NLTK) is a platform used for building programs for text analysis. We can observe that male and female names have some distinctive characteristics. Names ending in a, e and i are likely to be female, while names ending in k, o, r, s and t are likely to be male. Let’s build a classifier to model these differences more precisely. In order to run the below python program, you must have to install NLTK. Please follow the installation steps. pip install nltk The first step in creating a classifier is deciding what features of the input are relevant, and how to encode those features. For this example, we’ll start by just looking at the final letter of a given name. The following feature extractor function builds a dictionary containing relevant information about a given name. Example : Input : gender_features('saurabh') Output : {'last_letter': 'h'} Python3 def gender_features(word): return {'last_letter': word[-1]}gender_features('mahavir')# output : {'last_letter': 'r'} A GUI will pop up then choose to download “all” for all packages, and then click ‘download’. This will give you all of the tokenizers, chunkers, other algorithms, and all of the corpora, so that’s why the installation will take quite a time. nltk.download() Classification is the task of choosing the correct class label for a given input. In basic classification tasks, each input is considered in isolation from all other inputs, and the set of labels is defined in advance. Some examples of classification tasks are: Deciding whether an email is spam or not.Deciding what the topic of a news article is, from a fixed list of topic areas such as “sports, ” “technology, ” and “politics.”Deciding whether a given occurrence of the word bank is used to refer to a river bank, a financial institution, the act of tilting to the side, or the act of depositing something in a financial institution. Deciding whether an email is spam or not. Deciding what the topic of a news article is, from a fixed list of topic areas such as “sports, ” “technology, ” and “politics.” Deciding whether a given occurrence of the word bank is used to refer to a river bank, a financial institution, the act of tilting to the side, or the act of depositing something in a financial institution. The basic classification task has a number of interesting variants. For example, in multi-class classification, each instance may be assigned multiple labels; in open-class classification, the set of labels is not defined in advance; and in sequence classification, a list of inputs are jointly classified. A classifier is called supervised if it is built based on training corpora containing the correct label for each input. The framework used by supervised classification is shown in figure.The training set is used to train the model, and the dev-test set is used to perform error analysis. The test set serves in our final evaluation of the system. For reasons discussed below, it is important that we employ a separate dev-test set for error analysis, rather than just using the test set. The division of the corpus data into different subsets is shown in following Figure : Get the link of text file used from here – By text urls directly. male.txt, female.txt male.txt and female.txt files are downloaded automatically while nltk.download() method executed successfully. Path in local system:path of nltk: C:\Users\currentUserName\AppData\Roamingpath for files inside nltk: \nltk_data\corpora\names Python3 # importing librariesimport randomfrom nltk.corpus import namesimport nltk def gender_features(word): return {'last_letter':word[-1]} # preparing a list of examples and corresponding class labels.labeled_names = ([(name, 'male') for name in names.words('male.txt')]+ [(name, 'female') for name in names.words('female.txt')]) random.shuffle(labeled_names) # we use the feature extractor to process the names data.featuresets = [(gender_features(n), gender) for (n, gender)in labeled_names] # Divide the resulting list of feature# sets into a training set and a test set.train_set, test_set = featuresets[500:], featuresets[:500] # The training set is used to # train a new "naive Bayes" classifier.classifier = nltk.NaiveBayesClassifier.train(train_set) print(classifier.classify(gender_features('mahavir'))) # output should be 'male'print(nltk.classify.accuracy(classifier, train_set)) # it shows accuracy of our classifier and # train_set. which must be more than 99 % # classifier.show_most_informative_features(10) Getting informative features from Classifier: Python3 classifier.show_most_informative_features(10)# 10 indicates 10 rows Output: rkbhola5 Natural-language-processing Python-nltk Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Python String | replace() *args and **kwargs in Python Reading and Writing to text files in Python Create a Pandas DataFrame from Lists Convert integer to string in Python Check if element exists in list in Python
[ { "code": null, "e": 25807, "s": 25779, "text": "\n20 Jan, 2022" }, { "code": null, "e": 26162, "s": 25807, "text": "Natural Language Toolkit (NLTK) is a platform used for building programs for text analysis. We can observe that male and female names have some distinctive characteristics. Names ending in a, e and i are likely to be female, while names ending in k, o, r, s and t are likely to be male. Let’s build a classifier to model these differences more precisely." }, { "code": null, "e": 26273, "s": 26162, "text": "In order to run the below python program, you must have to install NLTK. Please follow the installation steps." }, { "code": null, "e": 26290, "s": 26273, "text": "pip install nltk" }, { "code": null, "e": 26613, "s": 26290, "text": "The first step in creating a classifier is deciding what features of the input are relevant, and how to encode those features. For this example, we’ll start by just looking at the final letter of a given name. The following feature extractor function builds a dictionary containing relevant information about a given name." }, { "code": null, "e": 26623, "s": 26613, "text": "Example :" }, { "code": null, "e": 26688, "s": 26623, "text": "Input : gender_features('saurabh')\nOutput : {'last_letter': 'h'}" }, { "code": null, "e": 26696, "s": 26688, "text": "Python3" }, { "code": "def gender_features(word): return {'last_letter': word[-1]}gender_features('mahavir')# output : {'last_letter': 'r'}", "e": 26817, "s": 26696, "text": null }, { "code": null, "e": 27059, "s": 26817, "text": "A GUI will pop up then choose to download “all” for all packages, and then click ‘download’. This will give you all of the tokenizers, chunkers, other algorithms, and all of the corpora, so that’s why the installation will take quite a time." }, { "code": null, "e": 27075, "s": 27059, "text": "nltk.download()" }, { "code": null, "e": 27337, "s": 27075, "text": "Classification is the task of choosing the correct class label for a given input. In basic classification tasks, each input is considered in isolation from all other inputs, and the set of labels is defined in advance. Some examples of classification tasks are:" }, { "code": null, "e": 27713, "s": 27337, "text": "Deciding whether an email is spam or not.Deciding what the topic of a news article is, from a fixed list of topic areas such as “sports, ” “technology, ” and “politics.”Deciding whether a given occurrence of the word bank is used to refer to a river bank, a financial institution, the act of tilting to the side, or the act of depositing something in a financial institution." }, { "code": null, "e": 27755, "s": 27713, "text": "Deciding whether an email is spam or not." }, { "code": null, "e": 27884, "s": 27755, "text": "Deciding what the topic of a news article is, from a fixed list of topic areas such as “sports, ” “technology, ” and “politics.”" }, { "code": null, "e": 28091, "s": 27884, "text": "Deciding whether a given occurrence of the word bank is used to refer to a river bank, a financial institution, the act of tilting to the side, or the act of depositing something in a financial institution." }, { "code": null, "e": 28398, "s": 28091, "text": "The basic classification task has a number of interesting variants. For example, in multi-class classification, each instance may be assigned multiple labels; in open-class classification, the set of labels is not defined in advance; and in sequence classification, a list of inputs are jointly classified." }, { "code": null, "e": 28886, "s": 28398, "text": "A classifier is called supervised if it is built based on training corpora containing the correct label for each input. The framework used by supervised classification is shown in figure.The training set is used to train the model, and the dev-test set is used to perform error analysis. The test set serves in our final evaluation of the system. For reasons discussed below, it is important that we employ a separate dev-test set for error analysis, rather than just using the test set." }, { "code": null, "e": 28972, "s": 28886, "text": "The division of the corpus data into different subsets is shown in following Figure :" }, { "code": null, "e": 29015, "s": 28972, "text": "Get the link of text file used from here –" }, { "code": null, "e": 29059, "s": 29015, "text": "By text urls directly. male.txt, female.txt" }, { "code": null, "e": 29298, "s": 29059, "text": "male.txt and female.txt files are downloaded automatically while nltk.download() method executed successfully. Path in local system:path of nltk: C:\\Users\\currentUserName\\AppData\\Roamingpath for files inside nltk: \\nltk_data\\corpora\\names" }, { "code": null, "e": 29306, "s": 29298, "text": "Python3" }, { "code": "# importing librariesimport randomfrom nltk.corpus import namesimport nltk def gender_features(word): return {'last_letter':word[-1]} # preparing a list of examples and corresponding class labels.labeled_names = ([(name, 'male') for name in names.words('male.txt')]+ [(name, 'female') for name in names.words('female.txt')]) random.shuffle(labeled_names) # we use the feature extractor to process the names data.featuresets = [(gender_features(n), gender) for (n, gender)in labeled_names] # Divide the resulting list of feature# sets into a training set and a test set.train_set, test_set = featuresets[500:], featuresets[:500] # The training set is used to # train a new \"naive Bayes\" classifier.classifier = nltk.NaiveBayesClassifier.train(train_set) print(classifier.classify(gender_features('mahavir'))) # output should be 'male'print(nltk.classify.accuracy(classifier, train_set)) # it shows accuracy of our classifier and # train_set. which must be more than 99 % # classifier.show_most_informative_features(10)", "e": 30363, "s": 29306, "text": null }, { "code": null, "e": 30410, "s": 30363, "text": " Getting informative features from Classifier:" }, { "code": null, "e": 30418, "s": 30410, "text": "Python3" }, { "code": "classifier.show_most_informative_features(10)# 10 indicates 10 rows", "e": 30486, "s": 30418, "text": null }, { "code": null, "e": 30494, "s": 30486, "text": "Output:" }, { "code": null, "e": 30503, "s": 30494, "text": "rkbhola5" }, { "code": null, "e": 30531, "s": 30503, "text": "Natural-language-processing" }, { "code": null, "e": 30543, "s": 30531, "text": "Python-nltk" }, { "code": null, "e": 30550, "s": 30543, "text": "Python" }, { "code": null, "e": 30648, "s": 30550, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30666, "s": 30648, "text": "Python Dictionary" }, { "code": null, "e": 30698, "s": 30666, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 30720, "s": 30698, "text": "Enumerate() in Python" }, { "code": null, "e": 30762, "s": 30720, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 30788, "s": 30762, "text": "Python String | replace()" }, { "code": null, "e": 30817, "s": 30788, "text": "*args and **kwargs in Python" }, { "code": null, "e": 30861, "s": 30817, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 30898, "s": 30861, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 30934, "s": 30898, "text": "Convert integer to string in Python" } ]
A Product Array Puzzle | Set 3 - GeeksforGeeks
26 Sep, 2021 Given an array arr[] consisting of N integers, the task is to construct a Product array of the same size without using division (‘/’) operator such that each array element becomes equal to the product of all the elements of arr[] except arr[i]. Examples: Input: arr[] = {10, 3, 5, 6, 2}Output: 180 600 360 300 900Explanation:3 * 5 * 6 * 2 is the product of all array elements except 10 is 18010 * 5 * 6 * 2 is the product of all array elements except 3 is 600.10 * 3 * 6 * 2 is the product of all array elements except 5 is 360.10 * 3 * 5 * 2 is the product of all array elements except 6 is 300.10 * 3 * 6 * 5 is the product of all array elements except 2 is 9. Input: arr[] = {1, 2, 1, 3, 4}Output: 24 12 24 8 6 Approach: The idea is to use log() and exp() functions instead of log10() and pow(). Below are some observations regarding the same: Suppose M is the multiplication of all the array elements then the element of output array at ith position will be equal M/arr[i]. The divisions of two numbers can be performed by using the property of logarithm and exp functions. The logarithmic function is not defined for numbers less than zero so to maintain the such cases separately. Follow the steps below to solve the problem: Initialize two variables, say product = 1 and Z = 1, to store the product of array and count of zero elements. Traverse the array and multiply the product by arr[i] if arr[i] is not equal to 0. Otherwise, increment count of Z by one. Traverse the array arr[] and perform the following:If Z is 1 and arr[i] is not zero then update arr[i] as arr[i] = 0 and continue.Otherwise, if Z is 1 and arr[i] is 0 then update arr[i] as product and continue.Otherwise, if Z is greater than 1 then assign arr[i] as 0 and continue.Now find the value of abs(product)/abs(arr[i]) using the formula discussed above and store it in a variable say curr.If the value of arr[i] and product is negative or if arr[i] and product is positive then assign arr[i] as curr.Otherwise, assign arr[i] as -1*curr. If Z is 1 and arr[i] is not zero then update arr[i] as arr[i] = 0 and continue. Otherwise, if Z is 1 and arr[i] is 0 then update arr[i] as product and continue. Otherwise, if Z is greater than 1 then assign arr[i] as 0 and continue. Now find the value of abs(product)/abs(arr[i]) using the formula discussed above and store it in a variable say curr. If the value of arr[i] and product is negative or if arr[i] and product is positive then assign arr[i] as curr. Otherwise, assign arr[i] as -1*curr. After completing the above steps, print the array arr[]. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to form product array// with O(n) time and O(1) spacevoid productExceptSelf(int arr[], int N){ // Stores the product of array int product = 1; // Stores the count of zeros int z = 0; // Traverse the array for (int i = 0; i < N; i++) { // If arr[i] is not zero if (arr[i]) product *= arr[i]; // If arr[i] is zero then // increment count of z by 1 z += (arr[i] == 0); } // Stores the absolute value // of the product int a = abs(product), b; for (int i = 0; i < N; i++) { // If Z is equal to 1 if (z == 1) { // If arr[i] is not zero if (arr[i]) arr[i] = 0; // Else else arr[i] = product; continue; } // If count of 0s at least 2 else if (z > 1) { // Assign arr[i] = 0 arr[i] = 0; continue; } // Store absolute value of arr[i] int b = abs(arr[i]); // Find the value of a/b int curr = round(exp(log(a) - log(b))); // If arr[i] and product both // are less than zero if (arr[i] < 0 && product < 0) arr[i] = curr; // If arr[i] and product both // are greater than zero else if (arr[i] > 0 && product > 0) arr[i] = curr; // Else else arr[i] = -1 * curr; } // Traverse the array arr[] for (int i = 0; i < N; i++) { cout << arr[i] << " "; }} // Driver Codeint main(){ int arr[] = { 10, 3, 5, 6, 2 }; int N = sizeof(arr) / sizeof(arr[0]); // Function Call productExceptSelf(arr, N); return 0;} // Java program to implement// the above approachimport java.util.*; class GFG{ // Function to form product array// with O(n) time and O(1) spacestatic void productExceptSelf(int arr[], int N){ // Stores the product of array int product = 1; // Stores the count of zeros int z = 0; // Traverse the array for (int i = 0; i < N; i++) { // If arr[i] is not zero if (arr[i] != 0) product *= arr[i]; // If arr[i] is zero then // increment count of z by 1 if (arr[i] == 0) z += 1; } // Stores the absolute value // of the product int a = Math.abs(product); for (int i = 0; i < N; i++) { // If Z is equal to 1 if (z == 1) { // If arr[i] is not zero if (arr[i] != 0) arr[i] = 0; // Else else arr[i] = product; continue; } // If count of 0s at least 2 else if (z > 1) { // Assign arr[i] = 0 arr[i] = 0; continue; } // Store absolute value of arr[i] int b = Math.abs(arr[i]); // Find the value of a/b int curr = (int)Math.round(Math.exp(Math.log(a) - Math.log(b))); // If arr[i] and product both // are less than zero if (arr[i] < 0 && product < 0) arr[i] = curr; // If arr[i] and product both // are greater than zero else if (arr[i] > 0 && product > 0) arr[i] = curr; // Else else arr[i] = -1 * curr; } // Traverse the array arr[] for (int i = 0; i < N; i++) { System.out.print(arr[i] + " "); }} // Driver Codepublic static void main(String args[]){ int arr[] = { 10, 3, 5, 6, 2 }; int N = arr.length; // Function Call productExceptSelf(arr, N);}} // This code is contributed by splevel62. # Python 3 program for the above approachimport math # Function to form product array# with O(n) time and O(1) spacedef productExceptSelf(arr, N) : # Stores the product of array product = 1 # Stores the count of zeros z = 0 # Traverse the array for i in range(N): # If arr[i] is not zero if (arr[i] != 0) : product *= arr[i] # If arr[i] is zero then # increment count of z by 1 if(arr[i] == 0): z += 1 # Stores the absolute value # of the product a = abs(product) for i in range(N): # If Z is equal to 1 if (z == 1) : # If arr[i] is not zero if (arr[i] != 0) : arr[i] = 0 # Else else : arr[i] = product continue # If count of 0s at least 2 elif (z > 1) : # Assign arr[i] = 0 arr[i] = 0 continue # Store absolute value of arr[i] b = abs(arr[i]) # Find the value of a/b curr = round(math.exp(math.log(a) - math.log(b))) # If arr[i] and product both # are less than zero if (arr[i] < 0 and product < 0): arr[i] = curr # If arr[i] and product both # are greater than zero elif (arr[i] > 0 and product > 0): arr[i] = curr # Else else: arr[i] = -1 * curr # Traverse the array arr[] for i in range(N): print(arr[i], end = " ") # Driver Codearr = [ 10, 3, 5, 6, 2 ]N = len(arr) # Function CallproductExceptSelf(arr, N) # This code is contributed by code_hunt. // C# program for the above approachusing System;class GFG{ // Function to form product array// with O(n) time and O(1) spacestatic void productExceptSelf(int[] arr, int N){ // Stores the product of array int product = 1; // Stores the count of zeros int z = 0; // Traverse the array for (int i = 0; i < N; i++) { // If arr[i] is not zero if (arr[i] != 0) product *= arr[i]; // If arr[i] is zero then // increment count of z by 1 if (arr[i] == 0) z += 1; } // Stores the absolute value // of the product int a = Math.Abs(product); for (int i = 0; i < N; i++) { // If Z is equal to 1 if (z == 1) { // If arr[i] is not zero if (arr[i] != 0) arr[i] = 0; // Else else arr[i] = product; continue; } // If count of 0s at least 2 else if (z > 1) { // Assign arr[i] = 0 arr[i] = 0; continue; } // Store absolute value of arr[i] int b = Math.Abs(arr[i]); // Find the value of a/b int curr = (int)Math.Round(Math.Exp(Math.Log(a) - Math.Log(b))); // If arr[i] and product both // are less than zero if (arr[i] < 0 && product < 0) arr[i] = curr; // If arr[i] and product both // are greater than zero else if (arr[i] > 0 && product > 0) arr[i] = curr; // Else else arr[i] = -1 * curr; } // Traverse the array arr[] for (int i = 0; i < N; i++) { Console.Write(arr[i] + " "); }} // Driver Codepublic static void Main(String[] args){ int[] arr = { 10, 3, 5, 6, 2 }; int N = arr.Length; // Function Call productExceptSelf(arr, N);}} // This code is contributed by sanjoy_62. <script> // Javascript Program to check matrix// is scalar matrix or not. // Function to form product array// with O(n) time and O(1) spacefunction productExceptSelf(arr, N){ // Stores the product of array let product = 1; // Stores the count of zeros let z = 0; // Traverse the array for (let i = 0; i < N; i++) { // If arr[i] is not zero if (arr[i] != 0) product *= arr[i]; // If arr[i] is zero then // increment count of z by 1 if (arr[i] == 0) z += 1; } // Stores the absolute value // of the product let a = Math.abs(product); for (let i = 0; i < N; i++) { // If Z is equal to 1 if (z == 1) { // If arr[i] is not zero if (arr[i] != 0) arr[i] = 0; // Else else arr[i] = product; continue; } // If count of 0s at least 2 else if (z > 1) { // Assign arr[i] = 0 arr[i] = 0; continue; } // Store absolute value of arr[i] let b = Math.abs(arr[i]); // Find the value of a/b let curr = Math.round(Math.exp(Math.log(a) - Math.log(b))); // If arr[i] and product both // are less than zero if (arr[i] < 0 && product < 0) arr[i] = curr; // If arr[i] and product both // are greater than zero else if (arr[i] > 0 && product > 0) arr[i] = curr; // Else else arr[i] = -1 * curr; } // Traverse the array arr[] for (let i = 0; i < N; i++) { document.write(arr[i] + " "); }} // Driver Code let arr = [ 10, 3, 5, 6, 2 ]; let N = arr.length; // Function Call productExceptSelf(arr, N); // This code is contributed by souravghosh0416.</script> 180 600 360 300 900 Time Complexity: O(N)Auxiliary Space: O(1) Alternate Approaches: Please refer to the previous posts of this article for alternate approaches: A Product Array Puzzle A Product Array Puzzle | Set 2 splevel62 sanjoy_62 code_hunt souravghosh0416 saurabh1990aror Accolite Amazon DE Shaw Morgan Stanley Opera Arrays Mathematical Morgan Stanley Accolite Amazon Opera DE Shaw Arrays Mathematical 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 Introduction to Arrays Multidimensional Arrays in Java Linear Search Linked List vs Array Program for Fibonacci numbers Write a program to print all permutations of a given string Set in C++ Standard Template Library (STL) C++ Data Types Coin Change | DP-7
[ { "code": null, "e": 26521, "s": 26493, "text": "\n26 Sep, 2021" }, { "code": null, "e": 26766, "s": 26521, "text": "Given an array arr[] consisting of N integers, the task is to construct a Product array of the same size without using division (‘/’) operator such that each array element becomes equal to the product of all the elements of arr[] except arr[i]." }, { "code": null, "e": 26776, "s": 26766, "text": "Examples:" }, { "code": null, "e": 27184, "s": 26776, "text": "Input: arr[] = {10, 3, 5, 6, 2}Output: 180 600 360 300 900Explanation:3 * 5 * 6 * 2 is the product of all array elements except 10 is 18010 * 5 * 6 * 2 is the product of all array elements except 3 is 600.10 * 3 * 6 * 2 is the product of all array elements except 5 is 360.10 * 3 * 5 * 2 is the product of all array elements except 6 is 300.10 * 3 * 6 * 5 is the product of all array elements except 2 is 9." }, { "code": null, "e": 27235, "s": 27184, "text": "Input: arr[] = {1, 2, 1, 3, 4}Output: 24 12 24 8 6" }, { "code": null, "e": 27368, "s": 27235, "text": "Approach: The idea is to use log() and exp() functions instead of log10() and pow(). Below are some observations regarding the same:" }, { "code": null, "e": 27499, "s": 27368, "text": "Suppose M is the multiplication of all the array elements then the element of output array at ith position will be equal M/arr[i]." }, { "code": null, "e": 27599, "s": 27499, "text": "The divisions of two numbers can be performed by using the property of logarithm and exp functions." }, { "code": null, "e": 27708, "s": 27599, "text": "The logarithmic function is not defined for numbers less than zero so to maintain the such cases separately." }, { "code": null, "e": 27753, "s": 27708, "text": "Follow the steps below to solve the problem:" }, { "code": null, "e": 27864, "s": 27753, "text": "Initialize two variables, say product = 1 and Z = 1, to store the product of array and count of zero elements." }, { "code": null, "e": 27987, "s": 27864, "text": "Traverse the array and multiply the product by arr[i] if arr[i] is not equal to 0. Otherwise, increment count of Z by one." }, { "code": null, "e": 28533, "s": 27987, "text": "Traverse the array arr[] and perform the following:If Z is 1 and arr[i] is not zero then update arr[i] as arr[i] = 0 and continue.Otherwise, if Z is 1 and arr[i] is 0 then update arr[i] as product and continue.Otherwise, if Z is greater than 1 then assign arr[i] as 0 and continue.Now find the value of abs(product)/abs(arr[i]) using the formula discussed above and store it in a variable say curr.If the value of arr[i] and product is negative or if arr[i] and product is positive then assign arr[i] as curr.Otherwise, assign arr[i] as -1*curr." }, { "code": null, "e": 28613, "s": 28533, "text": "If Z is 1 and arr[i] is not zero then update arr[i] as arr[i] = 0 and continue." }, { "code": null, "e": 28694, "s": 28613, "text": "Otherwise, if Z is 1 and arr[i] is 0 then update arr[i] as product and continue." }, { "code": null, "e": 28766, "s": 28694, "text": "Otherwise, if Z is greater than 1 then assign arr[i] as 0 and continue." }, { "code": null, "e": 28884, "s": 28766, "text": "Now find the value of abs(product)/abs(arr[i]) using the formula discussed above and store it in a variable say curr." }, { "code": null, "e": 28996, "s": 28884, "text": "If the value of arr[i] and product is negative or if arr[i] and product is positive then assign arr[i] as curr." }, { "code": null, "e": 29033, "s": 28996, "text": "Otherwise, assign arr[i] as -1*curr." }, { "code": null, "e": 29090, "s": 29033, "text": "After completing the above steps, print the array arr[]." }, { "code": null, "e": 29141, "s": 29090, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 29145, "s": 29141, "text": "C++" }, { "code": null, "e": 29150, "s": 29145, "text": "Java" }, { "code": null, "e": 29158, "s": 29150, "text": "Python3" }, { "code": null, "e": 29161, "s": 29158, "text": "C#" }, { "code": null, "e": 29172, "s": 29161, "text": "Javascript" }, { "code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to form product array// with O(n) time and O(1) spacevoid productExceptSelf(int arr[], int N){ // Stores the product of array int product = 1; // Stores the count of zeros int z = 0; // Traverse the array for (int i = 0; i < N; i++) { // If arr[i] is not zero if (arr[i]) product *= arr[i]; // If arr[i] is zero then // increment count of z by 1 z += (arr[i] == 0); } // Stores the absolute value // of the product int a = abs(product), b; for (int i = 0; i < N; i++) { // If Z is equal to 1 if (z == 1) { // If arr[i] is not zero if (arr[i]) arr[i] = 0; // Else else arr[i] = product; continue; } // If count of 0s at least 2 else if (z > 1) { // Assign arr[i] = 0 arr[i] = 0; continue; } // Store absolute value of arr[i] int b = abs(arr[i]); // Find the value of a/b int curr = round(exp(log(a) - log(b))); // If arr[i] and product both // are less than zero if (arr[i] < 0 && product < 0) arr[i] = curr; // If arr[i] and product both // are greater than zero else if (arr[i] > 0 && product > 0) arr[i] = curr; // Else else arr[i] = -1 * curr; } // Traverse the array arr[] for (int i = 0; i < N; i++) { cout << arr[i] << \" \"; }} // Driver Codeint main(){ int arr[] = { 10, 3, 5, 6, 2 }; int N = sizeof(arr) / sizeof(arr[0]); // Function Call productExceptSelf(arr, N); return 0;}", "e": 30980, "s": 29172, "text": null }, { "code": "// Java program to implement// the above approachimport java.util.*; class GFG{ // Function to form product array// with O(n) time and O(1) spacestatic void productExceptSelf(int arr[], int N){ // Stores the product of array int product = 1; // Stores the count of zeros int z = 0; // Traverse the array for (int i = 0; i < N; i++) { // If arr[i] is not zero if (arr[i] != 0) product *= arr[i]; // If arr[i] is zero then // increment count of z by 1 if (arr[i] == 0) z += 1; } // Stores the absolute value // of the product int a = Math.abs(product); for (int i = 0; i < N; i++) { // If Z is equal to 1 if (z == 1) { // If arr[i] is not zero if (arr[i] != 0) arr[i] = 0; // Else else arr[i] = product; continue; } // If count of 0s at least 2 else if (z > 1) { // Assign arr[i] = 0 arr[i] = 0; continue; } // Store absolute value of arr[i] int b = Math.abs(arr[i]); // Find the value of a/b int curr = (int)Math.round(Math.exp(Math.log(a) - Math.log(b))); // If arr[i] and product both // are less than zero if (arr[i] < 0 && product < 0) arr[i] = curr; // If arr[i] and product both // are greater than zero else if (arr[i] > 0 && product > 0) arr[i] = curr; // Else else arr[i] = -1 * curr; } // Traverse the array arr[] for (int i = 0; i < N; i++) { System.out.print(arr[i] + \" \"); }} // Driver Codepublic static void main(String args[]){ int arr[] = { 10, 3, 5, 6, 2 }; int N = arr.length; // Function Call productExceptSelf(arr, N);}} // This code is contributed by splevel62.", "e": 32899, "s": 30980, "text": null }, { "code": "# Python 3 program for the above approachimport math # Function to form product array# with O(n) time and O(1) spacedef productExceptSelf(arr, N) : # Stores the product of array product = 1 # Stores the count of zeros z = 0 # Traverse the array for i in range(N): # If arr[i] is not zero if (arr[i] != 0) : product *= arr[i] # If arr[i] is zero then # increment count of z by 1 if(arr[i] == 0): z += 1 # Stores the absolute value # of the product a = abs(product) for i in range(N): # If Z is equal to 1 if (z == 1) : # If arr[i] is not zero if (arr[i] != 0) : arr[i] = 0 # Else else : arr[i] = product continue # If count of 0s at least 2 elif (z > 1) : # Assign arr[i] = 0 arr[i] = 0 continue # Store absolute value of arr[i] b = abs(arr[i]) # Find the value of a/b curr = round(math.exp(math.log(a) - math.log(b))) # If arr[i] and product both # are less than zero if (arr[i] < 0 and product < 0): arr[i] = curr # If arr[i] and product both # are greater than zero elif (arr[i] > 0 and product > 0): arr[i] = curr # Else else: arr[i] = -1 * curr # Traverse the array arr[] for i in range(N): print(arr[i], end = \" \") # Driver Codearr = [ 10, 3, 5, 6, 2 ]N = len(arr) # Function CallproductExceptSelf(arr, N) # This code is contributed by code_hunt.", "e": 34565, "s": 32899, "text": null }, { "code": "// C# program for the above approachusing System;class GFG{ // Function to form product array// with O(n) time and O(1) spacestatic void productExceptSelf(int[] arr, int N){ // Stores the product of array int product = 1; // Stores the count of zeros int z = 0; // Traverse the array for (int i = 0; i < N; i++) { // If arr[i] is not zero if (arr[i] != 0) product *= arr[i]; // If arr[i] is zero then // increment count of z by 1 if (arr[i] == 0) z += 1; } // Stores the absolute value // of the product int a = Math.Abs(product); for (int i = 0; i < N; i++) { // If Z is equal to 1 if (z == 1) { // If arr[i] is not zero if (arr[i] != 0) arr[i] = 0; // Else else arr[i] = product; continue; } // If count of 0s at least 2 else if (z > 1) { // Assign arr[i] = 0 arr[i] = 0; continue; } // Store absolute value of arr[i] int b = Math.Abs(arr[i]); // Find the value of a/b int curr = (int)Math.Round(Math.Exp(Math.Log(a) - Math.Log(b))); // If arr[i] and product both // are less than zero if (arr[i] < 0 && product < 0) arr[i] = curr; // If arr[i] and product both // are greater than zero else if (arr[i] > 0 && product > 0) arr[i] = curr; // Else else arr[i] = -1 * curr; } // Traverse the array arr[] for (int i = 0; i < N; i++) { Console.Write(arr[i] + \" \"); }} // Driver Codepublic static void Main(String[] args){ int[] arr = { 10, 3, 5, 6, 2 }; int N = arr.Length; // Function Call productExceptSelf(arr, N);}} // This code is contributed by sanjoy_62.", "e": 36488, "s": 34565, "text": null }, { "code": "<script> // Javascript Program to check matrix// is scalar matrix or not. // Function to form product array// with O(n) time and O(1) spacefunction productExceptSelf(arr, N){ // Stores the product of array let product = 1; // Stores the count of zeros let z = 0; // Traverse the array for (let i = 0; i < N; i++) { // If arr[i] is not zero if (arr[i] != 0) product *= arr[i]; // If arr[i] is zero then // increment count of z by 1 if (arr[i] == 0) z += 1; } // Stores the absolute value // of the product let a = Math.abs(product); for (let i = 0; i < N; i++) { // If Z is equal to 1 if (z == 1) { // If arr[i] is not zero if (arr[i] != 0) arr[i] = 0; // Else else arr[i] = product; continue; } // If count of 0s at least 2 else if (z > 1) { // Assign arr[i] = 0 arr[i] = 0; continue; } // Store absolute value of arr[i] let b = Math.abs(arr[i]); // Find the value of a/b let curr = Math.round(Math.exp(Math.log(a) - Math.log(b))); // If arr[i] and product both // are less than zero if (arr[i] < 0 && product < 0) arr[i] = curr; // If arr[i] and product both // are greater than zero else if (arr[i] > 0 && product > 0) arr[i] = curr; // Else else arr[i] = -1 * curr; } // Traverse the array arr[] for (let i = 0; i < N; i++) { document.write(arr[i] + \" \"); }} // Driver Code let arr = [ 10, 3, 5, 6, 2 ]; let N = arr.length; // Function Call productExceptSelf(arr, N); // This code is contributed by souravghosh0416.</script>", "e": 38381, "s": 36488, "text": null }, { "code": null, "e": 38401, "s": 38381, "text": "180 600 360 300 900" }, { "code": null, "e": 38446, "s": 38403, "text": "Time Complexity: O(N)Auxiliary Space: O(1)" }, { "code": null, "e": 38545, "s": 38446, "text": "Alternate Approaches: Please refer to the previous posts of this article for alternate approaches:" }, { "code": null, "e": 38568, "s": 38545, "text": "A Product Array Puzzle" }, { "code": null, "e": 38599, "s": 38568, "text": "A Product Array Puzzle | Set 2" }, { "code": null, "e": 38609, "s": 38599, "text": "splevel62" }, { "code": null, "e": 38619, "s": 38609, "text": "sanjoy_62" }, { "code": null, "e": 38629, "s": 38619, "text": "code_hunt" }, { "code": null, "e": 38645, "s": 38629, "text": "souravghosh0416" }, { "code": null, "e": 38661, "s": 38645, "text": "saurabh1990aror" }, { "code": null, "e": 38670, "s": 38661, "text": "Accolite" }, { "code": null, "e": 38677, "s": 38670, "text": "Amazon" }, { "code": null, "e": 38685, "s": 38677, "text": "DE Shaw" }, { "code": null, "e": 38700, "s": 38685, "text": "Morgan Stanley" }, { "code": null, "e": 38706, "s": 38700, "text": "Opera" }, { "code": null, "e": 38713, "s": 38706, "text": "Arrays" }, { "code": null, "e": 38726, "s": 38713, "text": "Mathematical" }, { "code": null, "e": 38741, "s": 38726, "text": "Morgan Stanley" }, { "code": null, "e": 38750, "s": 38741, "text": "Accolite" }, { "code": null, "e": 38757, "s": 38750, "text": "Amazon" }, { "code": null, "e": 38763, "s": 38757, "text": "Opera" }, { "code": null, "e": 38771, "s": 38763, "text": "DE Shaw" }, { "code": null, "e": 38778, "s": 38771, "text": "Arrays" }, { "code": null, "e": 38791, "s": 38778, "text": "Mathematical" }, { "code": null, "e": 38889, "s": 38791, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 38957, "s": 38889, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 38980, "s": 38957, "text": "Introduction to Arrays" }, { "code": null, "e": 39012, "s": 38980, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 39026, "s": 39012, "text": "Linear Search" }, { "code": null, "e": 39047, "s": 39026, "text": "Linked List vs Array" }, { "code": null, "e": 39077, "s": 39047, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 39137, "s": 39077, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 39180, "s": 39137, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 39195, "s": 39180, "text": "C++ Data Types" } ]
Variables and Datatypes in JavaScript - GeeksforGeeks
26 Jul, 2021 Datatypes in JavaScript There are majorly two types of languages. First, one is Statically typed language where each variable and expression type is already known at compile time. Once a variable is declared to be of a certain data type, it cannot hold values of other data types. Example: C, C++, Java. Java // Java(Statically typed)int x = 5 // variable x is of type int and it will not store any other type.string y = 'abc' // type string and will only accept string values Other, Dynamically typed languages: These languages can receive different data types over time. For example- Ruby, Python, JavaScript, etc. Javascript // Javascript(Dynamically typed)var x = 5; // can store an integervar name = 'string'; // can also store a string. JavaScript is a dynamically typed (also called loosely typed) scripting language. That is, in JavaScript variables can receive different data types over time. Datatypes are basically typed data that can be used and manipulated in a program. The latest ECMAScript(ES6) standard defines seven data types: Out of which six data types are Primitive(predefined). Numbers: 5, 6.5, 7 etc. String: “Hello GeeksforGeeks” etc. Boolean: Represent a logical entity and can have two values: true or false. Null: This type has only one value : null. Undefined: A variable that has not been assigned a value is undefined. Object: It is the most important data-type and forms the building blocks for modern JavaScript. We will learn about these data types in detail in further articles. Variables in JavaScript: Variables in JavaScript are containers that hold reusable data. It is the basic unit of storage in a program. The value stored in a variable can be changed during program execution. A variable is only a name given to a memory location, all the operations done on the variable effects that memory location. In JavaScript, all the variables must be declared before they can be used. Before ES2015, JavaScript variables were solely declared using the var keyword followed by the name of the variable and semi-colon. Below is the syntax to create variables in JavaScript: var var_name; var x; The var_name is the name of the variable which should be defined by the user and should be unique. These types of names are also known as identifiers. The rules for creating an identifier in JavaScript are, the name of the identifier should not be any pre-defined word(known as keywords), the first character must be a letter, an underscore (_), or a dollar sign ($). Subsequent characters may be any letter or digit or an underscore or dollar sign. Notice in the above code sample, we didn’t assign any values to the variables. We are only saying they exist. If you were to look at the value of each variable in the above code sample, it would be undefined. We can initialize the variables either at the time of declaration or also later when we want to use them. Below are some examples of declaring and initializing variables in JavaScript: // declaring single variable var name; // declaring multiple variables var name, title, num; // initializing variables var name = "Harsh"; name = "Rakesh"; JavaScript is also known as untyped language. This means, that once a variable is created in JavaScript using the keyword var, we can store any type of value in this variable supported by JavaScript. Below is the example for this: // creating variable to store a number var num = 5; // store string in the variable num num = "GeeksforGeeks"; The above example executes well without any error in JavaScript, unlike other programming languages. Variables in JavaScript can also evaluate simple mathematical expressions and assume their value. // storing a mathematical expression var x = 5 + 10 + 1; console.log(x); // 16 After ES2015, we now have two new variable containers: let and const. Now we shall look at both of them one by one. The variable type Let shares lots of similarities with var but unlike var, it has scope constraints. To know more about them visit let vs var. Let’s make use of the let variable: // let variable let x; // undefined let name = 'Mukul'; // can also declare multiple values let a=1,b=2,c=3; // assignment let a = 3; a = 4; // works same as var. Const is another variable type assigned to data whose value cannot and will not change throughout the script. // const variable const name = 'Mukul'; name = 'Mayank'; // will give Assignment to constant variable error. Variable Scope in Javascript Scope of a variable is the part of the program from where the variable may directly be accessible. In JavaScript, there are two types of scopes: Global Scope – Scope outside the outermost function attached to Window.Local Scope – Inside the function being executed. Global Scope – Scope outside the outermost function attached to Window. Local Scope – Inside the function being executed. Let’s look at the code below. We have a global variable defined in the first line in the global scope. Then we have a local variable defined inside the function fun(). Javascript let globalVar = "This is a global variable"; function fun() { let localVar = "This is a local variable"; console.log(globalVar); console.log(localVar);} fun(); Output: When we execute the function fun(), the output shows that both global, and local variables, are accessible inside the function as we are able to console.log them. This shows that inside the function we have access to both global variables (declared outside the function) and local variables (declared inside the function). Let’s move the console.log statements outside the function and put them just after calling the function. Javascript let globalVar = "This is a global variable"; function fun() { let localVar = "This is a local variable";} fun(); console.log(globalVar);console.log(localVar); Output: We are still able to see the value of the global variable, but for the local variable, console.log throws an error. This is because now the console.log statements are present in global scope where they have access to global variables but cannot access the local variables. Also, any variable defined in a function with the same name as a global variable takes precedence over the global variable, shadowing it. To understand variable scopes in detail in JavaScript, please refer to the article on understanding variable scopes in Javascript. immukul simmytarika5 sagartomar9927 javascript-basics JavaScript Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React How to calculate the number of days between two dates in javascript? File uploading in React.js How to append HTML code to a div using JavaScript ? Hide or show elements in HTML using display property How to Open URL in New Tab using JavaScript ? Difference Between PUT and PATCH Request
[ { "code": null, "e": 31327, "s": 31299, "text": "\n26 Jul, 2021" }, { "code": null, "e": 31351, "s": 31327, "text": "Datatypes in JavaScript" }, { "code": null, "e": 31608, "s": 31351, "text": "There are majorly two types of languages. First, one is Statically typed language where each variable and expression type is already known at compile time. Once a variable is declared to be of a certain data type, it cannot hold values of other data types." }, { "code": null, "e": 31632, "s": 31608, "text": "Example: C, C++, Java. " }, { "code": null, "e": 31637, "s": 31632, "text": "Java" }, { "code": "// Java(Statically typed)int x = 5 // variable x is of type int and it will not store any other type.string y = 'abc' // type string and will only accept string values", "e": 31806, "s": 31637, "text": null }, { "code": null, "e": 31946, "s": 31806, "text": "Other, Dynamically typed languages: These languages can receive different data types over time. For example- Ruby, Python, JavaScript, etc." }, { "code": null, "e": 31957, "s": 31946, "text": "Javascript" }, { "code": "// Javascript(Dynamically typed)var x = 5; // can store an integervar name = 'string'; // can also store a string.", "e": 32072, "s": 31957, "text": null }, { "code": null, "e": 32313, "s": 32072, "text": "JavaScript is a dynamically typed (also called loosely typed) scripting language. That is, in JavaScript variables can receive different data types over time. Datatypes are basically typed data that can be used and manipulated in a program." }, { "code": null, "e": 32431, "s": 32313, "text": "The latest ECMAScript(ES6) standard defines seven data types: Out of which six data types are Primitive(predefined). " }, { "code": null, "e": 32455, "s": 32431, "text": "Numbers: 5, 6.5, 7 etc." }, { "code": null, "e": 32490, "s": 32455, "text": "String: “Hello GeeksforGeeks” etc." }, { "code": null, "e": 32566, "s": 32490, "text": "Boolean: Represent a logical entity and can have two values: true or false." }, { "code": null, "e": 32609, "s": 32566, "text": "Null: This type has only one value : null." }, { "code": null, "e": 32680, "s": 32609, "text": "Undefined: A variable that has not been assigned a value is undefined." }, { "code": null, "e": 32844, "s": 32680, "text": "Object: It is the most important data-type and forms the building blocks for modern JavaScript. We will learn about these data types in detail in further articles." }, { "code": null, "e": 32869, "s": 32844, "text": "Variables in JavaScript:" }, { "code": null, "e": 32981, "s": 32869, "text": "Variables in JavaScript are containers that hold reusable data. It is the basic unit of storage in a program. " }, { "code": null, "e": 33053, "s": 32981, "text": "The value stored in a variable can be changed during program execution." }, { "code": null, "e": 33177, "s": 33053, "text": "A variable is only a name given to a memory location, all the operations done on the variable effects that memory location." }, { "code": null, "e": 33252, "s": 33177, "text": "In JavaScript, all the variables must be declared before they can be used." }, { "code": null, "e": 33440, "s": 33252, "text": "Before ES2015, JavaScript variables were solely declared using the var keyword followed by the name of the variable and semi-colon. Below is the syntax to create variables in JavaScript: " }, { "code": null, "e": 33461, "s": 33440, "text": "var var_name;\nvar x;" }, { "code": null, "e": 34120, "s": 33461, "text": "The var_name is the name of the variable which should be defined by the user and should be unique. These types of names are also known as identifiers. The rules for creating an identifier in JavaScript are, the name of the identifier should not be any pre-defined word(known as keywords), the first character must be a letter, an underscore (_), or a dollar sign ($). Subsequent characters may be any letter or digit or an underscore or dollar sign. Notice in the above code sample, we didn’t assign any values to the variables. We are only saying they exist. If you were to look at the value of each variable in the above code sample, it would be undefined." }, { "code": null, "e": 34307, "s": 34120, "text": "We can initialize the variables either at the time of declaration or also later when we want to use them. Below are some examples of declaring and initializing variables in JavaScript: " }, { "code": null, "e": 34465, "s": 34307, "text": "// declaring single variable\nvar name;\n\n// declaring multiple variables\nvar name, title, num;\n\n// initializing variables\nvar name = \"Harsh\";\nname = \"Rakesh\";" }, { "code": null, "e": 34698, "s": 34465, "text": "JavaScript is also known as untyped language. This means, that once a variable is created in JavaScript using the keyword var, we can store any type of value in this variable supported by JavaScript. Below is the example for this: " }, { "code": null, "e": 34810, "s": 34698, "text": "// creating variable to store a number\nvar num = 5;\n\n// store string in the variable num\nnum = \"GeeksforGeeks\";" }, { "code": null, "e": 35011, "s": 34810, "text": "The above example executes well without any error in JavaScript, unlike other programming languages. Variables in JavaScript can also evaluate simple mathematical expressions and assume their value. " }, { "code": null, "e": 35090, "s": 35011, "text": "// storing a mathematical expression\nvar x = 5 + 10 + 1;\nconsole.log(x); // 16" }, { "code": null, "e": 35387, "s": 35090, "text": "After ES2015, we now have two new variable containers: let and const. Now we shall look at both of them one by one. The variable type Let shares lots of similarities with var but unlike var, it has scope constraints. To know more about them visit let vs var. Let’s make use of the let variable: " }, { "code": null, "e": 35552, "s": 35387, "text": "// let variable\nlet x; // undefined\nlet name = 'Mukul';\n\n// can also declare multiple values\nlet a=1,b=2,c=3;\n\n// assignment\nlet a = 3;\na = 4; // works same as var." }, { "code": null, "e": 35663, "s": 35552, "text": "Const is another variable type assigned to data whose value cannot and will not change throughout the script. " }, { "code": null, "e": 35772, "s": 35663, "text": "// const variable\nconst name = 'Mukul';\nname = 'Mayank'; // will give Assignment to constant variable error." }, { "code": null, "e": 35801, "s": 35772, "text": "Variable Scope in Javascript" }, { "code": null, "e": 35948, "s": 35801, "text": "Scope of a variable is the part of the program from where the variable may directly be accessible. In JavaScript, there are two types of scopes: " }, { "code": null, "e": 36069, "s": 35948, "text": "Global Scope – Scope outside the outermost function attached to Window.Local Scope – Inside the function being executed." }, { "code": null, "e": 36141, "s": 36069, "text": "Global Scope – Scope outside the outermost function attached to Window." }, { "code": null, "e": 36191, "s": 36141, "text": "Local Scope – Inside the function being executed." }, { "code": null, "e": 36360, "s": 36191, "text": "Let’s look at the code below. We have a global variable defined in the first line in the global scope. Then we have a local variable defined inside the function fun(). " }, { "code": null, "e": 36371, "s": 36360, "text": "Javascript" }, { "code": "let globalVar = \"This is a global variable\"; function fun() { let localVar = \"This is a local variable\"; console.log(globalVar); console.log(localVar);} fun();", "e": 36535, "s": 36371, "text": null }, { "code": null, "e": 36544, "s": 36535, "text": "Output: " }, { "code": null, "e": 36973, "s": 36544, "text": "When we execute the function fun(), the output shows that both global, and local variables, are accessible inside the function as we are able to console.log them. This shows that inside the function we have access to both global variables (declared outside the function) and local variables (declared inside the function). Let’s move the console.log statements outside the function and put them just after calling the function. " }, { "code": null, "e": 36984, "s": 36973, "text": "Javascript" }, { "code": "let globalVar = \"This is a global variable\"; function fun() { let localVar = \"This is a local variable\";} fun(); console.log(globalVar);console.log(localVar);", "e": 37144, "s": 36984, "text": null }, { "code": null, "e": 37153, "s": 37144, "text": "Output: " }, { "code": null, "e": 37427, "s": 37153, "text": "We are still able to see the value of the global variable, but for the local variable, console.log throws an error. This is because now the console.log statements are present in global scope where they have access to global variables but cannot access the local variables. " }, { "code": null, "e": 37697, "s": 37427, "text": "Also, any variable defined in a function with the same name as a global variable takes precedence over the global variable, shadowing it. To understand variable scopes in detail in JavaScript, please refer to the article on understanding variable scopes in Javascript. " }, { "code": null, "e": 37705, "s": 37697, "text": "immukul" }, { "code": null, "e": 37718, "s": 37705, "text": "simmytarika5" }, { "code": null, "e": 37733, "s": 37718, "text": "sagartomar9927" }, { "code": null, "e": 37751, "s": 37733, "text": "javascript-basics" }, { "code": null, "e": 37762, "s": 37751, "text": "JavaScript" }, { "code": null, "e": 37860, "s": 37762, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 37900, "s": 37860, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 37945, "s": 37900, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 38006, "s": 37945, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 38078, "s": 38006, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 38147, "s": 38078, "text": "How to calculate the number of days between two dates in javascript?" }, { "code": null, "e": 38174, "s": 38147, "text": "File uploading in React.js" }, { "code": null, "e": 38226, "s": 38174, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 38279, "s": 38226, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 38325, "s": 38279, "text": "How to Open URL in New Tab using JavaScript ?" } ]
Find a peak element - GeeksforGeeks
28 Apr, 2022 Given an array of integers. Find a peak element in it. An array element is a peak if it is NOT smaller than its neighbours. For corner elements, we need to consider only one neighbour. Example: Input: array[]= {5, 10, 20, 15} Output: 20 The element 20 has neighbours 10 and 15, both of them are less than 20. Input: array[] = {10, 20, 15, 2, 23, 90, 67} Output: 20 or 90 The element 20 has neighbours 10 and 15, both of them are less than 20, similarly 90 has neighbours 23 and 67. Following corner cases give better idea about the problem. If input array is sorted in strictly increasing order, the last element is always a peak element. For example, 50 is peak element in {10, 20, 30, 40, 50}.If the input array is sorted in strictly decreasing order, the first element is always a peak element. 100 is the peak element in {100, 80, 60, 50, 20}.If all elements of input array are same, every element is a peak element. If input array is sorted in strictly increasing order, the last element is always a peak element. For example, 50 is peak element in {10, 20, 30, 40, 50}. If the input array is sorted in strictly decreasing order, the first element is always a peak element. 100 is the peak element in {100, 80, 60, 50, 20}. If all elements of input array are same, every element is a peak element. It is clear from the above examples that there is always a peak element in the input array. Naive Approach: The array can be traversed and the element whose neighbours are less than that element can be returned.Algorithm: If in the array, the first element is greater than the second or the last element is greater than the second last, print the respective element and terminate the program.Else traverse the array from the second index to the second last indexIf for an element array[i], it is greater than both its neighbours, i.e., array[i] > array[i-1] and array[i] > array[i+1], then print that element and terminate. If in the array, the first element is greater than the second or the last element is greater than the second last, print the respective element and terminate the program. Else traverse the array from the second index to the second last index If for an element array[i], it is greater than both its neighbours, i.e., array[i] > array[i-1] and array[i] > array[i+1], then print that element and terminate. C++ C Java Python3 C# Javascript // A C++ program to find a peak element#include <bits/stdc++.h>using namespace std; // Find the peak element in the arrayint findPeak(int arr[], int n){ // first or last element is peak element if (n == 1) return 0; if (arr[0] >= arr[1]) return 0; if (arr[n - 1] >= arr[n - 2]) return n - 1; // check for every other element for (int i = 1; i < n - 1; i++) { // check if the neighbors are smaller if (arr[i] >= arr[i - 1] && arr[i] >= arr[i + 1]) return i; }} // Driver Codeint main(){ int arr[] = { 1, 3, 20, 4, 1, 0 }; int n = sizeof(arr) / sizeof(arr[0]); cout << "Index of a peak point is " << findPeak(arr, n); return 0;} // This code is contributed by Aditya Kumar (adityakumar129) // A C program to find a peak element#include <stdio.h> // Find the peak element in the arrayint findPeak(int arr[], int n){ // first or last element is peak element if (n == 1) return 0; if (arr[0] >= arr[1]) return 0; if (arr[n - 1] >= arr[n - 2]) return n - 1; // check for every other element for (int i = 1; i < n - 1; i++) { // check if the neighbors are smaller if (arr[i] >= arr[i - 1] && arr[i] >= arr[i + 1]) return i; }} // Driver Codeint main(){ int arr[] = { 1, 3, 20, 4, 1, 0 }; int n = sizeof(arr) / sizeof(arr[0]); printf("Index of a peak point is %d",findPeak(arr, n)); return 0;} // This code is contributed by Aditya Kumar (adityakumar129) // A Java program to find a peak elementimport java.util.*; class GFG { // Find the peak element in the array static int findPeak(int arr[], int n) { // First or last element is peak element if (n == 1) return 0; if (arr[0] >= arr[1]) return 0; if (arr[n - 1] >= arr[n - 2]) return n - 1; // Check for every other element for (int i = 1; i < n - 1; i++) { // Check if the neighbors are smaller if (arr[i] >= arr[i - 1] && arr[i] >= arr[i + 1]) return i; } return 0; } // Driver Code public static void main(String[] args) { int arr[] = { 1, 3, 20, 4, 1, 0 }; int n = arr.length; System.out.print("Index of a peak point is " + findPeak(arr, n)); }} // This code is contributed by Aditya Kumar (adityakumar129) # A Python3 program to find a peak element # Find the peak element in the arraydef findPeak(arr, n) : # first or last element is peak element if (n == 1) : return 0 if (arr[0] >= arr[1]) : return 0 if (arr[n - 1] >= arr[n - 2]) : return n - 1 # check for every other element for i in range(1, n - 1) : # check if the neighbors are smaller if (arr[i] >= arr[i - 1] and arr[i] >= arr[i + 1]) : return i # Driver code.arr = [ 1, 3, 20, 4, 1, 0 ]n = len(arr)print("Index of a peak point is", findPeak(arr, n)) # This code is contributed by divyeshrabadiya07 // A C# program to find a peak elementusing System; public class GFG{ // Find the peak element in the arraystatic int findPeak(int []arr, int n){ // First or last element is peak element if (n == 1) return 0; if (arr[0] >= arr[1]) return 0; if (arr[n - 1] >= arr[n - 2]) return n - 1; // Check for every other element for(int i = 1; i < n - 1; i++) { // Check if the neighbors are smaller if (arr[i] >= arr[i - 1] && arr[i] >= arr[i + 1]) return i; } return 0;} // Driver Codepublic static void Main(String[] args){ int []arr = { 1, 3, 20, 4, 1, 0 }; int n = arr.Length; Console.Write("Index of a peak point is " + findPeak(arr, n));}} // This code is contributed by 29AjayKumar <script> // A JavaScript program to find a peak element // Find the peak element in the array function findPeak(arr, n) { // first or last element is peak element if (n == 1) return 0; if (arr[0] >= arr[1]) return 0; if (arr[n - 1] >= arr[n - 2]) return n - 1; // check for every other element for (var i = 1; i < n - 1; i++) { // check if the neighbors are smaller if (arr[i] >= arr[i - 1] && arr[i] >= arr[i + 1]) return i; } } // Driver Code var arr = [1, 3, 20, 4, 1, 0]; var n = arr.length; document.write("Index of a peak point is " + findPeak(arr, n)); // This code is contributed by rdtank. </script> Output: Index of a peak point is 2 Complexity Analysis: Time complexity: O(n). One traversal is needed so the time complexity is O(n) Space Complexity: O(1). No extra space is needed, so space complexity is constant Efficient Approach: Divide and Conquer can be used to find a peak in O(Logn) time. The idea is based on the technique of Binary Search to check if the middle element is the peak element or not. If the middle element is not the peak element, then check if the element on the right side is greater than the middle element then there is always a peak element on the right side. If the element on the left side is greater than the middle element then there is always a peak element on the left side. Form a recursion and the peak element can be found in log n time. Algorithm: Create two variables, l and r, initialize l = 0 and r = n-1Iterate the steps below till l <= r, lowerbound is less than the upperboundCheck if the mid value or index mid = (l+r)/2, is the peak element or not, if yes then print the element and terminate.Else if the element on the left side of the middle element is greater then check for peak element on the left side, i.e. update r = mid – 1Else if the element on the right side of the middle element is greater then check for peak element on the right side, i.e. update l = mid + 1 Create two variables, l and r, initialize l = 0 and r = n-1 Iterate the steps below till l <= r, lowerbound is less than the upperbound Check if the mid value or index mid = (l+r)/2, is the peak element or not, if yes then print the element and terminate. Else if the element on the left side of the middle element is greater then check for peak element on the left side, i.e. update r = mid – 1 Else if the element on the right side of the middle element is greater then check for peak element on the right side, i.e. update l = mid + 1 C++ C Java Python3 C# PHP Javascript // A C++ program to find a peak element// using divide and conquer#include <bits/stdc++.h>using namespace std; // A binary search based function// that returns index of a peak elementint findPeakUtil(int arr[], int low, int high, int n){ // Find index of middle element // (low + high)/2 int mid = low + (high - low) / 2; // Compare middle element with its // neighbours (if neighbours exist) if ((mid == 0 || arr[mid - 1] <= arr[mid]) && (mid == n - 1 || arr[mid + 1] <= arr[mid])) return mid; // If middle element is not peak and its // left neighbour is greater than it, // then left half must have a peak element else if (mid > 0 && arr[mid - 1] > arr[mid]) return findPeakUtil(arr, low, (mid - 1), n); // If middle element is not peak and its // right neighbour is greater than it, // then right half must have a peak element else return findPeakUtil( arr, (mid + 1), high, n);} // A wrapper over recursive function findPeakUtil()int findPeak(int arr[], int n){ return findPeakUtil(arr, 0, n - 1, n);} // Driver Codeint main(){ int arr[] = { 1, 3, 20, 4, 1, 0 }; int n = sizeof(arr) / sizeof(arr[0]); cout << "Index of a peak point is " << findPeak(arr, n); return 0;} // This code is contributed by rathbhupendra // C program to find a peak// element using divide and conquer#include <stdio.h> // A binary search based function that// returns index of a peak elementint findPeakUtil( int arr[], int low, int high, int n){ // Find index of middle element // (low + high)/2 int mid = low + (high - low) / 2; // Compare middle element with // its neighbours (if neighbours exist) if ((mid == 0 || arr[mid - 1] <= arr[mid]) && (mid == n - 1 || arr[mid + 1] <= arr[mid])) return mid; // If middle element is not peak and // its left neighbour is greater // than it, then left half must have a peak element else if (mid > 0 && arr[mid - 1] > arr[mid]) return findPeakUtil(arr, low, (mid - 1), n); // If middle element is not peak and // its right neighbour is greater // than it, then right half must have a peak element else return findPeakUtil(arr, (mid + 1), high, n);} // A wrapper over recursive function findPeakUtil()int findPeak(int arr[], int n){ return findPeakUtil(arr, 0, n - 1, n);} /* Driver program to check above functions */int main(){ int arr[] = { 1, 3, 20, 4, 1, 0 }; int n = sizeof(arr) / sizeof(arr[0]); printf( "Index of a peak point is %d", findPeak(arr, n)); return 0;} // A Java program to find a peak// element using divide and conquerimport java.util.*;import java.lang.*;import java.io.*; class PeakElement { // A binary search based function // that returns index of a peak element static int findPeakUtil( int arr[], int low, int high, int n) { // Find index of middle element // (low + high)/2 int mid = low + (high - low) / 2; // Compare middle element with its // neighbours (if neighbours exist) if ((mid == 0 || arr[mid - 1] <= arr[mid]) && (mid == n - 1 || arr[mid + 1] <= arr[mid])) return mid; // If middle element is not peak // and its left neighbor is // greater than it, then left half // must have a peak element else if (mid > 0 && arr[mid - 1] > arr[mid]) return findPeakUtil(arr, low, (mid - 1), n); // If middle element is not peak // and its right neighbor // is greater than it, then right // half must have a peak // element else return findPeakUtil( arr, (mid + 1), high, n); } // A wrapper over recursive function // findPeakUtil() static int findPeak(int arr[], int n) { return findPeakUtil(arr, 0, n - 1, n); } // Driver method public static void main(String[] args) { int arr[] = { 1, 3, 20, 4, 1, 0 }; int n = arr.length; System.out.println( "Index of a peak point is " + findPeak(arr, n)); }} # A python3 program to find a peak# element using divide and conquer # A binary search based function# that returns index of a peak elementdef findPeakUtil(arr, low, high, n): # Find index of middle element # (low + high)/2 mid = low + (high - low)/2 mid = int(mid) # Compare middle element with its # neighbours (if neighbours exist) if ((mid == 0 or arr[mid - 1] <= arr[mid]) and (mid == n - 1 or arr[mid + 1] <= arr[mid])): return mid # If middle element is not peak and # its left neighbour is greater # than it, then left half must # have a peak element elif (mid > 0 and arr[mid - 1] > arr[mid]): return findPeakUtil(arr, low, (mid - 1), n) # If middle element is not peak and # its right neighbour is greater # than it, then right half must # have a peak element else: return findPeakUtil(arr, (mid + 1), high, n) # A wrapper over recursive# function findPeakUtil()def findPeak(arr, n): return findPeakUtil(arr, 0, n - 1, n) # Driver codearr = [1, 3, 20, 4, 1, 0]n = len(arr)print("Index of a peak point is", findPeak(arr, n)) # This code is contributed by# Smitha Dinesh Semwal // A C# program to find// a peak element// using divide and conquerusing System; class GFG { // A binary search based // function that returns // index of a peak element static int findPeakUtil(int[] arr, int low, int high, int n) { // Find index of // middle element int mid = low + (high - low) / 2; // Compare middle element with // its neighbours (if neighbours // exist) if ((mid == 0 || arr[mid - 1] <= arr[mid]) && (mid == n - 1 || arr[mid + 1] <= arr[mid])) return mid; // If middle element is not // peak and its left neighbor // is greater than it, then // left half must have a // peak element else if (mid > 0 && arr[mid - 1] > arr[mid]) return findPeakUtil(arr, low, (mid - 1), n); // If middle element is not // peak and its right neighbor // is greater than it, then // right half must have a peak // element else return findPeakUtil(arr, (mid + 1), high, n); } // A wrapper over recursive // function findPeakUtil() static int findPeak(int[] arr, int n) { return findPeakUtil(arr, 0, n - 1, n); } // Driver Code static public void Main() { int[] arr = { 1, 3, 20, 4, 1, 0 }; int n = arr.Length; Console.WriteLine("Index of a peak " + "point is " + findPeak(arr, n)); }} // This code is contributed by ajit <?php// A PHP program to find a// peak element using// divide and conquer // A binary search based function// that returns index of a peak// elementfunction findPeakUtil($arr, $low, $high, $n){ // Find index of middle element $mid = $low + ($high - $low) / 2; // (low + high)/2 // Compare middle element with // its neighbours (if neighbours exist) if (($mid == 0 || $arr[$mid - 1] <= $arr[$mid]) && ($mid == $n - 1 || $arr[$mid + 1] <= $arr[$mid])) return $mid; // If middle element is not peak // and its left neighbour is greater // than it, then left half must // have a peak element else if ($mid > 0 && $arr[$mid - 1] > $arr[$mid]) return findPeakUtil($arr, $low, ($mid - 1), $n); // If middle element is not peak // and its right neighbour is // greater than it, then right // half must have a peak element else return(findPeakUtil($arr, ($mid + 1), $high, $n));} // A wrapper over recursive// function findPeakUtil()function findPeak($arr, $n){ return floor(findPeakUtil($arr, 0, $n - 1, $n));} // Driver Code$arr = array(1, 3, 20, 4, 1, 0);$n = sizeof($arr);echo "Index of a peak point is ", findPeak($arr, $n); // This code is contributed by ajit?> <script> // A Javascript program to find a peak element// using divide and conquer // A binary search based function// that returns index of a peak elementfunction findPeakUtil(arr, low, high, n){ // Find index of middle element // (low + high)/2 var mid = low + parseInt((high - low) / 2); // Compare middle element with its // neighbours (if neighbours exist) if ((mid == 0 || arr[mid - 1] <= arr[mid]) && (mid == n - 1 || arr[mid + 1] <= arr[mid])) return mid; // If middle element is not peak and its // left neighbour is greater than it, // then left half must have a peak element else if (mid > 0 && arr[mid - 1] > arr[mid]) return findPeakUtil(arr, low, (mid - 1), n); // If middle element is not peak and its // right neighbour is greater than it, // then right half must have a peak element else return findPeakUtil( arr, (mid + 1), high, n);} // A wrapper over recursive function findPeakUtil() function findPeak(arr, n){ return findPeakUtil(arr, 0, n - 1, n);} // Driver Codevar arr = [ 1, 3, 20, 4, 1, 0 ];var n = arr.length;document.write("Index of a peak point is " + findPeak(arr, n)); </script> Output: Index of a peak point is 2 Complexity Analysis: Time Complexity: O(Logn). Where n is the number of elements in the input array. In each step our search becomes half. So it can be compared to Binary search, So the time complexity is O(log n) Space complexity: O(1). No extra space is required, so the space complexity is constant. Iterative Approach : The below given code is the iterative version of the above explained and demonstrated recursive based divide and conquer technique. C++ C Java Python3 C# Javascript // A C++ program to find a peak element// using divide and conquer#include <bits/stdc++.h>using namespace std; // A binary search based function// that returns index of a peak elementint findPeakUtil(int arr[], int low, int high, int n){ int l = low; int r = high; int mid; while (l <= r) { // finding mid by binary right shifting. mid = (l + r) >> 1; // first case if mid is the answer if ((mid == 0 || arr[mid - 1] <= arr[mid]) and (mid == n - 1 || arr[mid + 1] <= arr[mid])) break; // if we have to perform left recursion if (mid > 0 and arr[mid - 1] > arr[mid]) r = mid - 1; // else right recursion. else l = mid + 1; } return mid;} // A wrapper over recursive function findPeakUtil()int findPeak(int arr[], int n){ return findPeakUtil(arr, 0, n - 1, n);} // Driver Codeint main(){ int arr[] = { 1, 3, 20, 4, 1, 0 }; int n = sizeof(arr) / sizeof(arr[0]); cout << "Index of a peak point is " << findPeak(arr, n); return 0;} // This code is contributed by Aditya Kumar (adityakumar129) // A C program to find a peak element using divide and// conquer#include <stdio.h> // A binary search based function// that returns index of a peak elementint findPeakUtil(int arr[], int low, int high, int n){ int l = low; int r = high; int mid; while (l <= r) { // finding mid by binary right shifting. mid = (l + r) >> 1; // first case if mid is the answer if ((mid == 0 || arr[mid - 1] <= arr[mid]) && (mid == n - 1 || arr[mid + 1] <= arr[mid])) break; // if we have to perform left recursion if (mid > 0 && arr[mid - 1] > arr[mid]) r = mid - 1; // else right recursion. else l = mid + 1; } return mid;} // A wrapper over recursive function findPeakUtil()int findPeak(int arr[], int n){ return findPeakUtil(arr, 0, n - 1, n);} // Driver Codeint main(){ int arr[] = { 1, 3, 20, 4, 1, 0 }; int n = sizeof(arr) / sizeof(arr[0]); printf("Index of a peak point is %d", findPeak(arr, n)); return 0;} // This code is contributed by Aditya Kumar (adityakumar129) // A Java program to find a peak element using divide and// conquerclass GFG { // A binary search based function that returns index of // a peak element static int findPeakUtil(int arr[], int low, int high, int n) { int l = low; int r = high; int mid = 0; while (l <= r) { // finding mid by binary right shifting. mid = (l + r) >> 1; // first case if mid is the answer if ((mid == 0 || arr[mid - 1] <= arr[mid] && (mid == n - 1 || arr[mid + 1] <= arr[mid]))) break; // if we have to perform left recursion if (mid > 0 && arr[mid - 1] > arr[mid]) r = mid - 1; // else right recursion. else l = mid + 1; } return mid; } // A wrapper over recursive function findPeakUtil() static int findPeak(int arr[], int n) { return findPeakUtil(arr, 0, n - 1, n); } // Driver Code public static void main(String args[]) { int arr[] = { 1, 3, 20, 4, 1, 0 }; int n = arr.length; System.out.println("Index of a peak point is " + findPeak(arr, n)); }} // This code is contributed by Aditya Kumar (adityakumar129) # A Python program to find a peak element# using divide and conquer # A binary search based function# that returns index of a peak elementdef findPeakUtil(arr, low, high, n): l = low r = high while(l <= r): # finding mid by binary right shifting. mid = (l + r)>>1 # first case if mid is the answer if((mid == 0 or arr[mid - 1] <= arr[mid]) and (mid == n - 1 or arr[mid + 1] <= arr[mid])): break # if we have to perform left recursion if(mid > 0 and arr[mid - 1] > arr[mid]): r = mid - 1 # else right recursion. else: l = mid + 1 return mid # A wrapper over recursive function findPeakUtil()def findPeak(arr, n): return findPeakUtil(arr, 0, n - 1, n) # Driver Codearr = [ 1, 3, 20, 4, 1, 0 ]n = len(arr)print(f"Index of a peak point is {findPeak(arr, n)}") # This code is contributed by shinjanpatra // A C# program to find a peak element// using divide and conquerusing System; public class GFG{ // A binary search based function // that returns index of a peak element static int findPeakUtil(int []arr, int low, int high, int n) { int l = low; int r = high; int mid = 0; while (l <= r) { // finding mid by binary right shifting. mid = (l + r) >> 1; // first case if mid is the answer if ((mid == 0 || arr[mid - 1] <= arr[mid] && (mid == n - 1 || arr[mid + 1] <= arr[mid]))) break; // if we have to perform left recursion if (mid > 0 && arr[mid - 1] > arr[mid]) r = mid - 1; // else right recursion. else l = mid + 1; } return mid; } // A wrapper over recursive function findPeakUtil() static int findPeak(int []arr, int n) { return findPeakUtil(arr, 0, n - 1, n); } // Driver Code public static void Main(String []args) { int []arr = { 1, 3, 20, 4, 1, 0 }; int n = arr.Length; Console.WriteLine("Index of a peak point is " + findPeak(arr, n)); }} // This code is contributed by shikhasingrajput <script> // A JavaScript program to find a peak element// using divide and conquer // A binary search based function// that returns index of a peak elementfunction findPeakUtil(arr,low,high,n){ let l = low; let r = high; let mid; while(l<=r) { // finding mid by binary right shifting. mid = (l + r)>>1; // first case if mid is the answer if((mid == 0 || arr[mid - 1] <= arr[mid]) && (mid == n - 1 || arr[mid + 1] <= arr[mid])) break; // if we have to perform left recursion if(mid > 0 && arr[mid - 1] > arr[mid]) r = mid - 1; // else right recursion. else l = mid + 1; } return mid;} // A wrapper over recursive function findPeakUtil()function findPeak(arr,n){ return findPeakUtil(arr, 0, n - 1, n);} // Driver Codelet arr = [ 1, 3, 20, 4, 1, 0 ];let n = arr.length;document.write("Index of a peak point is " +findPeak(arr, n)); // This code is contributed by shinjanpatra</script> Index of a peak point is 2 YouTubeGeeksforGeeks507K subscribersFind a Peak Element | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 12:03•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=NFvAD5na5oU" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> Exercise: Consider the following modified definition of peak element. An array element is a peak if it is greater than its neighbors. Note that an array may not contain a peak element with this modified definition. References: http://courses.csail.mit.edu/6.006/spring11/lectures/lec02.pdf http://www.youtube.com/watch?v=HtSuA80QTyo Related Problem: Find local minima in an arrayPlease write comments if you find anything incorrect, or you want to share more information about the topic discussed above. jit_t ShubhamMaurya3 rathbhupendra andrew1234 princi singh 29AjayKumar divyeshrabadiya07 rdtank rrrtnx pallavisinha239 arorakashish0911 harshkumarchoudhary144 _saurabh_jaiswal shikhasingrajput shinjanpatra simmytarika5 adityakumar129 Adobe Amazon Visa Arrays Divide and Conquer Searching Amazon Visa Adobe Arrays Searching Divide and Conquer Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Arrays in Java Arrays in C/C++ Write a program to reverse an array or string Program for array rotation Largest Sum Contiguous Subarray Merge Sort QuickSort Binary Search Program for Tower of Hanoi Count Inversions in an array | Set 1 (Using Merge Sort)
[ { "code": null, "e": 42521, "s": 42493, "text": "\n28 Apr, 2022" }, { "code": null, "e": 42707, "s": 42521, "text": "Given an array of integers. Find a peak element in it. An array element is a peak if it is NOT smaller than its neighbours. For corner elements, we need to consider only one neighbour. " }, { "code": null, "e": 42716, "s": 42707, "text": "Example:" }, { "code": null, "e": 43006, "s": 42716, "text": "Input: array[]= {5, 10, 20, 15}\nOutput: 20\nThe element 20 has neighbours 10 and 15,\nboth of them are less than 20.\n\nInput: array[] = {10, 20, 15, 2, 23, 90, 67}\nOutput: 20 or 90\nThe element 20 has neighbours 10 and 15, \nboth of them are less than 20, similarly 90 has neighbours 23 and 67." }, { "code": null, "e": 43066, "s": 43006, "text": "Following corner cases give better idea about the problem. " }, { "code": null, "e": 43446, "s": 43066, "text": "If input array is sorted in strictly increasing order, the last element is always a peak element. For example, 50 is peak element in {10, 20, 30, 40, 50}.If the input array is sorted in strictly decreasing order, the first element is always a peak element. 100 is the peak element in {100, 80, 60, 50, 20}.If all elements of input array are same, every element is a peak element." }, { "code": null, "e": 43601, "s": 43446, "text": "If input array is sorted in strictly increasing order, the last element is always a peak element. For example, 50 is peak element in {10, 20, 30, 40, 50}." }, { "code": null, "e": 43754, "s": 43601, "text": "If the input array is sorted in strictly decreasing order, the first element is always a peak element. 100 is the peak element in {100, 80, 60, 50, 20}." }, { "code": null, "e": 43828, "s": 43754, "text": "If all elements of input array are same, every element is a peak element." }, { "code": null, "e": 43920, "s": 43828, "text": "It is clear from the above examples that there is always a peak element in the input array." }, { "code": null, "e": 44051, "s": 43920, "text": "Naive Approach: The array can be traversed and the element whose neighbours are less than that element can be returned.Algorithm: " }, { "code": null, "e": 44453, "s": 44051, "text": "If in the array, the first element is greater than the second or the last element is greater than the second last, print the respective element and terminate the program.Else traverse the array from the second index to the second last indexIf for an element array[i], it is greater than both its neighbours, i.e., array[i] > array[i-1] and array[i] > array[i+1], then print that element and terminate." }, { "code": null, "e": 44624, "s": 44453, "text": "If in the array, the first element is greater than the second or the last element is greater than the second last, print the respective element and terminate the program." }, { "code": null, "e": 44695, "s": 44624, "text": "Else traverse the array from the second index to the second last index" }, { "code": null, "e": 44857, "s": 44695, "text": "If for an element array[i], it is greater than both its neighbours, i.e., array[i] > array[i-1] and array[i] > array[i+1], then print that element and terminate." }, { "code": null, "e": 44861, "s": 44857, "text": "C++" }, { "code": null, "e": 44863, "s": 44861, "text": "C" }, { "code": null, "e": 44868, "s": 44863, "text": "Java" }, { "code": null, "e": 44876, "s": 44868, "text": "Python3" }, { "code": null, "e": 44879, "s": 44876, "text": "C#" }, { "code": null, "e": 44890, "s": 44879, "text": "Javascript" }, { "code": "// A C++ program to find a peak element#include <bits/stdc++.h>using namespace std; // Find the peak element in the arrayint findPeak(int arr[], int n){ // first or last element is peak element if (n == 1) return 0; if (arr[0] >= arr[1]) return 0; if (arr[n - 1] >= arr[n - 2]) return n - 1; // check for every other element for (int i = 1; i < n - 1; i++) { // check if the neighbors are smaller if (arr[i] >= arr[i - 1] && arr[i] >= arr[i + 1]) return i; }} // Driver Codeint main(){ int arr[] = { 1, 3, 20, 4, 1, 0 }; int n = sizeof(arr) / sizeof(arr[0]); cout << \"Index of a peak point is \" << findPeak(arr, n); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)", "e": 45659, "s": 44890, "text": null }, { "code": "// A C program to find a peak element#include <stdio.h> // Find the peak element in the arrayint findPeak(int arr[], int n){ // first or last element is peak element if (n == 1) return 0; if (arr[0] >= arr[1]) return 0; if (arr[n - 1] >= arr[n - 2]) return n - 1; // check for every other element for (int i = 1; i < n - 1; i++) { // check if the neighbors are smaller if (arr[i] >= arr[i - 1] && arr[i] >= arr[i + 1]) return i; }} // Driver Codeint main(){ int arr[] = { 1, 3, 20, 4, 1, 0 }; int n = sizeof(arr) / sizeof(arr[0]); printf(\"Index of a peak point is %d\",findPeak(arr, n)); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)", "e": 46399, "s": 45659, "text": null }, { "code": "// A Java program to find a peak elementimport java.util.*; class GFG { // Find the peak element in the array static int findPeak(int arr[], int n) { // First or last element is peak element if (n == 1) return 0; if (arr[0] >= arr[1]) return 0; if (arr[n - 1] >= arr[n - 2]) return n - 1; // Check for every other element for (int i = 1; i < n - 1; i++) { // Check if the neighbors are smaller if (arr[i] >= arr[i - 1] && arr[i] >= arr[i + 1]) return i; } return 0; } // Driver Code public static void main(String[] args) { int arr[] = { 1, 3, 20, 4, 1, 0 }; int n = arr.length; System.out.print(\"Index of a peak point is \" + findPeak(arr, n)); }} // This code is contributed by Aditya Kumar (adityakumar129)", "e": 47281, "s": 46399, "text": null }, { "code": "# A Python3 program to find a peak element # Find the peak element in the arraydef findPeak(arr, n) : # first or last element is peak element if (n == 1) : return 0 if (arr[0] >= arr[1]) : return 0 if (arr[n - 1] >= arr[n - 2]) : return n - 1 # check for every other element for i in range(1, n - 1) : # check if the neighbors are smaller if (arr[i] >= arr[i - 1] and arr[i] >= arr[i + 1]) : return i # Driver code.arr = [ 1, 3, 20, 4, 1, 0 ]n = len(arr)print(\"Index of a peak point is\", findPeak(arr, n)) # This code is contributed by divyeshrabadiya07", "e": 47914, "s": 47281, "text": null }, { "code": "// A C# program to find a peak elementusing System; public class GFG{ // Find the peak element in the arraystatic int findPeak(int []arr, int n){ // First or last element is peak element if (n == 1) return 0; if (arr[0] >= arr[1]) return 0; if (arr[n - 1] >= arr[n - 2]) return n - 1; // Check for every other element for(int i = 1; i < n - 1; i++) { // Check if the neighbors are smaller if (arr[i] >= arr[i - 1] && arr[i] >= arr[i + 1]) return i; } return 0;} // Driver Codepublic static void Main(String[] args){ int []arr = { 1, 3, 20, 4, 1, 0 }; int n = arr.Length; Console.Write(\"Index of a peak point is \" + findPeak(arr, n));}} // This code is contributed by 29AjayKumar", "e": 48727, "s": 47914, "text": null }, { "code": "<script> // A JavaScript program to find a peak element // Find the peak element in the array function findPeak(arr, n) { // first or last element is peak element if (n == 1) return 0; if (arr[0] >= arr[1]) return 0; if (arr[n - 1] >= arr[n - 2]) return n - 1; // check for every other element for (var i = 1; i < n - 1; i++) { // check if the neighbors are smaller if (arr[i] >= arr[i - 1] && arr[i] >= arr[i + 1]) return i; } } // Driver Code var arr = [1, 3, 20, 4, 1, 0]; var n = arr.length; document.write(\"Index of a peak point is \" + findPeak(arr, n)); // This code is contributed by rdtank. </script>", "e": 49489, "s": 48727, "text": null }, { "code": null, "e": 49498, "s": 49489, "text": "Output: " }, { "code": null, "e": 49525, "s": 49498, "text": "Index of a peak point is 2" }, { "code": null, "e": 49547, "s": 49525, "text": "Complexity Analysis: " }, { "code": null, "e": 49625, "s": 49547, "text": "Time complexity: O(n). One traversal is needed so the time complexity is O(n)" }, { "code": null, "e": 49707, "s": 49625, "text": "Space Complexity: O(1). No extra space is needed, so space complexity is constant" }, { "code": null, "e": 50270, "s": 49707, "text": "Efficient Approach: Divide and Conquer can be used to find a peak in O(Logn) time. The idea is based on the technique of Binary Search to check if the middle element is the peak element or not. If the middle element is not the peak element, then check if the element on the right side is greater than the middle element then there is always a peak element on the right side. If the element on the left side is greater than the middle element then there is always a peak element on the left side. Form a recursion and the peak element can be found in log n time. " }, { "code": null, "e": 50282, "s": 50270, "text": "Algorithm: " }, { "code": null, "e": 50816, "s": 50282, "text": "Create two variables, l and r, initialize l = 0 and r = n-1Iterate the steps below till l <= r, lowerbound is less than the upperboundCheck if the mid value or index mid = (l+r)/2, is the peak element or not, if yes then print the element and terminate.Else if the element on the left side of the middle element is greater then check for peak element on the left side, i.e. update r = mid – 1Else if the element on the right side of the middle element is greater then check for peak element on the right side, i.e. update l = mid + 1" }, { "code": null, "e": 50876, "s": 50816, "text": "Create two variables, l and r, initialize l = 0 and r = n-1" }, { "code": null, "e": 50952, "s": 50876, "text": "Iterate the steps below till l <= r, lowerbound is less than the upperbound" }, { "code": null, "e": 51072, "s": 50952, "text": "Check if the mid value or index mid = (l+r)/2, is the peak element or not, if yes then print the element and terminate." }, { "code": null, "e": 51212, "s": 51072, "text": "Else if the element on the left side of the middle element is greater then check for peak element on the left side, i.e. update r = mid – 1" }, { "code": null, "e": 51354, "s": 51212, "text": "Else if the element on the right side of the middle element is greater then check for peak element on the right side, i.e. update l = mid + 1" }, { "code": null, "e": 51358, "s": 51354, "text": "C++" }, { "code": null, "e": 51360, "s": 51358, "text": "C" }, { "code": null, "e": 51365, "s": 51360, "text": "Java" }, { "code": null, "e": 51373, "s": 51365, "text": "Python3" }, { "code": null, "e": 51376, "s": 51373, "text": "C#" }, { "code": null, "e": 51380, "s": 51376, "text": "PHP" }, { "code": null, "e": 51391, "s": 51380, "text": "Javascript" }, { "code": "// A C++ program to find a peak element// using divide and conquer#include <bits/stdc++.h>using namespace std; // A binary search based function// that returns index of a peak elementint findPeakUtil(int arr[], int low, int high, int n){ // Find index of middle element // (low + high)/2 int mid = low + (high - low) / 2; // Compare middle element with its // neighbours (if neighbours exist) if ((mid == 0 || arr[mid - 1] <= arr[mid]) && (mid == n - 1 || arr[mid + 1] <= arr[mid])) return mid; // If middle element is not peak and its // left neighbour is greater than it, // then left half must have a peak element else if (mid > 0 && arr[mid - 1] > arr[mid]) return findPeakUtil(arr, low, (mid - 1), n); // If middle element is not peak and its // right neighbour is greater than it, // then right half must have a peak element else return findPeakUtil( arr, (mid + 1), high, n);} // A wrapper over recursive function findPeakUtil()int findPeak(int arr[], int n){ return findPeakUtil(arr, 0, n - 1, n);} // Driver Codeint main(){ int arr[] = { 1, 3, 20, 4, 1, 0 }; int n = sizeof(arr) / sizeof(arr[0]); cout << \"Index of a peak point is \" << findPeak(arr, n); return 0;} // This code is contributed by rathbhupendra", "e": 52733, "s": 51391, "text": null }, { "code": "// C program to find a peak// element using divide and conquer#include <stdio.h> // A binary search based function that// returns index of a peak elementint findPeakUtil( int arr[], int low, int high, int n){ // Find index of middle element // (low + high)/2 int mid = low + (high - low) / 2; // Compare middle element with // its neighbours (if neighbours exist) if ((mid == 0 || arr[mid - 1] <= arr[mid]) && (mid == n - 1 || arr[mid + 1] <= arr[mid])) return mid; // If middle element is not peak and // its left neighbour is greater // than it, then left half must have a peak element else if (mid > 0 && arr[mid - 1] > arr[mid]) return findPeakUtil(arr, low, (mid - 1), n); // If middle element is not peak and // its right neighbour is greater // than it, then right half must have a peak element else return findPeakUtil(arr, (mid + 1), high, n);} // A wrapper over recursive function findPeakUtil()int findPeak(int arr[], int n){ return findPeakUtil(arr, 0, n - 1, n);} /* Driver program to check above functions */int main(){ int arr[] = { 1, 3, 20, 4, 1, 0 }; int n = sizeof(arr) / sizeof(arr[0]); printf( \"Index of a peak point is %d\", findPeak(arr, n)); return 0;}", "e": 54000, "s": 52733, "text": null }, { "code": "// A Java program to find a peak// element using divide and conquerimport java.util.*;import java.lang.*;import java.io.*; class PeakElement { // A binary search based function // that returns index of a peak element static int findPeakUtil( int arr[], int low, int high, int n) { // Find index of middle element // (low + high)/2 int mid = low + (high - low) / 2; // Compare middle element with its // neighbours (if neighbours exist) if ((mid == 0 || arr[mid - 1] <= arr[mid]) && (mid == n - 1 || arr[mid + 1] <= arr[mid])) return mid; // If middle element is not peak // and its left neighbor is // greater than it, then left half // must have a peak element else if (mid > 0 && arr[mid - 1] > arr[mid]) return findPeakUtil(arr, low, (mid - 1), n); // If middle element is not peak // and its right neighbor // is greater than it, then right // half must have a peak // element else return findPeakUtil( arr, (mid + 1), high, n); } // A wrapper over recursive function // findPeakUtil() static int findPeak(int arr[], int n) { return findPeakUtil(arr, 0, n - 1, n); } // Driver method public static void main(String[] args) { int arr[] = { 1, 3, 20, 4, 1, 0 }; int n = arr.length; System.out.println( \"Index of a peak point is \" + findPeak(arr, n)); }}", "e": 55527, "s": 54000, "text": null }, { "code": "# A python3 program to find a peak# element using divide and conquer # A binary search based function# that returns index of a peak elementdef findPeakUtil(arr, low, high, n): # Find index of middle element # (low + high)/2 mid = low + (high - low)/2 mid = int(mid) # Compare middle element with its # neighbours (if neighbours exist) if ((mid == 0 or arr[mid - 1] <= arr[mid]) and (mid == n - 1 or arr[mid + 1] <= arr[mid])): return mid # If middle element is not peak and # its left neighbour is greater # than it, then left half must # have a peak element elif (mid > 0 and arr[mid - 1] > arr[mid]): return findPeakUtil(arr, low, (mid - 1), n) # If middle element is not peak and # its right neighbour is greater # than it, then right half must # have a peak element else: return findPeakUtil(arr, (mid + 1), high, n) # A wrapper over recursive# function findPeakUtil()def findPeak(arr, n): return findPeakUtil(arr, 0, n - 1, n) # Driver codearr = [1, 3, 20, 4, 1, 0]n = len(arr)print(\"Index of a peak point is\", findPeak(arr, n)) # This code is contributed by# Smitha Dinesh Semwal", "e": 56720, "s": 55527, "text": null }, { "code": "// A C# program to find// a peak element// using divide and conquerusing System; class GFG { // A binary search based // function that returns // index of a peak element static int findPeakUtil(int[] arr, int low, int high, int n) { // Find index of // middle element int mid = low + (high - low) / 2; // Compare middle element with // its neighbours (if neighbours // exist) if ((mid == 0 || arr[mid - 1] <= arr[mid]) && (mid == n - 1 || arr[mid + 1] <= arr[mid])) return mid; // If middle element is not // peak and its left neighbor // is greater than it, then // left half must have a // peak element else if (mid > 0 && arr[mid - 1] > arr[mid]) return findPeakUtil(arr, low, (mid - 1), n); // If middle element is not // peak and its right neighbor // is greater than it, then // right half must have a peak // element else return findPeakUtil(arr, (mid + 1), high, n); } // A wrapper over recursive // function findPeakUtil() static int findPeak(int[] arr, int n) { return findPeakUtil(arr, 0, n - 1, n); } // Driver Code static public void Main() { int[] arr = { 1, 3, 20, 4, 1, 0 }; int n = arr.Length; Console.WriteLine(\"Index of a peak \" + \"point is \" + findPeak(arr, n)); }} // This code is contributed by ajit", "e": 58372, "s": 56720, "text": null }, { "code": "<?php// A PHP program to find a// peak element using// divide and conquer // A binary search based function// that returns index of a peak// elementfunction findPeakUtil($arr, $low, $high, $n){ // Find index of middle element $mid = $low + ($high - $low) / 2; // (low + high)/2 // Compare middle element with // its neighbours (if neighbours exist) if (($mid == 0 || $arr[$mid - 1] <= $arr[$mid]) && ($mid == $n - 1 || $arr[$mid + 1] <= $arr[$mid])) return $mid; // If middle element is not peak // and its left neighbour is greater // than it, then left half must // have a peak element else if ($mid > 0 && $arr[$mid - 1] > $arr[$mid]) return findPeakUtil($arr, $low, ($mid - 1), $n); // If middle element is not peak // and its right neighbour is // greater than it, then right // half must have a peak element else return(findPeakUtil($arr, ($mid + 1), $high, $n));} // A wrapper over recursive// function findPeakUtil()function findPeak($arr, $n){ return floor(findPeakUtil($arr, 0, $n - 1, $n));} // Driver Code$arr = array(1, 3, 20, 4, 1, 0);$n = sizeof($arr);echo \"Index of a peak point is \", findPeak($arr, $n); // This code is contributed by ajit?>", "e": 59749, "s": 58372, "text": null }, { "code": "<script> // A Javascript program to find a peak element// using divide and conquer // A binary search based function// that returns index of a peak elementfunction findPeakUtil(arr, low, high, n){ // Find index of middle element // (low + high)/2 var mid = low + parseInt((high - low) / 2); // Compare middle element with its // neighbours (if neighbours exist) if ((mid == 0 || arr[mid - 1] <= arr[mid]) && (mid == n - 1 || arr[mid + 1] <= arr[mid])) return mid; // If middle element is not peak and its // left neighbour is greater than it, // then left half must have a peak element else if (mid > 0 && arr[mid - 1] > arr[mid]) return findPeakUtil(arr, low, (mid - 1), n); // If middle element is not peak and its // right neighbour is greater than it, // then right half must have a peak element else return findPeakUtil( arr, (mid + 1), high, n);} // A wrapper over recursive function findPeakUtil() function findPeak(arr, n){ return findPeakUtil(arr, 0, n - 1, n);} // Driver Codevar arr = [ 1, 3, 20, 4, 1, 0 ];var n = arr.length;document.write(\"Index of a peak point is \" + findPeak(arr, n)); </script>", "e": 60951, "s": 59749, "text": null }, { "code": null, "e": 60960, "s": 60951, "text": "Output: " }, { "code": null, "e": 60987, "s": 60960, "text": "Index of a peak point is 2" }, { "code": null, "e": 61009, "s": 60987, "text": "Complexity Analysis: " }, { "code": null, "e": 61202, "s": 61009, "text": "Time Complexity: O(Logn). Where n is the number of elements in the input array. In each step our search becomes half. So it can be compared to Binary search, So the time complexity is O(log n)" }, { "code": null, "e": 61291, "s": 61202, "text": "Space complexity: O(1). No extra space is required, so the space complexity is constant." }, { "code": null, "e": 61444, "s": 61291, "text": "Iterative Approach : The below given code is the iterative version of the above explained and demonstrated recursive based divide and conquer technique." }, { "code": null, "e": 61448, "s": 61444, "text": "C++" }, { "code": null, "e": 61450, "s": 61448, "text": "C" }, { "code": null, "e": 61455, "s": 61450, "text": "Java" }, { "code": null, "e": 61463, "s": 61455, "text": "Python3" }, { "code": null, "e": 61466, "s": 61463, "text": "C#" }, { "code": null, "e": 61477, "s": 61466, "text": "Javascript" }, { "code": "// A C++ program to find a peak element// using divide and conquer#include <bits/stdc++.h>using namespace std; // A binary search based function// that returns index of a peak elementint findPeakUtil(int arr[], int low, int high, int n){ int l = low; int r = high; int mid; while (l <= r) { // finding mid by binary right shifting. mid = (l + r) >> 1; // first case if mid is the answer if ((mid == 0 || arr[mid - 1] <= arr[mid]) and (mid == n - 1 || arr[mid + 1] <= arr[mid])) break; // if we have to perform left recursion if (mid > 0 and arr[mid - 1] > arr[mid]) r = mid - 1; // else right recursion. else l = mid + 1; } return mid;} // A wrapper over recursive function findPeakUtil()int findPeak(int arr[], int n){ return findPeakUtil(arr, 0, n - 1, n);} // Driver Codeint main(){ int arr[] = { 1, 3, 20, 4, 1, 0 }; int n = sizeof(arr) / sizeof(arr[0]); cout << \"Index of a peak point is \" << findPeak(arr, n); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)", "e": 62598, "s": 61477, "text": null }, { "code": "// A C program to find a peak element using divide and// conquer#include <stdio.h> // A binary search based function// that returns index of a peak elementint findPeakUtil(int arr[], int low, int high, int n){ int l = low; int r = high; int mid; while (l <= r) { // finding mid by binary right shifting. mid = (l + r) >> 1; // first case if mid is the answer if ((mid == 0 || arr[mid - 1] <= arr[mid]) && (mid == n - 1 || arr[mid + 1] <= arr[mid])) break; // if we have to perform left recursion if (mid > 0 && arr[mid - 1] > arr[mid]) r = mid - 1; // else right recursion. else l = mid + 1; } return mid;} // A wrapper over recursive function findPeakUtil()int findPeak(int arr[], int n){ return findPeakUtil(arr, 0, n - 1, n);} // Driver Codeint main(){ int arr[] = { 1, 3, 20, 4, 1, 0 }; int n = sizeof(arr) / sizeof(arr[0]); printf(\"Index of a peak point is %d\", findPeak(arr, n)); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)", "e": 63689, "s": 62598, "text": null }, { "code": "// A Java program to find a peak element using divide and// conquerclass GFG { // A binary search based function that returns index of // a peak element static int findPeakUtil(int arr[], int low, int high, int n) { int l = low; int r = high; int mid = 0; while (l <= r) { // finding mid by binary right shifting. mid = (l + r) >> 1; // first case if mid is the answer if ((mid == 0 || arr[mid - 1] <= arr[mid] && (mid == n - 1 || arr[mid + 1] <= arr[mid]))) break; // if we have to perform left recursion if (mid > 0 && arr[mid - 1] > arr[mid]) r = mid - 1; // else right recursion. else l = mid + 1; } return mid; } // A wrapper over recursive function findPeakUtil() static int findPeak(int arr[], int n) { return findPeakUtil(arr, 0, n - 1, n); } // Driver Code public static void main(String args[]) { int arr[] = { 1, 3, 20, 4, 1, 0 }; int n = arr.length; System.out.println(\"Index of a peak point is \" + findPeak(arr, n)); }} // This code is contributed by Aditya Kumar (adityakumar129)", "e": 64943, "s": 63689, "text": null }, { "code": "# A Python program to find a peak element# using divide and conquer # A binary search based function# that returns index of a peak elementdef findPeakUtil(arr, low, high, n): l = low r = high while(l <= r): # finding mid by binary right shifting. mid = (l + r)>>1 # first case if mid is the answer if((mid == 0 or arr[mid - 1] <= arr[mid]) and (mid == n - 1 or arr[mid + 1] <= arr[mid])): break # if we have to perform left recursion if(mid > 0 and arr[mid - 1] > arr[mid]): r = mid - 1 # else right recursion. else: l = mid + 1 return mid # A wrapper over recursive function findPeakUtil()def findPeak(arr, n): return findPeakUtil(arr, 0, n - 1, n) # Driver Codearr = [ 1, 3, 20, 4, 1, 0 ]n = len(arr)print(f\"Index of a peak point is {findPeak(arr, n)}\") # This code is contributed by shinjanpatra", "e": 65895, "s": 64943, "text": null }, { "code": "// A C# program to find a peak element// using divide and conquerusing System; public class GFG{ // A binary search based function // that returns index of a peak element static int findPeakUtil(int []arr, int low, int high, int n) { int l = low; int r = high; int mid = 0; while (l <= r) { // finding mid by binary right shifting. mid = (l + r) >> 1; // first case if mid is the answer if ((mid == 0 || arr[mid - 1] <= arr[mid] && (mid == n - 1 || arr[mid + 1] <= arr[mid]))) break; // if we have to perform left recursion if (mid > 0 && arr[mid - 1] > arr[mid]) r = mid - 1; // else right recursion. else l = mid + 1; } return mid; } // A wrapper over recursive function findPeakUtil() static int findPeak(int []arr, int n) { return findPeakUtil(arr, 0, n - 1, n); } // Driver Code public static void Main(String []args) { int []arr = { 1, 3, 20, 4, 1, 0 }; int n = arr.Length; Console.WriteLine(\"Index of a peak point is \" + findPeak(arr, n)); }} // This code is contributed by shikhasingrajput", "e": 67014, "s": 65895, "text": null }, { "code": "<script> // A JavaScript program to find a peak element// using divide and conquer // A binary search based function// that returns index of a peak elementfunction findPeakUtil(arr,low,high,n){ let l = low; let r = high; let mid; while(l<=r) { // finding mid by binary right shifting. mid = (l + r)>>1; // first case if mid is the answer if((mid == 0 || arr[mid - 1] <= arr[mid]) && (mid == n - 1 || arr[mid + 1] <= arr[mid])) break; // if we have to perform left recursion if(mid > 0 && arr[mid - 1] > arr[mid]) r = mid - 1; // else right recursion. else l = mid + 1; } return mid;} // A wrapper over recursive function findPeakUtil()function findPeak(arr,n){ return findPeakUtil(arr, 0, n - 1, n);} // Driver Codelet arr = [ 1, 3, 20, 4, 1, 0 ];let n = arr.length;document.write(\"Index of a peak point is \" +findPeak(arr, n)); // This code is contributed by shinjanpatra</script>", "e": 68077, "s": 67014, "text": null }, { "code": null, "e": 68104, "s": 68077, "text": "Index of a peak point is 2" }, { "code": null, "e": 68923, "s": 68104, "text": "YouTubeGeeksforGeeks507K subscribersFind a Peak Element | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 12:03•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=NFvAD5na5oU\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>" }, { "code": null, "e": 69138, "s": 68923, "text": "Exercise: Consider the following modified definition of peak element. An array element is a peak if it is greater than its neighbors. Note that an array may not contain a peak element with this modified definition." }, { "code": null, "e": 69257, "s": 69138, "text": "References: http://courses.csail.mit.edu/6.006/spring11/lectures/lec02.pdf http://www.youtube.com/watch?v=HtSuA80QTyo " }, { "code": null, "e": 69429, "s": 69257, "text": "Related Problem: Find local minima in an arrayPlease write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 69437, "s": 69431, "text": "jit_t" }, { "code": null, "e": 69452, "s": 69437, "text": "ShubhamMaurya3" }, { "code": null, "e": 69466, "s": 69452, "text": "rathbhupendra" }, { "code": null, "e": 69477, "s": 69466, "text": "andrew1234" }, { "code": null, "e": 69490, "s": 69477, "text": "princi singh" }, { "code": null, "e": 69502, "s": 69490, "text": "29AjayKumar" }, { "code": null, "e": 69520, "s": 69502, "text": "divyeshrabadiya07" }, { "code": null, "e": 69527, "s": 69520, "text": "rdtank" }, { "code": null, "e": 69534, "s": 69527, "text": "rrrtnx" }, { "code": null, "e": 69550, "s": 69534, "text": "pallavisinha239" }, { "code": null, "e": 69567, "s": 69550, "text": "arorakashish0911" }, { "code": null, "e": 69590, "s": 69567, "text": "harshkumarchoudhary144" }, { "code": null, "e": 69607, "s": 69590, "text": "_saurabh_jaiswal" }, { "code": null, "e": 69624, "s": 69607, "text": "shikhasingrajput" }, { "code": null, "e": 69637, "s": 69624, "text": "shinjanpatra" }, { "code": null, "e": 69650, "s": 69637, "text": "simmytarika5" }, { "code": null, "e": 69665, "s": 69650, "text": "adityakumar129" }, { "code": null, "e": 69671, "s": 69665, "text": "Adobe" }, { "code": null, "e": 69678, "s": 69671, "text": "Amazon" }, { "code": null, "e": 69683, "s": 69678, "text": "Visa" }, { "code": null, "e": 69690, "s": 69683, "text": "Arrays" }, { "code": null, "e": 69709, "s": 69690, "text": "Divide and Conquer" }, { "code": null, "e": 69719, "s": 69709, "text": "Searching" }, { "code": null, "e": 69726, "s": 69719, "text": "Amazon" }, { "code": null, "e": 69731, "s": 69726, "text": "Visa" }, { "code": null, "e": 69737, "s": 69731, "text": "Adobe" }, { "code": null, "e": 69744, "s": 69737, "text": "Arrays" }, { "code": null, "e": 69754, "s": 69744, "text": "Searching" }, { "code": null, "e": 69773, "s": 69754, "text": "Divide and Conquer" }, { "code": null, "e": 69871, "s": 69773, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 69886, "s": 69871, "text": "Arrays in Java" }, { "code": null, "e": 69902, "s": 69886, "text": "Arrays in C/C++" }, { "code": null, "e": 69948, "s": 69902, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 69975, "s": 69948, "text": "Program for array rotation" }, { "code": null, "e": 70007, "s": 69975, "text": "Largest Sum Contiguous Subarray" }, { "code": null, "e": 70018, "s": 70007, "text": "Merge Sort" }, { "code": null, "e": 70028, "s": 70018, "text": "QuickSort" }, { "code": null, "e": 70042, "s": 70028, "text": "Binary Search" }, { "code": null, "e": 70069, "s": 70042, "text": "Program for Tower of Hanoi" } ]
How to get substring of a string in jQuery?
To get substring of a string in jQuery, use the substring() method. It has the following two parameters: from: The from parameter specifies the index where to start the substring. to: The to parameter is optional. It specifies the index where to stop the extraction. This is an optional parameter, which extracts the remaining string, when nothing is mentioned. You can try to run the following code to learn how to get substring of a string in jQuery: Live Demo <html> <head> <title>jQuery subtring</title> <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script> $(document).ready(function(){ $("#button1").click(function(){ var str1 = "Hello World!"; var subStr = str1.substring(0, 5); alert(subStr); }); }); </script> </head> <body> <p>Hello World!</p> <button id="button1">Get substring</button> </body> </html>
[ { "code": null, "e": 1167, "s": 1062, "text": "To get substring of a string in jQuery, use the substring() method. It has the following two parameters:" }, { "code": null, "e": 1242, "s": 1167, "text": "from: The from parameter specifies the index where to start the substring." }, { "code": null, "e": 1424, "s": 1242, "text": "to: The to parameter is optional. It specifies the index where to stop the extraction. This is an optional parameter, which extracts the remaining string, when nothing is mentioned." }, { "code": null, "e": 1515, "s": 1424, "text": "You can try to run the following code to learn how to get substring of a string in jQuery:" }, { "code": null, "e": 1525, "s": 1515, "text": "Live Demo" }, { "code": null, "e": 2085, "s": 1525, "text": "<html>\n\n <head>\n <title>jQuery subtring</title>\n <script src = \"https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js\"></script>\n \n <script>\n $(document).ready(function(){\n $(\"#button1\").click(function(){\n var str1 = \"Hello World!\";\n var subStr = str1.substring(0, 5);\n alert(subStr);\n });\n });\n </script>\n \n </head>\n \n <body>\n <p>Hello World!</p>\n <button id=\"button1\">Get substring</button> \n </body>\n \n</html>" } ]
Counting No. of Parameters in Deep Learning Models by Hand | by Raimi Karim | Towards Data Science
Why do we need to count the number of parameters in a deep learning model again? We don’t. But in cases where we need to reduce the file size of the model or even reduce the time taken for model inference, knowing the number of parameters before and after model quantization would come in handy. (See video here on Efficient Methods and Hardware for Deep Learning.) Counting the number of trainable parameters of deep learning models is considered too trivial, because your code can already do this for you. But I’d like to keep my notes here for us to refer to once in a while. Here are the models that we’ll run through: Feed-Forward Neural Network (FFNN)Recurrent Neural Network (RNN)Convolutional Neural Network (CNN) Feed-Forward Neural Network (FFNN) Recurrent Neural Network (RNN) Convolutional Neural Network (CNN) In parallel, I will build the model with APIs from Keras for easy prototyping and a clean code so let’s quickly import the relevant objects here: from keras.layers import Input, Dense, SimpleRNN, LSTM, GRU, Conv2Dfrom keras.layers import Bidirectionalfrom keras.models import Model After building the model, call model.count_params() to verify how many parameters are trainable. i, input size h, size of hidden layer o, output size For one hidden layer, num_params = connections between layers + biases in every layer= (i×h + h×o) + (h+o) Example 1.1: Input size 3, hidden layer size 5, output size 2 i = 3 h = 5 o = 2 num_params = connections between layers + biases in every layer= (3×5 + 5×2) + (5+2) = 32 input = Input((None, 3)) dense = Dense(5)(input)output = Dense(2)(dense) model = Model(input, output) Example 1.2: Input size 50, hidden layers size [100,1,100], output size 50 i = 50 h = 100, 1, 100 o = 50 num_params = connections between layers + biases in every layer= (50×100 + 100×1 + 1×100 + 100×50) + (100+1+100+50) = 10,451 input = Input((None, 50)) dense = Dense(100)(input) dense = Dense(1)(dense) dense = Dense(100)(dense)output = Dense(50)(dense) model = Model(input, output) g, no. of FFNNs in a unit (RNN has 1, GRU has 3, LSTM has 4) h, size of hidden units i, dimension/size of input Since every FFNN has h(h+i) + h parameters, we have num_params = g × [h(h+i) + h] Example 2.1: LSTM with 2 hidden units and input dimension 3. g = 4 (LSTM has 4 FFNNs) h = 2 i = 3 num_params = g × [h(h+i) + h]= 4 × [2(2+3) + 2] = 48 input = Input((None, 3)) lstm = LSTM(2)(input)model = Model(input, lstm) Example 2.2: Stacked Bidirectional GRU with 5 hidden units and input size 8 (whose outputs are concatenated) + LSTM with 50 hidden units Bidirectional GRU with 5 hidden units and input size 8 g = 3 (GRU has 3 FFNNs) h = 5 i = 8 num_params_layer1= 2 × g × [h(h+i) + h] (first term is 2 because of bidirectionality)= 2 × 3 × [5(5+8) + 5]= 420 LSTM with 50 hidden units g = 4 (LSTM has 4 FFNNs) h = 50 i = 5+5 (outputs from bidirectional GRU concatenated; output size of GRU is 5, same as no. of hidden units) num_params_layer2= g × [h(h+i) + h]= 4 × [50(50+10) + 50]= 12,200 total_params = 420 + 12,200 = 12,620 input = Input((None, 8))layer1 = Bidirectional(GRU(5, return_sequences=True))(input)layer2 = LSTM(50)(layer1) model = Model(input, layer2) merge_mode is concatenation by default. For one layer, i, no. of input maps (or channels) f, filter size (just the length) o, no. of output maps (or channels. this is also defined by how many filters are used) One filter is applied to every input map. num_params= weights + biases= [i × (f×f) × o] + o Example 3.1: Greyscale image with 2×2 filter, output 3 channels i = 1 (greyscale has only 1 channel) f = 2 o = 3 num_params= [i × (f×f) × o] + o= [1 × (2×2) × 3] + 3= 15 input = Input((None, None, 1))conv2d = Conv2D(kernel_size=2, filters=3)(input) model = Model(input, conv2d) Example 3.2: RGB image with 2×2 filter, output of 1 channel There is 1 filter for each input feature map. The resulting convolutions are added element-wise, and a bias term is added to each element. This gives an output with 1 feature map. i = 3 (RGB image has 3 channels) f = 2 o = 1 num_params = [i × (f×f) × o] + o= [3 × (2×2) × 1] + 1= 13 input = Input((None, None, 3))conv2d = Conv2D(kernel_size=2, filters=1)(input) model = Model(input, conv2d) Example 3.3: Image with 2 channels, with 2×2 filter, and output of 3 channels There are 3 filters (purple, yellow, cyan) for each input feature map. The resulting convolutions are added element-wise, and a bias term is added to each element. This gives an output with 3 feature maps. i = 2 f = 2 o = 3 num_params = [i × (f×f) × o] + o= [2 × (2×2) × 3] + 3= 27 input = Input((None, None, 2))conv2d = Conv2D(kernel_size=2, filters=3)(input) model = Model(input, conv2d) That’s all for now! Do leave comments below if you have any feedback! Animated RNN, LSTM and GRU Step-by-Step Tutorial on Linear Regression with Stochastic Gradient Descent 10 Gradient Descent Optimisation Algorithms + Cheat Sheet Attn: Illustrated Attention Illustrated: Self-Attention Follow me on Twitter @remykarem or LinkedIn. You may also reach out to me via [email protected]. Feel free to visit my website at remykarem.github.io.
[ { "code": null, "e": 538, "s": 172, "text": "Why do we need to count the number of parameters in a deep learning model again? We don’t. But in cases where we need to reduce the file size of the model or even reduce the time taken for model inference, knowing the number of parameters before and after model quantization would come in handy. (See video here on Efficient Methods and Hardware for Deep Learning.)" }, { "code": null, "e": 795, "s": 538, "text": "Counting the number of trainable parameters of deep learning models is considered too trivial, because your code can already do this for you. But I’d like to keep my notes here for us to refer to once in a while. Here are the models that we’ll run through:" }, { "code": null, "e": 894, "s": 795, "text": "Feed-Forward Neural Network (FFNN)Recurrent Neural Network (RNN)Convolutional Neural Network (CNN)" }, { "code": null, "e": 929, "s": 894, "text": "Feed-Forward Neural Network (FFNN)" }, { "code": null, "e": 960, "s": 929, "text": "Recurrent Neural Network (RNN)" }, { "code": null, "e": 995, "s": 960, "text": "Convolutional Neural Network (CNN)" }, { "code": null, "e": 1141, "s": 995, "text": "In parallel, I will build the model with APIs from Keras for easy prototyping and a clean code so let’s quickly import the relevant objects here:" }, { "code": null, "e": 1277, "s": 1141, "text": "from keras.layers import Input, Dense, SimpleRNN, LSTM, GRU, Conv2Dfrom keras.layers import Bidirectionalfrom keras.models import Model" }, { "code": null, "e": 1374, "s": 1277, "text": "After building the model, call model.count_params() to verify how many parameters are trainable." }, { "code": null, "e": 1388, "s": 1374, "text": "i, input size" }, { "code": null, "e": 1412, "s": 1388, "text": "h, size of hidden layer" }, { "code": null, "e": 1427, "s": 1412, "text": "o, output size" }, { "code": null, "e": 1449, "s": 1427, "text": "For one hidden layer," }, { "code": null, "e": 1534, "s": 1449, "text": "num_params = connections between layers + biases in every layer= (i×h + h×o) + (h+o)" }, { "code": null, "e": 1596, "s": 1534, "text": "Example 1.1: Input size 3, hidden layer size 5, output size 2" }, { "code": null, "e": 1602, "s": 1596, "text": "i = 3" }, { "code": null, "e": 1608, "s": 1602, "text": "h = 5" }, { "code": null, "e": 1614, "s": 1608, "text": "o = 2" }, { "code": null, "e": 1704, "s": 1614, "text": "num_params = connections between layers + biases in every layer= (3×5 + 5×2) + (5+2) = 32" }, { "code": null, "e": 1807, "s": 1704, "text": " input = Input((None, 3)) dense = Dense(5)(input)output = Dense(2)(dense) model = Model(input, output)" }, { "code": null, "e": 1882, "s": 1807, "text": "Example 1.2: Input size 50, hidden layers size [100,1,100], output size 50" }, { "code": null, "e": 1889, "s": 1882, "text": "i = 50" }, { "code": null, "e": 1905, "s": 1889, "text": "h = 100, 1, 100" }, { "code": null, "e": 1912, "s": 1905, "text": "o = 50" }, { "code": null, "e": 2037, "s": 1912, "text": "num_params = connections between layers + biases in every layer= (50×100 + 100×1 + 1×100 + 100×50) + (100+1+100+50) = 10,451" }, { "code": null, "e": 2194, "s": 2037, "text": " input = Input((None, 50)) dense = Dense(100)(input) dense = Dense(1)(dense) dense = Dense(100)(dense)output = Dense(50)(dense) model = Model(input, output)" }, { "code": null, "e": 2255, "s": 2194, "text": "g, no. of FFNNs in a unit (RNN has 1, GRU has 3, LSTM has 4)" }, { "code": null, "e": 2279, "s": 2255, "text": "h, size of hidden units" }, { "code": null, "e": 2306, "s": 2279, "text": "i, dimension/size of input" }, { "code": null, "e": 2358, "s": 2306, "text": "Since every FFNN has h(h+i) + h parameters, we have" }, { "code": null, "e": 2388, "s": 2358, "text": "num_params = g × [h(h+i) + h]" }, { "code": null, "e": 2449, "s": 2388, "text": "Example 2.1: LSTM with 2 hidden units and input dimension 3." }, { "code": null, "e": 2474, "s": 2449, "text": "g = 4 (LSTM has 4 FFNNs)" }, { "code": null, "e": 2480, "s": 2474, "text": "h = 2" }, { "code": null, "e": 2486, "s": 2480, "text": "i = 3" }, { "code": null, "e": 2539, "s": 2486, "text": "num_params = g × [h(h+i) + h]= 4 × [2(2+3) + 2] = 48" }, { "code": null, "e": 2612, "s": 2539, "text": "input = Input((None, 3)) lstm = LSTM(2)(input)model = Model(input, lstm)" }, { "code": null, "e": 2749, "s": 2612, "text": "Example 2.2: Stacked Bidirectional GRU with 5 hidden units and input size 8 (whose outputs are concatenated) + LSTM with 50 hidden units" }, { "code": null, "e": 2804, "s": 2749, "text": "Bidirectional GRU with 5 hidden units and input size 8" }, { "code": null, "e": 2828, "s": 2804, "text": "g = 3 (GRU has 3 FFNNs)" }, { "code": null, "e": 2834, "s": 2828, "text": "h = 5" }, { "code": null, "e": 2840, "s": 2834, "text": "i = 8" }, { "code": null, "e": 2953, "s": 2840, "text": "num_params_layer1= 2 × g × [h(h+i) + h] (first term is 2 because of bidirectionality)= 2 × 3 × [5(5+8) + 5]= 420" }, { "code": null, "e": 2979, "s": 2953, "text": "LSTM with 50 hidden units" }, { "code": null, "e": 3004, "s": 2979, "text": "g = 4 (LSTM has 4 FFNNs)" }, { "code": null, "e": 3011, "s": 3004, "text": "h = 50" }, { "code": null, "e": 3119, "s": 3011, "text": "i = 5+5 (outputs from bidirectional GRU concatenated; output size of GRU is 5, same as no. of hidden units)" }, { "code": null, "e": 3185, "s": 3119, "text": "num_params_layer2= g × [h(h+i) + h]= 4 × [50(50+10) + 50]= 12,200" }, { "code": null, "e": 3222, "s": 3185, "text": "total_params = 420 + 12,200 = 12,620" }, { "code": null, "e": 3362, "s": 3222, "text": " input = Input((None, 8))layer1 = Bidirectional(GRU(5, return_sequences=True))(input)layer2 = LSTM(50)(layer1) model = Model(input, layer2)" }, { "code": null, "e": 3402, "s": 3362, "text": "merge_mode is concatenation by default." }, { "code": null, "e": 3417, "s": 3402, "text": "For one layer," }, { "code": null, "e": 3452, "s": 3417, "text": "i, no. of input maps (or channels)" }, { "code": null, "e": 3485, "s": 3452, "text": "f, filter size (just the length)" }, { "code": null, "e": 3572, "s": 3485, "text": "o, no. of output maps (or channels. this is also defined by how many filters are used)" }, { "code": null, "e": 3614, "s": 3572, "text": "One filter is applied to every input map." }, { "code": null, "e": 3664, "s": 3614, "text": "num_params= weights + biases= [i × (f×f) × o] + o" }, { "code": null, "e": 3728, "s": 3664, "text": "Example 3.1: Greyscale image with 2×2 filter, output 3 channels" }, { "code": null, "e": 3765, "s": 3728, "text": "i = 1 (greyscale has only 1 channel)" }, { "code": null, "e": 3771, "s": 3765, "text": "f = 2" }, { "code": null, "e": 3777, "s": 3771, "text": "o = 3" }, { "code": null, "e": 3834, "s": 3777, "text": "num_params= [i × (f×f) × o] + o= [1 × (2×2) × 3] + 3= 15" }, { "code": null, "e": 3943, "s": 3834, "text": " input = Input((None, None, 1))conv2d = Conv2D(kernel_size=2, filters=3)(input) model = Model(input, conv2d)" }, { "code": null, "e": 4003, "s": 3943, "text": "Example 3.2: RGB image with 2×2 filter, output of 1 channel" }, { "code": null, "e": 4183, "s": 4003, "text": "There is 1 filter for each input feature map. The resulting convolutions are added element-wise, and a bias term is added to each element. This gives an output with 1 feature map." }, { "code": null, "e": 4216, "s": 4183, "text": "i = 3 (RGB image has 3 channels)" }, { "code": null, "e": 4222, "s": 4216, "text": "f = 2" }, { "code": null, "e": 4228, "s": 4222, "text": "o = 1" }, { "code": null, "e": 4286, "s": 4228, "text": "num_params = [i × (f×f) × o] + o= [3 × (2×2) × 1] + 1= 13" }, { "code": null, "e": 4395, "s": 4286, "text": " input = Input((None, None, 3))conv2d = Conv2D(kernel_size=2, filters=1)(input) model = Model(input, conv2d)" }, { "code": null, "e": 4473, "s": 4395, "text": "Example 3.3: Image with 2 channels, with 2×2 filter, and output of 3 channels" }, { "code": null, "e": 4679, "s": 4473, "text": "There are 3 filters (purple, yellow, cyan) for each input feature map. The resulting convolutions are added element-wise, and a bias term is added to each element. This gives an output with 3 feature maps." }, { "code": null, "e": 4685, "s": 4679, "text": "i = 2" }, { "code": null, "e": 4691, "s": 4685, "text": "f = 2" }, { "code": null, "e": 4697, "s": 4691, "text": "o = 3" }, { "code": null, "e": 4755, "s": 4697, "text": "num_params = [i × (f×f) × o] + o= [2 × (2×2) × 3] + 3= 27" }, { "code": null, "e": 4864, "s": 4755, "text": " input = Input((None, None, 2))conv2d = Conv2D(kernel_size=2, filters=3)(input) model = Model(input, conv2d)" }, { "code": null, "e": 4934, "s": 4864, "text": "That’s all for now! Do leave comments below if you have any feedback!" }, { "code": null, "e": 4961, "s": 4934, "text": "Animated RNN, LSTM and GRU" }, { "code": null, "e": 5037, "s": 4961, "text": "Step-by-Step Tutorial on Linear Regression with Stochastic Gradient Descent" }, { "code": null, "e": 5095, "s": 5037, "text": "10 Gradient Descent Optimisation Algorithms + Cheat Sheet" }, { "code": null, "e": 5123, "s": 5095, "text": "Attn: Illustrated Attention" }, { "code": null, "e": 5151, "s": 5123, "text": "Illustrated: Self-Attention" } ]
C++ Program to Perform Right Rotation on a Binary Search Tree
A Binary Search Tree is a sorted binary tree in which all the nodes have following two properties − The right sub-tree of a node has a key greater than to its parent node's key. The left sub-tree of a node has a key less than or equal to its parent node's key. Each node should not have more than two children. Tree rotation is an operation that changes the structure without interfering with the order of the elements on a binary tree. It moves one node up in the tree and one node down. It is used to change the shape of the tree, and to decrease its height by moving smaller subtrees down and larger subtrees up, resulting in improved performance of many tree operations. The direction of a rotation depends on the side which the tree nodes are shifted upon whilst others say that it depends on which child takes the root’s place. This is a C++ program to perform Left Rotation on a Binary Search Tree. Begin Create a structure avl to declare variables data d, a left pointer l and a right pointer r. Declare a class avl_tree to declare following functions: height() - To calculate height of the tree by max function. Difference() - To calculate height difference of the tree. rr_rotat() - For right-right rotation of the tree. ll_rotat() - For left-left rotation of the tree. lr_rotat() - For left-right rotation of the tree. rl_rotat() - For right-left rotation of the tree. balance() - Balance the tree by getting balance factor. Put the difference in bal_factor. If bal_factor>1 balance the left subtree. If bal_factor<-1 balance the right subtree. insert() - To insert the elements in the tree. show() - To print the tree. inorder() - To print inorder traversal of the tree. preorder() - To print preorder traversal of the tree. postorder() - To print postorder traversal of the tree. In main(), perform switch operation and call the functions as per choice. End. Live Demo #include<iostream> #include<cstdio> #include<sstream> #include<algorithm> #define pow2(n) (1 << (n)) using namespace std; struct avl { int d; struct avl *l; struct avl *r; }*r; class avl_tree { public: int height(avl *); int difference(avl *); avl *rr_rotat(avl *); avl *ll_rotat(avl *); avl *lr_rotat(avl*); avl *rl_rotat(avl *); avl * balance(avl *); avl * insert(avl*, int); void show(avl*, int); void inorder(avl *); void preorder(avl *); void postorder(avl*); avl_tree() { r = NULL; } }; int avl_tree::height(avl *t) { int h = 0; if (t != NULL) { int l_height = height(t->l); int r_height = height(t->r); int max_height = max(l_height, r_height); h = max_height + 1; } return h; } int avl_tree::difference(avl *t) { int l_height = height(t->l); int r_height = height(t->r); int b_factor = l_height - r_height; return b_factor; } avl *avl_tree::rr_rotat(avl *parent) { avl *t; t = parent->r; parent->r = t->l; t->l = parent; cout<<"Right-Right Rotation"; return t; } avl *avl_tree::ll_rotat(avl *parent) { avl *t; t = parent->l; parent->l = t->r; t->r = parent; cout<<"Left-Left Rotation"; return t; } avl *avl_tree::lr_rotat(avl *parent) { avl *t; t = parent->l; parent->l = rr_rotat(t); cout<<"Left-Right Rotation"; return ll_rotat(parent); } avl *avl_tree::rl_rotat(avl *parent) { avl *t; t= parent->r; parent->r = ll_rotat(t); cout<<"Right-Left Rotation"; return rr_rotat(parent); } avl *avl_tree::balance(avl *t) { int bal_factor = difference(t); if (bal_factor > 1) { if (difference(t->l) > 0) t = ll_rotat(t); else t = lr_rotat(t); } else if (bal_factor < -1) { if (difference(t->r) > 0) t= rl_rotat(t); else t = rr_rotat(t); } return t; } avl *avl_tree::insert(avl *r, int v) { if (r == NULL) { r= new avl; r->d = v; r->l = NULL; r->r= NULL; return r; } else if (v< r->d) { r->l= insert(r->l, v); r = balance(r); } else if (v >= r->d) { r->r= insert(r->r, v); r = balance(r); } return r; } void avl_tree::show(avl *p, int l) { int i; if (p != NULL) { show(p->r, l+ 1); cout<<" "; if (p == r) cout << "Root -> "; for (i = 0; i < l&& p != r; i++) cout << " "; cout << p->d; show(p->l, l + 1); } } void avl_tree::inorder(avl *t) { if (t == NULL) return; inorder(t->l); cout << t->d << " "; inorder(t->r); } void avl_tree::preorder(avl *t) { if (t == NULL) return; cout << t->d << " "; preorder(t->l); preorder(t->r); } void avl_tree::postorder(avl *t) { if (t == NULL) return; postorder(t ->l); postorder(t ->r); cout << t->d << " "; } int main() { int c, i; avl_tree avl; while (1) { cout << "1.Insert Element into the tree" << endl; cout << "2.show Balanced AVL Tree" << endl; cout << "3.InOrder traversal" << endl; cout << "4.PreOrder traversal" << endl; cout << "5.PostOrder traversal" << endl; cout << "6.Exit" << endl; cout << "Enter your Choice: "; cin >> c; switch (c) { case 1: cout << "Enter value to be inserted: "; cin >> i; r= avl.insert(r, i); break; case 2: if (r == NULL) { cout << "Tree is Empty" << endl; continue; } cout << "Balanced AVL Tree:" << endl; avl.show(r, 1); cout<<endl; break; case 3: cout << "Inorder Traversal:" << endl; avl.inorder(r); cout << endl; break; case 4: cout << "Preorder Traversal:" << endl; avl.preorder(r); cout << endl; break; case 5: cout << "Postorder Traversal:" << endl; avl.postorder(r); cout << endl; break; case 6: exit(1); break; default: cout << "Wrong Choice" << endl; } } return 0; } 1.Insert Element into the tree 2.show Balanced AVL Tree 3.InOrder traversal 4.PreOrder traversal 5.PostOrder traversal 6.Exit Enter your Choice: 1 Enter value to be inserted: 13 1.Insert Element into the tree 2.show Balanced AVL Tree 3.InOrder traversal 4.PreOrder traversal 5.PostOrder traversal 6.Exit Enter your Choice: 1 Enter value to be inserted: 10 1.Insert Element into the tree 2.show Balanced AVL Tree 3.InOrder traversal 4.PreOrder traversal 5.PostOrder traversal 6.Exit Enter your Choice: 1 Enter value to be inserted: 15 1.Insert Element into the tree 2.show Balanced AVL Tree 3.InOrder traversal 4.PreOrder traversal 5.PostOrder traversal 6.Exit Enter your Choice: 1 Enter value to be inserted: 5 1.Insert Element into the tree 2.show Balanced AVL Tree 3.InOrder traversal 4.PreOrder traversal 5.PostOrder traversal 6.Exit Enter your Choice: 1 Enter value to be inserted: 11 1.Insert Element into the tree 2.show Balanced AVL Tree 3.InOrder traversal 4.PreOrder traversal 5.PostOrder traversal 6.Exit Enter your Choice: 1 Enter value to be inserted: 4 Left-Left Rotation1.Insert Element into the tree 2.show Balanced AVL Tree 3.InOrder traversal 4.PreOrder traversal 5.PostOrder traversal 6.Exit Enter your Choice: 1 Enter value to be inserted: 8 1.Insert Element into the tree 2.show Balanced AVL Tree 3.InOrder traversal 4.PreOrder traversal 5.PostOrder traversal 6.Exit Enter your Choice: 1 Enter value to be inserted: 16 1.Insert Element into the tree 2.show Balanced AVL Tree 3.InOrder traversal 4.PreOrder traversal 5.PostOrder traversal 6.Exit Enter your Choice: 3 Inorder Traversal: 4 5 8 10 11 13 15 16 1.Insert Element into the tree 2.show Balanced AVL Tree 3.InOrder traversal 4.PreOrder traversal 5.PostOrder traversal 6.Exit Enter your Choice: 4 Preorder Traversal: 10 5 4 8 13 11 15 16 1.Insert Element into the tree 2.show Balanced AVL Tree 3.InOrder traversal 4.PreOrder traversal 5.PostOrder traversal 6.Exit Enter your Choice: 5 Postorder Traversal: 4 8 5 11 16 15 13 10 1.Insert Element into the tree 2.show Balanced AVL Tree 3.InOrder traversal 4.PreOrder traversal 5.PostOrder traversal 6.Exit Enter your Choice: 1 Enter value to be inserted: 14 1.Insert Element into the tree 2.show Balanced AVL Tree 3.InOrder traversal 4.PreOrder traversal 5.PostOrder traversal 6.Exit Enter your Choice: 1 Enter value to be inserted: 3 1.Insert Element into the tree 2.show Balanced AVL Tree 3.InOrder traversal 4.PreOrder traversal 5.PostOrder traversal 6.Exit Enter your Choice: 1 Enter value to be inserted: 7 1.Insert Element into the tree 2.show Balanced AVL Tree 3.InOrder traversal 4.PreOrder traversal 5.PostOrder traversal 6.Exit Enter your Choice: 1 Enter value to be inserted: 9 1.Insert Element into the tree 2.show Balanced AVL Tree 3.InOrder traversal 4.PreOrder traversal 5.PostOrder traversal 6.Exit Enter your Choice: 1 Enter value to be inserted: 52 Right-Right Rotation 1.Insert Element into the tree 2.show Balanced AVL Tree 3.InOrder traversal 4.PreOrder traversal 5.PostOrder traversal 6.Exit Enter your Choice: 6
[ { "code": null, "e": 1162, "s": 1062, "text": "A Binary Search Tree is a sorted binary tree in which all the nodes have following two properties −" }, { "code": null, "e": 1240, "s": 1162, "text": "The right sub-tree of a node has a key greater than to its parent node's key." }, { "code": null, "e": 1323, "s": 1240, "text": "The left sub-tree of a node has a key less than or equal to its parent node's key." }, { "code": null, "e": 1373, "s": 1323, "text": "Each node should not have more than two children." }, { "code": null, "e": 1968, "s": 1373, "text": "Tree rotation is an operation that changes the structure without interfering with the order of the elements on a binary tree. It moves one node up in the tree and one node down. It is used to change the shape of the tree, and to decrease its height by moving smaller subtrees down and larger subtrees up, resulting in improved performance of many tree operations. The direction of a rotation depends on the side which the tree nodes are shifted upon whilst others say that it depends on which child takes the root’s place. This is a C++ program to perform Left Rotation on a Binary Search Tree." }, { "code": null, "e": 2982, "s": 1968, "text": "Begin\n Create a structure avl to declare variables data d, a left pointer l and a right pointer r.\n Declare a class avl_tree to declare following functions:\n height() - To calculate height of the tree by max function.\n Difference() - To calculate height difference of the tree.\n rr_rotat() - For right-right rotation of the tree.\n ll_rotat() - For left-left rotation of the tree.\n lr_rotat() - For left-right rotation of the tree.\n rl_rotat() - For right-left rotation of the tree.\n balance() - Balance the tree by getting balance factor. Put the difference in bal_factor. If bal_factor>1 balance the left subtree.\n If bal_factor<-1 balance the right subtree.\n insert() - To insert the elements in the tree.\n show() - To print the tree.\n inorder() - To print inorder traversal of the tree.\n preorder() - To print preorder traversal of the tree.\n postorder() - To print postorder traversal of the tree.\n In main(), perform switch operation and call the functions as per choice.\nEnd." }, { "code": null, "e": 2993, "s": 2982, "text": " Live Demo" }, { "code": null, "e": 7282, "s": 2993, "text": "#include<iostream>\n#include<cstdio>\n#include<sstream>\n#include<algorithm>\n#define pow2(n) (1 << (n))\nusing namespace std;\nstruct avl {\n int d;\n struct avl *l;\n struct avl *r;\n}*r;\nclass avl_tree {\n public:\n int height(avl *);\n int difference(avl *);\n avl *rr_rotat(avl *);\n avl *ll_rotat(avl *);\n avl *lr_rotat(avl*);\n avl *rl_rotat(avl *);\n avl * balance(avl *);\n avl * insert(avl*, int);\n void show(avl*, int);\n void inorder(avl *);\n void preorder(avl *);\n void postorder(avl*);\n avl_tree() {\n r = NULL;\n }\n};\nint avl_tree::height(avl *t) {\n int h = 0;\n if (t != NULL) {\n int l_height = height(t->l);\n int r_height = height(t->r);\n int max_height = max(l_height, r_height);\n h = max_height + 1;\n }\n return h;\n}\nint avl_tree::difference(avl *t) {\n int l_height = height(t->l);\n int r_height = height(t->r);\n int b_factor = l_height - r_height;\n return b_factor;\n}\navl *avl_tree::rr_rotat(avl *parent) {\n avl *t;\n t = parent->r;\n parent->r = t->l;\n t->l = parent;\n cout<<\"Right-Right Rotation\";\n return t;\n}\navl *avl_tree::ll_rotat(avl *parent) {\n avl *t;\n t = parent->l;\n parent->l = t->r;\n t->r = parent;\n cout<<\"Left-Left Rotation\";\n return t;\n}\navl *avl_tree::lr_rotat(avl *parent) {\n avl *t;\n t = parent->l;\n parent->l = rr_rotat(t);\n cout<<\"Left-Right Rotation\";\n return ll_rotat(parent);\n}\navl *avl_tree::rl_rotat(avl *parent) {\n avl *t;\n t= parent->r;\n parent->r = ll_rotat(t);\n cout<<\"Right-Left Rotation\";\n return rr_rotat(parent);\n}\navl *avl_tree::balance(avl *t) {\n int bal_factor = difference(t);\n if (bal_factor > 1) {\n if (difference(t->l) > 0)\n t = ll_rotat(t);\n else\n t = lr_rotat(t);\n }\n else if (bal_factor < -1) {\n if (difference(t->r) > 0)\n t= rl_rotat(t);\n else\n t = rr_rotat(t);\n }\n return t;\n}\navl *avl_tree::insert(avl *r, int v) {\n if (r == NULL) {\n r= new avl;\n r->d = v;\n r->l = NULL;\n r->r= NULL;\n return r;\n }\n else if (v< r->d) {\n r->l= insert(r->l, v);\n r = balance(r);\n }\n else if (v >= r->d) {\n r->r= insert(r->r, v);\n r = balance(r);\n }\n return r;\n}\nvoid avl_tree::show(avl *p, int l) {\n int i;\n if (p != NULL) {\n show(p->r, l+ 1);\n cout<<\" \";\n if (p == r)\n cout << \"Root -> \";\n for (i = 0; i < l&& p != r; i++)\n cout << \" \";\n cout << p->d;\n show(p->l, l + 1);\n }\n}\nvoid avl_tree::inorder(avl *t) {\n if (t == NULL)\n return;\n inorder(t->l);\n cout << t->d << \" \";\n inorder(t->r);\n}\nvoid avl_tree::preorder(avl *t) {\n if (t == NULL)\n return;\n cout << t->d << \" \";\n preorder(t->l);\n preorder(t->r);\n}\nvoid avl_tree::postorder(avl *t) {\n if (t == NULL)\n return;\n postorder(t ->l);\n postorder(t ->r);\n cout << t->d << \" \";\n}\nint main() {\n int c, i;\n avl_tree avl;\n while (1) {\n cout << \"1.Insert Element into the tree\" << endl;\n cout << \"2.show Balanced AVL Tree\" << endl;\n cout << \"3.InOrder traversal\" << endl;\n cout << \"4.PreOrder traversal\" << endl;\n cout << \"5.PostOrder traversal\" << endl;\n cout << \"6.Exit\" << endl;\n cout << \"Enter your Choice: \";\n cin >> c;\n switch (c) {\n case 1:\n cout << \"Enter value to be inserted: \";\n cin >> i;\n r= avl.insert(r, i);\n break;\n case 2:\n if (r == NULL) {\n cout << \"Tree is Empty\" << endl;\n continue;\n }\n cout << \"Balanced AVL Tree:\" << endl;\n avl.show(r, 1);\n cout<<endl;\n break;\n case 3:\n cout << \"Inorder Traversal:\" << endl;\n avl.inorder(r);\n cout << endl;\n break;\n case 4:\n cout << \"Preorder Traversal:\" << endl;\n avl.preorder(r);\n cout << endl;\n break;\n case 5:\n cout << \"Postorder Traversal:\" << endl;\n avl.postorder(r);\n cout << endl;\n break;\n case 6:\n exit(1);\n break;\n default:\n cout << \"Wrong Choice\" << endl;\n }\n }\n return 0;\n}" }, { "code": null, "e": 10340, "s": 7282, "text": "1.Insert Element into the tree\n2.show Balanced AVL Tree\n3.InOrder traversal\n4.PreOrder traversal\n5.PostOrder traversal\n6.Exit\nEnter your Choice: 1\nEnter value to be inserted: 13\n1.Insert Element into the tree\n2.show Balanced AVL Tree\n3.InOrder traversal\n4.PreOrder traversal\n5.PostOrder traversal\n6.Exit\nEnter your Choice: 1\nEnter value to be inserted: 10\n1.Insert Element into the tree\n2.show Balanced AVL Tree\n3.InOrder traversal\n4.PreOrder traversal\n5.PostOrder traversal\n6.Exit\nEnter your Choice: 1\nEnter value to be inserted: 15\n1.Insert Element into the tree\n2.show Balanced AVL Tree\n3.InOrder traversal\n4.PreOrder traversal\n5.PostOrder traversal\n6.Exit\nEnter your Choice: 1\nEnter value to be inserted: 5\n1.Insert Element into the tree\n2.show Balanced AVL Tree\n3.InOrder traversal\n4.PreOrder traversal\n5.PostOrder traversal\n6.Exit\nEnter your Choice: 1\nEnter value to be inserted: 11\n1.Insert Element into the tree\n2.show Balanced AVL Tree\n3.InOrder traversal\n4.PreOrder traversal\n5.PostOrder traversal\n6.Exit\nEnter your Choice: 1\nEnter value to be inserted: 4\nLeft-Left Rotation1.Insert Element into the tree\n2.show Balanced AVL Tree\n3.InOrder traversal\n4.PreOrder traversal\n5.PostOrder traversal\n6.Exit\nEnter your Choice: 1\nEnter value to be inserted: 8\n1.Insert Element into the tree\n2.show Balanced AVL Tree\n3.InOrder traversal\n4.PreOrder traversal\n5.PostOrder traversal\n6.Exit\nEnter your Choice: 1\nEnter value to be inserted: 16\n1.Insert Element into the tree\n2.show Balanced AVL Tree\n3.InOrder traversal\n4.PreOrder traversal\n5.PostOrder traversal\n6.Exit\nEnter your Choice: 3\nInorder Traversal:\n4 5 8 10 11 13 15 16\n1.Insert Element into the tree\n2.show Balanced AVL Tree\n3.InOrder traversal\n4.PreOrder traversal\n5.PostOrder traversal\n6.Exit\nEnter your Choice: 4\nPreorder Traversal:\n10 5 4 8 13 11 15 16\n1.Insert Element into the tree\n2.show Balanced AVL Tree\n3.InOrder traversal\n4.PreOrder traversal\n5.PostOrder traversal\n6.Exit\nEnter your Choice: 5\nPostorder Traversal:\n4 8 5 11 16 15 13 10\n1.Insert Element into the tree\n2.show Balanced AVL Tree\n3.InOrder traversal\n4.PreOrder traversal\n5.PostOrder traversal\n6.Exit\nEnter your Choice: 1\nEnter value to be inserted: 14\n1.Insert Element into the tree\n2.show Balanced AVL Tree\n3.InOrder traversal\n4.PreOrder traversal\n5.PostOrder traversal\n6.Exit\nEnter your Choice: 1\nEnter value to be inserted: 3\n1.Insert Element into the tree\n2.show Balanced AVL Tree\n3.InOrder traversal\n4.PreOrder traversal\n5.PostOrder traversal\n6.Exit\nEnter your Choice: 1\nEnter value to be inserted: 7\n1.Insert Element into the tree\n2.show Balanced AVL Tree\n3.InOrder traversal\n4.PreOrder traversal\n5.PostOrder traversal\n6.Exit\nEnter your Choice: 1\nEnter value to be inserted: 9\n1.Insert Element into the tree\n2.show Balanced AVL Tree\n3.InOrder traversal\n4.PreOrder traversal\n5.PostOrder traversal\n6.Exit\nEnter your Choice: 1\nEnter value to be inserted: 52\nRight-Right Rotation\n1.Insert Element into the tree\n2.show Balanced AVL Tree\n3.InOrder traversal\n4.PreOrder traversal\n5.PostOrder traversal\n6.Exit\nEnter your Choice: 6" } ]
SAS - IF-THEN-DELETE Statement
An IF-THEN-DELETE statement consists of a boolean expression followed by SAS THEN DELETE statement. The basic syntax for creating an if statement in SAS is − IF (condition ) THEN DELETE; If the condition evaluates to be true, then the respective observation is processed. DATA EMPDAT; INPUT EMPID ENAME $ SALARY DEPT $ DOJ DATE9.; LABEL ID = 'Employee ID'; FORMAT DOJ DATE9.; DATALINES; 1 Rick 623.3 IT 02APR2001 2 Dan 515.2 OPS 11JUL2012 3 Mike 611.5 IT 21OCT2000 4 Ryan 729.1 HR 30JUL2012 5 Gary 843.2 FIN 06AUG2000 6 Tusar 578.6 IT 01MAR2009 7 Pranab 632.8 OPS 16AUG1998 8 Rasmi 722.5 FIN 13SEP2014 ; Data EMPDAT1; Set EMPDAT; IF SALARY > 700 THEN DELETE; PROC PRINT DATA = EMPDAT1; run; When the above code is executed, it produces the following result − 50 Lectures 5.5 hours Code And Create 124 Lectures 30 hours Juan Galvan 162 Lectures 31.5 hours Yossef Ayman Zedan 35 Lectures 2.5 hours Ermin Dedic 167 Lectures 45.5 hours Muslim Helalee Print Add Notes Bookmark this page
[ { "code": null, "e": 2683, "s": 2583, "text": "An IF-THEN-DELETE statement consists of a boolean expression followed by SAS THEN DELETE statement." }, { "code": null, "e": 2741, "s": 2683, "text": "The basic syntax for creating an if statement in SAS is −" }, { "code": null, "e": 2770, "s": 2741, "text": "IF (condition ) THEN DELETE;" }, { "code": null, "e": 2855, "s": 2770, "text": "If the condition evaluates to be true, then the respective observation is processed." }, { "code": null, "e": 3277, "s": 2855, "text": "DATA EMPDAT;\nINPUT EMPID ENAME $ SALARY DEPT $ DOJ DATE9.;\nLABEL ID = 'Employee ID';\nFORMAT DOJ DATE9.;\nDATALINES;\n1 Rick 623.3 IT 02APR2001\n2 Dan 515.2 OPS 11JUL2012\n3 Mike 611.5 IT 21OCT2000\n4 Ryan 729.1 HR 30JUL2012\n5 Gary 843.2 FIN 06AUG2000\n6 Tusar 578.6 IT 01MAR2009\n7 Pranab 632.8 OPS 16AUG1998\n8 Rasmi 722.5 FIN 13SEP2014\n;\nData EMPDAT1;\nSet EMPDAT;\nIF SALARY > 700 THEN DELETE;\nPROC PRINT DATA = EMPDAT1;\nrun; " }, { "code": null, "e": 3345, "s": 3277, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 3380, "s": 3345, "text": "\n 50 Lectures \n 5.5 hours \n" }, { "code": null, "e": 3397, "s": 3380, "text": " Code And Create" }, { "code": null, "e": 3432, "s": 3397, "text": "\n 124 Lectures \n 30 hours \n" }, { "code": null, "e": 3445, "s": 3432, "text": " Juan Galvan" }, { "code": null, "e": 3482, "s": 3445, "text": "\n 162 Lectures \n 31.5 hours \n" }, { "code": null, "e": 3502, "s": 3482, "text": " Yossef Ayman Zedan" }, { "code": null, "e": 3537, "s": 3502, "text": "\n 35 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3550, "s": 3537, "text": " Ermin Dedic" }, { "code": null, "e": 3587, "s": 3550, "text": "\n 167 Lectures \n 45.5 hours \n" }, { "code": null, "e": 3603, "s": 3587, "text": " Muslim Helalee" }, { "code": null, "e": 3610, "s": 3603, "text": " Print" }, { "code": null, "e": 3621, "s": 3610, "text": " Add Notes" } ]
C# - For Loop
A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times. The syntax of a for loop in C# is − for ( init; condition; increment ) { statement(s); } Here is the flow of control in a for loop − The init step is executed first, and only once. This step allows you to declare and initialize any loop control variables. You are not required to put a statement here, as long as a semicolon appears. The init step is executed first, and only once. This step allows you to declare and initialize any loop control variables. You are not required to put a statement here, as long as a semicolon appears. Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop does not execute and flow of control jumps to the next statement just after the for loop. Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop does not execute and flow of control jumps to the next statement just after the for loop. After the body of the for loop executes, the flow of control jumps back up to the increment statement. This statement allows you to update any loop control variables. This statement can be left blank, as long as a semicolon appears after the condition. After the body of the for loop executes, the flow of control jumps back up to the increment statement. This statement allows you to update any loop control variables. This statement can be left blank, as long as a semicolon appears after the condition. The condition is now evaluated again. If it is true, the loop executes and the process repeats itself (body of loop, then increment step, and then again testing for a condition). After the condition becomes false, the for loop terminates. The condition is now evaluated again. If it is true, the loop executes and the process repeats itself (body of loop, then increment step, and then again testing for a condition). After the condition becomes false, the for loop terminates. using System; namespace Loops { class Program { static void Main(string[] args) { /* for loop execution */ for (int a = 10; a < 20; a = a + 1) { Console.WriteLine("value of a: {0}", a); } Console.ReadLine(); } } } 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 119 Lectures 23.5 hours Raja Biswas 37 Lectures 13 hours Trevoir Williams 16 Lectures 1 hours Peter Jepson 159 Lectures 21.5 hours Ebenezer Ogbu 193 Lectures 17 hours Arnold Higuit 24 Lectures 2.5 hours Eric Frick Print Add Notes Bookmark this page
[ { "code": null, "e": 2409, "s": 2270, "text": "A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times." }, { "code": null, "e": 2445, "s": 2409, "text": "The syntax of a for loop in C# is −" }, { "code": null, "e": 2502, "s": 2445, "text": "for ( init; condition; increment ) {\n statement(s);\n}\n" }, { "code": null, "e": 2546, "s": 2502, "text": "Here is the flow of control in a for loop −" }, { "code": null, "e": 2747, "s": 2546, "text": "The init step is executed first, and only once. This step allows you to declare and initialize any loop control variables. You are not required to put a statement here, as long as a semicolon appears." }, { "code": null, "e": 2948, "s": 2747, "text": "The init step is executed first, and only once. This step allows you to declare and initialize any loop control variables. You are not required to put a statement here, as long as a semicolon appears." }, { "code": null, "e": 3158, "s": 2948, "text": "Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop does not execute and flow of control jumps to the next statement just after the for loop." }, { "code": null, "e": 3368, "s": 3158, "text": "Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop does not execute and flow of control jumps to the next statement just after the for loop." }, { "code": null, "e": 3621, "s": 3368, "text": "After the body of the for loop executes, the flow of control jumps back up to the increment statement. This statement allows you to update any loop control variables. This statement can be left blank, as long as a semicolon appears after the condition." }, { "code": null, "e": 3874, "s": 3621, "text": "After the body of the for loop executes, the flow of control jumps back up to the increment statement. This statement allows you to update any loop control variables. This statement can be left blank, as long as a semicolon appears after the condition." }, { "code": null, "e": 4113, "s": 3874, "text": "The condition is now evaluated again. If it is true, the loop executes and the process repeats itself (body of loop, then increment step, and then again testing for a condition). After the condition becomes false, the for loop terminates." }, { "code": null, "e": 4352, "s": 4113, "text": "The condition is now evaluated again. If it is true, the loop executes and the process repeats itself (body of loop, then increment step, and then again testing for a condition). After the condition becomes false, the for loop terminates." }, { "code": null, "e": 4644, "s": 4352, "text": "using System;\n\nnamespace Loops {\n class Program {\n static void Main(string[] args) {\n \n /* for loop execution */\n for (int a = 10; a < 20; a = a + 1) {\n Console.WriteLine(\"value of a: {0}\", a);\n }\n Console.ReadLine();\n }\n }\n} " }, { "code": null, "e": 4725, "s": 4644, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 4876, "s": 4725, "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": 4913, "s": 4876, "text": "\n 119 Lectures \n 23.5 hours \n" }, { "code": null, "e": 4926, "s": 4913, "text": " Raja Biswas" }, { "code": null, "e": 4960, "s": 4926, "text": "\n 37 Lectures \n 13 hours \n" }, { "code": null, "e": 4978, "s": 4960, "text": " Trevoir Williams" }, { "code": null, "e": 5011, "s": 4978, "text": "\n 16 Lectures \n 1 hours \n" }, { "code": null, "e": 5025, "s": 5011, "text": " Peter Jepson" }, { "code": null, "e": 5062, "s": 5025, "text": "\n 159 Lectures \n 21.5 hours \n" }, { "code": null, "e": 5077, "s": 5062, "text": " Ebenezer Ogbu" }, { "code": null, "e": 5112, "s": 5077, "text": "\n 193 Lectures \n 17 hours \n" }, { "code": null, "e": 5127, "s": 5112, "text": " Arnold Higuit" }, { "code": null, "e": 5162, "s": 5127, "text": "\n 24 Lectures \n 2.5 hours \n" }, { "code": null, "e": 5174, "s": 5162, "text": " Eric Frick" }, { "code": null, "e": 5181, "s": 5174, "text": " Print" }, { "code": null, "e": 5192, "s": 5181, "text": " Add Notes" } ]
How to create a CSV file manually in PowerShell?
There are few methods to create a CSV file in the PowerShell, but we will use the best easy method to create it. First, to create a CSV file in PowerShell, we need to create headers for it. But before it, we need output file name along with its path. $outfile = "C:\temp\Outfile.csv" Here we have given output file name Outfile.csv in the path C:\temp. Now we will create headers, $newcsv = {} | Select "EMP_Name","EMP_ID","CITY" | Export-Csv $outfile Here, we have created a CSV file and exported a file to the newly created file. We will now import this file to check if the headers are created. Import-Csv $outfile EMP_Name EMP_ID CITY -------- ------ ---- So, in the above output, we can see the headers are created. Now we need to insert the data inside the CSV file, for that we first import CSV file into a variable and then we will insert data. $csvfile = Import-Csv $outfile $csvfile.Emp_Name = "Charles" $csvfile.EMP_ID = "2000" $csvfile.CITY = "New York" Check the output of the above-inserted data. PS C:\WINDOWS\system32> $csvfile EMP_Name EMP_ID CITY -------- ------ ---- Charles 2000 New York Overall commands to create a script − $outfile = "C:\temp\Outfile.csv" $newcsv = {} | Select "EMP_Name","EMP_ID","CITY" | Export-Csv $outfile $csvfile = Import-Csv $outfile $csvfile.Emp_Name = "Charles" $csvfile.EMP_ID = "2000" $csvfile.CITY = "New York" This output is stored into the variable, to store this output into the created CSV file, you need to export CSV file to the output file again as shown in the below example. $csvfile | Export-CSV $outfile Import-Csv $outfile EMP_Name EMP_ID CITY -------- ------ ---- Charles 2000 New York
[ { "code": null, "e": 1175, "s": 1062, "text": "There are few methods to create a CSV file in the PowerShell, but we will use the best easy method\nto create it." }, { "code": null, "e": 1313, "s": 1175, "text": "First, to create a CSV file in PowerShell, we need to create headers for it. But before it, we need\noutput file name along with its path." }, { "code": null, "e": 1346, "s": 1313, "text": "$outfile = \"C:\\temp\\Outfile.csv\"" }, { "code": null, "e": 1415, "s": 1346, "text": "Here we have given output file name Outfile.csv in the path C:\\temp." }, { "code": null, "e": 1443, "s": 1415, "text": "Now we will create headers," }, { "code": null, "e": 1514, "s": 1443, "text": "$newcsv = {} | Select \"EMP_Name\",\"EMP_ID\",\"CITY\" | Export-Csv $outfile" }, { "code": null, "e": 1594, "s": 1514, "text": "Here, we have created a CSV file and exported a file to the newly created file." }, { "code": null, "e": 1660, "s": 1594, "text": "We will now import this file to check if the headers are created." }, { "code": null, "e": 1680, "s": 1660, "text": "Import-Csv $outfile" }, { "code": null, "e": 1722, "s": 1680, "text": "EMP_Name EMP_ID CITY\n-------- ------ ----" }, { "code": null, "e": 1783, "s": 1722, "text": "So, in the above output, we can see the headers are created." }, { "code": null, "e": 1915, "s": 1783, "text": "Now we need to insert the data inside the CSV file, for that we first import CSV file into a variable\nand then we will insert data." }, { "code": null, "e": 2028, "s": 1915, "text": "$csvfile = Import-Csv $outfile\n$csvfile.Emp_Name = \"Charles\"\n$csvfile.EMP_ID = \"2000\"\n$csvfile.CITY = \"New York\"" }, { "code": null, "e": 2073, "s": 2028, "text": "Check the output of the above-inserted data." }, { "code": null, "e": 2191, "s": 2073, "text": "PS C:\\WINDOWS\\system32> $csvfile\nEMP_Name EMP_ID CITY\n-------- ------ ----\nCharles 2000 New York" }, { "code": null, "e": 2229, "s": 2191, "text": "Overall commands to create a script −" }, { "code": null, "e": 2446, "s": 2229, "text": "$outfile = \"C:\\temp\\Outfile.csv\"\n$newcsv = {} | Select \"EMP_Name\",\"EMP_ID\",\"CITY\" | Export-Csv $outfile\n$csvfile = Import-Csv $outfile\n$csvfile.Emp_Name = \"Charles\"\n$csvfile.EMP_ID = \"2000\"\n$csvfile.CITY = \"New York\"" }, { "code": null, "e": 2619, "s": 2446, "text": "This output is stored into the variable, to store this output into the created CSV file, you need to\nexport CSV file to the output file again as shown in the below example." }, { "code": null, "e": 2650, "s": 2619, "text": "$csvfile | Export-CSV $outfile" }, { "code": null, "e": 2670, "s": 2650, "text": "Import-Csv $outfile" }, { "code": null, "e": 2760, "s": 2670, "text": "EMP_Name EMP_ID CITY\n-------- ------ ----\nCharles 2000 New York" } ]
Largest rectangle that can be inscribed in a semicircle - GeeksforGeeks
15 Mar, 2021 Given a semicircle of radius r, we have to find the largest rectangle that can be inscribed in the semicircle, with base lying on the diameter.Examples: Input : r = 4 Output : 16 Input : r = 5 Output :25 Let r be the radius of the semicircle, x one half of the base of the rectangle, and y the height of the rectangle. We want to maximize the area, A = 2xy. So from the diagram we have, y = √(r^2 – x^2) So, A = 2*x*(√(r^2 – x^2)), or dA/dx = 2*√(r^2 – x^2) -2*x^2/√(r^2 – x^2) Setting this derivative equal to 0 and solving for x, dA/dx = 0 or, 2*√(r^2 – x^2) – 2*x^2/√(r^2 – x^2) = 0 2r^2 – 4x^2 = 0 x = r/√2This is the maximum of the area as, dA/dx > 0 when x > r/√2 and, dA/dx < 0 when x > r/√2Since y =√(r^2 – x^2) we then havey = r/√2Thus, the base of the rectangle has length = r/√2 and its height has length √2*r/2. So, Area, A=r^2 C++ Java Python 3 C# PHP Javascript // C++ Program to find the// the biggest rectangle// which can be inscribed// within the semicircle#include <bits/stdc++.h>using namespace std; // Function to find the area// of the biggest rectanglefloat rectanglearea(float r){ // the radius cannot be negative if (r < 0) return -1; // area of the rectangle float a = r * r; return a;} // Driver codeint main(){ float r = 5; cout << rectanglearea(r) << endl; return 0;} // Java Program to find the// the biggest rectangle// which can be inscribed// within the semicircleclass GFG{ // Function to find the area// of the biggest rectanglestatic float rectanglearea(float r){ // the radius cannot be negativeif (r < 0) return -1; // area of the rectanglefloat a = r * r; return a;} // Driver codepublic static void main(String[] args){ float r = 5; System.out.println((int)rectanglearea(r));}} // This code is contributed// by ChitraNayal # Python 3 Program to find the# the biggest rectangle# which can be inscribed# within the semicircle # Function to find the area# of the biggest rectangledef rectanglearea(r) : # the radius cannot # be negative if r < 0 : return -1 # area of the rectangle a = r * r return a # Driver Codeif __name__ == "__main__" : r = 5 # function calling print(rectanglearea(r)) # This code is contributed# by ANKITRAI1 // C# Program to find the// the biggest rectangle// which can be inscribed// within the semicircleusing System; class GFG{ // Function to find the area// of the biggest rectanglestatic float rectanglearea(float r){ // the radius cannot be negativeif (r < 0) return -1; // area of the rectanglefloat a = r * r; return a;} // Driver codepublic static void Main(){ float r = 5; Console.Write((int)rectanglearea(r));}} // This code is contributed// by ChitraNayal <?php// PHP Program to find the// the biggest rectangle// which can be inscribed// within the semicircle // Function to find the area// of the biggest rectanglefunction rectanglearea($r){ // the radius cannot // be negative if ($r < 0) return -1; // area of the rectangle $a = $r * $r; return $a;} // Driver code$r = 5;echo rectanglearea($r)."\n"; // This code is contributed// by ChitraNayal?> <script> // javascript Program to find the// the biggest rectangle// which can be inscribed// within the semicircle // Function to find the area// of the biggest rectanglefunction rectanglearea(r){ // the radius cannot be negative if (r < 0) return -1; // area of the rectangle var a = r * r; return a;} // Driver code var r = 5;document.write(parseInt(rectanglearea(r))); // This code is contributed by Amit Katiyar </script> OUTPUT : 25 ankthon ukasp amit143katiyar circle square-rectangle Geometric School Programming Geometric Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Convex Hull | Set 2 (Graham Scan) Check whether a given point lies inside a triangle or not Convex Hull using Divide and Conquer Algorithm Optimum location of point to minimize total distance Program to find area of a triangle Python Dictionary Arrays in C/C++ Inheritance in C++ Reverse a string in Java C++ Classes and Objects
[ { "code": null, "e": 26811, "s": 26783, "text": "\n15 Mar, 2021" }, { "code": null, "e": 26966, "s": 26811, "text": "Given a semicircle of radius r, we have to find the largest rectangle that can be inscribed in the semicircle, with base lying on the diameter.Examples: " }, { "code": null, "e": 27019, "s": 26966, "text": "Input : r = 4\nOutput : 16\n\nInput : r = 5 \nOutput :25" }, { "code": null, "e": 27660, "s": 27023, "text": "Let r be the radius of the semicircle, x one half of the base of the rectangle, and y the height of the rectangle. We want to maximize the area, A = 2xy. So from the diagram we have, y = √(r^2 – x^2) So, A = 2*x*(√(r^2 – x^2)), or dA/dx = 2*√(r^2 – x^2) -2*x^2/√(r^2 – x^2) Setting this derivative equal to 0 and solving for x, dA/dx = 0 or, 2*√(r^2 – x^2) – 2*x^2/√(r^2 – x^2) = 0 2r^2 – 4x^2 = 0 x = r/√2This is the maximum of the area as, dA/dx > 0 when x > r/√2 and, dA/dx < 0 when x > r/√2Since y =√(r^2 – x^2) we then havey = r/√2Thus, the base of the rectangle has length = r/√2 and its height has length √2*r/2. So, Area, A=r^2 " }, { "code": null, "e": 27664, "s": 27660, "text": "C++" }, { "code": null, "e": 27669, "s": 27664, "text": "Java" }, { "code": null, "e": 27678, "s": 27669, "text": "Python 3" }, { "code": null, "e": 27681, "s": 27678, "text": "C#" }, { "code": null, "e": 27685, "s": 27681, "text": "PHP" }, { "code": null, "e": 27696, "s": 27685, "text": "Javascript" }, { "code": "// C++ Program to find the// the biggest rectangle// which can be inscribed// within the semicircle#include <bits/stdc++.h>using namespace std; // Function to find the area// of the biggest rectanglefloat rectanglearea(float r){ // the radius cannot be negative if (r < 0) return -1; // area of the rectangle float a = r * r; return a;} // Driver codeint main(){ float r = 5; cout << rectanglearea(r) << endl; return 0;}", "e": 28151, "s": 27696, "text": null }, { "code": "// Java Program to find the// the biggest rectangle// which can be inscribed// within the semicircleclass GFG{ // Function to find the area// of the biggest rectanglestatic float rectanglearea(float r){ // the radius cannot be negativeif (r < 0) return -1; // area of the rectanglefloat a = r * r; return a;} // Driver codepublic static void main(String[] args){ float r = 5; System.out.println((int)rectanglearea(r));}} // This code is contributed// by ChitraNayal", "e": 28626, "s": 28151, "text": null }, { "code": "# Python 3 Program to find the# the biggest rectangle# which can be inscribed# within the semicircle # Function to find the area# of the biggest rectangledef rectanglearea(r) : # the radius cannot # be negative if r < 0 : return -1 # area of the rectangle a = r * r return a # Driver Codeif __name__ == \"__main__\" : r = 5 # function calling print(rectanglearea(r)) # This code is contributed# by ANKITRAI1", "e": 29071, "s": 28626, "text": null }, { "code": "// C# Program to find the// the biggest rectangle// which can be inscribed// within the semicircleusing System; class GFG{ // Function to find the area// of the biggest rectanglestatic float rectanglearea(float r){ // the radius cannot be negativeif (r < 0) return -1; // area of the rectanglefloat a = r * r; return a;} // Driver codepublic static void Main(){ float r = 5; Console.Write((int)rectanglearea(r));}} // This code is contributed// by ChitraNayal", "e": 29540, "s": 29071, "text": null }, { "code": "<?php// PHP Program to find the// the biggest rectangle// which can be inscribed// within the semicircle // Function to find the area// of the biggest rectanglefunction rectanglearea($r){ // the radius cannot // be negative if ($r < 0) return -1; // area of the rectangle $a = $r * $r; return $a;} // Driver code$r = 5;echo rectanglearea($r).\"\\n\"; // This code is contributed// by ChitraNayal?>", "e": 29963, "s": 29540, "text": null }, { "code": "<script> // javascript Program to find the// the biggest rectangle// which can be inscribed// within the semicircle // Function to find the area// of the biggest rectanglefunction rectanglearea(r){ // the radius cannot be negative if (r < 0) return -1; // area of the rectangle var a = r * r; return a;} // Driver code var r = 5;document.write(parseInt(rectanglearea(r))); // This code is contributed by Amit Katiyar </script>", "e": 30423, "s": 29963, "text": null }, { "code": null, "e": 30434, "s": 30423, "text": "OUTPUT : " }, { "code": null, "e": 30437, "s": 30434, "text": "25" }, { "code": null, "e": 30447, "s": 30439, "text": "ankthon" }, { "code": null, "e": 30453, "s": 30447, "text": "ukasp" }, { "code": null, "e": 30468, "s": 30453, "text": "amit143katiyar" }, { "code": null, "e": 30475, "s": 30468, "text": "circle" }, { "code": null, "e": 30492, "s": 30475, "text": "square-rectangle" }, { "code": null, "e": 30502, "s": 30492, "text": "Geometric" }, { "code": null, "e": 30521, "s": 30502, "text": "School Programming" }, { "code": null, "e": 30531, "s": 30521, "text": "Geometric" }, { "code": null, "e": 30629, "s": 30531, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30663, "s": 30629, "text": "Convex Hull | Set 2 (Graham Scan)" }, { "code": null, "e": 30721, "s": 30663, "text": "Check whether a given point lies inside a triangle or not" }, { "code": null, "e": 30768, "s": 30721, "text": "Convex Hull using Divide and Conquer Algorithm" }, { "code": null, "e": 30821, "s": 30768, "text": "Optimum location of point to minimize total distance" }, { "code": null, "e": 30856, "s": 30821, "text": "Program to find area of a triangle" }, { "code": null, "e": 30874, "s": 30856, "text": "Python Dictionary" }, { "code": null, "e": 30890, "s": 30874, "text": "Arrays in C/C++" }, { "code": null, "e": 30909, "s": 30890, "text": "Inheritance in C++" }, { "code": null, "e": 30934, "s": 30909, "text": "Reverse a string in Java" } ]
Analysis of Algorithms | Set 1 (Asymptotic Analysis) - GeeksforGeeks
09 Nov, 2020 Why performance analysis?There are many important things that should be taken care of, like user friendliness, modularity, security, maintainability, etc. Why to worry about performance?The answer to this is simple, we can have all the above things only if we have performance. So performance is like currency through which we can buy all the above things. Another reason for studying performance is – speed is fun!To summarize, performance == scale. Imagine a text editor that can load 1000 pages, but can spell check 1 page per minute OR an image editor that takes 1 hour to rotate your image 90 degrees left OR ... you get it. If a software feature can not cope with the scale of tasks users need to perform – it is as good as dead. Given two algorithms for a task, how do we find out which one is better?One naive way of doing this is – implement both the algorithms and run the two programs on your computer for different inputs and see which one takes less time. There are many problems with this approach for analysis of algorithms.1) It might be possible that for some inputs, first algorithm performs better than the second. And for some inputs second performs better.2) It might also be possible that for some inputs, first algorithm perform better on one machine and the second works better on other machine for some other inputs. Asymptotic Analysis is the big idea that handles above issues in analyzing algorithms. In Asymptotic Analysis, we evaluate the performance of an algorithm in terms of input size (we don’t measure the actual running time). We calculate, how the time (or space) taken by an algorithm increases with the input size.For example, let us consider the search problem (searching a given item) in a sorted array. One way to search is Linear Search (order of growth is linear) and the other way is Binary Search (order of growth is logarithmic). To understand how Asymptotic Analysis solves the above mentioned problems in analyzing algorithms, let us say we run the Linear Search on a fast computer A and Binary Search on a slow computer B and we pick the constant values for the two computers so that it tells us exactly how long it takes for the given machine to perform the search in seconds. Let’s say the constant for A is 0.2 and the constant for B is 1000 which means that A is 5000 times more powerful than B. For small values of input array size n, the fast computer may take less time. But, after a certain value of input array size, the Binary Search will definitely start taking less time compared to the Linear Search even though the Binary Search is being run on a slow machine. The reason is the order of growth of Binary Search with respect to input size is logarithmic while the order of growth of Linear Search is linear. So the machine dependent constants can always be ignored after a certain value of input size.Here are some running times for this example:Linear Search running time in seconds on A: 0.2 * nBinary Search running time in seconds on B: 1000*log(n) ------------------------------------------------ |n | Running time on A | Running time on B | ------------------------------------------------- |10 | 2 sec | ~ 1 h | ------------------------------------------------- |100 | 20 sec | ~ 1.8 h | ------------------------------------------------- |10^6 | ~ 55.5 h | ~ 5.5 h | ------------------------------------------------- |10^9 | ~ 6.3 years | ~ 8.3 h | ------------------------------------------------- Does Asymptotic Analysis always work?Asymptotic Analysis is not perfect, but that’s the best way available for analyzing algorithms. For example, say there are two sorting algorithms that take 1000nLogn and 2nLogn time respectively on a machine. Both of these algorithms are asymptotically same (order of growth is nLogn). So, With Asymptotic Analysis, we can’t judge which one is better as we ignore constants in Asymptotic Analysis.Also, in Asymptotic analysis, we always talk about input sizes larger than a constant value. It might be possible that those large inputs are never given to your software and an algorithm which is asymptotically slower, always performs better for your particular situation. So, you may end up choosing an algorithm that is Asymptotically slower but faster for your software.YouTubeGeeksforGeeks500K subscribersAsymptotic Analysis (Analysis of Algorithms) | Set 1 | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 3:08•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=QJMtPlYPQTA" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> Next – Analysis of Algorithms | Set 2 (Worst, Average and Best Cases) References:MIT’s Video lecture 1 on Introduction to Algorithms. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Danail Kozhuharov biplab_prasad BenceAment Analysis Articles Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Practice Questions on Time Complexity Analysis Understanding Time Complexity with Simple Examples Time Complexity and Space Complexity Complexity of different operations in Binary tree, Binary Search Tree and AVL tree Time Complexity of building a heap Tree Traversals (Inorder, Preorder and Postorder) SQL | Join (Inner, Left, Right and Full Joins) find command in Linux with examples Mutex vs Semaphore Understanding "extern" keyword in C
[ { "code": null, "e": 34515, "s": 34487, "text": "\n09 Nov, 2020" }, { "code": null, "e": 35251, "s": 34515, "text": "Why performance analysis?There are many important things that should be taken care of, like user friendliness, modularity, security, maintainability, etc. Why to worry about performance?The answer to this is simple, we can have all the above things only if we have performance. So performance is like currency through which we can buy all the above things. Another reason for studying performance is – speed is fun!To summarize, performance == scale. Imagine a text editor that can load 1000 pages, but can spell check 1 page per minute OR an image editor that takes 1 hour to rotate your image 90 degrees left OR ... you get it. If a software feature can not cope with the scale of tasks users need to perform – it is as good as dead." }, { "code": null, "e": 35857, "s": 35251, "text": "Given two algorithms for a task, how do we find out which one is better?One naive way of doing this is – implement both the algorithms and run the two programs on your computer for different inputs and see which one takes less time. There are many problems with this approach for analysis of algorithms.1) It might be possible that for some inputs, first algorithm performs better than the second. And for some inputs second performs better.2) It might also be possible that for some inputs, first algorithm perform better on one machine and the second works better on other machine for some other inputs." }, { "code": null, "e": 37533, "s": 35857, "text": "Asymptotic Analysis is the big idea that handles above issues in analyzing algorithms. In Asymptotic Analysis, we evaluate the performance of an algorithm in terms of input size (we don’t measure the actual running time). We calculate, how the time (or space) taken by an algorithm increases with the input size.For example, let us consider the search problem (searching a given item) in a sorted array. One way to search is Linear Search (order of growth is linear) and the other way is Binary Search (order of growth is logarithmic). To understand how Asymptotic Analysis solves the above mentioned problems in analyzing algorithms, let us say we run the Linear Search on a fast computer A and Binary Search on a slow computer B and we pick the constant values for the two computers so that it tells us exactly how long it takes for the given machine to perform the search in seconds. Let’s say the constant for A is 0.2 and the constant for B is 1000 which means that A is 5000 times more powerful than B. For small values of input array size n, the fast computer may take less time. But, after a certain value of input array size, the Binary Search will definitely start taking less time compared to the Linear Search even though the Binary Search is being run on a slow machine. The reason is the order of growth of Binary Search with respect to input size is logarithmic while the order of growth of Linear Search is linear. So the machine dependent constants can always be ignored after a certain value of input size.Here are some running times for this example:Linear Search running time in seconds on A: 0.2 * nBinary Search running time in seconds on B: 1000*log(n)" }, { "code": null, "e": 38083, "s": 37533, "text": "------------------------------------------------\n|n | Running time on A | Running time on B |\n-------------------------------------------------\n|10 | 2 sec | ~ 1 h |\n-------------------------------------------------\n|100 | 20 sec | ~ 1.8 h |\n-------------------------------------------------\n|10^6 | ~ 55.5 h | ~ 5.5 h |\n-------------------------------------------------\n|10^9 | ~ 6.3 years | ~ 8.3 h |\n-------------------------------------------------\n" }, { "code": null, "e": 39742, "s": 38083, "text": "Does Asymptotic Analysis always work?Asymptotic Analysis is not perfect, but that’s the best way available for analyzing algorithms. For example, say there are two sorting algorithms that take 1000nLogn and 2nLogn time respectively on a machine. Both of these algorithms are asymptotically same (order of growth is nLogn). So, With Asymptotic Analysis, we can’t judge which one is better as we ignore constants in Asymptotic Analysis.Also, in Asymptotic analysis, we always talk about input sizes larger than a constant value. It might be possible that those large inputs are never given to your software and an algorithm which is asymptotically slower, always performs better for your particular situation. So, you may end up choosing an algorithm that is Asymptotically slower but faster for your software.YouTubeGeeksforGeeks500K subscribersAsymptotic Analysis (Analysis of Algorithms) | Set 1 | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 3:08•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=QJMtPlYPQTA\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>" }, { "code": null, "e": 39812, "s": 39742, "text": "Next – Analysis of Algorithms | Set 2 (Worst, Average and Best Cases)" }, { "code": null, "e": 39876, "s": 39812, "text": "References:MIT’s Video lecture 1 on Introduction to Algorithms." }, { "code": null, "e": 40001, "s": 39876, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 40019, "s": 40001, "text": "Danail Kozhuharov" }, { "code": null, "e": 40033, "s": 40019, "text": "biplab_prasad" }, { "code": null, "e": 40044, "s": 40033, "text": "BenceAment" }, { "code": null, "e": 40053, "s": 40044, "text": "Analysis" }, { "code": null, "e": 40062, "s": 40053, "text": "Articles" }, { "code": null, "e": 40160, "s": 40062, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 40169, "s": 40160, "text": "Comments" }, { "code": null, "e": 40182, "s": 40169, "text": "Old Comments" }, { "code": null, "e": 40229, "s": 40182, "text": "Practice Questions on Time Complexity Analysis" }, { "code": null, "e": 40280, "s": 40229, "text": "Understanding Time Complexity with Simple Examples" }, { "code": null, "e": 40317, "s": 40280, "text": "Time Complexity and Space Complexity" }, { "code": null, "e": 40400, "s": 40317, "text": "Complexity of different operations in Binary tree, Binary Search Tree and AVL tree" }, { "code": null, "e": 40435, "s": 40400, "text": "Time Complexity of building a heap" }, { "code": null, "e": 40485, "s": 40435, "text": "Tree Traversals (Inorder, Preorder and Postorder)" }, { "code": null, "e": 40532, "s": 40485, "text": "SQL | Join (Inner, Left, Right and Full Joins)" }, { "code": null, "e": 40568, "s": 40532, "text": "find command in Linux with examples" }, { "code": null, "e": 40587, "s": 40568, "text": "Mutex vs Semaphore" } ]
Camel case of a given sentence - GeeksforGeeks
09 May, 2022 Given a sentence, task is to remove spaces from the sentence and rewrite in Camel case. It is a style of writing where we don’t have spaces and all words begin with capital letters.Examples: Input : I got intern at geeksforgeeks Output : IGotInternAtGeeksforgeeks Input : Here comes the garden Output : HereComesTheGarden Simple solution: First method is to traverse sentence and one by one remove spaces by moving subsequent characters one position back and changing case of first character to capital. It takes O(n*n) time.Efficient solution : We traverse given string, while traversing we copy non space character to result and whenever we encounter space, we ignore it and change next letter to capital.Below is code implementation C++ Java Python C# Javascript // CPP program to convert given sentence/// to camel case.#include <bits/stdc++.h>using namespace std; // Function to remove spaces and convert// into camel casestring convert(string s){ int n = s.length(); int res_ind = 0; for (int i = 0; i < n; i++) { // check for spaces in the sentence if (s[i] == ' ') { // conversion into upper case s[i + 1] = toupper(s[i + 1]); continue; } // If not space, copy character else s[res_ind++] = s[i]; } // return string to main return s.substr(0, res_ind);} // Driver programint main(){ string str = "I get intern at geeksforgeeks"; cout << convert(str); return 0;} // Java program to convert given sentence/// to camel case.class GFG{ // Function to remove spaces and convert // into camel case static String convert(String s) { // to count spaces int cnt= 0; int n = s.length(); char ch[] = s.toCharArray(); int res_ind = 0; for (int i = 0; i < n; i++) { // check for spaces in the sentence if (ch[i] == ' ') { cnt++; // conversion into upper case ch[i + 1] = Character.toUpperCase(ch[i + 1]); continue; } // If not space, copy character else ch[res_ind++] = ch[i]; } // new string will be reduced by the // size of spaces in the original string return String.valueOf(ch, 0, n - cnt); } // Driver code public static void main(String args[]) { String str = "I get intern at geeksforgeeks"; System.out.println(convert(str)); }} // This code is contributed by gp6. # Python program to convert# given sentence to camel case. # Function to remove spaces# and convert into camel casedef convert(s): if(len(s) == 0): return s1 = '' s1 += s[0].upper() for i in range(1, len(s)): if (s[i] == ' '): s1 += s[i + 1].upper() i += 1 elif(s[i - 1] != ' '): s1 += s[i] print(s1) # Driver Codedef main(): s = "I get intern at geeksforgeeks" convert(s) if __name__=="__main__": main() # This code is contributed# prabhat kumar singh // C# program to convert given sentence// to camel case.using System; class GFG{ // Function to remove spaces and convert // into camel case static void convert(String s) { // to count spaces int cnt= 0; int n = s.Length; char []ch = s.ToCharArray(); int res_ind = 0; for (int i = 0; i < n; i++) { // check for spaces in the sentence if (ch[i] == ' ') { cnt++; // conversion into upper case ch[i + 1] = char.ToUpper(ch[i + 1]); continue; } // If not space, copy character else ch[res_ind++] = ch[i]; } // new string will be reduced by the // size of spaces in the original string for(int i = 0; i < n - cnt; i++) Console.Write(ch[i]); } // Driver code public static void Main(String []args) { String str = "I get intern at geeksforgeeks"; convert(str); }} // This code is contributed by 29AjayKumar <script> // Function to remove spaces and convert// into camel casefunction convert( s){ var n = s.length; var str=""; for (var i = 0; i < n; i++) { // check for spaces in the sentence if (s[i] == ' ') { // conversion into upper case str+= s[i+1].toUpperCase(); i++; } // If not space, copy character else{ str+= s[i]; } } // return string to main return str;} var str = "I get intern at geeksforgeeks"; document.write(convert(str)); </script> IGetInternAtGeeksforgeeks YouTubeGeeksforGeeks507K subscribersCamel case of a given sentence | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 3:20•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=okegGKuR5RI" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> This article is contributed by Himanshu Ranjan. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. prabhat kumar singh gp6 29AjayKumar sgrpwr akshitsaxenaa09 simmytarika5 Strings Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Array of Strings in C++ (5 Different Ways to Create) Convert string to char array in C++ Caesar Cipher in Cryptography Check whether two strings are anagram of each other Top 50 String Coding Problems for Interviews Length of the longest substring without repeating characters Reverse words in a given string Remove duplicates from a given string How to split a string in C/C++, Python and Java? Reverse string in Python (5 different ways)
[ { "code": null, "e": 25953, "s": 25925, "text": "\n09 May, 2022" }, { "code": null, "e": 26146, "s": 25953, "text": "Given a sentence, task is to remove spaces from the sentence and rewrite in Camel case. It is a style of writing where we don’t have spaces and all words begin with capital letters.Examples: " }, { "code": null, "e": 26280, "s": 26146, "text": "Input : I got intern at geeksforgeeks\nOutput : IGotInternAtGeeksforgeeks\n\nInput : Here comes the garden\nOutput : HereComesTheGarden" }, { "code": null, "e": 26696, "s": 26280, "text": "Simple solution: First method is to traverse sentence and one by one remove spaces by moving subsequent characters one position back and changing case of first character to capital. It takes O(n*n) time.Efficient solution : We traverse given string, while traversing we copy non space character to result and whenever we encounter space, we ignore it and change next letter to capital.Below is code implementation " }, { "code": null, "e": 26700, "s": 26696, "text": "C++" }, { "code": null, "e": 26705, "s": 26700, "text": "Java" }, { "code": null, "e": 26712, "s": 26705, "text": "Python" }, { "code": null, "e": 26715, "s": 26712, "text": "C#" }, { "code": null, "e": 26726, "s": 26715, "text": "Javascript" }, { "code": "// CPP program to convert given sentence/// to camel case.#include <bits/stdc++.h>using namespace std; // Function to remove spaces and convert// into camel casestring convert(string s){ int n = s.length(); int res_ind = 0; for (int i = 0; i < n; i++) { // check for spaces in the sentence if (s[i] == ' ') { // conversion into upper case s[i + 1] = toupper(s[i + 1]); continue; } // If not space, copy character else s[res_ind++] = s[i]; } // return string to main return s.substr(0, res_ind);} // Driver programint main(){ string str = \"I get intern at geeksforgeeks\"; cout << convert(str); return 0;}", "e": 27450, "s": 26726, "text": null }, { "code": "// Java program to convert given sentence/// to camel case.class GFG{ // Function to remove spaces and convert // into camel case static String convert(String s) { // to count spaces int cnt= 0; int n = s.length(); char ch[] = s.toCharArray(); int res_ind = 0; for (int i = 0; i < n; i++) { // check for spaces in the sentence if (ch[i] == ' ') { cnt++; // conversion into upper case ch[i + 1] = Character.toUpperCase(ch[i + 1]); continue; } // If not space, copy character else ch[res_ind++] = ch[i]; } // new string will be reduced by the // size of spaces in the original string return String.valueOf(ch, 0, n - cnt); } // Driver code public static void main(String args[]) { String str = \"I get intern at geeksforgeeks\"; System.out.println(convert(str)); }} // This code is contributed by gp6.", "e": 28514, "s": 27450, "text": null }, { "code": "# Python program to convert# given sentence to camel case. # Function to remove spaces# and convert into camel casedef convert(s): if(len(s) == 0): return s1 = '' s1 += s[0].upper() for i in range(1, len(s)): if (s[i] == ' '): s1 += s[i + 1].upper() i += 1 elif(s[i - 1] != ' '): s1 += s[i] print(s1) # Driver Codedef main(): s = \"I get intern at geeksforgeeks\" convert(s) if __name__==\"__main__\": main() # This code is contributed# prabhat kumar singh ", "e": 29074, "s": 28514, "text": null }, { "code": "// C# program to convert given sentence// to camel case.using System; class GFG{ // Function to remove spaces and convert // into camel case static void convert(String s) { // to count spaces int cnt= 0; int n = s.Length; char []ch = s.ToCharArray(); int res_ind = 0; for (int i = 0; i < n; i++) { // check for spaces in the sentence if (ch[i] == ' ') { cnt++; // conversion into upper case ch[i + 1] = char.ToUpper(ch[i + 1]); continue; } // If not space, copy character else ch[res_ind++] = ch[i]; } // new string will be reduced by the // size of spaces in the original string for(int i = 0; i < n - cnt; i++) Console.Write(ch[i]); } // Driver code public static void Main(String []args) { String str = \"I get intern at geeksforgeeks\"; convert(str); }} // This code is contributed by 29AjayKumar", "e": 30171, "s": 29074, "text": null }, { "code": "<script> // Function to remove spaces and convert// into camel casefunction convert( s){ var n = s.length; var str=\"\"; for (var i = 0; i < n; i++) { // check for spaces in the sentence if (s[i] == ' ') { // conversion into upper case str+= s[i+1].toUpperCase(); i++; } // If not space, copy character else{ str+= s[i]; } } // return string to main return str;} var str = \"I get intern at geeksforgeeks\"; document.write(convert(str)); </script>", "e": 30763, "s": 30171, "text": null }, { "code": null, "e": 30789, "s": 30763, "text": "IGetInternAtGeeksforgeeks" }, { "code": null, "e": 31620, "s": 30791, "text": "YouTubeGeeksforGeeks507K subscribersCamel case of a given sentence | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 3:20•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=okegGKuR5RI\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>" }, { "code": null, "e": 32044, "s": 31620, "text": "This article is contributed by Himanshu Ranjan. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 32064, "s": 32044, "text": "prabhat kumar singh" }, { "code": null, "e": 32068, "s": 32064, "text": "gp6" }, { "code": null, "e": 32080, "s": 32068, "text": "29AjayKumar" }, { "code": null, "e": 32087, "s": 32080, "text": "sgrpwr" }, { "code": null, "e": 32103, "s": 32087, "text": "akshitsaxenaa09" }, { "code": null, "e": 32116, "s": 32103, "text": "simmytarika5" }, { "code": null, "e": 32124, "s": 32116, "text": "Strings" }, { "code": null, "e": 32132, "s": 32124, "text": "Strings" }, { "code": null, "e": 32230, "s": 32132, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32283, "s": 32230, "text": "Array of Strings in C++ (5 Different Ways to Create)" }, { "code": null, "e": 32319, "s": 32283, "text": "Convert string to char array in C++" }, { "code": null, "e": 32349, "s": 32319, "text": "Caesar Cipher in Cryptography" }, { "code": null, "e": 32401, "s": 32349, "text": "Check whether two strings are anagram of each other" }, { "code": null, "e": 32446, "s": 32401, "text": "Top 50 String Coding Problems for Interviews" }, { "code": null, "e": 32507, "s": 32446, "text": "Length of the longest substring without repeating characters" }, { "code": null, "e": 32539, "s": 32507, "text": "Reverse words in a given string" }, { "code": null, "e": 32577, "s": 32539, "text": "Remove duplicates from a given string" }, { "code": null, "e": 32626, "s": 32577, "text": "How to split a string in C/C++, Python and Java?" } ]
How to fix java.lang.ClassCastException while using the TreeMap in Java? - GeeksforGeeks
01 Oct, 2021 The java.lang.ClassCastException is one of the unchecked exception in Java. It can occur in our program when we tried to convert an object of one class type into an object of another class type. When we use custom class objects as keys in the TreeMap and neither implements the comparable interface nor comparator interface, then the java.lang.ClassCastException arises. So there are two ways to fix java.lang.ClassCastException while using the TreeMap in Java: Using Comparable Using Comparator Method 1: Using Comparable We can fix java.lang.ClassCastException by the objects used as keys of the TreeMap implement the Comparable interface. Pseudo Code: // Custom class Student implements comparable interface class Student implements Comparable<Student> { String name; Integer marks; public Student(String name, Integer marks) { this.name = name; this.marks = marks; } // Override toString method public String toString() { return this.name + " : " + this.marks; } public int getMarks() { return this.marks; } // Override compareTo method that sort treemap in the ascending order of the marks public int compareTo(Student stu) { return this.getMarks() - stu.getMarks(); } } Implementation: Java // Java program to demonstrate how to fix// java.lang.ClassCastException while using the TreeMap import java.util.*; // Custom class Student implements comparable interfaceclass Student implements Comparable<Student> { String name; Integer marks; public Student(String name, Integer marks) { this.name = name; this.marks = marks; } // Override toString method public String toString() { return this.name + " : " + this.marks; } public int getMarks() { return this.marks; } // Override compareTo method that sort treemap in the // ascending order of the marks public int compareTo(Student stu) { return this.getMarks() - stu.getMarks(); }} public class GFG { public static void main(String[] args) { // New TreeMap TreeMap<Student, Integer> map = new TreeMap<>(); map.put(new Student("Akshay", 500), 1); map.put(new Student("Bhanu", 600), 2); map.put(new Student("Chetan", 300), 3); System.out.println("The Treemap : " + map); }} The Treemap : {Chetan : 300=3, Akshay : 500=1, Bhanu : 600=2} Method 2: Using Comparator We can fix java.lang.ClassCastException by provide a custom comparator to the constructor at the creation time of the TreeMap. Pseudo Code: // Custom comparator class MyComparator implements Comparator<Student> { // Compare method that sort TreeMap in the ascending order of the marks public int compare(Student stu1, Student stu2) { return stu1.getMarks() - stu2.getMarks(); } } Implementation: Java // Java program to demonstrate how to fix// java.lang.ClassCastException while using the TreeMap import java.util.*; // Custom class Student implements comparable interfaceclass Student { String name; Integer marks; public Student(String name, Integer marks) { this.name = name; this.marks = marks; } // Override toString method public String toString() { return this.name + " : " + this.marks; } public int getMarks() { return this.marks; }} // Custom comparatorclass MyComparator implements Comparator<Student> { // Compare method that sort TreeMap in the ascending // order of the marks public int compare(Student stu1, Student stu2) { return stu1.getMarks() - stu2.getMarks(); }} public class GFG { public static void main(String[] args) { // New TreeMap TreeMap<Student, Integer> map = new TreeMap<>(new MyComparator()); map.put(new Student("Akshay", 500), 1); map.put(new Student("Bhanu", 600), 2); map.put(new Student("Chetan", 300), 3); System.out.println("The Treemap : " + map); }} The Treemap : {Chetan : 300=3, Akshay : 500=1, Bhanu : 600=2} anikakapoor Java-Exceptions java-TreeMap Picked Java Java Programs 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 Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class How to Iterate HashMap in Java? Iterate through List in Java
[ { "code": null, "e": 25347, "s": 25319, "text": "\n01 Oct, 2021" }, { "code": null, "e": 25542, "s": 25347, "text": "The java.lang.ClassCastException is one of the unchecked exception in Java. It can occur in our program when we tried to convert an object of one class type into an object of another class type." }, { "code": null, "e": 25718, "s": 25542, "text": "When we use custom class objects as keys in the TreeMap and neither implements the comparable interface nor comparator interface, then the java.lang.ClassCastException arises." }, { "code": null, "e": 25809, "s": 25718, "text": "So there are two ways to fix java.lang.ClassCastException while using the TreeMap in Java:" }, { "code": null, "e": 25826, "s": 25809, "text": "Using Comparable" }, { "code": null, "e": 25843, "s": 25826, "text": "Using Comparator" }, { "code": null, "e": 25870, "s": 25843, "text": "Method 1: Using Comparable" }, { "code": null, "e": 25989, "s": 25870, "text": "We can fix java.lang.ClassCastException by the objects used as keys of the TreeMap implement the Comparable interface." }, { "code": null, "e": 26002, "s": 25989, "text": "Pseudo Code:" }, { "code": null, "e": 26573, "s": 26002, "text": "// Custom class Student implements comparable interface\n\nclass Student implements Comparable<Student> {\n\n String name;\n Integer marks;\n\n public Student(String name, Integer marks) {\n this.name = name;\n this.marks = marks;\n }\n\n // Override toString method\n public String toString() {\n return this.name + \" : \" + this.marks;\n }\n\n public int getMarks() {\n return this.marks;\n }\n\n // Override compareTo method that sort treemap in the ascending order of the marks\n public int compareTo(Student stu) {\n return this.getMarks() - stu.getMarks();\n }\n}" }, { "code": null, "e": 26589, "s": 26573, "text": "Implementation:" }, { "code": null, "e": 26594, "s": 26589, "text": "Java" }, { "code": "// Java program to demonstrate how to fix// java.lang.ClassCastException while using the TreeMap import java.util.*; // Custom class Student implements comparable interfaceclass Student implements Comparable<Student> { String name; Integer marks; public Student(String name, Integer marks) { this.name = name; this.marks = marks; } // Override toString method public String toString() { return this.name + \" : \" + this.marks; } public int getMarks() { return this.marks; } // Override compareTo method that sort treemap in the // ascending order of the marks public int compareTo(Student stu) { return this.getMarks() - stu.getMarks(); }} public class GFG { public static void main(String[] args) { // New TreeMap TreeMap<Student, Integer> map = new TreeMap<>(); map.put(new Student(\"Akshay\", 500), 1); map.put(new Student(\"Bhanu\", 600), 2); map.put(new Student(\"Chetan\", 300), 3); System.out.println(\"The Treemap : \" + map); }}", "e": 27655, "s": 26594, "text": null }, { "code": null, "e": 27717, "s": 27655, "text": "The Treemap : {Chetan : 300=3, Akshay : 500=1, Bhanu : 600=2}" }, { "code": null, "e": 27744, "s": 27717, "text": "Method 2: Using Comparator" }, { "code": null, "e": 27871, "s": 27744, "text": "We can fix java.lang.ClassCastException by provide a custom comparator to the constructor at the creation time of the TreeMap." }, { "code": null, "e": 27885, "s": 27871, "text": "Pseudo Code: " }, { "code": null, "e": 28136, "s": 27885, "text": "// Custom comparator\n\nclass MyComparator implements Comparator<Student> {\n // Compare method that sort TreeMap in the ascending order of the marks\n public int compare(Student stu1, Student stu2) {\n return stu1.getMarks() - stu2.getMarks();\n }\n}" }, { "code": null, "e": 28153, "s": 28136, "text": "Implementation: " }, { "code": null, "e": 28158, "s": 28153, "text": "Java" }, { "code": "// Java program to demonstrate how to fix// java.lang.ClassCastException while using the TreeMap import java.util.*; // Custom class Student implements comparable interfaceclass Student { String name; Integer marks; public Student(String name, Integer marks) { this.name = name; this.marks = marks; } // Override toString method public String toString() { return this.name + \" : \" + this.marks; } public int getMarks() { return this.marks; }} // Custom comparatorclass MyComparator implements Comparator<Student> { // Compare method that sort TreeMap in the ascending // order of the marks public int compare(Student stu1, Student stu2) { return stu1.getMarks() - stu2.getMarks(); }} public class GFG { public static void main(String[] args) { // New TreeMap TreeMap<Student, Integer> map = new TreeMap<>(new MyComparator()); map.put(new Student(\"Akshay\", 500), 1); map.put(new Student(\"Bhanu\", 600), 2); map.put(new Student(\"Chetan\", 300), 3); System.out.println(\"The Treemap : \" + map); }}", "e": 29295, "s": 28158, "text": null }, { "code": null, "e": 29357, "s": 29295, "text": "The Treemap : {Chetan : 300=3, Akshay : 500=1, Bhanu : 600=2}" }, { "code": null, "e": 29371, "s": 29359, "text": "anikakapoor" }, { "code": null, "e": 29387, "s": 29371, "text": "Java-Exceptions" }, { "code": null, "e": 29400, "s": 29387, "text": "java-TreeMap" }, { "code": null, "e": 29407, "s": 29400, "text": "Picked" }, { "code": null, "e": 29412, "s": 29407, "text": "Java" }, { "code": null, "e": 29426, "s": 29412, "text": "Java Programs" }, { "code": null, "e": 29431, "s": 29426, "text": "Java" }, { "code": null, "e": 29529, "s": 29431, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29544, "s": 29529, "text": "Stream In Java" }, { "code": null, "e": 29565, "s": 29544, "text": "Constructors in Java" }, { "code": null, "e": 29584, "s": 29565, "text": "Exceptions in Java" }, { "code": null, "e": 29614, "s": 29584, "text": "Functional Interfaces in Java" }, { "code": null, "e": 29660, "s": 29614, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 29686, "s": 29660, "text": "Java Programming Examples" }, { "code": null, "e": 29720, "s": 29686, "text": "Convert Double to Integer in Java" }, { "code": null, "e": 29767, "s": 29720, "text": "Implementing a Linked List in Java using Class" }, { "code": null, "e": 29799, "s": 29767, "text": "How to Iterate HashMap in Java?" } ]
C Program For Swapping Nodes In A Linked List Without Swapping Data - GeeksforGeeks
30 Mar, 2022 Given a linked list and two keys in it, swap nodes for two given keys. Nodes should be swapped by changing links. Swapping data of nodes may be expensive in many situations when data contains many fields. It may be assumed that all keys in the linked list are distinct. Examples: Input : 10->15->12->13->20->14, x = 12, y = 20 Output: 10->15->20->13->12->14 Input : 10->15->12->13->20->14, x = 10, y = 20 Output: 20->15->12->13->10->14 Input : 10->15->12->13->20->14, x = 12, y = 13 Output: 10->15->13->12->20->14 This may look a simple problem, but is an interesting question as it has the following cases to be handled. x and y may or may not be adjacent.Either x or y may be a head node.Either x or y may be the last node.x and/or y may not be present in the linked list. x and y may or may not be adjacent. Either x or y may be a head node. Either x or y may be the last node. x and/or y may not be present in the linked list. How to write a clean working code that handles all the above possibilities. The idea is to first search x and y in the given linked list. If any of them is not present, then return. While searching for x and y, keep track of current and previous pointers. First change next of previous pointers, then change next of current pointers. Below is the implementation of the above approach. C // C program to swap the nodes of linked list// rather than swapping the field from the nodes.#include <stdio.h>#include <stdlib.h> // A linked list nodestruct Node{ int data; struct Node* next;}; /* Function to swap nodes x and y in linked list by changing links */void swapNodes(struct Node** head_ref, int x, int y){ // Nothing to do if x and y are same if (x == y) return; // Search for x (keep track of prevX and CurrX struct Node *prevX = NULL, *currX = *head_ref; while (currX && currX->data != x) { prevX = currX; currX = currX->next; } // Search for y (keep track of prevY and CurrY struct Node *prevY = NULL, *currY = *head_ref; while (currY && currY->data != y) { prevY = currY; currY = currY->next; } // If either x or y is not present, // nothing to do if (currX == NULL || currY == NULL) return; // If x is not head of linked list if (prevX != NULL) prevX->next = currY; else // Else make y as new head *head_ref = currY; // If y is not head of linked list if (prevY != NULL) prevY->next = currX; else // Else make x as new head *head_ref = currX; // Swap next pointers struct Node* temp = currY->next; currY->next = currX->next; currX->next = temp;} // Function to add a node at the// beginning of Listvoid push(struct Node** head_ref, int new_data){ // Allocate node struct Node* new_node = (struct Node*)malloc(sizeof(struct Node)); // Put in the data new_node->data = new_data; // Link the old list off the new node new_node->next = (*head_ref); // Move the head to point to the new node (*head_ref) = new_node;} // Function to print nodes in a given// linked listvoid printList(struct Node* node){ while (node != NULL) { printf("%d ", node->data); node = node->next; }} // Driver codeint main(){ struct Node* start = NULL; // The constructed linked list is: // 1->2->3->4->5->6->7 push(&start, 7); push(&start, 6); push(&start, 5); push(&start, 4); push(&start, 3); push(&start, 2); push(&start, 1); printf("Linked list before calling swapNodes() "); printList(start); swapNodes(&start, 4, 3); printf("Linked list after calling swapNodes() "); printList(start); return 0;} Output: Linked list before calling swapNodes() 1 2 3 4 5 6 7 Linked list after calling swapNodes() 1 2 4 3 5 6 7 Time Complexity: O(n) Auxiliary Space: O(1) Please refer complete article on Swap nodes in a linked list without swapping data for more details! rohan07 Linked Lists C Language C Programs Linked List Linked List Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. TCP Server-Client implementation in C Exception Handling in C++ Multithreading in C 'this' pointer in C++ Arrow operator -> in C/C++ with Examples Strings in C Arrow operator -> in C/C++ with Examples C Program to read contents of Whole File Header files in C/C++ and its uses Basics of File Handling in C
[ { "code": null, "e": 25531, "s": 25503, "text": "\n30 Mar, 2022" }, { "code": null, "e": 25736, "s": 25531, "text": "Given a linked list and two keys in it, swap nodes for two given keys. Nodes should be swapped by changing links. Swapping data of nodes may be expensive in many situations when data contains many fields." }, { "code": null, "e": 25801, "s": 25736, "text": "It may be assumed that all keys in the linked list are distinct." }, { "code": null, "e": 25812, "s": 25801, "text": "Examples: " }, { "code": null, "e": 26051, "s": 25812, "text": "Input : 10->15->12->13->20->14, x = 12, y = 20\nOutput: 10->15->20->13->12->14\n\nInput : 10->15->12->13->20->14, x = 10, y = 20\nOutput: 20->15->12->13->10->14\n\nInput : 10->15->12->13->20->14, x = 12, y = 13\nOutput: 10->15->13->12->20->14" }, { "code": null, "e": 26160, "s": 26051, "text": "This may look a simple problem, but is an interesting question as it has the following cases to be handled. " }, { "code": null, "e": 26313, "s": 26160, "text": "x and y may or may not be adjacent.Either x or y may be a head node.Either x or y may be the last node.x and/or y may not be present in the linked list." }, { "code": null, "e": 26349, "s": 26313, "text": "x and y may or may not be adjacent." }, { "code": null, "e": 26383, "s": 26349, "text": "Either x or y may be a head node." }, { "code": null, "e": 26419, "s": 26383, "text": "Either x or y may be the last node." }, { "code": null, "e": 26469, "s": 26419, "text": "x and/or y may not be present in the linked list." }, { "code": null, "e": 26545, "s": 26469, "text": "How to write a clean working code that handles all the above possibilities." }, { "code": null, "e": 26804, "s": 26545, "text": "The idea is to first search x and y in the given linked list. If any of them is not present, then return. While searching for x and y, keep track of current and previous pointers. First change next of previous pointers, then change next of current pointers. " }, { "code": null, "e": 26856, "s": 26804, "text": "Below is the implementation of the above approach. " }, { "code": null, "e": 26858, "s": 26856, "text": "C" }, { "code": "// C program to swap the nodes of linked list// rather than swapping the field from the nodes.#include <stdio.h>#include <stdlib.h> // A linked list nodestruct Node{ int data; struct Node* next;}; /* Function to swap nodes x and y in linked list by changing links */void swapNodes(struct Node** head_ref, int x, int y){ // Nothing to do if x and y are same if (x == y) return; // Search for x (keep track of prevX and CurrX struct Node *prevX = NULL, *currX = *head_ref; while (currX && currX->data != x) { prevX = currX; currX = currX->next; } // Search for y (keep track of prevY and CurrY struct Node *prevY = NULL, *currY = *head_ref; while (currY && currY->data != y) { prevY = currY; currY = currY->next; } // If either x or y is not present, // nothing to do if (currX == NULL || currY == NULL) return; // If x is not head of linked list if (prevX != NULL) prevX->next = currY; else // Else make y as new head *head_ref = currY; // If y is not head of linked list if (prevY != NULL) prevY->next = currX; else // Else make x as new head *head_ref = currX; // Swap next pointers struct Node* temp = currY->next; currY->next = currX->next; currX->next = temp;} // Function to add a node at the// beginning of Listvoid push(struct Node** head_ref, int new_data){ // Allocate node struct Node* new_node = (struct Node*)malloc(sizeof(struct Node)); // Put in the data new_node->data = new_data; // Link the old list off the new node new_node->next = (*head_ref); // Move the head to point to the new node (*head_ref) = new_node;} // Function to print nodes in a given// linked listvoid printList(struct Node* node){ while (node != NULL) { printf(\"%d \", node->data); node = node->next; }} // Driver codeint main(){ struct Node* start = NULL; // The constructed linked list is: // 1->2->3->4->5->6->7 push(&start, 7); push(&start, 6); push(&start, 5); push(&start, 4); push(&start, 3); push(&start, 2); push(&start, 1); printf(\"Linked list before calling swapNodes() \"); printList(start); swapNodes(&start, 4, 3); printf(\"Linked list after calling swapNodes() \"); printList(start); return 0;}", "e": 29267, "s": 26858, "text": null }, { "code": null, "e": 29275, "s": 29267, "text": "Output:" }, { "code": null, "e": 29382, "s": 29275, "text": "Linked list before calling swapNodes() 1 2 3 4 5 6 7 \nLinked list after calling swapNodes() 1 2 4 3 5 6 7 " }, { "code": null, "e": 29404, "s": 29382, "text": "Time Complexity: O(n)" }, { "code": null, "e": 29426, "s": 29404, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 29527, "s": 29426, "text": "Please refer complete article on Swap nodes in a linked list without swapping data for more details!" }, { "code": null, "e": 29535, "s": 29527, "text": "rohan07" }, { "code": null, "e": 29548, "s": 29535, "text": "Linked Lists" }, { "code": null, "e": 29559, "s": 29548, "text": "C Language" }, { "code": null, "e": 29570, "s": 29559, "text": "C Programs" }, { "code": null, "e": 29582, "s": 29570, "text": "Linked List" }, { "code": null, "e": 29594, "s": 29582, "text": "Linked List" }, { "code": null, "e": 29692, "s": 29594, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29730, "s": 29692, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 29756, "s": 29730, "text": "Exception Handling in C++" }, { "code": null, "e": 29776, "s": 29756, "text": "Multithreading in C" }, { "code": null, "e": 29798, "s": 29776, "text": "'this' pointer in C++" }, { "code": null, "e": 29839, "s": 29798, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 29852, "s": 29839, "text": "Strings in C" }, { "code": null, "e": 29893, "s": 29852, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 29934, "s": 29893, "text": "C Program to read contents of Whole File" }, { "code": null, "e": 29969, "s": 29934, "text": "Header files in C/C++ and its uses" } ]
find_elements_by_xpath() driver method - Selenium Python - GeeksforGeeks
14 Apr, 2020 Selenium’s Python Module is built to perform automated testing with Python. Selenium Python bindings provides a simple API to write functional/acceptance tests using Selenium WebDriver. After you have installed selenium and checked out – Navigating links using get method, you might want to play more with Selenium Python. After one has opened a page using selenium such as geeksforgeeks, one might want to click some buttons automatically or fill a form automatically or any such automated task. This article revolves around how to grab or locate elements in a webpage using locating strategies of Selenium Web Driver. More specifically, find_elements_by_xpath() is discussed in this article. This method returns a list with type of elements specified. XPath is the language used for locating nodes in an XML document. As HTML can be an implementation of XML (XHTML), Selenium users can leverage this powerful language to target elements in their web applications.To grab a single first element, checkout – find_element_by_xpath() driver method – Selenium Python driver.find_elements_by_xpath("xpath") Example –For instance, consider this page source: <html> <body> <form id="loginForm"> <input name="username" type="text" /> <input name="password" type="password" /> <input name="submit" type="submit" value="Login" /> </form> </body><html> Now after you have created a driver, you can grab an element using – login_form = driver.find_elements_by_xpath('//input[@name='username']') Let’s try to practically implement this method and get a element instance for “https://www.geeksforgeeks.org/”. Let’s try to grab search form input using its name “articleTitle”.Create a file called run.py to demonstrate find_elements_by_xpath method – # Python program to demonstrate# selenium # import webdriverfrom selenium import webdriver # create webdriver objectdriver = webdriver.Firefox() # enter keyword to searchkeyword = "geeksforgeeks" # get geeksforgeeks.orgdriver.get("https://www.geeksforgeeks.org/") # get elementselements = driver.find_elements_by_xpath("//div[@name ='articlePath']") # print complete elements listprint(element) Now run using – Python run.py First, it will open firefox window with geeksforgeeks, and then select the element and print it on terminal as show below.Browser Output –Terminal Output – Python-selenium selenium 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": 26045, "s": 26017, "text": "\n14 Apr, 2020" }, { "code": null, "e": 26542, "s": 26045, "text": "Selenium’s Python Module is built to perform automated testing with Python. Selenium Python bindings provides a simple API to write functional/acceptance tests using Selenium WebDriver. After you have installed selenium and checked out – Navigating links using get method, you might want to play more with Selenium Python. After one has opened a page using selenium such as geeksforgeeks, one might want to click some buttons automatically or fill a form automatically or any such automated task." }, { "code": null, "e": 27109, "s": 26542, "text": "This article revolves around how to grab or locate elements in a webpage using locating strategies of Selenium Web Driver. More specifically, find_elements_by_xpath() is discussed in this article. This method returns a list with type of elements specified. XPath is the language used for locating nodes in an XML document. As HTML can be an implementation of XML (XHTML), Selenium users can leverage this powerful language to target elements in their web applications.To grab a single first element, checkout – find_element_by_xpath() driver method – Selenium Python" }, { "code": null, "e": 27149, "s": 27109, "text": "driver.find_elements_by_xpath(\"xpath\")\n" }, { "code": null, "e": 27199, "s": 27149, "text": "Example –For instance, consider this page source:" }, { "code": "<html> <body> <form id=\"loginForm\"> <input name=\"username\" type=\"text\" /> <input name=\"password\" type=\"password\" /> <input name=\"submit\" type=\"submit\" value=\"Login\" /> </form> </body><html>", "e": 27397, "s": 27199, "text": null }, { "code": null, "e": 27466, "s": 27397, "text": "Now after you have created a driver, you can grab an element using –" }, { "code": null, "e": 27539, "s": 27466, "text": "login_form = driver.find_elements_by_xpath('//input[@name='username']')\n" }, { "code": null, "e": 27792, "s": 27539, "text": "Let’s try to practically implement this method and get a element instance for “https://www.geeksforgeeks.org/”. Let’s try to grab search form input using its name “articleTitle”.Create a file called run.py to demonstrate find_elements_by_xpath method –" }, { "code": "# Python program to demonstrate# selenium # import webdriverfrom selenium import webdriver # create webdriver objectdriver = webdriver.Firefox() # enter keyword to searchkeyword = \"geeksforgeeks\" # get geeksforgeeks.orgdriver.get(\"https://www.geeksforgeeks.org/\") # get elementselements = driver.find_elements_by_xpath(\"//div[@name ='articlePath']\") # print complete elements listprint(element)", "e": 28193, "s": 27792, "text": null }, { "code": null, "e": 28209, "s": 28193, "text": "Now run using –" }, { "code": null, "e": 28223, "s": 28209, "text": "Python run.py" }, { "code": null, "e": 28379, "s": 28223, "text": "First, it will open firefox window with geeksforgeeks, and then select the element and print it on terminal as show below.Browser Output –Terminal Output –" }, { "code": null, "e": 28395, "s": 28379, "text": "Python-selenium" }, { "code": null, "e": 28404, "s": 28395, "text": "selenium" }, { "code": null, "e": 28411, "s": 28404, "text": "Python" }, { "code": null, "e": 28509, "s": 28411, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28527, "s": 28509, "text": "Python Dictionary" }, { "code": null, "e": 28562, "s": 28527, "text": "Read a file line by line in Python" }, { "code": null, "e": 28594, "s": 28562, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28616, "s": 28594, "text": "Enumerate() in Python" }, { "code": null, "e": 28658, "s": 28616, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28688, "s": 28658, "text": "Iterate over a list in Python" }, { "code": null, "e": 28714, "s": 28688, "text": "Python String | replace()" }, { "code": null, "e": 28743, "s": 28714, "text": "*args and **kwargs in Python" }, { "code": null, "e": 28787, "s": 28743, "text": "Reading and Writing to text files in Python" } ]
sciPy stats.zmap() function | Python - GeeksforGeeks
20 Feb, 2019 scipy.stats.zmap(scores, compare, axis=0, ddof=0) function computes the relative Z-score of the input data. The scores that are standardized to zero mean and unit variance, where mean and variance are calculated from the comparison array. Its formula: Parameters :scores : [array_like]Input array or object for which Z-score is to calculate.compare : [array_like]Input array or object for which the mean and standard deviation of the normalization are takenaxis : Axis along which the mean is to be computed. By default axis = 0.ddof : Degree of freedom correction for Standard Deviation. Results : Z-score of the input data. Code #1: Working # stats.zmap() method import numpy as npfrom scipy import stats arr1 = [[20, 2, 7, 1, 34], [50, 12, 12, 34, 4]] arr2 = [[50, 12, 12, 34, 4], [12, 11, 10, 34, 21]] print ("\narr1 : ", arr1)print ("\narr2 : ", arr2) print ("\nZ-score : \n", stats.zmap(arr1, arr2)) Output : arr1 : [[20, 2, 7, 1, 34], [50, 12, 12, 34, 4]] arr2 : [[50, 12, 12, 34, 4], [12, 11, 10, 34, 21]] Z-score : [[ -0.57894737 -19. -4. -inf 2.52941176] [ 1. 1. 1. nan -1. ]] Code #2 : Z-score # stats.zmap() method import numpy as npfrom scipy import stats arr1 = [[20, 2, 7, 1, 34], [50, 12, 12, 34, 4]] arr2 = [[50, 12, 12, 34, 4], [12, 11, 10, 34, 21]] print ("\nZ-score : \n", stats.zmap(arr1, arr2, axis = 1)) Output : sem ratio for arr1 : [[-0.14087457 -1.19743386 -0.90394517 -1.2561316 0.68089376] [ 3.5640998 -0.61601725 -0.61601725 1.80405051 -1.49604189]] Python scipy-stats-functions Python-scipy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | Get unique values from a list Python | os.path.join() method Defaultdict in Python Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n20 Feb, 2019" }, { "code": null, "e": 25776, "s": 25537, "text": "scipy.stats.zmap(scores, compare, axis=0, ddof=0) function computes the relative Z-score of the input data. The scores that are standardized to zero mean and unit variance, where mean and variance are calculated from the comparison array." }, { "code": null, "e": 25789, "s": 25776, "text": "Its formula:" }, { "code": null, "e": 26126, "s": 25789, "text": "Parameters :scores : [array_like]Input array or object for which Z-score is to calculate.compare : [array_like]Input array or object for which the mean and standard deviation of the normalization are takenaxis : Axis along which the mean is to be computed. By default axis = 0.ddof : Degree of freedom correction for Standard Deviation." }, { "code": null, "e": 26163, "s": 26126, "text": "Results : Z-score of the input data." }, { "code": null, "e": 26180, "s": 26163, "text": "Code #1: Working" }, { "code": "# stats.zmap() method import numpy as npfrom scipy import stats arr1 = [[20, 2, 7, 1, 34], [50, 12, 12, 34, 4]] arr2 = [[50, 12, 12, 34, 4], [12, 11, 10, 34, 21]] print (\"\\narr1 : \", arr1)print (\"\\narr2 : \", arr2) print (\"\\nZ-score : \\n\", stats.zmap(arr1, arr2))", "e": 26466, "s": 26180, "text": null }, { "code": null, "e": 26475, "s": 26466, "text": "Output :" }, { "code": null, "e": 26728, "s": 26475, "text": "arr1 : [[20, 2, 7, 1, 34], [50, 12, 12, 34, 4]]\n\narr2 : [[50, 12, 12, 34, 4], [12, 11, 10, 34, 21]]\n\nZ-score : \n [[ -0.57894737 -19. -4. -inf 2.52941176]\n [ 1. 1. 1. nan -1. ]]\n" }, { "code": null, "e": 26747, "s": 26728, "text": " Code #2 : Z-score" }, { "code": "# stats.zmap() method import numpy as npfrom scipy import stats arr1 = [[20, 2, 7, 1, 34], [50, 12, 12, 34, 4]] arr2 = [[50, 12, 12, 34, 4], [12, 11, 10, 34, 21]] print (\"\\nZ-score : \\n\", stats.zmap(arr1, arr2, axis = 1))", "e": 26991, "s": 26747, "text": null }, { "code": null, "e": 27000, "s": 26991, "text": "Output :" }, { "code": null, "e": 27151, "s": 27000, "text": "sem ratio for arr1 : \n [[-0.14087457 -1.19743386 -0.90394517 -1.2561316 0.68089376]\n [ 3.5640998 -0.61601725 -0.61601725 1.80405051 -1.49604189]]\n" }, { "code": null, "e": 27180, "s": 27151, "text": "Python scipy-stats-functions" }, { "code": null, "e": 27193, "s": 27180, "text": "Python-scipy" }, { "code": null, "e": 27200, "s": 27193, "text": "Python" }, { "code": null, "e": 27298, "s": 27200, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27330, "s": 27298, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27372, "s": 27330, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27414, "s": 27372, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27470, "s": 27414, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27497, "s": 27470, "text": "Python Classes and Objects" }, { "code": null, "e": 27536, "s": 27497, "text": "Python | Get unique values from a list" }, { "code": null, "e": 27567, "s": 27536, "text": "Python | os.path.join() method" }, { "code": null, "e": 27589, "s": 27567, "text": "Defaultdict in Python" }, { "code": null, "e": 27618, "s": 27589, "text": "Create a directory in Python" } ]
Java Program to check whether two Strings are an anagram or not.
According to wiki “An anagram is word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.” To compare whether two strings are anagrams check if their lengths are equal? If so, convert these two strings into character arrays then, sort them and compare them using the sort() method of the Arrays class, if both are equal then given two strings are anagrams. Live Demo import java.util.Arrays; public class AnagramSample { public static void main(String args[]) { String str1 = "recitals"; String str2 = "articles"; if (str1.length()==str2.length()) { char[] arr1 = str1.toCharArray(); Arrays.sort(arr1); System.out.println(Arrays.toString(arr1)); char[] arr2 = str2.toCharArray(); Arrays.sort(arr2); System.out.println(Arrays.toString(arr2)); System.out.println(Arrays.equals(arr1, arr2)); if(arr1.equals(arr2)) { System.out.println("Given strings are anagrams"); } else { System.out.println("Given strings are not anagrams"); } } } } [a, c, e, i, l, r, s, t] [a, c, e, i, l, r, s, t] true Given strings are not anagrams
[ { "code": null, "e": 1231, "s": 1062, "text": "According to wiki “An anagram is word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.”" }, { "code": null, "e": 1497, "s": 1231, "text": "To compare whether two strings are anagrams check if their lengths are equal? If so, convert these two strings into character arrays then, sort them and compare them using the sort() method of the Arrays class, if both are equal then given two strings are anagrams." }, { "code": null, "e": 1507, "s": 1497, "text": "Live Demo" }, { "code": null, "e": 2220, "s": 1507, "text": "import java.util.Arrays;\npublic class AnagramSample {\n public static void main(String args[]) {\n String str1 = \"recitals\";\n String str2 = \"articles\";\n\n if (str1.length()==str2.length()) {\n char[] arr1 = str1.toCharArray();\n Arrays.sort(arr1);\n System.out.println(Arrays.toString(arr1));\n char[] arr2 = str2.toCharArray();\n Arrays.sort(arr2);\n System.out.println(Arrays.toString(arr2));\n System.out.println(Arrays.equals(arr1, arr2));\n if(arr1.equals(arr2)) {\n System.out.println(\"Given strings are anagrams\");\n } else {\n System.out.println(\"Given strings are not anagrams\");\n }\n }\n }\n}" }, { "code": null, "e": 2306, "s": 2220, "text": "[a, c, e, i, l, r, s, t]\n[a, c, e, i, l, r, s, t]\ntrue\nGiven strings are not anagrams" } ]
Apache CXF with JAX-RS
Before proceeding ahead into this chapter, we assume that you know how to write a RESTful web service in Java. I will show you how to use CXF on top of this JAX-RS (Java API for RESTful Web Services) . We will create a web service that maintains a list of latest movies. When the user requests a movie, he specifies the movie ID in his request, the server will locate the movie and return it to the client. In our trivial case, we will simply return the movie name to the client and not the actual binary MP4 file. So let us start creating a JAX-RS application. We will declare an XML root element called Movie for storing the id and the name for a given movie. The element is declared in a file called Movie.java. The contents of the file are shown here − //Movie.java package com.tutorialspoint.cxf.jaxrs.movie; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement(name = "Movie") public class Movie { private long id; private String name; public long getId() { return id; } public void setId(long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } } Note the use of XmlRootElement tag to declare the XML element for the Movie tag. Next, we will create a service that holds the list of movies in its database. To store the list of movies we use Java supplied Map that stores the key-value pairs. If the list is large, you will use an external database storage which will also be easier to manage. In our trivial case, we will store only five movies in our database. The code for the MovieService class is given below − //MovieService.java package com.tutorialspoint.cxf.jaxrs.movie; import java.util.HashMap; import java.util.Map; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; @Path("/movieservice/") @Produces("text/xml") public class MovieService { long currentId = 123; Map<Long, Movie> movies = new HashMap<>(); public MovieService() { init(); } @GET @Path("/movie/{id}/") public Movie getMovie(@PathParam("id") String id) { long idNumber = Long.parseLong(id); return movies.get(idNumber); } final void init() { Movie c1 = new Movie(); c1.setName("Aquaman"); c1.setId(1001); movies.put(c1.getId(), c1); Movie c2 = new Movie(); c2.setName("Mission Imposssible"); c2.setId(1002); movies.put(c2.getId(), c2); Movie c3 = new Movie(); c3.setName("Black Panther"); c3.setId(1003); movies.put(c3.getId(), c3); Movie c4 = new Movie(); c4.setName("A Star is Born"); c4.setId(1004); movies.put(c4.getId(), c4); Movie c5 = new Movie(); c5.setName("The Meg"); c5.setId(1005); movies.put(c5.getId(), c5); } } Note that we use the following two annotations to specify the URL path for our movie service and its return type − @Path("/movieservice/") @Produces("text/xml") We use the @GET and @Path annotations to specify the URL for the GET request as follows − @GET @Path("/movie/{id}/") The movie database itself is initialized in the init method, where we add five movie items to the database. Our next task is to write a server application. To create a server, we use CXF supplied JAXRSServerFactoryBean class. JAXRSServerFactoryBean factory = new JAXRSServerFactoryBean(); We set its resource classes by calling the setResourceClasses method. factory.setResourceClasses(Movie.class); factory.setResourceClasses(MovieService.class); We set the service provider by calling the setResourceProvider method. factory.setResourceProvider(MovieService.class, new SingletonResourceProvider(new MovieService())); We set the desired publish address by calling the aetAddress method − factory.setAddress("http://localhost:9000/"); Finally, we publish the server by calling the create method on the factory instance. factory.create(); The entire code for the server application is given below − //Server.java package com.tutorialspoint.cxf.jaxrs.movie; import org.apache.cxf.jaxrs.JAXRSServerFactoryBean; import org.apache.cxf.jaxrs.lifecycle.SingletonResourceProvider; public class Server { public static void main(String[] args) throws Exception { JAXRSServerFactoryBean factory = new JAXRSServerFactoryBean(); factory.setResourceClasses(Movie.class); factory.setResourceClasses(MovieService.class); factory.setResourceProvider(MovieService.class, new SingletonResourceProvider(new MovieService())); factory.setAddress("http://localhost:9000/"); factory.create(); System.out.println("Server ready..."); Thread.sleep(5 * 60 * 1000); System.out.println("Server exiting ..."); System.exit(0); } } Here we have included the final version of pom.xml below − <?xml version = "1.0" encoding = "UTF-8"?> <project xmlns = "http://maven.apache.org/POM/4.0.0" xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation = "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.tutorialspoint</groupId> <artifactId>cxf-jaxrs</artifactId> <version>1.0</version> <packaging>jar</packaging> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> </properties> <profiles> <profile> <id>server</id> <build> <defaultGoal>test</defaultGoal> <plugins> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>exec-maven-plugin</artifactId> <version>1.6.0</version> <executions> <execution> <phase>test</phase> <goals> <goal>java</goal> </goals> <configuration> <mainClass> com.tutorialspoint.cxf.jaxrs.movie.Server </mainClass> </configuration> </execution> </executions> </plugin> </plugins> </build> <dependencies> <dependency> <groupId>org.apache.cxf</groupId> <artifactId>cxf-rt-transports-http-jetty</artifactId> <version>3.3.0</version> </dependency> </dependencies> </profile> <profile> <id>client</id> <build> <defaultGoal>test</defaultGoal> <plugins> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>exec-maven-plugin</artifactId> <executions> <execution> <phase>test</phase> <goals> <goal>java</goal> </goals> <configuration> <mainClass> com.tutorialspoint.cxf.jaxrs.movie.Client </mainClass> </configuration> </execution> </executions> </plugin> </plugins> </build> </profile> </profiles> <dependencies> <dependency> <groupId>org.apache.cxf</groupId> <artifactId>cxf-rt-transports-http</artifactId> <version>3.3.0</version> </dependency> <dependency> <groupId>org.apache.cxf</groupId> <artifactId>cxf-rt-transports-http-jetty</artifactId> <version>3.3.0</version> </dependency> <dependency> <groupId>org.apache.cxf</groupId> <artifactId>cxf-rt-frontend-jaxrs</artifactId> <version>3.3.0</version> </dependency> <dependency> <groupId>jakarta.ws.rs</groupId> <artifactId>jakarta.ws.rs-api</artifactId> <version>2.1.5</version> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.7</version> </dependency> </dependencies> </project> Writing the RS client is trivial. We simply create a URL object and open its stream. We use CXF supplied IOUtils class to copy the contents of input stream to a local stream. URL url = new URL("http://localhost:9000/movieservice/movie/1002"); try (InputStream instream = url.openStream(); CachedOutputStream outstream = new CachedOutputStream()) { IOUtils.copy(instream, outstream); } The entire code for the client application is given below − //Client.java package com.tutorialspoint.cxf.jaxrs.movie; import java.io.InputStream; import java.net.URL; import org.apache.cxf.helpers.IOUtils; import org.apache.cxf.io.CachedOutputStream; public class Client { public static void main(String[] args) throws Exception { URL url = new URL("http://localhost:9000/movieservice/movie/1002"); try (InputStream instream = url.openStream(); CachedOutputStream outstream = new CachedOutputStream()) { IOUtils.copy(instream, outstream); String str = outstream.getOut().toString(); System.out.println(str); } } } Run the server using the following command in the command-line window − mvn -Pserver Now, you will see the following message on the console − INFO: Setting the server's publish address to be http://localhost:9000 Now, open your browser and type the following URL − http://localhost:9000/movieservice/movie/1002 You will see the following in the browser window. You may invoke the service by using a Java client application that we have developed by running the following command in a separate command-line window. mvn -Pclient You will see the following output − <?xml version="1.0" encoding = "UTF-8" standalone="yes"?> <Movie><id>1002</id><name>Mission Imposssible</name></Movie> CXF samples provides several examples on how to use CXF with JAX-RS. The interested readers are encouraged to study these samples. 46 Lectures 3.5 hours Arnab Chakraborty 23 Lectures 1.5 hours Mukund Kumar Mishra 16 Lectures 1 hours Nilay Mehta 52 Lectures 1.5 hours Bigdata Engineer 14 Lectures 1 hours Bigdata Engineer 23 Lectures 1 hours Bigdata Engineer Print Add Notes Bookmark this page
[ { "code": null, "e": 2325, "s": 1763, "text": "Before proceeding ahead into this chapter, we assume that you know how to write a RESTful web service in Java. I will show you how to use CXF on top of this JAX-RS (Java API for RESTful Web Services) . We will create a web service that maintains a list of latest movies. When the user requests a movie, he specifies the movie ID in his request, the server will locate the movie and return it to the client. In our trivial case, we will simply return the movie name to the client and not the actual binary MP4 file. So let us start creating a JAX-RS application." }, { "code": null, "e": 2520, "s": 2325, "text": "We will declare an XML root element called Movie for storing the id and the name for a given movie. The element is declared in a file called Movie.java. The contents of the file are shown here −" }, { "code": null, "e": 2949, "s": 2520, "text": "//Movie.java\npackage com.tutorialspoint.cxf.jaxrs.movie;\nimport javax.xml.bind.annotation.XmlRootElement;\n@XmlRootElement(name = \"Movie\")\npublic class Movie {\n private long id;\n private String name;\n public long getId() {\n return id;\n }\n public void setId(long id) {\n this.id = id;\n }\n public String getName() {\n return name;\n }\n public void setName(String name) {\n this.name = name;\n }\n}" }, { "code": null, "e": 3108, "s": 2949, "text": "Note the use of XmlRootElement tag to declare the XML element for the Movie tag. Next, we will create a service that holds the list of movies in its database." }, { "code": null, "e": 3417, "s": 3108, "text": "To store the list of movies we use Java supplied Map that stores the key-value pairs. If the list is large, you will use an external database storage which will also be easier to manage. In our trivial case, we will store only five movies in our database. The code for the MovieService class is given below −" }, { "code": null, "e": 4656, "s": 3417, "text": "//MovieService.java\npackage com.tutorialspoint.cxf.jaxrs.movie;\nimport java.util.HashMap;\nimport java.util.Map;\nimport javax.ws.rs.GET;\nimport javax.ws.rs.Path;\nimport javax.ws.rs.PathParam;\nimport javax.ws.rs.Produces;\n@Path(\"/movieservice/\")\n@Produces(\"text/xml\")\npublic class MovieService {\n long currentId = 123;\n Map<Long, Movie> movies = new HashMap<>();\n public MovieService() {\n init();\n }\n @GET\n @Path(\"/movie/{id}/\")\n public Movie getMovie(@PathParam(\"id\") String id) {\n long idNumber = Long.parseLong(id);\n return movies.get(idNumber);\n }\n final void init() {\n Movie c1 = new Movie();\n c1.setName(\"Aquaman\");\n c1.setId(1001);\n movies.put(c1.getId(), c1);\n \n Movie c2 = new Movie();\n c2.setName(\"Mission Imposssible\");\n c2.setId(1002);\n movies.put(c2.getId(), c2);\n \n Movie c3 = new Movie();\n c3.setName(\"Black Panther\");\n c3.setId(1003);\n movies.put(c3.getId(), c3);\n \n Movie c4 = new Movie();\n c4.setName(\"A Star is Born\");\n c4.setId(1004);\n movies.put(c4.getId(), c4);\n \n Movie c5 = new Movie();\n c5.setName(\"The Meg\");\n c5.setId(1005);\n movies.put(c5.getId(), c5);\n }\n}" }, { "code": null, "e": 4771, "s": 4656, "text": "Note that we use the following two annotations to specify the URL path for our movie service and its return type −" }, { "code": null, "e": 4818, "s": 4771, "text": "@Path(\"/movieservice/\")\n@Produces(\"text/xml\")\n" }, { "code": null, "e": 4908, "s": 4818, "text": "We use the @GET and @Path annotations to specify the URL for the GET request as follows −" }, { "code": null, "e": 4936, "s": 4908, "text": "@GET\n@Path(\"/movie/{id}/\")\n" }, { "code": null, "e": 5044, "s": 4936, "text": "The movie database itself is initialized in the init method, where we add five movie items to the database." }, { "code": null, "e": 5092, "s": 5044, "text": "Our next task is to write a server application." }, { "code": null, "e": 5162, "s": 5092, "text": "To create a server, we use CXF supplied JAXRSServerFactoryBean class." }, { "code": null, "e": 5226, "s": 5162, "text": "JAXRSServerFactoryBean factory = new JAXRSServerFactoryBean();\n" }, { "code": null, "e": 5296, "s": 5226, "text": "We set its resource classes by calling the setResourceClasses method." }, { "code": null, "e": 5386, "s": 5296, "text": "factory.setResourceClasses(Movie.class);\nfactory.setResourceClasses(MovieService.class);\n" }, { "code": null, "e": 5457, "s": 5386, "text": "We set the service provider by calling the setResourceProvider method." }, { "code": null, "e": 5558, "s": 5457, "text": "factory.setResourceProvider(MovieService.class,\nnew SingletonResourceProvider(new MovieService()));\n" }, { "code": null, "e": 5628, "s": 5558, "text": "We set the desired publish address by calling the aetAddress method −" }, { "code": null, "e": 5675, "s": 5628, "text": "factory.setAddress(\"http://localhost:9000/\");\n" }, { "code": null, "e": 5760, "s": 5675, "text": "Finally, we publish the server by calling the create method on the factory instance." }, { "code": null, "e": 5779, "s": 5760, "text": "factory.create();\n" }, { "code": null, "e": 5839, "s": 5779, "text": "The entire code for the server application is given below −" }, { "code": null, "e": 6631, "s": 5839, "text": "//Server.java\npackage com.tutorialspoint.cxf.jaxrs.movie;\nimport org.apache.cxf.jaxrs.JAXRSServerFactoryBean;\nimport org.apache.cxf.jaxrs.lifecycle.SingletonResourceProvider;\npublic class Server {\n public static void main(String[] args) throws Exception {\n JAXRSServerFactoryBean factory = new JAXRSServerFactoryBean();\n factory.setResourceClasses(Movie.class);\n factory.setResourceClasses(MovieService.class); \n factory.setResourceProvider(MovieService.class,\n new SingletonResourceProvider(new MovieService()));\n factory.setAddress(\"http://localhost:9000/\");\n factory.create();\n \n System.out.println(\"Server ready...\");\n Thread.sleep(5 * 60 * 1000);\n \n System.out.println(\"Server exiting ...\");\n System.exit(0);\n }\n}" }, { "code": null, "e": 6690, "s": 6631, "text": "Here we have included the final version of pom.xml below −" }, { "code": null, "e": 10316, "s": 6690, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<project xmlns = \"http://maven.apache.org/POM/4.0.0\"\n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation = \"http://maven.apache.org/POM/4.0.0\n http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n <modelVersion>4.0.0</modelVersion>\n <groupId>com.tutorialspoint</groupId>\n <artifactId>cxf-jaxrs</artifactId>\n <version>1.0</version>\n <packaging>jar</packaging>\n <properties>\n <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>\n <maven.compiler.source>1.8</maven.compiler.source>\n <maven.compiler.target>1.8</maven.compiler.target>\n </properties>\n <profiles>\n <profile>\n <id>server</id>\n <build>\n <defaultGoal>test</defaultGoal>\n <plugins>\n <plugin>\n <groupId>org.codehaus.mojo</groupId>\n <artifactId>exec-maven-plugin</artifactId>\n <version>1.6.0</version>\n <executions>\n <execution>\n <phase>test</phase>\n <goals>\n <goal>java</goal>\n </goals>\n <configuration>\n <mainClass>\n com.tutorialspoint.cxf.jaxrs.movie.Server\n </mainClass>\n </configuration>\n </execution>\n </executions>\n </plugin>\n </plugins>\n </build>\n <dependencies>\n <dependency>\n <groupId>org.apache.cxf</groupId>\n <artifactId>cxf-rt-transports-http-jetty</artifactId>\n <version>3.3.0</version>\n </dependency>\n </dependencies>\n </profile>\n <profile>\n <id>client</id>\n <build>\n <defaultGoal>test</defaultGoal>\n <plugins>\n <plugin>\n <groupId>org.codehaus.mojo</groupId>\n <artifactId>exec-maven-plugin</artifactId>\n <executions>\n <execution>\n <phase>test</phase>\n <goals>\n <goal>java</goal>\n </goals>\n <configuration>\n <mainClass>\n com.tutorialspoint.cxf.jaxrs.movie.Client\n </mainClass>\n </configuration>\n </execution>\n </executions>\n </plugin>\n </plugins>\n </build>\n </profile>\n </profiles>\n <dependencies>\n <dependency>\n <groupId>org.apache.cxf</groupId>\n <artifactId>cxf-rt-transports-http</artifactId>\n <version>3.3.0</version>\n </dependency>\n <dependency>\n <groupId>org.apache.cxf</groupId>\n <artifactId>cxf-rt-transports-http-jetty</artifactId>\n <version>3.3.0</version>\n </dependency>\n <dependency>\n <groupId>org.apache.cxf</groupId>\n <artifactId>cxf-rt-frontend-jaxrs</artifactId>\n <version>3.3.0</version>\n </dependency>\n <dependency>\n <groupId>jakarta.ws.rs</groupId>\n <artifactId>jakarta.ws.rs-api</artifactId>\n <version>2.1.5</version>\n </dependency>\n <dependency>\n <groupId>org.apache.httpcomponents</groupId>\n <artifactId>httpclient</artifactId>\n <version>4.5.7</version>\n </dependency>\n </dependencies>\n</project>" }, { "code": null, "e": 10491, "s": 10316, "text": "Writing the RS client is trivial. We simply create a URL object and open its stream. We use CXF supplied IOUtils class to copy the contents of input stream to a local stream." }, { "code": null, "e": 10705, "s": 10491, "text": "URL url = new URL(\"http://localhost:9000/movieservice/movie/1002\");\ntry (InputStream instream = url.openStream();\nCachedOutputStream outstream = new CachedOutputStream()) {\n IOUtils.copy(instream, outstream);\n}\n" }, { "code": null, "e": 10765, "s": 10705, "text": "The entire code for the client application is given below −" }, { "code": null, "e": 11376, "s": 10765, "text": "//Client.java\npackage com.tutorialspoint.cxf.jaxrs.movie;\nimport java.io.InputStream;\nimport java.net.URL;\nimport org.apache.cxf.helpers.IOUtils;\nimport org.apache.cxf.io.CachedOutputStream;\npublic class Client {\n public static void main(String[] args) throws Exception {\n URL url = new URL(\"http://localhost:9000/movieservice/movie/1002\");\n try (InputStream instream = url.openStream();\n CachedOutputStream outstream = new CachedOutputStream()) {\n IOUtils.copy(instream, outstream);\n String str = outstream.getOut().toString();\n System.out.println(str);\n }\n }\n}" }, { "code": null, "e": 11448, "s": 11376, "text": "Run the server using the following command in the command-line window −" }, { "code": null, "e": 11462, "s": 11448, "text": "mvn -Pserver\n" }, { "code": null, "e": 11519, "s": 11462, "text": "Now, you will see the following message on the console −" }, { "code": null, "e": 11591, "s": 11519, "text": "INFO: Setting the server's publish address to be http://localhost:9000\n" }, { "code": null, "e": 11643, "s": 11591, "text": "Now, open your browser and type the following URL −" }, { "code": null, "e": 11690, "s": 11643, "text": "http://localhost:9000/movieservice/movie/1002\n" }, { "code": null, "e": 11740, "s": 11690, "text": "You will see the following in the browser window." }, { "code": null, "e": 11893, "s": 11740, "text": "You may invoke the service by using a Java client application that we have developed by running the following command in a separate command-line window." }, { "code": null, "e": 11907, "s": 11893, "text": "mvn -Pclient\n" }, { "code": null, "e": 11943, "s": 11907, "text": "You will see the following output −" }, { "code": null, "e": 12063, "s": 11943, "text": "<?xml version=\"1.0\" encoding = \"UTF-8\" standalone=\"yes\"?>\n<Movie><id>1002</id><name>Mission Imposssible</name></Movie>\n" }, { "code": null, "e": 12194, "s": 12063, "text": "CXF samples provides several examples on how to use CXF with JAX-RS. The interested readers are encouraged to study these samples." }, { "code": null, "e": 12229, "s": 12194, "text": "\n 46 Lectures \n 3.5 hours \n" }, { "code": null, "e": 12248, "s": 12229, "text": " Arnab Chakraborty" }, { "code": null, "e": 12283, "s": 12248, "text": "\n 23 Lectures \n 1.5 hours \n" }, { "code": null, "e": 12304, "s": 12283, "text": " Mukund Kumar Mishra" }, { "code": null, "e": 12337, "s": 12304, "text": "\n 16 Lectures \n 1 hours \n" }, { "code": null, "e": 12350, "s": 12337, "text": " Nilay Mehta" }, { "code": null, "e": 12385, "s": 12350, "text": "\n 52 Lectures \n 1.5 hours \n" }, { "code": null, "e": 12403, "s": 12385, "text": " Bigdata Engineer" }, { "code": null, "e": 12436, "s": 12403, "text": "\n 14 Lectures \n 1 hours \n" }, { "code": null, "e": 12454, "s": 12436, "text": " Bigdata Engineer" }, { "code": null, "e": 12487, "s": 12454, "text": "\n 23 Lectures \n 1 hours \n" }, { "code": null, "e": 12505, "s": 12487, "text": " Bigdata Engineer" }, { "code": null, "e": 12512, "s": 12505, "text": " Print" }, { "code": null, "e": 12523, "s": 12512, "text": " Add Notes" } ]
Establish communication between sibling components in Angular 11 - GeeksforGeeks
23 Feb, 2021 In this article, we will see how we can pass data between sibling components on client machine. In Angular, we divide our web page into multiple components and the relation among these component forms a tree like structure. A component may have a parent and multiple children. That said, it can also have siblings. In some situations we need to pass data among these independent components. Passing the data is easy, and it makes our code cleaner and more readable while working on a large project. Prerequisites: NPM must be preinstalled. To understand how it works, see the diagram below: In case of a user event, we can emit data from one component. This data will be sent to the parent component. The parent component can further transfer this data in form of an input to the other child component. It is a one way transmission, but we can use it the other way in order to make a two-way communication channel. In Angular, we can achieve this using its inbuilt features: The @Output decorator helps in emitting the data through an EventEmitter<T> object. We will see its working through the example. The parent component will catch the data as $event variable. It can use it in a method or transmit it by other means. Finally the @Input() decorator uses a variable and any input through the parent will get stored in this variable. Lets see all of this through a simple example. In this post we will see a simple web page that takes keywords as user input in one component and displays the matching rows in other component. Lets setup the environment first: Install angular cli. Run as administrator or use sudo in case of permission errors. npm i -g @angular/cli When angular CLI is installed, start a new project using the following command: ng new <project-name> Now test it using: ng serve -o If the angular landing page can be accessed on http://localhost:4200, the setup is successful. Clear the content of app.component.html before moving further. After that generate two new components : ng generate component search ng generate component table You will see two directories ‘search’ and ‘table’ in the app folder. Both of them will have 4 new files in each. Lets make our search component and emit an event from it. First in search.component.html write the following code: HTML <br><br><div> <label for="search">Enter the text</label> <br> <br> <input type="text" id="search" placeholder="type some words" (keyup)="emit(keyword.value);" #keyword></div> In above code, there is a simple input field which uses an emit() function when keyup event occurs. We will use this to emit the keyword to parent component. Lets define this method and event in search.component.ts: Javascript import { Component, EventEmitter, OnInit, Output } from '@angular/core'; @Component({ selector: 'app-search', templateUrl: './search.component.html', styleUrls: ['./search.component.css']})export class SearchComponent implements OnInit { constructor() { } ngOnInit(): void { } @Output() emitter:EventEmitter<string> = new EventEmitter<string>(); emit(keyword){ this.emitter.emit(keyword); }} The emitter object of type “string” will emit the specified parameter in its emit() method. On keyup event, the emit() method executes emitter object’s emit() method. Now lets populate the code in table.component.ts: Javascript import { Component, DoCheck, Input, OnInit } from '@angular/core'; @Component({ selector: 'app-table', templateUrl: './table.component.html', styleUrls: ['./table.component.css']})export class TableComponent implements OnInit, DoCheck { data = [ {name:"Liam", age:"20", post: "Marketing Coordinator"}, {name:"Noah", age:"25" , post:"Medical Assistant"}, {name:"Oliver", age:"22", post:"Web Designer"}, {name:"William", age:"20", post:"Dog Trainer"}, {name:"Bill", age: "22", post:"President of Sales"}, {name:"James", age: "19", post:"Project Manager"}, ]; items = []; constructor() { } @Input() keyword:string; ngOnInit(): void { this.refresh(); } ngDoCheck(){ this.refresh(); } refresh(){ this.items = []; this.data.forEach( item => { if(item.name.search(this.keyword) != -1 || item.age.search(this.keyword) != -1 || item.post.search(this.keyword) != -1) { this.items.push(item) } } ) }} We have declared a data object that is some static data for our table for this example. The “keyword” variable is defined as Input to this component using @Input() decorator. We have declared a refresh() method that populates the items list using if the content is matched in either of the field with the “keyword” variable. We have called this method in ngDoCheck and ngOnInit methods (Note that we have to implement the interface for them). ngDoCheck method is called post change detection in the app. Hence whenever the keyword changes in parent, this method will replace the list. We will show this list on the table.component.html using the below code: HTML <p *ngIf="!items.length">No results found</p> <table class="table" *ngIf="items.length"> <thead > <td>Name</td> <td>Age</td> <td>Post</td> </thead> <br> <tr *ngFor="let item of items"> <td>{{item.name}}</td> <td>{{item.age}}</td> <td>{{item.post}}</td> </tr></table> Above code displays the table present in “items” array. Now lets write the code for the parent component app.component.ts: Javascript import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css']})export class AppComponent { title = 'GeeksForGeeks'; keyword = ""; send(keyword){ this.keyword = keyword; }} In the above code: We have declared a keyword variable. The send() method takes the keyword as parameter and sets it to the class variable. We will use the class variable “keyword” as an input to table component. The event emitted by search component will be handled by send() method. See the code below for app.component.html: HTML <div> <app-search (emitter)="send($event)"></app-search></div><hr> <div> <app-table [keyword]="keyword"></app-table></div> In this code: “$event” variable represents the emitted data from search component. The table component’s keyword variable is passed as [keyword]. Now save all the files and test the code using: ng serve -o On http://localhost:4200 we can see the result. Output: Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. AngularJS-Questions AngularJS HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Top 10 Angular Libraries For Web Developers How to use <mat-chip-list> and <mat-chip> in Angular Material ? How to make a Bootstrap Modal Popup in Angular 9/8 ? Angular 10 (blur) Event Angular PrimeNG Dropdown Component Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? How to update Node.js and NPM to next version ? How to set the default value for an HTML <select> element ? How to set input type date in dd-mm-yyyy format using HTML ?
[ { "code": null, "e": 25133, "s": 25105, "text": "\n23 Feb, 2021" }, { "code": null, "e": 25230, "s": 25133, "text": "In this article, we will see how we can pass data between sibling components on client machine. " }, { "code": null, "e": 25633, "s": 25230, "text": "In Angular, we divide our web page into multiple components and the relation among these component forms a tree like structure. A component may have a parent and multiple children. That said, it can also have siblings. In some situations we need to pass data among these independent components. Passing the data is easy, and it makes our code cleaner and more readable while working on a large project." }, { "code": null, "e": 25674, "s": 25633, "text": "Prerequisites: NPM must be preinstalled." }, { "code": null, "e": 25725, "s": 25674, "text": "To understand how it works, see the diagram below:" }, { "code": null, "e": 25787, "s": 25725, "text": "In case of a user event, we can emit data from one component." }, { "code": null, "e": 25835, "s": 25787, "text": "This data will be sent to the parent component." }, { "code": null, "e": 25937, "s": 25835, "text": "The parent component can further transfer this data in form of an input to the other child component." }, { "code": null, "e": 26049, "s": 25937, "text": "It is a one way transmission, but we can use it the other way in order to make a two-way communication channel." }, { "code": null, "e": 26109, "s": 26049, "text": "In Angular, we can achieve this using its inbuilt features:" }, { "code": null, "e": 26238, "s": 26109, "text": "The @Output decorator helps in emitting the data through an EventEmitter<T> object. We will see its working through the example." }, { "code": null, "e": 26356, "s": 26238, "text": "The parent component will catch the data as $event variable. It can use it in a method or transmit it by other means." }, { "code": null, "e": 26470, "s": 26356, "text": "Finally the @Input() decorator uses a variable and any input through the parent will get stored in this variable." }, { "code": null, "e": 26662, "s": 26470, "text": "Lets see all of this through a simple example. In this post we will see a simple web page that takes keywords as user input in one component and displays the matching rows in other component." }, { "code": null, "e": 26696, "s": 26662, "text": "Lets setup the environment first:" }, { "code": null, "e": 26780, "s": 26696, "text": "Install angular cli. Run as administrator or use sudo in case of permission errors." }, { "code": null, "e": 26802, "s": 26780, "text": "npm i -g @angular/cli" }, { "code": null, "e": 26882, "s": 26802, "text": "When angular CLI is installed, start a new project using the following command:" }, { "code": null, "e": 26904, "s": 26882, "text": "ng new <project-name>" }, { "code": null, "e": 26923, "s": 26904, "text": "Now test it using:" }, { "code": null, "e": 26935, "s": 26923, "text": "ng serve -o" }, { "code": null, "e": 27093, "s": 26935, "text": "If the angular landing page can be accessed on http://localhost:4200, the setup is successful. Clear the content of app.component.html before moving further." }, { "code": null, "e": 27134, "s": 27093, "text": "After that generate two new components :" }, { "code": null, "e": 27191, "s": 27134, "text": "ng generate component search\nng generate component table" }, { "code": null, "e": 27304, "s": 27191, "text": "You will see two directories ‘search’ and ‘table’ in the app folder. Both of them will have 4 new files in each." }, { "code": null, "e": 27419, "s": 27304, "text": "Lets make our search component and emit an event from it. First in search.component.html write the following code:" }, { "code": null, "e": 27424, "s": 27419, "text": "HTML" }, { "code": "<br><br><div> <label for=\"search\">Enter the text</label> <br> <br> <input type=\"text\" id=\"search\" placeholder=\"type some words\" (keyup)=\"emit(keyword.value);\" #keyword></div>", "e": 27622, "s": 27424, "text": null }, { "code": null, "e": 27838, "s": 27622, "text": "In above code, there is a simple input field which uses an emit() function when keyup event occurs. We will use this to emit the keyword to parent component. Lets define this method and event in search.component.ts:" }, { "code": null, "e": 27849, "s": 27838, "text": "Javascript" }, { "code": "import { Component, EventEmitter, OnInit, Output } from '@angular/core'; @Component({ selector: 'app-search', templateUrl: './search.component.html', styleUrls: ['./search.component.css']})export class SearchComponent implements OnInit { constructor() { } ngOnInit(): void { } @Output() emitter:EventEmitter<string> = new EventEmitter<string>(); emit(keyword){ this.emitter.emit(keyword); }}", "e": 28274, "s": 27849, "text": null }, { "code": null, "e": 28441, "s": 28274, "text": "The emitter object of type “string” will emit the specified parameter in its emit() method. On keyup event, the emit() method executes emitter object’s emit() method." }, { "code": null, "e": 28491, "s": 28441, "text": "Now lets populate the code in table.component.ts:" }, { "code": null, "e": 28502, "s": 28491, "text": "Javascript" }, { "code": "import { Component, DoCheck, Input, OnInit } from '@angular/core'; @Component({ selector: 'app-table', templateUrl: './table.component.html', styleUrls: ['./table.component.css']})export class TableComponent implements OnInit, DoCheck { data = [ {name:\"Liam\", age:\"20\", post: \"Marketing Coordinator\"}, {name:\"Noah\", age:\"25\" , post:\"Medical Assistant\"}, {name:\"Oliver\", age:\"22\", post:\"Web Designer\"}, {name:\"William\", age:\"20\", post:\"Dog Trainer\"}, {name:\"Bill\", age: \"22\", post:\"President of Sales\"}, {name:\"James\", age: \"19\", post:\"Project Manager\"}, ]; items = []; constructor() { } @Input() keyword:string; ngOnInit(): void { this.refresh(); } ngDoCheck(){ this.refresh(); } refresh(){ this.items = []; this.data.forEach( item => { if(item.name.search(this.keyword) != -1 || item.age.search(this.keyword) != -1 || item.post.search(this.keyword) != -1) { this.items.push(item) } } ) }}", "e": 29497, "s": 28502, "text": null }, { "code": null, "e": 29586, "s": 29497, "text": "We have declared a data object that is some static data for our table for this example. " }, { "code": null, "e": 29673, "s": 29586, "text": "The “keyword” variable is defined as Input to this component using @Input() decorator." }, { "code": null, "e": 29823, "s": 29673, "text": "We have declared a refresh() method that populates the items list using if the content is matched in either of the field with the “keyword” variable." }, { "code": null, "e": 30083, "s": 29823, "text": "We have called this method in ngDoCheck and ngOnInit methods (Note that we have to implement the interface for them). ngDoCheck method is called post change detection in the app. Hence whenever the keyword changes in parent, this method will replace the list." }, { "code": null, "e": 30156, "s": 30083, "text": "We will show this list on the table.component.html using the below code:" }, { "code": null, "e": 30161, "s": 30156, "text": "HTML" }, { "code": "<p *ngIf=\"!items.length\">No results found</p> <table class=\"table\" *ngIf=\"items.length\"> <thead > <td>Name</td> <td>Age</td> <td>Post</td> </thead> <br> <tr *ngFor=\"let item of items\"> <td>{{item.name}}</td> <td>{{item.age}}</td> <td>{{item.post}}</td> </tr></table>", "e": 30486, "s": 30161, "text": null }, { "code": null, "e": 30609, "s": 30486, "text": "Above code displays the table present in “items” array. Now lets write the code for the parent component app.component.ts:" }, { "code": null, "e": 30620, "s": 30609, "text": "Javascript" }, { "code": "import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css']})export class AppComponent { title = 'GeeksForGeeks'; keyword = \"\"; send(keyword){ this.keyword = keyword; }}", "e": 30891, "s": 30620, "text": null }, { "code": null, "e": 30910, "s": 30891, "text": "In the above code:" }, { "code": null, "e": 30947, "s": 30910, "text": "We have declared a keyword variable." }, { "code": null, "e": 31031, "s": 30947, "text": "The send() method takes the keyword as parameter and sets it to the class variable." }, { "code": null, "e": 31104, "s": 31031, "text": "We will use the class variable “keyword” as an input to table component." }, { "code": null, "e": 31176, "s": 31104, "text": "The event emitted by search component will be handled by send() method." }, { "code": null, "e": 31219, "s": 31176, "text": "See the code below for app.component.html:" }, { "code": null, "e": 31224, "s": 31219, "text": "HTML" }, { "code": "<div> <app-search (emitter)=\"send($event)\"></app-search></div><hr> <div> <app-table [keyword]=\"keyword\"></app-table></div>", "e": 31350, "s": 31224, "text": null }, { "code": null, "e": 31364, "s": 31350, "text": "In this code:" }, { "code": null, "e": 31433, "s": 31364, "text": "“$event” variable represents the emitted data from search component." }, { "code": null, "e": 31496, "s": 31433, "text": "The table component’s keyword variable is passed as [keyword]." }, { "code": null, "e": 31544, "s": 31496, "text": "Now save all the files and test the code using:" }, { "code": null, "e": 31556, "s": 31544, "text": "ng serve -o" }, { "code": null, "e": 31604, "s": 31556, "text": "On http://localhost:4200 we can see the result." }, { "code": null, "e": 31612, "s": 31604, "text": "Output:" }, { "code": null, "e": 31749, "s": 31612, "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": 31769, "s": 31749, "text": "AngularJS-Questions" }, { "code": null, "e": 31779, "s": 31769, "text": "AngularJS" }, { "code": null, "e": 31784, "s": 31779, "text": "HTML" }, { "code": null, "e": 31801, "s": 31784, "text": "Web Technologies" }, { "code": null, "e": 31806, "s": 31801, "text": "HTML" }, { "code": null, "e": 31904, "s": 31806, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31913, "s": 31904, "text": "Comments" }, { "code": null, "e": 31926, "s": 31913, "text": "Old Comments" }, { "code": null, "e": 31970, "s": 31926, "text": "Top 10 Angular Libraries For Web Developers" }, { "code": null, "e": 32034, "s": 31970, "text": "How to use <mat-chip-list> and <mat-chip> in Angular Material ?" }, { "code": null, "e": 32087, "s": 32034, "text": "How to make a Bootstrap Modal Popup in Angular 9/8 ?" }, { "code": null, "e": 32111, "s": 32087, "text": "Angular 10 (blur) Event" }, { "code": null, "e": 32146, "s": 32111, "text": "Angular PrimeNG Dropdown Component" }, { "code": null, "e": 32208, "s": 32146, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 32258, "s": 32208, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 32306, "s": 32258, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 32366, "s": 32306, "text": "How to set the default value for an HTML <select> element ?" } ]
Space Science with Python — Space maps | by Thomas Albin | Towards Data Science
This is the 5th part of my Python tutorial series “Space Science with Python”. All codes that are shown here are uploaded on GitHub. Enjoy! In our last tutorials we computed the position and velocity vectors of different celestial objects. We determined the apparent angular distance between objects (so called phase-angle) and worked on some small projects using Python and the NASA library SPICE (using the SPICE wrapper spiceypy). In the next couple of weeks we will learn and work together on (scientific) data and larger projects that will cover e.g.: Asteroids, Near-Earth Objects and Meteors The Rosetta Mission and the descent of Philae on 67P/Churyumov–Gerasimenko The Cassini Mission, especially the Cosmic Dust Analyzer, where we will also apply Machine Learning algorithms for data reduction and analysis Before we start with our scientific deep dives we need to cover 2 fundamental topics: Coordinate Systems / Reference Frames Orbital Mechanics It may sound like dry theory, but we will work closely with Python examples. With a solid knowledge fundament and understanding of both topics, in combination with SPICE and other tools that will follow, you will be prepared to achieve great scientific insights! A 3-dimensional coordinate system has an x, y and z component. All three components are aligned orthogonally, so the angle between all components is 90°. The orientation of the components fulfil the so called right-hand rule: Make a fist. Do a “thumbs up” with your right hand (x axis). Point the forefinger (y axis) to the front (make a “pistol” gesture). Now, point the middle finger away from the palm (z axis). Now let’s take a look at the first coordinate system: The Ecliptic Coordinate System. It is widely used for Space Science and for interplanetary missions and can be applied for Solar System centred or planetary tasks. In our last tutorials I was already referring to this system as ECLIPJ2000 (SPICE naming convention). Let’s take a look at Earth. Our planet revolves around the Sun on an imaginary plane, the so called ecliptic plane. Now, for a coordinate system, we need to define 2 axes; the third one results from the right-hand rule. The x axis is the so called Vernal Equinox: At the beginning of spring, we take the a look at the Sun. The corresponding direction is defined as the x axis (see sketch below). At this very moment, based on the direction to the Sun and the Earth’s velocity vector, we get the ecliptic plane. The z axis is perpendicular to this plane (to the Ecliptic north) and the y axis results from the right-hand rule. Any 3-dimensional vector can be transformed to spherical coordinates that can be described by 3 parameters: the radius, the azimuth and the inclination. Projecting these values on a unit sphere (sphere with radius = 1) leads to a sky map. The following coordinates describe the position on this map: Longitude (l): Is defined from 0° to 360°. For the Ecliptic Coordinate System, a longitude of 0° indicates the Vernal Equinox line. All other longitude values are specified with respect to this line (an imaginary line from one pole to the other. Latitude (b): Is defined from -90° (south pole of the sphere) to +90° (north pole of the sphere). Values with a latitude of 0° lie on the equator; respectively on the ecliptic plane for the Ecliptic Coordinate System. This means that l=0° and b=0° (x axis) is the Vernal Equinox point. Now what does J2000 mean? Due to gravitational perturbations of other planets our Earth’s orbit “wobbles” a little bit. Consequently, the ecliptic plane changes slightly with time. To avoid a yearly or even daily reference frame update, the ecliptic plane that is being defined at the date J2000 (noon 1st January 2000) is commonly used. Okay, enough theory. Let’s have a look at the programming part. How can we work with these reference frames? How can we compute positions on the sky? And how does SPICE helps us with that? Let’s compute and plot a sky map with the coordinates of the Sun, Venus, Mars and our Moon. First, we need to import all necessary modules that were already introduced and used in the previous tutorials: datetime, spiceypy (SPICE wrapper), numpy, pandas and matplotlib (plotting). Before we can compute any positions, we need the SPICE kernel meta file that contains the relative paths to the relevant kernels. It contains the spk kernel de432s.bsp for the planetary positions and naif0012.tls for the time conversions and leap seconds. The meta file is loaded with furnsh. We set this very moment (datetime.datetime.now()) as the date-time object and convert it directly to a corresponding string (line 12). Please consider the following warning from the official datetime documentation if you are using .now(): Because naive datetime objects are treated by many datetime methods as local times, it is preferred to use aware datetimes to represent times in UTC. As such, the recommended way to create an object representing the current time in UTC is by calling datetime.now(timezone.utc). Line 15 converts the UTC string to the corresponding Ephemeris time (ET) with the SPICE function utc2et. For the computation a pandas dataframe is defined. This dataframe will contain all resulting coordinates of the ET respectively the UTC time (line 7+8). The positions are computed in a for-loop that iterates through a dictionary of all needed celestial bodies and their NAIF ID code (defined in line 13). Since the loaded spk kernel does not contains the planet’s centre of Mars, the barycentre is used (ID: 4). Now, the for-loop iterates through the dictionary and computes the directional vector to each celestial object as seen from Earth (line 8–13). The SPICE function spkezp is used for this purpose with the following input arguments: targ: The NAIF ID of the object that shall be observed et: The ET as computed in the beginning ref: The reference frame. Here it is the Ecliptic Coordinate System ECLIPJ2000 abcorr: The light time correction as described last time (NAIF detailed documentation, if you want to know everything). Here the input LT+S indicates that the position determination as seen from the observer (Earth) considers the object’s velocity and the travel time of the light. obs: The NAIF ID of the observer, here: our home planet (399) Thanks to the SPICE function recrad, the direction vectors can be easily converted to spherical coordinates. The longitude and latitude values are the second and third output values, respectively. The first output value is the length (norm) of the vector and is not needed in our case. Now we have the coordinates of our objects. Plotting should be quite easy, right? We can create a simple matplotlib plot and we are done. Not so fast ... A rectangular plot would be quick and dirty and there are better solutions to plot sky coordinates. If you “cut a sphere” and try to project its surface in 2 dimensions one has several projection options, like: Aitoff Hammer Mollweide Each projection type has its advantages and disadvantages, like representing an equal area map, but not providing correct angular measures (Mollweide). The Aitoff projection provides only a length accuracy and equal area around the meridian and equator, respectively. Hammer compensates these Aitoff issues. An extensive list of projections can be found on the NASA’s GISS website. Let’s have a look at an empty map with an Aitoff projection. The following Python code creates the figure below: You can see the latitude values range from -90° to +90° and the longitudes vary between -180° and +180°. As mentioned before however, the longitude values in the Ecliptic Coordinate System range from 0° to 360°. Further, the longitude’s values count from right to left. matplotlib does not allow one to redefine the projection properties and one cannot easily invert the x axis with a formatting function. Thus, we need to create a small workaround and be a little bit creative. The following coding part shows a for-loop that iterates through all longitude values and creates a new column with longitudes “for the plot”: All angles are given in radians. Values that are larger than pi (180°) exceed the plotting range of matplotlib. The modulo operator is applied with pi (% np.pi). The remainder is consequently between 0 and pi and should be “on the left side” of the projection map (-180° to 0°), so we need to subtract pi. Finally we multiply the result with -1 to invert the x axis values. -1*((x % np.pi) — np.pi) applies only if x is larger than pi-1*x applies else (x is smaller than pi) Now we can plot the coordinates of the celestial bodies in Ecliptic coordinates. First a dark background is set (line 4) because ... space is dark! Line 7 defines the figure and the line after sets the projection. We use the UTC time stamp as a title (line 11) and a simple array defines some colours (line 14) that are used in a for-loop that iterates through all celestial bodies (line 17 to 24). Line 27 to 30 redefine the x ticks and replace the matplotlib ticks with the ecliptic longitudes. Finally, the labels are set, a legend and grid are created and the plot is saved. The resulting sky map can be seen below. The sky map shows the Ecliptic Coordinate System and the positions of the Sun, Venus, Mars and the Moon at around 5 pm on the 5th May 2020. You can see that the planets are located close to the ecliptic plane. The Moon is almost 180° away from the Sun. Have a look outside at the evening: It is almost Full Moon. Did you consider buying a telescope? It is a calm and inspiring hobby. Either in a group or alone you can explore the planets, galaxies and other cosmic wonders from your backyard (if it is not too light-polluted). But there are a lot of different telescope types and mounts. One common mount type is the so called equatorial mount. This mount is aligned with the rotation axis of the Earth and “rotates with the sky”. Long exposure images, or visual observations without constant re-adjustments are possible with these mounts. Modern mounts have an internal clock combined with an electric motor to compensate the rotation. The corresponding coordinate system is the so called Equatorial Coordinate System (In SPICE it is simply called J2000 ... a little bit confusing, considering that J2000 is a timestamp), where the x axis points to the Vernal Equinox direction and the z axis is the rotation axis of Earth. Earth’s equator is inclined with respect to the Ecliptic plane (around 23°, see 2nd sketch at the beginning) and does not “overlap” with the Ecliptic Coordinate System. The longitude and latitude in equatorial coordinates are described as: Right ascension: This is the longitude of the Equatorial Coordinate System and is defined in hours (h), not in degrees, and ranges from 0h to 24h (1h corresponds to 15 degrees). Declination: This is the latitude and ranges from -90° to +90°. 0° corresponds to the equator line. Now, let’s compute the equatorial coordinates for our celestial bodies of interest. We apply again a for-loop that iterates through all bodies and we apply the same functions as before to compute the directional vector and the coordinates in the Equatorial Coordinate System. To visualise the resulting distortion between the Ecliptic and Equatorial Coordinate System, we add the ecliptic plane in our computations. For this purpose, an additional pandas dataframe is created (line 6). Line 11 adds the longitude coordinates in ECLIPJ2000, from 0 to 2*pi (360°), as an array. Line 12 adds the latitude values. Actually, the coordinates should be 0°, in this case we need the spherical coordinate convention. Line 18 to 23 converts the spherical ecliptic coordinates to directional vectors using the SPICE function sphrec. The function needs the distance r (here: unit sphere with radius 1), the latitude (colat) and longitude (lon) values. The returned vectors are the directional vectors of the ecliptic plane in a vectorised Ecliptic Coordinate System (x, y, z components). In a next step we need to transform these vectors to the vectorised Equatorial Coordinate System (x, y, z components). We use the SPICE function pxform that computes a 3x3 transformation matrix between both coordinate systems. The function requires the following input: fromstr: (Note: the suffix str applies only for the spiceypy library) The coordinate system’s name to transform from (here: ECLIPJ2000) tostr: (Note: the suffix str applies only for the spiceypy library) The coordinate system’s name to transform to (here: J2000) et: The ET between both transformations. For inertial coordinate systems this value can be any ET (systems that do not change their orientation / definition in time. In future tutorials we will encounter rotational coordinate systems, where this input parameter must be considered) With the transformation matrix we can transform the vectors from ECLIPJ2000 to J2000 as shown in line 10 and 11. The matrix is applied with a dot product on the vectors. Afterwards (line 15–24) the vectors in the vectorised Equatorial Coordinate System can be transformed to right ascension and declination values using the SPICE function recrad. Now we can plot the celestial objects and add the ecliptic plane in equatorial coordinates (line 17–19) as a blue dotted line. Similarly as before, we set some formatting properties and change the x ticks to right ascension hours (line 22–25). The resulting figure is shown below. You can see that the ecliptic plane describes a sinusoidal curve on the Equatorial Coordinate System. The Sun and the planets are again close to the ecliptic plane. The Sun is at around 3 hours and has a declination of more than 15 degrees. During the year, the Sun “moves” along the blue dotted line from right to left. You can see seasonal variations: The Sun crossed already the 0h / 0° Vernal Equinox point and moves “higher” in declination. This mean that the readers of you who live on the northern hemisphere will have longer days until the beginning of Summer. Afterwards, the Sun moves downwards and the days get shorter. Today we learned how to compute the coordinates of celestial bodies for different coordinate systems. This knowledge will be required for future tutorials, where we will make observation planning and asteroid tracking. Astronomers and radio telescope operators need to compute these coordinates precisely, e.g., to find objects, for the determination of an asteroids orbits or to track and communicate with satellites and spacecraft missions. If you want to get a “better feeling” about this topic with more flexibility and visualisations (but with less Python computations) have a look at the Open Source planetarium software Stellarium.
[ { "code": null, "e": 311, "s": 171, "text": "This is the 5th part of my Python tutorial series “Space Science with Python”. All codes that are shown here are uploaded on GitHub. Enjoy!" }, { "code": null, "e": 605, "s": 311, "text": "In our last tutorials we computed the position and velocity vectors of different celestial objects. We determined the apparent angular distance between objects (so called phase-angle) and worked on some small projects using Python and the NASA library SPICE (using the SPICE wrapper spiceypy)." }, { "code": null, "e": 728, "s": 605, "text": "In the next couple of weeks we will learn and work together on (scientific) data and larger projects that will cover e.g.:" }, { "code": null, "e": 770, "s": 728, "text": "Asteroids, Near-Earth Objects and Meteors" }, { "code": null, "e": 845, "s": 770, "text": "The Rosetta Mission and the descent of Philae on 67P/Churyumov–Gerasimenko" }, { "code": null, "e": 988, "s": 845, "text": "The Cassini Mission, especially the Cosmic Dust Analyzer, where we will also apply Machine Learning algorithms for data reduction and analysis" }, { "code": null, "e": 1074, "s": 988, "text": "Before we start with our scientific deep dives we need to cover 2 fundamental topics:" }, { "code": null, "e": 1112, "s": 1074, "text": "Coordinate Systems / Reference Frames" }, { "code": null, "e": 1130, "s": 1112, "text": "Orbital Mechanics" }, { "code": null, "e": 1393, "s": 1130, "text": "It may sound like dry theory, but we will work closely with Python examples. With a solid knowledge fundament and understanding of both topics, in combination with SPICE and other tools that will follow, you will be prepared to achieve great scientific insights!" }, { "code": null, "e": 1619, "s": 1393, "text": "A 3-dimensional coordinate system has an x, y and z component. All three components are aligned orthogonally, so the angle between all components is 90°. The orientation of the components fulfil the so called right-hand rule:" }, { "code": null, "e": 1808, "s": 1619, "text": "Make a fist. Do a “thumbs up” with your right hand (x axis). Point the forefinger (y axis) to the front (make a “pistol” gesture). Now, point the middle finger away from the palm (z axis)." }, { "code": null, "e": 2128, "s": 1808, "text": "Now let’s take a look at the first coordinate system: The Ecliptic Coordinate System. It is widely used for Space Science and for interplanetary missions and can be applied for Solar System centred or planetary tasks. In our last tutorials I was already referring to this system as ECLIPJ2000 (SPICE naming convention)." }, { "code": null, "e": 2754, "s": 2128, "text": "Let’s take a look at Earth. Our planet revolves around the Sun on an imaginary plane, the so called ecliptic plane. Now, for a coordinate system, we need to define 2 axes; the third one results from the right-hand rule. The x axis is the so called Vernal Equinox: At the beginning of spring, we take the a look at the Sun. The corresponding direction is defined as the x axis (see sketch below). At this very moment, based on the direction to the Sun and the Earth’s velocity vector, we get the ecliptic plane. The z axis is perpendicular to this plane (to the Ecliptic north) and the y axis results from the right-hand rule." }, { "code": null, "e": 3054, "s": 2754, "text": "Any 3-dimensional vector can be transformed to spherical coordinates that can be described by 3 parameters: the radius, the azimuth and the inclination. Projecting these values on a unit sphere (sphere with radius = 1) leads to a sky map. The following coordinates describe the position on this map:" }, { "code": null, "e": 3300, "s": 3054, "text": "Longitude (l): Is defined from 0° to 360°. For the Ecliptic Coordinate System, a longitude of 0° indicates the Vernal Equinox line. All other longitude values are specified with respect to this line (an imaginary line from one pole to the other." }, { "code": null, "e": 3518, "s": 3300, "text": "Latitude (b): Is defined from -90° (south pole of the sphere) to +90° (north pole of the sphere). Values with a latitude of 0° lie on the equator; respectively on the ecliptic plane for the Ecliptic Coordinate System." }, { "code": null, "e": 3586, "s": 3518, "text": "This means that l=0° and b=0° (x axis) is the Vernal Equinox point." }, { "code": null, "e": 3924, "s": 3586, "text": "Now what does J2000 mean? Due to gravitational perturbations of other planets our Earth’s orbit “wobbles” a little bit. Consequently, the ecliptic plane changes slightly with time. To avoid a yearly or even daily reference frame update, the ecliptic plane that is being defined at the date J2000 (noon 1st January 2000) is commonly used." }, { "code": null, "e": 4113, "s": 3924, "text": "Okay, enough theory. Let’s have a look at the programming part. How can we work with these reference frames? How can we compute positions on the sky? And how does SPICE helps us with that?" }, { "code": null, "e": 4926, "s": 4113, "text": "Let’s compute and plot a sky map with the coordinates of the Sun, Venus, Mars and our Moon. First, we need to import all necessary modules that were already introduced and used in the previous tutorials: datetime, spiceypy (SPICE wrapper), numpy, pandas and matplotlib (plotting). Before we can compute any positions, we need the SPICE kernel meta file that contains the relative paths to the relevant kernels. It contains the spk kernel de432s.bsp for the planetary positions and naif0012.tls for the time conversions and leap seconds. The meta file is loaded with furnsh. We set this very moment (datetime.datetime.now()) as the date-time object and convert it directly to a corresponding string (line 12). Please consider the following warning from the official datetime documentation if you are using .now():" }, { "code": null, "e": 5204, "s": 4926, "text": "Because naive datetime objects are treated by many datetime methods as local times, it is preferred to use aware datetimes to represent times in UTC. As such, the recommended way to create an object representing the current time in UTC is by calling datetime.now(timezone.utc)." }, { "code": null, "e": 5309, "s": 5204, "text": "Line 15 converts the UTC string to the corresponding Ephemeris time (ET) with the SPICE function utc2et." }, { "code": null, "e": 5721, "s": 5309, "text": "For the computation a pandas dataframe is defined. This dataframe will contain all resulting coordinates of the ET respectively the UTC time (line 7+8). The positions are computed in a for-loop that iterates through a dictionary of all needed celestial bodies and their NAIF ID code (defined in line 13). Since the loaded spk kernel does not contains the planet’s centre of Mars, the barycentre is used (ID: 4)." }, { "code": null, "e": 5951, "s": 5721, "text": "Now, the for-loop iterates through the dictionary and computes the directional vector to each celestial object as seen from Earth (line 8–13). The SPICE function spkezp is used for this purpose with the following input arguments:" }, { "code": null, "e": 6006, "s": 5951, "text": "targ: The NAIF ID of the object that shall be observed" }, { "code": null, "e": 6046, "s": 6006, "text": "et: The ET as computed in the beginning" }, { "code": null, "e": 6125, "s": 6046, "text": "ref: The reference frame. Here it is the Ecliptic Coordinate System ECLIPJ2000" }, { "code": null, "e": 6407, "s": 6125, "text": "abcorr: The light time correction as described last time (NAIF detailed documentation, if you want to know everything). Here the input LT+S indicates that the position determination as seen from the observer (Earth) considers the object’s velocity and the travel time of the light." }, { "code": null, "e": 6469, "s": 6407, "text": "obs: The NAIF ID of the observer, here: our home planet (399)" }, { "code": null, "e": 6755, "s": 6469, "text": "Thanks to the SPICE function recrad, the direction vectors can be easily converted to spherical coordinates. The longitude and latitude values are the second and third output values, respectively. The first output value is the length (norm) of the vector and is not needed in our case." }, { "code": null, "e": 6893, "s": 6755, "text": "Now we have the coordinates of our objects. Plotting should be quite easy, right? We can create a simple matplotlib plot and we are done." }, { "code": null, "e": 7120, "s": 6893, "text": "Not so fast ... A rectangular plot would be quick and dirty and there are better solutions to plot sky coordinates. If you “cut a sphere” and try to project its surface in 2 dimensions one has several projection options, like:" }, { "code": null, "e": 7127, "s": 7120, "text": "Aitoff" }, { "code": null, "e": 7134, "s": 7127, "text": "Hammer" }, { "code": null, "e": 7144, "s": 7134, "text": "Mollweide" }, { "code": null, "e": 7639, "s": 7144, "text": "Each projection type has its advantages and disadvantages, like representing an equal area map, but not providing correct angular measures (Mollweide). The Aitoff projection provides only a length accuracy and equal area around the meridian and equator, respectively. Hammer compensates these Aitoff issues. An extensive list of projections can be found on the NASA’s GISS website. Let’s have a look at an empty map with an Aitoff projection. The following Python code creates the figure below:" }, { "code": null, "e": 8261, "s": 7639, "text": "You can see the latitude values range from -90° to +90° and the longitudes vary between -180° and +180°. As mentioned before however, the longitude values in the Ecliptic Coordinate System range from 0° to 360°. Further, the longitude’s values count from right to left. matplotlib does not allow one to redefine the projection properties and one cannot easily invert the x axis with a formatting function. Thus, we need to create a small workaround and be a little bit creative. The following coding part shows a for-loop that iterates through all longitude values and creates a new column with longitudes “for the plot”:" }, { "code": null, "e": 8635, "s": 8261, "text": "All angles are given in radians. Values that are larger than pi (180°) exceed the plotting range of matplotlib. The modulo operator is applied with pi (% np.pi). The remainder is consequently between 0 and pi and should be “on the left side” of the projection map (-180° to 0°), so we need to subtract pi. Finally we multiply the result with -1 to invert the x axis values." }, { "code": null, "e": 8736, "s": 8635, "text": "-1*((x % np.pi) — np.pi) applies only if x is larger than pi-1*x applies else (x is smaller than pi)" }, { "code": null, "e": 9356, "s": 8736, "text": "Now we can plot the coordinates of the celestial bodies in Ecliptic coordinates. First a dark background is set (line 4) because ... space is dark! Line 7 defines the figure and the line after sets the projection. We use the UTC time stamp as a title (line 11) and a simple array defines some colours (line 14) that are used in a for-loop that iterates through all celestial bodies (line 17 to 24). Line 27 to 30 redefine the x ticks and replace the matplotlib ticks with the ecliptic longitudes. Finally, the labels are set, a legend and grid are created and the plot is saved. The resulting sky map can be seen below." }, { "code": null, "e": 9669, "s": 9356, "text": "The sky map shows the Ecliptic Coordinate System and the positions of the Sun, Venus, Mars and the Moon at around 5 pm on the 5th May 2020. You can see that the planets are located close to the ecliptic plane. The Moon is almost 180° away from the Sun. Have a look outside at the evening: It is almost Full Moon." }, { "code": null, "e": 10294, "s": 9669, "text": "Did you consider buying a telescope? It is a calm and inspiring hobby. Either in a group or alone you can explore the planets, galaxies and other cosmic wonders from your backyard (if it is not too light-polluted). But there are a lot of different telescope types and mounts. One common mount type is the so called equatorial mount. This mount is aligned with the rotation axis of the Earth and “rotates with the sky”. Long exposure images, or visual observations without constant re-adjustments are possible with these mounts. Modern mounts have an internal clock combined with an electric motor to compensate the rotation." }, { "code": null, "e": 10751, "s": 10294, "text": "The corresponding coordinate system is the so called Equatorial Coordinate System (In SPICE it is simply called J2000 ... a little bit confusing, considering that J2000 is a timestamp), where the x axis points to the Vernal Equinox direction and the z axis is the rotation axis of Earth. Earth’s equator is inclined with respect to the Ecliptic plane (around 23°, see 2nd sketch at the beginning) and does not “overlap” with the Ecliptic Coordinate System." }, { "code": null, "e": 10822, "s": 10751, "text": "The longitude and latitude in equatorial coordinates are described as:" }, { "code": null, "e": 11000, "s": 10822, "text": "Right ascension: This is the longitude of the Equatorial Coordinate System and is defined in hours (h), not in degrees, and ranges from 0h to 24h (1h corresponds to 15 degrees)." }, { "code": null, "e": 11100, "s": 11000, "text": "Declination: This is the latitude and ranges from -90° to +90°. 0° corresponds to the equator line." }, { "code": null, "e": 11376, "s": 11100, "text": "Now, let’s compute the equatorial coordinates for our celestial bodies of interest. We apply again a for-loop that iterates through all bodies and we apply the same functions as before to compute the directional vector and the coordinates in the Equatorial Coordinate System." }, { "code": null, "e": 12176, "s": 11376, "text": "To visualise the resulting distortion between the Ecliptic and Equatorial Coordinate System, we add the ecliptic plane in our computations. For this purpose, an additional pandas dataframe is created (line 6). Line 11 adds the longitude coordinates in ECLIPJ2000, from 0 to 2*pi (360°), as an array. Line 12 adds the latitude values. Actually, the coordinates should be 0°, in this case we need the spherical coordinate convention. Line 18 to 23 converts the spherical ecliptic coordinates to directional vectors using the SPICE function sphrec. The function needs the distance r (here: unit sphere with radius 1), the latitude (colat) and longitude (lon) values. The returned vectors are the directional vectors of the ecliptic plane in a vectorised Ecliptic Coordinate System (x, y, z components)." }, { "code": null, "e": 12446, "s": 12176, "text": "In a next step we need to transform these vectors to the vectorised Equatorial Coordinate System (x, y, z components). We use the SPICE function pxform that computes a 3x3 transformation matrix between both coordinate systems. The function requires the following input:" }, { "code": null, "e": 12582, "s": 12446, "text": "fromstr: (Note: the suffix str applies only for the spiceypy library) The coordinate system’s name to transform from (here: ECLIPJ2000)" }, { "code": null, "e": 12709, "s": 12582, "text": "tostr: (Note: the suffix str applies only for the spiceypy library) The coordinate system’s name to transform to (here: J2000)" }, { "code": null, "e": 12991, "s": 12709, "text": "et: The ET between both transformations. For inertial coordinate systems this value can be any ET (systems that do not change their orientation / definition in time. In future tutorials we will encounter rotational coordinate systems, where this input parameter must be considered)" }, { "code": null, "e": 13338, "s": 12991, "text": "With the transformation matrix we can transform the vectors from ECLIPJ2000 to J2000 as shown in line 10 and 11. The matrix is applied with a dot product on the vectors. Afterwards (line 15–24) the vectors in the vectorised Equatorial Coordinate System can be transformed to right ascension and declination values using the SPICE function recrad." }, { "code": null, "e": 13619, "s": 13338, "text": "Now we can plot the celestial objects and add the ecliptic plane in equatorial coordinates (line 17–19) as a blue dotted line. Similarly as before, we set some formatting properties and change the x ticks to right ascension hours (line 22–25). The resulting figure is shown below." }, { "code": null, "e": 14250, "s": 13619, "text": "You can see that the ecliptic plane describes a sinusoidal curve on the Equatorial Coordinate System. The Sun and the planets are again close to the ecliptic plane. The Sun is at around 3 hours and has a declination of more than 15 degrees. During the year, the Sun “moves” along the blue dotted line from right to left. You can see seasonal variations: The Sun crossed already the 0h / 0° Vernal Equinox point and moves “higher” in declination. This mean that the readers of you who live on the northern hemisphere will have longer days until the beginning of Summer. Afterwards, the Sun moves downwards and the days get shorter." }, { "code": null, "e": 14469, "s": 14250, "text": "Today we learned how to compute the coordinates of celestial bodies for different coordinate systems. This knowledge will be required for future tutorials, where we will make observation planning and asteroid tracking." } ]
PyQt - QDialog Class
A QDialog widget presents a top level window mostly used to collect response from the user. It can be configured to be Modal (where it blocks its parent window) or Modeless (the dialog window can be bypassed). PyQt API has a number of preconfigured Dialog widgets such as InputDialog, FileDialog, FontDialog, etc. In the following example, WindowModality attribute of Dialog window decides whether it is modal or modeless. Any one button on the dialog can be set to be default. The dialog is discarded by QDialog.reject() method when the user presses the Escape key. A PushButton on a top level QWidget window, when clicked, produces a Dialog window. A Dialog box doesn’t have minimize and maximize controls on its title bar. The user cannot relegate this dialog box in the background because its WindowModality is set to ApplicationModal. import sys from PyQt4.QtGui import * from PyQt4.QtCore import * def window(): app = QApplication(sys.argv) w = QWidget() b = QPushButton(w) b.setText("Hello World!") b.move(50,50) b.clicked.connect(showdialog) w.setWindowTitle("PyQt Dialog demo") w.show() sys.exit(app.exec_()) def showdialog(): d = QDialog() b1 = QPushButton("ok",d) b1.move(50,50) d.setWindowTitle("Dialog") d.setWindowModality(Qt.ApplicationModal) d.exec_() if __name__ == '__main__': window() The above code produces the following output − 146 Lectures 22.5 hours ALAA EID Print Add Notes Bookmark this page
[ { "code": null, "e": 2136, "s": 1926, "text": "A QDialog widget presents a top level window mostly used to collect response from the user. It can be configured to be Modal (where it blocks its parent window) or Modeless (the dialog window can be bypassed)." }, { "code": null, "e": 2240, "s": 2136, "text": "PyQt API has a number of preconfigured Dialog widgets such as InputDialog, FileDialog, FontDialog, etc." }, { "code": null, "e": 2493, "s": 2240, "text": "In the following example, WindowModality attribute of Dialog window decides whether it is modal or modeless. Any one button on the dialog can be set to be default. The dialog is discarded by QDialog.reject() method when the user presses the Escape key." }, { "code": null, "e": 2652, "s": 2493, "text": "A PushButton on a top level QWidget window, when clicked, produces a Dialog window. A Dialog box doesn’t have minimize and maximize controls on its title bar." }, { "code": null, "e": 2766, "s": 2652, "text": "The user cannot relegate this dialog box in the background because its WindowModality is set to ApplicationModal." }, { "code": null, "e": 3283, "s": 2766, "text": "import sys\nfrom PyQt4.QtGui import *\nfrom PyQt4.QtCore import *\n\ndef window():\n app = QApplication(sys.argv)\n w = QWidget()\n b = QPushButton(w)\n b.setText(\"Hello World!\")\n b.move(50,50)\n b.clicked.connect(showdialog)\n w.setWindowTitle(\"PyQt Dialog demo\")\n w.show()\n sys.exit(app.exec_())\n\t\ndef showdialog():\n d = QDialog()\n b1 = QPushButton(\"ok\",d)\n b1.move(50,50)\n d.setWindowTitle(\"Dialog\")\n d.setWindowModality(Qt.ApplicationModal)\n d.exec_()\n\t\nif __name__ == '__main__':\n window()" }, { "code": null, "e": 3330, "s": 3283, "text": "The above code produces the following output −" }, { "code": null, "e": 3367, "s": 3330, "text": "\n 146 Lectures \n 22.5 hours \n" }, { "code": null, "e": 3377, "s": 3367, "text": " ALAA EID" }, { "code": null, "e": 3384, "s": 3377, "text": " Print" }, { "code": null, "e": 3395, "s": 3384, "text": " Add Notes" } ]
Remove all duplicates from a given string in Python - GeeksforGeeks
13 Apr, 2022 We are given a string and we need to remove all duplicates from it? What will be the output if the order of character matters? Examples: Input : geeksforgeeksOutput : efgkors This problem has existing solution please refer Remove all duplicates from a given string.Method 1: from collections import OrderedDict # Function to remove all duplicates from string # and order does not matter def removeDupWithoutOrder(str): # set() --> A Set is an unordered collection # data type that is iterable, mutable, # and has no duplicate elements. # "".join() --> It joins two adjacent elements in # iterable with any symbol defined in # "" ( double quotes ) and returns a # single string return "".join(set(str)) # Function to remove all duplicates from string # and keep the order of characters same def removeDupWithOrder(str): return "".join(OrderedDict.fromkeys(str)) # Driver program if __name__ == "__main__": str = "geeksforgeeks" print ("Without Order = ",removeDupWithoutOrder(str)) print ("With Order = ",removeDupWithOrder(str)) Output: Without Order = egfkosr With Order = geksfor Method 2: def removeDuplicate(str): s=set(str) s="".join(s) print("Without Order:",s) t="" for i in str: if(i in t): pass else: t=t+i print("With Order:",t) str="geeksforgeeks"removeDuplicate(str) Output: Without Order: rofgeks With Order: geksfor What do OrderedDict and fromkeys() do ? An OrderedDict is a dictionary that remembers the order of the keys that were inserted first. If a new entry overwrites an existing entry, the original insertion position is left unchanged. For example see below code snippet : from collections import OrderedDict ordinary_dictionary = {}ordinary_dictionary['a'] = 1ordinary_dictionary['b'] = 2ordinary_dictionary['c'] = 3ordinary_dictionary['d'] = 4ordinary_dictionary['e'] = 5 # Output = {'a': 1, 'c': 3, 'b': 2, 'e': 5, 'd': 4}print (ordinary_dictionary) ordered_dictionary = OrderedDict()ordered_dictionary['a'] = 1ordered_dictionary['b'] = 2ordered_dictionary['c'] = 3ordered_dictionary['d'] = 4ordered_dictionary['e'] = 5 # Output = {'a':1,'b':2,'c':3,'d':4,'e':5}print (ordered_dictionary) fromkeys() creates a new dictionary with keys from seq and values set to value and returns list of keys, fromkeys(seq[, value]) is the syntax for fromkeys() method. Parameters : seq : This is the list of values which would be used for dictionary keys preparation. value : This is optional, if provided then value would be set to this value. For example see below code snippet : from collections import OrderedDictseq = ('name', 'age', 'gender')dict = OrderedDict.fromkeys(seq) # Output = {'age': None, 'name': None, 'gender': None}print (str(dict)) dict = OrderedDict.fromkeys(seq, 10) # Output = {'age': 10, 'name': 10, 'gender': 10}print (str(dict)) This article is contributed by Shashank Mishra (Gullu). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. vs164758 raghavsarimisetty Python Strings Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Python String | replace() Write a program to reverse an array or string Reverse a string in Java Longest Common Subsequence | DP-4 C++ Data Types Write a program to print all permutations of a given string
[ { "code": null, "e": 25172, "s": 25144, "text": "\n13 Apr, 2022" }, { "code": null, "e": 25299, "s": 25172, "text": "We are given a string and we need to remove all duplicates from it? What will be the output if the order of character matters?" }, { "code": null, "e": 25309, "s": 25299, "text": "Examples:" }, { "code": null, "e": 25347, "s": 25309, "text": "Input : geeksforgeeksOutput : efgkors" }, { "code": null, "e": 25447, "s": 25347, "text": "This problem has existing solution please refer Remove all duplicates from a given string.Method 1:" }, { "code": "from collections import OrderedDict # Function to remove all duplicates from string # and order does not matter def removeDupWithoutOrder(str): # set() --> A Set is an unordered collection # data type that is iterable, mutable, # and has no duplicate elements. # \"\".join() --> It joins two adjacent elements in # iterable with any symbol defined in # \"\" ( double quotes ) and returns a # single string return \"\".join(set(str)) # Function to remove all duplicates from string # and keep the order of characters same def removeDupWithOrder(str): return \"\".join(OrderedDict.fromkeys(str)) # Driver program if __name__ == \"__main__\": str = \"geeksforgeeks\" print (\"Without Order = \",removeDupWithoutOrder(str)) print (\"With Order = \",removeDupWithOrder(str)) ", "e": 26309, "s": 25447, "text": null }, { "code": null, "e": 26317, "s": 26309, "text": "Output:" }, { "code": null, "e": 26368, "s": 26317, "text": "Without Order = egfkosr\nWith Order = geksfor\n" }, { "code": null, "e": 26378, "s": 26368, "text": "Method 2:" }, { "code": "def removeDuplicate(str): s=set(str) s=\"\".join(s) print(\"Without Order:\",s) t=\"\" for i in str: if(i in t): pass else: t=t+i print(\"With Order:\",t) str=\"geeksforgeeks\"removeDuplicate(str)", "e": 26628, "s": 26378, "text": null }, { "code": null, "e": 26636, "s": 26628, "text": "Output:" }, { "code": null, "e": 26679, "s": 26636, "text": "Without Order: rofgeks\nWith Order: geksfor" }, { "code": null, "e": 26719, "s": 26679, "text": "What do OrderedDict and fromkeys() do ?" }, { "code": null, "e": 26909, "s": 26719, "text": "An OrderedDict is a dictionary that remembers the order of the keys that were inserted first. If a new entry overwrites an existing entry, the original insertion position is left unchanged." }, { "code": null, "e": 26946, "s": 26909, "text": "For example see below code snippet :" }, { "code": "from collections import OrderedDict ordinary_dictionary = {}ordinary_dictionary['a'] = 1ordinary_dictionary['b'] = 2ordinary_dictionary['c'] = 3ordinary_dictionary['d'] = 4ordinary_dictionary['e'] = 5 # Output = {'a': 1, 'c': 3, 'b': 2, 'e': 5, 'd': 4}print (ordinary_dictionary) ordered_dictionary = OrderedDict()ordered_dictionary['a'] = 1ordered_dictionary['b'] = 2ordered_dictionary['c'] = 3ordered_dictionary['d'] = 4ordered_dictionary['e'] = 5 # Output = {'a':1,'b':2,'c':3,'d':4,'e':5}print (ordered_dictionary) ", "e": 27479, "s": 26946, "text": null }, { "code": null, "e": 27644, "s": 27479, "text": "fromkeys() creates a new dictionary with keys from seq and values set to value and returns list of keys, fromkeys(seq[, value]) is the syntax for fromkeys() method." }, { "code": null, "e": 27657, "s": 27644, "text": "Parameters :" }, { "code": null, "e": 27743, "s": 27657, "text": "seq : This is the list of values which would be used for dictionary keys preparation." }, { "code": null, "e": 27820, "s": 27743, "text": "value : This is optional, if provided then value would be set to this value." }, { "code": null, "e": 27857, "s": 27820, "text": "For example see below code snippet :" }, { "code": "from collections import OrderedDictseq = ('name', 'age', 'gender')dict = OrderedDict.fromkeys(seq) # Output = {'age': None, 'name': None, 'gender': None}print (str(dict)) dict = OrderedDict.fromkeys(seq, 10) # Output = {'age': 10, 'name': 10, 'gender': 10}print (str(dict)) ", "e": 28140, "s": 27857, "text": null }, { "code": null, "e": 28447, "s": 28140, "text": "This article is contributed by Shashank Mishra (Gullu). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 28572, "s": 28447, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 28581, "s": 28572, "text": "vs164758" }, { "code": null, "e": 28599, "s": 28581, "text": "raghavsarimisetty" }, { "code": null, "e": 28606, "s": 28599, "text": "Python" }, { "code": null, "e": 28614, "s": 28606, "text": "Strings" }, { "code": null, "e": 28622, "s": 28614, "text": "Strings" }, { "code": null, "e": 28720, "s": 28622, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28738, "s": 28720, "text": "Python Dictionary" }, { "code": null, "e": 28770, "s": 28738, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28792, "s": 28770, "text": "Enumerate() in Python" }, { "code": null, "e": 28834, "s": 28792, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28860, "s": 28834, "text": "Python String | replace()" }, { "code": null, "e": 28906, "s": 28860, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 28931, "s": 28906, "text": "Reverse a string in Java" }, { "code": null, "e": 28965, "s": 28931, "text": "Longest Common Subsequence | DP-4" }, { "code": null, "e": 28980, "s": 28965, "text": "C++ Data Types" } ]
Nagios - NRPE
The Nagios daemon which run checks on remote machines in NRPE (Nagios Remote Plugin Executor). It allows you to run Nagios plugins on other machines remotely. You can monitor remote machine metrics such as disk usage, CPU load etc. It can also check metrics of remote windows machines through some windows agent addons. Let us see how to install and configure NRPE step by step on client machine which needs to be monitored. Step 1 − Run below command to install NRPE on the remote linux machine to be monitored. sudo apt-get install nagios-nrpe-server nagios-plugins Step 2 − Now, create a host file inside the server directory, and put all the necessary definitions for the host. sudo gedit /usr/local/nagios/etc/servers/ubuntu_host.cfg # Ubuntu Host configuration file define host { use linux-server host_name ubuntu_host alias Ubuntu Host address 192.168.1.10 register 1 } define service { host_name ubuntu_host service_description PING check_command check_ping!100.0,20%!500.0,60% max_check_attempts 2 check_interval 2 retry_interval 2 check_period 24x7 check_freshness 1 contact_groups admins notification_interval 2 notification_period 24x7 notifications_enabled 1 register 1 } define service { host_name ubuntu_host service_description Check Users check_command check_local_users!20!50 max_check_attempts 2 check_interval 2 retry_interval 2 check_period 24x7 check_freshness 1 contact_groups admins notification_interval 2 notification_period 24x7 notifications_enabled 1 register 1 } define service { host_name ubuntu_host service_description Local Disk check_command check_local_disk!20%!10%!/ max_check_attempts 2 check_interval 2 retry_interval 2 check_period 24x7 check_freshness 1 groups admins notification_interval 2 notification_period 24x7 notifications_enabled 1 register 1 } define service { host_name ubuntu_host service_description Check SSH check_command check_ssh max_check_attempts 2 check_interval 2 retry_interval 2 check_period 24x7 check_freshness 1 contact_groups admins notification_interval 2 notification_period 24x7 notifications_enabled 1 register 1 } define service { host_name ubuntu_host service_description Total Process check_command check_local_procs!250!400!RSZDT max_check_attempts 2 check_interval 2 retry_interval 2 check_period 24x7 check_freshness 1 contact_groups admins notification_interval 2 notification_period 24x7 notifications_enabled 1 register 1 } Step 3 − Run the command shown below for the verification of configuration file. sudo /usr/local/nagios/bin/nagios -v /usr/local/nagios/etc/nagios.cfg Step 4 − Restart NRPE, Apache and Nagios if there are no errors. service nagios-nrpe-server restart service apache2 restart service nagios restart Step 5 − Open your browser and go to Nagios web interface. You can see the host which needs to be monitored has been added to Nagios core service. Similarly, you can add more hosts to be monitored by Nagios. Print Add Notes Bookmark this page
[ { "code": null, "e": 2216, "s": 1896, "text": "The Nagios daemon which run checks on remote machines in NRPE (Nagios Remote Plugin Executor). It allows you to run Nagios plugins on other machines remotely. You can monitor remote machine metrics such as disk usage, CPU load etc. It can also check metrics of remote windows machines through some windows agent addons." }, { "code": null, "e": 2321, "s": 2216, "text": "Let us see how to install and configure NRPE step by step on client machine which needs to be monitored." }, { "code": null, "e": 2409, "s": 2321, "text": "Step 1 − Run below command to install NRPE on the remote linux machine to be monitored." }, { "code": null, "e": 2465, "s": 2409, "text": "sudo apt-get install nagios-nrpe-server nagios-plugins\n" }, { "code": null, "e": 2579, "s": 2465, "text": "Step 2 − Now, create a host file inside the server directory, and put all the necessary definitions for the host." }, { "code": null, "e": 2637, "s": 2579, "text": "sudo gedit /usr/local/nagios/etc/servers/ubuntu_host.cfg\n" }, { "code": null, "e": 4519, "s": 2637, "text": "# Ubuntu Host configuration file\n\ndefine host {\n use linux-server\n host_name ubuntu_host\n alias Ubuntu Host\n address 192.168.1.10\n register 1\n}\n\ndefine service {\n host_name ubuntu_host\n service_description PING\n check_command check_ping!100.0,20%!500.0,60%\n max_check_attempts 2\n check_interval 2\n retry_interval 2\n check_period 24x7\n check_freshness 1\n contact_groups admins\n notification_interval 2\n notification_period 24x7\n notifications_enabled 1\n register 1\n}\n\ndefine service {\n host_name ubuntu_host\n service_description Check Users\n check_command check_local_users!20!50\n max_check_attempts 2\n check_interval 2\n retry_interval 2\n check_period 24x7\n check_freshness 1\n contact_groups admins\n notification_interval 2\n notification_period 24x7\n notifications_enabled 1\n register 1\n}\n\ndefine service {\n host_name ubuntu_host\n service_description Local Disk\n check_command check_local_disk!20%!10%!/\n max_check_attempts 2\n check_interval 2\n retry_interval 2\n check_period 24x7\n check_freshness 1\n groups admins\n notification_interval 2\n notification_period 24x7\n notifications_enabled 1\n register 1\n}\n\ndefine service {\n host_name ubuntu_host\n service_description Check SSH\n check_command check_ssh\n max_check_attempts 2\n check_interval 2\n retry_interval 2\n check_period 24x7\n check_freshness 1\n contact_groups admins\n notification_interval 2\n notification_period 24x7\n notifications_enabled 1\n register 1\n}\n\ndefine service {\n host_name ubuntu_host\n service_description Total Process\n check_command check_local_procs!250!400!RSZDT\n max_check_attempts 2\n check_interval 2\n retry_interval 2\n check_period 24x7\n check_freshness 1\n contact_groups admins\n notification_interval 2\n notification_period 24x7\n notifications_enabled 1\n register 1\n}" }, { "code": null, "e": 4600, "s": 4519, "text": "Step 3 − Run the command shown below for the verification of configuration file." }, { "code": null, "e": 4671, "s": 4600, "text": "sudo /usr/local/nagios/bin/nagios -v /usr/local/nagios/etc/nagios.cfg\n" }, { "code": null, "e": 4736, "s": 4671, "text": "Step 4 − Restart NRPE, Apache and Nagios if there are no errors." }, { "code": null, "e": 4819, "s": 4736, "text": "service nagios-nrpe-server restart\nservice apache2 restart\nservice nagios restart\n" }, { "code": null, "e": 5027, "s": 4819, "text": "Step 5 − Open your browser and go to Nagios web interface. You can see the host which needs to be monitored has been added to Nagios core service. Similarly, you can add more hosts to be monitored by Nagios." }, { "code": null, "e": 5034, "s": 5027, "text": " Print" }, { "code": null, "e": 5045, "s": 5034, "text": " Add Notes" } ]
Python | Multiple indices Replace in String - GeeksforGeeks
22 Apr, 2020 Sometimes, while working with Python Stings, we can have a problem, in which we need to perform the replace of characters based on several indices of String. This kind of problem can have applications in many domains. Lets discuss certain ways in which this task can be performed. Method #1 : Using loop + join()This is brute force way in which this task can be performed. In this, we iterate for each character and substitute with replace character if that is one. # Python3 code to demonstrate working of # Multiple indices Replace in String# Using loop + join() # initializing stringtest_str = 'geeksforgeeks is best' # printing original stringprint("The original string is : " + test_str) # initializing list test_list = [2, 4, 7, 10] # initializing repl charrepl_char = '*' # Multiple indices Replace in String# Using loop + join()temp = list(test_str)for idx in test_list: temp[idx] = repl_charres = ''.join(temp) # printing result print("The String after performing replace : " + str(res)) The original string is : geeksforgeeks is best The String after performing replace : ge*k*fo*ge*ks is best Method #2 : Using list comprehension + join()The combination of above functions can also be used to perform this task. In this, we perform similar task as above, just in one liner format using list comprehension. # Python3 code to demonstrate working of # Multiple indices Replace in String# Using list comprehension + join() # initializing stringtest_str = 'geeksforgeeks is best' # printing original stringprint("The original string is : " + test_str) # initializing list test_list = [2, 4, 7, 10] # initializing repl charrepl_char = '*' # Multiple indices Replace in String# Using list comprehension + join()temp = list(test_str)res = [repl_char if idx in test_list else ele for idx, ele in enumerate(temp)]res = ''.join(res) # printing result print("The String after performing replace : " + str(res)) The original string is : geeksforgeeks is best The String after performing replace : ge*k*fo*ge*ks is best Python string-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Reading and Writing to text files in Python Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary How to print without newline in Python?
[ { "code": null, "e": 26197, "s": 26169, "text": "\n22 Apr, 2020" }, { "code": null, "e": 26478, "s": 26197, "text": "Sometimes, while working with Python Stings, we can have a problem, in which we need to perform the replace of characters based on several indices of String. This kind of problem can have applications in many domains. Lets discuss certain ways in which this task can be performed." }, { "code": null, "e": 26663, "s": 26478, "text": "Method #1 : Using loop + join()This is brute force way in which this task can be performed. In this, we iterate for each character and substitute with replace character if that is one." }, { "code": "# Python3 code to demonstrate working of # Multiple indices Replace in String# Using loop + join() # initializing stringtest_str = 'geeksforgeeks is best' # printing original stringprint(\"The original string is : \" + test_str) # initializing list test_list = [2, 4, 7, 10] # initializing repl charrepl_char = '*' # Multiple indices Replace in String# Using loop + join()temp = list(test_str)for idx in test_list: temp[idx] = repl_charres = ''.join(temp) # printing result print(\"The String after performing replace : \" + str(res)) ", "e": 27204, "s": 26663, "text": null }, { "code": null, "e": 27312, "s": 27204, "text": "The original string is : geeksforgeeks is best\nThe String after performing replace : ge*k*fo*ge*ks is best\n" }, { "code": null, "e": 27527, "s": 27314, "text": "Method #2 : Using list comprehension + join()The combination of above functions can also be used to perform this task. In this, we perform similar task as above, just in one liner format using list comprehension." }, { "code": "# Python3 code to demonstrate working of # Multiple indices Replace in String# Using list comprehension + join() # initializing stringtest_str = 'geeksforgeeks is best' # printing original stringprint(\"The original string is : \" + test_str) # initializing list test_list = [2, 4, 7, 10] # initializing repl charrepl_char = '*' # Multiple indices Replace in String# Using list comprehension + join()temp = list(test_str)res = [repl_char if idx in test_list else ele for idx, ele in enumerate(temp)]res = ''.join(res) # printing result print(\"The String after performing replace : \" + str(res)) ", "e": 28127, "s": 27527, "text": null }, { "code": null, "e": 28235, "s": 28127, "text": "The original string is : geeksforgeeks is best\nThe String after performing replace : ge*k*fo*ge*ks is best\n" }, { "code": null, "e": 28258, "s": 28235, "text": "Python string-programs" }, { "code": null, "e": 28265, "s": 28258, "text": "Python" }, { "code": null, "e": 28281, "s": 28265, "text": "Python Programs" }, { "code": null, "e": 28379, "s": 28281, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28397, "s": 28379, "text": "Python Dictionary" }, { "code": null, "e": 28429, "s": 28397, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28451, "s": 28429, "text": "Enumerate() in Python" }, { "code": null, "e": 28493, "s": 28451, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28537, "s": 28493, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 28559, "s": 28537, "text": "Defaultdict in Python" }, { "code": null, "e": 28598, "s": 28559, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 28644, "s": 28598, "text": "Python | Split string into list of characters" }, { "code": null, "e": 28682, "s": 28644, "text": "Python | Convert a list to dictionary" } ]
C Program Addition and Subtraction without using + - Operators
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 We can do addition and subtraction without using +,- operators in C Language. #include<stdio.h> int addition(int x, int y) { int a, b; do { a = x & y; b = x ^ y; x = a << 1; y = b; } while (a); return b; } int main(void) { printf("10+20 = %d", addition(10, 20)); return 0; } Output: 10+20 = 30 #include<stdio.h> int sub(int x, int y) { unsigned a, b; do { a = ~x & y; b = x ^ y; x = b; y = a << 1; } while (a); return b; } int main(void) { printf("10 - 20 = %d", sub(10, 20)); return 0; } Output: 10 - 20 = -10 Happy Learning 🙂 C Program – Addition of two Matrices Example Java Program For Binary Addition C Program – Bubble Sort Program in C C Program – Given number is Even or Odd C Program – Reverse of a number C Program – Find GCD of two numbers C Program to add elements of an array C Program – Multiplication of two Matrices Example PHP Operators Example Tutorials Python Operators Example C Program – Ways to Generate Fibonacci Series C Program – Print the sum of digits of given number C Program – Sum of digits of given number till single digit C Program – Check a number is Palindrome or not C Program – Find the factorial of given number C Program – Addition of two Matrices Example Java Program For Binary Addition C Program – Bubble Sort Program in C C Program – Given number is Even or Odd C Program – Reverse of a number C Program – Find GCD of two numbers C Program to add elements of an array C Program – Multiplication of two Matrices Example PHP Operators Example Tutorials Python Operators Example C Program – Ways to Generate Fibonacci Series C Program – Print the sum of digits of given number C Program – Sum of digits of given number till single digit C Program – Check a number is Palindrome or not C Program – Find the factorial of given number Δ C – Introduction C – Features C – Variables & Keywords C – Program Structure C – Comment Lines & Tokens C – Number System C – Local and Global Variables C – Scope & Lifetime of Variables C – Data Types C – Integer Data Types C – Floating Data Types C – Derived, Defined Data Types C – Type Conversions C – Arithmetic Operators C – Bitwise Operators C – Logical Operators C – Comma and sizeof Operators C – Operator Precedence and Associativity C – Relational Operators C Flow Control – if, if-else, nested if-else, if-else-if C – Switch Case C Iterative – for, while, dowhile loops C Unconditional – break, continue, goto statements C – Expressions and Statements C – Header Files & Preprocessor Directives C – One Dimensional Arrays C – Multi Dimensional Arrays C – Pointers Basics C – Pointers with Arrays C – Functions C – How to Pass Arrays to Functions C – Categories of Functions C – User defined Functions C – Formal and Actual Arguments C – Recursion functions C – Structures Part -1 C – Structures Part -2 C – Unions C – File Handling C – File Operations C – Dynamic Memory Allocation C Program – Fibonacci Series C Program – Prime or Not C Program – Factorial of Number C Program – Even or Odd C Program – Sum of digits till Single Digit C Program – Sum of digits C Program – Reverse of a number C Program – Armstrong Numbers C Program – Print prime Numbers C Program – GCD of two Numbers C Program – Number Palindrome or Not C Program – Find Largest and Smallest number in an Array C Program – Add elements of an Array C Program – Addition of Matrices C Program – Multiplication of Matrices C Program – Reverse of an Array C Program – Bubble Sort C Program – Add and Sub without using + –
[ { "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": 476, "s": 398, "text": "We can do addition and subtraction without using +,- operators in C Language." }, { "code": null, "e": 715, "s": 476, "text": "#include<stdio.h>\n int addition(int x, int y) {\n int a, b;\n do {\n a = x & y;\n b = x ^ y;\n x = a << 1;\n y = b;\n } while (a);\n return b;\n }\n int main(void) {\n printf(\"10+20 = %d\", addition(10, 20));\n return 0;\n }" }, { "code": null, "e": 723, "s": 715, "text": "Output:" }, { "code": null, "e": 734, "s": 723, "text": "10+20 = 30" }, { "code": null, "e": 959, "s": 734, "text": "#include<stdio.h> \n\nint sub(int x, int y) {\n unsigned a, b;\n do {\n a = ~x & y;\n b = x ^ y;\n x = b;\n y = a << 1;\n } while (a);\n return b;\n}\nint main(void) {\n printf(\"10 - 20 = %d\", sub(10, 20));\n return 0;\n}" }, { "code": null, "e": 967, "s": 959, "text": "Output:" }, { "code": null, "e": 981, "s": 967, "text": "10 - 20 = -10" }, { "code": null, "e": 998, "s": 981, "text": "Happy Learning 🙂" }, { "code": null, "e": 1622, "s": 998, "text": "\nC Program – Addition of two Matrices Example\nJava Program For Binary Addition\nC Program – Bubble Sort Program in C\nC Program – Given number is Even or Odd\nC Program – Reverse of a number\nC Program – Find GCD of two numbers\nC Program to add elements of an array\nC Program – Multiplication of two Matrices Example\nPHP Operators Example Tutorials\nPython Operators Example\nC Program – Ways to Generate Fibonacci Series\nC Program – Print the sum of digits of given number\nC Program – Sum of digits of given number till single digit\nC Program – Check a number is Palindrome or not\nC Program – Find the factorial of given number\n" }, { "code": null, "e": 1667, "s": 1622, "text": "C Program – Addition of two Matrices Example" }, { "code": null, "e": 1700, "s": 1667, "text": "Java Program For Binary Addition" }, { "code": null, "e": 1737, "s": 1700, "text": "C Program – Bubble Sort Program in C" }, { "code": null, "e": 1777, "s": 1737, "text": "C Program – Given number is Even or Odd" }, { "code": null, "e": 1809, "s": 1777, "text": "C Program – Reverse of a number" }, { "code": null, "e": 1845, "s": 1809, "text": "C Program – Find GCD of two numbers" }, { "code": null, "e": 1883, "s": 1845, "text": "C Program to add elements of an array" }, { "code": null, "e": 1934, "s": 1883, "text": "C Program – Multiplication of two Matrices Example" }, { "code": null, "e": 1966, "s": 1934, "text": "PHP Operators Example Tutorials" }, { "code": null, "e": 1991, "s": 1966, "text": "Python Operators Example" }, { "code": null, "e": 2037, "s": 1991, "text": "C Program – Ways to Generate Fibonacci Series" }, { "code": null, "e": 2089, "s": 2037, "text": "C Program – Print the sum of digits of given number" }, { "code": null, "e": 2149, "s": 2089, "text": "C Program – Sum of digits of given number till single digit" }, { "code": null, "e": 2197, "s": 2149, "text": "C Program – Check a number is Palindrome or not" }, { "code": null, "e": 2244, "s": 2197, "text": "C Program – Find the factorial of given number" }, { "code": null, "e": 2250, "s": 2248, "text": "Δ" }, { "code": null, "e": 2268, "s": 2250, "text": " C – Introduction" }, { "code": null, "e": 2282, "s": 2268, "text": " C – Features" }, { "code": null, "e": 2308, "s": 2282, "text": " C – Variables & Keywords" }, { "code": null, "e": 2331, "s": 2308, "text": " C – Program Structure" }, { "code": null, "e": 2360, "s": 2331, "text": " C – Comment Lines & Tokens" }, { "code": null, "e": 2379, "s": 2360, "text": " C – Number System" }, { "code": null, "e": 2411, "s": 2379, "text": " C – Local and Global Variables" }, { "code": null, "e": 2446, "s": 2411, "text": " C – Scope & Lifetime of Variables" }, { "code": null, "e": 2462, "s": 2446, "text": " C – Data Types" }, { "code": null, "e": 2486, "s": 2462, "text": " C – Integer Data Types" }, { "code": null, "e": 2511, "s": 2486, "text": " C – Floating Data Types" }, { "code": null, "e": 2544, "s": 2511, "text": " C – Derived, Defined Data Types" }, { "code": null, "e": 2566, "s": 2544, "text": " C – Type Conversions" }, { "code": null, "e": 2592, "s": 2566, "text": " C – Arithmetic Operators" }, { "code": null, "e": 2615, "s": 2592, "text": " C – Bitwise Operators" }, { "code": null, "e": 2638, "s": 2615, "text": " C – Logical Operators" }, { "code": null, "e": 2671, "s": 2638, "text": " C – Comma and sizeof Operators" }, { "code": null, "e": 2714, "s": 2671, "text": " C – Operator Precedence and Associativity" }, { "code": null, "e": 2740, "s": 2714, "text": " C – Relational Operators" }, { "code": null, "e": 2798, "s": 2740, "text": " C Flow Control – if, if-else, nested if-else, if-else-if" }, { "code": null, "e": 2815, "s": 2798, "text": " C – Switch Case" }, { "code": null, "e": 2856, "s": 2815, "text": " C Iterative – for, while, dowhile loops" }, { "code": null, "e": 2908, "s": 2856, "text": " C Unconditional – break, continue, goto statements" }, { "code": null, "e": 2940, "s": 2908, "text": " C – Expressions and Statements" }, { "code": null, "e": 2984, "s": 2940, "text": " C – Header Files & Preprocessor Directives" }, { "code": null, "e": 3012, "s": 2984, "text": " C – One Dimensional Arrays" }, { "code": null, "e": 3042, "s": 3012, "text": " C – Multi Dimensional Arrays" }, { "code": null, "e": 3063, "s": 3042, "text": " C – Pointers Basics" }, { "code": null, "e": 3089, "s": 3063, "text": " C – Pointers with Arrays" }, { "code": null, "e": 3104, "s": 3089, "text": " C – Functions" }, { "code": null, "e": 3141, "s": 3104, "text": " C – How to Pass Arrays to Functions" }, { "code": null, "e": 3170, "s": 3141, "text": " C – Categories of Functions" }, { "code": null, "e": 3198, "s": 3170, "text": " C – User defined Functions" }, { "code": null, "e": 3231, "s": 3198, "text": " C – Formal and Actual Arguments" }, { "code": null, "e": 3256, "s": 3231, "text": " C – Recursion functions" }, { "code": null, "e": 3280, "s": 3256, "text": " C – Structures Part -1" }, { "code": null, "e": 3304, "s": 3280, "text": " C – Structures Part -2" }, { "code": null, "e": 3316, "s": 3304, "text": " C – Unions" }, { "code": null, "e": 3335, "s": 3316, "text": " C – File Handling" }, { "code": null, "e": 3356, "s": 3335, "text": " C – File Operations" }, { "code": null, "e": 3387, "s": 3356, "text": " C – Dynamic Memory Allocation" }, { "code": null, "e": 3417, "s": 3387, "text": " C Program – Fibonacci Series" }, { "code": null, "e": 3443, "s": 3417, "text": " C Program – Prime or Not" }, { "code": null, "e": 3476, "s": 3443, "text": " C Program – Factorial of Number" }, { "code": null, "e": 3501, "s": 3476, "text": " C Program – Even or Odd" }, { "code": null, "e": 3546, "s": 3501, "text": " C Program – Sum of digits till Single Digit" }, { "code": null, "e": 3573, "s": 3546, "text": " C Program – Sum of digits" }, { "code": null, "e": 3606, "s": 3573, "text": " C Program – Reverse of a number" }, { "code": null, "e": 3637, "s": 3606, "text": " C Program – Armstrong Numbers" }, { "code": null, "e": 3670, "s": 3637, "text": " C Program – Print prime Numbers" }, { "code": null, "e": 3702, "s": 3670, "text": " C Program – GCD of two Numbers" }, { "code": null, "e": 3740, "s": 3702, "text": " C Program – Number Palindrome or Not" }, { "code": null, "e": 3798, "s": 3740, "text": " C Program – Find Largest and Smallest number in an Array" }, { "code": null, "e": 3836, "s": 3798, "text": " C Program – Add elements of an Array" }, { "code": null, "e": 3870, "s": 3836, "text": " C Program – Addition of Matrices" }, { "code": null, "e": 3910, "s": 3870, "text": " C Program – Multiplication of Matrices" }, { "code": null, "e": 3943, "s": 3910, "text": " C Program – Reverse of an Array" }, { "code": null, "e": 3968, "s": 3943, "text": " C Program – Bubble Sort" } ]
Convex Hull | Monotone chain algorithm - GeeksforGeeks
27 Jul, 2021 Given a set of points, the task is to find the convex hull of the given points. The convex hull is the smallest convex polygon that contains all the points. Please check this article first: Convex Hull | Set 1 (Jarvis’s Algorithm or Wrapping) Examples: Input: Points[] = {{0, 3}, {2, 2}, {1, 1}, {2, 1}, {3, 0}, {0, 0}, {3, 3}} Output: (0, 0) (3, 0) (3, 3) (0, 3) Approach: Monotone chain algorithm constructs the convex hull in O(n * log(n)) time. We have to sort the points first and then calculate the upper and lower hulls in O(n) time. The points will be sorted with respect to x-coordinates (with respect to y-coordinates in case of a tie in x-coordinates), we will then find the left most point and then try to rotate in clockwise direction and find the next point and then repeat the step until we reach the rightmost point and then again rotate in the the clockwise direction and find the lower hull.Below is the implementation of the above approach: CPP // C++ implementation of the approach#include <bits/stdc++.h>#define llu long long intusing namespace std; struct Point { llu x, y; bool operator<(Point p) { return x < p.x || (x == p.x && y < p.y); }}; // Cross product of two vectors OA and OB// returns positive for counter clockwise// turn and negative for clockwise turnllu cross_product(Point O, Point A, Point B){ return (A.x - O.x) * (B.y - O.y) - (A.y - O.y) * (B.x - O.x);} // Returns a list of points on the convex hull// in counter-clockwise ordervector<Point> convex_hull(vector<Point> A){ int n = A.size(), k = 0; if (n <= 3) return A; vector<Point> ans(2 * n); // Sort points lexicographically sort(A.begin(), A.end()); // Build lower hull for (int i = 0; i < n; ++i) { // If the point at K-1 position is not a part // of hull as vector from ans[k-2] to ans[k-1] // and ans[k-2] to A[i] has a clockwise turn while (k >= 2 && cross_product(ans[k - 2], ans[k - 1], A[i]) <= 0) k--; ans[k++] = A[i]; } // Build upper hull for (size_t i = n - 1, t = k + 1; i > 0; --i) { // If the point at K-1 position is not a part // of hull as vector from ans[k-2] to ans[k-1] // and ans[k-2] to A[i] has a clockwise turn while (k >= t && cross_product(ans[k - 2], ans[k - 1], A[i - 1]) <= 0) k--; ans[k++] = A[i - 1]; } // Resize the array to desired size ans.resize(k - 1); return ans;} // Driver codeint main(){ vector<Point> points; // Add points points.push_back({ 0, 3 }); points.push_back({ 2, 2 }); points.push_back({ 1, 1 }); points.push_back({ 2, 1 }); points.push_back({ 3, 0 }); points.push_back({ 0, 0 }); points.push_back({ 3, 3 }); // Find the convex hull vector<Point> ans = convex_hull(points); // Print the convex hull for (int i = 0; i < ans.size(); i++) cout << "(" << ans[i].x << ", " << ans[i].y << ")" << endl; return 0;} (0, 0) (3, 0) (3, 3) (0, 3) surinderdawra388 Competitive Programming Geometric Sorting Sorting Geometric Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Multistage Graph (Shortest Path) Breadth First Traversal ( BFS ) on a 2D array Difference between Backtracking and Branch-N-Bound technique 5 Best Languages for Competitive Programming Minimum changes required to make all Array elements Prime How to check if a given point lies inside or outside a polygon? Closest Pair of Points using Divide and Conquer algorithm Program for distance between two points on earth How to check if two given line segments intersect? Convex Hull | Set 1 (Jarvis's Algorithm or Wrapping)
[ { "code": null, "e": 26467, "s": 26439, "text": "\n27 Jul, 2021" }, { "code": null, "e": 26712, "s": 26467, "text": "Given a set of points, the task is to find the convex hull of the given points. The convex hull is the smallest convex polygon that contains all the points. Please check this article first: Convex Hull | Set 1 (Jarvis’s Algorithm or Wrapping) " }, { "code": null, "e": 26722, "s": 26712, "text": "Examples:" }, { "code": null, "e": 26835, "s": 26722, "text": "Input: Points[] = {{0, 3}, {2, 2}, {1, 1}, {2, 1}, {3, 0}, {0, 0}, {3, 3}} Output: (0, 0) (3, 0) (3, 3) (0, 3) " }, { "code": null, "e": 27434, "s": 26837, "text": "Approach: Monotone chain algorithm constructs the convex hull in O(n * log(n)) time. We have to sort the points first and then calculate the upper and lower hulls in O(n) time. The points will be sorted with respect to x-coordinates (with respect to y-coordinates in case of a tie in x-coordinates), we will then find the left most point and then try to rotate in clockwise direction and find the next point and then repeat the step until we reach the rightmost point and then again rotate in the the clockwise direction and find the lower hull.Below is the implementation of the above approach: " }, { "code": null, "e": 27438, "s": 27434, "text": "CPP" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>#define llu long long intusing namespace std; struct Point { llu x, y; bool operator<(Point p) { return x < p.x || (x == p.x && y < p.y); }}; // Cross product of two vectors OA and OB// returns positive for counter clockwise// turn and negative for clockwise turnllu cross_product(Point O, Point A, Point B){ return (A.x - O.x) * (B.y - O.y) - (A.y - O.y) * (B.x - O.x);} // Returns a list of points on the convex hull// in counter-clockwise ordervector<Point> convex_hull(vector<Point> A){ int n = A.size(), k = 0; if (n <= 3) return A; vector<Point> ans(2 * n); // Sort points lexicographically sort(A.begin(), A.end()); // Build lower hull for (int i = 0; i < n; ++i) { // If the point at K-1 position is not a part // of hull as vector from ans[k-2] to ans[k-1] // and ans[k-2] to A[i] has a clockwise turn while (k >= 2 && cross_product(ans[k - 2], ans[k - 1], A[i]) <= 0) k--; ans[k++] = A[i]; } // Build upper hull for (size_t i = n - 1, t = k + 1; i > 0; --i) { // If the point at K-1 position is not a part // of hull as vector from ans[k-2] to ans[k-1] // and ans[k-2] to A[i] has a clockwise turn while (k >= t && cross_product(ans[k - 2], ans[k - 1], A[i - 1]) <= 0) k--; ans[k++] = A[i - 1]; } // Resize the array to desired size ans.resize(k - 1); return ans;} // Driver codeint main(){ vector<Point> points; // Add points points.push_back({ 0, 3 }); points.push_back({ 2, 2 }); points.push_back({ 1, 1 }); points.push_back({ 2, 1 }); points.push_back({ 3, 0 }); points.push_back({ 0, 0 }); points.push_back({ 3, 3 }); // Find the convex hull vector<Point> ans = convex_hull(points); // Print the convex hull for (int i = 0; i < ans.size(); i++) cout << \"(\" << ans[i].x << \", \" << ans[i].y << \")\" << endl; return 0;}", "e": 29553, "s": 27438, "text": null }, { "code": null, "e": 29581, "s": 29553, "text": "(0, 0)\n(3, 0)\n(3, 3)\n(0, 3)" }, { "code": null, "e": 29600, "s": 29583, "text": "surinderdawra388" }, { "code": null, "e": 29624, "s": 29600, "text": "Competitive Programming" }, { "code": null, "e": 29634, "s": 29624, "text": "Geometric" }, { "code": null, "e": 29642, "s": 29634, "text": "Sorting" }, { "code": null, "e": 29650, "s": 29642, "text": "Sorting" }, { "code": null, "e": 29660, "s": 29650, "text": "Geometric" }, { "code": null, "e": 29758, "s": 29660, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29791, "s": 29758, "text": "Multistage Graph (Shortest Path)" }, { "code": null, "e": 29837, "s": 29791, "text": "Breadth First Traversal ( BFS ) on a 2D array" }, { "code": null, "e": 29898, "s": 29837, "text": "Difference between Backtracking and Branch-N-Bound technique" }, { "code": null, "e": 29943, "s": 29898, "text": "5 Best Languages for Competitive Programming" }, { "code": null, "e": 30001, "s": 29943, "text": "Minimum changes required to make all Array elements Prime" }, { "code": null, "e": 30065, "s": 30001, "text": "How to check if a given point lies inside or outside a polygon?" }, { "code": null, "e": 30123, "s": 30065, "text": "Closest Pair of Points using Divide and Conquer algorithm" }, { "code": null, "e": 30172, "s": 30123, "text": "Program for distance between two points on earth" }, { "code": null, "e": 30223, "s": 30172, "text": "How to check if two given line segments intersect?" } ]
How to Create an Ogive Graph in Python? - GeeksforGeeks
08 Mar, 2021 In this article, we will create an Ogive Graph. An ogive graph can also be called as cumulative histograms, this graph is used to determine the number of values that lie above or below a particular value in a data set. The class interval is plotted on the x-axis whereas the cumulative frequency is plotted on the y-axis. These points are plotted on the graph and joined by lines. NumPy has a function named a histogram() that represents the frequency of data in a particular set range graphically. The histogram function returns two values first one is the frequency and which is stored in values and the second one is the bin values or the interval between which the numbers from the dataset lie, it is stored in the base variable. After this we will calculate the cumulative sum which can be done easily with the cumsum() function, it returns the cumulative sum along a particular axis. At last, we will plot the graph using plot() function and passing base as x-axis value and cumsum as y-axis value. We can format the graph using markers, color, and linestlye attributes. Example 1: (More than Ogive graph) The more than ogive graph shows the number of values greater than the class intervals. The resultant graph shows the number of values in between the class interval. Eg- 0-10,10-20 and so on. Let us take a dataset, and we will now plot it’s more than ogive graph- [22,87,5,43,56,73, 55,54,11,20,51,5,79,31,27]. Table representing intervals, frequency and cumulative frequency(less than)- Approach: Import the modules (matplotlib and numpy). Calculate the frequency and cumulative frequency of the data. Plot it using the plot() function. Python3 # importing modulesimport numpy as npimport matplotlib.pyplot as plt # creating datasetdata = [22, 87, 5, 43, 56, 73, 55, 54, 11, 20, 51, 5, 79, 31, 27] # creating class intervalclassInterval = [0, 10, 20, 30, 40, 50, 60, 70, 80, 90] # calculating frequency and class intervalvalues, base = np.histogram(data, bins=classInterval) # calculating cumulative sumcumsum = np.cumsum(values) # plotting the ogive graphplt.plot(base[1:], cumsum, color='red', marker='o', linestyle='-') # formattingplt.title('Ogive Graph')plt.xlabel('Marks in End-Term')plt.ylabel('Cumulative Frequency') Output: Example 2: (Less than Ogive Graph) In this example, we will plot less than Ogive graph which will show the less than values of class intervals. Dataset:[44,27,5,2,43,56,77,53,89,54,11,23, 51,5,79,25,39] Table representing intervals, frequency and cumulative frequency(more than)- Approach is same as above only the cumulative sum that we will calculate will be reversed using flipud() function present in the numpy library. Python3 # importing modulesimport numpy as npimport matplotlib.pyplot as plt # creating datasetdata = [44, 27, 5, 2, 43, 56, 77, 53, 89, 54, 11, 23, 51, 5, 79, 25, 39] # creating class intervalclassInterval = [0, 10, 20, 30, 40, 50, 60, 70, 80, 90] # calculating frequency and intervalsvalues, base = np.histogram(data, bins=classInterval) # calculating cumulative frequencycumsum = np.cumsum(values) # reversing cumulative frequencyres = np.flipud(cumsum) # plotting ogiveplt.plot(base[1:], res, color='brown', marker='o', linestyle='-') # formatting the graphplt.title('Ogive Graph')plt.xlabel('Marks in End-Term')plt.ylabel('Cumulative Frequency') Output: Data Visualization Picked Python-matplotlib Technical Scripter 2020 Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install PIP on Windows ? Selecting rows in pandas DataFrame based on conditions How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Get unique values from a list Defaultdict in Python Python OOPs Concepts Python | os.path.join() method Python | Pandas dataframe.groupby()
[ { "code": null, "e": 24316, "s": 24288, "text": "\n08 Mar, 2021" }, { "code": null, "e": 24697, "s": 24316, "text": "In this article, we will create an Ogive Graph. An ogive graph can also be called as cumulative histograms, this graph is used to determine the number of values that lie above or below a particular value in a data set. The class interval is plotted on the x-axis whereas the cumulative frequency is plotted on the y-axis. These points are plotted on the graph and joined by lines." }, { "code": null, "e": 25051, "s": 24697, "text": "NumPy has a function named a histogram() that represents the frequency of data in a particular set range graphically. The histogram function returns two values first one is the frequency and which is stored in values and the second one is the bin values or the interval between which the numbers from the dataset lie, it is stored in the base variable. " }, { "code": null, "e": 25394, "s": 25051, "text": "After this we will calculate the cumulative sum which can be done easily with the cumsum() function, it returns the cumulative sum along a particular axis. At last, we will plot the graph using plot() function and passing base as x-axis value and cumsum as y-axis value. We can format the graph using markers, color, and linestlye attributes." }, { "code": null, "e": 25429, "s": 25394, "text": "Example 1: (More than Ogive graph)" }, { "code": null, "e": 25739, "s": 25429, "text": "The more than ogive graph shows the number of values greater than the class intervals. The resultant graph shows the number of values in between the class interval. Eg- 0-10,10-20 and so on. Let us take a dataset, and we will now plot it’s more than ogive graph- [22,87,5,43,56,73, 55,54,11,20,51,5,79,31,27]." }, { "code": null, "e": 25816, "s": 25739, "text": "Table representing intervals, frequency and cumulative frequency(less than)-" }, { "code": null, "e": 25826, "s": 25816, "text": "Approach:" }, { "code": null, "e": 25869, "s": 25826, "text": "Import the modules (matplotlib and numpy)." }, { "code": null, "e": 25931, "s": 25869, "text": "Calculate the frequency and cumulative frequency of the data." }, { "code": null, "e": 25966, "s": 25931, "text": "Plot it using the plot() function." }, { "code": null, "e": 25974, "s": 25966, "text": "Python3" }, { "code": "# importing modulesimport numpy as npimport matplotlib.pyplot as plt # creating datasetdata = [22, 87, 5, 43, 56, 73, 55, 54, 11, 20, 51, 5, 79, 31, 27] # creating class intervalclassInterval = [0, 10, 20, 30, 40, 50, 60, 70, 80, 90] # calculating frequency and class intervalvalues, base = np.histogram(data, bins=classInterval) # calculating cumulative sumcumsum = np.cumsum(values) # plotting the ogive graphplt.plot(base[1:], cumsum, color='red', marker='o', linestyle='-') # formattingplt.title('Ogive Graph')plt.xlabel('Marks in End-Term')plt.ylabel('Cumulative Frequency')", "e": 26561, "s": 25974, "text": null }, { "code": null, "e": 26569, "s": 26561, "text": "Output:" }, { "code": null, "e": 26604, "s": 26569, "text": "Example 2: (Less than Ogive Graph)" }, { "code": null, "e": 26772, "s": 26604, "text": "In this example, we will plot less than Ogive graph which will show the less than values of class intervals. Dataset:[44,27,5,2,43,56,77,53,89,54,11,23, 51,5,79,25,39]" }, { "code": null, "e": 26849, "s": 26772, "text": "Table representing intervals, frequency and cumulative frequency(more than)-" }, { "code": null, "e": 26993, "s": 26849, "text": "Approach is same as above only the cumulative sum that we will calculate will be reversed using flipud() function present in the numpy library." }, { "code": null, "e": 27001, "s": 26993, "text": "Python3" }, { "code": "# importing modulesimport numpy as npimport matplotlib.pyplot as plt # creating datasetdata = [44, 27, 5, 2, 43, 56, 77, 53, 89, 54, 11, 23, 51, 5, 79, 25, 39] # creating class intervalclassInterval = [0, 10, 20, 30, 40, 50, 60, 70, 80, 90] # calculating frequency and intervalsvalues, base = np.histogram(data, bins=classInterval) # calculating cumulative frequencycumsum = np.cumsum(values) # reversing cumulative frequencyres = np.flipud(cumsum) # plotting ogiveplt.plot(base[1:], res, color='brown', marker='o', linestyle='-') # formatting the graphplt.title('Ogive Graph')plt.xlabel('Marks in End-Term')plt.ylabel('Cumulative Frequency')", "e": 27651, "s": 27001, "text": null }, { "code": null, "e": 27659, "s": 27651, "text": "Output:" }, { "code": null, "e": 27678, "s": 27659, "text": "Data Visualization" }, { "code": null, "e": 27685, "s": 27678, "text": "Picked" }, { "code": null, "e": 27703, "s": 27685, "text": "Python-matplotlib" }, { "code": null, "e": 27727, "s": 27703, "text": "Technical Scripter 2020" }, { "code": null, "e": 27734, "s": 27727, "text": "Python" }, { "code": null, "e": 27753, "s": 27734, "text": "Technical Scripter" }, { "code": null, "e": 27851, "s": 27753, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27860, "s": 27851, "text": "Comments" }, { "code": null, "e": 27873, "s": 27860, "text": "Old Comments" }, { "code": null, "e": 27905, "s": 27873, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27960, "s": 27905, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 28016, "s": 27960, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28058, "s": 28016, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 28100, "s": 28058, "text": "Check if element exists in list in Python" }, { "code": null, "e": 28139, "s": 28100, "text": "Python | Get unique values from a list" }, { "code": null, "e": 28161, "s": 28139, "text": "Defaultdict in Python" }, { "code": null, "e": 28182, "s": 28161, "text": "Python OOPs Concepts" }, { "code": null, "e": 28213, "s": 28182, "text": "Python | os.path.join() method" } ]
Doolittle Algorithm : LU Decomposition - GeeksforGeeks
12 Jun, 2021 In numerical analysis and linear algebra, LU decomposition (where ‘LU’ stands for ‘lower upper’, and also called LU factorization) factors a matrix as the product of a lower triangular matrix and an upper triangular matrix. Computers usually solve square systems of linear equations using the LU decomposition, and it is also a key step when inverting a matrix, or computing the determinant of a matrix. The LU decomposition was introduced by mathematician Tadeusz Banachiewicz in 1938. Let A be a square matrix. An LU factorization refers to the factorization of A, with proper row and/or column orderings or permutations, into two factors, a lower triangular matrix L and an upper triangular matrix U, A=LU. Doolittle Algorithm : It is always possible to factor a square matrix into a lower triangular matrix and an upper triangular matrix. That is, [A] = [L][U]Doolittle’s method provides an alternative way to factor A into an LU decomposition without going through the hassle of Gaussian Elimination.For a general n×n matrix A, we assume that an LU decomposition exists, and write the form of L and U explicitly. We then systematically solve for the entries in L and U from the equations that result from the multiplications necessary for A=LU. Terms of U matrix are given by: And the terms for L matrix: Example : Input : Output : C++ Java Python3 C# PHP Javascript // C++ Program to decompose a matrix into// lower and upper triangular matrix#include <bits/stdc++.h>using namespace std; const int MAX = 100; void luDecomposition(int mat[][MAX], int n){ int lower[n][n], upper[n][n]; memset(lower, 0, sizeof(lower)); memset(upper, 0, sizeof(upper)); // Decomposing matrix into Upper and Lower // triangular matrix for (int i = 0; i < n; i++) { // Upper Triangular for (int k = i; k < n; k++) { // Summation of L(i, j) * U(j, k) int sum = 0; for (int j = 0; j < i; j++) sum += (lower[i][j] * upper[j][k]); // Evaluating U(i, k) upper[i][k] = mat[i][k] - sum; } // Lower Triangular for (int k = i; k < n; k++) { if (i == k) lower[i][i] = 1; // Diagonal as 1 else { // Summation of L(k, j) * U(j, i) int sum = 0; for (int j = 0; j < i; j++) sum += (lower[k][j] * upper[j][i]); // Evaluating L(k, i) lower[k][i] = (mat[k][i] - sum) / upper[i][i]; } } } // setw is for displaying nicely cout << setw(6) << " Lower Triangular" << setw(32) << "Upper Triangular" << endl; // Displaying the result : for (int i = 0; i < n; i++) { // Lower for (int j = 0; j < n; j++) cout << setw(6) << lower[i][j] << "\t"; cout << "\t"; // Upper for (int j = 0; j < n; j++) cout << setw(6) << upper[i][j] << "\t"; cout << endl; }} // Driver codeint main(){ int mat[][MAX] = { { 2, -1, -2 }, { -4, 6, 3 }, { -4, -2, 8 } }; luDecomposition(mat, 3); return 0;} // Java Program to decompose a matrix into// lower and upper triangular matrixclass GFG { static int MAX = 100; static String s = ""; static void luDecomposition(int[][] mat, int n) { int[][] lower = new int[n][n]; int[][] upper = new int[n][n]; // Decomposing matrix into Upper and Lower // triangular matrix for (int i = 0; i < n; i++) { // Upper Triangular for (int k = i; k < n; k++) { // Summation of L(i, j) * U(j, k) int sum = 0; for (int j = 0; j < i; j++) sum += (lower[i][j] * upper[j][k]); // Evaluating U(i, k) upper[i][k] = mat[i][k] - sum; } // Lower Triangular for (int k = i; k < n; k++) { if (i == k) lower[i][i] = 1; // Diagonal as 1 else { // Summation of L(k, j) * U(j, i) int sum = 0; for (int j = 0; j < i; j++) sum += (lower[k][j] * upper[j][i]); // Evaluating L(k, i) lower[k][i] = (mat[k][i] - sum) / upper[i][i]; } } } // setw is for displaying nicely System.out.println(setw(2) + " Lower Triangular" + setw(10) + "Upper Triangular"); // Displaying the result : for (int i = 0; i < n; i++) { // Lower for (int j = 0; j < n; j++) System.out.print(setw(4) + lower[i][j] + "\t"); System.out.print("\t"); // Upper for (int j = 0; j < n; j++) System.out.print(setw(4) + upper[i][j] + "\t"); System.out.print("\n"); } } static String setw(int noOfSpace) { s = ""; for (int i = 0; i < noOfSpace; i++) s += " "; return s; } // Driver code public static void main(String arr[]) { int mat[][] = { { 2, -1, -2 }, { -4, 6, 3 }, { -4, -2, 8 } }; luDecomposition(mat, 3); }} /* This code contributed by PrinciRaj1992 */ # Python3 Program to decompose# a matrix into lower and# upper triangular matrixMAX = 100 def luDecomposition(mat, n): lower = [[0 for x in range(n)] for y in range(n)] upper = [[0 for x in range(n)] for y in range(n)] # Decomposing matrix into Upper # and Lower triangular matrix for i in range(n): # Upper Triangular for k in range(i, n): # Summation of L(i, j) * U(j, k) sum = 0 for j in range(i): sum += (lower[i][j] * upper[j][k]) # Evaluating U(i, k) upper[i][k] = mat[i][k] - sum # Lower Triangular for k in range(i, n): if (i == k): lower[i][i] = 1 # Diagonal as 1 else: # Summation of L(k, j) * U(j, i) sum = 0 for j in range(i): sum += (lower[k][j] * upper[j][i]) # Evaluating L(k, i) lower[k][i] = int((mat[k][i] - sum) / upper[i][i]) # setw is for displaying nicely print("Lower Triangular\t\tUpper Triangular") # Displaying the result : for i in range(n): # Lower for j in range(n): print(lower[i][j], end="\t") print("", end="\t") # Upper for j in range(n): print(upper[i][j], end="\t") print("") # Driver codemat = [[2, -1, -2], [-4, 6, 3], [-4, -2, 8]] luDecomposition(mat, 3) # This code is contributed by mits // C# Program to decompose a matrix into// lower and upper triangular matrixusing System; class GFG { static int MAX = 100; static String s = ""; static void luDecomposition(int[, ] mat, int n) { int[, ] lower = new int[n, n]; int[, ] upper = new int[n, n]; // Decomposing matrix into Upper and Lower // triangular matrix for (int i = 0; i < n; i++) { // Upper Triangular for (int k = i; k < n; k++) { // Summation of L(i, j) * U(j, k) int sum = 0; for (int j = 0; j < i; j++) sum += (lower[i, j] * upper[j, k]); // Evaluating U(i, k) upper[i, k] = mat[i, k] - sum; } // Lower Triangular for (int k = i; k < n; k++) { if (i == k) lower[i, i] = 1; // Diagonal as 1 else { // Summation of L(k, j) * U(j, i) int sum = 0; for (int j = 0; j < i; j++) sum += (lower[k, j] * upper[j, i]); // Evaluating L(k, i) lower[k, i] = (mat[k, i] - sum) / upper[i, i]; } } } // setw is for displaying nicely Console.WriteLine(setw(2) + " Lower Triangular" + setw(10) + "Upper Triangular"); // Displaying the result : for (int i = 0; i < n; i++) { // Lower for (int j = 0; j < n; j++) Console.Write(setw(4) + lower[i, j] + "\t"); Console.Write("\t"); // Upper for (int j = 0; j < n; j++) Console.Write(setw(4) + upper[i, j] + "\t"); Console.Write("\n"); } } static String setw(int noOfSpace) { s = ""; for (int i = 0; i < noOfSpace; i++) s += " "; return s; } // Driver code public static void Main(String[] arr) { int[, ] mat = { { 2, -1, -2 }, { -4, 6, 3 }, { -4, -2, 8 } }; luDecomposition(mat, 3); }} // This code is contributed by Princi Singh <?php// PHP Program to decompose// a matrix into lower and// upper triangular matrix$MAX = 100; function luDecomposition($mat, $n){ $lower; $upper; for($i = 0; $i < $n; $i++) for($j = 0; $j < $n; $j++) { $lower[$i][$j]= 0; $upper[$i][$j]= 0; } // Decomposing matrix // into Upper and Lower // triangular matrix for ($i = 0; $i < $n; $i++) { // Upper Triangular for ($k = $i; $k < $n; $k++) { // Summation of // L(i, j) * U(j, k) $sum = 0; for ($j = 0; $j < $i; $j++) $sum += ($lower[$i][$j] * $upper[$j][$k]); // Evaluating U(i, k) $upper[$i][$k] = $mat[$i][$k] - $sum; } // Lower Triangular for ($k = $i; $k < $n; $k++) { if ($i == $k) $lower[$i][$i] = 1; // Diagonal as 1 else { // Summation of L(k, j) * U(j, i) $sum = 0; for ($j = 0; $j < $i; $j++) $sum += ($lower[$k][$j] * $upper[$j][$i]); // Evaluating L(k, i) $lower[$k][$i] = (int)(($mat[$k][$i] - $sum) / $upper[$i][$i]); } } } // setw is for // displaying nicely echo "\t\tLower Triangular"; echo "\t\t\tUpper Triangular\n"; // Displaying the result : for ($i = 0; $i < $n; $i++) { // Lower for ($j = 0; $j < $n; $j++) echo "\t" . $lower[$i][$j] . "\t"; echo "\t"; // Upper for ($j = 0; $j < $n; $j++) echo $upper[$i][$j] . "\t"; echo "\n"; }} // Driver code$mat = array(array(2, -1, -2), array(-4, 6, 3), array(-4, -2, 8)); luDecomposition($mat, 3); // This code is contributed by mits?> <script> // Javascript Program to decompose a matrix// into lower and upper triangular matrix // function MAX = 100;var s = ""; function luDecomposition(mat, n){ var lower = Array(n).fill(0).map( x => Array(n).fill(0)); var upper = Array(n).fill(0).map( x => Array(n).fill(0)); // Decomposing matrix into Upper and // Lower triangular matrix for(var i = 0; i < n; i++) { // Upper Triangular for(var k = i; k < n; k++) { // Summation of L(i, j) * U(j, k) var sum = 0; for(var j = 0; j < i; j++) sum += (lower[i][j] * upper[j][k]); // Evaluating U(i, k) upper[i][k] = mat[i][k] - sum; } // Lower Triangular for(var k = i; k < n; k++) { if (i == k) // Diagonal as 1 lower[i][i] = 1; else { // Summation of L(k, j) * U(j, i) var sum = 0; for(var j = 0; j < i; j++) sum += (lower[k][j] * upper[j][i]); // Evaluating L(k, i) lower[k][i] = parseInt((mat[k][i] - sum) / upper[i][i]); } } } // Setw is for displaying nicely document.write(setw(2) + "Lower Triangular" + setw(10) + "Upper Triangular<br>"); // Displaying the result : for(var i = 0; i < n; i++) { // Lower for(var j = 0; j < n; j++) document.write(setw(4) + lower[i][j] + "\t"); document.write(setw(10)); // Upper for(var j = 0; j < n; j++) document.write(setw(4) + upper[i][j] + "\t"); document.write("<br>"); }} function setw(noOfSpace){ var s = ""; for(i = 0; i < noOfSpace; i++) s += " "; return s;} // Driver codevar mat = [ [ 2, -1, -2 ], [ -4, 6, 3 ], [ -4, -2, 8 ] ]; luDecomposition(mat, 3); // This code is contributed by Amit Katiyar </script> Output: Lower Triangular Upper Triangular 1 0 0 2 -1 -2 -2 1 0 0 4 -1 -2 -1 1 0 0 3 This article is contributed by Shubham Rana. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Mithun Kumar princiraj1992 princi singh jesaldkotak agchiper45 amit143katiyar simranarora5sos Engineering Mathematics Mathematical Matrix Mathematical Matrix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Inequalities in LaTeX Newton's Divided Difference Interpolation Formula Arrow Symbols in LaTeX Set Notations in LaTeX Activation Functions Program for Fibonacci numbers C++ Data Types Write a program to print all permutations of a given string Set in C++ Standard Template Library (STL) Coin Change | DP-7
[ { "code": null, "e": 30110, "s": 30082, "text": "\n12 Jun, 2021" }, { "code": null, "e": 30597, "s": 30110, "text": "In numerical analysis and linear algebra, LU decomposition (where ‘LU’ stands for ‘lower upper’, and also called LU factorization) factors a matrix as the product of a lower triangular matrix and an upper triangular matrix. Computers usually solve square systems of linear equations using the LU decomposition, and it is also a key step when inverting a matrix, or computing the determinant of a matrix. The LU decomposition was introduced by mathematician Tadeusz Banachiewicz in 1938." }, { "code": null, "e": 30821, "s": 30597, "text": "Let A be a square matrix. An LU factorization refers to the factorization of A, with proper row and/or column orderings or permutations, into two factors, a lower triangular matrix L and an upper triangular matrix U, A=LU. " }, { "code": null, "e": 31361, "s": 30821, "text": "Doolittle Algorithm : It is always possible to factor a square matrix into a lower triangular matrix and an upper triangular matrix. That is, [A] = [L][U]Doolittle’s method provides an alternative way to factor A into an LU decomposition without going through the hassle of Gaussian Elimination.For a general n×n matrix A, we assume that an LU decomposition exists, and write the form of L and U explicitly. We then systematically solve for the entries in L and U from the equations that result from the multiplications necessary for A=LU." }, { "code": null, "e": 31393, "s": 31361, "text": "Terms of U matrix are given by:" }, { "code": null, "e": 31423, "s": 31395, "text": "And the terms for L matrix:" }, { "code": null, "e": 31434, "s": 31423, "text": "Example : " }, { "code": null, "e": 31443, "s": 31434, "text": "Input : " }, { "code": null, "e": 31452, "s": 31443, "text": "Output :" }, { "code": null, "e": 31456, "s": 31452, "text": "C++" }, { "code": null, "e": 31461, "s": 31456, "text": "Java" }, { "code": null, "e": 31469, "s": 31461, "text": "Python3" }, { "code": null, "e": 31472, "s": 31469, "text": "C#" }, { "code": null, "e": 31476, "s": 31472, "text": "PHP" }, { "code": null, "e": 31487, "s": 31476, "text": "Javascript" }, { "code": "// C++ Program to decompose a matrix into// lower and upper triangular matrix#include <bits/stdc++.h>using namespace std; const int MAX = 100; void luDecomposition(int mat[][MAX], int n){ int lower[n][n], upper[n][n]; memset(lower, 0, sizeof(lower)); memset(upper, 0, sizeof(upper)); // Decomposing matrix into Upper and Lower // triangular matrix for (int i = 0; i < n; i++) { // Upper Triangular for (int k = i; k < n; k++) { // Summation of L(i, j) * U(j, k) int sum = 0; for (int j = 0; j < i; j++) sum += (lower[i][j] * upper[j][k]); // Evaluating U(i, k) upper[i][k] = mat[i][k] - sum; } // Lower Triangular for (int k = i; k < n; k++) { if (i == k) lower[i][i] = 1; // Diagonal as 1 else { // Summation of L(k, j) * U(j, i) int sum = 0; for (int j = 0; j < i; j++) sum += (lower[k][j] * upper[j][i]); // Evaluating L(k, i) lower[k][i] = (mat[k][i] - sum) / upper[i][i]; } } } // setw is for displaying nicely cout << setw(6) << \" Lower Triangular\" << setw(32) << \"Upper Triangular\" << endl; // Displaying the result : for (int i = 0; i < n; i++) { // Lower for (int j = 0; j < n; j++) cout << setw(6) << lower[i][j] << \"\\t\"; cout << \"\\t\"; // Upper for (int j = 0; j < n; j++) cout << setw(6) << upper[i][j] << \"\\t\"; cout << endl; }} // Driver codeint main(){ int mat[][MAX] = { { 2, -1, -2 }, { -4, 6, 3 }, { -4, -2, 8 } }; luDecomposition(mat, 3); return 0;}", "e": 33311, "s": 31487, "text": null }, { "code": "// Java Program to decompose a matrix into// lower and upper triangular matrixclass GFG { static int MAX = 100; static String s = \"\"; static void luDecomposition(int[][] mat, int n) { int[][] lower = new int[n][n]; int[][] upper = new int[n][n]; // Decomposing matrix into Upper and Lower // triangular matrix for (int i = 0; i < n; i++) { // Upper Triangular for (int k = i; k < n; k++) { // Summation of L(i, j) * U(j, k) int sum = 0; for (int j = 0; j < i; j++) sum += (lower[i][j] * upper[j][k]); // Evaluating U(i, k) upper[i][k] = mat[i][k] - sum; } // Lower Triangular for (int k = i; k < n; k++) { if (i == k) lower[i][i] = 1; // Diagonal as 1 else { // Summation of L(k, j) * U(j, i) int sum = 0; for (int j = 0; j < i; j++) sum += (lower[k][j] * upper[j][i]); // Evaluating L(k, i) lower[k][i] = (mat[k][i] - sum) / upper[i][i]; } } } // setw is for displaying nicely System.out.println(setw(2) + \" Lower Triangular\" + setw(10) + \"Upper Triangular\"); // Displaying the result : for (int i = 0; i < n; i++) { // Lower for (int j = 0; j < n; j++) System.out.print(setw(4) + lower[i][j] + \"\\t\"); System.out.print(\"\\t\"); // Upper for (int j = 0; j < n; j++) System.out.print(setw(4) + upper[i][j] + \"\\t\"); System.out.print(\"\\n\"); } } static String setw(int noOfSpace) { s = \"\"; for (int i = 0; i < noOfSpace; i++) s += \" \"; return s; } // Driver code public static void main(String arr[]) { int mat[][] = { { 2, -1, -2 }, { -4, 6, 3 }, { -4, -2, 8 } }; luDecomposition(mat, 3); }} /* This code contributed by PrinciRaj1992 */", "e": 35664, "s": 33311, "text": null }, { "code": "# Python3 Program to decompose# a matrix into lower and# upper triangular matrixMAX = 100 def luDecomposition(mat, n): lower = [[0 for x in range(n)] for y in range(n)] upper = [[0 for x in range(n)] for y in range(n)] # Decomposing matrix into Upper # and Lower triangular matrix for i in range(n): # Upper Triangular for k in range(i, n): # Summation of L(i, j) * U(j, k) sum = 0 for j in range(i): sum += (lower[i][j] * upper[j][k]) # Evaluating U(i, k) upper[i][k] = mat[i][k] - sum # Lower Triangular for k in range(i, n): if (i == k): lower[i][i] = 1 # Diagonal as 1 else: # Summation of L(k, j) * U(j, i) sum = 0 for j in range(i): sum += (lower[k][j] * upper[j][i]) # Evaluating L(k, i) lower[k][i] = int((mat[k][i] - sum) / upper[i][i]) # setw is for displaying nicely print(\"Lower Triangular\\t\\tUpper Triangular\") # Displaying the result : for i in range(n): # Lower for j in range(n): print(lower[i][j], end=\"\\t\") print(\"\", end=\"\\t\") # Upper for j in range(n): print(upper[i][j], end=\"\\t\") print(\"\") # Driver codemat = [[2, -1, -2], [-4, 6, 3], [-4, -2, 8]] luDecomposition(mat, 3) # This code is contributed by mits", "e": 37196, "s": 35664, "text": null }, { "code": "// C# Program to decompose a matrix into// lower and upper triangular matrixusing System; class GFG { static int MAX = 100; static String s = \"\"; static void luDecomposition(int[, ] mat, int n) { int[, ] lower = new int[n, n]; int[, ] upper = new int[n, n]; // Decomposing matrix into Upper and Lower // triangular matrix for (int i = 0; i < n; i++) { // Upper Triangular for (int k = i; k < n; k++) { // Summation of L(i, j) * U(j, k) int sum = 0; for (int j = 0; j < i; j++) sum += (lower[i, j] * upper[j, k]); // Evaluating U(i, k) upper[i, k] = mat[i, k] - sum; } // Lower Triangular for (int k = i; k < n; k++) { if (i == k) lower[i, i] = 1; // Diagonal as 1 else { // Summation of L(k, j) * U(j, i) int sum = 0; for (int j = 0; j < i; j++) sum += (lower[k, j] * upper[j, i]); // Evaluating L(k, i) lower[k, i] = (mat[k, i] - sum) / upper[i, i]; } } } // setw is for displaying nicely Console.WriteLine(setw(2) + \" Lower Triangular\" + setw(10) + \"Upper Triangular\"); // Displaying the result : for (int i = 0; i < n; i++) { // Lower for (int j = 0; j < n; j++) Console.Write(setw(4) + lower[i, j] + \"\\t\"); Console.Write(\"\\t\"); // Upper for (int j = 0; j < n; j++) Console.Write(setw(4) + upper[i, j] + \"\\t\"); Console.Write(\"\\n\"); } } static String setw(int noOfSpace) { s = \"\"; for (int i = 0; i < noOfSpace; i++) s += \" \"; return s; } // Driver code public static void Main(String[] arr) { int[, ] mat = { { 2, -1, -2 }, { -4, 6, 3 }, { -4, -2, 8 } }; luDecomposition(mat, 3); }} // This code is contributed by Princi Singh", "e": 39482, "s": 37196, "text": null }, { "code": "<?php// PHP Program to decompose// a matrix into lower and// upper triangular matrix$MAX = 100; function luDecomposition($mat, $n){ $lower; $upper; for($i = 0; $i < $n; $i++) for($j = 0; $j < $n; $j++) { $lower[$i][$j]= 0; $upper[$i][$j]= 0; } // Decomposing matrix // into Upper and Lower // triangular matrix for ($i = 0; $i < $n; $i++) { // Upper Triangular for ($k = $i; $k < $n; $k++) { // Summation of // L(i, j) * U(j, k) $sum = 0; for ($j = 0; $j < $i; $j++) $sum += ($lower[$i][$j] * $upper[$j][$k]); // Evaluating U(i, k) $upper[$i][$k] = $mat[$i][$k] - $sum; } // Lower Triangular for ($k = $i; $k < $n; $k++) { if ($i == $k) $lower[$i][$i] = 1; // Diagonal as 1 else { // Summation of L(k, j) * U(j, i) $sum = 0; for ($j = 0; $j < $i; $j++) $sum += ($lower[$k][$j] * $upper[$j][$i]); // Evaluating L(k, i) $lower[$k][$i] = (int)(($mat[$k][$i] - $sum) / $upper[$i][$i]); } } } // setw is for // displaying nicely echo \"\\t\\tLower Triangular\"; echo \"\\t\\t\\tUpper Triangular\\n\"; // Displaying the result : for ($i = 0; $i < $n; $i++) { // Lower for ($j = 0; $j < $n; $j++) echo \"\\t\" . $lower[$i][$j] . \"\\t\"; echo \"\\t\"; // Upper for ($j = 0; $j < $n; $j++) echo $upper[$i][$j] . \"\\t\"; echo \"\\n\"; }} // Driver code$mat = array(array(2, -1, -2), array(-4, 6, 3), array(-4, -2, 8)); luDecomposition($mat, 3); // This code is contributed by mits?>", "e": 41372, "s": 39482, "text": null }, { "code": "<script> // Javascript Program to decompose a matrix// into lower and upper triangular matrix // function MAX = 100;var s = \"\"; function luDecomposition(mat, n){ var lower = Array(n).fill(0).map( x => Array(n).fill(0)); var upper = Array(n).fill(0).map( x => Array(n).fill(0)); // Decomposing matrix into Upper and // Lower triangular matrix for(var i = 0; i < n; i++) { // Upper Triangular for(var k = i; k < n; k++) { // Summation of L(i, j) * U(j, k) var sum = 0; for(var j = 0; j < i; j++) sum += (lower[i][j] * upper[j][k]); // Evaluating U(i, k) upper[i][k] = mat[i][k] - sum; } // Lower Triangular for(var k = i; k < n; k++) { if (i == k) // Diagonal as 1 lower[i][i] = 1; else { // Summation of L(k, j) * U(j, i) var sum = 0; for(var j = 0; j < i; j++) sum += (lower[k][j] * upper[j][i]); // Evaluating L(k, i) lower[k][i] = parseInt((mat[k][i] - sum) / upper[i][i]); } } } // Setw is for displaying nicely document.write(setw(2) + \"Lower Triangular\" + setw(10) + \"Upper Triangular<br>\"); // Displaying the result : for(var i = 0; i < n; i++) { // Lower for(var j = 0; j < n; j++) document.write(setw(4) + lower[i][j] + \"\\t\"); document.write(setw(10)); // Upper for(var j = 0; j < n; j++) document.write(setw(4) + upper[i][j] + \"\\t\"); document.write(\"<br>\"); }} function setw(noOfSpace){ var s = \"\"; for(i = 0; i < noOfSpace; i++) s += \" \"; return s;} // Driver codevar mat = [ [ 2, -1, -2 ], [ -4, 6, 3 ], [ -4, -2, 8 ] ]; luDecomposition(mat, 3); // This code is contributed by Amit Katiyar </script>", "e": 43579, "s": 41372, "text": null }, { "code": null, "e": 43588, "s": 43579, "text": "Output: " }, { "code": null, "e": 43742, "s": 43588, "text": "Lower Triangular Upper Triangular\n1 0 0 2 -1 -2 \n-2 1 0 0 4 -1 \n-2 -1 1 0 0 3 " }, { "code": null, "e": 44162, "s": 43742, "text": "This article is contributed by Shubham Rana. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 44175, "s": 44162, "text": "Mithun Kumar" }, { "code": null, "e": 44189, "s": 44175, "text": "princiraj1992" }, { "code": null, "e": 44202, "s": 44189, "text": "princi singh" }, { "code": null, "e": 44214, "s": 44202, "text": "jesaldkotak" }, { "code": null, "e": 44225, "s": 44214, "text": "agchiper45" }, { "code": null, "e": 44240, "s": 44225, "text": "amit143katiyar" }, { "code": null, "e": 44256, "s": 44240, "text": "simranarora5sos" }, { "code": null, "e": 44280, "s": 44256, "text": "Engineering Mathematics" }, { "code": null, "e": 44293, "s": 44280, "text": "Mathematical" }, { "code": null, "e": 44300, "s": 44293, "text": "Matrix" }, { "code": null, "e": 44313, "s": 44300, "text": "Mathematical" }, { "code": null, "e": 44320, "s": 44313, "text": "Matrix" }, { "code": null, "e": 44418, "s": 44320, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 44427, "s": 44418, "text": "Comments" }, { "code": null, "e": 44440, "s": 44427, "text": "Old Comments" }, { "code": null, "e": 44462, "s": 44440, "text": "Inequalities in LaTeX" }, { "code": null, "e": 44512, "s": 44462, "text": "Newton's Divided Difference Interpolation Formula" }, { "code": null, "e": 44535, "s": 44512, "text": "Arrow Symbols in LaTeX" }, { "code": null, "e": 44558, "s": 44535, "text": "Set Notations in LaTeX" }, { "code": null, "e": 44579, "s": 44558, "text": "Activation Functions" }, { "code": null, "e": 44609, "s": 44579, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 44624, "s": 44609, "text": "C++ Data Types" }, { "code": null, "e": 44684, "s": 44624, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 44727, "s": 44684, "text": "Set in C++ Standard Template Library (STL)" } ]
Arithmetic Mean - GeeksforGeeks
06 Jun, 2021 Arithmetic mean, also called the average or average value, is the quantity obtained by summing two or more numbers or variables and then dividing by the number of numbers or variables. The arithmetic mean is important in statistics. For example, Let’s say there are only two quantities involved, the arithmetic mean is obtained simply by adding the quantities and dividing by 2. Some interesting fact about Arithmetic Mean : The mean of n numbers x1, x2, . . ., xn is x. If each observation is increased by p, the mean of the new observations is (x + p).The mean of n numbers x1, x2, . . ., xn is x. If each observation is decreased by p, the mean of the new observations is (x – p).The mean of n numbers x1, x2, . . ., xn is x. If each observation is multiplied by a nonzero number p, the mean of the new observations is px.The mean of n numbers x1, x2, . . ., xn is x. If each observation is divided by a nonzero number p, the mean of the new observations is (x/p). The mean of n numbers x1, x2, . . ., xn is x. If each observation is increased by p, the mean of the new observations is (x + p). The mean of n numbers x1, x2, . . ., xn is x. If each observation is decreased by p, the mean of the new observations is (x – p). The mean of n numbers x1, x2, . . ., xn is x. If each observation is multiplied by a nonzero number p, the mean of the new observations is px. The mean of n numbers x1, x2, . . ., xn is x. If each observation is divided by a nonzero number p, the mean of the new observations is (x/p). Formula of Arithmetic Mean: How to find Arithmetic Mean ? Given three integers A, B and N the task is to find N Arithmetic means between A and B. We basically need to insert N terms in an Arithmetic progression. where A and B are first and last terms. Examples: Input : A = 20 B = 32 N = 5 Output : 22 24 26 28 30 The Arithmetic progression series is 20 22 24 26 28 30 32 Input : A = 5 B = 35 N = 5 Output : 10 15 20 25 30 Approach : Let A1, A2, A3, A4......An be N Arithmetic Means between two given numbers A and B . Then A, A1, A2 ..... An, B will be in Arithmetic Progression. Now B = (N+2)th term of the Arithmetic progression. So : Finding the (N+2)th term of the Arithmetic progression Series, where d is the Common Difference B = A + (N + 2 - 1)d B - A = (N + 1)d So the Common Difference d is given by. d = (B - A) / (N + 1) We have the value of A and the value of the common difference(d), now we can find all the N Arithmetic Means between A and B. C++ Java Python3 C# PHP Javascript // C++ program to find n arithmetic// means between A and B#include <bits/stdc++.h>using namespace std; // Prints N arithmetic means between// A and B.void printAMeans(int A, int B, int N){ // calculate common difference(d) float d = (float)(B - A) / (N + 1); // for finding N the arithmetic // mean between A and B for (int i = 1; i <= N; i++) cout << (A + i * d) << " ";} // Driver code to test aboveint main(){ int A = 20, B = 32, N = 5; printAMeans(A, B, N); return 0;} // java program to illustrate// n arithmetic mean between// A and Bimport java.io.*;import java.lang.*;import java.util.*; public class GFG { // insert function for calculating the means static void printAMeans(int A, int B, int N) { // Finding the value of d Common difference float d = (float)(B - A) / (N + 1); // for finding N the Arithmetic // mean between A and B for (int i = 1; i <= N; i++) System.out.print((A + i * d) + " "); } // Driver code public static void main(String args[]) { int A = 20, B = 32, N = 5; printAMeans(A, B, N); }} # Python3 program to find n arithmetic# means between A and B # Prints N arithmetic means# between A and B.def printAMeans(A, B, N): # Calculate common difference(d) d = (B - A) / (N + 1) # For finding N the arithmetic # mean between A and B for i in range(1, N + 1): print(int(A + i * d), end = " ") # Driver codeA = 20; B = 32; N = 5printAMeans(A, B, N) # This code is contributed by Smitha Dinesh Semwal // C# program to illustrate// n arithmetic mean between// A and Busing System; public class GFG { // insert function for calculating the means static void printAMeans(int A, int B, int N) { // Finding the value of d Common difference float d = (float)(B - A) / (N + 1); // for finding N the Arithmetic // mean between A and B for (int i = 1; i <= N; i++) Console.Write((A + i * d) + " "); } // Driver code public static void Main() { int A = 20, B = 32, N = 5; printAMeans(A, B, N); }}// Contributed by vt_m <?php// PHP program to find n arithmetic// means between A and B // Prints N arithmetic means// between A and B.function printAMeans($A, $B, $N){ // calculate common // difference(d) $d = ($B - $A) / ($N + 1); // for finding N the arithmetic // mean between A and B for ($i = 1; $i <= $N; $i++) echo ($A + $i * $d), " ";} // Driver Code $A = 20; $B = 32; $N = 5; printAMeans($A, $B, $N); // This code is Contributed by vt_m.?> <script> // Javascript program to find n arithmetic// means between A and B // Prints N arithmetic means between// A and B.function printAMeans(A, B, N){ // Calculate common difference(d) let d = (B - A) / (N + 1); // For finding N the arithmetic // mean between A and B for(let i = 1; i <= N; i++) document.write((A + i * d) + " ");} // Driver codelet A = 20, B = 32, N = 5;printAMeans(A, B, N); // This code is contributed by souravmahato348 </script> 22 24 26 28 30 Basic Program related to Arithmetic Mean Find Harmonic mean using Arithmetic mean and Geometric mean Program for class interval arithmetic mean ManasChhabra2 souravmahato348 arithmetic progression statistical-algorithms Mathematical Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Algorithm to solve Rubik's Cube Modular multiplicative inverse Program to multiply two matrices Program to print prime numbers from 1 to N. Count ways to reach the n'th stair Program to convert a given number to words Fizz Buzz Implementation Singular Value Decomposition (SVD) Check if a number is Palindrome Find first and last digits of a number
[ { "code": null, "e": 24692, "s": 24664, "text": "\n06 Jun, 2021" }, { "code": null, "e": 25071, "s": 24692, "text": "Arithmetic mean, also called the average or average value, is the quantity obtained by summing two or more numbers or variables and then dividing by the number of numbers or variables. The arithmetic mean is important in statistics. For example, Let’s say there are only two quantities involved, the arithmetic mean is obtained simply by adding the quantities and dividing by 2." }, { "code": null, "e": 25118, "s": 25071, "text": "Some interesting fact about Arithmetic Mean : " }, { "code": null, "e": 25661, "s": 25118, "text": "The mean of n numbers x1, x2, . . ., xn is x. If each observation is increased by p, the mean of the new observations is (x + p).The mean of n numbers x1, x2, . . ., xn is x. If each observation is decreased by p, the mean of the new observations is (x – p).The mean of n numbers x1, x2, . . ., xn is x. If each observation is multiplied by a nonzero number p, the mean of the new observations is px.The mean of n numbers x1, x2, . . ., xn is x. If each observation is divided by a nonzero number p, the mean of the new observations is (x/p)." }, { "code": null, "e": 25791, "s": 25661, "text": "The mean of n numbers x1, x2, . . ., xn is x. If each observation is increased by p, the mean of the new observations is (x + p)." }, { "code": null, "e": 25921, "s": 25791, "text": "The mean of n numbers x1, x2, . . ., xn is x. If each observation is decreased by p, the mean of the new observations is (x – p)." }, { "code": null, "e": 26064, "s": 25921, "text": "The mean of n numbers x1, x2, . . ., xn is x. If each observation is multiplied by a nonzero number p, the mean of the new observations is px." }, { "code": null, "e": 26207, "s": 26064, "text": "The mean of n numbers x1, x2, . . ., xn is x. If each observation is divided by a nonzero number p, the mean of the new observations is (x/p)." }, { "code": null, "e": 26237, "s": 26207, "text": "Formula of Arithmetic Mean: " }, { "code": null, "e": 26461, "s": 26237, "text": "How to find Arithmetic Mean ? Given three integers A, B and N the task is to find N Arithmetic means between A and B. We basically need to insert N terms in an Arithmetic progression. where A and B are first and last terms." }, { "code": null, "e": 26473, "s": 26461, "text": "Examples: " }, { "code": null, "e": 26639, "s": 26473, "text": "Input : A = 20 B = 32 N = 5\nOutput : 22 24 26 28 30\nThe Arithmetic progression series is \n20 22 24 26 28 30 32 \n\nInput : A = 5 B = 35 N = 5\nOutput : 10 15 20 25 30" }, { "code": null, "e": 26855, "s": 26639, "text": "Approach : Let A1, A2, A3, A4......An be N Arithmetic Means between two given numbers A and B . Then A, A1, A2 ..... An, B will be in Arithmetic Progression. Now B = (N+2)th term of the Arithmetic progression. So : " }, { "code": null, "e": 26951, "s": 26855, "text": "Finding the (N+2)th term of the Arithmetic progression Series, where d is the Common Difference" }, { "code": null, "e": 26990, "s": 26951, "text": "B = A + (N + 2 - 1)d\nB - A = (N + 1)d" }, { "code": null, "e": 27030, "s": 26990, "text": "So the Common Difference d is given by." }, { "code": null, "e": 27052, "s": 27030, "text": "d = (B - A) / (N + 1)" }, { "code": null, "e": 27179, "s": 27052, "text": "We have the value of A and the value of the common difference(d), now we can find all the N Arithmetic Means between A and B. " }, { "code": null, "e": 27183, "s": 27179, "text": "C++" }, { "code": null, "e": 27188, "s": 27183, "text": "Java" }, { "code": null, "e": 27196, "s": 27188, "text": "Python3" }, { "code": null, "e": 27199, "s": 27196, "text": "C#" }, { "code": null, "e": 27203, "s": 27199, "text": "PHP" }, { "code": null, "e": 27214, "s": 27203, "text": "Javascript" }, { "code": "// C++ program to find n arithmetic// means between A and B#include <bits/stdc++.h>using namespace std; // Prints N arithmetic means between// A and B.void printAMeans(int A, int B, int N){ // calculate common difference(d) float d = (float)(B - A) / (N + 1); // for finding N the arithmetic // mean between A and B for (int i = 1; i <= N; i++) cout << (A + i * d) << \" \";} // Driver code to test aboveint main(){ int A = 20, B = 32, N = 5; printAMeans(A, B, N); return 0;}", "e": 27720, "s": 27214, "text": null }, { "code": "// java program to illustrate// n arithmetic mean between// A and Bimport java.io.*;import java.lang.*;import java.util.*; public class GFG { // insert function for calculating the means static void printAMeans(int A, int B, int N) { // Finding the value of d Common difference float d = (float)(B - A) / (N + 1); // for finding N the Arithmetic // mean between A and B for (int i = 1; i <= N; i++) System.out.print((A + i * d) + \" \"); } // Driver code public static void main(String args[]) { int A = 20, B = 32, N = 5; printAMeans(A, B, N); }}", "e": 28353, "s": 27720, "text": null }, { "code": "# Python3 program to find n arithmetic# means between A and B # Prints N arithmetic means# between A and B.def printAMeans(A, B, N): # Calculate common difference(d) d = (B - A) / (N + 1) # For finding N the arithmetic # mean between A and B for i in range(1, N + 1): print(int(A + i * d), end = \" \") # Driver codeA = 20; B = 32; N = 5printAMeans(A, B, N) # This code is contributed by Smitha Dinesh Semwal", "e": 28788, "s": 28353, "text": null }, { "code": "// C# program to illustrate// n arithmetic mean between// A and Busing System; public class GFG { // insert function for calculating the means static void printAMeans(int A, int B, int N) { // Finding the value of d Common difference float d = (float)(B - A) / (N + 1); // for finding N the Arithmetic // mean between A and B for (int i = 1; i <= N; i++) Console.Write((A + i * d) + \" \"); } // Driver code public static void Main() { int A = 20, B = 32, N = 5; printAMeans(A, B, N); }}// Contributed by vt_m", "e": 29383, "s": 28788, "text": null }, { "code": "<?php// PHP program to find n arithmetic// means between A and B // Prints N arithmetic means// between A and B.function printAMeans($A, $B, $N){ // calculate common // difference(d) $d = ($B - $A) / ($N + 1); // for finding N the arithmetic // mean between A and B for ($i = 1; $i <= $N; $i++) echo ($A + $i * $d), \" \";} // Driver Code $A = 20; $B = 32; $N = 5; printAMeans($A, $B, $N); // This code is Contributed by vt_m.?>", "e": 29862, "s": 29383, "text": null }, { "code": "<script> // Javascript program to find n arithmetic// means between A and B // Prints N arithmetic means between// A and B.function printAMeans(A, B, N){ // Calculate common difference(d) let d = (B - A) / (N + 1); // For finding N the arithmetic // mean between A and B for(let i = 1; i <= N; i++) document.write((A + i * d) + \" \");} // Driver codelet A = 20, B = 32, N = 5;printAMeans(A, B, N); // This code is contributed by souravmahato348 </script>", "e": 30344, "s": 29862, "text": null }, { "code": null, "e": 30359, "s": 30344, "text": "22 24 26 28 30" }, { "code": null, "e": 30403, "s": 30361, "text": "Basic Program related to Arithmetic Mean " }, { "code": null, "e": 30463, "s": 30403, "text": "Find Harmonic mean using Arithmetic mean and Geometric mean" }, { "code": null, "e": 30506, "s": 30463, "text": "Program for class interval arithmetic mean" }, { "code": null, "e": 30522, "s": 30508, "text": "ManasChhabra2" }, { "code": null, "e": 30538, "s": 30522, "text": "souravmahato348" }, { "code": null, "e": 30561, "s": 30538, "text": "arithmetic progression" }, { "code": null, "e": 30584, "s": 30561, "text": "statistical-algorithms" }, { "code": null, "e": 30597, "s": 30584, "text": "Mathematical" }, { "code": null, "e": 30610, "s": 30597, "text": "Mathematical" }, { "code": null, "e": 30708, "s": 30610, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30717, "s": 30708, "text": "Comments" }, { "code": null, "e": 30730, "s": 30717, "text": "Old Comments" }, { "code": null, "e": 30762, "s": 30730, "text": "Algorithm to solve Rubik's Cube" }, { "code": null, "e": 30793, "s": 30762, "text": "Modular multiplicative inverse" }, { "code": null, "e": 30826, "s": 30793, "text": "Program to multiply two matrices" }, { "code": null, "e": 30870, "s": 30826, "text": "Program to print prime numbers from 1 to N." }, { "code": null, "e": 30905, "s": 30870, "text": "Count ways to reach the n'th stair" }, { "code": null, "e": 30948, "s": 30905, "text": "Program to convert a given number to words" }, { "code": null, "e": 30973, "s": 30948, "text": "Fizz Buzz Implementation" }, { "code": null, "e": 31008, "s": 30973, "text": "Singular Value Decomposition (SVD)" }, { "code": null, "e": 31040, "s": 31008, "text": "Check if a number is Palindrome" } ]