title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
UGC-NET | UGC NET CS 2017 Jan – III | Question 46
04 Apr, 2018 A software project was estimated at 352 Function Points (FP). A four person team will be assigned to this project consisting of an architect, two programmers, and a tester. The salary of the architect is ` 80,000 per month, the programmer ₹ 60,000 per month and the tester ₹ 50,000 per month. The average productivity for the team is 8 FP per person month. Which of the following represents the projected cost of the project ?(A) ₹ 28,16,000(B) ₹ 20,90,000(C) ₹ 26,95,000(D) ₹ 27,50,000Answer: (D)Explanation: In given question we have total 352 Function Points (FP)Average FP = 8 per person per month4 person team is assigned to the project which is consist of an architect(₹ 80,000 per month), two programmers(₹ 60,000 per person per month), and a tester(₹ 50,000 per month). So, 352 / (8 * 4) = 11 months projected cost of the project = (1 architect + 2 programmer + 1 tester) * 11 = (80000 + 2 * 60000 + 50000) * 11 = ₹ 2750000. So, option (D) is correct. Quiz of this Question UGC-NET Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. UGC-NET | UGC NET CS 2015 Jun - III | Question 33 UGC-NET | UGC NET CS 2015 Jun - III | Question 35 UGC-NET | UGC NET CS 2016 Aug - III | Question 32 UGC-NET | UGC NET CS 2015 Jun - III | Question 31 UGC-NET | UGC NET CS 2015 Jun - III | Question 64 UGC-NET | UGC NET CS 2016 July – III | Question 32 UGC-NET | UGC NET CS 2016 July – II | Question 27 UGC-NET | UGC NET CS 2015 Dec – III | Question 34 UGC-NET | UGC NET CS 2015 Jun - II | Question 1 UGC-NET | UGC NET CS 2015 Jun - III | Question 34
[ { "code": null, "e": 52, "s": 24, "text": "\n04 Apr, 2018" }, { "code": null, "e": 830, "s": 52, "text": "A software project was estimated at 352 Function Points (FP). A four person team will be assigned to this project consisting of an architect, two programmers, and a tester. The salary of the architect is ` 80,000 per month, the programmer ₹ 60,000 per month and the tester ₹ 50,000 per month. The average productivity for the team is 8 FP per person month. Which of the following represents the projected cost of the project ?(A) ₹ 28,16,000(B) ₹ 20,90,000(C) ₹ 26,95,000(D) ₹ 27,50,000Answer: (D)Explanation: In given question we have total 352 Function Points (FP)Average FP = 8 per person per month4 person team is assigned to the project which is consist of an architect(₹ 80,000 per month), two programmers(₹ 60,000 per person per month), and a tester(₹ 50,000 per month)." }, { "code": null, "e": 1047, "s": 830, "text": "So, 352 / (8 * 4) = 11 months\nprojected cost of the project = (1 architect + 2 programmer + 1 tester) * 11 \n = (80000 + 2 * 60000 + 50000) * 11 \n = ₹ 2750000." }, { "code": null, "e": 1074, "s": 1047, "text": "So, option (D) is correct." }, { "code": null, "e": 1096, "s": 1074, "text": "Quiz of this Question" }, { "code": null, "e": 1104, "s": 1096, "text": "UGC-NET" }, { "code": null, "e": 1202, "s": 1104, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1252, "s": 1202, "text": "UGC-NET | UGC NET CS 2015 Jun - III | Question 33" }, { "code": null, "e": 1302, "s": 1252, "text": "UGC-NET | UGC NET CS 2015 Jun - III | Question 35" }, { "code": null, "e": 1352, "s": 1302, "text": "UGC-NET | UGC NET CS 2016 Aug - III | Question 32" }, { "code": null, "e": 1402, "s": 1352, "text": "UGC-NET | UGC NET CS 2015 Jun - III | Question 31" }, { "code": null, "e": 1452, "s": 1402, "text": "UGC-NET | UGC NET CS 2015 Jun - III | Question 64" }, { "code": null, "e": 1503, "s": 1452, "text": "UGC-NET | UGC NET CS 2016 July – III | Question 32" }, { "code": null, "e": 1553, "s": 1503, "text": "UGC-NET | UGC NET CS 2016 July – II | Question 27" }, { "code": null, "e": 1603, "s": 1553, "text": "UGC-NET | UGC NET CS 2015 Dec – III | Question 34" }, { "code": null, "e": 1651, "s": 1603, "text": "UGC-NET | UGC NET CS 2015 Jun - II | Question 1" } ]
Printing source code of a C program itself
11 Feb, 2018 How to print source code of a C program itself? Note this is different from Quine problem. Here we need to modify any C program in a way that it prints whole source code. Explanation :We can use the concepts of file handling to print the source code of the program as output. The idea being : displaying the content from the same file you are writing the source code. The location of a C programming file is contained inside a predefined macro __FILE__. For example: #include <stdio.h>int main(){ // Prints location of C this C code. printf("%s",__FILE__);} The output of the above program is the location of this C file.The following program displays the content of this particular C file(source code) because __FILE__ contains the location of this C file in a string. // A C program that prints its source code.#include <stdio.h> int main(void){ // We can append this code to any C program // such that it prints its source code. char c; FILE *fp = fopen(__FILE__, "r"); do { c = fgetc(fp); putchar(c); } while (c != EOF); fclose(fp); return 0;} Output : // A C program that prints its source code. #include <stdio.h> int main(void) { // We can append this code to any C program // such that it prints its source code. char c; FILE *fp = fopen(__FILE__, "r"); do { c = fgetc(fp); putchar(c); } while (c != EOF); fclose(fp); return 0; } Note : The above program may not work online compiler as fopen might be blocked. This article is contributed by Rishav Raj. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. C-File Handling C Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Unordered Sets in C++ Standard Template Library Operators in C / C++ Exception Handling in C++ What is the purpose of a function prototype? TCP Server-Client implementation in C Smart Pointers in C++ and How to Use Them Storage Classes in C 'this' pointer in C++ Ways to copy a vector in C++ Arrow operator -> in C/C++ with Examples
[ { "code": null, "e": 54, "s": 26, "text": "\n11 Feb, 2018" }, { "code": null, "e": 225, "s": 54, "text": "How to print source code of a C program itself? Note this is different from Quine problem. Here we need to modify any C program in a way that it prints whole source code." }, { "code": null, "e": 422, "s": 225, "text": "Explanation :We can use the concepts of file handling to print the source code of the program as output. The idea being : displaying the content from the same file you are writing the source code." }, { "code": null, "e": 521, "s": 422, "text": "The location of a C programming file is contained inside a predefined macro __FILE__. For example:" }, { "code": " #include <stdio.h>int main(){ // Prints location of C this C code. printf(\"%s\",__FILE__);}", "e": 619, "s": 521, "text": null }, { "code": null, "e": 831, "s": 619, "text": "The output of the above program is the location of this C file.The following program displays the content of this particular C file(source code) because __FILE__ contains the location of this C file in a string." }, { "code": " // A C program that prints its source code.#include <stdio.h> int main(void){ // We can append this code to any C program // such that it prints its source code. char c; FILE *fp = fopen(__FILE__, \"r\"); do { c = fgetc(fp); putchar(c); } while (c != EOF); fclose(fp); return 0;}", "e": 1170, "s": 831, "text": null }, { "code": null, "e": 1179, "s": 1170, "text": "Output :" }, { "code": null, "e": 1527, "s": 1179, "text": "// A C program that prints its source code.\n#include <stdio.h>\n \nint main(void)\n{\n // We can append this code to any C program\n // such that it prints its source code.\n\n char c; \n FILE *fp = fopen(__FILE__, \"r\");\n \n do\n {\n c = fgetc(fp);\n putchar(c);\n }\n while (c != EOF);\n \n fclose(fp);\n \n return 0;\n}\n" }, { "code": null, "e": 1608, "s": 1527, "text": "Note : The above program may not work online compiler as fopen might be blocked." }, { "code": null, "e": 1906, "s": 1608, "text": "This article is contributed by Rishav Raj. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 2031, "s": 1906, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 2047, "s": 2031, "text": "C-File Handling" }, { "code": null, "e": 2058, "s": 2047, "text": "C Language" }, { "code": null, "e": 2156, "s": 2058, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2204, "s": 2156, "text": "Unordered Sets in C++ Standard Template Library" }, { "code": null, "e": 2225, "s": 2204, "text": "Operators in C / C++" }, { "code": null, "e": 2251, "s": 2225, "text": "Exception Handling in C++" }, { "code": null, "e": 2296, "s": 2251, "text": "What is the purpose of a function prototype?" }, { "code": null, "e": 2334, "s": 2296, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 2376, "s": 2334, "text": "Smart Pointers in C++ and How to Use Them" }, { "code": null, "e": 2397, "s": 2376, "text": "Storage Classes in C" }, { "code": null, "e": 2419, "s": 2397, "text": "'this' pointer in C++" }, { "code": null, "e": 2448, "s": 2419, "text": "Ways to copy a vector in C++" } ]
jQuery element Selector
11 Jul, 2022 jQuery is an open-source JavaScript library that simplifies the interactions between an HTML/CSS document, or more precisely the Document Object Model (DOM), and JavaScript. Elaborating the terms, it simplifies HTML document traversing and manipulation, browser event handling, DOM animations, Ajax interactions, and cross-browser JavaScript development. jQuery element selector is used to select and modify HTML elements based on the element name. Syntax: $("element_name") Example 1: This example selects the “h2” element and adds border to it. HTML <!DOCTYPE html><html><head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script> $(document).ready(function () { $("h2").css("border", "5px solid green"); }); </script></head><body> <h2>GeeksForGeeks</h2></body></html> Output: Example 2: This example changes text color of “h2” element on button click. HTML <!DOCTYPE html><html><head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script> $(document).ready(function () { $("button").click(function () { $("h2").css("color", "green"); }); }); </script></head><body> <h2>GeeksForGeeks</h2> <button>Change text color</button></body></html> Output: Supported Browsers: Google Chrome 90.0+ Internet Explorer 9.0 Firefox 3.6 Safari 4.0 Opera 10.5 ysachin2314 sahilintern jQuery-Selectors Picked JQuery 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": "\n11 Jul, 2022" }, { "code": null, "e": 383, "s": 28, "text": "jQuery is an open-source JavaScript library that simplifies the interactions between an HTML/CSS document, or more precisely the Document Object Model (DOM), and JavaScript. Elaborating the terms, it simplifies HTML document traversing and manipulation, browser event handling, DOM animations, Ajax interactions, and cross-browser JavaScript development." }, { "code": null, "e": 478, "s": 383, "text": "jQuery element selector is used to select and modify HTML elements based on the element name. " }, { "code": null, "e": 486, "s": 478, "text": "Syntax:" }, { "code": null, "e": 505, "s": 486, "text": "$(\"element_name\") " }, { "code": null, "e": 578, "s": 505, "text": "Example 1: This example selects the “h2” element and adds border to it. " }, { "code": null, "e": 583, "s": 578, "text": "HTML" }, { "code": "<!DOCTYPE html><html><head> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script> $(document).ready(function () { $(\"h2\").css(\"border\", \"5px solid green\"); }); </script></head><body> <h2>GeeksForGeeks</h2></body></html>", "e": 871, "s": 583, "text": null }, { "code": null, "e": 880, "s": 871, "text": "Output: " }, { "code": null, "e": 959, "s": 882, "text": "Example 2: This example changes text color of “h2” element on button click. " }, { "code": null, "e": 964, "s": 959, "text": "HTML" }, { "code": "<!DOCTYPE html><html><head> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script> $(document).ready(function () { $(\"button\").click(function () { $(\"h2\").css(\"color\", \"green\"); }); }); </script></head><body> <h2>GeeksForGeeks</h2> <button>Change text color</button></body></html>", "e": 1327, "s": 964, "text": null }, { "code": null, "e": 1335, "s": 1327, "text": "Output:" }, { "code": null, "e": 1359, "s": 1339, "text": "Supported Browsers:" }, { "code": null, "e": 1379, "s": 1359, "text": "Google Chrome 90.0+" }, { "code": null, "e": 1401, "s": 1379, "text": "Internet Explorer 9.0" }, { "code": null, "e": 1413, "s": 1401, "text": "Firefox 3.6" }, { "code": null, "e": 1424, "s": 1413, "text": "Safari 4.0" }, { "code": null, "e": 1435, "s": 1424, "text": "Opera 10.5" }, { "code": null, "e": 1447, "s": 1435, "text": "ysachin2314" }, { "code": null, "e": 1459, "s": 1447, "text": "sahilintern" }, { "code": null, "e": 1476, "s": 1459, "text": "jQuery-Selectors" }, { "code": null, "e": 1483, "s": 1476, "text": "Picked" }, { "code": null, "e": 1490, "s": 1483, "text": "JQuery" }, { "code": null, "e": 1507, "s": 1490, "text": "Web Technologies" } ]
How to plot a simple vector field in Matplotlib ?
20 Apr, 2022 The quantity incorporating both magnitude and direction is known as Vectors. In simple words, we can say, Vector Field is an engagement or collaboration of such vectors in a subset of space. Vector fields are the key aspects of understanding our real-life surrounding. For more intuition, you can think of a vector field as representing a multivariable function whose input and output spaces each have the same dimension. The length of arrows drawn in a vector field is usually not to scale, but the ratio of the length of one vector to another should be accurate. In this article, we are going to discuss how to plot a vector field in python. In order to perform this task we are going to use the quiver() method and the streamplot() method in matplotlib module. Syntax: To plot a vector field using the quiver() method: matplotlib.pyplot.quiver(X, Y, U, V, **kw) Where X, Y define the Vector location and U, V are directional arrows with respect of the Vector location. To plot a vector field using the streamplot() method: matplotlib.pyplot.streamplot(X, Y, U, V, density=1, linewidth=None, color=None, **kw) Where X, Y are evenly spaced grid[1D array] and U and V represent the stream velocity of each point present on the grid. Density is the no. of vector per area of the plot. Line width represents the thickness of streamlines. Below are some examples which depict how to plot vector fields using matplotlib module: Example 1: Plotting a single vector using quiver() method in matplotlib module. Python3 # Import librariesimport numpy as npimport matplotlib.pyplot as plt # Vector origin locationX = [0]Y = [0] # Directional vectorsU = [2] V = [1] # Creating plotplt.quiver(X, Y, U, V, color='b', units='xy', scale=1)plt.title('Single Vector') # x-lim and y-limplt.xlim(-2, 5)plt.ylim(-2, 2.5) # Show plot with gridplt.grid()plt.show() Output: Example 2: Generating multiple vectors using quiver() method. Python3 # Import required modulesimport numpy as npimport matplotlib.pyplot as plt # Meshgridx, y = np.meshgrid(np.linspace(-5, 5, 10), np.linspace(-5, 5, 10)) # Directional vectorsu = -y/np.sqrt(x**2 + y**2)v = x/(x**2 + y**2) # Plotting Vector Field with QUIVERplt.quiver(x, y, u, v, color='g')plt.title('Vector Field') # Setting x, y boundary limitsplt.xlim(-7, 7)plt.ylim(-7, 7) # Show plot with gridplt.grid()plt.show() Output: Example 3: Plotting multiple vectors using streamplot() method in matplotlib module. Python3 # Import required modulesimport numpy as npimport matplotlib.pyplot as plt # 1D arraysx = np.arange(-5,5,0.1)y = np.arange(-5,5,0.1) # MeshgridX,Y = np.meshgrid(x,y) # Assign vector directionsEx = (X + 1)/((X+1)**2 + Y**2) - (X - 1)/((X-1)**2 + Y**2)Ey = Y/((X+1)**2 + Y**2) - Y/((X-1)**2 + Y**2) # Depict illustrationplt.figure(figsize=(10, 10))plt.streamplot(X,Y,Ex,Ey, density=1.4, linewidth=None, color='#A23BEC')plt.plot(-1,0,'-or')plt.plot(1,0,'-og')plt.title('Electromagnetic Field') # Show plot with gridplt.grid()plt.show() Output: gabaa406 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. How to Install PIP on Windows ? Python Classes and Objects Python | os.path.join() method Introduction To PYTHON Python OOPs Concepts 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 Create a directory in Python
[ { "code": null, "e": 52, "s": 24, "text": "\n20 Apr, 2022" }, { "code": null, "e": 321, "s": 52, "text": "The quantity incorporating both magnitude and direction is known as Vectors. In simple words, we can say, Vector Field is an engagement or collaboration of such vectors in a subset of space. Vector fields are the key aspects of understanding our real-life surrounding." }, { "code": null, "e": 617, "s": 321, "text": "For more intuition, you can think of a vector field as representing a multivariable function whose input and output spaces each have the same dimension. The length of arrows drawn in a vector field is usually not to scale, but the ratio of the length of one vector to another should be accurate." }, { "code": null, "e": 816, "s": 617, "text": "In this article, we are going to discuss how to plot a vector field in python. In order to perform this task we are going to use the quiver() method and the streamplot() method in matplotlib module." }, { "code": null, "e": 824, "s": 816, "text": "Syntax:" }, { "code": null, "e": 874, "s": 824, "text": "To plot a vector field using the quiver() method:" }, { "code": null, "e": 918, "s": 874, "text": "matplotlib.pyplot.quiver(X, Y, U, V, **kw) " }, { "code": null, "e": 1025, "s": 918, "text": "Where X, Y define the Vector location and U, V are directional arrows with respect of the Vector location." }, { "code": null, "e": 1079, "s": 1025, "text": "To plot a vector field using the streamplot() method:" }, { "code": null, "e": 1165, "s": 1079, "text": "matplotlib.pyplot.streamplot(X, Y, U, V, density=1, linewidth=None, color=None, **kw)" }, { "code": null, "e": 1389, "s": 1165, "text": "Where X, Y are evenly spaced grid[1D array] and U and V represent the stream velocity of each point present on the grid. Density is the no. of vector per area of the plot. Line width represents the thickness of streamlines." }, { "code": null, "e": 1477, "s": 1389, "text": "Below are some examples which depict how to plot vector fields using matplotlib module:" }, { "code": null, "e": 1557, "s": 1477, "text": "Example 1: Plotting a single vector using quiver() method in matplotlib module." }, { "code": null, "e": 1565, "s": 1557, "text": "Python3" }, { "code": "# Import librariesimport numpy as npimport matplotlib.pyplot as plt # Vector origin locationX = [0]Y = [0] # Directional vectorsU = [2] V = [1] # Creating plotplt.quiver(X, Y, U, V, color='b', units='xy', scale=1)plt.title('Single Vector') # x-lim and y-limplt.xlim(-2, 5)plt.ylim(-2, 2.5) # Show plot with gridplt.grid()plt.show()", "e": 1905, "s": 1565, "text": null }, { "code": null, "e": 1913, "s": 1905, "text": "Output:" }, { "code": null, "e": 1975, "s": 1913, "text": "Example 2: Generating multiple vectors using quiver() method." }, { "code": null, "e": 1983, "s": 1975, "text": "Python3" }, { "code": "# Import required modulesimport numpy as npimport matplotlib.pyplot as plt # Meshgridx, y = np.meshgrid(np.linspace(-5, 5, 10), np.linspace(-5, 5, 10)) # Directional vectorsu = -y/np.sqrt(x**2 + y**2)v = x/(x**2 + y**2) # Plotting Vector Field with QUIVERplt.quiver(x, y, u, v, color='g')plt.title('Vector Field') # Setting x, y boundary limitsplt.xlim(-7, 7)plt.ylim(-7, 7) # Show plot with gridplt.grid()plt.show()", "e": 2424, "s": 1983, "text": null }, { "code": null, "e": 2432, "s": 2424, "text": "Output:" }, { "code": null, "e": 2517, "s": 2432, "text": "Example 3: Plotting multiple vectors using streamplot() method in matplotlib module." }, { "code": null, "e": 2525, "s": 2517, "text": "Python3" }, { "code": "# Import required modulesimport numpy as npimport matplotlib.pyplot as plt # 1D arraysx = np.arange(-5,5,0.1)y = np.arange(-5,5,0.1) # MeshgridX,Y = np.meshgrid(x,y) # Assign vector directionsEx = (X + 1)/((X+1)**2 + Y**2) - (X - 1)/((X-1)**2 + Y**2)Ey = Y/((X+1)**2 + Y**2) - Y/((X-1)**2 + Y**2) # Depict illustrationplt.figure(figsize=(10, 10))plt.streamplot(X,Y,Ex,Ey, density=1.4, linewidth=None, color='#A23BEC')plt.plot(-1,0,'-or')plt.plot(1,0,'-og')plt.title('Electromagnetic Field') # Show plot with gridplt.grid()plt.show()", "e": 3063, "s": 2525, "text": null }, { "code": null, "e": 3071, "s": 3063, "text": "Output:" }, { "code": null, "e": 3080, "s": 3071, "text": "gabaa406" }, { "code": null, "e": 3087, "s": 3080, "text": "Picked" }, { "code": null, "e": 3105, "s": 3087, "text": "Python-matplotlib" }, { "code": null, "e": 3129, "s": 3105, "text": "Technical Scripter 2020" }, { "code": null, "e": 3136, "s": 3129, "text": "Python" }, { "code": null, "e": 3155, "s": 3136, "text": "Technical Scripter" }, { "code": null, "e": 3253, "s": 3155, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3285, "s": 3253, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 3312, "s": 3285, "text": "Python Classes and Objects" }, { "code": null, "e": 3343, "s": 3312, "text": "Python | os.path.join() method" }, { "code": null, "e": 3366, "s": 3343, "text": "Introduction To PYTHON" }, { "code": null, "e": 3387, "s": 3366, "text": "Python OOPs Concepts" }, { "code": null, "e": 3443, "s": 3387, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 3485, "s": 3443, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 3527, "s": 3485, "text": "Check if element exists in list in Python" }, { "code": null, "e": 3566, "s": 3527, "text": "Python | Get unique values from a list" } ]
matplotlib.pyplot.polar() in Python
22 Apr, 2020 Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface. The polar() function in pyplot module of matplotlib library is used to make a polar plot. Syntax: matplotlib.pyplot.polar(*args, **kwargs) Parameters: This method does not accept any parameters. Returns: This method does not returns any value. Below examples illustrate the matplotlib.pyplot.polar() function in matplotlib.pyplot: Example #1: # Implementation of matplotlib functionimport matplotlib.pyplot as pltimport matplotlib.transforms as mtransformsimport numpy as np from matplotlib.transforms import offset_copy xs = np.arange(-2, 2)ys = np.cos(xs**2)plt.polar(xs, ys) plt.title('matplotlib.pyplot.polar() function Example', fontweight ="bold")plt.show() Output: Example #2: # Implementation of matplotlib functionimport matplotlib.pyplot as pltimport matplotlib.transforms as mtransformsimport numpy as np from matplotlib.transforms import offset_copy xs = np.arange(8)ys = np.cos(xs**2) fig = plt.figure(figsize =(5, 10))ax = plt.subplot(1, 1, 1) trans_offset = mtransforms.offset_copy(ax.transData, fig = fig, y = 6, units ='dots') for x, y in zip(xs, ys): plt.polar(x, y, 'go') plt.text(x, y, '% d, % d' % (int(x), int(y)), transform = trans_offset, horizontalalignment ='center', verticalalignment ='bottom') plt.title('matplotlib.pyplot.polar() function Example', fontweight ="bold")plt.show() Output: Python-matplotlib Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Python | os.path.join() method How to drop one or multiple columns in Pandas Dataframe Introduction To PYTHON How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | datetime.timedelta() function Python | Get unique values from a list
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Apr, 2020" }, { "code": null, "e": 223, "s": 28, "text": "Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface." }, { "code": null, "e": 313, "s": 223, "text": "The polar() function in pyplot module of matplotlib library is used to make a polar plot." }, { "code": null, "e": 362, "s": 313, "text": "Syntax: matplotlib.pyplot.polar(*args, **kwargs)" }, { "code": null, "e": 418, "s": 362, "text": "Parameters: This method does not accept any parameters." }, { "code": null, "e": 467, "s": 418, "text": "Returns: This method does not returns any value." }, { "code": null, "e": 554, "s": 467, "text": "Below examples illustrate the matplotlib.pyplot.polar() function in matplotlib.pyplot:" }, { "code": null, "e": 566, "s": 554, "text": "Example #1:" }, { "code": "# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport matplotlib.transforms as mtransformsimport numpy as np from matplotlib.transforms import offset_copy xs = np.arange(-2, 2)ys = np.cos(xs**2)plt.polar(xs, ys) plt.title('matplotlib.pyplot.polar() function Example', fontweight =\"bold\")plt.show()", "e": 929, "s": 566, "text": null }, { "code": null, "e": 937, "s": 929, "text": "Output:" }, { "code": null, "e": 949, "s": 937, "text": "Example #2:" }, { "code": "# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport matplotlib.transforms as mtransformsimport numpy as np from matplotlib.transforms import offset_copy xs = np.arange(8)ys = np.cos(xs**2) fig = plt.figure(figsize =(5, 10))ax = plt.subplot(1, 1, 1) trans_offset = mtransforms.offset_copy(ax.transData, fig = fig, y = 6, units ='dots') for x, y in zip(xs, ys): plt.polar(x, y, 'go') plt.text(x, y, '% d, % d' % (int(x), int(y)), transform = trans_offset, horizontalalignment ='center', verticalalignment ='bottom') plt.title('matplotlib.pyplot.polar() function Example', fontweight =\"bold\")plt.show()", "e": 1722, "s": 949, "text": null }, { "code": null, "e": 1730, "s": 1722, "text": "Output:" }, { "code": null, "e": 1748, "s": 1730, "text": "Python-matplotlib" }, { "code": null, "e": 1755, "s": 1748, "text": "Python" }, { "code": null, "e": 1853, "s": 1755, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1885, "s": 1853, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1912, "s": 1885, "text": "Python Classes and Objects" }, { "code": null, "e": 1933, "s": 1912, "text": "Python OOPs Concepts" }, { "code": null, "e": 1964, "s": 1933, "text": "Python | os.path.join() method" }, { "code": null, "e": 2020, "s": 1964, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 2043, "s": 2020, "text": "Introduction To PYTHON" }, { "code": null, "e": 2085, "s": 2043, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 2127, "s": 2085, "text": "Check if element exists in list in Python" }, { "code": null, "e": 2166, "s": 2127, "text": "Python | datetime.timedelta() function" } ]
Tailwind CSS Height
23 Mar, 2022 This class accepts lots of values in tailwind CSS in which all the properties are covered in class form. It is the alternative to the CSS height Property. This class is used to set the height of an element. The height class does not contain padding, margin, and the border of elements. Height classes: h-0: This class sets the height to zero. h-auto: This class sets the height according to the content. h-px: This class is used to set the height in 1px fix. h-1/2: This class sets the height to half of the window. h-1/3: This class sets the height to one-third of the window. h-1/4: This class sets the height to one-fourth of the window. h-1/5: This class sets the height to one-fifth of the window. h-1/6: This class sets the height to one-sixth of the window. h-full: This class sets an element’s height to 100% of its parent, as long as the parent has a defined height. h-screen: This class used to make an element span the entire height of the viewport. Note: You can change the number with the valid “rem” values or set the percentage value. h-0: This class is used to set the specific height for any element, you can change the number with a valid number of rem units to fix the height of the element. Syntax: <element class="h-0">...</element> Example: 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 Height Class</b> <div class="flex flex-wrap-reverse p-4 mx-12 space-x-4 h-64 bg-green-200"> <div class="h-8 w-12 bg-green-400 rounded-lg">h-8</div> <div class="h-12 w-12 bg-green-400 rounded-lg">h-12</div> <div class="h-16 w-12 bg-green-400 rounded-lg">h-16</div> <div class="h-20 w-12 bg-green-400 rounded-lg">h-20</div> <div class="h-24 w-12 bg-green-400 rounded-lg">h-24</div> <div class="h-32 w-12 bg-green-400 rounded-lg">h-32</div> <div class="h-40 w-12 bg-green-400 rounded-lg">h-40</div> <div class="h-48 w-12 bg-green-400 rounded-lg">h-48</div> <div class="h-52 w-12 bg-green-400 rounded-lg">h-52</div> </div></body> </html> Output: h-auto: This class is used to let the browser determine the height of the element. Syntax: <element class="h-auto">...</element> Example: 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 Height Class</b> <div class="mx-48 bg-green-200 p-8"> <div class="h-auto bg-green-400 rounded-lg">h-auto</div> </div></body> </html> Output: h-screen: This class is used to make an element span the entire height of the viewport. Syntax: <element class="h-screen">...</element> Example: 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 Height Class</b> <div class="mx-48 bg-green-200 p-8"> <div class="h-screen bg-green-400 rounded-lg">h-screen</div> </div></body> </html> Output: h-full: This class is used to set an element’s height to 100% of its parent, as long as the parent has a defined height. Syntax: <element class="h-full">...</element> Example: 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 Height Class</b> <div class="mx-48 h-48 bg-green-200 p-8"> <div class="h-full bg-green-400 rounded-lg">h-full</div> </div></body> </html> Output: Tailwind CSS Tailwind-Sizing CSS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to update Node.js and NPM to next version ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? How to create footer to stay at the bottom of a Web page? CSS to put icon inside an input element in a form Top 10 Projects For Beginners To Practice HTML and CSS Skills Installation of Node.js on Linux Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 28, "s": 0, "text": "\n23 Mar, 2022" }, { "code": null, "e": 315, "s": 28, "text": "This class accepts lots of values in tailwind CSS in which all the properties are covered in class form. It is the alternative to the CSS height Property. This class is used to set the height of an element. The height class does not contain padding, margin, and the border of elements." }, { "code": null, "e": 331, "s": 315, "text": "Height classes:" }, { "code": null, "e": 372, "s": 331, "text": "h-0: This class sets the height to zero." }, { "code": null, "e": 433, "s": 372, "text": "h-auto: This class sets the height according to the content." }, { "code": null, "e": 488, "s": 433, "text": "h-px: This class is used to set the height in 1px fix." }, { "code": null, "e": 545, "s": 488, "text": "h-1/2: This class sets the height to half of the window." }, { "code": null, "e": 607, "s": 545, "text": "h-1/3: This class sets the height to one-third of the window." }, { "code": null, "e": 670, "s": 607, "text": "h-1/4: This class sets the height to one-fourth of the window." }, { "code": null, "e": 732, "s": 670, "text": "h-1/5: This class sets the height to one-fifth of the window." }, { "code": null, "e": 794, "s": 732, "text": "h-1/6: This class sets the height to one-sixth of the window." }, { "code": null, "e": 905, "s": 794, "text": "h-full: This class sets an element’s height to 100% of its parent, as long as the parent has a defined height." }, { "code": null, "e": 990, "s": 905, "text": "h-screen: This class used to make an element span the entire height of the viewport." }, { "code": null, "e": 1079, "s": 990, "text": "Note: You can change the number with the valid “rem” values or set the percentage value." }, { "code": null, "e": 1240, "s": 1079, "text": "h-0: This class is used to set the specific height for any element, you can change the number with a valid number of rem units to fix the height of the element." }, { "code": null, "e": 1248, "s": 1240, "text": "Syntax:" }, { "code": null, "e": 1283, "s": 1248, "text": "<element class=\"h-0\">...</element>" }, { "code": null, "e": 1292, "s": 1283, "text": "Example:" }, { "code": null, "e": 1297, "s": 1292, "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 Height Class</b> <div class=\"flex flex-wrap-reverse p-4 mx-12 space-x-4 h-64 bg-green-200\"> <div class=\"h-8 w-12 bg-green-400 rounded-lg\">h-8</div> <div class=\"h-12 w-12 bg-green-400 rounded-lg\">h-12</div> <div class=\"h-16 w-12 bg-green-400 rounded-lg\">h-16</div> <div class=\"h-20 w-12 bg-green-400 rounded-lg\">h-20</div> <div class=\"h-24 w-12 bg-green-400 rounded-lg\">h-24</div> <div class=\"h-32 w-12 bg-green-400 rounded-lg\">h-32</div> <div class=\"h-40 w-12 bg-green-400 rounded-lg\">h-40</div> <div class=\"h-48 w-12 bg-green-400 rounded-lg\">h-48</div> <div class=\"h-52 w-12 bg-green-400 rounded-lg\">h-52</div> </div></body> </html>", "e": 2477, "s": 1297, "text": null }, { "code": null, "e": 2485, "s": 2477, "text": "Output:" }, { "code": null, "e": 2568, "s": 2485, "text": "h-auto: This class is used to let the browser determine the height of the element." }, { "code": null, "e": 2576, "s": 2568, "text": "Syntax:" }, { "code": null, "e": 2614, "s": 2576, "text": "<element class=\"h-auto\">...</element>" }, { "code": null, "e": 2623, "s": 2614, "text": "Example:" }, { "code": null, "e": 2628, "s": 2623, "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 Height Class</b> <div class=\"mx-48 bg-green-200 p-8\"> <div class=\"h-auto bg-green-400 rounded-lg\">h-auto</div> </div></body> </html>", "e": 3075, "s": 2628, "text": null }, { "code": null, "e": 3083, "s": 3075, "text": "Output:" }, { "code": null, "e": 3171, "s": 3083, "text": "h-screen: This class is used to make an element span the entire height of the viewport." }, { "code": null, "e": 3179, "s": 3171, "text": "Syntax:" }, { "code": null, "e": 3219, "s": 3179, "text": "<element class=\"h-screen\">...</element>" }, { "code": null, "e": 3228, "s": 3219, "text": "Example:" }, { "code": null, "e": 3233, "s": 3228, "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 Height Class</b> <div class=\"mx-48 bg-green-200 p-8\"> <div class=\"h-screen bg-green-400 rounded-lg\">h-screen</div> </div></body> </html>", "e": 3684, "s": 3233, "text": null }, { "code": null, "e": 3692, "s": 3684, "text": "Output:" }, { "code": null, "e": 3813, "s": 3692, "text": "h-full: This class is used to set an element’s height to 100% of its parent, as long as the parent has a defined height." }, { "code": null, "e": 3821, "s": 3813, "text": "Syntax:" }, { "code": null, "e": 3859, "s": 3821, "text": "<element class=\"h-full\">...</element>" }, { "code": null, "e": 3868, "s": 3859, "text": "Example:" }, { "code": null, "e": 3873, "s": 3868, "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 Height Class</b> <div class=\"mx-48 h-48 bg-green-200 p-8\"> <div class=\"h-full bg-green-400 rounded-lg\">h-full</div> </div></body> </html>", "e": 4325, "s": 3873, "text": null }, { "code": null, "e": 4333, "s": 4325, "text": "Output:" }, { "code": null, "e": 4346, "s": 4333, "text": "Tailwind CSS" }, { "code": null, "e": 4362, "s": 4346, "text": "Tailwind-Sizing" }, { "code": null, "e": 4366, "s": 4362, "text": "CSS" }, { "code": null, "e": 4383, "s": 4366, "text": "Web Technologies" }, { "code": null, "e": 4481, "s": 4383, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4529, "s": 4481, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 4591, "s": 4529, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 4641, "s": 4591, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 4699, "s": 4641, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 4749, "s": 4699, "text": "CSS to put icon inside an input element in a form" }, { "code": null, "e": 4811, "s": 4749, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 4844, "s": 4811, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 4905, "s": 4844, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 4955, "s": 4905, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
ASP.NET Core - Identity Configuration
In this chapter, we will install and configure the Identity framework, which takes just a little bit of work. If you go to the Visual Studio and create a new ASP.NET Core application, and you select the full web application template with authentication set to individual user accounts, that new project will include all the bits of the Identity framework set up for you. We started from an empty project. We will now set up the Identity framework from scratch, which is a good way to learn about all the pieces that are in the full application template because it can be confusing if you haven't worked your way through all the codes in detail. To get started, we will need to install the dependency, which is Microsoft.AspNet.Identity. We will proceed by installing Microsoft.AspNet.Identity.EntityFramework and then, implement the Identity framework that works with the Entity Framework. If we take a dependency on Identity.EntityFramework, the package is inclusive of the Identity package. If we take a dependency on Identity.EntityFramework, the package is inclusive of the Identity package. If you build your own data stores, you can work just with the Identity package. If you build your own data stores, you can work just with the Identity package. Once our dependencies are installed, we can create a customer User class with all the information we want to store about a user. Once our dependencies are installed, we can create a customer User class with all the information we want to store about a user. For this application, we are going to inherit from a class provided by the Identity framework and that class will give us all the essentials like the Username property and a place to store the hashed passwords. For this application, we are going to inherit from a class provided by the Identity framework and that class will give us all the essentials like the Username property and a place to store the hashed passwords. We will also need to modify our FirstAppDemoDbContext class to inherit from the Identity framework's IdentityDb class. We will also need to modify our FirstAppDemoDbContext class to inherit from the Identity framework's IdentityDb class. The IdentityDb gives us everything we need to store as user information with the Entity Framework. Once we have a User class and a DBContext set up, we will need to configure the Identity services into the application with the ConfigureServices method of the Startup class. The IdentityDb gives us everything we need to store as user information with the Entity Framework. Once we have a User class and a DBContext set up, we will need to configure the Identity services into the application with the ConfigureServices method of the Startup class. Just like when we needed to add services to support the MVC framework, the Identity framework needs services added to the application in order to work. Just like when we needed to add services to support the MVC framework, the Identity framework needs services added to the application in order to work. These services include services like the UserStore service and the SignInManager. These services include services like the UserStore service and the SignInManager. We will be injecting those services into our controller to create users and issue cookies at the appropriate time. We will be injecting those services into our controller to create users and issue cookies at the appropriate time. Finally, during the Configure method of startup, we will need to add the Identity middleware. Finally, during the Configure method of startup, we will need to add the Identity middleware. This middleware will not only help to turn cookies into a user identity, but also make sure that the user doesn't see an empty page with a 401 response. This middleware will not only help to turn cookies into a user identity, but also make sure that the user doesn't see an empty page with a 401 response. Let us now follow the steps given below. Step 1 − We need to proceed by adding a dependency on the Identity framework. Let us add Microsoft.AspNet.Identity.EntityFramework dependency into the project.json file. This will include all of the other necessary Identity packages that we need. { "version": "1.0.0-*", "compilationOptions": { "emitEntryPoint": true }, "dependencies": { "Microsoft.AspNet.Mvc": "6.0.0-rc1-final", "Microsoft.AspNet.Diagnostics": "1.0.0-rc1-final", "Microsoft.AspNet.IISPlatformHandler": "1.0.0-rc1-final", "Microsoft.AspNet.Server.Kestrel": "1.0.0-rc1-final", "Microsoft.AspNet.StaticFiles": "1.0.0-rc1-final", "EntityFramework.MicrosoftSqlServer": "7.0.0-rc1-final", "EntityFramework.Commands": "7.0.0-rc1-final", "Microsoft.AspNet.Mvc.TagHelpers": "6.0.0-rc1-final", "Microsoft.AspNet.Identity.EntityFramework": "3.0.0-rc1-final" }, "commands": { "web": "Microsoft.AspNet.Server.Kestrel", "ef": "EntityFramework.Commands" }, "frameworks": { "dnx451": { }, "dnxcore50": { } }, "exclude": [ "wwwroot", "node_modules" ], "publishExclude": [ "**.user", "**.vspscc" ] } Step 2 − Save this file. The Visual Studio restores the packages and now, we can add our User class. Let us add the User class by right-clicking on the Models folder and selecting Add → Class. Call this class User and click on the Add button as in the above screenshot. In this class, you can add properties to hold any information that you want to store about a user. Step 3 − Let us derive the User class from a class provided by the Identity framework. It is the IdentityUser class that is in the Identity.EntityFramework namespace. using Microsoft.AspNet.Identity.EntityFramework; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace FirstAppDemo.Models { public class User : IdentityUser { } } Step 4− Let us now go to the IdentityUser, put the cursor on that symbol, and press F12 to see the Visual Studio's metadata view. #region Assembly Microsoft.AspNet.Identity.EntityFramework, Version = 3.0.0.0, namespace Microsoft.AspNet.Identity.EntityFramework { public class IdentityUser : IdentityUser<string> { public IdentityUser(); public IdentityUser(string userName); } } Step 5 − You can see that IdentityUser is derived from the IdentityUser of the string. You can change the type of the primary key by deriving from the IdentityUser and specifying our generic type parameter. You can also store things with a primary key that is ideally an integer value. Step 6 − Let us now place the cursor on the IdentityUser of string and press F12 again to go to the metadata view. You can now see all the information related to a user by default. The information includes the following − The fields that we won't use in this application, but are available for use. The fields that we won't use in this application, but are available for use. The Identity framework can keep track of the number of failed login attempts for a particular user and can lock that account over a period of time. The Identity framework can keep track of the number of failed login attempts for a particular user and can lock that account over a period of time. The fields to store the PasswordHash, the PhoneNumber. The two important fields that we will be using are the PasswordHash and the UserName. The fields to store the PasswordHash, the PhoneNumber. The two important fields that we will be using are the PasswordHash and the UserName. We will also be implicitly using the primary key and the ID property of a user. You can also use that property if you need to query for a specific user. We will also be implicitly using the primary key and the ID property of a user. You can also use that property if you need to query for a specific user. Step 7 − Now, we need to make sure that the User is included in our DBContext. So, let us open the FirstAppDemoDBContext that we have in our application, and instead of deriving it directly from the DBContext, which is the built-in Entity Framework base class, we now need to derive it from the IdentityDbContext. using Microsoft.AspNet.Identity.EntityFramework; using Microsoft.Data.Entity; namespace FirstAppDemo.Models { public class FirstAppDemoDbContext : IdentityDbContext<User> { public DbSet<Employee> Employees { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { optionsBuilder.UseSqlServer("Data Source = (localdb)\\MSSQLLocalDB; Initial Catalog = FirstAppDemo;Integrated Security = True; Connect Timeout = 30;Encrypt = False;TrustServerCertificate = True; ApplicationIntent = ReadWrite;MultiSubnetFailover = False"); } } } Step 8 − The IdentityDbContext class is also in the Microsoft.AspNet.Identity.EntityFramework namespace and we can specify the type of user it should store. This way, any additional fields we add to the User class gets into the database. The IdentityDbContext brings additional DbSets, not just to store a user but also information about the user roles and the user claims. The IdentityDbContext brings additional DbSets, not just to store a user but also information about the user roles and the user claims. Our User class is ready now. Our FirstAppDemoDbContext class is configured to work with the Identity framework. Our User class is ready now. Our FirstAppDemoDbContext class is configured to work with the Identity framework. We can now go into Configure and ConfigureServices to set up the Identity framework. We can now go into Configure and ConfigureServices to set up the Identity framework. step 9 − Let us now start with ConfigureServices. In addition to our MVC services and our Entity Framework services, we need to add our Identity services. This will add all the services that the Identity framework relies on to do its work. public void ConfigureServices(IServiceCollection services) { services.AddMvc(); services.AddEntityFramework() .AddSqlServer() .AddDbContext<FirstAppDemoDbContext> (option => option.UseSqlServer(Configuration["database:connection"])); services.AddIdentity<User, IdentityRole>() .AddEntityFrameworkStores<FirstAppDemoDbContext>(); } The AddIdentity method takes two generic type parameters — the type of user entity and the type of role entity. The AddIdentity method takes two generic type parameters — the type of user entity and the type of role entity. The two generic type parameters are the types of our user — the User class we just created and the Role class that we want to work with. We will now use the built-in IdentityRole. This class is in the EntityFramework namespace. The two generic type parameters are the types of our user — the User class we just created and the Role class that we want to work with. We will now use the built-in IdentityRole. This class is in the EntityFramework namespace. When we are using the Entity Framework with Identity, we also need to invoke a second method − the AddEntityFrameworkStores. When we are using the Entity Framework with Identity, we also need to invoke a second method − the AddEntityFrameworkStores. The AddEntityFrameworkStores method will configure services like the UserStore, the service used to create users and validate their passwords. The AddEntityFrameworkStores method will configure services like the UserStore, the service used to create users and validate their passwords. Step 10 − The following two lines are all we need to configure the services for the application. services.AddIdentity<User, IdentityRole>() .AddEntityFrameworkStores<FirstAppDemoDbContext>(); Step 11 − We also need to add the middleware. The location of where we insert the middleware is important because if we insert the middleware too late in the pipeline, it will never have the chance to process a request. And if we require authorization checks inside our MVC controllers, we need to have the Identity middleware inserted before the MVC framework to make sure that cookies and also the 401 errors are processed successfully. public void Configure(IApplicationBuilder app) { app.UseIISPlatformHandler(); app.UseDeveloperExceptionPage(); app.UseRuntimeInfoPage(); app.UseFileServer(); app.UseIdentity(); app.UseMvc(ConfigureRoute); app.Run(async (context) => { var msg = Configuration["message"]; await context.Response.WriteAsync(msg); }); } Step 12 − The location where we insert the middleware is where we will add the Identity middleware. The following is the complete implementation of the Startup.cs file. using Microsoft.AspNet.Builder; using Microsoft.AspNet.Hosting; using Microsoft.AspNet.Http; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Configuration; using FirstAppDemo.Services; using Microsoft.AspNet.Routing; using System; using FirstAppDemo.Entities; using Microsoft.Data.Entity; using FirstAppDemo.Models; using Microsoft.AspNet.Identity.EntityFramework; namespace FirstAppDemo { public class Startup { public Startup() { var builder = new ConfigurationBuilder() .AddJsonFile("AppSettings.json"); Configuration = builder.Build(); } public IConfiguration Configuration { get; set; } // This method gets called by the runtime. // Use this method to add services to the container. // For more information on how to configure your application, // visit http://go.microsoft.com/fwlink/?LinkID = 398940 public void ConfigureServices(IServiceCollection services) { services.AddMvc(); services.AddEntityFramework() .AddSqlServer() .AddDbContext<FirstAppDemoDbContext>(option => option.UseSqlServer(Configuration["database:connection"])); services.AddIdentity<User, IdentityRole>() .AddEntityFrameworkStores<FirstAppDemoDbContext>(); } // This method gets called by the runtime. // Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app) { app.UseIISPlatformHandler(); app.UseDeveloperExceptionPage(); app.UseRuntimeInfoPage(); app.UseFileServer(); app.UseIdentity(); app.UseMvc(ConfigureRoute); app.Run(async (context) => { var msg = Configuration["message"]; await context.Response.WriteAsync(msg); }); } private void ConfigureRoute(IRouteBuilder routeBuilder) { //Home/Index routeBuilder.MapRoute("Default", "{controller=Home}/{action=Index}/{id?}"); } // Entry point for the application. public static void Main(string[] args) => WebApplication.Run<Startup>(args); } } Step 13 − Let us now move ahead by building the application. In the next chapter, we need to add another Entity Framework migration to make sure we have the Identity schema in our SQL Server database.
[ { "code": null, "e": 2966, "s": 2595, "text": "In this chapter, we will install and configure the Identity framework, which takes just a little bit of work. If you go to the Visual Studio and create a new ASP.NET Core application, and you select the full web application template with authentication set to individual user accounts, that new project will include all the bits of the Identity framework set up for you." }, { "code": null, "e": 3240, "s": 2966, "text": "We started from an empty project. We will now set up the Identity framework from scratch, which is a good way to learn about all the pieces that are in the full application template because it can be confusing if you haven't worked your way through all the codes in detail." }, { "code": null, "e": 3485, "s": 3240, "text": "To get started, we will need to install the dependency, which is Microsoft.AspNet.Identity. We will proceed by installing Microsoft.AspNet.Identity.EntityFramework and then, implement the Identity framework that works with the Entity Framework." }, { "code": null, "e": 3588, "s": 3485, "text": "If we take a dependency on Identity.EntityFramework, the package is inclusive of the Identity package." }, { "code": null, "e": 3691, "s": 3588, "text": "If we take a dependency on Identity.EntityFramework, the package is inclusive of the Identity package." }, { "code": null, "e": 3771, "s": 3691, "text": "If you build your own data stores, you can work just with the Identity package." }, { "code": null, "e": 3851, "s": 3771, "text": "If you build your own data stores, you can work just with the Identity package." }, { "code": null, "e": 3980, "s": 3851, "text": "Once our dependencies are installed, we can create a customer User class with all the information we want to store about a user." }, { "code": null, "e": 4109, "s": 3980, "text": "Once our dependencies are installed, we can create a customer User class with all the information we want to store about a user." }, { "code": null, "e": 4320, "s": 4109, "text": "For this application, we are going to inherit from a class provided by the Identity framework and that class will give us all the essentials like the Username property and a place to store the hashed passwords." }, { "code": null, "e": 4531, "s": 4320, "text": "For this application, we are going to inherit from a class provided by the Identity framework and that class will give us all the essentials like the Username property and a place to store the hashed passwords." }, { "code": null, "e": 4650, "s": 4531, "text": "We will also need to modify our FirstAppDemoDbContext class to inherit from the Identity framework's IdentityDb class." }, { "code": null, "e": 4769, "s": 4650, "text": "We will also need to modify our FirstAppDemoDbContext class to inherit from the Identity framework's IdentityDb class." }, { "code": null, "e": 5043, "s": 4769, "text": "The IdentityDb gives us everything we need to store as user information with the Entity Framework. Once we have a User class and a DBContext set up, we will need to configure the Identity services into the application with the ConfigureServices method of the Startup class." }, { "code": null, "e": 5317, "s": 5043, "text": "The IdentityDb gives us everything we need to store as user information with the Entity Framework. Once we have a User class and a DBContext set up, we will need to configure the Identity services into the application with the ConfigureServices method of the Startup class." }, { "code": null, "e": 5469, "s": 5317, "text": "Just like when we needed to add services to support the MVC framework, the Identity framework needs services added to the application in order to work." }, { "code": null, "e": 5621, "s": 5469, "text": "Just like when we needed to add services to support the MVC framework, the Identity framework needs services added to the application in order to work." }, { "code": null, "e": 5703, "s": 5621, "text": "These services include services like the UserStore service and the SignInManager." }, { "code": null, "e": 5785, "s": 5703, "text": "These services include services like the UserStore service and the SignInManager." }, { "code": null, "e": 5900, "s": 5785, "text": "We will be injecting those services into our controller to create users and issue cookies at the appropriate time." }, { "code": null, "e": 6015, "s": 5900, "text": "We will be injecting those services into our controller to create users and issue cookies at the appropriate time." }, { "code": null, "e": 6109, "s": 6015, "text": "Finally, during the Configure method of startup, we will need to add the Identity middleware." }, { "code": null, "e": 6203, "s": 6109, "text": "Finally, during the Configure method of startup, we will need to add the Identity middleware." }, { "code": null, "e": 6356, "s": 6203, "text": "This middleware will not only help to turn cookies into a user identity, but also make sure that the user doesn't see an empty page with a 401 response." }, { "code": null, "e": 6509, "s": 6356, "text": "This middleware will not only help to turn cookies into a user identity, but also make sure that the user doesn't see an empty page with a 401 response." }, { "code": null, "e": 6550, "s": 6509, "text": "Let us now follow the steps given below." }, { "code": null, "e": 6797, "s": 6550, "text": "Step 1 − We need to proceed by adding a dependency on the Identity framework. Let us add Microsoft.AspNet.Identity.EntityFramework dependency into the project.json file. This will include all of the other necessary Identity packages that we need." }, { "code": null, "e": 7806, "s": 6797, "text": "{ \n \"version\": \"1.0.0-*\", \n \"compilationOptions\": { \n \"emitEntryPoint\": true \n }, \n \n \"dependencies\": { \n \"Microsoft.AspNet.Mvc\": \"6.0.0-rc1-final\", \n \"Microsoft.AspNet.Diagnostics\": \"1.0.0-rc1-final\", \n \"Microsoft.AspNet.IISPlatformHandler\": \"1.0.0-rc1-final\", \n \"Microsoft.AspNet.Server.Kestrel\": \"1.0.0-rc1-final\", \n \"Microsoft.AspNet.StaticFiles\": \"1.0.0-rc1-final\", \n \"EntityFramework.MicrosoftSqlServer\": \"7.0.0-rc1-final\", \n \"EntityFramework.Commands\": \"7.0.0-rc1-final\", \n \"Microsoft.AspNet.Mvc.TagHelpers\": \"6.0.0-rc1-final\", \n \"Microsoft.AspNet.Identity.EntityFramework\": \"3.0.0-rc1-final\" \n }, \n \n \"commands\": { \n \"web\": \"Microsoft.AspNet.Server.Kestrel\", \n \"ef\": \"EntityFramework.Commands\" \n }, \n \n \"frameworks\": { \n \"dnx451\": { }, \n \"dnxcore50\": { } \n }, \n \n \"exclude\": [ \n \"wwwroot\", \n \"node_modules\" \n ], \n \n \"publishExclude\": [ \n \"**.user\", \n \"**.vspscc\" \n ] \n} " }, { "code": null, "e": 7999, "s": 7806, "text": "Step 2 − Save this file. The Visual Studio restores the packages and now, we can add our User class. Let us add the User class by right-clicking on the Models folder and selecting Add → Class." }, { "code": null, "e": 8175, "s": 7999, "text": "Call this class User and click on the Add button as in the above screenshot. In this class, you can add properties to hold any information that you want to store about a user." }, { "code": null, "e": 8342, "s": 8175, "text": "Step 3 − Let us derive the User class from a class provided by the Identity framework. It is the IdentityUser class that is in the Identity.EntityFramework namespace." }, { "code": null, "e": 8576, "s": 8342, "text": "using Microsoft.AspNet.Identity.EntityFramework; \n\nusing System; \nusing System.Collections.Generic; \nusing System.Linq; \nusing System.Threading.Tasks; \n\nnamespace FirstAppDemo.Models { \n public class User : IdentityUser { \n } \n}" }, { "code": null, "e": 8706, "s": 8576, "text": "Step 4− Let us now go to the IdentityUser, put the cursor on that symbol, and press F12 to see the Visual Studio's metadata view." }, { "code": null, "e": 8982, "s": 8706, "text": "#region Assembly Microsoft.AspNet.Identity.EntityFramework, Version = 3.0.0.0, \n\nnamespace Microsoft.AspNet.Identity.EntityFramework { \n public class IdentityUser : IdentityUser<string> { \n public IdentityUser(); \n public IdentityUser(string userName); \n } \n}" }, { "code": null, "e": 9268, "s": 8982, "text": "Step 5 − You can see that IdentityUser is derived from the IdentityUser of the string. You can change the type of the primary key by deriving from the IdentityUser and specifying our generic type parameter. You can also store things with a primary key that is ideally an integer value." }, { "code": null, "e": 9383, "s": 9268, "text": "Step 6 − Let us now place the cursor on the IdentityUser of string and press F12 again to go to the metadata view." }, { "code": null, "e": 9490, "s": 9383, "text": "You can now see all the information related to a user by default. The information includes the following −" }, { "code": null, "e": 9567, "s": 9490, "text": "The fields that we won't use in this application, but are available for use." }, { "code": null, "e": 9644, "s": 9567, "text": "The fields that we won't use in this application, but are available for use." }, { "code": null, "e": 9792, "s": 9644, "text": "The Identity framework can keep track of the number of failed login attempts for a particular user and can lock that account over a period of time." }, { "code": null, "e": 9940, "s": 9792, "text": "The Identity framework can keep track of the number of failed login attempts for a particular user and can lock that account over a period of time." }, { "code": null, "e": 10081, "s": 9940, "text": "The fields to store the PasswordHash, the PhoneNumber. The two important fields that we will be using are the PasswordHash and the UserName." }, { "code": null, "e": 10222, "s": 10081, "text": "The fields to store the PasswordHash, the PhoneNumber. The two important fields that we will be using are the PasswordHash and the UserName." }, { "code": null, "e": 10375, "s": 10222, "text": "We will also be implicitly using the primary key and the ID property of a user. You can also use that property if you need to query for a specific user." }, { "code": null, "e": 10528, "s": 10375, "text": "We will also be implicitly using the primary key and the ID property of a user. You can also use that property if you need to query for a specific user." }, { "code": null, "e": 10842, "s": 10528, "text": "Step 7 − Now, we need to make sure that the User is included in our DBContext. So, let us open the FirstAppDemoDBContext that we have in our application, and instead of deriving it directly from the DBContext, which is the built-in Entity Framework base class, we now need to derive it from the IdentityDbContext." }, { "code": null, "e": 11500, "s": 10842, "text": "using Microsoft.AspNet.Identity.EntityFramework; \nusing Microsoft.Data.Entity; \n\nnamespace FirstAppDemo.Models { \n public class FirstAppDemoDbContext : IdentityDbContext<User> { \n public DbSet<Employee> Employees { get; set; } \n \n protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { \n optionsBuilder.UseSqlServer(\"Data Source = (localdb)\\\\MSSQLLocalDB;\n Initial Catalog = FirstAppDemo;Integrated Security = True;\n Connect Timeout = 30;Encrypt = False;TrustServerCertificate = True;\n ApplicationIntent = ReadWrite;MultiSubnetFailover = False\"); \n } \n } \n} " }, { "code": null, "e": 11738, "s": 11500, "text": "Step 8 − The IdentityDbContext class is also in the Microsoft.AspNet.Identity.EntityFramework namespace and we can specify the type of user it should store. This way, any additional fields we add to the User class gets into the database." }, { "code": null, "e": 11874, "s": 11738, "text": "The IdentityDbContext brings additional DbSets, not just to store a user but also information about the user roles and the user claims." }, { "code": null, "e": 12010, "s": 11874, "text": "The IdentityDbContext brings additional DbSets, not just to store a user but also information about the user roles and the user claims." }, { "code": null, "e": 12122, "s": 12010, "text": "Our User class is ready now. Our FirstAppDemoDbContext class is configured to work with the Identity framework." }, { "code": null, "e": 12234, "s": 12122, "text": "Our User class is ready now. Our FirstAppDemoDbContext class is configured to work with the Identity framework." }, { "code": null, "e": 12319, "s": 12234, "text": "We can now go into Configure and ConfigureServices to set up the Identity framework." }, { "code": null, "e": 12404, "s": 12319, "text": "We can now go into Configure and ConfigureServices to set up the Identity framework." }, { "code": null, "e": 12644, "s": 12404, "text": "step 9 − Let us now start with ConfigureServices. In addition to our MVC services and our Entity Framework services, we need to add our Identity services. This will add all the services that the Identity framework relies on to do its work." }, { "code": null, "e": 13027, "s": 12644, "text": "public void ConfigureServices(IServiceCollection services) { \n services.AddMvc(); \n \n services.AddEntityFramework() \n .AddSqlServer() \n .AddDbContext<FirstAppDemoDbContext>\n (option => option.UseSqlServer(Configuration[\"database:connection\"])); \n \n services.AddIdentity<User, IdentityRole>() \n .AddEntityFrameworkStores<FirstAppDemoDbContext>(); \n}" }, { "code": null, "e": 13139, "s": 13027, "text": "The AddIdentity method takes two generic type parameters — the type of user entity and the type of role entity." }, { "code": null, "e": 13251, "s": 13139, "text": "The AddIdentity method takes two generic type parameters — the type of user entity and the type of role entity." }, { "code": null, "e": 13479, "s": 13251, "text": "The two generic type parameters are the types of our user — the User class we just created and the Role class that we want to work with. We will now use the built-in IdentityRole. This class is in the EntityFramework namespace." }, { "code": null, "e": 13707, "s": 13479, "text": "The two generic type parameters are the types of our user — the User class we just created and the Role class that we want to work with. We will now use the built-in IdentityRole. This class is in the EntityFramework namespace." }, { "code": null, "e": 13832, "s": 13707, "text": "When we are using the Entity Framework with Identity, we also need to invoke a second method − the AddEntityFrameworkStores." }, { "code": null, "e": 13957, "s": 13832, "text": "When we are using the Entity Framework with Identity, we also need to invoke a second method − the AddEntityFrameworkStores." }, { "code": null, "e": 14101, "s": 13957, "text": "The AddEntityFrameworkStores method will configure services like the UserStore, the service used to create users and validate their passwords." }, { "code": null, "e": 14245, "s": 14101, "text": "The AddEntityFrameworkStores method will configure services like the UserStore, the service used to create users and validate their passwords." }, { "code": null, "e": 14342, "s": 14245, "text": "Step 10 − The following two lines are all we need to configure the services for the application." }, { "code": null, "e": 14442, "s": 14342, "text": "services.AddIdentity<User, IdentityRole>() \n .AddEntityFrameworkStores<FirstAppDemoDbContext>();\n" }, { "code": null, "e": 14662, "s": 14442, "text": "Step 11 − We also need to add the middleware. The location of where we insert the middleware is important because if we insert the middleware too late in the pipeline, it will never have the chance to process a request." }, { "code": null, "e": 14881, "s": 14662, "text": "And if we require authorization checks inside our MVC controllers, we need to have the Identity middleware inserted before the MVC framework to make sure that cookies and also the 401 errors are processed successfully." }, { "code": null, "e": 15265, "s": 14881, "text": "public void Configure(IApplicationBuilder app) { \n app.UseIISPlatformHandler(); \n \n app.UseDeveloperExceptionPage(); \n app.UseRuntimeInfoPage(); \n \n app.UseFileServer(); \n \n app.UseIdentity(); \n app.UseMvc(ConfigureRoute); \n \n app.Run(async (context) => { \n var msg = Configuration[\"message\"]; \n await context.Response.WriteAsync(msg); \n }); \n} " }, { "code": null, "e": 15434, "s": 15265, "text": "Step 12 − The location where we insert the middleware is where we will add the Identity middleware. The following is the complete implementation of the Startup.cs file." }, { "code": null, "e": 17708, "s": 15434, "text": "using Microsoft.AspNet.Builder; \nusing Microsoft.AspNet.Hosting; \nusing Microsoft.AspNet.Http;\n\nusing Microsoft.Extensions.DependencyInjection; \nusing Microsoft.Extensions.Configuration; \n\nusing FirstAppDemo.Services; \nusing Microsoft.AspNet.Routing; \nusing System; \n\nusing FirstAppDemo.Entities; \nusing Microsoft.Data.Entity; \n\nusing FirstAppDemo.Models; \nusing Microsoft.AspNet.Identity.EntityFramework; \n\nnamespace FirstAppDemo { \n public class Startup { \n public Startup() { \n var builder = new ConfigurationBuilder() \n .AddJsonFile(\"AppSettings.json\"); \n Configuration = builder.Build(); \n } \n public IConfiguration Configuration { get; set; } \n \n // This method gets called by the runtime.\n // Use this method to add services to the container. \n // For more information on how to configure your application, \n // visit http://go.microsoft.com/fwlink/?LinkID = 398940 \n public void ConfigureServices(IServiceCollection services) { \n services.AddMvc(); \n services.AddEntityFramework() \n .AddSqlServer() \n .AddDbContext<FirstAppDemoDbContext>(option => \n option.UseSqlServer(Configuration[\"database:connection\"])); \n \n services.AddIdentity<User, IdentityRole>() \n .AddEntityFrameworkStores<FirstAppDemoDbContext>(); \n }\n // This method gets called by the runtime. \n // Use this method to configure the HTTP request pipeline. \n public void Configure(IApplicationBuilder app) { \n app.UseIISPlatformHandler(); \n app.UseDeveloperExceptionPage(); \n app.UseRuntimeInfoPage(); \n app.UseFileServer(); \n app.UseIdentity(); \n app.UseMvc(ConfigureRoute); \n \n app.Run(async (context) => { \n var msg = Configuration[\"message\"]; \n await context.Response.WriteAsync(msg); \n }); \n } \n private void ConfigureRoute(IRouteBuilder routeBuilder) { \n //Home/Index \n routeBuilder.MapRoute(\"Default\", \"{controller=Home}/{action=Index}/{id?}\"); \n } \n // Entry point for the application. \n public static void Main(string[] args) => WebApplication.Run<Startup>(args); \n } \n}" } ]
How to validate if input in input field has ASCII characters using express-validator ?
24 Dec, 2021 In HTML forms, we often required validation of different types. Validate existing email, validate password length, validate confirm password, validate to allow only integer inputs, these are some examples of validation. In a certain input field, only Ascii characters are allowed i.e. there is not allowed any Non-ASCII characters (Ex: ñ). We can also validate these input fields to accept only ASCII characters using express-validator middleware. Command to install express-validator: npm install express-validator Steps to use express-validator to implement the logic: Install express-validator middleware. Create a validator.js file to code all the validation logic. Validate input by validateInputField: check(input field name) and chain on the validation isAscii() with ‘ . ‘ Use the validation name(validateInputField) in the routes as a middleware as an array of validations. Destructure ‘validationResult’ function from express-validator to use it to find any errors. If error occurs redirect to the same page passing the error information. If error list is empty, give access to the user for the subsequent request. Note: Here we use local or custom database to implement the logic, the same steps can be followed to implement the logic in a regular database like MongoDB or MySql. Example: This example illustrates how to validate an input field to accept only ascii characters. Filename – index.js javascript const express = require('express')const bodyParser = require('body-parser')const {validationResult} = require('express-validator')const repo = require('./repository')const { validateAsciiCharacters } = require('./validator')const formTemplet = require('./form') const app = express()const port = process.env.PORT || 3000 // The body-parser middleware to parse form dataapp.use(bodyParser.urlencoded({extended : true})) // Get route to display HTML form to submit ascii textapp.get('/', (req, res) => { res.send(formTemplet({}))}) // Post route to handle form submission logic andapp.post( '/register/ascii', [validateAsciiCharacters], async (req, res) => { const errors = validationResult(req) if(!errors.isEmpty()){ return res.send(formTemplet({errors})) } const {submittedBy, ascii} = req.body await repo.create({submittedBy, ascii}) res.send('Ascii Characters registered successfully')}) // Server setupapp.listen(port, () => { console.log(`Server start on port ${port}`)}) Filename – repository.js: This file contains all the logic to create a local database and interact with it. javascript // Importing node.js file system moduleconst fs = require('fs') class Repository { constructor(filename) { // The filename where datas are going to store if(!filename) { throw new Error( 'Filename is required to create a datastore!') } this.filename = filename try { fs.accessSync(this.filename) } catch(err) { // If file not exist it is created // with empty array fs.writeFileSync(this.filename, '[]') } } // Get all existing records async getAll(){ return JSON.parse( await fs.promises.readFile(this.filename, { encoding : 'utf8' }) ) } // Create new record async create(attrs){ const records = await this.getAll() records.push(attrs) await fs.promises.writeFile( this.filename, JSON.stringify(records, null, 2) ) return attrs }} // The 'datastore.json' file created at// runtime and all the information provided// via signup form store in this file in// JSON format.module.exports = new Repository('datastore.json') Filename – form.js: This file contains logic to show the form to submit Ascii text. javascript const getError = (errors, prop) => { try { return errors.mapped()[prop].msg } catch (error) { return '' }} module.exports = ({errors}) => { return ` <!DOCTYPE html> <html> <head> <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/bulma/0.9.0/css/bulma.min.css'> <style> div.columns{ margin-top: 100px; } .button{ margin-top : 10px } </style> </head> <body> <div class='container'> <div class='columns is-centered'> <div class='column is-5'> <form action='/register/ascii' method='POST'> <div> <div> <label class='label' id='submittedBy'> Submitted By </label> </div> <input class='input' type='text' name='submittedBy' placeholder='SubmittedBy' for='submittedBy'> </div> <div> <div> <label class='label' id='ascii'> Ascii Characters </label> </div> <input class='input' type='text' name='ascii' placeholder='Ascii characters' for='ascii'> <p class="help is-danger"> ${getError(errors, 'ascii')} </p> </div> <div> <button class='button is-primary'> Submit </button> </div> </form> </div> </div> </div> </body> </html> `} Filename – validator.js: This file contain all the validation logic(Logic to validate a input field to accept only ascii characters). javascript const {check} = require('express-validator')const repo = require('./repository')module.exports = { validateAsciiCharacters : check('ascii') // To delete leading and trailing space .trim() // Validate minimum length of ascii text // Optional for this context .isLength({min:8}) .withMessage('Please submit minimum 8 characters long Ascii text') // Validate input field to accept only ascii chars .isAscii() .withMessage('Must be Ascii characters only') } Filename – package.json package.json file Database: Database Output: Attempt to submit form when Ascii characters input field contains non ascii characters Response when attempt to submit form where Ascii characters input field contains non ascii characters Attempt to submit form when Ascii characters input field contains only ascii characters Response when attempt to submit form where Ascii characters input field contains only ascii characters Database after successful form submission: Database after successful form submission Note: We have used some Bulma classes(CSS framework) in the signup.js file to design the content. kk773572498 Express.js Node.js-Misc Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n24 Dec, 2021" }, { "code": null, "e": 477, "s": 28, "text": "In HTML forms, we often required validation of different types. Validate existing email, validate password length, validate confirm password, validate to allow only integer inputs, these are some examples of validation. In a certain input field, only Ascii characters are allowed i.e. there is not allowed any Non-ASCII characters (Ex: ñ). We can also validate these input fields to accept only ASCII characters using express-validator middleware." }, { "code": null, "e": 515, "s": 477, "text": "Command to install express-validator:" }, { "code": null, "e": 545, "s": 515, "text": "npm install express-validator" }, { "code": null, "e": 600, "s": 545, "text": "Steps to use express-validator to implement the logic:" }, { "code": null, "e": 638, "s": 600, "text": "Install express-validator middleware." }, { "code": null, "e": 699, "s": 638, "text": "Create a validator.js file to code all the validation logic." }, { "code": null, "e": 810, "s": 699, "text": "Validate input by validateInputField: check(input field name) and chain on the validation isAscii() with ‘ . ‘" }, { "code": null, "e": 912, "s": 810, "text": "Use the validation name(validateInputField) in the routes as a middleware as an array of validations." }, { "code": null, "e": 1005, "s": 912, "text": "Destructure ‘validationResult’ function from express-validator to use it to find any errors." }, { "code": null, "e": 1078, "s": 1005, "text": "If error occurs redirect to the same page passing the error information." }, { "code": null, "e": 1154, "s": 1078, "text": "If error list is empty, give access to the user for the subsequent request." }, { "code": null, "e": 1320, "s": 1154, "text": "Note: Here we use local or custom database to implement the logic, the same steps can be followed to implement the logic in a regular database like MongoDB or MySql." }, { "code": null, "e": 1418, "s": 1320, "text": "Example: This example illustrates how to validate an input field to accept only ascii characters." }, { "code": null, "e": 1438, "s": 1418, "text": "Filename – index.js" }, { "code": null, "e": 1449, "s": 1438, "text": "javascript" }, { "code": "const express = require('express')const bodyParser = require('body-parser')const {validationResult} = require('express-validator')const repo = require('./repository')const { validateAsciiCharacters } = require('./validator')const formTemplet = require('./form') const app = express()const port = process.env.PORT || 3000 // The body-parser middleware to parse form dataapp.use(bodyParser.urlencoded({extended : true})) // Get route to display HTML form to submit ascii textapp.get('/', (req, res) => { res.send(formTemplet({}))}) // Post route to handle form submission logic andapp.post( '/register/ascii', [validateAsciiCharacters], async (req, res) => { const errors = validationResult(req) if(!errors.isEmpty()){ return res.send(formTemplet({errors})) } const {submittedBy, ascii} = req.body await repo.create({submittedBy, ascii}) res.send('Ascii Characters registered successfully')}) // Server setupapp.listen(port, () => { console.log(`Server start on port ${port}`)})", "e": 2454, "s": 1449, "text": null }, { "code": null, "e": 2562, "s": 2454, "text": "Filename – repository.js: This file contains all the logic to create a local database and interact with it." }, { "code": null, "e": 2573, "s": 2562, "text": "javascript" }, { "code": "// Importing node.js file system moduleconst fs = require('fs') class Repository { constructor(filename) { // The filename where datas are going to store if(!filename) { throw new Error( 'Filename is required to create a datastore!') } this.filename = filename try { fs.accessSync(this.filename) } catch(err) { // If file not exist it is created // with empty array fs.writeFileSync(this.filename, '[]') } } // Get all existing records async getAll(){ return JSON.parse( await fs.promises.readFile(this.filename, { encoding : 'utf8' }) ) } // Create new record async create(attrs){ const records = await this.getAll() records.push(attrs) await fs.promises.writeFile( this.filename, JSON.stringify(records, null, 2) ) return attrs }} // The 'datastore.json' file created at// runtime and all the information provided// via signup form store in this file in// JSON format.module.exports = new Repository('datastore.json')", "e": 3614, "s": 2573, "text": null }, { "code": null, "e": 3698, "s": 3614, "text": "Filename – form.js: This file contains logic to show the form to submit Ascii text." }, { "code": null, "e": 3709, "s": 3698, "text": "javascript" }, { "code": "const getError = (errors, prop) => { try { return errors.mapped()[prop].msg } catch (error) { return '' }} module.exports = ({errors}) => { return ` <!DOCTYPE html> <html> <head> <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/bulma/0.9.0/css/bulma.min.css'> <style> div.columns{ margin-top: 100px; } .button{ margin-top : 10px } </style> </head> <body> <div class='container'> <div class='columns is-centered'> <div class='column is-5'> <form action='/register/ascii' method='POST'> <div> <div> <label class='label' id='submittedBy'> Submitted By </label> </div> <input class='input' type='text' name='submittedBy' placeholder='SubmittedBy' for='submittedBy'> </div> <div> <div> <label class='label' id='ascii'> Ascii Characters </label> </div> <input class='input' type='text' name='ascii' placeholder='Ascii characters' for='ascii'> <p class=\"help is-danger\"> ${getError(errors, 'ascii')} </p> </div> <div> <button class='button is-primary'> Submit </button> </div> </form> </div> </div> </div> </body> </html> `}", "e": 5512, "s": 3709, "text": null }, { "code": null, "e": 5646, "s": 5512, "text": "Filename – validator.js: This file contain all the validation logic(Logic to validate a input field to accept only ascii characters)." }, { "code": null, "e": 5657, "s": 5646, "text": "javascript" }, { "code": "const {check} = require('express-validator')const repo = require('./repository')module.exports = { validateAsciiCharacters : check('ascii') // To delete leading and trailing space .trim() // Validate minimum length of ascii text // Optional for this context .isLength({min:8}) .withMessage('Please submit minimum 8 characters long Ascii text') // Validate input field to accept only ascii chars .isAscii() .withMessage('Must be Ascii characters only') }", "e": 6145, "s": 5657, "text": null }, { "code": null, "e": 6169, "s": 6145, "text": "Filename – package.json" }, { "code": null, "e": 6187, "s": 6169, "text": "package.json file" }, { "code": null, "e": 6197, "s": 6187, "text": "Database:" }, { "code": null, "e": 6206, "s": 6197, "text": "Database" }, { "code": null, "e": 6214, "s": 6206, "text": "Output:" }, { "code": null, "e": 6301, "s": 6214, "text": "Attempt to submit form when Ascii characters input field contains non ascii characters" }, { "code": null, "e": 6403, "s": 6301, "text": "Response when attempt to submit form where Ascii characters input field contains non ascii characters" }, { "code": null, "e": 6491, "s": 6403, "text": "Attempt to submit form when Ascii characters input field contains only ascii characters" }, { "code": null, "e": 6594, "s": 6491, "text": "Response when attempt to submit form where Ascii characters input field contains only ascii characters" }, { "code": null, "e": 6637, "s": 6594, "text": "Database after successful form submission:" }, { "code": null, "e": 6679, "s": 6637, "text": "Database after successful form submission" }, { "code": null, "e": 6777, "s": 6679, "text": "Note: We have used some Bulma classes(CSS framework) in the signup.js file to design the content." }, { "code": null, "e": 6789, "s": 6777, "text": "kk773572498" }, { "code": null, "e": 6800, "s": 6789, "text": "Express.js" }, { "code": null, "e": 6813, "s": 6800, "text": "Node.js-Misc" }, { "code": null, "e": 6821, "s": 6813, "text": "Node.js" }, { "code": null, "e": 6838, "s": 6821, "text": "Web Technologies" } ]
Creating a one-dimensional NumPy array
02 Sep, 2020 One dimensional array contains elements only in one dimension. In other words, the shape of the NumPy array should contain only one value in the tuple. Let us see how to create 1 dimensional NumPy arrays. Method 1: First make a list then pass it in numpy.array() Python3 # importing the moduleimport numpy as np # creating the listlist = [100, 200, 300, 400] # creating 1-d arrayn = np.array(list)print(n) Output: [100 200 300 400] Method 2: fromiter() is useful for creating non-numeric sequence type array however it can create any type of array. Here we will convert a string into a NumPy array of characters. Python3 # imporint gthe moduleimport numpy as np # creating the stringstr = "geeksforgeeks" # creating 1-d arrayx = np.fromiter(str, dtype = 'U2')print(x) Output: ['g' 'e' 'e' 'k' 's' 'f' 'o' 'r' 'g' 'e' 'e' 'k' 's'] Method 3: arange() returns evenly spaced values within a given interval. Python3 # importing the moduleimport numpy as np # creating 1-d arrayx = np.arange(3, 10, 2)print(x) Output: [3 5 7 9] Method 4: linspace() creates evenly space numerical elements between two given limits. Python3 # importing the moduleimport numpy as np # creating 1-d arrayx = np.linspace(3, 10, 3)print(x) Output: [ 3. 6.5 10. ] Python numpy-arrayCreation Python-numpy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Python | os.path.join() method Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python | Get unique values from a list Python | datetime.timedelta() function
[ { "code": null, "e": 28, "s": 0, "text": "\n02 Sep, 2020" }, { "code": null, "e": 233, "s": 28, "text": "One dimensional array contains elements only in one dimension. In other words, the shape of the NumPy array should contain only one value in the tuple. Let us see how to create 1 dimensional NumPy arrays." }, { "code": null, "e": 291, "s": 233, "text": "Method 1: First make a list then pass it in numpy.array()" }, { "code": null, "e": 299, "s": 291, "text": "Python3" }, { "code": "# importing the moduleimport numpy as np # creating the listlist = [100, 200, 300, 400] # creating 1-d arrayn = np.array(list)print(n)", "e": 436, "s": 299, "text": null }, { "code": null, "e": 444, "s": 436, "text": "Output:" }, { "code": null, "e": 462, "s": 444, "text": "[100 200 300 400]" }, { "code": null, "e": 643, "s": 462, "text": "Method 2: fromiter() is useful for creating non-numeric sequence type array however it can create any type of array. Here we will convert a string into a NumPy array of characters." }, { "code": null, "e": 651, "s": 643, "text": "Python3" }, { "code": "# imporint gthe moduleimport numpy as np # creating the stringstr = \"geeksforgeeks\" # creating 1-d arrayx = np.fromiter(str, dtype = 'U2')print(x)", "e": 800, "s": 651, "text": null }, { "code": null, "e": 808, "s": 800, "text": "Output:" }, { "code": null, "e": 862, "s": 808, "text": "['g' 'e' 'e' 'k' 's' 'f' 'o' 'r' 'g' 'e' 'e' 'k' 's']" }, { "code": null, "e": 935, "s": 862, "text": "Method 3: arange() returns evenly spaced values within a given interval." }, { "code": null, "e": 943, "s": 935, "text": "Python3" }, { "code": "# importing the moduleimport numpy as np # creating 1-d arrayx = np.arange(3, 10, 2)print(x)", "e": 1037, "s": 943, "text": null }, { "code": null, "e": 1045, "s": 1037, "text": "Output:" }, { "code": null, "e": 1055, "s": 1045, "text": "[3 5 7 9]" }, { "code": null, "e": 1142, "s": 1055, "text": "Method 4: linspace() creates evenly space numerical elements between two given limits." }, { "code": null, "e": 1150, "s": 1142, "text": "Python3" }, { "code": "# importing the moduleimport numpy as np # creating 1-d arrayx = np.linspace(3, 10, 3)print(x)", "e": 1246, "s": 1150, "text": null }, { "code": null, "e": 1254, "s": 1246, "text": "Output:" }, { "code": null, "e": 1271, "s": 1254, "text": "[ 3. 6.5 10. ]" }, { "code": null, "e": 1298, "s": 1271, "text": "Python numpy-arrayCreation" }, { "code": null, "e": 1311, "s": 1298, "text": "Python-numpy" }, { "code": null, "e": 1318, "s": 1311, "text": "Python" }, { "code": null, "e": 1416, "s": 1318, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1448, "s": 1416, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1475, "s": 1448, "text": "Python Classes and Objects" }, { "code": null, "e": 1496, "s": 1475, "text": "Python OOPs Concepts" }, { "code": null, "e": 1519, "s": 1496, "text": "Introduction To PYTHON" }, { "code": null, "e": 1575, "s": 1519, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 1606, "s": 1575, "text": "Python | os.path.join() method" }, { "code": null, "e": 1648, "s": 1606, "text": "Check if element exists in list in Python" }, { "code": null, "e": 1690, "s": 1648, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 1729, "s": 1690, "text": "Python | Get unique values from a list" } ]
Find sum of even factors of a number
23 Jun, 2022 Given a number n, the task is to find the even factor sum of a number.Examples: Input : 30 Output : 48 Even dividers sum 2 + 6 + 10 + 30 = 48 Input : 18 Output : 26 Even dividers sum 2 + 6 + 18 = 26 Prerequisite : Sum of factorsAs discussed in above mentioned previous post, sum of factors of a number isLet p1, p2, ... pk be prime factors of n. Let a1, a2, .. ak be highest powers of p1, p2, .. pk respectively that divide n, i.e., we can write n as n = (p1a1)*(p2a2)* ... (pkak). Sum of divisors = (1 + p1 + p12 ... p1a1) * (1 + p2 + p22 ... p2a2) * ........................... (1 + pk + pk2 ... pkak) If number is odd, then there are no even factors, so we simply return 0.If number is even, we use above formula. We only need to ignore 20. All other terms multiply to produce even factor sum. For example, consider n = 18. It can be written as 2132 and sun of all factors is (20 + 21)*(30 + 31 + 32). if we remove 20 then we get the Sum of even factors (2)*(1+3+32) = 26.To remove odd number in even factor, we ignore then 20 which is 1. After this step, we only get even factors. Note that 2 is the only even prime. Below is the implementation of the above approach. C++ Java Python3 C# PHP Javascript // Formula based CPP program to find sum of all// divisors of n.#include <bits/stdc++.h>using namespace std; // Returns sum of all factors of n.int sumofFactors(int n){ // If n is odd, then there are no even factors. if (n % 2 != 0) return 0; // Traversing through all prime factors. int res = 1; for (int i = 2; i <= sqrt(n); i++) { // While i divides n, print i and divide n int count = 0, curr_sum = 1, curr_term = 1; while (n % i == 0) { count++; n = n / i; // here we remove the 2^0 that is 1. All // other factors if (i == 2 && count == 1) curr_sum = 0; curr_term *= i; curr_sum += curr_term; } res *= curr_sum; } // This condition is to handle the case when n // is a prime number. if (n >= 2) res *= (1 + n); return res;} // Driver codeint main(){ int n = 18; cout << sumofFactors(n); return 0;} // Formula based Java program to // find sum of all divisors of n.import java.util.*;import java.lang.*; public class GfG{ // Returns sum of all factors of n. public static int sumofFactors(int n) { // If n is odd, then there // are no even factors. if (n % 2 != 0) return 0; // Traversing through all prime // factors. int res = 1; for (int i = 2; i <= Math.sqrt(n); i++) { int count = 0, curr_sum = 1; int curr_term = 1; // While i divides n, print i and // divide n while (n % i == 0) { count++; n = n / i; // here we remove the 2^0 that // is 1. All other factors if (i == 2 && count == 1) curr_sum = 0; curr_term *= i; curr_sum += curr_term; } res *= curr_sum; } // This condition is to handle the // case when n is a prime number. if (n >= 2) res *= (1 + n); return res; } // Driver function public static void main(String argc[]){ int n = 18; System.out.println(sumofFactors(n)); } } /* This code is contributed by Sagar Shukla */ # Formula based Python3# program to find sum# of alldivisors of n.import math # Returns sum of all# factors of n.def sumofFactors(n) : # If n is odd, then # there are no even # factors. if (n % 2 != 0) : return 0 # Traversing through # all prime factors. res = 1 for i in range(2, (int)(math.sqrt(n)) + 1) : # While i divides n # print i and divide n count = 0 curr_sum = 1 curr_term = 1 while (n % i == 0) : count= count + 1 n = n // i # here we remove the # 2^0 that is 1. All # other factors if (i == 2 and count == 1) : curr_sum = 0 curr_term = curr_term * i curr_sum = curr_sum + curr_term res = res * curr_sum # This condition is to # handle the case when # n is a prime number. if (n >= 2) : res = res * (1 + n) return res # Driver coden = 18print(sumofFactors(n)) # This code is contributed by Nikita Tiwari. // Formula based C# program to// find sum of all divisors of n.using System; public class GfG { // Returns sum of all factors of n. public static int sumofFactors(int n) { // If n is odd, then there // are no even factors. if (n % 2 != 0) return 0; // Traversing through all prime factors. int res = 1; for (int i = 2; i <= Math.Sqrt(n); i++) { int count = 0, curr_sum = 1; int curr_term = 1; // While i divides n, print i // and divide n while (n % i == 0) { count++; n = n / i; // here we remove the 2^0 that // is 1. All other factors if (i == 2 && count == 1) curr_sum = 0; curr_term *= i; curr_sum += curr_term; } res *= curr_sum; } // This condition is to handle the // case when n is a prime number. if (n >= 2) res *= (1 + n); return res; } // Driver Code public static void Main() { int n = 18; Console.WriteLine(sumofFactors(n)); } } // This code is contributed by vt_m <?php// Formula based php program to find sum// of all divisors of n. // Returns sum of all factors of n.function sumofFactors($n){ // If n is odd, then there are no // even factors. if ($n % 2 != 0) return 0; // Traversing through all prime factors. $res = 1; for ($i = 2; $i <= sqrt($n); $i++) { // While i divides n, print i // and divide n $count = 0; $curr_sum = 1; $curr_term = 1; while ($n % $i == 0) { $count++; $n = floor($n / $i); // here we remove the 2^0 // that is 1. All other // factors if ($i == 2 && $count == 1) $curr_sum = 0; $curr_term *= $i; $curr_sum += $curr_term; } $res *= $curr_sum; } // This condition is to handle the // case when n is a prime number. if ($n >= 2) $res *= (1 + $n); return $res;} // Driver code $n = 18; echo sumofFactors($n); // This code is contributed by mits?> <script> // javascript program to // find sum of all divisors of n. // Returns sum of all factors of n. function sumofFactors(n) { // If n is odd, then there // are no even factors. if (n % 2 != 0) return 0; // Traversing through all prime // factors. let res = 1; for (let i = 2; i <= Math.sqrt(n); i++) { let count = 0, curr_sum = 1; let curr_term = 1; // While i divides n, print i and // divide n while (n % i == 0) { count++; n = n / i; // here we remove the 2^0 that // is 1. All other factors if (i == 2 && count == 1) curr_sum = 0; curr_term *= i; curr_sum += curr_term; } res *= curr_sum; } // This condition is to handle the // case when n is a prime number. if (n >= 2) res *= (1 + n); return res; } // Driver Function let n = 18; document.write(sumofFactors(n)); // This code is contributed by susmitakundugoaldanga.</script> Output: 26 Time Complexity: O(√n log n) Auxiliary Space: O(1) Please suggest if someone has a better solution which is more efficient in terms of space and time.This article is contributed by Aarti_Rathi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above Mithun Kumar susmitakundugoaldanga vinayedula codewithshinchan number-theory prime-factor Mathematical number-theory Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Program for Fibonacci numbers Set in C++ Standard Template Library (STL) Write a program to print all permutations of a given string C++ Data Types Merge two sorted arrays Coin Change | DP-7 Operators in C / C++ Prime Numbers Program to find GCD or HCF of two numbers Find minimum number of coins that make a given value
[ { "code": null, "e": 54, "s": 26, "text": "\n23 Jun, 2022" }, { "code": null, "e": 136, "s": 54, "text": "Given a number n, the task is to find the even factor sum of a number.Examples: " }, { "code": null, "e": 256, "s": 136, "text": "Input : 30\nOutput : 48\nEven dividers sum 2 + 6 + 10 + 30 = 48\n\nInput : 18\nOutput : 26\nEven dividers sum 2 + 6 + 18 = 26" }, { "code": null, "e": 542, "s": 258, "text": "Prerequisite : Sum of factorsAs discussed in above mentioned previous post, sum of factors of a number isLet p1, p2, ... pk be prime factors of n. Let a1, a2, .. ak be highest powers of p1, p2, .. pk respectively that divide n, i.e., we can write n as n = (p1a1)*(p2a2)* ... (pkak). " }, { "code": null, "e": 720, "s": 542, "text": "Sum of divisors = (1 + p1 + p12 ... p1a1) * \n (1 + p2 + p22 ... p2a2) *\n ...........................\n (1 + pk + pk2 ... pkak) " }, { "code": null, "e": 1290, "s": 720, "text": "If number is odd, then there are no even factors, so we simply return 0.If number is even, we use above formula. We only need to ignore 20. All other terms multiply to produce even factor sum. For example, consider n = 18. It can be written as 2132 and sun of all factors is (20 + 21)*(30 + 31 + 32). if we remove 20 then we get the Sum of even factors (2)*(1+3+32) = 26.To remove odd number in even factor, we ignore then 20 which is 1. After this step, we only get even factors. Note that 2 is the only even prime. Below is the implementation of the above approach. " }, { "code": null, "e": 1294, "s": 1290, "text": "C++" }, { "code": null, "e": 1299, "s": 1294, "text": "Java" }, { "code": null, "e": 1307, "s": 1299, "text": "Python3" }, { "code": null, "e": 1310, "s": 1307, "text": "C#" }, { "code": null, "e": 1314, "s": 1310, "text": "PHP" }, { "code": null, "e": 1325, "s": 1314, "text": "Javascript" }, { "code": "// Formula based CPP program to find sum of all// divisors of n.#include <bits/stdc++.h>using namespace std; // Returns sum of all factors of n.int sumofFactors(int n){ // If n is odd, then there are no even factors. if (n % 2 != 0) return 0; // Traversing through all prime factors. int res = 1; for (int i = 2; i <= sqrt(n); i++) { // While i divides n, print i and divide n int count = 0, curr_sum = 1, curr_term = 1; while (n % i == 0) { count++; n = n / i; // here we remove the 2^0 that is 1. All // other factors if (i == 2 && count == 1) curr_sum = 0; curr_term *= i; curr_sum += curr_term; } res *= curr_sum; } // This condition is to handle the case when n // is a prime number. if (n >= 2) res *= (1 + n); return res;} // Driver codeint main(){ int n = 18; cout << sumofFactors(n); return 0;}", "e": 2317, "s": 1325, "text": null }, { "code": "// Formula based Java program to // find sum of all divisors of n.import java.util.*;import java.lang.*; public class GfG{ // Returns sum of all factors of n. public static int sumofFactors(int n) { // If n is odd, then there // are no even factors. if (n % 2 != 0) return 0; // Traversing through all prime // factors. int res = 1; for (int i = 2; i <= Math.sqrt(n); i++) { int count = 0, curr_sum = 1; int curr_term = 1; // While i divides n, print i and // divide n while (n % i == 0) { count++; n = n / i; // here we remove the 2^0 that // is 1. All other factors if (i == 2 && count == 1) curr_sum = 0; curr_term *= i; curr_sum += curr_term; } res *= curr_sum; } // This condition is to handle the // case when n is a prime number. if (n >= 2) res *= (1 + n); return res; } // Driver function public static void main(String argc[]){ int n = 18; System.out.println(sumofFactors(n)); } } /* This code is contributed by Sagar Shukla */", "e": 3650, "s": 2317, "text": null }, { "code": "# Formula based Python3# program to find sum# of alldivisors of n.import math # Returns sum of all# factors of n.def sumofFactors(n) : # If n is odd, then # there are no even # factors. if (n % 2 != 0) : return 0 # Traversing through # all prime factors. res = 1 for i in range(2, (int)(math.sqrt(n)) + 1) : # While i divides n # print i and divide n count = 0 curr_sum = 1 curr_term = 1 while (n % i == 0) : count= count + 1 n = n // i # here we remove the # 2^0 that is 1. All # other factors if (i == 2 and count == 1) : curr_sum = 0 curr_term = curr_term * i curr_sum = curr_sum + curr_term res = res * curr_sum # This condition is to # handle the case when # n is a prime number. if (n >= 2) : res = res * (1 + n) return res # Driver coden = 18print(sumofFactors(n)) # This code is contributed by Nikita Tiwari.", "e": 4718, "s": 3650, "text": null }, { "code": "// Formula based C# program to// find sum of all divisors of n.using System; public class GfG { // Returns sum of all factors of n. public static int sumofFactors(int n) { // If n is odd, then there // are no even factors. if (n % 2 != 0) return 0; // Traversing through all prime factors. int res = 1; for (int i = 2; i <= Math.Sqrt(n); i++) { int count = 0, curr_sum = 1; int curr_term = 1; // While i divides n, print i // and divide n while (n % i == 0) { count++; n = n / i; // here we remove the 2^0 that // is 1. All other factors if (i == 2 && count == 1) curr_sum = 0; curr_term *= i; curr_sum += curr_term; } res *= curr_sum; } // This condition is to handle the // case when n is a prime number. if (n >= 2) res *= (1 + n); return res; } // Driver Code public static void Main() { int n = 18; Console.WriteLine(sumofFactors(n)); } } // This code is contributed by vt_m", "e": 5985, "s": 4718, "text": null }, { "code": "<?php// Formula based php program to find sum// of all divisors of n. // Returns sum of all factors of n.function sumofFactors($n){ // If n is odd, then there are no // even factors. if ($n % 2 != 0) return 0; // Traversing through all prime factors. $res = 1; for ($i = 2; $i <= sqrt($n); $i++) { // While i divides n, print i // and divide n $count = 0; $curr_sum = 1; $curr_term = 1; while ($n % $i == 0) { $count++; $n = floor($n / $i); // here we remove the 2^0 // that is 1. All other // factors if ($i == 2 && $count == 1) $curr_sum = 0; $curr_term *= $i; $curr_sum += $curr_term; } $res *= $curr_sum; } // This condition is to handle the // case when n is a prime number. if ($n >= 2) $res *= (1 + $n); return $res;} // Driver code $n = 18; echo sumofFactors($n); // This code is contributed by mits?>", "e": 7016, "s": 5985, "text": null }, { "code": "<script> // javascript program to // find sum of all divisors of n. // Returns sum of all factors of n. function sumofFactors(n) { // If n is odd, then there // are no even factors. if (n % 2 != 0) return 0; // Traversing through all prime // factors. let res = 1; for (let i = 2; i <= Math.sqrt(n); i++) { let count = 0, curr_sum = 1; let curr_term = 1; // While i divides n, print i and // divide n while (n % i == 0) { count++; n = n / i; // here we remove the 2^0 that // is 1. All other factors if (i == 2 && count == 1) curr_sum = 0; curr_term *= i; curr_sum += curr_term; } res *= curr_sum; } // This condition is to handle the // case when n is a prime number. if (n >= 2) res *= (1 + n); return res; } // Driver Function let n = 18; document.write(sumofFactors(n)); // This code is contributed by susmitakundugoaldanga.</script>", "e": 8252, "s": 7016, "text": null }, { "code": null, "e": 8262, "s": 8252, "text": "Output: " }, { "code": null, "e": 8265, "s": 8262, "text": "26" }, { "code": null, "e": 8316, "s": 8265, "text": "Time Complexity: O(√n log n) Auxiliary Space: O(1)" }, { "code": null, "e": 8584, "s": 8316, "text": "Please suggest if someone has a better solution which is more efficient in terms of space and time.This article is contributed by Aarti_Rathi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 8597, "s": 8584, "text": "Mithun Kumar" }, { "code": null, "e": 8619, "s": 8597, "text": "susmitakundugoaldanga" }, { "code": null, "e": 8630, "s": 8619, "text": "vinayedula" }, { "code": null, "e": 8647, "s": 8630, "text": "codewithshinchan" }, { "code": null, "e": 8661, "s": 8647, "text": "number-theory" }, { "code": null, "e": 8674, "s": 8661, "text": "prime-factor" }, { "code": null, "e": 8687, "s": 8674, "text": "Mathematical" }, { "code": null, "e": 8701, "s": 8687, "text": "number-theory" }, { "code": null, "e": 8714, "s": 8701, "text": "Mathematical" }, { "code": null, "e": 8812, "s": 8714, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 8842, "s": 8812, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 8885, "s": 8842, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 8945, "s": 8885, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 8960, "s": 8945, "text": "C++ Data Types" }, { "code": null, "e": 8984, "s": 8960, "text": "Merge two sorted arrays" }, { "code": null, "e": 9003, "s": 8984, "text": "Coin Change | DP-7" }, { "code": null, "e": 9024, "s": 9003, "text": "Operators in C / C++" }, { "code": null, "e": 9038, "s": 9024, "text": "Prime Numbers" }, { "code": null, "e": 9080, "s": 9038, "text": "Program to find GCD or HCF of two numbers" } ]
Users in Linux System Administration
05 Jan, 2019 Users are accounts that can be used to login into a system. Each user is identified by a unique identification number or UID by the system. All the information of users in a system are stored in /etc/passwd file. The hashed passwords for users are stored in /etc/shadow file. Users can be divided into two categories on the basis of the level of access: Superuser/root/administrator : Access to all the files on the system.Normal users : Limited access. Superuser/root/administrator : Access to all the files on the system. Normal users : Limited access. When a new user is created, by default system takes following actions: Assigns UID to the user. Creates a home directory /home/. Sets the default shell of the user to be /bin/sh. Creates a private user group, named after the username itself. Contents of /etc/skel are copied to the home directory of the new user. .bashrc, .bash_profile and .bash_logout are copied to the home directory of new user.These files provide environment variables for this user’s session. This file is readable by any user but only root as read and write permissions for it. This file consists of the following colon separated information about users in a system: Username fieldPassword fieldAn `x` in this field denotes that the encrypted password is stored in the /etc/shadow file.The user ID number (UID)User’s group ID number (GID)Additional information field such as the full name of the user or comment (GECOS)Absolute path of user’s home directoryLogin shell of the user Username field Password fieldAn `x` in this field denotes that the encrypted password is stored in the /etc/shadow file. An `x` in this field denotes that the encrypted password is stored in the /etc/shadow file. The user ID number (UID) User’s group ID number (GID) Additional information field such as the full name of the user or comment (GECOS) Absolute path of user’s home directory Login shell of the user Syntax: [username]:[password]:[UID]:[GID]:[GECOS]:[home_dir]:[shell_path] Example: This file is readable and writable by only by root user. This file consists of the following colon separated information about password of users in a system: User name fieldPassword fieldContains an encrypted password.A blank entry, {:: }, indicates that a password is not required to login into that user’s account.An asterisk, {:*:}, indicates the account has been disabled.Last Password ChangeThis field denotes the number of days since the date of last password change counted since UNIX time (1-Jan-1970).The minimum number of days after which the user can change his password.Password validityDenotes the number of days after which the password will expire.Warning periodDenotes the number of days before the password expiry date, from which the user will start receiving warning notification for password change.Account validityDenotes the number of days after which the account will be disabled, once the password is expired.Account disabilityThis field denotes the number of days since which the account had been disabled counted from UNIX time (1-Jan-1970). User name field Password field Contains an encrypted password.A blank entry, {:: }, indicates that a password is not required to login into that user’s account.An asterisk, {:*:}, indicates the account has been disabled. A blank entry, {:: }, indicates that a password is not required to login into that user’s account. An asterisk, {:*:}, indicates the account has been disabled. Last Password ChangeThis field denotes the number of days since the date of last password change counted since UNIX time (1-Jan-1970). This field denotes the number of days since the date of last password change counted since UNIX time (1-Jan-1970). The minimum number of days after which the user can change his password. Password validityDenotes the number of days after which the password will expire. Denotes the number of days after which the password will expire. Warning periodDenotes the number of days before the password expiry date, from which the user will start receiving warning notification for password change. Denotes the number of days before the password expiry date, from which the user will start receiving warning notification for password change. Account validityDenotes the number of days after which the account will be disabled, once the password is expired. Denotes the number of days after which the account will be disabled, once the password is expired. Account disabilityThis field denotes the number of days since which the account had been disabled counted from UNIX time (1-Jan-1970). This field denotes the number of days since which the account had been disabled counted from UNIX time (1-Jan-1970). Syntax: [username]:[enc_pwd]:[last_pwd_change]:[pwd_validity]:[warn_date]:[acc_validity]:[acc_disablity] Example: linux-command Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n05 Jan, 2019" }, { "code": null, "e": 329, "s": 53, "text": "Users are accounts that can be used to login into a system. Each user is identified by a unique identification number or UID by the system. All the information of users in a system are stored in /etc/passwd file. The hashed passwords for users are stored in /etc/shadow file." }, { "code": null, "e": 407, "s": 329, "text": "Users can be divided into two categories on the basis of the level of access:" }, { "code": null, "e": 507, "s": 407, "text": "Superuser/root/administrator : Access to all the files on the system.Normal users : Limited access." }, { "code": null, "e": 577, "s": 507, "text": "Superuser/root/administrator : Access to all the files on the system." }, { "code": null, "e": 608, "s": 577, "text": "Normal users : Limited access." }, { "code": null, "e": 679, "s": 608, "text": "When a new user is created, by default system takes following actions:" }, { "code": null, "e": 704, "s": 679, "text": "Assigns UID to the user." }, { "code": null, "e": 737, "s": 704, "text": "Creates a home directory /home/." }, { "code": null, "e": 787, "s": 737, "text": "Sets the default shell of the user to be /bin/sh." }, { "code": null, "e": 850, "s": 787, "text": "Creates a private user group, named after the username itself." }, { "code": null, "e": 922, "s": 850, "text": "Contents of /etc/skel are copied to the home directory of the new user." }, { "code": null, "e": 1074, "s": 922, "text": ".bashrc, .bash_profile and .bash_logout are copied to the home directory of new user.These files provide environment variables for this user’s session." }, { "code": null, "e": 1249, "s": 1074, "text": "This file is readable by any user but only root as read and write permissions for it. This file consists of the following colon separated information about users in a system:" }, { "code": null, "e": 1563, "s": 1249, "text": "Username fieldPassword fieldAn `x` in this field denotes that the encrypted password is stored in the /etc/shadow file.The user ID number (UID)User’s group ID number (GID)Additional information field such as the full name of the user or comment (GECOS)Absolute path of user’s home directoryLogin shell of the user" }, { "code": null, "e": 1578, "s": 1563, "text": "Username field" }, { "code": null, "e": 1684, "s": 1578, "text": "Password fieldAn `x` in this field denotes that the encrypted password is stored in the /etc/shadow file." }, { "code": null, "e": 1776, "s": 1684, "text": "An `x` in this field denotes that the encrypted password is stored in the /etc/shadow file." }, { "code": null, "e": 1801, "s": 1776, "text": "The user ID number (UID)" }, { "code": null, "e": 1830, "s": 1801, "text": "User’s group ID number (GID)" }, { "code": null, "e": 1912, "s": 1830, "text": "Additional information field such as the full name of the user or comment (GECOS)" }, { "code": null, "e": 1951, "s": 1912, "text": "Absolute path of user’s home directory" }, { "code": null, "e": 1975, "s": 1951, "text": "Login shell of the user" }, { "code": null, "e": 1983, "s": 1975, "text": "Syntax:" }, { "code": null, "e": 2050, "s": 1983, "text": "[username]:[password]:[UID]:[GID]:[GECOS]:[home_dir]:[shell_path]\n" }, { "code": null, "e": 2059, "s": 2050, "text": "Example:" }, { "code": null, "e": 2217, "s": 2059, "text": "This file is readable and writable by only by root user. This file consists of the following colon separated information about password of users in a system:" }, { "code": null, "e": 3127, "s": 2217, "text": "User name fieldPassword fieldContains an encrypted password.A blank entry, {:: }, indicates that a password is not required to login into that user’s account.An asterisk, {:*:}, indicates the account has been disabled.Last Password ChangeThis field denotes the number of days since the date of last password change counted since UNIX time (1-Jan-1970).The minimum number of days after which the user can change his password.Password validityDenotes the number of days after which the password will expire.Warning periodDenotes the number of days before the password expiry date, from which the user will start receiving warning notification for password change.Account validityDenotes the number of days after which the account will be disabled, once the password is expired.Account disabilityThis field denotes the number of days since which the account had been disabled counted from UNIX time (1-Jan-1970)." }, { "code": null, "e": 3143, "s": 3127, "text": "User name field" }, { "code": null, "e": 3158, "s": 3143, "text": "Password field" }, { "code": null, "e": 3348, "s": 3158, "text": "Contains an encrypted password.A blank entry, {:: }, indicates that a password is not required to login into that user’s account.An asterisk, {:*:}, indicates the account has been disabled." }, { "code": null, "e": 3447, "s": 3348, "text": "A blank entry, {:: }, indicates that a password is not required to login into that user’s account." }, { "code": null, "e": 3508, "s": 3447, "text": "An asterisk, {:*:}, indicates the account has been disabled." }, { "code": null, "e": 3643, "s": 3508, "text": "Last Password ChangeThis field denotes the number of days since the date of last password change counted since UNIX time (1-Jan-1970)." }, { "code": null, "e": 3758, "s": 3643, "text": "This field denotes the number of days since the date of last password change counted since UNIX time (1-Jan-1970)." }, { "code": null, "e": 3831, "s": 3758, "text": "The minimum number of days after which the user can change his password." }, { "code": null, "e": 3913, "s": 3831, "text": "Password validityDenotes the number of days after which the password will expire." }, { "code": null, "e": 3978, "s": 3913, "text": "Denotes the number of days after which the password will expire." }, { "code": null, "e": 4135, "s": 3978, "text": "Warning periodDenotes the number of days before the password expiry date, from which the user will start receiving warning notification for password change." }, { "code": null, "e": 4278, "s": 4135, "text": "Denotes the number of days before the password expiry date, from which the user will start receiving warning notification for password change." }, { "code": null, "e": 4393, "s": 4278, "text": "Account validityDenotes the number of days after which the account will be disabled, once the password is expired." }, { "code": null, "e": 4492, "s": 4393, "text": "Denotes the number of days after which the account will be disabled, once the password is expired." }, { "code": null, "e": 4627, "s": 4492, "text": "Account disabilityThis field denotes the number of days since which the account had been disabled counted from UNIX time (1-Jan-1970)." }, { "code": null, "e": 4744, "s": 4627, "text": "This field denotes the number of days since which the account had been disabled counted from UNIX time (1-Jan-1970)." }, { "code": null, "e": 4752, "s": 4744, "text": "Syntax:" }, { "code": null, "e": 4850, "s": 4752, "text": "[username]:[enc_pwd]:[last_pwd_change]:[pwd_validity]:[warn_date]:[acc_validity]:[acc_disablity]\n" }, { "code": null, "e": 4859, "s": 4850, "text": "Example:" }, { "code": null, "e": 4873, "s": 4859, "text": "linux-command" }, { "code": null, "e": 4884, "s": 4873, "text": "Linux-Unix" } ]
MySQL Select Statement DISTINCT for Multiple Columns?
To understand the MySQL select statement DISTINCT for multiple columns, let us see an example and create a table. The query to create a table is as follows mysql> create table selectDistinctDemo -> ( -> InstructorId int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> StudentId int, -> TechnicalSubject varchar(100) -> ); Query OK, 0 rows affected (0.50 sec) Insert some records in the table using insert command. The query is as follows mysql> insert into selectDistinctDemo(StudentId,TechnicalSubject) values(121,'Java'); Query OK, 1 row affected (0.15 sec) mysql> insert into selectDistinctDemo(StudentId,TechnicalSubject) values(121,'MongoDB'); Query OK, 1 row affected (0.16 sec) mysql> insert into selectDistinctDemo(StudentId,TechnicalSubject) values(121,'MySQL'); Query OK, 1 row affected (0.15 sec) mysql> insert into selectDistinctDemo(StudentId,TechnicalSubject) values(298,'Python'); Query OK, 1 row affected (0.11 sec) mysql> insert into selectDistinctDemo(StudentId,TechnicalSubject) values(298,'SQL Server'); Query OK, 1 row affected (0.15 sec) mysql> insert into selectDistinctDemo(StudentId,TechnicalSubject) values(397,'C#'); Query OK, 1 row affected (0.13 sec) Display all records from the table using a select statement. The query is as follows mysql> select *from selectDistinctDemo; The following is the output +--------------+-----------+------------------+ | InstructorId | StudentId | TechnicalSubject | +--------------+-----------+------------------+ | 1 | 121 | Java | | 2 | 121 | MongoDB | | 3 | 121 | MySQL | | 4 | 298 | Python | | 5 | 298 | SQL Server | | 6 | 397 | C# | +--------------+-----------+------------------+ 6 rows in set (0.00 sec) Here is the query to use select statement DISTINCT for multiple columns mysql> select InstructorId,StudentId,TechnicalSubject from selectDistinctDemo -> where InstructorId IN -> ( -> select max(InstructorId) from selectDistinctDemo -> group by StudentId -> ) -> order by InstructorId desc; The following is the output +--------------+-----------+------------------+ | InstructorId | StudentId | TechnicalSubject | +--------------+-----------+------------------+ | 6 | 397 | C# | | 5 | 298 | SQL Server | | 3 | 121 | MySQL | +--------------+-----------+------------------+ 3 rows in set (0.10 sec)
[ { "code": null, "e": 1218, "s": 1062, "text": "To understand the MySQL select statement DISTINCT for multiple columns, let us see an example and create a table. The query to create a table is as follows" }, { "code": null, "e": 1428, "s": 1218, "text": "mysql> create table selectDistinctDemo\n -> (\n -> InstructorId int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n -> StudentId int,\n -> TechnicalSubject varchar(100)\n -> );\nQuery OK, 0 rows affected (0.50 sec)" }, { "code": null, "e": 1507, "s": 1428, "text": "Insert some records in the table using insert command. The query is as follows" }, { "code": null, "e": 2249, "s": 1507, "text": "mysql> insert into selectDistinctDemo(StudentId,TechnicalSubject) values(121,'Java');\nQuery OK, 1 row affected (0.15 sec)\nmysql> insert into selectDistinctDemo(StudentId,TechnicalSubject) values(121,'MongoDB');\nQuery OK, 1 row affected (0.16 sec)\nmysql> insert into selectDistinctDemo(StudentId,TechnicalSubject) values(121,'MySQL');\nQuery OK, 1 row affected (0.15 sec)\nmysql> insert into selectDistinctDemo(StudentId,TechnicalSubject) values(298,'Python');\nQuery OK, 1 row affected (0.11 sec)\nmysql> insert into selectDistinctDemo(StudentId,TechnicalSubject) values(298,'SQL Server');\nQuery OK, 1 row affected (0.15 sec)\nmysql> insert into selectDistinctDemo(StudentId,TechnicalSubject) values(397,'C#');\nQuery OK, 1 row affected (0.13 sec)" }, { "code": null, "e": 2334, "s": 2249, "text": "Display all records from the table using a select statement. The query is as follows" }, { "code": null, "e": 2374, "s": 2334, "text": "mysql> select *from selectDistinctDemo;" }, { "code": null, "e": 2402, "s": 2374, "text": "The following is the output" }, { "code": null, "e": 2907, "s": 2402, "text": "+--------------+-----------+------------------+\n| InstructorId | StudentId | TechnicalSubject |\n+--------------+-----------+------------------+\n| 1 | 121 | Java |\n| 2 | 121 | MongoDB |\n| 3 | 121 | MySQL |\n| 4 | 298 | Python |\n| 5 | 298 | SQL Server |\n| 6 | 397 | C# |\n+--------------+-----------+------------------+\n6 rows in set (0.00 sec)" }, { "code": null, "e": 2979, "s": 2907, "text": "Here is the query to use select statement DISTINCT for multiple columns" }, { "code": null, "e": 3209, "s": 2979, "text": "mysql> select InstructorId,StudentId,TechnicalSubject from selectDistinctDemo\n-> where InstructorId IN\n -> (\n -> select max(InstructorId) from selectDistinctDemo\n -> group by StudentId\n -> )\n-> order by InstructorId desc;" }, { "code": null, "e": 3237, "s": 3209, "text": "The following is the output" }, { "code": null, "e": 3598, "s": 3237, "text": "+--------------+-----------+------------------+\n| InstructorId | StudentId | TechnicalSubject |\n+--------------+-----------+------------------+\n| 6 | 397 | C# |\n| 5 | 298 | SQL Server |\n| 3 | 121 | MySQL |\n+--------------+-----------+------------------+\n3 rows in set (0.10 sec)" } ]
3 Super Simple Projects to Learn Natural Language Processing using Python | by Eric Kleppen | Towards Data Science
Working in Data Science and having a background in Technical Writing, I was drawn to the field of Natural Language Processing (NLP). Machines understanding language fascinates me, and I often ponder which algorithms Aristotle would have used to build a rhetorical analysis machine if he had the chance. If you’re new to Data Science, getting into NLP can seem complicated, especially since there have been so many recent advancements in the field. It is hard to know where to start. These three super simple projects will give you an introduction to concepts and techniques used in Natural Language Processing. Word CloudSentiment AnalysisSpam Detection The data used for these projects is the spam email data set, and it can be found with all of the code in my GitHub: github.com While a computer can actually be quite good at finding patterns and summarizing documents, it must transform words into numbers before making sense of them. This transformation is needed because machines “learn” thanks to mathematics, and math doesn’t work very well on words. Before transforming the words into numbers, they are often cleaned of things like special characters and punctuation, and modified into forms that make them more uniform and interpretable. Cleaning the words is often called preprocessing, and that is the focus of project 1: Word Cloud. Start by importing the dependencies and the data. The data is stored as a comma separated values (csv) file, so I will use pandas’ read_csv() function to open it into a DataFrame. import pandas as pdimport sqlite3import regex as reimport matplotlib.pyplot as pltfrom wordcloud import WordCloud#create dataframe from csvdf = pd.read_csv('emails.csv')df.head() Before anything, it is best to do a quick analysis of the data to eliminate duplicate rows and establish some baseline counts. I use pandas drop_duplicates to drop the duplicate rows. print("spam count: " +str(len(df.loc[df.spam==1])))print("not spam count: " +str(len(df.loc[df.spam==0])))print(df.shape)df['spam'] = df['spam'].astype(int)df = df.drop_duplicates()df = df.reset_index(inplace = False)[['text','spam']]print(df.shape) Word clouds are a useful way to visualize text data because they make understanding word frequencies easier. Words that appear more frequently within the email text appear larger in the cloud. Word Clouds make it easy to identify “key words.” Notice in the word cloud image, all the text is lower case. There are no punctuation marks or special characters. That’s because the text has been cleaned to make it easier to analyze. Using regular expressions, it is easy to clean the text using a loop: clean_desc = []for w in range(len(df.text)): desc = df['text'][w].lower() #remove punctuation desc = re.sub('[^a-zA-Z]', ' ', desc) #remove tags desc=re.sub("&lt;/?.*?&gt;"," &lt;&gt; ",desc) #remove digits and special chars desc=re.sub("(\\d|\\W)+"," ",desc) clean_desc.append(desc)#assign the cleaned descriptions to the data framedf['text'] = clean_desc df.head(3) Notice I create an empty list clean_desc, then use a for loop to go through the text line by line, setting it to lower case, removing punctuation and special chars, and appending it to the list. Then I replace the text column with the data in the clean_desc list. Stop words are the most common words like “the” and “of.” Removing them from the email text allows the more relevant frequent words to stand out. Removing stop words is a common technique! Some Python libraries like NLTK come pre-loaded with a list of stop words, but it is easy to create one from scratch. stop_words = ['is','you','your','and', 'the', 'to', 'from', 'or', 'I', 'for', 'do', 'get', 'not', 'here', 'in', 'im', 'have', 'on', 're', 'new', 'subject'] Notice I include a few email related words like “re” and “subject.” It is up to the analyst to determine what words should be included or excluded. Sometimes it is beneficial to include all words! Conveniently there is a Python library for creating word clouds. It can be installed using pip. pip install wordcloud When constructing the word cloud, it is possible to set several parameters like height and width, stop words, and max words. It is even possible to shape it instead of displaying the default rectangle. wordcloud = WordCloud(width = 800, height = 800, background_color = 'black', stopwords = stop_words, max_words = 1000 , min_font_size = 20).generate(str(df1['text']))#plot the word cloudfig = plt.figure(figsize = (8,8), facecolor = None)plt.imshow(wordcloud)plt.axis('off')plt.show() The word cloud can be saved and displayed using matplotlib and .show(). This is the result of all records, regardless of it being spam. Push the exercise further by splitting the data frame and making two word clouds to help analyze the difference between key words used in spam email and not spam email. This is a binary classification problem since an email can either be spam (1) or not spam (0). I want to build a machine learneing model that can identify whether or not an email is spam. I am going to use the Python library Scikit-Learn to explore tokenization, vectorization, and statistical classification algorithms. Import the Scikit-Learn functionality we need to transform and model the data. I will use CountVectorizer, train_test_split, ensemble models, and a couple metrics. from sklearn.feature_extraction.text import CountVectorizerfrom sklearn.model_selection import train_test_splitfrom sklearn import ensemble from sklearn.metrics import classification_report, accuracy_score In project 1, the text was cleaned. When you look at a word cloud, notice it is primarily single words. The larger the word, the higher its frequency. To prevent the word cloud from outputting sentences, the text goes through a processes called tokenization. It is the process of breaking down a sentence into the individual words. The individual words are called tokens. Using SciKit-Learn’s CountVectorizer(), it is easy to transform the body of text into a sparse matrix of numbers that the computer can pass to machine learning algorithms. To simplify the concept of count vectorization, imagine you have two sentences: The dog is whiteThe cat is black Converting the sentences to a vector space model would transform them in such a way that looks at the words in all sentences, and then represents the words in the sentence with a number. The dog cat is white blackThe dog is white = [1,1,0,1,1,0]The cat is black = [1,0,1,1,0,1] We can show this using code as well. I’ll add a third sentence to show that it counts the tokens. #list of sentencestext = ["the dog is white", "the cat is black", "the cat and the dog are friends"]#instantiate the classcv = CountVectorizer()#tokenize and build vocabcv.fit(text)print(cv.vocabulary_)#transform the textvector = cv.transform(text)print(vector.toarray()) Notice in the last vector, you can see a 2 since the word “the” appears twice. The CountVectorizer is counting the tokens and allowing me to construct the sparse matrix containing the transformed words to numbers. Because the model doesn’t take word placement into account, and instead mixes the words up as if they were tiles in a scrabble game, this is called the bag of words method. I am going to create the sparse matrix, then split the data using sk-learn train_test_split(). text_vec = CountVectorizer().fit_transform(df['text'])X_train, X_test, y_train, y_test = train_test_split(text_vec, df['spam'], test_size = 0.45, random_state = 42, shuffle = True) Notice I set the sparse matrix text_vec to X and the df[‘spam’] column to Y. I shuffle and take a test size of 45%. I highly recommend experimenting with several classifiers and determine which one works best for this scenario. In this example, I am using the GradientBoostingClassifier() model from the Scikit-Learn Ensemble collection. classifier = ensemble.GradientBoostingClassifier( n_estimators = 100, #how many decision trees to build learning_rate = 0.5, #learning rate max_depth = 6) Each algorithm will have its own set of parameters you can tweak. That is called hyper-parameter tuning. Go through the documentation to learn more about each of the parameters used in the models. Finally, we fit the data, call predict and generate the classification report. Using classification_report(), it is easy to build a text report showing the main classification metrics. classifier.fit(X_train, y_train)predictions = classifier.predict(X_test)print(classification_report(y_test, predictions)) Notice our model achieved 97% accuracy. Push the exercise further by tweaking the hyper-parameters, exploring different classifiers, and trying different vectorizers! Sentiment Analysis is also a classification problem of sorts. The text is essentially going to reflect a positive, neutral, or negative sentiment. That is referred to as the polarity of the text. It is also possible to gauge and account for the subjectivity of the text! There are a ton of great resources that cover the theory behind sentiment analysis. Instead of building another model, this project uses a simple, out of box tool to analyze sentiment called TextBlob. I’ll use TextBlob to add sentiment columns to the DataFrame so it can be analyzed. Built on top of NLTK and pattern, the TextBlob library for Python 2 and 3 tries to simplify several text processing tasks. It provides tools for classification, part-of-speech tagging, noun phrase extraction, sentiment analysis and more. Install it using pip and check out the installation guide. pip install -U textblobpython -m textblob.download_corpora Using the sentiment property, TextBlob returns a named tuple of the form Sentiment(polarity, subjectivity). Polarity is a float in the range [-1.0, 1.0] where -1 is the most negative and 1 is the most positive. Subjectivity is a float in the range [0.0, 1.0] where 0.0 is very objective and 1.0 is very subjective. blob = TextBlob("This is a good example of a TextBlob")print(blob)blob.sentiment#Sentiment(polarity=0.7, subjectivity=0.6000000000000001) Using list comprehensions, it is easy to load the text column as a TextBlob, and then create two new columns to store the Polarity and Subjectivity. #load the descriptions into textblobemail_blob = [TextBlob(text) for text in df['text']]#add the sentiment metrics to the dataframedf['tb_Pol'] = [b.sentiment.polarity for b in email_blob]df['tb_Subj'] = [b.sentiment.subjectivity for b in email_blob]#show dataframedf.head(3) TextBlob makes it super simple to generate a baseline sentiment score for polarity and subjectivity. To push this exerciser further, see if you can add these new features to the spam detection model to increase the accuracy! Even though Natural Language Processing can seem like an intimidating topic, the foundational pieces are not that hard to grasp. There are plenty of libraries that make it easy to begin exploring data science and NLP. Completing these three projects: Word CloudSpam DetectionSentiment Analysis You explore concrete examples of applying preprocessing, tokenization, vectorization, and feature engineering on text data. If you’re interested in learning more about data science or programming, check out my other articles! towardsdatascience.com If you enjoyed this, follow me on Medium for more Get FULL ACCESS and help support my content by subscribing Let’s connect on LinkedIn Analyze Data using Python? Check out my website — Eric Kleppen
[ { "code": null, "e": 655, "s": 172, "text": "Working in Data Science and having a background in Technical Writing, I was drawn to the field of Natural Language Processing (NLP). Machines understanding language fascinates me, and I often ponder which algorithms Aristotle would have used to build a rhetorical analysis machine if he had the chance. If you’re new to Data Science, getting into NLP can seem complicated, especially since there have been so many recent advancements in the field. It is hard to know where to start." }, { "code": null, "e": 783, "s": 655, "text": "These three super simple projects will give you an introduction to concepts and techniques used in Natural Language Processing." }, { "code": null, "e": 826, "s": 783, "text": "Word CloudSentiment AnalysisSpam Detection" }, { "code": null, "e": 942, "s": 826, "text": "The data used for these projects is the spam email data set, and it can be found with all of the code in my GitHub:" }, { "code": null, "e": 953, "s": 942, "text": "github.com" }, { "code": null, "e": 1419, "s": 953, "text": "While a computer can actually be quite good at finding patterns and summarizing documents, it must transform words into numbers before making sense of them. This transformation is needed because machines “learn” thanks to mathematics, and math doesn’t work very well on words. Before transforming the words into numbers, they are often cleaned of things like special characters and punctuation, and modified into forms that make them more uniform and interpretable." }, { "code": null, "e": 1517, "s": 1419, "text": "Cleaning the words is often called preprocessing, and that is the focus of project 1: Word Cloud." }, { "code": null, "e": 1697, "s": 1517, "text": "Start by importing the dependencies and the data. The data is stored as a comma separated values (csv) file, so I will use pandas’ read_csv() function to open it into a DataFrame." }, { "code": null, "e": 1876, "s": 1697, "text": "import pandas as pdimport sqlite3import regex as reimport matplotlib.pyplot as pltfrom wordcloud import WordCloud#create dataframe from csvdf = pd.read_csv('emails.csv')df.head()" }, { "code": null, "e": 2060, "s": 1876, "text": "Before anything, it is best to do a quick analysis of the data to eliminate duplicate rows and establish some baseline counts. I use pandas drop_duplicates to drop the duplicate rows." }, { "code": null, "e": 2310, "s": 2060, "text": "print(\"spam count: \" +str(len(df.loc[df.spam==1])))print(\"not spam count: \" +str(len(df.loc[df.spam==0])))print(df.shape)df['spam'] = df['spam'].astype(int)df = df.drop_duplicates()df = df.reset_index(inplace = False)[['text','spam']]print(df.shape)" }, { "code": null, "e": 2553, "s": 2310, "text": "Word clouds are a useful way to visualize text data because they make understanding word frequencies easier. Words that appear more frequently within the email text appear larger in the cloud. Word Clouds make it easy to identify “key words.”" }, { "code": null, "e": 2808, "s": 2553, "text": "Notice in the word cloud image, all the text is lower case. There are no punctuation marks or special characters. That’s because the text has been cleaned to make it easier to analyze. Using regular expressions, it is easy to clean the text using a loop:" }, { "code": null, "e": 3223, "s": 2808, "text": "clean_desc = []for w in range(len(df.text)): desc = df['text'][w].lower() #remove punctuation desc = re.sub('[^a-zA-Z]', ' ', desc) #remove tags desc=re.sub(\"&lt;/?.*?&gt;\",\" &lt;&gt; \",desc) #remove digits and special chars desc=re.sub(\"(\\\\d|\\\\W)+\",\" \",desc) clean_desc.append(desc)#assign the cleaned descriptions to the data framedf['text'] = clean_desc df.head(3)" }, { "code": null, "e": 3487, "s": 3223, "text": "Notice I create an empty list clean_desc, then use a for loop to go through the text line by line, setting it to lower case, removing punctuation and special chars, and appending it to the list. Then I replace the text column with the data in the clean_desc list." }, { "code": null, "e": 3794, "s": 3487, "text": "Stop words are the most common words like “the” and “of.” Removing them from the email text allows the more relevant frequent words to stand out. Removing stop words is a common technique! Some Python libraries like NLTK come pre-loaded with a list of stop words, but it is easy to create one from scratch." }, { "code": null, "e": 3950, "s": 3794, "text": "stop_words = ['is','you','your','and', 'the', 'to', 'from', 'or', 'I', 'for', 'do', 'get', 'not', 'here', 'in', 'im', 'have', 'on', 're', 'new', 'subject']" }, { "code": null, "e": 4147, "s": 3950, "text": "Notice I include a few email related words like “re” and “subject.” It is up to the analyst to determine what words should be included or excluded. Sometimes it is beneficial to include all words!" }, { "code": null, "e": 4243, "s": 4147, "text": "Conveniently there is a Python library for creating word clouds. It can be installed using pip." }, { "code": null, "e": 4265, "s": 4243, "text": "pip install wordcloud" }, { "code": null, "e": 4467, "s": 4265, "text": "When constructing the word cloud, it is possible to set several parameters like height and width, stop words, and max words. It is even possible to shape it instead of displaying the default rectangle." }, { "code": null, "e": 4772, "s": 4467, "text": "wordcloud = WordCloud(width = 800, height = 800, background_color = 'black', stopwords = stop_words, max_words = 1000 , min_font_size = 20).generate(str(df1['text']))#plot the word cloudfig = plt.figure(figsize = (8,8), facecolor = None)plt.imshow(wordcloud)plt.axis('off')plt.show()" }, { "code": null, "e": 4908, "s": 4772, "text": "The word cloud can be saved and displayed using matplotlib and .show(). This is the result of all records, regardless of it being spam." }, { "code": null, "e": 5077, "s": 4908, "text": "Push the exercise further by splitting the data frame and making two word clouds to help analyze the difference between key words used in spam email and not spam email." }, { "code": null, "e": 5398, "s": 5077, "text": "This is a binary classification problem since an email can either be spam (1) or not spam (0). I want to build a machine learneing model that can identify whether or not an email is spam. I am going to use the Python library Scikit-Learn to explore tokenization, vectorization, and statistical classification algorithms." }, { "code": null, "e": 5562, "s": 5398, "text": "Import the Scikit-Learn functionality we need to transform and model the data. I will use CountVectorizer, train_test_split, ensemble models, and a couple metrics." }, { "code": null, "e": 5768, "s": 5562, "text": "from sklearn.feature_extraction.text import CountVectorizerfrom sklearn.model_selection import train_test_splitfrom sklearn import ensemble from sklearn.metrics import classification_report, accuracy_score" }, { "code": null, "e": 6140, "s": 5768, "text": "In project 1, the text was cleaned. When you look at a word cloud, notice it is primarily single words. The larger the word, the higher its frequency. To prevent the word cloud from outputting sentences, the text goes through a processes called tokenization. It is the process of breaking down a sentence into the individual words. The individual words are called tokens." }, { "code": null, "e": 6392, "s": 6140, "text": "Using SciKit-Learn’s CountVectorizer(), it is easy to transform the body of text into a sparse matrix of numbers that the computer can pass to machine learning algorithms. To simplify the concept of count vectorization, imagine you have two sentences:" }, { "code": null, "e": 6425, "s": 6392, "text": "The dog is whiteThe cat is black" }, { "code": null, "e": 6612, "s": 6425, "text": "Converting the sentences to a vector space model would transform them in such a way that looks at the words in all sentences, and then represents the words in the sentence with a number." }, { "code": null, "e": 6703, "s": 6612, "text": "The dog cat is white blackThe dog is white = [1,1,0,1,1,0]The cat is black = [1,0,1,1,0,1]" }, { "code": null, "e": 6801, "s": 6703, "text": "We can show this using code as well. I’ll add a third sentence to show that it counts the tokens." }, { "code": null, "e": 7073, "s": 6801, "text": "#list of sentencestext = [\"the dog is white\", \"the cat is black\", \"the cat and the dog are friends\"]#instantiate the classcv = CountVectorizer()#tokenize and build vocabcv.fit(text)print(cv.vocabulary_)#transform the textvector = cv.transform(text)print(vector.toarray())" }, { "code": null, "e": 7287, "s": 7073, "text": "Notice in the last vector, you can see a 2 since the word “the” appears twice. The CountVectorizer is counting the tokens and allowing me to construct the sparse matrix containing the transformed words to numbers." }, { "code": null, "e": 7555, "s": 7287, "text": "Because the model doesn’t take word placement into account, and instead mixes the words up as if they were tiles in a scrabble game, this is called the bag of words method. I am going to create the sparse matrix, then split the data using sk-learn train_test_split()." }, { "code": null, "e": 7736, "s": 7555, "text": "text_vec = CountVectorizer().fit_transform(df['text'])X_train, X_test, y_train, y_test = train_test_split(text_vec, df['spam'], test_size = 0.45, random_state = 42, shuffle = True)" }, { "code": null, "e": 7852, "s": 7736, "text": "Notice I set the sparse matrix text_vec to X and the df[‘spam’] column to Y. I shuffle and take a test size of 45%." }, { "code": null, "e": 8074, "s": 7852, "text": "I highly recommend experimenting with several classifiers and determine which one works best for this scenario. In this example, I am using the GradientBoostingClassifier() model from the Scikit-Learn Ensemble collection." }, { "code": null, "e": 8238, "s": 8074, "text": "classifier = ensemble.GradientBoostingClassifier( n_estimators = 100, #how many decision trees to build learning_rate = 0.5, #learning rate max_depth = 6)" }, { "code": null, "e": 8435, "s": 8238, "text": "Each algorithm will have its own set of parameters you can tweak. That is called hyper-parameter tuning. Go through the documentation to learn more about each of the parameters used in the models." }, { "code": null, "e": 8620, "s": 8435, "text": "Finally, we fit the data, call predict and generate the classification report. Using classification_report(), it is easy to build a text report showing the main classification metrics." }, { "code": null, "e": 8742, "s": 8620, "text": "classifier.fit(X_train, y_train)predictions = classifier.predict(X_test)print(classification_report(y_test, predictions))" }, { "code": null, "e": 8909, "s": 8742, "text": "Notice our model achieved 97% accuracy. Push the exercise further by tweaking the hyper-parameters, exploring different classifiers, and trying different vectorizers!" }, { "code": null, "e": 9264, "s": 8909, "text": "Sentiment Analysis is also a classification problem of sorts. The text is essentially going to reflect a positive, neutral, or negative sentiment. That is referred to as the polarity of the text. It is also possible to gauge and account for the subjectivity of the text! There are a ton of great resources that cover the theory behind sentiment analysis." }, { "code": null, "e": 9464, "s": 9264, "text": "Instead of building another model, this project uses a simple, out of box tool to analyze sentiment called TextBlob. I’ll use TextBlob to add sentiment columns to the DataFrame so it can be analyzed." }, { "code": null, "e": 9761, "s": 9464, "text": "Built on top of NLTK and pattern, the TextBlob library for Python 2 and 3 tries to simplify several text processing tasks. It provides tools for classification, part-of-speech tagging, noun phrase extraction, sentiment analysis and more. Install it using pip and check out the installation guide." }, { "code": null, "e": 9820, "s": 9761, "text": "pip install -U textblobpython -m textblob.download_corpora" }, { "code": null, "e": 10135, "s": 9820, "text": "Using the sentiment property, TextBlob returns a named tuple of the form Sentiment(polarity, subjectivity). Polarity is a float in the range [-1.0, 1.0] where -1 is the most negative and 1 is the most positive. Subjectivity is a float in the range [0.0, 1.0] where 0.0 is very objective and 1.0 is very subjective." }, { "code": null, "e": 10273, "s": 10135, "text": "blob = TextBlob(\"This is a good example of a TextBlob\")print(blob)blob.sentiment#Sentiment(polarity=0.7, subjectivity=0.6000000000000001)" }, { "code": null, "e": 10422, "s": 10273, "text": "Using list comprehensions, it is easy to load the text column as a TextBlob, and then create two new columns to store the Polarity and Subjectivity." }, { "code": null, "e": 10698, "s": 10422, "text": "#load the descriptions into textblobemail_blob = [TextBlob(text) for text in df['text']]#add the sentiment metrics to the dataframedf['tb_Pol'] = [b.sentiment.polarity for b in email_blob]df['tb_Subj'] = [b.sentiment.subjectivity for b in email_blob]#show dataframedf.head(3)" }, { "code": null, "e": 10923, "s": 10698, "text": "TextBlob makes it super simple to generate a baseline sentiment score for polarity and subjectivity. To push this exerciser further, see if you can add these new features to the spam detection model to increase the accuracy!" }, { "code": null, "e": 11174, "s": 10923, "text": "Even though Natural Language Processing can seem like an intimidating topic, the foundational pieces are not that hard to grasp. There are plenty of libraries that make it easy to begin exploring data science and NLP. Completing these three projects:" }, { "code": null, "e": 11217, "s": 11174, "text": "Word CloudSpam DetectionSentiment Analysis" }, { "code": null, "e": 11341, "s": 11217, "text": "You explore concrete examples of applying preprocessing, tokenization, vectorization, and feature engineering on text data." }, { "code": null, "e": 11443, "s": 11341, "text": "If you’re interested in learning more about data science or programming, check out my other articles!" }, { "code": null, "e": 11466, "s": 11443, "text": "towardsdatascience.com" }, { "code": null, "e": 11516, "s": 11466, "text": "If you enjoyed this, follow me on Medium for more" }, { "code": null, "e": 11575, "s": 11516, "text": "Get FULL ACCESS and help support my content by subscribing" }, { "code": null, "e": 11601, "s": 11575, "text": "Let’s connect on LinkedIn" }, { "code": null, "e": 11649, "s": 11601, "text": "Analyze Data using Python? Check out my website" } ]
How to get Source Code of any website ? - GeeksforGeeks
11 Sep, 2021 A Website is defined as a collection of web pages. A website can be designed using HTML, CSS, Bootstrap, etc. HTML language decides what will appear on the webpage and CSS language depicts how it will appear. In other words, HTML place elements on the webpage, and CSS styles it. Bootstrap is pre-compiled CSS. Suppose we see a website eg. geeksforgeeks.org, and we want its source code then there are two ways to get it: Using Inspect Element (Ctrl + Shift + I ) Using View Page Source ( Ctrl + U ) Let’s understand both methods one by one. 1. Using Inspect Element Below is the step-by-step implementation. Step 1: Visit your desired website eg geeksforgeeks.org. Step 2: Click on Inspect. Step 3: You will get code on right-hand side. Short Cut Key: (Ctrl + Shift + I ) 2. Using Page Source: Step 1: Visit your desired website eg geeksforgeeks.org. Step 2: Right click on website and click on “View Page Source”. Step 3: You will get source code as following. Shortcut Key CTRL + U Blogathon-2021 Blogathon Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Import JSON Data into SQL Server? How to Create a Table With Multiple Foreign Keys in SQL? How to Install Tkinter in Windows? SQL Query to Convert Datetime to Date SQL Query to Create Table With a Primary Key Roadmap to Become a Web Developer in 2022 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? Top 10 Projects For Beginners To Practice HTML and CSS Skills
[ { "code": null, "e": 24814, "s": 24786, "text": "\n11 Sep, 2021" }, { "code": null, "e": 25236, "s": 24814, "text": "A Website is defined as a collection of web pages. A website can be designed using HTML, CSS, Bootstrap, etc. HTML language decides what will appear on the webpage and CSS language depicts how it will appear. In other words, HTML place elements on the webpage, and CSS styles it. Bootstrap is pre-compiled CSS. Suppose we see a website eg. geeksforgeeks.org, and we want its source code then there are two ways to get it:" }, { "code": null, "e": 25278, "s": 25236, "text": "Using Inspect Element (Ctrl + Shift + I )" }, { "code": null, "e": 25314, "s": 25278, "text": "Using View Page Source ( Ctrl + U )" }, { "code": null, "e": 25356, "s": 25314, "text": "Let’s understand both methods one by one." }, { "code": null, "e": 25382, "s": 25356, "text": "1. Using Inspect Element " }, { "code": null, "e": 25424, "s": 25382, "text": "Below is the step-by-step implementation." }, { "code": null, "e": 25483, "s": 25426, "text": "Step 1: Visit your desired website eg geeksforgeeks.org." }, { "code": null, "e": 25509, "s": 25483, "text": "Step 2: Click on Inspect." }, { "code": null, "e": 25555, "s": 25509, "text": "Step 3: You will get code on right-hand side." }, { "code": null, "e": 25571, "s": 25555, "text": "Short Cut Key: " }, { "code": null, "e": 25591, "s": 25571, "text": "(Ctrl + Shift + I )" }, { "code": null, "e": 25615, "s": 25593, "text": "2. Using Page Source:" }, { "code": null, "e": 25672, "s": 25615, "text": "Step 1: Visit your desired website eg geeksforgeeks.org." }, { "code": null, "e": 25736, "s": 25672, "text": "Step 2: Right click on website and click on “View Page Source”." }, { "code": null, "e": 25784, "s": 25736, "text": "Step 3: You will get source code as following. " }, { "code": null, "e": 25797, "s": 25784, "text": "Shortcut Key" }, { "code": null, "e": 25806, "s": 25797, "text": "CTRL + U" }, { "code": null, "e": 25821, "s": 25806, "text": "Blogathon-2021" }, { "code": null, "e": 25831, "s": 25821, "text": "Blogathon" }, { "code": null, "e": 25848, "s": 25831, "text": "Web Technologies" }, { "code": null, "e": 25946, "s": 25848, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25987, "s": 25946, "text": "How to Import JSON Data into SQL Server?" }, { "code": null, "e": 26044, "s": 25987, "text": "How to Create a Table With Multiple Foreign Keys in SQL?" }, { "code": null, "e": 26079, "s": 26044, "text": "How to Install Tkinter in Windows?" }, { "code": null, "e": 26117, "s": 26079, "text": "SQL Query to Convert Datetime to Date" }, { "code": null, "e": 26162, "s": 26117, "text": "SQL Query to Create Table With a Primary Key" }, { "code": null, "e": 26204, "s": 26162, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 26237, "s": 26204, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 26280, "s": 26237, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 26330, "s": 26280, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Get unique values from a list in Python
A list in python is a number of items placed with in [] which may or may not have same data types. It can also contain duplicates. In this article we will see how to extract only the unique values from a list. In this approach we will first create a new empty list and then keep appending elements to this new list only if it is not already present in this new list. A for loop is used along with not in condition. It checks for the existence of the incoming element and it is appended only if it is not already present. Live Demo def catch_unique(list_in): # intilize an empty list unq_list = [] # Check for elements for x in list_in: # check if exists in unq_list if x not in unq_list: unq_list.append(x) # print list for x in unq_list: print(x) Alist = ['Mon', 'Tue', 'Mon', 'wed', 40, 40] print("Unique values from the list is") catch_unique(Alist) Running the above code gives us the following result − Unique values from the list is Mon Tue wed 40 A set only contains unique values. In this approach we convert the list to a set and then convert the set back to a list which holds all the unique elements. Live Demo Alist = ['Mon', 'Tue', 'Mon', 'wed', 40, 40] A_set = set(Alist) New_List=list(A_set) print("Unique values from the list is") print(New_List) Running the above code gives us the following result − Unique values from the list is [40, 'Tue', 'wed', 'Mon'] The numpy library has a function named unique which does the straight job of taking the list as input and giving the unique elements as a new list. Live Demo import numpy as np Alist = ['Mon', 'Tue', 'Mon', 'wed', 40, 40] print("The unique values from list is: ") print(np.unique(Alist)) Running the above code gives us the following result − The unique values from list is: ['40' 'Mon' 'Tue' 'wed']
[ { "code": null, "e": 1272, "s": 1062, "text": "A list in python is a number of items placed with in [] which may or may not have same data types. It can also contain duplicates. In this article we will see how to extract only the unique values from a list." }, { "code": null, "e": 1583, "s": 1272, "text": "In this approach we will first create a new empty list and then keep appending elements to this new list only if it is not already present in this new list. A for loop is used along with not in condition. It checks for the existence of the incoming element and it is appended only if it is not already present." }, { "code": null, "e": 1594, "s": 1583, "text": " Live Demo" }, { "code": null, "e": 1969, "s": 1594, "text": "def catch_unique(list_in):\n # intilize an empty list\n unq_list = []\n\n # Check for elements\n for x in list_in:\n # check if exists in unq_list\n if x not in unq_list:\n unq_list.append(x)\n # print list\n for x in unq_list:\n print(x)\n\nAlist = ['Mon', 'Tue', 'Mon', 'wed', 40, 40]\nprint(\"Unique values from the list is\")\ncatch_unique(Alist)" }, { "code": null, "e": 2024, "s": 1969, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 2070, "s": 2024, "text": "Unique values from the list is\nMon\nTue\nwed\n40" }, { "code": null, "e": 2228, "s": 2070, "text": "A set only contains unique values. In this approach we convert the list to a set and then convert the set back to a list which holds all the unique elements." }, { "code": null, "e": 2239, "s": 2228, "text": " Live Demo" }, { "code": null, "e": 2380, "s": 2239, "text": "Alist = ['Mon', 'Tue', 'Mon', 'wed', 40, 40]\nA_set = set(Alist)\nNew_List=list(A_set)\nprint(\"Unique values from the list is\")\nprint(New_List)" }, { "code": null, "e": 2435, "s": 2380, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 2492, "s": 2435, "text": "Unique values from the list is\n[40, 'Tue', 'wed', 'Mon']" }, { "code": null, "e": 2640, "s": 2492, "text": "The numpy library has a function named unique which does the straight job of taking the list as input and giving the unique elements as a new list." }, { "code": null, "e": 2651, "s": 2640, "text": " Live Demo" }, { "code": null, "e": 2782, "s": 2651, "text": "import numpy as np\n\nAlist = ['Mon', 'Tue', 'Mon', 'wed', 40, 40]\nprint(\"The unique values from list is: \")\nprint(np.unique(Alist))" }, { "code": null, "e": 2837, "s": 2782, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 2894, "s": 2837, "text": "The unique values from list is:\n['40' 'Mon' 'Tue' 'wed']" } ]
How to raise an error within MySQL?
MySQL has introduced signals similar to an exception in other languages. Let us first see the syntax of signal. SIGNAL SQLSTATE ' PredefinedValueforSignalError' SET MESSAGE_TEXT = 'AnyMessageInformation'; Above, we have set our own error message text as well. We will apply the above query to get an error message with the help of signals. mysql > SIGNAL SQLSTATE '42927' SET MESSAGE_TEXT = 'Error Generated'; The following is the output of the above query. ERROR 1644 (42927): Error Generated In the above output, ‘42927’ is a SQLSTATE and ‘Error Generated’ is an error message, which we added.
[ { "code": null, "e": 1174, "s": 1062, "text": "MySQL has introduced signals similar to an exception in other languages. Let us first see the syntax of signal." }, { "code": null, "e": 1269, "s": 1174, "text": "SIGNAL SQLSTATE ' PredefinedValueforSignalError' \nSET MESSAGE_TEXT = 'AnyMessageInformation';\n" }, { "code": null, "e": 1324, "s": 1269, "text": "Above, we have set our own error message text as well." }, { "code": null, "e": 1404, "s": 1324, "text": "We will apply the above query to get an error message with the help of signals." }, { "code": null, "e": 1474, "s": 1404, "text": "mysql > SIGNAL SQLSTATE '42927' SET MESSAGE_TEXT = 'Error Generated';" }, { "code": null, "e": 1522, "s": 1474, "text": "The following is the output of the above query." }, { "code": null, "e": 1559, "s": 1522, "text": "ERROR 1644 (42927): Error Generated\n" }, { "code": null, "e": 1661, "s": 1559, "text": "In the above output, ‘42927’ is a SQLSTATE and ‘Error Generated’ is an error message, which we added." } ]
Social Media Sentiment Analysis using Machine Learning : Part — II | by Deepak Das | Towards Data Science
Hello everyone, so let’s start right where we left off in Part — I. In this post we will discuss how we can extract features from our textual dataset by using Bag-of-Words and TF-IDF. Then we will see how we can apply Machine Learning models using these features to predict whether a tweet falls into the Positive: ‘0’ or Negative: ‘1’ sentiment. Note : In case you haven’t read the Part — I of this series do give it a read to get a better understanding of Part — II. medium.com So, let’s start shall we ? Bag of Words is a method to extract features from text documents. These features can be used for training machine learning algorithms. It creates a vocabulary of all the unique words occurring in all the documents in the training set. Consider a corpus (a collection of texts) called C of D documents {d1,d2.....dD} and N unique tokens extracted out of the corpus C. The N tokens (words) will form a list, and the size of the bag-of-words matrix M will be given by D X N. Each row in the matrix M contains the frequency of tokens in document D(i). For example, if you have 2 documents- D1: He is a lazy boy. She is also lazy. D2: Smith is a lazy person. First, it creates a vocabulary using unique words from all the documents. [‘He’ , ’She’ , ’lazy’ , ‘boy’ , ‘Smith’ , ’person’] As we can see in the above list we don’t consider “is” , “a” , “also” in this set because they don’t convey the necessary information required for the model. Here, D=2, N=6 The matrix M of size 2 X 6 will be represented as: The above table depicts the training features containing term frequencies of each word in each document. This is called bag-of-words approach since the number of occurrence and not sequence or order of words matters in this approach. So,let’s apply this word embedding technique to our available dataset. We have a package called CountVectorizer to perform this task. OUTPUT :- TF-IDF stands for Term Frequency-Inverse Document Frequency, and the TF-IDF weight is a weight often used in information retrieval and text mining. This weight is a statistical measure used to evaluate how important a word is to a document in a collection or corpus. The importance increases proportionally to the number of times a word appears in the document but is offset by the frequency of the word in the corpus. Typically, the TF-IDF weight is composed by two terms: The first computes the normalized Term Frequency (TF), aka. the number of times a word appears in a document, divided by the total number of words in that document. Example :- Consider a document containing 100 words wherein the word cat appears 3 times. The Term Frequency (TF) for cat is then (3 / 100) = 0.03 The second term is the Inverse Document Frequency (IDF), computed as the logarithm of the number of the documents in the corpus divided by the number of documents where the specific term appears. Example :- Assume we have 10 million documents and the word cat appears in one thousand of these. Then, the Inverse Document Frequency (IDF) is calculated as log(10,000,000 / 1,000) = 4. Formula for finding the TF-IDF weight :- From the above examples the Term Frequency is 0.03 and Inverse Document Frequency is 4. Thus, the TF-IDF weight is the product of these quantities : 0.03 * 4 = 0.12. CODE :- Let us apply this technique to our dataset using Python. We have a package available for this in Scikit-Learn known as TfidfVectorizer. OUTPUT :- These are the Word Embedding techniques which we have used on our dataset for feature extraction. Let’s move on to the next step. Splitting of our dataset into training and validation set. From the above two techniques that is Bag-of-Words and TF-IDF we have extracted features from the tweets present in our dataset. Now, we have one dataset with features from the Bag-of-Words model and another dataset with features from TF-IDF model. First task is to split the dataset into training and validation set so that we can train and test our model before applying it to predict for unseen and unlabeled test data. Using the features from Bag-of-Words for training set train_bow = bow[:31962]train_bow.todense() OUTPUT :- Using features from TF-IDF for training set train_tfidf_matrix = tfidf_matrix[:31962]train_tfidf_matrix.todense() OUTPUT :- Splitting the data into training and validation set from sklearn.model_selection import train_test_split Bag-of-Words Features x_train_bow, x_valid_bow, y_train_bow, y_valid_bow = train_test_split(train_bow,train['label'],test_size=0.3,random_state=2) TF-IDF features x_train_tfidf, x_valid_tfidf, y_train_tfidf, y_valid_tfidf = train_test_split(train_tfidf_matrix,train['label'],test_size=0.3,random_state=17) We are done with splitting our dataset into train and validation set. Want to know more about the Bag-of-Words and TF-IDF models used for feature extraction. Do give a read to the following blog post for an in depth discussion. towardsdatascience.com Finally , we are here for the most awaited part of this series that is applying Machine Learning Models on our dataset. The underlying problem we are going to solve comes under the Supervised Machine Learning category. So, let us have a brief discussion about this topic before moving on to apply different Machine Learning models on our dataset. The majority of practical machine learning uses supervised learning. Supervised learning is where you have input variables (x) and an output variable (Y) and you use an algorithm to learn the mapping function from the input to the output. The goal is to approximate the mapping function so well that when you have new input data (x) that you can predict the output variables (Y) for that data. It is called supervised learning because the process of an algorithm learning from the training dataset can be thought of as a teacher supervising the learning process. We know the correct answers, the algorithm iteratively makes predictions on the training data and is corrected by the teacher. Learning stops when the algorithm achieves an acceptable level of performance. Supervised learning problems can be further grouped into regression and classification problems. Classification: A classification problem is when the output variable is a category, such as “red” or “blue” or “disease” and “no disease” or in our case “Positive” or “Negative” Regression: A regression problem is when the output variable is a real value, such as “dollars” or “weight”. Our problem comes under the classification category because we have to classify our results into either Positive or Negative class. There is another category of Machine Learning algorithm called Unsupervised Machine Learning where you have an input data but no corresponding output variables. The goal for unsupervised learning is to model the underlying structure or distribution in the data in order to learn more about the data. But that is of no concern for us for this problem statement. So from the above splitting of dataset we see that we will use features from the Bag-of-Words and TF-IDF for our Machine Learning Models. We generally use different models to see which best fits our dataset and then we use that model for predicting results on the test data. Here we will use 3 different models Logistic Regression XGBoost Decision Trees and then we will compare their performance and choose the best possible model with the best possible feature extraction technique for predicting results on our test data. We will use F1 Score throughout to asses our model’s performance instead of accuracy. You will get to know why at the end of this article. CODE :- from sklearn.metrics import f1_score Now, let’s move on to applying different models on our dataset from the features extracted by using Bag-of-Words and TF-IDF. The first model we are going to use is Logistic Regression. from sklearn.linear_model import LogisticRegressionLog_Reg = LogisticRegression(random_state=0,solver='lbfgs') Fitting the Logistic Regression Model. Log_Reg.fit(x_train_bow,y_train_bow) Predicting the probabilities. prediction_bow = Log_Reg.predict_proba(x_valid_bow)prediction_bow OUTPUT :- If you are confused about the above output , read this stack overflow answer and you will have a clear idea about it. stackoverflow.com The output basically provides us with the probabilities of the tweet falling into either of the classes that is Negative or Positive. Calculating the F1 score Fitting the Logistic Regression Model. Log_Reg.fit(x_train_tfidf,y_train_tfidf) Predicting the probabilities. prediction_tfidf = Log_Reg.predict_proba(x_valid_tfidf)prediction_tfidf OUTPUT :- Calculating the F1 Score Note : In the nested list the element[0][0] is for label : 0 or Positive tweets and element [0][1] is for label : 1 or Negative Tweets. For an in depth analysis of Logistic Regression do read the following article. machinelearningmastery.com The next model we use is XGBoost. from xgboost import XGBClassifier model_bow = XGBClassifier(random_state=22,learning_rate=0.9) Fitting the XGBoost Model model_bow.fit(x_train_bow, y_train_bow) Predicting the probabilities. xgb = model_bow.predict_proba(x_valid_bow)xgb Calculating the F1 Score OUTPUT :- model_tfidf = XGBClassifier(random_state=29,learning_rate=0.7) Fitting the XGBoost model model_tfidf.fit(x_train_tfidf, y_train_tfidf) Predicting the probabilities. xgb_tfidf=model_tfidf.predict_proba(x_valid_tfidf)xgb_tfidf Calculating the F1 Score OUTPUT :- For a more in depth analysis of the XGBoost model read the following article. machinelearningmastery.com The last model we use is Decision Trees. from sklearn.tree import DecisionTreeClassifierdct = DecisionTreeClassifier(criterion='entropy', random_state=1) Fitting the Decision Tree model. dct.fit(x_train_bow,y_train_bow) Predicting the probabilities. dct_bow = dct.predict_proba(x_valid_bow)dct_bow Calculating the F1 Score Fitting the Decision Tree model dct.fit(x_train_tfidf,y_train_tfidf) Predicting the probabilities. dct_tfidf = dct.predict_proba(x_valid_tfidf)dct_tfidf Calculating the F1 Score For a more in depth analysis of Decision Trees model do give a read to the following article. towardsdatascience.com Now, let us compare the different models we have applied on our dataset with different word embedding techniques. Comparison Graph Comparison Graph As we can see the best possible model from both Bag-of-Words and TF-IDF is Logistic Regression. Now, let us compare the score of the Logistic Regression model with both the feature extraction techniques that is Bag-of-Words and TF-IDF. Comparison Graph From the above comparison graph we can clearly see that the best possible F1 Score is obtained by the Logistic Regression Model using TF-IDF features. Code :- res = pd.read_csv('result.csv')res From the above output we can see that our Logistic Regression model with TF-IDF features predicts whether a tweets falls into the category of Positive — label : 0 or Negative — label : 1 sentiment. Bag-of-Words TF-IDF Logistic Regression XGBoost Decision Trees F1 Score So, finally we have reached the end of our journey. We completed the tasks which were required to predict the sentiment of a particular tweet using Machine Learning. The questions that arises are “What is F1 Score ?” and “Why F1 Score instead of accuracy ?”. So, before we proceed you need to have a basic idea about the terminologies like Confusion Matrix and its contents for example. So, refer to this article for a basic understanding of the terminologies associated with Confusion Matrix. towardsdatascience.com OK , let us answer the above queries. Let us generate a countplot for our training dataset labels i.e. ‘0’ or ‘1’ . sns.countplot(train_original['label'])sns.despine() From the above countplot generated above we see how imbalanced our dataset is.We can see that the values with Positive — label : 0 sentiments are quite high in number as compared to the values with Negative — label : 1 sentiments. So when we keep Accuracy as our evaluation metric there may be cases where we may encounter high number of false positives. So that is why we use F1 Score as our evaluation metric instead of Accuracy. To know about F1 Score we first have to know about Precision and Recall. Precision means the percentage of your results which are relevant. Recall refers to the percentage of total relevant results correctly classified by your algorithm. We always face a trade-off situation between Precision and Recall i.e. High Precision gives low Recall and vice versa. In most problems, you could either give a higher priority to maximising precision, or recall, depending upon the problem you are trying to solve. But in general, there is a simpler metric which takes into account both precision and recall, and therefore, you can aim to maximise this number to make your model better. This metric is known as F1-score, which is simply the harmonic mean of Precision and Recall. So this metric seems much more easier and convenient to work with, as you only have to maximise one score, rather than balancing two separate scores. Finally, we have reached the end of the two part series of this article. I hope after this post you get a basic understanding of how you can start off with text processing and apply Machine Learning models to text data and extract information out of it. After this we can try to deploy our Machine Learning Models over a website using the available web frameworks such as Flask ,FastAPI etc. to production. But that’s a story for another blog post. You can reach me at : LinkedIn : https://www.linkedin.com/in/deepak-das-profile/ GitHub : https://github.com/dD2405
[ { "code": null, "e": 240, "s": 172, "text": "Hello everyone, so let’s start right where we left off in Part — I." }, { "code": null, "e": 519, "s": 240, "text": "In this post we will discuss how we can extract features from our textual dataset by using Bag-of-Words and TF-IDF. Then we will see how we can apply Machine Learning models using these features to predict whether a tweet falls into the Positive: ‘0’ or Negative: ‘1’ sentiment." }, { "code": null, "e": 641, "s": 519, "text": "Note : In case you haven’t read the Part — I of this series do give it a read to get a better understanding of Part — II." }, { "code": null, "e": 652, "s": 641, "text": "medium.com" }, { "code": null, "e": 679, "s": 652, "text": "So, let’s start shall we ?" }, { "code": null, "e": 914, "s": 679, "text": "Bag of Words is a method to extract features from text documents. These features can be used for training machine learning algorithms. It creates a vocabulary of all the unique words occurring in all the documents in the training set." }, { "code": null, "e": 1227, "s": 914, "text": "Consider a corpus (a collection of texts) called C of D documents {d1,d2.....dD} and N unique tokens extracted out of the corpus C. The N tokens (words) will form a list, and the size of the bag-of-words matrix M will be given by D X N. Each row in the matrix M contains the frequency of tokens in document D(i)." }, { "code": null, "e": 1265, "s": 1227, "text": "For example, if you have 2 documents-" }, { "code": null, "e": 1305, "s": 1265, "text": "D1: He is a lazy boy. She is also lazy." }, { "code": null, "e": 1333, "s": 1305, "text": "D2: Smith is a lazy person." }, { "code": null, "e": 1407, "s": 1333, "text": "First, it creates a vocabulary using unique words from all the documents." }, { "code": null, "e": 1460, "s": 1407, "text": "[‘He’ , ’She’ , ’lazy’ , ‘boy’ , ‘Smith’ , ’person’]" }, { "code": null, "e": 1618, "s": 1460, "text": "As we can see in the above list we don’t consider “is” , “a” , “also” in this set because they don’t convey the necessary information required for the model." }, { "code": null, "e": 1633, "s": 1618, "text": "Here, D=2, N=6" }, { "code": null, "e": 1684, "s": 1633, "text": "The matrix M of size 2 X 6 will be represented as:" }, { "code": null, "e": 1918, "s": 1684, "text": "The above table depicts the training features containing term frequencies of each word in each document. This is called bag-of-words approach since the number of occurrence and not sequence or order of words matters in this approach." }, { "code": null, "e": 1989, "s": 1918, "text": "So,let’s apply this word embedding technique to our available dataset." }, { "code": null, "e": 2052, "s": 1989, "text": "We have a package called CountVectorizer to perform this task." }, { "code": null, "e": 2062, "s": 2052, "text": "OUTPUT :-" }, { "code": null, "e": 2481, "s": 2062, "text": "TF-IDF stands for Term Frequency-Inverse Document Frequency, and the TF-IDF weight is a weight often used in information retrieval and text mining. This weight is a statistical measure used to evaluate how important a word is to a document in a collection or corpus. The importance increases proportionally to the number of times a word appears in the document but is offset by the frequency of the word in the corpus." }, { "code": null, "e": 2536, "s": 2481, "text": "Typically, the TF-IDF weight is composed by two terms:" }, { "code": null, "e": 2701, "s": 2536, "text": "The first computes the normalized Term Frequency (TF), aka. the number of times a word appears in a document, divided by the total number of words in that document." }, { "code": null, "e": 2712, "s": 2701, "text": "Example :-" }, { "code": null, "e": 2791, "s": 2712, "text": "Consider a document containing 100 words wherein the word cat appears 3 times." }, { "code": null, "e": 2848, "s": 2791, "text": "The Term Frequency (TF) for cat is then (3 / 100) = 0.03" }, { "code": null, "e": 3044, "s": 2848, "text": "The second term is the Inverse Document Frequency (IDF), computed as the logarithm of the number of the documents in the corpus divided by the number of documents where the specific term appears." }, { "code": null, "e": 3055, "s": 3044, "text": "Example :-" }, { "code": null, "e": 3142, "s": 3055, "text": "Assume we have 10 million documents and the word cat appears in one thousand of these." }, { "code": null, "e": 3202, "s": 3142, "text": "Then, the Inverse Document Frequency (IDF) is calculated as" }, { "code": null, "e": 3231, "s": 3202, "text": "log(10,000,000 / 1,000) = 4." }, { "code": null, "e": 3272, "s": 3231, "text": "Formula for finding the TF-IDF weight :-" }, { "code": null, "e": 3360, "s": 3272, "text": "From the above examples the Term Frequency is 0.03 and Inverse Document Frequency is 4." }, { "code": null, "e": 3438, "s": 3360, "text": "Thus, the TF-IDF weight is the product of these quantities : 0.03 * 4 = 0.12." }, { "code": null, "e": 3446, "s": 3438, "text": "CODE :-" }, { "code": null, "e": 3503, "s": 3446, "text": "Let us apply this technique to our dataset using Python." }, { "code": null, "e": 3582, "s": 3503, "text": "We have a package available for this in Scikit-Learn known as TfidfVectorizer." }, { "code": null, "e": 3592, "s": 3582, "text": "OUTPUT :-" }, { "code": null, "e": 3690, "s": 3592, "text": "These are the Word Embedding techniques which we have used on our dataset for feature extraction." }, { "code": null, "e": 3722, "s": 3690, "text": "Let’s move on to the next step." }, { "code": null, "e": 3781, "s": 3722, "text": "Splitting of our dataset into training and validation set." }, { "code": null, "e": 3910, "s": 3781, "text": "From the above two techniques that is Bag-of-Words and TF-IDF we have extracted features from the tweets present in our dataset." }, { "code": null, "e": 4030, "s": 3910, "text": "Now, we have one dataset with features from the Bag-of-Words model and another dataset with features from TF-IDF model." }, { "code": null, "e": 4204, "s": 4030, "text": "First task is to split the dataset into training and validation set so that we can train and test our model before applying it to predict for unseen and unlabeled test data." }, { "code": null, "e": 4258, "s": 4204, "text": "Using the features from Bag-of-Words for training set" }, { "code": null, "e": 4301, "s": 4258, "text": "train_bow = bow[:31962]train_bow.todense()" }, { "code": null, "e": 4311, "s": 4301, "text": "OUTPUT :-" }, { "code": null, "e": 4355, "s": 4311, "text": "Using features from TF-IDF for training set" }, { "code": null, "e": 4425, "s": 4355, "text": "train_tfidf_matrix = tfidf_matrix[:31962]train_tfidf_matrix.todense()" }, { "code": null, "e": 4435, "s": 4425, "text": "OUTPUT :-" }, { "code": null, "e": 4487, "s": 4435, "text": "Splitting the data into training and validation set" }, { "code": null, "e": 4540, "s": 4487, "text": "from sklearn.model_selection import train_test_split" }, { "code": null, "e": 4562, "s": 4540, "text": "Bag-of-Words Features" }, { "code": null, "e": 4687, "s": 4562, "text": "x_train_bow, x_valid_bow, y_train_bow, y_valid_bow = train_test_split(train_bow,train['label'],test_size=0.3,random_state=2)" }, { "code": null, "e": 4703, "s": 4687, "text": "TF-IDF features" }, { "code": null, "e": 4846, "s": 4703, "text": "x_train_tfidf, x_valid_tfidf, y_train_tfidf, y_valid_tfidf = train_test_split(train_tfidf_matrix,train['label'],test_size=0.3,random_state=17)" }, { "code": null, "e": 4916, "s": 4846, "text": "We are done with splitting our dataset into train and validation set." }, { "code": null, "e": 5074, "s": 4916, "text": "Want to know more about the Bag-of-Words and TF-IDF models used for feature extraction. Do give a read to the following blog post for an in depth discussion." }, { "code": null, "e": 5097, "s": 5074, "text": "towardsdatascience.com" }, { "code": null, "e": 5217, "s": 5097, "text": "Finally , we are here for the most awaited part of this series that is applying Machine Learning Models on our dataset." }, { "code": null, "e": 5444, "s": 5217, "text": "The underlying problem we are going to solve comes under the Supervised Machine Learning category. So, let us have a brief discussion about this topic before moving on to apply different Machine Learning models on our dataset." }, { "code": null, "e": 5513, "s": 5444, "text": "The majority of practical machine learning uses supervised learning." }, { "code": null, "e": 5683, "s": 5513, "text": "Supervised learning is where you have input variables (x) and an output variable (Y) and you use an algorithm to learn the mapping function from the input to the output." }, { "code": null, "e": 5838, "s": 5683, "text": "The goal is to approximate the mapping function so well that when you have new input data (x) that you can predict the output variables (Y) for that data." }, { "code": null, "e": 6213, "s": 5838, "text": "It is called supervised learning because the process of an algorithm learning from the training dataset can be thought of as a teacher supervising the learning process. We know the correct answers, the algorithm iteratively makes predictions on the training data and is corrected by the teacher. Learning stops when the algorithm achieves an acceptable level of performance." }, { "code": null, "e": 6310, "s": 6213, "text": "Supervised learning problems can be further grouped into regression and classification problems." }, { "code": null, "e": 6488, "s": 6310, "text": "Classification: A classification problem is when the output variable is a category, such as “red” or “blue” or “disease” and “no disease” or in our case “Positive” or “Negative”" }, { "code": null, "e": 6597, "s": 6488, "text": "Regression: A regression problem is when the output variable is a real value, such as “dollars” or “weight”." }, { "code": null, "e": 6729, "s": 6597, "text": "Our problem comes under the classification category because we have to classify our results into either Positive or Negative class." }, { "code": null, "e": 7090, "s": 6729, "text": "There is another category of Machine Learning algorithm called Unsupervised Machine Learning where you have an input data but no corresponding output variables. The goal for unsupervised learning is to model the underlying structure or distribution in the data in order to learn more about the data. But that is of no concern for us for this problem statement." }, { "code": null, "e": 7228, "s": 7090, "text": "So from the above splitting of dataset we see that we will use features from the Bag-of-Words and TF-IDF for our Machine Learning Models." }, { "code": null, "e": 7365, "s": 7228, "text": "We generally use different models to see which best fits our dataset and then we use that model for predicting results on the test data." }, { "code": null, "e": 7401, "s": 7365, "text": "Here we will use 3 different models" }, { "code": null, "e": 7421, "s": 7401, "text": "Logistic Regression" }, { "code": null, "e": 7429, "s": 7421, "text": "XGBoost" }, { "code": null, "e": 7444, "s": 7429, "text": "Decision Trees" }, { "code": null, "e": 7615, "s": 7444, "text": "and then we will compare their performance and choose the best possible model with the best possible feature extraction technique for predicting results on our test data." }, { "code": null, "e": 7754, "s": 7615, "text": "We will use F1 Score throughout to asses our model’s performance instead of accuracy. You will get to know why at the end of this article." }, { "code": null, "e": 7762, "s": 7754, "text": "CODE :-" }, { "code": null, "e": 7799, "s": 7762, "text": "from sklearn.metrics import f1_score" }, { "code": null, "e": 7924, "s": 7799, "text": "Now, let’s move on to applying different models on our dataset from the features extracted by using Bag-of-Words and TF-IDF." }, { "code": null, "e": 7984, "s": 7924, "text": "The first model we are going to use is Logistic Regression." }, { "code": null, "e": 8095, "s": 7984, "text": "from sklearn.linear_model import LogisticRegressionLog_Reg = LogisticRegression(random_state=0,solver='lbfgs')" }, { "code": null, "e": 8134, "s": 8095, "text": "Fitting the Logistic Regression Model." }, { "code": null, "e": 8171, "s": 8134, "text": "Log_Reg.fit(x_train_bow,y_train_bow)" }, { "code": null, "e": 8201, "s": 8171, "text": "Predicting the probabilities." }, { "code": null, "e": 8267, "s": 8201, "text": "prediction_bow = Log_Reg.predict_proba(x_valid_bow)prediction_bow" }, { "code": null, "e": 8277, "s": 8267, "text": "OUTPUT :-" }, { "code": null, "e": 8395, "s": 8277, "text": "If you are confused about the above output , read this stack overflow answer and you will have a clear idea about it." }, { "code": null, "e": 8413, "s": 8395, "text": "stackoverflow.com" }, { "code": null, "e": 8547, "s": 8413, "text": "The output basically provides us with the probabilities of the tweet falling into either of the classes that is Negative or Positive." }, { "code": null, "e": 8572, "s": 8547, "text": "Calculating the F1 score" }, { "code": null, "e": 8611, "s": 8572, "text": "Fitting the Logistic Regression Model." }, { "code": null, "e": 8652, "s": 8611, "text": "Log_Reg.fit(x_train_tfidf,y_train_tfidf)" }, { "code": null, "e": 8682, "s": 8652, "text": "Predicting the probabilities." }, { "code": null, "e": 8754, "s": 8682, "text": "prediction_tfidf = Log_Reg.predict_proba(x_valid_tfidf)prediction_tfidf" }, { "code": null, "e": 8764, "s": 8754, "text": "OUTPUT :-" }, { "code": null, "e": 8789, "s": 8764, "text": "Calculating the F1 Score" }, { "code": null, "e": 8925, "s": 8789, "text": "Note : In the nested list the element[0][0] is for label : 0 or Positive tweets and element [0][1] is for label : 1 or Negative Tweets." }, { "code": null, "e": 9004, "s": 8925, "text": "For an in depth analysis of Logistic Regression do read the following article." }, { "code": null, "e": 9031, "s": 9004, "text": "machinelearningmastery.com" }, { "code": null, "e": 9065, "s": 9031, "text": "The next model we use is XGBoost." }, { "code": null, "e": 9099, "s": 9065, "text": "from xgboost import XGBClassifier" }, { "code": null, "e": 9160, "s": 9099, "text": "model_bow = XGBClassifier(random_state=22,learning_rate=0.9)" }, { "code": null, "e": 9186, "s": 9160, "text": "Fitting the XGBoost Model" }, { "code": null, "e": 9226, "s": 9186, "text": "model_bow.fit(x_train_bow, y_train_bow)" }, { "code": null, "e": 9256, "s": 9226, "text": "Predicting the probabilities." }, { "code": null, "e": 9302, "s": 9256, "text": "xgb = model_bow.predict_proba(x_valid_bow)xgb" }, { "code": null, "e": 9327, "s": 9302, "text": "Calculating the F1 Score" }, { "code": null, "e": 9337, "s": 9327, "text": "OUTPUT :-" }, { "code": null, "e": 9400, "s": 9337, "text": "model_tfidf = XGBClassifier(random_state=29,learning_rate=0.7)" }, { "code": null, "e": 9426, "s": 9400, "text": "Fitting the XGBoost model" }, { "code": null, "e": 9472, "s": 9426, "text": "model_tfidf.fit(x_train_tfidf, y_train_tfidf)" }, { "code": null, "e": 9502, "s": 9472, "text": "Predicting the probabilities." }, { "code": null, "e": 9562, "s": 9502, "text": "xgb_tfidf=model_tfidf.predict_proba(x_valid_tfidf)xgb_tfidf" }, { "code": null, "e": 9587, "s": 9562, "text": "Calculating the F1 Score" }, { "code": null, "e": 9597, "s": 9587, "text": "OUTPUT :-" }, { "code": null, "e": 9675, "s": 9597, "text": "For a more in depth analysis of the XGBoost model read the following article." }, { "code": null, "e": 9702, "s": 9675, "text": "machinelearningmastery.com" }, { "code": null, "e": 9743, "s": 9702, "text": "The last model we use is Decision Trees." }, { "code": null, "e": 9856, "s": 9743, "text": "from sklearn.tree import DecisionTreeClassifierdct = DecisionTreeClassifier(criterion='entropy', random_state=1)" }, { "code": null, "e": 9889, "s": 9856, "text": "Fitting the Decision Tree model." }, { "code": null, "e": 9922, "s": 9889, "text": "dct.fit(x_train_bow,y_train_bow)" }, { "code": null, "e": 9952, "s": 9922, "text": "Predicting the probabilities." }, { "code": null, "e": 10000, "s": 9952, "text": "dct_bow = dct.predict_proba(x_valid_bow)dct_bow" }, { "code": null, "e": 10025, "s": 10000, "text": "Calculating the F1 Score" }, { "code": null, "e": 10057, "s": 10025, "text": "Fitting the Decision Tree model" }, { "code": null, "e": 10094, "s": 10057, "text": "dct.fit(x_train_tfidf,y_train_tfidf)" }, { "code": null, "e": 10124, "s": 10094, "text": "Predicting the probabilities." }, { "code": null, "e": 10178, "s": 10124, "text": "dct_tfidf = dct.predict_proba(x_valid_tfidf)dct_tfidf" }, { "code": null, "e": 10203, "s": 10178, "text": "Calculating the F1 Score" }, { "code": null, "e": 10297, "s": 10203, "text": "For a more in depth analysis of Decision Trees model do give a read to the following article." }, { "code": null, "e": 10320, "s": 10297, "text": "towardsdatascience.com" }, { "code": null, "e": 10434, "s": 10320, "text": "Now, let us compare the different models we have applied on our dataset with different word embedding techniques." }, { "code": null, "e": 10451, "s": 10434, "text": "Comparison Graph" }, { "code": null, "e": 10468, "s": 10451, "text": "Comparison Graph" }, { "code": null, "e": 10564, "s": 10468, "text": "As we can see the best possible model from both Bag-of-Words and TF-IDF is Logistic Regression." }, { "code": null, "e": 10704, "s": 10564, "text": "Now, let us compare the score of the Logistic Regression model with both the feature extraction techniques that is Bag-of-Words and TF-IDF." }, { "code": null, "e": 10721, "s": 10704, "text": "Comparison Graph" }, { "code": null, "e": 10872, "s": 10721, "text": "From the above comparison graph we can clearly see that the best possible F1 Score is obtained by the Logistic Regression Model using TF-IDF features." }, { "code": null, "e": 10880, "s": 10872, "text": "Code :-" }, { "code": null, "e": 10915, "s": 10880, "text": "res = pd.read_csv('result.csv')res" }, { "code": null, "e": 11113, "s": 10915, "text": "From the above output we can see that our Logistic Regression model with TF-IDF features predicts whether a tweets falls into the category of Positive — label : 0 or Negative — label : 1 sentiment." }, { "code": null, "e": 11126, "s": 11113, "text": "Bag-of-Words" }, { "code": null, "e": 11133, "s": 11126, "text": "TF-IDF" }, { "code": null, "e": 11153, "s": 11133, "text": "Logistic Regression" }, { "code": null, "e": 11161, "s": 11153, "text": "XGBoost" }, { "code": null, "e": 11176, "s": 11161, "text": "Decision Trees" }, { "code": null, "e": 11185, "s": 11176, "text": "F1 Score" }, { "code": null, "e": 11351, "s": 11185, "text": "So, finally we have reached the end of our journey. We completed the tasks which were required to predict the sentiment of a particular tweet using Machine Learning." }, { "code": null, "e": 11444, "s": 11351, "text": "The questions that arises are “What is F1 Score ?” and “Why F1 Score instead of accuracy ?”." }, { "code": null, "e": 11572, "s": 11444, "text": "So, before we proceed you need to have a basic idea about the terminologies like Confusion Matrix and its contents for example." }, { "code": null, "e": 11679, "s": 11572, "text": "So, refer to this article for a basic understanding of the terminologies associated with Confusion Matrix." }, { "code": null, "e": 11702, "s": 11679, "text": "towardsdatascience.com" }, { "code": null, "e": 11740, "s": 11702, "text": "OK , let us answer the above queries." }, { "code": null, "e": 11818, "s": 11740, "text": "Let us generate a countplot for our training dataset labels i.e. ‘0’ or ‘1’ ." }, { "code": null, "e": 11870, "s": 11818, "text": "sns.countplot(train_original['label'])sns.despine()" }, { "code": null, "e": 12101, "s": 11870, "text": "From the above countplot generated above we see how imbalanced our dataset is.We can see that the values with Positive — label : 0 sentiments are quite high in number as compared to the values with Negative — label : 1 sentiments." }, { "code": null, "e": 12302, "s": 12101, "text": "So when we keep Accuracy as our evaluation metric there may be cases where we may encounter high number of false positives. So that is why we use F1 Score as our evaluation metric instead of Accuracy." }, { "code": null, "e": 12375, "s": 12302, "text": "To know about F1 Score we first have to know about Precision and Recall." }, { "code": null, "e": 12442, "s": 12375, "text": "Precision means the percentage of your results which are relevant." }, { "code": null, "e": 12540, "s": 12442, "text": "Recall refers to the percentage of total relevant results correctly classified by your algorithm." }, { "code": null, "e": 12659, "s": 12540, "text": "We always face a trade-off situation between Precision and Recall i.e. High Precision gives low Recall and vice versa." }, { "code": null, "e": 13070, "s": 12659, "text": "In most problems, you could either give a higher priority to maximising precision, or recall, depending upon the problem you are trying to solve. But in general, there is a simpler metric which takes into account both precision and recall, and therefore, you can aim to maximise this number to make your model better. This metric is known as F1-score, which is simply the harmonic mean of Precision and Recall." }, { "code": null, "e": 13220, "s": 13070, "text": "So this metric seems much more easier and convenient to work with, as you only have to maximise one score, rather than balancing two separate scores." }, { "code": null, "e": 13474, "s": 13220, "text": "Finally, we have reached the end of the two part series of this article. I hope after this post you get a basic understanding of how you can start off with text processing and apply Machine Learning models to text data and extract information out of it." }, { "code": null, "e": 13669, "s": 13474, "text": "After this we can try to deploy our Machine Learning Models over a website using the available web frameworks such as Flask ,FastAPI etc. to production. But that’s a story for another blog post." }, { "code": null, "e": 13691, "s": 13669, "text": "You can reach me at :" }, { "code": null, "e": 13750, "s": 13691, "text": "LinkedIn : https://www.linkedin.com/in/deepak-das-profile/" } ]
How to write and render LaTeX math formulas on Medium | by Shuyi Yang | Towards Data Science
Every day, many practitioners share technical tutorials and findings by creating contents on Medium. However, posting articles with math formulas (eg. equations written in LaTeX) is a struggle since it is not supported on Medium. The most common solution to this limitation is transforming your formulas in images and add them to the article. You can take a screenshot to a rendered PDF file or use an online LaTeX editor like CodeCogs. The image containing the formula attached to this article will be visualized as: This is the most simple strategy to add math formulas when posting on Medium, but it is not flexible and it doesn’t work for inline equations. A similar approach consists in creating Jupyter Notebook Markdown with math formulas and upload the notebook to GitHub Gist. Then, just copy the Share link on Medium and the result is: This is a math formula rendered in Jupyter Notebook: Honestly, it is not very fancy. Another way to add LaTeX formulas on Medium is using TeX to Unicode Chrome Addon to convert LaTeX code to Unicode. Once installed the addon, just select the LaTeX code you want to convert, for example \alpha : \mathbb{R} \to \mathbb{R} press Alt+W (you can change the shortcut in configuration) and you should get the unicode version of the equation: α : R → R This method doesn’t rely on images or embedded objects, it can work inline but it is also limited in characters and layout conversion. For example, the instance above (\cos x + \sin x)^2 = \underbrace{\cos^2 x + \sin^2 x}_{1} + \overbrace{2 \sin x \cos x}^{\sin 2x} is converted in (\cos x + \sin x)2 = \underbrace{\cos2 x + \sin2 x}1 + \overbrace{2 \sin x \cos x}^{\sin 2x} Not very useful when the formula is a little complex. The last method to render mathematics formulas on Medium requires the installation of a Chome addon both on creator’s and reader’s browser. The addon is called Math Anywhere and it should render every MathML/LaTeX formulas on any page, also outside Medium. During the editing, you just need to put your formulas in appropriate delimiters like dollar symbols (the addon should be turned off) and during the reading, once activated the addon, the equations will be converted. The formula should be rendered correctly: (cosx+sinx)2=cos2x+sin2x+2sinxcosx(cos⁡x+sin⁡x)2=cos2⁡x+sin2⁡x+2sin⁡xcos⁡x(\cos x + \sin x)^2=\cos^2 x + \sin^2 x+2 \sin x \cos x and also inline formulas like α:R→Rα:R→R\alpha: \mathbb{R} \to \mathbb{R} should work. The drawback of this approach is that the reader is required to install the addon (only the first time). Of course, we can insert a kind reminder at the beginning of the post like this: This post contains LaTeX formulas. To render them correctly, install Math Anywhere addon and activate it. Do you know any other method to add math formulas on Medium? Let me know in comments! How to write mathematics on MediumHow to use math formula on Medium posting Contacts: LinkedIn | Twitter
[ { "code": null, "e": 609, "s": 172, "text": "Every day, many practitioners share technical tutorials and findings by creating contents on Medium. However, posting articles with math formulas (eg. equations written in LaTeX) is a struggle since it is not supported on Medium. The most common solution to this limitation is transforming your formulas in images and add them to the article. You can take a screenshot to a rendered PDF file or use an online LaTeX editor like CodeCogs." }, { "code": null, "e": 690, "s": 609, "text": "The image containing the formula attached to this article will be visualized as:" }, { "code": null, "e": 833, "s": 690, "text": "This is the most simple strategy to add math formulas when posting on Medium, but it is not flexible and it doesn’t work for inline equations." }, { "code": null, "e": 958, "s": 833, "text": "A similar approach consists in creating Jupyter Notebook Markdown with math formulas and upload the notebook to GitHub Gist." }, { "code": null, "e": 1018, "s": 958, "text": "Then, just copy the Share link on Medium and the result is:" }, { "code": null, "e": 1071, "s": 1018, "text": "This is a math formula rendered in Jupyter Notebook:" }, { "code": null, "e": 1103, "s": 1071, "text": "Honestly, it is not very fancy." }, { "code": null, "e": 1304, "s": 1103, "text": "Another way to add LaTeX formulas on Medium is using TeX to Unicode Chrome Addon to convert LaTeX code to Unicode. Once installed the addon, just select the LaTeX code you want to convert, for example" }, { "code": null, "e": 1339, "s": 1304, "text": "\\alpha : \\mathbb{R} \\to \\mathbb{R}" }, { "code": null, "e": 1454, "s": 1339, "text": "press Alt+W (you can change the shortcut in configuration) and you should get the unicode version of the equation:" }, { "code": null, "e": 1464, "s": 1454, "text": "α : R → R" }, { "code": null, "e": 1631, "s": 1464, "text": "This method doesn’t rely on images or embedded objects, it can work inline but it is also limited in characters and layout conversion. For example, the instance above" }, { "code": null, "e": 1736, "s": 1631, "text": "(\\cos x + \\sin x)^2 = \\underbrace{\\cos^2 x + \\sin^2 x}_{1} + \\overbrace{2 \\sin x \\cos x}^{\\sin 2x}" }, { "code": null, "e": 1752, "s": 1736, "text": "is converted in" }, { "code": null, "e": 1851, "s": 1752, "text": "(\\cos x + \\sin x)2 = \\underbrace{\\cos2 x + \\sin2 x}1 + \\overbrace{2 \\sin x \\cos x}^{\\sin 2x}" }, { "code": null, "e": 1905, "s": 1851, "text": "Not very useful when the formula is a little complex." }, { "code": null, "e": 2379, "s": 1905, "text": "The last method to render mathematics formulas on Medium requires the installation of a Chome addon both on creator’s and reader’s browser. The addon is called Math Anywhere and it should render every MathML/LaTeX formulas on any page, also outside Medium. During the editing, you just need to put your formulas in appropriate delimiters like dollar symbols (the addon should be turned off) and during the reading, once activated the addon, the equations will be converted." }, { "code": null, "e": 2391, "s": 2379, "text": "The formula" }, { "code": null, "e": 2421, "s": 2391, "text": "should be rendered correctly:" }, { "code": null, "e": 2551, "s": 2421, "text": "(cosx+sinx)2=cos2x+sin2x+2sinxcosx(cos⁡x+sin⁡x)2=cos2⁡x+sin2⁡x+2sin⁡xcos⁡x(\\cos x + \\sin x)^2=\\cos^2 x + \\sin^2 x+2 \\sin x \\cos x" }, { "code": null, "e": 2824, "s": 2551, "text": "and also inline formulas like α:R→Rα:R→R\\alpha: \\mathbb{R} \\to \\mathbb{R} should work. The drawback of this approach is that the reader is required to install the addon (only the first time). Of course, we can insert a kind reminder at the beginning of the post like this:" }, { "code": null, "e": 2930, "s": 2824, "text": "This post contains LaTeX formulas. To render them correctly, install Math Anywhere addon and activate it." }, { "code": null, "e": 3016, "s": 2930, "text": "Do you know any other method to add math formulas on Medium? Let me know in comments!" }, { "code": null, "e": 3092, "s": 3016, "text": "How to write mathematics on MediumHow to use math formula on Medium posting" } ]
Async and Await in Dart Programming
Async and Await keywords are used to provide a declarative way to define the asynchronous function and use their results. The async keyword is used when we want to declare a function as asynchronous and the await keyword is used only on asynchronous functions. void main() async { .. } If the function has a declared return type, then update the type of the Future<T> to the return type. Future<void> main() async { .. } And finally, we make use of await keyword when we want to wait for the asynchronous function to finish. await someAsynchronousFunction() Let's consider an example where we are declaring the main function with the help of the async keyword and then wait for an asynchronous result using the await keyword. Future<void> printDelayedMessage() { return Future.delayed(Duration(seconds: 4), () => print('Delayed Output.')); } void main() async { await printDelayedMessage(); // will block the output until the asynchronous result print('First output ...'); } Delayed Output. First output ... Let's consider one more complete example where we make use of both the async and await keyword. Consider the example shown below − void main() async { var userEmailFuture = getUserEmail(); // register callback await userEmailFuture.then((userEmail) => print(userEmail)); print('Hello'); } // method which computes a future Future<String> getUserEmail() { // simulate a long network call return Future.delayed(Duration(seconds: 4), () => "mukul@tutorialspoint.com"); } mukul@tutorialspoint.com Hello
[ { "code": null, "e": 1184, "s": 1062, "text": "Async and Await keywords are used to provide a declarative way to define the asynchronous function and use their results." }, { "code": null, "e": 1323, "s": 1184, "text": "The async keyword is used when we want to declare a function as asynchronous and the await keyword is used only on asynchronous functions." }, { "code": null, "e": 1348, "s": 1323, "text": "void main() async { .. }" }, { "code": null, "e": 1450, "s": 1348, "text": "If the function has a declared return type, then update the type of the Future<T> to the return type." }, { "code": null, "e": 1483, "s": 1450, "text": "Future<void> main() async { .. }" }, { "code": null, "e": 1587, "s": 1483, "text": "And finally, we make use of await keyword when we want to wait for the asynchronous function to finish." }, { "code": null, "e": 1620, "s": 1587, "text": "await someAsynchronousFunction()" }, { "code": null, "e": 1788, "s": 1620, "text": "Let's consider an example where we are declaring the main function with the help of the async keyword and then wait for an asynchronous result using the await keyword." }, { "code": null, "e": 2040, "s": 1788, "text": "Future<void> printDelayedMessage() {\n return Future.delayed(Duration(seconds: 4), () => print('Delayed Output.'));\n}\nvoid main() async {\nawait printDelayedMessage(); // will block the output until the asynchronous result\nprint('First output ...');\n}" }, { "code": null, "e": 2073, "s": 2040, "text": "Delayed Output.\nFirst output ..." }, { "code": null, "e": 2169, "s": 2073, "text": "Let's consider one more complete example where we make use of both the async and await keyword." }, { "code": null, "e": 2204, "s": 2169, "text": "Consider the example shown below −" }, { "code": null, "e": 2559, "s": 2204, "text": "void main() async {\n var userEmailFuture = getUserEmail();\n // register callback\n await userEmailFuture.then((userEmail) => print(userEmail));\n print('Hello');\n}\n// method which computes a future\nFuture<String> getUserEmail() {\n // simulate a long network call\n return Future.delayed(Duration(seconds: 4), () => \"mukul@tutorialspoint.com\");\n}" }, { "code": null, "e": 2590, "s": 2559, "text": "mukul@tutorialspoint.com\nHello" } ]
Python - Filter tuple with all same elements - GeeksforGeeks
07 Oct, 2021 Given List of tuples, filter tuples that have same values. Input : test_list = [(5, 6, 5, 5), (6, 6, 6), (9, 10)] Output : [(6, 6, 6)] Explanation : 1 tuple with same elements. Input : test_list = [(5, 6, 5, 5), (6, 5, 6), (9, 10)] Output : [] Explanation : No tuple with same elements. Method #1 : Using list comprehension + set() + len() In this, we check for length of set converted tuple to be 1, if that checks out, tuple is added to result, else, omitted. Python3 # Python3 code to demonstrate working of# Filter similar elements Tuples# Using list comprehension + set() + len() # initializing listtest_list = [(5, 6, 5, 5), (6, 6, 6), (1, 1), (9, 10)] # printing original listprint("The original list is : " + str(test_list)) # length is computed using len()res = [sub for sub in test_list if len(set(sub)) == 1] # printing resultsprint("Filtered Tuples : " + str(res)) The original list is : [(5, 6, 5, 5), (6, 6, 6), (1, 1), (9, 10)] Filtered Tuples : [(6, 6, 6), (1, 1)] Method #2 : Using filter() + lambda + set() + len() In this, we perform task of filtering using filter(), and single element logic is checked in lambda function using set() and len(). Python3 # Python3 code to demonstrate working of# Filter similar elements Tuples# Using filter() + lambda + set() + len() # initializing listtest_list = [(5, 6, 5, 5), (6, 6, 6), (1, 1), (9, 10)] # printing original listprint("The original list is : " + str(test_list)) # end result converted to list object# filter extracts req. tuplesres = list(filter(lambda sub : len(set(sub)) == 1, test_list)) # printing resultsprint("Filtered Tuples : " + str(res)) The original list is : [(5, 6, 5, 5), (6, 6, 6), (1, 1), (9, 10)] Filtered Tuples : [(6, 6, 6), (1, 1)] abhishek0719kadiyan Python list-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary Enumerate() in Python Read a file line by line in Python Defaultdict in Python Different ways to create Pandas Dataframe Defaultdict in Python Python program to convert a list to string Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary
[ { "code": null, "e": 24119, "s": 24091, "text": "\n07 Oct, 2021" }, { "code": null, "e": 24178, "s": 24119, "text": "Given List of tuples, filter tuples that have same values." }, { "code": null, "e": 24296, "s": 24178, "text": "Input : test_list = [(5, 6, 5, 5), (6, 6, 6), (9, 10)] Output : [(6, 6, 6)] Explanation : 1 tuple with same elements." }, { "code": null, "e": 24407, "s": 24296, "text": "Input : test_list = [(5, 6, 5, 5), (6, 5, 6), (9, 10)] Output : [] Explanation : No tuple with same elements. " }, { "code": null, "e": 24460, "s": 24407, "text": "Method #1 : Using list comprehension + set() + len()" }, { "code": null, "e": 24582, "s": 24460, "text": "In this, we check for length of set converted tuple to be 1, if that checks out, tuple is added to result, else, omitted." }, { "code": null, "e": 24590, "s": 24582, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of# Filter similar elements Tuples# Using list comprehension + set() + len() # initializing listtest_list = [(5, 6, 5, 5), (6, 6, 6), (1, 1), (9, 10)] # printing original listprint(\"The original list is : \" + str(test_list)) # length is computed using len()res = [sub for sub in test_list if len(set(sub)) == 1] # printing resultsprint(\"Filtered Tuples : \" + str(res))", "e": 25005, "s": 24590, "text": null }, { "code": null, "e": 25109, "s": 25005, "text": "The original list is : [(5, 6, 5, 5), (6, 6, 6), (1, 1), (9, 10)]\nFiltered Tuples : [(6, 6, 6), (1, 1)]" }, { "code": null, "e": 25161, "s": 25109, "text": "Method #2 : Using filter() + lambda + set() + len()" }, { "code": null, "e": 25293, "s": 25161, "text": "In this, we perform task of filtering using filter(), and single element logic is checked in lambda function using set() and len()." }, { "code": null, "e": 25301, "s": 25293, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of# Filter similar elements Tuples# Using filter() + lambda + set() + len() # initializing listtest_list = [(5, 6, 5, 5), (6, 6, 6), (1, 1), (9, 10)] # printing original listprint(\"The original list is : \" + str(test_list)) # end result converted to list object# filter extracts req. tuplesres = list(filter(lambda sub : len(set(sub)) == 1, test_list)) # printing resultsprint(\"Filtered Tuples : \" + str(res))", "e": 25757, "s": 25301, "text": null }, { "code": null, "e": 25861, "s": 25757, "text": "The original list is : [(5, 6, 5, 5), (6, 6, 6), (1, 1), (9, 10)]\nFiltered Tuples : [(6, 6, 6), (1, 1)]" }, { "code": null, "e": 25881, "s": 25861, "text": "abhishek0719kadiyan" }, { "code": null, "e": 25902, "s": 25881, "text": "Python list-programs" }, { "code": null, "e": 25909, "s": 25902, "text": "Python" }, { "code": null, "e": 25925, "s": 25909, "text": "Python Programs" }, { "code": null, "e": 26023, "s": 25925, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26032, "s": 26023, "text": "Comments" }, { "code": null, "e": 26045, "s": 26032, "text": "Old Comments" }, { "code": null, "e": 26063, "s": 26045, "text": "Python Dictionary" }, { "code": null, "e": 26085, "s": 26063, "text": "Enumerate() in Python" }, { "code": null, "e": 26120, "s": 26085, "text": "Read a file line by line in Python" }, { "code": null, "e": 26142, "s": 26120, "text": "Defaultdict in Python" }, { "code": null, "e": 26184, "s": 26142, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 26206, "s": 26184, "text": "Defaultdict in Python" }, { "code": null, "e": 26249, "s": 26206, "text": "Python program to convert a list to string" }, { "code": null, "e": 26288, "s": 26249, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 26334, "s": 26288, "text": "Python | Split string into list of characters" } ]
Animate border-color property with CSS
To implement animation on the border-color property with CSS, you can try to run the following code Live Demo <!DOCTYPE html> <html> <head> <style> div { width: 500px; height: 300px; background: yellow; border: 10px solid gray; animation: myanim 3s infinite; background-position: bottom left; background-size: 50px; } @keyframes myanim { 20% { border-color: red; } } </style> </head> <body> <h2>Performing Animation for color of border</h2> <div></div> </body> </html>
[ { "code": null, "e": 1162, "s": 1062, "text": "To implement animation on the border-color property with CSS, you can try to run the following code" }, { "code": null, "e": 1172, "s": 1162, "text": "Live Demo" }, { "code": null, "e": 1726, "s": 1172, "text": "<!DOCTYPE html>\n<html>\n <head>\n <style>\n div {\n width: 500px;\n height: 300px;\n background: yellow;\n border: 10px solid gray;\n animation: myanim 3s infinite;\n background-position: bottom left;\n background-size: 50px;\n }\n @keyframes myanim {\n 20% {\n border-color: red;\n }\n }\n </style>\n </head>\n <body>\n <h2>Performing Animation for color of border</h2>\n <div></div>\n </body>\n</html>" } ]
AbstractList remove() Method in Java with Examples - GeeksforGeeks
26 Nov, 2018 The remove(int index) method of java.util.AbstractList class is used to remove an element from an abstract list from a specific position or index. Syntax: AbstractList.remove(int index) Parameters: The parameter index is of integer data type and specifies the position of the element to be removed from the AbstractList. Return Value: This method returns the element that has just been removed from the list. Below programs illustrate the AbstractList.remove(int index) method: Program 1: // Java code to illustrate remove() method import java.util.*;import java.util.LinkedList; public class AbstractListDemo { public static void main(String args[]) { // Creating an empty AbstractList AbstractList<String> list = new LinkedList<String>(); // Using add() method to add elements in the list list.add("Geeks"); list.add("for"); list.add("Geeks"); list.add("10"); list.add("20"); // Output the list System.out.println("AbstractList: " + list); // Remove the head using remove() list.remove(3); // Print the final list System.out.println("Final AbstractList: " + list); }} AbstractList: [Geeks, for, Geeks, 10, 20] Final AbstractList: [Geeks, for, Geeks, 20] Program 2: // Java code to illustrate remove() when position of// element is passed as parameter import java.util.*;import java.util.LinkedList; public class AbstractListDemo { public static void main(String args[]) { // Creating an empty AbstractList AbstractList<String> list = new LinkedList<String>(); // Use add() method to add elements in the list list.add("Geeks"); list.add("for"); list.add("Geeks"); list.add("10"); list.add("20"); // Output the list System.out.println("AbstractList:" + list); // Remove the head using remove() list.remove(0); // Print the final list System.out.println("Final AbstractList:" + list); }} AbstractList:[Geeks, for, Geeks, 10, 20] Final AbstractList:[for, Geeks, 10, 20] Java - util package Java-AbstractList Java-Collections Java-Functions Java Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Arrays in Java Split() String method in Java with examples For-each loop in Java Reverse a string in Java Arrays.sort() in Java with examples Object Oriented Programming (OOPs) Concept in Java HashMap in Java with Examples How to iterate any Map in Java Interfaces in Java Initialize an ArrayList in Java
[ { "code": null, "e": 23299, "s": 23271, "text": "\n26 Nov, 2018" }, { "code": null, "e": 23446, "s": 23299, "text": "The remove(int index) method of java.util.AbstractList class is used to remove an element from an abstract list from a specific position or index." }, { "code": null, "e": 23454, "s": 23446, "text": "Syntax:" }, { "code": null, "e": 23485, "s": 23454, "text": "AbstractList.remove(int index)" }, { "code": null, "e": 23620, "s": 23485, "text": "Parameters: The parameter index is of integer data type and specifies the position of the element to be removed from the AbstractList." }, { "code": null, "e": 23708, "s": 23620, "text": "Return Value: This method returns the element that has just been removed from the list." }, { "code": null, "e": 23777, "s": 23708, "text": "Below programs illustrate the AbstractList.remove(int index) method:" }, { "code": null, "e": 23788, "s": 23777, "text": "Program 1:" }, { "code": "// Java code to illustrate remove() method import java.util.*;import java.util.LinkedList; public class AbstractListDemo { public static void main(String args[]) { // Creating an empty AbstractList AbstractList<String> list = new LinkedList<String>(); // Using add() method to add elements in the list list.add(\"Geeks\"); list.add(\"for\"); list.add(\"Geeks\"); list.add(\"10\"); list.add(\"20\"); // Output the list System.out.println(\"AbstractList: \" + list); // Remove the head using remove() list.remove(3); // Print the final list System.out.println(\"Final AbstractList: \" + list); }}", "e": 24499, "s": 23788, "text": null }, { "code": null, "e": 24586, "s": 24499, "text": "AbstractList: [Geeks, for, Geeks, 10, 20]\nFinal AbstractList: [Geeks, for, Geeks, 20]\n" }, { "code": null, "e": 24597, "s": 24586, "text": "Program 2:" }, { "code": "// Java code to illustrate remove() when position of// element is passed as parameter import java.util.*;import java.util.LinkedList; public class AbstractListDemo { public static void main(String args[]) { // Creating an empty AbstractList AbstractList<String> list = new LinkedList<String>(); // Use add() method to add elements in the list list.add(\"Geeks\"); list.add(\"for\"); list.add(\"Geeks\"); list.add(\"10\"); list.add(\"20\"); // Output the list System.out.println(\"AbstractList:\" + list); // Remove the head using remove() list.remove(0); // Print the final list System.out.println(\"Final AbstractList:\" + list); }}", "e": 25336, "s": 24597, "text": null }, { "code": null, "e": 25418, "s": 25336, "text": "AbstractList:[Geeks, for, Geeks, 10, 20]\nFinal AbstractList:[for, Geeks, 10, 20]\n" }, { "code": null, "e": 25438, "s": 25418, "text": "Java - util package" }, { "code": null, "e": 25456, "s": 25438, "text": "Java-AbstractList" }, { "code": null, "e": 25473, "s": 25456, "text": "Java-Collections" }, { "code": null, "e": 25488, "s": 25473, "text": "Java-Functions" }, { "code": null, "e": 25493, "s": 25488, "text": "Java" }, { "code": null, "e": 25498, "s": 25493, "text": "Java" }, { "code": null, "e": 25515, "s": 25498, "text": "Java-Collections" }, { "code": null, "e": 25613, "s": 25515, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25622, "s": 25613, "text": "Comments" }, { "code": null, "e": 25635, "s": 25622, "text": "Old Comments" }, { "code": null, "e": 25650, "s": 25635, "text": "Arrays in Java" }, { "code": null, "e": 25694, "s": 25650, "text": "Split() String method in Java with examples" }, { "code": null, "e": 25716, "s": 25694, "text": "For-each loop in Java" }, { "code": null, "e": 25741, "s": 25716, "text": "Reverse a string in Java" }, { "code": null, "e": 25777, "s": 25741, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 25828, "s": 25777, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 25858, "s": 25828, "text": "HashMap in Java with Examples" }, { "code": null, "e": 25889, "s": 25858, "text": "How to iterate any Map in Java" }, { "code": null, "e": 25908, "s": 25889, "text": "Interfaces in Java" } ]
How to define the breaks for a histogram using ggplot2 in R?
To manually define the breaks for a histogram using ggplot2, we can use breaks argument in the geom_histogram function. While creating the number of breaks we must be careful about the starting point and the difference between values for breaks. This will define the number of bars for histogram so it should be taken seriously and should be according to the distribution of the data. Consider the below data frame − Live Demo x<-rnorm(5000,525,30.24) df<-data.frame(x) head(df,20) x 1 524.0964 2 490.5952 3 518.6243 4 544.0018 5 480.8306 6 461.2975 7 464.0870 8 516.5240 9 517.3936 10 506.0277 11 480.3274 12 505.6415 13 440.9464 14 532.0064 15 482.7700 16 517.3608 17 536.5500 18 518.7121 19 598.5776 20 506.3834 Loading ggplot2 package and creating a histogram of x − library(ggplot2) ggplot(df,aes(x))+geom_histogram(bins=30) Creating histogram of x with manually defined breaks − ggplot(df,aes(x))+geom_histogram(bins=30,breaks=c(400,420,440,460,480,500,520,540,560))
[ { "code": null, "e": 1447, "s": 1062, "text": "To manually define the breaks for a histogram using ggplot2, we can use breaks argument in the geom_histogram function. While creating the number of breaks we must be careful about the starting point and the difference between values for breaks. This will define the number of bars for histogram so it should be taken seriously and should be according to the distribution of the data." }, { "code": null, "e": 1479, "s": 1447, "text": "Consider the below data frame −" }, { "code": null, "e": 1490, "s": 1479, "text": " Live Demo" }, { "code": null, "e": 1545, "s": 1490, "text": "x<-rnorm(5000,525,30.24)\ndf<-data.frame(x)\nhead(df,20)" }, { "code": null, "e": 1791, "s": 1545, "text": " x\n1 524.0964\n2 490.5952\n3 518.6243\n4 544.0018\n5 480.8306\n6 461.2975\n7 464.0870\n8 516.5240\n9 517.3936\n10 506.0277\n11 480.3274\n12 505.6415\n13 440.9464\n14 532.0064\n15 482.7700\n16 517.3608\n17 536.5500\n18 518.7121\n19 598.5776\n20 506.3834" }, { "code": null, "e": 1847, "s": 1791, "text": "Loading ggplot2 package and creating a histogram of x −" }, { "code": null, "e": 1906, "s": 1847, "text": "library(ggplot2)\nggplot(df,aes(x))+geom_histogram(bins=30)" }, { "code": null, "e": 1961, "s": 1906, "text": "Creating histogram of x with manually defined breaks −" }, { "code": null, "e": 2049, "s": 1961, "text": "ggplot(df,aes(x))+geom_histogram(bins=30,breaks=c(400,420,440,460,480,500,520,540,560))" } ]
.NET Core API for the Angular Tour of Heroes App — Introduction | by Richard Peterson | Towards Data Science
This article assumes that you have already built the Angular official tutorial — Tour of Heroes app. If you have not built this, you should check the Angular docs, or download from here. Everything else will be taken care of in this series of articles! In this series, we will embark on a magical exploration of .NET Core, Angular, Docker, Azure, and Azure SQL Server. We will become familiar with several technologies, such as Docker containers, C#, JavaScript, SQL, and the Azure Command Line Interface. The end result of these articles will be an Angular front end with a .NET Core API that talks to an Azure SQL server, all hosted on Azure. This article — environment setup and explanation of MVC.Local Docker setup of a Microsoft SQL Server (mssql).Build the .NET API.Deploying your API to Azure.Deploy your Angular app to Azure. This article — environment setup and explanation of MVC. Local Docker setup of a Microsoft SQL Server (mssql). Build the .NET API. Deploying your API to Azure. Deploy your Angular app to Azure. Visual Studio Code (it’s the free one)Angular CLI (should already be setup from the Tour Of Heroes Tutorial).NET Core — This API will use version 3.0.2Postman — for testing the APIDocker — for a local dev database, and for containerizing our apps Visual Studio Code (it’s the free one) Angular CLI (should already be setup from the Tour Of Heroes Tutorial) .NET Core — This API will use version 3.0.2 Postman — for testing the API Docker — for a local dev database, and for containerizing our apps Follow along using my GitHub repo. First, launch your Tour of Heroes Angular app by running ng serve --open from the root directory of your app. You should see the app running on port 4200. When you built the original app, it had a built-in web server that mimicked an actual server. We will be replacing this artificial server with a web API written in C# using the .NET framework. Let’s shutdown the app and get to work on the API. Make sure the .NET Core CLI is installed by running dotnet --version. The .NET Core CLI has lots of templates from which to choose. Check these option flags with dotnet new -h. Do you see the Template for ASP.NET Core Web API? Its Short Name is webapi. Create your API from the command line by running: dotnet new webapi -n Heroes.API You should get a result of Restore succeeded. Move into the new directory by typing cd Heroes.API. Check ls to see the folders and files that have been created, and launch VS Code in this directory by typing (with a period)code . . Let’s also make sure the API launches by running dotnet run. In a web browser, navigate to https://localhost:5001/weatherforecast and accept the unsafe destination to view sample output returned by your API in JSON format. This is great because is gives you an idea of how .NET Core APIs work by using a Model and a Controller. We will create our own Model and Controller, and also add a database Context. MVC is a web development philosophy that recommends the separation of pieces of an app into logical components. This allows you to build each piece separately and confirm it works, and then connect your pieces for a finished whole. This article from FreeCodeCamp.org does an excellent job of explaining how MVC is like ordering a drink from a bar. The drink menu is the View, and you make requests to the bartender (Controller), who makes drinks based on ingredients and instructions (Model), and returns your finished drink to the bar (View). In the context of our app, this means: VIEW: The Angular app will receive input, make requests, and display data.CONTROLLER: C# class that accepts incoming requests, deciphers the route of the request, and uses a specified Model to interact with the database based on the route it receives.MODEL: C# class that defines the data being passed to or retrieved from the database. This will mean defining things like id is an integer, name is a string, so that C# can pass these values in a way that SQL can interpret. Database context is important to the Model VIEW: The Angular app will receive input, make requests, and display data. CONTROLLER: C# class that accepts incoming requests, deciphers the route of the request, and uses a specified Model to interact with the database based on the route it receives. MODEL: C# class that defines the data being passed to or retrieved from the database. This will mean defining things like id is an integer, name is a string, so that C# can pass these values in a way that SQL can interpret. Database context is important to the Model Microsoft has published great tutorials on .NET Core, and I highly recommend checking out: Tutorial: Create a web API with ASP.NET Core.Create a web app with ASP.NET Core MVC Tutorial: Create a web API with ASP.NET Core. Create a web app with ASP.NET Core MVC At this point, you should have 2 resources: A working Angular Tour of Heroes App.A generic .NET Core API. A working Angular Tour of Heroes App. A generic .NET Core API. We need to create a database that can handle requests from our API Controller. We will eventually move to a hosted Azure SQL database, but for now, let’s launch a local Docker container of a Microsoft SQL Server. This container is a lightweight version of SQL Server that we can easily spin up for development. Head on over to Build a MSSQL Docker Container to setup the database! Build your .NET API from scratch, with a little help from the aspnet-codegenerator. The app will handle API requests to these routes: GET: api/Heroes — this method will return all the heroes in the databaseGET: api/Heroes/5 — this method will return a specific hero from the database. In this case, it will return the hero with an Id of 5.PUT: api/Heroes/5 — this method will update a specific hero’s information.POST: api/Heroes — this method will post a new hero to the database.DELETE: api/Heroes/5 — this method will delete a specific hero from the database. GET: api/Heroes — this method will return all the heroes in the database GET: api/Heroes/5 — this method will return a specific hero from the database. In this case, it will return the hero with an Id of 5. PUT: api/Heroes/5 — this method will update a specific hero’s information. POST: api/Heroes — this method will post a new hero to the database. DELETE: api/Heroes/5 — this method will delete a specific hero from the database. At the end of this article, you will have a working local version of the Angular app, .NET API, and database. Finally, you will create an Azure SQL server and deploy your .NET API to an Azure remote git repo, and serve with a web app. Then you will deploy your angular app to Azure as a Docker container web app. Thank you for reading!
[ { "code": null, "e": 425, "s": 172, "text": "This article assumes that you have already built the Angular official tutorial — Tour of Heroes app. If you have not built this, you should check the Angular docs, or download from here. Everything else will be taken care of in this series of articles!" }, { "code": null, "e": 541, "s": 425, "text": "In this series, we will embark on a magical exploration of .NET Core, Angular, Docker, Azure, and Azure SQL Server." }, { "code": null, "e": 678, "s": 541, "text": "We will become familiar with several technologies, such as Docker containers, C#, JavaScript, SQL, and the Azure Command Line Interface." }, { "code": null, "e": 817, "s": 678, "text": "The end result of these articles will be an Angular front end with a .NET Core API that talks to an Azure SQL server, all hosted on Azure." }, { "code": null, "e": 1007, "s": 817, "text": "This article — environment setup and explanation of MVC.Local Docker setup of a Microsoft SQL Server (mssql).Build the .NET API.Deploying your API to Azure.Deploy your Angular app to Azure." }, { "code": null, "e": 1064, "s": 1007, "text": "This article — environment setup and explanation of MVC." }, { "code": null, "e": 1118, "s": 1064, "text": "Local Docker setup of a Microsoft SQL Server (mssql)." }, { "code": null, "e": 1138, "s": 1118, "text": "Build the .NET API." }, { "code": null, "e": 1167, "s": 1138, "text": "Deploying your API to Azure." }, { "code": null, "e": 1201, "s": 1167, "text": "Deploy your Angular app to Azure." }, { "code": null, "e": 1448, "s": 1201, "text": "Visual Studio Code (it’s the free one)Angular CLI (should already be setup from the Tour Of Heroes Tutorial).NET Core — This API will use version 3.0.2Postman — for testing the APIDocker — for a local dev database, and for containerizing our apps" }, { "code": null, "e": 1487, "s": 1448, "text": "Visual Studio Code (it’s the free one)" }, { "code": null, "e": 1558, "s": 1487, "text": "Angular CLI (should already be setup from the Tour Of Heroes Tutorial)" }, { "code": null, "e": 1602, "s": 1558, "text": ".NET Core — This API will use version 3.0.2" }, { "code": null, "e": 1632, "s": 1602, "text": "Postman — for testing the API" }, { "code": null, "e": 1699, "s": 1632, "text": "Docker — for a local dev database, and for containerizing our apps" }, { "code": null, "e": 1734, "s": 1699, "text": "Follow along using my GitHub repo." }, { "code": null, "e": 1889, "s": 1734, "text": "First, launch your Tour of Heroes Angular app by running ng serve --open from the root directory of your app. You should see the app running on port 4200." }, { "code": null, "e": 2133, "s": 1889, "text": "When you built the original app, it had a built-in web server that mimicked an actual server. We will be replacing this artificial server with a web API written in C# using the .NET framework. Let’s shutdown the app and get to work on the API." }, { "code": null, "e": 2436, "s": 2133, "text": "Make sure the .NET Core CLI is installed by running dotnet --version. The .NET Core CLI has lots of templates from which to choose. Check these option flags with dotnet new -h. Do you see the Template for ASP.NET Core Web API? Its Short Name is webapi. Create your API from the command line by running:" }, { "code": null, "e": 2468, "s": 2436, "text": "dotnet new webapi -n Heroes.API" }, { "code": null, "e": 2700, "s": 2468, "text": "You should get a result of Restore succeeded. Move into the new directory by typing cd Heroes.API. Check ls to see the folders and files that have been created, and launch VS Code in this directory by typing (with a period)code . ." }, { "code": null, "e": 3106, "s": 2700, "text": "Let’s also make sure the API launches by running dotnet run. In a web browser, navigate to https://localhost:5001/weatherforecast and accept the unsafe destination to view sample output returned by your API in JSON format. This is great because is gives you an idea of how .NET Core APIs work by using a Model and a Controller. We will create our own Model and Controller, and also add a database Context." }, { "code": null, "e": 3650, "s": 3106, "text": "MVC is a web development philosophy that recommends the separation of pieces of an app into logical components. This allows you to build each piece separately and confirm it works, and then connect your pieces for a finished whole. This article from FreeCodeCamp.org does an excellent job of explaining how MVC is like ordering a drink from a bar. The drink menu is the View, and you make requests to the bartender (Controller), who makes drinks based on ingredients and instructions (Model), and returns your finished drink to the bar (View)." }, { "code": null, "e": 3689, "s": 3650, "text": "In the context of our app, this means:" }, { "code": null, "e": 4207, "s": 3689, "text": "VIEW: The Angular app will receive input, make requests, and display data.CONTROLLER: C# class that accepts incoming requests, deciphers the route of the request, and uses a specified Model to interact with the database based on the route it receives.MODEL: C# class that defines the data being passed to or retrieved from the database. This will mean defining things like id is an integer, name is a string, so that C# can pass these values in a way that SQL can interpret. Database context is important to the Model" }, { "code": null, "e": 4282, "s": 4207, "text": "VIEW: The Angular app will receive input, make requests, and display data." }, { "code": null, "e": 4460, "s": 4282, "text": "CONTROLLER: C# class that accepts incoming requests, deciphers the route of the request, and uses a specified Model to interact with the database based on the route it receives." }, { "code": null, "e": 4727, "s": 4460, "text": "MODEL: C# class that defines the data being passed to or retrieved from the database. This will mean defining things like id is an integer, name is a string, so that C# can pass these values in a way that SQL can interpret. Database context is important to the Model" }, { "code": null, "e": 4818, "s": 4727, "text": "Microsoft has published great tutorials on .NET Core, and I highly recommend checking out:" }, { "code": null, "e": 4902, "s": 4818, "text": "Tutorial: Create a web API with ASP.NET Core.Create a web app with ASP.NET Core MVC" }, { "code": null, "e": 4948, "s": 4902, "text": "Tutorial: Create a web API with ASP.NET Core." }, { "code": null, "e": 4987, "s": 4948, "text": "Create a web app with ASP.NET Core MVC" }, { "code": null, "e": 5031, "s": 4987, "text": "At this point, you should have 2 resources:" }, { "code": null, "e": 5093, "s": 5031, "text": "A working Angular Tour of Heroes App.A generic .NET Core API." }, { "code": null, "e": 5131, "s": 5093, "text": "A working Angular Tour of Heroes App." }, { "code": null, "e": 5156, "s": 5131, "text": "A generic .NET Core API." }, { "code": null, "e": 5467, "s": 5156, "text": "We need to create a database that can handle requests from our API Controller. We will eventually move to a hosted Azure SQL database, but for now, let’s launch a local Docker container of a Microsoft SQL Server. This container is a lightweight version of SQL Server that we can easily spin up for development." }, { "code": null, "e": 5537, "s": 5467, "text": "Head on over to Build a MSSQL Docker Container to setup the database!" }, { "code": null, "e": 5671, "s": 5537, "text": "Build your .NET API from scratch, with a little help from the aspnet-codegenerator. The app will handle API requests to these routes:" }, { "code": null, "e": 6100, "s": 5671, "text": "GET: api/Heroes — this method will return all the heroes in the databaseGET: api/Heroes/5 — this method will return a specific hero from the database. In this case, it will return the hero with an Id of 5.PUT: api/Heroes/5 — this method will update a specific hero’s information.POST: api/Heroes — this method will post a new hero to the database.DELETE: api/Heroes/5 — this method will delete a specific hero from the database." }, { "code": null, "e": 6173, "s": 6100, "text": "GET: api/Heroes — this method will return all the heroes in the database" }, { "code": null, "e": 6307, "s": 6173, "text": "GET: api/Heroes/5 — this method will return a specific hero from the database. In this case, it will return the hero with an Id of 5." }, { "code": null, "e": 6382, "s": 6307, "text": "PUT: api/Heroes/5 — this method will update a specific hero’s information." }, { "code": null, "e": 6451, "s": 6382, "text": "POST: api/Heroes — this method will post a new hero to the database." }, { "code": null, "e": 6533, "s": 6451, "text": "DELETE: api/Heroes/5 — this method will delete a specific hero from the database." }, { "code": null, "e": 6643, "s": 6533, "text": "At the end of this article, you will have a working local version of the Angular app, .NET API, and database." }, { "code": null, "e": 6768, "s": 6643, "text": "Finally, you will create an Azure SQL server and deploy your .NET API to an Azure remote git repo, and serve with a web app." }, { "code": null, "e": 6846, "s": 6768, "text": "Then you will deploy your angular app to Azure as a Docker container web app." } ]
Go - The Switch Statement
A switch statement allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being switched on is checked for each switch case. In Go programming, switch statements are of two types − Expression Switch − In expression switch, a case contains expressions, which is compared against the value of the switch expression. Expression Switch − In expression switch, a case contains expressions, which is compared against the value of the switch expression. Type Switch − In type switch, a case contain type which is compared against the type of a specially annotated switch expression. Type Switch − In type switch, a case contain type which is compared against the type of a specially annotated switch expression. The syntax for expression switch statement in Go programming language is as follows − switch(boolean-expression or integral type){ case boolean-expression or integral type : statement(s); case boolean-expression or integral type : statement(s); /* you can have any number of case statements */ default : /* Optional */ statement(s); } The following rules apply to a switch statement − The expression used in a switch statement must have an integral or boolean expression, or be of a class type in which the class has a single conversion function to an integral or boolean value. If the expression is not passed then the default value is true. The expression used in a switch statement must have an integral or boolean expression, or be of a class type in which the class has a single conversion function to an integral or boolean value. If the expression is not passed then the default value is true. You can have any number of case statements within a switch. Each case is followed by the value to be compared to and a colon. You can have any number of case statements within a switch. Each case is followed by the value to be compared to and a colon. The constant-expression for a case must be the same data type as the variable in the switch, and it must be a constant or a literal. The constant-expression for a case must be the same data type as the variable in the switch, and it must be a constant or a literal. When the variable being switched on is equal to a case, the statements following that case will execute. No break is needed in the case statement. When the variable being switched on is equal to a case, the statements following that case will execute. No break is needed in the case statement. A switch statement can have an optional default case, which must appear at the end of the switch. The default case can be used for performing a task when none of the cases is true. No break is needed in the default case. A switch statement can have an optional default case, which must appear at the end of the switch. The default case can be used for performing a task when none of the cases is true. No break is needed in the default case. package main import "fmt" func main() { /* local variable definition */ var grade string = "B" var marks int = 90 switch marks { case 90: grade = "A" case 80: grade = "B" case 50,60,70 : grade = "C" default: grade = "D" } switch { case grade == "A" : fmt.Printf("Excellent!\n" ) case grade == "B", grade == "C" : fmt.Printf("Well done\n" ) case grade == "D" : fmt.Printf("You passed\n" ) case grade == "F": fmt.Printf("Better try again\n" ) default: fmt.Printf("Invalid grade\n" ); } fmt.Printf("Your grade is %s\n", grade ); } When the above code is compiled and executed, it produces the following result − Excellent! Your grade is A The syntax for a type switch statement in Go programming is as follows − switch x.(type){ case type: statement(s); case type: statement(s); /* you can have any number of case statements */ default: /* Optional */ statement(s); } The following rules apply to a switch statement − The expression used in a switch statement must have an variable of interface{} type. The expression used in a switch statement must have an variable of interface{} type. You can have any number of case statements within a switch. Each case is followed by the value to be compared to and a colon. You can have any number of case statements within a switch. Each case is followed by the value to be compared to and a colon. The type for a case must be the same data type as the variable in the switch, and it must be a valid data type. The type for a case must be the same data type as the variable in the switch, and it must be a valid data type. When the variable being switched on is equal to a case, the statements following that case will execute. No break is needed in the case statement. When the variable being switched on is equal to a case, the statements following that case will execute. No break is needed in the case statement. A switch statement can have an optional default case, which must appear at the end of the switch. The default case can be used for performing a task when none of the cases is true. No break is needed in the default case. A switch statement can have an optional default case, which must appear at the end of the switch. The default case can be used for performing a task when none of the cases is true. No break is needed in the default case. package main import "fmt" func main() { var x interface{} switch i := x.(type) { case nil: fmt.Printf("type of x :%T",i) case int: fmt.Printf("x is int") case float64: fmt.Printf("x is float64") case func(int) float64: fmt.Printf("x is func(int)") case bool, string: fmt.Printf("x is bool or string") default: fmt.Printf("don't know the type") } } When the above code is compiled and executed, it produces the following result − type of x :<nil> 64 Lectures 6.5 hours Ridhi Arora 20 Lectures 2.5 hours Asif Hussain 22 Lectures 4 hours Dilip Padmanabhan 48 Lectures 6 hours Arnab Chakraborty 7 Lectures 1 hours Aditya Kulkarni 44 Lectures 3 hours Arnab Chakraborty Print Add Notes Bookmark this page
[ { "code": null, "e": 2123, "s": 1937, "text": "A switch statement allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being switched on is checked for each switch case." }, { "code": null, "e": 2179, "s": 2123, "text": "In Go programming, switch statements are of two types −" }, { "code": null, "e": 2312, "s": 2179, "text": "Expression Switch − In expression switch, a case contains expressions, which is compared against the value of the switch expression." }, { "code": null, "e": 2445, "s": 2312, "text": "Expression Switch − In expression switch, a case contains expressions, which is compared against the value of the switch expression." }, { "code": null, "e": 2574, "s": 2445, "text": "Type Switch − In type switch, a case contain type which is compared against the type of a specially annotated switch expression." }, { "code": null, "e": 2703, "s": 2574, "text": "Type Switch − In type switch, a case contain type which is compared against the type of a specially annotated switch expression." }, { "code": null, "e": 2789, "s": 2703, "text": "The syntax for expression switch statement in Go programming language is as follows −" }, { "code": null, "e": 3080, "s": 2789, "text": "switch(boolean-expression or integral type){\n case boolean-expression or integral type :\n statement(s); \n case boolean-expression or integral type :\n statement(s); \n \n /* you can have any number of case statements */\n default : /* Optional */\n statement(s);\n}\n" }, { "code": null, "e": 3130, "s": 3080, "text": "The following rules apply to a switch statement −" }, { "code": null, "e": 3388, "s": 3130, "text": "The expression used in a switch statement must have an integral or boolean expression, or be of a class type in which the class has a single conversion function to an integral or boolean value. If the expression is not passed then the default value is true." }, { "code": null, "e": 3646, "s": 3388, "text": "The expression used in a switch statement must have an integral or boolean expression, or be of a class type in which the class has a single conversion function to an integral or boolean value. If the expression is not passed then the default value is true." }, { "code": null, "e": 3772, "s": 3646, "text": "You can have any number of case statements within a switch. Each case is followed by the value to be compared to and a colon." }, { "code": null, "e": 3898, "s": 3772, "text": "You can have any number of case statements within a switch. Each case is followed by the value to be compared to and a colon." }, { "code": null, "e": 4031, "s": 3898, "text": "The constant-expression for a case must be the same data type as the variable in the switch, and it must be a constant or a literal." }, { "code": null, "e": 4164, "s": 4031, "text": "The constant-expression for a case must be the same data type as the variable in the switch, and it must be a constant or a literal." }, { "code": null, "e": 4311, "s": 4164, "text": "When the variable being switched on is equal to a case, the statements following that case will execute. No break is needed in the case statement." }, { "code": null, "e": 4458, "s": 4311, "text": "When the variable being switched on is equal to a case, the statements following that case will execute. No break is needed in the case statement." }, { "code": null, "e": 4679, "s": 4458, "text": "A switch statement can have an optional default case, which must appear at the end of the switch. The default case can be used for performing a task when none of the cases is true. No break is needed in the default case." }, { "code": null, "e": 4900, "s": 4679, "text": "A switch statement can have an optional default case, which must appear at the end of the switch. The default case can be used for performing a task when none of the cases is true. No break is needed in the default case." }, { "code": null, "e": 5580, "s": 4900, "text": "package main\n\nimport \"fmt\"\n\nfunc main() {\n /* local variable definition */\n var grade string = \"B\"\n var marks int = 90\n\n switch marks {\n case 90: grade = \"A\"\n case 80: grade = \"B\"\n case 50,60,70 : grade = \"C\"\n default: grade = \"D\" \n }\n switch {\n case grade == \"A\" :\n fmt.Printf(\"Excellent!\\n\" ) \n case grade == \"B\", grade == \"C\" :\n fmt.Printf(\"Well done\\n\" ) \n case grade == \"D\" :\n fmt.Printf(\"You passed\\n\" ) \n case grade == \"F\":\n fmt.Printf(\"Better try again\\n\" )\n default:\n fmt.Printf(\"Invalid grade\\n\" );\n }\n fmt.Printf(\"Your grade is %s\\n\", grade ); \n}" }, { "code": null, "e": 5661, "s": 5580, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 5690, "s": 5661, "text": "Excellent!\nYour grade is A\n" }, { "code": null, "e": 5763, "s": 5690, "text": "The syntax for a type switch statement in Go programming is as follows −" }, { "code": null, "e": 5957, "s": 5763, "text": "switch x.(type){\n case type:\n statement(s); \n case type:\n statement(s); \n /* you can have any number of case statements */\n default: /* Optional */\n statement(s);\n}\n" }, { "code": null, "e": 6007, "s": 5957, "text": "The following rules apply to a switch statement −" }, { "code": null, "e": 6092, "s": 6007, "text": "The expression used in a switch statement must have an variable of interface{} type." }, { "code": null, "e": 6177, "s": 6092, "text": "The expression used in a switch statement must have an variable of interface{} type." }, { "code": null, "e": 6303, "s": 6177, "text": "You can have any number of case statements within a switch. Each case is followed by the value to be compared to and a colon." }, { "code": null, "e": 6429, "s": 6303, "text": "You can have any number of case statements within a switch. Each case is followed by the value to be compared to and a colon." }, { "code": null, "e": 6541, "s": 6429, "text": "The type for a case must be the same data type as the variable in the switch, and it must be a valid data type." }, { "code": null, "e": 6653, "s": 6541, "text": "The type for a case must be the same data type as the variable in the switch, and it must be a valid data type." }, { "code": null, "e": 6800, "s": 6653, "text": "When the variable being switched on is equal to a case, the statements following that case will execute. No break is needed in the case statement." }, { "code": null, "e": 6947, "s": 6800, "text": "When the variable being switched on is equal to a case, the statements following that case will execute. No break is needed in the case statement." }, { "code": null, "e": 7168, "s": 6947, "text": "A switch statement can have an optional default case, which must appear at the end of the switch. The default case can be used for performing a task when none of the cases is true. No break is needed in the default case." }, { "code": null, "e": 7389, "s": 7168, "text": "A switch statement can have an optional default case, which must appear at the end of the switch. The default case can be used for performing a task when none of the cases is true. No break is needed in the default case." }, { "code": null, "e": 7937, "s": 7389, "text": "package main\n\nimport \"fmt\"\n\nfunc main() {\n var x interface{}\n \n switch i := x.(type) {\n case nil:\t \n fmt.Printf(\"type of x :%T\",i) \n case int:\t \n fmt.Printf(\"x is int\") \n case float64:\n fmt.Printf(\"x is float64\") \n case func(int) float64:\n fmt.Printf(\"x is func(int)\") \n case bool, string:\n fmt.Printf(\"x is bool or string\") \n default:\n fmt.Printf(\"don't know the type\") \n } \n}" }, { "code": null, "e": 8018, "s": 7937, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 8036, "s": 8018, "text": "type of x :<nil>\n" }, { "code": null, "e": 8071, "s": 8036, "text": "\n 64 Lectures \n 6.5 hours \n" }, { "code": null, "e": 8084, "s": 8071, "text": " Ridhi Arora" }, { "code": null, "e": 8119, "s": 8084, "text": "\n 20 Lectures \n 2.5 hours \n" }, { "code": null, "e": 8133, "s": 8119, "text": " Asif Hussain" }, { "code": null, "e": 8166, "s": 8133, "text": "\n 22 Lectures \n 4 hours \n" }, { "code": null, "e": 8185, "s": 8166, "text": " Dilip Padmanabhan" }, { "code": null, "e": 8218, "s": 8185, "text": "\n 48 Lectures \n 6 hours \n" }, { "code": null, "e": 8237, "s": 8218, "text": " Arnab Chakraborty" }, { "code": null, "e": 8269, "s": 8237, "text": "\n 7 Lectures \n 1 hours \n" }, { "code": null, "e": 8286, "s": 8269, "text": " Aditya Kulkarni" }, { "code": null, "e": 8319, "s": 8286, "text": "\n 44 Lectures \n 3 hours \n" }, { "code": null, "e": 8338, "s": 8319, "text": " Arnab Chakraborty" }, { "code": null, "e": 8345, "s": 8338, "text": " Print" }, { "code": null, "e": 8356, "s": 8345, "text": " Add Notes" } ]
MATLAB - GNU Octave Tutorial
GNU Octave is a high-level programming language like MATLAB and it is mostly compatible with MATLAB. It is also used for numerical computations. Octave has the following common features with MATLAB − matrices are fundamental data type it has built-in support for complex numbers it has built-in math functions and libraries it supports user-defined functions GNU Octave is also freely redistributable software. You may redistribute it and/or modify it under the terms of the GNU General Public License (GPL) as published by the Free Software Foundation. Most MATLAB programs run in Octave, but some of the Octave programs may not run in MATLAB because, Octave allows some syntax that MATLAB does not. For example, MATLAB supports single quotes only, but Octave supports both single and double quotes for defining strings. If you are looking for a tutorial on Octave, then kindly go through this tutorial from beginning which covers both MATLAB as well as Octave. Almost all the examples covered in this tutorial are compatible with MATLAB as well as Octave. Let's try following example in MATLAB and Octave which produces same result without any syntax changes − This example creates a 3D surface map for the function g = xe-(x2 + y2). Create a script file and type the following code − [x,y] = meshgrid(-2:.2:2); g = x .* exp(-x.^2 - y.^2); surf(x, y, g) print -deps graph.eps When you run the file, MATLAB displays the following 3-D map − Though all the core functionality of MATLAB is available in Octave, there are some functionality for example, Differential & Integration Calculus, which does not match exactly in both the languages. This tutorial has tried to give both type of examples where they differed in their syntax. Consider following example where MATLAB and Octave make use of different functions to get the area of a curve: f(x) = x2 cos(x) for −4 ≤ x ≤ 9. Following is MATLAB version of the code − f = x^2*cos(x); ezplot(f, [-4,9]) a = int(f, -4, 9) disp('Area: '), disp(double(a)); When you run the file, MATLAB plots the graph − The following result is displayed a = 8*cos(4) + 18*cos(9) + 14*sin(4) + 79*sin(9) Area: 0.3326 But to give area of the same curve in Octave, you will have to make use of symbolic package as follows − pkg load symbolic symbols x = sym("x"); f = inline("x^2*cos(x)"); ezplot(f, [-4,9]) print -deps graph.eps [a, ierror, nfneval] = quad(f, -4, 9); display('Area: '), disp(double(a)); 30 Lectures 4 hours Nouman Azam 127 Lectures 12 hours Nouman Azam 17 Lectures 3 hours Sanjeev 37 Lectures 5 hours TELCOMA Global 22 Lectures 4 hours TELCOMA Global 18 Lectures 3 hours Phinite Academy Print Add Notes Bookmark this page
[ { "code": null, "e": 2286, "s": 2141, "text": "GNU Octave is a high-level programming language like MATLAB and it is mostly compatible with MATLAB. It is also used for numerical computations." }, { "code": null, "e": 2341, "s": 2286, "text": "Octave has the following common features with MATLAB −" }, { "code": null, "e": 2376, "s": 2341, "text": "matrices are fundamental data type" }, { "code": null, "e": 2420, "s": 2376, "text": "it has built-in support for complex numbers" }, { "code": null, "e": 2465, "s": 2420, "text": "it has built-in math functions and libraries" }, { "code": null, "e": 2500, "s": 2465, "text": "it supports user-defined functions" }, { "code": null, "e": 2695, "s": 2500, "text": "GNU Octave is also freely redistributable software. You may redistribute it and/or modify it under the terms of the GNU General Public License (GPL) as published by the Free Software Foundation." }, { "code": null, "e": 2842, "s": 2695, "text": "Most MATLAB programs run in Octave, but some of the Octave programs may not run in MATLAB because, Octave allows some syntax that MATLAB does not." }, { "code": null, "e": 3105, "s": 2842, "text": "For example, MATLAB supports single quotes only, but Octave supports both single and double quotes for defining strings. If you are looking for a tutorial on Octave, then kindly go through this tutorial from beginning which covers both MATLAB as well as Octave." }, { "code": null, "e": 3305, "s": 3105, "text": "Almost all the examples covered in this tutorial are compatible with MATLAB as well as Octave. Let's try following example in MATLAB and Octave which produces same result without any syntax changes −" }, { "code": null, "e": 3429, "s": 3305, "text": "This example creates a 3D surface map for the function g = xe-(x2 + y2). Create a script file and type the following code −" }, { "code": null, "e": 3520, "s": 3429, "text": "[x,y] = meshgrid(-2:.2:2);\ng = x .* exp(-x.^2 - y.^2);\nsurf(x, y, g)\nprint -deps graph.eps" }, { "code": null, "e": 3583, "s": 3520, "text": "When you run the file, MATLAB displays the following 3-D map −" }, { "code": null, "e": 3873, "s": 3583, "text": "Though all the core functionality of MATLAB is available in Octave, there are some functionality for example, Differential & Integration Calculus, which does not match exactly in both the languages. This tutorial has tried to give both type of examples where they differed in their syntax." }, { "code": null, "e": 4059, "s": 3873, "text": "Consider following example where MATLAB and Octave make use of different functions to get the area of a curve: f(x) = x2 cos(x) for −4 ≤ x ≤ 9. Following is MATLAB version of the code −" }, { "code": null, "e": 4144, "s": 4059, "text": "f = x^2*cos(x);\nezplot(f, [-4,9])\na = int(f, -4, 9)\ndisp('Area: '), disp(double(a));" }, { "code": null, "e": 4192, "s": 4144, "text": "When you run the file, MATLAB plots the graph −" }, { "code": null, "e": 4226, "s": 4192, "text": "The following result is displayed" }, { "code": null, "e": 4295, "s": 4226, "text": "a =\n8*cos(4) + 18*cos(9) + 14*sin(4) + 79*sin(9)\n \nArea: \n 0.3326\n" }, { "code": null, "e": 4400, "s": 4295, "text": "But to give area of the same curve in Octave, you will have to make use of symbolic package as follows −" }, { "code": null, "e": 4584, "s": 4400, "text": "pkg load symbolic\nsymbols\n\nx = sym(\"x\");\nf = inline(\"x^2*cos(x)\");\n\nezplot(f, [-4,9])\nprint -deps graph.eps\n\n[a, ierror, nfneval] = quad(f, -4, 9);\ndisplay('Area: '), disp(double(a));" }, { "code": null, "e": 4617, "s": 4584, "text": "\n 30 Lectures \n 4 hours \n" }, { "code": null, "e": 4630, "s": 4617, "text": " Nouman Azam" }, { "code": null, "e": 4665, "s": 4630, "text": "\n 127 Lectures \n 12 hours \n" }, { "code": null, "e": 4678, "s": 4665, "text": " Nouman Azam" }, { "code": null, "e": 4711, "s": 4678, "text": "\n 17 Lectures \n 3 hours \n" }, { "code": null, "e": 4720, "s": 4711, "text": " Sanjeev" }, { "code": null, "e": 4753, "s": 4720, "text": "\n 37 Lectures \n 5 hours \n" }, { "code": null, "e": 4769, "s": 4753, "text": " TELCOMA Global" }, { "code": null, "e": 4802, "s": 4769, "text": "\n 22 Lectures \n 4 hours \n" }, { "code": null, "e": 4818, "s": 4802, "text": " TELCOMA Global" }, { "code": null, "e": 4851, "s": 4818, "text": "\n 18 Lectures \n 3 hours \n" }, { "code": null, "e": 4868, "s": 4851, "text": " Phinite Academy" }, { "code": null, "e": 4875, "s": 4868, "text": " Print" }, { "code": null, "e": 4886, "s": 4875, "text": " Add Notes" } ]
Bootstrap 5 Modal - GeeksforGeeks
11 Sep, 2020 Bootstrap 5 is the latest major release by Bootstrap in which they have revamped the UI and made various changes. Modals are used to add dialogs to your site for lightboxes, user notifications, or completely custom content. Modals are built with HTML, CSS, and JavaScript. They’re positioned over everything else in the document and remove scroll from the <body> so that modal content scrolls instead. Syntax: <div class="modal"> Contents... <div> Example: This example uses show the working of a modal in Bootstrap 5. <!DOCTYPE html><html> <head> <!-- Load Bootstrap --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css" integrity="sha384-r4NyP46KrjDleawBgD5tp8Y7UzmLA05oM1iAEQ17CSuDqnUK2+k9luXQOfXJCJ4I" crossorigin="anonymous" /> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/js/bootstrap.min.js" integrity="sha384-oesi62hOLfzrys4LxRF63OJCXdXDipiYWBnvTl9Y9/TRlw5xlKIEHpNyvvDShgf/" crossorigin="anonymous"></script> </head> <body style="text-align: center;"> <div class="container mt-3" style="width: 700px;"> <h1 style="color: green;"> GeeksforGeeks </h1> <!-- Button trigger modal --> <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal"> Launch demo modal </button> <!-- Modal --> <div class="modal fade" id="exampleModal"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title"> Modal title</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true"> ×</span> </button> </div> <div class="modal-body"> GeeksforGeeks </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal"> Close</button> <button type="button" class="btn btn-primary"> Save changes</button> </div> </div> </div> </div> </div> </body></html> Output before triggering the modal: Output after triggering the modal: Tooltips: can be added inside the modal. When modals are closed, tooltips within are also automatically dismissed.Example: <!DOCTYPE html><html> <head> <!-- Load Bootstrap --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css" integrity="sha384-r4NyP46KrjDleawBgD5tp8Y7UzmLA05oM1iAEQ17CSuDqnUK2+k9luXQOfXJCJ4I" crossorigin="anonymous" /> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/js/bootstrap.min.js" integrity="sha384-oesi62hOLfzrys4LxRF63OJCXdXDipiYWBnvTl9Y9/TRlw5xlKIEHpNyvvDShgf/" crossorigin="anonymous"></script> </head> <body style="text-align: center;"> <div class="container mt-3" style="width: 700px;"> <h1 style="color: green;"> GeeksforGeeks </h1> <!-- Button trigger modal --> <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal"> Launch demo modal </button> <!-- Modal --> <div class="modal fade" id="exampleModal"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title">Modal title</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true"> ×</span> </button> </div> <div class="modal-body"> <h5>Tooltips in a modal</h5> <a href="#" data-toggle="tooltip" title="GeeksforGeeks" data-placement="right"> Hover over me</a> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal"> Close</button> <button type="button" class="btn btn-primary"> Save changes </button> </div> </div> </div> </div> </div> <script> // Enable tooltips var tooltipTriggerList = [].slice.call( document.querySelectorAll('[data-toggle="tooltip"]')); var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) { return new bootstrap.Tooltip(tooltipTriggerEl); }); </script> </body></html> Output: Popovers: can be added inside the modal. When modals are closed, popovers within are also automatically dismissed.Example: <!DOCTYPE html><html> <head> <!-- Load Bootstrap --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css" integrity="sha384-r4NyP46KrjDleawBgD5tp8Y7UzmLA05oM1iAEQ17CSuDqnUK2+k9luXQOfXJCJ4I" crossorigin="anonymous" /> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/js/bootstrap.min.js" integrity="sha384-oesi62hOLfzrys4LxRF63OJCXdXDipiYWBnvTl9Y9/TRlw5xlKIEHpNyvvDShgf/" crossorigin="anonymous"></script> </head> <body style="text-align: center;"> <div class="container mt-3" style="width: 700px;"> <h1 style="color: green;"> GeeksforGeeks </h1> <!-- Button trigger modal --> <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal"> Launch demo modal </button> <!-- Modal --> <div class="modal fade" id="exampleModal"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title"> Modal title</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true"> ×</span> </button> </div> <div class="modal-body"> <h5>Popover in a modal</h5> <a href="#" data-toggle="popover" title="This is GeeksforGeeks" data-content= "Portal for CS Geeks"> Toggle popover</a> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal"> Close</button> <button type="button" class="btn btn-primary"> Save changes</button> </div> </div> </div> </div> </div> <script> // Enable popovers var popoverTriggerList = [].slice.call( document.querySelectorAll('[data-toggle="popover"]')); var popoverList = popoverTriggerList.map(function (popoverTriggerEl) { return new bootstrap.Popover(popoverTriggerEl); }); </script> </body></html> Output: Using Grids: We can utilize the Bootstrap grid system within a modal by nesting .container-fluid within the .modal-body. Then, use the normal grid system classes as you would anywhere else.Example: <!DOCTYPE html><html> <head> <!-- Load Bootstrap --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css" integrity="sha384-r4NyP46KrjDleawBgD5tp8Y7UzmLA05oM1iAEQ17CSuDqnUK2+k9luXQOfXJCJ4I" crossorigin="anonymous" /> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/js/bootstrap.min.js" integrity="sha384-oesi62hOLfzrys4LxRF63OJCXdXDipiYWBnvTl9Y9/TRlw5xlKIEHpNyvvDShgf/" crossorigin="anonymous"></script> </head> <body style="text-align: center;"> <div class="container mt-3" style="width: 700px;"> <h1 style="color: green;"> GeeksforGeeks </h1> <!-- Button trigger modal --> <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal"> Launch demo modal </button> <!-- Modal --> <div class="modal fade" id="exampleModal"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title">Modal title</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true"> ×</span> </button> </div> <div class="modal-body"> <div class="container-fluid"> <div class="row"> <div class="col-md-4" style="background: red; color: white;"> This is 4 grids</div> <div class="col-md-8" style="background: green; color: white;"> This is 8 grids</div> </div> <div class="row"> <div class="col-md-12" style="background: blue; color: white;"> This is 12 grids</div> </div> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal"> Close</button> <button type="button" class="btn btn-primary"> Save changes</button> </div> </div> </div> </div> </div> </body></html> Output: Varying modal content: We can trigger the same modal with different data as given below.Example: <!DOCTYPE html><html> <head> <!-- Load Bootstrap --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css" integrity="sha384-r4NyP46KrjDleawBgD5tp8Y7UzmLA05oM1iAEQ17CSuDqnUK2+k9luXQOfXJCJ4I" crossorigin="anonymous" /> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/js/bootstrap.min.js" integrity="sha384-oesi62hOLfzrys4LxRF63OJCXdXDipiYWBnvTl9Y9/TRlw5xlKIEHpNyvvDShgf/" crossorigin="anonymous"></script> </head> <body style="text-align: center;"> <div class="container mt-3" style="width: 700px;"> <h1 style="color: green;"> GeeksforGeeks </h1> <!-- Button trigger modal --> <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal" data-whatever="@geeksforgeeks"> Send email to @geeksforgeeks</button> <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal" data-whatever="@gurrrung"> Send email to author @gurrrung</button> <!-- Modal --> <div class="modal fade" id="exampleModal"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title"> New message</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true"> ×</span> </button> </div> <div class="modal-body"> <form> <div class="mb-3"> <label for="recipient-name" class="col-form-label"> Recipient:</label> <input type="text" class="form-control" id="recipient-name" /> </div> <div class="mb-3"> <label for="message-text" class="col-form-label"> Message:</label> <textarea class="form-control" id="message-text"> </textarea> </div> </form> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal"> Close</button> <button type="button" class="btn btn-primary"> Send message</button> </div> </div> </div> </div> </div> <script> var exampleModal = document.getElementById("exampleModal"); exampleModal.addEventListener( "show.bs.modal", function (event) { // Button that triggered the modal var button = event.relatedTarget; // Extract info from data-* attributes var recipient = button.getAttribute("data-whatever"); // Update the modal's content. var modalTitle = exampleModal.querySelector(".modal-title"); var modalBodyInput = exampleModal.querySelector(".modal-body input"); modalTitle.textContent = "New message to " + recipient; modalBodyInput.value = recipient; }); </script> </body></html> Output without triggering any modal:Output for clicking on Send email to @geeksforgeeks:Output for clicking on Send email to author @gurrrung: Optional sizes Default max-width of a Bootstrap modal is 500px. Bootstrap provides the option to customize the size of the Modal by using certain classes as described below: modal-xl modal-lg modal-sm modal-xl: This provides the largest modal size with max-width of 1140px.Example: <!DOCTYPE html><html> <head> <!-- Load Bootstrap --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css" integrity="sha384-r4NyP46KrjDleawBgD5tp8Y7UzmLA05oM1iAEQ17CSuDqnUK2+k9luXQOfXJCJ4I" crossorigin="anonymous" /> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/js/bootstrap.min.js" integrity="sha384-oesi62hOLfzrys4LxRF63OJCXdXDipiYWBnvTl9Y9/TRlw5xlKIEHpNyvvDShgf/" crossorigin="anonymous"></script> </head> <body style="text-align: center;"> <div class="container mt-3" style="width: 700px;"> <h1 style="color: green;"> GeeksforGeeks </h1> <!-- Button trigger modal --> <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal"> Launch demo modal </button> <!-- Modal --> <div class="modal fade" id="exampleModal"> <div class="modal-dialog modal-xl"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title"> Modal title</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true"> ×</span> </button> </div> <div class="modal-body"> GeeksforGeeks </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal"> Close</button> <button type="button" class="btn btn-primary"> Save changes</button> </div> </div> </div> </div> </div> </body></html> Output: modal-lg: This provides the large modal size with max-width of 800px.Example: <!DOCTYPE html><html> <head> <!-- Load Bootstrap --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css" integrity="sha384-r4NyP46KrjDleawBgD5tp8Y7UzmLA05oM1iAEQ17CSuDqnUK2+k9luXQOfXJCJ4I" crossorigin="anonymous" /> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/js/bootstrap.min.js" integrity="sha384-oesi62hOLfzrys4LxRF63OJCXdXDipiYWBnvTl9Y9/TRlw5xlKIEHpNyvvDShgf/" crossorigin="anonymous"></script> </head> <body style="text-align: center;"> <div class="container mt-3" style="width: 700px;"> <h1 style="color: green;"> GeeksforGeeks </h1> <!-- Button trigger modal --> <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal"> Launch demo modal </button> <!-- Modal --> <div class="modal fade" id="exampleModal"> <div class="modal-dialog modal-lg"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title"> Modal title</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true"> ×</span> </button> </div> <div class="modal-body"> GeeksforGeeks </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal"> Close</button> <button type="button" class="btn btn-primary"> Save changes</button> </div> </div> </div> </div> </div> </body></html> Output: modal-sm: This provides the largest modal size with max-width of 300px.Example: <!DOCTYPE html><html> <head> <!-- Load Bootstrap --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css" integrity="sha384-r4NyP46KrjDleawBgD5tp8Y7UzmLA05oM1iAEQ17CSuDqnUK2+k9luXQOfXJCJ4I" crossorigin="anonymous" /> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/js/bootstrap.min.js" integrity="sha384-oesi62hOLfzrys4LxRF63OJCXdXDipiYWBnvTl9Y9/TRlw5xlKIEHpNyvvDShgf/" crossorigin="anonymous"></script> </head> <body style="text-align: center;"> <div class="container mt-3" style="width: 700px;"> <h1 style="color: green;"> GeeksforGeeks </h1> <!-- Button trigger modal --> <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal"> Launch demo modal </button> <!-- Modal --> <div class="modal fade" id="exampleModal"> <div class="modal-dialog modal-sm"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title"> Modal title</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true"> ×</span> </button> </div> <div class="modal-body"> GeeksforGeeks </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal"> Close</button> <button type="button" class="btn btn-primary"> Save changes</button> </div> </div> </div> </div> </div> </body></html> Output: Bootstrap-Misc Bootstrap Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to change navigation bar color in Bootstrap ? Form validation using jQuery How to align navbar items to the right in Bootstrap 4 ? How to pass data into a bootstrap modal? How to Show Images on Click using HTML ? Top 10 Front End Developer Skills That You Need in 2022 Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 28049, "s": 28021, "text": "\n11 Sep, 2020" }, { "code": null, "e": 28451, "s": 28049, "text": "Bootstrap 5 is the latest major release by Bootstrap in which they have revamped the UI and made various changes. Modals are used to add dialogs to your site for lightboxes, user notifications, or completely custom content. Modals are built with HTML, CSS, and JavaScript. They’re positioned over everything else in the document and remove scroll from the <body> so that modal content scrolls instead." }, { "code": null, "e": 28459, "s": 28451, "text": "Syntax:" }, { "code": null, "e": 28497, "s": 28459, "text": "<div class=\"modal\"> Contents... <div>" }, { "code": null, "e": 28568, "s": 28497, "text": "Example: This example uses show the working of a modal in Bootstrap 5." }, { "code": "<!DOCTYPE html><html> <head> <!-- Load Bootstrap --> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css\" integrity=\"sha384-r4NyP46KrjDleawBgD5tp8Y7UzmLA05oM1iAEQ17CSuDqnUK2+k9luXQOfXJCJ4I\" crossorigin=\"anonymous\" /> <script src=\"https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js\" integrity=\"sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo\" crossorigin=\"anonymous\"></script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/js/bootstrap.min.js\" integrity=\"sha384-oesi62hOLfzrys4LxRF63OJCXdXDipiYWBnvTl9Y9/TRlw5xlKIEHpNyvvDShgf/\" crossorigin=\"anonymous\"></script> </head> <body style=\"text-align: center;\"> <div class=\"container mt-3\" style=\"width: 700px;\"> <h1 style=\"color: green;\"> GeeksforGeeks </h1> <!-- Button trigger modal --> <button type=\"button\" class=\"btn btn-primary\" data-toggle=\"modal\" data-target=\"#exampleModal\"> Launch demo modal </button> <!-- Modal --> <div class=\"modal fade\" id=\"exampleModal\"> <div class=\"modal-dialog\"> <div class=\"modal-content\"> <div class=\"modal-header\"> <h5 class=\"modal-title\"> Modal title</h5> <button type=\"button\" class=\"close\" data-dismiss=\"modal\" aria-label=\"Close\"> <span aria-hidden=\"true\"> ×</span> </button> </div> <div class=\"modal-body\"> GeeksforGeeks </div> <div class=\"modal-footer\"> <button type=\"button\" class=\"btn btn-secondary\" data-dismiss=\"modal\"> Close</button> <button type=\"button\" class=\"btn btn-primary\"> Save changes</button> </div> </div> </div> </div> </div> </body></html>", "e": 31235, "s": 28568, "text": null }, { "code": null, "e": 31271, "s": 31235, "text": "Output before triggering the modal:" }, { "code": null, "e": 31306, "s": 31271, "text": "Output after triggering the modal:" }, { "code": null, "e": 31429, "s": 31306, "text": "Tooltips: can be added inside the modal. When modals are closed, tooltips within are also automatically dismissed.Example:" }, { "code": "<!DOCTYPE html><html> <head> <!-- Load Bootstrap --> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css\" integrity=\"sha384-r4NyP46KrjDleawBgD5tp8Y7UzmLA05oM1iAEQ17CSuDqnUK2+k9luXQOfXJCJ4I\" crossorigin=\"anonymous\" /> <script src=\"https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js\" integrity=\"sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo\" crossorigin=\"anonymous\"></script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/js/bootstrap.min.js\" integrity=\"sha384-oesi62hOLfzrys4LxRF63OJCXdXDipiYWBnvTl9Y9/TRlw5xlKIEHpNyvvDShgf/\" crossorigin=\"anonymous\"></script> </head> <body style=\"text-align: center;\"> <div class=\"container mt-3\" style=\"width: 700px;\"> <h1 style=\"color: green;\"> GeeksforGeeks </h1> <!-- Button trigger modal --> <button type=\"button\" class=\"btn btn-primary\" data-toggle=\"modal\" data-target=\"#exampleModal\"> Launch demo modal </button> <!-- Modal --> <div class=\"modal fade\" id=\"exampleModal\"> <div class=\"modal-dialog\"> <div class=\"modal-content\"> <div class=\"modal-header\"> <h5 class=\"modal-title\">Modal title</h5> <button type=\"button\" class=\"close\" data-dismiss=\"modal\" aria-label=\"Close\"> <span aria-hidden=\"true\"> ×</span> </button> </div> <div class=\"modal-body\"> <h5>Tooltips in a modal</h5> <a href=\"#\" data-toggle=\"tooltip\" title=\"GeeksforGeeks\" data-placement=\"right\"> Hover over me</a> </div> <div class=\"modal-footer\"> <button type=\"button\" class=\"btn btn-secondary\" data-dismiss=\"modal\"> Close</button> <button type=\"button\" class=\"btn btn-primary\"> Save changes </button> </div> </div> </div> </div> </div> <script> // Enable tooltips var tooltipTriggerList = [].slice.call( document.querySelectorAll('[data-toggle=\"tooltip\"]')); var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) { return new bootstrap.Tooltip(tooltipTriggerEl); }); </script> </body></html>", "e": 34693, "s": 31429, "text": null }, { "code": null, "e": 34701, "s": 34693, "text": "Output:" }, { "code": null, "e": 34824, "s": 34701, "text": "Popovers: can be added inside the modal. When modals are closed, popovers within are also automatically dismissed.Example:" }, { "code": "<!DOCTYPE html><html> <head> <!-- Load Bootstrap --> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css\" integrity=\"sha384-r4NyP46KrjDleawBgD5tp8Y7UzmLA05oM1iAEQ17CSuDqnUK2+k9luXQOfXJCJ4I\" crossorigin=\"anonymous\" /> <script src=\"https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js\" integrity=\"sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo\" crossorigin=\"anonymous\"></script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/js/bootstrap.min.js\" integrity=\"sha384-oesi62hOLfzrys4LxRF63OJCXdXDipiYWBnvTl9Y9/TRlw5xlKIEHpNyvvDShgf/\" crossorigin=\"anonymous\"></script> </head> <body style=\"text-align: center;\"> <div class=\"container mt-3\" style=\"width: 700px;\"> <h1 style=\"color: green;\"> GeeksforGeeks </h1> <!-- Button trigger modal --> <button type=\"button\" class=\"btn btn-primary\" data-toggle=\"modal\" data-target=\"#exampleModal\"> Launch demo modal </button> <!-- Modal --> <div class=\"modal fade\" id=\"exampleModal\"> <div class=\"modal-dialog\"> <div class=\"modal-content\"> <div class=\"modal-header\"> <h5 class=\"modal-title\"> Modal title</h5> <button type=\"button\" class=\"close\" data-dismiss=\"modal\" aria-label=\"Close\"> <span aria-hidden=\"true\"> ×</span> </button> </div> <div class=\"modal-body\"> <h5>Popover in a modal</h5> <a href=\"#\" data-toggle=\"popover\" title=\"This is GeeksforGeeks\" data-content= \"Portal for CS Geeks\"> Toggle popover</a> </div> <div class=\"modal-footer\"> <button type=\"button\" class=\"btn btn-secondary\" data-dismiss=\"modal\"> Close</button> <button type=\"button\" class=\"btn btn-primary\"> Save changes</button> </div> </div> </div> </div> </div> <script> // Enable popovers var popoverTriggerList = [].slice.call( document.querySelectorAll('[data-toggle=\"popover\"]')); var popoverList = popoverTriggerList.map(function (popoverTriggerEl) { return new bootstrap.Popover(popoverTriggerEl); }); </script> </body></html>", "e": 38164, "s": 34824, "text": null }, { "code": null, "e": 38172, "s": 38164, "text": "Output:" }, { "code": null, "e": 38370, "s": 38172, "text": "Using Grids: We can utilize the Bootstrap grid system within a modal by nesting .container-fluid within the .modal-body. Then, use the normal grid system classes as you would anywhere else.Example:" }, { "code": "<!DOCTYPE html><html> <head> <!-- Load Bootstrap --> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css\" integrity=\"sha384-r4NyP46KrjDleawBgD5tp8Y7UzmLA05oM1iAEQ17CSuDqnUK2+k9luXQOfXJCJ4I\" crossorigin=\"anonymous\" /> <script src=\"https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js\" integrity=\"sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo\" crossorigin=\"anonymous\"></script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/js/bootstrap.min.js\" integrity=\"sha384-oesi62hOLfzrys4LxRF63OJCXdXDipiYWBnvTl9Y9/TRlw5xlKIEHpNyvvDShgf/\" crossorigin=\"anonymous\"></script> </head> <body style=\"text-align: center;\"> <div class=\"container mt-3\" style=\"width: 700px;\"> <h1 style=\"color: green;\"> GeeksforGeeks </h1> <!-- Button trigger modal --> <button type=\"button\" class=\"btn btn-primary\" data-toggle=\"modal\" data-target=\"#exampleModal\"> Launch demo modal </button> <!-- Modal --> <div class=\"modal fade\" id=\"exampleModal\"> <div class=\"modal-dialog\"> <div class=\"modal-content\"> <div class=\"modal-header\"> <h5 class=\"modal-title\">Modal title</h5> <button type=\"button\" class=\"close\" data-dismiss=\"modal\" aria-label=\"Close\"> <span aria-hidden=\"true\"> ×</span> </button> </div> <div class=\"modal-body\"> <div class=\"container-fluid\"> <div class=\"row\"> <div class=\"col-md-4\" style=\"background: red; color: white;\"> This is 4 grids</div> <div class=\"col-md-8\" style=\"background: green; color: white;\"> This is 8 grids</div> </div> <div class=\"row\"> <div class=\"col-md-12\" style=\"background: blue; color: white;\"> This is 12 grids</div> </div> </div> </div> <div class=\"modal-footer\"> <button type=\"button\" class=\"btn btn-secondary\" data-dismiss=\"modal\"> Close</button> <button type=\"button\" class=\"btn btn-primary\"> Save changes</button> </div> </div> </div> </div> </div> </body></html>", "e": 41974, "s": 38370, "text": null }, { "code": null, "e": 41982, "s": 41974, "text": "Output:" }, { "code": null, "e": 42079, "s": 41982, "text": "Varying modal content: We can trigger the same modal with different data as given below.Example:" }, { "code": "<!DOCTYPE html><html> <head> <!-- Load Bootstrap --> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css\" integrity=\"sha384-r4NyP46KrjDleawBgD5tp8Y7UzmLA05oM1iAEQ17CSuDqnUK2+k9luXQOfXJCJ4I\" crossorigin=\"anonymous\" /> <script src=\"https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js\" integrity=\"sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo\" crossorigin=\"anonymous\"></script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/js/bootstrap.min.js\" integrity=\"sha384-oesi62hOLfzrys4LxRF63OJCXdXDipiYWBnvTl9Y9/TRlw5xlKIEHpNyvvDShgf/\" crossorigin=\"anonymous\"></script> </head> <body style=\"text-align: center;\"> <div class=\"container mt-3\" style=\"width: 700px;\"> <h1 style=\"color: green;\"> GeeksforGeeks </h1> <!-- Button trigger modal --> <button type=\"button\" class=\"btn btn-primary\" data-toggle=\"modal\" data-target=\"#exampleModal\" data-whatever=\"@geeksforgeeks\"> Send email to @geeksforgeeks</button> <button type=\"button\" class=\"btn btn-primary\" data-toggle=\"modal\" data-target=\"#exampleModal\" data-whatever=\"@gurrrung\"> Send email to author @gurrrung</button> <!-- Modal --> <div class=\"modal fade\" id=\"exampleModal\"> <div class=\"modal-dialog\"> <div class=\"modal-content\"> <div class=\"modal-header\"> <h5 class=\"modal-title\"> New message</h5> <button type=\"button\" class=\"close\" data-dismiss=\"modal\" aria-label=\"Close\"> <span aria-hidden=\"true\"> ×</span> </button> </div> <div class=\"modal-body\"> <form> <div class=\"mb-3\"> <label for=\"recipient-name\" class=\"col-form-label\"> Recipient:</label> <input type=\"text\" class=\"form-control\" id=\"recipient-name\" /> </div> <div class=\"mb-3\"> <label for=\"message-text\" class=\"col-form-label\"> Message:</label> <textarea class=\"form-control\" id=\"message-text\"> </textarea> </div> </form> </div> <div class=\"modal-footer\"> <button type=\"button\" class=\"btn btn-secondary\" data-dismiss=\"modal\"> Close</button> <button type=\"button\" class=\"btn btn-primary\"> Send message</button> </div> </div> </div> </div> </div> <script> var exampleModal = document.getElementById(\"exampleModal\"); exampleModal.addEventListener( \"show.bs.modal\", function (event) { // Button that triggered the modal var button = event.relatedTarget; // Extract info from data-* attributes var recipient = button.getAttribute(\"data-whatever\"); // Update the modal's content. var modalTitle = exampleModal.querySelector(\".modal-title\"); var modalBodyInput = exampleModal.querySelector(\".modal-body input\"); modalTitle.textContent = \"New message to \" + recipient; modalBodyInput.value = recipient; }); </script> </body></html>", "e": 46839, "s": 42079, "text": null }, { "code": null, "e": 46982, "s": 46839, "text": "Output without triggering any modal:Output for clicking on Send email to @geeksforgeeks:Output for clicking on Send email to author @gurrrung:" }, { "code": null, "e": 47156, "s": 46982, "text": "Optional sizes Default max-width of a Bootstrap modal is 500px. Bootstrap provides the option to customize the size of the Modal by using certain classes as described below:" }, { "code": null, "e": 47165, "s": 47156, "text": "modal-xl" }, { "code": null, "e": 47174, "s": 47165, "text": "modal-lg" }, { "code": null, "e": 47183, "s": 47174, "text": "modal-sm" }, { "code": null, "e": 47264, "s": 47183, "text": "modal-xl: This provides the largest modal size with max-width of 1140px.Example:" }, { "code": "<!DOCTYPE html><html> <head> <!-- Load Bootstrap --> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css\" integrity=\"sha384-r4NyP46KrjDleawBgD5tp8Y7UzmLA05oM1iAEQ17CSuDqnUK2+k9luXQOfXJCJ4I\" crossorigin=\"anonymous\" /> <script src=\"https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js\" integrity=\"sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo\" crossorigin=\"anonymous\"></script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/js/bootstrap.min.js\" integrity=\"sha384-oesi62hOLfzrys4LxRF63OJCXdXDipiYWBnvTl9Y9/TRlw5xlKIEHpNyvvDShgf/\" crossorigin=\"anonymous\"></script> </head> <body style=\"text-align: center;\"> <div class=\"container mt-3\" style=\"width: 700px;\"> <h1 style=\"color: green;\"> GeeksforGeeks </h1> <!-- Button trigger modal --> <button type=\"button\" class=\"btn btn-primary\" data-toggle=\"modal\" data-target=\"#exampleModal\"> Launch demo modal </button> <!-- Modal --> <div class=\"modal fade\" id=\"exampleModal\"> <div class=\"modal-dialog modal-xl\"> <div class=\"modal-content\"> <div class=\"modal-header\"> <h5 class=\"modal-title\"> Modal title</h5> <button type=\"button\" class=\"close\" data-dismiss=\"modal\" aria-label=\"Close\"> <span aria-hidden=\"true\"> ×</span> </button> </div> <div class=\"modal-body\"> GeeksforGeeks </div> <div class=\"modal-footer\"> <button type=\"button\" class=\"btn btn-secondary\" data-dismiss=\"modal\"> Close</button> <button type=\"button\" class=\"btn btn-primary\"> Save changes</button> </div> </div> </div> </div> </div> </body></html>", "e": 49943, "s": 47264, "text": null }, { "code": null, "e": 49951, "s": 49943, "text": "Output:" }, { "code": null, "e": 50029, "s": 49951, "text": "modal-lg: This provides the large modal size with max-width of 800px.Example:" }, { "code": "<!DOCTYPE html><html> <head> <!-- Load Bootstrap --> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css\" integrity=\"sha384-r4NyP46KrjDleawBgD5tp8Y7UzmLA05oM1iAEQ17CSuDqnUK2+k9luXQOfXJCJ4I\" crossorigin=\"anonymous\" /> <script src=\"https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js\" integrity=\"sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo\" crossorigin=\"anonymous\"></script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/js/bootstrap.min.js\" integrity=\"sha384-oesi62hOLfzrys4LxRF63OJCXdXDipiYWBnvTl9Y9/TRlw5xlKIEHpNyvvDShgf/\" crossorigin=\"anonymous\"></script> </head> <body style=\"text-align: center;\"> <div class=\"container mt-3\" style=\"width: 700px;\"> <h1 style=\"color: green;\"> GeeksforGeeks </h1> <!-- Button trigger modal --> <button type=\"button\" class=\"btn btn-primary\" data-toggle=\"modal\" data-target=\"#exampleModal\"> Launch demo modal </button> <!-- Modal --> <div class=\"modal fade\" id=\"exampleModal\"> <div class=\"modal-dialog modal-lg\"> <div class=\"modal-content\"> <div class=\"modal-header\"> <h5 class=\"modal-title\"> Modal title</h5> <button type=\"button\" class=\"close\" data-dismiss=\"modal\" aria-label=\"Close\"> <span aria-hidden=\"true\"> ×</span> </button> </div> <div class=\"modal-body\"> GeeksforGeeks </div> <div class=\"modal-footer\"> <button type=\"button\" class=\"btn btn-secondary\" data-dismiss=\"modal\"> Close</button> <button type=\"button\" class=\"btn btn-primary\"> Save changes</button> </div> </div> </div> </div> </div> </body></html>", "e": 52704, "s": 50029, "text": null }, { "code": null, "e": 52712, "s": 52704, "text": "Output:" }, { "code": null, "e": 52792, "s": 52712, "text": "modal-sm: This provides the largest modal size with max-width of 300px.Example:" }, { "code": "<!DOCTYPE html><html> <head> <!-- Load Bootstrap --> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css\" integrity=\"sha384-r4NyP46KrjDleawBgD5tp8Y7UzmLA05oM1iAEQ17CSuDqnUK2+k9luXQOfXJCJ4I\" crossorigin=\"anonymous\" /> <script src=\"https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js\" integrity=\"sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo\" crossorigin=\"anonymous\"></script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/js/bootstrap.min.js\" integrity=\"sha384-oesi62hOLfzrys4LxRF63OJCXdXDipiYWBnvTl9Y9/TRlw5xlKIEHpNyvvDShgf/\" crossorigin=\"anonymous\"></script> </head> <body style=\"text-align: center;\"> <div class=\"container mt-3\" style=\"width: 700px;\"> <h1 style=\"color: green;\"> GeeksforGeeks </h1> <!-- Button trigger modal --> <button type=\"button\" class=\"btn btn-primary\" data-toggle=\"modal\" data-target=\"#exampleModal\"> Launch demo modal </button> <!-- Modal --> <div class=\"modal fade\" id=\"exampleModal\"> <div class=\"modal-dialog modal-sm\"> <div class=\"modal-content\"> <div class=\"modal-header\"> <h5 class=\"modal-title\"> Modal title</h5> <button type=\"button\" class=\"close\" data-dismiss=\"modal\" aria-label=\"Close\"> <span aria-hidden=\"true\"> ×</span> </button> </div> <div class=\"modal-body\"> GeeksforGeeks </div> <div class=\"modal-footer\"> <button type=\"button\" class=\"btn btn-secondary\" data-dismiss=\"modal\"> Close</button> <button type=\"button\" class=\"btn btn-primary\"> Save changes</button> </div> </div> </div> </div> </div> </body></html>", "e": 55470, "s": 52792, "text": null }, { "code": null, "e": 55478, "s": 55470, "text": "Output:" }, { "code": null, "e": 55493, "s": 55478, "text": "Bootstrap-Misc" }, { "code": null, "e": 55503, "s": 55493, "text": "Bootstrap" }, { "code": null, "e": 55520, "s": 55503, "text": "Web Technologies" }, { "code": null, "e": 55618, "s": 55520, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 55627, "s": 55618, "text": "Comments" }, { "code": null, "e": 55640, "s": 55627, "text": "Old Comments" }, { "code": null, "e": 55690, "s": 55640, "text": "How to change navigation bar color in Bootstrap ?" }, { "code": null, "e": 55719, "s": 55690, "text": "Form validation using jQuery" }, { "code": null, "e": 55775, "s": 55719, "text": "How to align navbar items to the right in Bootstrap 4 ?" }, { "code": null, "e": 55816, "s": 55775, "text": "How to pass data into a bootstrap modal?" }, { "code": null, "e": 55857, "s": 55816, "text": "How to Show Images on Click using HTML ?" }, { "code": null, "e": 55913, "s": 55857, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 55946, "s": 55913, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 56008, "s": 55946, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 56051, "s": 56008, "text": "How to fetch data from an API in ReactJS ?" } ]
HTML canvas strokeRect() Method
The strokeRect() method of the HTML canvas is used to create a rectangle on a web page. The <canvas> element allows you to draw graphics on a web page using JavaScript. Every canvas has two elements that describes the height and width of the canvas i.e. height and width respectively. Following is the syntax − context.strokeRect(p,q,width,height); Above, p − The x-coordinate of the upper-left corner of the rectangle q − The y-coordinate of the upper-left corner of the rectangle width − Width of the rectangle height − Height of the rectangle Let us now see an example to implement the strokeStyle property of canvas − Live Demo <!DOCTYPE html> <html> <body> <canvas id="newCanvas" width="550" height="400" style="border −2px solid orange;"></canvas> <script> var c = document.getElementById("newCanvas"); var ctx = c.getContext("2d"); ctx.strokeRect(120, 120, 220, 120); </script> </body> </html>
[ { "code": null, "e": 1347, "s": 1062, "text": "The strokeRect() method of the HTML canvas is used to create a rectangle on a web page. The <canvas> element allows you to draw graphics on a web page using JavaScript. Every canvas has two elements that describes the height and width of the canvas i.e. height and width respectively." }, { "code": null, "e": 1373, "s": 1347, "text": "Following is the syntax −" }, { "code": null, "e": 1411, "s": 1373, "text": "context.strokeRect(p,q,width,height);" }, { "code": null, "e": 1418, "s": 1411, "text": "Above," }, { "code": null, "e": 1481, "s": 1418, "text": "p − The x-coordinate of the upper-left corner of the rectangle" }, { "code": null, "e": 1544, "s": 1481, "text": "q − The y-coordinate of the upper-left corner of the rectangle" }, { "code": null, "e": 1575, "s": 1544, "text": "width − Width of the rectangle" }, { "code": null, "e": 1608, "s": 1575, "text": "height − Height of the rectangle" }, { "code": null, "e": 1684, "s": 1608, "text": "Let us now see an example to implement the strokeStyle property of canvas −" }, { "code": null, "e": 1695, "s": 1684, "text": " Live Demo" }, { "code": null, "e": 1973, "s": 1695, "text": "<!DOCTYPE html>\n<html>\n<body>\n<canvas id=\"newCanvas\" width=\"550\" height=\"400\" style=\"border −2px solid orange;\"></canvas>\n<script>\n var c = document.getElementById(\"newCanvas\");\n var ctx = c.getContext(\"2d\");\n ctx.strokeRect(120, 120, 220, 120);\n</script>\n</body>\n</html>" } ]
How to start service using Alarm Manager in android?
This example demonstrates how do I start a service using alarm manager in android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/activity_main" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="16sp" android:orientation="vertical" android:gravity="center_horizontal"> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/btnStartService" android:text="Start Service Alarm" android:layout_marginTop="30dp"/> <Button android:id="@+id/btnStopService" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:text="Cancel Service"/> </LinearLayout> Step 3 − Add the following code to src/MainActivity.java package app.com.sample; import android.app.AlarmManager; import android.app.PendingIntent; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.Toast; import java.util.Calendar; public class MainActivity extends AppCompatActivity { Button btnStart, btnStop; PendingIntent pendingIntent; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btnStart = findViewById(R.id.btnStartService); btnStop = findViewById(R.id.btnStopService); btnStart.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent myIntent = new Intent(MainActivity.this, MyAlarmService.class); pendingIntent = PendingIntent.getService(MainActivity.this, 0, myIntent, 0); AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE); Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(System.currentTimeMillis()); calendar.add(Calendar.SECOND, 3); assert alarmManager != null; alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent); Toast.makeText(MainActivity.this, "Starting Service Alarm", Toast.LENGTH_LONG).show(); }}); btnStop.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE); assert alarmManager != null; alarmManager.cancel(pendingIntent); Toast.makeText(MainActivity.this, "Service Cancelled", Toast.LENGTH_LONG).show(); } }); } } Step 4 – Create a java class (MyAlarmService.java) and add the following code? import android.app.Service; import android.content.Intent; import android.os.IBinder; import android.support.annotation.Nullable; import android.widget.Toast; public class MyAlarmService extends Service { @Override public void onCreate() { Toast.makeText(this, "MyAlarmService.onCreate()", Toast.LENGTH_LONG).show(); } @Nullable @Override public IBinder onBind(Intent intent) { Toast.makeText(this, "MyAlarmService.onBind()", Toast.LENGTH_LONG).show(); return null; } @Override public void onDestroy() { super.onDestroy(); Toast.makeText(this, "MyAlarmService.onDestroy()", Toast.LENGTH_LONG).show(); } @Override public void onStart(Intent intent, int startId) { super.onStart(intent, startId); Toast.makeText(this, "MyAlarmService.onStart()", Toast.LENGTH_LONG).show(); } @Override public boolean onUnbind(Intent intent) { Toast.makeText(this, "MyAlarmService.onUnbind()", Toast.LENGTH_LONG).show(); return super.onUnbind(intent); } } Step 5 − Add the following code to androidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <service android:name=".MyAlarmService" /> </application> </manifest> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen – Click here to download the project code.
[ { "code": null, "e": 1145, "s": 1062, "text": "This example demonstrates how do I start a service using alarm manager in android." }, { "code": null, "e": 1274, "s": 1145, "text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project." }, { "code": null, "e": 1339, "s": 1274, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2109, "s": 1339, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n android:id=\"@+id/activity_main\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:padding=\"16sp\"\n android:orientation=\"vertical\"\n android:gravity=\"center_horizontal\">\n <Button\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:id=\"@+id/btnStartService\"\n android:text=\"Start Service Alarm\"\n android:layout_marginTop=\"30dp\"/>\n <Button\n android:id=\"@+id/btnStopService\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:layout_marginTop=\"10dp\"\n android:text=\"Cancel Service\"/>\n</LinearLayout>" }, { "code": null, "e": 2166, "s": 2109, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 4033, "s": 2166, "text": "package app.com.sample;\nimport android.app.AlarmManager;\nimport android.app.PendingIntent;\nimport android.content.Intent;\nimport android.support.v7.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.view.View;\nimport android.widget.Button;\nimport android.widget.Toast;\nimport java.util.Calendar;\npublic class MainActivity extends AppCompatActivity {\n Button btnStart, btnStop;\n PendingIntent pendingIntent;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n btnStart = findViewById(R.id.btnStartService);\n btnStop = findViewById(R.id.btnStopService);\n btnStart.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n Intent myIntent = new Intent(MainActivity.this, MyAlarmService.class);\n pendingIntent = PendingIntent.getService(MainActivity.this, 0, myIntent, 0);\n AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);\n Calendar calendar = Calendar.getInstance();\n calendar.setTimeInMillis(System.currentTimeMillis());\n calendar.add(Calendar.SECOND, 3);\n assert alarmManager != null;\n alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);\n Toast.makeText(MainActivity.this, \"Starting Service Alarm\", Toast.LENGTH_LONG).show();\n }});\n btnStop.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);\n assert alarmManager != null;\n alarmManager.cancel(pendingIntent);\n Toast.makeText(MainActivity.this, \"Service Cancelled\", Toast.LENGTH_LONG).show();\n }\n });\n }\n}" }, { "code": null, "e": 4112, "s": 4033, "text": "Step 4 – Create a java class (MyAlarmService.java) and add the following code?" }, { "code": null, "e": 5150, "s": 4112, "text": "import android.app.Service;\nimport android.content.Intent;\nimport android.os.IBinder;\nimport android.support.annotation.Nullable;\nimport android.widget.Toast;\npublic class MyAlarmService extends Service {\n @Override\n public void onCreate() {\n Toast.makeText(this, \"MyAlarmService.onCreate()\", Toast.LENGTH_LONG).show();\n }\n @Nullable\n @Override\n public IBinder onBind(Intent intent) {\n Toast.makeText(this, \"MyAlarmService.onBind()\", Toast.LENGTH_LONG).show();\n return null;\n }\n @Override\n public void onDestroy() {\n super.onDestroy();\n Toast.makeText(this, \"MyAlarmService.onDestroy()\", Toast.LENGTH_LONG).show();\n }\n @Override\n public void onStart(Intent intent, int startId) {\n super.onStart(intent, startId);\n Toast.makeText(this, \"MyAlarmService.onStart()\", Toast.LENGTH_LONG).show();\n }\n @Override\n public boolean onUnbind(Intent intent) {\n Toast.makeText(this, \"MyAlarmService.onUnbind()\", Toast.LENGTH_LONG).show();\n return super.onUnbind(intent);\n }\n}" }, { "code": null, "e": 5205, "s": 5150, "text": "Step 5 − Add the following code to androidManifest.xml" }, { "code": null, "e": 5921, "s": 5205, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"app.com.sample\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n <service android:name=\".MyAlarmService\" />\n </application>\n</manifest>" }, { "code": null, "e": 6268, "s": 5921, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –" }, { "code": null, "e": 6309, "s": 6268, "text": "Click here to download the project code." } ]
Python Number Systems Example - onlinetutorialspoint
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 According to the mathematics we have four types of number systems which are representing the numbers in computer architecture. In this tutorial, we are going to learn how to deal with these number systems in Python Language. The python number system is representing the way of using the below numbers in Language. Binary Number System Octal Number System Decimal Number System Hexadecimal Number System Let’s see one by one, how these are used in the python language. In general, a binary number represents a 0 or 1 in the system. The base or radix of the binary number system is 2. The possible digits that are used in a binary number system are 0 and 1. If we wanted to store a binary number in python variable, that number should sharts with 0b. x = 0b1010 print('Value is : ',x) Output : (Value is : 10) Note: we can not give the x=ob1020 since binary numbers contain only 0 and 1. If so we will get an error message like SyntaxError: invalid syntax. The base or radix of the octal number system is 8. The possible digits that are used in the octal number system are 0 to 7. To represent an octal number in Python, the number should start with 0 (python2) or ox (python3). x=0123 print('Value is : '+x) Output : (Value is : 83) Note: we can not give the x=o180 since octal numbers contain from 0 to 7. If so we will get an error message like SyntaxError: invalid token. The base or radix of the decimal number system is 10. The possible digits that are used in the decimal number system are 0 to 9. The default number system followed by python is the decimal number system. x=1234 print('Value is : '+x) Output : (Value is : 1234) Note: we can not give the x=1234p since the decimal numbers contain from 0 to 9. If so we will get an error message like SyntaxError: invalid syntax. The base or radix of the hexadecimal number system is 16. The possible digits that are used in hexadecimal number systems are 0 to 9 and a to f. To represent a hexadecimal number in Python, the number should start with 0x. x=0x25 print('Value is :'+x) Output : (Value is : 37) Number System Wiki Python-Dev Peps Happy Learning 🙂 Convert any Number to Python Binary Number Binary To Hexadecimal Conversion Java Program Decimal To Octal Conversion Java Program Octal To Decimal Conversion Java Program Decimal To Hex Conversion Java Program Binary To Decimal Conversion Java Program Decimal To Binary Conversion Java Program Python – Find the biggest of 2 given numbers Features of Python Language Modes of Python Program Python Operators Example Python Conditional Statements What are different Python Data Types What are the List of Python Keywords Python String to int Conversion Example Convert any Number to Python Binary Number Binary To Hexadecimal Conversion Java Program Decimal To Octal Conversion Java Program Octal To Decimal Conversion Java Program Decimal To Hex Conversion Java Program Binary To Decimal Conversion Java Program Decimal To Binary Conversion Java Program Python – Find the biggest of 2 given numbers Features of Python Language Modes of Python Program Python Operators Example Python Conditional Statements What are different Python Data Types What are the List of Python Keywords Python String to int Conversion Example Δ Python – Introduction Python – Features Python – Install on Windows Python – Modes of Program Python – Number System Python – Identifiers Python – Operators Python – Ternary Operator Python – Command Line Arguments Python – Keywords Python – Data Types Python – Upgrade Python PIP Python – Virtual Environment Pyhton – Type Casting Python – String to Int Python – Conditional Statements Python – if statement Python – *args and **kwargs Python – Date Formatting Python – Read input from keyboard Python – raw_input Python – List In Depth Python – List Comprehension Python – Set in Depth Python – Dictionary in Depth Python – Tuple in Depth Python – Stack Datastructure Python – Classes and Objects Python – Constructors Python – Object Introspection Python – Inheritance Python – Decorators Python – Serialization with Pickle Python – Exceptions Handling Python – User defined Exceptions Python – Multiprocessing Python – Default function parameters Python – Lambdas Functions Python – NumPy Library Python – MySQL Connector Python – MySQL Create Database Python – MySQL Read Data Python – MySQL Insert Data Python – MySQL Update Records Python – MySQL Delete Records Python – String Case Conversion Howto – Find biggest of 2 numbers Howto – Remove duplicates from List Howto – Convert any Number to Binary Howto – Merge two Lists Howto – Merge two dicts Howto – Get Characters Count in a File Howto – Get Words Count in a File Howto – Remove Spaces from String Howto – Read Env variables Howto – Read a text File Howto – Read a JSON File Howto – Read Config.ini files Howto – Iterate Dictionary Howto – Convert List Of Objects to CSV Howto – Merge two dict in Python Howto – create Zip File Howto – Get OS info Howto – Get size of Directory Howto – Check whether a file exists Howto – Remove key from dictionary Howto – Sort Objects Howto – Create or Delete Directories Howto – Read CSV File Howto – Create Python Iterable class Howto – Access for loop index Howto – Clear all elements from List Howto – Remove empty lists from a List Howto – Remove special characters from String Howto – Sort dictionary by key Howto – Filter a list
[ { "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": 623, "s": 398, "text": "According to the mathematics we have four types of number systems which are representing the numbers in computer architecture. In this tutorial, we are going to learn how to deal with these number systems in Python Language." }, { "code": null, "e": 712, "s": 623, "text": "The python number system is representing the way of using the below numbers in Language." }, { "code": null, "e": 733, "s": 712, "text": "Binary Number System" }, { "code": null, "e": 753, "s": 733, "text": "Octal Number System" }, { "code": null, "e": 775, "s": 753, "text": "Decimal Number System" }, { "code": null, "e": 801, "s": 775, "text": "Hexadecimal Number System" }, { "code": null, "e": 866, "s": 801, "text": "Let’s see one by one, how these are used in the python language." }, { "code": null, "e": 929, "s": 866, "text": "In general, a binary number represents a 0 or 1 in the system." }, { "code": null, "e": 981, "s": 929, "text": "The base or radix of the binary number system is 2." }, { "code": null, "e": 1054, "s": 981, "text": "The possible digits that are used in a binary number system are 0 and 1." }, { "code": null, "e": 1147, "s": 1054, "text": "If we wanted to store a binary number in python variable, that number should sharts with 0b." }, { "code": null, "e": 1184, "s": 1147, "text": "x = 0b1010\n\nprint('Value is : ',x)\n\n" }, { "code": null, "e": 1193, "s": 1184, "text": "Output :" }, { "code": null, "e": 1209, "s": 1193, "text": "(Value is : 10)" }, { "code": null, "e": 1356, "s": 1209, "text": "Note: we can not give the x=ob1020 since binary numbers contain only 0 and 1. If so we will get an error message like SyntaxError: invalid syntax." }, { "code": null, "e": 1407, "s": 1356, "text": "The base or radix of the octal number system is 8." }, { "code": null, "e": 1480, "s": 1407, "text": "The possible digits that are used in the octal number system are 0 to 7." }, { "code": null, "e": 1578, "s": 1480, "text": "To represent an octal number in Python, the number should start with 0 (python2) or ox (python3)." }, { "code": null, "e": 1610, "s": 1578, "text": "x=0123\n\nprint('Value is : '+x)\n" }, { "code": null, "e": 1619, "s": 1610, "text": "Output :" }, { "code": null, "e": 1635, "s": 1619, "text": "(Value is : 83)" }, { "code": null, "e": 1777, "s": 1635, "text": "Note: we can not give the x=o180 since octal numbers contain from 0 to 7. If so we will get an error message like SyntaxError: invalid token." }, { "code": null, "e": 1831, "s": 1777, "text": "The base or radix of the decimal number system is 10." }, { "code": null, "e": 1906, "s": 1831, "text": "The possible digits that are used in the decimal number system are 0 to 9." }, { "code": null, "e": 1981, "s": 1906, "text": "The default number system followed by python is the decimal number system." }, { "code": null, "e": 2013, "s": 1981, "text": "x=1234\n\nprint('Value is : '+x)\n" }, { "code": null, "e": 2022, "s": 2013, "text": "Output :" }, { "code": null, "e": 2040, "s": 2022, "text": "(Value is : 1234)" }, { "code": null, "e": 2190, "s": 2040, "text": "Note: we can not give the x=1234p since the decimal numbers contain from 0 to 9. If so we will get an error message like SyntaxError: invalid syntax." }, { "code": null, "e": 2248, "s": 2190, "text": "The base or radix of the hexadecimal number system is 16." }, { "code": null, "e": 2336, "s": 2248, "text": "The possible digits that are used in hexadecimal number systems are 0 to 9 and a to f." }, { "code": null, "e": 2414, "s": 2336, "text": "To represent a hexadecimal number in Python, the number should start with 0x." }, { "code": null, "e": 2445, "s": 2414, "text": "x=0x25\n\nprint('Value is :'+x)\n" }, { "code": null, "e": 2454, "s": 2445, "text": "Output :" }, { "code": null, "e": 2470, "s": 2454, "text": "(Value is : 37)" }, { "code": null, "e": 2489, "s": 2470, "text": "Number System Wiki" }, { "code": null, "e": 2505, "s": 2489, "text": "Python-Dev Peps" }, { "code": null, "e": 2522, "s": 2505, "text": "Happy Learning 🙂" }, { "code": null, "e": 3084, "s": 2522, "text": "\nConvert any Number to Python Binary Number\nBinary To Hexadecimal Conversion Java Program\nDecimal To Octal Conversion Java Program\nOctal To Decimal Conversion Java Program\nDecimal To Hex Conversion Java Program\nBinary To Decimal Conversion Java Program\nDecimal To Binary Conversion Java Program\nPython – Find the biggest of 2 given numbers\nFeatures of Python Language\nModes of Python Program\nPython Operators Example\nPython Conditional Statements\nWhat are different Python Data Types\nWhat are the List of Python Keywords\nPython String to int Conversion Example\n" }, { "code": null, "e": 3127, "s": 3084, "text": "Convert any Number to Python Binary Number" }, { "code": null, "e": 3173, "s": 3127, "text": "Binary To Hexadecimal Conversion Java Program" }, { "code": null, "e": 3214, "s": 3173, "text": "Decimal To Octal Conversion Java Program" }, { "code": null, "e": 3255, "s": 3214, "text": "Octal To Decimal Conversion Java Program" }, { "code": null, "e": 3294, "s": 3255, "text": "Decimal To Hex Conversion Java Program" }, { "code": null, "e": 3336, "s": 3294, "text": "Binary To Decimal Conversion Java Program" }, { "code": null, "e": 3378, "s": 3336, "text": "Decimal To Binary Conversion Java Program" }, { "code": null, "e": 3423, "s": 3378, "text": "Python – Find the biggest of 2 given numbers" }, { "code": null, "e": 3451, "s": 3423, "text": "Features of Python Language" }, { "code": null, "e": 3475, "s": 3451, "text": "Modes of Python Program" }, { "code": null, "e": 3500, "s": 3475, "text": "Python Operators Example" }, { "code": null, "e": 3530, "s": 3500, "text": "Python Conditional Statements" }, { "code": null, "e": 3567, "s": 3530, "text": "What are different Python Data Types" }, { "code": null, "e": 3604, "s": 3567, "text": "What are the List of Python Keywords" }, { "code": null, "e": 3644, "s": 3604, "text": "Python String to int Conversion Example" }, { "code": null, "e": 3650, "s": 3648, "text": "Δ" }, { "code": null, "e": 3673, "s": 3650, "text": " Python – Introduction" }, { "code": null, "e": 3692, "s": 3673, "text": " Python – Features" }, { "code": null, "e": 3721, "s": 3692, "text": " Python – Install on Windows" }, { "code": null, "e": 3748, "s": 3721, "text": " Python – Modes of Program" }, { "code": null, "e": 3772, "s": 3748, "text": " Python – Number System" }, { "code": null, "e": 3794, "s": 3772, "text": " Python – Identifiers" }, { "code": null, "e": 3814, "s": 3794, "text": " Python – Operators" }, { "code": null, "e": 3841, "s": 3814, "text": " Python – Ternary Operator" }, { "code": null, "e": 3874, "s": 3841, "text": " Python – Command Line Arguments" }, { "code": null, "e": 3893, "s": 3874, "text": " Python – Keywords" }, { "code": null, "e": 3914, "s": 3893, "text": " Python – Data Types" }, { "code": null, "e": 3943, "s": 3914, "text": " Python – Upgrade Python PIP" }, { "code": null, "e": 3973, "s": 3943, "text": " Python – Virtual Environment" }, { "code": null, "e": 3996, "s": 3973, "text": " Pyhton – Type Casting" }, { "code": null, "e": 4020, "s": 3996, "text": " Python – String to Int" }, { "code": null, "e": 4053, "s": 4020, "text": " Python – Conditional Statements" }, { "code": null, "e": 4076, "s": 4053, "text": " Python – if statement" }, { "code": null, "e": 4105, "s": 4076, "text": " Python – *args and **kwargs" }, { "code": null, "e": 4131, "s": 4105, "text": " Python – Date Formatting" }, { "code": null, "e": 4166, "s": 4131, "text": " Python – Read input from keyboard" }, { "code": null, "e": 4186, "s": 4166, "text": " Python – raw_input" }, { "code": null, "e": 4210, "s": 4186, "text": " Python – List In Depth" }, { "code": null, "e": 4239, "s": 4210, "text": " Python – List Comprehension" }, { "code": null, "e": 4262, "s": 4239, "text": " Python – Set in Depth" }, { "code": null, "e": 4292, "s": 4262, "text": " Python – Dictionary in Depth" }, { "code": null, "e": 4317, "s": 4292, "text": " Python – Tuple in Depth" }, { "code": null, "e": 4347, "s": 4317, "text": " Python – Stack Datastructure" }, { "code": null, "e": 4377, "s": 4347, "text": " Python – Classes and Objects" }, { "code": null, "e": 4400, "s": 4377, "text": " Python – Constructors" }, { "code": null, "e": 4431, "s": 4400, "text": " Python – Object Introspection" }, { "code": null, "e": 4453, "s": 4431, "text": " Python – Inheritance" }, { "code": null, "e": 4474, "s": 4453, "text": " Python – Decorators" }, { "code": null, "e": 4510, "s": 4474, "text": " Python – Serialization with Pickle" }, { "code": null, "e": 4540, "s": 4510, "text": " Python – Exceptions Handling" }, { "code": null, "e": 4574, "s": 4540, "text": " Python – User defined Exceptions" }, { "code": null, "e": 4600, "s": 4574, "text": " Python – Multiprocessing" }, { "code": null, "e": 4638, "s": 4600, "text": " Python – Default function parameters" }, { "code": null, "e": 4666, "s": 4638, "text": " Python – Lambdas Functions" }, { "code": null, "e": 4690, "s": 4666, "text": " Python – NumPy Library" }, { "code": null, "e": 4716, "s": 4690, "text": " Python – MySQL Connector" }, { "code": null, "e": 4748, "s": 4716, "text": " Python – MySQL Create Database" }, { "code": null, "e": 4774, "s": 4748, "text": " Python – MySQL Read Data" }, { "code": null, "e": 4802, "s": 4774, "text": " Python – MySQL Insert Data" }, { "code": null, "e": 4833, "s": 4802, "text": " Python – MySQL Update Records" }, { "code": null, "e": 4864, "s": 4833, "text": " Python – MySQL Delete Records" }, { "code": null, "e": 4897, "s": 4864, "text": " Python – String Case Conversion" }, { "code": null, "e": 4932, "s": 4897, "text": " Howto – Find biggest of 2 numbers" }, { "code": null, "e": 4969, "s": 4932, "text": " Howto – Remove duplicates from List" }, { "code": null, "e": 5007, "s": 4969, "text": " Howto – Convert any Number to Binary" }, { "code": null, "e": 5033, "s": 5007, "text": " Howto – Merge two Lists" }, { "code": null, "e": 5058, "s": 5033, "text": " Howto – Merge two dicts" }, { "code": null, "e": 5098, "s": 5058, "text": " Howto – Get Characters Count in a File" }, { "code": null, "e": 5133, "s": 5098, "text": " Howto – Get Words Count in a File" }, { "code": null, "e": 5168, "s": 5133, "text": " Howto – Remove Spaces from String" }, { "code": null, "e": 5197, "s": 5168, "text": " Howto – Read Env variables" }, { "code": null, "e": 5223, "s": 5197, "text": " Howto – Read a text File" }, { "code": null, "e": 5249, "s": 5223, "text": " Howto – Read a JSON File" }, { "code": null, "e": 5281, "s": 5249, "text": " Howto – Read Config.ini files" }, { "code": null, "e": 5309, "s": 5281, "text": " Howto – Iterate Dictionary" }, { "code": null, "e": 5349, "s": 5309, "text": " Howto – Convert List Of Objects to CSV" }, { "code": null, "e": 5383, "s": 5349, "text": " Howto – Merge two dict in Python" }, { "code": null, "e": 5408, "s": 5383, "text": " Howto – create Zip File" }, { "code": null, "e": 5429, "s": 5408, "text": " Howto – Get OS info" }, { "code": null, "e": 5460, "s": 5429, "text": " Howto – Get size of Directory" }, { "code": null, "e": 5497, "s": 5460, "text": " Howto – Check whether a file exists" }, { "code": null, "e": 5534, "s": 5497, "text": " Howto – Remove key from dictionary" }, { "code": null, "e": 5556, "s": 5534, "text": " Howto – Sort Objects" }, { "code": null, "e": 5594, "s": 5556, "text": " Howto – Create or Delete Directories" }, { "code": null, "e": 5617, "s": 5594, "text": " Howto – Read CSV File" }, { "code": null, "e": 5655, "s": 5617, "text": " Howto – Create Python Iterable class" }, { "code": null, "e": 5686, "s": 5655, "text": " Howto – Access for loop index" }, { "code": null, "e": 5724, "s": 5686, "text": " Howto – Clear all elements from List" }, { "code": null, "e": 5764, "s": 5724, "text": " Howto – Remove empty lists from a List" }, { "code": null, "e": 5811, "s": 5764, "text": " Howto – Remove special characters from String" }, { "code": null, "e": 5843, "s": 5811, "text": " Howto – Sort dictionary by key" } ]
How to write Java program to add two matrices
To add two matrices − Create an empty matrix At each position in the new matrix, assign the sum of the values in the same position from the given two matrices i.e. if A[i][j] and B[i][j] are the two given matrices then, the value of c[i][j] should be A[i][j] + B[i][j] Live Demo public class AddingTwoMatrices{ public static void main(String args[]){ int a[][]={{1,2,3},{4,5,6},{7,8,9}}; int b[][]={{1,1,1},{1,1,1},{1,1,1}}; int c[][]=new int[3][3]; for(int i = 0;i<3;i++){ for(int j = 0;j<3;j++){ c[i][j] = a[i][j]+b[i][j]; System.out.print(c[i][j]+" "); } System.out.println(); } } } 2 3 4 5 6 7 8 9 10
[ { "code": null, "e": 1084, "s": 1062, "text": "To add two matrices −" }, { "code": null, "e": 1107, "s": 1084, "text": "Create an empty matrix" }, { "code": null, "e": 1331, "s": 1107, "text": "At each position in the new matrix, assign the sum of the values in the same position from the given two matrices i.e. if A[i][j] and B[i][j] are the two given matrices then, the value of c[i][j] should be A[i][j] + B[i][j]" }, { "code": null, "e": 1341, "s": 1331, "text": "Live Demo" }, { "code": null, "e": 1736, "s": 1341, "text": "public class AddingTwoMatrices{\n public static void main(String args[]){\n int a[][]={{1,2,3},{4,5,6},{7,8,9}};\n int b[][]={{1,1,1},{1,1,1},{1,1,1}};\n int c[][]=new int[3][3];\n\n for(int i = 0;i<3;i++){\n for(int j = 0;j<3;j++){\n c[i][j] = a[i][j]+b[i][j];\n System.out.print(c[i][j]+\" \");\n }\n System.out.println();\n }\n }\n}" }, { "code": null, "e": 1755, "s": 1736, "text": "2 3 4\n5 6 7\n8 9 10" } ]
How to implement the Fibonacci series using lambda expression in Java?
The Fibonacci is a sequence of numbers in which every number after the first two numbers is the sum of the two preceding numbers like 0, 1, 1, 2, 3, 5, 8, 13, 21 and so on. The sequence of Fibonacci numbers defined by using "F(n)=F(n-1)+F(n-2)". In the below example, we can implement the Fibonacci series with the help of Stream API and lambda expression. The Stream.iterate() method returns an infinite sequential ordered stream produced by iterative application of a function to an initial element seed, producing a stream consisting of seed, f(seed), f(f(seed)), etc. import java.util.List; import java.util.stream.*; public class FibonacciTest { public static void main(String args[]) { System.out.println(FibonacciTest.generate(10)); } public static List generate(int series) { return Stream.iterate(new int[]{0, 1}, s -> new int[]{s[1], s[0] + s[1]}) // lambda expression .limit(series) .map(n -> n[0]) .collect(Collectors.toList()); } } [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
[ { "code": null, "e": 1308, "s": 1062, "text": "The Fibonacci is a sequence of numbers in which every number after the first two numbers is the sum of the two preceding numbers like 0, 1, 1, 2, 3, 5, 8, 13, 21 and so on. The sequence of Fibonacci numbers defined by using \"F(n)=F(n-1)+F(n-2)\"." }, { "code": null, "e": 1634, "s": 1308, "text": "In the below example, we can implement the Fibonacci series with the help of Stream API and lambda expression. The Stream.iterate() method returns an infinite sequential ordered stream produced by iterative application of a function to an initial element seed, producing a stream consisting of seed, f(seed), f(f(seed)), etc." }, { "code": null, "e": 2060, "s": 1634, "text": "import java.util.List;\nimport java.util.stream.*;\n\npublic class FibonacciTest {\n public static void main(String args[]) {\n System.out.println(FibonacciTest.generate(10));\n }\n public static List generate(int series) {\n return Stream.iterate(new int[]{0, 1}, s -> new int[]{s[1], s[0] + s[1]}) // lambda expression\n .limit(series)\n .map(n -> n[0])\n .collect(Collectors.toList());\n }\n}" }, { "code": null, "e": 2094, "s": 2060, "text": "[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]" } ]
PyCaret 2.1 is here — What’s new? | by Moez Ali | Towards Data Science
We are excited to announce PyCaret 2.1 — update for the month of Aug 2020. PyCaret is an open-source, low-code machine learning library in Python that automates the machine learning workflow. It is an end-to-end machine learning and model management tool that speeds up the machine learning experiment cycle and makes you 10x more productive. In comparison with the other open-source machine learning libraries, PyCaret is an alternate low-code library that can be used to replace hundreds of lines of code with few words only. This makes experiments exponentially fast and efficient. If you haven’t heard or used PyCaret before, please see our previous announcement to get started quickly. Installing PyCaret is very easy and takes only a few minutes. We strongly recommend using a virtual environment to avoid potential conflict with other libraries. See the following example code to create a conda environment and install pycaret within that conda environment: # create a conda environment conda create --name yourenvname python=3.6 # activate environment conda activate yourenvname # install pycaret pip install pycaret # create notebook kernel linked with the conda environment python -m ipykernel install --user --name yourenvname --display-name "display-name" If you have PyCaret already installed, you can update it using pip: pip install --upgrade pycaret In PyCaret 2.0 we have announced GPU-enabled training for certain algorithms (XGBoost, LightGBM and Catboost). What’s new in 2.1 is now you can also tune the hyperparameters of those models on GPU. # train xgboost using gpuxgboost = create_model('xgboost', tree_method = 'gpu_hist')# tune xgboost tuned_xgboost = tune_model(xgboost) No additional parameter needed inside tune_model function as it automatically inherits the tree_method from xgboost instance created using the create_model function. If you are interested in little comparison, here it is: 100,000 rows with 88 features in a Multiclass problem with 8 classes Since the first release of PyCaret in April 2020, you can deploy trained models on AWS simply by using the deploy_model from your Notebook. In the recent release, we have added functionalities to support deployment on GCP as well as Microsoft Azure. To deploy a model on Microsoft Azure, environment variables for connection string must be set. The connection string can be obtained from the ‘Access Keys’ of your storage account in Azure. Once you have copied the connection string, you can set it as an environment variable. See example below: import osos.environ['AZURE_STORAGE_CONNECTION_STRING'] = 'your-conn-string'from pycaret.classification import deploy_modeldeploy_model(model = model, model_name = 'model-name', platform = 'azure', authentication = {'container' : 'container-name'}) BOOM! That’s it. Just by using one line of code, your entire machine learning pipeline is now shipped on the container in Microsoft Azure. You can access that using the load_model function. import osos.environ['AZURE_STORAGE_CONNECTION_STRING'] = 'your-conn-string'from pycaret.classification import load_modelloaded_model = load_model(model_name = 'model-name', platform = 'azure', authentication = {'container' : 'container-name'})from pycaret.classification import predict_modelpredictions = predict_model(loaded_model, data = new-dataframe) To deploy a model on Google Cloud Platform (GCP), you must create a project first either using a command line or GCP console. Once the project is created, you must create a service account and download the service account key as a JSON file, which is then used to set the environment variable. To learn more about creating a service account, read the official documentation. Once you have created a service account and downloaded the JSON file from your GCP console you are ready for deployment. import osos.environ['GOOGLE_APPLICATION_CREDENTIALS'] = 'c:/path-to-json-file.json'from pycaret.classification import deploy_modeldeploy_model(model = model, model_name = 'model-name', platform = 'gcp', authentication = {'project' : 'project-name', 'bucket' : 'bucket-name'}) Model uploaded. You can now access the model from the GCP bucket using the load_model function. import osos.environ['GOOGLE_APPLICATION_CREDENTIALS'] = 'c:/path-to-json-file.json'from pycaret.classification import load_modelloaded_model = load_model(model_name = 'model-name', platform = 'gcp', authentication = {'project' : 'project-name', 'bucket' : 'bucket-name'})from pycaret.classification import predict_modelpredictions = predict_model(loaded_model, data = new-dataframe) In addition to using PyCaret’s native deployment functionalities, you can now also use all the MLFlow deployment capabilities. To use those, you must log your experiment using the log_experiment parameter in the setup function. # init setupexp1 = setup(data, target = 'target-name', log_experiment = True, experiment_name = 'exp-name')# create xgboost modelxgboost = create_model('xgboost')......# rest of your script# start mlflow server on localhost:5000!mlflow ui Now open https://localhost:5000 on your favorite browser. You can see the details of run by clicking the “Start Time” shown on the left of “Run Name”. What you see inside is all the hyperparameters and scoring metrics of a trained model and if you scroll down a little, all the artifacts are shown as well (see below). A trained model along with other metadata files are stored under the directory “/model”. MLFlow follows a standard format for packaging machine learning models that can be used in a variety of downstream tools — for example, real-time serving through a REST API or batch inference on Apache Spark. If you want you can serve this model locally you can do that by using MLFlow command line. mlflow models serve -m local-path-to-model You can then send the request to model using CURL to get the predictions. curl http://127.0.0.1:5000/invocations -H 'Content-Type: application/json' -d '{ "columns": ["age", "sex", "bmi", "children", "smoker", "region"], "data": [[19, "female", 27.9, 0, "yes", "southwest"]]}' (Note: This functionality of MLFlow is not supported on Windows OS yet). MLFlow also provide integration with AWS Sagemaker and Azure Machine Learning Service. You can train models locally in a Docker container with SageMaker compatible environment or remotely on SageMaker. To deploy remotely to SageMaker you need to set up your environment and AWS user account. Example workflow using the MLflow CLI mlflow sagemaker build-and-push-container mlflow sagemaker run-local -m <path-to-model>mlflow sagemaker deploy <parameters> To learn more about all deployment capabilities of MLFlow, click here. The MLflow Model Registry component is a centralized model store, set of APIs, and UI, to collaboratively manage the full lifecycle of an MLflow Model. It provides model lineage (which MLflow experiment and run produced the model), model versioning, stage transitions (for example from staging to production), and annotations. If running your own MLflow server, you must use a database-backed backend store in order to access the model registry. Click here for more information. However, if you are using Databricks or any of the managed Databricks services such as Azure Databricks, you don’t need to worry about setting up anything. It comes with all the bells and whistles you would ever need. This is not ground-breaking but indeed a very useful addition for people using PyCaret for research and publications. The plot_model now has an additional parameter called “scale” through which you can control the resolution and generate high quality plot for your publications. # create linear regression modellr = create_model('lr')# plot in high-quality resolutionplot_model(lr, scale = 5) # default is 1 This is one of the most requested feature ever since release of the first version. Allowing to tune hyperparameters of a model using custom / user-defined function gives immense flexibility to data scientists. It is now possible to use user-defined custom loss functions using custom_scorer parameter in the tune_model function. # define the loss functiondef my_function(y_true, y_pred):......# create scorer using sklearnfrom sklearn.metrics import make_scorermy_own_scorer = make_scorer(my_function, needs_proba=True)# train catboost modelcatboost = create_model('catboost')# tune catboost using custom scorertuned_catboost = tune_model(catboost, custom_scorer = my_own_scorer) Feature selection is a fundamental step in machine learning. You dispose of a bunch of features and you want to select only the relevant ones and to discard the others. The aim is simplifying the problem by removing unuseful features which would introduce unnecessary noise. In PyCaret 2.1 we have introduced implementation of Boruta algorithm in Python (originally implemented in R). Boruta is a pretty smart algorithm dating back to 2010 designed to automatically perform feature selection on a dataset. To use this, you simply have to pass the feature_selection_method within the setup function. exp1 = setup(data, target = 'target-var', feature_selection = True, feature_selection_method = 'boruta') To read more about Boruta algorithm, click here. blacklist and whitelist parameters in compare_models function is now renamed to exclude and include with no change in functionality. To set the upper limit on training time in compare_models function, new parameter budget_time has been added. PyCaret is now compatible with Pandas categorical datatype. Internally they are converted into object and are treated as the same way as object or bool is treated. Numeric Imputation New method zero has been added in the numeric_imputation in the setup function. When method is set to zero, missing values are replaced with constant 0. To make the output more human-readable, the Label column returned by predict_model function now returns the original value instead of encoded value. To learn more about all the updates in PyCaret 2.1, please see the release notes. There is no limit to what you can achieve using the lightweight workflow automation library in Python. If you find this useful, please do not forget to give us ⭐️ on our GitHub repo. To hear more about PyCaret follow us on LinkedIn and Youtube. User GuideDocumentationOfficial TutorialsExample NotebooksOther Resources Click on the links below to see the documentation and working examples. ClassificationRegressionClusteringAnomaly DetectionNatural Language ProcessingAssociation Rule Mining
[ { "code": null, "e": 247, "s": 172, "text": "We are excited to announce PyCaret 2.1 — update for the month of Aug 2020." }, { "code": null, "e": 515, "s": 247, "text": "PyCaret is an open-source, low-code machine learning library in Python that automates the machine learning workflow. It is an end-to-end machine learning and model management tool that speeds up the machine learning experiment cycle and makes you 10x more productive." }, { "code": null, "e": 757, "s": 515, "text": "In comparison with the other open-source machine learning libraries, PyCaret is an alternate low-code library that can be used to replace hundreds of lines of code with few words only. This makes experiments exponentially fast and efficient." }, { "code": null, "e": 863, "s": 757, "text": "If you haven’t heard or used PyCaret before, please see our previous announcement to get started quickly." }, { "code": null, "e": 1137, "s": 863, "text": "Installing PyCaret is very easy and takes only a few minutes. We strongly recommend using a virtual environment to avoid potential conflict with other libraries. See the following example code to create a conda environment and install pycaret within that conda environment:" }, { "code": null, "e": 1442, "s": 1137, "text": "# create a conda environment conda create --name yourenvname python=3.6 # activate environment conda activate yourenvname # install pycaret pip install pycaret # create notebook kernel linked with the conda environment python -m ipykernel install --user --name yourenvname --display-name \"display-name\"" }, { "code": null, "e": 1510, "s": 1442, "text": "If you have PyCaret already installed, you can update it using pip:" }, { "code": null, "e": 1540, "s": 1510, "text": "pip install --upgrade pycaret" }, { "code": null, "e": 1738, "s": 1540, "text": "In PyCaret 2.0 we have announced GPU-enabled training for certain algorithms (XGBoost, LightGBM and Catboost). What’s new in 2.1 is now you can also tune the hyperparameters of those models on GPU." }, { "code": null, "e": 1873, "s": 1738, "text": "# train xgboost using gpuxgboost = create_model('xgboost', tree_method = 'gpu_hist')# tune xgboost tuned_xgboost = tune_model(xgboost)" }, { "code": null, "e": 2095, "s": 1873, "text": "No additional parameter needed inside tune_model function as it automatically inherits the tree_method from xgboost instance created using the create_model function. If you are interested in little comparison, here it is:" }, { "code": null, "e": 2164, "s": 2095, "text": "100,000 rows with 88 features in a Multiclass problem with 8 classes" }, { "code": null, "e": 2414, "s": 2164, "text": "Since the first release of PyCaret in April 2020, you can deploy trained models on AWS simply by using the deploy_model from your Notebook. In the recent release, we have added functionalities to support deployment on GCP as well as Microsoft Azure." }, { "code": null, "e": 2604, "s": 2414, "text": "To deploy a model on Microsoft Azure, environment variables for connection string must be set. The connection string can be obtained from the ‘Access Keys’ of your storage account in Azure." }, { "code": null, "e": 2710, "s": 2604, "text": "Once you have copied the connection string, you can set it as an environment variable. See example below:" }, { "code": null, "e": 2958, "s": 2710, "text": "import osos.environ['AZURE_STORAGE_CONNECTION_STRING'] = 'your-conn-string'from pycaret.classification import deploy_modeldeploy_model(model = model, model_name = 'model-name', platform = 'azure', authentication = {'container' : 'container-name'})" }, { "code": null, "e": 3148, "s": 2958, "text": "BOOM! That’s it. Just by using one line of code, your entire machine learning pipeline is now shipped on the container in Microsoft Azure. You can access that using the load_model function." }, { "code": null, "e": 3503, "s": 3148, "text": "import osos.environ['AZURE_STORAGE_CONNECTION_STRING'] = 'your-conn-string'from pycaret.classification import load_modelloaded_model = load_model(model_name = 'model-name', platform = 'azure', authentication = {'container' : 'container-name'})from pycaret.classification import predict_modelpredictions = predict_model(loaded_model, data = new-dataframe)" }, { "code": null, "e": 3797, "s": 3503, "text": "To deploy a model on Google Cloud Platform (GCP), you must create a project first either using a command line or GCP console. Once the project is created, you must create a service account and download the service account key as a JSON file, which is then used to set the environment variable." }, { "code": null, "e": 3999, "s": 3797, "text": "To learn more about creating a service account, read the official documentation. Once you have created a service account and downloaded the JSON file from your GCP console you are ready for deployment." }, { "code": null, "e": 4275, "s": 3999, "text": "import osos.environ['GOOGLE_APPLICATION_CREDENTIALS'] = 'c:/path-to-json-file.json'from pycaret.classification import deploy_modeldeploy_model(model = model, model_name = 'model-name', platform = 'gcp', authentication = {'project' : 'project-name', 'bucket' : 'bucket-name'})" }, { "code": null, "e": 4371, "s": 4275, "text": "Model uploaded. You can now access the model from the GCP bucket using the load_model function." }, { "code": null, "e": 4754, "s": 4371, "text": "import osos.environ['GOOGLE_APPLICATION_CREDENTIALS'] = 'c:/path-to-json-file.json'from pycaret.classification import load_modelloaded_model = load_model(model_name = 'model-name', platform = 'gcp', authentication = {'project' : 'project-name', 'bucket' : 'bucket-name'})from pycaret.classification import predict_modelpredictions = predict_model(loaded_model, data = new-dataframe)" }, { "code": null, "e": 4982, "s": 4754, "text": "In addition to using PyCaret’s native deployment functionalities, you can now also use all the MLFlow deployment capabilities. To use those, you must log your experiment using the log_experiment parameter in the setup function." }, { "code": null, "e": 5221, "s": 4982, "text": "# init setupexp1 = setup(data, target = 'target-name', log_experiment = True, experiment_name = 'exp-name')# create xgboost modelxgboost = create_model('xgboost')......# rest of your script# start mlflow server on localhost:5000!mlflow ui" }, { "code": null, "e": 5279, "s": 5221, "text": "Now open https://localhost:5000 on your favorite browser." }, { "code": null, "e": 5540, "s": 5279, "text": "You can see the details of run by clicking the “Start Time” shown on the left of “Run Name”. What you see inside is all the hyperparameters and scoring metrics of a trained model and if you scroll down a little, all the artifacts are shown as well (see below)." }, { "code": null, "e": 5929, "s": 5540, "text": "A trained model along with other metadata files are stored under the directory “/model”. MLFlow follows a standard format for packaging machine learning models that can be used in a variety of downstream tools — for example, real-time serving through a REST API or batch inference on Apache Spark. If you want you can serve this model locally you can do that by using MLFlow command line." }, { "code": null, "e": 5972, "s": 5929, "text": "mlflow models serve -m local-path-to-model" }, { "code": null, "e": 6046, "s": 5972, "text": "You can then send the request to model using CURL to get the predictions." }, { "code": null, "e": 6255, "s": 6046, "text": "curl http://127.0.0.1:5000/invocations -H 'Content-Type: application/json' -d '{ \"columns\": [\"age\", \"sex\", \"bmi\", \"children\", \"smoker\", \"region\"], \"data\": [[19, \"female\", 27.9, 0, \"yes\", \"southwest\"]]}'" }, { "code": null, "e": 6328, "s": 6255, "text": "(Note: This functionality of MLFlow is not supported on Windows OS yet)." }, { "code": null, "e": 6620, "s": 6328, "text": "MLFlow also provide integration with AWS Sagemaker and Azure Machine Learning Service. You can train models locally in a Docker container with SageMaker compatible environment or remotely on SageMaker. To deploy remotely to SageMaker you need to set up your environment and AWS user account." }, { "code": null, "e": 6658, "s": 6620, "text": "Example workflow using the MLflow CLI" }, { "code": null, "e": 6782, "s": 6658, "text": "mlflow sagemaker build-and-push-container mlflow sagemaker run-local -m <path-to-model>mlflow sagemaker deploy <parameters>" }, { "code": null, "e": 6853, "s": 6782, "text": "To learn more about all deployment capabilities of MLFlow, click here." }, { "code": null, "e": 7180, "s": 6853, "text": "The MLflow Model Registry component is a centralized model store, set of APIs, and UI, to collaboratively manage the full lifecycle of an MLflow Model. It provides model lineage (which MLflow experiment and run produced the model), model versioning, stage transitions (for example from staging to production), and annotations." }, { "code": null, "e": 7550, "s": 7180, "text": "If running your own MLflow server, you must use a database-backed backend store in order to access the model registry. Click here for more information. However, if you are using Databricks or any of the managed Databricks services such as Azure Databricks, you don’t need to worry about setting up anything. It comes with all the bells and whistles you would ever need." }, { "code": null, "e": 7829, "s": 7550, "text": "This is not ground-breaking but indeed a very useful addition for people using PyCaret for research and publications. The plot_model now has an additional parameter called “scale” through which you can control the resolution and generate high quality plot for your publications." }, { "code": null, "e": 7958, "s": 7829, "text": "# create linear regression modellr = create_model('lr')# plot in high-quality resolutionplot_model(lr, scale = 5) # default is 1" }, { "code": null, "e": 8287, "s": 7958, "text": "This is one of the most requested feature ever since release of the first version. Allowing to tune hyperparameters of a model using custom / user-defined function gives immense flexibility to data scientists. It is now possible to use user-defined custom loss functions using custom_scorer parameter in the tune_model function." }, { "code": null, "e": 8638, "s": 8287, "text": "# define the loss functiondef my_function(y_true, y_pred):......# create scorer using sklearnfrom sklearn.metrics import make_scorermy_own_scorer = make_scorer(my_function, needs_proba=True)# train catboost modelcatboost = create_model('catboost')# tune catboost using custom scorertuned_catboost = tune_model(catboost, custom_scorer = my_own_scorer)" }, { "code": null, "e": 8913, "s": 8638, "text": "Feature selection is a fundamental step in machine learning. You dispose of a bunch of features and you want to select only the relevant ones and to discard the others. The aim is simplifying the problem by removing unuseful features which would introduce unnecessary noise." }, { "code": null, "e": 9237, "s": 8913, "text": "In PyCaret 2.1 we have introduced implementation of Boruta algorithm in Python (originally implemented in R). Boruta is a pretty smart algorithm dating back to 2010 designed to automatically perform feature selection on a dataset. To use this, you simply have to pass the feature_selection_method within the setup function." }, { "code": null, "e": 9342, "s": 9237, "text": "exp1 = setup(data, target = 'target-var', feature_selection = True, feature_selection_method = 'boruta')" }, { "code": null, "e": 9391, "s": 9342, "text": "To read more about Boruta algorithm, click here." }, { "code": null, "e": 9524, "s": 9391, "text": "blacklist and whitelist parameters in compare_models function is now renamed to exclude and include with no change in functionality." }, { "code": null, "e": 9634, "s": 9524, "text": "To set the upper limit on training time in compare_models function, new parameter budget_time has been added." }, { "code": null, "e": 9798, "s": 9634, "text": "PyCaret is now compatible with Pandas categorical datatype. Internally they are converted into object and are treated as the same way as object or bool is treated." }, { "code": null, "e": 9970, "s": 9798, "text": "Numeric Imputation New method zero has been added in the numeric_imputation in the setup function. When method is set to zero, missing values are replaced with constant 0." }, { "code": null, "e": 10119, "s": 9970, "text": "To make the output more human-readable, the Label column returned by predict_model function now returns the original value instead of encoded value." }, { "code": null, "e": 10201, "s": 10119, "text": "To learn more about all the updates in PyCaret 2.1, please see the release notes." }, { "code": null, "e": 10384, "s": 10201, "text": "There is no limit to what you can achieve using the lightweight workflow automation library in Python. If you find this useful, please do not forget to give us ⭐️ on our GitHub repo." }, { "code": null, "e": 10446, "s": 10384, "text": "To hear more about PyCaret follow us on LinkedIn and Youtube." }, { "code": null, "e": 10520, "s": 10446, "text": "User GuideDocumentationOfficial TutorialsExample NotebooksOther Resources" }, { "code": null, "e": 10592, "s": 10520, "text": "Click on the links below to see the documentation and working examples." } ]
Enhancements for Switch Statement in Java 13 - GeeksforGeeks
24 Oct, 2020 Java 12 improved the traditional switch statement and made it more useful. Java 13 further introduced new features. Before going into the details of new features, let’s have a look at the drawbacks faced by the traditional Switch statement. 1. Default fall through due to missing break The default fall-through behavior is error-prone. Let’s understand it with an example. switch (itemCode) { case 001 : System.out.println("It's a laptop!"); break; case 002 : System.out.println("It's a desktop!"); break; case 003 : System.out.println("It's a mobile phone!"); break; default : System.out.println("Unknown device!"); } The above code works by matching the corresponding case and executing the particular code block. As long as you provide the necessary break statements, it works fine. But what happens if we forget any of the required break statements: switch (itemCode) { case 001 : System.out.println("It's a laptop!"); // missed out break here case 002 : System.out.println("It's a desktop!"); break; } Here, if we pass 001, the first case matches, and the code block executes. But due to missing break, execution falls through and continues for case 002. We get the following wrong output: It's a laptop! It's a desktop! Clearly, this is not the intended output. It is a result of accidentally missing-out break statements. 2. Multiple values per case not supported There may be situations where similar processing is required for multiple case values. But the traditional switch makes to follow the fall through behaviour. case 001: case 002: case 003: System.out.println("It's an electronic gadget!"); Much improved switch accepts multiple values per case. case 001, 002, 003 : System.out.println("It's an electronic gadget!"); Enhancements to switch statements were introduced by Java 12 and then further modified by Java 13. Let’s dive into the important features of this improved version of the Switch statement. 1. Supports multiple values per case With multiple values being specified per case, it simplifies the code structure and eliminates the need for using fall through. The values need to be separated by commas and break should follow the case block. switch (itemCode) { case 001, 002, 003 : System.out.println("It's an electronic gadget!"); break; case 004, 005: System.out.println("It's a mechanical device!"); break; } 2. yield is used to return a value A new keyword yield has been introduced. It returns values from a switch branch only. We don’t need a break after yield as it automatically terminates the switch expression. int val = switch (code) { case "x", "y" : yield 1; case "z", "w" : yield 2; } 3. Switch can be used as an expression The switch can now be used as an expression. This means the switch can now return values based on our input. There is a slight change in switch syntax to accommodate this change. A switch block needs to be delimited by a semicolon. The yield keyword is used to return values. No break required with the yield statement. Let’s have a look at a code snippet to understand these changes better. String text = switch (itemCode) { case 001 : yield "It's a laptop!"; case 002 : yield "It's a desktop!"; case 003 : yield "It's a mobile phone!"; default : throw new IllegalArgumentException(itemCode + "is an unknown device!"); } 4. Necessary to return value/exception The switch expression is required to specify the handling of all the possible input values. Either we provide all the possible cases or specify the default one. This means, irrespective of the input value, switch expression should always return some value or explicitly throw an exception. For instance, if the above code block is changed to – String text = switch (itemCode) { case 001 : yield "It's a laptop!"; case 002 : yield "It's a desktop!"; case 003 : yield "It's a mobile phone!"; // default : // throw new IllegalArgumentException(itemCode + "is an unknown device!"); } This will result in an error saying that all possible values have not been covered by the switch expression. 5. Switch with arrows The new arrow ⇾ syntax has been introduced for the switch. It can be used with the switch as an expression as well as a statement. The statements on the right side of an ⇾ are executed if an exact case matches on the left side. On the right side of ⇾ we can have any of the following – Statement / expression throw statement {} block The main advantage of this syntax is that we don’t need a break statement to avoid the default fall-through. So the rule is, if we need fall-through, use case: else if not use case ⇾. Also note, for all case branches it should be either case: or case ⇾. It cannot be different or different cases in a switch else it results in an error. switch (itemCode) { case 001 -> System.out.println("It's a laptop!"); case 002 -> System.out.println("It's a desktop!"); case 003,004 -> System.out.println("It's a mobile phone!"); } As we can see in the above code, the syntax can also be used for multiple values per case. 6. Scope The variables declared in the traditional switch exists until the end of the switch statement. If we want the variables to have a case level scope, we can use {} introduced by the enhanced switch in Java 13. switch (errorCode) { case 101: { // This variable exists just in this {} block int num = 200; break; } case 300: { // This is ok, {} block has a separate scope int num = 300; break; } } 7. Preview feature After diving into the features related to the enhanced switch, the point noteworthy is — the enhanced switch functionality is available only as a preview feature in Java 13. This means it is not enabled by default. To use it, we need to explicitly enable it. At compile time, add the following params to javac: javac -- release 13 --enable-preview MyClass.java At run time, add the following: java --enable-preview MyClass The enhanced switch in Java 13 provides a number of impressive features to the traditional switch. However, it is still in the experiment phase and not yet meant for use in production. Java-Control-Flow Java Java-Control-Flow Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Constructors in Java Exceptions in Java Functional Interfaces in Java Different ways of Reading a text file in Java Generics in Java Introduction to Java Comparator Interface in Java with Examples PriorityQueue in Java Internal Working of HashMap in Java
[ { "code": null, "e": 25262, "s": 25234, "text": "\n24 Oct, 2020" }, { "code": null, "e": 25503, "s": 25262, "text": "Java 12 improved the traditional switch statement and made it more useful. Java 13 further introduced new features. Before going into the details of new features, let’s have a look at the drawbacks faced by the traditional Switch statement." }, { "code": null, "e": 25548, "s": 25503, "text": "1. Default fall through due to missing break" }, { "code": null, "e": 25635, "s": 25548, "text": "The default fall-through behavior is error-prone. Let’s understand it with an example." }, { "code": null, "e": 25955, "s": 25635, "text": "switch (itemCode) {\n case 001 : \n System.out.println(\"It's a laptop!\");\n break;\n case 002 :\n System.out.println(\"It's a desktop!\");\n break;\n case 003 :\n System.out.println(\"It's a mobile phone!\");\n break;\n default :\n System.out.println(\"Unknown device!\");\n}\n" }, { "code": null, "e": 26122, "s": 25955, "text": "The above code works by matching the corresponding case and executing the particular code block. As long as you provide the necessary break statements, it works fine." }, { "code": null, "e": 26190, "s": 26122, "text": "But what happens if we forget any of the required break statements:" }, { "code": null, "e": 26388, "s": 26190, "text": " switch (itemCode) {\n case 001 : \n System.out.println(\"It's a laptop!\");\n // missed out break here \n case 002 :\n System.out.println(\"It's a desktop!\");\n break;\n}\n\n" }, { "code": null, "e": 26576, "s": 26388, "text": "Here, if we pass 001, the first case matches, and the code block executes. But due to missing break, execution falls through and continues for case 002. We get the following wrong output:" }, { "code": null, "e": 26608, "s": 26576, "text": "It's a laptop!\nIt's a desktop!\n" }, { "code": null, "e": 26711, "s": 26608, "text": "Clearly, this is not the intended output. It is a result of accidentally missing-out break statements." }, { "code": null, "e": 26753, "s": 26711, "text": "2. Multiple values per case not supported" }, { "code": null, "e": 26911, "s": 26753, "text": "There may be situations where similar processing is required for multiple case values. But the traditional switch makes to follow the fall through behaviour." }, { "code": null, "e": 26992, "s": 26911, "text": "case 001:\ncase 002:\ncase 003:\nSystem.out.println(\"It's an electronic gadget!\");\n" }, { "code": null, "e": 27047, "s": 26992, "text": "Much improved switch accepts multiple values per case." }, { "code": null, "e": 27129, "s": 27047, "text": "case 001, 002, 003 : \n System.out.println(\"It's an electronic gadget!\");\n\n" }, { "code": null, "e": 27228, "s": 27129, "text": "Enhancements to switch statements were introduced by Java 12 and then further modified by Java 13." }, { "code": null, "e": 27317, "s": 27228, "text": "Let’s dive into the important features of this improved version of the Switch statement." }, { "code": null, "e": 27354, "s": 27317, "text": "1. Supports multiple values per case" }, { "code": null, "e": 27482, "s": 27354, "text": "With multiple values being specified per case, it simplifies the code structure and eliminates the need for using fall through." }, { "code": null, "e": 27564, "s": 27482, "text": "The values need to be separated by commas and break should follow the case block." }, { "code": null, "e": 27786, "s": 27564, "text": "switch (itemCode) {\n case 001, 002, 003 : \n System.out.println(\"It's an electronic gadget!\");\n break;\n \n case 004, 005:\n System.out.println(\"It's a mechanical device!\");\n break;\n}\n" }, { "code": null, "e": 27821, "s": 27786, "text": "2. yield is used to return a value" }, { "code": null, "e": 27908, "s": 27821, "text": "A new keyword yield has been introduced. It returns values from a switch branch only. " }, { "code": null, "e": 27996, "s": 27908, "text": "We don’t need a break after yield as it automatically terminates the switch expression." }, { "code": null, "e": 28099, "s": 27996, "text": "int val = switch (code) {\n case \"x\", \"y\" :\n yield 1;\n case \"z\", \"w\" :\n yield 2;\n}\n" }, { "code": null, "e": 28138, "s": 28099, "text": "3. Switch can be used as an expression" }, { "code": null, "e": 28458, "s": 28138, "text": "The switch can now be used as an expression. This means the switch can now return values based on our input. There is a slight change in switch syntax to accommodate this change. A switch block needs to be delimited by a semicolon. The yield keyword is used to return values. No break required with the yield statement." }, { "code": null, "e": 28530, "s": 28458, "text": "Let’s have a look at a code snippet to understand these changes better." }, { "code": null, "e": 28818, "s": 28530, "text": "String text = switch (itemCode) {\n case 001 : \n yield \"It's a laptop!\";\n case 002 :\n yield \"It's a desktop!\"; \n case 003 :\n yield \"It's a mobile phone!\";\n default :\n throw new IllegalArgumentException(itemCode + \"is an unknown device!\");\n}\n" }, { "code": null, "e": 28857, "s": 28818, "text": "4. Necessary to return value/exception" }, { "code": null, "e": 29147, "s": 28857, "text": "The switch expression is required to specify the handling of all the possible input values. Either we provide all the possible cases or specify the default one. This means, irrespective of the input value, switch expression should always return some value or explicitly throw an exception." }, { "code": null, "e": 29201, "s": 29147, "text": "For instance, if the above code block is changed to –" }, { "code": null, "e": 29494, "s": 29201, "text": "String text = switch (itemCode) {\n case 001 : \n yield \"It's a laptop!\";\n case 002 :\n yield \"It's a desktop!\"; \n case 003 :\n yield \"It's a mobile phone!\";\n // default :\n // throw new IllegalArgumentException(itemCode + \"is an unknown device!\");\n}\n" }, { "code": null, "e": 29603, "s": 29494, "text": "This will result in an error saying that all possible values have not been covered by the switch expression." }, { "code": null, "e": 29626, "s": 29603, "text": "5. Switch with arrows " }, { "code": null, "e": 29758, "s": 29626, "text": "The new arrow ⇾ syntax has been introduced for the switch. It can be used with the switch as an expression as well as a statement. " }, { "code": null, "e": 29855, "s": 29758, "text": "The statements on the right side of an ⇾ are executed if an exact case matches on the left side." }, { "code": null, "e": 29913, "s": 29855, "text": "On the right side of ⇾ we can have any of the following –" }, { "code": null, "e": 29936, "s": 29913, "text": "Statement / expression" }, { "code": null, "e": 29952, "s": 29936, "text": "throw statement" }, { "code": null, "e": 29961, "s": 29952, "text": "{} block" }, { "code": null, "e": 30298, "s": 29961, "text": "The main advantage of this syntax is that we don’t need a break statement to avoid the default fall-through. So the rule is, if we need fall-through, use case: else if not use case ⇾. Also note, for all case branches it should be either case: or case ⇾. It cannot be different or different cases in a switch else it results in an error." }, { "code": null, "e": 30494, "s": 30298, "text": "switch (itemCode) {\n case 001 -> System.out.println(\"It's a laptop!\");\n case 002 -> System.out.println(\"It's a desktop!\");\n case 003,004 -> System.out.println(\"It's a mobile phone!\");\n}\n" }, { "code": null, "e": 30586, "s": 30494, "text": "As we can see in the above code, the syntax can also be used for multiple values per case. " }, { "code": null, "e": 30595, "s": 30586, "text": "6. Scope" }, { "code": null, "e": 30803, "s": 30595, "text": "The variables declared in the traditional switch exists until the end of the switch statement. If we want the variables to have a case level scope, we can use {} introduced by the enhanced switch in Java 13." }, { "code": null, "e": 31054, "s": 30803, "text": "switch (errorCode) {\n case 101: {\n // This variable exists just in this {} block\n int num = 200;\n break;\n }\n case 300: {\n // This is ok, {} block has a separate scope\n int num = 300;\n break;\n }\n}\n" }, { "code": null, "e": 31074, "s": 31054, "text": "7. Preview feature " }, { "code": null, "e": 31333, "s": 31074, "text": "After diving into the features related to the enhanced switch, the point noteworthy is — the enhanced switch functionality is available only as a preview feature in Java 13. This means it is not enabled by default. To use it, we need to explicitly enable it." }, { "code": null, "e": 31385, "s": 31333, "text": "At compile time, add the following params to javac:" }, { "code": null, "e": 31436, "s": 31385, "text": "javac -- release 13 --enable-preview MyClass.java\n" }, { "code": null, "e": 31468, "s": 31436, "text": "At run time, add the following:" }, { "code": null, "e": 31499, "s": 31468, "text": "java --enable-preview MyClass\n" }, { "code": null, "e": 31684, "s": 31499, "text": "The enhanced switch in Java 13 provides a number of impressive features to the traditional switch. However, it is still in the experiment phase and not yet meant for use in production." }, { "code": null, "e": 31702, "s": 31684, "text": "Java-Control-Flow" }, { "code": null, "e": 31707, "s": 31702, "text": "Java" }, { "code": null, "e": 31725, "s": 31707, "text": "Java-Control-Flow" }, { "code": null, "e": 31730, "s": 31725, "text": "Java" }, { "code": null, "e": 31828, "s": 31730, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31843, "s": 31828, "text": "Stream In Java" }, { "code": null, "e": 31864, "s": 31843, "text": "Constructors in Java" }, { "code": null, "e": 31883, "s": 31864, "text": "Exceptions in Java" }, { "code": null, "e": 31913, "s": 31883, "text": "Functional Interfaces in Java" }, { "code": null, "e": 31959, "s": 31913, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 31976, "s": 31959, "text": "Generics in Java" }, { "code": null, "e": 31997, "s": 31976, "text": "Introduction to Java" }, { "code": null, "e": 32040, "s": 31997, "text": "Comparator Interface in Java with Examples" }, { "code": null, "e": 32062, "s": 32040, "text": "PriorityQueue in Java" } ]
How to Read Data from Firebase Firestore in Android? - GeeksforGeeks
17 Jan, 2021 In the previous article, we have seen on How to Add Data to Firebase Firestore in Android. This is the continuation of this series. Now we will see How to Read this added data inside our Firebase Firestore. Now we will move towards the implementation of this reading data in Android Firebase. We will be creating a new screen in the previous application and inside that, we will display our data which we added inside our Firebase Firestore in the RecyclerView. We will read all data from Firebase Firestore inside our app. Step 1: Working with the activity_main.xml file Go to the activity_main.xml file add one more Button for showing the list of all added courses. Below is the code snippet and add the code at last. XML <!--Button for showing the list of added courses--> <Button android:id="@+id/idBtnViewCourses" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="10dp" android:text="View Added Courses" android:textAllCaps="false" /> Now below is the updated code for the activity_main.xml file after adding the above code snippet. XML <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity"> <!--Edittext for getting course Name--> <EditText android:id="@+id/idEdtCourseName" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginStart="10dp" android:layout_marginTop="20dp" android:layout_marginEnd="10dp" android:hint="Course Name" android:importantForAutofill="no" android:inputType="text" /> <!--Edittext for getting course Duration--> <EditText android:id="@+id/idEdtCourseDuration" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginStart="10dp" android:layout_marginTop="20dp" android:layout_marginEnd="10dp" android:hint="Course Duration in min" android:importantForAutofill="no" android:inputType="time" /> <!--Edittext for getting course Description--> <EditText android:id="@+id/idEdtCourseDescription" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginStart="10dp" android:layout_marginTop="20dp" android:layout_marginEnd="10dp" android:hint="Course Description" android:importantForAutofill="no" android:inputType="text" /> <!--Button for adding your course to Firebase--> <Button android:id="@+id/idBtnSubmitCourse" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="10dp" android:text="Submit Course Details" android:textAllCaps="false" /> <!--Button for showing the list of added courses--> <Button android:id="@+id/idBtnViewCourses" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="10dp" android:text="View Added Courses" android:textAllCaps="false" /> </LinearLayout> Step 2: Now we will create new Activity for displaying our data from Firebase Firestore in RecyclerView To create a new Activity we have to navigate to the app > java > your app’s package name > Right click on package name > New > Empty Activity and name your activity as CourseDetails and create new Activity. Make sure to select the empty activity. Step 3: Now we will move towards the implementation of XML in our Course Details activity Navigate to the app > res > layout > activity_course_details.xml and add the below code to it. XML <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".CourseDetails"> <!--Recycler view for displaying our data from Firestore--> <androidx.recyclerview.widget.RecyclerView android:id="@+id/idRVCourses" android:layout_width="match_parent" android:layout_height="match_parent" /> <!--Progress bar for showing loading screen--> <ProgressBar android:id="@+id/idProgressBar" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" /> </RelativeLayout> Step 4: Now we will create a card layout for our item of RecyclerView To create a new item for RecyclerView, navigate to the app > res > layout > Right-click on layout > New > layout resource file and name as course_item.xml and add below code to it. XML <?xml version="1.0" encoding="utf-8"?> <androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:id="@+id/idCVCOurseItem" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="5dp" app:cardCornerRadius="6dp" app:cardElevation="4dp"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="2dp" android:orientation="vertical" android:padding="4dp"> <!--Textview for displaying our Course Name--> <TextView android:id="@+id/idTVCourseName" android:layout_width="match_parent" android:layout_height="wrap_content" android:padding="2dp" android:text="CourseName" android:textColor="@color/purple_500" android:textSize="18sp" android:textStyle="bold" /> <!--Textview for displaying our Course Duration--> <TextView android:id="@+id/idTVCourseDuration" android:layout_width="match_parent" android:layout_height="wrap_content" android:padding="2dp" android:text="Duration" android:textColor="@color/black" /> <!--Textview for displaying our Course Description--> <TextView android:id="@+id/idTVCourseDescription" android:layout_width="match_parent" android:layout_height="wrap_content" android:padding="2dp" android:text="Description" android:textColor="@color/black" /> </LinearLayout> </androidx.cardview.widget.CardView> Step 5: Now we will create our Adapter class which will handle data for our RecyclerView items For creating an Adapter class for our Recycler View, navigate to the app > java > Your app’s package name > Right-click on it and Click > New > Java class and name your class as CourseRVAdapter. After creating this class add the below code to it. Comments are added in the code to know in more detail. Java import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import java.util.ArrayList; public class CourseRVAdapter extends RecyclerView.Adapter<CourseRVAdapter.ViewHolder> { // creating variables for our ArrayList and context private ArrayList<Courses> coursesArrayList; private Context context; // creating constructor for our adapter class public CourseRVAdapter(ArrayList<Courses> coursesArrayList, Context context) { this.coursesArrayList = coursesArrayList; this.context = context; } @NonNull @Override public CourseRVAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { // passing our layout file for displaying our card item return new ViewHolder(LayoutInflater.from(context).inflate(R.layout.course_item, parent, false)); } @Override public void onBindViewHolder(@NonNull CourseRVAdapter.ViewHolder holder, int position) { // setting data to our text views from our modal class. Courses courses = coursesArrayList.get(position); holder.courseNameTV.setText(courses.getCourseName()); holder.courseDurationTV.setText(courses.getCourseDuration()); holder.courseDescTV.setText(courses.getCourseDescription()); } @Override public int getItemCount() { // returning the size of our array list. return coursesArrayList.size(); } class ViewHolder extends RecyclerView.ViewHolder { // creating variables for our text views. private final TextView courseNameTV; private final TextView courseDurationTV; private final TextView courseDescTV; public ViewHolder(@NonNull View itemView) { super(itemView); // initializing our text views. courseNameTV = itemView.findViewById(R.id.idTVCourseName); courseDurationTV = itemView.findViewById(R.id.idTVCourseDuration); courseDescTV = itemView.findViewById(R.id.idTVCourseDescription); } } } Step 6: Working with the CourseDetails.java file After creating a new Adapter class for our RecyclerView, we have to move towards our CourseDetails.java file and add the below code to it. Java import android.os.Bundle; import android.view.View; import android.widget.ProgressBar; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.firebase.firestore.DocumentSnapshot; import com.google.firebase.firestore.FirebaseFirestore; import com.google.firebase.firestore.QuerySnapshot; import java.util.ArrayList; import java.util.List; public class CourseDetails extends AppCompatActivity { // creating variables for our recycler view, // array list, adapter, firebase firestore // and our progress bar. private RecyclerView courseRV; private ArrayList<Courses> coursesArrayList; private CourseRVAdapter courseRVAdapter; private FirebaseFirestore db; ProgressBar loadingPB; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_course_details); // initializing our variables. courseRV = findViewById(R.id.idRVCourses); loadingPB = findViewById(R.id.idProgressBar); // initializing our variable for firebase // firestore and getting its instance. db = FirebaseFirestore.getInstance(); // creating our new array list coursesArrayList = new ArrayList<>(); courseRV.setHasFixedSize(true); courseRV.setLayoutManager(new LinearLayoutManager(this)); // adding our array list to our recycler view adapter class. courseRVAdapter = new CourseRVAdapter(coursesArrayList, this); // setting adapter to our recycler view. courseRV.setAdapter(courseRVAdapter); // below line is use to get the data from Firebase Firestore. // previously we were saving data on a reference of Courses // now we will be getting the data from the same reference. db.collection("Courses").get() .addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() { @Override public void onSuccess(QuerySnapshot queryDocumentSnapshots) { // after getting the data we are calling on success method // and inside this method we are checking if the received // query snapshot is empty or not. if (!queryDocumentSnapshots.isEmpty()) { // if the snapshot is not empty we are // hiding our progress bar and adding // our data in a list. loadingPB.setVisibility(View.GONE); List<DocumentSnapshot> list = queryDocumentSnapshots.getDocuments(); for (DocumentSnapshot d : list) { // after getting this list we are passing // that list to our object class. Courses c = d.toObject(Courses.class); // and we will pass this object class // inside our arraylist which we have // created for recycler view. coursesArrayList.add(c); } // after adding the data to recycler view. // we are calling recycler view notifuDataSetChanged // method to notify that data has been changed in recycler view. courseRVAdapter.notifyDataSetChanged(); } else { // if the snapshot is empty we are displaying a toast message. Toast.makeText(CourseDetails.this, "No data found in Database", Toast.LENGTH_SHORT).show(); } } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { // if we do not get any data or any error we are displaying // a toast message that we do not get any data Toast.makeText(CourseDetails.this, "Fail to get the data.", Toast.LENGTH_SHORT).show(); } }); } } Step 7: Working with the MainActivity.java file In the MainActivity.java file, we have to add an Intent to the CourseDetails.class file. Below is the code snippet to do so. Java // adding onclick listener to view data in new activity viewCoursesBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // opening a new activity on button click Intent i = new Intent(MainActivity.this,CourseDetails.class); startActivity(i); } }); Below is the updated code for the MainActivity.java file. Java import android.content.Intent; import android.os.Bundle; import android.text.TextUtils; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.firebase.firestore.CollectionReference; import com.google.firebase.firestore.DocumentReference; import com.google.firebase.firestore.FirebaseFirestore; public class MainActivity extends AppCompatActivity { // creating variables for our edit text private EditText courseNameEdt, courseDurationEdt, courseDescriptionEdt; // creating variable for button private Button submitCourseBtn, viewCoursesBtn; // creating a strings for storing // our values from edittext fields. private String courseName, courseDuration, courseDescription; // creating a variable // for firebasefirestore. private FirebaseFirestore db; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // getting our instance // from Firebase Firestore. db = FirebaseFirestore.getInstance(); // initializing our edittext and buttons courseNameEdt = findViewById(R.id.idEdtCourseName); courseDescriptionEdt = findViewById(R.id.idEdtCourseDescription); courseDurationEdt = findViewById(R.id.idEdtCourseDuration); submitCourseBtn = findViewById(R.id.idBtnSubmitCourse); viewCoursesBtn = findViewById(R.id.idBtnViewCourses); // adding onclick listener to view data in new activity viewCoursesBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // opening a new activity on button click Intent i = new Intent(MainActivity.this,CourseDetails.class); startActivity(i); } }); // adding on click listener for button submitCourseBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // getting data from edittext fields. courseName = courseNameEdt.getText().toString(); courseDescription = courseDescriptionEdt.getText().toString(); courseDuration = courseDurationEdt.getText().toString(); // validating the text fields if empty or not. if (TextUtils.isEmpty(courseName)) { courseNameEdt.setError("Please enter Course Name"); } else if (TextUtils.isEmpty(courseDescription)) { courseDescriptionEdt.setError("Please enter Course Description"); } else if (TextUtils.isEmpty(courseDuration)) { courseDurationEdt.setError("Please enter Course Duration"); } else { // calling method to add data to Firebase Firestore. addDataToFirestore(courseName, courseDescription, courseDuration); } } }); } private void addDataToFirestore(String courseName, String courseDescription, String courseDuration) { // creating a collection reference // for our Firebase Firetore database. CollectionReference dbCourses = db.collection("Courses"); // adding our data to our courses object class. Courses courses = new Courses(courseName, courseDescription, courseDuration); // below method is use to add data to Firebase Firestore. dbCourses.add(courses).addOnSuccessListener(new OnSuccessListener<DocumentReference>() { @Override public void onSuccess(DocumentReference documentReference) { // after the data addition is successful // we are displaying a success toast message. Toast.makeText(MainActivity.this, "Your Course has been added to Firebase Firestore", Toast.LENGTH_SHORT).show(); } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { // this method is called when the data addition process is failed. // displaying a toast message when data addition is failed. Toast.makeText(MainActivity.this, "Fail to add course \n" + e, Toast.LENGTH_SHORT).show(); } }); } } After completing this process we have to add the data from our app in Firebase Console and after that click on View Added Courses button you will get to see the list of courses that we have added inside our Firebase Console. Below is the image of how our Firebase Firestore database will look like for only one recycler item. After completing this Run your app and see the output of the code. android Technical Scripter 2020 Android Java Technical Scripter 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? Retrofit with Kotlin Coroutine in Android How to Post Data to API using Retrofit in Android? Arrays in Java Split() String method in Java with examples For-each loop in Java Object Oriented Programming (OOPs) Concept in Java Reverse a string in Java
[ { "code": null, "e": 26480, "s": 26449, "text": " \n17 Jan, 2021\n" }, { "code": null, "e": 26774, "s": 26480, "text": "In the previous article, we have seen on How to Add Data to Firebase Firestore in Android. This is the continuation of this series. Now we will see How to Read this added data inside our Firebase Firestore. Now we will move towards the implementation of this reading data in Android Firebase. " }, { "code": null, "e": 27006, "s": 26774, "text": "We will be creating a new screen in the previous application and inside that, we will display our data which we added inside our Firebase Firestore in the RecyclerView. We will read all data from Firebase Firestore inside our app. " }, { "code": null, "e": 27054, "s": 27006, "text": "Step 1: Working with the activity_main.xml file" }, { "code": null, "e": 27203, "s": 27054, "text": "Go to the activity_main.xml file add one more Button for showing the list of all added courses. Below is the code snippet and add the code at last. " }, { "code": null, "e": 27207, "s": 27203, "text": "XML" }, { "code": "\n\n\n\n\n\n\n<!--Button for showing the list of added courses-->\n<Button\n android:id=\"@+id/idBtnViewCourses\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:layout_margin=\"10dp\"\n android:text=\"View Added Courses\"\n android:textAllCaps=\"false\" />\n\n\n\n\n\n", "e": 27504, "s": 27217, "text": null }, { "code": null, "e": 27602, "s": 27504, "text": "Now below is the updated code for the activity_main.xml file after adding the above code snippet." }, { "code": null, "e": 27606, "s": 27602, "text": "XML" }, { "code": "\n\n\n\n\n\n\n<?xml version=\"1.0\" encoding=\"utf-8\"?> \n<LinearLayout \n xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:orientation=\"vertical\"\n tools:context=\".MainActivity\"> \n \n <!--Edittext for getting course Name-->\n <EditText\n android:id=\"@+id/idEdtCourseName\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:layout_marginStart=\"10dp\"\n android:layout_marginTop=\"20dp\"\n android:layout_marginEnd=\"10dp\"\n android:hint=\"Course Name\"\n android:importantForAutofill=\"no\"\n android:inputType=\"text\" /> \n \n <!--Edittext for getting course Duration-->\n <EditText\n android:id=\"@+id/idEdtCourseDuration\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:layout_marginStart=\"10dp\"\n android:layout_marginTop=\"20dp\"\n android:layout_marginEnd=\"10dp\"\n android:hint=\"Course Duration in min\"\n android:importantForAutofill=\"no\"\n android:inputType=\"time\" /> \n \n <!--Edittext for getting course Description-->\n <EditText\n android:id=\"@+id/idEdtCourseDescription\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:layout_marginStart=\"10dp\"\n android:layout_marginTop=\"20dp\"\n android:layout_marginEnd=\"10dp\"\n android:hint=\"Course Description\"\n android:importantForAutofill=\"no\"\n android:inputType=\"text\" /> \n \n <!--Button for adding your course to Firebase-->\n <Button\n android:id=\"@+id/idBtnSubmitCourse\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:layout_margin=\"10dp\"\n android:text=\"Submit Course Details\"\n android:textAllCaps=\"false\" /> \n \n <!--Button for showing the list of added courses-->\n <Button\n android:id=\"@+id/idBtnViewCourses\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:layout_margin=\"10dp\"\n android:text=\"View Added Courses\"\n android:textAllCaps=\"false\" /> \n \n</LinearLayout>\n\n\n\n\n\n", "e": 29938, "s": 27616, "text": null }, { "code": null, "e": 30042, "s": 29938, "text": "Step 2: Now we will create new Activity for displaying our data from Firebase Firestore in RecyclerView" }, { "code": null, "e": 30290, "s": 30042, "text": "To create a new Activity we have to navigate to the app > java > your app’s package name > Right click on package name > New > Empty Activity and name your activity as CourseDetails and create new Activity. Make sure to select the empty activity. " }, { "code": null, "e": 30380, "s": 30290, "text": "Step 3: Now we will move towards the implementation of XML in our Course Details activity" }, { "code": null, "e": 30476, "s": 30380, "text": "Navigate to the app > res > layout > activity_course_details.xml and add the below code to it. " }, { "code": null, "e": 30480, "s": 30476, "text": "XML" }, { "code": "\n\n\n\n\n\n\n<?xml version=\"1.0\" encoding=\"utf-8\"?> \n<RelativeLayout \n xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n tools:context=\".CourseDetails\"> \n \n <!--Recycler view for displaying \n our data from Firestore-->\n <androidx.recyclerview.widget.RecyclerView\n android:id=\"@+id/idRVCourses\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\" /> \n \n <!--Progress bar for showing loading screen-->\n <ProgressBar\n android:id=\"@+id/idProgressBar\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerInParent=\"true\" /> \n \n</RelativeLayout>\n\n\n\n\n\n", "e": 31320, "s": 30490, "text": null }, { "code": null, "e": 31390, "s": 31320, "text": "Step 4: Now we will create a card layout for our item of RecyclerView" }, { "code": null, "e": 31572, "s": 31390, "text": "To create a new item for RecyclerView, navigate to the app > res > layout > Right-click on layout > New > layout resource file and name as course_item.xml and add below code to it. " }, { "code": null, "e": 31576, "s": 31572, "text": "XML" }, { "code": "\n\n\n\n\n\n\n<?xml version=\"1.0\" encoding=\"utf-8\"?> \n<androidx.cardview.widget.CardView \n xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:app=\"http://schemas.android.com/apk/res-auto\"\n android:id=\"@+id/idCVCOurseItem\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:layout_margin=\"5dp\"\n app:cardCornerRadius=\"6dp\"\n app:cardElevation=\"4dp\"> \n \n <LinearLayout\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:layout_margin=\"2dp\"\n android:orientation=\"vertical\"\n android:padding=\"4dp\"> \n \n <!--Textview for displaying our Course Name-->\n <TextView\n android:id=\"@+id/idTVCourseName\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:padding=\"2dp\"\n android:text=\"CourseName\"\n android:textColor=\"@color/purple_500\"\n android:textSize=\"18sp\"\n android:textStyle=\"bold\" /> \n \n <!--Textview for displaying our Course Duration-->\n <TextView\n android:id=\"@+id/idTVCourseDuration\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:padding=\"2dp\"\n android:text=\"Duration\"\n android:textColor=\"@color/black\" /> \n \n <!--Textview for displaying our Course Description-->\n <TextView\n android:id=\"@+id/idTVCourseDescription\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:padding=\"2dp\"\n android:text=\"Description\"\n android:textColor=\"@color/black\" /> \n \n </LinearLayout> \n \n</androidx.cardview.widget.CardView>\n\n\n\n\n\n", "e": 33426, "s": 31586, "text": null }, { "code": null, "e": 33521, "s": 33426, "text": "Step 5: Now we will create our Adapter class which will handle data for our RecyclerView items" }, { "code": null, "e": 33824, "s": 33521, "text": "For creating an Adapter class for our Recycler View, navigate to the app > java > Your app’s package name > Right-click on it and Click > New > Java class and name your class as CourseRVAdapter. After creating this class add the below code to it. Comments are added in the code to know in more detail. " }, { "code": null, "e": 33829, "s": 33824, "text": "Java" }, { "code": "\n\n\n\n\n\n\nimport android.content.Context; \nimport android.view.LayoutInflater; \nimport android.view.View; \nimport android.view.ViewGroup; \nimport android.widget.TextView; \n \nimport androidx.annotation.NonNull; \nimport androidx.recyclerview.widget.RecyclerView; \n \nimport java.util.ArrayList; \n \npublic class CourseRVAdapter extends RecyclerView.Adapter<CourseRVAdapter.ViewHolder> { \n // creating variables for our ArrayList and context \n private ArrayList<Courses> coursesArrayList; \n private Context context; \n \n // creating constructor for our adapter class \n public CourseRVAdapter(ArrayList<Courses> coursesArrayList, Context context) { \n this.coursesArrayList = coursesArrayList; \n this.context = context; \n } \n \n @NonNull\n @Override\n public CourseRVAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { \n // passing our layout file for displaying our card item \n return new ViewHolder(LayoutInflater.from(context).inflate(R.layout.course_item, parent, false)); \n } \n \n @Override\n public void onBindViewHolder(@NonNull CourseRVAdapter.ViewHolder holder, int position) { \n // setting data to our text views from our modal class. \n Courses courses = coursesArrayList.get(position); \n holder.courseNameTV.setText(courses.getCourseName()); \n holder.courseDurationTV.setText(courses.getCourseDuration()); \n holder.courseDescTV.setText(courses.getCourseDescription()); \n } \n \n @Override\n public int getItemCount() { \n // returning the size of our array list. \n return coursesArrayList.size(); \n } \n \n class ViewHolder extends RecyclerView.ViewHolder { \n // creating variables for our text views. \n private final TextView courseNameTV; \n private final TextView courseDurationTV; \n private final TextView courseDescTV; \n \n public ViewHolder(@NonNull View itemView) { \n super(itemView); \n // initializing our text views. \n courseNameTV = itemView.findViewById(R.id.idTVCourseName); \n courseDurationTV = itemView.findViewById(R.id.idTVCourseDuration); \n courseDescTV = itemView.findViewById(R.id.idTVCourseDescription); \n } \n } \n}\n\n\n\n\n\n", "e": 36133, "s": 33839, "text": null }, { "code": null, "e": 36182, "s": 36133, "text": "Step 6: Working with the CourseDetails.java file" }, { "code": null, "e": 36322, "s": 36182, "text": "After creating a new Adapter class for our RecyclerView, we have to move towards our CourseDetails.java file and add the below code to it. " }, { "code": null, "e": 36327, "s": 36322, "text": "Java" }, { "code": "\n\n\n\n\n\n\nimport android.os.Bundle; \nimport android.view.View; \nimport android.widget.ProgressBar; \nimport android.widget.Toast; \n \nimport androidx.annotation.NonNull; \nimport androidx.appcompat.app.AppCompatActivity; \nimport androidx.recyclerview.widget.LinearLayoutManager; \nimport androidx.recyclerview.widget.RecyclerView; \n \nimport com.google.android.gms.tasks.OnFailureListener; \nimport com.google.android.gms.tasks.OnSuccessListener; \nimport com.google.firebase.firestore.DocumentSnapshot; \nimport com.google.firebase.firestore.FirebaseFirestore; \nimport com.google.firebase.firestore.QuerySnapshot; \n \nimport java.util.ArrayList; \nimport java.util.List; \n \npublic class CourseDetails extends AppCompatActivity { \n \n // creating variables for our recycler view, \n // array list, adapter, firebase firestore \n // and our progress bar. \n private RecyclerView courseRV; \n private ArrayList<Courses> coursesArrayList; \n private CourseRVAdapter courseRVAdapter; \n private FirebaseFirestore db; \n ProgressBar loadingPB; \n \n @Override\n protected void onCreate(Bundle savedInstanceState) { \n super.onCreate(savedInstanceState); \n setContentView(R.layout.activity_course_details); \n \n // initializing our variables. \n courseRV = findViewById(R.id.idRVCourses); \n loadingPB = findViewById(R.id.idProgressBar); \n \n // initializing our variable for firebase \n // firestore and getting its instance. \n db = FirebaseFirestore.getInstance(); \n \n // creating our new array list \n coursesArrayList = new ArrayList<>(); \n courseRV.setHasFixedSize(true); \n courseRV.setLayoutManager(new LinearLayoutManager(this)); \n \n // adding our array list to our recycler view adapter class. \n courseRVAdapter = new CourseRVAdapter(coursesArrayList, this); \n \n // setting adapter to our recycler view. \n courseRV.setAdapter(courseRVAdapter); \n \n // below line is use to get the data from Firebase Firestore. \n // previously we were saving data on a reference of Courses \n // now we will be getting the data from the same reference. \n db.collection(\"Courses\").get() \n .addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() { \n @Override\n public void onSuccess(QuerySnapshot queryDocumentSnapshots) { \n // after getting the data we are calling on success method \n // and inside this method we are checking if the received \n // query snapshot is empty or not. \n if (!queryDocumentSnapshots.isEmpty()) { \n // if the snapshot is not empty we are \n // hiding our progress bar and adding \n // our data in a list. \n loadingPB.setVisibility(View.GONE); \n List<DocumentSnapshot> list = queryDocumentSnapshots.getDocuments(); \n for (DocumentSnapshot d : list) { \n // after getting this list we are passing \n // that list to our object class. \n Courses c = d.toObject(Courses.class); \n \n // and we will pass this object class \n // inside our arraylist which we have \n // created for recycler view. \n coursesArrayList.add(c); \n } \n // after adding the data to recycler view. \n // we are calling recycler view notifuDataSetChanged \n // method to notify that data has been changed in recycler view. \n courseRVAdapter.notifyDataSetChanged(); \n } else { \n // if the snapshot is empty we are displaying a toast message. \n Toast.makeText(CourseDetails.this, \"No data found in Database\", Toast.LENGTH_SHORT).show(); \n } \n } \n }).addOnFailureListener(new OnFailureListener() { \n @Override\n public void onFailure(@NonNull Exception e) { \n // if we do not get any data or any error we are displaying \n // a toast message that we do not get any data \n Toast.makeText(CourseDetails.this, \"Fail to get the data.\", Toast.LENGTH_SHORT).show(); \n } \n }); \n } \n}\n\n\n\n\n\n", "e": 41109, "s": 36337, "text": null }, { "code": null, "e": 41157, "s": 41109, "text": "Step 7: Working with the MainActivity.java file" }, { "code": null, "e": 41282, "s": 41157, "text": "In the MainActivity.java file, we have to add an Intent to the CourseDetails.class file. Below is the code snippet to do so." }, { "code": null, "e": 41287, "s": 41282, "text": "Java" }, { "code": "\n\n\n\n\n\n\n// adding onclick listener to view data in new activity \nviewCoursesBtn.setOnClickListener(new View.OnClickListener() { \n @Override\n public void onClick(View v) { \n // opening a new activity on button click \n Intent i = new Intent(MainActivity.this,CourseDetails.class); \n startActivity(i); \n } \n });\n\n\n\n\n\n", "e": 41691, "s": 41297, "text": null }, { "code": null, "e": 41749, "s": 41691, "text": "Below is the updated code for the MainActivity.java file." }, { "code": null, "e": 41754, "s": 41749, "text": "Java" }, { "code": "\n\n\n\n\n\n\nimport android.content.Intent; \nimport android.os.Bundle; \nimport android.text.TextUtils; \nimport android.view.View; \nimport android.widget.Button; \nimport android.widget.EditText; \nimport android.widget.Toast; \n \nimport androidx.annotation.NonNull; \nimport androidx.appcompat.app.AppCompatActivity; \n \nimport com.google.android.gms.tasks.OnFailureListener; \nimport com.google.android.gms.tasks.OnSuccessListener; \nimport com.google.firebase.firestore.CollectionReference; \nimport com.google.firebase.firestore.DocumentReference; \nimport com.google.firebase.firestore.FirebaseFirestore; \n \npublic class MainActivity extends AppCompatActivity { \n \n // creating variables for our edit text \n private EditText courseNameEdt, courseDurationEdt, courseDescriptionEdt; \n \n // creating variable for button \n private Button submitCourseBtn, viewCoursesBtn; \n \n // creating a strings for storing \n // our values from edittext fields. \n private String courseName, courseDuration, courseDescription; \n \n // creating a variable \n // for firebasefirestore. \n private FirebaseFirestore db; \n \n @Override\n protected void onCreate(Bundle savedInstanceState) { \n super.onCreate(savedInstanceState); \n setContentView(R.layout.activity_main); \n \n // getting our instance \n // from Firebase Firestore. \n db = FirebaseFirestore.getInstance(); \n \n // initializing our edittext and buttons \n courseNameEdt = findViewById(R.id.idEdtCourseName); \n courseDescriptionEdt = findViewById(R.id.idEdtCourseDescription); \n courseDurationEdt = findViewById(R.id.idEdtCourseDuration); \n submitCourseBtn = findViewById(R.id.idBtnSubmitCourse); \n viewCoursesBtn = findViewById(R.id.idBtnViewCourses); \n \n // adding onclick listener to view data in new activity \n viewCoursesBtn.setOnClickListener(new View.OnClickListener() { \n @Override\n public void onClick(View v) { \n // opening a new activity on button click \n Intent i = new Intent(MainActivity.this,CourseDetails.class); \n startActivity(i); \n } \n }); \n \n // adding on click listener for button \n submitCourseBtn.setOnClickListener(new View.OnClickListener() { \n @Override\n public void onClick(View v) { \n \n // getting data from edittext fields. \n courseName = courseNameEdt.getText().toString(); \n courseDescription = courseDescriptionEdt.getText().toString(); \n courseDuration = courseDurationEdt.getText().toString(); \n \n // validating the text fields if empty or not. \n if (TextUtils.isEmpty(courseName)) { \n courseNameEdt.setError(\"Please enter Course Name\"); \n } else if (TextUtils.isEmpty(courseDescription)) { \n courseDescriptionEdt.setError(\"Please enter Course Description\"); \n } else if (TextUtils.isEmpty(courseDuration)) { \n courseDurationEdt.setError(\"Please enter Course Duration\"); \n } else { \n // calling method to add data to Firebase Firestore. \n addDataToFirestore(courseName, courseDescription, courseDuration); \n } \n } \n }); \n } \n \n private void addDataToFirestore(String courseName, String courseDescription, String courseDuration) { \n \n // creating a collection reference \n // for our Firebase Firetore database. \n CollectionReference dbCourses = db.collection(\"Courses\"); \n \n // adding our data to our courses object class. \n Courses courses = new Courses(courseName, courseDescription, courseDuration); \n \n // below method is use to add data to Firebase Firestore. \n dbCourses.add(courses).addOnSuccessListener(new OnSuccessListener<DocumentReference>() { \n @Override\n public void onSuccess(DocumentReference documentReference) { \n // after the data addition is successful \n // we are displaying a success toast message. \n Toast.makeText(MainActivity.this, \"Your Course has been added to Firebase Firestore\", Toast.LENGTH_SHORT).show(); \n } \n }).addOnFailureListener(new OnFailureListener() { \n @Override\n public void onFailure(@NonNull Exception e) { \n // this method is called when the data addition process is failed. \n // displaying a toast message when data addition is failed. \n Toast.makeText(MainActivity.this, \"Fail to add course \\n\" + e, Toast.LENGTH_SHORT).show(); \n } \n }); \n } \n}\n\n\n\n\n\n", "e": 46572, "s": 41764, "text": null }, { "code": null, "e": 46899, "s": 46572, "text": "After completing this process we have to add the data from our app in Firebase Console and after that click on View Added Courses button you will get to see the list of courses that we have added inside our Firebase Console. Below is the image of how our Firebase Firestore database will look like for only one recycler item. " }, { "code": null, "e": 46966, "s": 46899, "text": "After completing this Run your app and see the output of the code." }, { "code": null, "e": 46976, "s": 46966, "text": "\nandroid\n" }, { "code": null, "e": 47002, "s": 46976, "text": "\nTechnical Scripter 2020\n" }, { "code": null, "e": 47012, "s": 47002, "text": "\nAndroid\n" }, { "code": null, "e": 47019, "s": 47012, "text": "\nJava\n" }, { "code": null, "e": 47040, "s": 47019, "text": "\nTechnical Scripter\n" }, { "code": null, "e": 47245, "s": 47040, "text": "Writing code in comment? \n Please use ide.geeksforgeeks.org, \n generate link and share the link here.\n " }, { "code": null, "e": 47283, "s": 47245, "text": "Resource Raw Folder in Android Studio" }, { "code": null, "e": 47322, "s": 47283, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 47372, "s": 47322, "text": "How to Read Data from SQLite Database in Android?" }, { "code": null, "e": 47414, "s": 47372, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 47465, "s": 47414, "text": "How to Post Data to API using Retrofit in Android?" }, { "code": null, "e": 47480, "s": 47465, "text": "Arrays in Java" }, { "code": null, "e": 47524, "s": 47480, "text": "Split() String method in Java with examples" }, { "code": null, "e": 47546, "s": 47524, "text": "For-each loop in Java" }, { "code": null, "e": 47597, "s": 47546, "text": "Object Oriented Programming (OOPs) Concept in Java" } ]
How to create a comment in a pull request using ocktokit? - GeeksforGeeks
13 Dec, 2021 Introduction: The Octokit client can be used to send requests to GitHub’s REST API and queries to GitHub’s GraphQL API. The octokit package integrates the three main Octokit libraries: API client (REST API requests, GraphQL API queries, Authentication)App client (GitHub App & installations, Webhooks, OAuth)Action client (Pre-authenticated API client for single repository). API client (REST API requests, GraphQL API queries, Authentication) App client (GitHub App & installations, Webhooks, OAuth) Action client (Pre-authenticated API client for single repository). Approach: We are going to create a script using Github’s API Client octokit/rest.js through which we will comment on a pull request as soon as it opened . Below is the step-by-step implementation of the above approach. Step 1: Initialize a node project First of all the create a root folder named as GFG: mkdir GFG Navigate into the GFG folder: cd GFG Initialize this folder as a node repository: npm init After this, you will find a package.json file at the root of your project. Step 2: Create a new Github action Create a new file named as action.yml with the below content: name: 'GeeksForGeeks' description: 'Say "GeeksForGeeks" to new pull requests' author: '[GFG]' inputs: GITHUB_TOKEN: description: 'GitHub token' required: true runs: using: 'node12' main: 'dist/index.js' An action is declared above with the name GeeksForGeeks taking one input GITHUB_TOKEN which should run in node12 version and the main entry point is set to ‘dist/index.js’. Step3: Create the base file for the app to run First of all install two dependencies to use ocktokit and context payloads of pull request. npm install @actions/core @actions/github Create a src directory. Then create an action.js file in src directory with the following content: Javascript const core = require('@actions/core');const github = require('@actions/github');const { context } = require('@actions/github')const GITHUB_TOKEN = core.getInput('GITHUB_TOKEN');const octokit = github.getOctokit(GITHUB_TOKEN); const { pull_request } = context.payload; async function run() { await octokit.rest.issues.createComment({ ...context.repo, issue_number: pull_request.number, body: 'Thank you for submitting a pull request! We will try to review this as soon as we can.' });} run(); What we are doing above is: After the two dependencies are installed they are imported into the file. const core = require('@actions/core'); const github = require('@actions/github'); In each function which requires access to the github api, use the following to create octokit. const GITHUB_TOKEN = core.getInput('GITHUB_TOKEN'); const octokit = github.getOctokit(GITHUB_TOKEN); Now as we have got the octokit instance, we can now create comment using Github API’s client ocktokit. octokit.rest.issues.createComment({ owner, repo, issue_number, body, }); Step 4: Building src/action.js with Vercel’s ncc While we’re not yet doing anything inside of our src/action.js that requires anything more than node to run, we’re going to set up our Action to build and compile into a dist folder which is what our Action will use to actually run the code. If you remember, we set the main attribute inside of action.yml to dist/index.js! To start, we can first install ncc from Vercel, which will take our scripts and dependencies and package it all up in one file for us. In your terminal, install the file with: npm install @vercel/ncc Next, inside of our package.json file, under the scripts object, let’s add a new script: "scripts": { "build": "ncc build src/action.js -o dist" ..., }, This sets up a new script so any time we run the build command, it will tell ncc to build our Action script and output it into the dist folder. We can try it out by running: npm run build And once it’s finished, you should now see a dist folder at the root of your project with an index.js file inside of it. If you look inside it, you might notice a bunch of weird-looking code. ncc uses webpack to compile our script so that it’s able to be used as a module, allowing different processes to understand it. The reason we’re compiling our script is when GitHub tries to use our Action from another repository, it doesn’t have all of the dependencies available. Packaging it up in a single file allows our script to work with just that one file! Output: rkbhola5 GitHub JavaScript-Questions NodeJS-Questions JavaScript Node.js Web Technologies 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? Installation of Node.js on Linux How to update Node.js and NPM to next version ? Node.js fs.readFileSync() Method Node.js fs.writeFile() Method Node.js fs.readFile() Method
[ { "code": null, "e": 26915, "s": 26887, "text": "\n13 Dec, 2021" }, { "code": null, "e": 27100, "s": 26915, "text": "Introduction: The Octokit client can be used to send requests to GitHub’s REST API and queries to GitHub’s GraphQL API. The octokit package integrates the three main Octokit libraries:" }, { "code": null, "e": 27291, "s": 27100, "text": "API client (REST API requests, GraphQL API queries, Authentication)App client (GitHub App & installations, Webhooks, OAuth)Action client (Pre-authenticated API client for single repository)." }, { "code": null, "e": 27359, "s": 27291, "text": "API client (REST API requests, GraphQL API queries, Authentication)" }, { "code": null, "e": 27416, "s": 27359, "text": "App client (GitHub App & installations, Webhooks, OAuth)" }, { "code": null, "e": 27484, "s": 27416, "text": "Action client (Pre-authenticated API client for single repository)." }, { "code": null, "e": 27640, "s": 27484, "text": "Approach: We are going to create a script using Github’s API Client octokit/rest.js through which we will comment on a pull request as soon as it opened ." }, { "code": null, "e": 27704, "s": 27640, "text": "Below is the step-by-step implementation of the above approach." }, { "code": null, "e": 27741, "s": 27706, "text": "Step 1: Initialize a node project " }, { "code": null, "e": 27793, "s": 27741, "text": "First of all the create a root folder named as GFG:" }, { "code": null, "e": 27803, "s": 27793, "text": "mkdir GFG" }, { "code": null, "e": 27833, "s": 27803, "text": "Navigate into the GFG folder:" }, { "code": null, "e": 27840, "s": 27833, "text": "cd GFG" }, { "code": null, "e": 27885, "s": 27840, "text": "Initialize this folder as a node repository:" }, { "code": null, "e": 27894, "s": 27885, "text": "npm init" }, { "code": null, "e": 27969, "s": 27894, "text": "After this, you will find a package.json file at the root of your project." }, { "code": null, "e": 28004, "s": 27969, "text": "Step 2: Create a new Github action" }, { "code": null, "e": 28066, "s": 28004, "text": "Create a new file named as action.yml with the below content:" }, { "code": null, "e": 28286, "s": 28066, "text": "name: 'GeeksForGeeks'\ndescription: 'Say \"GeeksForGeeks\" to new pull requests'\nauthor: '[GFG]'\n\ninputs:\n GITHUB_TOKEN:\n description: 'GitHub token'\n required: true\n\nruns:\n using: 'node12'\n main: 'dist/index.js' " }, { "code": null, "e": 28459, "s": 28286, "text": "An action is declared above with the name GeeksForGeeks taking one input GITHUB_TOKEN which should run in node12 version and the main entry point is set to ‘dist/index.js’." }, { "code": null, "e": 28506, "s": 28459, "text": "Step3: Create the base file for the app to run" }, { "code": null, "e": 28598, "s": 28506, "text": "First of all install two dependencies to use ocktokit and context payloads of pull request." }, { "code": null, "e": 28640, "s": 28598, "text": "npm install @actions/core @actions/github" }, { "code": null, "e": 28739, "s": 28640, "text": "Create a src directory. Then create an action.js file in src directory with the following content:" }, { "code": null, "e": 28750, "s": 28739, "text": "Javascript" }, { "code": "const core = require('@actions/core');const github = require('@actions/github');const { context } = require('@actions/github')const GITHUB_TOKEN = core.getInput('GITHUB_TOKEN');const octokit = github.getOctokit(GITHUB_TOKEN); const { pull_request } = context.payload; async function run() { await octokit.rest.issues.createComment({ ...context.repo, issue_number: pull_request.number, body: 'Thank you for submitting a pull request! We will try to review this as soon as we can.' });} run();", "e": 29265, "s": 28750, "text": null }, { "code": null, "e": 29293, "s": 29265, "text": "What we are doing above is:" }, { "code": null, "e": 29367, "s": 29293, "text": "After the two dependencies are installed they are imported into the file." }, { "code": null, "e": 29449, "s": 29367, "text": "const core = require('@actions/core');\nconst github = require('@actions/github');" }, { "code": null, "e": 29544, "s": 29449, "text": "In each function which requires access to the github api, use the following to create octokit." }, { "code": null, "e": 29645, "s": 29544, "text": "const GITHUB_TOKEN = core.getInput('GITHUB_TOKEN');\nconst octokit = github.getOctokit(GITHUB_TOKEN);" }, { "code": null, "e": 29748, "s": 29645, "text": "Now as we have got the octokit instance, we can now create comment using Github API’s client ocktokit." }, { "code": null, "e": 29829, "s": 29748, "text": "octokit.rest.issues.createComment({\n owner,\n repo,\n issue_number,\n body,\n});" }, { "code": null, "e": 29878, "s": 29829, "text": "Step 4: Building src/action.js with Vercel’s ncc" }, { "code": null, "e": 30120, "s": 29878, "text": "While we’re not yet doing anything inside of our src/action.js that requires anything more than node to run, we’re going to set up our Action to build and compile into a dist folder which is what our Action will use to actually run the code." }, { "code": null, "e": 30202, "s": 30120, "text": "If you remember, we set the main attribute inside of action.yml to dist/index.js!" }, { "code": null, "e": 30337, "s": 30202, "text": "To start, we can first install ncc from Vercel, which will take our scripts and dependencies and package it all up in one file for us." }, { "code": null, "e": 30378, "s": 30337, "text": "In your terminal, install the file with:" }, { "code": null, "e": 30402, "s": 30378, "text": "npm install @vercel/ncc" }, { "code": null, "e": 30491, "s": 30402, "text": "Next, inside of our package.json file, under the scripts object, let’s add a new script:" }, { "code": null, "e": 30557, "s": 30491, "text": "\"scripts\": {\n \"build\": \"ncc build src/action.js -o dist\"\n ...,\n}," }, { "code": null, "e": 30701, "s": 30557, "text": "This sets up a new script so any time we run the build command, it will tell ncc to build our Action script and output it into the dist folder." }, { "code": null, "e": 30731, "s": 30701, "text": "We can try it out by running:" }, { "code": null, "e": 30745, "s": 30731, "text": "npm run build" }, { "code": null, "e": 31302, "s": 30745, "text": "And once it’s finished, you should now see a dist folder at the root of your project with an index.js file inside of it. If you look inside it, you might notice a bunch of weird-looking code. ncc uses webpack to compile our script so that it’s able to be used as a module, allowing different processes to understand it. The reason we’re compiling our script is when GitHub tries to use our Action from another repository, it doesn’t have all of the dependencies available. Packaging it up in a single file allows our script to work with just that one file!" }, { "code": null, "e": 31310, "s": 31302, "text": "Output:" }, { "code": null, "e": 31319, "s": 31310, "text": "rkbhola5" }, { "code": null, "e": 31326, "s": 31319, "text": "GitHub" }, { "code": null, "e": 31347, "s": 31326, "text": "JavaScript-Questions" }, { "code": null, "e": 31364, "s": 31347, "text": "NodeJS-Questions" }, { "code": null, "e": 31375, "s": 31364, "text": "JavaScript" }, { "code": null, "e": 31383, "s": 31375, "text": "Node.js" }, { "code": null, "e": 31400, "s": 31383, "text": "Web Technologies" }, { "code": null, "e": 31498, "s": 31400, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31538, "s": 31498, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 31599, "s": 31538, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 31640, "s": 31599, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 31662, "s": 31640, "text": "JavaScript | Promises" }, { "code": null, "e": 31716, "s": 31662, "text": "How to get character array from string in JavaScript?" }, { "code": null, "e": 31749, "s": 31716, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 31797, "s": 31749, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 31830, "s": 31797, "text": "Node.js fs.readFileSync() Method" }, { "code": null, "e": 31860, "s": 31830, "text": "Node.js fs.writeFile() Method" } ]
Explaining Your Machine Learning Models with SHAP and LIME! | by David Hundley | Towards Data Science
Hello there all! Welcome back again to another data science quick tip. This particular post is most interesting for me not only because this is the most complex subject we’ve tackled to date, but it’s also one that I just spent the last few hours learning myself. And of course, what better way to learn than to figure out how to teach it to the masses? Before getting into it, I’ve uploaded all the work shown in this post to a singular Jupyter notebook. You can find it at my personal GitHub if you’d like to follow along more closely. So even though this is a very complex topic behind the scenes, I’m going to intentionally dial it down as much as possible for the widest possible audience. Even though this is ultimately a post designed for data science practitioners, I think it’s equally important for any business person to understand why they should care about this topic. Prior to jumping into how to calculate/visualize these values, let’s build some intuition on why would we would even care about this topic. If you’re familiar at all with machine learning in general, you know that you pop some data into a predictive model and that it produces an outputted prediction on the other side. But let’s be honest: do you know what’s really going on inside in that model? Remember, we’re talking about algorithms doing a lot of fancy math under the hood. In reality, this is probably what your ML model looks like to you right now: You really have no idea what’s going on in that black box. The math totally obscures how important those features are in your model. So what if Features 1 and 2 are carrying all the weight and that Features 3 and 4 are not adding any value at all to the model? What you’d prefer to see is something that looks more like this: Okay, we’re obviously using layman’s terms in our example here. But this stuff is important because if your models are relying on one 1 or 2 features to be doing all the predictive power, that might indicate something is wrong. It also might indicate that you’re using some sort of feature that may be considered to be morally incorrect. For example, many companies today will steer clear of using things like gender or ethnicity within their models because they tend to produce a lot of undesired bias in a model. Understanding these concepts always makes more sense through a tangible example, so we’re going to return to the dataset we’ve been using the last few posts to concretely demo both SHAP and LIME: the Titanic dataset. Alright, so in the last few post where we’ve used the Titanic dataset, we created models that were pretty poor since our focus was more on learning a new skill. In order to effectively demo both SHAP and LIME, we really need a model that shows some level of “trying” (?) so that we can see how ML explainability will play out. Now, I’m not going to spend time in this post showing you all my code for that data cleansing and modeling piece (which you can definitely find in my GitHub here), but I’ll summarize quickly the features that go into producing the end model. PClass: Notes the ticket class the person boarded the ship with. (Either 1st, 2nd, or 3rd.) Age Bins: Based on the person’s age, they are segmented into general people groups. These groups include child, teen, young adult, adult, elder, and unknown. Sex (Gender): Notes whether the person is male or female. Cabin Section: If the person had a cabin, I pulled out what section they might be in. These can either be A, B, C, or no cabin. Embarked: Notes one of three locations from which the person originally departed. SibSp (Sibling / Spouse): Notes how many siblings and/or spouses the person had onboard the ship with them. Parch (Parent / Child): Notes how many parents / children the person had onboard the ship with them. For the actual model itself, I’m choosing to use a simple Random Forest Classifier from Scikit-Learn. Splitting the data into training and validation sets, I get the following metrics with the validation set: The metrics aren’t exactly great, but that’s fine for our learning here. At least we’ll get to see in the next section how important these features necessarily are. Let’s move on! At this point, we currently have no idea how our Random Forest model is using the features to make its predictions. I’m going to wager a guess that Sex and Age Bin are influential factors, but we don’t know that quite yet. This is where smart people developed complex algorithms based on game theory to generate these things to better explain our current black box. Of course, I’m referring to SHAP and LIME. Now, I’m going to be 100% honest: I’m not very familiar with how these algorithms work under the hood, so I’m not even going to attempt to do that in this post. Instead, I’ll point you to this post about SHAP and this other post about LIME. Just like Scikit-Learn abstracts away the underlying algorithms for our Random Forest classifier, there are some neat Python libraries that we’ll use that abstract away the inner workings of both SHAP and LIME. To use those, all you need to do is a simple pip install for both: pip install shappip install lime At a high level, the way both of these work is that you give your training data and model to an “explainer”, and then you’re later able to pass any observation to the “explainer” which will tell you the feature importance of that model. That might sound like gobbledegook right now, but we’ll make this extra clear with our Titanic example! First, we need to pull two people from our validation set that we know respectively did not survive and survive. The reason for this is because we’re going to run these through our SHAP and LIME explainers to understand which characteristics about these people had the most influence for survivability according to our model. (Again, you can see this work in my notebook.) Let’s start off with SHAP. The syntax here is pretty simple. We’ll first instantiate the SHAP explainer object, fit our Random Forest Classifier (rfc) to the object, and plug in each respective person to generate their explainable SHAP values. The code below shows you how to do it for person 1. To do the same for person 2, simply swap out the appropriate values. # Importing the SHAP libraryimport shap# Instantiating the SHAP explainer using our trained RFC modelshap_explainer = shap.TreeExplainer(rfc)shap.initjs()# Getting SHAP values for person 1person_1_shap_values = shap_explainer.shap_values(person_1)# Visualizing plot of expected survivability of person 1shap.force_plot(shap_explainer.expected_value[1], person_1_shap_values[1], person_1)# Visualizing impact of each feature for person 1shap.summary_plot(person_1_shap_values, person_1) And that’s really all there is to it! Let’s take a look at the actual output from what we just did above in the screenshots below. First up, person 1. According to the top visual, our model predicted a 94% chance that person 1 survived, which is correct. It’s a little difficult to read, but look at the second visual, it looks like the most influential factors included the gender of the person, whether or not the person had a 3rd class ticket, and if the person was a child. In this case, person 1 was a female child, so those two factors alone drove our model most to say yes, this person probably survived. Let’s look at person 2 now. Our model here predicted that the person probably did not survive, and it is unfortunately correct. Again looking at the influential factors here, it looks like person 2 here was an adult male that did not have a cabin. I’m no history buff, but I would guess women and children were rescued off the boat first, so it makes a lot of sense to me that person 1 (a female child) did survive and person 2 (a male adult) did not. Alright, let’s move onto our LIME explainer! The syntax for using LIME is a little bit different, but conceptually speaking, both SHAP and LIME are doing a lot of similar stuff. # Importing LIMEimport lime.lime_tabular# Defining our LIME explainerlime_explainer = lime.lime_tabular.LimeTabularExplainer(X_train.values, mode = 'classification', feature_names = X_train.columns, class_names = ['Did Not Survive', 'Survived'])# Defining a quick function that can be used to explain the instance passedpredict_rfc_prob = lambda x: rfc.predict_proba(x).astype(float)# Viewing LIME explainability for person 1person_1_lime = lime_explainer.explain_instance(person_1.iloc[0].values, predict_rfc_prob, num_features = 10)person_1_lime.show_in_notebook() Let’s take a look at what LIME shows us for each person. I’m a little biased here, but I think the UI for these LIME values is a lot easier to read that SHAP. We see the same prediction probabilities for whether each person did or did not survive. In the center, we see how influential the top 10 features were. Compared to SHAP, LIME has a tiny difference in its explainability, but they’re largely the same. We again see that Sex is a huge influencing factor here as well as whether or not the person was a child. On the right, they nicely display the precise values for this particular observation. So which one is better: SHAP or LIME? I’m going to say neither. While each complement each other quite well, I think it’s important to show your business users both just to give them the best picture on which features are most explainable. I don’t think anybody can definitively say either SHAP or LIME is always more accurate, so show them both. The syntax is easy enough to chug out, anyway! That wraps up another post! Hope you all enjoyed this one. I’d say this one has been my favorite to learn and write about so far, and I look forward to applying this in my own work moving forward. Catch you all in the next post!
[ { "code": null, "e": 526, "s": 172, "text": "Hello there all! Welcome back again to another data science quick tip. This particular post is most interesting for me not only because this is the most complex subject we’ve tackled to date, but it’s also one that I just spent the last few hours learning myself. And of course, what better way to learn than to figure out how to teach it to the masses?" }, { "code": null, "e": 710, "s": 526, "text": "Before getting into it, I’ve uploaded all the work shown in this post to a singular Jupyter notebook. You can find it at my personal GitHub if you’d like to follow along more closely." }, { "code": null, "e": 1054, "s": 710, "text": "So even though this is a very complex topic behind the scenes, I’m going to intentionally dial it down as much as possible for the widest possible audience. Even though this is ultimately a post designed for data science practitioners, I think it’s equally important for any business person to understand why they should care about this topic." }, { "code": null, "e": 1194, "s": 1054, "text": "Prior to jumping into how to calculate/visualize these values, let’s build some intuition on why would we would even care about this topic." }, { "code": null, "e": 1612, "s": 1194, "text": "If you’re familiar at all with machine learning in general, you know that you pop some data into a predictive model and that it produces an outputted prediction on the other side. But let’s be honest: do you know what’s really going on inside in that model? Remember, we’re talking about algorithms doing a lot of fancy math under the hood. In reality, this is probably what your ML model looks like to you right now:" }, { "code": null, "e": 1938, "s": 1612, "text": "You really have no idea what’s going on in that black box. The math totally obscures how important those features are in your model. So what if Features 1 and 2 are carrying all the weight and that Features 3 and 4 are not adding any value at all to the model? What you’d prefer to see is something that looks more like this:" }, { "code": null, "e": 2453, "s": 1938, "text": "Okay, we’re obviously using layman’s terms in our example here. But this stuff is important because if your models are relying on one 1 or 2 features to be doing all the predictive power, that might indicate something is wrong. It also might indicate that you’re using some sort of feature that may be considered to be morally incorrect. For example, many companies today will steer clear of using things like gender or ethnicity within their models because they tend to produce a lot of undesired bias in a model." }, { "code": null, "e": 2670, "s": 2453, "text": "Understanding these concepts always makes more sense through a tangible example, so we’re going to return to the dataset we’ve been using the last few posts to concretely demo both SHAP and LIME: the Titanic dataset." }, { "code": null, "e": 3239, "s": 2670, "text": "Alright, so in the last few post where we’ve used the Titanic dataset, we created models that were pretty poor since our focus was more on learning a new skill. In order to effectively demo both SHAP and LIME, we really need a model that shows some level of “trying” (?) so that we can see how ML explainability will play out. Now, I’m not going to spend time in this post showing you all my code for that data cleansing and modeling piece (which you can definitely find in my GitHub here), but I’ll summarize quickly the features that go into producing the end model." }, { "code": null, "e": 3331, "s": 3239, "text": "PClass: Notes the ticket class the person boarded the ship with. (Either 1st, 2nd, or 3rd.)" }, { "code": null, "e": 3489, "s": 3331, "text": "Age Bins: Based on the person’s age, they are segmented into general people groups. These groups include child, teen, young adult, adult, elder, and unknown." }, { "code": null, "e": 3547, "s": 3489, "text": "Sex (Gender): Notes whether the person is male or female." }, { "code": null, "e": 3675, "s": 3547, "text": "Cabin Section: If the person had a cabin, I pulled out what section they might be in. These can either be A, B, C, or no cabin." }, { "code": null, "e": 3757, "s": 3675, "text": "Embarked: Notes one of three locations from which the person originally departed." }, { "code": null, "e": 3865, "s": 3757, "text": "SibSp (Sibling / Spouse): Notes how many siblings and/or spouses the person had onboard the ship with them." }, { "code": null, "e": 3966, "s": 3865, "text": "Parch (Parent / Child): Notes how many parents / children the person had onboard the ship with them." }, { "code": null, "e": 4175, "s": 3966, "text": "For the actual model itself, I’m choosing to use a simple Random Forest Classifier from Scikit-Learn. Splitting the data into training and validation sets, I get the following metrics with the validation set:" }, { "code": null, "e": 4355, "s": 4175, "text": "The metrics aren’t exactly great, but that’s fine for our learning here. At least we’ll get to see in the next section how important these features necessarily are. Let’s move on!" }, { "code": null, "e": 4578, "s": 4355, "text": "At this point, we currently have no idea how our Random Forest model is using the features to make its predictions. I’m going to wager a guess that Sex and Age Bin are influential factors, but we don’t know that quite yet." }, { "code": null, "e": 5005, "s": 4578, "text": "This is where smart people developed complex algorithms based on game theory to generate these things to better explain our current black box. Of course, I’m referring to SHAP and LIME. Now, I’m going to be 100% honest: I’m not very familiar with how these algorithms work under the hood, so I’m not even going to attempt to do that in this post. Instead, I’ll point you to this post about SHAP and this other post about LIME." }, { "code": null, "e": 5283, "s": 5005, "text": "Just like Scikit-Learn abstracts away the underlying algorithms for our Random Forest classifier, there are some neat Python libraries that we’ll use that abstract away the inner workings of both SHAP and LIME. To use those, all you need to do is a simple pip install for both:" }, { "code": null, "e": 5316, "s": 5283, "text": "pip install shappip install lime" }, { "code": null, "e": 5657, "s": 5316, "text": "At a high level, the way both of these work is that you give your training data and model to an “explainer”, and then you’re later able to pass any observation to the “explainer” which will tell you the feature importance of that model. That might sound like gobbledegook right now, but we’ll make this extra clear with our Titanic example!" }, { "code": null, "e": 6030, "s": 5657, "text": "First, we need to pull two people from our validation set that we know respectively did not survive and survive. The reason for this is because we’re going to run these through our SHAP and LIME explainers to understand which characteristics about these people had the most influence for survivability according to our model. (Again, you can see this work in my notebook.)" }, { "code": null, "e": 6395, "s": 6030, "text": "Let’s start off with SHAP. The syntax here is pretty simple. We’ll first instantiate the SHAP explainer object, fit our Random Forest Classifier (rfc) to the object, and plug in each respective person to generate their explainable SHAP values. The code below shows you how to do it for person 1. To do the same for person 2, simply swap out the appropriate values." }, { "code": null, "e": 6881, "s": 6395, "text": "# Importing the SHAP libraryimport shap# Instantiating the SHAP explainer using our trained RFC modelshap_explainer = shap.TreeExplainer(rfc)shap.initjs()# Getting SHAP values for person 1person_1_shap_values = shap_explainer.shap_values(person_1)# Visualizing plot of expected survivability of person 1shap.force_plot(shap_explainer.expected_value[1], person_1_shap_values[1], person_1)# Visualizing impact of each feature for person 1shap.summary_plot(person_1_shap_values, person_1)" }, { "code": null, "e": 7032, "s": 6881, "text": "And that’s really all there is to it! Let’s take a look at the actual output from what we just did above in the screenshots below. First up, person 1." }, { "code": null, "e": 7493, "s": 7032, "text": "According to the top visual, our model predicted a 94% chance that person 1 survived, which is correct. It’s a little difficult to read, but look at the second visual, it looks like the most influential factors included the gender of the person, whether or not the person had a 3rd class ticket, and if the person was a child. In this case, person 1 was a female child, so those two factors alone drove our model most to say yes, this person probably survived." }, { "code": null, "e": 7521, "s": 7493, "text": "Let’s look at person 2 now." }, { "code": null, "e": 7945, "s": 7521, "text": "Our model here predicted that the person probably did not survive, and it is unfortunately correct. Again looking at the influential factors here, it looks like person 2 here was an adult male that did not have a cabin. I’m no history buff, but I would guess women and children were rescued off the boat first, so it makes a lot of sense to me that person 1 (a female child) did survive and person 2 (a male adult) did not." }, { "code": null, "e": 7990, "s": 7945, "text": "Alright, let’s move onto our LIME explainer!" }, { "code": null, "e": 8123, "s": 7990, "text": "The syntax for using LIME is a little bit different, but conceptually speaking, both SHAP and LIME are doing a lot of similar stuff." }, { "code": null, "e": 8690, "s": 8123, "text": "# Importing LIMEimport lime.lime_tabular# Defining our LIME explainerlime_explainer = lime.lime_tabular.LimeTabularExplainer(X_train.values, mode = 'classification', feature_names = X_train.columns, class_names = ['Did Not Survive', 'Survived'])# Defining a quick function that can be used to explain the instance passedpredict_rfc_prob = lambda x: rfc.predict_proba(x).astype(float)# Viewing LIME explainability for person 1person_1_lime = lime_explainer.explain_instance(person_1.iloc[0].values, predict_rfc_prob, num_features = 10)person_1_lime.show_in_notebook()" }, { "code": null, "e": 8747, "s": 8690, "text": "Let’s take a look at what LIME shows us for each person." }, { "code": null, "e": 9292, "s": 8747, "text": "I’m a little biased here, but I think the UI for these LIME values is a lot easier to read that SHAP. We see the same prediction probabilities for whether each person did or did not survive. In the center, we see how influential the top 10 features were. Compared to SHAP, LIME has a tiny difference in its explainability, but they’re largely the same. We again see that Sex is a huge influencing factor here as well as whether or not the person was a child. On the right, they nicely display the precise values for this particular observation." }, { "code": null, "e": 9686, "s": 9292, "text": "So which one is better: SHAP or LIME? I’m going to say neither. While each complement each other quite well, I think it’s important to show your business users both just to give them the best picture on which features are most explainable. I don’t think anybody can definitively say either SHAP or LIME is always more accurate, so show them both. The syntax is easy enough to chug out, anyway!" } ]
ssh - Unix, Linux Command
ssh connects and logs into the specified hostname (with optional user name). The user must prove his/her identity to the remote machine using one of several methods depending on the protocol version used (see below). If command is specified, it is executed on the remote host instead of a login shell. The options are as follows: Agent forwarding should be enabled with caution. Users with the ability to bypass file permissions on the remote host (for the agent’s Unix-domain socket) can access the local agent through the forwarded connection. An attacker cannot obtain key material from the agent, however they can perform operations on the keys that enable them to authenticate using the identities loaded into the agent. Protocol version 1 allows specification of a single cipher. The supported values are "3des", "blowfish", and "des". 3des (triple-des) is an encrypt-decrypt-encrypt triple with three different keys. It is believed to be secure. blowfish is a fast block cipher; it appears very secure and is much faster than 3des. des is only supported in the ssh client for interoperability with legacy protocol 1 implementations that do not support the 3des cipher. Its use is strongly discouraged due to cryptographic weaknesses. The default is "3des". For protocol version 2, cipher_spec is a comma-separated list of ciphers listed in order of preference. The supported ciphers are: 3des-cbc, aes128-cbc, aes192-cbc, aes256-cbc, aes128-ctr, aes192-ctr, aes256-ctr, arcfour128, arcfour256, arcfour, blowfish-cbc, and cast128-cbc. The default is: aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,arcfour128, arcfour256,arcfour,aes192-cbc,aes256-cbc,aes128-ctr, aes192-ctr,aes256-ctr IPv6 addresses can be specified with an alternative syntax: .Sm off .Xo [bind_address /] port Port forwardings can also be specified in the configuration file. Privileged ports can be forwarded only when logging in as root on the remote machine. IPv6 addresses can be specified by enclosing the address in square braces or using an alternative syntax: .Sm off .Xo [bind_address /] host / port / hostport By default, the listening socket on the server will be bound to the loopback interface only. This may be overriden by specifying a bind_address. An empty bind_address, or the address ‘*’, indicates that the remote socket should listen on all interfaces. Specifying a remote bind_address will only succeed if the server’s GatewayPorts option is enabled (see sshd_config(5)). X11 forwarding should be enabled with caution. Users with the ability to bypass file permissions on the remote host (for the user’s X authorization database) can access the local X11 display through the forwarded connection. An attacker may then be able to perform activities such as keystroke monitoring. For this reason, X11 forwarding is subjected to X11 SECURITY extension restrictions by default. Please refer to the ssh -Y option and the ForwardX11Trusted directive in ssh_config(5) for more information. ssh may additionally obtain configuration data from a per-user configuration file and a system-wide configuration file. The file format and configuration options are described in ssh_config(5). ssh exits with the exit status of the remote command or with 255 if an error occurred. The methods available for authentication are: host-based authentication, public key authentication, challenge-response authentication, and password authentication. Authentication methods are tried in the order specified above, though protocol 2 has a configuration option to change the default order: PreferredAuthentications. Host-based authentication works as follows: If the machine the user logs in from is listed in /etc/hosts.equiv or /etc/ssh/shosts.equiv on the remote machine, and the user names are the same on both sides, or if the files ~/.rhosts or ~/.shosts exist in the user’s home directory on the remote machine and contain a line containing the name of the client machine and the name of the user on that machine, the user is considered for login. Additionally, the server must be able to verify the client’s host key (see the description of /etc/ssh/ssh_known_hosts and ~/.ssh/known_hosts, below) for login to be permitted. This authentication method closes security holes due to IP spoofing, DNS spoofing, and routing spoofing. [Note to the administrator: /etc/hosts.equiv, ~/.rhosts, and the rlogin/rsh protocol in general, are inherently insecure and should be disabled if security is desired.] Public key authentication works as follows: The scheme is based on public-key cryptography, using cryptosystems where encryption and decryption are done using separate keys, and it is unfeasible to derive the decryption key from the encryption key. The idea is that each user creates a public/private key pair for authentication purposes. The server knows the public key, and only the user knows the private key. ssh implements public key authentication protocol automatically, using either the RSA or DSA algorithms. Protocol 1 is restricted to using only RSA keys, but protocol 2 may use either. The HISTORY section of ssl(8) contains a brief discussion of the two algorithms. The file ~/.ssh/authorized_keys lists the public keys that are permitted for logging in. When the user logs in, the ssh program tells the server which key pair it would like to use for authentication. The client proves that it has access to the private key and the server checks that the corresponding public key is authorized to accept the account. The user creates his/her key pair by running ssh-keygen(1). This stores the private key in ~/.ssh/identity (protocol 1), ~/.ssh/id_dsa (protocol 2 DSA), or ~/.ssh/id_rsa (protocol 2 RSA) and stores the public key in ~/.ssh/identity.pub (protocol 1), ~/.ssh/id_dsa.pub (protocol 2 DSA), or ~/.ssh/id_rsa.pub (protocol 2 RSA) in the user’s home directory. The user should then copy the public key to ~/.ssh/authorized_keys in his/her home directory on the remote machine. The authorized_keys file corresponds to the conventional ~/.rhosts file, and has one key per line, though the lines can be very long. After this, the user can log in without giving the password. The most convenient way to use public key authentication may be with an authentication agent. See ssh-agent(1) for more information. Challenge-response authentication works as follows: The server sends an arbitrary "challenge" text, and prompts for a response. Protocol 2 allows multiple challenges and responses; protocol 1 is restricted to just one challenge/response. Examples of challenge-response authentication include BSD Authentication (see login.conf(5)) and PAM (some non-OpenBSD systems). Finally, if other authentication methods fail, ssh prompts the user for a password. The password is sent to the remote host for checking; however, since all communications are encrypted, the password cannot be seen by someone listening on the network. ssh automatically maintains and checks a database containing identification for all hosts it has ever been used with. Host keys are stored in ~/.ssh/known_hosts in the user’s home directory. Additionally, the file /etc/ssh/ssh_known_hosts is automatically checked for known hosts. Any new hosts are automatically added to the user’s file. If a host’s identification ever changes, ssh warns about this and disables password authentication to prevent server spoofing or man-in-the-middle attacks, which could otherwise be used to circumvent the encryption. The StrictHostKeyChecking option can be used to control logins to machines whose host key is not known or has changed. When the user’s identity has been accepted by the server, the server either executes the given command, or logs into the machine and gives the user a normal shell on the remote machine. All communication with the remote command or shell will be automatically encrypted. If a pseudo-terminal has been allocated (normal login session), the user may use the escape characters noted below. If no pseudo-tty has been allocated, the session is transparent and can be used to reliably transfer binary data. On most systems, setting the escape character to "none" will also make the session transparent even if a tty is used. The session terminates when the command or shell on the remote machine exits and all X11 and TCP connections have been closed. A single tilde character can be sent as ~~ or by following the tilde by a character other than those described below. The escape character must always follow a newline to be interpreted as special. The escape character can be changed in configuration files using the EscapeChar configuration directive or on the command line by the -e option. The supported escapes (assuming the default ‘~’) are: In the example below, we look at encrypting communication between an IRC client and server, even though the IRC server does not directly support encrypted communications. This works as follows: the user connects to the remote host using ssh, specifying a port to be used to forward connections to the remote server. After that it is possible to start the service which is to be encrypted on the client machine, connecting to the same local port, and ssh will encrypt and forward the connection. The following example tunnels an IRC session from client machine "127.0.0.1" (localhost) to remote server "server.example.com": $ ssh -f -L 1234:localhost:6667 server.example.com sleep 10 $ irc -c ’#users’ -p 1234 pinky 127.0.0.1 This tunnels a connection to IRC server "server.example.com", joining channel "#users", nickname "pinky", using port 1234. It doesn’t matter which port is used, as long as it’s greater than 1023 (remember, only root can open sockets on privileged ports) and doesn’t conflict with any ports already in use. The connection is forwarded to port 6667 on the remote server, since that’s the standard port for IRC services. The -f option backgrounds ssh and the remote command "sleep 10" is specified to allow an amount of time (10 seconds, in the example) to start the service which is to be tunnelled. If no connections are made within the time specified, ssh will exit. The DISPLAY value set by ssh will point to the server machine, but with a display number greater than zero. This is normal, and happens because ssh creates a "proxy" X server on the server machine for forwarding the connections over the encrypted channel. ssh will also automatically set up Xauthority data on the server machine. For this purpose, it will generate a random authorization cookie, store it in Xauthority on the server, and verify that any forwarded connections carry this cookie and replace it by the real cookie when the connection is opened. The real authentication cookie is never sent to the server machine (and no cookies are sent in the plain). If the ForwardAgent variable is set to "yes" (or see the description of the -A and -a options above) and the user is using an authentication agent, the connection to the agent is automatically forwarded to the remote side. $ ssh-keygen -l -f /etc/ssh/ssh_host_rsa_key If the fingerprint is already known, it can be matched and verified, and the key can be accepted. If the fingerprint is unknown, an alternative method of verification is available: SSH fingerprints verified by DNS. An additional resource record (RR), SSHFP, is added to a zonefile and the connecting client is able to match the fingerprint with that of the key presented. In this example, we are connecting a client to a server, "host.example.com". The SSHFP resource records should first be added to the zonefile for host.example.com: $ ssh-keygen -f /etc/ssh/ssh_host_rsa_key.pub -r host.example.com. $ ssh-keygen -f /etc/ssh/ssh_host_dsa_key.pub -r host.example.com. The output lines will have to be added to the zonefile. To check that the zone is answering fingerprint queries: $ dig -t SSHFP host.example.com Finally the client connects: $ ssh -o "VerifyHostKeyDNS ask" host.example.com [...] Matching host key fingerprint found in DNS. Are you sure you want to continue connecting (yes/no)? See the VerifyHostKeyDNS option in ssh_config(5) for more information. The following example would connect client network 10.0.50.0/24 with remote network 10.0.99.0/24, provided that the SSH server running on the gateway to the remote network, at 192.168.1.15, allows it: # ssh -f -w 0:1 192.168.1.15 true # ifconfig tun0 10.0.50.1 10.0.99.1 netmask 255.255.255.252 Client access may be more finely tuned via the /root/.ssh/authorized_keys file (see below) and the PermitRootLogin server option. The following entry would permit connections on the first tun(4) device from user "jane" and on the second device from user "john", if PermitRootLogin is set to "forced-commands-only": tunnel="1",command="sh /etc/netstart tun1" ssh-rsa ... jane tunnel="2",command="sh /etc/netstart tun1" ssh-rsa ... john Since a SSH-based setup entails a fair amount of overhead, it may be more suited to temporary setups, such as for wireless VPNs. More permanent VPNs are better provided by tools such as ipsecctl(8) and isakmpd(8). Additionally, ssh reads ~/.ssh/environment, and adds lines of the format "VARNAME=value" to the environment if the file exists and users are allowed to change their environment. For more information, see the PermitUserEnvironment option in sshd_config(5). Advertisements 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": 10798, "s": 10577, "text": "\nssh\nconnects and logs into the specified\n hostname\n(with optional\n user\nname).\nThe user must prove\nhis/her identity to the remote machine using one of several methods\ndepending on the protocol version used (see below).\n" }, { "code": null, "e": 10886, "s": 10798, "text": "\nIf\n command\nis specified,\nit is executed on the remote host instead of a login shell.\n" }, { "code": null, "e": 10916, "s": 10886, "text": "\nThe options are as follows:\n" }, { "code": null, "e": 11314, "s": 10916, "text": "\nAgent forwarding should be enabled with caution.\nUsers with the ability to bypass file permissions on the remote host\n(for the agent’s Unix-domain socket)\ncan access the local agent through the forwarded connection.\nAn attacker cannot obtain key material from the agent,\nhowever they can perform operations on the keys that enable them to\nauthenticate using the identities loaded into the agent.\n" }, { "code": null, "e": 11859, "s": 11314, "text": "\nProtocol version 1 allows specification of a single cipher.\nThe supported values are\n\"3des\",\n\"blowfish\",\nand\n\"des\".\n 3des\n(triple-des) is an encrypt-decrypt-encrypt triple with three different keys.\nIt is believed to be secure.\n blowfish\nis a fast block cipher; it appears very secure and is much faster than\n 3des.\n des\nis only supported in the\nssh\nclient for interoperability with legacy protocol 1 implementations\nthat do not support the\n 3des\ncipher.\nIts use is strongly discouraged due to cryptographic weaknesses.\nThe default is\n\"3des\".\n" }, { "code": null, "e": 12155, "s": 11859, "text": "\nFor protocol version 2,\n cipher_spec\nis a comma-separated list of ciphers\nlisted in order of preference.\nThe supported ciphers are:\n3des-cbc,\naes128-cbc,\naes192-cbc,\naes256-cbc,\naes128-ctr,\naes192-ctr,\naes256-ctr,\narcfour128,\narcfour256,\narcfour,\nblowfish-cbc,\nand\ncast128-cbc.\nThe default is:\n" }, { "code": null, "e": 12288, "s": 12155, "text": "aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,arcfour128,\narcfour256,arcfour,aes192-cbc,aes256-cbc,aes128-ctr,\naes192-ctr,aes256-ctr\n" }, { "code": null, "e": 12386, "s": 12288, "text": "\nIPv6 addresses can be specified with an alternative syntax:\n.Sm off\n.Xo \n[bind_address /]\n port\n" }, { "code": null, "e": 12703, "s": 12388, "text": "\nPort forwardings can also be specified in the configuration file.\nPrivileged ports can be forwarded only when\nlogging in as root on the remote machine.\nIPv6 addresses can be specified by enclosing the address in square braces or\nusing an alternative syntax:\n.Sm off\n.Xo \n[bind_address /]\n host / port /\n hostport\n" }, { "code": null, "e": 13083, "s": 12703, "text": "\nBy default, the listening socket on the server will be bound to the loopback\ninterface only.\nThis may be overriden by specifying a\n bind_address.\nAn empty\n bind_address,\nor the address\n‘*’,\nindicates that the remote socket should listen on all interfaces.\nSpecifying a remote\n bind_address\nwill only succeed if the server’s\n GatewayPorts\noption is enabled (see\nsshd_config(5)).\n" }, { "code": null, "e": 13391, "s": 13083, "text": "\nX11 forwarding should be enabled with caution.\nUsers with the ability to bypass file permissions on the remote host\n(for the user’s X authorization database)\ncan access the local X11 display through the forwarded connection.\nAn attacker may then be able to perform activities such as keystroke monitoring.\n" }, { "code": null, "e": 13600, "s": 13391, "text": "\nFor this reason, X11 forwarding is subjected to X11 SECURITY extension\nrestrictions by default.\nPlease refer to the\nssh\n-Y \noption and the\n ForwardX11Trusted\ndirective in\nssh_config(5)\nfor more information.\n" }, { "code": null, "e": 13796, "s": 13600, "text": "\nssh\nmay additionally obtain configuration data from\na per-user configuration file and a system-wide configuration file.\nThe file format and configuration options are described in\nssh_config(5).\n" }, { "code": null, "e": 13885, "s": 13796, "text": "\nssh\nexits with the exit status of the remote command or with 255\nif an error occurred.\n" }, { "code": null, "e": 14215, "s": 13885, "text": "\nThe methods available for authentication are:\nhost-based authentication,\npublic key authentication,\nchallenge-response authentication,\nand password authentication.\nAuthentication methods are tried in the order specified above,\nthough protocol 2 has a configuration option to change the default order:\n PreferredAuthentications.\n" }, { "code": null, "e": 15116, "s": 14215, "text": "\nHost-based authentication works as follows:\nIf the machine the user logs in from is listed in\n /etc/hosts.equiv\nor\n /etc/ssh/shosts.equiv\non the remote machine, and the user names are\nthe same on both sides, or if the files\n ~/.rhosts\nor\n ~/.shosts\nexist in the user’s home directory on the\nremote machine and contain a line containing the name of the client\nmachine and the name of the user on that machine, the user is\nconsidered for login.\nAdditionally, the server\n must\nbe able to verify the client’s\nhost key (see the description of\n /etc/ssh/ssh_known_hosts\nand\n ~/.ssh/known_hosts,\nbelow)\nfor login to be permitted.\nThis authentication method closes security holes due to IP\nspoofing, DNS spoofing, and routing spoofing.\n[Note to the administrator:\n /etc/hosts.equiv,\n ~/.rhosts,\nand the rlogin/rsh protocol in general, are inherently insecure and should be\ndisabled if security is desired.]\n" }, { "code": null, "e": 15797, "s": 15116, "text": "\nPublic key authentication works as follows:\nThe scheme is based on public-key cryptography,\nusing cryptosystems\nwhere encryption and decryption are done using separate keys,\nand it is unfeasible to derive the decryption key from the encryption key.\nThe idea is that each user creates a public/private\nkey pair for authentication purposes.\nThe server knows the public key, and only the user knows the private key.\nssh\nimplements public key authentication protocol automatically,\nusing either the RSA or DSA algorithms.\nProtocol 1 is restricted to using only RSA keys,\nbut protocol 2 may use either.\nThe\nHISTORY\nsection of\nssl(8)\ncontains a brief discussion of the two algorithms.\n" }, { "code": null, "e": 16150, "s": 15797, "text": "\nThe file\n ~/.ssh/authorized_keys\nlists the public keys that are permitted for logging in.\nWhen the user logs in, the\nssh\nprogram tells the server which key pair it would like to use for\nauthentication.\nThe client proves that it has access to the private key\nand the server checks that the corresponding public key\nis authorized to accept the account.\n" }, { "code": null, "e": 16826, "s": 16150, "text": "\nThe user creates his/her key pair by running\nssh-keygen(1).\nThis stores the private key in\n ~/.ssh/identity\n(protocol 1),\n ~/.ssh/id_dsa\n(protocol 2 DSA),\nor\n ~/.ssh/id_rsa\n(protocol 2 RSA)\nand stores the public key in\n ~/.ssh/identity.pub\n(protocol 1),\n ~/.ssh/id_dsa.pub\n(protocol 2 DSA),\nor\n ~/.ssh/id_rsa.pub\n(protocol 2 RSA)\nin the user’s home directory.\nThe user should then copy the public key\nto\n ~/.ssh/authorized_keys\nin his/her home directory on the remote machine.\nThe\n authorized_keys\nfile corresponds to the conventional\n ~/.rhosts\nfile, and has one key\nper line, though the lines can be very long.\nAfter this, the user can log in without giving the password.\n" }, { "code": null, "e": 16961, "s": 16826, "text": "\nThe most convenient way to use public key authentication may be with an\nauthentication agent.\nSee\nssh-agent(1)\nfor more information.\n" }, { "code": null, "e": 17330, "s": 16961, "text": "\nChallenge-response authentication works as follows:\nThe server sends an arbitrary\n\"challenge\"\ntext, and prompts for a response.\nProtocol 2 allows multiple challenges and responses;\nprotocol 1 is restricted to just one challenge/response.\nExamples of challenge-response authentication include\nBSD Authentication (see\nlogin.conf(5))\nand PAM (some non-OpenBSD systems).\n" }, { "code": null, "e": 17584, "s": 17330, "text": "\nFinally, if other authentication methods fail,\nssh\nprompts the user for a password.\nThe password is sent to the remote\nhost for checking; however, since all communications are encrypted,\nthe password cannot be seen by someone listening on the network.\n" }, { "code": null, "e": 18263, "s": 17584, "text": "\nssh\nautomatically maintains and checks a database containing\nidentification for all hosts it has ever been used with.\nHost keys are stored in\n ~/.ssh/known_hosts\nin the user’s home directory.\nAdditionally, the file\n /etc/ssh/ssh_known_hosts\nis automatically checked for known hosts.\nAny new hosts are automatically added to the user’s file.\nIf a host’s identification ever changes,\nssh\nwarns about this and disables password authentication to prevent\nserver spoofing or man-in-the-middle attacks,\nwhich could otherwise be used to circumvent the encryption.\nThe\n StrictHostKeyChecking\noption can be used to control logins to machines whose\nhost key is not known or has changed.\n" }, { "code": null, "e": 18535, "s": 18263, "text": "\nWhen the user’s identity has been accepted by the server, the server\neither executes the given command, or logs into the machine and gives\nthe user a normal shell on the remote machine.\nAll communication with\nthe remote command or shell will be automatically encrypted.\n" }, { "code": null, "e": 18653, "s": 18535, "text": "\nIf a pseudo-terminal has been allocated (normal login session), the\nuser may use the escape characters noted below.\n" }, { "code": null, "e": 18887, "s": 18653, "text": "\nIf no pseudo-tty has been allocated,\nthe session is transparent and can be used to reliably transfer binary data.\nOn most systems, setting the escape character to\n\"none\"\nwill also make the session transparent even if a tty is used.\n" }, { "code": null, "e": 19016, "s": 18887, "text": "\nThe session terminates when the command or shell on the remote\nmachine exits and all X11 and TCP connections have been closed.\n" }, { "code": null, "e": 19364, "s": 19016, "text": "\nA single tilde character can be sent as\n ~~\nor by following the tilde by a character other than those described below.\nThe escape character must always follow a newline to be interpreted as\nspecial.\nThe escape character can be changed in configuration files using the\n EscapeChar\nconfiguration directive or on the command line by the\n-e \noption.\n" }, { "code": null, "e": 19420, "s": 19364, "text": "\nThe supported escapes (assuming the default\n‘~’)\nare:\n" }, { "code": null, "e": 19917, "s": 19420, "text": "\nIn the example below, we look at encrypting communication between\nan IRC client and server, even though the IRC server does not directly\nsupport encrypted communications.\nThis works as follows:\nthe user connects to the remote host using\nssh,\nspecifying a port to be used to forward connections\nto the remote server.\nAfter that it is possible to start the service which is to be encrypted\non the client machine,\nconnecting to the same local port,\nand\nssh\nwill encrypt and forward the connection.\n" }, { "code": null, "e": 20047, "s": 19917, "text": "\nThe following example tunnels an IRC session from client machine\n\"127.0.0.1\"\n(localhost)\nto remote server\n\"server.example.com\":\n" }, { "code": null, "e": 20150, "s": 20047, "text": "$ ssh -f -L 1234:localhost:6667 server.example.com sleep 10\n$ irc -c ’#users’ -p 1234 pinky 127.0.0.1\n" }, { "code": null, "e": 20570, "s": 20150, "text": "\nThis tunnels a connection to IRC server\n\"server.example.com\",\njoining channel\n\"#users\",\nnickname\n\"pinky\",\nusing port 1234.\nIt doesn’t matter which port is used,\nas long as it’s greater than 1023\n(remember, only root can open sockets on privileged ports)\nand doesn’t conflict with any ports already in use.\nThe connection is forwarded to port 6667 on the remote server,\nsince that’s the standard port for IRC services.\n" }, { "code": null, "e": 20822, "s": 20570, "text": "\nThe\n-f \noption backgrounds\nssh\nand the remote command\n\"sleep 10\"\nis specified to allow an amount of time\n(10 seconds, in the example)\nto start the service which is to be tunnelled.\nIf no connections are made within the time specified,\nssh\nwill exit.\n" }, { "code": null, "e": 21081, "s": 20822, "text": "\nThe\n DISPLAY\nvalue set by\nssh\nwill point to the server machine, but with a display number greater than zero.\nThis is normal, and happens because\nssh\ncreates a\n\"proxy\"\nX server on the server machine for forwarding the\nconnections over the encrypted channel.\n" }, { "code": null, "e": 21493, "s": 21081, "text": "\nssh\nwill also automatically set up Xauthority data on the server machine.\nFor this purpose, it will generate a random authorization cookie,\nstore it in Xauthority on the server, and verify that any forwarded\nconnections carry this cookie and replace it by the real cookie when\nthe connection is opened.\nThe real authentication cookie is never\nsent to the server machine (and no cookies are sent in the plain).\n" }, { "code": null, "e": 21721, "s": 21493, "text": "\nIf the\n ForwardAgent\nvariable is set to\n\"yes\"\n(or see the description of the\n-A \nand\n-a \noptions above) and\nthe user is using an authentication agent, the connection to the agent\nis automatically forwarded to the remote side.\n" }, { "code": null, "e": 21773, "s": 21723, "text": " $ ssh-keygen -l -f /etc/ssh/ssh_host_rsa_key" }, { "code": null, "e": 22149, "s": 21775, "text": "\nIf the fingerprint is already known,\nit can be matched and verified,\nand the key can be accepted.\nIf the fingerprint is unknown,\nan alternative method of verification is available:\nSSH fingerprints verified by DNS.\nAn additional resource record (RR),\nSSHFP,\nis added to a zonefile\nand the connecting client is able to match the fingerprint\nwith that of the key presented.\n" }, { "code": null, "e": 22315, "s": 22149, "text": "\nIn this example, we are connecting a client to a server,\n\"host.example.com\".\nThe SSHFP resource records should first be added to the zonefile for\nhost.example.com:\n" }, { "code": null, "e": 22450, "s": 22315, "text": "$ ssh-keygen -f /etc/ssh/ssh_host_rsa_key.pub -r host.example.com.\n$ ssh-keygen -f /etc/ssh/ssh_host_dsa_key.pub -r host.example.com.\n" }, { "code": null, "e": 22565, "s": 22450, "text": "\nThe output lines will have to be added to the zonefile.\nTo check that the zone is answering fingerprint queries:\n" }, { "code": null, "e": 22604, "s": 22567, "text": " $ dig -t SSHFP host.example.com" }, { "code": null, "e": 22637, "s": 22606, "text": "\nFinally the client connects:\n" }, { "code": null, "e": 22792, "s": 22637, "text": "$ ssh -o \"VerifyHostKeyDNS ask\" host.example.com\n[...]\nMatching host key fingerprint found in DNS.\nAre you sure you want to continue connecting (yes/no)?\n" }, { "code": null, "e": 22866, "s": 22792, "text": "\nSee the\n VerifyHostKeyDNS\noption in\nssh_config(5)\nfor more information.\n" }, { "code": null, "e": 23069, "s": 22866, "text": "\nThe following example would connect client network 10.0.50.0/24\nwith remote network 10.0.99.0/24, provided that the SSH server\nrunning on the gateway to the remote network,\nat 192.168.1.15, allows it:\n" }, { "code": null, "e": 23164, "s": 23069, "text": "# ssh -f -w 0:1 192.168.1.15 true\n# ifconfig tun0 10.0.50.1 10.0.99.1 netmask 255.255.255.252\n" }, { "code": null, "e": 23484, "s": 23164, "text": "\nClient access may be more finely tuned via the\n /root/.ssh/authorized_keys\nfile (see below) and the\n PermitRootLogin\nserver option.\nThe following entry would permit connections on the first\ntun(4)\ndevice from user\n\"jane\"\nand on the second device from user\n\"john\",\nif\n PermitRootLogin\nis set to\n\"forced-commands-only\":\n" }, { "code": null, "e": 23605, "s": 23484, "text": "tunnel=\"1\",command=\"sh /etc/netstart tun1\" ssh-rsa ... jane\ntunnel=\"2\",command=\"sh /etc/netstart tun1\" ssh-rsa ... john\n" }, { "code": null, "e": 23821, "s": 23605, "text": "\nSince a SSH-based setup entails a fair amount of overhead,\nit may be more suited to temporary setups,\nsuch as for wireless VPNs.\nMore permanent VPNs are better provided by tools such as\nipsecctl(8)\nand\nisakmpd(8).\n" }, { "code": null, "e": 24081, "s": 23821, "text": "\nAdditionally,\nssh\nreads\n ~/.ssh/environment,\nand adds lines of the format\n\"VARNAME=value\"\nto the environment if the file exists and users are allowed to\nchange their environment.\nFor more information, see the\n PermitUserEnvironment\noption in\nsshd_config(5).\n" }, { "code": null, "e": 24126, "s": 24109, "text": "\nAdvertisements\n" }, { "code": null, "e": 24161, "s": 24126, "text": "\n 129 Lectures \n 23 hours \n" }, { "code": null, "e": 24189, "s": 24161, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 24223, "s": 24189, "text": "\n 5 Lectures \n 4.5 hours \n" }, { "code": null, "e": 24240, "s": 24223, "text": " Frahaan Hussain" }, { "code": null, "e": 24273, "s": 24240, "text": "\n 35 Lectures \n 2 hours \n" }, { "code": null, "e": 24284, "s": 24273, "text": " Pradeep D" }, { "code": null, "e": 24319, "s": 24284, "text": "\n 41 Lectures \n 2.5 hours \n" }, { "code": null, "e": 24335, "s": 24319, "text": " Musab Zayadneh" }, { "code": null, "e": 24368, "s": 24335, "text": "\n 46 Lectures \n 4 hours \n" }, { "code": null, "e": 24380, "s": 24368, "text": " GUHARAJANM" }, { "code": null, "e": 24412, "s": 24380, "text": "\n 6 Lectures \n 4 hours \n" }, { "code": null, "e": 24420, "s": 24412, "text": " Uplatz" }, { "code": null, "e": 24427, "s": 24420, "text": " Print" }, { "code": null, "e": 24438, "s": 24427, "text": " Add Notes" } ]
Google Charts - Stacked Column Chart
Following is an example of a stacked column chart. We've already seen the configuration used to draw this chart in Google Charts Configuration Syntax chapter. So, let's see the complete example. We've used isStacked configuration to show stacked chart. // Set chart options var options = { isStacked: true }; googlecharts_column_stacked.htm <html> <head> <title>Google Charts Tutorial</title> <script type = "text/javascript" src = "https://www.gstatic.com/charts/loader.js"> </script> <script type = "text/javascript"> google.charts.load('current', {packages: ['corechart']}); </script> </head> <body> <div id = "container" style = "width: 550px; height: 400px; margin: 0 auto"> </div> <script language = "JavaScript"> function drawChart() { // Define the chart to be drawn. var data = google.visualization.arrayToDataTable([ ['Year', 'Asia', 'Europe'], ['2012', 900, 390], ['2013', 1000, 400], ['2014', 1170, 440], ['2015', 1250, 480], ['2016', 1530, 540] ]); var options = {title: 'Population (in millions)', isStacked:true}; // Instantiate and draw the chart. var chart = new google.visualization.ColumnChart(document.getElementById('container')); chart.draw(data, options); } google.charts.setOnLoadCallback(drawChart); </script> </body> </html> Verify the result. Print Add Notes Bookmark this page
[ { "code": null, "e": 2456, "s": 2261, "text": "Following is an example of a stacked column chart. We've already seen the configuration used to draw this chart in Google Charts Configuration Syntax chapter. So, let's see the complete example." }, { "code": null, "e": 2514, "s": 2456, "text": "We've used isStacked configuration to show stacked chart." }, { "code": null, "e": 2573, "s": 2514, "text": "// Set chart options\nvar options = {\n isStacked: true\n};" }, { "code": null, "e": 2605, "s": 2573, "text": "googlecharts_column_stacked.htm" }, { "code": null, "e": 3835, "s": 2605, "text": "<html>\n <head>\n <title>Google Charts Tutorial</title>\n <script type = \"text/javascript\" src = \"https://www.gstatic.com/charts/loader.js\">\n </script>\n <script type = \"text/javascript\">\n google.charts.load('current', {packages: ['corechart']}); \n </script>\n </head>\n \n <body>\n <div id = \"container\" style = \"width: 550px; height: 400px; margin: 0 auto\">\n </div>\n <script language = \"JavaScript\">\n function drawChart() {\n // Define the chart to be drawn.\n var data = google.visualization.arrayToDataTable([\n ['Year', 'Asia', 'Europe'],\n ['2012', 900, 390],\n ['2013', 1000, 400],\n ['2014', 1170, 440],\n ['2015', 1250, 480],\n ['2016', 1530, 540]\n ]);\n\n var options = {title: 'Population (in millions)', isStacked:true}; \n\n // Instantiate and draw the chart.\n var chart = new google.visualization.ColumnChart(document.getElementById('container'));\n chart.draw(data, options);\n }\n google.charts.setOnLoadCallback(drawChart);\n </script>\n </body>\n</html>" }, { "code": null, "e": 3854, "s": 3835, "text": "Verify the result." }, { "code": null, "e": 3861, "s": 3854, "text": " Print" }, { "code": null, "e": 3872, "s": 3861, "text": " Add Notes" } ]
How Region of Interest (ROI) works in OpenCV using C++?
To separate a particular portion from the image, we have to locate the area first. Then we have to copy that area from the main image to another matrix. This is how the ROI in OpenCV works. In this example, two matrices have been declared at the beginning. After that, an image named 'image_name.jpg' has been loaded into the 'image1' matrix. The next line 'image2=image1 (Rect(100, 100, 120, 120));' requires special attention. This line is cropping out the defined region of the image and storing it in the 'image2' matrix. The figure shows what we have done here with the 'Rect(100,100,120,120)' code. The basic form of this line of code is 'Rect(x, y,x1,y1)'. Here x and y defines the rectangle's starting point and x1 and y1represents the endpoint of the rectangle. By changing these values, we can change the size of the rectangle. The following program demonstrates the working of Region of Interest in OpenCV: #include #include #include using namespace std; using namespace cv; int main() { Mat image1; //Declaring a matrix named 'image1'// Mat image2; //Declaring a matrix named 'image2'// image1 = imread("RGB.png"); //Loading an image name 'image_name.png into image1 matrix// image2 = image1(Rect(100, 100, 120, 120)); //imposing a rectangle on image1// namedWindow("Image_Window1"); //Declaring an window to show actual image// namedWindow("Image_Window2"); //Declaring an window to show ROI// imshow("Image_Window1", image1); //Showing actual image// imshow("Image_Window2", image2); waitKey(0); return 0; }
[ { "code": null, "e": 1252, "s": 1062, "text": "To separate a particular portion from the image, we have to locate the area first. Then we\nhave to copy that area from the main image to another matrix. This is how the ROI in\nOpenCV works." }, { "code": null, "e": 1588, "s": 1252, "text": "In this example, two matrices have been declared at the beginning. After that, an image named 'image_name.jpg' has been loaded into the 'image1' matrix. The next line 'image2=image1 (Rect(100, 100, 120, 120));' requires special attention. This line is cropping out the defined region of the image and storing it in the 'image2' matrix." }, { "code": null, "e": 1900, "s": 1588, "text": "The figure shows what we have done here with the 'Rect(100,100,120,120)' code. The\nbasic form of this line of code is 'Rect(x, y,x1,y1)'. Here x and y defines the rectangle's starting point and x1 and y1represents the endpoint of the rectangle. By changing these values, we can change the size of the rectangle." }, { "code": null, "e": 1980, "s": 1900, "text": "The following program demonstrates the working of Region of Interest in OpenCV:" }, { "code": null, "e": 2617, "s": 1980, "text": "#include\n#include\n#include\nusing namespace std;\nusing namespace cv;\nint main() {\n Mat image1; //Declaring a matrix named 'image1'//\n Mat image2; //Declaring a matrix named 'image2'//\n image1 = imread(\"RGB.png\"); //Loading an image name 'image_name.png into image1 matrix//\n image2 = image1(Rect(100, 100, 120, 120)); //imposing a rectangle on\n image1//\n namedWindow(\"Image_Window1\"); //Declaring an window to show actual image//\n namedWindow(\"Image_Window2\"); //Declaring an window to show ROI//\n imshow(\"Image_Window1\", image1); //Showing actual image//\n imshow(\"Image_Window2\", image2);\n waitKey(0);\n return 0;\n}" } ]
Bitonic Sort - GeeksforGeeks
12 Apr, 2022 Background Bitonic Sort is a classic parallel algorithm for sorting. Bitonic sort does O(n Log 2n) comparisons. The number of comparisons done by Bitonic sort are more than popular sorting algorithms like Merge Sort [ does O(nLogn) comparisons], but Bitonice sort is better for parallel implementation because we always compare elements in predefined sequence and the sequence of comparison doesn’t depend on data. Therefore it is suitable for implementation in hardware and parallel processor array. Bitonic Sort must be done if number of elements to sort are 2^n. The procedure of bitonic sequence fails if the number of elements are not in the aforementioned quantity precisely. To understand Bitonic Sort, we must first understand what is Bitonic Sequence and how to make a given sequence Bitonic. Bitonic Sequence A sequence is called Bitonic if it is first increasing, then decreasing. In other words, an array arr[0..n-i] is Bitonic if there exists an index i where 0<=i<=n-1 such that x0 <= x1 .....<= xi and xi >= xi+1..... >= xn-1 A sequence, sorted in increasing order is considered Bitonic with the decreasing part as empty. Similarly, decreasing order sequence is considered Bitonic with the increasing part as empty.A rotation of Bitonic Sequence is also bitonic. A sequence, sorted in increasing order is considered Bitonic with the decreasing part as empty. Similarly, decreasing order sequence is considered Bitonic with the increasing part as empty. A rotation of Bitonic Sequence is also bitonic. How to form a Bitonic Sequence from a random input? We start by forming 4-element bitonic sequences from consecutive 2-element sequence. Consider 4-element in sequence x0, x1, x2, x3. We sort x0 and x1 in ascending order and x2 and x3 in descending order. We then concatenate the two pairs to form a 4 element bitonic sequence. Next, we take two 4 element bitonic sequences, sorting one in ascending order, the other in descending order (using the Bitonic Sort which we will discuss below), and so on, until we obtain the bitonic sequence. Example: Convert the following sequence to bitonic sequence: 3, 7, 4, 8, 6, 2, 1, 5 Step 1: Consider each 2-consecutive elements as bitonic sequence and apply bitonic sort on each 2- pair elements. In next step, take two 4 element bitonic sequences and so on. Note: x0 and x1 are sorted in ascending order and x2 and x3 in descending order and so on Step 2: Two 4 element bitonic sequences: A(3,7,8,4) and B(2,6,5,1) with comparator length as 2 After this step, we’ll get Bitonic sequence of length 8. 3, 4, 7, 8, 6, 5, 2, 1 Bitonic Sorting It mainly involves two steps. Forming a bitonic sequence (discussed above in detail). After this step we reach the fourth stage in below diagram, i.e., the array becomes {3, 4, 7, 8, 6, 5, 2, 1}Creating one sorted sequence from bitonic sequence: After first step, first half is sorted in increasing order and second half in decreasing order. We compare first element of first half with first element of second half, then second element of first half with second element of second, and so on. We exchange elements if an element of first half is smaller. After above compare and exchange steps, we get two bitonic sequences in array. See fifth stage in below diagram. In the fifth stage, we have {3, 4, 2, 1, 6, 5, 7, 8}. If we take a closer look at the elements, we can notice that there are two bitonic sequences of length n/2 such that all elements in first bitonic sequence {3, 4, 2, 1} are smaller than all elements of second bitonic sequence {6, 5, 7, 8}. We repeat the same process within two bitonic sequences and we get four bitonic sequences of length n/4 such that all elements of leftmost bitonic sequence are smaller and all elements of rightmost. See sixth stage in below diagram, arrays is {2, 1, 3, 4, 6, 5, 7, 8}. If we repeat this process one more time we get 8 bitonic sequences of size n/8 which is 1. Since all these bitonic sequence are sorted and every bitonic sequence has one element, we get the sorted array. Forming a bitonic sequence (discussed above in detail). After this step we reach the fourth stage in below diagram, i.e., the array becomes {3, 4, 7, 8, 6, 5, 2, 1} Creating one sorted sequence from bitonic sequence: After first step, first half is sorted in increasing order and second half in decreasing order. We compare first element of first half with first element of second half, then second element of first half with second element of second, and so on. We exchange elements if an element of first half is smaller. After above compare and exchange steps, we get two bitonic sequences in array. See fifth stage in below diagram. In the fifth stage, we have {3, 4, 2, 1, 6, 5, 7, 8}. If we take a closer look at the elements, we can notice that there are two bitonic sequences of length n/2 such that all elements in first bitonic sequence {3, 4, 2, 1} are smaller than all elements of second bitonic sequence {6, 5, 7, 8}. We repeat the same process within two bitonic sequences and we get four bitonic sequences of length n/4 such that all elements of leftmost bitonic sequence are smaller and all elements of rightmost. See sixth stage in below diagram, arrays is {2, 1, 3, 4, 6, 5, 7, 8}. If we repeat this process one more time we get 8 bitonic sequences of size n/8 which is 1. Since all these bitonic sequence are sorted and every bitonic sequence has one element, we get the sorted array. Below are implementations of Bitonic Sort. C++ Java Python3 C# Javascript /* C++ Program for Bitonic Sort. Note that this program works only when size of input is a power of 2. */#include<bits/stdc++.h>using namespace std; /*The parameter dir indicates the sorting direction, ASCENDING or DESCENDING; if (a[i] > a[j]) agrees with the direction, then a[i] and a[j] are interchanged.*/void compAndSwap(int a[], int i, int j, int dir){ if (dir==(a[i]>a[j])) swap(a[i],a[j]);} /*It recursively sorts a bitonic sequence in ascending order, if dir = 1, and in descending order otherwise (means dir=0). The sequence to be sorted starts at index position low, the parameter cnt is the number of elements to be sorted.*/void bitonicMerge(int a[], int low, int cnt, int dir){ if (cnt>1) { int k = cnt/2; for (int i=low; i<low+k; i++) compAndSwap(a, i, i+k, dir); bitonicMerge(a, low, k, dir); bitonicMerge(a, low+k, k, dir); }} /* This function first produces a bitonic sequence by recursively sorting its two halves in opposite sorting orders, and then calls bitonicMerge to make them in the same order */void bitonicSort(int a[],int low, int cnt, int dir){ if (cnt>1) { int k = cnt/2; // sort in ascending order since dir here is 1 bitonicSort(a, low, k, 1); // sort in descending order since dir here is 0 bitonicSort(a, low+k, k, 0); // Will merge whole sequence in ascending order // since dir=1. bitonicMerge(a,low, cnt, dir); }} /* Caller of bitonicSort for sorting the entire array of length N in ASCENDING order */void sort(int a[], int N, int up){ bitonicSort(a,0, N, up);} // Driver codeint main(){ int a[]= {3, 7, 4, 8, 6, 2, 1, 5}; int N = sizeof(a)/sizeof(a[0]); int up = 1; // means sort in ascending order sort(a, N, up); printf("Sorted array: \n"); for (int i=0; i<N; i++) printf("%d ", a[i]); return 0;} /* Java program for Bitonic Sort. Note that this program works only when size of input is a power of 2. */public class BitonicSort{ /* The parameter dir indicates the sorting direction, ASCENDING or DESCENDING; if (a[i] > a[j]) agrees with the direction, then a[i] and a[j] are interchanged. */ void compAndSwap(int a[], int i, int j, int dir) { if ( (a[i] > a[j] && dir == 1) || (a[i] < a[j] && dir == 0)) { // Swapping elements int temp = a[i]; a[i] = a[j]; a[j] = temp; } } /* It recursively sorts a bitonic sequence in ascending order, if dir = 1, and in descending order otherwise (means dir=0). The sequence to be sorted starts at index position low, the parameter cnt is the number of elements to be sorted.*/ void bitonicMerge(int a[], int low, int cnt, int dir) { if (cnt>1) { int k = cnt/2; for (int i=low; i<low+k; i++) compAndSwap(a,i, i+k, dir); bitonicMerge(a,low, k, dir); bitonicMerge(a,low+k, k, dir); } } /* This function first produces a bitonic sequence by recursively sorting its two halves in opposite sorting orders, and then calls bitonicMerge to make them in the same order */ void bitonicSort(int a[], int low, int cnt, int dir) { if (cnt>1) { int k = cnt/2; // sort in ascending order since dir here is 1 bitonicSort(a, low, k, 1); // sort in descending order since dir here is 0 bitonicSort(a,low+k, k, 0); // Will merge whole sequence in ascending order // since dir=1. bitonicMerge(a, low, cnt, dir); } } /*Caller of bitonicSort for sorting the entire array of length N in ASCENDING order */ void sort(int a[], int N, int up) { bitonicSort(a, 0, N, up); } /* A utility function to print array of size n */ static void printArray(int arr[]) { int n = arr.length; for (int i=0; i<n; ++i) System.out.print(arr[i] + " "); System.out.println(); } // Driver method public static void main(String args[]) { int a[] = {3, 7, 4, 8, 6, 2, 1, 5}; int up = 1; BitonicSort ob = new BitonicSort(); ob.sort(a, a.length,up); System.out.println("\nSorted array"); printArray(a); }} # Python program for Bitonic Sort. Note that this program# works only when size of input is a power of 2. # The parameter dir indicates the sorting direction, ASCENDING# or DESCENDING; if (a[i] > a[j]) agrees with the direction,# then a[i] and a[j] are interchanged.*/def compAndSwap(a, i, j, dire): if (dire==1 and a[i] > a[j]) or (dire==0 and a[i] < a[j]): a[i],a[j] = a[j],a[i] # It recursively sorts a bitonic sequence in ascending order,# if dir = 1, and in descending order otherwise (means dir=0).# The sequence to be sorted starts at index position low,# the parameter cnt is the number of elements to be sorted.def bitonicMerge(a, low, cnt, dire): if cnt > 1: k = cnt//2 for i in range(low , low+k): compAndSwap(a, i, i+k, dire) bitonicMerge(a, low, k, dire) bitonicMerge(a, low+k, k, dire) # This function first produces a bitonic sequence by recursively# sorting its two halves in opposite sorting orders, and then# calls bitonicMerge to make them in the same orderdef bitonicSort(a, low, cnt,dire): if cnt > 1: k = cnt//2 bitonicSort(a, low, k, 1) bitonicSort(a, low+k, k, 0) bitonicMerge(a, low, cnt, dire) # Caller of bitonicSort for sorting the entire array of length N# in ASCENDING orderdef sort(a,N, up): bitonicSort(a,0, N, up) # Driver code to test abovea = [3, 7, 4, 8, 6, 2, 1, 5]n = len(a)up = 1 sort(a, n, up)print ("\n\nSorted array is")for i in range(n): print("%d" %a[i],end=" ") /* C# Program for Bitonic Sort. Note that this program works only when size of input is a power of 2. */using System; /*The parameter dir indicates the sorting direction, ASCENDING or DESCENDING; if (a[i] > a[j]) agrees with the direction, then a[i] and a[j] are interchanged.*/class GFG{ /* To swap values */ static void Swap<T>(ref T lhs, ref T rhs) { T temp; temp = lhs; lhs = rhs; rhs = temp; } public static void compAndSwap(int[] a, int i, int j, int dir) { int k; if((a[i]>a[j])) k=1; else k=0; if (dir==k) Swap(ref a[i],ref a[j]); } /*It recursively sorts a bitonic sequence in ascending order, if dir = 1, and in descending order otherwise (means dir=0). The sequence to be sorted starts at index position low, the parameter cnt is the number of elements to be sorted.*/ public static void bitonicMerge(int[] a, int low, int cnt, int dir) { if (cnt>1) { int k = cnt/2; for (int i=low; i<low+k; i++) compAndSwap(a, i, i+k, dir); bitonicMerge(a, low, k, dir); bitonicMerge(a, low+k, k, dir); } } /* This function first produces a bitonic sequence by recursively sorting its two halves in opposite sorting orders, and then calls bitonicMerge to make them in the same order */ public static void bitonicSort(int[] a,int low, int cnt, int dir) { if (cnt>1) { int k = cnt/2; // sort in ascending order since dir here is 1 bitonicSort(a, low, k, 1); // sort in descending order since dir here is 0 bitonicSort(a, low+k, k, 0); // Will merge whole sequence in ascending order // since dir=1. bitonicMerge(a,low, cnt, dir); } } /* Caller of bitonicSort for sorting the entire array of length N in ASCENDING order */ public static void sort(int[] a, int N, int up) { bitonicSort(a,0, N, up); } // Driver code static void Main() { int[] a= {3, 7, 4, 8, 6, 2, 1, 5}; int N = a.Length; int up = 1; // means sort in ascending order sort(a, N, up); Console.Write("Sorted array: \n"); for (int i=0; i<N; i++) Console.Write(a[i] + " "); } //This code is contributed by DrRoot_} <script> /* JavaScript program for Bitonic Sort. Note that this program works only when size of input is a power of 2. */ /* The parameter dir indicates the sorting direction, ASCENDING or DESCENDING; if (a[i] > a[j]) agrees with the direction, then a[i] and a[j] are interchanged. */ function compAndSwap(a, i, j, dir) { if ((a[i] > a[j] && dir === 1) || (a[i] < a[j] && dir === 0)) { // Swapping elements var temp = a[i]; a[i] = a[j]; a[j] = temp; } } /* It recursively sorts a bitonic sequence in ascending order, if dir = 1, and in descending order otherwise (means dir=0). The sequence to be sorted starts at index position low, the parameter cnt is the number of elements to be sorted.*/ function bitonicMerge(a, low, cnt, dir) { if (cnt > 1) { var k = parseInt(cnt / 2); for (var i = low; i < low + k; i++) compAndSwap(a, i, i + k, dir); bitonicMerge(a, low, k, dir); bitonicMerge(a, low + k, k, dir); } } /* This function first produces a bitonic sequence by recursively sorting its two halves in opposite sorting orders, and then calls bitonicMerge to make them in the same order */ function bitonicSort(a, low, cnt, dir) { if (cnt > 1) { var k = parseInt(cnt / 2); // sort in ascending order since dir here is 1 bitonicSort(a, low, k, 1); // sort in descending order since dir here is 0 bitonicSort(a, low + k, k, 0); // Will merge whole sequence in ascending order // since dir=1. bitonicMerge(a, low, cnt, dir); } } /*Caller of bitonicSort for sorting the entire array of length N in ASCENDING order */ function sort(a, N, up) { bitonicSort(a, 0, N, up); } /* A utility function to print array of size n */ function printArray(arr) { var n = arr.length; for (var i = 0; i < n; ++i) document.write(arr[i] + " "); document.write("<br>"); } // Driver method var a = [3, 7, 4, 8, 6, 2, 1, 5]; var up = 1; sort(a, a.length, up); document.write("Sorted array: <br>"); printArray(a); </script> Output: Sorted array: 1 2 3 4 5 6 7 8 Analysis of Bitonic Sort To form a sorted sequence of length n from two sorted sequences of length n/2, log(n) comparisons are required (for example: log(8) = 3 when sequence size. Therefore, The number of comparisons T(n) of the entire sorting is given by:T(n) = log(n) + T(n/2)The solution of this recurrence equation isT(n) = log(n) + log(n)-1 + log(n)-2 + ... + 1 = log(n) · (log(n)+1) / 2As, each stage of the sorting network consists of n/2 comparators. Therefore total ?(n log2n) comparators. References: 1. https://www.youtube.com/watch?v=GEQ8y26blEY 2. http://www.iti.fh-flensburg.de/lang/algorithmen/sortieren/bitonic/bitonicen.htm 3. https://en.wikipedia.org/wiki/Bitonic_sorterThis article is contributed by Rahul Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. DrRoot_ shantanukonwar rdtank kk9826225 sagar0719kumar amartyaniel20 simmytarika5 Sorting Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. std::sort() in C++ STL Time Complexities of all Sorting Algorithms Radix Sort Merge two sorted arrays Sort an array of 0s, 1s and 2s Python Program for Bubble Sort Sorting Vector of Pairs in C++ | Set 1 (Sort by first and second) k largest(or smallest) elements in an array sort() in Python Count Inversions in an array | Set 1 (Using Merge Sort)
[ { "code": null, "e": 23634, "s": 23606, "text": "\n12 Apr, 2022" }, { "code": null, "e": 23645, "s": 23634, "text": "Background" }, { "code": null, "e": 23704, "s": 23645, "text": "Bitonic Sort is a classic parallel algorithm for sorting. " }, { "code": null, "e": 23747, "s": 23704, "text": "Bitonic sort does O(n Log 2n) comparisons." }, { "code": null, "e": 24136, "s": 23747, "text": "The number of comparisons done by Bitonic sort are more than popular sorting algorithms like Merge Sort [ does O(nLogn) comparisons], but Bitonice sort is better for parallel implementation because we always compare elements in predefined sequence and the sequence of comparison doesn’t depend on data. Therefore it is suitable for implementation in hardware and parallel processor array." }, { "code": null, "e": 24317, "s": 24136, "text": "Bitonic Sort must be done if number of elements to sort are 2^n. The procedure of bitonic sequence fails if the number of elements are not in the aforementioned quantity precisely." }, { "code": null, "e": 24439, "s": 24317, "text": "To understand Bitonic Sort, we must first understand what is Bitonic Sequence and how to make a given sequence Bitonic. " }, { "code": null, "e": 24456, "s": 24439, "text": "Bitonic Sequence" }, { "code": null, "e": 24632, "s": 24456, "text": "A sequence is called Bitonic if it is first increasing, then decreasing. In other words, an array arr[0..n-i] is Bitonic if there exists an index i where 0<=i<=n-1 such that " }, { "code": null, "e": 24683, "s": 24632, "text": "x0 <= x1 .....<= xi and xi >= xi+1..... >= xn-1 " }, { "code": null, "e": 24920, "s": 24683, "text": "A sequence, sorted in increasing order is considered Bitonic with the decreasing part as empty. Similarly, decreasing order sequence is considered Bitonic with the increasing part as empty.A rotation of Bitonic Sequence is also bitonic." }, { "code": null, "e": 25110, "s": 24920, "text": "A sequence, sorted in increasing order is considered Bitonic with the decreasing part as empty. Similarly, decreasing order sequence is considered Bitonic with the increasing part as empty." }, { "code": null, "e": 25158, "s": 25110, "text": "A rotation of Bitonic Sequence is also bitonic." }, { "code": null, "e": 25698, "s": 25158, "text": "How to form a Bitonic Sequence from a random input? We start by forming 4-element bitonic sequences from consecutive 2-element sequence. Consider 4-element in sequence x0, x1, x2, x3. We sort x0 and x1 in ascending order and x2 and x3 in descending order. We then concatenate the two pairs to form a 4 element bitonic sequence. Next, we take two 4 element bitonic sequences, sorting one in ascending order, the other in descending order (using the Bitonic Sort which we will discuss below), and so on, until we obtain the bitonic sequence." }, { "code": null, "e": 25783, "s": 25698, "text": "Example: Convert the following sequence to bitonic sequence: 3, 7, 4, 8, 6, 2, 1, 5 " }, { "code": null, "e": 25959, "s": 25783, "text": "Step 1: Consider each 2-consecutive elements as bitonic sequence and apply bitonic sort on each 2- pair elements. In next step, take two 4 element bitonic sequences and so on." }, { "code": null, "e": 26049, "s": 25959, "text": "Note: x0 and x1 are sorted in ascending order and x2 and x3 in descending order and so on" }, { "code": null, "e": 26145, "s": 26049, "text": "Step 2: Two 4 element bitonic sequences: A(3,7,8,4) and B(2,6,5,1) with comparator length as 2 " }, { "code": null, "e": 26203, "s": 26145, "text": "After this step, we’ll get Bitonic sequence of length 8. " }, { "code": null, "e": 26227, "s": 26203, "text": " 3, 4, 7, 8, 6, 5, 2, 1" }, { "code": null, "e": 26243, "s": 26227, "text": "Bitonic Sorting" }, { "code": null, "e": 26275, "s": 26243, "text": "It mainly involves two steps. " }, { "code": null, "e": 27678, "s": 26275, "text": "Forming a bitonic sequence (discussed above in detail). After this step we reach the fourth stage in below diagram, i.e., the array becomes {3, 4, 7, 8, 6, 5, 2, 1}Creating one sorted sequence from bitonic sequence: After first step, first half is sorted in increasing order and second half in decreasing order. We compare first element of first half with first element of second half, then second element of first half with second element of second, and so on. We exchange elements if an element of first half is smaller. After above compare and exchange steps, we get two bitonic sequences in array. See fifth stage in below diagram. In the fifth stage, we have {3, 4, 2, 1, 6, 5, 7, 8}. If we take a closer look at the elements, we can notice that there are two bitonic sequences of length n/2 such that all elements in first bitonic sequence {3, 4, 2, 1} are smaller than all elements of second bitonic sequence {6, 5, 7, 8}. We repeat the same process within two bitonic sequences and we get four bitonic sequences of length n/4 such that all elements of leftmost bitonic sequence are smaller and all elements of rightmost. See sixth stage in below diagram, arrays is {2, 1, 3, 4, 6, 5, 7, 8}. If we repeat this process one more time we get 8 bitonic sequences of size n/8 which is 1. Since all these bitonic sequence are sorted and every bitonic sequence has one element, we get the sorted array." }, { "code": null, "e": 27843, "s": 27678, "text": "Forming a bitonic sequence (discussed above in detail). After this step we reach the fourth stage in below diagram, i.e., the array becomes {3, 4, 7, 8, 6, 5, 2, 1}" }, { "code": null, "e": 29082, "s": 27843, "text": "Creating one sorted sequence from bitonic sequence: After first step, first half is sorted in increasing order and second half in decreasing order. We compare first element of first half with first element of second half, then second element of first half with second element of second, and so on. We exchange elements if an element of first half is smaller. After above compare and exchange steps, we get two bitonic sequences in array. See fifth stage in below diagram. In the fifth stage, we have {3, 4, 2, 1, 6, 5, 7, 8}. If we take a closer look at the elements, we can notice that there are two bitonic sequences of length n/2 such that all elements in first bitonic sequence {3, 4, 2, 1} are smaller than all elements of second bitonic sequence {6, 5, 7, 8}. We repeat the same process within two bitonic sequences and we get four bitonic sequences of length n/4 such that all elements of leftmost bitonic sequence are smaller and all elements of rightmost. See sixth stage in below diagram, arrays is {2, 1, 3, 4, 6, 5, 7, 8}. If we repeat this process one more time we get 8 bitonic sequences of size n/8 which is 1. Since all these bitonic sequence are sorted and every bitonic sequence has one element, we get the sorted array." }, { "code": null, "e": 29126, "s": 29082, "text": "Below are implementations of Bitonic Sort. " }, { "code": null, "e": 29130, "s": 29126, "text": "C++" }, { "code": null, "e": 29135, "s": 29130, "text": "Java" }, { "code": null, "e": 29143, "s": 29135, "text": "Python3" }, { "code": null, "e": 29146, "s": 29143, "text": "C#" }, { "code": null, "e": 29157, "s": 29146, "text": "Javascript" }, { "code": "/* C++ Program for Bitonic Sort. Note that this program works only when size of input is a power of 2. */#include<bits/stdc++.h>using namespace std; /*The parameter dir indicates the sorting direction, ASCENDING or DESCENDING; if (a[i] > a[j]) agrees with the direction, then a[i] and a[j] are interchanged.*/void compAndSwap(int a[], int i, int j, int dir){ if (dir==(a[i]>a[j])) swap(a[i],a[j]);} /*It recursively sorts a bitonic sequence in ascending order, if dir = 1, and in descending order otherwise (means dir=0). The sequence to be sorted starts at index position low, the parameter cnt is the number of elements to be sorted.*/void bitonicMerge(int a[], int low, int cnt, int dir){ if (cnt>1) { int k = cnt/2; for (int i=low; i<low+k; i++) compAndSwap(a, i, i+k, dir); bitonicMerge(a, low, k, dir); bitonicMerge(a, low+k, k, dir); }} /* This function first produces a bitonic sequence by recursively sorting its two halves in opposite sorting orders, and then calls bitonicMerge to make them in the same order */void bitonicSort(int a[],int low, int cnt, int dir){ if (cnt>1) { int k = cnt/2; // sort in ascending order since dir here is 1 bitonicSort(a, low, k, 1); // sort in descending order since dir here is 0 bitonicSort(a, low+k, k, 0); // Will merge whole sequence in ascending order // since dir=1. bitonicMerge(a,low, cnt, dir); }} /* Caller of bitonicSort for sorting the entire array of length N in ASCENDING order */void sort(int a[], int N, int up){ bitonicSort(a,0, N, up);} // Driver codeint main(){ int a[]= {3, 7, 4, 8, 6, 2, 1, 5}; int N = sizeof(a)/sizeof(a[0]); int up = 1; // means sort in ascending order sort(a, N, up); printf(\"Sorted array: \\n\"); for (int i=0; i<N; i++) printf(\"%d \", a[i]); return 0;}", "e": 31073, "s": 29157, "text": null }, { "code": "/* Java program for Bitonic Sort. Note that this program works only when size of input is a power of 2. */public class BitonicSort{ /* The parameter dir indicates the sorting direction, ASCENDING or DESCENDING; if (a[i] > a[j]) agrees with the direction, then a[i] and a[j] are interchanged. */ void compAndSwap(int a[], int i, int j, int dir) { if ( (a[i] > a[j] && dir == 1) || (a[i] < a[j] && dir == 0)) { // Swapping elements int temp = a[i]; a[i] = a[j]; a[j] = temp; } } /* It recursively sorts a bitonic sequence in ascending order, if dir = 1, and in descending order otherwise (means dir=0). The sequence to be sorted starts at index position low, the parameter cnt is the number of elements to be sorted.*/ void bitonicMerge(int a[], int low, int cnt, int dir) { if (cnt>1) { int k = cnt/2; for (int i=low; i<low+k; i++) compAndSwap(a,i, i+k, dir); bitonicMerge(a,low, k, dir); bitonicMerge(a,low+k, k, dir); } } /* This function first produces a bitonic sequence by recursively sorting its two halves in opposite sorting orders, and then calls bitonicMerge to make them in the same order */ void bitonicSort(int a[], int low, int cnt, int dir) { if (cnt>1) { int k = cnt/2; // sort in ascending order since dir here is 1 bitonicSort(a, low, k, 1); // sort in descending order since dir here is 0 bitonicSort(a,low+k, k, 0); // Will merge whole sequence in ascending order // since dir=1. bitonicMerge(a, low, cnt, dir); } } /*Caller of bitonicSort for sorting the entire array of length N in ASCENDING order */ void sort(int a[], int N, int up) { bitonicSort(a, 0, N, up); } /* A utility function to print array of size n */ static void printArray(int arr[]) { int n = arr.length; for (int i=0; i<n; ++i) System.out.print(arr[i] + \" \"); System.out.println(); } // Driver method public static void main(String args[]) { int a[] = {3, 7, 4, 8, 6, 2, 1, 5}; int up = 1; BitonicSort ob = new BitonicSort(); ob.sort(a, a.length,up); System.out.println(\"\\nSorted array\"); printArray(a); }}", "e": 33563, "s": 31073, "text": null }, { "code": "# Python program for Bitonic Sort. Note that this program# works only when size of input is a power of 2. # The parameter dir indicates the sorting direction, ASCENDING# or DESCENDING; if (a[i] > a[j]) agrees with the direction,# then a[i] and a[j] are interchanged.*/def compAndSwap(a, i, j, dire): if (dire==1 and a[i] > a[j]) or (dire==0 and a[i] < a[j]): a[i],a[j] = a[j],a[i] # It recursively sorts a bitonic sequence in ascending order,# if dir = 1, and in descending order otherwise (means dir=0).# The sequence to be sorted starts at index position low,# the parameter cnt is the number of elements to be sorted.def bitonicMerge(a, low, cnt, dire): if cnt > 1: k = cnt//2 for i in range(low , low+k): compAndSwap(a, i, i+k, dire) bitonicMerge(a, low, k, dire) bitonicMerge(a, low+k, k, dire) # This function first produces a bitonic sequence by recursively# sorting its two halves in opposite sorting orders, and then# calls bitonicMerge to make them in the same orderdef bitonicSort(a, low, cnt,dire): if cnt > 1: k = cnt//2 bitonicSort(a, low, k, 1) bitonicSort(a, low+k, k, 0) bitonicMerge(a, low, cnt, dire) # Caller of bitonicSort for sorting the entire array of length N# in ASCENDING orderdef sort(a,N, up): bitonicSort(a,0, N, up) # Driver code to test abovea = [3, 7, 4, 8, 6, 2, 1, 5]n = len(a)up = 1 sort(a, n, up)print (\"\\n\\nSorted array is\")for i in range(n): print(\"%d\" %a[i],end=\" \")", "e": 35067, "s": 33563, "text": null }, { "code": "/* C# Program for Bitonic Sort. Note that this program works only when size of input is a power of 2. */using System; /*The parameter dir indicates the sorting direction, ASCENDING or DESCENDING; if (a[i] > a[j]) agrees with the direction, then a[i] and a[j] are interchanged.*/class GFG{ /* To swap values */ static void Swap<T>(ref T lhs, ref T rhs) { T temp; temp = lhs; lhs = rhs; rhs = temp; } public static void compAndSwap(int[] a, int i, int j, int dir) { int k; if((a[i]>a[j])) k=1; else k=0; if (dir==k) Swap(ref a[i],ref a[j]); } /*It recursively sorts a bitonic sequence in ascending order, if dir = 1, and in descending order otherwise (means dir=0). The sequence to be sorted starts at index position low, the parameter cnt is the number of elements to be sorted.*/ public static void bitonicMerge(int[] a, int low, int cnt, int dir) { if (cnt>1) { int k = cnt/2; for (int i=low; i<low+k; i++) compAndSwap(a, i, i+k, dir); bitonicMerge(a, low, k, dir); bitonicMerge(a, low+k, k, dir); } } /* This function first produces a bitonic sequence by recursively sorting its two halves in opposite sorting orders, and then calls bitonicMerge to make them in the same order */ public static void bitonicSort(int[] a,int low, int cnt, int dir) { if (cnt>1) { int k = cnt/2; // sort in ascending order since dir here is 1 bitonicSort(a, low, k, 1); // sort in descending order since dir here is 0 bitonicSort(a, low+k, k, 0); // Will merge whole sequence in ascending order // since dir=1. bitonicMerge(a,low, cnt, dir); } } /* Caller of bitonicSort for sorting the entire array of length N in ASCENDING order */ public static void sort(int[] a, int N, int up) { bitonicSort(a,0, N, up); } // Driver code static void Main() { int[] a= {3, 7, 4, 8, 6, 2, 1, 5}; int N = a.Length; int up = 1; // means sort in ascending order sort(a, N, up); Console.Write(\"Sorted array: \\n\"); for (int i=0; i<N; i++) Console.Write(a[i] + \" \"); } //This code is contributed by DrRoot_}", "e": 37563, "s": 35067, "text": null }, { "code": "<script> /* JavaScript program for Bitonic Sort. Note that this program works only when size of input is a power of 2. */ /* The parameter dir indicates the sorting direction, ASCENDING or DESCENDING; if (a[i] > a[j]) agrees with the direction, then a[i] and a[j] are interchanged. */ function compAndSwap(a, i, j, dir) { if ((a[i] > a[j] && dir === 1) || (a[i] < a[j] && dir === 0)) { // Swapping elements var temp = a[i]; a[i] = a[j]; a[j] = temp; } } /* It recursively sorts a bitonic sequence in ascending order, if dir = 1, and in descending order otherwise (means dir=0). The sequence to be sorted starts at index position low, the parameter cnt is the number of elements to be sorted.*/ function bitonicMerge(a, low, cnt, dir) { if (cnt > 1) { var k = parseInt(cnt / 2); for (var i = low; i < low + k; i++) compAndSwap(a, i, i + k, dir); bitonicMerge(a, low, k, dir); bitonicMerge(a, low + k, k, dir); } } /* This function first produces a bitonic sequence by recursively sorting its two halves in opposite sorting orders, and then calls bitonicMerge to make them in the same order */ function bitonicSort(a, low, cnt, dir) { if (cnt > 1) { var k = parseInt(cnt / 2); // sort in ascending order since dir here is 1 bitonicSort(a, low, k, 1); // sort in descending order since dir here is 0 bitonicSort(a, low + k, k, 0); // Will merge whole sequence in ascending order // since dir=1. bitonicMerge(a, low, cnt, dir); } } /*Caller of bitonicSort for sorting the entire array of length N in ASCENDING order */ function sort(a, N, up) { bitonicSort(a, 0, N, up); } /* A utility function to print array of size n */ function printArray(arr) { var n = arr.length; for (var i = 0; i < n; ++i) document.write(arr[i] + \" \"); document.write(\"<br>\"); } // Driver method var a = [3, 7, 4, 8, 6, 2, 1, 5]; var up = 1; sort(a, a.length, up); document.write(\"Sorted array: <br>\"); printArray(a); </script>", "e": 39874, "s": 37563, "text": null }, { "code": null, "e": 39884, "s": 39874, "text": "Output: " }, { "code": null, "e": 39915, "s": 39884, "text": "Sorted array: \n1 2 3 4 5 6 7 8" }, { "code": null, "e": 39942, "s": 39917, "text": "Analysis of Bitonic Sort" }, { "code": null, "e": 40417, "s": 39942, "text": "To form a sorted sequence of length n from two sorted sequences of length n/2, log(n) comparisons are required (for example: log(8) = 3 when sequence size. Therefore, The number of comparisons T(n) of the entire sorting is given by:T(n) = log(n) + T(n/2)The solution of this recurrence equation isT(n) = log(n) + log(n)-1 + log(n)-2 + ... + 1 = log(n) · (log(n)+1) / 2As, each stage of the sorting network consists of n/2 comparators. Therefore total ?(n log2n) comparators." }, { "code": null, "e": 40999, "s": 40417, "text": "References: 1. https://www.youtube.com/watch?v=GEQ8y26blEY 2. http://www.iti.fh-flensburg.de/lang/algorithmen/sortieren/bitonic/bitonicen.htm 3. https://en.wikipedia.org/wiki/Bitonic_sorterThis article is contributed by Rahul Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 41007, "s": 40999, "text": "DrRoot_" }, { "code": null, "e": 41022, "s": 41007, "text": "shantanukonwar" }, { "code": null, "e": 41029, "s": 41022, "text": "rdtank" }, { "code": null, "e": 41039, "s": 41029, "text": "kk9826225" }, { "code": null, "e": 41054, "s": 41039, "text": "sagar0719kumar" }, { "code": null, "e": 41068, "s": 41054, "text": "amartyaniel20" }, { "code": null, "e": 41081, "s": 41068, "text": "simmytarika5" }, { "code": null, "e": 41089, "s": 41081, "text": "Sorting" }, { "code": null, "e": 41097, "s": 41089, "text": "Sorting" }, { "code": null, "e": 41195, "s": 41097, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 41218, "s": 41195, "text": "std::sort() in C++ STL" }, { "code": null, "e": 41262, "s": 41218, "text": "Time Complexities of all Sorting Algorithms" }, { "code": null, "e": 41273, "s": 41262, "text": "Radix Sort" }, { "code": null, "e": 41297, "s": 41273, "text": "Merge two sorted arrays" }, { "code": null, "e": 41328, "s": 41297, "text": "Sort an array of 0s, 1s and 2s" }, { "code": null, "e": 41359, "s": 41328, "text": "Python Program for Bubble Sort" }, { "code": null, "e": 41425, "s": 41359, "text": "Sorting Vector of Pairs in C++ | Set 1 (Sort by first and second)" }, { "code": null, "e": 41469, "s": 41425, "text": "k largest(or smallest) elements in an array" }, { "code": null, "e": 41486, "s": 41469, "text": "sort() in Python" } ]
Calculating n-th real root using binary search - GeeksforGeeks
28 Mar, 2022 Given two number x and n, find n-th root of x. Examples: Input : 5 2Output : 2.2360679768025875 Input : x = 5, n = 3Output : 1.70997594668 In order to calculate nth root of a number, we can use the following procedure. If x lies in the range [0, 1) then we set the lower limit low = x and upper limit high = 1, because for this range of numbers the nth root is always greater than the given number and can never exceed 1.eg- Otherwise, we take low = 1 and high = x.Declare a variable named epsilon and initialize it for accuracy you need. Say epsilon=0.01, then we can guarantee that our guess for nth root of the given number will be correct up to 2 decimal places.Declare a variable guess and initialize it to guess=(low+high)/2.Run a loop such that: if the absolute error of our guess is more than epsilon then do: if guessn > x, then high=guesselse low=guessMaking a new better guess i.e., guess=(low+high)/2.If the absolute error of our guess is less than epsilon then exit the loop. If x lies in the range [0, 1) then we set the lower limit low = x and upper limit high = 1, because for this range of numbers the nth root is always greater than the given number and can never exceed 1.eg- Otherwise, we take low = 1 and high = x. Declare a variable named epsilon and initialize it for accuracy you need. Say epsilon=0.01, then we can guarantee that our guess for nth root of the given number will be correct up to 2 decimal places. Declare a variable guess and initialize it to guess=(low+high)/2. Run a loop such that: if the absolute error of our guess is more than epsilon then do: if guessn > x, then high=guesselse low=guessMaking a new better guess i.e., guess=(low+high)/2.If the absolute error of our guess is less than epsilon then exit the loop. if the absolute error of our guess is more than epsilon then do: if guessn > x, then high=guesselse low=guessMaking a new better guess i.e., guess=(low+high)/2. if guessn > x, then high=guesselse low=guessMaking a new better guess i.e., guess=(low+high)/2. if guessn > x, then high=guess else low=guess Making a new better guess i.e., guess=(low+high)/2. If the absolute error of our guess is less than epsilon then exit the loop. Absolute Error: Absolute Error can be calculated as abs(guessn -x) C++ Java Python3 C# Javascript // C++ Program to find// n-th real root of x#include <bits/stdc++.h>using namespace std; void findNthRoot(double x, int n){ // Initialize boundary values double low, high; if (x >= 0 and x <= 1) { low = x; high = 1; } else { low = 1; high = x; } // Used for taking approximations // of the answer double epsilon = 0.00000001; // Do binary search double guess = (low + high) / 2; while (abs((pow(guess, n)) - x) >= epsilon) { if (pow(guess, n) > x) { high = guess; } else { low = guess; } guess = (low + high) / 2; } cout << fixed << setprecision(16) << guess;} // Driver codeint main(){ double x = 5; int n = 2; findNthRoot(x, n);} // This code is contributed// by Subhadeep // Java Program to find n-th real root of xclass GFG{ static void findNthRoot(double x, int n) { // Initialize boundary values double low, high; if (x >= 0 && x <= 1) { low = x; high = 1; } else { low = 1; high = x; } // used for taking approximations // of the answer double epsilon = 0.00000001; // Do binary search double guess = (low + high) / 2; while (Math.abs((Math.pow(guess, n)) - x) >= epsilon) { if (Math.pow(guess, n) > x) { high = guess; } else { low = guess; } guess = (low + high) / 2; } System.out.println(guess); } // Driver code public static void main(String[] args) { double x = 5; int n = 2; findNthRoot(x, n); }} // This code is contributed// by mits # Python Program to find n-th real root# of x def findNthRoot(x, n): # Initialize boundary values x = float(x) n = int(n) if (x >= 0 and x <= 1): low = x high = 1 else: low = 1 high = x # used for taking approximations # of the answer epsilon = 0.00000001 # Do binary search guess = (low + high) / 2 while abs(guess ** n - x) >= epsilon: if guess ** n > x: high = guess else: low = guess guess = (low + high) / 2 print(guess) # Driver codex = 5n = 2findNthRoot(x, n) // C# Program to find n-th real root of x using System; public class GFG { static void findNthRoot(double x, int n) { // Initialize boundary values double low, high; if (x >= 0 && x <= 1) { low = x; high = 1; } else { low = 1; high = x; } // used for taking approximations // of the answer double epsilon = 0.00000001; // Do binary search double guess = (low + high) / 2; while (Math.Abs((Math.Pow(guess, n)) - x) >= epsilon) { if (Math.Pow(guess, n) > x) { high = guess; } else { low = guess; } guess = (low + high) / 2; } Console.WriteLine(guess); } // Driver code static public void Main() { double x = 5; int n = 2; findNthRoot(x, n); }} // This code is contributed by akt_mit <script> // Javascript Program to find n-th // real root of x function findNthRoot(x, n) { // Initialize boundary values let low, high; if (x >= 0 && x <= 1) { low = x; high = 1; } else { low = 1; high = x; } // used for taking approximations // of the answer let epsilon = 0.00000001; // Do binary search let guess = parseInt((low + high) / 2, 10); while (Math.abs((Math.pow(guess, n)) - x) >= epsilon) { if (Math.pow(guess, n) > x) { high = guess; } else { low = guess; } guess = (low + high) / 2; } document.write(guess); } let x = 5; let n = 2; findNthRoot(x, n); </script> 2.2360679768025875 Time Complexity: O( log( x * 10d)*logguess(n) ) Auxiliary Space: O(1) Here d is the number of decimal places upto which we want the result accurately. Explanation of first example with epsilon = 0.01 Since taking too small value of epsilon as taken in our program might not be feasible for explanation because it will increase the number of steps drastically so for the sake of simplicity we are taking epsilon = 0.01 The above procedure will work as follows: Say we have to calculate the then x = 5, low = 1, high = 5.Taking epsilon = 0.01First Guess:guess = (1 + 5) / 2 = 3Absolute error = |32 - 5| = 4 > epsilonguess2 = 9 > 5(x) then high = guess --> high = 3Second Guess:guess = (1 + 3) / 2 = 2Absolute error = |22 - 5| = 1 > epsilonguess2 = 4 > 5(x) then low = guess --> low = 2Third Guess:guess = (2 + 3) / 2 = 2.5Absolute error = |2.52 - 5| = 1.25 > epsilonguess2 = 6.25 > 5(x) then high = guess --> high = 2.5and proceeding so on we will get the correct up to 2 decimal places i.e., = 2.23600456We will ignore the digits after 2 decimal places since they may or may not be correct. tufan_gupta2000 Mithun Kumar jit_t mdrashidmeraj2002 divyeshrabadiya07 rohanthakurarmy Binary Search Mathematical Mathematical Binary Search Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Modulo Operator (%) in C/C++ with Examples Program to find GCD or HCF of two numbers Merge two sorted arrays Prime Numbers Program to find sum of elements in a given array Program for factorial of a number Program for Decimal to Binary Conversion Sieve of Eratosthenes Operators in C / C++ The Knight's tour problem | Backtracking-1
[ { "code": null, "e": 24906, "s": 24878, "text": "\n28 Mar, 2022" }, { "code": null, "e": 24954, "s": 24906, "text": "Given two number x and n, find n-th root of x. " }, { "code": null, "e": 24965, "s": 24954, "text": "Examples: " }, { "code": null, "e": 25004, "s": 24965, "text": "Input : 5 2Output : 2.2360679768025875" }, { "code": null, "e": 25048, "s": 25004, "text": "Input : x = 5, n = 3Output : 1.70997594668" }, { "code": null, "e": 25130, "s": 25048, "text": "In order to calculate nth root of a number, we can use the following procedure. " }, { "code": null, "e": 25900, "s": 25130, "text": "If x lies in the range [0, 1) then we set the lower limit low = x and upper limit high = 1, because for this range of numbers the nth root is always greater than the given number and can never exceed 1.eg- Otherwise, we take low = 1 and high = x.Declare a variable named epsilon and initialize it for accuracy you need. Say epsilon=0.01, then we can guarantee that our guess for nth root of the given number will be correct up to 2 decimal places.Declare a variable guess and initialize it to guess=(low+high)/2.Run a loop such that: if the absolute error of our guess is more than epsilon then do: if guessn > x, then high=guesselse low=guessMaking a new better guess i.e., guess=(low+high)/2.If the absolute error of our guess is less than epsilon then exit the loop." }, { "code": null, "e": 26107, "s": 25900, "text": "If x lies in the range [0, 1) then we set the lower limit low = x and upper limit high = 1, because for this range of numbers the nth root is always greater than the given number and can never exceed 1.eg- " }, { "code": null, "e": 26148, "s": 26107, "text": "Otherwise, we take low = 1 and high = x." }, { "code": null, "e": 26350, "s": 26148, "text": "Declare a variable named epsilon and initialize it for accuracy you need. Say epsilon=0.01, then we can guarantee that our guess for nth root of the given number will be correct up to 2 decimal places." }, { "code": null, "e": 26416, "s": 26350, "text": "Declare a variable guess and initialize it to guess=(low+high)/2." }, { "code": null, "e": 26674, "s": 26416, "text": "Run a loop such that: if the absolute error of our guess is more than epsilon then do: if guessn > x, then high=guesselse low=guessMaking a new better guess i.e., guess=(low+high)/2.If the absolute error of our guess is less than epsilon then exit the loop." }, { "code": null, "e": 26835, "s": 26674, "text": "if the absolute error of our guess is more than epsilon then do: if guessn > x, then high=guesselse low=guessMaking a new better guess i.e., guess=(low+high)/2." }, { "code": null, "e": 26931, "s": 26835, "text": "if guessn > x, then high=guesselse low=guessMaking a new better guess i.e., guess=(low+high)/2." }, { "code": null, "e": 26962, "s": 26931, "text": "if guessn > x, then high=guess" }, { "code": null, "e": 26977, "s": 26962, "text": "else low=guess" }, { "code": null, "e": 27029, "s": 26977, "text": "Making a new better guess i.e., guess=(low+high)/2." }, { "code": null, "e": 27105, "s": 27029, "text": "If the absolute error of our guess is less than epsilon then exit the loop." }, { "code": null, "e": 27173, "s": 27105, "text": "Absolute Error: Absolute Error can be calculated as abs(guessn -x) " }, { "code": null, "e": 27177, "s": 27173, "text": "C++" }, { "code": null, "e": 27182, "s": 27177, "text": "Java" }, { "code": null, "e": 27190, "s": 27182, "text": "Python3" }, { "code": null, "e": 27193, "s": 27190, "text": "C#" }, { "code": null, "e": 27204, "s": 27193, "text": "Javascript" }, { "code": "// C++ Program to find// n-th real root of x#include <bits/stdc++.h>using namespace std; void findNthRoot(double x, int n){ // Initialize boundary values double low, high; if (x >= 0 and x <= 1) { low = x; high = 1; } else { low = 1; high = x; } // Used for taking approximations // of the answer double epsilon = 0.00000001; // Do binary search double guess = (low + high) / 2; while (abs((pow(guess, n)) - x) >= epsilon) { if (pow(guess, n) > x) { high = guess; } else { low = guess; } guess = (low + high) / 2; } cout << fixed << setprecision(16) << guess;} // Driver codeint main(){ double x = 5; int n = 2; findNthRoot(x, n);} // This code is contributed// by Subhadeep", "e": 28042, "s": 27204, "text": null }, { "code": "// Java Program to find n-th real root of xclass GFG{ static void findNthRoot(double x, int n) { // Initialize boundary values double low, high; if (x >= 0 && x <= 1) { low = x; high = 1; } else { low = 1; high = x; } // used for taking approximations // of the answer double epsilon = 0.00000001; // Do binary search double guess = (low + high) / 2; while (Math.abs((Math.pow(guess, n)) - x) >= epsilon) { if (Math.pow(guess, n) > x) { high = guess; } else { low = guess; } guess = (low + high) / 2; } System.out.println(guess); } // Driver code public static void main(String[] args) { double x = 5; int n = 2; findNthRoot(x, n); }} // This code is contributed// by mits", "e": 29046, "s": 28042, "text": null }, { "code": "# Python Program to find n-th real root# of x def findNthRoot(x, n): # Initialize boundary values x = float(x) n = int(n) if (x >= 0 and x <= 1): low = x high = 1 else: low = 1 high = x # used for taking approximations # of the answer epsilon = 0.00000001 # Do binary search guess = (low + high) / 2 while abs(guess ** n - x) >= epsilon: if guess ** n > x: high = guess else: low = guess guess = (low + high) / 2 print(guess) # Driver codex = 5n = 2findNthRoot(x, n)", "e": 29625, "s": 29046, "text": null }, { "code": "// C# Program to find n-th real root of x using System; public class GFG { static void findNthRoot(double x, int n) { // Initialize boundary values double low, high; if (x >= 0 && x <= 1) { low = x; high = 1; } else { low = 1; high = x; } // used for taking approximations // of the answer double epsilon = 0.00000001; // Do binary search double guess = (low + high) / 2; while (Math.Abs((Math.Pow(guess, n)) - x) >= epsilon) { if (Math.Pow(guess, n) > x) { high = guess; } else { low = guess; } guess = (low + high) / 2; } Console.WriteLine(guess); } // Driver code static public void Main() { double x = 5; int n = 2; findNthRoot(x, n); }} // This code is contributed by akt_mit", "e": 30637, "s": 29625, "text": null }, { "code": "<script> // Javascript Program to find n-th // real root of x function findNthRoot(x, n) { // Initialize boundary values let low, high; if (x >= 0 && x <= 1) { low = x; high = 1; } else { low = 1; high = x; } // used for taking approximations // of the answer let epsilon = 0.00000001; // Do binary search let guess = parseInt((low + high) / 2, 10); while (Math.abs((Math.pow(guess, n)) - x) >= epsilon) { if (Math.pow(guess, n) > x) { high = guess; } else { low = guess; } guess = (low + high) / 2; } document.write(guess); } let x = 5; let n = 2; findNthRoot(x, n); </script>", "e": 31547, "s": 30637, "text": null }, { "code": null, "e": 31566, "s": 31547, "text": "2.2360679768025875" }, { "code": null, "e": 31614, "s": 31566, "text": "Time Complexity: O( log( x * 10d)*logguess(n) )" }, { "code": null, "e": 31636, "s": 31614, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 31717, "s": 31636, "text": "Here d is the number of decimal places upto which we want the result accurately." }, { "code": null, "e": 31766, "s": 31717, "text": "Explanation of first example with epsilon = 0.01" }, { "code": null, "e": 32658, "s": 31766, "text": "Since taking too small value of epsilon as taken in our program might not be feasible for\nexplanation because it will increase the number of steps drastically so for the sake of\nsimplicity we are taking epsilon = 0.01\nThe above procedure will work as follows:\nSay we have to calculate the then x = 5, low = 1, high = 5.Taking epsilon = 0.01First Guess:guess = (1 + 5) / 2 = 3Absolute error = |32 - 5| = 4 > epsilonguess2 = 9 > 5(x) then high = guess --> high = 3Second Guess:guess = (1 + 3) / 2 = 2Absolute error = |22 - 5| = 1 > epsilonguess2 = 4 > 5(x) then low = guess --> low = 2Third Guess:guess = (2 + 3) / 2 = 2.5Absolute error = |2.52 - 5| = 1.25 > epsilonguess2 = 6.25 > 5(x) then high = guess --> high = 2.5and proceeding so on we will get the correct up to 2 decimal places i.e., = 2.23600456We will ignore the digits after 2 decimal places since they may or may not be correct." }, { "code": null, "e": 32674, "s": 32658, "text": "tufan_gupta2000" }, { "code": null, "e": 32687, "s": 32674, "text": "Mithun Kumar" }, { "code": null, "e": 32693, "s": 32687, "text": "jit_t" }, { "code": null, "e": 32711, "s": 32693, "text": "mdrashidmeraj2002" }, { "code": null, "e": 32729, "s": 32711, "text": "divyeshrabadiya07" }, { "code": null, "e": 32745, "s": 32729, "text": "rohanthakurarmy" }, { "code": null, "e": 32759, "s": 32745, "text": "Binary Search" }, { "code": null, "e": 32772, "s": 32759, "text": "Mathematical" }, { "code": null, "e": 32785, "s": 32772, "text": "Mathematical" }, { "code": null, "e": 32799, "s": 32785, "text": "Binary Search" }, { "code": null, "e": 32897, "s": 32799, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32940, "s": 32897, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 32982, "s": 32940, "text": "Program to find GCD or HCF of two numbers" }, { "code": null, "e": 33006, "s": 32982, "text": "Merge two sorted arrays" }, { "code": null, "e": 33020, "s": 33006, "text": "Prime Numbers" }, { "code": null, "e": 33069, "s": 33020, "text": "Program to find sum of elements in a given array" }, { "code": null, "e": 33103, "s": 33069, "text": "Program for factorial of a number" }, { "code": null, "e": 33144, "s": 33103, "text": "Program for Decimal to Binary Conversion" }, { "code": null, "e": 33166, "s": 33144, "text": "Sieve of Eratosthenes" }, { "code": null, "e": 33187, "s": 33166, "text": "Operators in C / C++" } ]
How to prevent Cloning to break a Singleton Class Pattern?
A Singleton pattern states that a class can have a single instance and multiple instances are not permitted to be created. For this purpose, we make the constructor of the class a private and return a instance via a static method. But using cloning, we can still create multiple instance of a class. See the example below − public class Tester{ public static void main(String[] args) throws CloneNotSupportedException { A a = A.getInstance(); A b = (A)a.clone(); System.out.println(a.hashCode()); System.out.println(b.hashCode()); } } class A implements Cloneable { private static A a; private A(){} public static A getInstance(){ if(a == null){ a = new A(); } return a; } @Override protected Object clone() throws CloneNotSupportedException { return super.clone(); } } 705927765 366712642 Here you can see, we've created another object of a Singleton class. Let's see how to prevent such a situation − Return the same object in the clone method as well. @Override protected Object clone() throws CloneNotSupportedException { return getInstance(); } 705927765 705927765
[ { "code": null, "e": 1386, "s": 1062, "text": "A Singleton pattern states that a class can have a single instance and multiple instances are not permitted to be created. For this purpose, we make the constructor of the class a private and return a instance via a static method. But using cloning, we can still create multiple instance of a class. See the example below −" }, { "code": null, "e": 1926, "s": 1386, "text": "public class Tester{\n public static void main(String[] args)\n throws CloneNotSupportedException {\n A a = A.getInstance();\n A b = (A)a.clone();\n\n System.out.println(a.hashCode());\n System.out.println(b.hashCode());\n }\n}\n\nclass A implements Cloneable {\n private static A a;\n private A(){}\n\n public static A getInstance(){\n if(a == null){\n a = new A();\n }\n return a;\n }\n\n @Override\n protected Object clone()\n throws CloneNotSupportedException {\n return super.clone();\n }\n}" }, { "code": null, "e": 1946, "s": 1926, "text": "705927765\n366712642" }, { "code": null, "e": 2059, "s": 1946, "text": "Here you can see, we've created another object of a Singleton class. Let's see how to prevent such a situation −" }, { "code": null, "e": 2111, "s": 2059, "text": "Return the same object in the clone method as well." }, { "code": null, "e": 2209, "s": 2111, "text": "@Override\nprotected Object clone()\nthrows CloneNotSupportedException {\n return getInstance();\n}" }, { "code": null, "e": 2229, "s": 2209, "text": "705927765\n705927765" } ]
Capitalize first letter of a column in Pandas dataframe - GeeksforGeeks
06 Dec, 2018 Analyzing real-world data is somewhat difficult because we need to take various things into consideration. Apart from getting the useful data from large datasets, keeping data in required format is also very important. One might encounter a situation where we need to capitalize any specific column in given dataframe. Let’s see how can we capitalize first letter of a column in Pandas dataframe. Let’s create a dataframe from the dict of lists. # Create a simple dataframe # importing pandas as pdimport pandas as pd # creating a dataframedf = pd.DataFrame({'A': ['john', 'bODAY', 'minA', 'Peter', 'nicky'], 'B': ['masters', 'graduate', 'graduate', 'Masters', 'Graduate'], 'C': [27, 23, 21, 23, 24]}) df Output: There are certain methods we can change/modify the case of column in pandas dataframe. Let’s see how can we capitalize first letter of columns using capitalize() method. Method #1: # Create a simple dataframe # importing pandas as pdimport pandas as pd # creating a dataframedf = pd.DataFrame({'A': ['john', 'bODAY', 'minA', 'Peter', 'nicky'], 'B': ['masters', 'graduate', 'graduate', 'Masters', 'Graduate'], 'C': [27, 23, 21, 23, 24]}) df['A'] = df['A'].str.capitalize() df Output: Method #2: Using lambda with capitalize() method # Create a simple dataframe # importing pandas as pdimport pandas as pd # creating a dataframedf = pd.DataFrame({'A': ['john', 'bODAY', 'minA', 'Peter', 'nicky'], 'B': ['masters', 'graduate', 'graduate', 'Masters', 'Graduate'], 'C': [27, 23, 21, 23, 24]}) df['A'].apply(lambda x: x.capitalize()) Output: pandas-dataframe-program Python pandas-dataFrame Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary 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 Reading and Writing to text files in Python *args and **kwargs in Python How To Convert Python Dictionary To JSON?
[ { "code": null, "e": 24956, "s": 24928, "text": "\n06 Dec, 2018" }, { "code": null, "e": 25175, "s": 24956, "text": "Analyzing real-world data is somewhat difficult because we need to take various things into consideration. Apart from getting the useful data from large datasets, keeping data in required format is also very important." }, { "code": null, "e": 25353, "s": 25175, "text": "One might encounter a situation where we need to capitalize any specific column in given dataframe. Let’s see how can we capitalize first letter of a column in Pandas dataframe." }, { "code": null, "e": 25402, "s": 25353, "text": "Let’s create a dataframe from the dict of lists." }, { "code": "# Create a simple dataframe # importing pandas as pdimport pandas as pd # creating a dataframedf = pd.DataFrame({'A': ['john', 'bODAY', 'minA', 'Peter', 'nicky'], 'B': ['masters', 'graduate', 'graduate', 'Masters', 'Graduate'], 'C': [27, 23, 21, 23, 24]}) df", "e": 25737, "s": 25402, "text": null }, { "code": null, "e": 25745, "s": 25737, "text": "Output:" }, { "code": null, "e": 25915, "s": 25745, "text": "There are certain methods we can change/modify the case of column in pandas dataframe. Let’s see how can we capitalize first letter of columns using capitalize() method." }, { "code": null, "e": 25926, "s": 25915, "text": "Method #1:" }, { "code": "# Create a simple dataframe # importing pandas as pdimport pandas as pd # creating a dataframedf = pd.DataFrame({'A': ['john', 'bODAY', 'minA', 'Peter', 'nicky'], 'B': ['masters', 'graduate', 'graduate', 'Masters', 'Graduate'], 'C': [27, 23, 21, 23, 24]}) df['A'] = df['A'].str.capitalize() df", "e": 26297, "s": 25926, "text": null }, { "code": null, "e": 26354, "s": 26297, "text": "Output: Method #2: Using lambda with capitalize() method" }, { "code": "# Create a simple dataframe # importing pandas as pdimport pandas as pd # creating a dataframedf = pd.DataFrame({'A': ['john', 'bODAY', 'minA', 'Peter', 'nicky'], 'B': ['masters', 'graduate', 'graduate', 'Masters', 'Graduate'], 'C': [27, 23, 21, 23, 24]}) df['A'].apply(lambda x: x.capitalize())", "e": 26726, "s": 26354, "text": null }, { "code": null, "e": 26734, "s": 26726, "text": "Output:" }, { "code": null, "e": 26759, "s": 26734, "text": "pandas-dataframe-program" }, { "code": null, "e": 26783, "s": 26759, "text": "Python pandas-dataFrame" }, { "code": null, "e": 26797, "s": 26783, "text": "Python-pandas" }, { "code": null, "e": 26804, "s": 26797, "text": "Python" }, { "code": null, "e": 26902, "s": 26804, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26920, "s": 26902, "text": "Python Dictionary" }, { "code": null, "e": 26942, "s": 26920, "text": "Enumerate() in Python" }, { "code": null, "e": 26974, "s": 26942, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27004, "s": 26974, "text": "Iterate over a list in Python" }, { "code": null, "e": 27046, "s": 27004, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 27072, "s": 27046, "text": "Python String | replace()" }, { "code": null, "e": 27109, "s": 27072, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 27153, "s": 27109, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 27182, "s": 27153, "text": "*args and **kwargs in Python" } ]
Properties getOrDefault(key, defaultValue) method in Java with Examples - GeeksforGeeks
10 Dec, 2019 The getOrDefault(key, defaultValue) method of Properties class is used to get the value mapped to this key, passed as the parameter, in this Properties object. This method will fetch the corresponding value to this key, if present, and return it. If there is no such mapping, then it returns the defaultValue. Syntax: public Object getOrDefault(Object key, Object defaultValue) Parameters: This method accepts two parameter: key: whose mapping is to be checked in this Properties object. defaultValue: which is the default mapping of the key Returns: This method returns the value fetched corresponding to this key, if present. If there is no such mapping, then it returns the defaultValue. Below programs illustrate the getOrDefault(key, defaultValue) method: Program 1: // Java program to demonstrate// getOrDefault(key, defaultValue) method. import java.util.*; public class GFG { // Main method public static void main(String[] args) { // Create a properties and add some values Properties properties = new Properties(); properties.put("Pen", 10); properties.put("Book", 500); properties.put("Clothes", 400); properties.put("Mobile", 5000); // Print Properties details System.out.println("Properties: " + properties.toString()); // Getting the value of Pen System.out.println("Value of Pen: " + properties .getOrDefault("Pen", 200)); // Getting the value of Phone System.out.println("Value of Phone: " + properties .getOrDefault("Phone", 200)); }} Properties: {Book=500, Mobile=5000, Pen=10, Clothes=400} Value of Pen: 10 Value of Phone: 200 Program 2: // Java program to demonstrate// getOrDefault(key, defaultValue) method. import java.util.*; public class GFG { // Main method public static void main(String[] args) { // Create a properties and add some values Properties properties = new Properties(); properties.put(1, "100RS"); properties.put(2, "500RS"); properties.put(3, "1000RS"); // Print Properties details System.out.println("Current Properties: " + properties.toString()); // Getting the value of 1 System.out.println("Value of 1: " + properties .getOrDefault(1, "200RS")); // Getting the value of 5 System.out.println("Value of 5: " + properties .getOrDefault(5, "200RS")); }} Current Properties: {3=1000RS, 2=500RS, 1=100RS} Value of 1: 100RS Value of 5: 200RS References: https://docs.oracle.com/javase/9/docs/api/java/util/Properties.html#getOrDefault-java.lang.Object-java.lang.Object- Akanksha_Rai Java - util package Java-Functions Java-Properties Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Initialize an ArrayList in Java Overriding in Java Multidimensional Arrays in Java LinkedList in Java PriorityQueue in Java ArrayList in Java Queue Interface In Java Stack Class in Java Collections.sort() in Java with Examples Initializing a List in Java
[ { "code": null, "e": 23971, "s": 23943, "text": "\n10 Dec, 2019" }, { "code": null, "e": 24281, "s": 23971, "text": "The getOrDefault(key, defaultValue) method of Properties class is used to get the value mapped to this key, passed as the parameter, in this Properties object. This method will fetch the corresponding value to this key, if present, and return it. If there is no such mapping, then it returns the defaultValue." }, { "code": null, "e": 24289, "s": 24281, "text": "Syntax:" }, { "code": null, "e": 24349, "s": 24289, "text": "public Object getOrDefault(Object key, Object defaultValue)" }, { "code": null, "e": 24396, "s": 24349, "text": "Parameters: This method accepts two parameter:" }, { "code": null, "e": 24459, "s": 24396, "text": "key: whose mapping is to be checked in this Properties object." }, { "code": null, "e": 24513, "s": 24459, "text": "defaultValue: which is the default mapping of the key" }, { "code": null, "e": 24662, "s": 24513, "text": "Returns: This method returns the value fetched corresponding to this key, if present. If there is no such mapping, then it returns the defaultValue." }, { "code": null, "e": 24732, "s": 24662, "text": "Below programs illustrate the getOrDefault(key, defaultValue) method:" }, { "code": null, "e": 24743, "s": 24732, "text": "Program 1:" }, { "code": "// Java program to demonstrate// getOrDefault(key, defaultValue) method. import java.util.*; public class GFG { // Main method public static void main(String[] args) { // Create a properties and add some values Properties properties = new Properties(); properties.put(\"Pen\", 10); properties.put(\"Book\", 500); properties.put(\"Clothes\", 400); properties.put(\"Mobile\", 5000); // Print Properties details System.out.println(\"Properties: \" + properties.toString()); // Getting the value of Pen System.out.println(\"Value of Pen: \" + properties .getOrDefault(\"Pen\", 200)); // Getting the value of Phone System.out.println(\"Value of Phone: \" + properties .getOrDefault(\"Phone\", 200)); }}", "e": 25673, "s": 24743, "text": null }, { "code": null, "e": 25768, "s": 25673, "text": "Properties: {Book=500, Mobile=5000, Pen=10, Clothes=400}\nValue of Pen: 10\nValue of Phone: 200\n" }, { "code": null, "e": 25779, "s": 25768, "text": "Program 2:" }, { "code": "// Java program to demonstrate// getOrDefault(key, defaultValue) method. import java.util.*; public class GFG { // Main method public static void main(String[] args) { // Create a properties and add some values Properties properties = new Properties(); properties.put(1, \"100RS\"); properties.put(2, \"500RS\"); properties.put(3, \"1000RS\"); // Print Properties details System.out.println(\"Current Properties: \" + properties.toString()); // Getting the value of 1 System.out.println(\"Value of 1: \" + properties .getOrDefault(1, \"200RS\")); // Getting the value of 5 System.out.println(\"Value of 5: \" + properties .getOrDefault(5, \"200RS\")); }}", "e": 26663, "s": 25779, "text": null }, { "code": null, "e": 26749, "s": 26663, "text": "Current Properties: {3=1000RS, 2=500RS, 1=100RS}\nValue of 1: 100RS\nValue of 5: 200RS\n" }, { "code": null, "e": 26877, "s": 26749, "text": "References: https://docs.oracle.com/javase/9/docs/api/java/util/Properties.html#getOrDefault-java.lang.Object-java.lang.Object-" }, { "code": null, "e": 26890, "s": 26877, "text": "Akanksha_Rai" }, { "code": null, "e": 26910, "s": 26890, "text": "Java - util package" }, { "code": null, "e": 26925, "s": 26910, "text": "Java-Functions" }, { "code": null, "e": 26941, "s": 26925, "text": "Java-Properties" }, { "code": null, "e": 26946, "s": 26941, "text": "Java" }, { "code": null, "e": 26951, "s": 26946, "text": "Java" }, { "code": null, "e": 27049, "s": 26951, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27058, "s": 27049, "text": "Comments" }, { "code": null, "e": 27071, "s": 27058, "text": "Old Comments" }, { "code": null, "e": 27103, "s": 27071, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 27122, "s": 27103, "text": "Overriding in Java" }, { "code": null, "e": 27154, "s": 27122, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 27173, "s": 27154, "text": "LinkedList in Java" }, { "code": null, "e": 27195, "s": 27173, "text": "PriorityQueue in Java" }, { "code": null, "e": 27213, "s": 27195, "text": "ArrayList in Java" }, { "code": null, "e": 27237, "s": 27213, "text": "Queue Interface In Java" }, { "code": null, "e": 27257, "s": 27237, "text": "Stack Class in Java" }, { "code": null, "e": 27298, "s": 27257, "text": "Collections.sort() in Java with Examples" } ]
Understand Text Summarization and create your own summarizer in python | by Praveen Dubey | Towards Data Science
We all interact with applications which uses text summarization. Many of those applications are for the platform which publishes articles on daily news, entertainment, sports. With our busy schedule, we prefer to read the summary of those article before we decide to jump in for reading entire article. Reading a summary help us to identify the interest area, gives a brief context of the story. Summarization can be defined as a task of producing a concise and fluent summary while preserving key information and overall meaning. Summarization systems often have additional evidence they can utilize in order to specify the most important topics of document(s). For example, when summarizing blogs, there are discussions or comments coming after the blog post that are good sources of information to determine which parts of the blog are critical and interesting. In scientific paper summarization, there is a considerable amount of information such as cited papers and conference information which can be leveraged to identify important sentences in the original paper. In general there are two types of summarization, abstractive and extractive summarization. Abstractive Summarization: Abstractive methods select words based on semantic understanding, even those words did not appear in the source documents. It aims at producing important material in a new way. They interpret and examine the text using advanced natural language techniques in order to generate a new shorter text that conveys the most critical information from the original text. Abstractive Summarization: Abstractive methods select words based on semantic understanding, even those words did not appear in the source documents. It aims at producing important material in a new way. They interpret and examine the text using advanced natural language techniques in order to generate a new shorter text that conveys the most critical information from the original text. It can be correlated to the way human reads a text article or blog post and then summarizes in their own word. Input document → understand context → semantics → create own summary. 2. Extractive Summarization: Extractive methods attempt to summarize articles by selecting a subset of words that retain the most important points. This approach weights the important part of sentences and uses the same to form the summary. Different algorithm and techniques are used to define weights for the sentences and further rank them based on importance and similarity among each other. Input document → sentences similarity → weight sentences → select sentences with higher rank. The limited study is available for abstractive summarization as it requires a deeper understanding of the text as compared to the extractive approach. Purely extractive summaries often times give better results compared to automatic abstractive summaries. This is because of the fact that abstractive summarization methods cope with problems such as semantic representation,inference and natural language generation which is relatively harder than data-driven approaches such as sentence extraction. There are many techniques available to generate extractive summarization. To keep it simple, I will be using an unsupervised learning approach to find the sentences similarity and rank them. One benefit of this will be, you don’t need to train and build a model prior start using it for your project. It’s good to understand Cosine similarity to make the best use of code you are going to see. Cosine similarity is a measure of similarity between two non-zero vectors of an inner product space that measures the cosine of the angle between them. Since we will be representing our sentences as the bunch of vectors, we can use it to find the similarity among sentences. Its measures cosine of the angle between vectors. Angle will be 0 if sentences are similar. All good till now..? Hope so :) Next, Below is our code flow to generate summarize text:- Input article → split into sentences → remove stop words → build a similarity matrix → generate rank based on matrix → pick top N sentences for summary. Let’s create these methods. from nltk.corpus import stopwordsfrom nltk.cluster.util import cosine_distanceimport numpy as npimport networkx as nx def read_article(file_name): file = open(file_name, "r") filedata = file.readlines() article = filedata[0].split(". ") sentences = [] for sentence in article: print(sentence) sentences.append(sentence.replace("[^a-zA-Z]", " ").split(" ")) sentences.pop() return sentences This is where we will be using cosine similarity to find similarity between sentences. def build_similarity_matrix(sentences, stop_words): # Create an empty similarity matrix similarity_matrix = np.zeros((len(sentences), len(sentences))) for idx1 in range(len(sentences)): for idx2 in range(len(sentences)): if idx1 == idx2: #ignore if both are same sentences continue similarity_matrix[idx1][idx2] = sentence_similarity(sentences[idx1], sentences[idx2], stop_words)return similarity_matrix Method will keep calling all other helper function to keep our summarization pipeline going. Make sure to take a look at all # Steps in below code. def generate_summary(file_name, top_n=5): stop_words = stopwords.words('english') summarize_text = [] # Step 1 - Read text and tokenize sentences = read_article(file_name) # Step 2 - Generate Similary Martix across sentences sentence_similarity_martix = build_similarity_matrix(sentences, stop_words) # Step 3 - Rank sentences in similarity martix sentence_similarity_graph = nx.from_numpy_array(sentence_similarity_martix) scores = nx.pagerank(sentence_similarity_graph) # Step 4 - Sort the rank and pick top sentences ranked_sentence = sorted(((scores[i],s) for i,s in enumerate(sentences)), reverse=True) print("Indexes of top ranked_sentence order are ", ranked_sentence)for i in range(top_n): summarize_text.append(" ".join(ranked_sentence[i][1])) # Step 5 - Offcourse, output the summarize texr print("Summarize Text: \n", ". ".join(summarize_text)) All put together, here is the complete code. The complete text from an article titled Microsoft Launches Intelligent Cloud Hub To Upskill Students In AI & Cloud Technologies In an attempt to build an AI-ready workforce, Microsoft announced Intelligent Cloud Hub which has been launched to empower the next generation of students with AI-ready skills. Envisioned as a three-year collaborative program, Intelligent Cloud Hub will support around 100 institutions with AI infrastructure, course content and curriculum, developer support, development tools and give students access to cloud and AI services. As part of the program, the Redmond giant which wants to expand its reach and is planning to build a strong developer ecosystem in India with the program will set up the core AI infrastructure and IoT Hub for the selected campuses. The company will provide AI development tools and Azure AI services such as Microsoft Cognitive Services, Bot Services and Azure Machine Learning.According to Manish Prakash, Country General Manager-PS, Health and Education, Microsoft India, said, "With AI being the defining technology of our time, it is transforming lives and industry and the jobs of tomorrow will require a different skillset. This will require more collaborations and training and working with AI. That’s why it has become more critical than ever for educational institutions to integrate new cloud and AI technologies. The program is an attempt to ramp up the institutional set-up and build capabilities among the educators to educate the workforce of tomorrow." The program aims to build up the cognitive skills and in-depth understanding of developing intelligent cloud connected solutions for applications across industry. Earlier in April this year, the company announced Microsoft Professional Program In AI as a learning track open to the public. The program was developed to provide job ready skills to programmers who wanted to hone their skills in AI and data science with a series of online courses which featured hands-on labs and expert instructors as well. This program also included developer-focused AI school that provided a bunch of assets to help build AI skills. (source: analyticsindiamag.com) and the summarized text with 2 lines as an input is Envisioned as a three-year collaborative program, Intelligent Cloud Hub will support around 100 institutions with AI infrastructure, course content and curriculum, developer support, development tools and give students access to cloud and AI services. The company will provide AI development tools and Azure AI services such as Microsoft Cognitive Services, Bot Services and Azure Machine Learning. According to Manish Prakash, Country General Manager-PS, Health and Education, Microsoft India, said, "With AI being the defining technology of our time, it is transforming lives and industry and the jobs of tomorrow will require a different skillset. As you can see, it does a pretty good job. You can further customized it to reduce to number to character instead of lines. It is important to understand that we have used textrank as an approach to rank the sentences. TextRank does not rely on any previous training data and can work with any arbitrary piece of text. TextRank is a general purpose graph-based ranking algorithm for NLP. There are much-advanced techniques available for text summarization. If you are new to it, you can start with an interesting research paper named Text Summarization Techniques: A Brief Survey Survey of the State of the Art in Natural Language Generation: Core tasks, applications and evaluation is a much more detailed research paper which you can go through for better understanding. Hope this would have given you a brief overview of text summarization and sample demonstration of code to summarize the text. You can start with the above research papers for advance knowledge and approaches to solve this problem. The code shown here is available on my GitHub. You can download and play around with it. You can follow me on Medium, Twitter, and LinkedIn, For any question, reach out to me on email (praveend806 [at] gmail [dot] com).
[ { "code": null, "e": 568, "s": 172, "text": "We all interact with applications which uses text summarization. Many of those applications are for the platform which publishes articles on daily news, entertainment, sports. With our busy schedule, we prefer to read the summary of those article before we decide to jump in for reading entire article. Reading a summary help us to identify the interest area, gives a brief context of the story." }, { "code": null, "e": 703, "s": 568, "text": "Summarization can be defined as a task of producing a concise and fluent summary while preserving key information and overall meaning." }, { "code": null, "e": 1037, "s": 703, "text": "Summarization systems often have additional evidence they can utilize in order to specify the most important topics of document(s). For example, when summarizing blogs, there are discussions or comments coming after the blog post that are good sources of information to determine which parts of the blog are critical and interesting." }, { "code": null, "e": 1244, "s": 1037, "text": "In scientific paper summarization, there is a considerable amount of information such as cited papers and conference information which can be leveraged to identify important sentences in the original paper." }, { "code": null, "e": 1335, "s": 1244, "text": "In general there are two types of summarization, abstractive and extractive summarization." }, { "code": null, "e": 1725, "s": 1335, "text": "Abstractive Summarization: Abstractive methods select words based on semantic understanding, even those words did not appear in the source documents. It aims at producing important material in a new way. They interpret and examine the text using advanced natural language techniques in order to generate a new shorter text that conveys the most critical information from the original text." }, { "code": null, "e": 2115, "s": 1725, "text": "Abstractive Summarization: Abstractive methods select words based on semantic understanding, even those words did not appear in the source documents. It aims at producing important material in a new way. They interpret and examine the text using advanced natural language techniques in order to generate a new shorter text that conveys the most critical information from the original text." }, { "code": null, "e": 2226, "s": 2115, "text": "It can be correlated to the way human reads a text article or blog post and then summarizes in their own word." }, { "code": null, "e": 2296, "s": 2226, "text": "Input document → understand context → semantics → create own summary." }, { "code": null, "e": 2444, "s": 2296, "text": "2. Extractive Summarization: Extractive methods attempt to summarize articles by selecting a subset of words that retain the most important points." }, { "code": null, "e": 2692, "s": 2444, "text": "This approach weights the important part of sentences and uses the same to form the summary. Different algorithm and techniques are used to define weights for the sentences and further rank them based on importance and similarity among each other." }, { "code": null, "e": 2786, "s": 2692, "text": "Input document → sentences similarity → weight sentences → select sentences with higher rank." }, { "code": null, "e": 2937, "s": 2786, "text": "The limited study is available for abstractive summarization as it requires a deeper understanding of the text as compared to the extractive approach." }, { "code": null, "e": 3286, "s": 2937, "text": "Purely extractive summaries often times give better results compared to automatic abstractive summaries. This is because of the fact that abstractive summarization methods cope with problems such as semantic representation,inference and natural language generation which is relatively harder than data-driven approaches such as sentence extraction." }, { "code": null, "e": 3587, "s": 3286, "text": "There are many techniques available to generate extractive summarization. To keep it simple, I will be using an unsupervised learning approach to find the sentences similarity and rank them. One benefit of this will be, you don’t need to train and build a model prior start using it for your project." }, { "code": null, "e": 4047, "s": 3587, "text": "It’s good to understand Cosine similarity to make the best use of code you are going to see. Cosine similarity is a measure of similarity between two non-zero vectors of an inner product space that measures the cosine of the angle between them. Since we will be representing our sentences as the bunch of vectors, we can use it to find the similarity among sentences. Its measures cosine of the angle between vectors. Angle will be 0 if sentences are similar." }, { "code": null, "e": 4079, "s": 4047, "text": "All good till now..? Hope so :)" }, { "code": null, "e": 4137, "s": 4079, "text": "Next, Below is our code flow to generate summarize text:-" }, { "code": null, "e": 4290, "s": 4137, "text": "Input article → split into sentences → remove stop words → build a similarity matrix → generate rank based on matrix → pick top N sentences for summary." }, { "code": null, "e": 4318, "s": 4290, "text": "Let’s create these methods." }, { "code": null, "e": 4436, "s": 4318, "text": "from nltk.corpus import stopwordsfrom nltk.cluster.util import cosine_distanceimport numpy as npimport networkx as nx" }, { "code": null, "e": 4742, "s": 4436, "text": "def read_article(file_name): file = open(file_name, \"r\") filedata = file.readlines() article = filedata[0].split(\". \") sentences = [] for sentence in article: print(sentence) sentences.append(sentence.replace(\"[^a-zA-Z]\", \" \").split(\" \")) sentences.pop() return sentences" }, { "code": null, "e": 4829, "s": 4742, "text": "This is where we will be using cosine similarity to find similarity between sentences." }, { "code": null, "e": 5288, "s": 4829, "text": "def build_similarity_matrix(sentences, stop_words): # Create an empty similarity matrix similarity_matrix = np.zeros((len(sentences), len(sentences))) for idx1 in range(len(sentences)): for idx2 in range(len(sentences)): if idx1 == idx2: #ignore if both are same sentences continue similarity_matrix[idx1][idx2] = sentence_similarity(sentences[idx1], sentences[idx2], stop_words)return similarity_matrix" }, { "code": null, "e": 5436, "s": 5288, "text": "Method will keep calling all other helper function to keep our summarization pipeline going. Make sure to take a look at all # Steps in below code." }, { "code": null, "e": 6344, "s": 5436, "text": "def generate_summary(file_name, top_n=5): stop_words = stopwords.words('english') summarize_text = [] # Step 1 - Read text and tokenize sentences = read_article(file_name) # Step 2 - Generate Similary Martix across sentences sentence_similarity_martix = build_similarity_matrix(sentences, stop_words) # Step 3 - Rank sentences in similarity martix sentence_similarity_graph = nx.from_numpy_array(sentence_similarity_martix) scores = nx.pagerank(sentence_similarity_graph) # Step 4 - Sort the rank and pick top sentences ranked_sentence = sorted(((scores[i],s) for i,s in enumerate(sentences)), reverse=True) print(\"Indexes of top ranked_sentence order are \", ranked_sentence)for i in range(top_n): summarize_text.append(\" \".join(ranked_sentence[i][1])) # Step 5 - Offcourse, output the summarize texr print(\"Summarize Text: \\n\", \". \".join(summarize_text))" }, { "code": null, "e": 6389, "s": 6344, "text": "All put together, here is the complete code." }, { "code": null, "e": 6518, "s": 6389, "text": "The complete text from an article titled Microsoft Launches Intelligent Cloud Hub To Upskill Students In AI & Cloud Technologies" }, { "code": null, "e": 8534, "s": 6518, "text": "In an attempt to build an AI-ready workforce, Microsoft announced Intelligent Cloud Hub which has been launched to empower the next generation of students with AI-ready skills. Envisioned as a three-year collaborative program, Intelligent Cloud Hub will support around 100 institutions with AI infrastructure, course content and curriculum, developer support, development tools and give students access to cloud and AI services. As part of the program, the Redmond giant which wants to expand its reach and is planning to build a strong developer ecosystem in India with the program will set up the core AI infrastructure and IoT Hub for the selected campuses. The company will provide AI development tools and Azure AI services such as Microsoft Cognitive Services, Bot Services and Azure Machine Learning.According to Manish Prakash, Country General Manager-PS, Health and Education, Microsoft India, said, \"With AI being the defining technology of our time, it is transforming lives and industry and the jobs of tomorrow will require a different skillset. This will require more collaborations and training and working with AI. That’s why it has become more critical than ever for educational institutions to integrate new cloud and AI technologies. The program is an attempt to ramp up the institutional set-up and build capabilities among the educators to educate the workforce of tomorrow.\" The program aims to build up the cognitive skills and in-depth understanding of developing intelligent cloud connected solutions for applications across industry. Earlier in April this year, the company announced Microsoft Professional Program In AI as a learning track open to the public. The program was developed to provide job ready skills to programmers who wanted to hone their skills in AI and data science with a series of online courses which featured hands-on labs and expert instructors as well. This program also included developer-focused AI school that provided a bunch of assets to help build AI skills." }, { "code": null, "e": 8566, "s": 8534, "text": "(source: analyticsindiamag.com)" }, { "code": null, "e": 8618, "s": 8566, "text": "and the summarized text with 2 lines as an input is" }, { "code": null, "e": 9269, "s": 8618, "text": "Envisioned as a three-year collaborative program, Intelligent Cloud Hub will support around 100 institutions with AI infrastructure, course content and curriculum, developer support, development tools and give students access to cloud and AI services. The company will provide AI development tools and Azure AI services such as Microsoft Cognitive Services, Bot Services and Azure Machine Learning. According to Manish Prakash, Country General Manager-PS, Health and Education, Microsoft India, said, \"With AI being the defining technology of our time, it is transforming lives and industry and the jobs of tomorrow will require a different skillset." }, { "code": null, "e": 9393, "s": 9269, "text": "As you can see, it does a pretty good job. You can further customized it to reduce to number to character instead of lines." }, { "code": null, "e": 9657, "s": 9393, "text": "It is important to understand that we have used textrank as an approach to rank the sentences. TextRank does not rely on any previous training data and can work with any arbitrary piece of text. TextRank is a general purpose graph-based ranking algorithm for NLP." }, { "code": null, "e": 9849, "s": 9657, "text": "There are much-advanced techniques available for text summarization. If you are new to it, you can start with an interesting research paper named Text Summarization Techniques: A Brief Survey" }, { "code": null, "e": 10042, "s": 9849, "text": "Survey of the State of the Art in Natural Language Generation: Core tasks, applications and evaluation is a much more detailed research paper which you can go through for better understanding." }, { "code": null, "e": 10273, "s": 10042, "text": "Hope this would have given you a brief overview of text summarization and sample demonstration of code to summarize the text. You can start with the above research papers for advance knowledge and approaches to solve this problem." }, { "code": null, "e": 10362, "s": 10273, "text": "The code shown here is available on my GitHub. You can download and play around with it." } ]
How to Convert Decimal to Binary?
Decimal number is most familiar number system to the general public. It is base 10 which has only 10 symbols − 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9. Whereas Binary number is most familiar number system to the digital systems, networking, and computer professionals. It is base 2 which has only 2 symbols: 0 and 1, these digits can be represented by off and on respectively. There are various direct or indirect methods to convert a decimal number into binary number. In an indirect method, you need to convert a decimal number into other number system (e.g., octal or hexadecimal), then you can convert into binary number by converting each digit into binary number. Example − Convert decimal number 125 into binary number. First convert it into octal or hexadecimal number, = (125)10 = (1x82+7x81+5x80)10 or (7x161+13x160)10 Because base of octal and hexadecimal are 8 and 16 respectively. = (175)8 or (7D)16 Then convert it into binary number by converting each digit. = (001 111 101)2 or (0111 1101)2 = (01111101)2 However, there are two direct methods are available for converting a decimal number into binary number: Performing Short Division by Two with Remainder (for integer part), Performing Short Multiplication by Two with result (For fractional part) and Descending Powers of Two and Subtraction. These are explained as following below. This is a straightforward method which involve dividing the number to be converted. Let decimal number is N then divide this number from 2 because base of binary number system is 2. Note down the value of remainder, which will be either 0 or 1. Again divide remaining decimal number till it became 0 and note every remainder of every step. Then write remainders from bottom to up (or in reverse order), which will be equivalent binary number of given decimal number. This is procedure for converting an integer decimal number, algorithm is given below. Take decimal number as dividend. Take decimal number as dividend. Divide this number by 2 (2 is base of binary so divisor here). Divide this number by 2 (2 is base of binary so divisor here). Store the remainder in an array (it will be either 0 or 1 because of divisor 2). Store the remainder in an array (it will be either 0 or 1 because of divisor 2). Repeat the above two steps until the number is greater than zero. Repeat the above two steps until the number is greater than zero. Print the array in reverse order (which will be equivalent binary number of given decimal number). Print the array in reverse order (which will be equivalent binary number of given decimal number). Note that dividend (here given decimal number) is the number being divided, the divisor (here base of binary, i.e., 2) in the number by which the dividend is divided, and quotient (remaining divided decimal number) is the result of the division. Example − Convert decimal number 112 into binary number. Since given number is decimal integer number, so by using above algorithm performing short division by 2 with remainder. Now, write remainder from bottom to up (in reverse order), this will be 1110000 which is equivalent binary number of decimal integer 112. But above method can not convert fraction part of a mixed (a number with integer and fraction part) decimal number. For decimal fractional part, the method is explained as following below. Let decimal fractional part is M then multiply this number from 2 because base of binary number system is 2. Note down the value of integer part, which will be either 0 or 1. Again multiply remaining decimal fractional number till it became 0 and note every integer part of result of every step. Then write noted results of integer part, which will be equivalent fraction binary number of given decimal number. This is procedure for converting an fractional decimal number, algorithm is given below. Take decimal number as multiplicand. Take decimal number as multiplicand. Multiple this number by 2 (2 is base of binary so multiplier here). Multiple this number by 2 (2 is base of binary so multiplier here). Store the value of integer part of result in an array (it will be either 0 or 1 because of multiplier 2). Store the value of integer part of result in an array (it will be either 0 or 1 because of multiplier 2). Repeat the above two steps until the number became zero. Repeat the above two steps until the number became zero. Print the array (which will be equivalent fractional binary number of given decimal fractional number). Print the array (which will be equivalent fractional binary number of given decimal fractional number). Note that a multiplicand (here decimal fractional number) is that to be multiplied by multiplier (here base of 2, i.e., 2) Example − Convert decimal fractional number 0.8125 into binary number. Since given number is decimal fractional number, so by using above algorithm performing short multiplication by 2 with integer part. Now, write these resultant integer part, this will be 0.11010 which is equivalent binary fractional number of decimal fractional 0.8125. This method is gussing binary number of a decimal number. You need to draw a table of power of 2, then take given decimal number and subtract it from maximum possible power of 2 that does not return resultant number negative. Then put 1 into that box of this power in the table. Repeat these steps till number is greater than zero. Put a 0 in all other empty boxes and take the output which will be equivalent binary number of given decimal number. For integer part, The algorithm is explained as following below. Start by making a chart. Start by making a chart. Look for the greatest power of 2. Look for the greatest power of 2. Move to the next lower power of two. Move to the next lower power of two. Subtract each successive number that can fit, and mark it with a 1. Subtract each successive number that can fit, and mark it with a 1. Continue until you reach the end of your chart. Continue until you reach the end of your chart. Write out the binary answer. Write out the binary answer. Example − Convert decimal number 205 into binary number. Take table of power of 2, Subtract given number 205 from maximum possible power of 2, = 205 - 128 = 77 Put 1 in box of 128 (= 27), then again subtract remaining number 77 from maximum possible power of 2, = 77 - 64 =13 Put 1 in box of 64 (= 26), then repeat above steps, = 13 - 8 =5 = 5 - 4 =1 = 1 - 1 =0 And put a 0 in remaining boxes. Therefore equivalent binary number will be 11001101 of given 205 decimal number.
[ { "code": null, "e": 1431, "s": 1062, "text": "Decimal number is most familiar number system to the general public. It is base 10 which has only 10 symbols − 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9. Whereas Binary number is most familiar number system to the digital systems, networking, and computer professionals. It is base 2 which has only 2 symbols: 0 and 1, these digits can be represented by off and on respectively." }, { "code": null, "e": 1724, "s": 1431, "text": "There are various direct or indirect methods to convert a decimal number into binary number. In an indirect method, you need to convert a decimal number into other number system (e.g., octal or hexadecimal), then you can convert into binary number by converting each digit into binary number." }, { "code": null, "e": 1781, "s": 1724, "text": "Example − Convert decimal number 125 into binary number." }, { "code": null, "e": 2075, "s": 1781, "text": "First convert it into octal or hexadecimal number,\n= (125)10\n= (1x82+7x81+5x80)10\nor (7x161+13x160)10\nBecause base of octal and hexadecimal are 8 and 16 respectively.\n= (175)8\nor (7D)16\nThen convert it into binary number by converting each digit.\n= (001 111 101)2\nor (0111 1101)2\n= (01111101)2" }, { "code": null, "e": 2406, "s": 2075, "text": "However, there are two direct methods are available for converting a decimal number into binary number: Performing Short Division by Two with Remainder (for integer part), Performing Short Multiplication by Two with result (For fractional part) and Descending Powers of Two and Subtraction. These are explained as following below." }, { "code": null, "e": 2959, "s": 2406, "text": "This is a straightforward method which involve dividing the number to be converted. Let decimal number is N then divide this number from 2 because base of binary number system is 2. Note down the value of remainder, which will be either 0 or 1. Again divide remaining decimal number till it became 0 and note every remainder of every step. Then write remainders from bottom to up (or in reverse order), which will be equivalent binary number of given decimal number. This is procedure for converting an integer decimal number, algorithm is given below." }, { "code": null, "e": 2992, "s": 2959, "text": "Take decimal number as dividend." }, { "code": null, "e": 3025, "s": 2992, "text": "Take decimal number as dividend." }, { "code": null, "e": 3088, "s": 3025, "text": "Divide this number by 2 (2 is base of binary so divisor here)." }, { "code": null, "e": 3151, "s": 3088, "text": "Divide this number by 2 (2 is base of binary so divisor here)." }, { "code": null, "e": 3232, "s": 3151, "text": "Store the remainder in an array (it will be either 0 or 1 because of divisor 2)." }, { "code": null, "e": 3313, "s": 3232, "text": "Store the remainder in an array (it will be either 0 or 1 because of divisor 2)." }, { "code": null, "e": 3379, "s": 3313, "text": "Repeat the above two steps until the number is greater than zero." }, { "code": null, "e": 3445, "s": 3379, "text": "Repeat the above two steps until the number is greater than zero." }, { "code": null, "e": 3544, "s": 3445, "text": "Print the array in reverse order (which will be equivalent binary number of given decimal number)." }, { "code": null, "e": 3643, "s": 3544, "text": "Print the array in reverse order (which will be equivalent binary number of given decimal number)." }, { "code": null, "e": 3889, "s": 3643, "text": "Note that dividend (here given decimal number) is the number being divided, the divisor (here base of binary, i.e., 2) in the number by which the dividend is divided, and quotient (remaining divided decimal number) is the result of the division." }, { "code": null, "e": 3946, "s": 3889, "text": "Example − Convert decimal number 112 into binary number." }, { "code": null, "e": 4067, "s": 3946, "text": "Since given number is decimal integer number, so by using above algorithm performing short division by 2 with remainder." }, { "code": null, "e": 4205, "s": 4067, "text": "Now, write remainder from bottom to up (in reverse order), this will be 1110000 which is equivalent binary number of decimal integer 112." }, { "code": null, "e": 4394, "s": 4205, "text": "But above method can not convert fraction part of a mixed (a number with integer and fraction part) decimal number. For decimal fractional part, the method is explained as following below." }, { "code": null, "e": 4894, "s": 4394, "text": "Let decimal fractional part is M then multiply this number from 2 because base of binary number system is 2. Note down the value of integer part, which will be either 0 or 1. Again multiply remaining decimal fractional number till it became 0 and note every integer part of result of every step. Then write noted results of integer part, which will be equivalent fraction binary number of given decimal number. This is procedure for converting an fractional decimal number, algorithm is given below." }, { "code": null, "e": 4931, "s": 4894, "text": "Take decimal number as multiplicand." }, { "code": null, "e": 4968, "s": 4931, "text": "Take decimal number as multiplicand." }, { "code": null, "e": 5036, "s": 4968, "text": "Multiple this number by 2 (2 is base of binary so multiplier here)." }, { "code": null, "e": 5104, "s": 5036, "text": "Multiple this number by 2 (2 is base of binary so multiplier here)." }, { "code": null, "e": 5210, "s": 5104, "text": "Store the value of integer part of result in an array (it will be either 0 or 1 because of multiplier 2)." }, { "code": null, "e": 5316, "s": 5210, "text": "Store the value of integer part of result in an array (it will be either 0 or 1 because of multiplier 2)." }, { "code": null, "e": 5373, "s": 5316, "text": "Repeat the above two steps until the number became zero." }, { "code": null, "e": 5430, "s": 5373, "text": "Repeat the above two steps until the number became zero." }, { "code": null, "e": 5534, "s": 5430, "text": "Print the array (which will be equivalent fractional binary number of given decimal fractional number)." }, { "code": null, "e": 5638, "s": 5534, "text": "Print the array (which will be equivalent fractional binary number of given decimal fractional number)." }, { "code": null, "e": 5761, "s": 5638, "text": "Note that a multiplicand (here decimal fractional number) is that to be multiplied by multiplier (here base of 2, i.e., 2)" }, { "code": null, "e": 5832, "s": 5761, "text": "Example − Convert decimal fractional number 0.8125 into binary number." }, { "code": null, "e": 5965, "s": 5832, "text": "Since given number is decimal fractional number, so by using above algorithm performing short multiplication by 2 with integer part." }, { "code": null, "e": 6102, "s": 5965, "text": "Now, write these resultant integer part, this will be 0.11010 which is equivalent binary fractional number of decimal fractional 0.8125." }, { "code": null, "e": 6616, "s": 6102, "text": "This method is gussing binary number of a decimal number. You need to draw a table of power of 2, then take given decimal number and subtract it from maximum possible power of 2 that does not return resultant number negative. Then put 1 into that box of this power in the table. Repeat these steps till number is greater than zero. Put a 0 in all other empty boxes and take the output which will be equivalent binary number of given decimal number. For integer part, The algorithm is explained as following below." }, { "code": null, "e": 6641, "s": 6616, "text": "Start by making a chart." }, { "code": null, "e": 6666, "s": 6641, "text": "Start by making a chart." }, { "code": null, "e": 6700, "s": 6666, "text": "Look for the greatest power of 2." }, { "code": null, "e": 6734, "s": 6700, "text": "Look for the greatest power of 2." }, { "code": null, "e": 6771, "s": 6734, "text": "Move to the next lower power of two." }, { "code": null, "e": 6808, "s": 6771, "text": "Move to the next lower power of two." }, { "code": null, "e": 6876, "s": 6808, "text": "Subtract each successive number that can fit, and mark it with a 1." }, { "code": null, "e": 6944, "s": 6876, "text": "Subtract each successive number that can fit, and mark it with a 1." }, { "code": null, "e": 6992, "s": 6944, "text": "Continue until you reach the end of your chart." }, { "code": null, "e": 7040, "s": 6992, "text": "Continue until you reach the end of your chart." }, { "code": null, "e": 7069, "s": 7040, "text": "Write out the binary answer." }, { "code": null, "e": 7098, "s": 7069, "text": "Write out the binary answer." }, { "code": null, "e": 7155, "s": 7098, "text": "Example − Convert decimal number 205 into binary number." }, { "code": null, "e": 7181, "s": 7155, "text": "Take table of power of 2," }, { "code": null, "e": 7573, "s": 7181, "text": "Subtract given number 205 from maximum possible power of 2,\n= 205 - 128 = 77\nPut 1 in box of 128 (= 27), then again subtract remaining number 77 from maximum possible power of 2,\n= 77 - 64 =13\nPut 1 in box of 64 (= 26), then repeat above steps,\n= 13 - 8 =5\n= 5 - 4 =1\n= 1 - 1 =0\nAnd put a 0 in remaining boxes. Therefore equivalent binary number will be 11001101 of given 205 decimal number." } ]
Basic Text Summarization in Python | by Graham Harrison | Towards Data Science
Text summarization is a sub-set of text mining and natural language processing that aims to take long corpus of text and transform them into a summary that can be easily and quickly read and understood without losing the meaning of the original text. In particular text summarisation “tokenizes” words (i.e. converts them into data) and then assesses the importance of each by looking at relative frequency and other factors. The word importance scores can then be aggregated back into values for sentences with the most important sentences bubbling up to the top of the summary. If you would like a more in-depth exploration of the principles, this article is a great place to start — https://towardsdatascience.com/a-quick-introduction-to-text-summarization-in-machine-learning-3d27ccf18a9f The objective of this article is to produce a basic interactive text summarization utility to demonstrate the principles and to provide a way of generating basic summaries for complex reports. The summarization will have been successful if the summaries impart the majority of the meaning of the source report and can be read and understood in a fraction of the time. To start with we will need to import the libraries that will be used ... The building blocks for our text summarization utility handle the leg-work of allowing the user to browse the local file system to select a file to summarize. openfile() handles showing the File | Open dialog box, selecting a file, and returning the full path of the selected file. Next getText takes the path, opens the file and reads the text contained in the file into a str. The code provided can read from .txt or .docx files. The main work is done in a single line of code by calling the gensim.summarization.summarize function. The same effect can be achieved by using the nltk natural language toolkit but it would be more involved and it would require a bit more low level work. The summarise function provides the implementation and it follows 3 basic steps involved in text summarization - Pre-process and prepare the text.Perform the text summarization process.Post-process and tidy the result. Pre-process and prepare the text. Perform the text summarization process. Post-process and tidy the result. There will be many serious, industry-strength text processing engines that involve complex and comprehensive implementations of these 3 steps but this serves as a good example and it does provide summarization which can be quite useful as we will see. The last few helper functions are - printmd which formats and prints text that includes markup to give us a nicely formatted heading. openLocalFileAndSummarize which calls the functions we have defined above to select a file and summarize the contents. on_button_clicked which handles the button click event to add interactivity to the Notebook and to enable several files to be selected and summarised sequentially. In order to test the text summarization I collected the text from two public web sites which have published freely available reports on the topics of online reporting and marketing. The two web sites used to provide the test data are - https://www.sustainability-reports.com/unleashing-the-power-of-online-reporting/ https://www.mckinsey.com/business-functions/marketing-and-sales/our-insights/were-all-marketers-now Lastly a single line of code creates a button that can be clicked repeatedly to select a .txt or a .docx from the local disk which will then be transformed into a 300 word summary which is printed out below. When the button is clicked a File | Open dialog box is displayed to select a file- Once the file has been selected gensim.summarization.summarize does the work and the output is formatted in the cell output - Executive Summary for Unleashing the Power of Online Reporting.txt Unleashing the Power of Online Reporting Source: Sustainable Brands, 15 February 2018 Confronted with an ever-growing demand for transparency and materiality, companies need to find an adequate format to publish both financial and pre-financial information to their stakeholders in an effective way.In the real world, they are confronted with a multitude of information sources different in name, type and content, like Annual Report, CSR Report, Financial Statement, Sustainability Report, Annual Review, Corporate Citizenship Report, or Integrated Report.Online integrated reporting to the rescue Research from Message Group among Europe’s 800 largest companies shows that between 2015 and 2017 the number of businesses publishing financial and extra-financial information in one single integrated report increased by 34 percent, while the number of companies publishing separate sustainability and annual reports decreased by 30 percent.Unlike stand-alone annual or sustainability reports, online integrated reporting formats put an organization’s financial performance, business strategy and governance into the social, environmental and economic context within which it operates.Instead of directing readers from a webpage to separate PDF reports and resources located in different online places, Core & More provides all the relevant information on a single multi-layered website.Moreover, it is flexible enough to integrate multiple reporting frameworks, accounting standards and concepts, such as the International Financial Reporting Standard (IFRS) in combination with GRI, <IR>, the TCFD recommendations, or the SDGs. On top of all this flexibility, a digital reporting format is highly interactive and customizable, allowing the reader to create charts or compile selected content into personal PDF or printed reports.Turning reporting into a powerful communications tool In view of growing demand for ESG disclosure, the related surge in sustainability reporting, and a complex reporting landscape companies are challenged to find a disclosure format for both financial and extra-financial information that has a measurable value for their key stakeholders. Text summarization can be a complex and involved process of pre-processing, summarization and post-processing and a real-world application that could summarize complex reports without losing the meaning of the original text would have commercial value. However, in this article we have explored the basic concepts and quickly built a simple text summarization tool that can be used to open .txt or .docx files and then summarise the contents into 300 words based on evaluating the most popular sentences. The test on two public reports proved that the basic text summarization process works and provided an example of what the summarization output looks like. The full source code can be found here - github.com If you enjoyed reading this article, why not check out my other articles at https://grahamharrison-86487.medium.com/? Also, I would love to hear from you to get your thoughts on this piece, any of my other articles or anything else related to data science and data analytics. If you would like to get in touch to discuss any of these topics please look me up on LinkedIn — https://www.linkedin.com/in/grahamharrison1 or feel free to e-mail me at GHarrison@lincolncollege.ac.uk.
[ { "code": null, "e": 423, "s": 172, "text": "Text summarization is a sub-set of text mining and natural language processing that aims to take long corpus of text and transform them into a summary that can be easily and quickly read and understood without losing the meaning of the original text." }, { "code": null, "e": 752, "s": 423, "text": "In particular text summarisation “tokenizes” words (i.e. converts them into data) and then assesses the importance of each by looking at relative frequency and other factors. The word importance scores can then be aggregated back into values for sentences with the most important sentences bubbling up to the top of the summary." }, { "code": null, "e": 965, "s": 752, "text": "If you would like a more in-depth exploration of the principles, this article is a great place to start — https://towardsdatascience.com/a-quick-introduction-to-text-summarization-in-machine-learning-3d27ccf18a9f" }, { "code": null, "e": 1158, "s": 965, "text": "The objective of this article is to produce a basic interactive text summarization utility to demonstrate the principles and to provide a way of generating basic summaries for complex reports." }, { "code": null, "e": 1333, "s": 1158, "text": "The summarization will have been successful if the summaries impart the majority of the meaning of the source report and can be read and understood in a fraction of the time." }, { "code": null, "e": 1406, "s": 1333, "text": "To start with we will need to import the libraries that will be used ..." }, { "code": null, "e": 1565, "s": 1406, "text": "The building blocks for our text summarization utility handle the leg-work of allowing the user to browse the local file system to select a file to summarize." }, { "code": null, "e": 1688, "s": 1565, "text": "openfile() handles showing the File | Open dialog box, selecting a file, and returning the full path of the selected file." }, { "code": null, "e": 1838, "s": 1688, "text": "Next getText takes the path, opens the file and reads the text contained in the file into a str. The code provided can read from .txt or .docx files." }, { "code": null, "e": 2094, "s": 1838, "text": "The main work is done in a single line of code by calling the gensim.summarization.summarize function. The same effect can be achieved by using the nltk natural language toolkit but it would be more involved and it would require a bit more low level work." }, { "code": null, "e": 2207, "s": 2094, "text": "The summarise function provides the implementation and it follows 3 basic steps involved in text summarization -" }, { "code": null, "e": 2313, "s": 2207, "text": "Pre-process and prepare the text.Perform the text summarization process.Post-process and tidy the result." }, { "code": null, "e": 2347, "s": 2313, "text": "Pre-process and prepare the text." }, { "code": null, "e": 2387, "s": 2347, "text": "Perform the text summarization process." }, { "code": null, "e": 2421, "s": 2387, "text": "Post-process and tidy the result." }, { "code": null, "e": 2673, "s": 2421, "text": "There will be many serious, industry-strength text processing engines that involve complex and comprehensive implementations of these 3 steps but this serves as a good example and it does provide summarization which can be quite useful as we will see." }, { "code": null, "e": 2709, "s": 2673, "text": "The last few helper functions are -" }, { "code": null, "e": 2807, "s": 2709, "text": "printmd which formats and prints text that includes markup to give us a nicely formatted heading." }, { "code": null, "e": 2926, "s": 2807, "text": "openLocalFileAndSummarize which calls the functions we have defined above to select a file and summarize the contents." }, { "code": null, "e": 3090, "s": 2926, "text": "on_button_clicked which handles the button click event to add interactivity to the Notebook and to enable several files to be selected and summarised sequentially." }, { "code": null, "e": 3272, "s": 3090, "text": "In order to test the text summarization I collected the text from two public web sites which have published freely available reports on the topics of online reporting and marketing." }, { "code": null, "e": 3326, "s": 3272, "text": "The two web sites used to provide the test data are -" }, { "code": null, "e": 3407, "s": 3326, "text": "https://www.sustainability-reports.com/unleashing-the-power-of-online-reporting/" }, { "code": null, "e": 3507, "s": 3407, "text": "https://www.mckinsey.com/business-functions/marketing-and-sales/our-insights/were-all-marketers-now" }, { "code": null, "e": 3715, "s": 3507, "text": "Lastly a single line of code creates a button that can be clicked repeatedly to select a .txt or a .docx from the local disk which will then be transformed into a 300 word summary which is printed out below." }, { "code": null, "e": 3798, "s": 3715, "text": "When the button is clicked a File | Open dialog box is displayed to select a file-" }, { "code": null, "e": 3924, "s": 3798, "text": "Once the file has been selected gensim.summarization.summarize does the work and the output is formatted in the cell output -" }, { "code": null, "e": 3991, "s": 3924, "text": "Executive Summary for Unleashing the Power of Online Reporting.txt" }, { "code": null, "e": 6162, "s": 3991, "text": "Unleashing the Power of Online Reporting Source: Sustainable Brands, 15 February 2018 Confronted with an ever-growing demand for transparency and materiality, companies need to find an adequate format to publish both financial and pre-financial information to their stakeholders in an effective way.In the real world, they are confronted with a multitude of information sources different in name, type and content, like Annual Report, CSR Report, Financial Statement, Sustainability Report, Annual Review, Corporate Citizenship Report, or Integrated Report.Online integrated reporting to the rescue Research from Message Group among Europe’s 800 largest companies shows that between 2015 and 2017 the number of businesses publishing financial and extra-financial information in one single integrated report increased by 34 percent, while the number of companies publishing separate sustainability and annual reports decreased by 30 percent.Unlike stand-alone annual or sustainability reports, online integrated reporting formats put an organization’s financial performance, business strategy and governance into the social, environmental and economic context within which it operates.Instead of directing readers from a webpage to separate PDF reports and resources located in different online places, Core & More provides all the relevant information on a single multi-layered website.Moreover, it is flexible enough to integrate multiple reporting frameworks, accounting standards and concepts, such as the International Financial Reporting Standard (IFRS) in combination with GRI, <IR>, the TCFD recommendations, or the SDGs. On top of all this flexibility, a digital reporting format is highly interactive and customizable, allowing the reader to create charts or compile selected content into personal PDF or printed reports.Turning reporting into a powerful communications tool In view of growing demand for ESG disclosure, the related surge in sustainability reporting, and a complex reporting landscape companies are challenged to find a disclosure format for both financial and extra-financial information that has a measurable value for their key stakeholders." }, { "code": null, "e": 6415, "s": 6162, "text": "Text summarization can be a complex and involved process of pre-processing, summarization and post-processing and a real-world application that could summarize complex reports without losing the meaning of the original text would have commercial value." }, { "code": null, "e": 6667, "s": 6415, "text": "However, in this article we have explored the basic concepts and quickly built a simple text summarization tool that can be used to open .txt or .docx files and then summarise the contents into 300 words based on evaluating the most popular sentences." }, { "code": null, "e": 6822, "s": 6667, "text": "The test on two public reports proved that the basic text summarization process works and provided an example of what the summarization output looks like." }, { "code": null, "e": 6863, "s": 6822, "text": "The full source code can be found here -" }, { "code": null, "e": 6874, "s": 6863, "text": "github.com" }, { "code": null, "e": 6992, "s": 6874, "text": "If you enjoyed reading this article, why not check out my other articles at https://grahamharrison-86487.medium.com/?" }, { "code": null, "e": 7150, "s": 6992, "text": "Also, I would love to hear from you to get your thoughts on this piece, any of my other articles or anything else related to data science and data analytics." } ]
Java SAX Parser - Modify XML Document
Here is the input XML file that we need to modify by appending <Result>Pass<Result/> at the end of </marks> tag. <?xml version = "1.0"?> <class> <student rollno = "393"> <firstname>dinkar</firstname> <lastname>kad</lastname> <nickname>dinkar</nickname> <marks>85</marks> </student> <student rollno = "493"> <firstname>Vaneet</firstname> <lastname>Gupta</lastname> <nickname>vinni</nickname> <marks>95</marks> </student> <student rollno = "593"> <firstname>jasvir</firstname> <lastname>singn</lastname> <nickname>jazz</nickname> <marks>90</marks> </student> </class> package com.tutorialspoint.xml; import java.io.*; import org.xml.sax.*; import javax.xml.parsers.*; import org.xml.sax.helpers.DefaultHandler; public class SAXModifyDemo extends DefaultHandler { static String displayText[] = new String[1000]; static int numberLines = 0; static String indentation = ""; public static void main(String args[]) { try { File inputFile = new File("input.txt"); SAXParserFactory factory = SAXParserFactory.newInstance(); SAXModifyDemo obj = new SAXModifyDemo(); obj.childLoop(inputFile); FileWriter filewriter = new FileWriter("newfile.xml"); for(int loopIndex = 0; loopIndex < numberLines; loopIndex++) { filewriter.write(displayText[loopIndex].toCharArray()); filewriter.write('\n'); System.out.println(displayText[loopIndex].toString()); } filewriter.close(); } catch (Exception e) { e.printStackTrace(System.err); } } public void childLoop(File input) { DefaultHandler handler = this; SAXParserFactory factory = SAXParserFactory.newInstance(); try { SAXParser saxParser = factory.newSAXParser(); saxParser.parse(input, handler); } catch (Throwable t) {} } public void startDocument() { displayText[numberLines] = indentation; displayText[numberLines] += "<?xml version = \"1.0\" encoding = \""+ "UTF-8" + "\"?>"; numberLines++; } public void processingInstruction(String target, String data) { displayText[numberLines] = indentation; displayText[numberLines] += "<?"; displayText[numberLines] += target; if (data != null && data.length() > 0) { displayText[numberLines] += ' '; displayText[numberLines] += data; } displayText[numberLines] += "?>"; numberLines++; } public void startElement(String uri, String localName, String qualifiedName, Attributes attributes) { displayText[numberLines] = indentation; indentation += " "; displayText[numberLines] += '<'; displayText[numberLines] += qualifiedName; if (attributes != null) { int numberAttributes = attributes.getLength(); for (int loopIndex = 0; loopIndex < numberAttributes; loopIndex++) { displayText[numberLines] += ' '; displayText[numberLines] += attributes.getQName(loopIndex); displayText[numberLines] += "=\""; displayText[numberLines] += attributes.getValue(loopIndex); displayText[numberLines] += '"'; } } displayText[numberLines] += '>'; numberLines++; } public void characters(char characters[], int start, int length) { String characterData = (new String(characters, start, length)).trim(); if(characterData.indexOf("\n") < 0 && characterData.length() > 0) { displayText[numberLines] = indentation; displayText[numberLines] += characterData; numberLines++; } } public void endElement(String uri, String localName, String qualifiedName) { indentation = indentation.substring(0, indentation.length() - 4) ; displayText[numberLines] = indentation; displayText[numberLines] += "</"; displayText[numberLines] += qualifiedName; displayText[numberLines] += '>'; numberLines++; if (qualifiedName.equals("marks")) { startElement("", "Result", "Result", null); characters("Pass".toCharArray(), 0, "Pass".length()); endElement("", "Result", "Result"); } } } This would produce the following result − <?xml version = "1.0" encoding = "UTF-8"?> <class> <student rollno = "393"> <firstname> dinkar </firstname> <lastname> kad </lastname> <nickname> dinkar </nickname> <marks> 85 </marks> <Result> Pass </Result> </student> <student rollno = "493"> <firstname> Vaneet </firstname> <lastname> Gupta </lastname> <nickname> vinni </nickname> <marks> 95 </marks> <Result> Pass </Result> </student> <student rollno = "593"> <firstname> jasvir </firstname> <lastname> singn </lastname> <nickname> jazz </nickname> <marks> 90 </marks> <Result> Pass </Result> </student> </class> 16 Lectures 2 hours Malhar Lathkar 19 Lectures 5 hours Malhar Lathkar 25 Lectures 2.5 hours Anadi Sharma 126 Lectures 7 hours Tushar Kale 119 Lectures 17.5 hours Monica Mittal 76 Lectures 7 hours Arnab Chakraborty Print Add Notes Bookmark this page
[ { "code": null, "e": 2436, "s": 2323, "text": "Here is the input XML file that we need to modify by appending <Result>Pass<Result/> at the end of </marks> tag." }, { "code": null, "e": 2987, "s": 2436, "text": "<?xml version = \"1.0\"?>\n<class>\n <student rollno = \"393\">\n <firstname>dinkar</firstname>\n <lastname>kad</lastname>\n <nickname>dinkar</nickname>\n <marks>85</marks>\n </student>\n \n <student rollno = \"493\">\n <firstname>Vaneet</firstname>\n <lastname>Gupta</lastname>\n <nickname>vinni</nickname>\n <marks>95</marks>\n </student>\n \n <student rollno = \"593\">\n <firstname>jasvir</firstname>\n <lastname>singn</lastname>\n <nickname>jazz</nickname>\n <marks>90</marks>\n </student>\n</class>" }, { "code": null, "e": 6681, "s": 2987, "text": "package com.tutorialspoint.xml;\n\nimport java.io.*;\nimport org.xml.sax.*;\nimport javax.xml.parsers.*;\nimport org.xml.sax.helpers.DefaultHandler;\n\npublic class SAXModifyDemo extends DefaultHandler {\n static String displayText[] = new String[1000];\n static int numberLines = 0;\n static String indentation = \"\";\n\n public static void main(String args[]) {\n\n try {\n File inputFile = new File(\"input.txt\");\n SAXParserFactory factory = \n SAXParserFactory.newInstance();\n SAXModifyDemo obj = new SAXModifyDemo();\n obj.childLoop(inputFile);\n FileWriter filewriter = new FileWriter(\"newfile.xml\");\n \n for(int loopIndex = 0; loopIndex < numberLines; loopIndex++) {\n filewriter.write(displayText[loopIndex].toCharArray());\n filewriter.write('\\n');\n System.out.println(displayText[loopIndex].toString());\n }\n filewriter.close();\n }\n catch (Exception e) {\n e.printStackTrace(System.err);\n }\n }\n\n public void childLoop(File input) {\n DefaultHandler handler = this;\n SAXParserFactory factory = SAXParserFactory.newInstance();\n \n try {\n SAXParser saxParser = factory.newSAXParser();\n saxParser.parse(input, handler);\n } catch (Throwable t) {}\n }\n\n public void startDocument() {\n displayText[numberLines] = indentation;\n displayText[numberLines] += \"<?xml version = \\\"1.0\\\" encoding = \\\"\"+\n \"UTF-8\" + \"\\\"?>\";\n numberLines++;\n }\n\n public void processingInstruction(String target, String data) {\n displayText[numberLines] = indentation;\n displayText[numberLines] += \"<?\";\n displayText[numberLines] += target;\n \n if (data != null && data.length() > 0) {\n displayText[numberLines] += ' ';\n displayText[numberLines] += data;\n }\n displayText[numberLines] += \"?>\";\n numberLines++;\n }\n\n public void startElement(String uri, String localName, String qualifiedName,\n Attributes attributes) {\n\n displayText[numberLines] = indentation;\n\n indentation += \" \";\n\n displayText[numberLines] += '<';\n displayText[numberLines] += qualifiedName;\n \n if (attributes != null) {\n int numberAttributes = attributes.getLength();\n\n for (int loopIndex = 0; loopIndex < numberAttributes; loopIndex++) {\n displayText[numberLines] += ' ';\n displayText[numberLines] += attributes.getQName(loopIndex);\n displayText[numberLines] += \"=\\\"\";\n displayText[numberLines] += attributes.getValue(loopIndex);\n displayText[numberLines] += '\"';\n }\n }\n displayText[numberLines] += '>';\n numberLines++;\n }\n\n public void characters(char characters[], int start, int length) {\n String characterData = (new String(characters, start, length)).trim();\n \n if(characterData.indexOf(\"\\n\") < 0 && characterData.length() > 0) {\n displayText[numberLines] = indentation;\n displayText[numberLines] += characterData;\n numberLines++;\n }\n }\n\n public void endElement(String uri, String localName, String qualifiedName) {\n indentation = indentation.substring(0, indentation.length() - 4) ;\n displayText[numberLines] = indentation;\n displayText[numberLines] += \"</\";\n displayText[numberLines] += qualifiedName;\n displayText[numberLines] += '>';\n numberLines++;\n\n if (qualifiedName.equals(\"marks\")) {\n startElement(\"\", \"Result\", \"Result\", null);\n characters(\"Pass\".toCharArray(), 0, \"Pass\".length());\n endElement(\"\", \"Result\", \"Result\");\n }\n }\n}" }, { "code": null, "e": 6723, "s": 6681, "text": "This would produce the following result −" }, { "code": null, "e": 7625, "s": 6723, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<class>\n <student rollno = \"393\">\n <firstname>\n dinkar\n </firstname>\n <lastname>\n kad\n </lastname>\n <nickname>\n dinkar\n </nickname>\n <marks>\n 85\n </marks>\n <Result>\n Pass\n </Result>\n </student>\n <student rollno = \"493\">\n <firstname>\n Vaneet\n </firstname>\n <lastname>\n Gupta\n </lastname>\n <nickname>\n vinni\n </nickname>\n <marks>\n 95\n </marks>\n <Result>\n Pass\n </Result>\n </student>\n <student rollno = \"593\">\n <firstname>\n jasvir\n </firstname>\n <lastname>\n singn\n </lastname>\n <nickname>\n jazz\n </nickname>\n <marks>\n 90\n </marks>\n <Result>\n Pass\n </Result>\n </student>\n</class>\n" }, { "code": null, "e": 7658, "s": 7625, "text": "\n 16 Lectures \n 2 hours \n" }, { "code": null, "e": 7674, "s": 7658, "text": " Malhar Lathkar" }, { "code": null, "e": 7707, "s": 7674, "text": "\n 19 Lectures \n 5 hours \n" }, { "code": null, "e": 7723, "s": 7707, "text": " Malhar Lathkar" }, { "code": null, "e": 7758, "s": 7723, "text": "\n 25 Lectures \n 2.5 hours \n" }, { "code": null, "e": 7772, "s": 7758, "text": " Anadi Sharma" }, { "code": null, "e": 7806, "s": 7772, "text": "\n 126 Lectures \n 7 hours \n" }, { "code": null, "e": 7820, "s": 7806, "text": " Tushar Kale" }, { "code": null, "e": 7857, "s": 7820, "text": "\n 119 Lectures \n 17.5 hours \n" }, { "code": null, "e": 7872, "s": 7857, "text": " Monica Mittal" }, { "code": null, "e": 7905, "s": 7872, "text": "\n 76 Lectures \n 7 hours \n" }, { "code": null, "e": 7924, "s": 7905, "text": " Arnab Chakraborty" }, { "code": null, "e": 7931, "s": 7924, "text": " Print" }, { "code": null, "e": 7942, "s": 7931, "text": " Add Notes" } ]
BufferedReader mark() method in Java with Examples - GeeksforGeeks
05 Jun, 2020 The mark() method of BufferedReader class in Java is used to mark the current position in the buffer reader stream. The reset() method of the same BufferedReader class is also called subsequently, after the mark() method is called. The reset() method fixes the position at the last marked position so that same byte can be read again. Syntax: public void mark(int readAheadLimit) throws IOException Overrides: It overrides the mark() method of Reader class. Parameters: This method accepts readAheadLimit of Integer type which represents the maximum limit of bytes that can be read before the mark position becomes invalid. Return value: This method does not return any value. Exceptions: This method can throw two types of exceptions. IllegalArgumentException – This exception is thrown if the passed parameter readAheadLimit is less than zero. IOException – This exception is thrown if an I/O error occurs. Below programs illustrate mark() method in BufferedReader class in IO package.Program 1: Assume the existence of the file “c:/demo.txt”. // Java program to illustrate// BufferedReader mark() method import java.io.*; public class GFG { public static void main(String[] args) { // Read the stream 'demo.txt' // for containing text "GEEKS" FileReader fileReader = new FileReader( "c:/demo.txt"); // Convert fileReader to // bufferedReader BufferedReader buffReader = new BufferedReader( fileReader); // Read and print characters // one by one System.out.println( "Char : " + (char)buffReader.read()); System.out.println( "Char : " + (char)buffReader.read()); System.out.println( "Char : " + (char)buffReader.read()); // Mark is set on the stream buffReader.mark(0); System.out.println( "Char : " + (char)buffReader.read()); // Reset() is invoked buffReader.reset(); // Read and print characters System.out.println( "Char : " + (char)buffReader.read()); System.out.println( "Char : " + (char)buffReader.read()); }} Char : G Char : E Char : E Char : K Char : K Char : S Program 2: Assume the existence of the file “c:/demo.txt”. // Java program to illustrate// BufferedReader mark() method import java.io.*;public class GFG { public static void main(String[] args) { // Read the stream 'demo.txt' // containing text "GEEKSFORGEEKS" FileReader fileReader = new FileReader( "c:/demo.txt"); // Convert fileReader to // bufferedReader BufferedReader buffReader = new BufferedReader( fileReader); // Read and print characters // one by one System.out.println( "Char : " + (char)buffReader.read()); System.out.println( "Char : " + (char)buffReader.read()); System.out.println( "Char : " + (char)buffReader.read()); System.out.println( "Char : " + (char)buffReader.read()); // Mark is set on the stream buffReader.mark(0); System.out.println( "Char : " + (char)buffReader.read()); // Reset() is invoked buffReader.reset(); // read and print characters System.out.println( "Char : " + (char)buffReader.read()); System.out.println( "Char : " + (char)buffReader.read()); System.out.println( "Char : " + (char)buffReader.read()); System.out.println( "Char : " + (char)buffReader.read()); }} Char : G Char : E Char : E Char : K Char : S Char : S Char : F Char : O Char : R References:https://docs.oracle.com/javase/10/docs/api/java/io/BufferedReader.html#mark(int) Java-Functions Java-IO package Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Initialize an ArrayList in Java Object Oriented Programming (OOPs) Concept in Java HashMap in Java with Examples Interfaces in Java ArrayList in Java How to iterate any Map in Java Multidimensional Arrays in Java Stack Class in Java Singleton Class in Java Set in Java
[ { "code": null, "e": 24480, "s": 24452, "text": "\n05 Jun, 2020" }, { "code": null, "e": 24815, "s": 24480, "text": "The mark() method of BufferedReader class in Java is used to mark the current position in the buffer reader stream. The reset() method of the same BufferedReader class is also called subsequently, after the mark() method is called. The reset() method fixes the position at the last marked position so that same byte can be read again." }, { "code": null, "e": 24823, "s": 24815, "text": "Syntax:" }, { "code": null, "e": 24900, "s": 24823, "text": "public void mark(int readAheadLimit) \n throws IOException\n" }, { "code": null, "e": 24959, "s": 24900, "text": "Overrides: It overrides the mark() method of Reader class." }, { "code": null, "e": 25125, "s": 24959, "text": "Parameters: This method accepts readAheadLimit of Integer type which represents the maximum limit of bytes that can be read before the mark position becomes invalid." }, { "code": null, "e": 25178, "s": 25125, "text": "Return value: This method does not return any value." }, { "code": null, "e": 25237, "s": 25178, "text": "Exceptions: This method can throw two types of exceptions." }, { "code": null, "e": 25347, "s": 25237, "text": "IllegalArgumentException – This exception is thrown if the passed parameter readAheadLimit is less than zero." }, { "code": null, "e": 25410, "s": 25347, "text": "IOException – This exception is thrown if an I/O error occurs." }, { "code": null, "e": 25547, "s": 25410, "text": "Below programs illustrate mark() method in BufferedReader class in IO package.Program 1: Assume the existence of the file “c:/demo.txt”." }, { "code": "// Java program to illustrate// BufferedReader mark() method import java.io.*; public class GFG { public static void main(String[] args) { // Read the stream 'demo.txt' // for containing text \"GEEKS\" FileReader fileReader = new FileReader( \"c:/demo.txt\"); // Convert fileReader to // bufferedReader BufferedReader buffReader = new BufferedReader( fileReader); // Read and print characters // one by one System.out.println( \"Char : \" + (char)buffReader.read()); System.out.println( \"Char : \" + (char)buffReader.read()); System.out.println( \"Char : \" + (char)buffReader.read()); // Mark is set on the stream buffReader.mark(0); System.out.println( \"Char : \" + (char)buffReader.read()); // Reset() is invoked buffReader.reset(); // Read and print characters System.out.println( \"Char : \" + (char)buffReader.read()); System.out.println( \"Char : \" + (char)buffReader.read()); }}", "e": 26763, "s": 25547, "text": null }, { "code": null, "e": 26818, "s": 26763, "text": "Char : G\nChar : E\nChar : E\nChar : K\nChar : K\nChar : S\n" }, { "code": null, "e": 26877, "s": 26818, "text": "Program 2: Assume the existence of the file “c:/demo.txt”." }, { "code": "// Java program to illustrate// BufferedReader mark() method import java.io.*;public class GFG { public static void main(String[] args) { // Read the stream 'demo.txt' // containing text \"GEEKSFORGEEKS\" FileReader fileReader = new FileReader( \"c:/demo.txt\"); // Convert fileReader to // bufferedReader BufferedReader buffReader = new BufferedReader( fileReader); // Read and print characters // one by one System.out.println( \"Char : \" + (char)buffReader.read()); System.out.println( \"Char : \" + (char)buffReader.read()); System.out.println( \"Char : \" + (char)buffReader.read()); System.out.println( \"Char : \" + (char)buffReader.read()); // Mark is set on the stream buffReader.mark(0); System.out.println( \"Char : \" + (char)buffReader.read()); // Reset() is invoked buffReader.reset(); // read and print characters System.out.println( \"Char : \" + (char)buffReader.read()); System.out.println( \"Char : \" + (char)buffReader.read()); System.out.println( \"Char : \" + (char)buffReader.read()); System.out.println( \"Char : \" + (char)buffReader.read()); }}", "e": 28356, "s": 26877, "text": null }, { "code": null, "e": 28438, "s": 28356, "text": "Char : G\nChar : E\nChar : E\nChar : K\nChar : S\nChar : S\nChar : F\nChar : O\nChar : R\n" }, { "code": null, "e": 28530, "s": 28438, "text": "References:https://docs.oracle.com/javase/10/docs/api/java/io/BufferedReader.html#mark(int)" }, { "code": null, "e": 28545, "s": 28530, "text": "Java-Functions" }, { "code": null, "e": 28561, "s": 28545, "text": "Java-IO package" }, { "code": null, "e": 28566, "s": 28561, "text": "Java" }, { "code": null, "e": 28571, "s": 28566, "text": "Java" }, { "code": null, "e": 28669, "s": 28571, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28701, "s": 28669, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 28752, "s": 28701, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 28782, "s": 28752, "text": "HashMap in Java with Examples" }, { "code": null, "e": 28801, "s": 28782, "text": "Interfaces in Java" }, { "code": null, "e": 28819, "s": 28801, "text": "ArrayList in Java" }, { "code": null, "e": 28850, "s": 28819, "text": "How to iterate any Map in Java" }, { "code": null, "e": 28882, "s": 28850, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 28902, "s": 28882, "text": "Stack Class in Java" }, { "code": null, "e": 28926, "s": 28902, "text": "Singleton Class in Java" } ]
Average of Levels in Binary Tree in C++
Suppose we have a non-empty binary tree; we have to find the average value of the nodes on each level in the return the average values as an array. So, if the input is like then the output will be [3, 14.5, 11]. To solve this, we will follow these steps − Define an array result Define an array result Define one queue q Define one queue q insert root into q insert root into q while (not q is empty), do −n := size of qDefine an array tempwhile n is non-zero, do −t := first element of qinsert value of t into tempdelete element from qif left of t is not null, then −insert left of t into qif right of t is not null, then −insert right of t into q(decrease n by 1)if size of temp is same as 1, then −insert temp[0] at the end of resultotherwise when size of temp > 1, then −sum := 0for initialize i := 0, when i < size of temp, update (increase i by 1), do −sum := sum + temp[i]insert (sum / size of temp) at the end of result while (not q is empty), do − n := size of q n := size of q Define an array temp Define an array temp while n is non-zero, do −t := first element of qinsert value of t into tempdelete element from qif left of t is not null, then −insert left of t into qif right of t is not null, then −insert right of t into q(decrease n by 1) while n is non-zero, do − t := first element of q t := first element of q insert value of t into temp insert value of t into temp delete element from q delete element from q if left of t is not null, then −insert left of t into q if left of t is not null, then − insert left of t into q insert left of t into q if right of t is not null, then −insert right of t into q if right of t is not null, then − insert right of t into q insert right of t into q (decrease n by 1) (decrease n by 1) if size of temp is same as 1, then −insert temp[0] at the end of result if size of temp is same as 1, then − insert temp[0] at the end of result insert temp[0] at the end of result otherwise when size of temp > 1, then −sum := 0for initialize i := 0, when i < size of temp, update (increase i by 1), do −sum := sum + temp[i]insert (sum / size of temp) at the end of result otherwise when size of temp > 1, then − sum := 0 sum := 0 for initialize i := 0, when i < size of temp, update (increase i by 1), do −sum := sum + temp[i] for initialize i := 0, when i < size of temp, update (increase i by 1), do − sum := sum + temp[i] sum := sum + temp[i] insert (sum / size of temp) at the end of result insert (sum / size of temp) at the end of result return result return result Let us see the following implementation to get a better understanding − Live Demo #include <bits/stdc++.h> using namespace std; void print_vector(vector<auto> v){ cout << "["; for(int i = 0; i<v.size(); i++){ cout << v[i] << ", "; } cout << "]"<<endl; } class TreeNode{ public: int val; TreeNode *left, *right; TreeNode(int data){ val = data; left = NULL; right = NULL; } }; void insert(TreeNode **root, int val){ queue<TreeNode*> q; q.push(*root); while(q.size()){ TreeNode *temp = q.front(); q.pop(); if(!temp->left){ if(val != NULL) temp->left = new TreeNode(val); else temp->left = new TreeNode(0); return; } else{ q.push(temp->left); } if(!temp->right){ if(val != NULL) temp->right = new TreeNode(val); else temp->right = new TreeNode(0); return; } else{ q.push(temp->right); } } } TreeNode *make_tree(vector<int> v){ TreeNode *root = new TreeNode(v[0]); for(int i = 1; i<v.size(); i++){ insert(&root, v[i]); } return root; } class Solution{ public: vector<float> averageOfLevels(TreeNode *root){ vector<float> result; queue<TreeNode*> q; q.push(root); while (!q.empty()) { int n = q.size(); vector<float> temp; while (n) { TreeNode* t = q.front(); temp.push_back(t->val); q.pop(); if (t->left && t->left->val != 0) q.push(t->left); if (t->right && t->right->val != 0) q.push(t->right); n--; } if (temp.size() == 1) result.push_back(temp[0]); else if (temp.size() > 1) { double sum = 0; for (int i = 0; i < temp.size(); i++) { sum += temp[i]; } result.push_back(sum / temp.size()); } } return result; } }; main(){ Solution ob; vector<int> v = {3,9,20,NULL,NULL,15,7}; TreeNode *root = make_tree(v); print_vector(ob.averageOfLevels(root)); } {3,9,20,NULL,NULL,15,7} [3, 14.5, 11, ]
[ { "code": null, "e": 1210, "s": 1062, "text": "Suppose we have a non-empty binary tree; we have to find the average value of the nodes on each level in the return the average values as an array." }, { "code": null, "e": 1235, "s": 1210, "text": "So, if the input is like" }, { "code": null, "e": 1274, "s": 1235, "text": "then the output will be [3, 14.5, 11]." }, { "code": null, "e": 1318, "s": 1274, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1341, "s": 1318, "text": "Define an array result" }, { "code": null, "e": 1364, "s": 1341, "text": "Define an array result" }, { "code": null, "e": 1383, "s": 1364, "text": "Define one queue q" }, { "code": null, "e": 1402, "s": 1383, "text": "Define one queue q" }, { "code": null, "e": 1421, "s": 1402, "text": "insert root into q" }, { "code": null, "e": 1440, "s": 1421, "text": "insert root into q" }, { "code": null, "e": 1990, "s": 1440, "text": "while (not q is empty), do −n := size of qDefine an array tempwhile n is non-zero, do −t := first element of qinsert value of t into tempdelete element from qif left of t is not null, then −insert left of t into qif right of t is not null, then −insert right of t into q(decrease n by 1)if size of temp is same as 1, then −insert temp[0] at the end of resultotherwise when size of temp > 1, then −sum := 0for initialize i := 0, when i < size of temp, update (increase i by 1), do −sum := sum + temp[i]insert (sum / size of temp) at the end of result" }, { "code": null, "e": 2019, "s": 1990, "text": "while (not q is empty), do −" }, { "code": null, "e": 2034, "s": 2019, "text": "n := size of q" }, { "code": null, "e": 2049, "s": 2034, "text": "n := size of q" }, { "code": null, "e": 2070, "s": 2049, "text": "Define an array temp" }, { "code": null, "e": 2091, "s": 2070, "text": "Define an array temp" }, { "code": null, "e": 2317, "s": 2091, "text": "while n is non-zero, do −t := first element of qinsert value of t into tempdelete element from qif left of t is not null, then −insert left of t into qif right of t is not null, then −insert right of t into q(decrease n by 1)" }, { "code": null, "e": 2343, "s": 2317, "text": "while n is non-zero, do −" }, { "code": null, "e": 2367, "s": 2343, "text": "t := first element of q" }, { "code": null, "e": 2391, "s": 2367, "text": "t := first element of q" }, { "code": null, "e": 2419, "s": 2391, "text": "insert value of t into temp" }, { "code": null, "e": 2447, "s": 2419, "text": "insert value of t into temp" }, { "code": null, "e": 2469, "s": 2447, "text": "delete element from q" }, { "code": null, "e": 2491, "s": 2469, "text": "delete element from q" }, { "code": null, "e": 2547, "s": 2491, "text": "if left of t is not null, then −insert left of t into q" }, { "code": null, "e": 2580, "s": 2547, "text": "if left of t is not null, then −" }, { "code": null, "e": 2604, "s": 2580, "text": "insert left of t into q" }, { "code": null, "e": 2628, "s": 2604, "text": "insert left of t into q" }, { "code": null, "e": 2686, "s": 2628, "text": "if right of t is not null, then −insert right of t into q" }, { "code": null, "e": 2720, "s": 2686, "text": "if right of t is not null, then −" }, { "code": null, "e": 2745, "s": 2720, "text": "insert right of t into q" }, { "code": null, "e": 2770, "s": 2745, "text": "insert right of t into q" }, { "code": null, "e": 2788, "s": 2770, "text": "(decrease n by 1)" }, { "code": null, "e": 2806, "s": 2788, "text": "(decrease n by 1)" }, { "code": null, "e": 2878, "s": 2806, "text": "if size of temp is same as 1, then −insert temp[0] at the end of result" }, { "code": null, "e": 2915, "s": 2878, "text": "if size of temp is same as 1, then −" }, { "code": null, "e": 2951, "s": 2915, "text": "insert temp[0] at the end of result" }, { "code": null, "e": 2987, "s": 2951, "text": "insert temp[0] at the end of result" }, { "code": null, "e": 3179, "s": 2987, "text": "otherwise when size of temp > 1, then −sum := 0for initialize i := 0, when i < size of temp, update (increase i by 1), do −sum := sum + temp[i]insert (sum / size of temp) at the end of result" }, { "code": null, "e": 3219, "s": 3179, "text": "otherwise when size of temp > 1, then −" }, { "code": null, "e": 3228, "s": 3219, "text": "sum := 0" }, { "code": null, "e": 3237, "s": 3228, "text": "sum := 0" }, { "code": null, "e": 3334, "s": 3237, "text": "for initialize i := 0, when i < size of temp, update (increase i by 1), do −sum := sum + temp[i]" }, { "code": null, "e": 3411, "s": 3334, "text": "for initialize i := 0, when i < size of temp, update (increase i by 1), do −" }, { "code": null, "e": 3432, "s": 3411, "text": "sum := sum + temp[i]" }, { "code": null, "e": 3453, "s": 3432, "text": "sum := sum + temp[i]" }, { "code": null, "e": 3502, "s": 3453, "text": "insert (sum / size of temp) at the end of result" }, { "code": null, "e": 3551, "s": 3502, "text": "insert (sum / size of temp) at the end of result" }, { "code": null, "e": 3565, "s": 3551, "text": "return result" }, { "code": null, "e": 3579, "s": 3565, "text": "return result" }, { "code": null, "e": 3651, "s": 3579, "text": "Let us see the following implementation to get a better understanding −" }, { "code": null, "e": 3662, "s": 3651, "text": " Live Demo" }, { "code": null, "e": 5805, "s": 3662, "text": "#include <bits/stdc++.h>\nusing namespace std;\nvoid print_vector(vector<auto> v){\n cout << \"[\";\n for(int i = 0; i<v.size(); i++){\n cout << v[i] << \", \";\n }\n cout << \"]\"<<endl;\n}\nclass TreeNode{\n public:\n int val;\n TreeNode *left, *right;\n TreeNode(int data){\n val = data;\n left = NULL;\n right = NULL;\n }\n};\nvoid insert(TreeNode **root, int val){\n queue<TreeNode*> q;\n q.push(*root);\n while(q.size()){\n TreeNode *temp = q.front();\n q.pop();\n if(!temp->left){\n if(val != NULL)\n temp->left = new TreeNode(val);\n else\n temp->left = new TreeNode(0);\n return;\n }\n else{\n q.push(temp->left);\n }\n if(!temp->right){\n if(val != NULL)\n temp->right = new TreeNode(val);\n else\n temp->right = new TreeNode(0);\n return;\n }\n else{\n q.push(temp->right);\n }\n }\n}\nTreeNode *make_tree(vector<int> v){\n TreeNode *root = new TreeNode(v[0]);\n for(int i = 1; i<v.size(); i++){\n insert(&root, v[i]);\n }\n return root;\n}\nclass Solution{\npublic:\n vector<float> averageOfLevels(TreeNode *root){\n vector<float> result;\n queue<TreeNode*> q;\n q.push(root);\n while (!q.empty()) {\n int n = q.size();\n vector<float> temp;\n while (n) {\n TreeNode* t = q.front();\n temp.push_back(t->val);\n q.pop();\n if (t->left && t->left->val != 0)\n q.push(t->left);\n if (t->right && t->right->val != 0)\n q.push(t->right);\n n--;\n }\n if (temp.size() == 1)\n result.push_back(temp[0]);\n else if (temp.size() > 1) {\n double sum = 0;\n for (int i = 0; i < temp.size(); i++) {\n sum += temp[i];\n }\n result.push_back(sum / temp.size());\n }\n }\n return result;\n }\n};\nmain(){\n Solution ob;\n vector<int> v = {3,9,20,NULL,NULL,15,7};\n TreeNode *root = make_tree(v);\n print_vector(ob.averageOfLevels(root));\n}" }, { "code": null, "e": 5829, "s": 5805, "text": "{3,9,20,NULL,NULL,15,7}" }, { "code": null, "e": 5845, "s": 5829, "text": "[3, 14.5, 11, ]" } ]
Length of the smallest substring which contains all vowels - GeeksforGeeks
08 Jun, 2021 Given string str consisting of only lowercase English alphabets, the task is to find the substring of the smallest length which contains all the vowels. If no such substring is found, print -1. Example: Input: str = “babeivoucu” Output: 7 Explanation: Smallest substring which contains each vowel atleast once is “abeivou” of length 7. Input: str = “abcdef” Output: -1 Explanation: No such substring is found. Two Pointer Approach: Store the frequencies of each vowel and the indices at which the vowels are present. If all the vowels are not present, straightaway print -1. Take two pointers i and j at the first and last indices containing a vowel. If the frequencies of vowel at ith and jth index exceed 1, decrease the count of that vowel and shift i and j to the right and left respectively to the next index containing a vowel. If the frequencies of vowel at ith or jth index is equal to 1, set flag1 or flag2 respectively and continue. Once both flag1 and flag2 are set, the length of the substring cannot be further minimized. The distance between the current indices pointed by the two pointers denotes the result. The below code is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ Program to find the// length of the smallest// substring of which// contains all vowels #include <bits/stdc++.h>using namespace std; int findMinLength(string s){ int n = s.size(); // Map to store the // frequency of vowels map<char, int> counts; // Store the indices // which contains // the vowels vector<int> indices; for (int i = 0; i < n; i++) { if (s[i] == 'a' || s[i] == 'e' || s[i] == 'o' || s[i] == 'i' || s[i] == 'u') { counts[s[i]]++; indices.push_back(i); } } // If all vowels are not // present in the string if (counts.size() < 5) return -1; int flag1 = 0, flag2 = 0; int i = 0; int j = indices.size() - 1; while ((j - i) >= 4) { // If the frequency of the // vowel at i-th index // exceeds 1 if (!flag1 && counts[s[indices[i]]] > 1) { // Decrease the frequency // of that vowel counts[s[indices[i]]]--; // Move to the left i++; } // Otherwise set flag1 else flag1 = 1; // If the frequency of the // vowel at j-th index // exceeds 1 if (!flag2 && counts[s[indices[j]]] > 1) { // Decrease the frequency // of that vowel counts[s[indices[j]]]--; // Move to the right j--; } // Otherwise set flag2 else flag2 = 1; // If both flag1 and flag2 // are set, break out of the // loop as the substring // length cannot be minimized if (flag1 && flag2) break; } // Return the length of the substring return (indices[j] - indices[i] + 1);} int main(){ string s = "aaeebbeaccaaoiuooooooooiuu"; cout << findMinLength(s); return 0;} // Java program to find the length of// the smallest substring of which// contains all vowelsimport java.util.*;class GFG{ public static int findMinLength(String s){ int n = s.length(); // Map to store the // frequency of vowels HashMap<Character, Integer> counts = new HashMap<>(); // Store the indices // which contains // the vowels Vector<Integer> indices = new Vector<Integer>(); for(int i = 0; i < n; i++) { if (s.charAt(i) == 'a' || s.charAt(i) == 'e' || s.charAt(i) == 'o' || s.charAt(i) == 'i' || s.charAt(i) == 'u') { if (counts.containsKey(s.charAt(i))) { counts.replace(s.charAt(i), counts.get(s.charAt(i)) + 1); } else { counts.put(s.charAt(i), 1); } indices.add(i); } } // If all vowels are not // present in the string if (counts.size() < 5) return -1; int flag1 = 0, flag2 = 0; int i = 0; int j = indices.size() - 1; while ((j - i) >= 4) { // If the frequency of the // vowel at i-th index // exceeds 1 if (flag1 == 0 && counts.get(s.charAt( indices.get(i))) > 1) { // Decrease the frequency // of that vowel counts.replace(s.charAt(indices.get(i)), counts.get(s.charAt(indices.get(i))) - 1); // Move to the left i++; } // Otherwise set flag1 else flag1 = 1; // If the frequency of the // vowel at j-th index // exceeds 1 if (flag2 == 0 && counts.get(s.charAt( indices.get(j))) > 1) { // Decrease the frequency // of that vowel counts.replace(s.charAt(indices.get(j)), counts.get(s.charAt(indices.get(j))) - 1); // Move to the right j--; } // Otherwise set flag2 else flag2 = 1; // If both flag1 and flag2 // are set, break out of the // loop as the substring // length cannot be minimized if (flag1 == 1 && flag2 == 1) break; } // Return the length of the substring return (indices.get(j) - indices.get(i) + 1);} // Driver Codepublic static void main(String[] args){ String s = "aaeebbeaccaaoiuooooooooiuu"; System.out.print(findMinLength(s));}} // This code is contributed by divyeshrabadiya07 # Python3 program to find the# length of the smallest# substring of which# contains all vowelsfrom collections import defaultdict def findMinLength(s): n = len(s) # Map to store the # frequency of vowels counts = defaultdict(int) # Store the indices # which contains # the vowels indices = [] for i in range(n): if (s[i] == 'a' or s[i] == 'e' or s[i] == 'o' or s[i] == 'i' or s[i] == 'u'): counts[s[i]] += 1 indices.append(i) # If all vowels are not # present in the string if len(counts) < 5: return -1 flag1 = 0 flag2 = 0 i = 0 j = len(indices) - 1 while (j - i) >= 4: # If the frequency of the # vowel at i-th index # exceeds 1 if (~flag1 and counts[s[indices[i]]] > 1): # Decrease the frequency # of that vowel counts[s[indices[i]]] -= 1 # Move to the left i += 1 # Otherwise set flag1 else: flag1 = 1 # If the frequency of the # vowel at j-th index # exceeds 1 if (~flag2 and counts[s[indices[j]]] > 1): # Decrease the frequency # of that vowel counts[s[indices[j]]] -= 1 # Move to the right j -= 1 # Otherwise set flag2 else: flag2 = 1 # If both flag1 and flag2 # are set, break out of the # loop as the substring # length cannot be minimized if (flag1 and flag2): break # Return the length of the substring return (indices[j] - indices[i] + 1) # Driver Codes = "aaeebbeaccaaoiuooooooooiuu"print(findMinLength(s)) # This code is contributed by# divyamohan123 // C# program to find the length of// the smallest substring of which// contains all vowelsusing System;using System.Collections.Generic;class GFG{ public static int findMinLength(String s){ int n = s.Length; int i = 0; // Map to store the // frequency of vowels Dictionary<char, int> counts = new Dictionary<char, int>(); // Store the indices // which contains // the vowels List<int> indices = new List<int>(); for(i = 0; i < n; i++) { if (s[i] == 'a' || s[i] == 'e' || s[i] == 'o' || s[i] == 'i' || s[i] == 'u') { if (counts.ContainsKey(s[i])) { counts[s[i]] = counts[s[i]] + 1; } else { counts.Add(s[i], 1); } indices.Add(i); } } // If all vowels are not // present in the string if (counts.Count < 5) return -1; int flag1 = 0, flag2 = 0; i = 0; int j = indices.Count - 1; while ((j - i) >= 4) { // If the frequency of the // vowel at i-th index // exceeds 1 if (flag1 == 0 && counts[s[indices[i]]] > 1) { // Decrease the frequency // of that vowel counts[s[indices[i]]]= counts[s[indices[i]]] - 1; // Move to the left i++; } // Otherwise set flag1 else flag1 = 1; // If the frequency of the // vowel at j-th index // exceeds 1 if (flag2 == 0 && counts[s[indices[j]]] > 1) { // Decrease the frequency // of that vowel counts[s[indices[j]]] = counts[s[indices[j]]] - 1; // Move to the right j--; } // Otherwise set flag2 else flag2 = 1; // If both flag1 and flag2 // are set, break out of the // loop as the substring // length cannot be minimized if (flag1 == 1 && flag2 == 1) break; } // Return the length of the substring return (indices[j] - indices[i] + 1);} // Driver Codepublic static void Main(String[] args){ String s = "aaeebbeaccaaoiuooooooooiuu"; Console.Write(findMinLength(s));}} // This code is contributed by shikhasingrajput <script> // JavaScript Program to find the// length of the smallest// substring of which// contains all vowels function findMinLength(s){ var n = s.length; // Map to store the // frequency of vowels var counts = new Map(); // Store the indices // which contains // the vowels var indices = []; for (var i = 0; i < n; i++) { if (s[i] == 'a' || s[i] == 'e' || s[i] == 'o' || s[i] == 'i' || s[i] == 'u') { if(counts.has(s[i])) counts.set(s[i], counts.get(s[i])+1) else counts.set(s[i], 1) indices.push(i); } } // If all vowels are not // present in the string if (counts.size < 5) return -1; var flag1 = 0, flag2 = 0; var i = 0; var j = indices.length - 1; while ((j - i) >= 4) { // If the frequency of the // vowel at i-th index // exceeds 1 if (!flag1 && counts.get(s[indices[i]]) > 1) { // Decrease the frequency // of that vowel if(counts.has(s[indices[i]])) counts.set(s[indices[i]], counts.get(s[indices[i]])-1) // Move to the left i++; } // Otherwise set flag1 else flag1 = 1; // If the frequency of the // vowel at j-th index // exceeds 1 if (!flag2 && counts.get(s[indices[j]]) > 1) { // Decrease the frequency // of that vowel if(counts.has(s[indices[j]])) counts.set(s[indices[j]], counts.get(s[indices[j]])-1) // Move to the right j--; } // Otherwise set flag2 else flag2 = 1; // If both flag1 and flag2 // are set, break out of the // loop as the substring // length cannot be minimized if (flag1 && flag2) break; } // Return the length of the substring return (indices[j] - indices[i] + 1);} var s = "aaeebbeaccaaoiuooooooooiuu";document.write( findMinLength(s)); </script> 9 Time Complexity: O(N) Auxiliary Space: O(N) Sliding Window Approach: Maintain an array count to store the frequency of each vowel. Maintain a start variable to store the starting index of the current substring. Iterate over the string and do the following: Increase the frequency of the character if it is a vowel.Move start as right as possible based on the condition that either the character at the start is not a vowel or it is a vowel with a frequency greater than 1 which means that it has appeared previously.Once the start is moved as far as possible, check if all vowels are present in the substring between start and the current index.Whenever the above condition satisfies, update the minimum length of such substring obtained Increase the frequency of the character if it is a vowel. Move start as right as possible based on the condition that either the character at the start is not a vowel or it is a vowel with a frequency greater than 1 which means that it has appeared previously. Once the start is moved as far as possible, check if all vowels are present in the substring between start and the current index. Whenever the above condition satisfies, update the minimum length of such substring obtained Print the minimum length of substring obtained or print -1 if no such substring is obtained The below code implements the above approach: C++ Java Python3 C# Javascript // C++ Program to find the// length of the smallest// substring of which// contains all vowels #include <bits/stdc++.h>using namespace std; // Function to return the// index for respective// vowels to increase their countint get_index(char ch){ if (ch == 'a') return 0; else if (ch == 'e') return 1; else if (ch == 'i') return 2; else if (ch == 'o') return 3; else if (ch == 'u') return 4; // Returns -1 for consonants else return -1;} // Function to find the minimum lengthint findMinLength(string s){ int n = s.size(); int ans = n + 1; // Store the starting index // of the current substring int start = 0; // Store the frequencies of vowels int count[5] = { 0 }; for (int x = 0; x < n; x++) { int idx = get_index(s[x]); // If the current character // is a vowel if (idx != -1) { // Increase its count count[idx]++; } // Move start as much // right as possible int idx_start = get_index(s[start]); while (idx_start == -1 || count[idx_start] > 1) { if (idx_start != -1) { count[idx_start]--; } start++; if (start < n) idx_start = get_index(s[start]); } // Condition for valid substring if (count[0] > 0 && count[1] > 0 && count[2] > 0 && count[3] > 0 && count[4] > 0) { ans = min(ans, x - start + 1); } } if (ans == n + 1) return -1; return ans;} // Driver codeint main(){ string s = "aaeebbeaccaaoiuooooooooiuu"; cout << findMinLength(s); return 0;} // Java program to find the length// of the smallest subString of// which contains all vowelsimport java.util.*; class GFG{ // Function to return the// index for respective// vowels to increase their countstatic int get_index(char ch){ if (ch == 'a') return 0; else if (ch == 'e') return 1; else if (ch == 'i') return 2; else if (ch == 'o') return 3; else if (ch == 'u') return 4; // Returns -1 for consonants else return -1;} // Function to find the minimum lengthstatic int findMinLength(String s){ int n = s.length(); int ans = n + 1; // Store the starting index // of the current subString int start = 0; // Store the frequencies of vowels int count[] = new int[5]; for(int x = 0; x < n; x++) { int idx = get_index(s.charAt(x)); // If the current character // is a vowel if (idx != -1) { // Increase its count count[idx]++; } // Move start as much // right as possible int idx_start = get_index(s.charAt(start)); while (idx_start == -1 || count[idx_start] > 1) { if (idx_start != -1) { count[idx_start]--; } start++; if (start < n) idx_start = get_index(s.charAt(start)); } // Condition for valid subString if (count[0] > 0 && count[1] > 0 && count[2] > 0 && count[3] > 0 && count[4] > 0) { ans = Math.min(ans, x - start + 1); } } if (ans == n + 1) return -1; return ans;} // Driver codepublic static void main(String[] args){ String s = "aaeebbeaccaaoiuooooooooiuu"; System.out.print(findMinLength(s));}} // This code is contributed by 29AjayKumar # Python3 Program to find the# length of the smallest# substring of which# contains all vowels # Function to return the# index for respective# vowels to increase their countdef get_index(ch): if (ch == 'a'): return 0 elif (ch == 'e'): return 1 elif (ch == 'i'): return 2 elif (ch == 'o'): return 3 elif (ch == 'u'): return 4 # Returns -1 for consonants else: return -1 # Function to find the minimum lengthdef findMinLength(s): n = len(s) ans = n + 1 # Store the starting index # of the current substring start = 0 # Store the frequencies # of vowels count = [0] * 5 for x in range (n): idx = get_index(s[x]) # If the current character # is a vowel if (idx != -1): # Increase its count count[idx] += 1 # Move start as much # right as possible idx_start = get_index(s[start]) while (idx_start == -1 or count[idx_start] > 1): if (idx_start != -1): count[idx_start] -= 1 start += 1 if (start < n): idx_start = get_index(s[start]) # Condition for valid substring if (count[0] > 0 and count[1] > 0 and count[2] > 0 and count[3] > 0 and count[4] > 0): ans = min(ans, x - start + 1) if (ans == n + 1): return -1 return ans # Driver codeif __name__ == "__main__": s = "aaeebbeaccaaoiuooooooooiuu" print(findMinLength(s)) # This code is contributed by Chitranayal // C# program to find the length// of the smallest subString of// which contains all vowelsusing System;class GFG{ // Function to return the// index for respective// vowels to increase their countstatic int get_index(char ch){ if (ch == 'a') return 0; else if (ch == 'e') return 1; else if (ch == 'i') return 2; else if (ch == 'o') return 3; else if (ch == 'u') return 4; // Returns -1 for consonants else return -1;} // Function to find the minimum lengthstatic int findMinLength(String s){ int n = s.Length; int ans = n + 1; // Store the starting index // of the current subString int start = 0; // Store the frequencies of vowels int []count = new int[5]; for(int x = 0; x < n; x++) { int idx = get_index(s[x]); // If the current character // is a vowel if (idx != -1) { // Increase its count count[idx]++; } // Move start as much // right as possible int idx_start = get_index(s[start]); while (idx_start == -1 || count[idx_start] > 1) { if (idx_start != -1) { count[idx_start]--; } start++; if (start < n) idx_start = get_index(s[start]); } // Condition for valid subString if (count[0] > 0 && count[1] > 0 && count[2] > 0 && count[3] > 0 && count[4] > 0) { ans = Math.Min(ans, x - start + 1); } } if (ans == n + 1) return -1; return ans;} // Driver codepublic static void Main(String[] args){ String s = "aaeebbeaccaaoiuooooooooiuu"; Console.Write(findMinLength(s));}} // This code is contributed by sapnasingh4991 <script>// Javascript program to find the length// of the smallest subString of// which contains all vowels // Function to return the// index for respective// vowels to increase their countfunction get_index(ch){ if (ch == 'a') return 0; else if (ch == 'e') return 1; else if (ch == 'i') return 2; else if (ch == 'o') return 3; else if (ch == 'u') return 4; // Returns -1 for consonants else return -1;} // Function to find the minimum lengthfunction findMinLength(s){ let n = s.length; let ans = n + 1; // Store the starting index // of the current subString let start = 0; // Store the frequencies of vowels let count = new Array(5); for(let i = 0; i < 5; i++) { count[i] = 0; } for(let x = 0; x < n; x++) { let idx = get_index(s[x]); // If the current character // is a vowel if (idx != -1) { // Increase its count count[idx]++; } // Move start as much // right as possible let idx_start = get_index(s[start]); while (idx_start == -1 || count[idx_start] > 1) { if (idx_start != -1) { count[idx_start]--; } start++; if (start < n) idx_start = get_index(s[start]); } // Condition for valid subString if (count[0] > 0 && count[1] > 0 && count[2] > 0 && count[3] > 0 && count[4] > 0) { ans = Math.min(ans, x - start + 1); } } if (ans == n + 1) return -1; return ans;} // Driver codelet s = "aaeebbeaccaaoiuooooooooiuu";document.write(findMinLength(s)); // This code is contributed by avanitrachhadiya2155</script> 9 Time Complexity: O(N) divyamohan123 29AjayKumar sapnasingh4991 nidhi_biet ukasp divyeshrabadiya07 shikhasingrajput rutvik_56 avanitrachhadiya2155 sliding-window substring two-pointer-algorithm vowel-consonant Competitive Programming Hash Strings Write From Home sliding-window two-pointer-algorithm Hash Strings 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 Shortest path in a directed graph by Dijkstra’s algorithm 5 Best Books for Competitive Programming Check whether bitwise AND of a number with any subset of an array is zero or not Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) Internal Working of HashMap in Java Count pairs with given sum Hashing | Set 1 (Introduction) Hashing | Set 3 (Open Addressing)
[ { "code": null, "e": 26357, "s": 26329, "text": "\n08 Jun, 2021" }, { "code": null, "e": 26551, "s": 26357, "text": "Given string str consisting of only lowercase English alphabets, the task is to find the substring of the smallest length which contains all the vowels. If no such substring is found, print -1." }, { "code": null, "e": 26562, "s": 26551, "text": "Example: " }, { "code": null, "e": 26695, "s": 26562, "text": "Input: str = “babeivoucu” Output: 7 Explanation: Smallest substring which contains each vowel atleast once is “abeivou” of length 7." }, { "code": null, "e": 26770, "s": 26695, "text": "Input: str = “abcdef” Output: -1 Explanation: No such substring is found. " }, { "code": null, "e": 26794, "s": 26770, "text": "Two Pointer Approach: " }, { "code": null, "e": 26879, "s": 26794, "text": "Store the frequencies of each vowel and the indices at which the vowels are present." }, { "code": null, "e": 26937, "s": 26879, "text": "If all the vowels are not present, straightaway print -1." }, { "code": null, "e": 27013, "s": 26937, "text": "Take two pointers i and j at the first and last indices containing a vowel." }, { "code": null, "e": 27196, "s": 27013, "text": "If the frequencies of vowel at ith and jth index exceed 1, decrease the count of that vowel and shift i and j to the right and left respectively to the next index containing a vowel." }, { "code": null, "e": 27305, "s": 27196, "text": "If the frequencies of vowel at ith or jth index is equal to 1, set flag1 or flag2 respectively and continue." }, { "code": null, "e": 27486, "s": 27305, "text": "Once both flag1 and flag2 are set, the length of the substring cannot be further minimized. The distance between the current indices pointed by the two pointers denotes the result." }, { "code": null, "e": 27547, "s": 27486, "text": "The below code is the implementation of the above approach: " }, { "code": null, "e": 27551, "s": 27547, "text": "C++" }, { "code": null, "e": 27556, "s": 27551, "text": "Java" }, { "code": null, "e": 27564, "s": 27556, "text": "Python3" }, { "code": null, "e": 27567, "s": 27564, "text": "C#" }, { "code": null, "e": 27578, "s": 27567, "text": "Javascript" }, { "code": "// C++ Program to find the// length of the smallest// substring of which// contains all vowels #include <bits/stdc++.h>using namespace std; int findMinLength(string s){ int n = s.size(); // Map to store the // frequency of vowels map<char, int> counts; // Store the indices // which contains // the vowels vector<int> indices; for (int i = 0; i < n; i++) { if (s[i] == 'a' || s[i] == 'e' || s[i] == 'o' || s[i] == 'i' || s[i] == 'u') { counts[s[i]]++; indices.push_back(i); } } // If all vowels are not // present in the string if (counts.size() < 5) return -1; int flag1 = 0, flag2 = 0; int i = 0; int j = indices.size() - 1; while ((j - i) >= 4) { // If the frequency of the // vowel at i-th index // exceeds 1 if (!flag1 && counts[s[indices[i]]] > 1) { // Decrease the frequency // of that vowel counts[s[indices[i]]]--; // Move to the left i++; } // Otherwise set flag1 else flag1 = 1; // If the frequency of the // vowel at j-th index // exceeds 1 if (!flag2 && counts[s[indices[j]]] > 1) { // Decrease the frequency // of that vowel counts[s[indices[j]]]--; // Move to the right j--; } // Otherwise set flag2 else flag2 = 1; // If both flag1 and flag2 // are set, break out of the // loop as the substring // length cannot be minimized if (flag1 && flag2) break; } // Return the length of the substring return (indices[j] - indices[i] + 1);} int main(){ string s = \"aaeebbeaccaaoiuooooooooiuu\"; cout << findMinLength(s); return 0;}", "e": 29478, "s": 27578, "text": null }, { "code": "// Java program to find the length of// the smallest substring of which// contains all vowelsimport java.util.*;class GFG{ public static int findMinLength(String s){ int n = s.length(); // Map to store the // frequency of vowels HashMap<Character, Integer> counts = new HashMap<>(); // Store the indices // which contains // the vowels Vector<Integer> indices = new Vector<Integer>(); for(int i = 0; i < n; i++) { if (s.charAt(i) == 'a' || s.charAt(i) == 'e' || s.charAt(i) == 'o' || s.charAt(i) == 'i' || s.charAt(i) == 'u') { if (counts.containsKey(s.charAt(i))) { counts.replace(s.charAt(i), counts.get(s.charAt(i)) + 1); } else { counts.put(s.charAt(i), 1); } indices.add(i); } } // If all vowels are not // present in the string if (counts.size() < 5) return -1; int flag1 = 0, flag2 = 0; int i = 0; int j = indices.size() - 1; while ((j - i) >= 4) { // If the frequency of the // vowel at i-th index // exceeds 1 if (flag1 == 0 && counts.get(s.charAt( indices.get(i))) > 1) { // Decrease the frequency // of that vowel counts.replace(s.charAt(indices.get(i)), counts.get(s.charAt(indices.get(i))) - 1); // Move to the left i++; } // Otherwise set flag1 else flag1 = 1; // If the frequency of the // vowel at j-th index // exceeds 1 if (flag2 == 0 && counts.get(s.charAt( indices.get(j))) > 1) { // Decrease the frequency // of that vowel counts.replace(s.charAt(indices.get(j)), counts.get(s.charAt(indices.get(j))) - 1); // Move to the right j--; } // Otherwise set flag2 else flag2 = 1; // If both flag1 and flag2 // are set, break out of the // loop as the substring // length cannot be minimized if (flag1 == 1 && flag2 == 1) break; } // Return the length of the substring return (indices.get(j) - indices.get(i) + 1);} // Driver Codepublic static void main(String[] args){ String s = \"aaeebbeaccaaoiuooooooooiuu\"; System.out.print(findMinLength(s));}} // This code is contributed by divyeshrabadiya07", "e": 32131, "s": 29478, "text": null }, { "code": "# Python3 program to find the# length of the smallest# substring of which# contains all vowelsfrom collections import defaultdict def findMinLength(s): n = len(s) # Map to store the # frequency of vowels counts = defaultdict(int) # Store the indices # which contains # the vowels indices = [] for i in range(n): if (s[i] == 'a' or s[i] == 'e' or s[i] == 'o' or s[i] == 'i' or s[i] == 'u'): counts[s[i]] += 1 indices.append(i) # If all vowels are not # present in the string if len(counts) < 5: return -1 flag1 = 0 flag2 = 0 i = 0 j = len(indices) - 1 while (j - i) >= 4: # If the frequency of the # vowel at i-th index # exceeds 1 if (~flag1 and counts[s[indices[i]]] > 1): # Decrease the frequency # of that vowel counts[s[indices[i]]] -= 1 # Move to the left i += 1 # Otherwise set flag1 else: flag1 = 1 # If the frequency of the # vowel at j-th index # exceeds 1 if (~flag2 and counts[s[indices[j]]] > 1): # Decrease the frequency # of that vowel counts[s[indices[j]]] -= 1 # Move to the right j -= 1 # Otherwise set flag2 else: flag2 = 1 # If both flag1 and flag2 # are set, break out of the # loop as the substring # length cannot be minimized if (flag1 and flag2): break # Return the length of the substring return (indices[j] - indices[i] + 1) # Driver Codes = \"aaeebbeaccaaoiuooooooooiuu\"print(findMinLength(s)) # This code is contributed by# divyamohan123", "e": 33936, "s": 32131, "text": null }, { "code": "// C# program to find the length of// the smallest substring of which// contains all vowelsusing System;using System.Collections.Generic;class GFG{ public static int findMinLength(String s){ int n = s.Length; int i = 0; // Map to store the // frequency of vowels Dictionary<char, int> counts = new Dictionary<char, int>(); // Store the indices // which contains // the vowels List<int> indices = new List<int>(); for(i = 0; i < n; i++) { if (s[i] == 'a' || s[i] == 'e' || s[i] == 'o' || s[i] == 'i' || s[i] == 'u') { if (counts.ContainsKey(s[i])) { counts[s[i]] = counts[s[i]] + 1; } else { counts.Add(s[i], 1); } indices.Add(i); } } // If all vowels are not // present in the string if (counts.Count < 5) return -1; int flag1 = 0, flag2 = 0; i = 0; int j = indices.Count - 1; while ((j - i) >= 4) { // If the frequency of the // vowel at i-th index // exceeds 1 if (flag1 == 0 && counts[s[indices[i]]] > 1) { // Decrease the frequency // of that vowel counts[s[indices[i]]]= counts[s[indices[i]]] - 1; // Move to the left i++; } // Otherwise set flag1 else flag1 = 1; // If the frequency of the // vowel at j-th index // exceeds 1 if (flag2 == 0 && counts[s[indices[j]]] > 1) { // Decrease the frequency // of that vowel counts[s[indices[j]]] = counts[s[indices[j]]] - 1; // Move to the right j--; } // Otherwise set flag2 else flag2 = 1; // If both flag1 and flag2 // are set, break out of the // loop as the substring // length cannot be minimized if (flag1 == 1 && flag2 == 1) break; } // Return the length of the substring return (indices[j] - indices[i] + 1);} // Driver Codepublic static void Main(String[] args){ String s = \"aaeebbeaccaaoiuooooooooiuu\"; Console.Write(findMinLength(s));}} // This code is contributed by shikhasingrajput", "e": 36033, "s": 33936, "text": null }, { "code": "<script> // JavaScript Program to find the// length of the smallest// substring of which// contains all vowels function findMinLength(s){ var n = s.length; // Map to store the // frequency of vowels var counts = new Map(); // Store the indices // which contains // the vowels var indices = []; for (var i = 0; i < n; i++) { if (s[i] == 'a' || s[i] == 'e' || s[i] == 'o' || s[i] == 'i' || s[i] == 'u') { if(counts.has(s[i])) counts.set(s[i], counts.get(s[i])+1) else counts.set(s[i], 1) indices.push(i); } } // If all vowels are not // present in the string if (counts.size < 5) return -1; var flag1 = 0, flag2 = 0; var i = 0; var j = indices.length - 1; while ((j - i) >= 4) { // If the frequency of the // vowel at i-th index // exceeds 1 if (!flag1 && counts.get(s[indices[i]]) > 1) { // Decrease the frequency // of that vowel if(counts.has(s[indices[i]])) counts.set(s[indices[i]], counts.get(s[indices[i]])-1) // Move to the left i++; } // Otherwise set flag1 else flag1 = 1; // If the frequency of the // vowel at j-th index // exceeds 1 if (!flag2 && counts.get(s[indices[j]]) > 1) { // Decrease the frequency // of that vowel if(counts.has(s[indices[j]])) counts.set(s[indices[j]], counts.get(s[indices[j]])-1) // Move to the right j--; } // Otherwise set flag2 else flag2 = 1; // If both flag1 and flag2 // are set, break out of the // loop as the substring // length cannot be minimized if (flag1 && flag2) break; } // Return the length of the substring return (indices[j] - indices[i] + 1);} var s = \"aaeebbeaccaaoiuooooooooiuu\";document.write( findMinLength(s)); </script>", "e": 38220, "s": 36033, "text": null }, { "code": null, "e": 38222, "s": 38220, "text": "9" }, { "code": null, "e": 38268, "s": 38224, "text": "Time Complexity: O(N) Auxiliary Space: O(N)" }, { "code": null, "e": 38295, "s": 38268, "text": "Sliding Window Approach: " }, { "code": null, "e": 38357, "s": 38295, "text": "Maintain an array count to store the frequency of each vowel." }, { "code": null, "e": 38437, "s": 38357, "text": "Maintain a start variable to store the starting index of the current substring." }, { "code": null, "e": 38964, "s": 38437, "text": "Iterate over the string and do the following: Increase the frequency of the character if it is a vowel.Move start as right as possible based on the condition that either the character at the start is not a vowel or it is a vowel with a frequency greater than 1 which means that it has appeared previously.Once the start is moved as far as possible, check if all vowels are present in the substring between start and the current index.Whenever the above condition satisfies, update the minimum length of such substring obtained" }, { "code": null, "e": 39022, "s": 38964, "text": "Increase the frequency of the character if it is a vowel." }, { "code": null, "e": 39225, "s": 39022, "text": "Move start as right as possible based on the condition that either the character at the start is not a vowel or it is a vowel with a frequency greater than 1 which means that it has appeared previously." }, { "code": null, "e": 39355, "s": 39225, "text": "Once the start is moved as far as possible, check if all vowels are present in the substring between start and the current index." }, { "code": null, "e": 39448, "s": 39355, "text": "Whenever the above condition satisfies, update the minimum length of such substring obtained" }, { "code": null, "e": 39540, "s": 39448, "text": "Print the minimum length of substring obtained or print -1 if no such substring is obtained" }, { "code": null, "e": 39587, "s": 39540, "text": "The below code implements the above approach: " }, { "code": null, "e": 39591, "s": 39587, "text": "C++" }, { "code": null, "e": 39596, "s": 39591, "text": "Java" }, { "code": null, "e": 39604, "s": 39596, "text": "Python3" }, { "code": null, "e": 39607, "s": 39604, "text": "C#" }, { "code": null, "e": 39618, "s": 39607, "text": "Javascript" }, { "code": "// C++ Program to find the// length of the smallest// substring of which// contains all vowels #include <bits/stdc++.h>using namespace std; // Function to return the// index for respective// vowels to increase their countint get_index(char ch){ if (ch == 'a') return 0; else if (ch == 'e') return 1; else if (ch == 'i') return 2; else if (ch == 'o') return 3; else if (ch == 'u') return 4; // Returns -1 for consonants else return -1;} // Function to find the minimum lengthint findMinLength(string s){ int n = s.size(); int ans = n + 1; // Store the starting index // of the current substring int start = 0; // Store the frequencies of vowels int count[5] = { 0 }; for (int x = 0; x < n; x++) { int idx = get_index(s[x]); // If the current character // is a vowel if (idx != -1) { // Increase its count count[idx]++; } // Move start as much // right as possible int idx_start = get_index(s[start]); while (idx_start == -1 || count[idx_start] > 1) { if (idx_start != -1) { count[idx_start]--; } start++; if (start < n) idx_start = get_index(s[start]); } // Condition for valid substring if (count[0] > 0 && count[1] > 0 && count[2] > 0 && count[3] > 0 && count[4] > 0) { ans = min(ans, x - start + 1); } } if (ans == n + 1) return -1; return ans;} // Driver codeint main(){ string s = \"aaeebbeaccaaoiuooooooooiuu\"; cout << findMinLength(s); return 0;}", "e": 41362, "s": 39618, "text": null }, { "code": "// Java program to find the length// of the smallest subString of// which contains all vowelsimport java.util.*; class GFG{ // Function to return the// index for respective// vowels to increase their countstatic int get_index(char ch){ if (ch == 'a') return 0; else if (ch == 'e') return 1; else if (ch == 'i') return 2; else if (ch == 'o') return 3; else if (ch == 'u') return 4; // Returns -1 for consonants else return -1;} // Function to find the minimum lengthstatic int findMinLength(String s){ int n = s.length(); int ans = n + 1; // Store the starting index // of the current subString int start = 0; // Store the frequencies of vowels int count[] = new int[5]; for(int x = 0; x < n; x++) { int idx = get_index(s.charAt(x)); // If the current character // is a vowel if (idx != -1) { // Increase its count count[idx]++; } // Move start as much // right as possible int idx_start = get_index(s.charAt(start)); while (idx_start == -1 || count[idx_start] > 1) { if (idx_start != -1) { count[idx_start]--; } start++; if (start < n) idx_start = get_index(s.charAt(start)); } // Condition for valid subString if (count[0] > 0 && count[1] > 0 && count[2] > 0 && count[3] > 0 && count[4] > 0) { ans = Math.min(ans, x - start + 1); } } if (ans == n + 1) return -1; return ans;} // Driver codepublic static void main(String[] args){ String s = \"aaeebbeaccaaoiuooooooooiuu\"; System.out.print(findMinLength(s));}} // This code is contributed by 29AjayKumar", "e": 43218, "s": 41362, "text": null }, { "code": "# Python3 Program to find the# length of the smallest# substring of which# contains all vowels # Function to return the# index for respective# vowels to increase their countdef get_index(ch): if (ch == 'a'): return 0 elif (ch == 'e'): return 1 elif (ch == 'i'): return 2 elif (ch == 'o'): return 3 elif (ch == 'u'): return 4 # Returns -1 for consonants else: return -1 # Function to find the minimum lengthdef findMinLength(s): n = len(s) ans = n + 1 # Store the starting index # of the current substring start = 0 # Store the frequencies # of vowels count = [0] * 5 for x in range (n): idx = get_index(s[x]) # If the current character # is a vowel if (idx != -1): # Increase its count count[idx] += 1 # Move start as much # right as possible idx_start = get_index(s[start]) while (idx_start == -1 or count[idx_start] > 1): if (idx_start != -1): count[idx_start] -= 1 start += 1 if (start < n): idx_start = get_index(s[start]) # Condition for valid substring if (count[0] > 0 and count[1] > 0 and count[2] > 0 and count[3] > 0 and count[4] > 0): ans = min(ans, x - start + 1) if (ans == n + 1): return -1 return ans # Driver codeif __name__ == \"__main__\": s = \"aaeebbeaccaaoiuooooooooiuu\" print(findMinLength(s)) # This code is contributed by Chitranayal", "e": 44813, "s": 43218, "text": null }, { "code": "// C# program to find the length// of the smallest subString of// which contains all vowelsusing System;class GFG{ // Function to return the// index for respective// vowels to increase their countstatic int get_index(char ch){ if (ch == 'a') return 0; else if (ch == 'e') return 1; else if (ch == 'i') return 2; else if (ch == 'o') return 3; else if (ch == 'u') return 4; // Returns -1 for consonants else return -1;} // Function to find the minimum lengthstatic int findMinLength(String s){ int n = s.Length; int ans = n + 1; // Store the starting index // of the current subString int start = 0; // Store the frequencies of vowels int []count = new int[5]; for(int x = 0; x < n; x++) { int idx = get_index(s[x]); // If the current character // is a vowel if (idx != -1) { // Increase its count count[idx]++; } // Move start as much // right as possible int idx_start = get_index(s[start]); while (idx_start == -1 || count[idx_start] > 1) { if (idx_start != -1) { count[idx_start]--; } start++; if (start < n) idx_start = get_index(s[start]); } // Condition for valid subString if (count[0] > 0 && count[1] > 0 && count[2] > 0 && count[3] > 0 && count[4] > 0) { ans = Math.Min(ans, x - start + 1); } } if (ans == n + 1) return -1; return ans;} // Driver codepublic static void Main(String[] args){ String s = \"aaeebbeaccaaoiuooooooooiuu\"; Console.Write(findMinLength(s));}} // This code is contributed by sapnasingh4991", "e": 46691, "s": 44813, "text": null }, { "code": "<script>// Javascript program to find the length// of the smallest subString of// which contains all vowels // Function to return the// index for respective// vowels to increase their countfunction get_index(ch){ if (ch == 'a') return 0; else if (ch == 'e') return 1; else if (ch == 'i') return 2; else if (ch == 'o') return 3; else if (ch == 'u') return 4; // Returns -1 for consonants else return -1;} // Function to find the minimum lengthfunction findMinLength(s){ let n = s.length; let ans = n + 1; // Store the starting index // of the current subString let start = 0; // Store the frequencies of vowels let count = new Array(5); for(let i = 0; i < 5; i++) { count[i] = 0; } for(let x = 0; x < n; x++) { let idx = get_index(s[x]); // If the current character // is a vowel if (idx != -1) { // Increase its count count[idx]++; } // Move start as much // right as possible let idx_start = get_index(s[start]); while (idx_start == -1 || count[idx_start] > 1) { if (idx_start != -1) { count[idx_start]--; } start++; if (start < n) idx_start = get_index(s[start]); } // Condition for valid subString if (count[0] > 0 && count[1] > 0 && count[2] > 0 && count[3] > 0 && count[4] > 0) { ans = Math.min(ans, x - start + 1); } } if (ans == n + 1) return -1; return ans;} // Driver codelet s = \"aaeebbeaccaaoiuooooooooiuu\";document.write(findMinLength(s)); // This code is contributed by avanitrachhadiya2155</script>", "e": 48526, "s": 46691, "text": null }, { "code": null, "e": 48528, "s": 48526, "text": "9" }, { "code": null, "e": 48553, "s": 48530, "text": "Time Complexity: O(N) " }, { "code": null, "e": 48567, "s": 48553, "text": "divyamohan123" }, { "code": null, "e": 48579, "s": 48567, "text": "29AjayKumar" }, { "code": null, "e": 48594, "s": 48579, "text": "sapnasingh4991" }, { "code": null, "e": 48605, "s": 48594, "text": "nidhi_biet" }, { "code": null, "e": 48611, "s": 48605, "text": "ukasp" }, { "code": null, "e": 48629, "s": 48611, "text": "divyeshrabadiya07" }, { "code": null, "e": 48646, "s": 48629, "text": "shikhasingrajput" }, { "code": null, "e": 48656, "s": 48646, "text": "rutvik_56" }, { "code": null, "e": 48677, "s": 48656, "text": "avanitrachhadiya2155" }, { "code": null, "e": 48692, "s": 48677, "text": "sliding-window" }, { "code": null, "e": 48702, "s": 48692, "text": "substring" }, { "code": null, "e": 48724, "s": 48702, "text": "two-pointer-algorithm" }, { "code": null, "e": 48740, "s": 48724, "text": "vowel-consonant" }, { "code": null, "e": 48764, "s": 48740, "text": "Competitive Programming" }, { "code": null, "e": 48769, "s": 48764, "text": "Hash" }, { "code": null, "e": 48777, "s": 48769, "text": "Strings" }, { "code": null, "e": 48793, "s": 48777, "text": "Write From Home" }, { "code": null, "e": 48808, "s": 48793, "text": "sliding-window" }, { "code": null, "e": 48830, "s": 48808, "text": "two-pointer-algorithm" }, { "code": null, "e": 48835, "s": 48830, "text": "Hash" }, { "code": null, "e": 48843, "s": 48835, "text": "Strings" }, { "code": null, "e": 48941, "s": 48843, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 48974, "s": 48941, "text": "Multistage Graph (Shortest Path)" }, { "code": null, "e": 49020, "s": 48974, "text": "Breadth First Traversal ( BFS ) on a 2D array" }, { "code": null, "e": 49078, "s": 49020, "text": "Shortest path in a directed graph by Dijkstra’s algorithm" }, { "code": null, "e": 49119, "s": 49078, "text": "5 Best Books for Competitive Programming" }, { "code": null, "e": 49200, "s": 49119, "text": "Check whether bitwise AND of a number with any subset of an array is zero or not" }, { "code": null, "e": 49285, "s": 49200, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 49321, "s": 49285, "text": "Internal Working of HashMap in Java" }, { "code": null, "e": 49348, "s": 49321, "text": "Count pairs with given sum" }, { "code": null, "e": 49379, "s": 49348, "text": "Hashing | Set 1 (Introduction)" } ]
Introducing LOB Locators - GeeksforGeeks
28 Jun, 2019 Large object (LOB) locators let you reference a LOB in Transact-SQL statements rather than referencing the LOB itself as the size of a text can be unitext, or image LOB can be many megabytes. Using a LOB locator in Transact-SQL statements helps to reduce network traffic between the client and SAP ASE and also reduces the amount of memory which would be needed by the client to process the LOB. SAP ASE or Sybase ASE help client applications to send and receive locators as host variables and parameter markers. A LOB locator will remain valid for the duration of the transaction in which it was created. SAP ASE performs validation which invalidates the locator whenever the transaction commits or is rolled back. Datatypes used in LOB Locators:LOB locators use three different datatypes: text_locator: for text LOBs. unitext_locator: for unitext LOBs. image_locator: for image LOBs. Declaring a local variable for the LOB Locator: One can declare local variables for the locator datatypes.For example: declare @v1 text_locator Because LOBs and locators are stored only in memory, you cannot use locator datatypes as column datatypes for user tables or views, or in constraints or defaults. Creating a LOB Locator: One can create a LOB locator explicitly or implicitly. In general, when LOB locator is used in a Transact-SQL statement, locators are implicitly converted to the LOB they reference. That is, whenever a LOB locator is passed to a Transact-SQL function, the function operates on the LOB that is referenced by the locator. Any changes you make to the LOB referenced by the locator are not reflected in the source LOB in the database—unless you explicitly save them. Similarly, if any changes you make to the LOB stored in the database will be not reflected in the LOB referenced by the locator. A LOB instance has both a locator and a value. The LOB locator is referred to where the LOB value is physically stored. The LOB value is termed as the data stored in the LOB. Whenever you use a LOB in an operation such as passing a LOB as a parameter, you are actually passing a LOB locator. For most of the part, you can work with a LOB instance in your application without being concerned with the semantics of LOB locators. There is no need to de-reference LOB locators because it is required with pointers in some programming languages. There are still some issues regarding the semantics of LOB locators and how LOB values are stored that you should be aware of. Temporary LOBs You can also create temporary LOBs, that are like local variables, to assist the use of database LOBs. Temporary LOBs are not associated with any table, they are only accessible by their creator, have locators (which is how they are accessed), and are deleted when a session ends. There is no support for temporary BFILES. Temporary LOBs are only permitted to be input variables (IN values) in the WHERE clauses of INSERT, UPDATE, or DELETE statements. They are also permitted as values inserted by an INSERT statement, or a value in the SET clause of an UPDATE statement. Temporary LOBs have no transactional support from the database server, which means that you cannot do COMMITS or ROLLBACKs on them. Temporary LOB locators can span transactions. They also are deleted when the server abnormally terminates, and when an error is returned from a database SQL operation. LOB Locators in Your ApplicationTo use a LOB locator in Pro*C/C++ application, we have to include the oci.h header file and have to declare a pointer to the type OCIBlobLocator for BLOBs, OCIClobLocator for CLOBs and NCLOBs, or OCIBFileLocator for BFILEs. For an NCLOB, you can either Use the clause ‘CHARACTER SET IS NCHAR_CS’ in Pro*C/C++ declaration, Or, you must have already used an NLS_CHAR precompiler option on the command line or in a configuration file to set the NLS_NCHAR environment variable. Oracle-LOB DBMS DBMS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. SQL Interview Questions Introduction of B-Tree Difference between Clustered and Non-clustered index Data Preprocessing in Data Mining Introduction of ER Model Introduction of DBMS (Database Management System) | Set 1 Difference between DDL and DML in DBMS SQL | Views SQL | GROUP BY Difference between Primary Key and Foreign Key
[ { "code": null, "e": 25067, "s": 25039, "text": "\n28 Jun, 2019" }, { "code": null, "e": 25580, "s": 25067, "text": "Large object (LOB) locators let you reference a LOB in Transact-SQL statements rather than referencing the LOB itself as the size of a text can be unitext, or image LOB can be many megabytes. Using a LOB locator in Transact-SQL statements helps to reduce network traffic between the client and SAP ASE and also reduces the amount of memory which would be needed by the client to process the LOB. SAP ASE or Sybase ASE help client applications to send and receive locators as host variables and parameter markers." }, { "code": null, "e": 25783, "s": 25580, "text": "A LOB locator will remain valid for the duration of the transaction in which it was created. SAP ASE performs validation which invalidates the locator whenever the transaction commits or is rolled back." }, { "code": null, "e": 25858, "s": 25783, "text": "Datatypes used in LOB Locators:LOB locators use three different datatypes:" }, { "code": null, "e": 25887, "s": 25858, "text": "text_locator: for text LOBs." }, { "code": null, "e": 25922, "s": 25887, "text": "unitext_locator: for unitext LOBs." }, { "code": null, "e": 25953, "s": 25922, "text": "image_locator: for image LOBs." }, { "code": null, "e": 26072, "s": 25953, "text": "Declaring a local variable for the LOB Locator: One can declare local variables for the locator datatypes.For example:" }, { "code": null, "e": 26098, "s": 26072, "text": "declare @v1 text_locator\n" }, { "code": null, "e": 26261, "s": 26098, "text": "Because LOBs and locators are stored only in memory, you cannot use locator datatypes as column datatypes for user tables or views, or in constraints or defaults." }, { "code": null, "e": 26340, "s": 26261, "text": "Creating a LOB Locator: One can create a LOB locator explicitly or implicitly." }, { "code": null, "e": 26605, "s": 26340, "text": "In general, when LOB locator is used in a Transact-SQL statement, locators are implicitly converted to the LOB they reference. That is, whenever a LOB locator is passed to a Transact-SQL function, the function operates on the LOB that is referenced by the locator." }, { "code": null, "e": 26877, "s": 26605, "text": "Any changes you make to the LOB referenced by the locator are not reflected in the source LOB in the database—unless you explicitly save them. Similarly, if any changes you make to the LOB stored in the database will be not reflected in the LOB referenced by the locator." }, { "code": null, "e": 27052, "s": 26877, "text": "A LOB instance has both a locator and a value. The LOB locator is referred to where the LOB value is physically stored. The LOB value is termed as the data stored in the LOB." }, { "code": null, "e": 27418, "s": 27052, "text": "Whenever you use a LOB in an operation such as passing a LOB as a parameter, you are actually passing a LOB locator. For most of the part, you can work with a LOB instance in your application without being concerned with the semantics of LOB locators. There is no need to de-reference LOB locators because it is required with pointers in some programming languages." }, { "code": null, "e": 27545, "s": 27418, "text": "There are still some issues regarding the semantics of LOB locators and how LOB values are stored that you should be aware of." }, { "code": null, "e": 27560, "s": 27545, "text": "Temporary LOBs" }, { "code": null, "e": 27841, "s": 27560, "text": "You can also create temporary LOBs, that are like local variables, to assist the use of database LOBs. Temporary LOBs are not associated with any table, they are only accessible by their creator, have locators (which is how they are accessed), and are deleted when a session ends." }, { "code": null, "e": 28265, "s": 27841, "text": "There is no support for temporary BFILES. Temporary LOBs are only permitted to be input variables (IN values) in the WHERE clauses of INSERT, UPDATE, or DELETE statements. They are also permitted as values inserted by an INSERT statement, or a value in the SET clause of an UPDATE statement. Temporary LOBs have no transactional support from the database server, which means that you cannot do COMMITS or ROLLBACKs on them." }, { "code": null, "e": 28433, "s": 28265, "text": "Temporary LOB locators can span transactions. They also are deleted when the server abnormally terminates, and when an error is returned from a database SQL operation." }, { "code": null, "e": 28689, "s": 28433, "text": "LOB Locators in Your ApplicationTo use a LOB locator in Pro*C/C++ application, we have to include the oci.h header file and have to declare a pointer to the type OCIBlobLocator for BLOBs, OCIClobLocator for CLOBs and NCLOBs, or OCIBFileLocator for BFILEs." }, { "code": null, "e": 28718, "s": 28689, "text": "For an NCLOB, you can either" }, { "code": null, "e": 28787, "s": 28718, "text": "Use the clause ‘CHARACTER SET IS NCHAR_CS’ in Pro*C/C++ declaration," }, { "code": null, "e": 28939, "s": 28787, "text": "Or, you must have already used an NLS_CHAR precompiler option on the command line or in a configuration file to set the NLS_NCHAR environment variable." }, { "code": null, "e": 28950, "s": 28939, "text": "Oracle-LOB" }, { "code": null, "e": 28955, "s": 28950, "text": "DBMS" }, { "code": null, "e": 28960, "s": 28955, "text": "DBMS" }, { "code": null, "e": 29058, "s": 28960, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29082, "s": 29058, "text": "SQL Interview Questions" }, { "code": null, "e": 29105, "s": 29082, "text": "Introduction of B-Tree" }, { "code": null, "e": 29158, "s": 29105, "text": "Difference between Clustered and Non-clustered index" }, { "code": null, "e": 29192, "s": 29158, "text": "Data Preprocessing in Data Mining" }, { "code": null, "e": 29217, "s": 29192, "text": "Introduction of ER Model" }, { "code": null, "e": 29275, "s": 29217, "text": "Introduction of DBMS (Database Management System) | Set 1" }, { "code": null, "e": 29314, "s": 29275, "text": "Difference between DDL and DML in DBMS" }, { "code": null, "e": 29326, "s": 29314, "text": "SQL | Views" }, { "code": null, "e": 29341, "s": 29326, "text": "SQL | GROUP BY" } ]
Analysis of Algorithms | Set 3 (Asymptotic Notations) - GeeksforGeeks
12 Nov, 2021 We have discussed Asymptotic Analysis, and Worst, Average, and Best Cases of Algorithms. The main idea of asymptotic analysis is to have a measure of the efficiency of algorithms that don’t depend on machine-specific constants and don’t require algorithms to be implemented and time taken by programs to be compared. Asymptotic notations are mathematical tools to represent the time complexity of algorithms for asymptotic analysis. The following 3 asymptotic notations are mostly used to represent the time complexity of algorithms. 1) Θ Notation: The theta notation bounds a function from above and below, so it defines exact asymptotic behavior. A simple way to get the Theta notation of an expression is to drop low-order terms and ignore leading constants. For example, consider the following expression. 3n3 + 6n2 + 6000 = Θ(n3) Dropping lower order terms is always fine because there will always be a number(n) after which Θ(n3) has higher values than Θ(n2) irrespective of the constants involved. For a given function g(n), we denote Θ(g(n)) is following set of functions. Θ(g(n)) = {f(n): there exist positive constants c1, c2 and n0 such that 0 <= c1*g(n) <= f(n) <= c2*g(n) for all n >= n0} The above definition means, if f(n) is theta of g(n), then the value f(n) is always between c1*g(n) and c2*g(n) for large values of n (n >= n0). The definition of theta also requires that f(n) must be non-negative for values of n greater than n0. 2) Big O Notation: The Big O notation defines an upper bound of an algorithm, it bounds a function only from above. For example, consider the case of Insertion Sort. It takes linear time in the best case and quadratic time in the worst case. We can safely say that the time complexity of Insertion sort is O(n^2). Note that O(n^2) also covers linear time. If we use Θ notation to represent time complexity of Insertion sort, we have to use two statements for best and worst cases: 1. The worst-case time complexity of Insertion Sort is Θ(n^2). 2. The best case time complexity of Insertion Sort is Θ(n). The Big O notation is useful when we only have an upper bound on the time complexity of an algorithm. Many times we easily find an upper bound by simply looking at the algorithm. O(g(n)) = { f(n): there exist positive constants c and n0 such that 0 <= f(n) <= c*g(n) for all n >= n0} 3) Ω Notation: Just as Big O notation provides an asymptotic upper bound on a function, Ω notation provides an asymptotic lower bound. Ω Notation can be useful when we have a lower bound on the time complexity of an algorithm. As discussed in the previous post, the best case performance of an algorithm is generally not useful, the Omega notation is the least used notation among all three. For a given function g(n), we denote by Ω(g(n)) the set of functions. Ω (g(n)) = {f(n): there exist positive constants c and n0 such that 0 <= c*g(n) <= f(n) for all n >= n0}. Let us consider the same Insertion sort example here. The time complexity of Insertion Sort can be written as Ω(n), but it is not very useful information about insertion sort, as we are generally interested in worst-case and sometimes in the average case. Properties of Asymptotic Notations : As we have gone through the definition of these three notations let’s now discuss some important properties of those notations. 1. General Properties : If f(n) is O(g(n)) then a*f(n) is also O(g(n)) ; where a is a constant. Example: f(n) = 2n2+5 is O(n2) then 7*f(n) = 7(2n2+5) = 14n2+35 is also O(n2) . Similarly, this property satisfies both Θ and Ω notation. We can say If f(n) is Θ(g(n)) then a*f(n) is also Θ(g(n)) ; where a is a constant. If f(n) is Ω (g(n)) then a*f(n) is also Ω (g(n)) ; where a is a constant. 2. Transitive Properties : If f(n) is O(g(n)) and g(n) is O(h(n)) then f(n) = O(h(n)) . Example: if f(n) = n, g(n) = n2 and h(n)=n3 n is O(n2) and n2 is O(n3) then n is O(n3) Similarly, this property satisfies both Θ and Ω notation. We can say If f(n) is Θ(g(n)) and g(n) is Θ(h(n)) then f(n) = Θ(h(n)) . If f(n) is Ω (g(n)) and g(n) is Ω (h(n)) then f(n) = Ω (h(n)) 3. Reflexive Properties : Reflexive properties are always easy to understand after transitive. If f(n) is given then f(n) is O(f(n)). Since MAXIMUM VALUE OF f(n) will be f(n) ITSELF ! Hence x = f(n) and y = O(f(n) tie themselves in reflexive relation always. Example: f(n) = n2 ; O(n2) i.e O(f(n)) Similarly, this property satisfies both Θ and Ω notation. We can say that: If f(n) is given then f(n) is Θ(f(n)). If f(n) is given then f(n) is Ω (f(n)). 4. Symmetric Properties : If f(n) is Θ(g(n)) then g(n) is Θ(f(n)) . Example: f(n) = n2 and g(n) = n2 then f(n) = Θ(n2) and g(n) = Θ(n2) This property only satisfies for Θ notation. 5. Transpose Symmetric Properties : If f(n) is O(g(n)) then g(n) is Ω (f(n)). Example: f(n) = n , g(n) = n2 then n is O(n2) and n2 is Ω (n) This property only satisfies O and Ω notations. 6. Some More Properties : 1.) If f(n) = O(g(n)) and f(n) = Ω(g(n)) then f(n) = Θ(g(n)) 2.) If f(n) = O(g(n)) and d(n)=O(e(n)) then f(n) + d(n) = O( max( g(n), e(n) )) Example: f(n) = n i.e O(n) d(n) = n2 i.e O(n2) then f(n) + d(n) = n + n2 i.e O(n2) 3.) If f(n)=O(g(n)) and d(n)=O(e(n)) then f(n) * d(n) = O( g(n) * e(n) ) Example: f(n) = n i.e O(n) d(n) = n2 i.e O(n2) then f(n) * d(n) = n * n2 = n3 i.e O(n3) _______________________________________________________________________________ Exercise: Which of the following statements is/are valid? 1. Time Complexity of QuickSort is Θ(n^2) 2. Time Complexity of QuickSort is O(n^2) 3. For any two functions f(n) and g(n), we have f(n) = Θ(g(n)) if and only if f(n) = O(g(n)) and f(n) = Ω(g(n)). 4. Time complexity of all computer algorithms can be written as Ω(1) Important Links : There are two more notations called little o and little omega. Little o provides a strict upper bound (equality condition is removed from Big O) and little omega provides strict lower bound (equality condition removed from big omega) Analysis of Algorithms | Set 4 (Analysis of Loops) Recent Articles on analysis of algorithm. References:Lec 1 | MIT (Introduction to Algorithms) This article is contributed by Abhay Rathi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. OmkarJai AmiyaRanjanRout kaustubh765 skmodi20bce2835 23603vaibhav2021 Analysis Articles Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Understanding Time Complexity with Simple Examples Time Complexity and Space Complexity Practice Questions on Time Complexity Analysis 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 How to write a Pseudo Code? SQL Interview Questions
[ { "code": null, "e": 35839, "s": 35811, "text": "\n12 Nov, 2021" }, { "code": null, "e": 36374, "s": 35839, "text": "We have discussed Asymptotic Analysis, and Worst, Average, and Best Cases of Algorithms. The main idea of asymptotic analysis is to have a measure of the efficiency of algorithms that don’t depend on machine-specific constants and don’t require algorithms to be implemented and time taken by programs to be compared. Asymptotic notations are mathematical tools to represent the time complexity of algorithms for asymptotic analysis. The following 3 asymptotic notations are mostly used to represent the time complexity of algorithms. " }, { "code": null, "e": 36925, "s": 36376, "text": "1) Θ Notation: The theta notation bounds a function from above and below, so it defines exact asymptotic behavior. A simple way to get the Theta notation of an expression is to drop low-order terms and ignore leading constants. For example, consider the following expression. 3n3 + 6n2 + 6000 = Θ(n3) Dropping lower order terms is always fine because there will always be a number(n) after which Θ(n3) has higher values than Θ(n2) irrespective of the constants involved. For a given function g(n), we denote Θ(g(n)) is following set of functions. " }, { "code": null, "e": 37064, "s": 36925, "text": "Θ(g(n)) = {f(n): there exist positive constants c1, c2 and n0 such \n that 0 <= c1*g(n) <= f(n) <= c2*g(n) for all n >= n0}" }, { "code": null, "e": 37312, "s": 37064, "text": "The above definition means, if f(n) is theta of g(n), then the value f(n) is always between c1*g(n) and c2*g(n) for large values of n (n >= n0). The definition of theta also requires that f(n) must be non-negative for values of n greater than n0. " }, { "code": null, "e": 37919, "s": 37314, "text": "2) Big O Notation: The Big O notation defines an upper bound of an algorithm, it bounds a function only from above. For example, consider the case of Insertion Sort. It takes linear time in the best case and quadratic time in the worst case. We can safely say that the time complexity of Insertion sort is O(n^2). Note that O(n^2) also covers linear time. If we use Θ notation to represent time complexity of Insertion sort, we have to use two statements for best and worst cases: 1. The worst-case time complexity of Insertion Sort is Θ(n^2). 2. The best case time complexity of Insertion Sort is Θ(n). " }, { "code": null, "e": 38100, "s": 37919, "text": "The Big O notation is useful when we only have an upper bound on the time complexity of an algorithm. Many times we easily find an upper bound by simply looking at the algorithm. " }, { "code": null, "e": 38243, "s": 38100, "text": "O(g(n)) = { f(n): there exist positive constants c and \n n0 such that 0 <= f(n) <= c*g(n) for \n all n >= n0}" }, { "code": null, "e": 38638, "s": 38245, "text": "3) Ω Notation: Just as Big O notation provides an asymptotic upper bound on a function, Ω notation provides an asymptotic lower bound. Ω Notation can be useful when we have a lower bound on the time complexity of an algorithm. As discussed in the previous post, the best case performance of an algorithm is generally not useful, the Omega notation is the least used notation among all three. " }, { "code": null, "e": 38710, "s": 38638, "text": "For a given function g(n), we denote by Ω(g(n)) the set of functions. " }, { "code": null, "e": 38852, "s": 38710, "text": "Ω (g(n)) = {f(n): there exist positive constants c and\n n0 such that 0 <= c*g(n) <= f(n) for\n all n >= n0}." }, { "code": null, "e": 39109, "s": 38852, "text": "Let us consider the same Insertion sort example here. The time complexity of Insertion Sort can be written as Ω(n), but it is not very useful information about insertion sort, as we are generally interested in worst-case and sometimes in the average case. " }, { "code": null, "e": 39275, "s": 39109, "text": "Properties of Asymptotic Notations : As we have gone through the definition of these three notations let’s now discuss some important properties of those notations. " }, { "code": null, "e": 39300, "s": 39275, "text": "1. General Properties : " }, { "code": null, "e": 39378, "s": 39300, "text": " If f(n) is O(g(n)) then a*f(n) is also O(g(n)) ; where a is a constant. " }, { "code": null, "e": 39468, "s": 39378, "text": " Example: f(n) = 2n2+5 is O(n2) then 7*f(n) = 7(2n2+5) = 14n2+35 is also O(n2) ." }, { "code": null, "e": 39533, "s": 39468, "text": " Similarly, this property satisfies both Θ and Ω notation. " }, { "code": null, "e": 39705, "s": 39533, "text": " We can say If f(n) is Θ(g(n)) then a*f(n) is also Θ(g(n)) ; where a is a constant. If f(n) is Ω (g(n)) then a*f(n) is also Ω (g(n)) ; where a is a constant." }, { "code": null, "e": 39733, "s": 39705, "text": "2. Transitive Properties : " }, { "code": null, "e": 39798, "s": 39733, "text": " If f(n) is O(g(n)) and g(n) is O(h(n)) then f(n) = O(h(n)) ." }, { "code": null, "e": 39895, "s": 39798, "text": " Example: if f(n) = n, g(n) = n2 and h(n)=n3 n is O(n2) and n2 is O(n3) then n is O(n3)" }, { "code": null, "e": 39956, "s": 39895, "text": " Similarly, this property satisfies both Θ and Ω notation." }, { "code": null, "e": 40097, "s": 39956, "text": " We can say If f(n) is Θ(g(n)) and g(n) is Θ(h(n)) then f(n) = Θ(h(n)) . If f(n) is Ω (g(n)) and g(n) is Ω (h(n)) then f(n) = Ω (h(n))" }, { "code": null, "e": 40124, "s": 40097, "text": "3. Reflexive Properties : " }, { "code": null, "e": 40199, "s": 40124, "text": " Reflexive properties are always easy to understand after transitive." }, { "code": null, "e": 40294, "s": 40199, "text": " If f(n) is given then f(n) is O(f(n)). Since MAXIMUM VALUE OF f(n) will be f(n) ITSELF !" }, { "code": null, "e": 40375, "s": 40294, "text": " Hence x = f(n) and y = O(f(n) tie themselves in reflexive relation always." }, { "code": null, "e": 40420, "s": 40375, "text": " Example: f(n) = n2 ; O(n2) i.e O(f(n))" }, { "code": null, "e": 40484, "s": 40420, "text": " Similarly, this property satisfies both Θ and Ω notation." }, { "code": null, "e": 40507, "s": 40484, "text": " We can say that:" }, { "code": null, "e": 40552, "s": 40507, "text": " If f(n) is given then f(n) is Θ(f(n))." }, { "code": null, "e": 40598, "s": 40552, "text": " If f(n) is given then f(n) is Ω (f(n))." }, { "code": null, "e": 40626, "s": 40598, "text": "4. Symmetric Properties : " }, { "code": null, "e": 40676, "s": 40626, "text": " If f(n) is Θ(g(n)) then g(n) is Θ(f(n)) . " }, { "code": null, "e": 40758, "s": 40676, "text": " Example: f(n) = n2 and g(n) = n2 then f(n) = Θ(n2) and g(n) = Θ(n2) " }, { "code": null, "e": 40809, "s": 40758, "text": " This property only satisfies for Θ notation." }, { "code": null, "e": 40847, "s": 40809, "text": "5. Transpose Symmetric Properties : " }, { "code": null, "e": 40897, "s": 40847, "text": " If f(n) is O(g(n)) then g(n) is Ω (f(n)). " }, { "code": null, "e": 40972, "s": 40897, "text": " Example: f(n) = n , g(n) = n2 then n is O(n2) and n2 is Ω (n) " }, { "code": null, "e": 41020, "s": 40972, "text": "This property only satisfies O and Ω notations." }, { "code": null, "e": 41047, "s": 41020, "text": "6. Some More Properties : " }, { "code": null, "e": 41113, "s": 41047, "text": " 1.) If f(n) = O(g(n)) and f(n) = Ω(g(n)) then f(n) = Θ(g(n))" }, { "code": null, "e": 41351, "s": 41113, "text": " 2.) If f(n) = O(g(n)) and d(n)=O(e(n)) then f(n) + d(n) = O( max( g(n), e(n) )) Example: f(n) = n i.e O(n) d(n) = n2 i.e O(n2) then f(n) + d(n) = n + n2 i.e O(n2)" }, { "code": null, "e": 41573, "s": 41351, "text": " 3.) If f(n)=O(g(n)) and d(n)=O(e(n)) then f(n) * d(n) = O( g(n) * e(n) ) Example: f(n) = n i.e O(n) d(n) = n2 i.e O(n2) then f(n) * d(n) = n * n2 = n3 i.e O(n3)" }, { "code": null, "e": 41653, "s": 41573, "text": "_______________________________________________________________________________" }, { "code": null, "e": 41978, "s": 41653, "text": "Exercise: Which of the following statements is/are valid? 1. Time Complexity of QuickSort is Θ(n^2) 2. Time Complexity of QuickSort is O(n^2) 3. For any two functions f(n) and g(n), we have f(n) = Θ(g(n)) if and only if f(n) = O(g(n)) and f(n) = Ω(g(n)). 4. Time complexity of all computer algorithms can be written as Ω(1) " }, { "code": null, "e": 41997, "s": 41978, "text": " Important Links :" }, { "code": null, "e": 42231, "s": 41997, "text": "There are two more notations called little o and little omega. Little o provides a strict upper bound (equality condition is removed from Big O) and little omega provides strict lower bound (equality condition removed from big omega)" }, { "code": null, "e": 42282, "s": 42231, "text": "Analysis of Algorithms | Set 4 (Analysis of Loops)" }, { "code": null, "e": 42324, "s": 42282, "text": "Recent Articles on analysis of algorithm." }, { "code": null, "e": 42376, "s": 42324, "text": "References:Lec 1 | MIT (Introduction to Algorithms)" }, { "code": null, "e": 42545, "s": 42376, "text": "This article is contributed by Abhay Rathi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 42554, "s": 42545, "text": "OmkarJai" }, { "code": null, "e": 42570, "s": 42554, "text": "AmiyaRanjanRout" }, { "code": null, "e": 42582, "s": 42570, "text": "kaustubh765" }, { "code": null, "e": 42598, "s": 42582, "text": "skmodi20bce2835" }, { "code": null, "e": 42615, "s": 42598, "text": "23603vaibhav2021" }, { "code": null, "e": 42624, "s": 42615, "text": "Analysis" }, { "code": null, "e": 42633, "s": 42624, "text": "Articles" }, { "code": null, "e": 42731, "s": 42633, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 42782, "s": 42731, "text": "Understanding Time Complexity with Simple Examples" }, { "code": null, "e": 42819, "s": 42782, "text": "Time Complexity and Space Complexity" }, { "code": null, "e": 42866, "s": 42819, "text": "Practice Questions on Time Complexity Analysis" }, { "code": null, "e": 42949, "s": 42866, "text": "Complexity of different operations in Binary tree, Binary Search Tree and AVL tree" }, { "code": null, "e": 42984, "s": 42949, "text": "Time Complexity of building a heap" }, { "code": null, "e": 43034, "s": 42984, "text": "Tree Traversals (Inorder, Preorder and Postorder)" }, { "code": null, "e": 43081, "s": 43034, "text": "SQL | Join (Inner, Left, Right and Full Joins)" }, { "code": null, "e": 43117, "s": 43081, "text": "find command in Linux with examples" }, { "code": null, "e": 43145, "s": 43117, "text": "How to write a Pseudo Code?" } ]
HTML | <iframe> marginwidth Attribute - GeeksforGeeks
07 Nov, 2019 The HTML <iframe> margin width Attribute is used to specifies the left and right margin of the content in an Iframe Element. Syntax: <iframe marginwidth="pixels"> Attribute Values: pixels: It contains the value i.e pixel which specifies the right and left a margin of the content in an Iframe Element. Note: This attribute is not supported in HTML 5, as a replacement you can use CSS.Below example illustrate the <iframe> marginwidth Attribute:Example: <!DOCTYPE html><html><head> <title> HTML <iframe> marginwidth Attribute </title></head><body> <center> <h1 style="color:green;"> GeeksforGeeks </h1> <h2> HTML Iframe marginwidth Attribute </h2> <p>Content goes here</p> <iframe src="https://ide.geeksforgeeks.org/tryit.php" height="200" width="400" marginwidth="50"> </iframe> </center> </body> </html> Output: Supported Browsers: The browsers supported by HTML <iframe> marginwidth Attribute are listed below: Google Chrome Internet Explorer Firefox Opera Safari Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. HTML-Attributes HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to update Node.js and NPM to next version ? REST API (Introduction) How to Insert Form Data into Database using PHP ? CSS to put icon inside an input element in a form Types of CSS (Cascading Style Sheet) Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 26155, "s": 26127, "text": "\n07 Nov, 2019" }, { "code": null, "e": 26280, "s": 26155, "text": "The HTML <iframe> margin width Attribute is used to specifies the left and right margin of the content in an Iframe Element." }, { "code": null, "e": 26288, "s": 26280, "text": "Syntax:" }, { "code": null, "e": 26318, "s": 26288, "text": "<iframe marginwidth=\"pixels\">" }, { "code": null, "e": 26336, "s": 26318, "text": "Attribute Values:" }, { "code": null, "e": 26457, "s": 26336, "text": "pixels: It contains the value i.e pixel which specifies the right and left a margin of the content in an Iframe Element." }, { "code": null, "e": 26608, "s": 26457, "text": "Note: This attribute is not supported in HTML 5, as a replacement you can use CSS.Below example illustrate the <iframe> marginwidth Attribute:Example:" }, { "code": "<!DOCTYPE html><html><head> <title> HTML <iframe> marginwidth Attribute </title></head><body> <center> <h1 style=\"color:green;\"> GeeksforGeeks </h1> <h2> HTML Iframe marginwidth Attribute </h2> <p>Content goes here</p> <iframe src=\"https://ide.geeksforgeeks.org/tryit.php\" height=\"200\" width=\"400\" marginwidth=\"50\"> </iframe> </center> </body> </html>", "e": 27087, "s": 26608, "text": null }, { "code": null, "e": 27095, "s": 27087, "text": "Output:" }, { "code": null, "e": 27195, "s": 27095, "text": "Supported Browsers: The browsers supported by HTML <iframe> marginwidth Attribute are listed below:" }, { "code": null, "e": 27209, "s": 27195, "text": "Google Chrome" }, { "code": null, "e": 27227, "s": 27209, "text": "Internet Explorer" }, { "code": null, "e": 27235, "s": 27227, "text": "Firefox" }, { "code": null, "e": 27241, "s": 27235, "text": "Opera" }, { "code": null, "e": 27248, "s": 27241, "text": "Safari" }, { "code": null, "e": 27385, "s": 27248, "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": 27401, "s": 27385, "text": "HTML-Attributes" }, { "code": null, "e": 27406, "s": 27401, "text": "HTML" }, { "code": null, "e": 27423, "s": 27406, "text": "Web Technologies" }, { "code": null, "e": 27428, "s": 27423, "text": "HTML" }, { "code": null, "e": 27526, "s": 27428, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27574, "s": 27526, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 27598, "s": 27574, "text": "REST API (Introduction)" }, { "code": null, "e": 27648, "s": 27598, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 27698, "s": 27648, "text": "CSS to put icon inside an input element in a form" }, { "code": null, "e": 27735, "s": 27698, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 27775, "s": 27735, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 27808, "s": 27775, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 27853, "s": 27808, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 27896, "s": 27853, "text": "How to fetch data from an API in ReactJS ?" } ]
Default value of Vector in C++ STL - GeeksforGeeks
23 Apr, 2020 Vectors are same as dynamic arrays with the ability to resize itself automatically when an element is inserted or deleted, with their storage being handled automatically by the container. Vector elements are placed in contiguous storage so that they can be accessed and traversed using iterators. By default, the size of the vector automatically changes when appending elements. To initialize the map with a random default value below is the approach:Approach: Declare a vector.Set the size of the vector to the user defined size N Declare a vector. Set the size of the vector to the user defined size N Default value of the Vector: The default value of a vector is 0. Syntax: // For declaring vector v1(size); // For Vector with default value 0 vector v1(5); Below is the implementation of the above approach: // C++ program to create an empty// vector with default value #include <bits/stdc++.h>using namespace std; int main(){ int n = 3; // Create a vector of size n with // all values as 0. vector<int> vect(n); for (int x : vect) cout << x << " "; return 0;} 0 0 0 Specifying a default value for the Vector: We can also specify a random default value for the vector. Inorder to do so, below is the approach: Syntax: // For declaring vector v(size, default_value); // For Vector with a specific default value // here 5 is the size of the vector // and 10 is the default value vector v1(5, 10); Below is the implementation of the above approach: // C++ program to create an empty vector// and with a specific default value #include <bits/stdc++.h>using namespace std; int main(){ int n = 3; int default_value = 10; // Create a vector of size n with // all values as 10. vector<int> vect(n, default_value); for (int x : vect) cout << x << " "; return 0;} 10 10 10 cpp-vector C++ C++ Programs Write From Home 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) Header files in C/C++ and its uses Program to print ASCII Value of a character C++ Program for QuickSort How to return multiple values from a function in C or C++? Sorting a Map by value in C++ STL
[ { "code": null, "e": 25368, "s": 25340, "text": "\n23 Apr, 2020" }, { "code": null, "e": 25747, "s": 25368, "text": "Vectors are same as dynamic arrays with the ability to resize itself automatically when an element is inserted or deleted, with their storage being handled automatically by the container. Vector elements are placed in contiguous storage so that they can be accessed and traversed using iterators. By default, the size of the vector automatically changes when appending elements." }, { "code": null, "e": 25829, "s": 25747, "text": "To initialize the map with a random default value below is the approach:Approach:" }, { "code": null, "e": 25900, "s": 25829, "text": "Declare a vector.Set the size of the vector to the user defined size N" }, { "code": null, "e": 25918, "s": 25900, "text": "Declare a vector." }, { "code": null, "e": 25972, "s": 25918, "text": "Set the size of the vector to the user defined size N" }, { "code": null, "e": 26001, "s": 25972, "text": "Default value of the Vector:" }, { "code": null, "e": 26037, "s": 26001, "text": "The default value of a vector is 0." }, { "code": null, "e": 26045, "s": 26037, "text": "Syntax:" }, { "code": null, "e": 26132, "s": 26045, "text": "// For declaring \nvector v1(size); \n\n// For Vector with default value 0\nvector v1(5);\n" }, { "code": null, "e": 26183, "s": 26132, "text": "Below is the implementation of the above approach:" }, { "code": "// C++ program to create an empty// vector with default value #include <bits/stdc++.h>using namespace std; int main(){ int n = 3; // Create a vector of size n with // all values as 0. vector<int> vect(n); for (int x : vect) cout << x << \" \"; return 0;}", "e": 26469, "s": 26183, "text": null }, { "code": null, "e": 26476, "s": 26469, "text": "0 0 0\n" }, { "code": null, "e": 26519, "s": 26476, "text": "Specifying a default value for the Vector:" }, { "code": null, "e": 26619, "s": 26519, "text": "We can also specify a random default value for the vector. Inorder to do so, below is the approach:" }, { "code": null, "e": 26627, "s": 26619, "text": "Syntax:" }, { "code": null, "e": 26808, "s": 26627, "text": "// For declaring \nvector v(size, default_value);\n\n// For Vector with a specific default value\n// here 5 is the size of the vector\n// and 10 is the default value\nvector v1(5, 10);\n" }, { "code": null, "e": 26859, "s": 26808, "text": "Below is the implementation of the above approach:" }, { "code": "// C++ program to create an empty vector// and with a specific default value #include <bits/stdc++.h>using namespace std; int main(){ int n = 3; int default_value = 10; // Create a vector of size n with // all values as 10. vector<int> vect(n, default_value); for (int x : vect) cout << x << \" \"; return 0;}", "e": 27203, "s": 26859, "text": null }, { "code": null, "e": 27213, "s": 27203, "text": "10 10 10\n" }, { "code": null, "e": 27224, "s": 27213, "text": "cpp-vector" }, { "code": null, "e": 27228, "s": 27224, "text": "C++" }, { "code": null, "e": 27241, "s": 27228, "text": "C++ Programs" }, { "code": null, "e": 27257, "s": 27241, "text": "Write From Home" }, { "code": null, "e": 27261, "s": 27257, "text": "CPP" }, { "code": null, "e": 27359, "s": 27261, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27387, "s": 27359, "text": "Operator Overloading in C++" }, { "code": null, "e": 27407, "s": 27387, "text": "Polymorphism in C++" }, { "code": null, "e": 27431, "s": 27407, "text": "Sorting a vector in C++" }, { "code": null, "e": 27464, "s": 27431, "text": "Friend class and function in C++" }, { "code": null, "e": 27508, "s": 27464, "text": "Pair in C++ Standard Template Library (STL)" }, { "code": null, "e": 27543, "s": 27508, "text": "Header files in C/C++ and its uses" }, { "code": null, "e": 27587, "s": 27543, "text": "Program to print ASCII Value of a character" }, { "code": null, "e": 27613, "s": 27587, "text": "C++ Program for QuickSort" }, { "code": null, "e": 27672, "s": 27613, "text": "How to return multiple values from a function in C or C++?" } ]
How to Compress and Extract Files Using the tar Command on Linux - GeeksforGeeks
29 Jun, 2021 An archive is a special file that contains any number of files inside. It can be restored via special programs, for example, tar.inside. .tar – archive files are usually not compressed. .tar.gz – archive file compressed with gzip tool .tar.bz2 – archive file compressed with bzip2 tool Syntax: tar options [archive_name.tar] files_to_archive The tar command does not create a compressed archive, instead, it uses external utilities like gzip and bzip2. Command functionality: –diff Chapters descriptions off, selected captions settings, opens captions settings dialog captions off, selected English This is a modal window. Beginning of dialog window. Escape will cancel and close the window. End of dialog window. –delete Showing the difference between archives Delete file from the archive Command parameters: –verbose –total Show process information Show final result 1) Compress one file using the tar command: tar -czvf one-file-compressed.tar.gz hello_world 2) Compress directory using the tar command: tar -czvf dir-compressed.tar.gz test_directory/ 3) Show the archive content: tar -tf archive.tar.gz 4) Add content to the existing archive: tar -rvf existing-archive-name.tar file-directory-to-compress/ 5) Update content in an archive: 6) Compress with bzip2: tar -cjvf one-file-compressed.tar.bz2 hello_world 7) Extract files from a .tar archive: tar -xf archive.tar.gz The same with .tar.gz and .tar.bz2 Linux-file-commands 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": 25725, "s": 25694, "text": " \n29 Jun, 2021\n" }, { "code": null, "e": 25862, "s": 25725, "text": "An archive is a special file that contains any number of files inside. It can be restored via special programs, for example, tar.inside." }, { "code": null, "e": 25911, "s": 25862, "text": ".tar – archive files are usually not compressed." }, { "code": null, "e": 25960, "s": 25911, "text": ".tar.gz – archive file compressed with gzip tool" }, { "code": null, "e": 26011, "s": 25960, "text": ".tar.bz2 – archive file compressed with bzip2 tool" }, { "code": null, "e": 26020, "s": 26011, "text": "Syntax: " }, { "code": null, "e": 26068, "s": 26020, "text": "tar options [archive_name.tar] files_to_archive" }, { "code": null, "e": 26179, "s": 26068, "text": "The tar command does not create a compressed archive, instead, it uses external utilities like gzip and bzip2." }, { "code": null, "e": 26202, "s": 26179, "text": "Command functionality:" }, { "code": null, "e": 26208, "s": 26202, "text": "–diff" }, { "code": null, "e": 26217, "s": 26208, "text": "Chapters" }, { "code": null, "e": 26244, "s": 26217, "text": "descriptions off, selected" }, { "code": null, "e": 26294, "s": 26244, "text": "captions settings, opens captions settings dialog" }, { "code": null, "e": 26317, "s": 26294, "text": "captions off, selected" }, { "code": null, "e": 26325, "s": 26317, "text": "English" }, { "code": null, "e": 26349, "s": 26325, "text": "This is a modal window." }, { "code": null, "e": 26418, "s": 26349, "text": "Beginning of dialog window. Escape will cancel and close the window." }, { "code": null, "e": 26440, "s": 26418, "text": "End of dialog window." }, { "code": null, "e": 26448, "s": 26440, "text": "–delete" }, { "code": null, "e": 26488, "s": 26448, "text": "Showing the difference between archives" }, { "code": null, "e": 26517, "s": 26488, "text": "Delete file from the archive" }, { "code": null, "e": 26537, "s": 26517, "text": "Command parameters:" }, { "code": null, "e": 26546, "s": 26537, "text": "–verbose" }, { "code": null, "e": 26553, "s": 26546, "text": "–total" }, { "code": null, "e": 26578, "s": 26553, "text": "Show process information" }, { "code": null, "e": 26597, "s": 26578, "text": "Show final result " }, { "code": null, "e": 26641, "s": 26597, "text": "1) Compress one file using the tar command:" }, { "code": null, "e": 26690, "s": 26641, "text": "tar -czvf one-file-compressed.tar.gz hello_world" }, { "code": null, "e": 26735, "s": 26690, "text": "2) Compress directory using the tar command:" }, { "code": null, "e": 26783, "s": 26735, "text": "tar -czvf dir-compressed.tar.gz test_directory/" }, { "code": null, "e": 26812, "s": 26783, "text": "3) Show the archive content:" }, { "code": null, "e": 26835, "s": 26812, "text": "tar -tf archive.tar.gz" }, { "code": null, "e": 26875, "s": 26835, "text": "4) Add content to the existing archive:" }, { "code": null, "e": 26938, "s": 26875, "text": "tar -rvf existing-archive-name.tar file-directory-to-compress/" }, { "code": null, "e": 26972, "s": 26938, "text": "5) Update content in an archive: " }, { "code": null, "e": 26996, "s": 26972, "text": "6) Compress with bzip2:" }, { "code": null, "e": 27046, "s": 26996, "text": "tar -cjvf one-file-compressed.tar.bz2 hello_world" }, { "code": null, "e": 27084, "s": 27046, "text": "7) Extract files from a .tar archive:" }, { "code": null, "e": 27107, "s": 27084, "text": "tar -xf archive.tar.gz" }, { "code": null, "e": 27142, "s": 27107, "text": "The same with .tar.gz and .tar.bz2" }, { "code": null, "e": 27164, "s": 27142, "text": "\nLinux-file-commands\n" }, { "code": null, "e": 27173, "s": 27164, "text": "\nPicked\n" }, { "code": null, "e": 27186, "s": 27173, "text": "\nLinux-Unix\n" }, { "code": null, "e": 27391, "s": 27186, "text": "Writing code in comment? \n Please use ide.geeksforgeeks.org, \n generate link and share the link here.\n " }, { "code": null, "e": 27426, "s": 27391, "text": "scp command in Linux with Examples" }, { "code": null, "e": 27460, "s": 27426, "text": "mv command in Linux with examples" }, { "code": null, "e": 27486, "s": 27460, "text": "Docker - COPY Instruction" }, { "code": null, "e": 27515, "s": 27486, "text": "SED command in Linux | Set 2" }, { "code": null, "e": 27552, "s": 27515, "text": "chown command in Linux with Examples" }, { "code": null, "e": 27589, "s": 27552, "text": "nohup Command in Linux with Examples" }, { "code": null, "e": 27631, "s": 27589, "text": "Named Pipe or FIFO with example C program" }, { "code": null, "e": 27657, "s": 27631, "text": "Thread functions in C/C++" }, { "code": null, "e": 27693, "s": 27657, "text": "uniq Command in LINUX with examples" } ]
Applying Multinomial Naive Bayes to NLP Problems - GeeksforGeeks
05 Aug, 2021 Naive Bayes Classifier Algorithm is a family of probabilistic algorithms based on applying Bayes’ theorem with the “naive” assumption of conditional independence between every pair of a feature. Bayes theorem calculates probability P(c|x) where c is the class of the possible outcomes and x is the given instance which has to be classified, representing some certain features.P(c|x) = P(x|c) * P(c) / P(x)Naive Bayes are mostly used in natural language processing (NLP) problems. Naive Bayes predict the tag of a text. They calculate the probability of each tag for a given text and then output the tag with the highest one. How Naive Bayes Algorithm Works ?Let’s consider an example, classify the review whether it is positive or negative.Training Dataset: We classify whether the text “overall liked the movie” has a positive review or a negative review. We have to calculate, P(positive | overall liked the movie) — the probability that the tag of a sentence is positive given that the sentence is “overall liked the movie”. P(negative | overall liked the movie) — the probability that the tag of a sentence is negative given that the sentence is “overall liked the movie”.Before that, first, we apply Removing Stopwords and Stemming in the text.Removing Stopwords: These are common words that don’t really add anything to the classification, such as an able, either, else, ever and so on.Stemming: Stemming to take out the root of the word.Now After applying these two techniques, our text becomes Feature Engineering: The important part is to find the features from the data to make machine learning algorithms works. In this case, we have text. We need to convert this text into numbers that we can do calculations on. We use word frequencies. That is treating every document as a set of the words it contains. Our features will be the counts of each of these words.In our case, we have P(positive | overall liked the movie), by using this theorem: P(positive | overall liked the movie) = P(overall liked the movie | positive) * P(positive) / P(overall liked the movie) Since for our classifier we have to find out which tag has a bigger probability, we can discard the divisor which is the same for both tags,P(overall liked the movie | positive)* P(positive) with P(overall liked the movie | negative) * P(negative)There’s a problem though: “overall liked the movie” doesn’t appear in our training dataset, so the probability is zero. Here, we assume the ‘naive’ condition that every word in a sentence is independent of the other ones. This means that now we look at individual words.We can write this as: P(overall liked the movie) = P(overall) * P(liked) * P(the) * P(movie) The next step is just applying the Bayes theorem:- P(overall liked the movie| positive) = P(overall | positive) * P(liked | positive) * P(the | positive) * P(movie | positive) And now, these individual words actually show up several times in our training data, and we can calculate them!Calculating probabilities: First, we calculate the a priori probability of each tag: for a given sentence in our training data, the probability that it is positive P(positive) is 3/5. Then, P(negative) is 2/5.Then, calculating P(overall | positive) means counting how many times the word “overall” appears in positive texts (1) divided by the total number of words in positive (11). Therefore, P(overall | positive) = 1/17, P(liked/positive) = 1/17, P(the/positive) = 2/17, P(movie/positive) = 3/17. If probability comes out to be zero then By using Laplace smoothing: we add 1 to every count so it’s never zero. To balance this, we add the number of possible words to the divisor, so the division will never be greater than 1. In our case, the total possible words count are 21.Applying smoothing, The results are: Now we just multiply all the probabilities, and see who is bigger: P(overall | positive) * P(liked | positive) * P(the | positive) * P(movie | positive) * P(positive ) = 1.38 * 10^{-5} = 0.0000138P(overall | negative) * P(liked | negative) * P(the | negative) * P(movie | negative) * P(negative) = 0.13 * 10^{-5} = 0.0000013 Our classifier gives “overall liked the movie” the positive tag.Below is the implementation : Python3 # cleaning textsimport pandas as pdimport reimport nltkfrom nltk.corpus import stopwordsfrom nltk.stem.porter import PorterStemmerfrom sklearn.feature_extraction.text import CountVectorizer dataset = [["I liked the movie", "positive"], ["It’s a good movie. Nice story", "positive"], ["Hero’s acting is bad but heroine looks good.\ Overall nice movie", "positive"], ["Nice songs. But sadly boring ending.", "negative"], ["sad movie, boring movie", "negative"]] dataset = pd.DataFrame(dataset)dataset.columns = ["Text", "Reviews"] nltk.download('stopwords') corpus = [] for i in range(0, 5): text = re.sub('[^a-zA-Z]', '', dataset['Text'][i]) text = text.lower() text = text.split() ps = PorterStemmer() text = ''.join(text) corpus.append(text) # creating bag of words modelcv = CountVectorizer(max_features = 1500) X = cv.fit_transform(corpus).toarray()y = dataset.iloc[:, 1].values Python3 # splitting the data set into training set and test setfrom sklearn.cross_validation import train_test_split X_train, X_test, y_train, y_test = train_test_split( X, y, test_size = 0.25, random_state = 0) Python3 # fitting naive bayes to the training setfrom sklearn.naive_bayes import GaussianNBfrom sklearn.metrics import confusion_matrix classifier = GaussianNB();classifier.fit(X_train, y_train) # predicting test set resultsy_pred = classifier.predict(X_test) # making the confusion matrixcm = confusion_matrix(y_test, y_pred)cm surinderdawra388 Advanced Computer Subject Machine Learning Python Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Reinforcement learning Decision Tree Introduction with example Copying Files to and from Docker Containers System Design Tutorial Python | Decision tree implementation Reinforcement learning Agents in Artificial Intelligence Activation functions in Neural Networks Decision Tree Introduction with example Introduction to Recurrent Neural Network
[ { "code": null, "e": 25888, "s": 25860, "text": "\n05 Aug, 2021" }, { "code": null, "e": 26647, "s": 25888, "text": "Naive Bayes Classifier Algorithm is a family of probabilistic algorithms based on applying Bayes’ theorem with the “naive” assumption of conditional independence between every pair of a feature. Bayes theorem calculates probability P(c|x) where c is the class of the possible outcomes and x is the given instance which has to be classified, representing some certain features.P(c|x) = P(x|c) * P(c) / P(x)Naive Bayes are mostly used in natural language processing (NLP) problems. Naive Bayes predict the tag of a text. They calculate the probability of each tag for a given text and then output the tag with the highest one. How Naive Bayes Algorithm Works ?Let’s consider an example, classify the review whether it is positive or negative.Training Dataset: " }, { "code": null, "e": 27392, "s": 26647, "text": "We classify whether the text “overall liked the movie” has a positive review or a negative review. We have to calculate, P(positive | overall liked the movie) — the probability that the tag of a sentence is positive given that the sentence is “overall liked the movie”. P(negative | overall liked the movie) — the probability that the tag of a sentence is negative given that the sentence is “overall liked the movie”.Before that, first, we apply Removing Stopwords and Stemming in the text.Removing Stopwords: These are common words that don’t really add anything to the classification, such as an able, either, else, ever and so on.Stemming: Stemming to take out the root of the word.Now After applying these two techniques, our text becomes " }, { "code": null, "e": 27846, "s": 27392, "text": "Feature Engineering: The important part is to find the features from the data to make machine learning algorithms works. In this case, we have text. We need to convert this text into numbers that we can do calculations on. We use word frequencies. That is treating every document as a set of the words it contains. Our features will be the counts of each of these words.In our case, we have P(positive | overall liked the movie), by using this theorem: " }, { "code": null, "e": 27967, "s": 27846, "text": "P(positive | overall liked the movie) = P(overall liked the movie | positive) * P(positive) / P(overall liked the movie)" }, { "code": null, "e": 28509, "s": 27967, "text": " Since for our classifier we have to find out which tag has a bigger probability, we can discard the divisor which is the same for both tags,P(overall liked the movie | positive)* P(positive) with P(overall liked the movie | negative) * P(negative)There’s a problem though: “overall liked the movie” doesn’t appear in our training dataset, so the probability is zero. Here, we assume the ‘naive’ condition that every word in a sentence is independent of the other ones. This means that now we look at individual words.We can write this as: " }, { "code": null, "e": 28580, "s": 28509, "text": "P(overall liked the movie) = P(overall) * P(liked) * P(the) * P(movie)" }, { "code": null, "e": 28633, "s": 28580, "text": "The next step is just applying the Bayes theorem:- " }, { "code": null, "e": 28758, "s": 28633, "text": "P(overall liked the movie| positive) = P(overall | positive) * P(liked | positive) * P(the | positive) * P(movie | positive)" }, { "code": null, "e": 29686, "s": 28758, "text": "And now, these individual words actually show up several times in our training data, and we can calculate them!Calculating probabilities: First, we calculate the a priori probability of each tag: for a given sentence in our training data, the probability that it is positive P(positive) is 3/5. Then, P(negative) is 2/5.Then, calculating P(overall | positive) means counting how many times the word “overall” appears in positive texts (1) divided by the total number of words in positive (11). Therefore, P(overall | positive) = 1/17, P(liked/positive) = 1/17, P(the/positive) = 2/17, P(movie/positive) = 3/17. If probability comes out to be zero then By using Laplace smoothing: we add 1 to every count so it’s never zero. To balance this, we add the number of possible words to the divisor, so the division will never be greater than 1. In our case, the total possible words count are 21.Applying smoothing, The results are: " }, { "code": null, "e": 29754, "s": 29686, "text": "Now we just multiply all the probabilities, and see who is bigger: " }, { "code": null, "e": 30012, "s": 29754, "text": "P(overall | positive) * P(liked | positive) * P(the | positive) * P(movie | positive) * P(positive ) = 1.38 * 10^{-5} = 0.0000138P(overall | negative) * P(liked | negative) * P(the | negative) * P(movie | negative) * P(negative) = 0.13 * 10^{-5} = 0.0000013" }, { "code": null, "e": 30109, "s": 30012, "text": " Our classifier gives “overall liked the movie” the positive tag.Below is the implementation : " }, { "code": null, "e": 30117, "s": 30109, "text": "Python3" }, { "code": "# cleaning textsimport pandas as pdimport reimport nltkfrom nltk.corpus import stopwordsfrom nltk.stem.porter import PorterStemmerfrom sklearn.feature_extraction.text import CountVectorizer dataset = [[\"I liked the movie\", \"positive\"], [\"It’s a good movie. Nice story\", \"positive\"], [\"Hero’s acting is bad but heroine looks good.\\ Overall nice movie\", \"positive\"], [\"Nice songs. But sadly boring ending.\", \"negative\"], [\"sad movie, boring movie\", \"negative\"]] dataset = pd.DataFrame(dataset)dataset.columns = [\"Text\", \"Reviews\"] nltk.download('stopwords') corpus = [] for i in range(0, 5): text = re.sub('[^a-zA-Z]', '', dataset['Text'][i]) text = text.lower() text = text.split() ps = PorterStemmer() text = ''.join(text) corpus.append(text) # creating bag of words modelcv = CountVectorizer(max_features = 1500) X = cv.fit_transform(corpus).toarray()y = dataset.iloc[:, 1].values", "e": 31082, "s": 30117, "text": null }, { "code": null, "e": 31090, "s": 31082, "text": "Python3" }, { "code": "# splitting the data set into training set and test setfrom sklearn.cross_validation import train_test_split X_train, X_test, y_train, y_test = train_test_split( X, y, test_size = 0.25, random_state = 0)", "e": 31304, "s": 31090, "text": null }, { "code": null, "e": 31312, "s": 31304, "text": "Python3" }, { "code": "# fitting naive bayes to the training setfrom sklearn.naive_bayes import GaussianNBfrom sklearn.metrics import confusion_matrix classifier = GaussianNB();classifier.fit(X_train, y_train) # predicting test set resultsy_pred = classifier.predict(X_test) # making the confusion matrixcm = confusion_matrix(y_test, y_pred)cm", "e": 31633, "s": 31312, "text": null }, { "code": null, "e": 31650, "s": 31633, "text": "surinderdawra388" }, { "code": null, "e": 31676, "s": 31650, "text": "Advanced Computer Subject" }, { "code": null, "e": 31693, "s": 31676, "text": "Machine Learning" }, { "code": null, "e": 31700, "s": 31693, "text": "Python" }, { "code": null, "e": 31717, "s": 31700, "text": "Machine Learning" }, { "code": null, "e": 31815, "s": 31717, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31838, "s": 31815, "text": "Reinforcement learning" }, { "code": null, "e": 31878, "s": 31838, "text": "Decision Tree Introduction with example" }, { "code": null, "e": 31922, "s": 31878, "text": "Copying Files to and from Docker Containers" }, { "code": null, "e": 31945, "s": 31922, "text": "System Design Tutorial" }, { "code": null, "e": 31983, "s": 31945, "text": "Python | Decision tree implementation" }, { "code": null, "e": 32006, "s": 31983, "text": "Reinforcement learning" }, { "code": null, "e": 32040, "s": 32006, "text": "Agents in Artificial Intelligence" }, { "code": null, "e": 32080, "s": 32040, "text": "Activation functions in Neural Networks" }, { "code": null, "e": 32120, "s": 32080, "text": "Decision Tree Introduction with example" } ]
C# | Count the number of key/value pairs in the Hashtable - GeeksforGeeks
01 Feb, 2019 The Hashtable class represents a collection of key-and-value pairs that are organized based on the hash code of the key. The key is used to access the items in the collection. Hashtable.Count Property is used to get the total number of the key/value pairs contained in the Hashtable. Syntax: myTable.Count Here, myTable is the name of the Hashtable. Below given are some examples to understand the implementation in a better way: Example 1: // C# code to get the number of key-and-value// pairs contained in the Hashtable.using System;using System.Collections; class GFG { // Driver code public static void Main() { // Creating a Hashtable Hashtable myTable = new Hashtable(); // Adding elements in Hashtable myTable.Add("2", "Even & Prime"); myTable.Add("3", "Odd & Prime"); myTable.Add("4", "Even & non-prime"); myTable.Add("9", "Odd & non-prime"); // To get the number of key-and-value // pairs contained in the Hashtable. Console.WriteLine(myTable.Count); }} 4 Example 2: // C# code to get the number of key-and-value// pairs contained in the Hashtable.using System;using System.Collections; class GFG { // Driver code public static void Main() { // Creating an empty Hashtable Hashtable myTable = new Hashtable(); // To get the number of key-and-value // pairs contained in the Hashtable. Console.WriteLine(myTable.Count); }} 0 Reference: https://docs.microsoft.com/en-us/dotnet/api/system.collections.hashtable.count?view=netframework-4.7.2 CSharp-Collections-Hashtable CSharp-Collections-Namespace C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C# | Delegates C# | Abstract Classes Difference between Ref and Out keywords in C# C# | Class and Object C# | Constructors Extension Method in C# Introduction to .NET Framework C# | String.IndexOf( ) Method | Set - 1 C# | Replace() Method C# | Arrays
[ { "code": null, "e": 25915, "s": 25887, "text": "\n01 Feb, 2019" }, { "code": null, "e": 26199, "s": 25915, "text": "The Hashtable class represents a collection of key-and-value pairs that are organized based on the hash code of the key. The key is used to access the items in the collection. Hashtable.Count Property is used to get the total number of the key/value pairs contained in the Hashtable." }, { "code": null, "e": 26207, "s": 26199, "text": "Syntax:" }, { "code": null, "e": 26222, "s": 26207, "text": "myTable.Count\n" }, { "code": null, "e": 26266, "s": 26222, "text": "Here, myTable is the name of the Hashtable." }, { "code": null, "e": 26346, "s": 26266, "text": "Below given are some examples to understand the implementation in a better way:" }, { "code": null, "e": 26357, "s": 26346, "text": "Example 1:" }, { "code": "// C# code to get the number of key-and-value// pairs contained in the Hashtable.using System;using System.Collections; class GFG { // Driver code public static void Main() { // Creating a Hashtable Hashtable myTable = new Hashtable(); // Adding elements in Hashtable myTable.Add(\"2\", \"Even & Prime\"); myTable.Add(\"3\", \"Odd & Prime\"); myTable.Add(\"4\", \"Even & non-prime\"); myTable.Add(\"9\", \"Odd & non-prime\"); // To get the number of key-and-value // pairs contained in the Hashtable. Console.WriteLine(myTable.Count); }}", "e": 26970, "s": 26357, "text": null }, { "code": null, "e": 26973, "s": 26970, "text": "4\n" }, { "code": null, "e": 26984, "s": 26973, "text": "Example 2:" }, { "code": "// C# code to get the number of key-and-value// pairs contained in the Hashtable.using System;using System.Collections; class GFG { // Driver code public static void Main() { // Creating an empty Hashtable Hashtable myTable = new Hashtable(); // To get the number of key-and-value // pairs contained in the Hashtable. Console.WriteLine(myTable.Count); }}", "e": 27393, "s": 26984, "text": null }, { "code": null, "e": 27396, "s": 27393, "text": "0\n" }, { "code": null, "e": 27407, "s": 27396, "text": "Reference:" }, { "code": null, "e": 27510, "s": 27407, "text": "https://docs.microsoft.com/en-us/dotnet/api/system.collections.hashtable.count?view=netframework-4.7.2" }, { "code": null, "e": 27539, "s": 27510, "text": "CSharp-Collections-Hashtable" }, { "code": null, "e": 27568, "s": 27539, "text": "CSharp-Collections-Namespace" }, { "code": null, "e": 27571, "s": 27568, "text": "C#" }, { "code": null, "e": 27669, "s": 27571, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27684, "s": 27669, "text": "C# | Delegates" }, { "code": null, "e": 27706, "s": 27684, "text": "C# | Abstract Classes" }, { "code": null, "e": 27752, "s": 27706, "text": "Difference between Ref and Out keywords in C#" }, { "code": null, "e": 27774, "s": 27752, "text": "C# | Class and Object" }, { "code": null, "e": 27792, "s": 27774, "text": "C# | Constructors" }, { "code": null, "e": 27815, "s": 27792, "text": "Extension Method in C#" }, { "code": null, "e": 27846, "s": 27815, "text": "Introduction to .NET Framework" }, { "code": null, "e": 27886, "s": 27846, "text": "C# | String.IndexOf( ) Method | Set - 1" }, { "code": null, "e": 27908, "s": 27886, "text": "C# | Replace() Method" } ]
Python | Pandas Series.nbytes - GeeksforGeeks
28 Jan, 2019 Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index. Pandas Series.nbytes attribute is return the number of bytes required to store the underlying data in the given Series object. Syntax:Series.nbytes Parameter : None Returns : number of bytes Example #1: Use Series.nbytes attribute is used to find the number of bytes required to store the underlying data of the given Series object. # importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(['New York', 'Chicago', 'Toronto', 'Lisbon', 'Rio']) # Creating the row axis labelssr.index = ['City 1', 'City 2', 'City 3', 'City 4', 'City 5'] # Print the seriesprint(sr) Output : Now we will use Series.nbytes attribute to find the number of bytes required to store the underlying data of the given Series object. # return the number of bytessr.nbytes Output : As we can see in the output, the Series.nbytes attribute has returned 40 indicating that the memory needed to store the given series object is 40 bytes. Example #2 : Use Series.nbytes attribute is used to find the number of bytes required to store the underlying data of the given Series object. # importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(['1/1/2018', '2/1/2018', '3/1/2018', '4/1/2018']) # Creating the row axis labelssr.index = ['Day 1', 'Day 2', 'Day 3', 'Day 4'] # Print the seriesprint(sr) Output : Now we will use Series.nbytes attribute to find the number of bytes required to store the underlying data of the given Series object. # return the number of bytessr.nbytes Output :As we can see in the output, the Series.nbytes attribute has returned 32 indicating that the memory needed to store the given series object is 32 bytes. Python pandas-series Python pandas-series-methods Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? 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": "\n28 Jan, 2019" }, { "code": null, "e": 25751, "s": 25537, "text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier." }, { "code": null, "e": 26008, "s": 25751, "text": "Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index." }, { "code": null, "e": 26135, "s": 26008, "text": "Pandas Series.nbytes attribute is return the number of bytes required to store the underlying data in the given Series object." }, { "code": null, "e": 26156, "s": 26135, "text": "Syntax:Series.nbytes" }, { "code": null, "e": 26173, "s": 26156, "text": "Parameter : None" }, { "code": null, "e": 26199, "s": 26173, "text": "Returns : number of bytes" }, { "code": null, "e": 26341, "s": 26199, "text": "Example #1: Use Series.nbytes attribute is used to find the number of bytes required to store the underlying data of the given Series object." }, { "code": "# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(['New York', 'Chicago', 'Toronto', 'Lisbon', 'Rio']) # Creating the row axis labelssr.index = ['City 1', 'City 2', 'City 3', 'City 4', 'City 5'] # Print the seriesprint(sr)", "e": 26598, "s": 26341, "text": null }, { "code": null, "e": 26607, "s": 26598, "text": "Output :" }, { "code": null, "e": 26741, "s": 26607, "text": "Now we will use Series.nbytes attribute to find the number of bytes required to store the underlying data of the given Series object." }, { "code": "# return the number of bytessr.nbytes", "e": 26779, "s": 26741, "text": null }, { "code": null, "e": 26788, "s": 26779, "text": "Output :" }, { "code": null, "e": 27084, "s": 26788, "text": "As we can see in the output, the Series.nbytes attribute has returned 40 indicating that the memory needed to store the given series object is 40 bytes. Example #2 : Use Series.nbytes attribute is used to find the number of bytes required to store the underlying data of the given Series object." }, { "code": "# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(['1/1/2018', '2/1/2018', '3/1/2018', '4/1/2018']) # Creating the row axis labelssr.index = ['Day 1', 'Day 2', 'Day 3', 'Day 4'] # Print the seriesprint(sr)", "e": 27323, "s": 27084, "text": null }, { "code": null, "e": 27332, "s": 27323, "text": "Output :" }, { "code": null, "e": 27466, "s": 27332, "text": "Now we will use Series.nbytes attribute to find the number of bytes required to store the underlying data of the given Series object." }, { "code": "# return the number of bytessr.nbytes", "e": 27504, "s": 27466, "text": null }, { "code": null, "e": 27665, "s": 27504, "text": "Output :As we can see in the output, the Series.nbytes attribute has returned 32 indicating that the memory needed to store the given series object is 32 bytes." }, { "code": null, "e": 27686, "s": 27665, "text": "Python pandas-series" }, { "code": null, "e": 27715, "s": 27686, "text": "Python pandas-series-methods" }, { "code": null, "e": 27729, "s": 27715, "text": "Python-pandas" }, { "code": null, "e": 27736, "s": 27729, "text": "Python" }, { "code": null, "e": 27834, "s": 27736, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27866, "s": 27834, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27908, "s": 27866, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27950, "s": 27908, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 28006, "s": 27950, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28033, "s": 28006, "text": "Python Classes and Objects" }, { "code": null, "e": 28072, "s": 28033, "text": "Python | Get unique values from a list" }, { "code": null, "e": 28103, "s": 28072, "text": "Python | os.path.join() method" }, { "code": null, "e": 28125, "s": 28103, "text": "Defaultdict in Python" }, { "code": null, "e": 28154, "s": 28125, "text": "Create a directory in Python" } ]
File Handling in C#
A file is a collection of data stored in a disk with a specific name and a directory path. When a file is opened for reading or writing, it becomes a stream. In C#, you need to create a FileStream object to create a new file or open an existing file. The syntax for creating a FileStream object is as follows − FileStream <object_name> = new FileStream( <file_name>, <FileMode Enumerator>, <FileAccess Enumerator>, <FileShare Enumerator>); Here, the file operations are also included as shown below − The FileMode enumerator defines various methods for opening files. The members of the FileMode enumerator are − Append − It opens an existing file and puts cursor at the end of file, or creates the file, if the file does not exist. Append − It opens an existing file and puts cursor at the end of file, or creates the file, if the file does not exist. Create − It creates a new file. Create − It creates a new file. CreateNew − It specifies to the operating system, that it should create a new file. CreateNew − It specifies to the operating system, that it should create a new file. Open − It opens an existing file. Open − It opens an existing file. OpenOrCreate − It specifies to the operating system that it should open a file if it exists, otherwise it should create a new file. OpenOrCreate − It specifies to the operating system that it should open a file if it exists, otherwise it should create a new file. Truncate − It opens an existing file and truncates its size to zero bytes. Truncate − It opens an existing file and truncates its size to zero bytes. FileAccess − The FileAccess enumerators have members: Read, ReadWrite and Write. FileShare − The FileShare enumerators have the following members − Inheritable − It allows a file handle to pass inheritance to the child processes Inheritable − It allows a file handle to pass inheritance to the child processes None − It declines sharing of the current file None − It declines sharing of the current file Read − It allows opening the file for readin. Read − It allows opening the file for readin. ReadWrite − It allows opening the file for reading and writing ReadWrite − It allows opening the file for reading and writing Write− It allows opening the file for writing Write− It allows opening the file for writing Let us see an example to get the directories. //creating a DirectoryInfo object DirectoryInfo mydir = new DirectoryInfo(@"d:\Demo"); // getting the files in the directory, their names and size FileInfo [] f = mydir.GetFiles(); foreach (FileInfo file in f) { Console.WriteLine("File Name: {0} Size: {1}", file.Name, file.Length); }
[ { "code": null, "e": 1220, "s": 1062, "text": "A file is a collection of data stored in a disk with a specific name and a directory path. When a file is opened for reading or writing, it becomes a stream." }, { "code": null, "e": 1373, "s": 1220, "text": "In C#, you need to create a FileStream object to create a new file or open an existing file. The syntax for creating a FileStream object is as follows −" }, { "code": null, "e": 1502, "s": 1373, "text": "FileStream <object_name> = new FileStream( <file_name>, <FileMode Enumerator>,\n<FileAccess Enumerator>, <FileShare Enumerator>);" }, { "code": null, "e": 1563, "s": 1502, "text": "Here, the file operations are also included as shown below −" }, { "code": null, "e": 1675, "s": 1563, "text": "The FileMode enumerator defines various methods for opening files. The members of the FileMode enumerator are −" }, { "code": null, "e": 1795, "s": 1675, "text": "Append − It opens an existing file and puts cursor at the end of file, or creates the file, if the file does not exist." }, { "code": null, "e": 1915, "s": 1795, "text": "Append − It opens an existing file and puts cursor at the end of file, or creates the file, if the file does not exist." }, { "code": null, "e": 1947, "s": 1915, "text": "Create − It creates a new file." }, { "code": null, "e": 1979, "s": 1947, "text": "Create − It creates a new file." }, { "code": null, "e": 2063, "s": 1979, "text": "CreateNew − It specifies to the operating system, that it should create a new file." }, { "code": null, "e": 2147, "s": 2063, "text": "CreateNew − It specifies to the operating system, that it should create a new file." }, { "code": null, "e": 2181, "s": 2147, "text": "Open − It opens an existing file." }, { "code": null, "e": 2215, "s": 2181, "text": "Open − It opens an existing file." }, { "code": null, "e": 2347, "s": 2215, "text": "OpenOrCreate − It specifies to the operating system that it should open a file if it exists, otherwise it should create a new file." }, { "code": null, "e": 2479, "s": 2347, "text": "OpenOrCreate − It specifies to the operating system that it should open a file if it exists, otherwise it should create a new file." }, { "code": null, "e": 2554, "s": 2479, "text": "Truncate − It opens an existing file and truncates its size to zero bytes." }, { "code": null, "e": 2629, "s": 2554, "text": "Truncate − It opens an existing file and truncates its size to zero bytes." }, { "code": null, "e": 2710, "s": 2629, "text": "FileAccess − The FileAccess enumerators have members: Read, ReadWrite and Write." }, { "code": null, "e": 2777, "s": 2710, "text": "FileShare − The FileShare enumerators have the following members −" }, { "code": null, "e": 2858, "s": 2777, "text": "Inheritable − It allows a file handle to pass inheritance to the child processes" }, { "code": null, "e": 2939, "s": 2858, "text": "Inheritable − It allows a file handle to pass inheritance to the child processes" }, { "code": null, "e": 2986, "s": 2939, "text": "None − It declines sharing of the current file" }, { "code": null, "e": 3033, "s": 2986, "text": "None − It declines sharing of the current file" }, { "code": null, "e": 3079, "s": 3033, "text": "Read − It allows opening the file for readin." }, { "code": null, "e": 3125, "s": 3079, "text": "Read − It allows opening the file for readin." }, { "code": null, "e": 3188, "s": 3125, "text": "ReadWrite − It allows opening the file for reading and writing" }, { "code": null, "e": 3251, "s": 3188, "text": "ReadWrite − It allows opening the file for reading and writing" }, { "code": null, "e": 3297, "s": 3251, "text": "Write− It allows opening the file for writing" }, { "code": null, "e": 3343, "s": 3297, "text": "Write− It allows opening the file for writing" }, { "code": null, "e": 3389, "s": 3343, "text": "Let us see an example to get the directories." }, { "code": null, "e": 3679, "s": 3389, "text": "//creating a DirectoryInfo object\nDirectoryInfo mydir = new DirectoryInfo(@\"d:\\Demo\");\n\n// getting the files in the directory, their names and size\nFileInfo [] f = mydir.GetFiles();\n\nforeach (FileInfo file in f) {\n Console.WriteLine(\"File Name: {0} Size: {1}\", file.Name, file.Length);\n}" } ]
Style options for the HTML5 Date picker
The date picker in HTML5 basically works very similar to how the JavaScript Libraries did, when we focus on the field a calendar will pop out, and then we can navigate through the months and years to select the date. Therefore, if you want the date input to use more spacing and a color scheme you could add the following to your code. ::-webkit-datetime-edit { padding: 2 em; } ::-webkit-datetime-edit-fields-wrapper { background:green; } ::-webkit-datetime-edit-text { color: blue; padding: 0 0.3em; } ::-webkit-datetime-edit-month-field { color: red; } ::-webkit-datetime-edit-day-field { color: orange; } ::-webkit-datetime-edit-year-field { color: red; } <input type = "date">
[ { "code": null, "e": 1279, "s": 1062, "text": "The date picker in HTML5 basically works very similar to how the JavaScript Libraries did, when we focus on the field a calendar will pop out, and then we can navigate through the months and years to select the date." }, { "code": null, "e": 1398, "s": 1279, "text": "Therefore, if you want the date input to use more spacing and a color scheme you could add the following to your code." }, { "code": null, "e": 1744, "s": 1398, "text": "::-webkit-datetime-edit { padding: 2 em; }\n::-webkit-datetime-edit-fields-wrapper { background:green; }\n::-webkit-datetime-edit-text { color: blue; padding: 0 0.3em; }\n::-webkit-datetime-edit-month-field { color: red; }\n::-webkit-datetime-edit-day-field { color: orange; }\n::-webkit-datetime-edit-year-field { color: red; }\n<input type = \"date\">" } ]
Clockwise rotation of Doubly Linked List by N places - GeeksforGeeks
08 Jun, 2021 Given a doubly-linked list and an integer N, the task is to rotate the linked list clockwise by N nodes.Examples: Input: N = 2 Output: Approach: To rotate the Doubly linked list first check whether the given N is greater than the length of the list or not. If N is greater than the size of the list then deduce it in the range of linked list size by taking modulo with the length of the list. After that subtract the value of N from the length of the list. Now the problem reduces to the counter-clockwise rotation of a doubly-linked list by N places. Change the next of the last node to point the Head node. Change the prev of the Head node to point the last node. Change the value of the Head_ref to be the next of the Nth node. Change the value of next of the Nth Node to be NULL. Finally, make the prev of Head node to point to NULL. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program to rotate a Doubly linked// list clock wise by N times#include <bits/stdc++.h>using namespace std; /* Link list node */struct Node { char data; struct Node* prev; struct Node* next;}; // Utility function to find the size of// Doubly Linked Listint size(struct Node* head_ref){ struct Node* curr = head_ref; int sz = 0; while (curr != NULL) { curr = curr->next; sz++; } return sz;} /* Function to print linked list */void printList(struct Node* node){ while (node->next != NULL) { cout << node->data << " " << "<=>" << " "; node = node->next; } cout << node->data;} // Function to insert a node at the// beginning of the Doubly Linked Listvoid push(struct Node** head_ref, int new_data){ struct Node* new_node = new Node; new_node->data = new_data; new_node->prev = NULL; new_node->next = (*head_ref); if ((*head_ref) != NULL) (*head_ref)->prev = new_node; *head_ref = new_node;} // Function to rotate a doubly linked// list clockwise and update the headvoid rotate(struct Node** head_ref, int N, int sz){ /* If N is greater than the size of Doubly Linked List, we have to deduce it in the range of Doubly linked list size by taking modulo with the length of the list.*/ N = N % sz; /* We will update N by subtracting it's value length of the list. After this the question will reduce to counter clockwise rotation of linked list to N places*/ N = sz - N; if (N == 0) return; struct Node* current = *head_ref; // current will either point to Nth // or NULL after this loop. Current // will point to node 'b' in the // above example int count = 1; while (count < N && current != NULL) { current = current->next; count++; } // If current is NULL, N is greater // than or equal to count of nodes // in linked list // Don't change the list in this case if (current == NULL) return; // current points to Nth node. Store // it in a variable. NthNode points to // node 'b' in the above example struct Node* NthNode = current; // current will point to last node // after this loop current will point // to node 'e' in the above example while (current->next != NULL) current = current->next; // Change next of last node to previous // head. Next of 'e' is now changed to // node 'a' current->next = *head_ref; // Change prev of Head node to current // Prev of 'a' is now changed to node 'e' (*head_ref)->prev = current; // Change head to (N+1)th node // head is now changed to node 'c' *head_ref = NthNode->next; // Change prev of New Head node to NULL // Because Prev of Head Node in Doubly // linked list is NULL (*head_ref)->prev = NULL; // Change next of Nth node to NULL // next of 'b' is now NULL NthNode->next = NULL;} // Driver codeint main(void){ /* Start with the empty list */ struct Node* head = NULL; /* Create the doubly linked list a<->b<->c<->d<->e */ push(&head, 'e'); push(&head, 'd'); push(&head, 'c'); push(&head, 'b'); push(&head, 'a'); int N = 2; // Length of the list int sz = size(head); cout << "Given Doubly linked list \n"; printList(head); rotate(&head, N, sz); cout << "\nRotated Linked list clockwise \n"; printList(head); return 0;} // Java program to rotate a Doubly linked// list clock wise by N timesclass GFG{ /* Link list node */static class Node{ char data; Node prev; Node next;}; // Utility function to find the size of// Doubly Linked Liststatic int size(Node head_ref){ Node curr = head_ref; int sz = 0; while (curr != null) { curr = curr.next; sz++; } return sz;} /* Function to print linked list */static void printList(Node node){ while (node.next != null) { System.out.print( node.data + " " + "<=>" + " "); node = node.next; } System.out.print(node.data);} // Function to insert a node at the// beginning of the Doubly Linked Liststatic Node push(Node head_ref, char new_data){ Node new_node = new Node(); new_node.data = new_data; new_node.prev = null; new_node.next = head_ref; if (head_ref != null) head_ref.prev = new_node; head_ref = new_node; return head_ref;} // Function to rotate a doubly linked// list clockwise and update the headstatic Node rotate(Node head_ref, int N, int sz){ /* If N is greater than the size of Doubly Linked List, we have to deduce it in the range of Doubly linked list size by taking modulo with the length of the list.*/ N = N % sz; /* We will update N by subtracting it's value length of the list. After this the question will reduce to counter clockwise rotation of linked list to N places*/ N = sz - N; if (N == 0) return null; Node current = head_ref; // current will either point to Nth // or null after this loop. Current // will point to node 'b' in the // above example int count = 1; while (count < N && current != null) { current = current.next; count++; } // If current is null, N is greater // than or equal to count of nodes // in linked list // Don't change the list in this case if (current == null) return null; // current points to Nth node. Store // it in a variable. NthNode points to // node 'b' in the above example Node NthNode = current; // current will point to last node // after this loop current will point // to node 'e' in the above example while (current.next != null) current = current.next; // Change next of last node to previous // head. Next of 'e' is now changed to // node 'a' current.next = head_ref; // Change prev of Head node to current // Prev of 'a' is now changed to node 'e' head_ref.prev = current; // Change head to (N+1)th node // head is now changed to node 'c' head_ref = NthNode.next; // Change prev of New Head node to null // Because Prev of Head Node in Doubly // linked list is null head_ref.prev = null; // Change next of Nth node to null // next of 'b' is now null NthNode.next = null; return head_ref;} // Driver codepublic static void main(String []args){ /* Start with the empty list */ Node head = null; /* Create the doubly linked list a<->b<->c<->d<->e */ head = push(head, 'e'); head = push(head, 'd'); head = push(head, 'c'); head = push(head, 'b'); head = push(head, 'a'); int N = 2; // Length of the list int sz = size(head); System.out.println("Given Doubly linked list "); printList(head); head = rotate(head, N, sz); System.out.println("\nRotated Linked list clockwise "); printList(head);}} // This code is contributed by 29AjayKumar # Node of a doubly linked listclass Node: def __init__(self, next = None, prev = None, data = None): self.next = next # reference to next node in DLL self.prev = prev # reference to previous node in DLL self.data = data # Function to insert a node at the# beginning of the Doubly Linked Listdef push(head, new_data): new_node = Node(data = new_data) new_node.next = head new_node.prev = None if head is not None: head.prev = new_node head = new_node return head # Utility function to find the size of# Doubly Linked Listdef size(head): node = head sz = 0 while(node is not None): sz+= 1 node = node.next return sz # Function to print linked listdef printList(head): node = head print("Given linked list") while(node is not None): print(node.data, end = " "), last = node node = node.next # Function to rotate a doubly linked# list clockwise and update the headdef rotate(start, N): if N == 0 : return # Let us understand the below code # for example N = 2 and # list = a <-> b <-> c <-> d <-> e. current = start # current will either point to Nth # or None after this loop. Current # will point to node 'b' in the # above example count = 1 while count < N and current != None : current = current.next count += 1 # If current is None, N is greater # than or equal to count of nodes # in linked list. Don't change the # list in this case if current == None : return # current points to Nth node. Store # it in a variable. NthNode points to # node 'b' in the above example NthNode = current # current will point to last node # after this loop current will point # to node 'e' in the above example while current.next != None : current = current.next # Change next of last node to previous # head. Next of 'e' is now changed to # node 'a' current.next = start # Change prev of Head node to current # Prev of 'a' is now changed to node 'e' start.prev = current # Change head to (N + 1)th node # head is now changed to node 'c' start = NthNode.next # Change prev of New Head node to None # Because Prev of Head Node in Doubly # linked list is None start.prev = None # change next of Nth node to None # next of 'b' is now None NthNode.next = None return start # Driver Codeif __name__ == "__main__": head = None head = push(head, 'e') head = push(head, 'd') head = push(head, 'c') head = push(head, 'b') head = push(head, 'a') printList(head) print("\n") N = 2 # Length of the list sz = size(head) # If N is greater than the size of Doubly # Linked List, we have to deduce it in the range # of Doubly linked list size by taking modulo with the # length of the list. N = N % sz; # We will update N by subtracting it's value length of # the list. After this the question will reduce to # counter-clockwise rotation of linked list to N places N = sz-N; head = rotate(head, N) printList(head) // C# program to rotate a Doubly linked// list clock wise by N timesusing System; class GFG{ /* Link list node */public class Node{ public char data; public Node prev; public Node next;}; // Utility function to find the size of// Doubly Linked Liststatic int size(Node head_ref){ Node curr = head_ref; int sz = 0; while (curr != null) { curr = curr.next; sz++; } return sz;} /* Function to print linked list */static void printList(Node node){ while (node.next != null) { Console.Write( node.data + " " + "<=>" + " "); node = node.next; } Console.Write(node.data);} // Function to insert a node at the// beginning of the Doubly Linked Liststatic Node push(Node head_ref, char new_data){ Node new_node = new Node(); new_node.data = new_data; new_node.prev = null; new_node.next = head_ref; if (head_ref != null) head_ref.prev = new_node; head_ref = new_node; return head_ref;} // Function to rotate a doubly linked// list clockwise and update the headstatic Node rotate(Node head_ref, int N, int sz){ /* If N is greater than the size of Doubly Linked List, we have to deduce it in the range of Doubly linked list size by taking modulo with the length of the list.*/ N = N % sz; /* We will update N by subtracting it's value length of the list. After this the question will reduce to counter clockwise rotation of linked list to N places*/ N = sz - N; if (N == 0) return null; Node current = head_ref; // current will either point to Nth // or null after this loop. Current // will point to node 'b' in the // above example int count = 1; while (count < N && current != null) { current = current.next; count++; } // If current is null, N is greater // than or equal to count of nodes // in linked list // Don't change the list in this case if (current == null) return null; // current points to Nth node. Store // it in a variable. NthNode points to // node 'b' in the above example Node NthNode = current; // current will point to last node // after this loop current will point // to node 'e' in the above example while (current.next != null) current = current.next; // Change next of last node to previous // head. Next of 'e' is now changed to // node 'a' current.next = head_ref; // Change prev of Head node to current // Prev of 'a' is now changed to node 'e' head_ref.prev = current; // Change head to (N+1)th node // head is now changed to node 'c' head_ref = NthNode.next; // Change prev of New Head node to null // Because Prev of Head Node in Doubly // linked list is null head_ref.prev = null; // Change next of Nth node to null // next of 'b' is now null NthNode.next = null; return head_ref;} // Driver codepublic static void Main(String []args){ /* Start with the empty list */ Node head = null; /* Create the doubly linked list a<->b<->c<->d<->e */ head = push(head, 'e'); head = push(head, 'd'); head = push(head, 'c'); head = push(head, 'b'); head = push(head, 'a'); int N = 2; // Length of the list int sz = size(head); Console.WriteLine("Given Doubly linked list "); printList(head); head = rotate(head, N, sz); Console.WriteLine("\nRotated Linked list clockwise "); printList(head);}} // This code is contributed by Rajput-Ji <script> // Javascript program to rotate a Doubly linked// list clock wise by N times /* Link list node */class Node { constructor() { this.data = null; this.prev = null; this.next = null; } } // Utility function to find the size of// Doubly Linked Listfunction size( head_ref){ var curr = head_ref; let sz = 0; while (curr != null) { curr = curr.next; sz++; } return sz;} /* Function to print linked list */function printList( node){ while (node.next != null) { document.write( node.data + " " + "<=>" + " "); node = node.next; } document.write(node.data);} // Function to insert a node at the// beginning of the Doubly Linked Listfunction push( head_ref, new_data){ var new_node = new Node(); new_node.data = new_data; new_node.prev = null; new_node.next = head_ref; if (head_ref != null) head_ref.prev = new_node; head_ref = new_node; return head_ref;} // Function to rotate a doubly linked// list clockwise and update the headfunction rotate( head_ref, N, sz){ /* If N is greater than the size of Doubly Linked List, we have to deduce it in the range of Doubly linked list size by taking modulo with the length of the list.*/ N = N % sz; /* We will update N by subtracting it's value length of the list. After this the question will reduce to counter clockwise rotation of linked list to N places*/ N = sz - N; if (N == 0) return null; var current = head_ref; // current will either point to Nth // or null after this loop. Current // will point to node 'b' in the // above example let count = 1; while (count < N && current != null) { current = current.next; count++; } // If current is null, N is greater // than or equal to count of nodes // in linked list // Don't change the list in this case if (current == null) return null; // current points to Nth node. Store // it in a variable. NthNode points to // node 'b' in the above example var NthNode = current; // current will point to last node // after this loop current will point // to node 'e' in the above example while (current.next != null) current = current.next; // Change next of last node to previous // head. Next of 'e' is now changed to // node 'a' current.next = head_ref; // Change prev of Head node to current // Prev of 'a' is now changed to node 'e' head_ref.prev = current; // Change head to (N+1)th node // head is now changed to node 'c' head_ref = NthNode.next; // Change prev of New Head node to null // Because Prev of Head Node in Doubly // linked list is null head_ref.prev = null; // Change next of Nth node to null // next of 'b' is now null NthNode.next = null; return head_ref;} // Driver Code /* Start with the empty list */var head = null; /* Create the doubly linkedlist a<->b<->c<->d<->e */head = push(head, 'e');head = push(head, 'd');head = push(head, 'c');head = push(head, 'b');head = push(head, 'a'); let N = 2; // Length of the listlet sz = size(head); document.write("Given Doubly linked list ");document.write("<br>");printList(head);head = rotate(head, N, sz); document.write("</br>"+"Rotated Linked list clockwise ");document.write("<br>");printList(head); </script> Given Doubly linked list a <=> b <=> c <=> d <=> e Rotated Linked list clockwise d <=> e <=> a <=> b <=> c Time Complexity: O(n) where n is the number of nodes in Linked List. 29AjayKumar Rajput-Ji jana_sayantan doubly linked list Linked List Linked List Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Circular Linked List | Set 2 (Traversal) Swap nodes in a linked list without swapping data Circular Singly Linked List | Insertion Given a linked list which is sorted, how will you insert in sorted way Program to implement Singly Linked List in C++ using class Delete a node in a Doubly Linked List Real-time application of Data Structures Insert a node at a specific position in a linked list Linked List Implementation in C# Priority Queue using Linked List
[ { "code": null, "e": 26313, "s": 26285, "text": "\n08 Jun, 2021" }, { "code": null, "e": 26429, "s": 26313, "text": "Given a doubly-linked list and an integer N, the task is to rotate the linked list clockwise by N nodes.Examples: " }, { "code": null, "e": 26444, "s": 26429, "text": "Input: N = 2 " }, { "code": null, "e": 26454, "s": 26444, "text": "Output: " }, { "code": null, "e": 26877, "s": 26458, "text": "Approach: To rotate the Doubly linked list first check whether the given N is greater than the length of the list or not. If N is greater than the size of the list then deduce it in the range of linked list size by taking modulo with the length of the list. After that subtract the value of N from the length of the list. Now the problem reduces to the counter-clockwise rotation of a doubly-linked list by N places. " }, { "code": null, "e": 26936, "s": 26877, "text": "Change the next of the last node to point the Head node. " }, { "code": null, "e": 26995, "s": 26936, "text": "Change the prev of the Head node to point the last node. " }, { "code": null, "e": 27062, "s": 26995, "text": "Change the value of the Head_ref to be the next of the Nth node. " }, { "code": null, "e": 27117, "s": 27062, "text": "Change the value of next of the Nth Node to be NULL. " }, { "code": null, "e": 27173, "s": 27117, "text": "Finally, make the prev of Head node to point to NULL. " }, { "code": null, "e": 27225, "s": 27173, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 27229, "s": 27225, "text": "C++" }, { "code": null, "e": 27234, "s": 27229, "text": "Java" }, { "code": null, "e": 27242, "s": 27234, "text": "Python3" }, { "code": null, "e": 27245, "s": 27242, "text": "C#" }, { "code": null, "e": 27256, "s": 27245, "text": "Javascript" }, { "code": "// C++ program to rotate a Doubly linked// list clock wise by N times#include <bits/stdc++.h>using namespace std; /* Link list node */struct Node { char data; struct Node* prev; struct Node* next;}; // Utility function to find the size of// Doubly Linked Listint size(struct Node* head_ref){ struct Node* curr = head_ref; int sz = 0; while (curr != NULL) { curr = curr->next; sz++; } return sz;} /* Function to print linked list */void printList(struct Node* node){ while (node->next != NULL) { cout << node->data << \" \" << \"<=>\" << \" \"; node = node->next; } cout << node->data;} // Function to insert a node at the// beginning of the Doubly Linked Listvoid push(struct Node** head_ref, int new_data){ struct Node* new_node = new Node; new_node->data = new_data; new_node->prev = NULL; new_node->next = (*head_ref); if ((*head_ref) != NULL) (*head_ref)->prev = new_node; *head_ref = new_node;} // Function to rotate a doubly linked// list clockwise and update the headvoid rotate(struct Node** head_ref, int N, int sz){ /* If N is greater than the size of Doubly Linked List, we have to deduce it in the range of Doubly linked list size by taking modulo with the length of the list.*/ N = N % sz; /* We will update N by subtracting it's value length of the list. After this the question will reduce to counter clockwise rotation of linked list to N places*/ N = sz - N; if (N == 0) return; struct Node* current = *head_ref; // current will either point to Nth // or NULL after this loop. Current // will point to node 'b' in the // above example int count = 1; while (count < N && current != NULL) { current = current->next; count++; } // If current is NULL, N is greater // than or equal to count of nodes // in linked list // Don't change the list in this case if (current == NULL) return; // current points to Nth node. Store // it in a variable. NthNode points to // node 'b' in the above example struct Node* NthNode = current; // current will point to last node // after this loop current will point // to node 'e' in the above example while (current->next != NULL) current = current->next; // Change next of last node to previous // head. Next of 'e' is now changed to // node 'a' current->next = *head_ref; // Change prev of Head node to current // Prev of 'a' is now changed to node 'e' (*head_ref)->prev = current; // Change head to (N+1)th node // head is now changed to node 'c' *head_ref = NthNode->next; // Change prev of New Head node to NULL // Because Prev of Head Node in Doubly // linked list is NULL (*head_ref)->prev = NULL; // Change next of Nth node to NULL // next of 'b' is now NULL NthNode->next = NULL;} // Driver codeint main(void){ /* Start with the empty list */ struct Node* head = NULL; /* Create the doubly linked list a<->b<->c<->d<->e */ push(&head, 'e'); push(&head, 'd'); push(&head, 'c'); push(&head, 'b'); push(&head, 'a'); int N = 2; // Length of the list int sz = size(head); cout << \"Given Doubly linked list \\n\"; printList(head); rotate(&head, N, sz); cout << \"\\nRotated Linked list clockwise \\n\"; printList(head); return 0;}", "e": 30687, "s": 27256, "text": null }, { "code": "// Java program to rotate a Doubly linked// list clock wise by N timesclass GFG{ /* Link list node */static class Node{ char data; Node prev; Node next;}; // Utility function to find the size of// Doubly Linked Liststatic int size(Node head_ref){ Node curr = head_ref; int sz = 0; while (curr != null) { curr = curr.next; sz++; } return sz;} /* Function to print linked list */static void printList(Node node){ while (node.next != null) { System.out.print( node.data + \" \" + \"<=>\" + \" \"); node = node.next; } System.out.print(node.data);} // Function to insert a node at the// beginning of the Doubly Linked Liststatic Node push(Node head_ref, char new_data){ Node new_node = new Node(); new_node.data = new_data; new_node.prev = null; new_node.next = head_ref; if (head_ref != null) head_ref.prev = new_node; head_ref = new_node; return head_ref;} // Function to rotate a doubly linked// list clockwise and update the headstatic Node rotate(Node head_ref, int N, int sz){ /* If N is greater than the size of Doubly Linked List, we have to deduce it in the range of Doubly linked list size by taking modulo with the length of the list.*/ N = N % sz; /* We will update N by subtracting it's value length of the list. After this the question will reduce to counter clockwise rotation of linked list to N places*/ N = sz - N; if (N == 0) return null; Node current = head_ref; // current will either point to Nth // or null after this loop. Current // will point to node 'b' in the // above example int count = 1; while (count < N && current != null) { current = current.next; count++; } // If current is null, N is greater // than or equal to count of nodes // in linked list // Don't change the list in this case if (current == null) return null; // current points to Nth node. Store // it in a variable. NthNode points to // node 'b' in the above example Node NthNode = current; // current will point to last node // after this loop current will point // to node 'e' in the above example while (current.next != null) current = current.next; // Change next of last node to previous // head. Next of 'e' is now changed to // node 'a' current.next = head_ref; // Change prev of Head node to current // Prev of 'a' is now changed to node 'e' head_ref.prev = current; // Change head to (N+1)th node // head is now changed to node 'c' head_ref = NthNode.next; // Change prev of New Head node to null // Because Prev of Head Node in Doubly // linked list is null head_ref.prev = null; // Change next of Nth node to null // next of 'b' is now null NthNode.next = null; return head_ref;} // Driver codepublic static void main(String []args){ /* Start with the empty list */ Node head = null; /* Create the doubly linked list a<->b<->c<->d<->e */ head = push(head, 'e'); head = push(head, 'd'); head = push(head, 'c'); head = push(head, 'b'); head = push(head, 'a'); int N = 2; // Length of the list int sz = size(head); System.out.println(\"Given Doubly linked list \"); printList(head); head = rotate(head, N, sz); System.out.println(\"\\nRotated Linked list clockwise \"); printList(head);}} // This code is contributed by 29AjayKumar", "e": 34205, "s": 30687, "text": null }, { "code": "# Node of a doubly linked listclass Node: def __init__(self, next = None, prev = None, data = None): self.next = next # reference to next node in DLL self.prev = prev # reference to previous node in DLL self.data = data # Function to insert a node at the# beginning of the Doubly Linked Listdef push(head, new_data): new_node = Node(data = new_data) new_node.next = head new_node.prev = None if head is not None: head.prev = new_node head = new_node return head # Utility function to find the size of# Doubly Linked Listdef size(head): node = head sz = 0 while(node is not None): sz+= 1 node = node.next return sz # Function to print linked listdef printList(head): node = head print(\"Given linked list\") while(node is not None): print(node.data, end = \" \"), last = node node = node.next # Function to rotate a doubly linked# list clockwise and update the headdef rotate(start, N): if N == 0 : return # Let us understand the below code # for example N = 2 and # list = a <-> b <-> c <-> d <-> e. current = start # current will either point to Nth # or None after this loop. Current # will point to node 'b' in the # above example count = 1 while count < N and current != None : current = current.next count += 1 # If current is None, N is greater # than or equal to count of nodes # in linked list. Don't change the # list in this case if current == None : return # current points to Nth node. Store # it in a variable. NthNode points to # node 'b' in the above example NthNode = current # current will point to last node # after this loop current will point # to node 'e' in the above example while current.next != None : current = current.next # Change next of last node to previous # head. Next of 'e' is now changed to # node 'a' current.next = start # Change prev of Head node to current # Prev of 'a' is now changed to node 'e' start.prev = current # Change head to (N + 1)th node # head is now changed to node 'c' start = NthNode.next # Change prev of New Head node to None # Because Prev of Head Node in Doubly # linked list is None start.prev = None # change next of Nth node to None # next of 'b' is now None NthNode.next = None return start # Driver Codeif __name__ == \"__main__\": head = None head = push(head, 'e') head = push(head, 'd') head = push(head, 'c') head = push(head, 'b') head = push(head, 'a') printList(head) print(\"\\n\") N = 2 # Length of the list sz = size(head) # If N is greater than the size of Doubly # Linked List, we have to deduce it in the range # of Doubly linked list size by taking modulo with the # length of the list. N = N % sz; # We will update N by subtracting it's value length of # the list. After this the question will reduce to # counter-clockwise rotation of linked list to N places N = sz-N; head = rotate(head, N) printList(head)", "e": 37374, "s": 34205, "text": null }, { "code": "// C# program to rotate a Doubly linked// list clock wise by N timesusing System; class GFG{ /* Link list node */public class Node{ public char data; public Node prev; public Node next;}; // Utility function to find the size of// Doubly Linked Liststatic int size(Node head_ref){ Node curr = head_ref; int sz = 0; while (curr != null) { curr = curr.next; sz++; } return sz;} /* Function to print linked list */static void printList(Node node){ while (node.next != null) { Console.Write( node.data + \" \" + \"<=>\" + \" \"); node = node.next; } Console.Write(node.data);} // Function to insert a node at the// beginning of the Doubly Linked Liststatic Node push(Node head_ref, char new_data){ Node new_node = new Node(); new_node.data = new_data; new_node.prev = null; new_node.next = head_ref; if (head_ref != null) head_ref.prev = new_node; head_ref = new_node; return head_ref;} // Function to rotate a doubly linked// list clockwise and update the headstatic Node rotate(Node head_ref, int N, int sz){ /* If N is greater than the size of Doubly Linked List, we have to deduce it in the range of Doubly linked list size by taking modulo with the length of the list.*/ N = N % sz; /* We will update N by subtracting it's value length of the list. After this the question will reduce to counter clockwise rotation of linked list to N places*/ N = sz - N; if (N == 0) return null; Node current = head_ref; // current will either point to Nth // or null after this loop. Current // will point to node 'b' in the // above example int count = 1; while (count < N && current != null) { current = current.next; count++; } // If current is null, N is greater // than or equal to count of nodes // in linked list // Don't change the list in this case if (current == null) return null; // current points to Nth node. Store // it in a variable. NthNode points to // node 'b' in the above example Node NthNode = current; // current will point to last node // after this loop current will point // to node 'e' in the above example while (current.next != null) current = current.next; // Change next of last node to previous // head. Next of 'e' is now changed to // node 'a' current.next = head_ref; // Change prev of Head node to current // Prev of 'a' is now changed to node 'e' head_ref.prev = current; // Change head to (N+1)th node // head is now changed to node 'c' head_ref = NthNode.next; // Change prev of New Head node to null // Because Prev of Head Node in Doubly // linked list is null head_ref.prev = null; // Change next of Nth node to null // next of 'b' is now null NthNode.next = null; return head_ref;} // Driver codepublic static void Main(String []args){ /* Start with the empty list */ Node head = null; /* Create the doubly linked list a<->b<->c<->d<->e */ head = push(head, 'e'); head = push(head, 'd'); head = push(head, 'c'); head = push(head, 'b'); head = push(head, 'a'); int N = 2; // Length of the list int sz = size(head); Console.WriteLine(\"Given Doubly linked list \"); printList(head); head = rotate(head, N, sz); Console.WriteLine(\"\\nRotated Linked list clockwise \"); printList(head);}} // This code is contributed by Rajput-Ji", "e": 40919, "s": 37374, "text": null }, { "code": "<script> // Javascript program to rotate a Doubly linked// list clock wise by N times /* Link list node */class Node { constructor() { this.data = null; this.prev = null; this.next = null; } } // Utility function to find the size of// Doubly Linked Listfunction size( head_ref){ var curr = head_ref; let sz = 0; while (curr != null) { curr = curr.next; sz++; } return sz;} /* Function to print linked list */function printList( node){ while (node.next != null) { document.write( node.data + \" \" + \"<=>\" + \" \"); node = node.next; } document.write(node.data);} // Function to insert a node at the// beginning of the Doubly Linked Listfunction push( head_ref, new_data){ var new_node = new Node(); new_node.data = new_data; new_node.prev = null; new_node.next = head_ref; if (head_ref != null) head_ref.prev = new_node; head_ref = new_node; return head_ref;} // Function to rotate a doubly linked// list clockwise and update the headfunction rotate( head_ref, N, sz){ /* If N is greater than the size of Doubly Linked List, we have to deduce it in the range of Doubly linked list size by taking modulo with the length of the list.*/ N = N % sz; /* We will update N by subtracting it's value length of the list. After this the question will reduce to counter clockwise rotation of linked list to N places*/ N = sz - N; if (N == 0) return null; var current = head_ref; // current will either point to Nth // or null after this loop. Current // will point to node 'b' in the // above example let count = 1; while (count < N && current != null) { current = current.next; count++; } // If current is null, N is greater // than or equal to count of nodes // in linked list // Don't change the list in this case if (current == null) return null; // current points to Nth node. Store // it in a variable. NthNode points to // node 'b' in the above example var NthNode = current; // current will point to last node // after this loop current will point // to node 'e' in the above example while (current.next != null) current = current.next; // Change next of last node to previous // head. Next of 'e' is now changed to // node 'a' current.next = head_ref; // Change prev of Head node to current // Prev of 'a' is now changed to node 'e' head_ref.prev = current; // Change head to (N+1)th node // head is now changed to node 'c' head_ref = NthNode.next; // Change prev of New Head node to null // Because Prev of Head Node in Doubly // linked list is null head_ref.prev = null; // Change next of Nth node to null // next of 'b' is now null NthNode.next = null; return head_ref;} // Driver Code /* Start with the empty list */var head = null; /* Create the doubly linkedlist a<->b<->c<->d<->e */head = push(head, 'e');head = push(head, 'd');head = push(head, 'c');head = push(head, 'b');head = push(head, 'a'); let N = 2; // Length of the listlet sz = size(head); document.write(\"Given Doubly linked list \");document.write(\"<br>\");printList(head);head = rotate(head, N, sz); document.write(\"</br>\"+\"Rotated Linked list clockwise \");document.write(\"<br>\");printList(head); </script>", "e": 44370, "s": 40919, "text": null }, { "code": null, "e": 44479, "s": 44370, "text": "Given Doubly linked list \na <=> b <=> c <=> d <=> e\nRotated Linked list clockwise \nd <=> e <=> a <=> b <=> c" }, { "code": null, "e": 44551, "s": 44481, "text": "Time Complexity: O(n) where n is the number of nodes in Linked List. " }, { "code": null, "e": 44563, "s": 44551, "text": "29AjayKumar" }, { "code": null, "e": 44573, "s": 44563, "text": "Rajput-Ji" }, { "code": null, "e": 44587, "s": 44573, "text": "jana_sayantan" }, { "code": null, "e": 44606, "s": 44587, "text": "doubly linked list" }, { "code": null, "e": 44618, "s": 44606, "text": "Linked List" }, { "code": null, "e": 44630, "s": 44618, "text": "Linked List" }, { "code": null, "e": 44728, "s": 44630, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 44769, "s": 44728, "text": "Circular Linked List | Set 2 (Traversal)" }, { "code": null, "e": 44819, "s": 44769, "text": "Swap nodes in a linked list without swapping data" }, { "code": null, "e": 44859, "s": 44819, "text": "Circular Singly Linked List | Insertion" }, { "code": null, "e": 44930, "s": 44859, "text": "Given a linked list which is sorted, how will you insert in sorted way" }, { "code": null, "e": 44989, "s": 44930, "text": "Program to implement Singly Linked List in C++ using class" }, { "code": null, "e": 45027, "s": 44989, "text": "Delete a node in a Doubly Linked List" }, { "code": null, "e": 45068, "s": 45027, "text": "Real-time application of Data Structures" }, { "code": null, "e": 45122, "s": 45068, "text": "Insert a node at a specific position in a linked list" }, { "code": null, "e": 45155, "s": 45122, "text": "Linked List Implementation in C#" } ]
Android Animations using Java - GeeksforGeeks
23 Feb, 2021 The animation is a method in which a collection of images is combined in a specific way and processed then they appear as moving images. Building animations make on-screen objects seems to be alive. Android has quite a few tools to help you create animations with relative ease. So in this article, let’s learn to create android animations using Java. Step 1: Create a New Project Start Android Studio (version > 2.2) Go to File -> New -> New Project. Select Empty Activity and click on next Select minimum SDK as 21 Choose the language as Java and click on the finish button. Modify the following XML and java files. Step 2: Modify activity_main.xml file In the XML file, we have added an ImageView, TextView, and Button inside the RelativeLayout. XML <?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:id="@+id/RL1" android:layout_height="match_parent" tools:context=".MainActivity"> <ImageView android:id="@+id/imageView1" android:layout_width="200dp" android:layout_height="150dp" android:layout_below="@id/textView0" android:layout_centerHorizontal="true" android:layout_marginTop="100dp" android:visibility="visible" android:src="@drawable/logo2" /> <TextView android:id="@+id/textView1" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="4 common animations in android" android:layout_below="@id/imageView1" android:layout_marginTop="50dp" android:layout_centerHorizontal="true" android:gravity="center" android:fontFamily="sans-serif" android:textSize="50px"/> <Button android:id="@+id/button1" android:layout_width="150dp" android:layout_height="wrap_content" android:text="Blink" android:layout_below="@id/textView1" android:layout_marginLeft="50dp" android:layout_marginTop="40dp"/> <Button android:id="@+id/button2" android:layout_width="150dp" android:layout_height="wrap_content" android:text="Slide" android:layout_below="@id/textView1" android:layout_alignParentRight="true" android:layout_marginRight="50dp" android:layout_marginTop="40dp"/> <Button android:id="@+id/button3" android:layout_width="150dp" android:layout_height="wrap_content" android:text="Rotate" android:layout_below="@id/button1" android:layout_marginLeft="50dp" android:layout_marginTop="30dp"/> <Button android:id="@+id/button4" android:layout_width="150dp" android:layout_height="wrap_content" android:text="Zoom" android:layout_below="@id/button2" android:layout_alignParentRight="true" android:layout_marginRight="50dp" android:layout_marginTop="30dp"/> </RelativeLayout> Step 3: Add these XML files to the anim directory After modifying the layout we will create XML files for animations. So we will first create a folder name anim. In this folder, we will be adding the XML files which will be used to produce the animations. For this to happen, go to app/res right-click and then select Android Resource Directory and name it as anim. Some Common Types of Animations in Android are, Blink – Hides the object for 0.6 to 1 second.Slide – Move the object either vertically or horizontally to its axis.Rotate – Rotate the object either clockwise or anti-clockwise.Zoom – Zoom in or out the object in the X and Y-axis. Blink – Hides the object for 0.6 to 1 second. Slide – Move the object either vertically or horizontally to its axis. Rotate – Rotate the object either clockwise or anti-clockwise. Zoom – Zoom in or out the object in the X and Y-axis. blinks.xml rotate.xml slides.xml zoom.xml <?xml version="1.0" encoding="utf-8"?><set xmlns:android="http://schemas.android.com/apk/res/android"> <alpha android:fromAlpha="0.0" android:toAlpha="1.0" android:interpolator="@android:anim/accelerate_interpolator" android:duration="700" android:repeatMode="reverse" android:repeatCount="infinite"/></set> <?xml version="1.0" encoding="utf-8"?><set xmlns:android="http://schemas.android.com/apk/res/android"> <rotate xmlns:android="http://schemas.android.com/apk/res/android" android:fromDegrees="0" android:toDegrees="360" android:pivotX="50%" android:pivotY="50%" android:duration="2500" > </rotate> <rotate xmlns:android="http://schemas.android.com/apk/res/android" android:startOffset="5000" android:fromDegrees="360" android:toDegrees="0" android:pivotX="50%" android:pivotY="50%" android:duration="2500" > </rotate> </set> <?xml version="1.0" encoding="utf-8"?><set xmlns:android="http://schemas.android.com/apk/res/android" android:fillAfter="true" > <scale android:duration="500" android:fromXScale="1.0" android:fromYScale="1.0" android:interpolator="@android:anim/linear_interpolator" android:toXScale="1.0" android:toYScale="0.0" /></set> <?xml version="1.0" encoding="utf-8"?><set xmlns:android="http://schemas.android.com/apk/res/android"> <scale xmlns:android="http://schemas.android.com/apk/res/android" android:fromXScale="0.5" android:toXScale="3.0" android:fromYScale="0.5" android:toYScale="3.0" android:duration="4000" android:pivotX="50%" android:pivotY="50%" > </scale> <scale xmlns:android="http://schemas.android.com/apk/res/android" android:startOffset="5000" android:fromXScale="3.0" android:toXScale="0.5" android:fromYScale="3.0" android:toYScale="0.5" android:duration="4000" android:pivotX="50%" android:pivotY="50%" > </scale> </set> Step 4: Modify MainActivity.java To perform animation in android, we have to call a static function loadAnimation() of the class AnimationUtils. We get the result in an instance of the Animation Object. Syntax to create animation object: Animation object = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.ANIMATIONFILE); To apply the above animation to an object(Let say in an image), we have to call the startAnimation() method of the object. Syntax to call the method: ImageView image = findViewById(R.id.imageID); image.startAnimation(object); Methods of animation class: Method Description Java import androidx.appcompat.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import android.view.animation.Animation;import android.view.animation.AnimationUtils;import android.widget.Button;import android.widget.ImageView; public class MainActivity extends AppCompatActivity { ImageView logo; Button blink, slide, rotate, zoom; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // GFG logo logo = findViewById(R.id.imageView1); // blink button blink = findViewById(R.id.button1); // slide button slide = findViewById(R.id.button2); // rotate button rotate = findViewById(R.id.button3); // zoom button zoom = findViewById(R.id.button4); // blink button listener blink.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // call a static function loadAnimation() // of the class AnimationUtils Animation object = AnimationUtils .loadAnimation( getApplicationContext(), // blink file is in anim folder R.anim.blinks); // call the startAnimation method logo.startAnimation(object); } }); // slide button listener slide.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // call a static function loadAnimation() // of the class AnimationUtils Animation object = AnimationUtils .loadAnimation( getApplicationContext(), // slide file is in anim folder R.anim.slide); // call the startAnimation method logo.startAnimation(object); } }); // rotate button listener rotate.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // call a static function loadAnimation() // of the class AnimationUtils Animation object = AnimationUtils .loadAnimation( getApplicationContext(), // rotate file is in anim folder R.anim.rotate); // call the startAnimation method logo.startAnimation(object); } }); // zoom button listener zoom.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // call a static function loadAnimation() // of the class AnimationUtils Animation object = AnimationUtils .loadAnimation( getApplicationContext(), // zoom file is in anim folder R.anim.zoom); // call the startAnimation method logo.startAnimation(object); } }); }} Android-Animation Android Java Java Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Resource Raw Folder in Android Studio Flutter - Custom Bottom Navigation Bar How to Read Data from SQLite Database in Android? How to Post Data to API using Retrofit in Android? Retrofit with Kotlin Coroutine in Android Arrays in Java Split() String method in Java with examples For-each loop in Java Stream In Java Object Oriented Programming (OOPs) Concept in Java
[ { "code": null, "e": 25258, "s": 25230, "text": "\n23 Feb, 2021" }, { "code": null, "e": 25611, "s": 25258, "text": "The animation is a method in which a collection of images is combined in a specific way and processed then they appear as moving images. Building animations make on-screen objects seems to be alive. Android has quite a few tools to help you create animations with relative ease. So in this article, let’s learn to create android animations using Java. " }, { "code": null, "e": 25640, "s": 25611, "text": "Step 1: Create a New Project" }, { "code": null, "e": 25677, "s": 25640, "text": "Start Android Studio (version > 2.2)" }, { "code": null, "e": 25711, "s": 25677, "text": "Go to File -> New -> New Project." }, { "code": null, "e": 25751, "s": 25711, "text": "Select Empty Activity and click on next" }, { "code": null, "e": 25776, "s": 25751, "text": "Select minimum SDK as 21" }, { "code": null, "e": 25836, "s": 25776, "text": "Choose the language as Java and click on the finish button." }, { "code": null, "e": 25877, "s": 25836, "text": "Modify the following XML and java files." }, { "code": null, "e": 25915, "s": 25877, "text": "Step 2: Modify activity_main.xml file" }, { "code": null, "e": 26008, "s": 25915, "text": "In the XML file, we have added an ImageView, TextView, and Button inside the RelativeLayout." }, { "code": null, "e": 26012, "s": 26008, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:id=\"@+id/RL1\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <ImageView android:id=\"@+id/imageView1\" android:layout_width=\"200dp\" android:layout_height=\"150dp\" android:layout_below=\"@id/textView0\" android:layout_centerHorizontal=\"true\" android:layout_marginTop=\"100dp\" android:visibility=\"visible\" android:src=\"@drawable/logo2\" /> <TextView android:id=\"@+id/textView1\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:text=\"4 common animations in android\" android:layout_below=\"@id/imageView1\" android:layout_marginTop=\"50dp\" android:layout_centerHorizontal=\"true\" android:gravity=\"center\" android:fontFamily=\"sans-serif\" android:textSize=\"50px\"/> <Button android:id=\"@+id/button1\" android:layout_width=\"150dp\" android:layout_height=\"wrap_content\" android:text=\"Blink\" android:layout_below=\"@id/textView1\" android:layout_marginLeft=\"50dp\" android:layout_marginTop=\"40dp\"/> <Button android:id=\"@+id/button2\" android:layout_width=\"150dp\" android:layout_height=\"wrap_content\" android:text=\"Slide\" android:layout_below=\"@id/textView1\" android:layout_alignParentRight=\"true\" android:layout_marginRight=\"50dp\" android:layout_marginTop=\"40dp\"/> <Button android:id=\"@+id/button3\" android:layout_width=\"150dp\" android:layout_height=\"wrap_content\" android:text=\"Rotate\" android:layout_below=\"@id/button1\" android:layout_marginLeft=\"50dp\" android:layout_marginTop=\"30dp\"/> <Button android:id=\"@+id/button4\" android:layout_width=\"150dp\" android:layout_height=\"wrap_content\" android:text=\"Zoom\" android:layout_below=\"@id/button2\" android:layout_alignParentRight=\"true\" android:layout_marginRight=\"50dp\" android:layout_marginTop=\"30dp\"/> </RelativeLayout>", "e": 28352, "s": 26012, "text": null }, { "code": null, "e": 28402, "s": 28352, "text": "Step 3: Add these XML files to the anim directory" }, { "code": null, "e": 28719, "s": 28402, "text": "After modifying the layout we will create XML files for animations. So we will first create a folder name anim. In this folder, we will be adding the XML files which will be used to produce the animations. For this to happen, go to app/res right-click and then select Android Resource Directory and name it as anim. " }, { "code": null, "e": 28767, "s": 28719, "text": "Some Common Types of Animations in Android are," }, { "code": null, "e": 28998, "s": 28767, "text": "Blink – Hides the object for 0.6 to 1 second.Slide – Move the object either vertically or horizontally to its axis.Rotate – Rotate the object either clockwise or anti-clockwise.Zoom – Zoom in or out the object in the X and Y-axis." }, { "code": null, "e": 29044, "s": 28998, "text": "Blink – Hides the object for 0.6 to 1 second." }, { "code": null, "e": 29115, "s": 29044, "text": "Slide – Move the object either vertically or horizontally to its axis." }, { "code": null, "e": 29178, "s": 29115, "text": "Rotate – Rotate the object either clockwise or anti-clockwise." }, { "code": null, "e": 29232, "s": 29178, "text": "Zoom – Zoom in or out the object in the X and Y-axis." }, { "code": null, "e": 29243, "s": 29232, "text": "blinks.xml" }, { "code": null, "e": 29254, "s": 29243, "text": "rotate.xml" }, { "code": null, "e": 29265, "s": 29254, "text": "slides.xml" }, { "code": null, "e": 29274, "s": 29265, "text": "zoom.xml" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><set xmlns:android=\"http://schemas.android.com/apk/res/android\"> <alpha android:fromAlpha=\"0.0\" android:toAlpha=\"1.0\" android:interpolator=\"@android:anim/accelerate_interpolator\" android:duration=\"700\" android:repeatMode=\"reverse\" android:repeatCount=\"infinite\"/></set>", "e": 29609, "s": 29274, "text": null }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><set xmlns:android=\"http://schemas.android.com/apk/res/android\"> <rotate xmlns:android=\"http://schemas.android.com/apk/res/android\" android:fromDegrees=\"0\" android:toDegrees=\"360\" android:pivotX=\"50%\" android:pivotY=\"50%\" android:duration=\"2500\" > </rotate> <rotate xmlns:android=\"http://schemas.android.com/apk/res/android\" android:startOffset=\"5000\" android:fromDegrees=\"360\" android:toDegrees=\"0\" android:pivotX=\"50%\" android:pivotY=\"50%\" android:duration=\"2500\" > </rotate> </set>", "e": 30206, "s": 29609, "text": null }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><set xmlns:android=\"http://schemas.android.com/apk/res/android\" android:fillAfter=\"true\" > <scale android:duration=\"500\" android:fromXScale=\"1.0\" android:fromYScale=\"1.0\" android:interpolator=\"@android:anim/linear_interpolator\" android:toXScale=\"1.0\" android:toYScale=\"0.0\" /></set>", "e": 30566, "s": 30206, "text": null }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><set xmlns:android=\"http://schemas.android.com/apk/res/android\"> <scale xmlns:android=\"http://schemas.android.com/apk/res/android\" android:fromXScale=\"0.5\" android:toXScale=\"3.0\" android:fromYScale=\"0.5\" android:toYScale=\"3.0\" android:duration=\"4000\" android:pivotX=\"50%\" android:pivotY=\"50%\" > </scale> <scale xmlns:android=\"http://schemas.android.com/apk/res/android\" android:startOffset=\"5000\" android:fromXScale=\"3.0\" android:toXScale=\"0.5\" android:fromYScale=\"3.0\" android:toYScale=\"0.5\" android:duration=\"4000\" android:pivotX=\"50%\" android:pivotY=\"50%\" > </scale> </set>", "e": 31275, "s": 30566, "text": null }, { "code": null, "e": 31308, "s": 31275, "text": "Step 4: Modify MainActivity.java" }, { "code": null, "e": 31513, "s": 31308, "text": "To perform animation in android, we have to call a static function loadAnimation() of the class AnimationUtils. We get the result in an instance of the Animation Object. Syntax to create animation object:" }, { "code": null, "e": 31609, "s": 31513, "text": "Animation object = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.ANIMATIONFILE);" }, { "code": null, "e": 31759, "s": 31609, "text": "To apply the above animation to an object(Let say in an image), we have to call the startAnimation() method of the object. Syntax to call the method:" }, { "code": null, "e": 31806, "s": 31759, "text": "ImageView image = findViewById(R.id.imageID); " }, { "code": null, "e": 31836, "s": 31806, "text": "image.startAnimation(object);" }, { "code": null, "e": 31864, "s": 31836, "text": "Methods of animation class:" }, { "code": null, "e": 31871, "s": 31864, "text": "Method" }, { "code": null, "e": 31883, "s": 31871, "text": "Description" }, { "code": null, "e": 31888, "s": 31883, "text": "Java" }, { "code": "import androidx.appcompat.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import android.view.animation.Animation;import android.view.animation.AnimationUtils;import android.widget.Button;import android.widget.ImageView; public class MainActivity extends AppCompatActivity { ImageView logo; Button blink, slide, rotate, zoom; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // GFG logo logo = findViewById(R.id.imageView1); // blink button blink = findViewById(R.id.button1); // slide button slide = findViewById(R.id.button2); // rotate button rotate = findViewById(R.id.button3); // zoom button zoom = findViewById(R.id.button4); // blink button listener blink.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // call a static function loadAnimation() // of the class AnimationUtils Animation object = AnimationUtils .loadAnimation( getApplicationContext(), // blink file is in anim folder R.anim.blinks); // call the startAnimation method logo.startAnimation(object); } }); // slide button listener slide.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // call a static function loadAnimation() // of the class AnimationUtils Animation object = AnimationUtils .loadAnimation( getApplicationContext(), // slide file is in anim folder R.anim.slide); // call the startAnimation method logo.startAnimation(object); } }); // rotate button listener rotate.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // call a static function loadAnimation() // of the class AnimationUtils Animation object = AnimationUtils .loadAnimation( getApplicationContext(), // rotate file is in anim folder R.anim.rotate); // call the startAnimation method logo.startAnimation(object); } }); // zoom button listener zoom.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // call a static function loadAnimation() // of the class AnimationUtils Animation object = AnimationUtils .loadAnimation( getApplicationContext(), // zoom file is in anim folder R.anim.zoom); // call the startAnimation method logo.startAnimation(object); } }); }}", "e": 35404, "s": 31888, "text": null }, { "code": null, "e": 35422, "s": 35404, "text": "Android-Animation" }, { "code": null, "e": 35430, "s": 35422, "text": "Android" }, { "code": null, "e": 35435, "s": 35430, "text": "Java" }, { "code": null, "e": 35440, "s": 35435, "text": "Java" }, { "code": null, "e": 35448, "s": 35440, "text": "Android" }, { "code": null, "e": 35546, "s": 35448, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35584, "s": 35546, "text": "Resource Raw Folder in Android Studio" }, { "code": null, "e": 35623, "s": 35584, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 35673, "s": 35623, "text": "How to Read Data from SQLite Database in Android?" }, { "code": null, "e": 35724, "s": 35673, "text": "How to Post Data to API using Retrofit in Android?" }, { "code": null, "e": 35766, "s": 35724, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 35781, "s": 35766, "text": "Arrays in Java" }, { "code": null, "e": 35825, "s": 35781, "text": "Split() String method in Java with examples" }, { "code": null, "e": 35847, "s": 35825, "text": "For-each loop in Java" }, { "code": null, "e": 35862, "s": 35847, "text": "Stream In Java" } ]
How do I find an element that contains specific text in Selenium WebDriver (Python)?
We can find an element that contains specific text with Selenium webdriver in Python using the xpath. This locator has functions that help to verify a specific text contained within an element. The function text() in xpath is used to locate a webelement depending on the text visible on the page. Another function contains() in xpath is used to locate a webelement with the sub-text of actual text visible on the page. Let us try to identify the element having the specific text - Privacy Policy. l = driver.find_element_by_xpath("//a[text()='Privacy Policy']") m = driver.find_element_by_xpath("//a[contains(text(), 'Privacy')]") from selenium import webdriver #set chromodriver.exe path driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe") driver.implicitly_wait(0.5) #launch URL driver.get("https://www.tutorialspoint.com/about/about_careers.htm") #identify element with text() xpath l = driver.find_element_by_xpath("//a[text()='Privacy Policy']") #identify element with contains xpath m = driver.find_element_by_xpath("//a[contains(text(), 'Privacy')]") #get element text print('Text obtained with text(): ' + l.text) print('Text obtained with contains(): ' + m.text) #close browser driver.quit()
[ { "code": null, "e": 1256, "s": 1062, "text": "We can find an element that contains specific text with Selenium webdriver in Python using the xpath. This locator has functions that help to verify a specific text contained within an element." }, { "code": null, "e": 1481, "s": 1256, "text": "The function text() in xpath is used to locate a webelement depending on the text visible on the page. Another function contains() in xpath is used to locate a webelement with the sub-text of actual text visible on the page." }, { "code": null, "e": 1559, "s": 1481, "text": "Let us try to identify the element having the specific text - Privacy Policy." }, { "code": null, "e": 1693, "s": 1559, "text": "l = driver.find_element_by_xpath(\"//a[text()='Privacy Policy']\")\nm = driver.find_element_by_xpath(\"//a[contains(text(), 'Privacy')]\")" }, { "code": null, "e": 2282, "s": 1693, "text": "from selenium import webdriver\n#set chromodriver.exe path\ndriver = webdriver.Chrome(executable_path=\"C:\\\\chromedriver.exe\")\ndriver.implicitly_wait(0.5)\n#launch URL\ndriver.get(\"https://www.tutorialspoint.com/about/about_careers.htm\")\n#identify element with text() xpath\nl = driver.find_element_by_xpath(\"//a[text()='Privacy Policy']\")\n#identify element with contains xpath\nm = driver.find_element_by_xpath(\"//a[contains(text(), 'Privacy')]\")\n\n#get element text\n\nprint('Text obtained with text(): ' + l.text)\n\nprint('Text obtained with contains(): ' + m.text)\n\n#close browser\n\ndriver.quit()" } ]
Create AI for Your Own Board Game From Scratch — Minimax — Part 2 | by Haryo Akbarianto Wibowo | Towards Data Science
Hi, How’s life? Welcome to the second part of the series of articles about project on making EvoPawness (Temporary Name) board game. Here, we will implement on how to add AI to to the game. In this article, we will focus on implementing some classic algorithms. It’s minimax and alpha beta pruning minimax. We will recap what we’ve done in the previous part and what I’ve done in the repository about the code of the board game (GitHub). Before we dive on how to implement it, I will tell you that this series of articles will tell step by step on creating the board game. So, I will write about how I design and code the game, the GUI, and the AI as detail as possible. I want to share about my experience on doing it. So, I will do it gradually and tell my success and failed attempt on creating the AI. We haven’t covered the GUI yet. Later, I will create the article about how to make and design the GUI. For now, we will skip the GUI and do the AI part first. This article is targeted for the one who is interested in AI and designing a game. If you are not one of them, of course you can still see this article. I hope that my writing skill will increase by publishing this article and the content benefits you 😄. RepositoryPrevious part recapEvaluation and Utility Function EngineeringMinimax Algorithm and ImplementationA-B Pruning Minimax Algorithm and ImplementationConclusionAfterwords Repository Previous part recap Evaluation and Utility Function Engineering Minimax Algorithm and Implementation A-B Pruning Minimax Algorithm and Implementation Conclusion Afterwords Here is the repository github.com I’ve added several changes to the repository Balance the game. I’ve played several times with friends and the previous rule of the game is really unbalance. Implement the GUI with PyQt5 library Change the rule to make the game deterministic for the sake of this article. It will be changed on the next part. Add Minimax, AB-Pruning Minimax, and random agent Reformat the folder’s structure If you want to play it in the Graphical User Interface (GUI) version, install PyQt5 with pip install PyQt5 command in your Command Line Interface (CLI). In the previous part, we’ve defined some components to be used by AI Algorithm. We’ve stated Game’s Rule, State Representation, Result Function, Actions, Result Functions, and Terminal Test. We also have implemented them. In this article, let’s make use the function that we’ve implemented before to make an agent that can choose the action by seeing opponent’s possible action. Let’s recap, Utility Function Defines the final numeric value for a game when it’s in the terminal state for a player. The numeric value formula is defined by us. Evaluation Function Defines an estimate of the expected utility numeric value from a given state for a player. This function is called when the game hasn’t ended. The receive input of state and player and output a numeric score that represent the outcome and desirability of the state by the player. Negative score means that the player is in a disadvantage position. There aren’t any rule to define the Evaluation and Utility Function. So, we need to think on how to formulate it. The function should differentiate whether the player is in an advantage situation or not. This part is really important as this function will define the smartness of our agent. Here’s the formula that I’ve came up with: In the utility function, we will define the utility as high as you want and should be higher than evaluation function that we will define after this one. We’ve stated in the previous part that our terminal state has 2 conditions: When one of the king is deadWhen all of player’s pawns are dead When one of the king is dead When all of player’s pawns are dead Here, if the terminal state is reached, it will return -120 (negative means disadvantage), 120 otherwise. In the evaluation function, We will formulate it by considering the pawn’s hp, atk, step, and dead status. Every attributes is weighted by: Weight of HP = 0.3Weight of ATK = 0.1Weight of Step = 0.1Weight of dead’s pawn = 10Weight of King’s HP = 1 Weight of HP = 0.3 Weight of ATK = 0.1 Weight of Step = 0.1 Weight of dead’s pawn = 10 Weight of King’s HP = 1 We give 10 weight to the dead’s pawn because it’s very bad on losing a single pawn in this game. So, we hope by give it a high weight, the AI will avoid dead of its pawn. King is really an important piece here. So, we will give a higher point to it. We will define the utility and evaluation function in the AIElements.evaluation_function() function which calls evaluation function in class State. Minimax is a decision rule which simulate the decision of a player to find the optimal move for the player. It assumes that the opponent will play with optimal choice too. There are two actors in the Minimax. It’s maximizer and minimizer. The maximizer will search the highest score as possible and the minimizer will search the lowest score as possible. Each players will see the opponent’s move best move and get the best one for him/her. Usually, the searching is represented in tree structure data. Here’s the example how the Minimax algorithm Look at Image 1, Max will output B,C,and D actions. First, the minimizer will see the possible action resulted in B . Get the lowest score min(3,12,8) = 3. Then do that to C and D. After that, the Maximizer will pick the highest score. Which is max(3,2,2) = 3 . At our board game, the algorithm will not expand the state/node until terminal state. It will have memory issue or takes very long time to process. We should define a cut-off to our search algorithm by defining the max_depth that limit the node that should be expanded. It will call evaluation function that will calculate the heuristic of the condition. Let’s implement it into our EvoPawness (Temporary Name): We will define a class for Minimax algorithm that receive max_depth and player_color as its input. The player_color is a parameter to points out who is the maximizer here. Let’s see the Minimax class: As you can see, the Minimax Agent will do Depth First Search with recursive search. It will output the score (best_value) and the best action action key name. It will take the largest score if it’s the maximizer’s turn and take the smallest score if it’s the minimizer’s turn. It will search recursively until terminal state or maximum depth is reached. We shuffle the list to make the agent choose action with the same score randomly. If you are wondering the type of the action_target, it’s str type. Remember that our game action is a dict type which save the information of the action and the action key name. For example: ‘p1a2’: {‘action’: ‘activate’, ‘pawn_atk’: 1, ‘pawn_hp’: 5, ‘pawn_index’: 2, ‘pawn_step’: 1, ‘pawn_x’: 4, ‘pawn_y’: 1, ‘player_index’: 1}, We will play with the MinimaxAgent with depth = 4 Go to line 52 in controller/game_controller.py and change it into self.ai_agent = MinimaxAgent(max_depth=4, player_color=0) Run the game with your CLI python main_gui.py The AI will prioritize reaching the rune first. Then, activating its pawn. After that attacking our pawn first. If possible, the AI will evolve its pawn into higher type. Of course there’s some flaw such as let our pawn attacking their king. Maybe there is a better evaluation function that can make the AI protect the king. If you’ve tried the AI, you will see that the consumed time on choosing the action is very long. Let’s see: As we can see above, as the game progressed, the expanded_node is also increasing because of the number of possible actions. It tends to rise the time of the algorithm as the expanded node increasing. We can see the time on turn 24 is 21 second. Who wants to wait that long? This is the weakness of this algorithm as it will search all of possible state until the desired cut-off or terminal state. Fortunately, it’s possible that we can effectively cut the expanded node. We will be using a technique called pruning to compute the correct Minimax decision without looking at every node. It’s called alpha-beta pruning. Alpha Beta Pruning is an optimization technique for Minimax algorithm. This will cut the some nodes that should not be expanded because there is a better move already found. When applied to the Minimax algorithm, it will returns the same action as Minimax would, but it will be more faster. It’s called Alpha Beta Pruning because it needs 2 new parameters for the parameters called Alpha and Beta. Alpha : the best value that maximizer can guarantee in the current state or before in the maximizer turn Beta : the best value that minimizer can guarantee in the current state or before it in the minimizer turn The general principle is : given a state s somewhere in the tree. If player has a choice of making action m which is found before s has been found, then s will never be reached. Let’s take Image 1 as the example: Remember the searching algorithm is using DFS (Depth First Search)! Let’s dive in step by step: Initialize Alpha to -inf and Beta to Inf. Alpha will be updated if its in the Maximizer turn and Beta is update if its Minimizer turn. They will be passed to the child of the state/node.Expand A (the initial state) possible action. It will produce B,C,D state. start from the first index (B)It’s minimizer B turn. Expand B possible action, go into the child and check its score. Update Beta as minimum as possible. We will find Beta = 3 = min(3,12,8,inf). Alpha is still -inf.It’s assumed that the depth is 2, return the minimum score (which is 3) to the A. Now it’s back to Maximizer turn A, update the Alpha = 3 = max(-inf,3). Then we go to C state/node, the second child:Now go to state C, the minimizer turn C with the passed Alpha parameters 3. In C, we find that the first child’s score that the C found is 2. Update the Beta = 2 = min(inf,2). Now, let’s think. Will the maximizer choose this action? The maximizer has already found better move, which is scored at 3. Of course not, if it’s optimal agent. So, don’t bother check another possible action in the C. This is the pruning process. Return the best score (it’s 2). To make it simpler if beta ≤ alpha then prune it.Maximizer Turn A: calculate max(alpha, 2) = alpha. Check the last child C.Minimizer Turn C : Calculate min(inf,14) , update beta to 14 and check if beta ≤ alpha (14 ≤ 3) and it’s not pruned. Calculate the next child. beta ≤ alpha (5 ≤ 3) and it’s not pruned. At last, check beta ≤ alpha (2 ≤ 3) it should be pruned. Since there are not any child after this node. No node that can be pruned. It can be pruned if the child that returned 2 is found at first. After this, return 2 to A.Maximizer Turn A, calculate max(alpha,2) = alpha. Then it’s done. return 3 as best score that has been found in the tree. Initialize Alpha to -inf and Beta to Inf. Alpha will be updated if its in the Maximizer turn and Beta is update if its Minimizer turn. They will be passed to the child of the state/node. Expand A (the initial state) possible action. It will produce B,C,D state. start from the first index (B) It’s minimizer B turn. Expand B possible action, go into the child and check its score. Update Beta as minimum as possible. We will find Beta = 3 = min(3,12,8,inf). Alpha is still -inf. It’s assumed that the depth is 2, return the minimum score (which is 3) to the A. Now it’s back to Maximizer turn A, update the Alpha = 3 = max(-inf,3). Then we go to C state/node, the second child: Now go to state C, the minimizer turn C with the passed Alpha parameters 3. In C, we find that the first child’s score that the C found is 2. Update the Beta = 2 = min(inf,2). Now, let’s think. Will the maximizer choose this action? The maximizer has already found better move, which is scored at 3. Of course not, if it’s optimal agent. So, don’t bother check another possible action in the C. This is the pruning process. Return the best score (it’s 2). To make it simpler if beta ≤ alpha then prune it. Maximizer Turn A: calculate max(alpha, 2) = alpha. Check the last child C. Minimizer Turn C : Calculate min(inf,14) , update beta to 14 and check if beta ≤ alpha (14 ≤ 3) and it’s not pruned. Calculate the next child. beta ≤ alpha (5 ≤ 3) and it’s not pruned. At last, check beta ≤ alpha (2 ≤ 3) it should be pruned. Since there are not any child after this node. No node that can be pruned. It can be pruned if the child that returned 2 is found at first. After this, return 2 to A. Maximizer Turn A, calculate max(alpha,2) = alpha. Then it’s done. return 3 as best score that has been found in the tree. Implement it into the EvoPawness (Temporary Name). This is the class for Minimax Alpha Beta Pruning: (NOTE: the self.node_expanded is for DEBUG purpose) We add alpha and beta as the parameter with default -inf and inf. Then we add these line: For Maximizer alpha = max(alpha, best_value) if beta <= alpha: break And For Minimizer beta = min(beta, best_value) if beta <= alpha: break That’s all, let’s test it 😃! We will play with the MinimaxABAgent with depth = 4 Go to line 52 in controller/game_controller.py and change it into self.ai_agent = MinimaxABAgent(max_depth=4, player_color=0) The behavior is the same as the minimax , but faster. Let’s see the running time until turn 24. We can see, the time spent is faster without using pruning technique. Until the end, I found that the worst run time on searching the best action is 17s with 2218 expanded node (Turn 66). It’s faster because of the pruning that remove unnecessary node. Go on challenge the AI. The AI is very challenging. Sometimes it will target the king in the beginning. I lost once to the AI because of a sudden attack to the king and I didn’t prepare to defend the king 😢. Even so, it’s winnable. The AI doesn’t defend the king. I think that it needs more depth in the tree to know it. It will cost longer run time. Well, No one would want to test his/her patience on playing with AI that takes its turn too long (you want to wait a minute or more to wait its turn?). Minimax also does not consider the state other than the state that is found in the chosen depth. Minimax only cares about the state that is found in it. It’s impossible to search all the node to the terminal state from start as it will cause Memory Error. It’s computationally expensive (O(action^depth ) ) This is the weakness of the Minimax, even with the improvement using pruning technique. We need some technique that consider the state other than the chosen depth and can also make the AI to choose the action faster. We will see it in the next part 😄. We’ve created the Utility and Evaluation Function that is used by Minimax algorithm. Although the performance is good, the Minimax algorithm is so slow. To mend it, we use pruning to the algorithm. It’s called Alpha Beta Pruning. The pattern of the actions is same and it’s faster without using pruning. Even so, the Minimax Alpha Beta Pruning has its flaw. It can only consider and see the movement n turns onward that n needs to be small. If n is large, it will be computationally expensive to choose an action. We need some algorithm that consider further turns and need to be faster. Thank you for reading my third article about Artificial Intelligence. I need some constructive feedback to make me better on writing and better knowledge about Artificial Intelligence. Go easy on me please 😆! I just want to share my knowledge to the reader. It’s good to share knowledge as it can be helpful to someone in needs. I’m in the process of learning this field and want to share what I’ve learnt. It’s nice if someone tell me if there’s something wrong with this article. Sorry for the bad User Experience (UX) on the GUI 😞. It also has messy and not enough documentation in the code. I hope I have the time to fix it. Maybe someone want to help me on fixing it? Next part (Part 3) will move on into Reinforcement Learning. We will explore kinds of Reinforcement Learning one by one. Before that, I will create an article on how I design the GUI and show the structure of the class in this project. It will be Part 1.5. Hope that I can release the article on this Sunday. We will experiment it on the Reinforcement Learning. I’m afraid that It will take a lot time to experiment it. I think, two weeks is the minimum interval that I can publish the articles. Someone want to join me experimenting it? Give me the spirit to write the next part ✌️. If you want another article from me like this one, please clap this article 👏 👏. It will boost my spirit to write my next article. I promise to make a better article. See you on the next article! Part 1 : Create AI for Your Own Board Game From Scratch — Preparation — Part 1 Part 2 : Create AI for Your Own Board Game From Scratch — Minimax — Part 2 Part 3 : Create AI for your Own Board Game From Scratch — AlphaZero-Part 3 Russell, Stuart J., and Peter Norvig. Artificial Intelligence: a Modern Approach. Prentice-Hall, 2010.
[ { "code": null, "e": 610, "s": 172, "text": "Hi, How’s life? Welcome to the second part of the series of articles about project on making EvoPawness (Temporary Name) board game. Here, we will implement on how to add AI to to the game. In this article, we will focus on implementing some classic algorithms. It’s minimax and alpha beta pruning minimax. We will recap what we’ve done in the previous part and what I’ve done in the repository about the code of the board game (GitHub)." }, { "code": null, "e": 978, "s": 610, "text": "Before we dive on how to implement it, I will tell you that this series of articles will tell step by step on creating the board game. So, I will write about how I design and code the game, the GUI, and the AI as detail as possible. I want to share about my experience on doing it. So, I will do it gradually and tell my success and failed attempt on creating the AI." }, { "code": null, "e": 1137, "s": 978, "text": "We haven’t covered the GUI yet. Later, I will create the article about how to make and design the GUI. For now, we will skip the GUI and do the AI part first." }, { "code": null, "e": 1392, "s": 1137, "text": "This article is targeted for the one who is interested in AI and designing a game. If you are not one of them, of course you can still see this article. I hope that my writing skill will increase by publishing this article and the content benefits you 😄." }, { "code": null, "e": 1569, "s": 1392, "text": "RepositoryPrevious part recapEvaluation and Utility Function EngineeringMinimax Algorithm and ImplementationA-B Pruning Minimax Algorithm and ImplementationConclusionAfterwords" }, { "code": null, "e": 1580, "s": 1569, "text": "Repository" }, { "code": null, "e": 1600, "s": 1580, "text": "Previous part recap" }, { "code": null, "e": 1644, "s": 1600, "text": "Evaluation and Utility Function Engineering" }, { "code": null, "e": 1681, "s": 1644, "text": "Minimax Algorithm and Implementation" }, { "code": null, "e": 1730, "s": 1681, "text": "A-B Pruning Minimax Algorithm and Implementation" }, { "code": null, "e": 1741, "s": 1730, "text": "Conclusion" }, { "code": null, "e": 1752, "s": 1741, "text": "Afterwords" }, { "code": null, "e": 1775, "s": 1752, "text": "Here is the repository" }, { "code": null, "e": 1786, "s": 1775, "text": "github.com" }, { "code": null, "e": 1831, "s": 1786, "text": "I’ve added several changes to the repository" }, { "code": null, "e": 1943, "s": 1831, "text": "Balance the game. I’ve played several times with friends and the previous rule of the game is really unbalance." }, { "code": null, "e": 1980, "s": 1943, "text": "Implement the GUI with PyQt5 library" }, { "code": null, "e": 2094, "s": 1980, "text": "Change the rule to make the game deterministic for the sake of this article. It will be changed on the next part." }, { "code": null, "e": 2144, "s": 2094, "text": "Add Minimax, AB-Pruning Minimax, and random agent" }, { "code": null, "e": 2176, "s": 2144, "text": "Reformat the folder’s structure" }, { "code": null, "e": 2329, "s": 2176, "text": "If you want to play it in the Graphical User Interface (GUI) version, install PyQt5 with pip install PyQt5 command in your Command Line Interface (CLI)." }, { "code": null, "e": 2551, "s": 2329, "text": "In the previous part, we’ve defined some components to be used by AI Algorithm. We’ve stated Game’s Rule, State Representation, Result Function, Actions, Result Functions, and Terminal Test. We also have implemented them." }, { "code": null, "e": 2708, "s": 2551, "text": "In this article, let’s make use the function that we’ve implemented before to make an agent that can choose the action by seeing opponent’s possible action." }, { "code": null, "e": 3239, "s": 2708, "text": "Let’s recap, Utility Function Defines the final numeric value for a game when it’s in the terminal state for a player. The numeric value formula is defined by us. Evaluation Function Defines an estimate of the expected utility numeric value from a given state for a player. This function is called when the game hasn’t ended. The receive input of state and player and output a numeric score that represent the outcome and desirability of the state by the player. Negative score means that the player is in a disadvantage position." }, { "code": null, "e": 3443, "s": 3239, "text": "There aren’t any rule to define the Evaluation and Utility Function. So, we need to think on how to formulate it. The function should differentiate whether the player is in an advantage situation or not." }, { "code": null, "e": 3530, "s": 3443, "text": "This part is really important as this function will define the smartness of our agent." }, { "code": null, "e": 3573, "s": 3530, "text": "Here’s the formula that I’ve came up with:" }, { "code": null, "e": 3727, "s": 3573, "text": "In the utility function, we will define the utility as high as you want and should be higher than evaluation function that we will define after this one." }, { "code": null, "e": 3803, "s": 3727, "text": "We’ve stated in the previous part that our terminal state has 2 conditions:" }, { "code": null, "e": 3867, "s": 3803, "text": "When one of the king is deadWhen all of player’s pawns are dead" }, { "code": null, "e": 3896, "s": 3867, "text": "When one of the king is dead" }, { "code": null, "e": 3932, "s": 3896, "text": "When all of player’s pawns are dead" }, { "code": null, "e": 4038, "s": 3932, "text": "Here, if the terminal state is reached, it will return -120 (negative means disadvantage), 120 otherwise." }, { "code": null, "e": 4178, "s": 4038, "text": "In the evaluation function, We will formulate it by considering the pawn’s hp, atk, step, and dead status. Every attributes is weighted by:" }, { "code": null, "e": 4285, "s": 4178, "text": "Weight of HP = 0.3Weight of ATK = 0.1Weight of Step = 0.1Weight of dead’s pawn = 10Weight of King’s HP = 1" }, { "code": null, "e": 4304, "s": 4285, "text": "Weight of HP = 0.3" }, { "code": null, "e": 4324, "s": 4304, "text": "Weight of ATK = 0.1" }, { "code": null, "e": 4345, "s": 4324, "text": "Weight of Step = 0.1" }, { "code": null, "e": 4372, "s": 4345, "text": "Weight of dead’s pawn = 10" }, { "code": null, "e": 4396, "s": 4372, "text": "Weight of King’s HP = 1" }, { "code": null, "e": 4646, "s": 4396, "text": "We give 10 weight to the dead’s pawn because it’s very bad on losing a single pawn in this game. So, we hope by give it a high weight, the AI will avoid dead of its pawn. King is really an important piece here. So, we will give a higher point to it." }, { "code": null, "e": 4794, "s": 4646, "text": "We will define the utility and evaluation function in the AIElements.evaluation_function() function which calls evaluation function in class State." }, { "code": null, "e": 5297, "s": 4794, "text": "Minimax is a decision rule which simulate the decision of a player to find the optimal move for the player. It assumes that the opponent will play with optimal choice too. There are two actors in the Minimax. It’s maximizer and minimizer. The maximizer will search the highest score as possible and the minimizer will search the lowest score as possible. Each players will see the opponent’s move best move and get the best one for him/her. Usually, the searching is represented in tree structure data." }, { "code": null, "e": 5342, "s": 5297, "text": "Here’s the example how the Minimax algorithm" }, { "code": null, "e": 5604, "s": 5342, "text": "Look at Image 1, Max will output B,C,and D actions. First, the minimizer will see the possible action resulted in B . Get the lowest score min(3,12,8) = 3. Then do that to C and D. After that, the Maximizer will pick the highest score. Which is max(3,2,2) = 3 ." }, { "code": null, "e": 5959, "s": 5604, "text": "At our board game, the algorithm will not expand the state/node until terminal state. It will have memory issue or takes very long time to process. We should define a cut-off to our search algorithm by defining the max_depth that limit the node that should be expanded. It will call evaluation function that will calculate the heuristic of the condition." }, { "code": null, "e": 6016, "s": 5959, "text": "Let’s implement it into our EvoPawness (Temporary Name):" }, { "code": null, "e": 6188, "s": 6016, "text": "We will define a class for Minimax algorithm that receive max_depth and player_color as its input. The player_color is a parameter to points out who is the maximizer here." }, { "code": null, "e": 6217, "s": 6188, "text": "Let’s see the Minimax class:" }, { "code": null, "e": 6571, "s": 6217, "text": "As you can see, the Minimax Agent will do Depth First Search with recursive search. It will output the score (best_value) and the best action action key name. It will take the largest score if it’s the maximizer’s turn and take the smallest score if it’s the minimizer’s turn. It will search recursively until terminal state or maximum depth is reached." }, { "code": null, "e": 6653, "s": 6571, "text": "We shuffle the list to make the agent choose action with the same score randomly." }, { "code": null, "e": 6844, "s": 6653, "text": "If you are wondering the type of the action_target, it’s str type. Remember that our game action is a dict type which save the information of the action and the action key name. For example:" }, { "code": null, "e": 6983, "s": 6844, "text": "‘p1a2’: {‘action’: ‘activate’, ‘pawn_atk’: 1, ‘pawn_hp’: 5, ‘pawn_index’: 2, ‘pawn_step’: 1, ‘pawn_x’: 4, ‘pawn_y’: 1, ‘player_index’: 1}," }, { "code": null, "e": 7033, "s": 6983, "text": "We will play with the MinimaxAgent with depth = 4" }, { "code": null, "e": 7099, "s": 7033, "text": "Go to line 52 in controller/game_controller.py and change it into" }, { "code": null, "e": 7157, "s": 7099, "text": "self.ai_agent = MinimaxAgent(max_depth=4, player_color=0)" }, { "code": null, "e": 7184, "s": 7157, "text": "Run the game with your CLI" }, { "code": null, "e": 7203, "s": 7184, "text": "python main_gui.py" }, { "code": null, "e": 7528, "s": 7203, "text": "The AI will prioritize reaching the rune first. Then, activating its pawn. After that attacking our pawn first. If possible, the AI will evolve its pawn into higher type. Of course there’s some flaw such as let our pawn attacking their king. Maybe there is a better evaluation function that can make the AI protect the king." }, { "code": null, "e": 7636, "s": 7528, "text": "If you’ve tried the AI, you will see that the consumed time on choosing the action is very long. Let’s see:" }, { "code": null, "e": 7911, "s": 7636, "text": "As we can see above, as the game progressed, the expanded_node is also increasing because of the number of possible actions. It tends to rise the time of the algorithm as the expanded node increasing. We can see the time on turn 24 is 21 second. Who wants to wait that long?" }, { "code": null, "e": 8256, "s": 7911, "text": "This is the weakness of this algorithm as it will search all of possible state until the desired cut-off or terminal state. Fortunately, it’s possible that we can effectively cut the expanded node. We will be using a technique called pruning to compute the correct Minimax decision without looking at every node. It’s called alpha-beta pruning." }, { "code": null, "e": 8654, "s": 8256, "text": "Alpha Beta Pruning is an optimization technique for Minimax algorithm. This will cut the some nodes that should not be expanded because there is a better move already found. When applied to the Minimax algorithm, it will returns the same action as Minimax would, but it will be more faster. It’s called Alpha Beta Pruning because it needs 2 new parameters for the parameters called Alpha and Beta." }, { "code": null, "e": 8759, "s": 8654, "text": "Alpha : the best value that maximizer can guarantee in the current state or before in the maximizer turn" }, { "code": null, "e": 8866, "s": 8759, "text": "Beta : the best value that minimizer can guarantee in the current state or before it in the minimizer turn" }, { "code": null, "e": 9044, "s": 8866, "text": "The general principle is : given a state s somewhere in the tree. If player has a choice of making action m which is found before s has been found, then s will never be reached." }, { "code": null, "e": 9079, "s": 9044, "text": "Let’s take Image 1 as the example:" }, { "code": null, "e": 9147, "s": 9079, "text": "Remember the searching algorithm is using DFS (Depth First Search)!" }, { "code": null, "e": 9175, "s": 9147, "text": "Let’s dive in step by step:" }, { "code": null, "e": 10958, "s": 9175, "text": "Initialize Alpha to -inf and Beta to Inf. Alpha will be updated if its in the Maximizer turn and Beta is update if its Minimizer turn. They will be passed to the child of the state/node.Expand A (the initial state) possible action. It will produce B,C,D state. start from the first index (B)It’s minimizer B turn. Expand B possible action, go into the child and check its score. Update Beta as minimum as possible. We will find Beta = 3 = min(3,12,8,inf). Alpha is still -inf.It’s assumed that the depth is 2, return the minimum score (which is 3) to the A. Now it’s back to Maximizer turn A, update the Alpha = 3 = max(-inf,3). Then we go to C state/node, the second child:Now go to state C, the minimizer turn C with the passed Alpha parameters 3. In C, we find that the first child’s score that the C found is 2. Update the Beta = 2 = min(inf,2). Now, let’s think. Will the maximizer choose this action? The maximizer has already found better move, which is scored at 3. Of course not, if it’s optimal agent. So, don’t bother check another possible action in the C. This is the pruning process. Return the best score (it’s 2). To make it simpler if beta ≤ alpha then prune it.Maximizer Turn A: calculate max(alpha, 2) = alpha. Check the last child C.Minimizer Turn C : Calculate min(inf,14) , update beta to 14 and check if beta ≤ alpha (14 ≤ 3) and it’s not pruned. Calculate the next child. beta ≤ alpha (5 ≤ 3) and it’s not pruned. At last, check beta ≤ alpha (2 ≤ 3) it should be pruned. Since there are not any child after this node. No node that can be pruned. It can be pruned if the child that returned 2 is found at first. After this, return 2 to A.Maximizer Turn A, calculate max(alpha,2) = alpha. Then it’s done. return 3 as best score that has been found in the tree." }, { "code": null, "e": 11145, "s": 10958, "text": "Initialize Alpha to -inf and Beta to Inf. Alpha will be updated if its in the Maximizer turn and Beta is update if its Minimizer turn. They will be passed to the child of the state/node." }, { "code": null, "e": 11251, "s": 11145, "text": "Expand A (the initial state) possible action. It will produce B,C,D state. start from the first index (B)" }, { "code": null, "e": 11437, "s": 11251, "text": "It’s minimizer B turn. Expand B possible action, go into the child and check its score. Update Beta as minimum as possible. We will find Beta = 3 = min(3,12,8,inf). Alpha is still -inf." }, { "code": null, "e": 11636, "s": 11437, "text": "It’s assumed that the depth is 2, return the minimum score (which is 3) to the A. Now it’s back to Maximizer turn A, update the Alpha = 3 = max(-inf,3). Then we go to C state/node, the second child:" }, { "code": null, "e": 12142, "s": 11636, "text": "Now go to state C, the minimizer turn C with the passed Alpha parameters 3. In C, we find that the first child’s score that the C found is 2. Update the Beta = 2 = min(inf,2). Now, let’s think. Will the maximizer choose this action? The maximizer has already found better move, which is scored at 3. Of course not, if it’s optimal agent. So, don’t bother check another possible action in the C. This is the pruning process. Return the best score (it’s 2). To make it simpler if beta ≤ alpha then prune it." }, { "code": null, "e": 12217, "s": 12142, "text": "Maximizer Turn A: calculate max(alpha, 2) = alpha. Check the last child C." }, { "code": null, "e": 12626, "s": 12217, "text": "Minimizer Turn C : Calculate min(inf,14) , update beta to 14 and check if beta ≤ alpha (14 ≤ 3) and it’s not pruned. Calculate the next child. beta ≤ alpha (5 ≤ 3) and it’s not pruned. At last, check beta ≤ alpha (2 ≤ 3) it should be pruned. Since there are not any child after this node. No node that can be pruned. It can be pruned if the child that returned 2 is found at first. After this, return 2 to A." }, { "code": null, "e": 12748, "s": 12626, "text": "Maximizer Turn A, calculate max(alpha,2) = alpha. Then it’s done. return 3 as best score that has been found in the tree." }, { "code": null, "e": 12799, "s": 12748, "text": "Implement it into the EvoPawness (Temporary Name)." }, { "code": null, "e": 12849, "s": 12799, "text": "This is the class for Minimax Alpha Beta Pruning:" }, { "code": null, "e": 12901, "s": 12849, "text": "(NOTE: the self.node_expanded is for DEBUG purpose)" }, { "code": null, "e": 12991, "s": 12901, "text": "We add alpha and beta as the parameter with default -inf and inf. Then we add these line:" }, { "code": null, "e": 13005, "s": 12991, "text": "For Maximizer" }, { "code": null, "e": 13140, "s": 13005, "text": "alpha = max(alpha, best_value) if beta <= alpha: break" }, { "code": null, "e": 13144, "s": 13140, "text": "And" }, { "code": null, "e": 13158, "s": 13144, "text": "For Minimizer" }, { "code": null, "e": 13291, "s": 13158, "text": "beta = min(beta, best_value) if beta <= alpha: break" }, { "code": null, "e": 13320, "s": 13291, "text": "That’s all, let’s test it 😃!" }, { "code": null, "e": 13372, "s": 13320, "text": "We will play with the MinimaxABAgent with depth = 4" }, { "code": null, "e": 13438, "s": 13372, "text": "Go to line 52 in controller/game_controller.py and change it into" }, { "code": null, "e": 13498, "s": 13438, "text": "self.ai_agent = MinimaxABAgent(max_depth=4, player_color=0)" }, { "code": null, "e": 13594, "s": 13498, "text": "The behavior is the same as the minimax , but faster. Let’s see the running time until turn 24." }, { "code": null, "e": 13847, "s": 13594, "text": "We can see, the time spent is faster without using pruning technique. Until the end, I found that the worst run time on searching the best action is 17s with 2218 expanded node (Turn 66). It’s faster because of the pruning that remove unnecessary node." }, { "code": null, "e": 14055, "s": 13847, "text": "Go on challenge the AI. The AI is very challenging. Sometimes it will target the king in the beginning. I lost once to the AI because of a sudden attack to the king and I didn’t prepare to defend the king 😢." }, { "code": null, "e": 14350, "s": 14055, "text": "Even so, it’s winnable. The AI doesn’t defend the king. I think that it needs more depth in the tree to know it. It will cost longer run time. Well, No one would want to test his/her patience on playing with AI that takes its turn too long (you want to wait a minute or more to wait its turn?)." }, { "code": null, "e": 14745, "s": 14350, "text": "Minimax also does not consider the state other than the state that is found in the chosen depth. Minimax only cares about the state that is found in it. It’s impossible to search all the node to the terminal state from start as it will cause Memory Error. It’s computationally expensive (O(action^depth ) ) This is the weakness of the Minimax, even with the improvement using pruning technique." }, { "code": null, "e": 14909, "s": 14745, "text": "We need some technique that consider the state other than the chosen depth and can also make the AI to choose the action faster. We will see it in the next part 😄." }, { "code": null, "e": 15497, "s": 14909, "text": "We’ve created the Utility and Evaluation Function that is used by Minimax algorithm. Although the performance is good, the Minimax algorithm is so slow. To mend it, we use pruning to the algorithm. It’s called Alpha Beta Pruning. The pattern of the actions is same and it’s faster without using pruning. Even so, the Minimax Alpha Beta Pruning has its flaw. It can only consider and see the movement n turns onward that n needs to be small. If n is large, it will be computationally expensive to choose an action. We need some algorithm that consider further turns and need to be faster." }, { "code": null, "e": 15706, "s": 15497, "text": "Thank you for reading my third article about Artificial Intelligence. I need some constructive feedback to make me better on writing and better knowledge about Artificial Intelligence. Go easy on me please 😆!" }, { "code": null, "e": 15979, "s": 15706, "text": "I just want to share my knowledge to the reader. It’s good to share knowledge as it can be helpful to someone in needs. I’m in the process of learning this field and want to share what I’ve learnt. It’s nice if someone tell me if there’s something wrong with this article." }, { "code": null, "e": 16170, "s": 15979, "text": "Sorry for the bad User Experience (UX) on the GUI 😞. It also has messy and not enough documentation in the code. I hope I have the time to fix it. Maybe someone want to help me on fixing it?" }, { "code": null, "e": 16479, "s": 16170, "text": "Next part (Part 3) will move on into Reinforcement Learning. We will explore kinds of Reinforcement Learning one by one. Before that, I will create an article on how I design the GUI and show the structure of the class in this project. It will be Part 1.5. Hope that I can release the article on this Sunday." }, { "code": null, "e": 16754, "s": 16479, "text": "We will experiment it on the Reinforcement Learning. I’m afraid that It will take a lot time to experiment it. I think, two weeks is the minimum interval that I can publish the articles. Someone want to join me experimenting it? Give me the spirit to write the next part ✌️." }, { "code": null, "e": 16921, "s": 16754, "text": "If you want another article from me like this one, please clap this article 👏 👏. It will boost my spirit to write my next article. I promise to make a better article." }, { "code": null, "e": 16950, "s": 16921, "text": "See you on the next article!" }, { "code": null, "e": 17029, "s": 16950, "text": "Part 1 : Create AI for Your Own Board Game From Scratch — Preparation — Part 1" }, { "code": null, "e": 17104, "s": 17029, "text": "Part 2 : Create AI for Your Own Board Game From Scratch — Minimax — Part 2" }, { "code": null, "e": 17179, "s": 17104, "text": "Part 3 : Create AI for your Own Board Game From Scratch — AlphaZero-Part 3" } ]
How to set the size of the background image with JavaScript?
To set the size of the background image in JavaScript, use the backgroundSize property. It allows you to set the image size for the background. You can try to run the following code to learn how to set the size of the background image: Live Demo <!DOCTYPE html> <html> <head> <style> #box { border: 2px dashed blue; width: 600px; height: 400px; background: url('https://www.tutorialspoint.com/videotutorials/images/coding_ground_home.jpg') no-repeat; } </style> </head> <body> <button onclick="display()">Set size of background image</button> <div id="box"> </div> <script> function display() { document.getElementById("box").style.backgroundSize = "150px 200px"; } </script> </body> </html>
[ { "code": null, "e": 1206, "s": 1062, "text": "To set the size of the background image in JavaScript, use the backgroundSize property. It allows you to set the image size for the background." }, { "code": null, "e": 1298, "s": 1206, "text": "You can try to run the following code to learn how to set the size of the background image:" }, { "code": null, "e": 1308, "s": 1298, "text": "Live Demo" }, { "code": null, "e": 1904, "s": 1308, "text": "<!DOCTYPE html>\n<html>\n <head>\n <style>\n #box {\n border: 2px dashed blue;\n width: 600px;\n height: 400px;\n background: url('https://www.tutorialspoint.com/videotutorials/images/coding_ground_home.jpg') no-repeat;\n }\n </style>\n </head>\n <body>\n <button onclick=\"display()\">Set size of background image</button>\n <div id=\"box\">\n </div>\n <script>\n function display() {\n document.getElementById(\"box\").style.backgroundSize = \"150px 200px\";\n }\n </script>\n </body>\n</html>" } ]
Cohesion in C#
Cohesion in C# shows the relationship within modules. It shows the functional strength of the modules. The greater the cohesion, the better will be the program design. It is the dependency between the modules internal elements like methods and internal modules. High cohesion will allow you to reuse classes and method. An example of High cohesion can be seen in System.Math class i.e.it has Mathematical constants and static methods − Math.Abs Math.PI Math.Pow A class that does a lot of things at a time is hard to understand and maintain. This is what we call low cohesion and should be avoided. If a class will provide functions for email, print, copy, etc time, then it would be hard to maintain and reuse. Always try to achieve strong i.e. high cohesion in your code.
[ { "code": null, "e": 1230, "s": 1062, "text": "Cohesion in C# shows the relationship within modules. It shows the functional strength of the modules. The greater the cohesion, the better will be the program design." }, { "code": null, "e": 1382, "s": 1230, "text": "It is the dependency between the modules internal elements like methods and internal modules. High cohesion will allow you to reuse classes and method." }, { "code": null, "e": 1498, "s": 1382, "text": "An example of High cohesion can be seen in System.Math class i.e.it has Mathematical constants and static methods −" }, { "code": null, "e": 1525, "s": 1498, "text": "Math.Abs\nMath.PI\nMath.Pow\n" }, { "code": null, "e": 1775, "s": 1525, "text": "A class that does a lot of things at a time is hard to understand and maintain. This is what we call low cohesion and should be avoided. If a class will provide functions for email, print, copy, etc time, then it would be hard to maintain and reuse." }, { "code": null, "e": 1837, "s": 1775, "text": "Always try to achieve strong i.e. high cohesion in your code." } ]
How to Make ECDF Plot with ggplot2 in R? - GeeksforGeeks
17 Oct, 2021 Empirical Cumulative Distribution Function Plot (ECDF) helps us to visualize one or more distributions. ECDF plot is a great alternative for histograms and it has the ability to show the full range of data without the need for various parameters. In this article, we will discuss how to draw an ECDF plot using the ggplot2 package of R Programing language. To draw an ECDF plot, we use the stat_ecdf() function of the ggplot2 package of R Language. Syntax: ggplot( df, aes(x)) + stat_ecdf( geom, col ) Parameters: df : determines dataframe used to plot ECDF plot geom: determines the shape of plot, i.e., point, step,etc. col: determines the color of plot In this example, we will create a basic ECDF plot. We will use the ggplot() function and the stat_ecdf() function to plot the ECDF plot. R # set seedset.seed(1234) # create a random data frame sample_data <- data.frame(x = round(rnorm(700, mean=800, sd=450))) # load library ggplot2library(ggplot2) # Basic ECDF plot using ggplot packageggplot(sample_data, aes(x)) + # stat_ecdf() function is used to plot ECDF plotstat_ecdf() Output: To change the color of the ECDF plot we use the col parameter of the stat_ecdf() function. We can add any color as the value of parameter col. We can even use hex codes of color. In this example, we have a green-colored ECDF plot made using stat_ecdf() function with the col parameter being green. R # set seedset.seed(1234) # create a random data frame sample_data <- data.frame(x = round(rnorm(700, mean=800, sd=450))) # load library ggplot2library(ggplot2) # Basic ECDF plot using ggplot packageggplot(sample_data, aes(x)) + # stat_ecdf() function is used to plot ECDF plot# col parameter is used to color plot as greenstat_ecdf(col="green") Output: To change the shape of the ECDF plot we use the geom parameter of the stat_ecdf() function. We can add any shape as the value of parameter geom. In this example, we have a stair-shaped ECDF plot made using stat_ecdf() function with the geom parameter being “step”. R # set seedset.seed(1234) # create a random data frame sample_data <- data.frame(x = round(rnorm(20, mean=800, sd=450))) # load library ggplot2library(ggplot2) # Basic ECDF plot using ggplot packageggplot(sample_data, aes(x)) + # stat_ecdf() function is used to plot ECDF plot# geom parameter is used to shape plot as stepstat_ecdf(geom="step") Output: ECDF plot can be used for plotting multiple distributions. To plot multiple ECDF plots, we firstly create a multi-dimension dataset and then use the col parameter of the aes() function to color them according to the group. Here, is a multiple distribution ECDF plots plotted with color by group using col parameter of the aes() function of the ggplot2 package. To create a multi-dimension dataset we will use rnorm() functions with gl() function to group them in 5 columns of size 1000. R # set seedset.seed(1234) # create a random data frame sample_data <- data.frame(x = c(rnorm(1000, 10, 5), rnorm(1000, 20, 10), rnorm(1000, 30, 20), rnorm(1000, 40, 30), rnorm(1000, 50, 30)), group = gl(5, 1000)) # load library ggplot2library(ggplot2) # Basic ECDF plot using ggplot package# col parameter is used to color plot # according to groupggplot(sample_data, aes(x=x, col=group)) + # stat_ecdf() function is used to plot ECDF plotstat_ecdf() Output: Picked R-ggplot R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Change Color of Bars in Barchart using ggplot2 in R How to Change Axis Scales in R Plots? Group by function in R using Dplyr How to Split Column Into Multiple Columns in R DataFrame? How to filter R DataFrame by values in a column? How to import an Excel File into R ? Time Series Analysis in R How to filter R dataframe by multiple conditions? Replace Specific Characters in String in R R - if statement
[ { "code": null, "e": 25242, "s": 25214, "text": "\n17 Oct, 2021" }, { "code": null, "e": 25489, "s": 25242, "text": "Empirical Cumulative Distribution Function Plot (ECDF) helps us to visualize one or more distributions. ECDF plot is a great alternative for histograms and it has the ability to show the full range of data without the need for various parameters." }, { "code": null, "e": 25691, "s": 25489, "text": "In this article, we will discuss how to draw an ECDF plot using the ggplot2 package of R Programing language. To draw an ECDF plot, we use the stat_ecdf() function of the ggplot2 package of R Language." }, { "code": null, "e": 25744, "s": 25691, "text": "Syntax: ggplot( df, aes(x)) + stat_ecdf( geom, col )" }, { "code": null, "e": 25757, "s": 25744, "text": "Parameters: " }, { "code": null, "e": 25806, "s": 25757, "text": "df : determines dataframe used to plot ECDF plot" }, { "code": null, "e": 25865, "s": 25806, "text": "geom: determines the shape of plot, i.e., point, step,etc." }, { "code": null, "e": 25899, "s": 25865, "text": "col: determines the color of plot" }, { "code": null, "e": 26036, "s": 25899, "text": "In this example, we will create a basic ECDF plot. We will use the ggplot() function and the stat_ecdf() function to plot the ECDF plot." }, { "code": null, "e": 26038, "s": 26036, "text": "R" }, { "code": "# set seedset.seed(1234) # create a random data frame sample_data <- data.frame(x = round(rnorm(700, mean=800, sd=450))) # load library ggplot2library(ggplot2) # Basic ECDF plot using ggplot packageggplot(sample_data, aes(x)) + # stat_ecdf() function is used to plot ECDF plotstat_ecdf()", "e": 26415, "s": 26038, "text": null }, { "code": null, "e": 26423, "s": 26415, "text": "Output:" }, { "code": null, "e": 26721, "s": 26423, "text": "To change the color of the ECDF plot we use the col parameter of the stat_ecdf() function. We can add any color as the value of parameter col. We can even use hex codes of color. In this example, we have a green-colored ECDF plot made using stat_ecdf() function with the col parameter being green." }, { "code": null, "e": 26723, "s": 26721, "text": "R" }, { "code": "# set seedset.seed(1234) # create a random data frame sample_data <- data.frame(x = round(rnorm(700, mean=800, sd=450))) # load library ggplot2library(ggplot2) # Basic ECDF plot using ggplot packageggplot(sample_data, aes(x)) + # stat_ecdf() function is used to plot ECDF plot# col parameter is used to color plot as greenstat_ecdf(col=\"green\")", "e": 27115, "s": 26723, "text": null }, { "code": null, "e": 27123, "s": 27115, "text": "Output:" }, { "code": null, "e": 27388, "s": 27123, "text": "To change the shape of the ECDF plot we use the geom parameter of the stat_ecdf() function. We can add any shape as the value of parameter geom. In this example, we have a stair-shaped ECDF plot made using stat_ecdf() function with the geom parameter being “step”." }, { "code": null, "e": 27390, "s": 27388, "text": "R" }, { "code": "# set seedset.seed(1234) # create a random data frame sample_data <- data.frame(x = round(rnorm(20, mean=800, sd=450))) # load library ggplot2library(ggplot2) # Basic ECDF plot using ggplot packageggplot(sample_data, aes(x)) + # stat_ecdf() function is used to plot ECDF plot# geom parameter is used to shape plot as stepstat_ecdf(geom=\"step\")", "e": 27739, "s": 27390, "text": null }, { "code": null, "e": 27747, "s": 27739, "text": "Output:" }, { "code": null, "e": 27971, "s": 27747, "text": "ECDF plot can be used for plotting multiple distributions. To plot multiple ECDF plots, we firstly create a multi-dimension dataset and then use the col parameter of the aes() function to color them according to the group. " }, { "code": null, "e": 28235, "s": 27971, "text": "Here, is a multiple distribution ECDF plots plotted with color by group using col parameter of the aes() function of the ggplot2 package. To create a multi-dimension dataset we will use rnorm() functions with gl() function to group them in 5 columns of size 1000." }, { "code": null, "e": 28237, "s": 28235, "text": "R" }, { "code": "# set seedset.seed(1234) # create a random data frame sample_data <- data.frame(x = c(rnorm(1000, 10, 5), rnorm(1000, 20, 10), rnorm(1000, 30, 20), rnorm(1000, 40, 30), rnorm(1000, 50, 30)), group = gl(5, 1000)) # load library ggplot2library(ggplot2) # Basic ECDF plot using ggplot package# col parameter is used to color plot # according to groupggplot(sample_data, aes(x=x, col=group)) + # stat_ecdf() function is used to plot ECDF plotstat_ecdf()", "e": 28810, "s": 28237, "text": null }, { "code": null, "e": 28818, "s": 28810, "text": "Output:" }, { "code": null, "e": 28825, "s": 28818, "text": "Picked" }, { "code": null, "e": 28834, "s": 28825, "text": "R-ggplot" }, { "code": null, "e": 28845, "s": 28834, "text": "R Language" }, { "code": null, "e": 28943, "s": 28845, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28995, "s": 28943, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 29033, "s": 28995, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 29068, "s": 29033, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 29126, "s": 29068, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 29175, "s": 29126, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 29212, "s": 29175, "text": "How to import an Excel File into R ?" }, { "code": null, "e": 29238, "s": 29212, "text": "Time Series Analysis in R" }, { "code": null, "e": 29288, "s": 29238, "text": "How to filter R dataframe by multiple conditions?" }, { "code": null, "e": 29331, "s": 29288, "text": "Replace Specific Characters in String in R" } ]
Program to find the Discount Percentage in C++
In this problem, we are given two numbers that define the marked price(M) and selling price(S) of a certain product. Our task is to create a program to find the Discount Percentage in C++. Discount is the amount that is deducted from the actual price (marked price) on a product. The formula for discount is, discount = marked price - selling price Discount percentage is the percentage of the price that is deducted from the actual price of the product. The formula for discount percentage is, discount percentage = (discount / marked price ) * 100 Let’s take an example to understand the problem, 240, 180 25% Discount = (240 - 180) = 60 Discount percentage = (60/240)*100 = 25% The formulas for discount and discount percentage are − Discount = marked price - selling price Discount percentage = (discount / marked price ) * 100 Program to illustrate the working of our solution, Live Demo #include <iostream> using namespace std; int main() { float MP = 130, SP = 120; float DP = (float)(((MP - SP) * 100) / MP); printf("The discount percentage on the given product is %.2f\n", DP); return 0; } The discount percentage on the given product is 7.69
[ { "code": null, "e": 1251, "s": 1062, "text": "In this problem, we are given two numbers that define the marked price(M) and selling price(S) of a certain product. Our task is to create a program to\nfind the Discount Percentage in C++." }, { "code": null, "e": 1342, "s": 1251, "text": "Discount is the amount that is deducted from the actual price (marked price) on a product." }, { "code": null, "e": 1371, "s": 1342, "text": "The formula for discount is," }, { "code": null, "e": 1411, "s": 1371, "text": "discount = marked price - selling price" }, { "code": null, "e": 1517, "s": 1411, "text": "Discount percentage is the percentage of the price that is deducted from the actual price of the product." }, { "code": null, "e": 1557, "s": 1517, "text": "The formula for discount percentage is," }, { "code": null, "e": 1612, "s": 1557, "text": "discount percentage = (discount / marked price ) * 100" }, { "code": null, "e": 1661, "s": 1612, "text": "Let’s take an example to understand the problem," }, { "code": null, "e": 1670, "s": 1661, "text": "240, 180" }, { "code": null, "e": 1674, "s": 1670, "text": "25%" }, { "code": null, "e": 1743, "s": 1674, "text": "Discount = (240 - 180) = 60\nDiscount percentage = (60/240)*100 = 25%" }, { "code": null, "e": 1799, "s": 1743, "text": "The formulas for discount and discount percentage are −" }, { "code": null, "e": 1894, "s": 1799, "text": "Discount = marked price - selling price\nDiscount percentage = (discount / marked price ) * 100" }, { "code": null, "e": 1945, "s": 1894, "text": "Program to illustrate the working of our solution," }, { "code": null, "e": 1956, "s": 1945, "text": " Live Demo" }, { "code": null, "e": 2174, "s": 1956, "text": "#include <iostream>\nusing namespace std;\nint main() {\n float MP = 130, SP = 120;\n float DP = (float)(((MP - SP) * 100) / MP);\n printf(\"The discount percentage on the given product is %.2f\\n\", DP);\n return 0;\n}" }, { "code": null, "e": 2227, "s": 2174, "text": "The discount percentage on the given product is 7.69" } ]
Count ways to express a number as sum of consecutive numbers in C++
Given an integer n as input. The goal is to find the number of ways in which we can represent ‘num’ as the sum of two or more consecutive natural numbers. For example, if n is 3 it can be represented as sum ( 1+2 ) so total 1 way. For Example num=6 Count of ways to express a number as sum of consecutive numbers are: 1 The ways in which we can express ‘num’ as sum of consecutive natural numbers: 1+2+3 num=19 Count of ways to express a number as sum of consecutive numbers are: 1 The ways in which we can express ‘num’ as sum of consecutive natural numbers: 9+10 Approach used in the below program is as follows − In this approach we will represent the number as the sum of ( a + a+1 + a+2.....+ a+i ). Which becomes (a)(L+1) times + 1+2+3+4...+i = a*(i+1) + i*(i+1)/2. (sum of i natural numbers) num=a*(i+1) + i*(i+1)/2.a= [ num − (i)*(i+1)/2 ] / (i+1) We will do this for i=1 to i*(i+1)/2 is less than num. Take an integer num as input. Take an integer num as input. Function sum_consecutive(int num) takes a num and returns the count of ways to express ‘num’ as sum of consecutive natural numbers. Function sum_consecutive(int num) takes a num and returns the count of ways to express ‘num’ as sum of consecutive natural numbers. Take the initial count as 0. Take the initial count as 0. Take temporary variable res as float. Take temporary variable res as float. Using for loop traverse from i=1 to i*(i+1)/2 < num. Using for loop traverse from i=1 to i*(i+1)/2 < num. Calculate the value [ num − (i)*(i+1)/2 ] / (i+1) and store in res. Calculate the value [ num − (i)*(i+1)/2 ] / (i+1) and store in res. If res is integer ( res − (int)res is 0 ) then increment count. If res is integer ( res − (int)res is 0 ) then increment count. At the end we have count as ways in which num can be represented as the sum of consecutive natural numbers. At the end we have count as ways in which num can be represented as the sum of consecutive natural numbers. Return count as result. Return count as result. Live Demo #include <bits/stdc++.h> using namespace std; int sum_consecutive(int num){ int count = 0; int temp = num * 2; float res; for (int i = 1; i * (i + 1) < temp; i++){ int store = i + 1; res = (1.0 * num−(i * (i + 1)) / 2) / store; float check = res − (int)res; if(check == 0.0){ count++; } } return count; } int main(){ int num = 20; cout<<"Count of ways to express a number as sum of consecutive numbers are: "<<sum_consecutive(num) << endl; return 0; } If we run the above code it will generate the following output − Count of ways to express a number as sum of consecutive numbers are: 1
[ { "code": null, "e": 1293, "s": 1062, "text": "Given an integer n as input. The goal is to find the number of ways in which we can represent ‘num’ as the sum of two or more consecutive natural numbers. For example, if n is 3 it can be represented as sum ( 1+2 ) so total 1 way." }, { "code": null, "e": 1305, "s": 1293, "text": "For Example" }, { "code": null, "e": 1311, "s": 1305, "text": "num=6" }, { "code": null, "e": 1382, "s": 1311, "text": "Count of ways to express a number as sum of consecutive numbers are: 1" }, { "code": null, "e": 1466, "s": 1382, "text": "The ways in which we can express ‘num’ as sum of consecutive natural\nnumbers: 1+2+3" }, { "code": null, "e": 1473, "s": 1466, "text": "num=19" }, { "code": null, "e": 1544, "s": 1473, "text": "Count of ways to express a number as sum of consecutive numbers are: 1" }, { "code": null, "e": 1627, "s": 1544, "text": "The ways in which we can express ‘num’ as sum of consecutive natural\nnumbers: 9+10" }, { "code": null, "e": 1678, "s": 1627, "text": "Approach used in the below program is as follows −" }, { "code": null, "e": 1767, "s": 1678, "text": "In this approach we will represent the number as the sum of ( a + a+1 + a+2.....+ a+i )." }, { "code": null, "e": 1918, "s": 1767, "text": "Which becomes (a)(L+1) times + 1+2+3+4...+i = a*(i+1) + i*(i+1)/2. (sum of i natural numbers) num=a*(i+1) + i*(i+1)/2.a= [ num − (i)*(i+1)/2 ] / (i+1)" }, { "code": null, "e": 1973, "s": 1918, "text": "We will do this for i=1 to i*(i+1)/2 is less than num." }, { "code": null, "e": 2003, "s": 1973, "text": "Take an integer num as input." }, { "code": null, "e": 2033, "s": 2003, "text": "Take an integer num as input." }, { "code": null, "e": 2165, "s": 2033, "text": "Function sum_consecutive(int num) takes a num and returns the count of ways to express ‘num’ as sum of consecutive natural numbers." }, { "code": null, "e": 2297, "s": 2165, "text": "Function sum_consecutive(int num) takes a num and returns the count of ways to express ‘num’ as sum of consecutive natural numbers." }, { "code": null, "e": 2326, "s": 2297, "text": "Take the initial count as 0." }, { "code": null, "e": 2355, "s": 2326, "text": "Take the initial count as 0." }, { "code": null, "e": 2393, "s": 2355, "text": "Take temporary variable res as float." }, { "code": null, "e": 2431, "s": 2393, "text": "Take temporary variable res as float." }, { "code": null, "e": 2484, "s": 2431, "text": "Using for loop traverse from i=1 to i*(i+1)/2 < num." }, { "code": null, "e": 2537, "s": 2484, "text": "Using for loop traverse from i=1 to i*(i+1)/2 < num." }, { "code": null, "e": 2605, "s": 2537, "text": "Calculate the value [ num − (i)*(i+1)/2 ] / (i+1) and store in res." }, { "code": null, "e": 2673, "s": 2605, "text": "Calculate the value [ num − (i)*(i+1)/2 ] / (i+1) and store in res." }, { "code": null, "e": 2737, "s": 2673, "text": "If res is integer ( res − (int)res is 0 ) then increment count." }, { "code": null, "e": 2801, "s": 2737, "text": "If res is integer ( res − (int)res is 0 ) then increment count." }, { "code": null, "e": 2909, "s": 2801, "text": "At the end we have count as ways in which num can be represented as the sum of consecutive natural numbers." }, { "code": null, "e": 3017, "s": 2909, "text": "At the end we have count as ways in which num can be represented as the sum of consecutive natural numbers." }, { "code": null, "e": 3041, "s": 3017, "text": "Return count as result." }, { "code": null, "e": 3065, "s": 3041, "text": "Return count as result." }, { "code": null, "e": 3076, "s": 3065, "text": " Live Demo" }, { "code": null, "e": 3594, "s": 3076, "text": "#include <bits/stdc++.h>\nusing namespace std;\nint sum_consecutive(int num){\n int count = 0;\n int temp = num * 2;\n float res;\n for (int i = 1; i * (i + 1) < temp; i++){\n int store = i + 1;\n res = (1.0 * num−(i * (i + 1)) / 2) / store;\n float check = res − (int)res;\n if(check == 0.0){\n count++;\n }\n }\n return count;\n}\nint main(){\n int num = 20;\n cout<<\"Count of ways to express a number as sum of consecutive numbers are: \"<<sum_consecutive(num) << endl;\n return 0;\n}" }, { "code": null, "e": 3659, "s": 3594, "text": "If we run the above code it will generate the following output −" }, { "code": null, "e": 3730, "s": 3659, "text": "Count of ways to express a number as sum of consecutive numbers are: 1" } ]
How to write functions in Python that accept any number of arguments
You want to write a function that accepts any number of input arguments. The * argument in python can accepts any number of arguments. We will understand this with an example of finding out the average of any given two or more numbers. In the below example, rest_arg is a tuple of all the extra arguments (in our case numbers) passed. The function treats the arguments as a sequence in performing average calculation. # Sample function to find the average of the given numbers def define_average(first_arg, *rest_arg): average = (first_arg + sum(rest_arg)) / (1 + len(rest_arg)) print(f"Output \n *** The average for the given numbers {average}") # Call the function with two numbers define_average(1, 2) *** The average for the given numbers 1.5 # Call the function with more numbers define_average(1, 2, 3, 4) *** The average for the given numbers 2.5 To accept any number of keyword arguments, use an argument that starts with **. def player_stats(player_name, player_country, **player_titles): print(f"Output \n*** Type of player_titles - {type(player_titles)}") titles = ' AND '.join('{} : {}'.format(key, value) for key, value in player_titles.items()) print(f"*** Type of titles post conversion - {type(titles)}") stats = 'The player - {name} from {country} has {titles}'.format(name = player_name, country=player_country, titles=titles) return stats player_stats('Roger Federer','Switzerland', Grandslams = 20, ATP = 103) *** Type of player_titles - <class 'dict'> *** Type of titles post conversion - <class 'str'> 'The player - Roger Federer from Switzerland has Grandslams : 20 AND ATP : 103' Here in above example, player_titles is a dictionary that holds the passed keyword arguments. If you want a function that can accept both any number of positional and keyword-only arguments, use * and ** together def func_anyargs(*args, **kwargs): print(args) # A tuple print(kwargs) # A dict With this function, all of the positional arguments are placed into a tuple args, and all of the keyword arguments are placed into a dictionary kwargs.
[ { "code": null, "e": 1135, "s": 1062, "text": "You want to write a function that accepts any number of input arguments." }, { "code": null, "e": 1480, "s": 1135, "text": "The * argument in python can accepts any number of arguments. We will understand this with an example of finding out the average of any given two or more numbers. In the below example, rest_arg is a tuple of all the extra arguments (in our case numbers) passed. The function treats the arguments as a sequence in performing average calculation." }, { "code": null, "e": 1768, "s": 1480, "text": "# Sample function to find the average of the given numbers\ndef define_average(first_arg, *rest_arg):\naverage = (first_arg + sum(rest_arg)) / (1 + len(rest_arg))\nprint(f\"Output \\n *** The average for the given numbers {average}\")\n\n# Call the function with two numbers\ndefine_average(1, 2)" }, { "code": null, "e": 1810, "s": 1768, "text": "*** The average for the given numbers 1.5" }, { "code": null, "e": 1875, "s": 1810, "text": "# Call the function with more numbers\ndefine_average(1, 2, 3, 4)" }, { "code": null, "e": 1917, "s": 1875, "text": "*** The average for the given numbers 2.5" }, { "code": null, "e": 1997, "s": 1917, "text": "To accept any number of keyword arguments, use an argument that starts with **." }, { "code": null, "e": 2495, "s": 1997, "text": "def player_stats(player_name, player_country, **player_titles):\nprint(f\"Output \\n*** Type of player_titles - {type(player_titles)}\")\ntitles = ' AND '.join('{} : {}'.format(key, value) for key, value in player_titles.items())\n\nprint(f\"*** Type of titles post conversion - {type(titles)}\")\nstats = 'The player - {name} from {country} has {titles}'.format(name = player_name,\ncountry=player_country,\ntitles=titles)\nreturn stats\n\nplayer_stats('Roger Federer','Switzerland', Grandslams = 20, ATP = 103)" }, { "code": null, "e": 2589, "s": 2495, "text": "*** Type of player_titles - <class 'dict'>\n*** Type of titles post conversion - <class 'str'>" }, { "code": null, "e": 2669, "s": 2589, "text": "'The player - Roger Federer from Switzerland has Grandslams : 20 AND ATP : 103'" }, { "code": null, "e": 2763, "s": 2669, "text": "Here in above example, player_titles is a dictionary that holds the passed keyword arguments." }, { "code": null, "e": 2882, "s": 2763, "text": "If you want a function that can accept both any number of positional and keyword-only arguments, use * and ** together" }, { "code": null, "e": 2962, "s": 2882, "text": "def func_anyargs(*args, **kwargs):\nprint(args) # A tuple\nprint(kwargs) # A dict" }, { "code": null, "e": 3114, "s": 2962, "text": "With this function, all of the positional arguments are placed into a tuple args, and all of the keyword arguments are placed into a dictionary kwargs." } ]
Erlang - spawn
This is used to create a new process and initialize it. spawn(Function) Function − The function which needs to be spawned. Function − The function which needs to be spawned. This method returns a process id. -module(helloworld). -export([start/0]). start() -> spawn(fun() -> server("Hello") end). server(Message) -> io:fwrite("~p",[Message]). When we run the above program, we will get the following result. “Hello” Print Add Notes Bookmark this page
[ { "code": null, "e": 2357, "s": 2301, "text": "This is used to create a new process and initialize it." }, { "code": null, "e": 2374, "s": 2357, "text": "spawn(Function)\n" }, { "code": null, "e": 2425, "s": 2374, "text": "Function − The function which needs to be spawned." }, { "code": null, "e": 2476, "s": 2425, "text": "Function − The function which needs to be spawned." }, { "code": null, "e": 2510, "s": 2476, "text": "This method returns a process id." }, { "code": null, "e": 2656, "s": 2510, "text": "-module(helloworld). \n-export([start/0]). \n\nstart() ->\n spawn(fun() -> server(\"Hello\") end). \n\nserver(Message) ->\n io:fwrite(\"~p\",[Message])." }, { "code": null, "e": 2721, "s": 2656, "text": "When we run the above program, we will get the following result." }, { "code": null, "e": 2730, "s": 2721, "text": "“Hello”\n" }, { "code": null, "e": 2737, "s": 2730, "text": " Print" }, { "code": null, "e": 2748, "s": 2737, "text": " Add Notes" } ]
Algorithms | Sorting | Question 1 - GeeksforGeeks
28 Jun, 2021 What is recurrence for worst case of QuickSort and what is the time complexity in Worst case?(A) Recurrence is T(n) = T(n-2) + O(n) and time complexity is O(n^2)(B) Recurrence is T(n) = T(n-1) + O(n) and time complexity is O(n^2)(C) Recurrence is T(n) = 2T(n/2) + O(n) and time complexity is O(nLogn)(D) Recurrence is T(n) = T(n/10) + T(9n/10) + O(n) and time complexity is O(nLogn)Answer: (B)Explanation: The worst case of QuickSort occurs when the picked pivot is always one of the corner elements in sorted array. In worst case, QuickSort recursively calls one subproblem with size 0 and other subproblem with size (n-1). So recurrence is T(n) = T(n-1) + T(0) + O(n) The above expression can be rewritten as T(n) = T(n-1) + O(n) void exchange(int *a, int *b){ int temp; temp = *a; *a = *b; *b = temp;} int partition(int arr[], int si, int ei){ int x = arr[ei]; int i = (si - 1); int j; for (j = si; j <= ei - 1; j++) { if(arr[j] <= x) { i++; exchange(&arr[i], &arr[j]); } } exchange (&arr[i + 1], &arr[ei]); return (i + 1);} /* Implementation of Quick Sortarr[] --> Array to be sortedsi --> Starting indexei --> Ending index*/void quickSort(int arr[], int si, int ei){ int pi; /* Partitioning index */ if(si < ei) { pi = partition(arr, si, ei); quickSort(arr, si, pi - 1); quickSort(arr, pi + 1, ei); }} Quiz of this Question Algorithms-Sorting-Quiz Sorting Quiz Algorithms Quiz Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Algorithms | Backtracking | Question 1 Algorithms | Dynamic Programming | Question 2 Algorithms | Greedy Algorithms | Question 1 Algorithms | Dynamic Programming | Question 3 Algorithms Quiz | Dynamic Programming | Question 8 Algorithms | Dynamic Programming | Question 7 Algorithms | Graph Traversals | Question 12 Algorithms | Analysis of Algorithms | Question 17 Algorithms | Graph Traversals | Question 8 Algorithms | Dynamic Programming | Question 7
[ { "code": null, "e": 23845, "s": 23817, "text": "\n28 Jun, 2021" }, { "code": null, "e": 24487, "s": 23845, "text": "What is recurrence for worst case of QuickSort and what is the time complexity in Worst case?(A) Recurrence is T(n) = T(n-2) + O(n) and time complexity is O(n^2)(B) Recurrence is T(n) = T(n-1) + O(n) and time complexity is O(n^2)(C) Recurrence is T(n) = 2T(n/2) + O(n) and time complexity is O(nLogn)(D) Recurrence is T(n) = T(n/10) + T(9n/10) + O(n) and time complexity is O(nLogn)Answer: (B)Explanation: The worst case of QuickSort occurs when the picked pivot is always one of the corner elements in sorted array. In worst case, QuickSort recursively calls one subproblem with size 0 and other subproblem with size (n-1). So recurrence is" }, { "code": null, "e": 24515, "s": 24487, "text": "T(n) = T(n-1) + T(0) + O(n)" }, { "code": null, "e": 24556, "s": 24515, "text": "The above expression can be rewritten as" }, { "code": null, "e": 24577, "s": 24556, "text": "T(n) = T(n-1) + O(n)" }, { "code": "void exchange(int *a, int *b){ int temp; temp = *a; *a = *b; *b = temp;} int partition(int arr[], int si, int ei){ int x = arr[ei]; int i = (si - 1); int j; for (j = si; j <= ei - 1; j++) { if(arr[j] <= x) { i++; exchange(&arr[i], &arr[j]); } } exchange (&arr[i + 1], &arr[ei]); return (i + 1);} /* Implementation of Quick Sortarr[] --> Array to be sortedsi --> Starting indexei --> Ending index*/void quickSort(int arr[], int si, int ei){ int pi; /* Partitioning index */ if(si < ei) { pi = partition(arr, si, ei); quickSort(arr, si, pi - 1); quickSort(arr, pi + 1, ei); }}", "e": 25215, "s": 24577, "text": null }, { "code": null, "e": 25237, "s": 25215, "text": "Quiz of this Question" }, { "code": null, "e": 25261, "s": 25237, "text": "Algorithms-Sorting-Quiz" }, { "code": null, "e": 25274, "s": 25261, "text": "Sorting Quiz" }, { "code": null, "e": 25290, "s": 25274, "text": "Algorithms Quiz" }, { "code": null, "e": 25388, "s": 25290, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25397, "s": 25388, "text": "Comments" }, { "code": null, "e": 25410, "s": 25397, "text": "Old Comments" }, { "code": null, "e": 25449, "s": 25410, "text": "Algorithms | Backtracking | Question 1" }, { "code": null, "e": 25495, "s": 25449, "text": "Algorithms | Dynamic Programming | Question 2" }, { "code": null, "e": 25539, "s": 25495, "text": "Algorithms | Greedy Algorithms | Question 1" }, { "code": null, "e": 25585, "s": 25539, "text": "Algorithms | Dynamic Programming | Question 3" }, { "code": null, "e": 25636, "s": 25585, "text": "Algorithms Quiz | Dynamic Programming | Question 8" }, { "code": null, "e": 25682, "s": 25636, "text": "Algorithms | Dynamic Programming | Question 7" }, { "code": null, "e": 25726, "s": 25682, "text": "Algorithms | Graph Traversals | Question 12" }, { "code": null, "e": 25776, "s": 25726, "text": "Algorithms | Analysis of Algorithms | Question 17" }, { "code": null, "e": 25819, "s": 25776, "text": "Algorithms | Graph Traversals | Question 8" } ]
Convert to Strictly increasing integer array with minimum changes in C++
In this tutorial, we will be discussing a program to convert to strictly increasing integer array with minimum changes. For this we will be provided with an array. Our task is to change the elements of the array to be in strictly increasing order by minimum number of changes in the elements. Live Demo #include <bits/stdc++.h> using namespace std; //calculating number of changes required int remove_min(int arr[], int n){ int LIS[n], len = 0; for (int i = 0; i < n; i++) LIS[i] = 1; for (int i = 1; i < n; i++) { for (int j = 0; j < i; j++) { if (arr[i] > arr[j] && (i-j)<=(arr[i]-arr[j])){ LIS[i] = max(LIS[i], LIS[j] + 1); } } len = max(len, LIS[i]); } //returning the changes required return n - len; } int main(){ int arr[] = { 1, 2, 6, 5, 4 }; int n = sizeof(arr) / sizeof(arr[0]); cout << remove_min(arr, n); return 0; } 2
[ { "code": null, "e": 1182, "s": 1062, "text": "In this tutorial, we will be discussing a program to convert to strictly increasing integer array with minimum changes." }, { "code": null, "e": 1355, "s": 1182, "text": "For this we will be provided with an array. Our task is to change the elements of the array to be in strictly increasing order by minimum number of changes in the elements." }, { "code": null, "e": 1366, "s": 1355, "text": " Live Demo" }, { "code": null, "e": 1976, "s": 1366, "text": "#include <bits/stdc++.h>\nusing namespace std;\n//calculating number of changes required\nint remove_min(int arr[], int n){\n int LIS[n], len = 0;\n for (int i = 0; i < n; i++)\n LIS[i] = 1;\n for (int i = 1; i < n; i++) {\n for (int j = 0; j < i; j++) {\n if (arr[i] > arr[j] && (i-j)<=(arr[i]-arr[j])){\n LIS[i] = max(LIS[i], LIS[j] + 1);\n }\n }\n len = max(len, LIS[i]);\n }\n //returning the changes required\n return n - len;\n}\nint main(){\n int arr[] = { 1, 2, 6, 5, 4 };\n int n = sizeof(arr) / sizeof(arr[0]);\n cout << remove_min(arr, n);\n return 0;\n}" }, { "code": null, "e": 1978, "s": 1976, "text": "2" } ]
Dice Throw | DP-30 - GeeksforGeeks
24 Feb, 2022 Given n dice each with m faces, numbered from 1 to m, find the number of ways to get sum X. X is the summation of values on each face when all the dice are thrown. The Naive approach is to find all the possible combinations of values from n dice and keep on counting the results that sum to X. This problem can be efficiently solved using Dynamic Programming (DP). Let the function to find X from n dice is: Sum(m, n, X) The function can be represented as: Sum(m, n, X) = Finding Sum (X - 1) from (n - 1) dice plus 1 from nth dice + Finding Sum (X - 2) from (n - 1) dice plus 2 from nth dice + Finding Sum (X - 3) from (n - 1) dice plus 3 from nth dice ................................................... ................................................... ................................................... + Finding Sum (X - m) from (n - 1) dice plus m from nth dice So we can recursively write Sum(m, n, x) as following Sum(m, n, X) = Sum(m, n - 1, X - 1) + Sum(m, n - 1, X - 2) + .................... + Sum(m, n - 1, X - m) Why DP approach? The above problem exhibits overlapping subproblems. See the below diagram. Also, see this recursive implementation. Let there be 3 dice, each with 6 faces and we need to find the number of ways to get sum 8: Sum(6, 3, 8) = Sum(6, 2, 7) + Sum(6, 2, 6) + Sum(6, 2, 5) + Sum(6, 2, 4) + Sum(6, 2, 3) + Sum(6, 2, 2) To evaluate Sum(6, 3, 8), we need to evaluate Sum(6, 2, 7) which can recursively written as following: Sum(6, 2, 7) = Sum(6, 1, 6) + Sum(6, 1, 5) + Sum(6, 1, 4) + Sum(6, 1, 3) + Sum(6, 1, 2) + Sum(6, 1, 1) We also need to evaluate Sum(6, 2, 6) which can recursively written as following: Sum(6, 2, 6) = Sum(6, 1, 5) + Sum(6, 1, 4) + Sum(6, 1, 3) + Sum(6, 1, 2) + Sum(6, 1, 1) .............................................. .............................................. Sum(6, 2, 2) = Sum(6, 1, 1) Please take a closer look at the above recursion. The sub-problems in RED are solved first time and sub-problems in BLUE are solved again (exhibit overlapping sub-problems). Hence, storing the results of the solved sub-problems saves time. Following is implementation of Dynamic Programming approach. C++ Java Python3 C# PHP Javascript // C++ program to find number of ways to get sum 'x' with 'n'// dice where every dice has 'm' faces#include <iostream>#include <string.h>using namespace std; // The main function that returns number of ways to get sum 'x'// with 'n' dice and 'm' with m faces.int findWays(int m, int n, int x){ // Create a table to store results of subproblems. One extra // row and column are used for simplicity (Number of dice // is directly used as row index and sum is directly used // as column index). The entries in 0th row and 0th column // are never used. int table[n + 1][x + 1]; memset(table, 0, sizeof(table)); // Initialize all entries as 0 // Table entries for only one dice for (int j = 1; j <= m && j <= x; j++) table[1][j] = 1; // Fill rest of the entries in table using recursive relation // i: number of dice, j: sum for (int i = 2; i <= n; i++) for (int j = 1; j <= x; j++) for (int k = 1; k <= m && k < j; k++) table[i][j] += table[i-1][j-k]; /* Uncomment these lines to see content of table for (int i = 0; i <= n; i++) { for (int j = 0; j <= x; j++) cout << table[i][j] << " "; cout << endl; } */ return table[n][x];} // Driver program to test above functionsint main(){ cout << findWays(4, 2, 1) << endl; cout << findWays(2, 2, 3) << endl; cout << findWays(6, 3, 8) << endl; cout << findWays(4, 2, 5) << endl; cout << findWays(4, 3, 5) << endl; return 0;} // Java program to find number of ways to get sum 'x' with 'n'// dice where every dice has 'm' facesimport java.util.*;import java.lang.*;import java.io.*; class GFG { /* The main function that returns the number of ways to get sum 'x' with 'n' dice and 'm' with m faces. */ public static long findWays(int m, int n, int x){ /* Create a table to store the results of subproblems. One extra row and column are used for simplicity (Number of dice is directly used as row index and sum is directly used as column index). The entries in 0th row and 0th column are never used. */ long[][] table = new long[n+1][x+1]; /* Table entries for only one dice */ for(int j = 1; j <= m && j <= x; j++) table[1][j] = 1; /* Fill rest of the entries in table using recursive relation i: number of dice, j: sum */ for(int i = 2; i <= n;i ++){ for(int j = 1; j <= x; j++){ for(int k = 1; k < j && k <= m; k++) table[i][j] += table[i-1][j-k]; } } /* Uncomment these lines to see content of table for(int i = 0; i< n+1; i++){ for(int j = 0; j< x+1; j++) System.out.print(dt[i][j] + " "); System.out.println(); } */ return table[n][x]; } // Driver Code public static void main (String[] args) { System.out.println(findWays(4, 2, 1)); System.out.println(findWays(2, 2, 3)); System.out.println(findWays(6, 3, 8)); System.out.println(findWays(4, 2, 5)); System.out.println(findWays(4, 3, 5)); }} // This code is contributed by MaheshwariPiyush # Python3 program to find the number of ways to get sum 'x' with 'n' dice# where every dice has 'm' faces # The main function that returns number of ways to get sum 'x'# with 'n' dice and 'm' with m faces.def findWays(m,n,x): # Create a table to store results of subproblems. One extra # row and column are used for simplicity (Number of dice # is directly used as row index and sum is directly used # as column index). The entries in 0th row and 0th column # are never used. table=[[0]*(x+1) for i in range(n+1)] #Initialize all entries as 0 for j in range(1,min(m+1,x+1)): #Table entries for only one dice table[1][j]=1 # Fill rest of the entries in table using recursive relation # i: number of dice, j: sum for i in range(2,n+1): for j in range(1,x+1): for k in range(1,min(m+1,j)): table[i][j]+=table[i-1][j-k] #print(dt) # Uncomment above line to see content of table return table[-1][-1] # Driver codeprint(findWays(4,2,1))print(findWays(2,2,3))print(findWays(6,3,8))print(findWays(4,2,5))print(findWays(4,3,5)) # This code is contributed by MaheshwariPiyush // C# program to find number// of ways to get sum 'x'// with 'n' dice where every// dice has 'm' facesusing System; class GFG{// The main function that returns// number of ways to get sum 'x'// with 'n' dice and 'm' with m faces.static int findWays(int m, int n, int x){ // Create a table to store // results of subproblems. // row and column are used // for simplicity (Number // of dice is directly used // as row index and sum is // directly used as column // index). The entries in 0th // row and 0th column are // never used. int[,] table = new int[n + 1, x + 1]; // Initialize all // entries as 0 for (int i = 0; i <= n; i++) for (int j = 0; j <= x; j++) table[i, j] = 0; // Table entries for // only one dice for (int j = 1; j <= m && j <= x; j++) table[1, j] = 1; // Fill rest of the entries // in table using recursive // relation i: number of // dice, j: sum for (int i = 2; i <= n; i++) for (int j = 1; j <= x; j++) for (int k = 1; k <= m && k < j; k++) table[i, j] += table[i - 1, j - k]; /* Uncomment these lines to see content of table for (int i = 0; i <= n; i++) { for (int j = 0; j <= x; j++) cout << table[i][j] << " "; cout << endl; } */ return table[n, x];} // Driver Codepublic static void Main(){ Console.WriteLine(findWays(4, 2, 1)); Console.WriteLine(findWays(2, 2, 3)); Console.WriteLine(findWays(6, 3, 8)); Console.WriteLine(findWays(4, 2, 5)); Console.WriteLine(findWays(4, 3, 5));}} // This code is contributed by mits. <?php// PHP program to find number// of ways to get sum 'x' with// 'n' dice where every dice// has 'm' faces // The main function that returns// number of ways to get sum 'x'// with 'n' dice and 'm' with m faces.function findWays($m, $n, $x){ // Create a table to store results // of subproblems. One extra row // and column are used for // simplicity (Number of dice is // directly used as row index and // sum is directly used as column // index). The entries in 0th row // and 0th column are never used. $table; // Initialize all entries as 0 for ($i = 1; $i < $n + 1; $i++) for ($j = 1; $j < $x + 1; $j++) $table[$i][$j] = 0; // Table entries for // only one dice for ($j = 1; $j <= $m && $j <= $x; $j++) $table[1][$j] = 1; // Fill rest of the entries // in table using recursive // relation i: number of dice, // j: sum for ($i = 2; $i <= $n; $i++) for ($j = 1; $j <= $x; $j++) for ($k = 1; $k <= $m && $k < $j; $k++) $table[$i][$j] += $table[$i - 1][$j - $k]; return $table[$n][$x];} // Driver Codeecho findWays(4, 2, 1). "\n";echo findWays(2, 2, 3). "\n";echo findWays(6, 3, 8). "\n";echo findWays(4, 2, 5). "\n";echo findWays(4, 3, 5). "\n"; // This code is contributed by mits.?> <script>// Javascript program to find number of ways to get sum 'x' with 'n'// dice where every dice has 'm' faces /* The main function that returns the number of ways to get sum 'x' with 'n' dice and 'm' with m faces. */function findWays(m,n,x){ /* Create a table to store the results of subproblems. One extra row and column are used for simplicity (Number of dice is directly used as row index and sum is directly used as column index). The entries in 0th row and 0th column are never used. */ let table = new Array(n+1); for(let i=0;i<(n+1);i++) { table[i]=new Array(x+1); for(let j=0;j<(x+1);j++) { table[i][j]=0; } } /* Table entries for only one dice */ for(let j = 1; j <= m && j <= x; j++) table[1][j] = 1; /* Fill rest of the entries in table using recursive relation i: number of dice, j: sum */ for(let i = 2; i <= n;i ++){ for(let j = 1; j <= x; j++){ for(let k = 1; k < j && k <= m; k++) table[i][j] += table[i-1][j-k]; } } /* Uncomment these lines to see content of table for(int i = 0; i< n+1; i++){ for(int j = 0; j< x+1; j++) System.out.print(dt[i][j] + " "); System.out.println(); } */ return table[n][x];} // Driver Codedocument.write(findWays(4, 2, 1)+"<br>");document.write(findWays(2, 2, 3)+"<br>");document.write(findWays(6, 3, 8)+"<br>");document.write(findWays(4, 2, 5)+"<br>");document.write(findWays(4, 3, 5)+"<br>"); // This code is contributed by rag2127</script> Output : 0 2 21 4 6 Time Complexity: O(m * n * x) where m is number of faces, n is number of dice and x is given sum. Auxiliary Space: O(n * x)We can add the following two conditions at the beginning of findWays() to improve performance of the program for extreme cases (x is too high or x is too low) C++ Java // When x is so high that sum can not go beyond x even when we// get maximum value in every dice throw.if (m*n <= x) return (m*n == x); // When x is too lowif (n >= x) return (n == x); // When x is so high that sum can not go beyond x even when we // get maximum value in every dice throw. if (m*n <= x) return (m*n == x); // When x is too low if (n >= x) return (n == x); // This code is contributed by umadevi9616 With above conditions added, time complexity becomes O(1) when x >= m*n or when x <= n. Following is the implementation of the Optimized Dynamic Programming approach. C++ Java Python3 C# Javascript // C++ program// The main function that returns number of ways to get sum 'x'// with 'n' dice and 'm' with m faces.#include<bits/stdc++.h>using namespace std; long findWays(int f, int d, int s){ // Create a table to store results of subproblems. One extra // row and column are used for simplicity (Number of dice // is directly used as row index and sum is directly used // as column index). The entries in 0th row and 0th column // are never used. long mem[d + 1][s + 1]; memset(mem,0,sizeof mem); // Table entries for no dices // If you do not have any data, then the value must be 0, so the result is 1 mem[0][0] = 1; // Iterate over dices for (int i = 1; i <= d; i++) { // Iterate over sum for (int j = i; j <= s; j++) { // The result is obtained in two ways, pin the current dice and spending 1 of the value, // so we have mem[i-1][j-1] remaining combinations, to find the remaining combinations we // would have to pin the values ??above 1 then we use mem[i][j-1] to sum all combinations // that pin the remaining j-1's. But there is a way, when "j-f-1> = 0" we would be adding // extra combinations, so we remove the combinations that only pin the extrapolated dice face and // subtract the extrapolated combinations. mem[i][j] = mem[i][j - 1] + mem[i - 1][j - 1]; if (j - f - 1 >= 0) mem[i][j] -= mem[i - 1][j - f - 1]; } } return mem[d][s];} // Driver codeint main(void){ cout << findWays(4, 2, 1) << endl; cout << findWays(2, 2, 3) << endl; cout << findWays(6, 3, 8) << endl; cout << findWays(4, 2, 5) << endl; cout << findWays(4, 3, 5) << endl; return 0;} // This code is contributed by ankush_953 /** * The main function that returns number of ways to get sum 'x' * with 'n' dice and 'm' with m faces. * * @author Pedro H. Chaves <pedrohcd@hotmail.com> <https://github.com/pedrohcdo> */public class GFG { /** * Count ways * * @param f * @param d * @param s * @return */ public static long findWays(int f, int d, int s) { // Create a table to store results of subproblems. One extra // row and column are used for simplicity (Number of dice // is directly used as row index and sum is directly used // as column index). The entries in 0th row and 0th column // are never used. long mem[][] = new long[d + 1][s + 1]; // Table entries for no dices // If you do not have any data, then the value must be 0, so the result is 1 mem[0][0] = 1; // Iterate over dices for(int i=1; i<=d; i++) { // Iterate over sum for(int j=i; j<=s; j++) { // The result is obtained in two ways, pin the current dice and spending 1 of the value, // so we have mem[i-1][j-1] remaining combinations, to find the remaining combinations we // would have to pin the values ??above 1 then we use mem[i][j-1] to sum all combinations // that pin the remaining j-1's. But there is a way, when "j-f-1> = 0" we would be adding // extra combinations, so we remove the combinations that only pin the extrapolated dice face and // subtract the extrapolated combinations. mem[i][j] = mem[i][j-1] + mem[i-1][j-1]; if(j-f-1 >= 0) mem[i][j] -= mem[i-1][j-f-1]; } } return mem[d][s]; } /** * Main * * @param args */ public static void main(String[] args) { System.out.println(findWays(4, 2, 1)); System.out.println(findWays(2, 2, 3)); System.out.println(findWays(6, 3, 8)); System.out.println(findWays(4, 2, 5)); System.out.println(findWays(4, 3, 5)); }} # Python program# The main function that returns number of ways to get sum 'x'# with 'n' dice and 'm' with m faces. def findWays(f, d, s): # Create a table to store results of subproblems. One extra # row and column are used for simplicity (Number of dice # is directly used as row index and sum is directly used # as column index). The entries in 0th row and 0th column # are never used. mem = [[0 for i in range(s+1)] for j in range(d+1)] # Table entries for no dices # If you do not have any data, then the value must be 0, so the result is 1 mem[0][0] = 1 # Iterate over dices for i in range(1, d+1): # Iterate over sum for j in range(1, s+1): # The result is obtained in two ways, pin the current dice and spending 1 of the value, # so we have mem[i-1][j-1] remaining combinations, to find the remaining combinations we # would have to pin the values ??above 1 then we use mem[i][j-1] to sum all combinations # that pin the remaining j-1's. But there is a way, when "j-f-1> = 0" we would be adding # extra combinations, so we remove the combinations that only pin the extrapolated dice face and # subtract the extrapolated combinations. mem[i][j] = mem[i][j - 1] + mem[i - 1][j - 1] if j - f - 1 >= 0: mem[i][j] -= mem[i - 1][j - f - 1] return mem[d][s] # Driver code print(findWays(4, 2, 1))print(findWays(2, 2, 3))print(findWays(6, 3, 8))print(findWays(4, 2, 5))print(findWays(4, 3, 5)) # This code is contributed by ankush_953 // C# program// The main function that returns number of ways to get sum 'x'// with 'n' dice and 'm' with m faces.using System; class GFG{ /** * Count ways * * @param f * @param d * @param s * @return */ public static long findWays(int f, int d, int s) { // Create a table to store results of subproblems. One extra // row and column are used for simplicity (Number of dice // is directly used as row index and sum is directly used // as column index). The entries in 0th row and 0th column // are never used. long [,]mem = new long[d + 1,s + 1]; // Table entries for no dices // If you do not have any data, then the value must be 0, so the result is 1 mem[0,0] = 1; // Iterate over dices for(int i = 1; i <= d; i++) { // Iterate over sum for(int j = i; j <= s; j++) { // The result is obtained in two ways, pin the current dice and spending 1 of the value, // so we have mem[i-1,j-1] remaining combinations, to find the remaining combinations we // would have to pin the values ??above 1 then we use mem[i,j-1] to sum all combinations // that pin the remaining j-1's. But there is a way, when "j-f-1> = 0" we would be adding // extra combinations, so we remove the combinations that only pin the extrapolated dice face and // subtract the extrapolated combinations. mem[i,j] = mem[i,j-1] + mem[i-1,j-1]; if(j-f-1 >= 0) mem[i,j] -= mem[i-1,j-f-1]; } } return mem[d,s]; } // Driver code public static void Main(String[] args) { Console.WriteLine(findWays(4, 2, 1)); Console.WriteLine(findWays(2, 2, 3)); Console.WriteLine(findWays(6, 3, 8)); Console.WriteLine(findWays(4, 2, 5)); Console.WriteLine(findWays(4, 3, 5)); }} // This code is contributed by 29AjayKumar <script> // Javascript program// The main function that returns number// of ways to get sum 'x' with 'n' dice// and 'm' with m faces. /** * Count ways * * @param f * @param d * @param s * @return */function findWays(f, d, s){ // Create a table to store results of subproblems. // One extra row and column are used for simplicity // (Number of dice is directly used as row index and // sum is directly used as column index). The entries // in 0th row and 0th column are never used. let mem = new Array(d + 1); for(let i = 0; i < (d + 1); i++) { mem[i] = new Array(s + 1); for(let j = 0; j < s + 1; j++) { mem[i][j] = 0; } } // Table entries for no dices // If you do not have any data, // then the value must be 0, // so the result is 1 mem[0][0] = 1; // Iterate over dices for(let i = 1; i <= d; i++) { // Iterate over sum for(let j = i; j <= s; j++) { // The result is obtained in two ways, // pin the current dice and spending 1 // of the value, so we have mem[i-1][j-1] // remaining combinations, to find the // remaining combinations we would have // to pin the values ??above 1 then we // use mem[i][j-1] to sum all combinations // that pin the remaining j-1's. But there // is a way, when "j-f-1> = 0" we would be // adding extra combinations, so we remove // the combinations that only pin the // extrapolated dice face and subtract the // extrapolated combinations. mem[i][j] = mem[i][j - 1] + mem[i - 1][j - 1]; if (j - f - 1 >= 0) mem[i][j] -= mem[i - 1][j - f - 1]; } } return mem[d][s];} // Driver codedocument.write(findWays(4, 2, 1) + "<br>");document.write(findWays(2, 2, 3) + "<br>");document.write(findWays(6, 3, 8) + "<br>");document.write(findWays(4, 2, 5) + "<br>");document.write(findWays(4, 3, 5) + "<br>"); // This code is contributed by avanitrachhadiya2155 </script> Output : 0 2 21 4 6 Time Complexity: O(n * x) where n is number of dice and x is given sum.Exercise: Extend the above algorithm to find the probability to get Sum > X.This article is compiled by Aashish Barnwal. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above Mithun Kumar MaheshwariPiyush pedrohcd ankush_953 29AjayKumar rag2127 avanitrachhadiya2155 subhammahato348 umadevi9616 simmytarika5 Amazon Dynamic Programming Mathematical Amazon Dynamic Programming Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Bellman–Ford Algorithm | DP-23 Floyd Warshall Algorithm | DP-16 Matrix Chain Multiplication | DP-8 Longest Palindromic Substring | Set 1 Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming) C++ Data Types Write a program to print all permutations of a given string Set in C++ Standard Template Library (STL) Program to find GCD or HCF of two numbers
[ { "code": null, "e": 24728, "s": 24700, "text": "\n24 Feb, 2022" }, { "code": null, "e": 24892, "s": 24728, "text": "Given n dice each with m faces, numbered from 1 to m, find the number of ways to get sum X. X is the summation of values on each face when all the dice are thrown." }, { "code": null, "e": 25022, "s": 24892, "text": "The Naive approach is to find all the possible combinations of values from n dice and keep on counting the results that sum to X." }, { "code": null, "e": 25095, "s": 25022, "text": "This problem can be efficiently solved using Dynamic Programming (DP). " }, { "code": null, "e": 25905, "s": 25095, "text": "Let the function to find X from n dice is: Sum(m, n, X)\nThe function can be represented as:\nSum(m, n, X) = Finding Sum (X - 1) from (n - 1) dice plus 1 from nth dice\n + Finding Sum (X - 2) from (n - 1) dice plus 2 from nth dice\n + Finding Sum (X - 3) from (n - 1) dice plus 3 from nth dice\n ...................................................\n ...................................................\n ...................................................\n + Finding Sum (X - m) from (n - 1) dice plus m from nth dice\n\nSo we can recursively write Sum(m, n, x) as following\nSum(m, n, X) = Sum(m, n - 1, X - 1) + \n Sum(m, n - 1, X - 2) +\n .................... + \n Sum(m, n - 1, X - m)" }, { "code": null, "e": 26131, "s": 25905, "text": "Why DP approach? The above problem exhibits overlapping subproblems. See the below diagram. Also, see this recursive implementation. Let there be 3 dice, each with 6 faces and we need to find the number of ways to get sum 8: " }, { "code": null, "e": 26784, "s": 26133, "text": "Sum(6, 3, 8) = Sum(6, 2, 7) + Sum(6, 2, 6) + Sum(6, 2, 5) + \n Sum(6, 2, 4) + Sum(6, 2, 3) + Sum(6, 2, 2)\n\nTo evaluate Sum(6, 3, 8), we need to evaluate Sum(6, 2, 7) which can \nrecursively written as following:\nSum(6, 2, 7) = Sum(6, 1, 6) + Sum(6, 1, 5) + Sum(6, 1, 4) + \n Sum(6, 1, 3) + Sum(6, 1, 2) + Sum(6, 1, 1)\n\nWe also need to evaluate Sum(6, 2, 6) which can recursively written\nas following:\nSum(6, 2, 6) = Sum(6, 1, 5) + Sum(6, 1, 4) + Sum(6, 1, 3) +\n Sum(6, 1, 2) + Sum(6, 1, 1)\n..............................................\n..............................................\nSum(6, 2, 2) = Sum(6, 1, 1)" }, { "code": null, "e": 27024, "s": 26784, "text": "Please take a closer look at the above recursion. The sub-problems in RED are solved first time and sub-problems in BLUE are solved again (exhibit overlapping sub-problems). Hence, storing the results of the solved sub-problems saves time." }, { "code": null, "e": 27087, "s": 27024, "text": "Following is implementation of Dynamic Programming approach. " }, { "code": null, "e": 27091, "s": 27087, "text": "C++" }, { "code": null, "e": 27096, "s": 27091, "text": "Java" }, { "code": null, "e": 27104, "s": 27096, "text": "Python3" }, { "code": null, "e": 27107, "s": 27104, "text": "C#" }, { "code": null, "e": 27111, "s": 27107, "text": "PHP" }, { "code": null, "e": 27122, "s": 27111, "text": "Javascript" }, { "code": "// C++ program to find number of ways to get sum 'x' with 'n'// dice where every dice has 'm' faces#include <iostream>#include <string.h>using namespace std; // The main function that returns number of ways to get sum 'x'// with 'n' dice and 'm' with m faces.int findWays(int m, int n, int x){ // Create a table to store results of subproblems. One extra // row and column are used for simplicity (Number of dice // is directly used as row index and sum is directly used // as column index). The entries in 0th row and 0th column // are never used. int table[n + 1][x + 1]; memset(table, 0, sizeof(table)); // Initialize all entries as 0 // Table entries for only one dice for (int j = 1; j <= m && j <= x; j++) table[1][j] = 1; // Fill rest of the entries in table using recursive relation // i: number of dice, j: sum for (int i = 2; i <= n; i++) for (int j = 1; j <= x; j++) for (int k = 1; k <= m && k < j; k++) table[i][j] += table[i-1][j-k]; /* Uncomment these lines to see content of table for (int i = 0; i <= n; i++) { for (int j = 0; j <= x; j++) cout << table[i][j] << \" \"; cout << endl; } */ return table[n][x];} // Driver program to test above functionsint main(){ cout << findWays(4, 2, 1) << endl; cout << findWays(2, 2, 3) << endl; cout << findWays(6, 3, 8) << endl; cout << findWays(4, 2, 5) << endl; cout << findWays(4, 3, 5) << endl; return 0;}", "e": 28620, "s": 27122, "text": null }, { "code": "// Java program to find number of ways to get sum 'x' with 'n'// dice where every dice has 'm' facesimport java.util.*;import java.lang.*;import java.io.*; class GFG { /* The main function that returns the number of ways to get sum 'x' with 'n' dice and 'm' with m faces. */ public static long findWays(int m, int n, int x){ /* Create a table to store the results of subproblems. One extra row and column are used for simplicity (Number of dice is directly used as row index and sum is directly used as column index). The entries in 0th row and 0th column are never used. */ long[][] table = new long[n+1][x+1]; /* Table entries for only one dice */ for(int j = 1; j <= m && j <= x; j++) table[1][j] = 1; /* Fill rest of the entries in table using recursive relation i: number of dice, j: sum */ for(int i = 2; i <= n;i ++){ for(int j = 1; j <= x; j++){ for(int k = 1; k < j && k <= m; k++) table[i][j] += table[i-1][j-k]; } } /* Uncomment these lines to see content of table for(int i = 0; i< n+1; i++){ for(int j = 0; j< x+1; j++) System.out.print(dt[i][j] + \" \"); System.out.println(); } */ return table[n][x]; } // Driver Code public static void main (String[] args) { System.out.println(findWays(4, 2, 1)); System.out.println(findWays(2, 2, 3)); System.out.println(findWays(6, 3, 8)); System.out.println(findWays(4, 2, 5)); System.out.println(findWays(4, 3, 5)); }} // This code is contributed by MaheshwariPiyush", "e": 30335, "s": 28620, "text": null }, { "code": "# Python3 program to find the number of ways to get sum 'x' with 'n' dice# where every dice has 'm' faces # The main function that returns number of ways to get sum 'x'# with 'n' dice and 'm' with m faces.def findWays(m,n,x): # Create a table to store results of subproblems. One extra # row and column are used for simplicity (Number of dice # is directly used as row index and sum is directly used # as column index). The entries in 0th row and 0th column # are never used. table=[[0]*(x+1) for i in range(n+1)] #Initialize all entries as 0 for j in range(1,min(m+1,x+1)): #Table entries for only one dice table[1][j]=1 # Fill rest of the entries in table using recursive relation # i: number of dice, j: sum for i in range(2,n+1): for j in range(1,x+1): for k in range(1,min(m+1,j)): table[i][j]+=table[i-1][j-k] #print(dt) # Uncomment above line to see content of table return table[-1][-1] # Driver codeprint(findWays(4,2,1))print(findWays(2,2,3))print(findWays(6,3,8))print(findWays(4,2,5))print(findWays(4,3,5)) # This code is contributed by MaheshwariPiyush", "e": 31508, "s": 30335, "text": null }, { "code": "// C# program to find number// of ways to get sum 'x'// with 'n' dice where every// dice has 'm' facesusing System; class GFG{// The main function that returns// number of ways to get sum 'x'// with 'n' dice and 'm' with m faces.static int findWays(int m, int n, int x){ // Create a table to store // results of subproblems. // row and column are used // for simplicity (Number // of dice is directly used // as row index and sum is // directly used as column // index). The entries in 0th // row and 0th column are // never used. int[,] table = new int[n + 1, x + 1]; // Initialize all // entries as 0 for (int i = 0; i <= n; i++) for (int j = 0; j <= x; j++) table[i, j] = 0; // Table entries for // only one dice for (int j = 1; j <= m && j <= x; j++) table[1, j] = 1; // Fill rest of the entries // in table using recursive // relation i: number of // dice, j: sum for (int i = 2; i <= n; i++) for (int j = 1; j <= x; j++) for (int k = 1; k <= m && k < j; k++) table[i, j] += table[i - 1, j - k]; /* Uncomment these lines to see content of table for (int i = 0; i <= n; i++) { for (int j = 0; j <= x; j++) cout << table[i][j] << \" \"; cout << endl; } */ return table[n, x];} // Driver Codepublic static void Main(){ Console.WriteLine(findWays(4, 2, 1)); Console.WriteLine(findWays(2, 2, 3)); Console.WriteLine(findWays(6, 3, 8)); Console.WriteLine(findWays(4, 2, 5)); Console.WriteLine(findWays(4, 3, 5));}} // This code is contributed by mits.", "e": 33262, "s": 31508, "text": null }, { "code": "<?php// PHP program to find number// of ways to get sum 'x' with// 'n' dice where every dice// has 'm' faces // The main function that returns// number of ways to get sum 'x'// with 'n' dice and 'm' with m faces.function findWays($m, $n, $x){ // Create a table to store results // of subproblems. One extra row // and column are used for // simplicity (Number of dice is // directly used as row index and // sum is directly used as column // index). The entries in 0th row // and 0th column are never used. $table; // Initialize all entries as 0 for ($i = 1; $i < $n + 1; $i++) for ($j = 1; $j < $x + 1; $j++) $table[$i][$j] = 0; // Table entries for // only one dice for ($j = 1; $j <= $m && $j <= $x; $j++) $table[1][$j] = 1; // Fill rest of the entries // in table using recursive // relation i: number of dice, // j: sum for ($i = 2; $i <= $n; $i++) for ($j = 1; $j <= $x; $j++) for ($k = 1; $k <= $m && $k < $j; $k++) $table[$i][$j] += $table[$i - 1][$j - $k]; return $table[$n][$x];} // Driver Codeecho findWays(4, 2, 1). \"\\n\";echo findWays(2, 2, 3). \"\\n\";echo findWays(6, 3, 8). \"\\n\";echo findWays(4, 2, 5). \"\\n\";echo findWays(4, 3, 5). \"\\n\"; // This code is contributed by mits.?>", "e": 34641, "s": 33262, "text": null }, { "code": "<script>// Javascript program to find number of ways to get sum 'x' with 'n'// dice where every dice has 'm' faces /* The main function that returns the number of ways to get sum 'x' with 'n' dice and 'm' with m faces. */function findWays(m,n,x){ /* Create a table to store the results of subproblems. One extra row and column are used for simplicity (Number of dice is directly used as row index and sum is directly used as column index). The entries in 0th row and 0th column are never used. */ let table = new Array(n+1); for(let i=0;i<(n+1);i++) { table[i]=new Array(x+1); for(let j=0;j<(x+1);j++) { table[i][j]=0; } } /* Table entries for only one dice */ for(let j = 1; j <= m && j <= x; j++) table[1][j] = 1; /* Fill rest of the entries in table using recursive relation i: number of dice, j: sum */ for(let i = 2; i <= n;i ++){ for(let j = 1; j <= x; j++){ for(let k = 1; k < j && k <= m; k++) table[i][j] += table[i-1][j-k]; } } /* Uncomment these lines to see content of table for(int i = 0; i< n+1; i++){ for(int j = 0; j< x+1; j++) System.out.print(dt[i][j] + \" \"); System.out.println(); } */ return table[n][x];} // Driver Codedocument.write(findWays(4, 2, 1)+\"<br>\");document.write(findWays(2, 2, 3)+\"<br>\");document.write(findWays(6, 3, 8)+\"<br>\");document.write(findWays(4, 2, 5)+\"<br>\");document.write(findWays(4, 3, 5)+\"<br>\"); // This code is contributed by rag2127</script>", "e": 36323, "s": 34641, "text": null }, { "code": null, "e": 36334, "s": 36323, "text": "Output : " }, { "code": null, "e": 36345, "s": 36334, "text": "0\n2\n21\n4\n6" }, { "code": null, "e": 36443, "s": 36345, "text": "Time Complexity: O(m * n * x) where m is number of faces, n is number of dice and x is given sum." }, { "code": null, "e": 36628, "s": 36443, "text": "Auxiliary Space: O(n * x)We can add the following two conditions at the beginning of findWays() to improve performance of the program for extreme cases (x is too high or x is too low) " }, { "code": null, "e": 36632, "s": 36628, "text": "C++" }, { "code": null, "e": 36637, "s": 36632, "text": "Java" }, { "code": "// When x is so high that sum can not go beyond x even when we// get maximum value in every dice throw.if (m*n <= x) return (m*n == x); // When x is too lowif (n >= x) return (n == x);", "e": 36828, "s": 36637, "text": null }, { "code": " // When x is so high that sum can not go beyond x even when we // get maximum value in every dice throw. if (m*n <= x) return (m*n == x); // When x is too low if (n >= x) return (n == x); // This code is contributed by umadevi9616", "e": 37091, "s": 36828, "text": null }, { "code": null, "e": 37179, "s": 37091, "text": "With above conditions added, time complexity becomes O(1) when x >= m*n or when x <= n." }, { "code": null, "e": 37259, "s": 37179, "text": "Following is the implementation of the Optimized Dynamic Programming approach. " }, { "code": null, "e": 37263, "s": 37259, "text": "C++" }, { "code": null, "e": 37268, "s": 37263, "text": "Java" }, { "code": null, "e": 37276, "s": 37268, "text": "Python3" }, { "code": null, "e": 37279, "s": 37276, "text": "C#" }, { "code": null, "e": 37290, "s": 37279, "text": "Javascript" }, { "code": "// C++ program// The main function that returns number of ways to get sum 'x'// with 'n' dice and 'm' with m faces.#include<bits/stdc++.h>using namespace std; long findWays(int f, int d, int s){ // Create a table to store results of subproblems. One extra // row and column are used for simplicity (Number of dice // is directly used as row index and sum is directly used // as column index). The entries in 0th row and 0th column // are never used. long mem[d + 1][s + 1]; memset(mem,0,sizeof mem); // Table entries for no dices // If you do not have any data, then the value must be 0, so the result is 1 mem[0][0] = 1; // Iterate over dices for (int i = 1; i <= d; i++) { // Iterate over sum for (int j = i; j <= s; j++) { // The result is obtained in two ways, pin the current dice and spending 1 of the value, // so we have mem[i-1][j-1] remaining combinations, to find the remaining combinations we // would have to pin the values ??above 1 then we use mem[i][j-1] to sum all combinations // that pin the remaining j-1's. But there is a way, when \"j-f-1> = 0\" we would be adding // extra combinations, so we remove the combinations that only pin the extrapolated dice face and // subtract the extrapolated combinations. mem[i][j] = mem[i][j - 1] + mem[i - 1][j - 1]; if (j - f - 1 >= 0) mem[i][j] -= mem[i - 1][j - f - 1]; } } return mem[d][s];} // Driver codeint main(void){ cout << findWays(4, 2, 1) << endl; cout << findWays(2, 2, 3) << endl; cout << findWays(6, 3, 8) << endl; cout << findWays(4, 2, 5) << endl; cout << findWays(4, 3, 5) << endl; return 0;} // This code is contributed by ankush_953", "e": 39097, "s": 37290, "text": null }, { "code": "/** * The main function that returns number of ways to get sum 'x' * with 'n' dice and 'm' with m faces. * * @author Pedro H. Chaves <pedrohcd@hotmail.com> <https://github.com/pedrohcdo> */public class GFG { /** * Count ways * * @param f * @param d * @param s * @return */ public static long findWays(int f, int d, int s) { // Create a table to store results of subproblems. One extra // row and column are used for simplicity (Number of dice // is directly used as row index and sum is directly used // as column index). The entries in 0th row and 0th column // are never used. long mem[][] = new long[d + 1][s + 1]; // Table entries for no dices // If you do not have any data, then the value must be 0, so the result is 1 mem[0][0] = 1; // Iterate over dices for(int i=1; i<=d; i++) { // Iterate over sum for(int j=i; j<=s; j++) { // The result is obtained in two ways, pin the current dice and spending 1 of the value, // so we have mem[i-1][j-1] remaining combinations, to find the remaining combinations we // would have to pin the values ??above 1 then we use mem[i][j-1] to sum all combinations // that pin the remaining j-1's. But there is a way, when \"j-f-1> = 0\" we would be adding // extra combinations, so we remove the combinations that only pin the extrapolated dice face and // subtract the extrapolated combinations. mem[i][j] = mem[i][j-1] + mem[i-1][j-1]; if(j-f-1 >= 0) mem[i][j] -= mem[i-1][j-f-1]; } } return mem[d][s]; } /** * Main * * @param args */ public static void main(String[] args) { System.out.println(findWays(4, 2, 1)); System.out.println(findWays(2, 2, 3)); System.out.println(findWays(6, 3, 8)); System.out.println(findWays(4, 2, 5)); System.out.println(findWays(4, 3, 5)); }}", "e": 41187, "s": 39097, "text": null }, { "code": "# Python program# The main function that returns number of ways to get sum 'x'# with 'n' dice and 'm' with m faces. def findWays(f, d, s): # Create a table to store results of subproblems. One extra # row and column are used for simplicity (Number of dice # is directly used as row index and sum is directly used # as column index). The entries in 0th row and 0th column # are never used. mem = [[0 for i in range(s+1)] for j in range(d+1)] # Table entries for no dices # If you do not have any data, then the value must be 0, so the result is 1 mem[0][0] = 1 # Iterate over dices for i in range(1, d+1): # Iterate over sum for j in range(1, s+1): # The result is obtained in two ways, pin the current dice and spending 1 of the value, # so we have mem[i-1][j-1] remaining combinations, to find the remaining combinations we # would have to pin the values ??above 1 then we use mem[i][j-1] to sum all combinations # that pin the remaining j-1's. But there is a way, when \"j-f-1> = 0\" we would be adding # extra combinations, so we remove the combinations that only pin the extrapolated dice face and # subtract the extrapolated combinations. mem[i][j] = mem[i][j - 1] + mem[i - 1][j - 1] if j - f - 1 >= 0: mem[i][j] -= mem[i - 1][j - f - 1] return mem[d][s] # Driver code print(findWays(4, 2, 1))print(findWays(2, 2, 3))print(findWays(6, 3, 8))print(findWays(4, 2, 5))print(findWays(4, 3, 5)) # This code is contributed by ankush_953", "e": 42780, "s": 41187, "text": null }, { "code": "// C# program// The main function that returns number of ways to get sum 'x'// with 'n' dice and 'm' with m faces.using System; class GFG{ /** * Count ways * * @param f * @param d * @param s * @return */ public static long findWays(int f, int d, int s) { // Create a table to store results of subproblems. One extra // row and column are used for simplicity (Number of dice // is directly used as row index and sum is directly used // as column index). The entries in 0th row and 0th column // are never used. long [,]mem = new long[d + 1,s + 1]; // Table entries for no dices // If you do not have any data, then the value must be 0, so the result is 1 mem[0,0] = 1; // Iterate over dices for(int i = 1; i <= d; i++) { // Iterate over sum for(int j = i; j <= s; j++) { // The result is obtained in two ways, pin the current dice and spending 1 of the value, // so we have mem[i-1,j-1] remaining combinations, to find the remaining combinations we // would have to pin the values ??above 1 then we use mem[i,j-1] to sum all combinations // that pin the remaining j-1's. But there is a way, when \"j-f-1> = 0\" we would be adding // extra combinations, so we remove the combinations that only pin the extrapolated dice face and // subtract the extrapolated combinations. mem[i,j] = mem[i,j-1] + mem[i-1,j-1]; if(j-f-1 >= 0) mem[i,j] -= mem[i-1,j-f-1]; } } return mem[d,s]; } // Driver code public static void Main(String[] args) { Console.WriteLine(findWays(4, 2, 1)); Console.WriteLine(findWays(2, 2, 3)); Console.WriteLine(findWays(6, 3, 8)); Console.WriteLine(findWays(4, 2, 5)); Console.WriteLine(findWays(4, 3, 5)); }} // This code is contributed by 29AjayKumar", "e": 44824, "s": 42780, "text": null }, { "code": "<script> // Javascript program// The main function that returns number// of ways to get sum 'x' with 'n' dice// and 'm' with m faces. /** * Count ways * * @param f * @param d * @param s * @return */function findWays(f, d, s){ // Create a table to store results of subproblems. // One extra row and column are used for simplicity // (Number of dice is directly used as row index and // sum is directly used as column index). The entries // in 0th row and 0th column are never used. let mem = new Array(d + 1); for(let i = 0; i < (d + 1); i++) { mem[i] = new Array(s + 1); for(let j = 0; j < s + 1; j++) { mem[i][j] = 0; } } // Table entries for no dices // If you do not have any data, // then the value must be 0, // so the result is 1 mem[0][0] = 1; // Iterate over dices for(let i = 1; i <= d; i++) { // Iterate over sum for(let j = i; j <= s; j++) { // The result is obtained in two ways, // pin the current dice and spending 1 // of the value, so we have mem[i-1][j-1] // remaining combinations, to find the // remaining combinations we would have // to pin the values ??above 1 then we // use mem[i][j-1] to sum all combinations // that pin the remaining j-1's. But there // is a way, when \"j-f-1> = 0\" we would be // adding extra combinations, so we remove // the combinations that only pin the // extrapolated dice face and subtract the // extrapolated combinations. mem[i][j] = mem[i][j - 1] + mem[i - 1][j - 1]; if (j - f - 1 >= 0) mem[i][j] -= mem[i - 1][j - f - 1]; } } return mem[d][s];} // Driver codedocument.write(findWays(4, 2, 1) + \"<br>\");document.write(findWays(2, 2, 3) + \"<br>\");document.write(findWays(6, 3, 8) + \"<br>\");document.write(findWays(4, 2, 5) + \"<br>\");document.write(findWays(4, 3, 5) + \"<br>\"); // This code is contributed by avanitrachhadiya2155 </script>", "e": 46998, "s": 44824, "text": null }, { "code": null, "e": 47009, "s": 46998, "text": "Output : " }, { "code": null, "e": 47020, "s": 47009, "text": "0\n2\n21\n4\n6" }, { "code": null, "e": 47337, "s": 47020, "text": "Time Complexity: O(n * x) where n is number of dice and x is given sum.Exercise: Extend the above algorithm to find the probability to get Sum > X.This article is compiled by Aashish Barnwal. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 47350, "s": 47337, "text": "Mithun Kumar" }, { "code": null, "e": 47367, "s": 47350, "text": "MaheshwariPiyush" }, { "code": null, "e": 47376, "s": 47367, "text": "pedrohcd" }, { "code": null, "e": 47387, "s": 47376, "text": "ankush_953" }, { "code": null, "e": 47399, "s": 47387, "text": "29AjayKumar" }, { "code": null, "e": 47407, "s": 47399, "text": "rag2127" }, { "code": null, "e": 47428, "s": 47407, "text": "avanitrachhadiya2155" }, { "code": null, "e": 47444, "s": 47428, "text": "subhammahato348" }, { "code": null, "e": 47456, "s": 47444, "text": "umadevi9616" }, { "code": null, "e": 47469, "s": 47456, "text": "simmytarika5" }, { "code": null, "e": 47476, "s": 47469, "text": "Amazon" }, { "code": null, "e": 47496, "s": 47476, "text": "Dynamic Programming" }, { "code": null, "e": 47509, "s": 47496, "text": "Mathematical" }, { "code": null, "e": 47516, "s": 47509, "text": "Amazon" }, { "code": null, "e": 47536, "s": 47516, "text": "Dynamic Programming" }, { "code": null, "e": 47549, "s": 47536, "text": "Mathematical" }, { "code": null, "e": 47647, "s": 47549, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 47656, "s": 47647, "text": "Comments" }, { "code": null, "e": 47669, "s": 47656, "text": "Old Comments" }, { "code": null, "e": 47700, "s": 47669, "text": "Bellman–Ford Algorithm | DP-23" }, { "code": null, "e": 47733, "s": 47700, "text": "Floyd Warshall Algorithm | DP-16" }, { "code": null, "e": 47768, "s": 47733, "text": "Matrix Chain Multiplication | DP-8" }, { "code": null, "e": 47806, "s": 47768, "text": "Longest Palindromic Substring | Set 1" }, { "code": null, "e": 47874, "s": 47806, "text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)" }, { "code": null, "e": 47889, "s": 47874, "text": "C++ Data Types" }, { "code": null, "e": 47949, "s": 47889, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 47992, "s": 47949, "text": "Set in C++ Standard Template Library (STL)" } ]
Kibana - Environment Setup
To start working with Kibana we need to install Logstash, Elasticsearch and Kibana. In this chapter, we will try to understand the installation of the ELK stack here. We would discuss the following installations here − Elasticsearch Installation Logstash Installation Kibana Installation A detailed documentation on Elasticsearch exists in our library. You can check here for elasticsearch installation. You will have to follow the steps mentioned in the tutorial to install Elasticsearch. Once done with the installation, start the elasticsearch server as follows − For Windows > cd kibanaproject/elasticsearch-6.5.4/elasticsearch-6.5.4/bin > elasticsearch Please note for windows user, the JAVA_HOME variable has to be set to the java jdk path. For Linux $ cd kibanaproject/elasticsearch-6.5.4/elasticsearch-6.5.4/bin $ elasticsearch The default port for elasticsearch is 9200. Once done, you can check the elasticsearch at port 9200 on localhost http://localhost:9200/as shown below − For Logstash installation, follow this elasticsearch installation which is already existing in our library. Go to the official Kibana site −https://www.elastic.co/products/kibana Click the downloads link on the top right corner and it will display screen as follows − Click the Download button for Kibana. Please note to work with Kibana we need 64 bit machine and it will not work with 32 bit. In this tutorial, we are going to use Kibana version 6. The download option is available for Windows, Mac and Linux. You can download as per your choice. Create a folder and unpack the tar/zip downloads for kibana. We are going to work with sample data uploaded in elasticsearch. Thus, for now let us see how to start elasticsearch and kibana. For this, go to the folder where Kibana is unpacked. For Windows > cd kibanaproject/kibana-6.5.4/kibana-6.5.4/bin > kibana For Linux $ cd kibanaproject/kibana-6.5.4/kibana-6.5.4/bin $ kibana Once Kibana starts, the user can see the following screen − Once you see the ready signal in the console, you can open Kibana in browser using http://localhost:5601/.The default port on which kibana is available is 5601. The user interface of Kibana is as shown here − In our next chapter, we will learn how to use the UI of Kibana. To know the Kibana version on Kibana UI, go to Management Tab on left side and it will display you the Kibana version we are using currently. Print Add Notes Bookmark this page
[ { "code": null, "e": 2272, "s": 2105, "text": "To start working with Kibana we need to install Logstash, Elasticsearch and Kibana. In this chapter, we will try to understand the installation of the ELK stack here." }, { "code": null, "e": 2324, "s": 2272, "text": "We would discuss the following installations here −" }, { "code": null, "e": 2351, "s": 2324, "text": "Elasticsearch Installation" }, { "code": null, "e": 2373, "s": 2351, "text": "Logstash Installation" }, { "code": null, "e": 2393, "s": 2373, "text": "Kibana Installation" }, { "code": null, "e": 2595, "s": 2393, "text": "A detailed documentation on Elasticsearch exists in our library. You can check here for elasticsearch installation. You will have to follow the steps mentioned in the tutorial to install Elasticsearch." }, { "code": null, "e": 2672, "s": 2595, "text": "Once done with the installation, start the elasticsearch server as follows −" }, { "code": null, "e": 2684, "s": 2672, "text": "For Windows" }, { "code": null, "e": 2764, "s": 2684, "text": "> cd kibanaproject/elasticsearch-6.5.4/elasticsearch-6.5.4/bin\n> elasticsearch\n" }, { "code": null, "e": 2853, "s": 2764, "text": "Please note for windows user, the JAVA_HOME variable has to be set to the java jdk path." }, { "code": null, "e": 2863, "s": 2853, "text": "For Linux" }, { "code": null, "e": 2943, "s": 2863, "text": "$ cd kibanaproject/elasticsearch-6.5.4/elasticsearch-6.5.4/bin\n$ elasticsearch\n" }, { "code": null, "e": 3095, "s": 2943, "text": "The default port for elasticsearch is 9200. Once done, you can check the elasticsearch at port 9200 on localhost http://localhost:9200/as shown below −" }, { "code": null, "e": 3203, "s": 3095, "text": "For Logstash installation, follow this elasticsearch installation which is already existing in our library." }, { "code": null, "e": 3274, "s": 3203, "text": "Go to the official Kibana site −https://www.elastic.co/products/kibana" }, { "code": null, "e": 3363, "s": 3274, "text": "Click the downloads link on the top right corner and it will display screen as follows −" }, { "code": null, "e": 3490, "s": 3363, "text": "Click the Download button for Kibana. Please note to work with Kibana we need 64 bit machine and it will not work with 32 bit." }, { "code": null, "e": 3644, "s": 3490, "text": "In this tutorial, we are going to use Kibana version 6. The download option is available for Windows, Mac and Linux. You can download as per your choice." }, { "code": null, "e": 3887, "s": 3644, "text": "Create a folder and unpack the tar/zip downloads for kibana. We are going to work with sample data uploaded in elasticsearch. Thus, for now let us see how to start elasticsearch and kibana. For this, go to the folder where Kibana is unpacked." }, { "code": null, "e": 3899, "s": 3887, "text": "For Windows" }, { "code": null, "e": 3958, "s": 3899, "text": "> cd kibanaproject/kibana-6.5.4/kibana-6.5.4/bin\n> kibana\n" }, { "code": null, "e": 3968, "s": 3958, "text": "For Linux" }, { "code": null, "e": 4027, "s": 3968, "text": "$ cd kibanaproject/kibana-6.5.4/kibana-6.5.4/bin\n$ kibana\n" }, { "code": null, "e": 4087, "s": 4027, "text": "Once Kibana starts, the user can see the following screen −" }, { "code": null, "e": 4248, "s": 4087, "text": "Once you see the ready signal in the console, you can open Kibana in browser using http://localhost:5601/.The default port on which kibana is available is 5601." }, { "code": null, "e": 4296, "s": 4248, "text": "The user interface of Kibana is as shown here −" }, { "code": null, "e": 4502, "s": 4296, "text": "In our next chapter, we will learn how to use the UI of Kibana. To know the Kibana version on Kibana UI, go to Management Tab on left side and it will display you the Kibana version we are using currently." }, { "code": null, "e": 4509, "s": 4502, "text": " Print" }, { "code": null, "e": 4520, "s": 4509, "text": " Add Notes" } ]
Difference between regular functions and arrow functions in JavaScript
According to MDN, An arrow function expression is a syntactically compact alternative to a regular function expression, although without its own bindings to the this, arguments, super, or new.target keywords. Arrow function expressions are ill suited as methods, and they cannot be used as constructors. There are 3 subtle differences in regular functions and arrow functions in JavaScript. Arrow functions do not have their own this value. The value of this inside an arrow function is always inherited from the enclosing scope. this.a = 100; let arrowFunc = () => {this.a = 150}; function regFunc() { this.a = 200; } console.log(this.a) arrowFunc() console.log(this.a) regFunc() console.log(this.a) 100 150 150 See that the arrow function changed the this object outside its scope. The regular function just made the changes within its own this. In JS arguments array in functions is a special object that can be used to get all the arguments passed to the function. Similar to this, arrow functions do not have their own binding to a arguments object, they are bound to arguments of enclosing scope. If a function is constructable, it can be called with new, i.e. new User(). If a function is callable, it can be called without new (i.e. normal function call). Functions created through function declarations / expressions are both constructable and callable. Arrow functions (and methods) are only callable. class constructors are only constructable. If you are trying to call a non-callable function or to construct a non-constructable function, you will get a runtime error. let arrowFunc = () => {} new arrowFunc() This code gives the error: arrowFunc is not a constructor
[ { "code": null, "e": 1366, "s": 1062, "text": "According to MDN, An arrow function expression is a syntactically compact alternative to a regular function expression, although without its own bindings to the this, arguments, super, or new.target keywords. Arrow function expressions are ill suited as methods, and they cannot be used as constructors." }, { "code": null, "e": 1453, "s": 1366, "text": "There are 3 subtle differences in regular functions and arrow functions in JavaScript." }, { "code": null, "e": 1592, "s": 1453, "text": "Arrow functions do not have their own this value. The value of this inside an arrow function is always inherited from the enclosing scope." }, { "code": null, "e": 1766, "s": 1592, "text": "this.a = 100;\nlet arrowFunc = () => {this.a = 150};\nfunction regFunc() {\n this.a = 200;\n}\nconsole.log(this.a)\narrowFunc()\nconsole.log(this.a)\nregFunc()\nconsole.log(this.a)" }, { "code": null, "e": 1778, "s": 1766, "text": "100\n150\n150" }, { "code": null, "e": 1913, "s": 1778, "text": "See that the arrow function changed the this object outside its scope. The regular function just made the changes within its own this." }, { "code": null, "e": 2168, "s": 1913, "text": "In JS arguments array in functions is a special object that can be used to get all the arguments passed to the function. Similar to this, arrow functions do not have their own binding to a arguments object, they are bound to arguments of enclosing scope." }, { "code": null, "e": 2329, "s": 2168, "text": "If a function is constructable, it can be called with new, i.e. new User(). If a function is callable, it can be called without new (i.e. normal function call)." }, { "code": null, "e": 2428, "s": 2329, "text": "Functions created through function declarations / expressions are both constructable and callable." }, { "code": null, "e": 2520, "s": 2428, "text": "Arrow functions (and methods) are only callable. class constructors are only constructable." }, { "code": null, "e": 2646, "s": 2520, "text": "If you are trying to call a non-callable function or to construct a non-constructable function, you will get a runtime error." }, { "code": null, "e": 2745, "s": 2646, "text": "let arrowFunc = () => {}\nnew arrowFunc()\nThis code gives the error:\narrowFunc is not a constructor" } ]
Useful pip commands for Data Science | by Parul Pandey | Towards Data Science
An in-depth article was published in the February of 2020 by Sebastian Raschka et al. that studies the role and importance of Python in the Machine Learning ecosystem. The paper titled Machine Learning in Python: Main Developments and Technology Trends in Data Science, Machine Learning, and Artificial Intelligence put forward a fascinating observation which I’d like to quote here: Historically, a wide range of different programming languages and environments have been used to enable machine learning research and application development. However, as the general-purpose Python language has seen a tremendous growth of popularity within the scientific computing community within the last decade, most recent machine learning and deep learning libraries are now Python-based. Python has truly changed the Data Science landscape and emerged as one of the most used libraries in data science, today. This is also quite evident from the sheer number of python packages being created and used. As of July 2020, over 235,000 Python packages could be accessed through PyPI. So what is PyPI? The Python Package Index (PyPI) is a repository of software for the Python programming language. This repository houses the packages created and shared by the ever-growing Python community. You can install any package from Pypi using pip which is the package installer for Python. Every Python programmer, new or old, uses pip install <package name> multiple times. However, there are other useful pip commands,, especially from a data science perspective which can be extremely useful. This article attempts to explain some of the commonly used pip commands along with their frequently used options. To begin with, we’ll create a virtual environment. This way, it’ll be easier to show the various pip commands in action. Let’s use venv to create this new virtual environment and name it as env.The python’s venv module is used for creating lightweight “virtual environments.” # Creating virtual environment in Mac/Linux python3 -m venv env# Creating virtual environment in Windowspy -m venv env Once the env environment has been created, we’ll activate it, and then we are good to go. Let’s start by checking if pip is installed in our environment or not. Technically, if you are using Python 2 >=2.7.9 or Python 3 >=3.4, pip should be already installed. The pip --version command returns the location as well as the version of the pip installed. Since everything is in place, let’s now look at a few important and most used pip commands, one by one. If you type pip help in your terminal, you’ll get a single-page scrollable document. It displays the various commands that can be used with pip, as well as how the commands can be used. Additionally, if you wish to see details concerning a single pip command, you can do: pip help <command_name>example: pip help <install> This brings up the information on the single commands whose details you are interested in. If want to take a look at all the installed packages, you can do a pip list and it will output all the packages that are currently installed in the environment. pip list The output above shows that currently, we have only two packages installed, and out of them, pip itself belongs to an outdated version. pip list can be used with a bunch of options, for instance: --outdated/ -o for listing all the outdated packages pip list --outdated or pip list -o It looks like both the installed packages are outdated. --uptodate/ -u for listing all the up-to-date packages pip list --uptodate or pip list -u --format selects the output format for displaying installed packages on the screen. The available options are — columns (default), freeze, or JSON. The pip install command is used to install a new package. Let’s install the pandas , the bread and butter package for data science, in our virtual environment. To check whether the pandas' package has been installed or not, we can do a quickpip list to have a look at all the installed packages. We can see that pandas, along with its other dependencies has been installed comfortably in the virtual environment. pip install also has few useful options to be used along. --upgrade/ -U for upgrading all specified packages to the newest available version. --requirement <file>/ -r for installing from the given requirements file. A requirements file is a list of all of a project’s dependencies. This text file contains all the package required including the specific version of each dependency. Here is how a requirement file typically looks like: To install all the packages mentioned in the requirements.txt file, you can simply do: pip install -r requirements.txt This command shows information about the installed packages. One can choose the amount of information to be displayed on the screen. Let’s say we want to know details about the pandas package which we know is installed in our environment. To show limited details, we can do pip show pandas: pip show pandas In case, you want the complete details, you can use the verbose option with the pip show command, pip show --verbose pandas As the name suggests, pip uninstall will uninstall the desired package. As per the documentation, there are few exceptions that cannot be uninstalled. They are: Pure distutils packages installed with python setup.py install, and Script wrappers installed by python setup.py develop. We’ll now uninstall the pandas' package that we had recently installed. The process is pretty straight forward, as follows: pip uninstall pandas pip uninstall has two options, namely: --requirement <file>/ -r for uninstalling packages from the requirements file. --yes / -y . This option if selected doesn’t ask for confirmation during uninstalling a package. In section 3, we touched upon the need for the requirements file in a project. Well, pip freeze lets you easily create one. It outputs all the installed packages and their version number in requirements format. The output of the freeze command can then be piped into a requirements file, as follows: These were some of the useful pip commands in Python, which I use in my day-to-day activities. This could be used as a handy resource to learn about pip. There are other commands too which have not been covered in this article. The official documentation is an excellent resource if you are thinking to go deeper into the details.
[ { "code": null, "e": 555, "s": 171, "text": "An in-depth article was published in the February of 2020 by Sebastian Raschka et al. that studies the role and importance of Python in the Machine Learning ecosystem. The paper titled Machine Learning in Python: Main Developments and Technology Trends in Data Science, Machine Learning, and Artificial Intelligence put forward a fascinating observation which I’d like to quote here:" }, { "code": null, "e": 950, "s": 555, "text": "Historically, a wide range of different programming languages and environments have been used to enable machine learning research and application development. However, as the general-purpose Python language has seen a tremendous growth of popularity within the scientific computing community within the last decade, most recent machine learning and deep learning libraries are now Python-based." }, { "code": null, "e": 1259, "s": 950, "text": "Python has truly changed the Data Science landscape and emerged as one of the most used libraries in data science, today. This is also quite evident from the sheer number of python packages being created and used. As of July 2020, over 235,000 Python packages could be accessed through PyPI. So what is PyPI?" }, { "code": null, "e": 1860, "s": 1259, "text": "The Python Package Index (PyPI) is a repository of software for the Python programming language. This repository houses the packages created and shared by the ever-growing Python community. You can install any package from Pypi using pip which is the package installer for Python. Every Python programmer, new or old, uses pip install <package name> multiple times. However, there are other useful pip commands,, especially from a data science perspective which can be extremely useful. This article attempts to explain some of the commonly used pip commands along with their frequently used options." }, { "code": null, "e": 2136, "s": 1860, "text": "To begin with, we’ll create a virtual environment. This way, it’ll be easier to show the various pip commands in action. Let’s use venv to create this new virtual environment and name it as env.The python’s venv module is used for creating lightweight “virtual environments.”" }, { "code": null, "e": 2255, "s": 2136, "text": "# Creating virtual environment in Mac/Linux python3 -m venv env# Creating virtual environment in Windowspy -m venv env" }, { "code": null, "e": 2345, "s": 2255, "text": "Once the env environment has been created, we’ll activate it, and then we are good to go." }, { "code": null, "e": 2607, "s": 2345, "text": "Let’s start by checking if pip is installed in our environment or not. Technically, if you are using Python 2 >=2.7.9 or Python 3 >=3.4, pip should be already installed. The pip --version command returns the location as well as the version of the pip installed." }, { "code": null, "e": 2711, "s": 2607, "text": "Since everything is in place, let’s now look at a few important and most used pip commands, one by one." }, { "code": null, "e": 2796, "s": 2711, "text": "If you type pip help in your terminal, you’ll get a single-page scrollable document." }, { "code": null, "e": 2983, "s": 2796, "text": "It displays the various commands that can be used with pip, as well as how the commands can be used. Additionally, if you wish to see details concerning a single pip command, you can do:" }, { "code": null, "e": 3034, "s": 2983, "text": "pip help <command_name>example: pip help <install>" }, { "code": null, "e": 3125, "s": 3034, "text": "This brings up the information on the single commands whose details you are interested in." }, { "code": null, "e": 3286, "s": 3125, "text": "If want to take a look at all the installed packages, you can do a pip list and it will output all the packages that are currently installed in the environment." }, { "code": null, "e": 3295, "s": 3286, "text": "pip list" }, { "code": null, "e": 3431, "s": 3295, "text": "The output above shows that currently, we have only two packages installed, and out of them, pip itself belongs to an outdated version." }, { "code": null, "e": 3491, "s": 3431, "text": "pip list can be used with a bunch of options, for instance:" }, { "code": null, "e": 3544, "s": 3491, "text": "--outdated/ -o for listing all the outdated packages" }, { "code": null, "e": 3579, "s": 3544, "text": "pip list --outdated or pip list -o" }, { "code": null, "e": 3635, "s": 3579, "text": "It looks like both the installed packages are outdated." }, { "code": null, "e": 3690, "s": 3635, "text": "--uptodate/ -u for listing all the up-to-date packages" }, { "code": null, "e": 3725, "s": 3690, "text": "pip list --uptodate or pip list -u" }, { "code": null, "e": 3873, "s": 3725, "text": "--format selects the output format for displaying installed packages on the screen. The available options are — columns (default), freeze, or JSON." }, { "code": null, "e": 4033, "s": 3873, "text": "The pip install command is used to install a new package. Let’s install the pandas , the bread and butter package for data science, in our virtual environment." }, { "code": null, "e": 4169, "s": 4033, "text": "To check whether the pandas' package has been installed or not, we can do a quickpip list to have a look at all the installed packages." }, { "code": null, "e": 4286, "s": 4169, "text": "We can see that pandas, along with its other dependencies has been installed comfortably in the virtual environment." }, { "code": null, "e": 4344, "s": 4286, "text": "pip install also has few useful options to be used along." }, { "code": null, "e": 4428, "s": 4344, "text": "--upgrade/ -U for upgrading all specified packages to the newest available version." }, { "code": null, "e": 4721, "s": 4428, "text": "--requirement <file>/ -r for installing from the given requirements file. A requirements file is a list of all of a project’s dependencies. This text file contains all the package required including the specific version of each dependency. Here is how a requirement file typically looks like:" }, { "code": null, "e": 4808, "s": 4721, "text": "To install all the packages mentioned in the requirements.txt file, you can simply do:" }, { "code": null, "e": 4840, "s": 4808, "text": "pip install -r requirements.txt" }, { "code": null, "e": 5131, "s": 4840, "text": "This command shows information about the installed packages. One can choose the amount of information to be displayed on the screen. Let’s say we want to know details about the pandas package which we know is installed in our environment. To show limited details, we can do pip show pandas:" }, { "code": null, "e": 5147, "s": 5131, "text": "pip show pandas" }, { "code": null, "e": 5245, "s": 5147, "text": "In case, you want the complete details, you can use the verbose option with the pip show command," }, { "code": null, "e": 5271, "s": 5245, "text": "pip show --verbose pandas" }, { "code": null, "e": 5432, "s": 5271, "text": "As the name suggests, pip uninstall will uninstall the desired package. As per the documentation, there are few exceptions that cannot be uninstalled. They are:" }, { "code": null, "e": 5500, "s": 5432, "text": "Pure distutils packages installed with python setup.py install, and" }, { "code": null, "e": 5554, "s": 5500, "text": "Script wrappers installed by python setup.py develop." }, { "code": null, "e": 5678, "s": 5554, "text": "We’ll now uninstall the pandas' package that we had recently installed. The process is pretty straight forward, as follows:" }, { "code": null, "e": 5699, "s": 5678, "text": "pip uninstall pandas" }, { "code": null, "e": 5738, "s": 5699, "text": "pip uninstall has two options, namely:" }, { "code": null, "e": 5817, "s": 5738, "text": "--requirement <file>/ -r for uninstalling packages from the requirements file." }, { "code": null, "e": 5914, "s": 5817, "text": "--yes / -y . This option if selected doesn’t ask for confirmation during uninstalling a package." }, { "code": null, "e": 6125, "s": 5914, "text": "In section 3, we touched upon the need for the requirements file in a project. Well, pip freeze lets you easily create one. It outputs all the installed packages and their version number in requirements format." }, { "code": null, "e": 6214, "s": 6125, "text": "The output of the freeze command can then be piped into a requirements file, as follows:" } ]
Dart Programming - Syntax
Syntax defines a set of rules for writing programs. Every language specification defines its own syntax. A Dart program is composed of − Variables and Operators Classes Functions Expressions and Programming Constructs Decision Making and Looping Constructs Comments Libraries and Packages Typedefs Data structures represented as Collections / Generics Let us start with the traditional “Hello World” example − main() { print("Hello World!"); } The main() function is a predefined method in Dart. This method acts as the entry point to the application. A Dart script needs the main() method for execution. print() is a predefined function that prints the specified string or value to the standard output i.e. the terminal. The output of the above code will be − Hello World! You can execute a Dart program in two ways − Via the terminal Via the WebStorm IDE To execute a Dart program via the terminal − Navigate to the path of the current project Type the following command in the Terminal window dart file_name.dart To execute a Dart program via the WebStorm IDE − Right-click the Dart script file on the IDE. (The file should contain the main() function to enable execution) Right-click the Dart script file on the IDE. (The file should contain the main() function to enable execution) Click on the ‘Run <file_name>’ option. A screenshot of the same is given below − Click on the ‘Run <file_name>’ option. A screenshot of the same is given below − One can alternatively click the button or use the shortcut Ctrl+Shift+F10 to execute the Dart Script. Dart command-line options are used to modify Dart Script execution. Common commandline options for Dart include the following − Enables both assertions and type checks (checked mode). Displays VM version information. Specifies the path to the package resolution configuration file. Specifies where to find imported libraries. This option cannot be used with --packages. Displays help. Dart programs run in two modes namely − Checked Mode Production Mode (Default) It is recommended to run the Dart VM in checked mode during development and testing, since it adds warnings and errors to aid development and debugging process. The checked mode enforces various checks like type-checking etc. To turn on the checked mode, add the -c or –-checked option before the script-file name while running the script. However, to ensure performance benefit while running the script, it is recommended to run the script in the production mode. Consider the following Test.dart script file − void main() { int n = "hello"; print(n); } Run the script by entering − dart Test.dart Though there is a type-mismatch the script executes successfully as the checked mode is turned off. The script will result in the following output − hello Now try executing the script with the "- - checked" or the "-c" option − dart -c Test.dart Or, dart - - checked Test.dart The Dart VM will throw an error stating that there is a type mismatch. Unhandled exception: type 'String' is not a subtype of type 'int' of 'n' where String is from dart:core int is from dart:core #0 main (file:///C:/Users/Administrator/Desktop/test.dart:3:9) #1 _startIsolate.<anonymous closure> (dart:isolate-patch/isolate_patch.dart :261) #2 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:148) Identifiers are names given to elements in a program like variables, functions etc. The rules for identifiers are − Identifiers can include both, characters and digits. However, the identifier cannot begin with a digit. Identifiers cannot include special symbols except for underscore (_) or a dollar sign ($). Identifiers cannot include special symbols except for underscore (_) or a dollar sign ($). Identifiers cannot be keywords. Identifiers cannot be keywords. They must be unique. They must be unique. Identifiers are case-sensitive. Identifiers are case-sensitive. Identifiers cannot contain spaces. Identifiers cannot contain spaces. The following tables lists a few examples of valid and invalid identifiers − Keywords have a special meaning in the context of a language. The following table lists some keywords in Dart. Dart ignores spaces, tabs, and newlines that appear in programs. You can use spaces, tabs, and newlines freely in your program and you are free to format and indent your programs in a neat and consistent way that makes the code easy to read and understand. Dart is case-sensitive. This means that Dart differentiates between uppercase and lowercase characters. Each line of instruction is called a statement. Each dart statement must end with a semicolon (;). A single line can contain multiple statements. However, these statements must be separated by a semicolon. Comments are a way to improve the readability of a program. Comments can be used to include additional information about a program like author of the code, hints about a function/ construct etc. Comments are ignored by the compiler. Dart supports the following types of comments − Single-line comments ( // ) − Any text between a "//" and the end of a line is treated as a comment Single-line comments ( // ) − Any text between a "//" and the end of a line is treated as a comment Multi-line comments (/* */) − These comments may span multiple lines. Multi-line comments (/* */) − These comments may span multiple lines. // this is single line comment /* This is a Multi-line comment */ Dart is an Object-Oriented language. Object Orientation is a software development paradigm that follows real-world modelling. Object Orientation considers a program as a collection of objects that communicate with each other via mechanism called methods. Object − An object is a real-time representation of any entity. As per Grady Brooch, every object must have three features − State − described by the attributes of an object. Behavior − describes how the object will act. Identity − a unique value that distinguishes an object from a set of similar such objects. Object − An object is a real-time representation of any entity. As per Grady Brooch, every object must have three features − State − described by the attributes of an object. State − described by the attributes of an object. Behavior − describes how the object will act. Behavior − describes how the object will act. Identity − a unique value that distinguishes an object from a set of similar such objects. Identity − a unique value that distinguishes an object from a set of similar such objects. Class − A class in terms of OOP is a blueprint for creating objects. A class encapsulates data for the object. Class − A class in terms of OOP is a blueprint for creating objects. A class encapsulates data for the object. Method − Methods facilitate communication between objects. Method − Methods facilitate communication between objects. class TestClass { void disp() { print("Hello World"); } } void main() { TestClass c = new TestClass(); c.disp(); } The above example defines a class TestClass. The class has a method disp(). The method prints the string “Hello World” on the terminal. The new keyword creates an object of the class. The object invokes the method disp(). The code should produce the following output − Hello World 44 Lectures 4.5 hours Sriyank Siddhartha 34 Lectures 4 hours Sriyank Siddhartha 69 Lectures 4 hours Frahaan Hussain 117 Lectures 10 hours Frahaan Hussain 22 Lectures 1.5 hours Pranjal Srivastava 34 Lectures 3 hours Pranjal Srivastava Print Add Notes Bookmark this page
[ { "code": null, "e": 2662, "s": 2525, "text": "Syntax defines a set of rules for writing programs. Every language specification defines its own syntax. A Dart program is composed of −" }, { "code": null, "e": 2686, "s": 2662, "text": "Variables and Operators" }, { "code": null, "e": 2694, "s": 2686, "text": "Classes" }, { "code": null, "e": 2704, "s": 2694, "text": "Functions" }, { "code": null, "e": 2743, "s": 2704, "text": "Expressions and Programming Constructs" }, { "code": null, "e": 2782, "s": 2743, "text": "Decision Making and Looping Constructs" }, { "code": null, "e": 2791, "s": 2782, "text": "Comments" }, { "code": null, "e": 2814, "s": 2791, "text": "Libraries and Packages" }, { "code": null, "e": 2823, "s": 2814, "text": "Typedefs" }, { "code": null, "e": 2877, "s": 2823, "text": "Data structures represented as Collections / Generics" }, { "code": null, "e": 2935, "s": 2877, "text": "Let us start with the traditional “Hello World” example −" }, { "code": null, "e": 2974, "s": 2935, "text": "main() { \n print(\"Hello World!\"); \n}" }, { "code": null, "e": 3252, "s": 2974, "text": "The main() function is a predefined method in Dart. This method acts as the entry point to the application. A Dart script needs the main() method for execution. print() is a predefined function that prints the specified string or value to the standard output i.e. the terminal." }, { "code": null, "e": 3291, "s": 3252, "text": "The output of the above code will be −" }, { "code": null, "e": 3305, "s": 3291, "text": "Hello World!\n" }, { "code": null, "e": 3350, "s": 3305, "text": "You can execute a Dart program in two ways −" }, { "code": null, "e": 3367, "s": 3350, "text": "Via the terminal" }, { "code": null, "e": 3388, "s": 3367, "text": "Via the WebStorm IDE" }, { "code": null, "e": 3433, "s": 3388, "text": "To execute a Dart program via the terminal −" }, { "code": null, "e": 3477, "s": 3433, "text": "Navigate to the path of the current project" }, { "code": null, "e": 3527, "s": 3477, "text": "Type the following command in the Terminal window" }, { "code": null, "e": 3548, "s": 3527, "text": "dart file_name.dart\n" }, { "code": null, "e": 3597, "s": 3548, "text": "To execute a Dart program via the WebStorm IDE −" }, { "code": null, "e": 3708, "s": 3597, "text": "Right-click the Dart script file on the IDE. (The file should contain the main() function to enable execution)" }, { "code": null, "e": 3819, "s": 3708, "text": "Right-click the Dart script file on the IDE. (The file should contain the main() function to enable execution)" }, { "code": null, "e": 3900, "s": 3819, "text": "Click on the ‘Run <file_name>’ option. A screenshot of the same is given below −" }, { "code": null, "e": 3981, "s": 3900, "text": "Click on the ‘Run <file_name>’ option. A screenshot of the same is given below −" }, { "code": null, "e": 4084, "s": 3981, "text": "One can alternatively click the button or use the shortcut Ctrl+Shift+F10 to execute the Dart Script." }, { "code": null, "e": 4212, "s": 4084, "text": "Dart command-line options are used to modify Dart Script execution. Common commandline options for Dart include the following −" }, { "code": null, "e": 4268, "s": 4212, "text": "Enables both assertions and type checks (checked mode)." }, { "code": null, "e": 4301, "s": 4268, "text": "Displays VM version information." }, { "code": null, "e": 4366, "s": 4301, "text": "Specifies the path to the package resolution configuration file." }, { "code": null, "e": 4454, "s": 4366, "text": "Specifies where to find imported libraries. This option cannot be used with --packages." }, { "code": null, "e": 4469, "s": 4454, "text": "Displays help." }, { "code": null, "e": 4509, "s": 4469, "text": "Dart programs run in two modes namely −" }, { "code": null, "e": 4522, "s": 4509, "text": "Checked Mode" }, { "code": null, "e": 4548, "s": 4522, "text": "Production Mode (Default)" }, { "code": null, "e": 4888, "s": 4548, "text": "It is recommended to run the Dart VM in checked mode during development and testing, since it adds warnings and errors to aid development and debugging process. The checked mode enforces various checks like type-checking etc. To turn on the checked mode, add the -c or –-checked option before the script-file name while running the script." }, { "code": null, "e": 5013, "s": 4888, "text": "However, to ensure performance benefit while running the script, it is recommended to run the script in the production mode." }, { "code": null, "e": 5060, "s": 5013, "text": "Consider the following Test.dart script file −" }, { "code": null, "e": 5113, "s": 5060, "text": "void main() { \n int n = \"hello\"; \n print(n); \n} " }, { "code": null, "e": 5142, "s": 5113, "text": "Run the script by entering −" }, { "code": null, "e": 5158, "s": 5142, "text": "dart Test.dart\n" }, { "code": null, "e": 5308, "s": 5158, "text": "Though there is a type-mismatch the script executes successfully as the checked mode is turned off. The script will result in the following output −" }, { "code": null, "e": 5315, "s": 5308, "text": "hello\n" }, { "code": null, "e": 5388, "s": 5315, "text": "Now try executing the script with the \"- - checked\" or the \"-c\" option −" }, { "code": null, "e": 5408, "s": 5388, "text": "dart -c Test.dart \n" }, { "code": null, "e": 5412, "s": 5408, "text": "Or," }, { "code": null, "e": 5440, "s": 5412, "text": "dart - - checked Test.dart\n" }, { "code": null, "e": 5511, "s": 5440, "text": "The Dart VM will throw an error stating that there is a type mismatch." }, { "code": null, "e": 5879, "s": 5511, "text": "Unhandled exception: \ntype 'String' is not a subtype of type 'int' of 'n' where \n String is from dart:core \n int is from dart:core \n#0 main (file:///C:/Users/Administrator/Desktop/test.dart:3:9) \n#1 _startIsolate.<anonymous closure> (dart:isolate-patch/isolate_patch.dart :261) \n#2 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:148)" }, { "code": null, "e": 5995, "s": 5879, "text": "Identifiers are names given to elements in a program like variables, functions etc. The rules for identifiers are −" }, { "code": null, "e": 6099, "s": 5995, "text": "Identifiers can include both, characters and digits. However, the identifier cannot begin with a digit." }, { "code": null, "e": 6190, "s": 6099, "text": "Identifiers cannot include special symbols except for underscore (_) or a dollar sign ($)." }, { "code": null, "e": 6281, "s": 6190, "text": "Identifiers cannot include special symbols except for underscore (_) or a dollar sign ($)." }, { "code": null, "e": 6313, "s": 6281, "text": "Identifiers cannot be keywords." }, { "code": null, "e": 6345, "s": 6313, "text": "Identifiers cannot be keywords." }, { "code": null, "e": 6366, "s": 6345, "text": "They must be unique." }, { "code": null, "e": 6387, "s": 6366, "text": "They must be unique." }, { "code": null, "e": 6419, "s": 6387, "text": "Identifiers are case-sensitive." }, { "code": null, "e": 6451, "s": 6419, "text": "Identifiers are case-sensitive." }, { "code": null, "e": 6486, "s": 6451, "text": "Identifiers cannot contain spaces." }, { "code": null, "e": 6521, "s": 6486, "text": "Identifiers cannot contain spaces." }, { "code": null, "e": 6598, "s": 6521, "text": "The following tables lists a few examples of valid and invalid identifiers −" }, { "code": null, "e": 6709, "s": 6598, "text": "Keywords have a special meaning in the context of a language. The following table lists some keywords in Dart." }, { "code": null, "e": 6966, "s": 6709, "text": "Dart ignores spaces, tabs, and newlines that appear in programs. You can use spaces, tabs, and newlines freely in your program and you are free to format and indent your programs in a neat and consistent way that makes the code easy to read and understand." }, { "code": null, "e": 7070, "s": 6966, "text": "Dart is case-sensitive. This means that Dart differentiates between uppercase and lowercase characters." }, { "code": null, "e": 7276, "s": 7070, "text": "Each line of instruction is called a statement. Each dart statement must end with a semicolon (;). A single line can contain multiple statements. However, these statements must be separated by a semicolon." }, { "code": null, "e": 7509, "s": 7276, "text": "Comments are a way to improve the readability of a program. Comments can be used to include additional information about a program like author of the code, hints about a function/ construct etc. Comments are ignored by the compiler." }, { "code": null, "e": 7557, "s": 7509, "text": "Dart supports the following types of comments −" }, { "code": null, "e": 7657, "s": 7557, "text": "Single-line comments ( // ) − Any text between a \"//\" and the end of a line is treated as a comment" }, { "code": null, "e": 7757, "s": 7657, "text": "Single-line comments ( // ) − Any text between a \"//\" and the end of a line is treated as a comment" }, { "code": null, "e": 7827, "s": 7757, "text": "Multi-line comments (/* */) − These comments may span multiple lines." }, { "code": null, "e": 7897, "s": 7827, "text": "Multi-line comments (/* */) − These comments may span multiple lines." }, { "code": null, "e": 7977, "s": 7897, "text": "// this is single line comment \n \n/* This is a \n Multi-line comment \n*/ " }, { "code": null, "e": 8232, "s": 7977, "text": "Dart is an Object-Oriented language. Object Orientation is a software development paradigm that follows real-world modelling. Object Orientation considers a program as a collection of objects that communicate with each other via mechanism called methods." }, { "code": null, "e": 8547, "s": 8232, "text": "Object − An object is a real-time representation of any entity. As per Grady Brooch, every object must have three features −\n\nState − described by the attributes of an object.\nBehavior − describes how the object will act.\nIdentity − a unique value that distinguishes an object from a set of similar such objects.\n\n" }, { "code": null, "e": 8672, "s": 8547, "text": "Object − An object is a real-time representation of any entity. As per Grady Brooch, every object must have three features −" }, { "code": null, "e": 8722, "s": 8672, "text": "State − described by the attributes of an object." }, { "code": null, "e": 8772, "s": 8722, "text": "State − described by the attributes of an object." }, { "code": null, "e": 8818, "s": 8772, "text": "Behavior − describes how the object will act." }, { "code": null, "e": 8864, "s": 8818, "text": "Behavior − describes how the object will act." }, { "code": null, "e": 8955, "s": 8864, "text": "Identity − a unique value that distinguishes an object from a set of similar such objects." }, { "code": null, "e": 9046, "s": 8955, "text": "Identity − a unique value that distinguishes an object from a set of similar such objects." }, { "code": null, "e": 9157, "s": 9046, "text": "Class − A class in terms of OOP is a blueprint for creating objects. A class encapsulates data for the object." }, { "code": null, "e": 9268, "s": 9157, "text": "Class − A class in terms of OOP is a blueprint for creating objects. A class encapsulates data for the object." }, { "code": null, "e": 9327, "s": 9268, "text": "Method − Methods facilitate communication between objects." }, { "code": null, "e": 9386, "s": 9327, "text": "Method − Methods facilitate communication between objects." }, { "code": null, "e": 9539, "s": 9386, "text": "class TestClass { \n void disp() { \n print(\"Hello World\"); \n } \n} \nvoid main() { \n TestClass c = new TestClass(); \n c.disp(); \n}" }, { "code": null, "e": 9761, "s": 9539, "text": "The above example defines a class TestClass. The class has a method disp(). The method prints the string “Hello World” on the terminal. The new keyword creates an object of the class. The object invokes the method disp()." }, { "code": null, "e": 9808, "s": 9761, "text": "The code should produce the following output −" }, { "code": null, "e": 9821, "s": 9808, "text": "Hello World\n" }, { "code": null, "e": 9856, "s": 9821, "text": "\n 44 Lectures \n 4.5 hours \n" }, { "code": null, "e": 9876, "s": 9856, "text": " Sriyank Siddhartha" }, { "code": null, "e": 9909, "s": 9876, "text": "\n 34 Lectures \n 4 hours \n" }, { "code": null, "e": 9929, "s": 9909, "text": " Sriyank Siddhartha" }, { "code": null, "e": 9962, "s": 9929, "text": "\n 69 Lectures \n 4 hours \n" }, { "code": null, "e": 9979, "s": 9962, "text": " Frahaan Hussain" }, { "code": null, "e": 10014, "s": 9979, "text": "\n 117 Lectures \n 10 hours \n" }, { "code": null, "e": 10031, "s": 10014, "text": " Frahaan Hussain" }, { "code": null, "e": 10066, "s": 10031, "text": "\n 22 Lectures \n 1.5 hours \n" }, { "code": null, "e": 10086, "s": 10066, "text": " Pranjal Srivastava" }, { "code": null, "e": 10119, "s": 10086, "text": "\n 34 Lectures \n 3 hours \n" }, { "code": null, "e": 10139, "s": 10119, "text": " Pranjal Srivastava" }, { "code": null, "e": 10146, "s": 10139, "text": " Print" }, { "code": null, "e": 10157, "s": 10146, "text": " Add Notes" } ]
Remove duplicates from a dataframe in PySpark
16 Dec, 2021 In this article, we are going to drop the duplicate data from dataframe using pyspark in Python Before starting we are going to create Dataframe for demonstration: Python3 # importing moduleimport pyspark # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of employee datadata =[["1","sravan","company 1"], ["2","ojaswi","company 1"], ["3","rohith","company 2"], ["4","sridevi","company 1"], ["1","sravan","company 1"], ["4","sridevi","company 1"]] # specify column namescolumns = ['Employee ID','Employee NAME','Company'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data,columns) print('Actual data in dataframe')dataframe.show() Output: It will remove the duplicate rows in the dataframe Syntax: dataframe.distinct() Where, dataframe is the dataframe name created from the nested lists using pyspark Example 1: Python program to drop duplicate data using distinct() function Python3 print('distinct data after dropping duplicate rows') # display distinct datadataframe.distinct().show() Output: Example 2: Python program to select distinct data in only two columns. We can use select () function along with distinct function to get distinct values from particular columns Syntax: dataframe.select([‘column 1′,’column n’]).distinct().show() Python3 # display distinct data in# Employee ID and Employee NAMEdataframe.select(['Employee ID', 'Employee NAME']).distinct().show() Output: Syntax: dataframe.dropDuplicates() where, dataframe is the dataframe name created from the nested lists using pyspark Example 1: Python program to remove duplicate data from the employee table. Python3 # remove duplicate data# using dropDuplicates()functiondataframe.dropDuplicates().show() Output: Example 2: Python program to remove duplicate values in specific columns Python3 # remove duplicate data# using dropDuplicates()function# in two columnsdataframe.select(['Employee ID', 'Employee NAME']).dropDuplicates().show() Output: sagar0719kumar Picked Python-Pyspark Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n16 Dec, 2021" }, { "code": null, "e": 124, "s": 28, "text": "In this article, we are going to drop the duplicate data from dataframe using pyspark in Python" }, { "code": null, "e": 192, "s": 124, "text": "Before starting we are going to create Dataframe for demonstration:" }, { "code": null, "e": 200, "s": 192, "text": "Python3" }, { "code": "# importing moduleimport pyspark # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of employee datadata =[[\"1\",\"sravan\",\"company 1\"], [\"2\",\"ojaswi\",\"company 1\"], [\"3\",\"rohith\",\"company 2\"], [\"4\",\"sridevi\",\"company 1\"], [\"1\",\"sravan\",\"company 1\"], [\"4\",\"sridevi\",\"company 1\"]] # specify column namescolumns = ['Employee ID','Employee NAME','Company'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data,columns) print('Actual data in dataframe')dataframe.show()", "e": 874, "s": 200, "text": null }, { "code": null, "e": 882, "s": 874, "text": "Output:" }, { "code": null, "e": 933, "s": 882, "text": "It will remove the duplicate rows in the dataframe" }, { "code": null, "e": 962, "s": 933, "text": "Syntax: dataframe.distinct()" }, { "code": null, "e": 1045, "s": 962, "text": "Where, dataframe is the dataframe name created from the nested lists using pyspark" }, { "code": null, "e": 1120, "s": 1045, "text": "Example 1: Python program to drop duplicate data using distinct() function" }, { "code": null, "e": 1128, "s": 1120, "text": "Python3" }, { "code": "print('distinct data after dropping duplicate rows') # display distinct datadataframe.distinct().show()", "e": 1232, "s": 1128, "text": null }, { "code": null, "e": 1240, "s": 1232, "text": "Output:" }, { "code": null, "e": 1311, "s": 1240, "text": "Example 2: Python program to select distinct data in only two columns." }, { "code": null, "e": 1417, "s": 1311, "text": "We can use select () function along with distinct function to get distinct values from particular columns" }, { "code": null, "e": 1485, "s": 1417, "text": "Syntax: dataframe.select([‘column 1′,’column n’]).distinct().show()" }, { "code": null, "e": 1493, "s": 1485, "text": "Python3" }, { "code": "# display distinct data in# Employee ID and Employee NAMEdataframe.select(['Employee ID', 'Employee NAME']).distinct().show()", "e": 1636, "s": 1493, "text": null }, { "code": null, "e": 1644, "s": 1636, "text": "Output:" }, { "code": null, "e": 1679, "s": 1644, "text": "Syntax: dataframe.dropDuplicates()" }, { "code": null, "e": 1762, "s": 1679, "text": "where, dataframe is the dataframe name created from the nested lists using pyspark" }, { "code": null, "e": 1838, "s": 1762, "text": "Example 1: Python program to remove duplicate data from the employee table." }, { "code": null, "e": 1846, "s": 1838, "text": "Python3" }, { "code": "# remove duplicate data# using dropDuplicates()functiondataframe.dropDuplicates().show()", "e": 1935, "s": 1846, "text": null }, { "code": null, "e": 1943, "s": 1935, "text": "Output:" }, { "code": null, "e": 2016, "s": 1943, "text": "Example 2: Python program to remove duplicate values in specific columns" }, { "code": null, "e": 2024, "s": 2016, "text": "Python3" }, { "code": "# remove duplicate data# using dropDuplicates()function# in two columnsdataframe.select(['Employee ID', 'Employee NAME']).dropDuplicates().show()", "e": 2187, "s": 2024, "text": null }, { "code": null, "e": 2195, "s": 2187, "text": "Output:" }, { "code": null, "e": 2210, "s": 2195, "text": "sagar0719kumar" }, { "code": null, "e": 2217, "s": 2210, "text": "Picked" }, { "code": null, "e": 2232, "s": 2217, "text": "Python-Pyspark" }, { "code": null, "e": 2239, "s": 2232, "text": "Python" } ]
Phong model (Specular Reflection) in Computer Graphics
07 Apr, 2021 Prerequisite – Basic Illumination Models Phong model of reflection :When we look at illuminated shiny surfaces, such as glittering surfaces, polished metal sheets, apple etc, we found a kind of bright spot at certain viewing point locations. This phenomenon is called specular reflection. Look at the following figure : N = Normal vector L = Point light source V = Viewing direction R = is representing the unit vector directed towards the ideal specular reflection ∅ = Viewing angle relative to the specular reflection direction R. θ = Angle made by L & R with N. For ideal reflector surfaces(perfect mirror), incident light is reflected only in the specular-reflection direction. So, in this case, we could be able to see reflected light when vectors V & R coincides(viewing angle(∅=0)). A Shiny surface has a narrow specular reflection range, while a dull surface has a wider reflection range. An empirical model for calculating the specular reflection range, invented by the Phong Bui Tuong is also known as Phong specular reflection model. This model sets the intensity of specular reflection directly proportional to the cosns(∅). The range of angle ∅ can lie between 0 ≤ ∅ ≤ 1. Where ns is a specular reflection parameter whose value is determined by the type of surface to be displayed. The value of ns for brighter(shiny) surfaces could be 100 or more whereas for dull surfaces its value is 1 or less than 1. The intensity of specular reflection depends on the object(Material) properties of the surface & the angle of light incidence, as well as other factors such as the polarization and color of the light incident. We can control the intensity variation of the light through, specular-reflection, using spectral-reflection function W(∅) for each surface. Where ∅ the value lies in the range of 0 ≤ ∅ ≤ 1. In general W(∅) tend to increase as the angle of incidence increases, at ∅=90* W(90*)=1, and in this case, all the light incidents on the surface of the material is reflected. So, using the spectral-reflection function W(∅) we can write the Phong specular reflection model as : For many opaque material surfaces, specular reflections are nearly constant for all incident angles. So, in such case, we can replace W(∅) with a constant coefficient(Ks), and the value lies between 0 & 1, for each surface: Since, V & R are unit vectors so, |V|=|R|=1 : V * R = |V|*|R|*cos(θ) , V * R = cos(θ) So, we can write just the previous equation as: Here, R can be calculated by the projection of L onto the direction of the normal vector is obtained: R + L = (2*N.L)*N So, using the above equation specular-reflection vector is obtained, R = (2*N.L)*N - L. Combined ambient, diffuse and specular reflections in the Phong model can be represented as the following equation with multiple light sources: So, for a single point light source, we can model the combined & specular reflections from a point on an illuminated surface as : And, for n point light source, the equation will be: computer-graphics Misc Misc Misc Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Hypervisor Advantages and Disadvantages of OOP Introduction to Electronic Mail Cloud Computing Analog to Digital Conversion array::size() in C++ STL Characteristics of Cloud Computing Bubble Sort algorithm using JavaScript Introduction to Deep Learning Practice Questions for Recursion | Set 4
[ { "code": null, "e": 28, "s": 0, "text": "\n07 Apr, 2021" }, { "code": null, "e": 69, "s": 28, "text": "Prerequisite – Basic Illumination Models" }, { "code": null, "e": 317, "s": 69, "text": "Phong model of reflection :When we look at illuminated shiny surfaces, such as glittering surfaces, polished metal sheets, apple etc, we found a kind of bright spot at certain viewing point locations. This phenomenon is called specular reflection." }, { "code": null, "e": 349, "s": 317, "text": "Look at the following figure : " }, { "code": null, "e": 594, "s": 349, "text": "N = Normal vector\nL = Point light source\nV = Viewing direction\nR = is representing the unit vector directed towards the ideal specular reflection\n∅ = Viewing angle relative to the specular reflection direction R.\nθ = Angle made by L & R with N." }, { "code": null, "e": 819, "s": 594, "text": "For ideal reflector surfaces(perfect mirror), incident light is reflected only in the specular-reflection direction. So, in this case, we could be able to see reflected light when vectors V & R coincides(viewing angle(∅=0))." }, { "code": null, "e": 1657, "s": 819, "text": "A Shiny surface has a narrow specular reflection range, while a dull surface has a wider reflection range. An empirical model for calculating the specular reflection range, invented by the Phong Bui Tuong is also known as Phong specular reflection model. This model sets the intensity of specular reflection directly proportional to the cosns(∅). The range of angle ∅ can lie between 0 ≤ ∅ ≤ 1. Where ns is a specular reflection parameter whose value is determined by the type of surface to be displayed. The value of ns for brighter(shiny) surfaces could be 100 or more whereas for dull surfaces its value is 1 or less than 1. The intensity of specular reflection depends on the object(Material) properties of the surface & the angle of light incidence, as well as other factors such as the polarization and color of the light incident." }, { "code": null, "e": 2126, "s": 1657, "text": "We can control the intensity variation of the light through, specular-reflection, using spectral-reflection function W(∅) for each surface. Where ∅ the value lies in the range of 0 ≤ ∅ ≤ 1. In general W(∅) tend to increase as the angle of incidence increases, at ∅=90* W(90*)=1, and in this case, all the light incidents on the surface of the material is reflected. So, using the spectral-reflection function W(∅) we can write the Phong specular reflection model as : " }, { "code": null, "e": 2354, "s": 2130, "text": "For many opaque material surfaces, specular reflections are nearly constant for all incident angles. So, in such case, we can replace W(∅) with a constant coefficient(Ks), and the value lies between 0 & 1, for each surface:" }, { "code": null, "e": 2575, "s": 2354, "text": "Since, V & R are unit vectors so, |V|=|R|=1 :\n V * R = |V|*|R|*cos(θ) , \n V * R = cos(θ) " }, { "code": null, "e": 2623, "s": 2575, "text": "So, we can write just the previous equation as:" }, { "code": null, "e": 2725, "s": 2623, "text": "Here, R can be calculated by the projection of L onto the direction of the normal vector is obtained:" }, { "code": null, "e": 2833, "s": 2727, "text": "R + L = (2*N.L)*N\nSo, using the above equation specular-reflection vector is obtained,\nR = (2*N.L)*N - L." }, { "code": null, "e": 2977, "s": 2833, "text": "Combined ambient, diffuse and specular reflections in the Phong model can be represented as the following equation with multiple light sources:" }, { "code": null, "e": 3107, "s": 2977, "text": "So, for a single point light source, we can model the combined & specular reflections from a point on an illuminated surface as :" }, { "code": null, "e": 3160, "s": 3107, "text": "And, for n point light source, the equation will be:" }, { "code": null, "e": 3178, "s": 3160, "text": "computer-graphics" }, { "code": null, "e": 3183, "s": 3178, "text": "Misc" }, { "code": null, "e": 3188, "s": 3183, "text": "Misc" }, { "code": null, "e": 3193, "s": 3188, "text": "Misc" }, { "code": null, "e": 3291, "s": 3193, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3302, "s": 3291, "text": "Hypervisor" }, { "code": null, "e": 3338, "s": 3302, "text": "Advantages and Disadvantages of OOP" }, { "code": null, "e": 3370, "s": 3338, "text": "Introduction to Electronic Mail" }, { "code": null, "e": 3386, "s": 3370, "text": "Cloud Computing" }, { "code": null, "e": 3415, "s": 3386, "text": "Analog to Digital Conversion" }, { "code": null, "e": 3440, "s": 3415, "text": "array::size() in C++ STL" }, { "code": null, "e": 3475, "s": 3440, "text": "Characteristics of Cloud Computing" }, { "code": null, "e": 3514, "s": 3475, "text": "Bubble Sort algorithm using JavaScript" }, { "code": null, "e": 3544, "s": 3514, "text": "Introduction to Deep Learning" } ]
How to Schedule Python Scripts As Cron Jobs With Crontab
18 Jul, 2021 In this article, we will discuss how to schedule Python scripts with crontab. The Cron job utility is a time-based job scheduler in Unix-like operating systems. Cron allows Linux and Unix users to run commands or scripts at a given time and date. One can schedule scripts to be executed periodically. The crontab is a list of commands that you want to run on a regular schedule, and also the name of the command used to manage that list. cron is the system process that will automatically perform tasks for you according to a set schedule. Below is a simple Python script that sends a notification message to remind the user to drink water. We will be scheduling this script to send a notification every 2 hours. (the script is tested for Linux-based systems only, but the scheduling process will be similar with any script) Python3 #!/usr/bin/env python3#-*- coding: utf-8 -*- import subprocess def sendmessage(message="drink water"): subprocess.Popen(['notify-send', message]) return if __name__ == '__main__': sendmessage() Note: #!/usr/bin/python3 (specifying the path of script interpreter) is necessary if wish to make the script executable. Assuming we have saved this script as my_script.py under our home directory, we can make it executable by entering the following command in our terminal: $ sudo chmod +x my_script.py We can test our script if it is working properly: ./my_script.py This will send a notification as the message “drink water”. The crontab scheduling expression has the following parts: To schedule our script to be executed, we need to enter the crontab scheduling expression into the crontab file. To do that, simply enter the following in the terminal: crontab -e You might be prompted to select an editor, choose nano and append the following line to the end of the opened crontab file: * */2 * * * /home/$(USER)/my_script.py where $(USER) can be replaced with your username. Save changes and exit. This will schedule our Python script to run every 2 hours. It will list all the scheduled jobs. crontab -l There are a few things to keep in mind before scheduling cron jobs: All cron jobs are scheduled in the local time zone in which the system where the jobs are being scheduled operates. This could be troublesome if jobs are being scheduled on servers with multinational personnel using it. Especially if the users also belong to countries that follow Daylight Savings Time practice. All cron jobs run in their own isolated, anonymous shell sessions and their output to STDOUT (if any) must be directed to a file if we wish to see them. All cron jobs run in the context of the user for which they were scheduled. It is therefore always good practice to provide an absolute path to scripts and output files to avoid any confusion and cluttering. Picked python-utility Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n18 Jul, 2021" }, { "code": null, "e": 106, "s": 28, "text": "In this article, we will discuss how to schedule Python scripts with crontab." }, { "code": null, "e": 568, "s": 106, "text": "The Cron job utility is a time-based job scheduler in Unix-like operating systems. Cron allows Linux and Unix users to run commands or scripts at a given time and date. One can schedule scripts to be executed periodically. The crontab is a list of commands that you want to run on a regular schedule, and also the name of the command used to manage that list. cron is the system process that will automatically perform tasks for you according to a set schedule." }, { "code": null, "e": 853, "s": 568, "text": "Below is a simple Python script that sends a notification message to remind the user to drink water. We will be scheduling this script to send a notification every 2 hours. (the script is tested for Linux-based systems only, but the scheduling process will be similar with any script)" }, { "code": null, "e": 861, "s": 853, "text": "Python3" }, { "code": "#!/usr/bin/env python3#-*- coding: utf-8 -*- import subprocess def sendmessage(message=\"drink water\"): subprocess.Popen(['notify-send', message]) return if __name__ == '__main__': sendmessage()", "e": 1067, "s": 861, "text": null }, { "code": null, "e": 1343, "s": 1067, "text": "Note: #!/usr/bin/python3 (specifying the path of script interpreter) is necessary if wish to make the script executable. Assuming we have saved this script as my_script.py under our home directory, we can make it executable by entering the following command in our terminal:" }, { "code": null, "e": 1372, "s": 1343, "text": "$ sudo chmod +x my_script.py" }, { "code": null, "e": 1422, "s": 1372, "text": "We can test our script if it is working properly:" }, { "code": null, "e": 1437, "s": 1422, "text": "./my_script.py" }, { "code": null, "e": 1497, "s": 1437, "text": "This will send a notification as the message “drink water”." }, { "code": null, "e": 1556, "s": 1497, "text": "The crontab scheduling expression has the following parts:" }, { "code": null, "e": 1725, "s": 1556, "text": "To schedule our script to be executed, we need to enter the crontab scheduling expression into the crontab file. To do that, simply enter the following in the terminal:" }, { "code": null, "e": 1736, "s": 1725, "text": "crontab -e" }, { "code": null, "e": 1860, "s": 1736, "text": "You might be prompted to select an editor, choose nano and append the following line to the end of the opened crontab file:" }, { "code": null, "e": 1899, "s": 1860, "text": "* */2 * * * /home/$(USER)/my_script.py" }, { "code": null, "e": 2031, "s": 1899, "text": "where $(USER) can be replaced with your username. Save changes and exit. This will schedule our Python script to run every 2 hours." }, { "code": null, "e": 2068, "s": 2031, "text": "It will list all the scheduled jobs." }, { "code": null, "e": 2079, "s": 2068, "text": "crontab -l" }, { "code": null, "e": 2147, "s": 2079, "text": "There are a few things to keep in mind before scheduling cron jobs:" }, { "code": null, "e": 2460, "s": 2147, "text": "All cron jobs are scheduled in the local time zone in which the system where the jobs are being scheduled operates. This could be troublesome if jobs are being scheduled on servers with multinational personnel using it. Especially if the users also belong to countries that follow Daylight Savings Time practice." }, { "code": null, "e": 2613, "s": 2460, "text": "All cron jobs run in their own isolated, anonymous shell sessions and their output to STDOUT (if any) must be directed to a file if we wish to see them." }, { "code": null, "e": 2821, "s": 2613, "text": "All cron jobs run in the context of the user for which they were scheduled. It is therefore always good practice to provide an absolute path to scripts and output files to avoid any confusion and cluttering." }, { "code": null, "e": 2828, "s": 2821, "text": "Picked" }, { "code": null, "e": 2843, "s": 2828, "text": "python-utility" }, { "code": null, "e": 2850, "s": 2843, "text": "Python" } ]
Stream.max() method in Java with Examples
06 Dec, 2018 Stream.max() returns the maximum element of the stream based on the provided Comparator. A Comparator is a comparison function, which imposes a total ordering on some collection of objects. max() is a terminal operation which combines stream elements and returns a summary result. So, max() is a special case of reduction. The method returns Optional instance. Syntax : Optional<T> max(Comparator<? super T> comparator) Where, Optional is a container object which may or may not contain a non-null value and T is the type of objects that may be compared by this comparator Exception : This method throws NullPointerException if the maximum element is null. Example 1 : // Implementation of Stream.max()// to get the maximum element// of the Stream according to the// provided Comparator.import java.util.*;import java.util.Optional;import java.util.Comparator; class GFG { // Driver code public static void main(String[] args) { // Creating a list of integers List<Integer> list = Arrays.asList(-9, -18, 0, 25, 4); System.out.print("The maximum value is : "); // Using stream.max() to get maximum // element according to provided Comparator // and storing in variable var Integer var = list.stream().max(Integer::compare).get(); System.out.print(var); }} Output : The maximum value is : 25 Example 2 : // Implementation of Stream.max()// to get the maximum element// of the Stream according to the// provided Comparator.import java.util.*;import java.util.Optional;import java.util.Comparator; class GFG { // Driver code public static void main(String[] args) { // Creating a list of integers List<Integer> list = Arrays.asList(-9, -18, 0, 25, 4); // Using stream.max() to get maximum // element according to provided Comparator // Here, the smallest element in list // will be stored in variable var Optional<Integer> var = list.stream() .max(Comparator.reverseOrder()); // If a value is present, isPresent() // will return true, else display message if (var.isPresent()) { System.out.println(var.get()); } else { System.out.println("-1"); } }} Output : -18 Example 3 : // Implementation of Stream.max()// to get the maximum element// of the Stream according to the// provided Comparator.import java.util.*;import java.util.Optional;import java.util.Comparator; class GFG { // Driver code public static void main(String[] args) { // Creating a list of Strings List<String> list = Arrays.asList("G", "E", "E", "K", "g", "e", "e", "k"); // using Stream.max() method with Comparator // Here, the character with maximum ASCII value // is stored in variable MAX String MAX = list.stream().max(Comparator. comparing(String::valueOf)).get(); // Displaying the maximum element in // the stream according to provided Comparator System.out.println("Maximum element in the " + "stream is : " + MAX); }} Output : Maximum element in the stream is : k Example 4 : // Implementation of Stream.max()// to get the maximum element// of the Stream according to the// provided Comparator.import java.util.*;import java.util.Optional;import java.util.Comparator; class GFG { // Driver code public static void main(String[] args) { // creating an array of strings String[] array = { "Geeks", "for", "GeeksforGeeks", "GeeksQuiz" }; // Here, the Comparator compares the strings // based on their last characters and returns // the maximum value accordingly // The result is stored in variable MAX Optional<String> MAX = Arrays.stream(array).max((str1, str2) -> Character.compare(str1.charAt(str1.length() - 1), str2.charAt(str2.length() - 1))); // If a value is present, // isPresent() will return true if (MAX.isPresent()) System.out.println(MAX.get()); else System.out.println("-1"); }} Output : GeeksQuiz 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 Stream In Java Multidimensional Arrays in Java Singleton Class in Java Set in Java
[ { "code": null, "e": 54, "s": 26, "text": "\n06 Dec, 2018" }, { "code": null, "e": 415, "s": 54, "text": "Stream.max() returns the maximum element of the stream based on the provided Comparator. A Comparator is a comparison function, which imposes a total ordering on some collection of objects. max() is a terminal operation which combines stream elements and returns a summary result. So, max() is a special case of reduction. The method returns Optional instance." }, { "code": null, "e": 424, "s": 415, "text": "Syntax :" }, { "code": null, "e": 630, "s": 424, "text": "Optional<T> max(Comparator<? super T> comparator)\n\nWhere, Optional is a container object which\nmay or may not contain a non-null value \nand T is the type of objects\nthat may be compared by this comparator\n" }, { "code": null, "e": 714, "s": 630, "text": "Exception : This method throws NullPointerException if the maximum element is null." }, { "code": null, "e": 726, "s": 714, "text": "Example 1 :" }, { "code": "// Implementation of Stream.max()// to get the maximum element// of the Stream according to the// provided Comparator.import java.util.*;import java.util.Optional;import java.util.Comparator; class GFG { // Driver code public static void main(String[] args) { // Creating a list of integers List<Integer> list = Arrays.asList(-9, -18, 0, 25, 4); System.out.print(\"The maximum value is : \"); // Using stream.max() to get maximum // element according to provided Comparator // and storing in variable var Integer var = list.stream().max(Integer::compare).get(); System.out.print(var); }}", "e": 1391, "s": 726, "text": null }, { "code": null, "e": 1400, "s": 1391, "text": "Output :" }, { "code": null, "e": 1427, "s": 1400, "text": "The maximum value is : 25\n" }, { "code": null, "e": 1439, "s": 1427, "text": "Example 2 :" }, { "code": "// Implementation of Stream.max()// to get the maximum element// of the Stream according to the// provided Comparator.import java.util.*;import java.util.Optional;import java.util.Comparator; class GFG { // Driver code public static void main(String[] args) { // Creating a list of integers List<Integer> list = Arrays.asList(-9, -18, 0, 25, 4); // Using stream.max() to get maximum // element according to provided Comparator // Here, the smallest element in list // will be stored in variable var Optional<Integer> var = list.stream() .max(Comparator.reverseOrder()); // If a value is present, isPresent() // will return true, else display message if (var.isPresent()) { System.out.println(var.get()); } else { System.out.println(\"-1\"); } }}", "e": 2337, "s": 1439, "text": null }, { "code": null, "e": 2346, "s": 2337, "text": "Output :" }, { "code": null, "e": 2351, "s": 2346, "text": "-18\n" }, { "code": null, "e": 2363, "s": 2351, "text": "Example 3 :" }, { "code": "// Implementation of Stream.max()// to get the maximum element// of the Stream according to the// provided Comparator.import java.util.*;import java.util.Optional;import java.util.Comparator; class GFG { // Driver code public static void main(String[] args) { // Creating a list of Strings List<String> list = Arrays.asList(\"G\", \"E\", \"E\", \"K\", \"g\", \"e\", \"e\", \"k\"); // using Stream.max() method with Comparator // Here, the character with maximum ASCII value // is stored in variable MAX String MAX = list.stream().max(Comparator. comparing(String::valueOf)).get(); // Displaying the maximum element in // the stream according to provided Comparator System.out.println(\"Maximum element in the \" + \"stream is : \" + MAX); }}", "e": 3258, "s": 2363, "text": null }, { "code": null, "e": 3267, "s": 3258, "text": "Output :" }, { "code": null, "e": 3305, "s": 3267, "text": "Maximum element in the stream is : k\n" }, { "code": null, "e": 3317, "s": 3305, "text": "Example 4 :" }, { "code": "// Implementation of Stream.max()// to get the maximum element// of the Stream according to the// provided Comparator.import java.util.*;import java.util.Optional;import java.util.Comparator; class GFG { // Driver code public static void main(String[] args) { // creating an array of strings String[] array = { \"Geeks\", \"for\", \"GeeksforGeeks\", \"GeeksQuiz\" }; // Here, the Comparator compares the strings // based on their last characters and returns // the maximum value accordingly // The result is stored in variable MAX Optional<String> MAX = Arrays.stream(array).max((str1, str2) -> Character.compare(str1.charAt(str1.length() - 1), str2.charAt(str2.length() - 1))); // If a value is present, // isPresent() will return true if (MAX.isPresent()) System.out.println(MAX.get()); else System.out.println(\"-1\"); }}", "e": 4359, "s": 3317, "text": null }, { "code": null, "e": 4368, "s": 4359, "text": "Output :" }, { "code": null, "e": 4379, "s": 4368, "text": "GeeksQuiz\n" }, { "code": null, "e": 4399, "s": 4379, "text": "Java - util package" }, { "code": null, "e": 4414, "s": 4399, "text": "Java-Functions" }, { "code": null, "e": 4426, "s": 4414, "text": "java-stream" }, { "code": null, "e": 4448, "s": 4426, "text": "Java-Stream interface" }, { "code": null, "e": 4453, "s": 4448, "text": "Java" }, { "code": null, "e": 4458, "s": 4453, "text": "Java" }, { "code": null, "e": 4556, "s": 4458, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4607, "s": 4556, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 4638, "s": 4607, "text": "How to iterate any Map in Java" }, { "code": null, "e": 4657, "s": 4638, "text": "Interfaces in Java" }, { "code": null, "e": 4687, "s": 4657, "text": "HashMap in Java with Examples" }, { "code": null, "e": 4705, "s": 4687, "text": "ArrayList in Java" }, { "code": null, "e": 4725, "s": 4705, "text": "Collections in Java" }, { "code": null, "e": 4740, "s": 4725, "text": "Stream In Java" }, { "code": null, "e": 4772, "s": 4740, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 4796, "s": 4772, "text": "Singleton Class in Java" } ]
How to open popup using Angular and Bootstrap ?
31 May, 2020 Adding Bootstrap to your Angular application is an easy process. Just write the following command in your Angular CLI. It will add bootstrap into your node_modules folder. ng add @ng-bootstrap/ng-bootstrap Approach: Import NgbModal module in the TypeScript file of the corresponding component, and then we have to write code for the popup model by using the above module in the HTML file of the corresponding component. Syntax: In typescript file:import {NgbModal} from '@ng-bootstrap/ng-bootstrap'; import {NgbModal} from '@ng-bootstrap/ng-bootstrap'; In html file:<ng-template #content let-modal> ... </ng-template> <ng-template #content let-modal> ... </ng-template> Example: modal-basic.ts import {Component} from '@angular/core'; import {NgbModal, ModalDismissReasons} from '@ng-bootstrap/ng-bootstrap'; @Component({ selector: 'ngbd-modal-basic', templateUrl: './modal-basic.html'})export class NgbdModalBasic { closeResult = ''; constructor(private modalService: NgbModal) {} open(content) { this.modalService.open(content, {ariaLabelledBy: 'modal-basic-title'}).result.then((result) => { this.closeResult = `Closed with: ${result}`; }, (reason) => { this.closeResult = `Dismissed ${this.getDismissReason(reason)}`; }); } private getDismissReason(reason: any): string { if (reason === ModalDismissReasons.ESC) { return 'by pressing ESC'; } else if (reason === ModalDismissReasons.BACKDROP_CLICK) { return 'by clicking on a backdrop'; } else { return `with: ${reason}`; } }} Now, we have to use ng-template to construct the model which will create a popup. Example: modal-basic.html <ng-template #content let-modal> <div class="modal-header"> <h4 class="modal-title" id="modal-basic-title"> Geeks of Geeks </h4> <button type="button" class="close" aria-label="Close" (click)= "modal.dismiss('Cross click')"> <span aria-hidden="true"> × </span> </button> </div> <div class="modal-body"> <form> <div class="form-group"> <label for="dateOfBirth"> Date of birth </label> <div class="input-group"> <input id="dateOfBirth" class="form-control" placeholder="yyyy-mm-dd" name="dp" ngbDatepicker #dp="ngbDatepicker"> <div class="input-group-append"> <button class="btn btn-outline-secondary calendar" (click)="dp.toggle()" type="button"> </button> </div> </div> </div> </form> </div> <div class="modal-footer"> <button type="button" class="btn btn-outline-dark" (click)="modal.close('Save click')"> Save </button> </div></ng-template> <button class="btn btn-lg btn-outline-primary" (click)="open(content)"> Popup using Angular and Bootstrap</button> Output: AngularJS-Misc Bootstrap-Misc Picked AngularJS Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Angular File Upload Angular | keyup event Auth Guards in Angular 9/10/11 Routing in Angular 9/10 What is AOT and JIT Compiler in Angular ? Top 10 Projects For Beginners To Practice HTML and CSS Skills Installation of Node.js on Linux Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 28, "s": 0, "text": "\n31 May, 2020" }, { "code": null, "e": 200, "s": 28, "text": "Adding Bootstrap to your Angular application is an easy process. Just write the following command in your Angular CLI. It will add bootstrap into your node_modules folder." }, { "code": null, "e": 235, "s": 200, "text": "ng add @ng-bootstrap/ng-bootstrap\n" }, { "code": null, "e": 449, "s": 235, "text": "Approach: Import NgbModal module in the TypeScript file of the corresponding component, and then we have to write code for the popup model by using the above module in the HTML file of the corresponding component." }, { "code": null, "e": 457, "s": 449, "text": "Syntax:" }, { "code": null, "e": 530, "s": 457, "text": "In typescript file:import {NgbModal} from '@ng-bootstrap/ng-bootstrap';\n" }, { "code": null, "e": 584, "s": 530, "text": "import {NgbModal} from '@ng-bootstrap/ng-bootstrap';\n" }, { "code": null, "e": 652, "s": 584, "text": "In html file:<ng-template #content let-modal>\n ...\n</ng-template>\n" }, { "code": null, "e": 707, "s": 652, "text": "<ng-template #content let-modal>\n ...\n</ng-template>\n" }, { "code": null, "e": 731, "s": 707, "text": "Example: modal-basic.ts" }, { "code": "import {Component} from '@angular/core'; import {NgbModal, ModalDismissReasons} from '@ng-bootstrap/ng-bootstrap'; @Component({ selector: 'ngbd-modal-basic', templateUrl: './modal-basic.html'})export class NgbdModalBasic { closeResult = ''; constructor(private modalService: NgbModal) {} open(content) { this.modalService.open(content, {ariaLabelledBy: 'modal-basic-title'}).result.then((result) => { this.closeResult = `Closed with: ${result}`; }, (reason) => { this.closeResult = `Dismissed ${this.getDismissReason(reason)}`; }); } private getDismissReason(reason: any): string { if (reason === ModalDismissReasons.ESC) { return 'by pressing ESC'; } else if (reason === ModalDismissReasons.BACKDROP_CLICK) { return 'by clicking on a backdrop'; } else { return `with: ${reason}`; } }}", "e": 1602, "s": 731, "text": null }, { "code": null, "e": 1684, "s": 1602, "text": "Now, we have to use ng-template to construct the model which will create a popup." }, { "code": null, "e": 1710, "s": 1684, "text": "Example: modal-basic.html" }, { "code": "<ng-template #content let-modal> <div class=\"modal-header\"> <h4 class=\"modal-title\" id=\"modal-basic-title\"> Geeks of Geeks </h4> <button type=\"button\" class=\"close\" aria-label=\"Close\" (click)= \"modal.dismiss('Cross click')\"> <span aria-hidden=\"true\"> × </span> </button> </div> <div class=\"modal-body\"> <form> <div class=\"form-group\"> <label for=\"dateOfBirth\"> Date of birth </label> <div class=\"input-group\"> <input id=\"dateOfBirth\" class=\"form-control\" placeholder=\"yyyy-mm-dd\" name=\"dp\" ngbDatepicker #dp=\"ngbDatepicker\"> <div class=\"input-group-append\"> <button class=\"btn btn-outline-secondary calendar\" (click)=\"dp.toggle()\" type=\"button\"> </button> </div> </div> </div> </form> </div> <div class=\"modal-footer\"> <button type=\"button\" class=\"btn btn-outline-dark\" (click)=\"modal.close('Save click')\"> Save </button> </div></ng-template> <button class=\"btn btn-lg btn-outline-primary\" (click)=\"open(content)\"> Popup using Angular and Bootstrap</button>", "e": 3260, "s": 1710, "text": null }, { "code": null, "e": 3268, "s": 3260, "text": "Output:" }, { "code": null, "e": 3283, "s": 3268, "text": "AngularJS-Misc" }, { "code": null, "e": 3298, "s": 3283, "text": "Bootstrap-Misc" }, { "code": null, "e": 3305, "s": 3298, "text": "Picked" }, { "code": null, "e": 3315, "s": 3305, "text": "AngularJS" }, { "code": null, "e": 3332, "s": 3315, "text": "Web Technologies" }, { "code": null, "e": 3359, "s": 3332, "text": "Web technologies Questions" }, { "code": null, "e": 3457, "s": 3359, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3477, "s": 3457, "text": "Angular File Upload" }, { "code": null, "e": 3499, "s": 3477, "text": "Angular | keyup event" }, { "code": null, "e": 3530, "s": 3499, "text": "Auth Guards in Angular 9/10/11" }, { "code": null, "e": 3554, "s": 3530, "text": "Routing in Angular 9/10" }, { "code": null, "e": 3596, "s": 3554, "text": "What is AOT and JIT Compiler in Angular ?" }, { "code": null, "e": 3658, "s": 3596, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 3691, "s": 3658, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 3752, "s": 3691, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 3802, "s": 3752, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Multiset of Pairs in C++ with Examples
19 Dec, 2021 What is Multiset? A multiset is an associative container that can hold a number of elements in a specific order. Unlike a set, a multiset can contain multiple occurrences of the same element. Some of the functions associated with a multiset: begin(): Returns an iterator to the first element in the multiset. end(): Returns an iterator to the theoretical element that follows the last element in the multiset. size(): Returns the number of elements in the multiset. max_size(): Returns the maximum number of elements that the multiset can hold. empty(): Returns whether the multiset is empty. What is 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? To access elements of a pair use the dot (.) operator. Syntax: auto fistElement = myPair.first; auto fistElement = myPair.second; Multiset of pairs A multiset of pairs is a multiset in which each element 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 particular order, in such cases multiset of pairs comes in handy. Syntax: multiset<pair<dataType1, dataType2>> myMultiset; Here, dataType1 and dataType2 can be similar or dismilar data types. Example 1: Below is the C++ program to demonstrate the working of a multiset of pairs having integer values. C++ // C++ program to illustrate the// implementation of multiset of// pairs#include <bits/stdc++.h>using namespace std; // Function to print multiset // elementsvoid print(multiset<pair<int, int>> &multisetOfPairs){ // Iterating over multiset of // pairs elements for (auto cuurentPair : multisetOfPairs) { // Each element is a tuple itself pair<int, int> pr = cuurentPair; // Printing pair elements cout << "[ " << pr.first << ' ' << pr.second << " ]"<< '\n'; }} // Driver codeint main(){ // Declaring a multiset of tuples multiset<pair<int, int>> multisetOfPairs; // Initializing a pair pair<int, int> pair1; pair1 = make_pair(1, 2); // Initializing a pair pair<int, int> pair2; pair2 = make_pair(3, 4); // Initializing another pair pair<int, int> pair3; pair3 = make_pair(5, 6); // Initializing another pair pair<int, int> pair4; pair4 = make_pair(7, 8); // Initializing another pair pair<int, int> pair5; pair5 = make_pair(9, 10); // Inserting into multiset multisetOfPairs.insert(pair1); multisetOfPairs.insert(pair2); multisetOfPairs.insert(pair3); multisetOfPairs.insert(pair4); multisetOfPairs.insert(pair5); // Calling print function print(multisetOfPairs); return 0;} Output: [ 1 2 ][ 3 4 ][ 5 6 ][ 7 8 ][ 9 10 ] Explanation: In the above output, the elements are arranged in sorted order of pairs in the multiset of pairs. Example 2: Below is the C++ program to demonstrate the working of a multiset of pairs having string values. C++ // C++ program to illustrate the// implementation of multiset of// pairs#include <bits/stdc++.h>using namespace std; // Function to print multiset elementsvoid print(multiset<pair<string, string>> &multisetOfPairs){ // Iterating over multiset of pairs elements for (auto currentPair : multisetOfPairs) { // Each element is a pair itself pair<string, string> pr = currentPair; // Printing pair elements cout << "[ " << pr.first << ' ' << pr.second << " ]"<< '\n'; }} // Driver codeint main(){ // Declaring a multiset of pairs multiset<pair<string, string>> multisetOfPairs; // Initializing a pair pair<string, string> pair1; pair1 = make_pair("GeeksforGeeks", "GFG"); // Initializing a pair pair<string, string> pair2; pair2 = make_pair("Swift", "Python"); // Initializing another pair pair<string, string> pair3; pair3 = make_pair("C++", "C"); // Initializing another pair pair<string, string> pair4; pair4 = make_pair("PHP", "HTML"); // Initializing another pair pair<string, string> pair5; pair5 = make_pair("Javascript", "CSS"); // Inserting into multiset multisetOfPairs.insert(pair1); multisetOfPairs.insert(pair2); multisetOfPairs.insert(pair3); multisetOfPairs.insert(pair4); multisetOfPairs.insert(pair5); // Calling print function print(multisetOfPairs); return 0;} Output: [ C++ C ][ GeeksforGeeks GFG ][ Javascript CSS ][ PHP HTML ][ Swift Python ] Explanation: In the above output, the elements are arranged in sorted order of pairs in the multiset of pairs. cpp-multiset cpp-pair STL C++ STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n19 Dec, 2021" }, { "code": null, "e": 46, "s": 28, "text": "What is Multiset?" }, { "code": null, "e": 220, "s": 46, "text": "A multiset is an associative container that can hold a number of elements in a specific order. Unlike a set, a multiset can contain multiple occurrences of the same element." }, { "code": null, "e": 272, "s": 220, "text": "Some of the functions associated with a multiset: " }, { "code": null, "e": 340, "s": 272, "text": "begin(): Returns an iterator to the first element in the multiset. " }, { "code": null, "e": 441, "s": 340, "text": "end(): Returns an iterator to the theoretical element that follows the last element in the multiset." }, { "code": null, "e": 497, "s": 441, "text": "size(): Returns the number of elements in the multiset." }, { "code": null, "e": 576, "s": 497, "text": "max_size(): Returns the maximum number of elements that the multiset can hold." }, { "code": null, "e": 624, "s": 576, "text": "empty(): Returns whether the multiset is empty." }, { "code": null, "e": 638, "s": 624, "text": "What is Pair?" }, { "code": null, "e": 737, "s": 638, "text": "Utility header in C++ provides us pair container. A pair consists of two data elements or objects." }, { "code": null, "e": 855, "s": 737, "text": "The first element is referenced as ‘first’ and the second element as ‘second’ and the order is fixed (first, second)." }, { "code": null, "e": 1003, "s": 855, "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": 1224, "s": 1003, "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": 1335, "s": 1224, "text": "To access the elements, we use variable name followed by dot operator followed by the keyword first or second." }, { "code": null, "e": 1357, "s": 1335, "text": "How to access a pair?" }, { "code": null, "e": 1412, "s": 1357, "text": "To access elements of a pair use the dot (.) operator." }, { "code": null, "e": 1420, "s": 1412, "text": "Syntax:" }, { "code": null, "e": 1487, "s": 1420, "text": "auto fistElement = myPair.first;\nauto fistElement = myPair.second;" }, { "code": null, "e": 1505, "s": 1487, "text": "Multiset of pairs" }, { "code": null, "e": 1851, "s": 1505, "text": "A multiset of pairs is a multiset in which each element 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 particular order, in such cases multiset of pairs comes in handy. " }, { "code": null, "e": 1859, "s": 1851, "text": "Syntax:" }, { "code": null, "e": 1908, "s": 1859, "text": "multiset<pair<dataType1, dataType2>> myMultiset;" }, { "code": null, "e": 1915, "s": 1908, "text": " Here," }, { "code": null, "e": 1978, "s": 1915, "text": "dataType1 and dataType2 can be similar or dismilar data types." }, { "code": null, "e": 2087, "s": 1978, "text": "Example 1: Below is the C++ program to demonstrate the working of a multiset of pairs having integer values." }, { "code": null, "e": 2091, "s": 2087, "text": "C++" }, { "code": "// C++ program to illustrate the// implementation of multiset of// pairs#include <bits/stdc++.h>using namespace std; // Function to print multiset // elementsvoid print(multiset<pair<int, int>> &multisetOfPairs){ // Iterating over multiset of // pairs elements for (auto cuurentPair : multisetOfPairs) { // Each element is a tuple itself pair<int, int> pr = cuurentPair; // Printing pair elements cout << \"[ \" << pr.first << ' ' << pr.second << \" ]\"<< '\\n'; }} // Driver codeint main(){ // Declaring a multiset of tuples multiset<pair<int, int>> multisetOfPairs; // Initializing a pair pair<int, int> pair1; pair1 = make_pair(1, 2); // Initializing a pair pair<int, int> pair2; pair2 = make_pair(3, 4); // Initializing another pair pair<int, int> pair3; pair3 = make_pair(5, 6); // Initializing another pair pair<int, int> pair4; pair4 = make_pair(7, 8); // Initializing another pair pair<int, int> pair5; pair5 = make_pair(9, 10); // Inserting into multiset multisetOfPairs.insert(pair1); multisetOfPairs.insert(pair2); multisetOfPairs.insert(pair3); multisetOfPairs.insert(pair4); multisetOfPairs.insert(pair5); // Calling print function print(multisetOfPairs); return 0;}", "e": 3358, "s": 2091, "text": null }, { "code": null, "e": 3366, "s": 3358, "text": "Output:" }, { "code": null, "e": 3403, "s": 3366, "text": "[ 1 2 ][ 3 4 ][ 5 6 ][ 7 8 ][ 9 10 ]" }, { "code": null, "e": 3416, "s": 3403, "text": "Explanation:" }, { "code": null, "e": 3514, "s": 3416, "text": "In the above output, the elements are arranged in sorted order of pairs in the multiset of pairs." }, { "code": null, "e": 3622, "s": 3514, "text": "Example 2: Below is the C++ program to demonstrate the working of a multiset of pairs having string values." }, { "code": null, "e": 3626, "s": 3622, "text": "C++" }, { "code": "// C++ program to illustrate the// implementation of multiset of// pairs#include <bits/stdc++.h>using namespace std; // Function to print multiset elementsvoid print(multiset<pair<string, string>> &multisetOfPairs){ // Iterating over multiset of pairs elements for (auto currentPair : multisetOfPairs) { // Each element is a pair itself pair<string, string> pr = currentPair; // Printing pair elements cout << \"[ \" << pr.first << ' ' << pr.second << \" ]\"<< '\\n'; }} // Driver codeint main(){ // Declaring a multiset of pairs multiset<pair<string, string>> multisetOfPairs; // Initializing a pair pair<string, string> pair1; pair1 = make_pair(\"GeeksforGeeks\", \"GFG\"); // Initializing a pair pair<string, string> pair2; pair2 = make_pair(\"Swift\", \"Python\"); // Initializing another pair pair<string, string> pair3; pair3 = make_pair(\"C++\", \"C\"); // Initializing another pair pair<string, string> pair4; pair4 = make_pair(\"PHP\", \"HTML\"); // Initializing another pair pair<string, string> pair5; pair5 = make_pair(\"Javascript\", \"CSS\"); // Inserting into multiset multisetOfPairs.insert(pair1); multisetOfPairs.insert(pair2); multisetOfPairs.insert(pair3); multisetOfPairs.insert(pair4); multisetOfPairs.insert(pair5); // Calling print function print(multisetOfPairs); return 0;}", "e": 5069, "s": 3626, "text": null }, { "code": null, "e": 5077, "s": 5069, "text": "Output:" }, { "code": null, "e": 5154, "s": 5077, "text": "[ C++ C ][ GeeksforGeeks GFG ][ Javascript CSS ][ PHP HTML ][ Swift Python ]" }, { "code": null, "e": 5167, "s": 5154, "text": "Explanation:" }, { "code": null, "e": 5265, "s": 5167, "text": "In the above output, the elements are arranged in sorted order of pairs in the multiset of pairs." }, { "code": null, "e": 5278, "s": 5265, "text": "cpp-multiset" }, { "code": null, "e": 5287, "s": 5278, "text": "cpp-pair" }, { "code": null, "e": 5291, "s": 5287, "text": "STL" }, { "code": null, "e": 5295, "s": 5291, "text": "C++" }, { "code": null, "e": 5299, "s": 5295, "text": "STL" }, { "code": null, "e": 5303, "s": 5299, "text": "CPP" } ]
How to create a DataFrame in Python?
Dataframe is a 2D data structure. Dataframe is used to represent data in tabular format in rows and columns. It is like a spreadsheet or a sql table. Dataframe is a Pandas object. To create a dataframe, we need to import pandas. Dataframe can be created using dataframe() function. The dataframe() takes one or two parameters. The first one is the data which is to be filled in the dataframe table. The data can be in form of list of lists or dictionary of lists. In case of list of lists data, the second parameter is the columns name. import pandas as pd data={'Name':['Karan','Rohit','Sahil','Aryan'],'Age':[23,22,21,24]} df=pd.dataframe(data) df #print the dataframe The output will be a table having two columns named ‘Name’ and ‘Age’ with the provided data fed into the table. import pandas as pd data=[[‘Karan’,23],[‘Rohit’,22],[‘Sahil’,21],[‘Aryan’,24]] df=pd.dataframe(data,columns=[‘Name’,’Age’]) df This also gives the same output. The only difference is in the form in which the data is provided. Since the columns names are not specified earlier, it is needed to pass column names as arguments in the dataframe() function. import pandas as pd data={'Name':['Karan','Rohit','Sahil','Aryan'],'Age':[23,22,21,24]} df=pd.dataframe(data,index=[‘No.1’,’No.2’,’No.3’,’No.4’]) df This creates the same dataframe with indexes as mentioned in the index list.
[ { "code": null, "e": 1367, "s": 1187, "text": "Dataframe is a 2D data structure. Dataframe is used to represent data in tabular format in rows and columns. It is like a spreadsheet or a sql table. Dataframe is a Pandas object." }, { "code": null, "e": 1724, "s": 1367, "text": "To create a dataframe, we need to import pandas. Dataframe can be created using dataframe() function. The dataframe() takes one or two parameters. The first one is the data which is to be filled in the dataframe table. The data can be in form of list of lists or dictionary of lists. In case of list of lists data, the second parameter is the columns name." }, { "code": null, "e": 1861, "s": 1724, "text": "import pandas as pd\n\ndata={'Name':['Karan','Rohit','Sahil','Aryan'],'Age':[23,22,21,24]}\n\ndf=pd.dataframe(data)\n\ndf #print the dataframe" }, { "code": null, "e": 1973, "s": 1861, "text": "The output will be a table having two columns named ‘Name’ and ‘Age’ with the provided data fed into the table." }, { "code": null, "e": 2103, "s": 1973, "text": "import pandas as pd\n\ndata=[[‘Karan’,23],[‘Rohit’,22],[‘Sahil’,21],[‘Aryan’,24]]\n\ndf=pd.dataframe(data,columns=[‘Name’,’Age’])\n\ndf" }, { "code": null, "e": 2329, "s": 2103, "text": "This also gives the same output. The only difference is in the form in which the data is provided. Since the columns names are not specified earlier, it is needed to pass column names as arguments in the dataframe() function." }, { "code": null, "e": 2481, "s": 2329, "text": "import pandas as pd\n\ndata={'Name':['Karan','Rohit','Sahil','Aryan'],'Age':[23,22,21,24]}\n\ndf=pd.dataframe(data,index=[‘No.1’,’No.2’,’No.3’,’No.4’])\n\ndf" }, { "code": null, "e": 2558, "s": 2481, "text": "This creates the same dataframe with indexes as mentioned in the index list." } ]
How to skip over an element in .map() ?
23 Jul, 2020 The map() function in JavaScript is used to generate a new array by calling function for every array element. Note: map() method calls the function for every array element in order. map() does not execute for array element that has no values. map() does not change the original array. There are various ways to skip over an element in the map: Using if loop inside the function to be executed to add the constraints to skip over that element. Using the filter method. Using the arrow function. Example 1: Adding the constraints inside the loop. HTML <!DOCTYPE html><html> <body> <p style="color: green; font-size: 30px;"> GeeksforGeeks </p> <p>[1,-1,-2,6,7,8]</p> <button onclick="myFunction()"> Click to skip negative values </button> <p id="demo"></p> <script> function display(num) { if (num > 0) { return num; } else { return "null"; } } var values = [1, -1, -2, 6, 7, 8] var filtered = values.map(display) function myFunction() { x = document.getElementById("demo") x.innerHTML = filtered; } </script></body> </html> Output: Example 2: Using the filter method. HTML <!DOCTYPE html><html> <body> <p style="color: green; font-size: 30px;"> GeeksforGeeks </p> <p>[1,-1,-2,6,7,8]</p> <button onclick="myFunction()"> Click to skip negative values </button> <p id="demo"></p> <script> function isPositive(value) { return value > 0; } function display(num) { return num; } var values = [1, -1, -2, 6, 7, 8] var filtered = values.map(display).filter(isPositive); function myFunction() { x = document.getElementById("demo") x.innerHTML = filtered; } </script></body> </html> Output: Example 3: Using the arrow function. HTML <!DOCTYPE html><html> <body> <p style="color: green; font-size: 30px;"> GeeksforGeeks </p> <p>Given<br>images = [{src: 1}, {src: 2}, {src: 3}, {src: 4}]<br>Skip src=3</p> <button onclick="myFunction()">Skip</button> <p id="demo"><br></p> <script> let images = [{ src: 1 }, { src: 2 }, { src: 3 }, { src: 4 }]; let sources = images.filter( img => img.src != 3).map(img => img.src); function myFunction() { x = document.getElementById("demo") x.innerHTML = sources; } </script></body> </html> Output: Before Clicking the Button: Before clicking After Clicking the Button: After clicking the button HTML-Misc JavaScript-Misc HTML JavaScript Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n23 Jul, 2020" }, { "code": null, "e": 163, "s": 53, "text": "The map() function in JavaScript is used to generate a new array by calling function for every array element." }, { "code": null, "e": 169, "s": 163, "text": "Note:" }, { "code": null, "e": 235, "s": 169, "text": "map() method calls the function for every array element in order." }, { "code": null, "e": 296, "s": 235, "text": "map() does not execute for array element that has no values." }, { "code": null, "e": 338, "s": 296, "text": "map() does not change the original array." }, { "code": null, "e": 397, "s": 338, "text": "There are various ways to skip over an element in the map:" }, { "code": null, "e": 496, "s": 397, "text": "Using if loop inside the function to be executed to add the constraints to skip over that element." }, { "code": null, "e": 521, "s": 496, "text": "Using the filter method." }, { "code": null, "e": 547, "s": 521, "text": "Using the arrow function." }, { "code": null, "e": 598, "s": 547, "text": "Example 1: Adding the constraints inside the loop." }, { "code": null, "e": 603, "s": 598, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <body> <p style=\"color: green; font-size: 30px;\"> GeeksforGeeks </p> <p>[1,-1,-2,6,7,8]</p> <button onclick=\"myFunction()\"> Click to skip negative values </button> <p id=\"demo\"></p> <script> function display(num) { if (num > 0) { return num; } else { return \"null\"; } } var values = [1, -1, -2, 6, 7, 8] var filtered = values.map(display) function myFunction() { x = document.getElementById(\"demo\") x.innerHTML = filtered; } </script></body> </html>", "e": 1273, "s": 603, "text": null }, { "code": null, "e": 1281, "s": 1273, "text": "Output:" }, { "code": null, "e": 1317, "s": 1281, "text": "Example 2: Using the filter method." }, { "code": null, "e": 1322, "s": 1317, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <body> <p style=\"color: green; font-size: 30px;\"> GeeksforGeeks </p> <p>[1,-1,-2,6,7,8]</p> <button onclick=\"myFunction()\"> Click to skip negative values </button> <p id=\"demo\"></p> <script> function isPositive(value) { return value > 0; } function display(num) { return num; } var values = [1, -1, -2, 6, 7, 8] var filtered = values.map(display).filter(isPositive); function myFunction() { x = document.getElementById(\"demo\") x.innerHTML = filtered; } </script></body> </html>", "e": 2008, "s": 1322, "text": null }, { "code": null, "e": 2016, "s": 2008, "text": "Output:" }, { "code": null, "e": 2053, "s": 2016, "text": "Example 3: Using the arrow function." }, { "code": null, "e": 2058, "s": 2053, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <body> <p style=\"color: green; font-size: 30px;\"> GeeksforGeeks </p> <p>Given<br>images = [{src: 1}, {src: 2}, {src: 3}, {src: 4}]<br>Skip src=3</p> <button onclick=\"myFunction()\">Skip</button> <p id=\"demo\"><br></p> <script> let images = [{ src: 1 }, { src: 2 }, { src: 3 }, { src: 4 }]; let sources = images.filter( img => img.src != 3).map(img => img.src); function myFunction() { x = document.getElementById(\"demo\") x.innerHTML = sources; } </script></body> </html>", "e": 2702, "s": 2058, "text": null }, { "code": null, "e": 2711, "s": 2702, "text": "Output: " }, { "code": null, "e": 2739, "s": 2711, "text": "Before Clicking the Button:" }, { "code": null, "e": 2755, "s": 2739, "text": "Before clicking" }, { "code": null, "e": 2782, "s": 2755, "text": "After Clicking the Button:" }, { "code": null, "e": 2808, "s": 2782, "text": "After clicking the button" }, { "code": null, "e": 2818, "s": 2808, "text": "HTML-Misc" }, { "code": null, "e": 2834, "s": 2818, "text": "JavaScript-Misc" }, { "code": null, "e": 2839, "s": 2834, "text": "HTML" }, { "code": null, "e": 2850, "s": 2839, "text": "JavaScript" }, { "code": null, "e": 2867, "s": 2850, "text": "Web Technologies" }, { "code": null, "e": 2872, "s": 2867, "text": "HTML" } ]
Use of realloc()
28 May, 2017 Size of dynamically allocated memory can be changed by using realloc(). As per the C99 standard: void *realloc(void *ptr, size_t size); realloc deallocates the old object pointed to by ptr and returns a pointer to a new object that has the size specified by size. The contents of the new object is identical to that of the old object prior to deallocation, up to the lesser of the new and old sizes. Any bytes in the new object beyond the size of the old object have indeterminate values. The point to note is that realloc() should only be used for dynamically allocated memory. If the memory is not dynamically allocated, then behavior is undefined.For example, program 1 demonstrates incorrect use of realloc() and program 2 demonstrates correct use of realloc(). Program 1: Chapters descriptions off, selected captions settings, opens captions settings dialog captions off, selected English This is a modal window. Beginning of dialog window. Escape will cancel and close the window. End of dialog window. #include <stdio.h>#include <stdlib.h>int main(){ int arr[2], i; int *ptr = arr; int *ptr_new; arr[0] = 10; arr[1] = 20; // incorrect use of new_ptr: undefined behaviour ptr_new = (int *)realloc(ptr, sizeof(int)*3); *(ptr_new + 2) = 30; for(i = 0; i < 3; i++) printf("%d ", *(ptr_new + i)); getchar(); return 0;} Output:Undefined Behavior Program 2: #include <stdio.h>#include <stdlib.h>int main(){ int *ptr = (int *)malloc(sizeof(int)*2); int i; int *ptr_new; *ptr = 10; *(ptr + 1) = 20; ptr_new = (int *)realloc(ptr, sizeof(int)*3); *(ptr_new + 2) = 30; for(i = 0; i < 3; i++) printf("%d ", *(ptr_new + i)); getchar(); return 0;} Output:10 20 30 Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. C-Dynamic Memory Allocation C Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Substring in C++ Function Pointer in C Different Methods to Reverse a String in C++ std::string class in C++ Unordered Sets in C++ Standard Template Library rand() and srand() in C/C++ Enumeration (or enum) in C Memory Layout of C Programs C Language Introduction Power Function in C/C++
[ { "code": null, "e": 52, "s": 24, "text": "\n28 May, 2017" }, { "code": null, "e": 124, "s": 52, "text": "Size of dynamically allocated memory can be changed by using realloc()." }, { "code": null, "e": 149, "s": 124, "text": "As per the C99 standard:" }, { "code": "void *realloc(void *ptr, size_t size);", "e": 188, "s": 149, "text": null }, { "code": null, "e": 541, "s": 188, "text": "realloc deallocates the old object pointed to by ptr and returns a pointer to a new object that has the size specified by size. The contents of the new object is identical to that of the old object prior to deallocation, up to the lesser of the new and old sizes. Any bytes in the new object beyond the size of the old object have indeterminate values." }, { "code": null, "e": 818, "s": 541, "text": "The point to note is that realloc() should only be used for dynamically allocated memory. If the memory is not dynamically allocated, then behavior is undefined.For example, program 1 demonstrates incorrect use of realloc() and program 2 demonstrates correct use of realloc()." }, { "code": null, "e": 829, "s": 818, "text": "Program 1:" }, { "code": null, "e": 838, "s": 829, "text": "Chapters" }, { "code": null, "e": 865, "s": 838, "text": "descriptions off, selected" }, { "code": null, "e": 915, "s": 865, "text": "captions settings, opens captions settings dialog" }, { "code": null, "e": 938, "s": 915, "text": "captions off, selected" }, { "code": null, "e": 946, "s": 938, "text": "English" }, { "code": null, "e": 970, "s": 946, "text": "This is a modal window." }, { "code": null, "e": 1039, "s": 970, "text": "Beginning of dialog window. Escape will cancel and close the window." }, { "code": null, "e": 1061, "s": 1039, "text": "End of dialog window." }, { "code": "#include <stdio.h>#include <stdlib.h>int main(){ int arr[2], i; int *ptr = arr; int *ptr_new; arr[0] = 10; arr[1] = 20; // incorrect use of new_ptr: undefined behaviour ptr_new = (int *)realloc(ptr, sizeof(int)*3); *(ptr_new + 2) = 30; for(i = 0; i < 3; i++) printf(\"%d \", *(ptr_new + i)); getchar(); return 0;}", "e": 1423, "s": 1061, "text": null }, { "code": null, "e": 1449, "s": 1423, "text": "Output:Undefined Behavior" }, { "code": null, "e": 1460, "s": 1449, "text": "Program 2:" }, { "code": "#include <stdio.h>#include <stdlib.h>int main(){ int *ptr = (int *)malloc(sizeof(int)*2); int i; int *ptr_new; *ptr = 10; *(ptr + 1) = 20; ptr_new = (int *)realloc(ptr, sizeof(int)*3); *(ptr_new + 2) = 30; for(i = 0; i < 3; i++) printf(\"%d \", *(ptr_new + i)); getchar(); return 0;}", "e": 1781, "s": 1460, "text": null }, { "code": null, "e": 1797, "s": 1781, "text": "Output:10 20 30" }, { "code": null, "e": 1922, "s": 1797, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 1950, "s": 1922, "text": "C-Dynamic Memory Allocation" }, { "code": null, "e": 1961, "s": 1950, "text": "C Language" }, { "code": null, "e": 2059, "s": 1961, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2076, "s": 2059, "text": "Substring in C++" }, { "code": null, "e": 2098, "s": 2076, "text": "Function Pointer in C" }, { "code": null, "e": 2143, "s": 2098, "text": "Different Methods to Reverse a String in C++" }, { "code": null, "e": 2168, "s": 2143, "text": "std::string class in C++" }, { "code": null, "e": 2216, "s": 2168, "text": "Unordered Sets in C++ Standard Template Library" }, { "code": null, "e": 2244, "s": 2216, "text": "rand() and srand() in C/C++" }, { "code": null, "e": 2271, "s": 2244, "text": "Enumeration (or enum) in C" }, { "code": null, "e": 2299, "s": 2271, "text": "Memory Layout of C Programs" }, { "code": null, "e": 2323, "s": 2299, "text": "C Language Introduction" } ]
strpbrk() in C
02 May, 2018 This function finds the first character in the string s1 that matches any character specified in s2 (It excludes terminating null-characters). Syntax : char *strpbrk(const char *s1, const char *s2) Parameters : s1 : string to be scanned. s2 : string containing the characters to match. Return Value : It returns a pointer to the character in s1 that matches one of the characters in s2, else returns NULL. // C code to demonstrate the working of// strpbrk#include <stdio.h>#include <string.h> // Driver functionint main(){ // Declaring three strings char s1[] = "geeksforgeeks"; char s2[] = "app"; char s3[] = "kite"; char* r, *t; // Checks for matching character // no match found r = strpbrk(s1, s2); if (r != 0) printf("First matching character: %c\n", *r); else printf("Character not found"); // Checks for matching character // first match found at "e" t = strpbrk(s1, s3); if (t != 0) printf("\nFirst matching character: %c\n", *t); else printf("Character not found"); return (0);} Output: Character not found First matching character: e Practical ApplicationThis function can be used in game of lottery where the person having string with lettercoming first in victory wins, i.e. this can be used at any place where first person wins. // C code to demonstrate practical application// of strpbrk#include <stdio.h>#include <string.h> // Driver functionint main(){ // Initializing victory string char s1[] = "victory"; // Declaring lottery strings char s2[] = "a23"; char s3[] = "i22"; char* r, *t; // Use of strpbrk() r = strpbrk(s1, s2); t = strpbrk(s1, s3); // Checks if player 1 has won lottery if (r != 0) printf("Congrats u have won"); else printf("Better luck next time"); // Checks if player 2 has won lottery if (t != 0) printf("\nCongrats u have won"); else printf("Better luck next time"); return (0);} Output: Better luck next time Congrats u have won This article is contributed by Shantanu Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. SACHIN KUNTE C-Library cpp-string C Language C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Substring in C++ Function Pointer in C Multidimensional Arrays in C / C++ Left Shift and Right Shift Operators in C/C++ Different Methods to Reverse a String in C++ Vector in C++ STL Map in C++ Standard Template Library (STL) Initialize a vector in C++ (7 different ways) Set in C++ Standard Template Library (STL) vector erase() and clear() in C++
[ { "code": null, "e": 52, "s": 24, "text": "\n02 May, 2018" }, { "code": null, "e": 195, "s": 52, "text": "This function finds the first character in the string s1 that matches any character specified in s2 (It excludes terminating null-characters)." }, { "code": null, "e": 463, "s": 195, "text": "Syntax : \nchar *strpbrk(const char *s1, const char *s2)\n\nParameters :\ns1 : string to be scanned.\ns2 : string containing the characters to match.\n\nReturn Value :\nIt returns a pointer to the character in s1 that \nmatches one of the characters in s2, else returns NULL.\n" }, { "code": "// C code to demonstrate the working of// strpbrk#include <stdio.h>#include <string.h> // Driver functionint main(){ // Declaring three strings char s1[] = \"geeksforgeeks\"; char s2[] = \"app\"; char s3[] = \"kite\"; char* r, *t; // Checks for matching character // no match found r = strpbrk(s1, s2); if (r != 0) printf(\"First matching character: %c\\n\", *r); else printf(\"Character not found\"); // Checks for matching character // first match found at \"e\" t = strpbrk(s1, s3); if (t != 0) printf(\"\\nFirst matching character: %c\\n\", *t); else printf(\"Character not found\"); return (0);}", "e": 1129, "s": 463, "text": null }, { "code": null, "e": 1137, "s": 1129, "text": "Output:" }, { "code": null, "e": 1186, "s": 1137, "text": "Character not found\nFirst matching character: e\n" }, { "code": null, "e": 1384, "s": 1186, "text": "Practical ApplicationThis function can be used in game of lottery where the person having string with lettercoming first in victory wins, i.e. this can be used at any place where first person wins." }, { "code": "// C code to demonstrate practical application// of strpbrk#include <stdio.h>#include <string.h> // Driver functionint main(){ // Initializing victory string char s1[] = \"victory\"; // Declaring lottery strings char s2[] = \"a23\"; char s3[] = \"i22\"; char* r, *t; // Use of strpbrk() r = strpbrk(s1, s2); t = strpbrk(s1, s3); // Checks if player 1 has won lottery if (r != 0) printf(\"Congrats u have won\"); else printf(\"Better luck next time\"); // Checks if player 2 has won lottery if (t != 0) printf(\"\\nCongrats u have won\"); else printf(\"Better luck next time\"); return (0);}", "e": 2047, "s": 1384, "text": null }, { "code": null, "e": 2055, "s": 2047, "text": "Output:" }, { "code": null, "e": 2098, "s": 2055, "text": "Better luck next time\nCongrats u have won\n" }, { "code": null, "e": 2400, "s": 2098, "text": "This article is contributed by Shantanu Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 2525, "s": 2400, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 2538, "s": 2525, "text": "SACHIN KUNTE" }, { "code": null, "e": 2548, "s": 2538, "text": "C-Library" }, { "code": null, "e": 2559, "s": 2548, "text": "cpp-string" }, { "code": null, "e": 2570, "s": 2559, "text": "C Language" }, { "code": null, "e": 2574, "s": 2570, "text": "C++" }, { "code": null, "e": 2578, "s": 2574, "text": "CPP" }, { "code": null, "e": 2676, "s": 2578, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2693, "s": 2676, "text": "Substring in C++" }, { "code": null, "e": 2715, "s": 2693, "text": "Function Pointer in C" }, { "code": null, "e": 2750, "s": 2715, "text": "Multidimensional Arrays in C / C++" }, { "code": null, "e": 2796, "s": 2750, "text": "Left Shift and Right Shift Operators in C/C++" }, { "code": null, "e": 2841, "s": 2796, "text": "Different Methods to Reverse a String in C++" }, { "code": null, "e": 2859, "s": 2841, "text": "Vector in C++ STL" }, { "code": null, "e": 2902, "s": 2859, "text": "Map in C++ Standard Template Library (STL)" }, { "code": null, "e": 2948, "s": 2902, "text": "Initialize a vector in C++ (7 different ways)" }, { "code": null, "e": 2991, "s": 2948, "text": "Set in C++ Standard Template Library (STL)" } ]
React-Bootstrap Dropdown Component
04 May, 2021 React-Bootstrap is a front-end framework that was designed keeping react in mind. Dropdown Component provides a way to displaying lists of links or more actions within a menu when clicked over it. We can use the following approach in ReactJS to use the react-bootstrap Dropdown Component. Dropdown Props: alignRight: It is used to align the menu to the right side of the Dropdown toggle. as: It can be used as a custom element type for this component. drop: It is used to determine the location and direction of the Menu in relation to its toggle. flip: It is used to flip the dropdown in case of overlapping on the reference element. focusFirstItemOnShow: When the dropdown is opened, it is used to control the focus behavior for it. navbar: It is the attribute that is by default false and indicates whether dropdown is navbar related or not. onSelect: It is a callback function that is triggered when a menu item is selected. onToggle: It is used to trigger a callback when the visibility of the dropdown needs to be changed. show: It is used to indicate whether the dropdown is visible or not. bsPrefix: It is an escape hatch for working with strongly customized bootstrap CSS. SplitButton Props: disabled: It is used to disable the button. href: It is used to pass the href attribute to the underlying non-toggle button. id: It is the general HTML id attribute for the toggle button. menuAlign: It is used to responsively align the dropdown menu. menuRole: It is used for the ARIA accessible role applied which is applied to the menu component. onClick: It is the callback function that is passed as a handler for the non-toggle button. renderMenuOnMount: It is used to indicate whether to render the dropdown menu before the first time it is shown in the DOM. rootCloseEvent: It is used to close the component when which event is triggered outside this component. size: It denotes the size of the component. target: For the non-toggle Button, it is an anchor target passed to it. title: It is used to define the content of non-toggle Button. toggleLabel: For the toggle button, it is the accessible label. type: It is used to pass the type for the non-toggle button. variant: It is used to indicate the style variant for it. bsPrefix: It is an escape hatch for working with strongly customized bootstrap CSS. Dropdown.Toggle Props: as: It can be used as a custom element type for this component. childBsPrefix: It is used for the DropdownButton to pass through to the underlying button or whatever from it. eventKey: It is used to uniquely identify the dropdown toggle component. id: It is used to pass the HTML id attribute to this element. split: It is used to pass the split attribute to this element. bsPrefix: It is an escape hatch for working with strongly customized bootstrap CSS. Dropdown.Menu Props: align: It is used for the dropdown menu to align it to the specified side of the container. alignRight: It is used for the dropdown menu to align it to the right side of the container. as: It can be used as a custom element type for this component. flip: It is used to flip the dropdown to its opposite placement. onSelect: It is a callback function that is triggered when the menu item is selected. popperConfig: It is used to pass the set of popper options to the popper directly. renderOnMount: It is used to indicate whether to render the dropdown menu before the first time it is shown in the DOM. rootCloseEvent: It is used to close the component when which event is triggered outside this component. show: It is used to indicate whether the dropdown menu is visible or not. bsPrefix: It is an escape hatch for working with strongly customized bootstrap CSS. Dropdown.Item Props: active: It can be used to mark the menu item as active. as: It can be used as a custom element type for this component. disabled: It is used to make the menu item disabled. eventKey: It is used to uniquely identify the selected menu item. href: It is used to pass the href attribute to this element. onClick: It is a callback function that is triggered when the menu item is clicked. onSelect: It is a callback function that is triggered when the menu item is selected. bsPrefix: It is an escape hatch for working with strongly customized bootstrap CSS. Dropdown.Header Props: as: It can be used as a custom element type for this component. bsPrefix: It is an escape hatch for working with strongly customized bootstrap CSS. Dropdown.Divider Props: as: It can be used as a custom element type for this component. bsPrefix: It is an escape hatch for working with strongly customized bootstrap CSS. Creating React Application And Installing Module: Step 1: Create a React application using the following command:npx create-react-app foldername Step 1: Create a React application using the following command: npx create-react-app foldername Step 2: After creating your project folder i.e. foldername, move to it using the following command:cd 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 required module using the following command:npm install react-bootstrap npm install bootstrap Step 3: After creating the ReactJS application, Install the required module using the following command: npm install react-bootstrap npm install bootstrap 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 'bootstrap/dist/css/bootstrap.css';import Dropdown from 'react-bootstrap/Dropdown'; export default function App() { return ( <div style={{ display: 'block', width: 700, padding: 30 }}> <h4>React-Bootstrap Dropdown Component</h4> <Dropdown> <Dropdown.Toggle variant="success"> Open Menu </Dropdown.Toggle> <Dropdown.Menu> <Dropdown.Item href="#"> Home Page </Dropdown.Item> <Dropdown.Item href="#"> Settings </Dropdown.Item> <Dropdown.Item href="#"> Logout </Dropdown.Item> </Dropdown.Menu> </Dropdown> </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://react-bootstrap.github.io/components/dropdowns/ React-Bootstrap ReactJS 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": "\n04 May, 2021" }, { "code": null, "e": 317, "s": 28, "text": "React-Bootstrap is a front-end framework that was designed keeping react in mind. Dropdown Component provides a way to displaying lists of links or more actions within a menu when clicked over it. We can use the following approach in ReactJS to use the react-bootstrap Dropdown Component." }, { "code": null, "e": 333, "s": 317, "text": "Dropdown Props:" }, { "code": null, "e": 416, "s": 333, "text": "alignRight: It is used to align the menu to the right side of the Dropdown toggle." }, { "code": null, "e": 480, "s": 416, "text": "as: It can be used as a custom element type for this component." }, { "code": null, "e": 576, "s": 480, "text": "drop: It is used to determine the location and direction of the Menu in relation to its toggle." }, { "code": null, "e": 663, "s": 576, "text": "flip: It is used to flip the dropdown in case of overlapping on the reference element." }, { "code": null, "e": 763, "s": 663, "text": "focusFirstItemOnShow: When the dropdown is opened, it is used to control the focus behavior for it." }, { "code": null, "e": 873, "s": 763, "text": "navbar: It is the attribute that is by default false and indicates whether dropdown is navbar related or not." }, { "code": null, "e": 957, "s": 873, "text": "onSelect: It is a callback function that is triggered when a menu item is selected." }, { "code": null, "e": 1057, "s": 957, "text": "onToggle: It is used to trigger a callback when the visibility of the dropdown needs to be changed." }, { "code": null, "e": 1126, "s": 1057, "text": "show: It is used to indicate whether the dropdown is visible or not." }, { "code": null, "e": 1210, "s": 1126, "text": "bsPrefix: It is an escape hatch for working with strongly customized bootstrap CSS." }, { "code": null, "e": 1229, "s": 1210, "text": "SplitButton Props:" }, { "code": null, "e": 1273, "s": 1229, "text": "disabled: It is used to disable the button." }, { "code": null, "e": 1354, "s": 1273, "text": "href: It is used to pass the href attribute to the underlying non-toggle button." }, { "code": null, "e": 1417, "s": 1354, "text": "id: It is the general HTML id attribute for the toggle button." }, { "code": null, "e": 1480, "s": 1417, "text": "menuAlign: It is used to responsively align the dropdown menu." }, { "code": null, "e": 1578, "s": 1480, "text": "menuRole: It is used for the ARIA accessible role applied which is applied to the menu component." }, { "code": null, "e": 1670, "s": 1578, "text": "onClick: It is the callback function that is passed as a handler for the non-toggle button." }, { "code": null, "e": 1794, "s": 1670, "text": "renderMenuOnMount: It is used to indicate whether to render the dropdown menu before the first time it is shown in the DOM." }, { "code": null, "e": 1898, "s": 1794, "text": "rootCloseEvent: It is used to close the component when which event is triggered outside this component." }, { "code": null, "e": 1942, "s": 1898, "text": "size: It denotes the size of the component." }, { "code": null, "e": 2014, "s": 1942, "text": "target: For the non-toggle Button, it is an anchor target passed to it." }, { "code": null, "e": 2076, "s": 2014, "text": "title: It is used to define the content of non-toggle Button." }, { "code": null, "e": 2140, "s": 2076, "text": "toggleLabel: For the toggle button, it is the accessible label." }, { "code": null, "e": 2201, "s": 2140, "text": "type: It is used to pass the type for the non-toggle button." }, { "code": null, "e": 2259, "s": 2201, "text": "variant: It is used to indicate the style variant for it." }, { "code": null, "e": 2343, "s": 2259, "text": "bsPrefix: It is an escape hatch for working with strongly customized bootstrap CSS." }, { "code": null, "e": 2366, "s": 2343, "text": "Dropdown.Toggle Props:" }, { "code": null, "e": 2430, "s": 2366, "text": "as: It can be used as a custom element type for this component." }, { "code": null, "e": 2541, "s": 2430, "text": "childBsPrefix: It is used for the DropdownButton to pass through to the underlying button or whatever from it." }, { "code": null, "e": 2614, "s": 2541, "text": "eventKey: It is used to uniquely identify the dropdown toggle component." }, { "code": null, "e": 2676, "s": 2614, "text": "id: It is used to pass the HTML id attribute to this element." }, { "code": null, "e": 2739, "s": 2676, "text": "split: It is used to pass the split attribute to this element." }, { "code": null, "e": 2823, "s": 2739, "text": "bsPrefix: It is an escape hatch for working with strongly customized bootstrap CSS." }, { "code": null, "e": 2844, "s": 2823, "text": "Dropdown.Menu Props:" }, { "code": null, "e": 2936, "s": 2844, "text": "align: It is used for the dropdown menu to align it to the specified side of the container." }, { "code": null, "e": 3029, "s": 2936, "text": "alignRight: It is used for the dropdown menu to align it to the right side of the container." }, { "code": null, "e": 3093, "s": 3029, "text": "as: It can be used as a custom element type for this component." }, { "code": null, "e": 3158, "s": 3093, "text": "flip: It is used to flip the dropdown to its opposite placement." }, { "code": null, "e": 3244, "s": 3158, "text": "onSelect: It is a callback function that is triggered when the menu item is selected." }, { "code": null, "e": 3327, "s": 3244, "text": "popperConfig: It is used to pass the set of popper options to the popper directly." }, { "code": null, "e": 3447, "s": 3327, "text": "renderOnMount: It is used to indicate whether to render the dropdown menu before the first time it is shown in the DOM." }, { "code": null, "e": 3551, "s": 3447, "text": "rootCloseEvent: It is used to close the component when which event is triggered outside this component." }, { "code": null, "e": 3625, "s": 3551, "text": "show: It is used to indicate whether the dropdown menu is visible or not." }, { "code": null, "e": 3709, "s": 3625, "text": "bsPrefix: It is an escape hatch for working with strongly customized bootstrap CSS." }, { "code": null, "e": 3730, "s": 3709, "text": "Dropdown.Item Props:" }, { "code": null, "e": 3786, "s": 3730, "text": "active: It can be used to mark the menu item as active." }, { "code": null, "e": 3850, "s": 3786, "text": "as: It can be used as a custom element type for this component." }, { "code": null, "e": 3903, "s": 3850, "text": "disabled: It is used to make the menu item disabled." }, { "code": null, "e": 3969, "s": 3903, "text": "eventKey: It is used to uniquely identify the selected menu item." }, { "code": null, "e": 4030, "s": 3969, "text": "href: It is used to pass the href attribute to this element." }, { "code": null, "e": 4114, "s": 4030, "text": "onClick: It is a callback function that is triggered when the menu item is clicked." }, { "code": null, "e": 4200, "s": 4114, "text": "onSelect: It is a callback function that is triggered when the menu item is selected." }, { "code": null, "e": 4284, "s": 4200, "text": "bsPrefix: It is an escape hatch for working with strongly customized bootstrap CSS." }, { "code": null, "e": 4307, "s": 4284, "text": "Dropdown.Header Props:" }, { "code": null, "e": 4371, "s": 4307, "text": "as: It can be used as a custom element type for this component." }, { "code": null, "e": 4455, "s": 4371, "text": "bsPrefix: It is an escape hatch for working with strongly customized bootstrap CSS." }, { "code": null, "e": 4479, "s": 4455, "text": "Dropdown.Divider Props:" }, { "code": null, "e": 4543, "s": 4479, "text": "as: It can be used as a custom element type for this component." }, { "code": null, "e": 4627, "s": 4543, "text": "bsPrefix: It is an escape hatch for working with strongly customized bootstrap CSS." }, { "code": null, "e": 4677, "s": 4627, "text": "Creating React Application And Installing Module:" }, { "code": null, "e": 4772, "s": 4677, "text": "Step 1: Create a React application using the following command:npx create-react-app foldername" }, { "code": null, "e": 4836, "s": 4772, "text": "Step 1: Create a React application using the following command:" }, { "code": null, "e": 4868, "s": 4836, "text": "npx create-react-app foldername" }, { "code": null, "e": 4981, "s": 4868, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:cd foldername" }, { "code": null, "e": 5081, "s": 4981, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:" }, { "code": null, "e": 5095, "s": 5081, "text": "cd foldername" }, { "code": null, "e": 5250, "s": 5095, "text": "Step 3: After creating the ReactJS application, Install the required module using the following command:npm install react-bootstrap \nnpm install bootstrap" }, { "code": null, "e": 5355, "s": 5250, "text": "Step 3: After creating the ReactJS application, Install the required module using the following command:" }, { "code": null, "e": 5406, "s": 5355, "text": "npm install react-bootstrap \nnpm install bootstrap" }, { "code": null, "e": 5458, "s": 5406, "text": "Project Structure: It will look like the following." }, { "code": null, "e": 5476, "s": 5458, "text": "Project Structure" }, { "code": null, "e": 5606, "s": 5476, "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": 5613, "s": 5606, "text": "App.js" }, { "code": "import React from 'react';import 'bootstrap/dist/css/bootstrap.css';import Dropdown from 'react-bootstrap/Dropdown'; export default function App() { return ( <div style={{ display: 'block', width: 700, padding: 30 }}> <h4>React-Bootstrap Dropdown Component</h4> <Dropdown> <Dropdown.Toggle variant=\"success\"> Open Menu </Dropdown.Toggle> <Dropdown.Menu> <Dropdown.Item href=\"#\"> Home Page </Dropdown.Item> <Dropdown.Item href=\"#\"> Settings </Dropdown.Item> <Dropdown.Item href=\"#\"> Logout </Dropdown.Item> </Dropdown.Menu> </Dropdown> </div> );}", "e": 6343, "s": 5613, "text": null }, { "code": null, "e": 6456, "s": 6343, "text": "Step to Run Application: Run the application using the following command from the root directory of the project:" }, { "code": null, "e": 6466, "s": 6456, "text": "npm start" }, { "code": null, "e": 6565, "s": 6466, "text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:" }, { "code": null, "e": 6632, "s": 6565, "text": "Reference: https://react-bootstrap.github.io/components/dropdowns/" }, { "code": null, "e": 6648, "s": 6632, "text": "React-Bootstrap" }, { "code": null, "e": 6656, "s": 6648, "text": "ReactJS" }, { "code": null, "e": 6673, "s": 6656, "text": "Web Technologies" } ]
Sylvester’s sequence
21 Jun, 2022 In number system, Sylvester’s sequence is an integer sequence in which each member of the sequence is the product of the previous members, plus one. Given a positive integer N. The task is to print the first N member of the sequence. Since numbers can be very big, use %10^9 + 7.Examples: Input : N = 6 Output : 2 3 7 43 1807 3263443 Input : N = 2 Output : 2 3 The idea is to run a loop and take two variables and initialise them as 1 and 2, one to store the product till now and other to store the current number which is nothing but the first number + 1 and for each step multiply both using arithmetic modular operation i.e (a + b)%N = (a%N + b%N)%N where N is a modular number.Below is the implementation of this approach: C++ Java Python C# PHP Javascript // CPP program to print terms of Sylvester's sequence#include <bits/stdc++.h>using namespace std;#define N 1000000007 void printSequence(int n){ int a = 1; // To store the product. int ans = 2; // To store the current number. // Loop till n. for (int i = 1; i <= n; i++) { cout << ans << " "; ans = ((a % N) * (ans % N)) % N; a = ans; ans = (ans + 1) % N; }} // Driven Programint main(){ int n = 6; printSequence(n); return 0;} // JAVA Code for Sylvester sequenceimport java.util.*; class GFG { public static void printSequence(int n) { int a = 1; // To store the product. int ans = 2; // To store the current number. int N = 1000000007; // Loop till n. for (int i = 1; i <= n; i++) { System.out.print(ans + " "); ans = ((a % N) * (ans % N)) % N; a = ans; ans = (ans + 1) % N; } } /* Driver program to test above function */ public static void main(String[] args) { int n = 6; printSequence(n); }} // This code is contributed by Arnav Kr. Mandal. # Python Code for Sylvester sequence def printSequence(n) : a = 1 # To store the product. ans = 2 # To store the current number. N = 1000000007 # Loop till n. i = 1 while i <= n : print ans, ans = ((a % N) * (ans % N)) % N a = ans ans = (ans + 1) % N i = i + 1 # Driver program to test above functionn = 6printSequence(n) # This code is contributed by Nikita Tiwari. // C# Code for Sylvester sequenceusing System; class GFG { public static void printSequence(int n) { // To store the product. int a = 1; // To store the current number. int ans = 2; int N = 1000000007; // Loop till n. for (int i = 1; i <= n; i++) { Console.Write(ans + " "); ans = ((a % N) * (ans % N)) % N; a = ans; ans = (ans + 1) % N; } } // Driver program public static void Main() { int n = 6; printSequence(n); }} // This code is contributed by vt_m. <?php// PHP program to print// terms of Sylvester's sequence $N = 1000000007; function printSequence($n){ global $N; // To store // the product. $a = 1; // To store the // current number. $ans = 2; // Loop till n. for ($i = 1; $i <= $n; $i++) { echo $ans ," "; $ans = (($a % $N) * ($ans % $N)) % $N; $a = $ans; $ans = ($ans + 1) % $N; }} // Driver Code $n = 6; printSequence($n); // This code is contributed by anuj_67.?> <script>// Javascript program to print// terms of Sylvester's sequence let N = 1000000007; function printSequence(n){ // To store // the product. let a = 1; // To store the // current number. let ans = 2; // Loop till n. for (let i = 1; i <= n; i++) { document.write(ans + " "); ans = ((a % N) * (ans % N)) % N; a = ans; ans = (ans + 1) % N; }} // Driver Code let n = 6; printSequence(n); // This code is contributed by gfgking.</script> Output: 2 3 7 43 1807 3263443 Time complexity : O(n) Auxiliary Space : O(1) This article is contributed by Anuj Chauhan. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. vt_m gfgking technophpfij series Mathematical School Programming Mathematical series Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Program for Fibonacci numbers Set in C++ Standard Template Library (STL) Write a program to print all permutations of a given string C++ Data Types Merge two sorted arrays Python Dictionary Reverse a string in Java Arrays in C/C++ Introduction To PYTHON Interfaces in Java
[ { "code": null, "e": 53, "s": 25, "text": "\n21 Jun, 2022" }, { "code": null, "e": 344, "s": 53, "text": "In number system, Sylvester’s sequence is an integer sequence in which each member of the sequence is the product of the previous members, plus one. Given a positive integer N. The task is to print the first N member of the sequence. Since numbers can be very big, use %10^9 + 7.Examples: " }, { "code": null, "e": 417, "s": 344, "text": "Input : N = 6\nOutput : 2 3 7 43 1807 3263443\n\nInput : N = 2\nOutput : 2 3" }, { "code": null, "e": 787, "s": 419, "text": "The idea is to run a loop and take two variables and initialise them as 1 and 2, one to store the product till now and other to store the current number which is nothing but the first number + 1 and for each step multiply both using arithmetic modular operation i.e (a + b)%N = (a%N + b%N)%N where N is a modular number.Below is the implementation of this approach: " }, { "code": null, "e": 791, "s": 787, "text": "C++" }, { "code": null, "e": 796, "s": 791, "text": "Java" }, { "code": null, "e": 803, "s": 796, "text": "Python" }, { "code": null, "e": 806, "s": 803, "text": "C#" }, { "code": null, "e": 810, "s": 806, "text": "PHP" }, { "code": null, "e": 821, "s": 810, "text": "Javascript" }, { "code": "// CPP program to print terms of Sylvester's sequence#include <bits/stdc++.h>using namespace std;#define N 1000000007 void printSequence(int n){ int a = 1; // To store the product. int ans = 2; // To store the current number. // Loop till n. for (int i = 1; i <= n; i++) { cout << ans << \" \"; ans = ((a % N) * (ans % N)) % N; a = ans; ans = (ans + 1) % N; }} // Driven Programint main(){ int n = 6; printSequence(n); return 0;}", "e": 1302, "s": 821, "text": null }, { "code": "// JAVA Code for Sylvester sequenceimport java.util.*; class GFG { public static void printSequence(int n) { int a = 1; // To store the product. int ans = 2; // To store the current number. int N = 1000000007; // Loop till n. for (int i = 1; i <= n; i++) { System.out.print(ans + \" \"); ans = ((a % N) * (ans % N)) % N; a = ans; ans = (ans + 1) % N; } } /* Driver program to test above function */ public static void main(String[] args) { int n = 6; printSequence(n); }} // This code is contributed by Arnav Kr. Mandal.", "e": 1967, "s": 1302, "text": null }, { "code": "# Python Code for Sylvester sequence def printSequence(n) : a = 1 # To store the product. ans = 2 # To store the current number. N = 1000000007 # Loop till n. i = 1 while i <= n : print ans, ans = ((a % N) * (ans % N)) % N a = ans ans = (ans + 1) % N i = i + 1 # Driver program to test above functionn = 6printSequence(n) # This code is contributed by Nikita Tiwari.", "e": 2401, "s": 1967, "text": null }, { "code": "// C# Code for Sylvester sequenceusing System; class GFG { public static void printSequence(int n) { // To store the product. int a = 1; // To store the current number. int ans = 2; int N = 1000000007; // Loop till n. for (int i = 1; i <= n; i++) { Console.Write(ans + \" \"); ans = ((a % N) * (ans % N)) % N; a = ans; ans = (ans + 1) % N; } } // Driver program public static void Main() { int n = 6; printSequence(n); }} // This code is contributed by vt_m.", "e": 3043, "s": 2401, "text": null }, { "code": "<?php// PHP program to print// terms of Sylvester's sequence $N = 1000000007; function printSequence($n){ global $N; // To store // the product. $a = 1; // To store the // current number. $ans = 2; // Loop till n. for ($i = 1; $i <= $n; $i++) { echo $ans ,\" \"; $ans = (($a % $N) * ($ans % $N)) % $N; $a = $ans; $ans = ($ans + 1) % $N; }} // Driver Code $n = 6; printSequence($n); // This code is contributed by anuj_67.?>", "e": 3551, "s": 3043, "text": null }, { "code": "<script>// Javascript program to print// terms of Sylvester's sequence let N = 1000000007; function printSequence(n){ // To store // the product. let a = 1; // To store the // current number. let ans = 2; // Loop till n. for (let i = 1; i <= n; i++) { document.write(ans + \" \"); ans = ((a % N) * (ans % N)) % N; a = ans; ans = (ans + 1) % N; }} // Driver Code let n = 6; printSequence(n); // This code is contributed by gfgking.</script>", "e": 4068, "s": 3551, "text": null }, { "code": null, "e": 4078, "s": 4068, "text": "Output: " }, { "code": null, "e": 4100, "s": 4078, "text": "2 3 7 43 1807 3263443" }, { "code": null, "e": 4146, "s": 4100, "text": "Time complexity : O(n) Auxiliary Space : O(1)" }, { "code": null, "e": 4567, "s": 4146, "text": "This article is contributed by Anuj Chauhan. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 4572, "s": 4567, "text": "vt_m" }, { "code": null, "e": 4580, "s": 4572, "text": "gfgking" }, { "code": null, "e": 4593, "s": 4580, "text": "technophpfij" }, { "code": null, "e": 4600, "s": 4593, "text": "series" }, { "code": null, "e": 4613, "s": 4600, "text": "Mathematical" }, { "code": null, "e": 4632, "s": 4613, "text": "School Programming" }, { "code": null, "e": 4645, "s": 4632, "text": "Mathematical" }, { "code": null, "e": 4652, "s": 4645, "text": "series" }, { "code": null, "e": 4750, "s": 4652, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4780, "s": 4750, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 4823, "s": 4780, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 4883, "s": 4823, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 4898, "s": 4883, "text": "C++ Data Types" }, { "code": null, "e": 4922, "s": 4898, "text": "Merge two sorted arrays" }, { "code": null, "e": 4940, "s": 4922, "text": "Python Dictionary" }, { "code": null, "e": 4965, "s": 4940, "text": "Reverse a string in Java" }, { "code": null, "e": 4981, "s": 4965, "text": "Arrays in C/C++" }, { "code": null, "e": 5004, "s": 4981, "text": "Introduction To PYTHON" } ]
How to create superuser in Django?
05 Sep, 2020 Django provides us Admin Panel for it’s users. So we need not worry about creating a separate Admin page or providing authentication feature as Django provides us that feature. Before using this feature, you must have migrated your project, otherwise the superuser database will not be created. How to create superuser in Django? For creating superuser, first reach the same directory as that of manage.py and run the following command: python manage.py createsuperuser Then enter the Username of your choice and press enter. Username: srishti Then enter the Email address and press enter.(It can be left blank) Email address: example@gmail.com Next, enter the Password in-front of the Password field and press enter.Enter a strong password so as to keep it secure. Password: ****** Then again enter the same Password for confirmation. Password(again): ****** Superuser created successfully if above fields are entered correctly. Image shown after above steps done Now we can login into our Django Admin page by running the command python manage.py runserver . Then, open a Web browser and go to “/admin/” on your local domain – e.g., http://127.0.0.1:8000/admin/ and then enter the same Username and Password. Django admin page Python Django Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n05 Sep, 2020" }, { "code": null, "e": 323, "s": 28, "text": "Django provides us Admin Panel for it’s users. So we need not worry about creating a separate Admin page or providing authentication feature as Django provides us that feature. Before using this feature, you must have migrated your project, otherwise the superuser database will not be created." }, { "code": null, "e": 358, "s": 323, "text": "How to create superuser in Django?" }, { "code": null, "e": 465, "s": 358, "text": "For creating superuser, first reach the same directory as that of manage.py and run the following command:" }, { "code": null, "e": 498, "s": 465, "text": "python manage.py createsuperuser" }, { "code": null, "e": 554, "s": 498, "text": "Then enter the Username of your choice and press enter." }, { "code": null, "e": 572, "s": 554, "text": "Username: srishti" }, { "code": null, "e": 640, "s": 572, "text": "Then enter the Email address and press enter.(It can be left blank)" }, { "code": null, "e": 673, "s": 640, "text": "Email address: example@gmail.com" }, { "code": null, "e": 794, "s": 673, "text": "Next, enter the Password in-front of the Password field and press enter.Enter a strong password so as to keep it secure." }, { "code": null, "e": 813, "s": 794, "text": "Password: ****** " }, { "code": null, "e": 866, "s": 813, "text": "Then again enter the same Password for confirmation." }, { "code": null, "e": 890, "s": 866, "text": "Password(again): ******" }, { "code": null, "e": 960, "s": 890, "text": "Superuser created successfully if above fields are entered correctly." }, { "code": null, "e": 996, "s": 960, "text": "Image shown after above steps done " }, { "code": null, "e": 1242, "s": 996, "text": "Now we can login into our Django Admin page by running the command python manage.py runserver . Then, open a Web browser and go to “/admin/” on your local domain – e.g., http://127.0.0.1:8000/admin/ and then enter the same Username and Password." }, { "code": null, "e": 1455, "s": 1437, "text": "Django admin page" }, { "code": null, "e": 1469, "s": 1455, "text": "Python Django" }, { "code": null, "e": 1476, "s": 1469, "text": "Python" } ]
Django Models
11 Apr, 2022 A Django model is the built-in feature that Django uses to create tables, their fields, and various constraints. In short, Django Models is the SQL of Database one uses with Django. SQL (Structured Query Language) is complex and involves a lot of different queries for creating, deleting, updating or any other stuff related to database. Django models simplify the tasks and organize tables into models. Generally, each model maps to a single database table. This article revolves about how one can use Django models to store data in the database conveniently. Moreover, we can use admin panel of Django to create, update, delete or retrieve fields of a model and various similar operations. Django models provide simplicity, consistency, version control and advanced metadata handling. Basics of a model include – Each model is a Python class that subclasses django.db.models.Model. Each attribute of the model represents a database field. With all of this, Django gives you an automatically-generated database-access API; see Making queries. Example – Python3 from django.db import models # Create your models here.class GeeksModel(models.Model): title = models.CharField(max_length = 200) description = models.TextField() Django maps the fields defined in Django models into table fields of the database as shown below. To use Django Models, one needs to have a project and an app working in it. After you start an app you can create models in app/models.py. Before starting to use a model let’s check how to start a project and create an app named geeks.py Refer to the following articles to check how to create a project and an app in Django. How to Create a Basic Project using MVT in Django? How to Create an App in Django ? Syntax from django.db import models class ModelName(models.Model): field_name = models.Field(**options) To create a model, in geeks/models.py Enter the code, Python3 # import the standard Django Model# from built-in libraryfrom django.db import models # declare a new model with a name "GeeksModel"class GeeksModel(models.Model): # fields of the model title = models.CharField(max_length = 200) description = models.TextField() last_modified = models.DateTimeField(auto_now_add = True) img = models.ImageField(upload_to = "images/") # renames the instances of the model # with their title name def __str__(self): return self.title Whenever we create a Model, Delete a Model, or update anything in any of models.py of our project. We need to run two commands makemigrations and migrate. makemigrations basically generates the SQL commands for preinstalled apps (which can be viewed in installed apps in settings.py) and your newly created app’s model which you add in installed apps whereas migrate executes those SQL commands in the database file. So when we run, Python manage.py makemigrations SQL Query to create above Model as a Table is created and Python manage.py migrate creates the table in the database.Now we have created a model we can perform various operations such as creating a Row for the table or in terms of Django Creating an instance of Model. To know more visit – Django Basic App Model – Makemigrations and Migrate To render a model in Django admin, we need to modify app/admin.py. Go to admin.py in geeks app and enter the following code. Import the corresponding model from models.py and register it to the admin interface. Python3 from django.contrib import admin # Register your models here.from .models import GeeksModel admin.site.register(GeeksModel) Now we can check whether the model has been rendered in Django Admin. Django Admin Interface can be used to graphically implement CRUD (Create, Retrieve, Update, Delete). To check more on rendering models in django admin, visit – Render Model in Django Admin Interface Django lets us interact with its database models, i.e. add, delete, modify and query objects, using a database-abstraction API called ORM(Object Relational Mapper). We can access the Django ORM by running the following command inside our project directory. python manage.py shell Adding objects. To create an object of model Album and save it into the database, we need to write the following command: >>>> a = GeeksModel( title = "GeeksForGeeks", description = "A description here", img = "geeks/abc.png" ) >>> a.save() Retrieving objects To retrieve all the objects of a model, we write the following command: >>> GeeksModel.objects.all() <QuerySet [<GeeksModel: Divide>, <GeeksModel: Abbey Road>, <GeeksModel: Revolver>]> Modifying existing objects We can modify an existing object as follows: >>> a = GeeksModel.objects.get(id = 3) >>> a.title = "Pop" >>> a.save() Deleting objects To delete a single object, we need to write the following commands: >>> a = Album.objects.get(id = 2) >>> a.delete() To check detailed post of Django’s ORM (Object) visit Django ORM – Inserting, Updating & Deleting Data Built-in Field Validations in Django models are the default validations that come predefined to all Django fields. Every field comes in with built-in validations from Django validators. For example, IntegerField comes with built-in validation that it can only store integer values and that too in a particular range. Enter the following code into models.py file of geeks app. Python3 from django.db import modelsfrom django.db.models import Model# Create your models here. class GeeksModel(Model): geeks_field = models.IntegerField() def __str__(self): return self.geeks_field After running makemigrations and migrate on Django and rendering above model, let us try to create an instance using string “GfG is Best“. You can see in the admin interface, one can not enter a string in an IntegerField. Similarly every field has its own validations. To know more about validations visit, Built-in Field Validations – Django Models Change Object Display Name using __str__ function – Django Models Custom Field Validations in Django Models Django python manage.py migrate command Django App Model – Python manage.py makemigrations command Django model data types and fields list How to use Django Field Choices ? Overriding the save method – Django Models The most important part of a model and the only required part of a model is the list of database fields it defines. Fields are specified by class attributes. Here is a list of all Field types used in Django. Django also defines a set of fields that represent relations. Field Options are the arguments given to each field for applying some constraint or imparting a particular characteristic to a particular Field. For example, adding an argument null = True to CharField will enable it to store empty values for that table in relational database. Here are the field options and attributes that an CharField can use. namankukreja01 Django-models Python Django Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Iterate over a list in Python Read JSON file using Python Python map() function How to iterate through Excel rows in Python? Enumerate() in Python Adding new column to existing DataFrame in Pandas Python OOPs Concepts Different ways to create Pandas Dataframe How to get column names in Pandas dataframe Stack in Python
[ { "code": null, "e": 54, "s": 26, "text": "\n11 Apr, 2022" }, { "code": null, "e": 871, "s": 54, "text": "A Django model is the built-in feature that Django uses to create tables, their fields, and various constraints. In short, Django Models is the SQL of Database one uses with Django. SQL (Structured Query Language) is complex and involves a lot of different queries for creating, deleting, updating or any other stuff related to database. Django models simplify the tasks and organize tables into models. Generally, each model maps to a single database table. This article revolves about how one can use Django models to store data in the database conveniently. Moreover, we can use admin panel of Django to create, update, delete or retrieve fields of a model and various similar operations. Django models provide simplicity, consistency, version control and advanced metadata handling. Basics of a model include – " }, { "code": null, "e": 940, "s": 871, "text": "Each model is a Python class that subclasses django.db.models.Model." }, { "code": null, "e": 999, "s": 942, "text": "Each attribute of the model represents a database field." }, { "code": null, "e": 1104, "s": 1001, "text": "With all of this, Django gives you an automatically-generated database-access API; see Making queries." }, { "code": null, "e": 1116, "s": 1104, "text": "Example – " }, { "code": null, "e": 1124, "s": 1116, "text": "Python3" }, { "code": "from django.db import models # Create your models here.class GeeksModel(models.Model): title = models.CharField(max_length = 200) description = models.TextField()", "e": 1293, "s": 1124, "text": null }, { "code": null, "e": 1393, "s": 1293, "text": "Django maps the fields defined in Django models into table fields of the database as shown below. " }, { "code": null, "e": 1634, "s": 1395, "text": "To use Django Models, one needs to have a project and an app working in it. After you start an app you can create models in app/models.py. Before starting to use a model let’s check how to start a project and create an app named geeks.py " }, { "code": null, "e": 1723, "s": 1634, "text": "Refer to the following articles to check how to create a project and an app in Django. " }, { "code": null, "e": 1774, "s": 1723, "text": "How to Create a Basic Project using MVT in Django?" }, { "code": null, "e": 1807, "s": 1774, "text": "How to Create an App in Django ?" }, { "code": null, "e": 1818, "s": 1809, "text": "Syntax " }, { "code": null, "e": 1932, "s": 1818, "text": "from django.db import models\n \nclass ModelName(models.Model):\n field_name = models.Field(**options)" }, { "code": null, "e": 1988, "s": 1932, "text": "To create a model, in geeks/models.py Enter the code, " }, { "code": null, "e": 1996, "s": 1988, "text": "Python3" }, { "code": "# import the standard Django Model# from built-in libraryfrom django.db import models # declare a new model with a name \"GeeksModel\"class GeeksModel(models.Model): # fields of the model title = models.CharField(max_length = 200) description = models.TextField() last_modified = models.DateTimeField(auto_now_add = True) img = models.ImageField(upload_to = \"images/\") # renames the instances of the model # with their title name def __str__(self): return self.title", "e": 2505, "s": 1996, "text": null }, { "code": null, "e": 2940, "s": 2505, "text": "Whenever we create a Model, Delete a Model, or update anything in any of models.py of our project. We need to run two commands makemigrations and migrate. makemigrations basically generates the SQL commands for preinstalled apps (which can be viewed in installed apps in settings.py) and your newly created app’s model which you add in installed apps whereas migrate executes those SQL commands in the database file. So when we run, " }, { "code": null, "e": 2972, "s": 2940, "text": "Python manage.py makemigrations" }, { "code": null, "e": 3032, "s": 2972, "text": "SQL Query to create above Model as a Table is created and " }, { "code": null, "e": 3058, "s": 3032, "text": " Python manage.py migrate" }, { "code": null, "e": 3319, "s": 3058, "text": "creates the table in the database.Now we have created a model we can perform various operations such as creating a Row for the table or in terms of Django Creating an instance of Model. To know more visit – Django Basic App Model – Makemigrations and Migrate " }, { "code": null, "e": 3531, "s": 3319, "text": "To render a model in Django admin, we need to modify app/admin.py. Go to admin.py in geeks app and enter the following code. Import the corresponding model from models.py and register it to the admin interface. " }, { "code": null, "e": 3539, "s": 3531, "text": "Python3" }, { "code": "from django.contrib import admin # Register your models here.from .models import GeeksModel admin.site.register(GeeksModel)", "e": 3667, "s": 3539, "text": null }, { "code": null, "e": 3840, "s": 3667, "text": "Now we can check whether the model has been rendered in Django Admin. Django Admin Interface can be used to graphically implement CRUD (Create, Retrieve, Update, Delete). " }, { "code": null, "e": 3939, "s": 3840, "text": "To check more on rendering models in django admin, visit – Render Model in Django Admin Interface " }, { "code": null, "e": 4197, "s": 3939, "text": "Django lets us interact with its database models, i.e. add, delete, modify and query objects, using a database-abstraction API called ORM(Object Relational Mapper). We can access the Django ORM by running the following command inside our project directory. " }, { "code": null, "e": 4220, "s": 4197, "text": "python manage.py shell" }, { "code": null, "e": 4343, "s": 4220, "text": "Adding objects. To create an object of model Album and save it into the database, we need to write the following command: " }, { "code": null, "e": 4505, "s": 4343, "text": ">>>> a = GeeksModel(\n\n title = \"GeeksForGeeks\", \n\n description = \"A description here\",\n\n img = \"geeks/abc.png\"\n\n )\n\n>>> a.save()" }, { "code": null, "e": 4597, "s": 4505, "text": "Retrieving objects To retrieve all the objects of a model, we write the following command: " }, { "code": null, "e": 4710, "s": 4597, "text": ">>> GeeksModel.objects.all()\n<QuerySet [<GeeksModel: Divide>, <GeeksModel: Abbey Road>, <GeeksModel: Revolver>]>" }, { "code": null, "e": 4783, "s": 4710, "text": "Modifying existing objects We can modify an existing object as follows: " }, { "code": null, "e": 4855, "s": 4783, "text": ">>> a = GeeksModel.objects.get(id = 3)\n>>> a.title = \"Pop\"\n>>> a.save()" }, { "code": null, "e": 4941, "s": 4855, "text": "Deleting objects To delete a single object, we need to write the following commands: " }, { "code": null, "e": 4990, "s": 4941, "text": ">>> a = Album.objects.get(id = 2)\n>>> a.delete()" }, { "code": null, "e": 5094, "s": 4990, "text": "To check detailed post of Django’s ORM (Object) visit Django ORM – Inserting, Updating & Deleting Data " }, { "code": null, "e": 5472, "s": 5094, "text": "Built-in Field Validations in Django models are the default validations that come predefined to all Django fields. Every field comes in with built-in validations from Django validators. For example, IntegerField comes with built-in validation that it can only store integer values and that too in a particular range. Enter the following code into models.py file of geeks app. " }, { "code": null, "e": 5480, "s": 5472, "text": "Python3" }, { "code": "from django.db import modelsfrom django.db.models import Model# Create your models here. class GeeksModel(Model): geeks_field = models.IntegerField() def __str__(self): return self.geeks_field", "e": 5687, "s": 5480, "text": null }, { "code": null, "e": 5828, "s": 5687, "text": "After running makemigrations and migrate on Django and rendering above model, let us try to create an instance using string “GfG is Best“. " }, { "code": null, "e": 6040, "s": 5828, "text": "You can see in the admin interface, one can not enter a string in an IntegerField. Similarly every field has its own validations. To know more about validations visit, Built-in Field Validations – Django Models " }, { "code": null, "e": 6110, "s": 6042, "text": "Change Object Display Name using __str__ function – Django Models " }, { "code": null, "e": 6152, "s": 6110, "text": "Custom Field Validations in Django Models" }, { "code": null, "e": 6192, "s": 6152, "text": "Django python manage.py migrate command" }, { "code": null, "e": 6251, "s": 6192, "text": "Django App Model – Python manage.py makemigrations command" }, { "code": null, "e": 6291, "s": 6251, "text": "Django model data types and fields list" }, { "code": null, "e": 6325, "s": 6291, "text": "How to use Django Field Choices ?" }, { "code": null, "e": 6368, "s": 6325, "text": "Overriding the save method – Django Models" }, { "code": null, "e": 6580, "s": 6370, "text": "The most important part of a model and the only required part of a model is the list of database fields it defines. Fields are specified by class attributes. Here is a list of all Field types used in Django. " }, { "code": null, "e": 6646, "s": 6584, "text": "Django also defines a set of fields that represent relations." }, { "code": null, "e": 6997, "s": 6650, "text": "Field Options are the arguments given to each field for applying some constraint or imparting a particular characteristic to a particular Field. For example, adding an argument null = True to CharField will enable it to store empty values for that table in relational database. Here are the field options and attributes that an CharField can use." }, { "code": null, "e": 7016, "s": 7001, "text": "namankukreja01" }, { "code": null, "e": 7030, "s": 7016, "text": "Django-models" }, { "code": null, "e": 7044, "s": 7030, "text": "Python Django" }, { "code": null, "e": 7051, "s": 7044, "text": "Python" }, { "code": null, "e": 7149, "s": 7051, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7179, "s": 7149, "text": "Iterate over a list in Python" }, { "code": null, "e": 7207, "s": 7179, "text": "Read JSON file using Python" }, { "code": null, "e": 7229, "s": 7207, "text": "Python map() function" }, { "code": null, "e": 7274, "s": 7229, "text": "How to iterate through Excel rows in Python?" }, { "code": null, "e": 7296, "s": 7274, "text": "Enumerate() in Python" }, { "code": null, "e": 7346, "s": 7296, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 7367, "s": 7346, "text": "Python OOPs Concepts" }, { "code": null, "e": 7409, "s": 7367, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 7453, "s": 7409, "text": "How to get column names in Pandas dataframe" } ]
HTML | Design Form
17 Mar, 2022 What is HTML Form : HTML Form is a document which stores information of a user on a web server using interactive controls. An HTML form contains different kind of information such as username, password, contact number, email id etc. The elements used in an HTML form are check box, input box, radio buttons, submit buttons etc. Using these elements the information of an user is submitted on a web server.The form tag is used to create an HTML form. html <!DOCTYPE html><html><body> <form> Username:<br> <input type="text" name="username"> <br> Email id:<br> <input type="text" name="email_id"> <br><br> <input type="submit" value="Submit"></form> </body></html> Output : Input Elements are the most common elements which are used in HTML Forms. Various user input fields can be created such as textfield, check box, password field, radio button, submit button etc. The most common input elements are listed below: Text Field in HTML Forms : The text field is a one line input field allowing the user to input text. Text Field input controls are created using the “input” element with a type attribute having value as “text”. Text Field in HTML Forms : The text field is a one line input field allowing the user to input text. Text Field input controls are created using the “input” element with a type attribute having value as “text”. html <!DOCTYPE html><html><body> <h3>Example Of Text Field</h3> <form> <label for="EMAIL ID">Email Id:</label><br> <input type="text" name="Email id" id="Email id"> </form></body></html> Output: Password Field in HTML Forms : Password fields are a type of text field in which the text entered is masked using asterisk or dots for prevention of user identity from another person who is looking onto the screen. Password Field input controls are created using the “input” element with a type attribute having value as “password”. Password Field in HTML Forms : Password fields are a type of text field in which the text entered is masked using asterisk or dots for prevention of user identity from another person who is looking onto the screen. Password Field input controls are created using the “input” element with a type attribute having value as “password”. html <!DOCTYPE html><html><body> <h3>Example of Password Field</h3> <form> <label for="user-password">Password: </label><br> <input type="password" name="user-pwd" id="user-password"> </form></body></html> Output : Output : Radio Buttons in HTML Form : Radio Buttons are used to let the user select exactly one option from a list of predefined options. Radio Button input controls are created using the “input” element with a type attribute having value as “radio”. Radio Buttons in HTML Form : Radio Buttons are used to let the user select exactly one option from a list of predefined options. Radio Button input controls are created using the “input” element with a type attribute having value as “radio”. html <!DOCTYPE html><html><body> <h3>Example of Radio Buttons</h3> <form> SELECT GENDER <br> <input type="radio" name="gender" id="male"> <label for="male">Male</label><br> <input type="radio" name="gender" id="female"> <label for="female">Female</label> </form></body></html> Output : Output : Checkboxes in HTML Form : Checkboxes are used to let the user select one or more options from a pre-defined set of options. Checkbox input controls are created using the “input” element with a type attribute having value as “checkbox”. Checkboxes in HTML Form : Checkboxes are used to let the user select one or more options from a pre-defined set of options. Checkbox input controls are created using the “input” element with a type attribute having value as “checkbox”. html <!DOCTYPE html><html><body> <h3>Example of HTML Checkboxes</h3> <form> <b>SELECT SUBJECTS</b> <br> <input type="checkbox" name="subject" id="maths"> <label for="maths">Maths</label> <input type="checkbox" name="subject" id="science"> <label for="science">Science</label> <input type="checkbox" name="subject" id="english"> <label for="english">English</label> </form></body></html> Output : Output : File select boxes are used to allow the user to select a local file and send it as an attachment to the web server.It is similar to a text box with a button which allows the user to browse for a file.Instead of browsing for the file, the path and the name of the file can also be written. File select boxes are created using the “input” element with a type attribute having value as “file”. html <!DOCTYPE html><html><body> <h3>Example of a File Select Box</h3> <form> <label for="fileselect">Upload:</label> <input type="file" name="upload" id="fileselect"> </form></body></html> Output : Text Area is a multiple line text input control which allows user to provide a description or text in multiple lines. A Text Area input control is created using the “textarea” element. html <!DOCTYPE html><html><body> <h3>Example of a Text Area Box</h3> <form> <label for="Description">Description:</label> <textarea rows="5" cols="50" name="Description" id="Description"></textarea> </form></body></html> Output : Select boxes are used to allow users to select one or more than one option from a pull-down list of options. Select boxes are created using two elements which are “select” and “option”.List items are defined within the select element. html <!DOCTYPE html><html><body> <h3>Example of a Select Box</h3> <form> <label for="country">Country:</label> <select name="country" id="country"> <option value="India">India</option> <option value="Sri Lanka">Sri Lanka</option> <option value="Australia">Australia</option> </select> </form></body></html> Output : The Submit Button allows the user to send the form data to the web server. The Reset Button is used to reset the form data and use the default values. html <!DOCTYPE html><html><body> <h3>Example of a Submit And Reset Button</h3> <form action="test.php" method="post" id="users"> <label for="username">Username:</label> <input type="text" name="username" id="Username"> <input type="submit" value="Submit"> <input type="reset" value="Reset"> </form></body></html> Output : Attributes Used in HTML Forms The Action Attribute : The action to be performed after the submission of the form is decided by the action attribute. Generally, the form data is sent to a webpage on the web server after the user clicks on the submit button.Example : html <!DOCTYPE html><html><body> <h3>Example of a Submit And Reset Button</h3> <form action="test.php" method="post" id="users"> <label for="username">Username:</label> <input type="text" name="username" id="Username"> <input type="submit" value="Submit"> <input type="reset" value="Reset"> </form></body></html> If you click the submit button, the form data would be sent to a page called test.php . The Target Attribute in HTML Forms : The Target attribute is used to specify whether the submitted result will open in the current window, a new tab or on a new frame. The default value used is “self” which results in the form submission in the same window. For making the form result open in a new browser tab, the value should be set to “blank”. html <!DOCTYPE html><html><body> <form action="/test.php" target="_blank"> Username:<br> <input type="text" name="username"> <br> Password:<br> <input type="password" name="password"> <br><br> <input type="submit" value="Submit"></form> </body></html> After clicking on the submit button, the result will open in a new browser tab. Name Attribute in Html Forms : The name attribute is required for each input field. If the name attribute is not specified in an input field then the data of that field would not be sent at all. html <!DOCTYPE html><html><body> <form action="/test.php" target="_blank"> Username:<br> <input type="text"> <br> Password:<br> <input type="password" name="password"> <br><br> <input type="submit" value="Submit"></form> </body></html> In the above code, after clicking the submit button, the form data will be sent to a page called /test.php. The data sent would not include the username input field data since the name attribute is omitted. It is used to specify the HTTP method used to send data while submitting the form.There are two kinds of HTTP Methods, which are GET and POST.The GET Method – html <!DOCTYPE html><html><body> <form action="/test.php" target="_blank" method="GET"> Username:<br> <input type="text" name="username"> <br> Password:<br> <input type="password" name="password"> <br><br> <input type="submit" value="Submit"></form> </body></html> In the GET method, after the submission of the form, the form values will be visible in the address bar of the new browser tab. The Post Method – html <!DOCTYPE html><html><body> <form action="/test.php" target="_blank" method="post"> Username:<br> <input type="text" name="username"> <br> Password:<br> <input type="password" name="password"> <br><br> <input type="submit" value="Submit"></form> </body></html> In the post method, after the submission of the form, the form values will not be visible in the address bar of the new browser tab as it was visible in the GET method. Supported Browser: Google Chrome Internet Explorer Firefox Opera Safari HTML is the foundation of webpages, is used for webpage development by structuring websites and web apps.You can learn HTML from the ground up by following this HTML Tutorial and HTML Examples. akshaysingh98088 ysachin2314 jochenhansoul HTML Technical Scripter Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. REST API (Introduction) Types of CSS (Cascading Style Sheet) Design a Tribute Page using HTML & CSS HTTP headers | Content-Type How to Insert Form Data into Database using PHP ? Installation of Node.js on Linux Difference between var, let and const keywords in JavaScript How to fetch data from an API in ReactJS ? Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array
[ { "code": null, "e": 54, "s": 26, "text": "\n17 Mar, 2022" }, { "code": null, "e": 505, "s": 54, "text": "What is HTML Form : HTML Form is a document which stores information of a user on a web server using interactive controls. An HTML form contains different kind of information such as username, password, contact number, email id etc. The elements used in an HTML form are check box, input box, radio buttons, submit buttons etc. Using these elements the information of an user is submitted on a web server.The form tag is used to create an HTML form. " }, { "code": null, "e": 512, "s": 507, "text": "html" }, { "code": "<!DOCTYPE html><html><body> <form> Username:<br> <input type=\"text\" name=\"username\"> <br> Email id:<br> <input type=\"text\" name=\"email_id\"> <br><br> <input type=\"submit\" value=\"Submit\"></form> </body></html>", "e": 727, "s": 512, "text": null }, { "code": null, "e": 738, "s": 727, "text": "Output : " }, { "code": null, "e": 984, "s": 740, "text": "Input Elements are the most common elements which are used in HTML Forms. Various user input fields can be created such as textfield, check box, password field, radio button, submit button etc. The most common input elements are listed below: " }, { "code": null, "e": 1196, "s": 984, "text": "Text Field in HTML Forms : The text field is a one line input field allowing the user to input text. Text Field input controls are created using the “input” element with a type attribute having value as “text”. " }, { "code": null, "e": 1408, "s": 1196, "text": "Text Field in HTML Forms : The text field is a one line input field allowing the user to input text. Text Field input controls are created using the “input” element with a type attribute having value as “text”. " }, { "code": null, "e": 1413, "s": 1408, "text": "html" }, { "code": "<!DOCTYPE html><html><body> <h3>Example Of Text Field</h3> <form> <label for=\"EMAIL ID\">Email Id:</label><br> <input type=\"text\" name=\"Email id\" id=\"Email id\"> </form></body></html>", "e": 1618, "s": 1413, "text": null }, { "code": null, "e": 1626, "s": 1618, "text": "Output:" }, { "code": null, "e": 1961, "s": 1626, "text": " Password Field in HTML Forms : Password fields are a type of text field in which the text entered is masked using asterisk or dots for prevention of user identity from another person who is looking onto the screen. Password Field input controls are created using the “input” element with a type attribute having value as “password”. " }, { "code": null, "e": 2297, "s": 1963, "text": "Password Field in HTML Forms : Password fields are a type of text field in which the text entered is masked using asterisk or dots for prevention of user identity from another person who is looking onto the screen. Password Field input controls are created using the “input” element with a type attribute having value as “password”. " }, { "code": null, "e": 2302, "s": 2297, "text": "html" }, { "code": "<!DOCTYPE html><html><body> <h3>Example of Password Field</h3> <form> <label for=\"user-password\">Password: </label><br> <input type=\"password\" name=\"user-pwd\" id=\"user-password\"> </form></body></html>", "e": 2563, "s": 2302, "text": null }, { "code": null, "e": 2574, "s": 2563, "text": "Output : " }, { "code": null, "e": 2585, "s": 2574, "text": "Output : " }, { "code": null, "e": 2829, "s": 2585, "text": " Radio Buttons in HTML Form : Radio Buttons are used to let the user select exactly one option from a list of predefined options. Radio Button input controls are created using the “input” element with a type attribute having value as “radio”. " }, { "code": null, "e": 3074, "s": 2831, "text": "Radio Buttons in HTML Form : Radio Buttons are used to let the user select exactly one option from a list of predefined options. Radio Button input controls are created using the “input” element with a type attribute having value as “radio”. " }, { "code": null, "e": 3079, "s": 3074, "text": "html" }, { "code": "<!DOCTYPE html><html><body> <h3>Example of Radio Buttons</h3> <form> SELECT GENDER <br> <input type=\"radio\" name=\"gender\" id=\"male\"> <label for=\"male\">Male</label><br> <input type=\"radio\" name=\"gender\" id=\"female\"> <label for=\"female\">Female</label> </form></body></html>", "e": 3402, "s": 3079, "text": null }, { "code": null, "e": 3413, "s": 3402, "text": "Output : " }, { "code": null, "e": 3424, "s": 3413, "text": "Output : " }, { "code": null, "e": 3662, "s": 3424, "text": " Checkboxes in HTML Form : Checkboxes are used to let the user select one or more options from a pre-defined set of options. Checkbox input controls are created using the “input” element with a type attribute having value as “checkbox”. " }, { "code": null, "e": 3901, "s": 3664, "text": "Checkboxes in HTML Form : Checkboxes are used to let the user select one or more options from a pre-defined set of options. Checkbox input controls are created using the “input” element with a type attribute having value as “checkbox”. " }, { "code": null, "e": 3906, "s": 3901, "text": "html" }, { "code": "<!DOCTYPE html><html><body> <h3>Example of HTML Checkboxes</h3> <form> <b>SELECT SUBJECTS</b> <br> <input type=\"checkbox\" name=\"subject\" id=\"maths\"> <label for=\"maths\">Maths</label> <input type=\"checkbox\" name=\"subject\" id=\"science\"> <label for=\"science\">Science</label> <input type=\"checkbox\" name=\"subject\" id=\"english\"> <label for=\"english\">English</label> </form></body></html>", "e": 4353, "s": 3906, "text": null }, { "code": null, "e": 4364, "s": 4353, "text": "Output : " }, { "code": null, "e": 4375, "s": 4364, "text": "Output : " }, { "code": null, "e": 4773, "s": 4381, "text": "File select boxes are used to allow the user to select a local file and send it as an attachment to the web server.It is similar to a text box with a button which allows the user to browse for a file.Instead of browsing for the file, the path and the name of the file can also be written. File select boxes are created using the “input” element with a type attribute having value as “file”. " }, { "code": null, "e": 4778, "s": 4773, "text": "html" }, { "code": "<!DOCTYPE html><html><body> <h3>Example of a File Select Box</h3> <form> <label for=\"fileselect\">Upload:</label> <input type=\"file\" name=\"upload\" id=\"fileselect\"> </form></body></html>", "e": 4986, "s": 4778, "text": null }, { "code": null, "e": 4997, "s": 4986, "text": "Output : " }, { "code": null, "e": 5185, "s": 4999, "text": "Text Area is a multiple line text input control which allows user to provide a description or text in multiple lines. A Text Area input control is created using the “textarea” element. " }, { "code": null, "e": 5190, "s": 5185, "text": "html" }, { "code": "<!DOCTYPE html><html><body> <h3>Example of a Text Area Box</h3> <form> <label for=\"Description\">Description:</label> <textarea rows=\"5\" cols=\"50\" name=\"Description\" id=\"Description\"></textarea> </form></body></html>", "e": 5456, "s": 5190, "text": null }, { "code": null, "e": 5467, "s": 5456, "text": "Output : " }, { "code": null, "e": 5705, "s": 5469, "text": "Select boxes are used to allow users to select one or more than one option from a pull-down list of options. Select boxes are created using two elements which are “select” and “option”.List items are defined within the select element. " }, { "code": null, "e": 5710, "s": 5705, "text": "html" }, { "code": "<!DOCTYPE html><html><body> <h3>Example of a Select Box</h3> <form> <label for=\"country\">Country:</label> <select name=\"country\" id=\"country\"> <option value=\"India\">India</option> <option value=\"Sri Lanka\">Sri Lanka</option> <option value=\"Australia\">Australia</option> </select> </form></body></html>", "e": 6075, "s": 5710, "text": null }, { "code": null, "e": 6085, "s": 6075, "text": "Output : " }, { "code": null, "e": 6241, "s": 6089, "text": "The Submit Button allows the user to send the form data to the web server. The Reset Button is used to reset the form data and use the default values. " }, { "code": null, "e": 6246, "s": 6241, "text": "html" }, { "code": "<!DOCTYPE html><html><body> <h3>Example of a Submit And Reset Button</h3> <form action=\"test.php\" method=\"post\" id=\"users\"> <label for=\"username\">Username:</label> <input type=\"text\" name=\"username\" id=\"Username\"> <input type=\"submit\" value=\"Submit\"> <input type=\"reset\" value=\"Reset\"> </form></body></html>", "e": 6591, "s": 6246, "text": null }, { "code": null, "e": 6602, "s": 6591, "text": "Output : " }, { "code": null, "e": 6634, "s": 6604, "text": "Attributes Used in HTML Forms" }, { "code": null, "e": 6872, "s": 6634, "text": "The Action Attribute : The action to be performed after the submission of the form is decided by the action attribute. Generally, the form data is sent to a webpage on the web server after the user clicks on the submit button.Example : " }, { "code": null, "e": 6879, "s": 6874, "text": "html" }, { "code": "<!DOCTYPE html><html><body> <h3>Example of a Submit And Reset Button</h3> <form action=\"test.php\" method=\"post\" id=\"users\"> <label for=\"username\">Username:</label> <input type=\"text\" name=\"username\" id=\"Username\"> <input type=\"submit\" value=\"Submit\"> <input type=\"reset\" value=\"Reset\"> </form></body></html>", "e": 7224, "s": 6879, "text": null }, { "code": null, "e": 7312, "s": 7224, "text": "If you click the submit button, the form data\nwould be sent to a page called test.php ." }, { "code": null, "e": 7661, "s": 7312, "text": "The Target Attribute in HTML Forms : The Target attribute is used to specify whether the submitted result will open in the current window, a new tab or on a new frame. The default value used is “self” which results in the form submission in the same window. For making the form result open in a new browser tab, the value should be set to “blank”. " }, { "code": null, "e": 7666, "s": 7661, "text": "html" }, { "code": "<!DOCTYPE html><html><body> <form action=\"/test.php\" target=\"_blank\"> Username:<br> <input type=\"text\" name=\"username\"> <br> Password:<br> <input type=\"password\" name=\"password\"> <br><br> <input type=\"submit\" value=\"Submit\"></form> </body></html>", "e": 7920, "s": 7666, "text": null }, { "code": null, "e": 8001, "s": 7920, "text": "After clicking on the submit button, the result \nwill open in a new browser tab." }, { "code": null, "e": 8197, "s": 8001, "text": "Name Attribute in Html Forms : The name attribute is required for each input field. If the name attribute is not specified in an input field then the data of that field would not be sent at all. " }, { "code": null, "e": 8202, "s": 8197, "text": "html" }, { "code": "<!DOCTYPE html><html><body> <form action=\"/test.php\" target=\"_blank\"> Username:<br> <input type=\"text\"> <br> Password:<br> <input type=\"password\" name=\"password\"> <br><br> <input type=\"submit\" value=\"Submit\"></form> </body></html>", "e": 8440, "s": 8202, "text": null }, { "code": null, "e": 8647, "s": 8440, "text": "In the above code, after clicking the submit button, the form data will\nbe sent to a page called /test.php. The data sent would not include the\nusername input field data since the name attribute is omitted." }, { "code": null, "e": 8807, "s": 8647, "text": "It is used to specify the HTTP method used to send data while submitting the form.There are two kinds of HTTP Methods, which are GET and POST.The GET Method – " }, { "code": null, "e": 8812, "s": 8807, "text": "html" }, { "code": "<!DOCTYPE html><html><body> <form action=\"/test.php\" target=\"_blank\" method=\"GET\"> Username:<br> <input type=\"text\" name=\"username\"> <br> Password:<br> <input type=\"password\" name=\"password\"> <br><br> <input type=\"submit\" value=\"Submit\"></form> </body></html>", "e": 9079, "s": 8812, "text": null }, { "code": null, "e": 9208, "s": 9079, "text": "In the GET method, after the submission of the form, the form values \nwill be visible in the address bar of the new browser tab." }, { "code": null, "e": 9227, "s": 9208, "text": "The Post Method – " }, { "code": null, "e": 9232, "s": 9227, "text": "html" }, { "code": "<!DOCTYPE html><html><body> <form action=\"/test.php\" target=\"_blank\" method=\"post\"> Username:<br> <input type=\"text\" name=\"username\"> <br> Password:<br> <input type=\"password\" name=\"password\"> <br><br> <input type=\"submit\" value=\"Submit\"></form> </body></html>", "e": 9500, "s": 9232, "text": null }, { "code": null, "e": 9669, "s": 9500, "text": "In the post method, after the submission of the form, the form values\nwill not be visible in the address bar of the new browser tab as it was\nvisible in the GET method." }, { "code": null, "e": 9688, "s": 9669, "text": "Supported Browser:" }, { "code": null, "e": 9702, "s": 9688, "text": "Google Chrome" }, { "code": null, "e": 9720, "s": 9702, "text": "Internet Explorer" }, { "code": null, "e": 9728, "s": 9720, "text": "Firefox" }, { "code": null, "e": 9734, "s": 9728, "text": "Opera" }, { "code": null, "e": 9741, "s": 9734, "text": "Safari" }, { "code": null, "e": 9935, "s": 9741, "text": "HTML is the foundation of webpages, is used for webpage development by structuring websites and web apps.You can learn HTML from the ground up by following this HTML Tutorial and HTML Examples." }, { "code": null, "e": 9952, "s": 9935, "text": "akshaysingh98088" }, { "code": null, "e": 9964, "s": 9952, "text": "ysachin2314" }, { "code": null, "e": 9978, "s": 9964, "text": "jochenhansoul" }, { "code": null, "e": 9983, "s": 9978, "text": "HTML" }, { "code": null, "e": 10002, "s": 9983, "text": "Technical Scripter" }, { "code": null, "e": 10019, "s": 10002, "text": "Web Technologies" }, { "code": null, "e": 10024, "s": 10019, "text": "HTML" }, { "code": null, "e": 10122, "s": 10024, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 10146, "s": 10122, "text": "REST API (Introduction)" }, { "code": null, "e": 10183, "s": 10146, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 10222, "s": 10183, "text": "Design a Tribute Page using HTML & CSS" }, { "code": null, "e": 10250, "s": 10222, "text": "HTTP headers | Content-Type" }, { "code": null, "e": 10300, "s": 10250, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 10333, "s": 10300, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 10394, "s": 10333, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 10437, "s": 10394, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 10509, "s": 10437, "text": "Differences between Functional Components and Class Components in React" } ]
Pearson Product Moment Correlation
06 Jul, 2022 The Pearson product-moment correlation coefficient (or Pearson correlation coefficient) is a measure of the strength of a linear association between two variables and is denoted by r. Basically, a Pearson product-moment correlation attempts to draw a line of best fit through the data of two variables, and the Pearson correlation coefficient, r, indicates how far away all these data points are to this line of best fit (i.e., how well the data points fit this new model/line of best fit). The correlation coefficient can be calculated as the covariance divided by the standard deviation of the variables. The following formula is used to calculate the Pearson correlation (r): r= coefficient of correlation x_bar = mean of x-variable y_bar = mean of y-variable. x_i, y_i = samples of variable x,y The above value of the correlation coefficient can be between -1 and 1. A value close to 1 represents that perfect degree of association b/w the two variables and called a strong correlation and a value close to -1 represents the strong negative correlation. The value closer to 0 represents the weaker or no degree of correlation. A strongly positive correlation (r=1) Strongly Negative Correlation (r=-1) No correlation (r~=0) A test of significance for the Pearson’s correlation coefficient may be used to find out if the computed Pearson correlation r could have significantly occurred in the population in which the two variables are significantly related or not. The test statistics follow t-distribution with N-2 degree of freedom. The significance is computed using the following formula While performing the test, we may assume following hypothesis: Null Hypothesis: The null hypothesis could be that there is no correlation b/w two variables at a given degree of significance. That is, the value of Pearson correlation coefficient is close to 0. Alternate Hypothesis: The alternate hypothesis hypothesize that the value of Pearson correlation coefficient is significantly different from 0. That is there may be some correlation b/w two variables. Set up the hypothesis. Decide the level of significance. Calculate the degree of freedom (df = N-2) and using that value determine the critical value of t from t-distribution table. Calculate Pearson’s correlation coefficient and calculate the value of t from the formula above. Determine whether to accept or reject the hypothesis Python3 # importsimport numpy as npimport scipy.stats as statsimport matplotlib.pyplot as plt # define the variablex = np.arange(1,11)y = np.array([2, 1, 4, 5, 8, 12, 18, 25, 30, 27]) # plot the variablesplt.scatter(x,y)plt.plot(x,y) # the plot above represents a strong correlation.correlation_coeff, p_value = stats.pearsonr(x,y)# print pearson correlation coefficientprint(correlation_coeff)# print p-value: the smallest level of significance that will be enough to reject H0print(p_value) Line plot # correlation coefficient 0.960576518918945 # p-value 1.0076332440506521e-05 as5853535 simmytarika5 ML-Statistics Machine Learning Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Support Vector Machine Algorithm Introduction to Recurrent Neural Network ML | Monte Carlo Tree Search (MCTS) Markov Decision Process DBSCAN Clustering in ML | Density based clustering Normalization vs Standardization Bagging vs Boosting in Machine Learning Principal Component Analysis with Python Types of Environments in AI k-nearest neighbor algorithm in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n06 Jul, 2022" }, { "code": null, "e": 519, "s": 28, "text": "The Pearson product-moment correlation coefficient (or Pearson correlation coefficient) is a measure of the strength of a linear association between two variables and is denoted by r. Basically, a Pearson product-moment correlation attempts to draw a line of best fit through the data of two variables, and the Pearson correlation coefficient, r, indicates how far away all these data points are to this line of best fit (i.e., how well the data points fit this new model/line of best fit)." }, { "code": null, "e": 707, "s": 519, "text": "The correlation coefficient can be calculated as the covariance divided by the standard deviation of the variables. The following formula is used to calculate the Pearson correlation (r):" }, { "code": null, "e": 737, "s": 707, "text": "r= coefficient of correlation" }, { "code": null, "e": 764, "s": 737, "text": "x_bar = mean of x-variable" }, { "code": null, "e": 792, "s": 764, "text": "y_bar = mean of y-variable." }, { "code": null, "e": 828, "s": 792, "text": "x_i, y_i = samples of variable x,y" }, { "code": null, "e": 1160, "s": 828, "text": "The above value of the correlation coefficient can be between -1 and 1. A value close to 1 represents that perfect degree of association b/w the two variables and called a strong correlation and a value close to -1 represents the strong negative correlation. The value closer to 0 represents the weaker or no degree of correlation." }, { "code": null, "e": 1198, "s": 1160, "text": "A strongly positive correlation (r=1)" }, { "code": null, "e": 1235, "s": 1198, "text": "Strongly Negative Correlation (r=-1)" }, { "code": null, "e": 1257, "s": 1235, "text": "No correlation (r~=0)" }, { "code": null, "e": 1624, "s": 1257, "text": "A test of significance for the Pearson’s correlation coefficient may be used to find out if the computed Pearson correlation r could have significantly occurred in the population in which the two variables are significantly related or not. The test statistics follow t-distribution with N-2 degree of freedom. The significance is computed using the following formula" }, { "code": null, "e": 1687, "s": 1624, "text": "While performing the test, we may assume following hypothesis:" }, { "code": null, "e": 1884, "s": 1687, "text": "Null Hypothesis: The null hypothesis could be that there is no correlation b/w two variables at a given degree of significance. That is, the value of Pearson correlation coefficient is close to 0." }, { "code": null, "e": 2085, "s": 1884, "text": "Alternate Hypothesis: The alternate hypothesis hypothesize that the value of Pearson correlation coefficient is significantly different from 0. That is there may be some correlation b/w two variables." }, { "code": null, "e": 2108, "s": 2085, "text": "Set up the hypothesis." }, { "code": null, "e": 2142, "s": 2108, "text": "Decide the level of significance." }, { "code": null, "e": 2267, "s": 2142, "text": "Calculate the degree of freedom (df = N-2) and using that value determine the critical value of t from t-distribution table." }, { "code": null, "e": 2364, "s": 2267, "text": "Calculate Pearson’s correlation coefficient and calculate the value of t from the formula above." }, { "code": null, "e": 2417, "s": 2364, "text": "Determine whether to accept or reject the hypothesis" }, { "code": null, "e": 2425, "s": 2417, "text": "Python3" }, { "code": "# importsimport numpy as npimport scipy.stats as statsimport matplotlib.pyplot as plt # define the variablex = np.arange(1,11)y = np.array([2, 1, 4, 5, 8, 12, 18, 25, 30, 27]) # plot the variablesplt.scatter(x,y)plt.plot(x,y) # the plot above represents a strong correlation.correlation_coeff, p_value = stats.pearsonr(x,y)# print pearson correlation coefficientprint(correlation_coeff)# print p-value: the smallest level of significance that will be enough to reject H0print(p_value)", "e": 2910, "s": 2425, "text": null }, { "code": null, "e": 2924, "s": 2913, "text": "Line plot " }, { "code": null, "e": 3001, "s": 2924, "text": "# correlation coefficient\n0.960576518918945\n# p-value\n1.0076332440506521e-05" }, { "code": null, "e": 3013, "s": 3003, "text": "as5853535" }, { "code": null, "e": 3026, "s": 3013, "text": "simmytarika5" }, { "code": null, "e": 3040, "s": 3026, "text": "ML-Statistics" }, { "code": null, "e": 3057, "s": 3040, "text": "Machine Learning" }, { "code": null, "e": 3074, "s": 3057, "text": "Machine Learning" }, { "code": null, "e": 3172, "s": 3074, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3205, "s": 3172, "text": "Support Vector Machine Algorithm" }, { "code": null, "e": 3246, "s": 3205, "text": "Introduction to Recurrent Neural Network" }, { "code": null, "e": 3282, "s": 3246, "text": "ML | Monte Carlo Tree Search (MCTS)" }, { "code": null, "e": 3306, "s": 3282, "text": "Markov Decision Process" }, { "code": null, "e": 3357, "s": 3306, "text": "DBSCAN Clustering in ML | Density based clustering" }, { "code": null, "e": 3390, "s": 3357, "text": "Normalization vs Standardization" }, { "code": null, "e": 3430, "s": 3390, "text": "Bagging vs Boosting in Machine Learning" }, { "code": null, "e": 3471, "s": 3430, "text": "Principal Component Analysis with Python" }, { "code": null, "e": 3499, "s": 3471, "text": "Types of Environments in AI" } ]
Tryit Editor v3.7
Tryit: Display a less-than sign
[]
Collapse multiple Columns in Pandas - GeeksforGeeks
08 Mar, 2019 While operating dataframes in Pandas, we might encounter a situation to collapse the columns. Let it becumulated data of multiple columns or collapse based on some other requirement. Let’s see how to collapse multiple columns in Pandas. Following steps are to be followed to collapse multiple columns in Pandas: Step #1: Load numpy and Pandas.Step #2: Create random data and use them to create a pandas dataframe.Step #3: Convert multiple lists into a single data frame, by creating a dictionary for each list with a name.Step #4: Then use Pandas dataframe into dict. A data frame with columns of data and column for names is ready.Step #5: Specify which columns are to be collapsed. That can be done by specifying the mapping as a dictionary, where the keys are the names of columns to be combined or collapsed and the values are the names of the resulting column. Example 1: # Python program to collapse# multiple Columns using Pandasimport pandas as pd # sample datan = 3Sample_1 = [57, 51, 6]Sample_2 = [92, 16, 19]Sample_3 = [15, 93, 71]Sample_4 = [28, 73, 31] sample_id = zip(["S"]*n, list(range(1, n + 1))) s_names = [''.join([w[0], str(w[1])]) for w in sample_id] d = {'s_names': s_names, 'Sample_1': Sample_1, 'Sample_2': Sample_2, 'Sample_3': Sample_3, 'Sample_4': Sample_4} df_1 = pd.DataFrame(d) mapping = {'Sample_1': 'Result_1', 'Sample_2': 'Result_1', 'Sample_3': 'Result_2', 'Sample_4': 'Result_2'} df = df_1.set_index('s_names').groupby(mapping, axis = 1).sum() df.reset_index(level = 0) Output: Example 2: # Python program to collapse# multiple Columns using Pandasimport pandas as pddf = pd.DataFrame({'First': ['Manan ', 'Raghav ', 'Sunny '], 'Last': ['Goel', 'Sharma', 'Chawla'], 'Age':[12, 24, 56]}) mapping = {'First': 'Full Name', 'Last': 'Full Name'} df = df.set_index('Age').groupby(mapping, axis = 1).sum() df.reset_index(level = 0) Output: pandas-dataframe-program Picked Python pandas-dataFrame Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python OOPs Concepts How to Install PIP on Windows ? Bar Plot in Matplotlib Defaultdict in Python Python Classes and Objects Deque in Python Check if element exists in list in Python How to drop one or multiple columns in Pandas Dataframe Python - Ways to remove duplicates from list Class method vs Static method in Python
[ { "code": null, "e": 24212, "s": 24184, "text": "\n08 Mar, 2019" }, { "code": null, "e": 24449, "s": 24212, "text": "While operating dataframes in Pandas, we might encounter a situation to collapse the columns. Let it becumulated data of multiple columns or collapse based on some other requirement. Let’s see how to collapse multiple columns in Pandas." }, { "code": null, "e": 24524, "s": 24449, "text": "Following steps are to be followed to collapse multiple columns in Pandas:" }, { "code": null, "e": 25078, "s": 24524, "text": "Step #1: Load numpy and Pandas.Step #2: Create random data and use them to create a pandas dataframe.Step #3: Convert multiple lists into a single data frame, by creating a dictionary for each list with a name.Step #4: Then use Pandas dataframe into dict. A data frame with columns of data and column for names is ready.Step #5: Specify which columns are to be collapsed. That can be done by specifying the mapping as a dictionary, where the keys are the names of columns to be combined or collapsed and the values are the names of the resulting column." }, { "code": null, "e": 25089, "s": 25078, "text": "Example 1:" }, { "code": "# Python program to collapse# multiple Columns using Pandasimport pandas as pd # sample datan = 3Sample_1 = [57, 51, 6]Sample_2 = [92, 16, 19]Sample_3 = [15, 93, 71]Sample_4 = [28, 73, 31] sample_id = zip([\"S\"]*n, list(range(1, n + 1))) s_names = [''.join([w[0], str(w[1])]) for w in sample_id] d = {'s_names': s_names, 'Sample_1': Sample_1, 'Sample_2': Sample_2, 'Sample_3': Sample_3, 'Sample_4': Sample_4} df_1 = pd.DataFrame(d) mapping = {'Sample_1': 'Result_1', 'Sample_2': 'Result_1', 'Sample_3': 'Result_2', 'Sample_4': 'Result_2'} df = df_1.set_index('s_names').groupby(mapping, axis = 1).sum() df.reset_index(level = 0)", "e": 25766, "s": 25089, "text": null }, { "code": null, "e": 25774, "s": 25766, "text": "Output:" }, { "code": null, "e": 25785, "s": 25774, "text": "Example 2:" }, { "code": "# Python program to collapse# multiple Columns using Pandasimport pandas as pddf = pd.DataFrame({'First': ['Manan ', 'Raghav ', 'Sunny '], 'Last': ['Goel', 'Sharma', 'Chawla'], 'Age':[12, 24, 56]}) mapping = {'First': 'Full Name', 'Last': 'Full Name'} df = df.set_index('Age').groupby(mapping, axis = 1).sum() df.reset_index(level = 0)", "e": 26160, "s": 25785, "text": null }, { "code": null, "e": 26168, "s": 26160, "text": "Output:" }, { "code": null, "e": 26193, "s": 26168, "text": "pandas-dataframe-program" }, { "code": null, "e": 26200, "s": 26193, "text": "Picked" }, { "code": null, "e": 26224, "s": 26200, "text": "Python pandas-dataFrame" }, { "code": null, "e": 26238, "s": 26224, "text": "Python-pandas" }, { "code": null, "e": 26245, "s": 26238, "text": "Python" }, { "code": null, "e": 26343, "s": 26245, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26352, "s": 26343, "text": "Comments" }, { "code": null, "e": 26365, "s": 26352, "text": "Old Comments" }, { "code": null, "e": 26386, "s": 26365, "text": "Python OOPs Concepts" }, { "code": null, "e": 26418, "s": 26386, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26441, "s": 26418, "text": "Bar Plot in Matplotlib" }, { "code": null, "e": 26463, "s": 26441, "text": "Defaultdict in Python" }, { "code": null, "e": 26490, "s": 26463, "text": "Python Classes and Objects" }, { "code": null, "e": 26506, "s": 26490, "text": "Deque in Python" }, { "code": null, "e": 26548, "s": 26506, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26604, "s": 26548, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26649, "s": 26604, "text": "Python - Ways to remove duplicates from list" } ]
Practical Guide to Ensemble Learning | by Idil Ismiguzel | Towards Data Science
Ensemble learning is a technique used in machine learning to combine multiple models into a group model, in other words into an ensemble model. The ensemble model aims to perform better than each model alone or if not, to perform at least as well as the best individual model in the group. In this article, you will learn popular ensemble methods: voting, bagging, boosting, and stacking along with their Python implementations. We will use libraries such as scikit-learn for voting, bagging and boosting, and mlxtend for stacking. While following the article, I encourage you to check out the Jupyter Notebook on my GitHub for the full analysis and code. 🌻 The intuition behind ensemble learning is often described with a phenomenon called the Wisdom of the Crowd which means aggregated decisions made by a group of individuals are often better than the individual decisions. There are multiple methods for creating aggregated models (or ensembles) which we can categorize as heterogenous and homogenous ensembles. In heterogeneous ensembles, we combine multiple different fine-tuned models trained on the same dataset to generate an ensemble model. This method usually involves voting, averaging, or stacking techniques. On the other hand in homogenous ensembles, we use the same model which we call the “weak model” and with techniques such as bagging and boosting we convert this weak model to a stronger one. Let’s start with the basic ensemble learning methods from heterogeneous ensembles: Voting and Averaging. Hard voting ensemble is used for classification tasks and it combines predictions from multiple fine-tuned models that are trained on the same data based on the majority voting principle. For example, if we are ensembling 3 classifiers that have predictions as “Class A”, “Class A”, “Class B”, then the ensemble model will predict the output as “Class A” based on the majority votes, or in other words, based on the mode of the distribution of individual model predictions. As you can see, we will prefer having an odd number of individual models (e.g. 3, 5, 7 models) to be sure we will not have equal votes. # Instantiate individual modelsclf_1 = KNeighborsClassifier()clf_2 = LogisticRegression()clf_3 = DecisionTreeClassifier()# Create voting classifiervoting_ens = VotingClassifier(estimators=[('knn', clf_1), ('lr', clf_2), ('dt', clf_3)], voting='hard')# Fit and predict with the models and ensemblefor clf in (clf_1, clf_2, clf_3, voting_ens): clf.fit(X_train, y_train) y_pred = clf.predict(X_test) print(clf.__class__.__name__, accuracy_score(y_test, y_pred)) Accuracy Scores: KNeighborsClassifier 0.93LogisticRegression 0.92DecisionTreeClassifier 0.93VotingClassifier 0.94 ✅ As we can see voting classifier has the highest accuracy score! Since ensemble will combine individual models predictions, each model should have been fine-tuned and already performing well. In the code above, I only initialized it for demonstrative purposes. Soft Voting is used for both classification and regression tasks and it combines predictions of multiple fine-tuned models trained on the same data by averaging them. For classification, it uses predicted probabilities and for regression, it uses predicted values. We do not need an odd number of individual models like in hard voting, but we need to have at least 2 models to build an ensemble. One advantage of soft voting is you can decide whether if you want to average each model weighted equally (mean) or weighted by the classifier’s importance, which is an input parameter. If you prefer using a weighted average, then output predictions of the ensemble model will be the greatest sum of weighted probabilities/values. # Instantiate individual modelsreg1 = DecisionTreeRegressor()reg2 = LinearRegression()# Create voting regressorvoting_ens = VotingRegressor(estimators=[('dt', reg1), ('lr', reg2)], weights=[2,1])# Fit and predict with the models and ensemblefor reg in (reg1, reg2, voting_ens): reg.fit(X_train, y_train) y_pred = reg.predict(X_test) print(reg.__class__.__name__, mean_absolute_error(y_test, y_pred)) Mean Absolute Errors: DecisionTreeRegressor 3.0LinearRegression 3.2VotingRegressor 2.5 ✅ It is important to understand that the performance of a voting ensemble (hard and soft voting) heavily depends on individual models’ performance. If we are ensembling one good and two average-performing models, then the ensemble model will show results close to the average models. In this case, we either need to improve average performing models or we shouldn’t make an ensemble and use the good-performing model instead. 📌 After understanding voting and averaging, we can continue with the last heterogeneous ensemble technique: Stacking. Stacking stands for “Stacked Generalization” and it combines multiple individual models (or base models) with a final model (or meta-model) that is trained with the predictions of base models. It can be used for both classification and regression tasks with an option to use values or probabilities for classification tasks. The difference from voting ensembles is that in stacking meta-model is also a trainable model and in fact, it is trained using base models’ predictions. Since these predictions are input features for meta-model, they are also called meta-features. We have the option to choose between including the initial dataset to meta-features or only using the predictions. Stacking can be implemented with more than two layers: multi-layer stacking, where we define base models, aggregated with another layer of models, and then the final meta-model. Even though this can produce better results, we should consider the cost of time due to complexity. To prevent overfitting, we can use stacking with cross-validation instead of standard stacking and mlxtend library has implementations for both versions. Below, I will implement: 1.Standard stacking for a classification task from mlxtend.classifier import StackingClassifier# Initialize individual modelsclf_1 = KNeighborsClassifier()clf_2 = GaussianNB()clf_3 = DecisionTreeClassifier()# Initialize meta-modelclf_meta = LogisticRegression()# Create stacking classifierclf_stack = StackingClassifier(classifiers=[clf_1, clf_2, clf_3], meta_classifier=clf_meta,use_probas=False, use_features_in_secondary=False)# Fit and predict with the models and ensemblefor clf in (clf_1, clf_2, clf_3, clf_meta, clf_stack): clf.fit(X_train, y_train) y_pred = clf.predict(X_test) print(clf.__class__.__name__, accuracy_score(y_test, y_pred)) KNeighborsClassifier 0.84GaussianNB 0.83 DecisionTreeClassifier 0.89 LogisticRegression 0.85 StackingClassifier 0.90 ✅ 2.Stacking with cross-validation for a regression task from mlxtend.regressor import StackingCVRegressor# Initialize individual modelsreg1 = DecisionTreeRegressor()reg2 = SVR()# Create meta-modelmeta_model = LinearRegression()# Create stacking classifierreg_stack = StackingCVRegressor(regressors=[reg1, reg2], meta_regressor=meta_model,use_features_in_secondary=False)# Fit and predict with the models and ensemblefor reg in (reg1, reg2, meta_model, reg_stack): reg.fit(X_train, y_train) y_pred = reg.predict(X_test) print(reg.__class__.__name__, mean_absolute_error(y_test, y_pred)) Mean Absolute Errors: DecisionTreeRegressor 3.3SVR 5.2LinearRegression 3.2StackingCVRegressor 2.9 ✅ Bootstrap Aggregating or in short “Bagging” aggregates multiple estimators that use the same algorithm trained with different subsets of the training data. It can be used for both classification and regression tasks, using bootstrapping to create training data for each estimator with random sampling. Bootstrapping is a method to create samples with replacement from the original data. It is done with replacement to give equal probability to each data point for being picked. Due to selection with replacement, some data points may be picked multiple times and some may never been picked. We can calculate probability of not being picked for a data point in bootstrap sample with size n with the following formula. (preferible n is a large number). This means that each bagging estimator is trained using around 63% of the training dataset and we call the remaining 37% out-of-bag (OOB) sample. To sum up, bagging draws n training datasets with replacement from the original training data for n estimators. Each estimator is trained on their sampled training dataset in parallel to make predictions. Then, bagging aggregates these predictions using techniques such as hard voting or soft voting. In scikit-learn, we can define parameter n_estimators equal to n — number of estimators/models we would like to produce and oob_score can be set “True” if we would like to evaluate each estimator’s performance on their out-of-bag samples. By doing that, we can easily learn estimators’ performance on unseen data without using cross-validation or a separate test set. oob_score_ function calculates the mean of all n oob_scores using metrics accuracy score for classification and R^2 for regression by default. from sklearn.ensemble import BaggingClassifier# Initialize weak modelbase_model = DecisionTreeClassifier(max_depth=3)# Create bagging classifierclf_bagging = BaggingClassifier(base_estimator=base_model, n_estimators=1000, oob_score=True)clf_bagging.fit(X_train, y_train)# Check oob scoreprint(clf_bagging.oob_score_) oob_score_ : 0.918 # Compare with test setpred = clf_bagging.predict(X_test)print(accuracy_score(y_test, pred)) accuracy_score: 0.916 Randomly sampled training datasets make the training less prone to deviations on the original data, therefore bagging reduces the variance of individual estimators. A very popular bagging technique is random forest where the estimators are chosen as a decision tree. Random forest uses bootstrapping to create training datasets with replacement and it also selects a set of features (without replacement) to maximize the randomization on each training dataset. Usually, the number of features selected is equal to the square root of the total number of features. Boosting uses gradual learning which is an iterative process focusing on minimizing errors of the previous estimator. It is a sequential method where each estimator is dependent on the previous estimator to improve predictions. The most popular boosting methods are adaptive boosting (AdaBoost) and gradient boosting. AdaBoost uses the entire training dataset for each n estimator with some important modifications. The first estimator (weak model) is trained on the original dataset with equally weighted data points. After the first predictions are made and error is calculated, the mispredicted data points are assigned with higher weights compared to the correctly predicted data points. By doing that next estimator will focus on these difficult-to-predict instances. This process will continue until all n estimators (say 1000) are sequentially trained. Finally, the ensemble’s prediction will be obtained with weighted majority voting or weighted averaging. from sklearn.ensemble import AdaBoostRegressor# Initialize weak modelbase_model = LinearRegression(normalize=True)# Create AdaBoost regressorreg_adaboost = AdaBoostRegressor(base_estimator=base_model, n_estimators=1000)reg_adaboost.fit(X_train, y_train)# Predict and compare with y_testpred = reg_adaboost.predict(X_test)rmse = np.sqrt(mean_squared_error(y_test, pred))print('RMSE:', rmse) RMSE: 4.18 Since every next estimator aims at correcting misclassified/miss-predicted data points, boosting reduces the bias of each estimator. Gradient Boosting, very similar to AdaBoost, improves previous estimators with sequential iterations, but instead of updating weights of training data it fits new estimators to the residual errors from the previous estimator. XGBoost, LightGBM and CatBoost are popular gradient boosting algorithms, especially XGBoost is the winner of many competitions and popular for being very fast and scalable. In this article, we have learned main ensemble learning techniques to improve model performance. We covered the theoretical background of each technique as well as relevant Python libraries to demonstrate these mechanisms. Ensemble learning has a big portion in machine learning and it is important for every data scientist and machine learning practitioner. You may find a ton to learn, but I am sure you will never regret it!! 💯 If you need a refresher on bootstrapping or if you want to learn more about sampling techniques you can have a look at my article below. towardsdatascience.com I hope you enjoyed reading about ensemble learning methods and find the article useful for your analyses! If you liked this article, you can read my other articles here and follow me on Medium. Let me know if you have any questions or suggestions.✨ Enjoy this article? Become a member for more! Ensemble Learning Further Readingmlxtend library Ensemble Learning Further Reading
[ { "code": null, "e": 462, "s": 172, "text": "Ensemble learning is a technique used in machine learning to combine multiple models into a group model, in other words into an ensemble model. The ensemble model aims to perform better than each model alone or if not, to perform at least as well as the best individual model in the group." }, { "code": null, "e": 704, "s": 462, "text": "In this article, you will learn popular ensemble methods: voting, bagging, boosting, and stacking along with their Python implementations. We will use libraries such as scikit-learn for voting, bagging and boosting, and mlxtend for stacking." }, { "code": null, "e": 830, "s": 704, "text": "While following the article, I encourage you to check out the Jupyter Notebook on my GitHub for the full analysis and code. 🌻" }, { "code": null, "e": 1188, "s": 830, "text": "The intuition behind ensemble learning is often described with a phenomenon called the Wisdom of the Crowd which means aggregated decisions made by a group of individuals are often better than the individual decisions. There are multiple methods for creating aggregated models (or ensembles) which we can categorize as heterogenous and homogenous ensembles." }, { "code": null, "e": 1586, "s": 1188, "text": "In heterogeneous ensembles, we combine multiple different fine-tuned models trained on the same dataset to generate an ensemble model. This method usually involves voting, averaging, or stacking techniques. On the other hand in homogenous ensembles, we use the same model which we call the “weak model” and with techniques such as bagging and boosting we convert this weak model to a stronger one." }, { "code": null, "e": 1691, "s": 1586, "text": "Let’s start with the basic ensemble learning methods from heterogeneous ensembles: Voting and Averaging." }, { "code": null, "e": 2301, "s": 1691, "text": "Hard voting ensemble is used for classification tasks and it combines predictions from multiple fine-tuned models that are trained on the same data based on the majority voting principle. For example, if we are ensembling 3 classifiers that have predictions as “Class A”, “Class A”, “Class B”, then the ensemble model will predict the output as “Class A” based on the majority votes, or in other words, based on the mode of the distribution of individual model predictions. As you can see, we will prefer having an odd number of individual models (e.g. 3, 5, 7 models) to be sure we will not have equal votes." }, { "code": null, "e": 2766, "s": 2301, "text": "# Instantiate individual modelsclf_1 = KNeighborsClassifier()clf_2 = LogisticRegression()clf_3 = DecisionTreeClassifier()# Create voting classifiervoting_ens = VotingClassifier(estimators=[('knn', clf_1), ('lr', clf_2), ('dt', clf_3)], voting='hard')# Fit and predict with the models and ensemblefor clf in (clf_1, clf_2, clf_3, voting_ens): clf.fit(X_train, y_train) y_pred = clf.predict(X_test) print(clf.__class__.__name__, accuracy_score(y_test, y_pred))" }, { "code": null, "e": 2783, "s": 2766, "text": "Accuracy Scores:" }, { "code": null, "e": 2882, "s": 2783, "text": "KNeighborsClassifier 0.93LogisticRegression 0.92DecisionTreeClassifier 0.93VotingClassifier 0.94 ✅" }, { "code": null, "e": 3142, "s": 2882, "text": "As we can see voting classifier has the highest accuracy score! Since ensemble will combine individual models predictions, each model should have been fine-tuned and already performing well. In the code above, I only initialized it for demonstrative purposes." }, { "code": null, "e": 3538, "s": 3142, "text": "Soft Voting is used for both classification and regression tasks and it combines predictions of multiple fine-tuned models trained on the same data by averaging them. For classification, it uses predicted probabilities and for regression, it uses predicted values. We do not need an odd number of individual models like in hard voting, but we need to have at least 2 models to build an ensemble." }, { "code": null, "e": 3869, "s": 3538, "text": "One advantage of soft voting is you can decide whether if you want to average each model weighted equally (mean) or weighted by the classifier’s importance, which is an input parameter. If you prefer using a weighted average, then output predictions of the ensemble model will be the greatest sum of weighted probabilities/values." }, { "code": null, "e": 4275, "s": 3869, "text": "# Instantiate individual modelsreg1 = DecisionTreeRegressor()reg2 = LinearRegression()# Create voting regressorvoting_ens = VotingRegressor(estimators=[('dt', reg1), ('lr', reg2)], weights=[2,1])# Fit and predict with the models and ensemblefor reg in (reg1, reg2, voting_ens): reg.fit(X_train, y_train) y_pred = reg.predict(X_test) print(reg.__class__.__name__, mean_absolute_error(y_test, y_pred))" }, { "code": null, "e": 4297, "s": 4275, "text": "Mean Absolute Errors:" }, { "code": null, "e": 4364, "s": 4297, "text": "DecisionTreeRegressor 3.0LinearRegression 3.2VotingRegressor 2.5 ✅" }, { "code": null, "e": 4790, "s": 4364, "text": "It is important to understand that the performance of a voting ensemble (hard and soft voting) heavily depends on individual models’ performance. If we are ensembling one good and two average-performing models, then the ensemble model will show results close to the average models. In this case, we either need to improve average performing models or we shouldn’t make an ensemble and use the good-performing model instead. 📌" }, { "code": null, "e": 4906, "s": 4790, "text": "After understanding voting and averaging, we can continue with the last heterogeneous ensemble technique: Stacking." }, { "code": null, "e": 5231, "s": 4906, "text": "Stacking stands for “Stacked Generalization” and it combines multiple individual models (or base models) with a final model (or meta-model) that is trained with the predictions of base models. It can be used for both classification and regression tasks with an option to use values or probabilities for classification tasks." }, { "code": null, "e": 5594, "s": 5231, "text": "The difference from voting ensembles is that in stacking meta-model is also a trainable model and in fact, it is trained using base models’ predictions. Since these predictions are input features for meta-model, they are also called meta-features. We have the option to choose between including the initial dataset to meta-features or only using the predictions." }, { "code": null, "e": 5872, "s": 5594, "text": "Stacking can be implemented with more than two layers: multi-layer stacking, where we define base models, aggregated with another layer of models, and then the final meta-model. Even though this can produce better results, we should consider the cost of time due to complexity." }, { "code": null, "e": 6051, "s": 5872, "text": "To prevent overfitting, we can use stacking with cross-validation instead of standard stacking and mlxtend library has implementations for both versions. Below, I will implement:" }, { "code": null, "e": 6097, "s": 6051, "text": "1.Standard stacking for a classification task" }, { "code": null, "e": 6705, "s": 6097, "text": "from mlxtend.classifier import StackingClassifier# Initialize individual modelsclf_1 = KNeighborsClassifier()clf_2 = GaussianNB()clf_3 = DecisionTreeClassifier()# Initialize meta-modelclf_meta = LogisticRegression()# Create stacking classifierclf_stack = StackingClassifier(classifiers=[clf_1, clf_2, clf_3], meta_classifier=clf_meta,use_probas=False, use_features_in_secondary=False)# Fit and predict with the models and ensemblefor clf in (clf_1, clf_2, clf_3, clf_meta, clf_stack): clf.fit(X_train, y_train) y_pred = clf.predict(X_test) print(clf.__class__.__name__, accuracy_score(y_test, y_pred))" }, { "code": null, "e": 6824, "s": 6705, "text": "KNeighborsClassifier 0.84GaussianNB 0.83 DecisionTreeClassifier 0.89 LogisticRegression 0.85 StackingClassifier 0.90 ✅" }, { "code": null, "e": 6879, "s": 6824, "text": "2.Stacking with cross-validation for a regression task" }, { "code": null, "e": 7415, "s": 6879, "text": "from mlxtend.regressor import StackingCVRegressor# Initialize individual modelsreg1 = DecisionTreeRegressor()reg2 = SVR()# Create meta-modelmeta_model = LinearRegression()# Create stacking classifierreg_stack = StackingCVRegressor(regressors=[reg1, reg2], meta_regressor=meta_model,use_features_in_secondary=False)# Fit and predict with the models and ensemblefor reg in (reg1, reg2, meta_model, reg_stack): reg.fit(X_train, y_train) y_pred = reg.predict(X_test) print(reg.__class__.__name__, mean_absolute_error(y_test, y_pred))" }, { "code": null, "e": 7437, "s": 7415, "text": "Mean Absolute Errors:" }, { "code": null, "e": 7515, "s": 7437, "text": "DecisionTreeRegressor 3.3SVR 5.2LinearRegression 3.2StackingCVRegressor 2.9 ✅" }, { "code": null, "e": 7817, "s": 7515, "text": "Bootstrap Aggregating or in short “Bagging” aggregates multiple estimators that use the same algorithm trained with different subsets of the training data. It can be used for both classification and regression tasks, using bootstrapping to create training data for each estimator with random sampling." }, { "code": null, "e": 8266, "s": 7817, "text": "Bootstrapping is a method to create samples with replacement from the original data. It is done with replacement to give equal probability to each data point for being picked. Due to selection with replacement, some data points may be picked multiple times and some may never been picked. We can calculate probability of not being picked for a data point in bootstrap sample with size n with the following formula. (preferible n is a large number)." }, { "code": null, "e": 8412, "s": 8266, "text": "This means that each bagging estimator is trained using around 63% of the training dataset and we call the remaining 37% out-of-bag (OOB) sample." }, { "code": null, "e": 8713, "s": 8412, "text": "To sum up, bagging draws n training datasets with replacement from the original training data for n estimators. Each estimator is trained on their sampled training dataset in parallel to make predictions. Then, bagging aggregates these predictions using techniques such as hard voting or soft voting." }, { "code": null, "e": 9224, "s": 8713, "text": "In scikit-learn, we can define parameter n_estimators equal to n — number of estimators/models we would like to produce and oob_score can be set “True” if we would like to evaluate each estimator’s performance on their out-of-bag samples. By doing that, we can easily learn estimators’ performance on unseen data without using cross-validation or a separate test set. oob_score_ function calculates the mean of all n oob_scores using metrics accuracy score for classification and R^2 for regression by default." }, { "code": null, "e": 9541, "s": 9224, "text": "from sklearn.ensemble import BaggingClassifier# Initialize weak modelbase_model = DecisionTreeClassifier(max_depth=3)# Create bagging classifierclf_bagging = BaggingClassifier(base_estimator=base_model, n_estimators=1000, oob_score=True)clf_bagging.fit(X_train, y_train)# Check oob scoreprint(clf_bagging.oob_score_)" }, { "code": null, "e": 9560, "s": 9541, "text": "oob_score_ : 0.918" }, { "code": null, "e": 9653, "s": 9560, "text": "# Compare with test setpred = clf_bagging.predict(X_test)print(accuracy_score(y_test, pred))" }, { "code": null, "e": 9675, "s": 9653, "text": "accuracy_score: 0.916" }, { "code": null, "e": 9840, "s": 9675, "text": "Randomly sampled training datasets make the training less prone to deviations on the original data, therefore bagging reduces the variance of individual estimators." }, { "code": null, "e": 10238, "s": 9840, "text": "A very popular bagging technique is random forest where the estimators are chosen as a decision tree. Random forest uses bootstrapping to create training datasets with replacement and it also selects a set of features (without replacement) to maximize the randomization on each training dataset. Usually, the number of features selected is equal to the square root of the total number of features." }, { "code": null, "e": 10556, "s": 10238, "text": "Boosting uses gradual learning which is an iterative process focusing on minimizing errors of the previous estimator. It is a sequential method where each estimator is dependent on the previous estimator to improve predictions. The most popular boosting methods are adaptive boosting (AdaBoost) and gradient boosting." }, { "code": null, "e": 11203, "s": 10556, "text": "AdaBoost uses the entire training dataset for each n estimator with some important modifications. The first estimator (weak model) is trained on the original dataset with equally weighted data points. After the first predictions are made and error is calculated, the mispredicted data points are assigned with higher weights compared to the correctly predicted data points. By doing that next estimator will focus on these difficult-to-predict instances. This process will continue until all n estimators (say 1000) are sequentially trained. Finally, the ensemble’s prediction will be obtained with weighted majority voting or weighted averaging." }, { "code": null, "e": 11593, "s": 11203, "text": "from sklearn.ensemble import AdaBoostRegressor# Initialize weak modelbase_model = LinearRegression(normalize=True)# Create AdaBoost regressorreg_adaboost = AdaBoostRegressor(base_estimator=base_model, n_estimators=1000)reg_adaboost.fit(X_train, y_train)# Predict and compare with y_testpred = reg_adaboost.predict(X_test)rmse = np.sqrt(mean_squared_error(y_test, pred))print('RMSE:', rmse)" }, { "code": null, "e": 11604, "s": 11593, "text": "RMSE: 4.18" }, { "code": null, "e": 11737, "s": 11604, "text": "Since every next estimator aims at correcting misclassified/miss-predicted data points, boosting reduces the bias of each estimator." }, { "code": null, "e": 12136, "s": 11737, "text": "Gradient Boosting, very similar to AdaBoost, improves previous estimators with sequential iterations, but instead of updating weights of training data it fits new estimators to the residual errors from the previous estimator. XGBoost, LightGBM and CatBoost are popular gradient boosting algorithms, especially XGBoost is the winner of many competitions and popular for being very fast and scalable." }, { "code": null, "e": 12359, "s": 12136, "text": "In this article, we have learned main ensemble learning techniques to improve model performance. We covered the theoretical background of each technique as well as relevant Python libraries to demonstrate these mechanisms." }, { "code": null, "e": 12567, "s": 12359, "text": "Ensemble learning has a big portion in machine learning and it is important for every data scientist and machine learning practitioner. You may find a ton to learn, but I am sure you will never regret it!! 💯" }, { "code": null, "e": 12704, "s": 12567, "text": "If you need a refresher on bootstrapping or if you want to learn more about sampling techniques you can have a look at my article below." }, { "code": null, "e": 12727, "s": 12704, "text": "towardsdatascience.com" }, { "code": null, "e": 12833, "s": 12727, "text": "I hope you enjoyed reading about ensemble learning methods and find the article useful for your analyses!" }, { "code": null, "e": 12976, "s": 12833, "text": "If you liked this article, you can read my other articles here and follow me on Medium. Let me know if you have any questions or suggestions.✨" }, { "code": null, "e": 13022, "s": 12976, "text": "Enjoy this article? Become a member for more!" }, { "code": null, "e": 13071, "s": 13022, "text": "Ensemble Learning Further Readingmlxtend library" } ]
Commonly Asked C++ Interview Questions
Here we will see some important C++ interview questions. What are the differences between C and C++? What are the differences between C and C++? What are the differences between pointers and references? What are the differences between pointers and references? The main differences between pointers and references are - References are used to refer an existing variable in another name whereas pointers are used to store address of variable. References are used to refer an existing variable in another name whereas pointers are used to store address of variable. References cannot have a null value assigned but pointer can. References cannot have a null value assigned but pointer can. A reference variable can be referenced by pass by value whereas a pointer can be referenced but pass by reference. A reference variable can be referenced by pass by value whereas a pointer can be referenced but pass by reference. A reference must be initialized on declaration while it is not necessary in case of pointer. A reference must be initialized on declaration while it is not necessary in case of pointer. A reference shares the same memory address with the original variable but also takes up some space on the stack whereas a pointer has its own memory address and size on the stack A reference shares the same memory address with the original variable but also takes up some space on the stack whereas a pointer has its own memory address and size on the stack What is virtual function in C++? What is virtual function in C++? Virtual functions in C++ use to create a list of base class pointers and call methods of any of the derived classes without even knowing the kind of derived class object. Virtual functions are resolved late, at the runtime. If A virtual function in a base class declared as once a member function, it becomes virtual in every class derived from that base class. So, use of the keyword virtual is not necessary in the derived class while declaring redefined versions of the virtual base class function. Live Demo #include<iostream> using namespace std; class B { public: virtual void s() { cout<<" In Base \n"; } }; class D: public B { public: void s() { cout<<"In Derived \n"; } }; int main(void) { D d; // An object of class D B *b= &d; // A pointer of type B* pointing to d b->s(); // prints"D::s() called" return 0; } In Derived What is this pointer in C++? Every object in C++ has access to its own address through an important pointer called this pointer. The this pointer is an implicit parameter to all member functions. Therefore, inside a member function, this may be used to refer to the invoking object. Friend functions do not have a this pointer, because friends are not members of a class. Only member functions have a this pointer. Let us try the following example to understand the concept of this pointer − Live Demo #include <iostream> using namespace std; class Box { public: // Constructor definition Box(double l = 2.0, double b = 2.0, double h = 2.0) { cout <<"Constructor called." << endl; length = l; breadth = b; height = h; } double Volume() { return length * breadth * height; } int compare(Box box) { return this->Volume() > box.Volume(); } private: double length; // Length of a box double breadth; // Breadth of a box double height; // Height of a box }; int main(void) { Box Box1(3.3, 1.2, 1.5); // Declare box1 Box Box2(8.5, 6.0, 2.0); // Declare box2 if(Box1.compare(Box2)) { cout << "Box2 is smaller than Box1" <<endl; } else { cout << "Box2 is equal to or larger than Box1" <<endl; } return 0; } Constructor called. Constructor called. Box2 is equal to or larger than Box1
[ { "code": null, "e": 1119, "s": 1062, "text": "Here we will see some important C++ interview questions." }, { "code": null, "e": 1163, "s": 1119, "text": "What are the differences between C and C++?" }, { "code": null, "e": 1207, "s": 1163, "text": "What are the differences between C and C++?" }, { "code": null, "e": 1265, "s": 1207, "text": "What are the differences between pointers and references?" }, { "code": null, "e": 1323, "s": 1265, "text": "What are the differences between pointers and references?" }, { "code": null, "e": 1382, "s": 1323, "text": "The main differences between pointers and references are -" }, { "code": null, "e": 1504, "s": 1382, "text": "References are used to refer an existing variable in another name whereas pointers are used to store address of variable." }, { "code": null, "e": 1626, "s": 1504, "text": "References are used to refer an existing variable in another name whereas pointers are used to store address of variable." }, { "code": null, "e": 1688, "s": 1626, "text": "References cannot have a null value assigned but pointer can." }, { "code": null, "e": 1750, "s": 1688, "text": "References cannot have a null value assigned but pointer can." }, { "code": null, "e": 1865, "s": 1750, "text": "A reference variable can be referenced by pass by value whereas a pointer can be referenced but pass by reference." }, { "code": null, "e": 1980, "s": 1865, "text": "A reference variable can be referenced by pass by value whereas a pointer can be referenced but pass by reference." }, { "code": null, "e": 2073, "s": 1980, "text": "A reference must be initialized on declaration while it is not necessary in case of pointer." }, { "code": null, "e": 2166, "s": 2073, "text": "A reference must be initialized on declaration while it is not necessary in case of pointer." }, { "code": null, "e": 2345, "s": 2166, "text": "A reference shares the same memory address with the original variable but also takes up some space on the stack whereas a pointer has its own memory address and size on the stack" }, { "code": null, "e": 2524, "s": 2345, "text": "A reference shares the same memory address with the original variable but also takes up some space on the stack whereas a pointer has its own memory address and size on the stack" }, { "code": null, "e": 2557, "s": 2524, "text": "What is virtual function in C++?" }, { "code": null, "e": 2590, "s": 2557, "text": "What is virtual function in C++?" }, { "code": null, "e": 2814, "s": 2590, "text": "Virtual functions in C++ use to create a list of base class pointers and call methods of any of the derived classes without even knowing the kind of derived class object. Virtual functions are resolved late, at the runtime." }, { "code": null, "e": 3092, "s": 2814, "text": "If A virtual function in a base class declared as once a member function, it becomes virtual in every class derived from that base class. So, use of the keyword virtual is not necessary in the derived class while declaring redefined versions of the virtual base class function." }, { "code": null, "e": 3103, "s": 3092, "text": " Live Demo" }, { "code": null, "e": 3454, "s": 3103, "text": "#include<iostream>\nusing namespace std;\nclass B {\n public:\n virtual void s() {\n cout<<\" In Base \\n\";\n }\n};\nclass D: public B {\n public:\n void s() {\n cout<<\"In Derived \\n\";\n }\n};\nint main(void) {\n D d; // An object of class D\n B *b= &d; // A pointer of type B* pointing to d\n b->s(); // prints\"D::s() called\"\n return 0;\n}" }, { "code": null, "e": 3465, "s": 3454, "text": "In Derived" }, { "code": null, "e": 3494, "s": 3465, "text": "What is this pointer in C++?" }, { "code": null, "e": 3748, "s": 3494, "text": "Every object in C++ has access to its own address through an important pointer called this pointer. The this pointer is an implicit parameter to all member functions. Therefore, inside a member function, this may be used to refer to the invoking object." }, { "code": null, "e": 3880, "s": 3748, "text": "Friend functions do not have a this pointer, because friends are not members of a class. Only member functions have a this pointer." }, { "code": null, "e": 3957, "s": 3880, "text": "Let us try the following example to understand the concept of this pointer −" }, { "code": null, "e": 3968, "s": 3957, "text": " Live Demo" }, { "code": null, "e": 4767, "s": 3968, "text": "#include <iostream>\nusing namespace std;\nclass Box {\n public:\n // Constructor definition\n Box(double l = 2.0, double b = 2.0, double h = 2.0) {\n cout <<\"Constructor called.\" << endl;\n length = l;\n breadth = b;\n height = h;\n }\n double Volume() {\n return length * breadth * height;\n }\n int compare(Box box) {\n return this->Volume() > box.Volume();\n }\n private:\n double length; // Length of a box\n double breadth; // Breadth of a box\n double height; // Height of a box\n};\nint main(void) {\n Box Box1(3.3, 1.2, 1.5); // Declare box1\n Box Box2(8.5, 6.0, 2.0); // Declare box2\n if(Box1.compare(Box2)) {\n cout << \"Box2 is smaller than Box1\" <<endl;\n } else {\n cout << \"Box2 is equal to or larger than Box1\" <<endl;\n }\n return 0;\n}" }, { "code": null, "e": 4844, "s": 4767, "text": "Constructor called.\nConstructor called.\nBox2 is equal to or larger than Box1" } ]