title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
How to convert a list to string in C#?
Declare a list. List < string > l = new List < string > (); Now, add elements to the list. // elements l.Add("Accessories"); l.Add("Footwear"); l.Add("Watches"); Now convert it into a string. string str = string.Join(" ", l.ToArray()); Let us see the final code to convert a list to string in C# − using System; using System.Collections.Generic; class Demo { static void Main() { List < string > l = new List < string > (); // elements l.Add("Accessories"); l.Add("Footwear"); l.Add("Watches"); string str = string.Join(" ", l.ToArray()); Console.WriteLine(str); } }
[ { "code": null, "e": 1078, "s": 1062, "text": "Declare a list." }, { "code": null, "e": 1122, "s": 1078, "text": "List < string > l = new List < string > ();" }, { "code": null, "e": 1153, "s": 1122, "text": "Now, add elements to the list." }, { "code": null, "e": 1224, "s": 1153, "text": "// elements\nl.Add(\"Accessories\");\nl.Add(\"Footwear\");\nl.Add(\"Watches\");" }, { "code": null, "e": 1254, "s": 1224, "text": "Now convert it into a string." }, { "code": null, "e": 1298, "s": 1254, "text": "string str = string.Join(\" \", l.ToArray());" }, { "code": null, "e": 1360, "s": 1298, "text": "Let us see the final code to convert a list to string in C# −" }, { "code": null, "e": 1677, "s": 1360, "text": "using System;\nusing System.Collections.Generic;\nclass Demo {\n static void Main() {\n List < string > l = new List < string > ();\n // elements\n l.Add(\"Accessories\");\n l.Add(\"Footwear\");\n l.Add(\"Watches\");\n string str = string.Join(\" \", l.ToArray());\n Console.WriteLine(str);\n }\n}" } ]
Python-Quizzes | Python List Quiz | Question 5 - GeeksforGeeks
17 Sep, 2020 Question: 5 Find the output of the following program: check1 = ['Learn', 'Quiz', 'Practice', 'Contribute'] check2 = check1 check3 = check1[:] check2[0] = 'Code'check3[1] = 'Mcq' count = 0for c in (check1, check2, check3): if c[0] == 'Code': count += 1 if c[1] == 'Mcq': count += 10 print (count) (A) 4(B) 5(C) 11(D) 12Answer: (D)Explanation: When assigning check1 to check2, we create a second reference to the same list. Changes to check2 affect check1. When assigning the slice of all elements in check1 to check3, we are creating a full copy of check1 which can be modified independently (i.e, any change in check3 will not affect check1).So, while checking check1 ‘Code’ gets matched and the count increases to 1, but Mcq doest gets matched since its available only in check3.Now checking check2 here also ‘Code’ gets matched resulting in a count value to 2.Finally while checking check3 which is separate from both check1 and check2 here only Mcq gets matched and the count becomes 12.Quiz of this Question Python-Quizzes Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python-Quizzes | Python Dictionary Quiz | Question 25 Python-Quizzes | Python Dictionary Quiz | Question 23 Python | Miscellaneous | Question 1 Python-Quizzes | Miscellaneous | Question 9 Python-Quizzes | Miscellaneous | Question 7 Python-Quizzes | Miscellaneous | Question 10 Output of Python Program - Dictionary (set 25) Python | Miscellaneous | Question 5 Python-Quizzes | Python Tuples Quiz | Question 10 Python | Miscellaneous | Question 4
[ { "code": null, "e": 23779, "s": 23751, "text": "\n17 Sep, 2020" }, { "code": null, "e": 23833, "s": 23779, "text": "Question: 5 Find the output of the following program:" }, { "code": "check1 = ['Learn', 'Quiz', 'Practice', 'Contribute'] check2 = check1 check3 = check1[:] check2[0] = 'Code'check3[1] = 'Mcq' count = 0for c in (check1, check2, check3): if c[0] == 'Code': count += 1 if c[1] == 'Mcq': count += 10 print (count) ", "e": 24103, "s": 23833, "text": null }, { "code": null, "e": 24819, "s": 24103, "text": "(A) 4(B) 5(C) 11(D) 12Answer: (D)Explanation: When assigning check1 to check2, we create a second reference to the same list. Changes to check2 affect check1. When assigning the slice of all elements in check1 to check3, we are creating a full copy of check1 which can be modified independently (i.e, any change in check3 will not affect check1).So, while checking check1 ‘Code’ gets matched and the count increases to 1, but Mcq doest gets matched since its available only in check3.Now checking check2 here also ‘Code’ gets matched resulting in a count value to 2.Finally while checking check3 which is separate from both check1 and check2 here only Mcq gets matched and the count becomes 12.Quiz of this Question" }, { "code": null, "e": 24834, "s": 24819, "text": "Python-Quizzes" }, { "code": null, "e": 24932, "s": 24834, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 24941, "s": 24932, "text": "Comments" }, { "code": null, "e": 24954, "s": 24941, "text": "Old Comments" }, { "code": null, "e": 25008, "s": 24954, "text": "Python-Quizzes | Python Dictionary Quiz | Question 25" }, { "code": null, "e": 25062, "s": 25008, "text": "Python-Quizzes | Python Dictionary Quiz | Question 23" }, { "code": null, "e": 25098, "s": 25062, "text": "Python | Miscellaneous | Question 1" }, { "code": null, "e": 25142, "s": 25098, "text": "Python-Quizzes | Miscellaneous | Question 9" }, { "code": null, "e": 25186, "s": 25142, "text": "Python-Quizzes | Miscellaneous | Question 7" }, { "code": null, "e": 25231, "s": 25186, "text": "Python-Quizzes | Miscellaneous | Question 10" }, { "code": null, "e": 25278, "s": 25231, "text": "Output of Python Program - Dictionary (set 25)" }, { "code": null, "e": 25314, "s": 25278, "text": "Python | Miscellaneous | Question 5" }, { "code": null, "e": 25364, "s": 25314, "text": "Python-Quizzes | Python Tuples Quiz | Question 10" } ]
Lucky Numbers | Practice | GeeksforGeeks
Lucky numbers are subset of integers. Rather than going into much theory, let us see the process of arriving at lucky numbers, Take the set of integers 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19,...... First, delete every second number, we get following reduced set. 1, 3, 5, 7, 9, 11, 13, 15, 17, 19,............ Now, delete every third number, we get 1, 3, 7, 9, 13, 15, 19,........ Continue this process indefinitely...... Any number that does NOT get deleted due to above process is called “lucky”. Example 1: Input: N = 5 Output: 0 Explanation: 5 is not a lucky number as it gets deleted in the second iteration. Example 2: Input: N = 19 Output: 1 Explanation: 19 is a lucky number Your Task: You don't need to read input or print anything. You only need to complete the function isLucky() that takes N as parameter and returns either False if the N is not lucky else True. Expected Time Complexity: O(sqrt(N)). Expected Auxiliary Space: O(sqrt(N)). Constraints: 1 <= N <= 105 0 sunilnishad100006 days ago *******C++ Code********* bool yesorno(int n, int r){ if(r<=n){ if(n%r==0){ return 0; }else { return yesorno(n-n/r,r+1); } }else { return 1; } } bool isLucky(int n) { yesorno(n,2);} +1 rahulrs1 week ago Java code................................ public static boolean isLucky(int n) { // Your code here boolean ans = check(n,2); return ans; } public static boolean check(int n, int counter){ if(counter>n) return true; if(n%counter==0) return false; return check(n-(n/counter), counter+1); } 0 akshatsaxenaanpas1 week ago bool checklucky(int n, int counter){ if(n%counter==0){ return false; } if(counter>n){ return true; } n = n - n/counter; counter = counter+1; return checklucky(n,counter); } bool isLucky(int n) { // code here bool t = checklucky(n,2); return t; } 0 crawler2 weeks ago Approach: We Check for a given number n, the position of its appearance in each step, example: in first step 7 appears at 7th position and i=2, but 7%2 ≠ 0, so recur to next stage modifying the position of 7 for the next step: Calculate position: position can be calculated by subtracting number of multiples of 2(i in previous state) less than n from n: i.e. n = n-(n/i), where n/i is number of numbers divisible by i. bool myFun(int n, int x){ if(n%x == 0) return false; if(x > n) return true; return myFun(n-(n/x), x+1); } bool isLucky(int n) { return myFun(n, 2); } 0 sushmithaguggella This comment was deleted. +3 zakarian17s3 weeks ago In the Question it is not made clear how this process should run, whether like deleting 2nd then 3rd then 4th then 5th ............. like this or deleting 2nd then 3rd then 2nd then 3rd .......... like this pls make this clear @gfg +1 nihal_singh1841 month ago why this code is not working for 74 bool isLucky(int n) { static int k=2; if(k>n){ return true; } else if(n%k==0){ return false; } return isLucky(n-(n/(k++))); // else{ // int nextpos=n-(n/k); // k++; // return isLucky(nextpos); 0 ankitparashxr1 month ago java public static boolean isLucky(int n) { ArrayList<Integer> num = new ArrayList<>(); for(int i=1;i<=n;i++) { if(i%2!=0) { num.add(i); } } //System.out.println(num); ArrayList<Integer> num1 =lucky(num,1,3); if(num1.contains(n)) { return true; } return false; } public static ArrayList<Integer> lucky(ArrayList<Integer> num,int a,int b) { if(num.size()<b) { return num; } ArrayList<Integer> num1 = new ArrayList<>(); for(int i=0;i<num.size();i++,a++) { if(a!=b) { num1.add(num.get(i)); } else { a=0; } } return lucky(num1,1,b+1); }} 0 jahidulhossainmekat1 month ago # Function attribute will act # as static variable def isLucky(n): if isLucky.counter > n: return 1 if n % isLucky.counter == 0: return 0 #calculate next position of input no. #Variable "next_position" is just for #readability of the program we can #remove it and update in "n" only next_position = n - (n/isLucky.counter) isLucky.counter = isLucky.counter + 1 return isLucky(next_position) # Driver Code isLucky.counter = 2 # Acts as static variable x = 5 if isLucky(x): print (x,"is a Lucky number") else: print (x,"is not a Lucky number") # } Driver Code Ends +2 mohitraj27411 month ago Note that the position matters and not the actual number. keep passing the new position with updated counter and check if its a lucky position in each pass. bool Lucky(int n,int counter){ if(counter>n) return true; if(n%counter == 0) return false; return Lucky(n - floor(n/counter), counter+1);} bool isLucky(int n) { // code here bool ans=Lucky(n,2); return ans;} We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 764, "s": 238, "text": "Lucky numbers are subset of integers. Rather than going into much theory, let us see the process of arriving at lucky numbers,\nTake the set of integers\n1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19,......\nFirst, delete every second number, we get following reduced set.\n1, 3, 5, 7, 9, 11, 13, 15, 17, 19,............\nNow, delete every third number, we get\n1, 3, 7, 9, 13, 15, 19,........\nContinue this process indefinitely......\nAny number that does NOT get deleted due to above process is called “lucky”." }, { "code": null, "e": 775, "s": 764, "text": "Example 1:" }, { "code": null, "e": 882, "s": 775, "text": "Input:\nN = 5\nOutput: 0\nExplanation: 5 is not a lucky number \nas it gets deleted in the second \niteration.\n" }, { "code": null, "e": 893, "s": 882, "text": "Example 2:" }, { "code": null, "e": 952, "s": 893, "text": "Input:\nN = 19\nOutput: 1\nExplanation: 19 is a lucky number\n" }, { "code": null, "e": 1144, "s": 952, "text": "Your Task:\nYou don't need to read input or print anything. You only need to complete the function isLucky() that takes N as parameter and returns either False if the N is not lucky else True." }, { "code": null, "e": 1220, "s": 1144, "text": "Expected Time Complexity: O(sqrt(N)).\nExpected Auxiliary Space: O(sqrt(N))." }, { "code": null, "e": 1247, "s": 1220, "text": "Constraints:\n1 <= N <= 105" }, { "code": null, "e": 1249, "s": 1247, "text": "0" }, { "code": null, "e": 1276, "s": 1249, "text": "sunilnishad100006 days ago" }, { "code": null, "e": 1301, "s": 1276, "text": "*******C++ Code*********" }, { "code": null, "e": 1468, "s": 1301, "text": "bool yesorno(int n, int r){ if(r<=n){ if(n%r==0){ return 0; }else { return yesorno(n-n/r,r+1); } }else { return 1; } }" }, { "code": null, "e": 1507, "s": 1468, "text": "bool isLucky(int n) { yesorno(n,2);}" }, { "code": null, "e": 1510, "s": 1507, "text": "+1" }, { "code": null, "e": 1528, "s": 1510, "text": "rahulrs1 week ago" }, { "code": null, "e": 1917, "s": 1528, "text": "Java code................................\n\npublic static boolean isLucky(int n)\n {\n // Your code here\n boolean ans = check(n,2);\n return ans;\n \n }\n public static boolean check(int n, int counter){\n \n if(counter>n) return true;\n if(n%counter==0) return false;\n \n return check(n-(n/counter), counter+1);\n \n }" }, { "code": null, "e": 1919, "s": 1917, "text": "0" }, { "code": null, "e": 1947, "s": 1919, "text": "akshatsaxenaanpas1 week ago" }, { "code": null, "e": 2266, "s": 1947, "text": "bool checklucky(int n, int counter){\n if(n%counter==0){\n return false;\n }\n if(counter>n){\n return true;\n }\n \n n = n - n/counter;\n counter = counter+1;\n \n return checklucky(n,counter);\n}\nbool isLucky(int n) {\n // code here\n bool t = checklucky(n,2);\n \n return t;\n}\n" }, { "code": null, "e": 2268, "s": 2266, "text": "0" }, { "code": null, "e": 2287, "s": 2268, "text": "crawler2 weeks ago" }, { "code": null, "e": 2373, "s": 2287, "text": "Approach: We Check for a given number n, the position of its appearance in each step," }, { "code": null, "e": 2515, "s": 2373, "text": "example: in first step 7 appears at 7th position and i=2, but 7%2 ≠ 0, so recur to next stage modifying the position of 7 for the next step:" }, { "code": null, "e": 2708, "s": 2515, "text": "Calculate position: position can be calculated by subtracting number of multiples of 2(i in previous state) less than n from n: i.e. n = n-(n/i), where n/i is number of numbers divisible by i." }, { "code": null, "e": 2890, "s": 2708, "text": "bool myFun(int n, int x){\n if(n%x == 0)\n return false;\n if(x > n)\n return true;\n return myFun(n-(n/x), x+1);\n}\nbool isLucky(int n) {\n return myFun(n, 2);\n}" }, { "code": null, "e": 2892, "s": 2890, "text": "0" }, { "code": null, "e": 2910, "s": 2892, "text": "sushmithaguggella" }, { "code": null, "e": 2936, "s": 2910, "text": "This comment was deleted." }, { "code": null, "e": 2939, "s": 2936, "text": "+3" }, { "code": null, "e": 2962, "s": 2939, "text": "zakarian17s3 weeks ago" }, { "code": null, "e": 3194, "s": 2962, "text": "In the Question it is not made clear how this process should run, whether like deleting 2nd then 3rd then 4th then 5th ............. like this or deleting 2nd then 3rd then 2nd then 3rd .......... like this pls make this clear @gfg" }, { "code": null, "e": 3197, "s": 3194, "text": "+1" }, { "code": null, "e": 3223, "s": 3197, "text": "nihal_singh1841 month ago" }, { "code": null, "e": 3259, "s": 3223, "text": "why this code is not working for 74" }, { "code": null, "e": 3499, "s": 3259, "text": "bool isLucky(int n) { static int k=2; if(k>n){ return true; } else if(n%k==0){ return false; } return isLucky(n-(n/(k++))); // else{ // int nextpos=n-(n/k); // k++; // return isLucky(nextpos); " }, { "code": null, "e": 3501, "s": 3499, "text": "0" }, { "code": null, "e": 3526, "s": 3501, "text": "ankitparashxr1 month ago" }, { "code": null, "e": 3531, "s": 3526, "text": "java" }, { "code": null, "e": 4324, "s": 3531, "text": " public static boolean isLucky(int n) { ArrayList<Integer> num = new ArrayList<>(); for(int i=1;i<=n;i++) { if(i%2!=0) { num.add(i); } } //System.out.println(num); ArrayList<Integer> num1 =lucky(num,1,3); if(num1.contains(n)) { return true; } return false; } public static ArrayList<Integer> lucky(ArrayList<Integer> num,int a,int b) { if(num.size()<b) { return num; } ArrayList<Integer> num1 = new ArrayList<>(); for(int i=0;i<num.size();i++,a++) { if(a!=b) { num1.add(num.get(i)); } else { a=0; } } return lucky(num1,1,b+1); }}" }, { "code": null, "e": 4326, "s": 4324, "text": "0" }, { "code": null, "e": 4357, "s": 4326, "text": "jahidulhossainmekat1 month ago" }, { "code": null, "e": 5010, "s": 4357, "text": " # Function attribute will act\n # as static variable \ndef isLucky(n):\n\n if isLucky.counter > n:\n return 1\n if n % isLucky.counter == 0:\n return 0\n #calculate next position of input no.\n #Variable \"next_position\" is just for\n #readability of the program we can\n #remove it and update in \"n\" only\n next_position = n - (n/isLucky.counter)\n \n isLucky.counter = isLucky.counter + 1\n \n return isLucky(next_position) \n# Driver Code\n \nisLucky.counter = 2 # Acts as static variable\nx = 5\nif isLucky(x):\n print (x,\"is a Lucky number\")\nelse:\n print (x,\"is not a Lucky number\")\n# } Driver Code Ends" }, { "code": null, "e": 5013, "s": 5010, "text": "+2" }, { "code": null, "e": 5037, "s": 5013, "text": "mohitraj27411 month ago" }, { "code": null, "e": 5095, "s": 5037, "text": "Note that the position matters and not the actual number." }, { "code": null, "e": 5194, "s": 5095, "text": "keep passing the new position with updated counter and check if its a lucky position in each pass." }, { "code": null, "e": 5348, "s": 5196, "text": "bool Lucky(int n,int counter){ if(counter>n) return true; if(n%counter == 0) return false; return Lucky(n - floor(n/counter), counter+1);}" }, { "code": null, "e": 5423, "s": 5348, "text": "bool isLucky(int n) { // code here bool ans=Lucky(n,2); return ans;}" }, { "code": null, "e": 5569, "s": 5423, "text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?" }, { "code": null, "e": 5605, "s": 5569, "text": " Login to access your submissions. " }, { "code": null, "e": 5615, "s": 5605, "text": "\nProblem\n" }, { "code": null, "e": 5625, "s": 5615, "text": "\nContest\n" }, { "code": null, "e": 5688, "s": 5625, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 5836, "s": 5688, "text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 6044, "s": 5836, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints." }, { "code": null, "e": 6150, "s": 6044, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
C++ Vector Library - clear() Function
The C++ function std::vector::clear() destroys the vector by removing all elements from the vector and sets size of vector to zero. Following is the declaration for std::vector::clear() function form std::vector header. void clear(); void clear() noexcept; None None. This member function never throws excpetion. Linear i.e. O(n) The following example shows the usage of std::vector::clear() function. #include <iostream> #include <vector> using namespace std; int main(void) { auto ilist = {1, 2, 3, 4, 5}; vector<int> v(ilist); cout << "Initial size of vector = " << v.size() << endl; /* destroy vector */ v.clear(); cout << "Size of vector after clear = " << v.size() << endl; return 0; } Let us compile and run the above program, this will produce the following result − Initial size of vector = 5 Size of vector after clear = 0 Print Add Notes Bookmark this page
[ { "code": null, "e": 2735, "s": 2603, "text": "The C++ function std::vector::clear() destroys the vector by removing all elements from the vector and sets size of vector to zero." }, { "code": null, "e": 2823, "s": 2735, "text": "Following is the declaration for std::vector::clear() function form std::vector header." }, { "code": null, "e": 2838, "s": 2823, "text": "void clear();\n" }, { "code": null, "e": 2862, "s": 2838, "text": "void clear() noexcept;\n" }, { "code": null, "e": 2867, "s": 2862, "text": "None" }, { "code": null, "e": 2873, "s": 2867, "text": "None." }, { "code": null, "e": 2918, "s": 2873, "text": "This member function never throws excpetion." }, { "code": null, "e": 2935, "s": 2918, "text": "Linear i.e. O(n)" }, { "code": null, "e": 3007, "s": 2935, "text": "The following example shows the usage of std::vector::clear() function." }, { "code": null, "e": 3326, "s": 3007, "text": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nint main(void) {\n auto ilist = {1, 2, 3, 4, 5};\n vector<int> v(ilist);\n\n cout << \"Initial size of vector = \" << v.size() << endl;\n /* destroy vector */\n v.clear();\n cout << \"Size of vector after clear = \" << v.size() << endl;\n\n return 0;\n}" }, { "code": null, "e": 3409, "s": 3326, "text": "Let us compile and run the above program, this will produce the following result −" }, { "code": null, "e": 3472, "s": 3409, "text": "Initial size of vector = 5\nSize of vector after clear = 0\n" }, { "code": null, "e": 3479, "s": 3472, "text": " Print" }, { "code": null, "e": 3490, "s": 3479, "text": " Add Notes" } ]
Uber Driver Schedule Optimization | by Ivan Zhou | Towards Data Science
This model implementation and graphs can be found in my Github Repository. Also, great thanks to my team members, Deep Prasad, Emily Xu, and Sharlene Peng, for contributing to this project. One of Uber’s key value propositions is offering scheduling flexibility to their driver-partners. According to a report by the Beneson Strategy Group, 73% of drivers prefer having a job that lets them choose their schedule. Drivers can use this flexibility to maximize their expected revenue during their available times. To this end, Uber provides heatmaps of customer demand that allow drivers to target high-demand regions that provide higher trip probability and therefore higher expected revenues. However, there is no readily available way to determine whether trips starting at a particular location are worth the time it would take to service the trip. For example, a trip that takes longer due to traffic but has high demand may result in fewer total trips and be less valuable. On the other hand trips with less demand but are consistently much faster may be more valuable. Therefore it is in the driver’s best interest to balance the demand of a location and the amount of time trips from that location will take. To address this gap, we sought to create a scheduling optimization model, using Mixed Integer Programming (MIP). Two datasets were used to determine demand and trip duration. Because Uber demand data was not available, DC Taxicab pickup data was used as a proxy for demand. Duration was determined from an Uber Movement dataset. The dataset was sourced from Open Data DC. It describes individual taxicab trips from a specific location expressed in coordinates. From January to March, the dataset contains a total of 5,546,786 pickups at 10,843 different locations. In order to discretize the data and scope down the size of our problem, we needed to sort the pickups into high demand regions. First, the number of pickups at each location was counted. Then, to define the regions we selected the first 100 locations with the most pickup counts (see Figure 1–1) as they cover 30% of the total number of pickups. MATLAB’s kmeans function was used to cluster the counts into 5 region centroids (see Figure 1–2). The radius of each region was calculated based on the minimum Euclidean distance to the other four regions. Since we only compare the intra-region trips, pickup counts were then filtered to only include trips that originated from one of the five regions and whose destinations are within the same region as the origin. Counts were then averaged and aggregated across the time of day, day of week, and region. A sample of the cleaned, discretized dataset can be found below. The dataset was sourced from Uber’s “Uber Movement” initiative (see Appendix A). It describes the mean, minimum, and maximum trip durations for each origin-destination region pair. Uber Movement’s regions are smaller than the five high-demand regions determined earlier. In order to make the two datasets comparable, origin-destination pairs were filtered to only include regions that fell completely within one of the five regions and whose destinations are within the same region as the origin (see Figure 2). The average mean, minimum, and maximum of trip durations for each of the five regions was then calculated. Similar to the demand data, these values were aggregated over the time of day, day of week, and region. A sample of the dataset can be found below. Using the demand and trip duration data, a Mixed Integer Programming (MIP) model was developed to find the optimal driving schedule for drivers. MIP’s are linear optimization programs where some variables are allowed to be integers while others are not once a solution has been obtained. The most famous MIP is one that is analogous to ours: the knapsack problem. In our case, the backpack’s capacity represents the “total time” the Uber driver has allocated for their schedule. We would like to maximize the expected revenue. The following MIP was developed: The objective function of the model maximizes the revenue made for the driver over the course of their work schedule for one week. This is accomplished by maximizing the sum of the expected revenues at each recommended region j and time block i. The expected revenue term R_{ij} is calculated according to: Where we assume that the probability of new trips is uniformly distributed between 0.5 and 1 as the 5 regions were chosen based on high demand. Based on this assumption, probability can be assigned using demand (see Appendix B). Number of trips at a given time was found for the worst case scenario by using the minimum number of trips possible in each set of region j and time block i. Because the time blocks were subdivided into 2 hour blocks, the minimum number of trips can be approximated as: The decision variable in the model is X_{ij}, where i and j indicate the corresponding time and region respectively. X_{ij} is a boolean variable where 1 indicates the region j at time i is selected. The following parameters are used in the model: R_{ij} — Expected revenue driver can make at region j during time i A_{i} — Boolean variable to indicate whether driver is available during block i B_{j} — Boolean variable to indicate whether drive is able to work in region j T_{max} — Maximum number of hours driver can work in a week Uber is attractive due to its scheduling flexibility. An Uber driver can work whenever and wherever they want. To accurately model flexibility, the MIP is subject to these constraints: Constraints 1 and 2 ensure that the optimal schedule generated does not include regions the driver is not willing to work in or times they are not available. In constraint 1, A_{i}=1indicates that the driver is available to drive at time block i, and 0 otherwise. In constraint 2,B_{j}=1indicate the driver is willing to drive in region j, and 0 otherwise. The constant Tmax ensures that the schedule’s total number of hours will not exceed the maximum number of hours the driver is willing to work per week. Constraint 4 ensures that only one region is recommended for each time block. Constraint 5 ensures that decision variable X_{ij} and parameters A_{i} and B_{j} are binary. In order to actually implement the model, a central program was written in MATLAB that prepares the MIP and solves it using the intlinprog function. The central program requires 6 parameters, each corresponding to the decision variables listed in above. The problem had to be formulated for intlinprog, which solves problems of the form: The code can be found in Launch_IP.m and Solve_IP.m First, the two datasets extracted from Taxi Pickup Data and Uber Movement Data were joined on Weekday, Hour, and Region. Each row of the dataset represents the traffic conditions in a given region during a given hour on a given weekday. Extracting the required subset data was done using the readtable() function. Using the data, the constraints were formulated for intlinprog by constructing the A and b matrices in 3 steps. The first step creates a vector A1, b1 of dimensions 1 x n that represent the number of hours the Uber driver is willing to work. The second step constructs a matrix A2, b2 that ensures no two regions are recommended at the same time. Finally, A1 is appended to A2, and b1 is appended b2 to make the final matrices A and b. The second constraint requires the recommended regions be within the regions the driver is willing to travel to. If the driver is unwilling to drive in a particular region, then all the duration, traffic, and constraint parameters of the region will be removed before creating the constraint matrix. Therefore, there was no need to incorporate region preference into the constraint matrix. The model also assumes that time to get from one region to the next is negligible. A driver may be expected to be in region B during time block i, but in region C, 12 miles away for time block i+1. The time cost of travelling between regions can be implemented in future iterations. To represent the objective function, two vectors were established and multiplied together. The first vector represents the probability of getting a customer at the current region during time i, and the second vector represents the estimated number of trips in the time block i. The final objective function is found using the following line of code: f = transpose(P_new_customer.*Min_Trips).*avg_revenue_trip; Where avg_revenue_trip is approximated to be $12 based on median earnings per hour and trips per hour information from a 2014 Uber study. Now, with the appropriate formulation, the optimal solution can be found by intlinprog() with the constructed A,b, and f vectors. Upper and lower bounds were set to 1 and 0 respectively. The model is able to generate a weekly schedule given one driver’s specified parameters. For example: To evaluate model performance, 2 metrics were considered: Model Performance and Optimality. Specifically, the team wanted to know how revenue and computation times were affected when the number of maximum working hours (Tmax), time blocks, and regions increased. To ensure stable results, the model was run 500 times for each instance and the average objective values and computation times were recorded. Time blocks and regions were chosen randomly for each instance to avoid bias. It was found that the computation time increased as number of time blocks increased but decreased as maximum number of hours increased (see Appendix C). The optimal revenue varied between $450 — $545 / week as the number of available time blocks varied between 1–42 (see Figure 3). An increase in the number of available time blocks represents an increase in driver schedule flexibility towards our defined time blocks. This positive relationship indicates that the more flexible the driver’s schedule is, the more revenue they can expect to earn. An increase in the number of available regions only caused an increase in revenue when more than one region was included, indicating that more available regions does not significantly impact revenue (see Appendix C). There are two potential reasons for an increasing revenue with increasing number of available time blocks. First, is “accidental revenue”. This means that the increase in revenue is a result of happening to drive during more high-revenue generating hours on average because of the increased diversity in service times. Alternatively, one could simply make more money because they are driving more often. In order to determine the causation, the team plotted the revenue as maximum working hours per week increased (see Figure 4). Increasing the maximum working hours appeared to significantly increase the driver’s revenue, indicating that the time blocks that one is driving during does not affect revenue nearly as much as how often they are driving. Additionally, the model’s validity was verified by comparing the expected revenue against real-life revenue. According to crowd-sourced information, an Uber driver working 30 hours a week earns approximately $772 per week. From our model, the optimal worst case expected revenue is approximately $1,900. This is significantly higher and indicates our model is a marked improvement on current driver driving patterns. The results from the model make intuitive sense, and show potential for broader applications. It is possible to generalize the model to apply to any city, not just D.C. The team would also like to incorporate a “competition” component to the model. If several drivers are recommended the same region at the same time, competition will increase and the probability of getting a trip goes down for each driver. This clearly decreases the expected revenue according to the formula the team established and would render the optimal solution falsely “optimal”. A more advanced model will be able to balance the number of recommendations it has given for a given region and time and “re-route” drivers to balance the number of drivers with recommendations for a region. Based on the MIP model results and interpretations, the team is able to claim that it brings meaningful value to an Uber driver in terms of expected revenue. There is a positive relationship between the number of time blocks prescribed by the model and the expected revenue for the driver. In order to increase their revenue, a driver should be available for as many time blocks as possible. Drivers now have a leg up on other drivers by making data-driven decisions as opposed to using heuristics for picking “optimal” locations to serve clients. With the feasible and convenient schedules that the model prescribes, drivers can now envision their job as a lucrative business with a competitive advantage. [1] Uber Newsroom, “BSG Report: The Driver Roadmap”.[Online]. Available: https://newsroom.uber.com/wp-content/uploads/2015/01/BSG_Uber_Report.pdf. [Accessed: 16- Apr- 2017]. [2] Opendata.dc.gov, “Taxicab Trips”. [Online]. Available: http://opendata.dc.gov/datasets?q=taxi. [Accessed: 16- Apr- 2017]. [3] Movement.uber.com, “Uber Movement: Let’s find smarter ways forward”, 2017. [Online]. Available: https://movement.uber.com/cities. [Accessed: 16- Apr- 2017]. [4] J. Hall and A. Krueger, “An Analysis of the Labor Market for Uber’s Driver-Partners in the United States”, 2017. [Online]. Available: https://timedotcom.files.wordpress.com/2015/01/uber_driver-partners_hall_kreuger_2015.pdf. [Accessed: 16- Apr- 2017]. [5] I Drive With Uber, “Home — I Drive With Uber”, 2017. [Online]. Available: http://www.idrivewithuber.com. [Accessed: 16- Apr- 2017]. Why matlab? It is more of a personal preference. Matlab is very professional (and fast) in solving optimization problems, like the MIP model in this case, and I am familiar with its syntax. Python does have several libraries for MIP, but I am not familiar with them. The data processing and analysis in the project were majorly implemented in Python. Technically it is do-able to close the entire loop, from processing to optimization, with Python. What will happen if all the drivers follow the “optimal solution” As more drivers adopt the “tool”, the competitive advantage will diminish towards zero. In an edge case, if we reach the equilibrium where the state of congestion is the same across all the areas with the same level of demand, the tool will become useless. However, that could never happen in reality, for now at least, so there are always some space for improvement. This is a just conceptual level. I would love to see we can achieve such intelligent and optimal allocation of resources in reality. The following is the Uber Movement interface the team had to use to access Uber trip duration data. Because the interface restricted the team to having to manually select time blocks and locations, the team had to scope down the locations chosen. The following is the formula implemented in MATLAB to find the probability of new trips: P_{min} and P_{max} are the lower and bounds of the uniform distribution used to find probability of new trips (in our case, 0.5 and 1) D_{min} and D_{max} are the maximum and minimum pickup counts for that region and time block. The following are supplementary graphs describing the analysis of computation time and objective function given changing parameters.
[ { "code": null, "e": 247, "s": 172, "text": "This model implementation and graphs can be found in my Github Repository." }, { "code": null, "e": 362, "s": 247, "text": "Also, great thanks to my team members, Deep Prasad, Emily Xu, and Sharlene Peng, for contributing to this project." }, { "code": null, "e": 865, "s": 362, "text": "One of Uber’s key value propositions is offering scheduling flexibility to their driver-partners. According to a report by the Beneson Strategy Group, 73% of drivers prefer having a job that lets them choose their schedule. Drivers can use this flexibility to maximize their expected revenue during their available times. To this end, Uber provides heatmaps of customer demand that allow drivers to target high-demand regions that provide higher trip probability and therefore higher expected revenues." }, { "code": null, "e": 1387, "s": 865, "text": "However, there is no readily available way to determine whether trips starting at a particular location are worth the time it would take to service the trip. For example, a trip that takes longer due to traffic but has high demand may result in fewer total trips and be less valuable. On the other hand trips with less demand but are consistently much faster may be more valuable. Therefore it is in the driver’s best interest to balance the demand of a location and the amount of time trips from that location will take." }, { "code": null, "e": 1500, "s": 1387, "text": "To address this gap, we sought to create a scheduling optimization model, using Mixed Integer Programming (MIP)." }, { "code": null, "e": 1716, "s": 1500, "text": "Two datasets were used to determine demand and trip duration. Because Uber demand data was not available, DC Taxicab pickup data was used as a proxy for demand. Duration was determined from an Uber Movement dataset." }, { "code": null, "e": 1952, "s": 1716, "text": "The dataset was sourced from Open Data DC. It describes individual taxicab trips from a specific location expressed in coordinates. From January to March, the dataset contains a total of 5,546,786 pickups at 10,843 different locations." }, { "code": null, "e": 2504, "s": 1952, "text": "In order to discretize the data and scope down the size of our problem, we needed to sort the pickups into high demand regions. First, the number of pickups at each location was counted. Then, to define the regions we selected the first 100 locations with the most pickup counts (see Figure 1–1) as they cover 30% of the total number of pickups. MATLAB’s kmeans function was used to cluster the counts into 5 region centroids (see Figure 1–2). The radius of each region was calculated based on the minimum Euclidean distance to the other four regions." }, { "code": null, "e": 2870, "s": 2504, "text": "Since we only compare the intra-region trips, pickup counts were then filtered to only include trips that originated from one of the five regions and whose destinations are within the same region as the origin. Counts were then averaged and aggregated across the time of day, day of week, and region. A sample of the cleaned, discretized dataset can be found below." }, { "code": null, "e": 3637, "s": 2870, "text": "The dataset was sourced from Uber’s “Uber Movement” initiative (see Appendix A). It describes the mean, minimum, and maximum trip durations for each origin-destination region pair. Uber Movement’s regions are smaller than the five high-demand regions determined earlier. In order to make the two datasets comparable, origin-destination pairs were filtered to only include regions that fell completely within one of the five regions and whose destinations are within the same region as the origin (see Figure 2). The average mean, minimum, and maximum of trip durations for each of the five regions was then calculated. Similar to the demand data, these values were aggregated over the time of day, day of week, and region. A sample of the dataset can be found below." }, { "code": null, "e": 3925, "s": 3637, "text": "Using the demand and trip duration data, a Mixed Integer Programming (MIP) model was developed to find the optimal driving schedule for drivers. MIP’s are linear optimization programs where some variables are allowed to be integers while others are not once a solution has been obtained." }, { "code": null, "e": 4197, "s": 3925, "text": "The most famous MIP is one that is analogous to ours: the knapsack problem. In our case, the backpack’s capacity represents the “total time” the Uber driver has allocated for their schedule. We would like to maximize the expected revenue. The following MIP was developed:" }, { "code": null, "e": 4504, "s": 4197, "text": "The objective function of the model maximizes the revenue made for the driver over the course of their work schedule for one week. This is accomplished by maximizing the sum of the expected revenues at each recommended region j and time block i. The expected revenue term R_{ij} is calculated according to:" }, { "code": null, "e": 4733, "s": 4504, "text": "Where we assume that the probability of new trips is uniformly distributed between 0.5 and 1 as the 5 regions were chosen based on high demand. Based on this assumption, probability can be assigned using demand (see Appendix B)." }, { "code": null, "e": 5003, "s": 4733, "text": "Number of trips at a given time was found for the worst case scenario by using the minimum number of trips possible in each set of region j and time block i. Because the time blocks were subdivided into 2 hour blocks, the minimum number of trips can be approximated as:" }, { "code": null, "e": 5251, "s": 5003, "text": "The decision variable in the model is X_{ij}, where i and j indicate the corresponding time and region respectively. X_{ij} is a boolean variable where 1 indicates the region j at time i is selected. The following parameters are used in the model:" }, { "code": null, "e": 5319, "s": 5251, "text": "R_{ij} — Expected revenue driver can make at region j during time i" }, { "code": null, "e": 5399, "s": 5319, "text": "A_{i} — Boolean variable to indicate whether driver is available during block i" }, { "code": null, "e": 5478, "s": 5399, "text": "B_{j} — Boolean variable to indicate whether drive is able to work in region j" }, { "code": null, "e": 5538, "s": 5478, "text": "T_{max} — Maximum number of hours driver can work in a week" }, { "code": null, "e": 5723, "s": 5538, "text": "Uber is attractive due to its scheduling flexibility. An Uber driver can work whenever and wherever they want. To accurately model flexibility, the MIP is subject to these constraints:" }, { "code": null, "e": 5881, "s": 5723, "text": "Constraints 1 and 2 ensure that the optimal schedule generated does not include regions the driver is not willing to work in or times they are not available." }, { "code": null, "e": 5987, "s": 5881, "text": "In constraint 1, A_{i}=1indicates that the driver is available to drive at time block i, and 0 otherwise." }, { "code": null, "e": 6080, "s": 5987, "text": "In constraint 2,B_{j}=1indicate the driver is willing to drive in region j, and 0 otherwise." }, { "code": null, "e": 6232, "s": 6080, "text": "The constant Tmax ensures that the schedule’s total number of hours will not exceed the maximum number of hours the driver is willing to work per week." }, { "code": null, "e": 6310, "s": 6232, "text": "Constraint 4 ensures that only one region is recommended for each time block." }, { "code": null, "e": 6404, "s": 6310, "text": "Constraint 5 ensures that decision variable X_{ij} and parameters A_{i} and B_{j} are binary." }, { "code": null, "e": 6742, "s": 6404, "text": "In order to actually implement the model, a central program was written in MATLAB that prepares the MIP and solves it using the intlinprog function. The central program requires 6 parameters, each corresponding to the decision variables listed in above. The problem had to be formulated for intlinprog, which solves problems of the form:" }, { "code": null, "e": 6794, "s": 6742, "text": "The code can be found in Launch_IP.m and Solve_IP.m" }, { "code": null, "e": 7108, "s": 6794, "text": "First, the two datasets extracted from Taxi Pickup Data and Uber Movement Data were joined on Weekday, Hour, and Region. Each row of the dataset represents the traffic conditions in a given region during a given hour on a given weekday. Extracting the required subset data was done using the readtable() function." }, { "code": null, "e": 7544, "s": 7108, "text": "Using the data, the constraints were formulated for intlinprog by constructing the A and b matrices in 3 steps. The first step creates a vector A1, b1 of dimensions 1 x n that represent the number of hours the Uber driver is willing to work. The second step constructs a matrix A2, b2 that ensures no two regions are recommended at the same time. Finally, A1 is appended to A2, and b1 is appended b2 to make the final matrices A and b." }, { "code": null, "e": 8217, "s": 7544, "text": "The second constraint requires the recommended regions be within the regions the driver is willing to travel to. If the driver is unwilling to drive in a particular region, then all the duration, traffic, and constraint parameters of the region will be removed before creating the constraint matrix. Therefore, there was no need to incorporate region preference into the constraint matrix. The model also assumes that time to get from one region to the next is negligible. A driver may be expected to be in region B during time block i, but in region C, 12 miles away for time block i+1. The time cost of travelling between regions can be implemented in future iterations." }, { "code": null, "e": 8567, "s": 8217, "text": "To represent the objective function, two vectors were established and multiplied together. The first vector represents the probability of getting a customer at the current region during time i, and the second vector represents the estimated number of trips in the time block i. The final objective function is found using the following line of code:" }, { "code": null, "e": 8627, "s": 8567, "text": "f = transpose(P_new_customer.*Min_Trips).*avg_revenue_trip;" }, { "code": null, "e": 8765, "s": 8627, "text": "Where avg_revenue_trip is approximated to be $12 based on median earnings per hour and trips per hour information from a 2014 Uber study." }, { "code": null, "e": 8952, "s": 8765, "text": "Now, with the appropriate formulation, the optimal solution can be found by intlinprog() with the constructed A,b, and f vectors. Upper and lower bounds were set to 1 and 0 respectively." }, { "code": null, "e": 9054, "s": 8952, "text": "The model is able to generate a weekly schedule given one driver’s specified parameters. For example:" }, { "code": null, "e": 9317, "s": 9054, "text": "To evaluate model performance, 2 metrics were considered: Model Performance and Optimality. Specifically, the team wanted to know how revenue and computation times were affected when the number of maximum working hours (Tmax), time blocks, and regions increased." }, { "code": null, "e": 9690, "s": 9317, "text": "To ensure stable results, the model was run 500 times for each instance and the average objective values and computation times were recorded. Time blocks and regions were chosen randomly for each instance to avoid bias. It was found that the computation time increased as number of time blocks increased but decreased as maximum number of hours increased (see Appendix C)." }, { "code": null, "e": 10085, "s": 9690, "text": "The optimal revenue varied between $450 — $545 / week as the number of available time blocks varied between 1–42 (see Figure 3). An increase in the number of available time blocks represents an increase in driver schedule flexibility towards our defined time blocks. This positive relationship indicates that the more flexible the driver’s schedule is, the more revenue they can expect to earn." }, { "code": null, "e": 10302, "s": 10085, "text": "An increase in the number of available regions only caused an increase in revenue when more than one region was included, indicating that more available regions does not significantly impact revenue (see Appendix C)." }, { "code": null, "e": 10409, "s": 10302, "text": "There are two potential reasons for an increasing revenue with increasing number of available time blocks." }, { "code": null, "e": 10621, "s": 10409, "text": "First, is “accidental revenue”. This means that the increase in revenue is a result of happening to drive during more high-revenue generating hours on average because of the increased diversity in service times." }, { "code": null, "e": 11055, "s": 10621, "text": "Alternatively, one could simply make more money because they are driving more often. In order to determine the causation, the team plotted the revenue as maximum working hours per week increased (see Figure 4). Increasing the maximum working hours appeared to significantly increase the driver’s revenue, indicating that the time blocks that one is driving during does not affect revenue nearly as much as how often they are driving." }, { "code": null, "e": 11472, "s": 11055, "text": "Additionally, the model’s validity was verified by comparing the expected revenue against real-life revenue. According to crowd-sourced information, an Uber driver working 30 hours a week earns approximately $772 per week. From our model, the optimal worst case expected revenue is approximately $1,900. This is significantly higher and indicates our model is a marked improvement on current driver driving patterns." }, { "code": null, "e": 12236, "s": 11472, "text": "The results from the model make intuitive sense, and show potential for broader applications. It is possible to generalize the model to apply to any city, not just D.C. The team would also like to incorporate a “competition” component to the model. If several drivers are recommended the same region at the same time, competition will increase and the probability of getting a trip goes down for each driver. This clearly decreases the expected revenue according to the formula the team established and would render the optimal solution falsely “optimal”. A more advanced model will be able to balance the number of recommendations it has given for a given region and time and “re-route” drivers to balance the number of drivers with recommendations for a region." }, { "code": null, "e": 12943, "s": 12236, "text": "Based on the MIP model results and interpretations, the team is able to claim that it brings meaningful value to an Uber driver in terms of expected revenue. There is a positive relationship between the number of time blocks prescribed by the model and the expected revenue for the driver. In order to increase their revenue, a driver should be available for as many time blocks as possible. Drivers now have a leg up on other drivers by making data-driven decisions as opposed to using heuristics for picking “optimal” locations to serve clients. With the feasible and convenient schedules that the model prescribes, drivers can now envision their job as a lucrative business with a competitive advantage." }, { "code": null, "e": 13117, "s": 12943, "text": "[1] Uber Newsroom, “BSG Report: The Driver Roadmap”.[Online]. Available: https://newsroom.uber.com/wp-content/uploads/2015/01/BSG_Uber_Report.pdf. [Accessed: 16- Apr- 2017]." }, { "code": null, "e": 13243, "s": 13117, "text": "[2] Opendata.dc.gov, “Taxicab Trips”. [Online]. Available: http://opendata.dc.gov/datasets?q=taxi. [Accessed: 16- Apr- 2017]." }, { "code": null, "e": 13404, "s": 13243, "text": "[3] Movement.uber.com, “Uber Movement: Let’s find smarter ways forward”, 2017. [Online]. Available: https://movement.uber.com/cities. [Accessed: 16- Apr- 2017]." }, { "code": null, "e": 13660, "s": 13404, "text": "[4] J. Hall and A. Krueger, “An Analysis of the Labor Market for Uber’s Driver-Partners in the United States”, 2017. [Online]. Available: https://timedotcom.files.wordpress.com/2015/01/uber_driver-partners_hall_kreuger_2015.pdf. [Accessed: 16- Apr- 2017]." }, { "code": null, "e": 13796, "s": 13660, "text": "[5] I Drive With Uber, “Home — I Drive With Uber”, 2017. [Online]. Available: http://www.idrivewithuber.com. [Accessed: 16- Apr- 2017]." }, { "code": null, "e": 13808, "s": 13796, "text": "Why matlab?" }, { "code": null, "e": 14245, "s": 13808, "text": "It is more of a personal preference. Matlab is very professional (and fast) in solving optimization problems, like the MIP model in this case, and I am familiar with its syntax. Python does have several libraries for MIP, but I am not familiar with them. The data processing and analysis in the project were majorly implemented in Python. Technically it is do-able to close the entire loop, from processing to optimization, with Python." }, { "code": null, "e": 14311, "s": 14245, "text": "What will happen if all the drivers follow the “optimal solution”" }, { "code": null, "e": 14679, "s": 14311, "text": "As more drivers adopt the “tool”, the competitive advantage will diminish towards zero. In an edge case, if we reach the equilibrium where the state of congestion is the same across all the areas with the same level of demand, the tool will become useless. However, that could never happen in reality, for now at least, so there are always some space for improvement." }, { "code": null, "e": 14812, "s": 14679, "text": "This is a just conceptual level. I would love to see we can achieve such intelligent and optimal allocation of resources in reality." }, { "code": null, "e": 15059, "s": 14812, "text": "The following is the Uber Movement interface the team had to use to access Uber trip duration data. Because the interface restricted the team to having to manually select time blocks and locations, the team had to scope down the locations chosen." }, { "code": null, "e": 15148, "s": 15059, "text": "The following is the formula implemented in MATLAB to find the probability of new trips:" }, { "code": null, "e": 15284, "s": 15148, "text": "P_{min} and P_{max} are the lower and bounds of the uniform distribution used to find probability of new trips (in our case, 0.5 and 1)" }, { "code": null, "e": 15378, "s": 15284, "text": "D_{min} and D_{max} are the maximum and minimum pickup counts for that region and time block." } ]
Python String endswith() Method
Python string method endswith() returns True if the string ends with the specified suffix, otherwise return False optionally restricting the matching with the given indices start and end. str.endswith(suffix[, start[, end]]) suffix − This could be a string or could also be a tuple of suffixes to look for. suffix − This could be a string or could also be a tuple of suffixes to look for. start − The slice begins from here. start − The slice begins from here. end − The slice ends here. end − The slice ends here. TRUE if the string ends with the specified suffix, otherwise FALSE. #!/usr/bin/python str = "this is string example....wow!!!"; suffix = "wow!!!"; print str.endswith(suffix) print str.endswith(suffix,20) suffix = "is"; print str.endswith(suffix, 2, 4) print str.endswith(suffix, 2, 6) True True True False 187 Lectures 17.5 hours Malhar Lathkar 55 Lectures 8 hours Arnab Chakraborty 136 Lectures 11 hours In28Minutes Official 75 Lectures 13 hours Eduonix Learning Solutions 70 Lectures 8.5 hours Lets Kode It 63 Lectures 6 hours Abhilash Nelson Print Add Notes Bookmark this page
[ { "code": null, "e": 2432, "s": 2244, "text": "Python string method endswith() returns True if the string ends with the specified suffix, otherwise return False optionally restricting the matching with the given indices start and end." }, { "code": null, "e": 2470, "s": 2432, "text": "str.endswith(suffix[, start[, end]])\n" }, { "code": null, "e": 2552, "s": 2470, "text": "suffix − This could be a string or could also be a tuple of suffixes to look for." }, { "code": null, "e": 2634, "s": 2552, "text": "suffix − This could be a string or could also be a tuple of suffixes to look for." }, { "code": null, "e": 2670, "s": 2634, "text": "start − The slice begins from here." }, { "code": null, "e": 2706, "s": 2670, "text": "start − The slice begins from here." }, { "code": null, "e": 2733, "s": 2706, "text": "end − The slice ends here." }, { "code": null, "e": 2760, "s": 2733, "text": "end − The slice ends here." }, { "code": null, "e": 2828, "s": 2760, "text": "TRUE if the string ends with the specified suffix, otherwise FALSE." }, { "code": null, "e": 3048, "s": 2828, "text": "#!/usr/bin/python\n\nstr = \"this is string example....wow!!!\";\n\nsuffix = \"wow!!!\";\nprint str.endswith(suffix)\nprint str.endswith(suffix,20)\n\nsuffix = \"is\";\nprint str.endswith(suffix, 2, 4)\nprint str.endswith(suffix, 2, 6)" }, { "code": null, "e": 3070, "s": 3048, "text": "True\nTrue\nTrue\nFalse\n" }, { "code": null, "e": 3107, "s": 3070, "text": "\n 187 Lectures \n 17.5 hours \n" }, { "code": null, "e": 3123, "s": 3107, "text": " Malhar Lathkar" }, { "code": null, "e": 3156, "s": 3123, "text": "\n 55 Lectures \n 8 hours \n" }, { "code": null, "e": 3175, "s": 3156, "text": " Arnab Chakraborty" }, { "code": null, "e": 3210, "s": 3175, "text": "\n 136 Lectures \n 11 hours \n" }, { "code": null, "e": 3232, "s": 3210, "text": " In28Minutes Official" }, { "code": null, "e": 3266, "s": 3232, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 3294, "s": 3266, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 3329, "s": 3294, "text": "\n 70 Lectures \n 8.5 hours \n" }, { "code": null, "e": 3343, "s": 3329, "text": " Lets Kode It" }, { "code": null, "e": 3376, "s": 3343, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 3393, "s": 3376, "text": " Abhilash Nelson" }, { "code": null, "e": 3400, "s": 3393, "text": " Print" }, { "code": null, "e": 3411, "s": 3400, "text": " Add Notes" } ]
10 Minutes to Building a CNN Binary Image Classifier in TensorFlow | by Binh Phan | Towards Data Science
This is a short introduction to computer vision — namely, how to build a binary image classifier using convolutional neural network layers in TensorFlow/Keras, geared mainly towards new users. This easy-to-follow tutorial is broken down into 3 sections: The dataThe model architectureThe accuracy, ROC curve, and AUC The data The model architecture The accuracy, ROC curve, and AUC Requirements: Nothing! All you need to follow this tutorial is this Google Colab notebook containing the data and code. Google Colab allows you to write and run Python code in-browser without any setup, and includes free GPU access! We’re going to build a dandelion and grass image classifier. I’ve created a small image dataset using images from Google Images, which you can download and parse in the first 8 cells of the tutorial. By the end of those 8 lines, visualizing a sample of your image dataset will look something like this: Note how some of the images in the dataset aren’t perfect representations of grass or dandelions. For simplicity’s sake, let’s make this okay and move on to how to easily create our training and validation dataset. The data that we fetched earlier is divided into two folders, train and valid. In those folders, the foldersdandelion and grass contain the images of each class. To create a dataset, let’s use the keras.preprocessing.image.ImageDataGenerator class to create our training and validation dataset and normalize our data. What this class does is create a dataset and automatically does the labeling for us, allowing us to create a dataset in just one line! At the beginning of this section, we first import TensorFlow. Let’s then add our CNN layers. We’ll first add a convolutional 2D layer with 16 filters, a kernel of 3x3, the input size as our image dimensions, 200x200x3, and the activation as ReLU. tf.keras.layers.Conv2D(16, (3,3), activation='relu', input_shape=(200, 200, 3)) After that, we’ll add a max pooling layer that halves the image dimension, so after this layer, the output will be 100x100x3. tf.keras.layers.MaxPooling2D(2, 2) We will stack 5 of these layers together, with each subsequent CNN adding more filters. Finally, we’ll flatten the output of the CNN layers, feed it into a fully-connected layer, and then to a sigmoid layer for binary classification. Here is the model that we have built: model = tf.keras.models.Sequential([# Note the input shape is the desired size of the image 200x200 with 3 bytes color# This is the first convolutiontf.keras.layers.Conv2D(16, (3,3), activation='relu', input_shape=(200, 200, 3)),tf.keras.layers.MaxPooling2D(2, 2),# The second convolutiontf.keras.layers.Conv2D(32, (3,3), activation='relu'),tf.keras.layers.MaxPooling2D(2,2),# The third convolutiontf.keras.layers.Conv2D(64, (3,3), activation='relu'),tf.keras.layers.MaxPooling2D(2,2),# The fourth convolutiontf.keras.layers.Conv2D(64, (3,3), activation='relu'),tf.keras.layers.MaxPooling2D(2,2),# # The fifth convolutiontf.keras.layers.Conv2D(64, (3,3), activation='relu'),tf.keras.layers.MaxPooling2D(2,2),# Flatten the results to feed into a DNNtf.keras.layers.Flatten(),# 512 neuron hidden layertf.keras.layers.Dense(512, activation='relu'),# Only 1 output neuron. It will contain a value from 0-1 where 0 for 1 class ('dandelions') and 1 for the other ('grass')tf.keras.layers.Dense(1, activation='sigmoid') Let’s see a summary of the model we have built: Model: "sequential" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= conv2d (Conv2D) (None, 198, 198, 16) 448 _________________________________________________________________ max_pooling2d (MaxPooling2D) (None, 99, 99, 16) 0 _________________________________________________________________ conv2d_1 (Conv2D) (None, 97, 97, 32) 4640 _________________________________________________________________ max_pooling2d_1 (MaxPooling2 (None, 48, 48, 32) 0 _________________________________________________________________ conv2d_2 (Conv2D) (None, 46, 46, 64) 18496 _________________________________________________________________ max_pooling2d_2 (MaxPooling2 (None, 23, 23, 64) 0 _________________________________________________________________ conv2d_3 (Conv2D) (None, 21, 21, 64) 36928 _________________________________________________________________ max_pooling2d_3 (MaxPooling2 (None, 10, 10, 64) 0 _________________________________________________________________ conv2d_4 (Conv2D) (None, 8, 8, 64) 36928 _________________________________________________________________ max_pooling2d_4 (MaxPooling2 (None, 4, 4, 64) 0 _________________________________________________________________ flatten (Flatten) (None, 1024) 0 _________________________________________________________________ dense (Dense) (None, 512) 524800 _________________________________________________________________ dense_1 (Dense) (None, 1) 513 ================================================================= Total params: 622,753 Trainable params: 622,753 Non-trainable params: 0 Next, we’ll configure the specifications for model training. We will train our model with the binary_crossentropy loss. We will use the RMSProp optimizer. RMSProp is a sensible optimization algorithm because it automates learning-rate tuning for us (alternatively, we could also use Adam or Adagrad for similar results). We will add accuracy to metrics so that the model will monitor accuracy during training. model.compile(loss='binary_crossentropy',optimizer=RMSprop(lr=0.001),metrics='accuracy') Let’s train for 15 epochs: history = model.fit(train_generator,steps_per_epoch=8,epochs=15,verbose=1,validation_data = validation_generator,validation_steps=8) Let’s evaluate the accuracy of our model: model.evaluate(validation_generator) Now, let’s calculate our ROC curve and plot it. First, let’s make predictions on our validation set. When using generators to make predictions, we must first turn off shuffle (as we did when we created validation_generator) and reset the generator: STEP_SIZE_TEST=validation_generator.n//validation_generator.batch_sizevalidation_generator.reset()preds = model.predict(validation_generator,verbose=1) To create the ROC curve and AUC, we’ll need to compute the false-positive rate and the true-positive rate: fpr, tpr, _ = roc_curve(validation_generator.classes, preds)roc_auc = auc(fpr, tpr)plt.figure()lw = 2plt.plot(fpr, tpr, color='darkorange',lw=lw, label='ROC curve (area = %0.2f)' % roc_auc)plt.plot([0, 1], [0, 1], color='navy', lw=lw, linestyle='--')plt.xlim([0.0, 1.0])plt.ylim([0.0, 1.05])plt.xlabel('False Positive Rate')plt.ylabel('True Positive Rate')plt.title('Receiver operating characteristic example')plt.legend(loc="lower right")plt.show() The ROC curve is a probability curve plotting the true-positive rate (TPR) against the false-positive rate (FPR). Similarly, the AUC (area under curve), as shown in the legend above, measures how much our model is capable of distinguishing between our two classes, dandelions and grass. It is also used to compare different models, which I will do in future tutorials when I present how to build an image classifier using fully-connected layers and also transfer learning with ResNet! Finally, at the end of the notebook, you’ll have a chance to make predictions on your own images! I hope this gives you a gentle introduction to building a simple binary image classifier using CNN layers. If you are interested in similar easy-to-follow, no-nonsense tutorials like this, please check out my other stories!
[ { "code": null, "e": 425, "s": 171, "text": "This is a short introduction to computer vision — namely, how to build a binary image classifier using convolutional neural network layers in TensorFlow/Keras, geared mainly towards new users. This easy-to-follow tutorial is broken down into 3 sections:" }, { "code": null, "e": 488, "s": 425, "text": "The dataThe model architectureThe accuracy, ROC curve, and AUC" }, { "code": null, "e": 497, "s": 488, "text": "The data" }, { "code": null, "e": 520, "s": 497, "text": "The model architecture" }, { "code": null, "e": 553, "s": 520, "text": "The accuracy, ROC curve, and AUC" }, { "code": null, "e": 786, "s": 553, "text": "Requirements: Nothing! All you need to follow this tutorial is this Google Colab notebook containing the data and code. Google Colab allows you to write and run Python code in-browser without any setup, and includes free GPU access!" }, { "code": null, "e": 986, "s": 786, "text": "We’re going to build a dandelion and grass image classifier. I’ve created a small image dataset using images from Google Images, which you can download and parse in the first 8 cells of the tutorial." }, { "code": null, "e": 1089, "s": 986, "text": "By the end of those 8 lines, visualizing a sample of your image dataset will look something like this:" }, { "code": null, "e": 1304, "s": 1089, "text": "Note how some of the images in the dataset aren’t perfect representations of grass or dandelions. For simplicity’s sake, let’s make this okay and move on to how to easily create our training and validation dataset." }, { "code": null, "e": 1757, "s": 1304, "text": "The data that we fetched earlier is divided into two folders, train and valid. In those folders, the foldersdandelion and grass contain the images of each class. To create a dataset, let’s use the keras.preprocessing.image.ImageDataGenerator class to create our training and validation dataset and normalize our data. What this class does is create a dataset and automatically does the labeling for us, allowing us to create a dataset in just one line!" }, { "code": null, "e": 1819, "s": 1757, "text": "At the beginning of this section, we first import TensorFlow." }, { "code": null, "e": 2004, "s": 1819, "text": "Let’s then add our CNN layers. We’ll first add a convolutional 2D layer with 16 filters, a kernel of 3x3, the input size as our image dimensions, 200x200x3, and the activation as ReLU." }, { "code": null, "e": 2084, "s": 2004, "text": "tf.keras.layers.Conv2D(16, (3,3), activation='relu', input_shape=(200, 200, 3))" }, { "code": null, "e": 2210, "s": 2084, "text": "After that, we’ll add a max pooling layer that halves the image dimension, so after this layer, the output will be 100x100x3." }, { "code": null, "e": 2245, "s": 2210, "text": "tf.keras.layers.MaxPooling2D(2, 2)" }, { "code": null, "e": 2333, "s": 2245, "text": "We will stack 5 of these layers together, with each subsequent CNN adding more filters." }, { "code": null, "e": 2479, "s": 2333, "text": "Finally, we’ll flatten the output of the CNN layers, feed it into a fully-connected layer, and then to a sigmoid layer for binary classification." }, { "code": null, "e": 2517, "s": 2479, "text": "Here is the model that we have built:" }, { "code": null, "e": 3530, "s": 2517, "text": "model = tf.keras.models.Sequential([# Note the input shape is the desired size of the image 200x200 with 3 bytes color# This is the first convolutiontf.keras.layers.Conv2D(16, (3,3), activation='relu', input_shape=(200, 200, 3)),tf.keras.layers.MaxPooling2D(2, 2),# The second convolutiontf.keras.layers.Conv2D(32, (3,3), activation='relu'),tf.keras.layers.MaxPooling2D(2,2),# The third convolutiontf.keras.layers.Conv2D(64, (3,3), activation='relu'),tf.keras.layers.MaxPooling2D(2,2),# The fourth convolutiontf.keras.layers.Conv2D(64, (3,3), activation='relu'),tf.keras.layers.MaxPooling2D(2,2),# # The fifth convolutiontf.keras.layers.Conv2D(64, (3,3), activation='relu'),tf.keras.layers.MaxPooling2D(2,2),# Flatten the results to feed into a DNNtf.keras.layers.Flatten(),# 512 neuron hidden layertf.keras.layers.Dense(512, activation='relu'),# Only 1 output neuron. It will contain a value from 0-1 where 0 for 1 class ('dandelions') and 1 for the other ('grass')tf.keras.layers.Dense(1, activation='sigmoid')" }, { "code": null, "e": 3578, "s": 3530, "text": "Let’s see a summary of the model we have built:" }, { "code": null, "e": 5584, "s": 3578, "text": "Model: \"sequential\" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= conv2d (Conv2D) (None, 198, 198, 16) 448 _________________________________________________________________ max_pooling2d (MaxPooling2D) (None, 99, 99, 16) 0 _________________________________________________________________ conv2d_1 (Conv2D) (None, 97, 97, 32) 4640 _________________________________________________________________ max_pooling2d_1 (MaxPooling2 (None, 48, 48, 32) 0 _________________________________________________________________ conv2d_2 (Conv2D) (None, 46, 46, 64) 18496 _________________________________________________________________ max_pooling2d_2 (MaxPooling2 (None, 23, 23, 64) 0 _________________________________________________________________ conv2d_3 (Conv2D) (None, 21, 21, 64) 36928 _________________________________________________________________ max_pooling2d_3 (MaxPooling2 (None, 10, 10, 64) 0 _________________________________________________________________ conv2d_4 (Conv2D) (None, 8, 8, 64) 36928 _________________________________________________________________ max_pooling2d_4 (MaxPooling2 (None, 4, 4, 64) 0 _________________________________________________________________ flatten (Flatten) (None, 1024) 0 _________________________________________________________________ dense (Dense) (None, 512) 524800 _________________________________________________________________ dense_1 (Dense) (None, 1) 513 ================================================================= Total params: 622,753 Trainable params: 622,753 Non-trainable params: 0" }, { "code": null, "e": 5994, "s": 5584, "text": "Next, we’ll configure the specifications for model training. We will train our model with the binary_crossentropy loss. We will use the RMSProp optimizer. RMSProp is a sensible optimization algorithm because it automates learning-rate tuning for us (alternatively, we could also use Adam or Adagrad for similar results). We will add accuracy to metrics so that the model will monitor accuracy during training." }, { "code": null, "e": 6083, "s": 5994, "text": "model.compile(loss='binary_crossentropy',optimizer=RMSprop(lr=0.001),metrics='accuracy')" }, { "code": null, "e": 6110, "s": 6083, "text": "Let’s train for 15 epochs:" }, { "code": null, "e": 6243, "s": 6110, "text": "history = model.fit(train_generator,steps_per_epoch=8,epochs=15,verbose=1,validation_data = validation_generator,validation_steps=8)" }, { "code": null, "e": 6285, "s": 6243, "text": "Let’s evaluate the accuracy of our model:" }, { "code": null, "e": 6322, "s": 6285, "text": "model.evaluate(validation_generator)" }, { "code": null, "e": 6370, "s": 6322, "text": "Now, let’s calculate our ROC curve and plot it." }, { "code": null, "e": 6571, "s": 6370, "text": "First, let’s make predictions on our validation set. When using generators to make predictions, we must first turn off shuffle (as we did when we created validation_generator) and reset the generator:" }, { "code": null, "e": 6723, "s": 6571, "text": "STEP_SIZE_TEST=validation_generator.n//validation_generator.batch_sizevalidation_generator.reset()preds = model.predict(validation_generator,verbose=1)" }, { "code": null, "e": 6830, "s": 6723, "text": "To create the ROC curve and AUC, we’ll need to compute the false-positive rate and the true-positive rate:" }, { "code": null, "e": 7280, "s": 6830, "text": "fpr, tpr, _ = roc_curve(validation_generator.classes, preds)roc_auc = auc(fpr, tpr)plt.figure()lw = 2plt.plot(fpr, tpr, color='darkorange',lw=lw, label='ROC curve (area = %0.2f)' % roc_auc)plt.plot([0, 1], [0, 1], color='navy', lw=lw, linestyle='--')plt.xlim([0.0, 1.0])plt.ylim([0.0, 1.05])plt.xlabel('False Positive Rate')plt.ylabel('True Positive Rate')plt.title('Receiver operating characteristic example')plt.legend(loc=\"lower right\")plt.show()" }, { "code": null, "e": 7394, "s": 7280, "text": "The ROC curve is a probability curve plotting the true-positive rate (TPR) against the false-positive rate (FPR)." }, { "code": null, "e": 7765, "s": 7394, "text": "Similarly, the AUC (area under curve), as shown in the legend above, measures how much our model is capable of distinguishing between our two classes, dandelions and grass. It is also used to compare different models, which I will do in future tutorials when I present how to build an image classifier using fully-connected layers and also transfer learning with ResNet!" }, { "code": null, "e": 7863, "s": 7765, "text": "Finally, at the end of the notebook, you’ll have a chance to make predictions on your own images!" } ]
Lua - while Loop
A while loop statement in Lua programming language repeatedly executes a target statement as long as a given condition is true. The syntax of a while loop in Lua programming language is as follows − while(condition) do statement(s) end Here, statement(s) may be a single statement or a block of statements. The condition may be any expression, and true is any non-zero value. The loop iterates while the condition is true. When the condition becomes false, the program control passes to the line immediately following the loop. Here, the key point to note is that the while loop might not be executed at all. When the condition is tested and the result is false, the loop body will be skipped and the first statement after the while loop will be executed. a = 10 while( a < 20 ) do print("value of a:", a) a = a+1 end When the above code is built and executed, it produces the following result − value of a: 10 value of a: 11 value of a: 12 value of a: 13 value of a: 14 value of a: 15 value of a: 16 value of a: 17 value of a: 18 value of a: 19 12 Lectures 2 hours Manish Gupta 80 Lectures 3 hours Sanjeev Mittal 54 Lectures 3.5 hours Mehmet GOKTEPE Print Add Notes Bookmark this page
[ { "code": null, "e": 2231, "s": 2103, "text": "A while loop statement in Lua programming language repeatedly executes a target statement as long as a given condition is true." }, { "code": null, "e": 2302, "s": 2231, "text": "The syntax of a while loop in Lua programming language is as follows −" }, { "code": null, "e": 2343, "s": 2302, "text": "while(condition)\ndo\n statement(s)\nend\n" }, { "code": null, "e": 2530, "s": 2343, "text": "Here, statement(s) may be a single statement or a block of statements. The condition may be any expression, and true is any non-zero value. The loop iterates while the condition is true." }, { "code": null, "e": 2635, "s": 2530, "text": "When the condition becomes false, the program control passes to the line immediately following the loop." }, { "code": null, "e": 2863, "s": 2635, "text": "Here, the key point to note is that the while loop might not be executed at all. When the condition is tested and the result is false, the loop body will be skipped and the first statement after the while loop will be executed." }, { "code": null, "e": 2932, "s": 2863, "text": "a = 10\n\nwhile( a < 20 )\ndo\n print(\"value of a:\", a)\n a = a+1\nend" }, { "code": null, "e": 3010, "s": 2932, "text": "When the above code is built and executed, it produces the following result −" }, { "code": null, "e": 3161, "s": 3010, "text": "value of a:\t10\nvalue of a:\t11\nvalue of a:\t12\nvalue of a:\t13\nvalue of a:\t14\nvalue of a:\t15\nvalue of a:\t16\nvalue of a:\t17\nvalue of a:\t18\nvalue of a:\t19\n" }, { "code": null, "e": 3194, "s": 3161, "text": "\n 12 Lectures \n 2 hours \n" }, { "code": null, "e": 3208, "s": 3194, "text": " Manish Gupta" }, { "code": null, "e": 3241, "s": 3208, "text": "\n 80 Lectures \n 3 hours \n" }, { "code": null, "e": 3257, "s": 3241, "text": " Sanjeev Mittal" }, { "code": null, "e": 3292, "s": 3257, "text": "\n 54 Lectures \n 3.5 hours \n" }, { "code": null, "e": 3308, "s": 3292, "text": " Mehmet GOKTEPE" }, { "code": null, "e": 3315, "s": 3308, "text": " Print" }, { "code": null, "e": 3326, "s": 3315, "text": " Add Notes" } ]
Step-by-step guide to build your own ‘mini IMDB’ database | by Tirthajyoti Sarkar | Towards Data Science
Often after a few introductory courses in Python, beginners wonder how to write a cool Python program which demonstrates somewhat advanced capabilities of the language such as web scraping or database manipulation. In this article, I will show how to use simple Python libraries and built-in capabilities to scrape the web for movie information and store them in a local SQLite database, which can later be queried for data analytics with movie info. Think of this as a project to build your own mini IMDB database! This type of data engineering task — gathering from web and building a database connection — is often the first step in a data analytics project. Before you do any cool predictive modeling, you need to master this step. This step is often messy and unstructured i.e. there is no one-shot formula or one-stop shop library which does it all for you. So, you have to extract the data from web, examine its structure and build your code to flawlessly crawl through it. Specifically, this demo will show the usage of following features, Python urllib library Web API service (with a secret key) for retrieving data Python json library Python OS module Python SQLite library Brief descriptions of these are given below, The gateway from Python to web is done through urllib module. It is a Python module for fetching URLs (Uniform Resource Locators). It offers a very simple interface, in the form of the urlopen function. This is capable of fetching URLs using a variety of different protocols. It also offers a slightly more complex interface for handling common situations — like basic authentication, cookies, proxies and so on. These are provided by objects called handlers and openers. Web scraping is often done by API services hosted by external websites. Think of them as repository or remote database which you can query by sending search string from your own little program. In this particular example, we will take help from Open Movie Database (OMDB) website which gives an API key to registered users for downloading information about movies. Because it is a free service, they have a restriction of 1000 requests per day. Note, you have to register on their website and get your own API key for making request from your Python program. The data obtained from this API service comes back as a JSON file. Therefore, we need to parse/convert the JSON file into a Python object, which we can work with easily. JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. It is based on a subset of the JavaScript Programming Language, Standard ECMA-262 3rd Edition — December 1999. JSON is a text format that is completely language independent but uses conventions that are familiar to programmers of the C-family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many others. These properties make JSON an ideal data-interchange language. The json library can parse JSON pages from strings or files. The library parses JSON into a Python dictionary or list. It can also convert Python dictionaries or lists into JSON strings. It is an extremely useful module and very simple to learn. This module is likely to be used in any Python based web data analytics program as the majority of webpages nowadays use JSON as primary object type while returning data. This module provides a portable way of using operating system dependent functionality. If you just want to read or write a file see open(), if you want to manipulate paths, see the os.path module, and if you want to read all the lines in all the files on the command line see the fileinput module. For creating temporary files and directories see the tempfile module, and for high-level file and directory handling see the shutil module. In this demo, we will use OS module methods for checking existing directory and manipulate files to save some data. SQLite is a C library that provides a lightweight disk-based database that doesn’t require a separate server process and allows accessing the database using a nonstandard variant of the SQL query language. Some applications can use SQLite for internal data storage. It’s also possible to prototype an application using SQLite and then port the code to a larger database such as PostgreSQL or Oracle. The sqlite3 module of Python provides a SQL interface compliant with the DB-API 2.0 specification. The flow of the program is shown below. Please note that the boiler plate code is available in my Github repository. Please download/fork/star if you like it. The basic idea is to send request to external API with a movie title that is entered by the user. The program then tries to download the data and if successful, prints it out. def search_movie(title): if len(title) < 1 or title==’quit’: print(“Goodbye now...”) return Nonetry: url = serviceurl + urllib.parse.urlencode({‘t’: title})+apikey print(f’Retrieving the data of “{title}” now... ‘) uh = urllib.request.urlopen(url) data = uh.read() json_data=json.loads(data) if json_data[‘Response’]==’True’: print_json(json_data)except urllib.error.URLError as e: print(f"ERROR: {e.reason}") Just for example, the JSON file looks like following, If the program finds a link to an image file for the poster of the movie, it asks the user if (s)he wants to download it. If user says OK, it downloads the image file to a local directory with the movie title as file name. # Asks user whether to download the poster of the movieif json_data['Poster']!='N/A': poster_yes_no=input ('Poster of this movie can be downloaded. Enter "yes" or "no": ').lower() if poster_yes_no=='yes': save_poster(json_data) Next, it asks the user if (s)he wants to save some basic information about the movie in a local database. If user gives the nod, it creates or inserts into a SQLite database a subset of the downloaded movie information. #Asks user whether to save the movie information in a local databasesave_database_yes_no=input ('Save the movie info in a local database? Enter "yes" or "no": ').lower()if save_database_yes_no=='yes': save_in_database(json_data) Here is the function definition to save in the database. The notebook also contains a function to save the information in an Excel file from an existing database. You will notice that the program uses a secret API key for accessing the data. This key can be obtained freely by going to OMDB website and be used for up to 1000 times a day. It is a very common practice to use a secret (user-specific) key for web scraping. The way I protect the integrity of my personal API key is that I create a small JSON file in the same directory of the Jupyter notebook, called APIkeys.json. The content of this file is hidden from the external user who will see my code. My Jupyter notebook reads this JSON file as a dictionary and copies the key corresponding to the movie website and appends that to the encoded URL request string that is sent by the urllib.request method. with open(‘APIkeys.json’) as f: keys = json.load(f) omdbapi = keys[‘OMDBapi’]serviceurl = 'http://www.omdbapi.com/?'apikey = '&apikey='+omdbapi This article goes over a demo Python notebook to illustrate how to retrieve basic information about movies using a free API service and to save the movie posters and the downloaded information in a lightweight SQLite database. Above all, it demonstrates simple utilization of Python libraries such as urllib, json, and sqlite3, which are extremely useful (and powerful) tools for data analytics/ web data mining tasks. I hope readers can benefit from the provided Notebook file and build upon it as per their own requirement and imagination. For more web data analytics notebooks, please see my repository. If you have any questions or ideas to share, please contact the author at tirthajyoti[AT]gmail.com. Also you can check author’s GitHub repositories for other fun code snippets in Python, R, or MATLAB and machine learning resources. If you are, like me, passionate about machine learning/data science, please feel free to add me on LinkedIn or follow me on Twitter.
[ { "code": null, "e": 688, "s": 172, "text": "Often after a few introductory courses in Python, beginners wonder how to write a cool Python program which demonstrates somewhat advanced capabilities of the language such as web scraping or database manipulation. In this article, I will show how to use simple Python libraries and built-in capabilities to scrape the web for movie information and store them in a local SQLite database, which can later be queried for data analytics with movie info. Think of this as a project to build your own mini IMDB database!" }, { "code": null, "e": 1153, "s": 688, "text": "This type of data engineering task — gathering from web and building a database connection — is often the first step in a data analytics project. Before you do any cool predictive modeling, you need to master this step. This step is often messy and unstructured i.e. there is no one-shot formula or one-stop shop library which does it all for you. So, you have to extract the data from web, examine its structure and build your code to flawlessly crawl through it." }, { "code": null, "e": 1220, "s": 1153, "text": "Specifically, this demo will show the usage of following features," }, { "code": null, "e": 1242, "s": 1220, "text": "Python urllib library" }, { "code": null, "e": 1298, "s": 1242, "text": "Web API service (with a secret key) for retrieving data" }, { "code": null, "e": 1318, "s": 1298, "text": "Python json library" }, { "code": null, "e": 1335, "s": 1318, "text": "Python OS module" }, { "code": null, "e": 1357, "s": 1335, "text": "Python SQLite library" }, { "code": null, "e": 1402, "s": 1357, "text": "Brief descriptions of these are given below," }, { "code": null, "e": 1874, "s": 1402, "text": "The gateway from Python to web is done through urllib module. It is a Python module for fetching URLs (Uniform Resource Locators). It offers a very simple interface, in the form of the urlopen function. This is capable of fetching URLs using a variety of different protocols. It also offers a slightly more complex interface for handling common situations — like basic authentication, cookies, proxies and so on. These are provided by objects called handlers and openers." }, { "code": null, "e": 2433, "s": 1874, "text": "Web scraping is often done by API services hosted by external websites. Think of them as repository or remote database which you can query by sending search string from your own little program. In this particular example, we will take help from Open Movie Database (OMDB) website which gives an API key to registered users for downloading information about movies. Because it is a free service, they have a restriction of 1000 requests per day. Note, you have to register on their website and get your own API key for making request from your Python program." }, { "code": null, "e": 2603, "s": 2433, "text": "The data obtained from this API service comes back as a JSON file. Therefore, we need to parse/convert the JSON file into a Python object, which we can work with easily." }, { "code": null, "e": 3158, "s": 2603, "text": "JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. It is based on a subset of the JavaScript Programming Language, Standard ECMA-262 3rd Edition — December 1999. JSON is a text format that is completely language independent but uses conventions that are familiar to programmers of the C-family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many others. These properties make JSON an ideal data-interchange language." }, { "code": null, "e": 3575, "s": 3158, "text": "The json library can parse JSON pages from strings or files. The library parses JSON into a Python dictionary or list. It can also convert Python dictionaries or lists into JSON strings. It is an extremely useful module and very simple to learn. This module is likely to be used in any Python based web data analytics program as the majority of webpages nowadays use JSON as primary object type while returning data." }, { "code": null, "e": 4129, "s": 3575, "text": "This module provides a portable way of using operating system dependent functionality. If you just want to read or write a file see open(), if you want to manipulate paths, see the os.path module, and if you want to read all the lines in all the files on the command line see the fileinput module. For creating temporary files and directories see the tempfile module, and for high-level file and directory handling see the shutil module. In this demo, we will use OS module methods for checking existing directory and manipulate files to save some data." }, { "code": null, "e": 4628, "s": 4129, "text": "SQLite is a C library that provides a lightweight disk-based database that doesn’t require a separate server process and allows accessing the database using a nonstandard variant of the SQL query language. Some applications can use SQLite for internal data storage. It’s also possible to prototype an application using SQLite and then port the code to a larger database such as PostgreSQL or Oracle. The sqlite3 module of Python provides a SQL interface compliant with the DB-API 2.0 specification." }, { "code": null, "e": 4787, "s": 4628, "text": "The flow of the program is shown below. Please note that the boiler plate code is available in my Github repository. Please download/fork/star if you like it." }, { "code": null, "e": 4963, "s": 4787, "text": "The basic idea is to send request to external API with a movie title that is entered by the user. The program then tries to download the data and if successful, prints it out." }, { "code": null, "e": 5406, "s": 4963, "text": "def search_movie(title): if len(title) < 1 or title==’quit’: print(“Goodbye now...”) return Nonetry: url = serviceurl + urllib.parse.urlencode({‘t’: title})+apikey print(f’Retrieving the data of “{title}” now... ‘) uh = urllib.request.urlopen(url) data = uh.read() json_data=json.loads(data) if json_data[‘Response’]==’True’: print_json(json_data)except urllib.error.URLError as e: print(f\"ERROR: {e.reason}\")" }, { "code": null, "e": 5460, "s": 5406, "text": "Just for example, the JSON file looks like following," }, { "code": null, "e": 5683, "s": 5460, "text": "If the program finds a link to an image file for the poster of the movie, it asks the user if (s)he wants to download it. If user says OK, it downloads the image file to a local directory with the movie title as file name." }, { "code": null, "e": 5924, "s": 5683, "text": "# Asks user whether to download the poster of the movieif json_data['Poster']!='N/A': poster_yes_no=input ('Poster of this movie can be downloaded. Enter \"yes\" or \"no\": ').lower() if poster_yes_no=='yes': save_poster(json_data)" }, { "code": null, "e": 6144, "s": 5924, "text": "Next, it asks the user if (s)he wants to save some basic information about the movie in a local database. If user gives the nod, it creates or inserts into a SQLite database a subset of the downloaded movie information." }, { "code": null, "e": 6376, "s": 6144, "text": "#Asks user whether to save the movie information in a local databasesave_database_yes_no=input ('Save the movie info in a local database? Enter \"yes\" or \"no\": ').lower()if save_database_yes_no=='yes': save_in_database(json_data)" }, { "code": null, "e": 6433, "s": 6376, "text": "Here is the function definition to save in the database." }, { "code": null, "e": 6539, "s": 6433, "text": "The notebook also contains a function to save the information in an Excel file from an existing database." }, { "code": null, "e": 7241, "s": 6539, "text": "You will notice that the program uses a secret API key for accessing the data. This key can be obtained freely by going to OMDB website and be used for up to 1000 times a day. It is a very common practice to use a secret (user-specific) key for web scraping. The way I protect the integrity of my personal API key is that I create a small JSON file in the same directory of the Jupyter notebook, called APIkeys.json. The content of this file is hidden from the external user who will see my code. My Jupyter notebook reads this JSON file as a dictionary and copies the key corresponding to the movie website and appends that to the encoded URL request string that is sent by the urllib.request method." }, { "code": null, "e": 7391, "s": 7241, "text": "with open(‘APIkeys.json’) as f: keys = json.load(f) omdbapi = keys[‘OMDBapi’]serviceurl = 'http://www.omdbapi.com/?'apikey = '&apikey='+omdbapi" }, { "code": null, "e": 7618, "s": 7391, "text": "This article goes over a demo Python notebook to illustrate how to retrieve basic information about movies using a free API service and to save the movie posters and the downloaded information in a lightweight SQLite database." }, { "code": null, "e": 7810, "s": 7618, "text": "Above all, it demonstrates simple utilization of Python libraries such as urllib, json, and sqlite3, which are extremely useful (and powerful) tools for data analytics/ web data mining tasks." }, { "code": null, "e": 7998, "s": 7810, "text": "I hope readers can benefit from the provided Notebook file and build upon it as per their own requirement and imagination. For more web data analytics notebooks, please see my repository." } ]
How to Master Scikit-learn for Data Science | by Chanin Nantasenamat | Towards Data Science
Scikit-learn is one of many scikits (i.e. short form for SciPy Toolkits) that specializes on machine learning. A scikit represents a package that is too specialized to be included in SciPy and are thus packaged as one of many scikits. Another popular scikit is the scikit-image (i.e. collection of algorithms for image processing). Scikit-learn is by far one of the pillars for machine learning in Python as it allows you to build machine learning models as well as providing utility functions for data preparation, post-model analysis and evaluation. In this article, we will be exploring the essential bare minimal knowledge that you need in order to master scikit-learn for getting started in data science. I try my best to distill the essence of the scikit-learn library through the use of hand-drawn illustrations of key concepts as well as code snippets that you can use for your own projects. Let’s dive in! Let’s start with the basics and consider the data representation used in scikit-learn, which is essentially a tabular dataset. At a high-level, for a supervised learning problem the tabular dataset will be comprised of both X and y variables while an unsupervised learning problem will constitute of only X variables. At a high-level, X variables are also known as independent variables and they can be either quantitative or qualitative descriptions of samples of interests while the y variable is also known as the dependent variable and they are essentially the target or response variable that predictive models are built to predict. A cartoon illustration of a typical tabular data that is used in scikit-learn is shown below. For example, if we’re building a predictive model to predict whether individuals have a disease or not the disease/non-disease status is the y variable whereas health indicators obtained by clinical test results are used as X variables. Practically, the contents of a dataset can be stored in a CSV file and it can be read in using the Pandas library via the pd.read_csv() function. Thus, the data structure of the loaded data is known as the Pandas DataFrame. Let’s see this in action. Afterwards, data processing can be performed on the DataFrame using the wide range of Pandas functions for handling missing data (i.e. dropping missing data or filling them in with imputed values), selecting specific column or range of columns, performing feature transformations, conditional filtering of data, etc. In the following example, we will separate the DataFrame as X and y variables, which will be used shortly for model building. This gives rise to the following X data matrix: And the following y variable: For a high-level overview of how to master Pandas for data science also check out a prior blog post that I’ve written. towardsdatascience.com One of the great things about scikit-learn aside from its machine learning capability is its utility functions. For instance, you can create artificial datasets using scikit-learn (as shown below) that can be used to try out different machine learning workflow that you may have devised. As features may be of heterogeneous scales with several magnitude difference, it is therefore essential to perform feature scaling. Common approaches include normalization (scaling features to a uniform range of 0 and 1) and standardization (scaling features such that they have centered mean and unit variance that is all X features will have a mean of 0 and standard deviation of 1). In scikit-learn, normalization can be performing using the normalize() function while standardization can be performed via the StandardScaler() function. A common feature selection approach that I like to use is to simply discard features that have low variance as they provide minimal signal (if we think of it in terms of signals and noises). It is often the case that provided features may not readily be suitable for model building. For instance, categorical features require us to encode such features to a form that is compatible with machine learning algorithms in scikit-learn (i.e. from strings to integers or binary numerical form). Two common types of categorical features includes: Nominal features — Categorical values of the feature has no logical order and are independent from one another. For instance, categorical values pertaining to cities such as Los Angeles, Irvine and Bangkok are nominal.Ordinal features — Categorical valeus of the feature has a logical order and are related to one another. For instance, categorical values that follow a scale such as low, medium and high has a logical order and relationship such that low < medium < high. Nominal features — Categorical values of the feature has no logical order and are independent from one another. For instance, categorical values pertaining to cities such as Los Angeles, Irvine and Bangkok are nominal. Ordinal features — Categorical valeus of the feature has a logical order and are related to one another. For instance, categorical values that follow a scale such as low, medium and high has a logical order and relationship such that low < medium < high. Such feature encoding can be performed using native Python (numerical mapping), Pandas (get_dummies() function and map() method) as well as from within scikit-learn (OneHotEncoder(), OrdinalEncoder(), LabelBinarizer(), LabelEncoder(), etc.). Scikit-learn also supports the imputation of missing values, which is an important part of data pre-processing prior to the construction of machine learning models. Users can use either the univariate or multivariate imputation method via the SimpleImputer() and IterativeImputer() functions from the sklearn.impute sub-module. A commonly used function would have to be data splitting for which we can separate the given input X and y variables as training and test subsets (X_train, y_train, X_test and y_test). The code snippet below makes use of the train_test_split() to perform the data splitting where its input arguments are the input X and y variables, the size of the test set set to 0.2 (or 20%) and a random seed number set to 42 (such that the code block will yield the same data split if it is ran multiple times). As the name implies, we can make use of the Pipeline() function to create a chain or sequence of tasks that are involved in the construction of machine learning models. For example, this could be a sequence that consists of feature imputation, feature encoding and model training. We can think of pipelines as the use of a collection of modular Lego-like building blocks for building machine learning workflows. For more information on building your own machine learning pipeline using scikit-learn, Jason Brownlee from Machine Learning Mastery provides a detailed account in the following tutorial: machinelearningmastery.com In a nutshell, if I can summarize the core essence of using learning algorithms in scikit-learn it would consist of the following 5 steps: from sklearn.modulename import EstimatorName # 0. Importmodel = EstimatorName() # 1. Instantiatemodel.fit(X_train, y_train) # 2. Fitmodel.predict(X_test) # 3. Predictmodel.score(X_test, y_test) # 4. Score Translating the above pseudo-code to the construction of an actual model (e.g. classification model) by using the random forest algorithm as an example would yield the following code block: from sklearn.ensemble import RandomForestClassifierrf = RandomForestClassifier(max_features=5, n_estimators=100)rf.fit(X_train, y_train)rf.predict(X_test)rf.score(X_test, y_test) A cartoon illustration summarizing these core basic steps for using estimators (i.e. the learning algorithm function) in scikit-learn is shown below. Step 0. Importing the estimator function from a module of scikit-learn. An estimator is used to refer to the learning algorithm such as RandomForestClassifier that is used to estimate the output y values given the input X values. Simply put, this can be best summarized by the equation y = f(X) where y can be estimated given known values of X. Step 1. Instantiating the estimator or model. This is done by calling the estimator function and simply assigning it to a variable. Particularly, we can name this variable as model, clf or rf (i.e. abbreviation of the learning algorithm used, random forest). The instantiated model can be thought of as an empty box with no trained knowledge from the data as no training has yet occured. Step 2. The instantiated model will now be allowed to learn from a training dataset in a process known as model building or model training. The training is initiated via the use of the fit() function where the training data is specified as the input argument of the fit() function as in rf.fit(X_train), which literally translates to allowing the instantiated rf estimator to learn from the X_train data. Upon completion of the calculation, the model is now trained on the training set. Step 3. The trained model will now be applied to make predictions on a new and unseen data (e.g. X_test) via the use of the predict() function. As a result, predicted y values (y_test) are generated (and can be stored into a variable such as y_test_pred that can later be used for computing the model performance). Step 4. The model performance can now be calculated. The simplest and quickest method is to use the score() function as in model.score(X_test, y_test). If this function is used for a classification model the score() function produces the accuracy value whereas if it is a regression model the score() function calculates the R2 value. For completeness, we can then extend this core workflow to also include other additional steps that could further boost the robustness and usability of constructed models. I’ll be talking about these additional steps separately in the following sections. A model is only useful if insights can be extracted from it so as to drive the decision-making process. In continuation of the random forest model built above, important features stored in the instantiated rf model can be extracted as follows: # Model interpretationrf.feature_importances_ The above code would produces the following an array of importance values for features used in model building: We can then tidy up the representation by combining it with the feature names to produce a clean DataFrame as follows: Finally, one can take these values to create a feature importance plot as shown below: In a nutshell, as the name implies a feature importance plot provides the relative importance of features as judged by importance value such as those obtained from Gini indices produced by the random forest model. Typically, I would use default hyperparameters when building the first few models. At the first few attempts the goal is to make sure that entire workflow works synchronously and does not spit out errors. My go-to machine learning algorithm is random forest and I use it as the baseline model. In many cases it is also selected as the final learning algorithm as it provides a good hybrid between robust performance and excellent model interpretability. Once the workflow is in place, the next goal is to perform hyperparameter tuning in order to achieve the best possible performance. Although random forest may work quite good straight out of the box but with some hyperparameter tuning it could achieve slightly higher performance. As for learning algorithms such as support vector machine, it is essential to perform hyperparameter tuning in order to obtain robust performance. Let’s now perform hyperparameter tuning which we can perform via the use of the GridSearchCV() function. Firstly, we will create an artificial dataset and perform data splitting, which will then serve as the data for which to build subsequent models. Firstly, we will create an artificial dataset and perform data splitting, which will then serve as the data for which to build subsequent models. 2. Secondly, we will now perform the actual hyperparameter tuning 3. Finally, we can display the results from hyperparameter tuning in a visual representation. You can download the full Jupyter notebook from which the above code snippets was taken from. If video is your thing, I’ve also created a YouTube video showing how to perform hyperparameter tuning using scikit-learn. In this section, I will provide an example workflow that you can use as a general guideline that can be adapted to your own projects. Feel free to experiment with and tweak the procedures mentioned herein. The first 6 steps can be performed using Pandas whereas subsequent steps are performed using scikit-learn, Pandas (to display results in a DataFrame) and also matplotlib (for displaying plots of model performance or plots of feature importance). Read in the data as a Pandas DataFrame and display the first and last few rows.Display the dataset dimension (how many rows and columns).Display the data types of the columns and summarize how many columns are categorical and numerical data types.Handle missing data. First check if there are missing data or not. If there are, make a decision to either drop the missing data or to fill the missing data. Also, be prepared to provide a reason justifying your decision.Perform Exploratory data analysis. Use Pandas groupby function (on categorical variables) together with the aggregate function as well as creating plots to explore the data.Assign independent variables to the X variable while assigning the dependent variable to the y variablePerform data splitting (using scikit-learn) to separate it as the training set and the testing set by using the 80/20 split ratio (remember to set the random seed number).Use the training set to build a machine learning model using the Random forest algorithm (using scikit-learn).Perform hyperparameter tuning coupled with cross-validation via the use of the GridSearchCV() function.Apply the trained model to make predictions on the test set via the predict() function.Explain the obtained model performance metrics as a summary Table with the help of Pandas (I like to display the consolidated model performance as a DataFrame) or also display it as a visualization with the help of matplotlib.Explain important features as identified by the Random forest model. Read in the data as a Pandas DataFrame and display the first and last few rows. Display the dataset dimension (how many rows and columns). Display the data types of the columns and summarize how many columns are categorical and numerical data types. Handle missing data. First check if there are missing data or not. If there are, make a decision to either drop the missing data or to fill the missing data. Also, be prepared to provide a reason justifying your decision. Perform Exploratory data analysis. Use Pandas groupby function (on categorical variables) together with the aggregate function as well as creating plots to explore the data. Assign independent variables to the X variable while assigning the dependent variable to the y variable Perform data splitting (using scikit-learn) to separate it as the training set and the testing set by using the 80/20 split ratio (remember to set the random seed number). Use the training set to build a machine learning model using the Random forest algorithm (using scikit-learn). Perform hyperparameter tuning coupled with cross-validation via the use of the GridSearchCV() function. Apply the trained model to make predictions on the test set via the predict() function. Explain the obtained model performance metrics as a summary Table with the help of Pandas (I like to display the consolidated model performance as a DataFrame) or also display it as a visualization with the help of matplotlib. Explain important features as identified by the Random forest model. All aspiring and data science practitioners would typically find it necessary to once in a while take a glance at the API documentation or even cheat sheets to quickly find the precise functions or input arguments for the myriad of functions available from scikit-learn. Thus, this section presents some amazing resources, cheat sheets and books that may aid your data science projects. Yes, that’s right! One of the best resources would have to be the API documentation, user guides and examples that are provided on the scikit-learn website. I find it extremely useful and quick to hop onto the API documentation for an extensive description of what input arguments are available and what each ones are doing. The examples and user guides are also helpful in providing ideas and inspiration that may help in our own data science projects. A very handy cheat sheet is the one provided by scikit-learn to help choose the appropriate machine learning algorithms by answering a few questions about your data. It should be noted that the above image is a preview of the scikit-learn algorithm cheat sheet. To make the most use of this cheat sheet (you can click on the algorithms to see the underlying documentation of the algorithm of interest), proceed to the cheat sheet by going to the link below: scikit-learn.org Another useful cheat sheet is the one from DataCamp which provides a printer-friendly one-page form in PDF format as well as a HTML version. The great thing about this cheat sheet are the code snippets that is provided for various machine learning tasks that can be performed by scikit-learn. A preview of the cheat sheet is provided below: The PDF and HTML version of the cheat sheet is available at the link below: https://www.datacamp.com/community/blog/scikit-learn-cheat-sheet Nothing beats some great books at your desk that you can occasionally read or browse through for ideas and inspiration for your projects. Sometimes, I would find a new way of approaching things from examples provided in the book. Here are some great books covering the usage of scikit-learn that I also personally own and find to be extremely useful. amzn.to The Hands-On Machine Learning book by Aurélien Géron is one of the classical books that provides a good coverage of both the concepts and practical sides of implementing machine learning and deep learning models in Python. There is also an appendix section that provide some practical advice on how to set up a machine learning project that may also be helpful for aspiring data scientists. The author has also shared the Jupyter notebooks of code mentioned in the book on GitHub in this link. amzn.to The Python Data Science Handbook by Jake VanderPlas is also another great book that covers some of the important libraries for implementing data science projects. Particularly, the book covers how to use Jupyter notebooks, NumPy, Pandas, Matplotlib and Scikit-learn. A free online version of the book is also available here. Another gem are the Jupyter notebooks mentioned in the book which is provided on GitHub here. Congratulations on reaching the end of this article, which also marks the beginning of the myriad of possibilities for exploring data science with scikit-learn. I hope that you’ve found this article helpful in your data science journey and please feel free to drop a comment to let me know if I’ve left out any approaches or resources in scikit-learn that have been instrumental in your own data science journey. As an Amazon Associate, I may earn from qualifying purchases, which goes into helping the creation of future contents. How to Master Python for Data ScienceHere’s the Essential Python you Need for Data Science How to Master Pandas for Data ScienceHere’s the Essential Pandas you Need for Data Science How to Build an AutoML App in Python Step-by-Step Tutorial using the Streamlit Library Strategies for Learning Data SciencePractical Advice for Breaking into Data Science How to Build a Simple Portfolio Website for FREE Step-by-step tutorial from scratch in less than 10 minutes I work full-time as an Associate Professor of Bioinformatics and Head of Data Mining and Biomedical Informatics at a Research University in Thailand. In my after work hours, I’m a YouTuber (AKA the Data Professor) making online videos about data science. In all tutorial videos that I make, I also share Jupyter notebooks on GitHub (Data Professor GitHub page). www.youtube.com ✅ YouTube: http://youtube.com/dataprofessor/✅ Website: http://dataprofessor.org/ (Under construction)✅ LinkedIn: https://www.linkedin.com/company/dataprofessor/✅ Twitter: https://twitter.com/thedataprof/✅ FaceBook: http://facebook.com/dataprofessor/✅ GitHub: https://github.com/dataprofessor/✅ Instagram: https://www.instagram.com/data.professor/
[ { "code": null, "e": 504, "s": 172, "text": "Scikit-learn is one of many scikits (i.e. short form for SciPy Toolkits) that specializes on machine learning. A scikit represents a package that is too specialized to be included in SciPy and are thus packaged as one of many scikits. Another popular scikit is the scikit-image (i.e. collection of algorithms for image processing)." }, { "code": null, "e": 724, "s": 504, "text": "Scikit-learn is by far one of the pillars for machine learning in Python as it allows you to build machine learning models as well as providing utility functions for data preparation, post-model analysis and evaluation." }, { "code": null, "e": 1072, "s": 724, "text": "In this article, we will be exploring the essential bare minimal knowledge that you need in order to master scikit-learn for getting started in data science. I try my best to distill the essence of the scikit-learn library through the use of hand-drawn illustrations of key concepts as well as code snippets that you can use for your own projects." }, { "code": null, "e": 1087, "s": 1072, "text": "Let’s dive in!" }, { "code": null, "e": 1214, "s": 1087, "text": "Let’s start with the basics and consider the data representation used in scikit-learn, which is essentially a tabular dataset." }, { "code": null, "e": 1405, "s": 1214, "text": "At a high-level, for a supervised learning problem the tabular dataset will be comprised of both X and y variables while an unsupervised learning problem will constitute of only X variables." }, { "code": null, "e": 1725, "s": 1405, "text": "At a high-level, X variables are also known as independent variables and they can be either quantitative or qualitative descriptions of samples of interests while the y variable is also known as the dependent variable and they are essentially the target or response variable that predictive models are built to predict." }, { "code": null, "e": 1819, "s": 1725, "text": "A cartoon illustration of a typical tabular data that is used in scikit-learn is shown below." }, { "code": null, "e": 2056, "s": 1819, "text": "For example, if we’re building a predictive model to predict whether individuals have a disease or not the disease/non-disease status is the y variable whereas health indicators obtained by clinical test results are used as X variables." }, { "code": null, "e": 2280, "s": 2056, "text": "Practically, the contents of a dataset can be stored in a CSV file and it can be read in using the Pandas library via the pd.read_csv() function. Thus, the data structure of the loaded data is known as the Pandas DataFrame." }, { "code": null, "e": 2306, "s": 2280, "text": "Let’s see this in action." }, { "code": null, "e": 2623, "s": 2306, "text": "Afterwards, data processing can be performed on the DataFrame using the wide range of Pandas functions for handling missing data (i.e. dropping missing data or filling them in with imputed values), selecting specific column or range of columns, performing feature transformations, conditional filtering of data, etc." }, { "code": null, "e": 2749, "s": 2623, "text": "In the following example, we will separate the DataFrame as X and y variables, which will be used shortly for model building." }, { "code": null, "e": 2797, "s": 2749, "text": "This gives rise to the following X data matrix:" }, { "code": null, "e": 2827, "s": 2797, "text": "And the following y variable:" }, { "code": null, "e": 2946, "s": 2827, "text": "For a high-level overview of how to master Pandas for data science also check out a prior blog post that I’ve written." }, { "code": null, "e": 2969, "s": 2946, "text": "towardsdatascience.com" }, { "code": null, "e": 3081, "s": 2969, "text": "One of the great things about scikit-learn aside from its machine learning capability is its utility functions." }, { "code": null, "e": 3257, "s": 3081, "text": "For instance, you can create artificial datasets using scikit-learn (as shown below) that can be used to try out different machine learning workflow that you may have devised." }, { "code": null, "e": 3389, "s": 3257, "text": "As features may be of heterogeneous scales with several magnitude difference, it is therefore essential to perform feature scaling." }, { "code": null, "e": 3643, "s": 3389, "text": "Common approaches include normalization (scaling features to a uniform range of 0 and 1) and standardization (scaling features such that they have centered mean and unit variance that is all X features will have a mean of 0 and standard deviation of 1)." }, { "code": null, "e": 3797, "s": 3643, "text": "In scikit-learn, normalization can be performing using the normalize() function while standardization can be performed via the StandardScaler() function." }, { "code": null, "e": 3988, "s": 3797, "text": "A common feature selection approach that I like to use is to simply discard features that have low variance as they provide minimal signal (if we think of it in terms of signals and noises)." }, { "code": null, "e": 4286, "s": 3988, "text": "It is often the case that provided features may not readily be suitable for model building. For instance, categorical features require us to encode such features to a form that is compatible with machine learning algorithms in scikit-learn (i.e. from strings to integers or binary numerical form)." }, { "code": null, "e": 4337, "s": 4286, "text": "Two common types of categorical features includes:" }, { "code": null, "e": 4810, "s": 4337, "text": "Nominal features — Categorical values of the feature has no logical order and are independent from one another. For instance, categorical values pertaining to cities such as Los Angeles, Irvine and Bangkok are nominal.Ordinal features — Categorical valeus of the feature has a logical order and are related to one another. For instance, categorical values that follow a scale such as low, medium and high has a logical order and relationship such that low < medium < high." }, { "code": null, "e": 5029, "s": 4810, "text": "Nominal features — Categorical values of the feature has no logical order and are independent from one another. For instance, categorical values pertaining to cities such as Los Angeles, Irvine and Bangkok are nominal." }, { "code": null, "e": 5284, "s": 5029, "text": "Ordinal features — Categorical valeus of the feature has a logical order and are related to one another. For instance, categorical values that follow a scale such as low, medium and high has a logical order and relationship such that low < medium < high." }, { "code": null, "e": 5526, "s": 5284, "text": "Such feature encoding can be performed using native Python (numerical mapping), Pandas (get_dummies() function and map() method) as well as from within scikit-learn (OneHotEncoder(), OrdinalEncoder(), LabelBinarizer(), LabelEncoder(), etc.)." }, { "code": null, "e": 5854, "s": 5526, "text": "Scikit-learn also supports the imputation of missing values, which is an important part of data pre-processing prior to the construction of machine learning models. Users can use either the univariate or multivariate imputation method via the SimpleImputer() and IterativeImputer() functions from the sklearn.impute sub-module." }, { "code": null, "e": 6039, "s": 5854, "text": "A commonly used function would have to be data splitting for which we can separate the given input X and y variables as training and test subsets (X_train, y_train, X_test and y_test)." }, { "code": null, "e": 6354, "s": 6039, "text": "The code snippet below makes use of the train_test_split() to perform the data splitting where its input arguments are the input X and y variables, the size of the test set set to 0.2 (or 20%) and a random seed number set to 42 (such that the code block will yield the same data split if it is ran multiple times)." }, { "code": null, "e": 6635, "s": 6354, "text": "As the name implies, we can make use of the Pipeline() function to create a chain or sequence of tasks that are involved in the construction of machine learning models. For example, this could be a sequence that consists of feature imputation, feature encoding and model training." }, { "code": null, "e": 6766, "s": 6635, "text": "We can think of pipelines as the use of a collection of modular Lego-like building blocks for building machine learning workflows." }, { "code": null, "e": 6954, "s": 6766, "text": "For more information on building your own machine learning pipeline using scikit-learn, Jason Brownlee from Machine Learning Mastery provides a detailed account in the following tutorial:" }, { "code": null, "e": 6981, "s": 6954, "text": "machinelearningmastery.com" }, { "code": null, "e": 7120, "s": 6981, "text": "In a nutshell, if I can summarize the core essence of using learning algorithms in scikit-learn it would consist of the following 5 steps:" }, { "code": null, "e": 7428, "s": 7120, "text": "from sklearn.modulename import EstimatorName # 0. Importmodel = EstimatorName() # 1. Instantiatemodel.fit(X_train, y_train) # 2. Fitmodel.predict(X_test) # 3. Predictmodel.score(X_test, y_test) # 4. Score" }, { "code": null, "e": 7618, "s": 7428, "text": "Translating the above pseudo-code to the construction of an actual model (e.g. classification model) by using the random forest algorithm as an example would yield the following code block:" }, { "code": null, "e": 7797, "s": 7618, "text": "from sklearn.ensemble import RandomForestClassifierrf = RandomForestClassifier(max_features=5, n_estimators=100)rf.fit(X_train, y_train)rf.predict(X_test)rf.score(X_test, y_test)" }, { "code": null, "e": 7947, "s": 7797, "text": "A cartoon illustration summarizing these core basic steps for using estimators (i.e. the learning algorithm function) in scikit-learn is shown below." }, { "code": null, "e": 8177, "s": 7947, "text": "Step 0. Importing the estimator function from a module of scikit-learn. An estimator is used to refer to the learning algorithm such as RandomForestClassifier that is used to estimate the output y values given the input X values." }, { "code": null, "e": 8292, "s": 8177, "text": "Simply put, this can be best summarized by the equation y = f(X) where y can be estimated given known values of X." }, { "code": null, "e": 8551, "s": 8292, "text": "Step 1. Instantiating the estimator or model. This is done by calling the estimator function and simply assigning it to a variable. Particularly, we can name this variable as model, clf or rf (i.e. abbreviation of the learning algorithm used, random forest)." }, { "code": null, "e": 8680, "s": 8551, "text": "The instantiated model can be thought of as an empty box with no trained knowledge from the data as no training has yet occured." }, { "code": null, "e": 8820, "s": 8680, "text": "Step 2. The instantiated model will now be allowed to learn from a training dataset in a process known as model building or model training." }, { "code": null, "e": 9167, "s": 8820, "text": "The training is initiated via the use of the fit() function where the training data is specified as the input argument of the fit() function as in rf.fit(X_train), which literally translates to allowing the instantiated rf estimator to learn from the X_train data. Upon completion of the calculation, the model is now trained on the training set." }, { "code": null, "e": 9311, "s": 9167, "text": "Step 3. The trained model will now be applied to make predictions on a new and unseen data (e.g. X_test) via the use of the predict() function." }, { "code": null, "e": 9482, "s": 9311, "text": "As a result, predicted y values (y_test) are generated (and can be stored into a variable such as y_test_pred that can later be used for computing the model performance)." }, { "code": null, "e": 9634, "s": 9482, "text": "Step 4. The model performance can now be calculated. The simplest and quickest method is to use the score() function as in model.score(X_test, y_test)." }, { "code": null, "e": 9817, "s": 9634, "text": "If this function is used for a classification model the score() function produces the accuracy value whereas if it is a regression model the score() function calculates the R2 value." }, { "code": null, "e": 9989, "s": 9817, "text": "For completeness, we can then extend this core workflow to also include other additional steps that could further boost the robustness and usability of constructed models." }, { "code": null, "e": 10072, "s": 9989, "text": "I’ll be talking about these additional steps separately in the following sections." }, { "code": null, "e": 10176, "s": 10072, "text": "A model is only useful if insights can be extracted from it so as to drive the decision-making process." }, { "code": null, "e": 10316, "s": 10176, "text": "In continuation of the random forest model built above, important features stored in the instantiated rf model can be extracted as follows:" }, { "code": null, "e": 10362, "s": 10316, "text": "# Model interpretationrf.feature_importances_" }, { "code": null, "e": 10473, "s": 10362, "text": "The above code would produces the following an array of importance values for features used in model building:" }, { "code": null, "e": 10592, "s": 10473, "text": "We can then tidy up the representation by combining it with the feature names to produce a clean DataFrame as follows:" }, { "code": null, "e": 10679, "s": 10592, "text": "Finally, one can take these values to create a feature importance plot as shown below:" }, { "code": null, "e": 10893, "s": 10679, "text": "In a nutshell, as the name implies a feature importance plot provides the relative importance of features as judged by importance value such as those obtained from Gini indices produced by the random forest model." }, { "code": null, "e": 11098, "s": 10893, "text": "Typically, I would use default hyperparameters when building the first few models. At the first few attempts the goal is to make sure that entire workflow works synchronously and does not spit out errors." }, { "code": null, "e": 11347, "s": 11098, "text": "My go-to machine learning algorithm is random forest and I use it as the baseline model. In many cases it is also selected as the final learning algorithm as it provides a good hybrid between robust performance and excellent model interpretability." }, { "code": null, "e": 11479, "s": 11347, "text": "Once the workflow is in place, the next goal is to perform hyperparameter tuning in order to achieve the best possible performance." }, { "code": null, "e": 11775, "s": 11479, "text": "Although random forest may work quite good straight out of the box but with some hyperparameter tuning it could achieve slightly higher performance. As for learning algorithms such as support vector machine, it is essential to perform hyperparameter tuning in order to obtain robust performance." }, { "code": null, "e": 11880, "s": 11775, "text": "Let’s now perform hyperparameter tuning which we can perform via the use of the GridSearchCV() function." }, { "code": null, "e": 12026, "s": 11880, "text": "Firstly, we will create an artificial dataset and perform data splitting, which will then serve as the data for which to build subsequent models." }, { "code": null, "e": 12172, "s": 12026, "text": "Firstly, we will create an artificial dataset and perform data splitting, which will then serve as the data for which to build subsequent models." }, { "code": null, "e": 12238, "s": 12172, "text": "2. Secondly, we will now perform the actual hyperparameter tuning" }, { "code": null, "e": 12332, "s": 12238, "text": "3. Finally, we can display the results from hyperparameter tuning in a visual representation." }, { "code": null, "e": 12549, "s": 12332, "text": "You can download the full Jupyter notebook from which the above code snippets was taken from. If video is your thing, I’ve also created a YouTube video showing how to perform hyperparameter tuning using scikit-learn." }, { "code": null, "e": 12755, "s": 12549, "text": "In this section, I will provide an example workflow that you can use as a general guideline that can be adapted to your own projects. Feel free to experiment with and tweak the procedures mentioned herein." }, { "code": null, "e": 13001, "s": 12755, "text": "The first 6 steps can be performed using Pandas whereas subsequent steps are performed using scikit-learn, Pandas (to display results in a DataFrame) and also matplotlib (for displaying plots of model performance or plots of feature importance)." }, { "code": null, "e": 14511, "s": 13001, "text": "Read in the data as a Pandas DataFrame and display the first and last few rows.Display the dataset dimension (how many rows and columns).Display the data types of the columns and summarize how many columns are categorical and numerical data types.Handle missing data. First check if there are missing data or not. If there are, make a decision to either drop the missing data or to fill the missing data. Also, be prepared to provide a reason justifying your decision.Perform Exploratory data analysis. Use Pandas groupby function (on categorical variables) together with the aggregate function as well as creating plots to explore the data.Assign independent variables to the X variable while assigning the dependent variable to the y variablePerform data splitting (using scikit-learn) to separate it as the training set and the testing set by using the 80/20 split ratio (remember to set the random seed number).Use the training set to build a machine learning model using the Random forest algorithm (using scikit-learn).Perform hyperparameter tuning coupled with cross-validation via the use of the GridSearchCV() function.Apply the trained model to make predictions on the test set via the predict() function.Explain the obtained model performance metrics as a summary Table with the help of Pandas (I like to display the consolidated model performance as a DataFrame) or also display it as a visualization with the help of matplotlib.Explain important features as identified by the Random forest model." }, { "code": null, "e": 14591, "s": 14511, "text": "Read in the data as a Pandas DataFrame and display the first and last few rows." }, { "code": null, "e": 14650, "s": 14591, "text": "Display the dataset dimension (how many rows and columns)." }, { "code": null, "e": 14761, "s": 14650, "text": "Display the data types of the columns and summarize how many columns are categorical and numerical data types." }, { "code": null, "e": 14983, "s": 14761, "text": "Handle missing data. First check if there are missing data or not. If there are, make a decision to either drop the missing data or to fill the missing data. Also, be prepared to provide a reason justifying your decision." }, { "code": null, "e": 15157, "s": 14983, "text": "Perform Exploratory data analysis. Use Pandas groupby function (on categorical variables) together with the aggregate function as well as creating plots to explore the data." }, { "code": null, "e": 15261, "s": 15157, "text": "Assign independent variables to the X variable while assigning the dependent variable to the y variable" }, { "code": null, "e": 15433, "s": 15261, "text": "Perform data splitting (using scikit-learn) to separate it as the training set and the testing set by using the 80/20 split ratio (remember to set the random seed number)." }, { "code": null, "e": 15544, "s": 15433, "text": "Use the training set to build a machine learning model using the Random forest algorithm (using scikit-learn)." }, { "code": null, "e": 15648, "s": 15544, "text": "Perform hyperparameter tuning coupled with cross-validation via the use of the GridSearchCV() function." }, { "code": null, "e": 15736, "s": 15648, "text": "Apply the trained model to make predictions on the test set via the predict() function." }, { "code": null, "e": 15963, "s": 15736, "text": "Explain the obtained model performance metrics as a summary Table with the help of Pandas (I like to display the consolidated model performance as a DataFrame) or also display it as a visualization with the help of matplotlib." }, { "code": null, "e": 16032, "s": 15963, "text": "Explain important features as identified by the Random forest model." }, { "code": null, "e": 16303, "s": 16032, "text": "All aspiring and data science practitioners would typically find it necessary to once in a while take a glance at the API documentation or even cheat sheets to quickly find the precise functions or input arguments for the myriad of functions available from scikit-learn." }, { "code": null, "e": 16419, "s": 16303, "text": "Thus, this section presents some amazing resources, cheat sheets and books that may aid your data science projects." }, { "code": null, "e": 16576, "s": 16419, "text": "Yes, that’s right! One of the best resources would have to be the API documentation, user guides and examples that are provided on the scikit-learn website." }, { "code": null, "e": 16873, "s": 16576, "text": "I find it extremely useful and quick to hop onto the API documentation for an extensive description of what input arguments are available and what each ones are doing. The examples and user guides are also helpful in providing ideas and inspiration that may help in our own data science projects." }, { "code": null, "e": 17039, "s": 16873, "text": "A very handy cheat sheet is the one provided by scikit-learn to help choose the appropriate machine learning algorithms by answering a few questions about your data." }, { "code": null, "e": 17331, "s": 17039, "text": "It should be noted that the above image is a preview of the scikit-learn algorithm cheat sheet. To make the most use of this cheat sheet (you can click on the algorithms to see the underlying documentation of the algorithm of interest), proceed to the cheat sheet by going to the link below:" }, { "code": null, "e": 17348, "s": 17331, "text": "scikit-learn.org" }, { "code": null, "e": 17489, "s": 17348, "text": "Another useful cheat sheet is the one from DataCamp which provides a printer-friendly one-page form in PDF format as well as a HTML version." }, { "code": null, "e": 17641, "s": 17489, "text": "The great thing about this cheat sheet are the code snippets that is provided for various machine learning tasks that can be performed by scikit-learn." }, { "code": null, "e": 17689, "s": 17641, "text": "A preview of the cheat sheet is provided below:" }, { "code": null, "e": 17765, "s": 17689, "text": "The PDF and HTML version of the cheat sheet is available at the link below:" }, { "code": null, "e": 17830, "s": 17765, "text": "https://www.datacamp.com/community/blog/scikit-learn-cheat-sheet" }, { "code": null, "e": 18060, "s": 17830, "text": "Nothing beats some great books at your desk that you can occasionally read or browse through for ideas and inspiration for your projects. Sometimes, I would find a new way of approaching things from examples provided in the book." }, { "code": null, "e": 18181, "s": 18060, "text": "Here are some great books covering the usage of scikit-learn that I also personally own and find to be extremely useful." }, { "code": null, "e": 18189, "s": 18181, "text": "amzn.to" }, { "code": null, "e": 18582, "s": 18189, "text": "The Hands-On Machine Learning book by Aurélien Géron is one of the classical books that provides a good coverage of both the concepts and practical sides of implementing machine learning and deep learning models in Python. There is also an appendix section that provide some practical advice on how to set up a machine learning project that may also be helpful for aspiring data scientists." }, { "code": null, "e": 18685, "s": 18582, "text": "The author has also shared the Jupyter notebooks of code mentioned in the book on GitHub in this link." }, { "code": null, "e": 18693, "s": 18685, "text": "amzn.to" }, { "code": null, "e": 18960, "s": 18693, "text": "The Python Data Science Handbook by Jake VanderPlas is also another great book that covers some of the important libraries for implementing data science projects. Particularly, the book covers how to use Jupyter notebooks, NumPy, Pandas, Matplotlib and Scikit-learn." }, { "code": null, "e": 19112, "s": 18960, "text": "A free online version of the book is also available here. Another gem are the Jupyter notebooks mentioned in the book which is provided on GitHub here." }, { "code": null, "e": 19273, "s": 19112, "text": "Congratulations on reaching the end of this article, which also marks the beginning of the myriad of possibilities for exploring data science with scikit-learn." }, { "code": null, "e": 19525, "s": 19273, "text": "I hope that you’ve found this article helpful in your data science journey and please feel free to drop a comment to let me know if I’ve left out any approaches or resources in scikit-learn that have been instrumental in your own data science journey." }, { "code": null, "e": 19644, "s": 19525, "text": "As an Amazon Associate, I may earn from qualifying purchases, which goes into helping the creation of future contents." }, { "code": null, "e": 19735, "s": 19644, "text": "How to Master Python for Data ScienceHere’s the Essential Python you Need for Data Science" }, { "code": null, "e": 19826, "s": 19735, "text": "How to Master Pandas for Data ScienceHere’s the Essential Pandas you Need for Data Science" }, { "code": null, "e": 19913, "s": 19826, "text": "How to Build an AutoML App in Python Step-by-Step Tutorial using the Streamlit Library" }, { "code": null, "e": 19997, "s": 19913, "text": "Strategies for Learning Data SciencePractical Advice for Breaking into Data Science" }, { "code": null, "e": 20105, "s": 19997, "text": "How to Build a Simple Portfolio Website for FREE Step-by-step tutorial from scratch in less than 10 minutes" }, { "code": null, "e": 20467, "s": 20105, "text": "I work full-time as an Associate Professor of Bioinformatics and Head of Data Mining and Biomedical Informatics at a Research University in Thailand. In my after work hours, I’m a YouTuber (AKA the Data Professor) making online videos about data science. In all tutorial videos that I make, I also share Jupyter notebooks on GitHub (Data Professor GitHub page)." }, { "code": null, "e": 20483, "s": 20467, "text": "www.youtube.com" } ]
Matplotlib - Histogram
A histogram is an accurate representation of the distribution of numerical data. It is an estimate of the probability distribution of a continuous variable. It is a kind of bar graph. To construct a histogram, follow these steps − Bin the range of values. Divide the entire range of values into a series of intervals. Count how many values fall into each interval. The bins are usually specified as consecutive, non-overlapping intervals of a variable. The matplotlib.pyplot.hist() function plots a histogram. It computes and draws the histogram of x. The following table lists down the parameters for a histogram − ‘bar’ is a traditional bar-type histogram. If multiple data are given the bars are arranged side by side. ‘barstacked’ is a bar-type histogram where multiple data are stacked on top of each other. ‘step’ generates a lineplot that is by default unfilled. ‘stepfilled’ generates a lineplot that is by default filled. Following example plots a histogram of marks obtained by students in a class. Four bins, 0-25, 26-50, 51-75, and 76-100 are defined. The Histogram shows number of students falling in this range. from matplotlib import pyplot as plt import numpy as np fig,ax = plt.subplots(1,1) a = np.array([22,87,5,43,56,73,55,54,11,20,51,5,79,31,27]) ax.hist(a, bins = [0,25,50,75,100]) ax.set_title("histogram of result") ax.set_xticks([0,25,50,75,100]) ax.set_xlabel('marks') ax.set_ylabel('no. of students') plt.show() The plot appears as shown below − 63 Lectures 6 hours Abhilash Nelson 11 Lectures 4 hours DATAhill Solutions Srinivas Reddy 9 Lectures 2.5 hours DATAhill Solutions Srinivas Reddy 32 Lectures 4 hours Aipython 10 Lectures 2.5 hours Akbar Khan 63 Lectures 6 hours Anmol Print Add Notes Bookmark this page
[ { "code": null, "e": 2700, "s": 2516, "text": "A histogram is an accurate representation of the distribution of numerical data. It is an estimate of the probability distribution of a continuous variable. It is a kind of bar graph." }, { "code": null, "e": 2747, "s": 2700, "text": "To construct a histogram, follow these steps −" }, { "code": null, "e": 2772, "s": 2747, "text": "Bin the range of values." }, { "code": null, "e": 2834, "s": 2772, "text": "Divide the entire range of values into a series of intervals." }, { "code": null, "e": 2881, "s": 2834, "text": "Count how many values fall into each interval." }, { "code": null, "e": 2969, "s": 2881, "text": "The bins are usually specified as consecutive, non-overlapping intervals of a variable." }, { "code": null, "e": 3068, "s": 2969, "text": "The matplotlib.pyplot.hist() function plots a histogram. It computes and draws the histogram of x." }, { "code": null, "e": 3132, "s": 3068, "text": "The following table lists down the parameters for a histogram −" }, { "code": null, "e": 3238, "s": 3132, "text": "‘bar’ is a traditional bar-type histogram. If multiple data are given the bars are arranged side by side." }, { "code": null, "e": 3329, "s": 3238, "text": "‘barstacked’ is a bar-type histogram where multiple data are stacked on top of each other." }, { "code": null, "e": 3386, "s": 3329, "text": "‘step’ generates a lineplot that is by default unfilled." }, { "code": null, "e": 3447, "s": 3386, "text": "‘stepfilled’ generates a lineplot that is by default filled." }, { "code": null, "e": 3642, "s": 3447, "text": "Following example plots a histogram of marks obtained by students in a class. Four bins, 0-25, 26-50, 51-75, and 76-100 are defined. The Histogram shows number of students falling in this range." }, { "code": null, "e": 3955, "s": 3642, "text": "from matplotlib import pyplot as plt\nimport numpy as np\nfig,ax = plt.subplots(1,1)\na = np.array([22,87,5,43,56,73,55,54,11,20,51,5,79,31,27])\nax.hist(a, bins = [0,25,50,75,100])\nax.set_title(\"histogram of result\")\nax.set_xticks([0,25,50,75,100])\nax.set_xlabel('marks')\nax.set_ylabel('no. of students')\nplt.show()" }, { "code": null, "e": 3989, "s": 3955, "text": "The plot appears as shown below −" }, { "code": null, "e": 4022, "s": 3989, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 4039, "s": 4022, "text": " Abhilash Nelson" }, { "code": null, "e": 4072, "s": 4039, "text": "\n 11 Lectures \n 4 hours \n" }, { "code": null, "e": 4107, "s": 4072, "text": " DATAhill Solutions Srinivas Reddy" }, { "code": null, "e": 4141, "s": 4107, "text": "\n 9 Lectures \n 2.5 hours \n" }, { "code": null, "e": 4176, "s": 4141, "text": " DATAhill Solutions Srinivas Reddy" }, { "code": null, "e": 4209, "s": 4176, "text": "\n 32 Lectures \n 4 hours \n" }, { "code": null, "e": 4219, "s": 4209, "text": " Aipython" }, { "code": null, "e": 4254, "s": 4219, "text": "\n 10 Lectures \n 2.5 hours \n" }, { "code": null, "e": 4266, "s": 4254, "text": " Akbar Khan" }, { "code": null, "e": 4299, "s": 4266, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 4306, "s": 4299, "text": " Anmol" }, { "code": null, "e": 4313, "s": 4306, "text": " Print" }, { "code": null, "e": 4324, "s": 4313, "text": " Add Notes" } ]
Cheat Codes to Better Visualisations with Plotly Express | by Ahilan Srivishnumohan | Towards Data Science
Two of the most popular libraries used for visualisations in Data Science is Matplotlib and Seaborn. I want to show how using the Plotly Express module from the Plotly library we can get the simplicity of Seaborn and Matplotlib, but achieve a more in-depth and interactive visualisation. Plotly Express is an easy-to-use and a high-level interface of the Plotly library. So, let’s have look at how we can get started. import plotly.express as px Let’s look at some datasets already in the Plotly Express module: tips = px.data.tips() #total_bill, tip, sex, smoker, day, time, sizegapminder = px.data.gapminder() #country, continent , year, lifeExp, pop, gdpPercap, iso_alpha, iso_numgapminder_canada = gapminder.query("country=='Canada'")gapminder_oceania = gapminder.query("continent=='Oceania'")gapminder_continent = gapminder.query("continent != 'Asia'")iris = px.data.iris() #sepal_length, sepal_width, petal_length, petal_width, species, species_idelection = px.data.election() #district, Coderre, Bergeron, Joly, total, winner, result, district_id Let’s look at the tips dataset using histograms because the data includes a lot of categorical variables. For the first one, I’ll use the total bill as the variable to plot as a histogram. fig = px.histogram(tips, #dataframe x = "total_bill", #x-values column nbins = 30 #number of bins )fig.show() With Plotly Express we can create an interactive histogram. We can see the bin range by the x-axis, the total_bill value, and the count at each point when hovering the cursor. Let’s level up our histograms by considering a second variable, sex: fig = px.histogram(tips, #dataframe x = ”total_bill”, #x-values column color = ”sex” #column shown by color )fig.show() Now we can see both male and female count for total bill, but on top of the hovering interactivity, we can also isolate the histogram to show either male, female, or both. Another minor update to a histogram can be adding a rug plot, a box plot, or a violin plot: fig = px.histogram(tips, #dataframe x = ”total_bill”, #x-values column color = ”sex”, #column shown by color marginal = ”rug”, #plot type (eg box,rug) hover_data = tips.columns #extra info in hover )fig.show() Here I have used a rug plot and now we can see the data points relative to the bins below in the histogram. As you may be wondering, you can interact with the rug plots as well. Another popular and effective visualisation type that Plotly Express not only simplifies yet enhances, is the scatter plot. Here we are looking at the iris dataset; which is about the sizes of different plant species. fig = px.scatter(iris, #dataframe x = "sepal_width", #x-values column y = "sepal_length" #y-values column )fig.show() We can make this scatterplot more dynamic and informative by adding colour, size, and more interactive data. fig = px.scatter(iris, #dataframe x = ”sepal_width”, #x-values column y = ”sepal_length”, #y-values column color = ”species”, #column shown by color size = ’petal_length’, #col shown by plotsize hover_data = [‘petal_width’] #extra info in hover )fig.show() Having the ability to isolate or group the plants by species on one set of axis with the addition of different colours helps us from having to create three individual plots for comparison. A traditional line graph is also very simple with Plotly Express. fig = px.line(gapminder_canada, #dataframe x = "year", #x-values column y = "lifeExp" #y-values column )fig.show() Line graphs are great for comparing two rows from a dataset, and this can be done by adding one more attribute to the plot. In this case, colour for country. fig = px.line(gapminder_oceania, #dataframe x = "year", #x-values column y = "lifeExp", #y-values column color = 'country' #column shown by color )fig.show() Here we have two countries from Oceania so they were both allocated a colour, without having to mention the names of the countries, but only the column name for the argument of colour. We can add more continents other than Oceania, but how do we keep graph from becoming overwhelming? Showing the continent as the colour then setting the line group as the country, allows us to visualise the life expectancy in different continents without having to average the life expectancy for all the countries within that continent. fig = px.line(gapminder_continent, #dataframe x = ”year”, #x-values column y = ”lifeExp”, #y-values column color = ”continent”, #column shown by color line_group = ”country”, #group rows of a column hover_name = ”country” #hover info title )fig.show() Once again we can isolate lines of the continents if individual observations are preferred, as well as a hover ability to check the country represented by each line. More simple code for bar charts. fig = px.bar(gapminder_canada, #dataframe x = ’year’, #x-values column y = ’pop’ #y-values column )fig.show() We can add more information about the change in population throughout time in Canada, by including life expectancy using colour. Upgrade axis label pop to population of Canada, using the labels attribute of bar charts, and also add more detail to the hover function. fig = px.bar(gapminder_canada, #dataframe x = ’year’, #x-values column y = ’pop’, #y-values column hover_data = [‘lifeExp’, ‘gdpPercap’],#extra hover info color = ’lifeExp’, #column by color labels = {‘pop’:’population of Canada’}#label change )fig.show() Above, we can depict two trends about the Canadian population over time with one graph effectively. Looking back at the tips dataset, we could stack a lot more information into a bar chart visualisation. fig = px.bar(tips, #dataframe x = ”sex”, #x-values column y = ”total_bill”, #y-values column color = ”smoker”, #column shown by color barmode = ”group”, #separate filter (smoker) facet_row = ”time”, #name of grid row facet_col = ”day”, #name of grid column category_orders= {“day”: [“Thur”, “Fri”, “Sat”, “Sun”], “time”: [“Lunch”, “Dinner”]} #grid arrangement )fig.show() We have five columns of the dataset that we can observe, accompanied with some interactivity. By using row and column facets we have a grid layout for days of the week and time of meal; consisting of smaller bar charts which contains a summary of the type of person (smoker and sex) and their total bill. Let’s get 3D. Here we are looking at the election dataset where the votes and outcomes of three candidates running for Mayor in Montreal are compared by the district. fig = px.scatter_3d( election, #dataframe x = ”Joly”, #x-values column y = ”Coderre”, #y-values column z = ”Bergeron”, #z-values column color = ”winner”, #column shown by color size = ”total”, #column shown by size hover_name = ”district”, #hover title symbol = ”result”, #column shown by shape color_discrete_map = {“Joly”: “blue”, “Bergeron”: “green”, “Coderre”:”red”} #specific colors for x,y,z values )fig.show() Combined with Plotly’s hover interactivity this plot manages to display all the information from the election dataset. Geographical charts are used in more unique situations but can also be easily done using Plotly Express. fig = px.scatter_geo(gapminder, #dataframe locations = ”iso_alpha”, #location code color = ”continent”, #column shown by color hover_name = ”country”, #hover info title size = ”pop”, #column shown by size animation_frame = ”year”,#column animated projection = ”orthographic”#type of map )fig.show() We have a very useful addition to the visualisation; which is the animation interactability. For this dataset I have chosen the year as the animation frame; so we can either autoplay throughout the years or manually select the years. Although the above globe shaped visualisation is interesting to look at, the following map visualisation will be better for a person to observe and analyse the information. fig = px.choropleth(gapminder, #dataframe locations = ”iso_alpha”, #location code color = ”lifeExp”, #column shown by color hover_name = ”country”, #hover info title animation_frame = ”year”, #column animated range_color = [20,80] #color range )fig.show() Now we have a very clear visualisation showing life expectancy around the world over time. The animated scatter plot (a bubble chart) is my favourite visualisation, as it explains the information well and it is very dynamic. px.scatter(gapminder, #dataframe x = "gdpPercap", #x-values column y = "lifeExp", #y-values column animation_frame = "year", #column animated animation_group = "country", #column shown as bubble size = "pop", #column shown by size color = "continent", #column shown by color hover_name = "country", #hover info title log_x = True, #use logs on x-values size_max = 55, #change max size of bubbles range_x = [100,100000], #axis range for x-values range_y = [25,90] #axis range for y-values ) So, using Plotly Express we can make great visualisations with interactability, that don’t require more than a few intuitive lines of code.
[ { "code": null, "e": 459, "s": 171, "text": "Two of the most popular libraries used for visualisations in Data Science is Matplotlib and Seaborn. I want to show how using the Plotly Express module from the Plotly library we can get the simplicity of Seaborn and Matplotlib, but achieve a more in-depth and interactive visualisation." }, { "code": null, "e": 589, "s": 459, "text": "Plotly Express is an easy-to-use and a high-level interface of the Plotly library. So, let’s have look at how we can get started." }, { "code": null, "e": 617, "s": 589, "text": "import plotly.express as px" }, { "code": null, "e": 683, "s": 617, "text": "Let’s look at some datasets already in the Plotly Express module:" }, { "code": null, "e": 1225, "s": 683, "text": "tips = px.data.tips() #total_bill, tip, sex, smoker, day, time, sizegapminder = px.data.gapminder() #country, continent , year, lifeExp, pop, gdpPercap, iso_alpha, iso_numgapminder_canada = gapminder.query(\"country=='Canada'\")gapminder_oceania = gapminder.query(\"continent=='Oceania'\")gapminder_continent = gapminder.query(\"continent != 'Asia'\")iris = px.data.iris() #sepal_length, sepal_width, petal_length, petal_width, species, species_idelection = px.data.election() #district, Coderre, Bergeron, Joly, total, winner, result, district_id" }, { "code": null, "e": 1414, "s": 1225, "text": "Let’s look at the tips dataset using histograms because the data includes a lot of categorical variables. For the first one, I’ll use the total bill as the variable to plot as a histogram." }, { "code": null, "e": 1597, "s": 1414, "text": "fig = px.histogram(tips, #dataframe x = \"total_bill\", #x-values column nbins = 30 #number of bins )fig.show()" }, { "code": null, "e": 1773, "s": 1597, "text": "With Plotly Express we can create an interactive histogram. We can see the bin range by the x-axis, the total_bill value, and the count at each point when hovering the cursor." }, { "code": null, "e": 1842, "s": 1773, "text": "Let’s level up our histograms by considering a second variable, sex:" }, { "code": null, "e": 2032, "s": 1842, "text": "fig = px.histogram(tips, #dataframe x = ”total_bill”, #x-values column color = ”sex” #column shown by color )fig.show()" }, { "code": null, "e": 2204, "s": 2032, "text": "Now we can see both male and female count for total bill, but on top of the hovering interactivity, we can also isolate the histogram to show either male, female, or both." }, { "code": null, "e": 2296, "s": 2204, "text": "Another minor update to a histogram can be adding a rug plot, a box plot, or a violin plot:" }, { "code": null, "e": 2644, "s": 2296, "text": "fig = px.histogram(tips, #dataframe x = ”total_bill”, #x-values column color = ”sex”, #column shown by color marginal = ”rug”, #plot type (eg box,rug) hover_data = tips.columns #extra info in hover )fig.show()" }, { "code": null, "e": 2822, "s": 2644, "text": "Here I have used a rug plot and now we can see the data points relative to the bins below in the histogram. As you may be wondering, you can interact with the rug plots as well." }, { "code": null, "e": 3040, "s": 2822, "text": "Another popular and effective visualisation type that Plotly Express not only simplifies yet enhances, is the scatter plot. Here we are looking at the iris dataset; which is about the sizes of different plant species." }, { "code": null, "e": 3222, "s": 3040, "text": "fig = px.scatter(iris, #dataframe x = \"sepal_width\", #x-values column y = \"sepal_length\" #y-values column )fig.show()" }, { "code": null, "e": 3331, "s": 3222, "text": "We can make this scatterplot more dynamic and informative by adding colour, size, and more interactive data." }, { "code": null, "e": 3742, "s": 3331, "text": "fig = px.scatter(iris, #dataframe x = ”sepal_width”, #x-values column y = ”sepal_length”, #y-values column color = ”species”, #column shown by color size = ’petal_length’, #col shown by plotsize hover_data = [‘petal_width’] #extra info in hover )fig.show()" }, { "code": null, "e": 3931, "s": 3742, "text": "Having the ability to isolate or group the plants by species on one set of axis with the addition of different colours helps us from having to create three individual plots for comparison." }, { "code": null, "e": 3997, "s": 3931, "text": "A traditional line graph is also very simple with Plotly Express." }, { "code": null, "e": 4161, "s": 3997, "text": "fig = px.line(gapminder_canada, #dataframe x = \"year\", #x-values column y = \"lifeExp\" #y-values column )fig.show()" }, { "code": null, "e": 4319, "s": 4161, "text": "Line graphs are great for comparing two rows from a dataset, and this can be done by adding one more attribute to the plot. In this case, colour for country." }, { "code": null, "e": 4541, "s": 4319, "text": "fig = px.line(gapminder_oceania, #dataframe x = \"year\", #x-values column y = \"lifeExp\", #y-values column color = 'country' #column shown by color )fig.show()" }, { "code": null, "e": 4726, "s": 4541, "text": "Here we have two countries from Oceania so they were both allocated a colour, without having to mention the names of the countries, but only the column name for the argument of colour." }, { "code": null, "e": 4826, "s": 4726, "text": "We can add more continents other than Oceania, but how do we keep graph from becoming overwhelming?" }, { "code": null, "e": 5064, "s": 4826, "text": "Showing the continent as the colour then setting the line group as the country, allows us to visualise the life expectancy in different continents without having to average the life expectancy for all the countries within that continent." }, { "code": null, "e": 5422, "s": 5064, "text": "fig = px.line(gapminder_continent, #dataframe x = ”year”, #x-values column y = ”lifeExp”, #y-values column color = ”continent”, #column shown by color line_group = ”country”, #group rows of a column hover_name = ”country” #hover info title )fig.show()" }, { "code": null, "e": 5588, "s": 5422, "text": "Once again we can isolate lines of the continents if individual observations are preferred, as well as a hover ability to check the country represented by each line." }, { "code": null, "e": 5621, "s": 5588, "text": "More simple code for bar charts." }, { "code": null, "e": 5781, "s": 5621, "text": "fig = px.bar(gapminder_canada, #dataframe x = ’year’, #x-values column y = ’pop’ #y-values column )fig.show()" }, { "code": null, "e": 6048, "s": 5781, "text": "We can add more information about the change in population throughout time in Canada, by including life expectancy using colour. Upgrade axis label pop to population of Canada, using the labels attribute of bar charts, and also add more detail to the hover function." }, { "code": null, "e": 6468, "s": 6048, "text": "fig = px.bar(gapminder_canada, #dataframe x = ’year’, #x-values column y = ’pop’, #y-values column hover_data = [‘lifeExp’, ‘gdpPercap’],#extra hover info color = ’lifeExp’, #column by color labels = {‘pop’:’population of Canada’}#label change )fig.show()" }, { "code": null, "e": 6568, "s": 6468, "text": "Above, we can depict two trends about the Canadian population over time with one graph effectively." }, { "code": null, "e": 6672, "s": 6568, "text": "Looking back at the tips dataset, we could stack a lot more information into a bar chart visualisation." }, { "code": null, "e": 7231, "s": 6672, "text": "fig = px.bar(tips, #dataframe x = ”sex”, #x-values column y = ”total_bill”, #y-values column color = ”smoker”, #column shown by color barmode = ”group”, #separate filter (smoker) facet_row = ”time”, #name of grid row facet_col = ”day”, #name of grid column category_orders= {“day”: [“Thur”, “Fri”, “Sat”, “Sun”], “time”: [“Lunch”, “Dinner”]} #grid arrangement )fig.show()" }, { "code": null, "e": 7536, "s": 7231, "text": "We have five columns of the dataset that we can observe, accompanied with some interactivity. By using row and column facets we have a grid layout for days of the week and time of meal; consisting of smaller bar charts which contains a summary of the type of person (smoker and sex) and their total bill." }, { "code": null, "e": 7703, "s": 7536, "text": "Let’s get 3D. Here we are looking at the election dataset where the votes and outcomes of three candidates running for Mayor in Montreal are compared by the district." }, { "code": null, "e": 8338, "s": 7703, "text": "fig = px.scatter_3d( election, #dataframe x = ”Joly”, #x-values column y = ”Coderre”, #y-values column z = ”Bergeron”, #z-values column color = ”winner”, #column shown by color size = ”total”, #column shown by size hover_name = ”district”, #hover title symbol = ”result”, #column shown by shape color_discrete_map = {“Joly”: “blue”, “Bergeron”: “green”, “Coderre”:”red”} #specific colors for x,y,z values )fig.show()" }, { "code": null, "e": 8457, "s": 8338, "text": "Combined with Plotly’s hover interactivity this plot manages to display all the information from the election dataset." }, { "code": null, "e": 8562, "s": 8457, "text": "Geographical charts are used in more unique situations but can also be easily done using Plotly Express." }, { "code": null, "e": 9032, "s": 8562, "text": "fig = px.scatter_geo(gapminder, #dataframe locations = ”iso_alpha”, #location code color = ”continent”, #column shown by color hover_name = ”country”, #hover info title size = ”pop”, #column shown by size animation_frame = ”year”,#column animated projection = ”orthographic”#type of map )fig.show()" }, { "code": null, "e": 9266, "s": 9032, "text": "We have a very useful addition to the visualisation; which is the animation interactability. For this dataset I have chosen the year as the animation frame; so we can either autoplay throughout the years or manually select the years." }, { "code": null, "e": 9439, "s": 9266, "text": "Although the above globe shaped visualisation is interesting to look at, the following map visualisation will be better for a person to observe and analyse the information." }, { "code": null, "e": 9838, "s": 9439, "text": "fig = px.choropleth(gapminder, #dataframe locations = ”iso_alpha”, #location code color = ”lifeExp”, #column shown by color hover_name = ”country”, #hover info title animation_frame = ”year”, #column animated range_color = [20,80] #color range )fig.show()" }, { "code": null, "e": 9929, "s": 9838, "text": "Now we have a very clear visualisation showing life expectancy around the world over time." }, { "code": null, "e": 10063, "s": 9929, "text": "The animated scatter plot (a bubble chart) is my favourite visualisation, as it explains the information well and it is very dynamic." }, { "code": null, "e": 10780, "s": 10063, "text": "px.scatter(gapminder, #dataframe x = \"gdpPercap\", #x-values column y = \"lifeExp\", #y-values column animation_frame = \"year\", #column animated animation_group = \"country\", #column shown as bubble size = \"pop\", #column shown by size color = \"continent\", #column shown by color hover_name = \"country\", #hover info title log_x = True, #use logs on x-values size_max = 55, #change max size of bubbles range_x = [100,100000], #axis range for x-values range_y = [25,90] #axis range for y-values )" } ]
Python Program to find out the determinant of a given special matrix
Suppose, we have a tree with n vertices, where each vertex is labeled from 1 to n. The root of the tree has the label 1, and each vertex weights wi. Now a nxn matrix A is formed where A(x,y) = Wf(x, y) where f(x, y) is the least common predecessor of vertex x and y. We have to find out the determinant of matrix A. The edges of the matrix, weights, and the total number of vertices are given to us as input. So, if the input is like input_array = [[1, 2], [1, 3], [1, 4], [1, 5]], weights = [1, 2, 3, 4, 5], vertices = 5, then the output will be 24. The matrix A is given as = the determinant of this matrix is 24. To solve this, we will follow these steps − w := an empty list for i in range 0 to vertices, doadd weights[i] and a new list to w add weights[i] and a new list to w for each i, item in enumerate(input_array), dop := item[0]q := item[1]insert q - 1 at the end of w[p - 1, 1]insert p - 1 at the end of w[q - 1, 1] p := item[0] q := item[1] insert q - 1 at the end of w[p - 1, 1] insert p - 1 at the end of w[q - 1, 1] det := 1 stack := a stack containing a tuple (0, 0) while stack is not empty, doi, weights := delete top element from stackdet := (det * (w[i, 0] - weights)) mod (10^9 + 7)for t in w[i][1], doadd tuple containing (t,w[i,0]) to the stackfor each t in w[i][1], dodelete i from w[t,1] i, weights := delete top element from stack det := (det * (w[i, 0] - weights)) mod (10^9 + 7) for t in w[i][1], doadd tuple containing (t,w[i,0]) to the stackfor each t in w[i][1], dodelete i from w[t,1] add tuple containing (t,w[i,0]) to the stack for each t in w[i][1], dodelete i from w[t,1] delete i from w[t,1] return det Let us see the following implementation to get better understanding − Live Demo def solve(input_array, weights, vertices): w = [[weights[i],[]] for i in range(vertices)] for i, item in enumerate(input_array): p,q = item[0], item[1] w[p - 1][1].append(q - 1) w[q - 1][1].append(p - 1) det = 1 stack = [(0,0)] while stack: i, weights = stack.pop() det = (det * (w[i][0] - weights)) % (10**9 + 7) stack += [(t,w[i][0]) for t in w[i][1]] for t in w[i][1]: w[t][1].remove(i) return det print(solve([[1, 2], [1, 3], [1, 4], [1, 5]], [1, 2, 3, 4, 5], 5)) [[1, 2], [1, 3], [1, 4], [1, 5]], [1, 2, 3, 4, 5], 5 24
[ { "code": null, "e": 1471, "s": 1062, "text": "Suppose, we have a tree with n vertices, where each vertex is labeled from 1 to n. The root of the tree has the label 1, and each vertex weights wi. Now a nxn matrix A is formed where A(x,y) = Wf(x, y) where f(x, y) is the least common predecessor of vertex x and y. We have to find out the determinant of matrix A. The edges of the matrix, weights, and the total number of vertices are given to us as input." }, { "code": null, "e": 1613, "s": 1471, "text": "So, if the input is like input_array = [[1, 2], [1, 3], [1, 4], [1, 5]], weights = [1, 2, 3, 4, 5], vertices = 5, then the output will be 24." }, { "code": null, "e": 1640, "s": 1613, "text": "The matrix A is given as =" }, { "code": null, "e": 1678, "s": 1640, "text": "the determinant of this matrix is 24." }, { "code": null, "e": 1722, "s": 1678, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1741, "s": 1722, "text": "w := an empty list" }, { "code": null, "e": 1808, "s": 1741, "text": "for i in range 0 to vertices, doadd weights[i] and a new list to w" }, { "code": null, "e": 1843, "s": 1808, "text": "add weights[i] and a new list to w" }, { "code": null, "e": 1990, "s": 1843, "text": "for each i, item in enumerate(input_array), dop := item[0]q := item[1]insert q - 1 at the end of w[p - 1, 1]insert p - 1 at the end of w[q - 1, 1]" }, { "code": null, "e": 2003, "s": 1990, "text": "p := item[0]" }, { "code": null, "e": 2016, "s": 2003, "text": "q := item[1]" }, { "code": null, "e": 2055, "s": 2016, "text": "insert q - 1 at the end of w[p - 1, 1]" }, { "code": null, "e": 2094, "s": 2055, "text": "insert p - 1 at the end of w[q - 1, 1]" }, { "code": null, "e": 2103, "s": 2094, "text": "det := 1" }, { "code": null, "e": 2146, "s": 2103, "text": "stack := a stack containing a tuple (0, 0)" }, { "code": null, "e": 2376, "s": 2146, "text": "while stack is not empty, doi, weights := delete top element from stackdet := (det * (w[i, 0] - weights)) mod (10^9 + 7)for t in w[i][1], doadd tuple containing (t,w[i,0]) to the stackfor each t in w[i][1], dodelete i from w[t,1]" }, { "code": null, "e": 2420, "s": 2376, "text": "i, weights := delete top element from stack" }, { "code": null, "e": 2470, "s": 2420, "text": "det := (det * (w[i, 0] - weights)) mod (10^9 + 7)" }, { "code": null, "e": 2580, "s": 2470, "text": "for t in w[i][1], doadd tuple containing (t,w[i,0]) to the stackfor each t in w[i][1], dodelete i from w[t,1]" }, { "code": null, "e": 2625, "s": 2580, "text": "add tuple containing (t,w[i,0]) to the stack" }, { "code": null, "e": 2671, "s": 2625, "text": "for each t in w[i][1], dodelete i from w[t,1]" }, { "code": null, "e": 2692, "s": 2671, "text": "delete i from w[t,1]" }, { "code": null, "e": 2703, "s": 2692, "text": "return det" }, { "code": null, "e": 2773, "s": 2703, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 2784, "s": 2773, "text": " Live Demo" }, { "code": null, "e": 3321, "s": 2784, "text": "def solve(input_array, weights, vertices):\n w = [[weights[i],[]] for i in range(vertices)]\n for i, item in enumerate(input_array):\n p,q = item[0], item[1]\n w[p - 1][1].append(q - 1)\n w[q - 1][1].append(p - 1)\n det = 1\n stack = [(0,0)]\n while stack:\n i, weights = stack.pop()\n det = (det * (w[i][0] - weights)) % (10**9 + 7)\n stack += [(t,w[i][0]) for t in w[i][1]]\n for t in w[i][1]:\n w[t][1].remove(i)\n return det\nprint(solve([[1, 2], [1, 3], [1, 4], [1, 5]], [1, 2, 3, 4, 5], 5))" }, { "code": null, "e": 3374, "s": 3321, "text": "[[1, 2], [1, 3], [1, 4], [1, 5]], [1, 2, 3, 4, 5], 5" }, { "code": null, "e": 3377, "s": 3374, "text": "24" } ]
MapStruct - Using constant
MapStruct allows to map a constant value to a property. @Mapping(target = "target-property", const = "const-value") Here target-property − the property for which we are doing the mapping. target-property − the property for which we are doing the mapping. const-value − mapper will map the const-value to target-property. const-value − mapper will map the const-value to target-property. Following example demonstrates the same. Open project mapping as updated in Mapping Using dateFormat chapter in Eclipse. Update CarEntity.java with following code − CarEntity.java package com.tutorialspoint.entity; import java.util.GregorianCalendar; public class CarEntity { private int id; private double price; private GregorianCalendar manufacturingDate; public int getId() { return id; } public void setId(int id) { this.id = id; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } public GregorianCalendar getManufacturingDate() { return manufacturingDate; } public void setManufacturingDate(GregorianCalendar manufacturingDate) { this.manufacturingDate = manufacturingDate; } } Update Car.java with following code − Car.java package com.tutorialspoint.model; public class Car { private int id; private String price; private String manufacturingDate; private String brand; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getPrice() { return price; } public void setPrice(String price) { this.price = price; } public String getManufacturingDate() { return manufacturingDate; } public void setManufacturingDate(String manufacturingDate) { this.manufacturingDate = manufacturingDate; } public String getBrand() { return brand; } public void setBrand(String brand) { this.brand = brand; } } Update CarMapper.java with following code − CarMapper.java package com.tutorialspoint.mapper; import org.mapstruct.Mapper; import org.mapstruct.Mapping; import com.tutorialspoint.entity.CarEntity; import com.tutorialspoint.model.Car; @Mapper public interface CarMapper { @Mapping(target = "brand", constant = "BMW") @Mapping(source = "price", target = "price", numberFormat = "$#.00") @Mapping(source = "manufacturingDate", target = "manufacturingDate", dateFormat = "dd.MM.yyyy") Car getModelFromEntity(CarEntity carEntity); } Update CarMapperTest.java with following code − CarMapperTest.java package com.tutorialspoint.mapping; import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.GregorianCalendar; import org.junit.jupiter.api.Test; import org.mapstruct.factory.Mappers; import com.tutorialspoint.entity.CarEntity; import com.tutorialspoint.mapper.CarMapper; import com.tutorialspoint.model.Car; public class CarMapperTest { private CarMapper carMapper = Mappers.getMapper(CarMapper.class); @Test public void testEntityToModel() { CarEntity entity = new CarEntity(); entity.setPrice(345000); entity.setId(1); entity.setManufacturingDate(new GregorianCalendar(2015, 3, 5)); Car model = carMapper.getModelFromEntity(entity); assertEquals(model.getPrice(), "$345000.00"); assertEquals(entity.getId(), model.getId()); assertEquals("05.04.2015", model.getManufacturingDate()); assertEquals("BMW", model.getBrand()); } } Run the following command to test the mappings. mvn clean test Once command is successful. Verify the output. mvn clean test [INFO] Scanning for projects... ... [INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ mapping --- [INFO] Surefire report directory: \mvn\mapping\target\surefire-reports ------------------------------------------------------- T E S T S ------------------------------------------------------- Running com.tutorialspoint.mapping.CarMapperTest Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.035 sec Running com.tutorialspoint.mapping.DeliveryAddressMapperTest Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0 sec Running com.tutorialspoint.mapping.StudentMapperTest Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.001 sec Results : Tests run: 4, Failures: 0, Errors: 0, Skipped: 0 ... Print Add Notes Bookmark this page
[ { "code": null, "e": 2317, "s": 2260, "text": "MapStruct allows to map a constant value to a property. " }, { "code": null, "e": 2378, "s": 2317, "text": "@Mapping(target = \"target-property\", const = \"const-value\")\n" }, { "code": null, "e": 2383, "s": 2378, "text": "Here" }, { "code": null, "e": 2450, "s": 2383, "text": "target-property − the property for which we are doing the mapping." }, { "code": null, "e": 2517, "s": 2450, "text": "target-property − the property for which we are doing the mapping." }, { "code": null, "e": 2583, "s": 2517, "text": "const-value − mapper will map the const-value to target-property." }, { "code": null, "e": 2649, "s": 2583, "text": "const-value − mapper will map the const-value to target-property." }, { "code": null, "e": 2690, "s": 2649, "text": "Following example demonstrates the same." }, { "code": null, "e": 2770, "s": 2690, "text": "Open project mapping as updated in Mapping Using dateFormat chapter in Eclipse." }, { "code": null, "e": 2814, "s": 2770, "text": "Update CarEntity.java with following code −" }, { "code": null, "e": 2829, "s": 2814, "text": "CarEntity.java" }, { "code": null, "e": 3468, "s": 2829, "text": "package com.tutorialspoint.entity;\nimport java.util.GregorianCalendar;\n\npublic class CarEntity {\n private int id;\n private double price;\n private GregorianCalendar manufacturingDate;\n public int getId() {\n return id;\n }\n public void setId(int id) {\n this.id = id;\n }\n public double getPrice() {\n return price;\n }\n public void setPrice(double price) {\n this.price = price;\n }\n public GregorianCalendar getManufacturingDate() {\n return manufacturingDate;\n }\n public void setManufacturingDate(GregorianCalendar manufacturingDate) {\n this.manufacturingDate = manufacturingDate;\n }\n}" }, { "code": null, "e": 3506, "s": 3468, "text": "Update Car.java with following code −" }, { "code": null, "e": 3515, "s": 3506, "text": "Car.java" }, { "code": null, "e": 4229, "s": 3515, "text": "package com.tutorialspoint.model;\n\npublic class Car {\n private int id;\n private String price;\n private String manufacturingDate;\n private String brand;\n public int getId() {\n return id;\n }\n public void setId(int id) {\n this.id = id;\n }\n public String getPrice() {\n return price;\n }\n public void setPrice(String price) {\n this.price = price;\n }\n public String getManufacturingDate() {\n return manufacturingDate;\n }\n public void setManufacturingDate(String manufacturingDate) {\n this.manufacturingDate = manufacturingDate;\n }\n public String getBrand() {\n return brand;\n }\n public void setBrand(String brand) {\n this.brand = brand;\n }\n}" }, { "code": null, "e": 4273, "s": 4229, "text": "Update CarMapper.java with following code −" }, { "code": null, "e": 4288, "s": 4273, "text": "CarMapper.java" }, { "code": null, "e": 4771, "s": 4288, "text": "package com.tutorialspoint.mapper;\n\nimport org.mapstruct.Mapper;\nimport org.mapstruct.Mapping;\nimport com.tutorialspoint.entity.CarEntity;\nimport com.tutorialspoint.model.Car;\n\n@Mapper\npublic interface CarMapper {\n @Mapping(target = \"brand\", constant = \"BMW\")\n @Mapping(source = \"price\", target = \"price\", numberFormat = \"$#.00\")\n @Mapping(source = \"manufacturingDate\", target = \"manufacturingDate\", dateFormat = \"dd.MM.yyyy\")\n Car getModelFromEntity(CarEntity carEntity);\n}" }, { "code": null, "e": 4819, "s": 4771, "text": "Update CarMapperTest.java with following code −" }, { "code": null, "e": 4838, "s": 4819, "text": "CarMapperTest.java" }, { "code": null, "e": 5757, "s": 4838, "text": "package com.tutorialspoint.mapping;\n\nimport static org.junit.jupiter.api.Assertions.assertEquals;\nimport java.util.GregorianCalendar;\nimport org.junit.jupiter.api.Test;\nimport org.mapstruct.factory.Mappers;\nimport com.tutorialspoint.entity.CarEntity;\nimport com.tutorialspoint.mapper.CarMapper;\nimport com.tutorialspoint.model.Car;\n\npublic class CarMapperTest {\n private CarMapper carMapper = Mappers.getMapper(CarMapper.class);\n\n @Test\n public void testEntityToModel() {\n CarEntity entity = new CarEntity();\n entity.setPrice(345000);\n entity.setId(1);\n entity.setManufacturingDate(new GregorianCalendar(2015, 3, 5));\n Car model = carMapper.getModelFromEntity(entity);\n assertEquals(model.getPrice(), \"$345000.00\");\n assertEquals(entity.getId(), model.getId());\n assertEquals(\"05.04.2015\", model.getManufacturingDate());\n assertEquals(\"BMW\", model.getBrand());\n }\n}" }, { "code": null, "e": 5805, "s": 5757, "text": "Run the following command to test the mappings." }, { "code": null, "e": 5821, "s": 5805, "text": "mvn clean test\n" }, { "code": null, "e": 5868, "s": 5821, "text": "Once command is successful. Verify the output." }, { "code": null, "e": 6635, "s": 5868, "text": "mvn clean test\n[INFO] Scanning for projects...\n...\n[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ mapping ---\n[INFO] Surefire report directory: \\mvn\\mapping\\target\\surefire-reports\n\n-------------------------------------------------------\n T E S T S\n-------------------------------------------------------\nRunning com.tutorialspoint.mapping.CarMapperTest\nTests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.035 sec\nRunning com.tutorialspoint.mapping.DeliveryAddressMapperTest\nTests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0 sec\nRunning com.tutorialspoint.mapping.StudentMapperTest\nTests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.001 sec\n\nResults :\n\nTests run: 4, Failures: 0, Errors: 0, Skipped: 0\n...\n" }, { "code": null, "e": 6642, "s": 6635, "text": " Print" }, { "code": null, "e": 6653, "s": 6642, "text": " Add Notes" } ]
HTML - <center> Tag
The HTML <center> tag is used for centering the content enclosed with this tag. This tag is depreciated. <!DOCTYPE html> <html> <head> <title>HTML center Tag</title> </head> <body> <center>This text is centered</center> </body> </html> This will produce the following result − This tag supports all the global attributes described in HTML Attribute Reference This tag supports all the event attributes described in HTML Events Reference 19 Lectures 2 hours Anadi Sharma 16 Lectures 1.5 hours Anadi Sharma 18 Lectures 1.5 hours Frahaan Hussain 57 Lectures 5.5 hours DigiFisk (Programming Is Fun) 54 Lectures 6 hours DigiFisk (Programming Is Fun) 45 Lectures 5.5 hours DigiFisk (Programming Is Fun) Print Add Notes Bookmark this page
[ { "code": null, "e": 2479, "s": 2374, "text": "The HTML <center> tag is used for centering the content enclosed with this tag. This tag is depreciated." }, { "code": null, "e": 2637, "s": 2479, "text": "<!DOCTYPE html>\n<html>\n\n <head>\n <title>HTML center Tag</title>\n </head>\n\n <body>\n <center>This text is centered</center>\n </body>\n\n</html>" }, { "code": null, "e": 2678, "s": 2637, "text": "This will produce the following result −" }, { "code": null, "e": 2760, "s": 2678, "text": "This tag supports all the global attributes described in HTML Attribute Reference" }, { "code": null, "e": 2838, "s": 2760, "text": "This tag supports all the event attributes described in HTML Events Reference" }, { "code": null, "e": 2871, "s": 2838, "text": "\n 19 Lectures \n 2 hours \n" }, { "code": null, "e": 2885, "s": 2871, "text": " Anadi Sharma" }, { "code": null, "e": 2920, "s": 2885, "text": "\n 16 Lectures \n 1.5 hours \n" }, { "code": null, "e": 2934, "s": 2920, "text": " Anadi Sharma" }, { "code": null, "e": 2969, "s": 2934, "text": "\n 18 Lectures \n 1.5 hours \n" }, { "code": null, "e": 2986, "s": 2969, "text": " Frahaan Hussain" }, { "code": null, "e": 3021, "s": 2986, "text": "\n 57 Lectures \n 5.5 hours \n" }, { "code": null, "e": 3052, "s": 3021, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 3085, "s": 3052, "text": "\n 54 Lectures \n 6 hours \n" }, { "code": null, "e": 3116, "s": 3085, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 3151, "s": 3116, "text": "\n 45 Lectures \n 5.5 hours \n" }, { "code": null, "e": 3182, "s": 3151, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 3189, "s": 3182, "text": " Print" }, { "code": null, "e": 3200, "s": 3189, "text": " Add Notes" } ]
Dart Programming - Classes
Dart is an object-oriented language. It supports object-oriented programming features like classes, interfaces, etc. A class in terms of OOP is a blueprint for creating objects. A class encapsulates data for the object. Dart gives built-in support for this concept called class. Use the class keyword to declare a class in Dart. A class definition starts with the keyword class followed by the class name; and the class body enclosed by a pair of curly braces. The syntax for the same is given below − class class_name { <fields> <getters/setters> <constructors> <functions> } The class keyword is followed by the class name. The rules for identifiers must be considered while naming a class. A class definition can include the following − Fields − A field is any variable declared in a class. Fields represent data pertaining to objects. Fields − A field is any variable declared in a class. Fields represent data pertaining to objects. Setters and Getters − Allows the program to initialize and retrieve the values of the fields of a class. A default getter/ setter is associated with every class. However, the default ones can be overridden by explicitly defining a setter/ getter. Setters and Getters − Allows the program to initialize and retrieve the values of the fields of a class. A default getter/ setter is associated with every class. However, the default ones can be overridden by explicitly defining a setter/ getter. Constructors − responsible for allocating memory for the objects of the class. Constructors − responsible for allocating memory for the objects of the class. Functions − Functions represent actions an object can take. They are also at times referred to as methods. Functions − Functions represent actions an object can take. They are also at times referred to as methods. These components put together are termed as the data members of the class. class Car { // field String engine = "E1001"; // function void disp() { print(engine); } } The example declares a class Car. The class has a field named engine. The disp() is a simple function that prints the value of the field engine. To create an instance of the class, use the new keyword followed by the class name. The syntax for the same is given below − var object_name = new class_name([ arguments ]) The new keyword is responsible for instantiation. The new keyword is responsible for instantiation. The right-hand side of the expression invokes the constructor. The constructor should be passed values if it is parameterized. The right-hand side of the expression invokes the constructor. The constructor should be passed values if it is parameterized. var obj = new Car("Engine 1") A class’s attributes and functions can be accessed through the object. Use the ‘.’ dot notation (called as the period) to access the data members of a class. //accessing an attribute obj.field_name //accessing a function obj.function_name() Take a look at the following example to understand how to access attributes and functions in Dart − void main() { Car c= new Car(); c.disp(); } class Car { // field String engine = "E1001"; // function void disp() { print(engine); } } The output of the above code is as follows − E1001 A constructor is a special function of the class that is responsible for initializing the variables of the class. Dart defines a constructor with the same name as that of the class. A constructor is a function and hence can be parameterized. However, unlike a function, constructors cannot have a return type. If you don’t declare a constructor, a default no-argument constructor is provided for you. Class_name(parameter_list) { //constructor body } The following example shows how to use constructors in Dart − void main() { Car c = new Car('E1001'); } class Car { Car(String engine) { print(engine); } } It should produce the following output − E1001 Dart provides named constructors to enable a class define multiple constructors. The syntax of named constructors is as given below − Class_name.constructor_name(param_list) The following example shows how you can use named constructors in Dart − void main() { Car c1 = new Car.namedConst('E1001'); Car c2 = new Car(); } class Car { Car() { print("Non-parameterized constructor invoked"); } Car.namedConst(String engine) { print("The engine is : ${engine}"); } } It should produce the following output − The engine is : E1001 Non-parameterized constructor invoked The this keyword refers to the current instance of the class. Here, the parameter name and the name of the class’s field are the same. Hence to avoid ambiguity, the class’s field is prefixed with the this keyword. The following example explains the same − The following example explains how to use the this keyword in Dart − void main() { Car c1 = new Car('E1001'); } class Car { String engine; Car(String engine) { this.engine = engine; print("The engine is : ${engine}"); } } It should produce the following output − The engine is : E1001 Getters and Setters, also called as accessors and mutators, allow the program to initialize and retrieve the values of class fields respectively. Getters or accessors are defined using the get keyword. Setters or mutators are defined using the set keyword. A default getter/setter is associated with every class. However, the default ones can be overridden by explicitly defining a setter/ getter. A getter has no parameters and returns a value, and the setter has one parameter and does not return a value. Return_type get identifier { } set identifier { } The following example shows how you can use getters and setters in a Dart class − class Student { String name; int age; String get stud_name { return name; } void set stud_name(String name) { this.name = name; } void set stud_age(int age) { if(age<= 0) { print("Age should be greater than 5"); } else { this.age = age; } } int get stud_age { return age; } } void main() { Student s1 = new Student(); s1.stud_name = 'MARK'; s1.stud_age = 0; print(s1.stud_name); print(s1.stud_age); } This program code should produce the following output − Age should be greater than 5 MARK Null Dart supports the concept of Inheritance which is the ability of a program to create new classes from an existing class. The class that is extended to create newer classes is called the parent class/super class. The newly created classes are called the child/sub classes. A class inherits from another class using the ‘extends’ keyword. Child classes inherit all properties and methods except constructors from the parent class. class child_class_name extends parent_class_name Note − Dart doesn’t support multiple inheritance. In the following example, we are declaring a class Shape. The class is extended by the Circle class. Since there is an inheritance relationship between the classes, the child class, i.e., the class Car gets an implicit access to its parent class data member. void main() { var obj = new Circle(); obj.cal_area(); } class Shape { void cal_area() { print("calling calc area defined in the Shape class"); } } class Circle extends Shape {} It should produce the following output − calling calc area defined in the Shape class Inheritance can be of the following three types − Single − Every class can at the most extend from one parent class. Single − Every class can at the most extend from one parent class. Multiple − A class can inherit from multiple classes. Dart doesn’t support multiple inheritance. Multiple − A class can inherit from multiple classes. Dart doesn’t support multiple inheritance. Multi-level − A class can inherit from another child class. Multi-level − A class can inherit from another child class. The following example shows how multi-level inheritance works − void main() { var obj = new Leaf(); obj.str = "hello"; print(obj.str); } class Root { String str; } class Child extends Root {} class Leaf extends Child {} //indirectly inherits from Root by virtue of inheritance The class Leaf derives the attributes from Root and Child classes by virtue of multi-level inheritance. Its output is as follows − hello Method Overriding is a mechanism by which the child class redefines a method in its parent class. The following example illustrates the same − void main() { Child c = new Child(); c.m1(12); } class Parent { void m1(int a){ print("value of a ${a}");} } class Child extends Parent { @override void m1(int b) { print("value of b ${b}"); } } It should produce the following output − value of b 12 The number and type of the function parameters must match while overriding the method. In case of a mismatch in the number of parameters or their data type, the Dart compiler throws an error. The following illustration explains the same − import 'dart:io'; void main() { Child c = new Child(); c.m1(12); } class Parent { void m1(int a){ print("value of a ${a}");} } class Child extends Parent { @override void m1(String b) { print("value of b ${b}"); } } It should produce the following output − value of b 12 The static keyword can be applied to the data members of a class, i.e., fields and methods. A static variable retains its values till the program finishes execution. Static members are referenced by the class name. class StaticMem { static int num; static disp() { print("The value of num is ${StaticMem.num}") ; } } void main() { StaticMem.num = 12; // initialize the static variable } StaticMem.disp(); // invoke the static method } It should produce the following output − The value of num is 12 The super keyword is used to refer to the immediate parent of a class. The keyword can be used to refer to the super class version of a variable, property, or method. The following example illustrates the same − void main() { Child c = new Child(); c.m1(12); } class Parent { String msg = "message variable from the parent class"; void m1(int a){ print("value of a ${a}");} } class Child extends Parent { @override void m1(int b) { print("value of b ${b}"); super.m1(13); print("${super.msg}") ; } } It should produce the following output − value of b 12 value of a 13 message variable from the parent class 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": 2804, "s": 2525, "text": "Dart is an object-oriented language. It supports object-oriented programming features like classes, interfaces, etc. A class in terms of OOP is a blueprint for creating objects. A class encapsulates data for the object. Dart gives built-in support for this concept called class." }, { "code": null, "e": 3027, "s": 2804, "text": "Use the class keyword to declare a class in Dart. A class definition starts with the keyword class followed by the class name; and the class body enclosed by a pair of curly braces. The syntax for the same is given below −" }, { "code": null, "e": 3121, "s": 3027, "text": "class class_name { \n <fields> \n <getters/setters> \n <constructors> \n <functions> \n}\n" }, { "code": null, "e": 3237, "s": 3121, "text": "The class keyword is followed by the class name. The rules for identifiers must be considered while naming a class." }, { "code": null, "e": 3284, "s": 3237, "text": "A class definition can include the following −" }, { "code": null, "e": 3383, "s": 3284, "text": "Fields − A field is any variable declared in a class. Fields represent data pertaining to objects." }, { "code": null, "e": 3482, "s": 3383, "text": "Fields − A field is any variable declared in a class. Fields represent data pertaining to objects." }, { "code": null, "e": 3730, "s": 3482, "text": "Setters and Getters − Allows the program to initialize and retrieve the values of the fields of a class. A default getter/ setter is associated with every class. However, the default ones can be overridden by explicitly defining a setter/ getter." }, { "code": null, "e": 3978, "s": 3730, "text": "Setters and Getters − Allows the program to initialize and retrieve the values of the fields of a class. A default getter/ setter is associated with every class. However, the default ones can be overridden by explicitly defining a setter/ getter." }, { "code": null, "e": 4057, "s": 3978, "text": "Constructors − responsible for allocating memory for the objects of the class." }, { "code": null, "e": 4136, "s": 4057, "text": "Constructors − responsible for allocating memory for the objects of the class." }, { "code": null, "e": 4243, "s": 4136, "text": "Functions − Functions represent actions an object can take. They are also at times referred to as methods." }, { "code": null, "e": 4350, "s": 4243, "text": "Functions − Functions represent actions an object can take. They are also at times referred to as methods." }, { "code": null, "e": 4425, "s": 4350, "text": "These components put together are termed as the data members of the class." }, { "code": null, "e": 4550, "s": 4425, "text": "class Car { \n // field \n String engine = \"E1001\"; \n \n // function \n void disp() { \n print(engine); \n } \n}" }, { "code": null, "e": 4695, "s": 4550, "text": "The example declares a class Car. The class has a field named engine. The disp() is a simple function that prints the value of the field engine." }, { "code": null, "e": 4820, "s": 4695, "text": "To create an instance of the class, use the new keyword followed by the class name. The syntax for the same is given below −" }, { "code": null, "e": 4869, "s": 4820, "text": "var object_name = new class_name([ arguments ])\n" }, { "code": null, "e": 4919, "s": 4869, "text": "The new keyword is responsible for instantiation." }, { "code": null, "e": 4969, "s": 4919, "text": "The new keyword is responsible for instantiation." }, { "code": null, "e": 5096, "s": 4969, "text": "The right-hand side of the expression invokes the constructor. The constructor should be passed values if it is parameterized." }, { "code": null, "e": 5223, "s": 5096, "text": "The right-hand side of the expression invokes the constructor. The constructor should be passed values if it is parameterized." }, { "code": null, "e": 5253, "s": 5223, "text": "var obj = new Car(\"Engine 1\")" }, { "code": null, "e": 5411, "s": 5253, "text": "A class’s attributes and functions can be accessed through the object. Use the ‘.’ dot notation (called as the period) to access the data members of a class." }, { "code": null, "e": 5499, "s": 5411, "text": "//accessing an attribute \nobj.field_name \n\n//accessing a function \nobj.function_name()" }, { "code": null, "e": 5599, "s": 5499, "text": "Take a look at the following example to understand how to access attributes and functions in Dart −" }, { "code": null, "e": 5779, "s": 5599, "text": "void main() { \n Car c= new Car(); \n c.disp(); \n} \nclass Car { \n // field \n String engine = \"E1001\"; \n \n // function \n void disp() { \n print(engine); \n } \n}" }, { "code": null, "e": 5824, "s": 5779, "text": "The output of the above code is as follows −" }, { "code": null, "e": 5831, "s": 5824, "text": "E1001\n" }, { "code": null, "e": 6233, "s": 5831, "text": "A constructor is a special function of the class that is responsible for initializing the variables of the class. Dart defines a constructor with the same name as that of the class. A constructor is a function and hence can be parameterized. However, unlike a function, constructors cannot have a return type. If you don’t declare a constructor, a default no-argument constructor is provided for you." }, { "code": null, "e": 6289, "s": 6233, "text": "Class_name(parameter_list) { \n //constructor body \n}\n" }, { "code": null, "e": 6351, "s": 6289, "text": "The following example shows how to use constructors in Dart −" }, { "code": null, "e": 6467, "s": 6351, "text": "void main() { \n Car c = new Car('E1001'); \n} \nclass Car { \n Car(String engine) { \n print(engine); \n } \n}" }, { "code": null, "e": 6508, "s": 6467, "text": "It should produce the following output −" }, { "code": null, "e": 6516, "s": 6508, "text": "E1001 \n" }, { "code": null, "e": 6650, "s": 6516, "text": "Dart provides named constructors to enable a class define multiple constructors. The syntax of named constructors is as given below −" }, { "code": null, "e": 6691, "s": 6650, "text": "Class_name.constructor_name(param_list)\n" }, { "code": null, "e": 6764, "s": 6691, "text": "The following example shows how you can use named constructors in Dart −" }, { "code": null, "e": 7189, "s": 6764, "text": "void main() { \n Car c1 = new Car.namedConst('E1001'); \n Car c2 = new Car(); \n} \nclass Car { \n Car() { \n print(\"Non-parameterized constructor invoked\");\n } \n Car.namedConst(String engine) { \n print(\"The engine is : ${engine}\"); \n } \n}" }, { "code": null, "e": 7230, "s": 7189, "text": "It should produce the following output −" }, { "code": null, "e": 7292, "s": 7230, "text": "The engine is : E1001 \nNon-parameterized constructor invoked\n" }, { "code": null, "e": 7548, "s": 7292, "text": "The this keyword refers to the current instance of the class. Here, the parameter name and the name of the class’s field are the same. Hence to avoid ambiguity, the class’s field is prefixed with the this keyword. The following example explains the same −" }, { "code": null, "e": 7617, "s": 7548, "text": "The following example explains how to use the this keyword in Dart −" }, { "code": null, "e": 7805, "s": 7617, "text": "void main() { \n Car c1 = new Car('E1001'); \n} \nclass Car { \n String engine; \n Car(String engine) { \n this.engine = engine; \n print(\"The engine is : ${engine}\"); \n } \n} " }, { "code": null, "e": 7846, "s": 7805, "text": "It should produce the following output −" }, { "code": null, "e": 7869, "s": 7846, "text": "The engine is : E1001\n" }, { "code": null, "e": 8127, "s": 7869, "text": "Getters and Setters, also called as accessors and mutators, allow the program to initialize and retrieve the values of class fields respectively. Getters or accessors are defined using the get keyword. Setters or mutators are defined using the set keyword." }, { "code": null, "e": 8379, "s": 8127, "text": "A default getter/setter is associated with every class. However, the default ones can be overridden by explicitly defining a setter/ getter. A getter has no parameters and returns a value, and the setter has one parameter and does not return a value." }, { "code": null, "e": 8415, "s": 8379, "text": "Return_type get identifier \n{ \n} \n" }, { "code": null, "e": 8437, "s": 8415, "text": "set identifier \n{ \n}\n" }, { "code": null, "e": 8519, "s": 8437, "text": "The following example shows how you can use getters and setters in a Dart class −" }, { "code": null, "e": 9069, "s": 8519, "text": "class Student { \n String name; \n int age; \n \n String get stud_name { \n return name; \n } \n \n void set stud_name(String name) { \n this.name = name; \n } \n \n void set stud_age(int age) { \n if(age<= 0) { \n print(\"Age should be greater than 5\"); \n } else { \n this.age = age; \n } \n } \n \n int get stud_age { \n return age; \n } \n} \nvoid main() { \n Student s1 = new Student(); \n s1.stud_name = 'MARK'; \n s1.stud_age = 0; \n print(s1.stud_name); \n print(s1.stud_age); \n} " }, { "code": null, "e": 9125, "s": 9069, "text": "This program code should produce the following output −" }, { "code": null, "e": 9168, "s": 9125, "text": "Age should be greater than 5 \nMARK \nNull \n" }, { "code": null, "e": 9440, "s": 9168, "text": "Dart supports the concept of Inheritance which is the ability of a program to create new classes from an existing class. The class that is extended to create newer classes is called the parent class/super class. The newly created classes are called the child/sub classes." }, { "code": null, "e": 9597, "s": 9440, "text": "A class inherits from another class using the ‘extends’ keyword. Child classes inherit all properties and methods except constructors from the parent class." }, { "code": null, "e": 9648, "s": 9597, "text": "class child_class_name extends parent_class_name \n" }, { "code": null, "e": 9698, "s": 9648, "text": "Note − Dart doesn’t support multiple inheritance." }, { "code": null, "e": 9957, "s": 9698, "text": "In the following example, we are declaring a class Shape. The class is extended by the Circle class. Since there is an inheritance relationship between the classes, the child class, i.e., the class Car gets an implicit access to its parent class data member." }, { "code": null, "e": 10163, "s": 9957, "text": "void main() { \n var obj = new Circle(); \n obj.cal_area(); \n} \nclass Shape { \n void cal_area() { \n print(\"calling calc area defined in the Shape class\"); \n } \n} \nclass Circle extends Shape {}" }, { "code": null, "e": 10204, "s": 10163, "text": "It should produce the following output −" }, { "code": null, "e": 10250, "s": 10204, "text": "calling calc area defined in the Shape class\n" }, { "code": null, "e": 10300, "s": 10250, "text": "Inheritance can be of the following three types −" }, { "code": null, "e": 10367, "s": 10300, "text": "Single − Every class can at the most extend from one parent class." }, { "code": null, "e": 10434, "s": 10367, "text": "Single − Every class can at the most extend from one parent class." }, { "code": null, "e": 10531, "s": 10434, "text": "Multiple − A class can inherit from multiple classes. Dart doesn’t support multiple inheritance." }, { "code": null, "e": 10628, "s": 10531, "text": "Multiple − A class can inherit from multiple classes. Dart doesn’t support multiple inheritance." }, { "code": null, "e": 10688, "s": 10628, "text": "Multi-level − A class can inherit from another child class." }, { "code": null, "e": 10748, "s": 10688, "text": "Multi-level − A class can inherit from another child class." }, { "code": null, "e": 10812, "s": 10748, "text": "The following example shows how multi-level inheritance works −" }, { "code": null, "e": 11051, "s": 10812, "text": "void main() { \n var obj = new Leaf(); \n obj.str = \"hello\"; \n print(obj.str); \n} \nclass Root { \n String str; \n} \nclass Child extends Root {} \nclass Leaf extends Child {} \n//indirectly inherits from Root by virtue of inheritance" }, { "code": null, "e": 11182, "s": 11051, "text": "The class Leaf derives the attributes from Root and Child classes by virtue of multi-level inheritance. Its output is as follows −" }, { "code": null, "e": 11189, "s": 11182, "text": "hello\n" }, { "code": null, "e": 11332, "s": 11189, "text": "Method Overriding is a mechanism by which the child class redefines a method in its parent class. The following example illustrates the same −" }, { "code": null, "e": 11564, "s": 11332, "text": "void main() { \n Child c = new Child(); \n c.m1(12); \n} \nclass Parent { \n void m1(int a){ print(\"value of a ${a}\");} \n} \nclass Child extends Parent { \n @override \n void m1(int b) { \n print(\"value of b ${b}\"); \n } \n}" }, { "code": null, "e": 11605, "s": 11564, "text": "It should produce the following output −" }, { "code": null, "e": 11620, "s": 11605, "text": "value of b 12\n" }, { "code": null, "e": 11859, "s": 11620, "text": "The number and type of the function parameters must match while overriding the method. In case of a mismatch in the number of parameters or their data type, the Dart compiler throws an error. The following illustration explains the same −" }, { "code": null, "e": 12111, "s": 11859, "text": "import 'dart:io'; \nvoid main() { \n Child c = new Child(); \n c.m1(12); \n} \nclass Parent { \n void m1(int a){ print(\"value of a ${a}\");} \n} \nclass Child extends Parent { \n @override \n void m1(String b) { \n print(\"value of b ${b}\");\n } \n}" }, { "code": null, "e": 12152, "s": 12111, "text": "It should produce the following output −" }, { "code": null, "e": 12167, "s": 12152, "text": "value of b 12\n" }, { "code": null, "e": 12382, "s": 12167, "text": "The static keyword can be applied to the data members of a class, i.e., fields and methods. A static variable retains its values till the program finishes execution. Static members are referenced by the class name." }, { "code": null, "e": 12646, "s": 12382, "text": "class StaticMem { \n static int num; \n static disp() { \n print(\"The value of num is ${StaticMem.num}\") ; \n } \n} \nvoid main() { \n StaticMem.num = 12; \n // initialize the static variable } \n StaticMem.disp(); \n // invoke the static method \n}" }, { "code": null, "e": 12687, "s": 12646, "text": "It should produce the following output −" }, { "code": null, "e": 12711, "s": 12687, "text": "The value of num is 12\n" }, { "code": null, "e": 12923, "s": 12711, "text": "The super keyword is used to refer to the immediate parent of a class. The keyword can be used to refer to the super class version of a variable, property, or method. The following example illustrates the same −" }, { "code": null, "e": 13267, "s": 12923, "text": "void main() { \n Child c = new Child(); \n c.m1(12); \n} \nclass Parent { \n String msg = \"message variable from the parent class\"; \n void m1(int a){ print(\"value of a ${a}\");} \n} \nclass Child extends Parent { \n @override \n void m1(int b) { \n print(\"value of b ${b}\"); \n super.m1(13); \n print(\"${super.msg}\") ; \n } \n}" }, { "code": null, "e": 13308, "s": 13267, "text": "It should produce the following output −" }, { "code": null, "e": 13378, "s": 13308, "text": "value of b 12 \nvalue of a 13 \nmessage variable from the parent class\n" }, { "code": null, "e": 13413, "s": 13378, "text": "\n 44 Lectures \n 4.5 hours \n" }, { "code": null, "e": 13433, "s": 13413, "text": " Sriyank Siddhartha" }, { "code": null, "e": 13466, "s": 13433, "text": "\n 34 Lectures \n 4 hours \n" }, { "code": null, "e": 13486, "s": 13466, "text": " Sriyank Siddhartha" }, { "code": null, "e": 13519, "s": 13486, "text": "\n 69 Lectures \n 4 hours \n" }, { "code": null, "e": 13536, "s": 13519, "text": " Frahaan Hussain" }, { "code": null, "e": 13571, "s": 13536, "text": "\n 117 Lectures \n 10 hours \n" }, { "code": null, "e": 13588, "s": 13571, "text": " Frahaan Hussain" }, { "code": null, "e": 13623, "s": 13588, "text": "\n 22 Lectures \n 1.5 hours \n" }, { "code": null, "e": 13643, "s": 13623, "text": " Pranjal Srivastava" }, { "code": null, "e": 13676, "s": 13643, "text": "\n 34 Lectures \n 3 hours \n" }, { "code": null, "e": 13696, "s": 13676, "text": " Pranjal Srivastava" }, { "code": null, "e": 13703, "s": 13696, "text": " Print" }, { "code": null, "e": 13714, "s": 13703, "text": " Add Notes" } ]
Calculate average value in MongoDB
To calculate average value in MongoDB, use aggregate() along with $avg. Let us create a collection with documents − > db.demo159.insertOne({"Score":50}); { "acknowledged" : true, "insertedId" : ObjectId("5e3557b2fdf09dd6d0853a01") } > db.demo159.insertOne({"Score":70}); { "acknowledged" : true, "insertedId" : ObjectId("5e3557b6fdf09dd6d0853a02") } > db.demo159.insertOne({"Score":60}); { "acknowledged" : true, "insertedId" : ObjectId("5e3557c4fdf09dd6d0853a03") } Display all documents from a collection with the help of find() method − > db.demo159.find(); This will produce the following output − { "_id" : ObjectId("5e3557b2fdf09dd6d0853a01"), "Score" : 50 } { "_id" : ObjectId("5e3557b6fdf09dd6d0853a02"), "Score" : 70 } { "_id" : ObjectId("5e3557c4fdf09dd6d0853a03"), "Score" : 60 } Following is the query to calculate $avg value − > db.demo159.aggregate([{$group: {_id:null, AverageValue: {$avg:"$Score"} } }]) This will produce the following output − { "_id" : null, "AverageValue" : 60 }
[ { "code": null, "e": 1178, "s": 1062, "text": "To calculate average value in MongoDB, use aggregate() along with $avg. Let us create a collection with documents −" }, { "code": null, "e": 1547, "s": 1178, "text": "> db.demo159.insertOne({\"Score\":50});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e3557b2fdf09dd6d0853a01\")\n}\n> db.demo159.insertOne({\"Score\":70});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e3557b6fdf09dd6d0853a02\")\n}\n> db.demo159.insertOne({\"Score\":60});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e3557c4fdf09dd6d0853a03\")\n}" }, { "code": null, "e": 1620, "s": 1547, "text": "Display all documents from a collection with the help of find() method −" }, { "code": null, "e": 1641, "s": 1620, "text": "> db.demo159.find();" }, { "code": null, "e": 1682, "s": 1641, "text": "This will produce the following output −" }, { "code": null, "e": 1871, "s": 1682, "text": "{ \"_id\" : ObjectId(\"5e3557b2fdf09dd6d0853a01\"), \"Score\" : 50 }\n{ \"_id\" : ObjectId(\"5e3557b6fdf09dd6d0853a02\"), \"Score\" : 70 }\n{ \"_id\" : ObjectId(\"5e3557c4fdf09dd6d0853a03\"), \"Score\" : 60 }" }, { "code": null, "e": 1920, "s": 1871, "text": "Following is the query to calculate $avg value −" }, { "code": null, "e": 2000, "s": 1920, "text": "> db.demo159.aggregate([{$group: {_id:null, AverageValue: {$avg:\"$Score\"} } }])" }, { "code": null, "e": 2041, "s": 2000, "text": "This will produce the following output −" }, { "code": null, "e": 2079, "s": 2041, "text": "{ \"_id\" : null, \"AverageValue\" : 60 }" } ]
How can I set the location of minor ticks in Matplotlib?
To set the location of the minor ticks in Matplotlib, we can take the following steps − Set the figure size and adjust the padding between and around the subplots. Create x and y data points using numpy. Create a figure and a set of subplots. Plot x and y data points using plot() method. To locate minor ticks, use set_minor_locator() method. To show the minor ticks, use grid(which='minor'). To display the figure, use show() method. import matplotlib.pyplot as plt import numpy as np from matplotlib.ticker import AutoMinorLocator plt.rcParams["figure.figsize"] = [7.50, 3.50] plt.rcParams["figure.autolayout"] = True x = np.linspace(1, 10, 100) y = np.log(x) fig, ax = plt.subplots() ax.plot(x, y) minor_locator = AutoMinorLocator(2) ax.xaxis.set_minor_locator(minor_locator) plt.grid(which='minor') plt.show()
[ { "code": null, "e": 1150, "s": 1062, "text": "To set the location of the minor ticks in Matplotlib, we can take the following steps −" }, { "code": null, "e": 1226, "s": 1150, "text": "Set the figure size and adjust the padding between and around the subplots." }, { "code": null, "e": 1266, "s": 1226, "text": "Create x and y data points using numpy." }, { "code": null, "e": 1305, "s": 1266, "text": "Create a figure and a set of subplots." }, { "code": null, "e": 1351, "s": 1305, "text": "Plot x and y data points using plot() method." }, { "code": null, "e": 1406, "s": 1351, "text": "To locate minor ticks, use set_minor_locator() method." }, { "code": null, "e": 1456, "s": 1406, "text": "To show the minor ticks, use grid(which='minor')." }, { "code": null, "e": 1498, "s": 1456, "text": "To display the figure, use show() method." }, { "code": null, "e": 1881, "s": 1498, "text": "import matplotlib.pyplot as plt\nimport numpy as np\nfrom matplotlib.ticker import AutoMinorLocator\n\nplt.rcParams[\"figure.figsize\"] = [7.50, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\n\nx = np.linspace(1, 10, 100)\ny = np.log(x)\n\nfig, ax = plt.subplots()\nax.plot(x, y)\nminor_locator = AutoMinorLocator(2)\nax.xaxis.set_minor_locator(minor_locator)\nplt.grid(which='minor')\n\nplt.show()" } ]
Copying files from Docker container to Host
We can use the Docker build command to build Docker images using a build context. The build context contains all the files which are required to create your containerized application environment. This includes the Dockerfile to build the Docker images, source code of the application, Dockerignore files, all the files, and directories that you want to be there beforehand in the container when you run it. However, it often happens that you might want to copy some files from the container to the host machine. For example, if you are working on an application inside a Docker container and you have generated some log files or outputs inside the container. You might want to share the results with your team. In such a case, you will have to get access to those files from the container to the host machine. There are two ways to do this. The first one is to mount directories in your host machine as volumes. However, for sharing simple files or directories, it might be unnecessary to create volumes. The second method is by using the Docker cp command to copy files from Docker containers to the host machine. Let’s discuss how to do so. We can use the Docker cp command to copy files and directories from the source path to the target path. We can use this command to copy files from local machines to Docker containers and vice-versa. The container which is involved in this process can be both stopped or running. By default, the Docker cp command will assume that all the paths mentioned inside the container are relative to the container’s root directory (/). This means that even if we don’t supply a forward slash, it is optional. Hence, the paths /user/app/folder1 and user/app/folder1 are identical. However, the paths that we specify for local machines can be both relative as well as absolute. The path in the host machine is relative to the current working directory. We can specify both paths for both files and directories in the source and destination paths. The syntax of the Docker cp command to copy files from Docker containers to host machines is - $ docker cp [OPTIONS] CONTAINER:SRC_PATH DEST_PATH|- Please note that we are not allowed to copy some sensitive files such as system files. These include resources under /dev, /proc, /sys, tmpfs, and certain mounts in the container that are created by the user. A workaround to this is by manually executing tar commands inside Docker containers using the Docker exec command. Let’s check out an example to create a file inside a Docker container, include some content in it, and copy it into the host machine using the Docker cp command. First, let’s create an Ubuntu container and access its bash. $ docker run -it --name=myubuntu ubuntu bash In the above command, we have used the Docker run command to pull and run an Ubuntu container. We have used the i (interactive) and t (pseudo-TTY) options along with the Docker run command to access the container in interactive mode. Next, we have specified the image name and the command that we need to run, which is the bash command, since we want access to the container environment. Now that we have access to the container’s bash, we can use the echo command to create a file with some content inside the container. # echo "Welcome to TutorialsPoint" > TutorialsPoint.txt You can verify the creation of the file by listing the files and using the cat command to list the contents. # ls # cat TutorialsPoint.txt Now, open another terminal. You can either keep this container running or exit from it. In the new terminal, let’s execute the Docker cp command to copy the TutorialsPoint.txt file from the ubuntu container to the host machine. $ docker cp myubuntu:TutorialsPoint.txt /home/user/Desktop/ In the above Docker cp command, we have specified the name of the container and the path of the file inside the container separated by a colon. We have also specified the destination path inside the host machine. After executing this command, the file will be copied to the destination path. There are several methods to copy files from Docker containers to host machines. You can use mounted volumes, save the image as tarball files, and various other techniques. But if you want to copy small files or directories, the best possible way is to use the Docker cp command. It’s quite fast and easy to use. Except for some important system files, you can copy any file or directory from the container. In this article, we discussed how to use the Docker cp command to do so along with it’s syntax and a complete end-to-end example.
[ { "code": null, "e": 1469, "s": 1062, "text": "We can use the Docker build command to build Docker images using a build context. The build context contains all the files which are required to create your containerized application environment. This includes the Dockerfile to build the Docker images, source code of the application, Dockerignore files, all the files, and directories that you want to be there beforehand in the container when you run it." }, { "code": null, "e": 1872, "s": 1469, "text": "However, it often happens that you might want to copy some files from the container to the host machine. For example, if you are working on an application inside a Docker container and you have generated some log files or outputs inside the container. You might want to share the results with your team. In such a case, you will have to get access to those files from the container to the host machine." }, { "code": null, "e": 2205, "s": 1872, "text": "There are two ways to do this. The first one is to mount directories in your host machine as volumes. However, for sharing simple files or directories, it might be unnecessary to create volumes. The second method is by using the Docker cp command to copy files from Docker containers to the host machine. Let’s discuss how to do so." }, { "code": null, "e": 2632, "s": 2205, "text": "We can use the Docker cp command to copy files and directories from the source path to the target path. We can use this command to copy files from local machines to Docker containers and vice-versa. The container which is involved in this process can be both stopped or running. By default, the Docker cp command will assume that all the paths mentioned inside the container are relative to the container’s root directory (/)." }, { "code": null, "e": 2947, "s": 2632, "text": "This means that even if we don’t supply a forward slash, it is optional. Hence, the paths /user/app/folder1 and user/app/folder1 are identical. However, the paths that we specify for local machines can be both relative as well as absolute. The path in the host machine is relative to the current working directory." }, { "code": null, "e": 3136, "s": 2947, "text": "We can specify both paths for both files and directories in the source and destination paths. The syntax of the Docker cp command to copy files from Docker containers to host machines is -" }, { "code": null, "e": 3189, "s": 3136, "text": "$ docker cp [OPTIONS] CONTAINER:SRC_PATH DEST_PATH|-" }, { "code": null, "e": 3513, "s": 3189, "text": "Please note that we are not allowed to copy some sensitive files such as system files. These include resources under /dev, /proc, /sys, tmpfs, and certain mounts in the container that are created by the user. A workaround to this is by manually executing tar commands inside Docker containers using the Docker exec command." }, { "code": null, "e": 3675, "s": 3513, "text": "Let’s check out an example to create a file inside a Docker container, include some content in it, and copy it into the host machine using the Docker cp command." }, { "code": null, "e": 3736, "s": 3675, "text": "First, let’s create an Ubuntu container and access its bash." }, { "code": null, "e": 3781, "s": 3736, "text": "$ docker run -it --name=myubuntu ubuntu bash" }, { "code": null, "e": 4169, "s": 3781, "text": "In the above command, we have used the Docker run command to pull and run an Ubuntu container. We have used the i (interactive) and t (pseudo-TTY) options along with the Docker run command to access the container in interactive mode. Next, we have specified the image name and the command that we need to run, which is the bash command, since we want access to the container environment." }, { "code": null, "e": 4303, "s": 4169, "text": "Now that we have access to the container’s bash, we can use the echo command to create a file with some content inside the container." }, { "code": null, "e": 4359, "s": 4303, "text": "# echo \"Welcome to TutorialsPoint\" > TutorialsPoint.txt" }, { "code": null, "e": 4468, "s": 4359, "text": "You can verify the creation of the file by listing the files and using the cat command to list the contents." }, { "code": null, "e": 4498, "s": 4468, "text": "# ls\n# cat TutorialsPoint.txt" }, { "code": null, "e": 4726, "s": 4498, "text": "Now, open another terminal. You can either keep this container running or exit from it. In the new terminal, let’s execute the Docker cp command to copy the TutorialsPoint.txt file from the ubuntu container to the host machine." }, { "code": null, "e": 4786, "s": 4726, "text": "$ docker cp myubuntu:TutorialsPoint.txt /home/user/Desktop/" }, { "code": null, "e": 5078, "s": 4786, "text": "In the above Docker cp command, we have specified the name of the container and the path of the file inside the container separated by a colon. We have also specified the destination path inside the host machine. After executing this command, the file will be copied to the destination path." }, { "code": null, "e": 5486, "s": 5078, "text": "There are several methods to copy files from Docker containers to host machines. You can use mounted volumes, save the image as tarball files, and various other techniques. But if you want to copy small files or directories, the best possible way is to use the Docker cp command. It’s quite fast and easy to use. Except for some important system files, you can copy any file or directory from the container." }, { "code": null, "e": 5616, "s": 5486, "text": "In this article, we discussed how to use the Docker cp command to do so along with it’s syntax and a complete end-to-end example." } ]
Building Dashboards using Dash (< 200 lines of code) | by Rishav Agarwal | Towards Data Science
Dashboards are user interfaces (UIs) that visualize data in an organized manner. Business dashboards usually contain information around Key Performance Indicators (KPIs) related to particular objectives or business processes. A dashboard is a “snapshot” report that allows us to display data at a given instant of time in a meaningful manner with the aid of charts for easy reference and quick inference. Some attributes of a useful dashboard are: Customizable: An excellent dashboarding tool must allow users to customize according to need. Accessible: Should be available in a variety of media formats like web, mobile etc. for viewing on the go. Scalable: Should have the ability to add/change KPIs and add/change data sources. Dashboards nowadays come in various shapes and sizes. Many companies roll out ready-made dashboarding services as SaaS. This software usually has workspaces where one can drag and drop data columns and KPIs. One of the most important dashboarding tools is Tabealu, which is self-contained software that allows users to build robust dashboards. However, if one might want to build their dashboarding tool, one would have to learn many technologies for visualization, database management and scripting. Below is a brief overview of some of the technologies involved (note this is not exhaustive): Components of a dashboard Technologies Visualization D3, React JavaScriptDatabase Management SQL, AWS, MongoDBScripting R-shiny, Python, Java, Cpp Visualization D3, React JavaScript Database Management SQL, AWS, MongoDB Scripting R-shiny, Python, Java, Cpp Using Python, we have several options at our disposal: Dash: Dash is a powerful open-source library that helps build interactive and live web-based dashboards using Plotly, Flask and React. Jupyter Dashboards: The dashboards layout extension is an add-on for Jupyter Notebook. It lets the user arrange notebook outputs in a grid or report like the format and saves this layout. The extension is required to be installed by other users to view this report. Pyxley: Pyxlex is another excellent option for building dashboards. It leverages React and Flask. However, the support and documentation for this are limited. Bokeh: A web dashboard tool that employs D3 and Tornado may require some knowledge of JavaScript. Few more: Bowtie, Spyre, Superset We go with Dash because: Easy to use: Built on Plotly and React, so it is straightforward to code and has many widgets available. All you need to know is Python; no need to learn React or D3. However, if you know React, then Dash allows you to plug into React’s extensive ecosystem through an included toolset that packages React components into Dash-useable components. Documentation: Dash is well documented and has a great and responsive community on Stack Overflow and Github. Most UIs follow an MVC framework, by MVC, we mean Model-View-Controller. Each interconnected component is built to take on a specific task in the development process. Model: The model is the heart of the dashboard. The model gets the data from the database, manipulates it and stores it in objects which can later be consumed by the view. Controller: Controller is how the user interacts with the dashboard. It usually requests the data from the model and presents it to the view. View: The view is where data is present to the user or the frontend. A view oversees the visual part of the dashboard. The MVC framework reduces the application’s complexity and makes it easier to maintain; for example, the developer can choose to change the UI without needing to change any backed code. We will look at Dash from an MVC perspective for more fundamental understanding. As mentioned earlier, Dash is a simple Python tool that helps us build beautiful and responsive web dashboards quickly. It has support for both R and Python and is maintained by Plotly. It uses React for the Controller and View, and Plotly and Flask, for the Model in our MVC setting. We build a flask application that creates a dashboard on a web browser, which can call the backend to re-render certain parts of the web page. Dash and Plotly can be installed very easily using pip. Using a virtual environment manager (like Conda) is recommended. pip install dash==0.26.3 # The core dash backendpip install dash-renderer==0.13.2 # The dash front-endpip install dash-html-components==0.11.0 # HTML componentspip install dash-core-components==0.28.1 # Supercharged componentspip install dash_table_experiments #for tablespip install plotly --upgrade # Plotly graphing library For the data manipulation, we install pandas. pip install pandas Please check the dash installation guide to get the latest version of these tools. Now we move to the problem statement. In a previous post, we had talked about building our own data set using Scrapy, that taught us how to use web scraping to download data. We had downloaded the top 500 albums of all time from the Metacritic.com library. Here is a snapshot of the dataset: We see that we have a genre, artist, release date, meta-score and the user score for each album. We will build a dashboard that has the following four components: Interactive Bubble chart of genresHistogram of decade popularity of each genre (bar chart)Meta-score/User-score trends (line chart)Table of the top 10 most popular artist by meta score/user score Interactive Bubble chart of genres Histogram of decade popularity of each genre (bar chart) Meta-score/User-score trends (line chart) Table of the top 10 most popular artist by meta score/user score User can interact with the bar table with a drop-down to get top 10 artists by average meta score or average user score. User can also interact with the bubble chart; on hover, it will change the bar chart to give the number of albums of that genre published in each decade. It is a good practice to build a small mock-up of the dashboard on paper or using a software (Adobe Illustrator and Balsamiq are great tools used by professionals). Here we have used MS PowerPoint to build a simple static view. We will divide our dash component into three parts: Data Manipulation (Model): Perform operation to read data from file and manipulate data for displayDashboard Layout (View): Visually render data on the web pageInteraction Between Components (Controller): Convert user input to commands for data manipulation and re-render. Data Manipulation (Model): Perform operation to read data from file and manipulate data for display Dashboard Layout (View): Visually render data on the web page Interaction Between Components (Controller): Convert user input to commands for data manipulation and re-render. Here we import the relevant libraries. import dashimport dash_core_components as dccimport dash_html_components as htmlimport dash_table_experiments as dtimport pandas as pdimport plotly.graph_objs as gofrom dash.dependencies import Input, Output, State, Eventimport random Here we have the data in a csv so we can simply import it using pandas. However, if the data is in a SQLdatabase or on a server somewhere we need to make a data connection that connects data to a pandas dataframe in our backend and the rest of the process will be the same. We assume that the reader has a basic knowledge about pandas and can understand the data manipulation. Basically, we are creating 4 major tables for each of the dashboard components: df_linechart: This table groups the data by year and gives us the number of albums, average meta-score and average user score. We also multiply user score by 10 to get it on the same scale as meta-score. This will be used to draw the Score trends graph.df_table: This table groups the data by artist and gives us the number of albums, total meta-score and total user score. The generate_table function uses this table to get the top 10 rows sorted by user score or meta score. This is used to draw the table.df_bubble: This table groups the data by genre, and gives us the number of albums, mean meta-score and mean users score. The number of albums becomes the size of our bubble and the mean scores become the axes. This is used to draw the bubble chart.df2_decade: This table groups the data by genre and decade and returns the number of albums for each genre in each decade. This is used to draw the bar chart. df_linechart: This table groups the data by year and gives us the number of albums, average meta-score and average user score. We also multiply user score by 10 to get it on the same scale as meta-score. This will be used to draw the Score trends graph. df_table: This table groups the data by artist and gives us the number of albums, total meta-score and total user score. The generate_table function uses this table to get the top 10 rows sorted by user score or meta score. This is used to draw the table. df_bubble: This table groups the data by genre, and gives us the number of albums, mean meta-score and mean users score. The number of albums becomes the size of our bubble and the mean scores become the axes. This is used to draw the bubble chart. df2_decade: This table groups the data by genre and decade and returns the number of albums for each genre in each decade. This is used to draw the bar chart. ###############################################################DATA MANIPULATION (model)##############################################################df= pd.read_csv("top500_albums_clean.csv")df['userscore'] = df['userscore'].astype(float)df['metascore'] = df['metascore'].astype(float)df['releasedate']=pd.to_datetime(df['releasedate'], format='%b %d, %Y')df['year']=df["releasedate"].dt.yeardf['decade']=(df["year"]//10)*10#cleaning Genredf['genre'] = df['genre'].str.strip()df['genre'] = df['genre'].str.replace("/", ",")df['genre'] = df['genre'].str.split(",")#year trenddf_linechart= df.groupby('year') .agg({'album':'size', 'metascore':'mean', 'userscore':'mean'}) .sort_values(['year'], ascending=[True]).reset_index()df_linechart.userscore=df_linechart.userscore*10#tabledf_table= df.groupby('artist').agg({'album':'size', 'metascore':'sum', 'userscore':'sum'})#genrebubbledf2=(df['genre'].apply(lambda x: pd.Series(x)) .stack().reset_index(level=1, drop=True).to_frame('genre').join(df[['year', 'decade', 'userscore', 'metascore']], how='left') )df_bubble= df2.groupby('genre') .agg({'year':'size', 'metascore':'mean', 'userscore':'mean'}) .sort_values(['year'], ascending=[False]).reset_index().head(15)df2_decade=df2.groupby(['genre', 'decade']).agg({'year':'size'}) .sort_values(['decade'], ascending=[False]).reset_index() The layout determines how the dashboard would look after deployment. Dash provides Python classes for all the components. The components are saved in the dash_core_components and the dash_html_components library. One can also build their own components with JavaScript and React. We use a Bootstrap layout for our dashboard. Simply, Bootstrap standardizes the position of the components by containing them in a grid. It divides the screen into 12 columns and we can define as many rows as we like. So our dashboard will look like: Row Column-12 (title)Row Column-6 (Table of most top 10 popular artist) Column-6 (Meta-score/User-score trends- line chart)Row Column-6 (Interactive Bubble chart of genres) Column-6 (Histogram of decade popularity (bar chart) Here is another visualization of the mock-up: We can add custom CSS, to our dashboard by using .append.css command. app = dash.Dash()app.css.append_css({"external_url": " https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"}) We also append the require JavaScript libraries for Bootstrap. Please refer to the Bootstrap page for latest versions: # Bootstrap Javascript.app.scripts.append_script({"external_url": "https://code.jquery.com/jquery-3.2.1.slim.min.js"})app.scripts.append_script({"external_url": "https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"}) The layout skeleton can be defined as html.Div( [ SOME_DASH_OR_HTML_COMPONENT( id, content (data), style (a dictionary with the properties)) ], className (name of the Bootstrap Class) ) the classname will be the Bootstrap class name which can be row or columns. Dash makes it very easy to draw graphs thanks to the core components. We can use functions to draw components or we can write the code inline. Adding table We can either use the html.Table tag or import Plotly tables. Here we’re using a html native table. def generate_table(dataframe, max_rows=10):'''Given dataframe, return template generated using Dash components'''return html.Table(# Header[html.Tr([html.Th(col) for col in dataframe.columns])] +# Body[html.Tr([ html.Td(dataframe.iloc[i][col]) for col in dataframe.columns]) for i in range(min(len(dataframe), max_rows))],style={'width': '100%', 'display': 'inline-block', 'vertical-align': 'middle'}) Simply, the function takes a pandas dataframe and coerces it to a table. Graphs Dash uses the Plotly graph layout. We define a graph inside a dcc.Graph component and define the graph inside a figure object (defined as go). In this figure object we set the data, the style and layout. Each type of graph will have different relevant components to it. We discuss three types of graphs here: Adding Line Graph For the line graph we have to choose the Scatter type of graph with go.Scatter and in mode we define lines as shown below. We also need to define the data for x and y for each line. In the layout section we can choose to display the legends, title and other style elements. html.Div([ #Line Chartdcc.Graph(id='line-graph',figure=go.Figure( data = [ go.Scatter( x = df_linechart.year, y = df_linechart.userscore, mode = 'lines', name = 'user score' ), go.Scatter( x = df_linechart.year, y = df_linechart.metascore, mode = 'lines', name = 'meta score' ), ], layout=go.Layout(title="Score trends"))),], className = "col-md-6" Adding bubble chart Similarly, for a bubble chart, we define a go.Scatter but use mode = markers. We can also define a text component that gives the text on hovering over the marker. Later in our dynamic view will use this text to fill our fourth bar graph of “Decade Popularity”. Markers are the points or bubbles on the graph, we can further customize the markers by passing a dictionary object with various options: Color: A list of colors to be used for the markers, can be names of colors or a list of numbers for a color scale. Here I have passes a random list of numbers between 0 and 100. Size: Size specifies the size of the bubble. Here we put the number of albums as the size. So a genre with more number of albums will have a larger bubble. With size we can further customize the size by passing the sizemode, sizeref and sizemin components. html.Div([dcc.Graph(id='bubble-chart', figure=go.Figure( data=[ go.Scatter( x=df_bubble.userscore, y=df_bubble.metascore, mode='markers', text=df_bubble.genre, marker=dict( color= random.sample(range(1,200),15), size=df_bubble.year, sizemode='area', sizeref=2.*max(df_bubble.year)/(40.**2), sizemin=4))],layout=go.Layout(title="Genre poularity")))], className = "col-md-6"), Adding Bar Chart Lastly, we draw a bar chart using a function. Note we could have directly pasted this part in the html div but since we want this graph to be interactive we use a function that can be used in a callback. We use go.Bar. def bar(results):gen =results["points"][0]["text"]figure = go.Figure( data=[ go.Bar(x=df2_decade[df2_decade.genre==gen].decade, y=df2_decade[df2_decade.genre==gen].year) ], layout=go.Layout( title="Decade popularity of " + gen))return figure Here we have wireframed the app next we populate with data and add controls. Entire layout code: #generate tabledef generate_table(dataframe, max_rows=10):'''Given dataframe, return template generated using Dash components'''return html.Table(# Header [html.Tr([html.Th(col) for col in dataframe.columns])] +# Body [html.Tr([html.Td(dataframe.iloc[i][col]) for col in dataframe.columns]) for i in range(min(len(dataframe), max_rows))], style={'width': '100%', 'display': 'inline-block', 'vertical-align': 'middle'})#generate bar chartdef bar(results): gen =results["points"][0]["text"] figure = go.Figure( data=[ go.Bar(x=df2_decade[df2_decade.genre==gen].decade, y=df2_decade[df2_decade.genre==gen].year) ], layout=go.Layout( title="Decade popularity of " + gen )) return figure# Set up Dashboard and create layoutapp = dash.Dash()# Bootstrap CSS.app.css.append_css({"external_url": "https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"})# Bootstrap Javascript.app.scripts.append_script({"external_url": "https://code.jquery.com/jquery-3.2.1.slim.min.js"})app.scripts.append_script({"external_url": "https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"})#define app layoutapp.layout = html.Div([ html.Div([ html.Div([ html.H1("Music Dashboard", className="text-center", id="heading") ], className = "col-md-12" ), ],className="row"), html.Div( [ #dropdown and score html.Div([ html.Div( [ dcc.Dropdown( options=[ {'label': 'userscore', 'value': 'userscore'}, {'label': 'metascore', 'value': 'metascore'}, ], id='score-dropdown' ) ], className="col-md-12"), html.Div( html.Table(id='datatable', className = "table col-md-12")), ],className="col-md-6"), html.Div( [ #Line Chart dcc.Graph(id='line-graph', figure=go.Figure( data = [ go.Scatter( x = df_linechart.year, y = df_linechart.userscore, mode = 'lines', name = 'user score' ), go.Scatter( x = df_linechart.year, y = df_linechart.metascore, mode = 'lines', name = 'meta score' ), ], layout=go.Layout(title="Score trends") ) ), ], className = "col-md-6" ), ], className="row"), html.Div( [ html.Div( [ dcc.Graph(id='bubble-chart', figure=go.Figure( data=[ go.Scatter( x=df_bubble.userscore, y=df_bubble.metascore, mode='markers', text=df_bubble.genre, marker=dict( color= random.sample(range(1,200),15), size=df_bubble.year, sizemode='area', sizeref=2.*max(df_bubble.year)/(40.**2), sizemin=4 ) ) ], layout=go.Layout(title="Genre poularity") ) ) ], className = "col-md-6" ), html.Div( [ dcc.Graph(id='bar-chart', style={'margin-top': '20'}) ], className = "col-md-6" ), ], className="row"),], className="container-fluid") Don’t be scared by the size of the code. The code is formatted in this way for easier understanding. Note how each div component has a class defined along with it. Now that we understand the layout let’s move to the controller. We have two interactive components in this dashboard one is the table that changes according to the type of score and the other is a bar chart that populates as per the selected genre bubble in out bubble chart. Our controller skeleton will look like: @app.callback( Output(component_id='selector-id', component_property='figure'), [ Input(component_id='input-selector-id',component_property='value') ] )def ctrl_func(input_selection) Here we have 4 parts: Callback: @app.callback is the callback function that hands the Input and Output. The Inputs and Outputs of our application are the properties of a particular component. Input: this takes the id of the component uses as input and the property of that component we need to capture. This can be the value, the hoverData, clickData and so on. Output: Output takes the id of the component which is to change and the property which will change typically this is either figure or children. Control Function: cltr_function defines how the html for the Output will change. Apart from these we also have State which allows us to add additional information apart from Input and Output. Simply put, the app callback automatically captures any change made in the input and updates the output based on the cltr_function defines. We can have multiple inputs and multiple outputs in a single callback. The code for callback in our case will look like: ###############################################################DATA CONTROL (CONTROLLER)##############################################################@app.callback( Output(component_id='datatable', component_property='children'), [Input(component_id='score-dropdown', component_property='value')] )def update_table(input_value): return generate_table(df_table.sort_values([input_value], ascending=[False]).reset_index())@app.callback( Output(component_id='bar-chart', component_property='figure'), [Input(component_id='bubble-chart', component_property='hoverData')] )def update_graph(hoverData): return bar(hoverData) In the first callback, we give the input from the dropdown. The callback captures the value of the dropdown and passes it to the function update table which generates the given table. It then passes the table html data to the datatable component and we see the relevant table in out dashboard. In the second callback, the data is passed is on hover from the bubble-chart component to the bar function. This data is a dictionary so we extract the relevant genre details using the text key and then pass the data to the bar function. The bar function subsets the df_decade data fro the given genre and plots a bar chart. Note how many different components are involved here and all it took was 10 lines! The following two lines need to be added to the code to run the app if __name__ == '__main__':app.run_server(debug=True) The app can be run using: python app.py and we’re done! You will see a message like this: Serving Flask app “songsapp” (lazy loading) Environment: production WARNING: Do not use the development server in a production environment. Use a production WSGI server instead. Debug mode: on Running on http://127.0.0.1:8050/ (Press CTRL+C to quit) Restarting with stat Debugger is active! Debugger PIN: 282–940–165 The dashboard is available on the link (can change on execution refer to the link in your own code execution): http://127.0.0.1:8050/ Our dashboard looks like: Finally, our dashboard is ready. The next step for this is to host the code on a server so that it accessible from any device. While hosting is easy, the steps involved require an in-depth understanding of hosting. Instead of burdening the reader with new concepts, we leave her with quick links to some hosting tutorials. This can be of use to both seasoned developers and freshers. Some popular hosting options are: Heroku: Dash has a short tutorial about hosting apps on Heroku. Alternatively, here is the tutorial by Heroku for deploying python apps. AWS: Amazons’ tutorial on deploying python apps. So this is how we build a simple yet interactive dashboard in < 200 lines of code. To really understand the real power of dash, do check out the dash gallery and the amazing stuff people have done with it. The entire code for this post can be found in this git repo. Dash tutorial Dash core component Library Writing own components using dash Video tutorial on Dash
[ { "code": null, "e": 577, "s": 172, "text": "Dashboards are user interfaces (UIs) that visualize data in an organized manner. Business dashboards usually contain information around Key Performance Indicators (KPIs) related to particular objectives or business processes. A dashboard is a “snapshot” report that allows us to display data at a given instant of time in a meaningful manner with the aid of charts for easy reference and quick inference." }, { "code": null, "e": 620, "s": 577, "text": "Some attributes of a useful dashboard are:" }, { "code": null, "e": 714, "s": 620, "text": "Customizable: An excellent dashboarding tool must allow users to customize according to need." }, { "code": null, "e": 821, "s": 714, "text": "Accessible: Should be available in a variety of media formats like web, mobile etc. for viewing on the go." }, { "code": null, "e": 903, "s": 821, "text": "Scalable: Should have the ability to add/change KPIs and add/change data sources." }, { "code": null, "e": 1498, "s": 903, "text": "Dashboards nowadays come in various shapes and sizes. Many companies roll out ready-made dashboarding services as SaaS. This software usually has workspaces where one can drag and drop data columns and KPIs. One of the most important dashboarding tools is Tabealu, which is self-contained software that allows users to build robust dashboards. However, if one might want to build their dashboarding tool, one would have to learn many technologies for visualization, database management and scripting. Below is a brief overview of some of the technologies involved (note this is not exhaustive):" }, { "code": null, "e": 1537, "s": 1498, "text": "Components of a dashboard Technologies" }, { "code": null, "e": 1645, "s": 1537, "text": "Visualization D3, React JavaScriptDatabase Management SQL, AWS, MongoDBScripting R-shiny, Python, Java, Cpp" }, { "code": null, "e": 1680, "s": 1645, "text": "Visualization D3, React JavaScript" }, { "code": null, "e": 1718, "s": 1680, "text": "Database Management SQL, AWS, MongoDB" }, { "code": null, "e": 1755, "s": 1718, "text": "Scripting R-shiny, Python, Java, Cpp" }, { "code": null, "e": 1810, "s": 1755, "text": "Using Python, we have several options at our disposal:" }, { "code": null, "e": 1945, "s": 1810, "text": "Dash: Dash is a powerful open-source library that helps build interactive and live web-based dashboards using Plotly, Flask and React." }, { "code": null, "e": 2211, "s": 1945, "text": "Jupyter Dashboards: The dashboards layout extension is an add-on for Jupyter Notebook. It lets the user arrange notebook outputs in a grid or report like the format and saves this layout. The extension is required to be installed by other users to view this report." }, { "code": null, "e": 2370, "s": 2211, "text": "Pyxley: Pyxlex is another excellent option for building dashboards. It leverages React and Flask. However, the support and documentation for this are limited." }, { "code": null, "e": 2468, "s": 2370, "text": "Bokeh: A web dashboard tool that employs D3 and Tornado may require some knowledge of JavaScript." }, { "code": null, "e": 2502, "s": 2468, "text": "Few more: Bowtie, Spyre, Superset" }, { "code": null, "e": 2527, "s": 2502, "text": "We go with Dash because:" }, { "code": null, "e": 2873, "s": 2527, "text": "Easy to use: Built on Plotly and React, so it is straightforward to code and has many widgets available. All you need to know is Python; no need to learn React or D3. However, if you know React, then Dash allows you to plug into React’s extensive ecosystem through an included toolset that packages React components into Dash-useable components." }, { "code": null, "e": 2983, "s": 2873, "text": "Documentation: Dash is well documented and has a great and responsive community on Stack Overflow and Github." }, { "code": null, "e": 3150, "s": 2983, "text": "Most UIs follow an MVC framework, by MVC, we mean Model-View-Controller. Each interconnected component is built to take on a specific task in the development process." }, { "code": null, "e": 3322, "s": 3150, "text": "Model: The model is the heart of the dashboard. The model gets the data from the database, manipulates it and stores it in objects which can later be consumed by the view." }, { "code": null, "e": 3464, "s": 3322, "text": "Controller: Controller is how the user interacts with the dashboard. It usually requests the data from the model and presents it to the view." }, { "code": null, "e": 3583, "s": 3464, "text": "View: The view is where data is present to the user or the frontend. A view oversees the visual part of the dashboard." }, { "code": null, "e": 3850, "s": 3583, "text": "The MVC framework reduces the application’s complexity and makes it easier to maintain; for example, the developer can choose to change the UI without needing to change any backed code. We will look at Dash from an MVC perspective for more fundamental understanding." }, { "code": null, "e": 4278, "s": 3850, "text": "As mentioned earlier, Dash is a simple Python tool that helps us build beautiful and responsive web dashboards quickly. It has support for both R and Python and is maintained by Plotly. It uses React for the Controller and View, and Plotly and Flask, for the Model in our MVC setting. We build a flask application that creates a dashboard on a web browser, which can call the backend to re-render certain parts of the web page." }, { "code": null, "e": 4399, "s": 4278, "text": "Dash and Plotly can be installed very easily using pip. Using a virtual environment manager (like Conda) is recommended." }, { "code": null, "e": 4730, "s": 4399, "text": "pip install dash==0.26.3 # The core dash backendpip install dash-renderer==0.13.2 # The dash front-endpip install dash-html-components==0.11.0 # HTML componentspip install dash-core-components==0.28.1 # Supercharged componentspip install dash_table_experiments #for tablespip install plotly --upgrade # Plotly graphing library" }, { "code": null, "e": 4776, "s": 4730, "text": "For the data manipulation, we install pandas." }, { "code": null, "e": 4795, "s": 4776, "text": "pip install pandas" }, { "code": null, "e": 4878, "s": 4795, "text": "Please check the dash installation guide to get the latest version of these tools." }, { "code": null, "e": 4916, "s": 4878, "text": "Now we move to the problem statement." }, { "code": null, "e": 5170, "s": 4916, "text": "In a previous post, we had talked about building our own data set using Scrapy, that taught us how to use web scraping to download data. We had downloaded the top 500 albums of all time from the Metacritic.com library. Here is a snapshot of the dataset:" }, { "code": null, "e": 5267, "s": 5170, "text": "We see that we have a genre, artist, release date, meta-score and the user score for each album." }, { "code": null, "e": 5333, "s": 5267, "text": "We will build a dashboard that has the following four components:" }, { "code": null, "e": 5529, "s": 5333, "text": "Interactive Bubble chart of genresHistogram of decade popularity of each genre (bar chart)Meta-score/User-score trends (line chart)Table of the top 10 most popular artist by meta score/user score" }, { "code": null, "e": 5564, "s": 5529, "text": "Interactive Bubble chart of genres" }, { "code": null, "e": 5621, "s": 5564, "text": "Histogram of decade popularity of each genre (bar chart)" }, { "code": null, "e": 5663, "s": 5621, "text": "Meta-score/User-score trends (line chart)" }, { "code": null, "e": 5728, "s": 5663, "text": "Table of the top 10 most popular artist by meta score/user score" }, { "code": null, "e": 6003, "s": 5728, "text": "User can interact with the bar table with a drop-down to get top 10 artists by average meta score or average user score. User can also interact with the bubble chart; on hover, it will change the bar chart to give the number of albums of that genre published in each decade." }, { "code": null, "e": 6168, "s": 6003, "text": "It is a good practice to build a small mock-up of the dashboard on paper or using a software (Adobe Illustrator and Balsamiq are great tools used by professionals)." }, { "code": null, "e": 6231, "s": 6168, "text": "Here we have used MS PowerPoint to build a simple static view." }, { "code": null, "e": 6283, "s": 6231, "text": "We will divide our dash component into three parts:" }, { "code": null, "e": 6556, "s": 6283, "text": "Data Manipulation (Model): Perform operation to read data from file and manipulate data for displayDashboard Layout (View): Visually render data on the web pageInteraction Between Components (Controller): Convert user input to commands for data manipulation and re-render." }, { "code": null, "e": 6656, "s": 6556, "text": "Data Manipulation (Model): Perform operation to read data from file and manipulate data for display" }, { "code": null, "e": 6718, "s": 6656, "text": "Dashboard Layout (View): Visually render data on the web page" }, { "code": null, "e": 6831, "s": 6718, "text": "Interaction Between Components (Controller): Convert user input to commands for data manipulation and re-render." }, { "code": null, "e": 6870, "s": 6831, "text": "Here we import the relevant libraries." }, { "code": null, "e": 7105, "s": 6870, "text": "import dashimport dash_core_components as dccimport dash_html_components as htmlimport dash_table_experiments as dtimport pandas as pdimport plotly.graph_objs as gofrom dash.dependencies import Input, Output, State, Eventimport random" }, { "code": null, "e": 7379, "s": 7105, "text": "Here we have the data in a csv so we can simply import it using pandas. However, if the data is in a SQLdatabase or on a server somewhere we need to make a data connection that connects data to a pandas dataframe in our backend and the rest of the process will be the same." }, { "code": null, "e": 7562, "s": 7379, "text": "We assume that the reader has a basic knowledge about pandas and can understand the data manipulation. Basically, we are creating 4 major tables for each of the dashboard components:" }, { "code": null, "e": 8477, "s": 7562, "text": "df_linechart: This table groups the data by year and gives us the number of albums, average meta-score and average user score. We also multiply user score by 10 to get it on the same scale as meta-score. This will be used to draw the Score trends graph.df_table: This table groups the data by artist and gives us the number of albums, total meta-score and total user score. The generate_table function uses this table to get the top 10 rows sorted by user score or meta score. This is used to draw the table.df_bubble: This table groups the data by genre, and gives us the number of albums, mean meta-score and mean users score. The number of albums becomes the size of our bubble and the mean scores become the axes. This is used to draw the bubble chart.df2_decade: This table groups the data by genre and decade and returns the number of albums for each genre in each decade. This is used to draw the bar chart." }, { "code": null, "e": 8731, "s": 8477, "text": "df_linechart: This table groups the data by year and gives us the number of albums, average meta-score and average user score. We also multiply user score by 10 to get it on the same scale as meta-score. This will be used to draw the Score trends graph." }, { "code": null, "e": 8987, "s": 8731, "text": "df_table: This table groups the data by artist and gives us the number of albums, total meta-score and total user score. The generate_table function uses this table to get the top 10 rows sorted by user score or meta score. This is used to draw the table." }, { "code": null, "e": 9236, "s": 8987, "text": "df_bubble: This table groups the data by genre, and gives us the number of albums, mean meta-score and mean users score. The number of albums becomes the size of our bubble and the mean scores become the axes. This is used to draw the bubble chart." }, { "code": null, "e": 9395, "s": 9236, "text": "df2_decade: This table groups the data by genre and decade and returns the number of albums for each genre in each decade. This is used to draw the bar chart." }, { "code": null, "e": 10737, "s": 9395, "text": "###############################################################DATA MANIPULATION (model)##############################################################df= pd.read_csv(\"top500_albums_clean.csv\")df['userscore'] = df['userscore'].astype(float)df['metascore'] = df['metascore'].astype(float)df['releasedate']=pd.to_datetime(df['releasedate'], format='%b %d, %Y')df['year']=df[\"releasedate\"].dt.yeardf['decade']=(df[\"year\"]//10)*10#cleaning Genredf['genre'] = df['genre'].str.strip()df['genre'] = df['genre'].str.replace(\"/\", \",\")df['genre'] = df['genre'].str.split(\",\")#year trenddf_linechart= df.groupby('year') .agg({'album':'size', 'metascore':'mean', 'userscore':'mean'}) .sort_values(['year'], ascending=[True]).reset_index()df_linechart.userscore=df_linechart.userscore*10#tabledf_table= df.groupby('artist').agg({'album':'size', 'metascore':'sum', 'userscore':'sum'})#genrebubbledf2=(df['genre'].apply(lambda x: pd.Series(x)) .stack().reset_index(level=1, drop=True).to_frame('genre').join(df[['year', 'decade', 'userscore', 'metascore']], how='left') )df_bubble= df2.groupby('genre') .agg({'year':'size', 'metascore':'mean', 'userscore':'mean'}) .sort_values(['year'], ascending=[False]).reset_index().head(15)df2_decade=df2.groupby(['genre', 'decade']).agg({'year':'size'}) .sort_values(['decade'], ascending=[False]).reset_index()" }, { "code": null, "e": 11017, "s": 10737, "text": "The layout determines how the dashboard would look after deployment. Dash provides Python classes for all the components. The components are saved in the dash_core_components and the dash_html_components library. One can also build their own components with JavaScript and React." }, { "code": null, "e": 11235, "s": 11017, "text": "We use a Bootstrap layout for our dashboard. Simply, Bootstrap standardizes the position of the components by containing them in a grid. It divides the screen into 12 columns and we can define as many rows as we like." }, { "code": null, "e": 11268, "s": 11235, "text": "So our dashboard will look like:" }, { "code": null, "e": 11509, "s": 11268, "text": "Row Column-12 (title)Row Column-6 (Table of most top 10 popular artist) Column-6 (Meta-score/User-score trends- line chart)Row Column-6 (Interactive Bubble chart of genres) Column-6 (Histogram of decade popularity (bar chart)" }, { "code": null, "e": 11555, "s": 11509, "text": "Here is another visualization of the mock-up:" }, { "code": null, "e": 11625, "s": 11555, "text": "We can add custom CSS, to our dashboard by using .append.css command." }, { "code": null, "e": 11754, "s": 11625, "text": "app = dash.Dash()app.css.append_css({\"external_url\": \" https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css\"})" }, { "code": null, "e": 11873, "s": 11754, "text": "We also append the require JavaScript libraries for Bootstrap. Please refer to the Bootstrap page for latest versions:" }, { "code": null, "e": 12106, "s": 11873, "text": "# Bootstrap Javascript.app.scripts.append_script({\"external_url\": \"https://code.jquery.com/jquery-3.2.1.slim.min.js\"})app.scripts.append_script({\"external_url\": \"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js\"})" }, { "code": null, "e": 12144, "s": 12106, "text": "The layout skeleton can be defined as" }, { "code": null, "e": 12302, "s": 12144, "text": "html.Div( [ SOME_DASH_OR_HTML_COMPONENT( \tid, \tcontent (data), \tstyle (a dictionary with the properties)) ], className (name of the Bootstrap Class) )" }, { "code": null, "e": 12378, "s": 12302, "text": "the classname will be the Bootstrap class name which can be row or columns." }, { "code": null, "e": 12521, "s": 12378, "text": "Dash makes it very easy to draw graphs thanks to the core components. We can use functions to draw components or we can write the code inline." }, { "code": null, "e": 12534, "s": 12521, "text": "Adding table" }, { "code": null, "e": 12634, "s": 12534, "text": "We can either use the html.Table tag or import Plotly tables. Here we’re using a html native table." }, { "code": null, "e": 13038, "s": 12634, "text": "def generate_table(dataframe, max_rows=10):'''Given dataframe, return template generated using Dash components'''return html.Table(# Header[html.Tr([html.Th(col) for col in dataframe.columns])] +# Body[html.Tr([\thtml.Td(dataframe.iloc[i][col]) for col in dataframe.columns]) for i in range(min(len(dataframe), max_rows))],style={'width': '100%', 'display': 'inline-block', 'vertical-align': 'middle'})" }, { "code": null, "e": 13111, "s": 13038, "text": "Simply, the function takes a pandas dataframe and coerces it to a table." }, { "code": null, "e": 13118, "s": 13111, "text": "Graphs" }, { "code": null, "e": 13427, "s": 13118, "text": "Dash uses the Plotly graph layout. We define a graph inside a dcc.Graph component and define the graph inside a figure object (defined as go). In this figure object we set the data, the style and layout. Each type of graph will have different relevant components to it. We discuss three types of graphs here:" }, { "code": null, "e": 13445, "s": 13427, "text": "Adding Line Graph" }, { "code": null, "e": 13627, "s": 13445, "text": "For the line graph we have to choose the Scatter type of graph with go.Scatter and in mode we define lines as shown below. We also need to define the data for x and y for each line." }, { "code": null, "e": 13719, "s": 13627, "text": "In the layout section we can choose to display the legends, title and other style elements." }, { "code": null, "e": 14078, "s": 13719, "text": "html.Div([ #Line Chartdcc.Graph(id='line-graph',figure=go.Figure(\tdata = [\tgo.Scatter(\t\tx = df_linechart.year,\t\ty = df_linechart.userscore,\t\tmode = 'lines',\t\tname = 'user score'\t\t),\tgo.Scatter(\t\tx = df_linechart.year,\t\ty = df_linechart.metascore,\t\tmode = 'lines',\t\tname = 'meta score'\t\t),\t],\tlayout=go.Layout(title=\"Score trends\"))),], className = \"col-md-6\"" }, { "code": null, "e": 14098, "s": 14078, "text": "Adding bubble chart" }, { "code": null, "e": 14359, "s": 14098, "text": "Similarly, for a bubble chart, we define a go.Scatter but use mode = markers. We can also define a text component that gives the text on hovering over the marker. Later in our dynamic view will use this text to fill our fourth bar graph of “Decade Popularity”." }, { "code": null, "e": 14497, "s": 14359, "text": "Markers are the points or bubbles on the graph, we can further customize the markers by passing a dictionary object with various options:" }, { "code": null, "e": 14675, "s": 14497, "text": "Color: A list of colors to be used for the markers, can be names of colors or a list of numbers for a color scale. Here I have passes a random list of numbers between 0 and 100." }, { "code": null, "e": 14932, "s": 14675, "text": "Size: Size specifies the size of the bubble. Here we put the number of albums as the size. So a genre with more number of albums will have a larger bubble. With size we can further customize the size by passing the sizemode, sizeref and sizemin components." }, { "code": null, "e": 15345, "s": 14932, "text": "html.Div([dcc.Graph(id='bubble-chart',\tfigure=go.Figure(\t\tdata=[\t\t\tgo.Scatter(\t\t\t\tx=df_bubble.userscore,\t\t\t\ty=df_bubble.metascore,\t\t\t\tmode='markers',\t\t\t\ttext=df_bubble.genre,\t\t\t\tmarker=dict(\t\t\t\t\tcolor= random.sample(range(1,200),15),\t\t\t\t\tsize=df_bubble.year,\t\t\t\t\tsizemode='area',\t\t\t\t\tsizeref=2.*max(df_bubble.year)/(40.**2),\t\t\t\t\tsizemin=4))],layout=go.Layout(title=\"Genre poularity\")))], className = \"col-md-6\")," }, { "code": null, "e": 15362, "s": 15345, "text": "Adding Bar Chart" }, { "code": null, "e": 15581, "s": 15362, "text": "Lastly, we draw a bar chart using a function. Note we could have directly pasted this part in the html div but since we want this graph to be interactive we use a function that can be used in a callback. We use go.Bar." }, { "code": null, "e": 15825, "s": 15581, "text": "def bar(results):gen =results[\"points\"][0][\"text\"]figure = go.Figure(\tdata=[\tgo.Bar(x=df2_decade[df2_decade.genre==gen].decade, \ty=df2_decade[df2_decade.genre==gen].year)\t],\tlayout=go.Layout(\ttitle=\"Decade popularity of \" + gen))return figure" }, { "code": null, "e": 15922, "s": 15825, "text": "Here we have wireframed the app next we populate with data and add controls. Entire layout code:" }, { "code": null, "e": 18570, "s": 15922, "text": "#generate tabledef generate_table(dataframe, max_rows=10):'''Given dataframe, return template generated using Dash components'''return html.Table(# Header\t[html.Tr([html.Th(col) for col in dataframe.columns])] +# Body\t[html.Tr([html.Td(dataframe.iloc[i][col]) for col in dataframe.columns]) for i in range(min(len(dataframe), max_rows))],\tstyle={'width': '100%', 'display': 'inline-block', 'vertical-align': 'middle'})#generate bar chartdef bar(results):\tgen =results[\"points\"][0][\"text\"]\tfigure = go.Figure(\t\tdata=[\t\t\tgo.Bar(x=df2_decade[df2_decade.genre==gen].decade, y=df2_decade[df2_decade.genre==gen].year)\t\t],\tlayout=go.Layout(\t\ttitle=\"Decade popularity of \" + gen\t))\treturn figure# Set up Dashboard and create layoutapp = dash.Dash()# Bootstrap CSS.app.css.append_css({\"external_url\": \"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css\"})# Bootstrap Javascript.app.scripts.append_script({\"external_url\": \"https://code.jquery.com/jquery-3.2.1.slim.min.js\"})app.scripts.append_script({\"external_url\": \"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js\"})#define app layoutapp.layout = html.Div([\thtml.Div([\t\thtml.Div([\t\t\thtml.H1(\"Music Dashboard\", className=\"text-center\", id=\"heading\")\t\t\t], className = \"col-md-12\"\t\t\t),\t\t],className=\"row\"),\thtml.Div(\t\t[ #dropdown and score\t\thtml.Div([\t\t\thtml.Div(\t\t\t\t[\t\t\t\tdcc.Dropdown(\t\t\t\toptions=[\t\t\t\t\t{'label': 'userscore', 'value': 'userscore'},\t\t\t\t\t{'label': 'metascore', 'value': 'metascore'},\t\t\t\t],\t\t\t\tid='score-dropdown'\t\t\t\t)\t\t], className=\"col-md-12\"),\thtml.Div(\t\thtml.Table(id='datatable', className = \"table col-md-12\")),\t\t],className=\"col-md-6\"),\thtml.Div(\t\t[ #Line Chart\t\tdcc.Graph(id='line-graph',\tfigure=go.Figure(\t\tdata = [\t\tgo.Scatter(\t\t\tx = df_linechart.year,\t\t\ty = df_linechart.userscore,\t\t\tmode = 'lines',\t\t\tname = 'user score'\t\t\t),\t\tgo.Scatter(\t\t\tx = df_linechart.year,\t\t\ty = df_linechart.metascore,\t\t\tmode = 'lines',\t\t\tname = 'meta score'\t\t\t),\t\t],\t\tlayout=go.Layout(title=\"Score trends\")\t\t)\t\t),\t\t], className = \"col-md-6\"\t),\t], className=\"row\"),\thtml.Div(\t\t[\t\thtml.Div(\t\t\t[\t\t\tdcc.Graph(id='bubble-chart',\t\t\tfigure=go.Figure(\t\t\tdata=[\t\t\t\tgo.Scatter(\t\t\t\tx=df_bubble.userscore,\t\t\t\ty=df_bubble.metascore,\t\t\t\tmode='markers',\t\t\t\ttext=df_bubble.genre,\t\t\tmarker=dict(\t\t\t\tcolor= random.sample(range(1,200),15),\t\t\t\tsize=df_bubble.year,\t\t\t\tsizemode='area',\t\t\t\tsizeref=2.*max(df_bubble.year)/(40.**2),\t\t\t\tsizemin=4\t\t\t\t)\t\t\t)\t\t],\tlayout=go.Layout(title=\"Genre poularity\")\t)\t)\t], className = \"col-md-6\"\t),\thtml.Div(\t\t[\t\tdcc.Graph(id='bar-chart',\t\t\tstyle={'margin-top': '20'})\t\t], className = \"col-md-6\"\t\t),\t\t], className=\"row\"),], className=\"container-fluid\")" }, { "code": null, "e": 18734, "s": 18570, "text": "Don’t be scared by the size of the code. The code is formatted in this way for easier understanding. Note how each div component has a class defined along with it." }, { "code": null, "e": 19010, "s": 18734, "text": "Now that we understand the layout let’s move to the controller. We have two interactive components in this dashboard one is the table that changes according to the type of score and the other is a bar chart that populates as per the selected genre bubble in out bubble chart." }, { "code": null, "e": 19050, "s": 19010, "text": "Our controller skeleton will look like:" }, { "code": null, "e": 19236, "s": 19050, "text": "@app.callback(\tOutput(component_id='selector-id', component_property='figure'),\t\t[\t\tInput(component_id='input-selector-id',component_property='value')\t\t]\t)def ctrl_func(input_selection)" }, { "code": null, "e": 19258, "s": 19236, "text": "Here we have 4 parts:" }, { "code": null, "e": 19428, "s": 19258, "text": "Callback: @app.callback is the callback function that hands the Input and Output. The Inputs and Outputs of our application are the properties of a particular component." }, { "code": null, "e": 19598, "s": 19428, "text": "Input: this takes the id of the component uses as input and the property of that component we need to capture. This can be the value, the hoverData, clickData and so on." }, { "code": null, "e": 19742, "s": 19598, "text": "Output: Output takes the id of the component which is to change and the property which will change typically this is either figure or children." }, { "code": null, "e": 19823, "s": 19742, "text": "Control Function: cltr_function defines how the html for the Output will change." }, { "code": null, "e": 19934, "s": 19823, "text": "Apart from these we also have State which allows us to add additional information apart from Input and Output." }, { "code": null, "e": 20145, "s": 19934, "text": "Simply put, the app callback automatically captures any change made in the input and updates the output based on the cltr_function defines. We can have multiple inputs and multiple outputs in a single callback." }, { "code": null, "e": 20195, "s": 20145, "text": "The code for callback in our case will look like:" }, { "code": null, "e": 20816, "s": 20195, "text": "###############################################################DATA CONTROL (CONTROLLER)##############################################################@app.callback(\tOutput(component_id='datatable', component_property='children'),\t[Input(component_id='score-dropdown', component_property='value')]\t)def update_table(input_value):\treturn generate_table(df_table.sort_values([input_value], ascending=[False]).reset_index())@app.callback(\tOutput(component_id='bar-chart', component_property='figure'),\t[Input(component_id='bubble-chart', component_property='hoverData')]\t)def update_graph(hoverData):\treturn bar(hoverData)" }, { "code": null, "e": 21110, "s": 20816, "text": "In the first callback, we give the input from the dropdown. The callback captures the value of the dropdown and passes it to the function update table which generates the given table. It then passes the table html data to the datatable component and we see the relevant table in out dashboard." }, { "code": null, "e": 21518, "s": 21110, "text": "In the second callback, the data is passed is on hover from the bubble-chart component to the bar function. This data is a dictionary so we extract the relevant genre details using the text key and then pass the data to the bar function. The bar function subsets the df_decade data fro the given genre and plots a bar chart. Note how many different components are involved here and all it took was 10 lines!" }, { "code": null, "e": 21586, "s": 21518, "text": "The following two lines need to be added to the code to run the app" }, { "code": null, "e": 21640, "s": 21586, "text": "if __name__ == '__main__':app.run_server(debug=True)" }, { "code": null, "e": 21666, "s": 21640, "text": "The app can be run using:" }, { "code": null, "e": 21680, "s": 21666, "text": "python app.py" }, { "code": null, "e": 21696, "s": 21680, "text": "and we’re done!" }, { "code": null, "e": 21730, "s": 21696, "text": "You will see a message like this:" }, { "code": null, "e": 22047, "s": 21730, "text": "Serving Flask app “songsapp” (lazy loading) Environment: production WARNING: Do not use the development server in a production environment. Use a production WSGI server instead. Debug mode: on Running on http://127.0.0.1:8050/ (Press CTRL+C to quit) Restarting with stat Debugger is active! Debugger PIN: 282–940–165" }, { "code": null, "e": 22158, "s": 22047, "text": "The dashboard is available on the link (can change on execution refer to the link in your own code execution):" }, { "code": null, "e": 22181, "s": 22158, "text": "http://127.0.0.1:8050/" }, { "code": null, "e": 22207, "s": 22181, "text": "Our dashboard looks like:" }, { "code": null, "e": 22591, "s": 22207, "text": "Finally, our dashboard is ready. The next step for this is to host the code on a server so that it accessible from any device. While hosting is easy, the steps involved require an in-depth understanding of hosting. Instead of burdening the reader with new concepts, we leave her with quick links to some hosting tutorials. This can be of use to both seasoned developers and freshers." }, { "code": null, "e": 22625, "s": 22591, "text": "Some popular hosting options are:" }, { "code": null, "e": 22762, "s": 22625, "text": "Heroku: Dash has a short tutorial about hosting apps on Heroku. Alternatively, here is the tutorial by Heroku for deploying python apps." }, { "code": null, "e": 22811, "s": 22762, "text": "AWS: Amazons’ tutorial on deploying python apps." }, { "code": null, "e": 23078, "s": 22811, "text": "So this is how we build a simple yet interactive dashboard in < 200 lines of code. To really understand the real power of dash, do check out the dash gallery and the amazing stuff people have done with it. The entire code for this post can be found in this git repo." } ]
What is the meaning of prepended double colon “::” in C++?
The prepended double colon is also known as the scope resolution operator. Some of the uses of this operator are given as follows. The scope resolution operator can be used to define a function outside a class. A program that demonstrates this is given as follows. Live Demo #include<iostream> using namespace std; class Example { int num; public: Example() { num = 10; } void display(); }; void Example::display() { cout << "The value of num is: "<<num;; } int main() { Example obj; obj.display(); return 0; } The output of the above program is as follows. The value of num is: 10 The scope resolution operator can be used to access a global variable when there is also a local variable with the same name. A program that demonstrates this is given as follows. Live Demo #include<iostream> using namespace std; int num = 7; int main() { int num = 3; cout << "Value of local variable num is: " << num; cout << "\nValue of global variable num is: " << ::num; return 0; } The output of the above program is as follows. Value of local variable num is: 3 Value of global variable num is: 7
[ { "code": null, "e": 1193, "s": 1062, "text": "The prepended double colon is also known as the scope resolution operator. Some of the uses of this operator are given as follows." }, { "code": null, "e": 1327, "s": 1193, "text": "The scope resolution operator can be used to define a function outside a class. A program that demonstrates this is given as follows." }, { "code": null, "e": 1338, "s": 1327, "text": " Live Demo" }, { "code": null, "e": 1607, "s": 1338, "text": "#include<iostream>\nusing namespace std;\nclass Example {\n int num;\n public:\n Example() {\n num = 10;\n }\n void display();\n};\nvoid Example::display() {\n cout << \"The value of num is: \"<<num;;\n}\nint main() {\n Example obj;\n obj.display();\n return 0;\n}" }, { "code": null, "e": 1654, "s": 1607, "text": "The output of the above program is as follows." }, { "code": null, "e": 1678, "s": 1654, "text": "The value of num is: 10" }, { "code": null, "e": 1858, "s": 1678, "text": "The scope resolution operator can be used to access a global variable when there is also a local variable with the same name. A program that demonstrates this is given as follows." }, { "code": null, "e": 1869, "s": 1858, "text": " Live Demo" }, { "code": null, "e": 2079, "s": 1869, "text": "#include<iostream>\nusing namespace std;\nint num = 7;\nint main() {\n int num = 3;\n cout << \"Value of local variable num is: \" << num;\n cout << \"\\nValue of global variable num is: \" << ::num;\n return 0;\n}" }, { "code": null, "e": 2126, "s": 2079, "text": "The output of the above program is as follows." }, { "code": null, "e": 2195, "s": 2126, "text": "Value of local variable num is: 3\nValue of global variable num is: 7" } ]
Pandas Groupby - Sort within groups - GeeksforGeeks
29 Aug, 2020 Pandas Groupby is used in situations where we want to split data and set into groups so that we can do various operations on those groups like – Aggregation of data, Transformation through some group computations or Filtration according to specific conditions applied on the groups. In similar ways, we can perform sorting within these groups. Example 1: Let’s take an example of a dataframe: df = pd.DataFrame({'X': ['B', 'B', 'A', 'A'], 'Y': [1, 2, 3, 4]}) # using groupby functiondf.groupby('X').sum() Output: Let’s pass the sort parameter as False. # using groupby function # with sortdf.groupby('X', sort = False).sum() Output: Here, we see a dataframe with sorted values within the groups. Example 2:Now, let’s take an example of a dataframe with ages of different people. Using sort along with groupby function will arrange the transformed dataframe on the basis of keys passes, for potential speedups. data = {'Name':['Elle', 'Chloe', 'Noah', 'Marco', 'Lee', 'Elle', 'Rachel', 'Noah'], 'Age':[17, 19, 18, 17, 22, 18, 21, 20]} df = pd.DataFrame(data) df Output: Let’s group the above dataframe according to the name # using groupby without sortdf.groupby(['Name']).sum() Output: Passing the sort parameter as False # using groupby function # with sortdf.groupby(['Name'], sort = False).sum() Output: Example 3:Let’s take another example of a dataframe that consists top speeds of various cars and bikes.We’ll try to get the top speeds sorted within the groups of vehicle type. import pandas as pd df = pd.DataFrame([('Bike', 'Kawasaki', 186), ('Bike', 'Ducati Panigale', 202), ('Car', 'Bugatti Chiron', 304), ('Car', 'Jaguar XJ220', 210), ('Bike', 'Lightning LS-218', 218), ('Car', 'Hennessey Venom GT', 270), ('Bike', 'BMW S1000RR', 188)], columns =('Type', 'Name', 'top_speed(mph)')) df Output: After Using the groupby function # Using groupby functiongrouped = df.groupby(['Type'])['top_speed(mph)'].nlargest() # using nlargest() function will get the # largest values of top_speed(mph) within# groups createdprint(grouped) Output: Python pandas-groupby Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python Different ways to create Pandas Dataframe Python String | replace() Python program to convert a list to string Reading and Writing to text files in Python sum() function in Python
[ { "code": null, "e": 24564, "s": 24536, "text": "\n29 Aug, 2020" }, { "code": null, "e": 24847, "s": 24564, "text": "Pandas Groupby is used in situations where we want to split data and set into groups so that we can do various operations on those groups like – Aggregation of data, Transformation through some group computations or Filtration according to specific conditions applied on the groups." }, { "code": null, "e": 24908, "s": 24847, "text": "In similar ways, we can perform sorting within these groups." }, { "code": null, "e": 24957, "s": 24908, "text": "Example 1: Let’s take an example of a dataframe:" }, { "code": "df = pd.DataFrame({'X': ['B', 'B', 'A', 'A'], 'Y': [1, 2, 3, 4]}) # using groupby functiondf.groupby('X').sum()", "e": 25088, "s": 24957, "text": null }, { "code": null, "e": 25096, "s": 25088, "text": "Output:" }, { "code": null, "e": 25136, "s": 25096, "text": "Let’s pass the sort parameter as False." }, { "code": "# using groupby function # with sortdf.groupby('X', sort = False).sum()", "e": 25208, "s": 25136, "text": null }, { "code": null, "e": 25216, "s": 25208, "text": "Output:" }, { "code": null, "e": 25279, "s": 25216, "text": "Here, we see a dataframe with sorted values within the groups." }, { "code": null, "e": 25493, "s": 25279, "text": "Example 2:Now, let’s take an example of a dataframe with ages of different people. Using sort along with groupby function will arrange the transformed dataframe on the basis of keys passes, for potential speedups." }, { "code": "data = {'Name':['Elle', 'Chloe', 'Noah', 'Marco', 'Lee', 'Elle', 'Rachel', 'Noah'], 'Age':[17, 19, 18, 17, 22, 18, 21, 20]} df = pd.DataFrame(data) df", "e": 25691, "s": 25493, "text": null }, { "code": null, "e": 25699, "s": 25691, "text": "Output:" }, { "code": null, "e": 25753, "s": 25699, "text": "Let’s group the above dataframe according to the name" }, { "code": "# using groupby without sortdf.groupby(['Name']).sum()", "e": 25808, "s": 25753, "text": null }, { "code": null, "e": 25816, "s": 25808, "text": "Output:" }, { "code": null, "e": 25852, "s": 25816, "text": "Passing the sort parameter as False" }, { "code": "# using groupby function # with sortdf.groupby(['Name'], sort = False).sum()", "e": 25929, "s": 25852, "text": null }, { "code": null, "e": 25937, "s": 25929, "text": "Output:" }, { "code": null, "e": 26114, "s": 25937, "text": "Example 3:Let’s take another example of a dataframe that consists top speeds of various cars and bikes.We’ll try to get the top speeds sorted within the groups of vehicle type." }, { "code": "import pandas as pd df = pd.DataFrame([('Bike', 'Kawasaki', 186), ('Bike', 'Ducati Panigale', 202), ('Car', 'Bugatti Chiron', 304), ('Car', 'Jaguar XJ220', 210), ('Bike', 'Lightning LS-218', 218), ('Car', 'Hennessey Venom GT', 270), ('Bike', 'BMW S1000RR', 188)], columns =('Type', 'Name', 'top_speed(mph)')) df", "e": 26558, "s": 26114, "text": null }, { "code": null, "e": 26566, "s": 26558, "text": "Output:" }, { "code": null, "e": 26599, "s": 26566, "text": "After Using the groupby function" }, { "code": "# Using groupby functiongrouped = df.groupby(['Type'])['top_speed(mph)'].nlargest() # using nlargest() function will get the # largest values of top_speed(mph) within# groups createdprint(grouped)", "e": 26797, "s": 26599, "text": null }, { "code": null, "e": 26805, "s": 26797, "text": "Output:" }, { "code": null, "e": 26827, "s": 26805, "text": "Python pandas-groupby" }, { "code": null, "e": 26841, "s": 26827, "text": "Python-pandas" }, { "code": null, "e": 26848, "s": 26841, "text": "Python" }, { "code": null, "e": 26946, "s": 26848, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26955, "s": 26946, "text": "Comments" }, { "code": null, "e": 26968, "s": 26955, "text": "Old Comments" }, { "code": null, "e": 26986, "s": 26968, "text": "Python Dictionary" }, { "code": null, "e": 27021, "s": 26986, "text": "Read a file line by line in Python" }, { "code": null, "e": 27043, "s": 27021, "text": "Enumerate() in Python" }, { "code": null, "e": 27075, "s": 27043, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27105, "s": 27075, "text": "Iterate over a list in Python" }, { "code": null, "e": 27147, "s": 27105, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 27173, "s": 27147, "text": "Python String | replace()" }, { "code": null, "e": 27216, "s": 27173, "text": "Python program to convert a list to string" }, { "code": null, "e": 27260, "s": 27216, "text": "Reading and Writing to text files in Python" } ]
Trading: Calculate Technical Analysis Indicators with Pandas 🐼 | by J Li | Towards Data Science
(This post is also available in my blog) In finance, technical analysis is an analysis methodology for forecasting the direction of prices through the study of past market data, primarily price and volume. Technical analysts rely on a combination of technical indicators to study a stock and give insight about trading strategy. Common technical indicators like SMA and Bollinger Band® are widely used. Here is a list of technical indicators. In a previous story, I talked about how to collect such information with Pandas. In this story, I will demonstrate how to compute Bollinger Bands® and use it to provide potential buy / sell signals. Bollinger Bands® Bollinger Bands is used to define the prevailing high and low prices in a market to characterize the trading band of a financial instrument or commodity. Bollinger Bands are a volatility indicator. Bands are consists of Moving Average (MA) line, a upper band and lower band. The upper and lower bands are simply MA adding and subtracting standard deviation. Standard deviation is a measurement of volatility. That’s why it’s a volatility indictor. Upper Band = (MA + Kσ)Lower Band = (MA − Kσ) MA is typical 20 day moving average and K is 2. I will use them in this example. Prerequisite environment setup (follow Step1 in this post) Data: We will use a csv file (AMZN.csv) collected from the previous post in this example Code: import pandas as pdimport matplotlib.pyplot as pltsymbol='AMZN'# read csv file, use date as index and read close as a columndf = pd.read_csv('~/workspace/{}.csv'.format(symbol), index_col='date', parse_dates=True, usecols=['date', 'close'], na_values='nan')# rename the column header with symbol namedf = df.rename(columns={'close': symbol})df.dropna(inplace=True)# calculate Simple Moving Average with 20 days windowsma = df.rolling(window=20).mean()# calculate the standar deviationrstd = df.rolling(window=20).std()upper_band = sma + 2 * rstdupper_band = upper_band.rename(columns={symbol: 'upper'})lower_band = sma - 2 * rstdlower_band = lower_band.rename(columns={symbol: 'lower'})df = df.join(upper_band).join(lower_band)ax = df.plot(title='{} Price and BB'.format(symbol))ax.fill_between(df.index, lower_band['lower'], upper_band['upper'], color='#ADCCFF', alpha='0.4')ax.set_xlabel('date')ax.set_ylabel('SMA and BB')ax.grid()plt.show() Output Interpretation of Buy / Sell signals Approximately 90% of price action between the two bands. Therefore the bands can be used to identify potential overbought or oversold conditions. If stock price breaks out the upper band, it could be an overbought condition (indication of short). Similarly, when it breaks out the lower band, it could be oversold condition (indication of long). But Bollinger Bands is not a standalone system that always gives accurate buy / sell signals. One should consider the overall trend with the bands to identify the signal. Otherwise, with only Bollinger Bands, one could make wrong orders constantly. In the above Amazon example, the trend is up. So one should only take long positions when the lower band is tagged. More information could be found here. That’s how easy to compute technical indicators with 🐼! If you would like to learn more about Machine Learning there is a helpful series of courses in educative.io. These courses cover topics like basic ML, NLP, Image Recognition etc. Recommended reading: Hands-On Machine Learning Python for Data Analysis: Data Wrangling with Pandas, NumPy, and IPython What Hedge Funds Really Do My posts: My posts about Finance and Tech My YouTube Channel My posts about FAANG interview From CRUD web app dev to SDE in voice assistant — My ongoing Journey to Machine Learning Full Stack Development Tutorial: Integrate AWS Lambda Serverless Service into Angular SPA Full Stack Development Tutorial: Serving Trading Data with Serverless REST API running on AWS Lambda Full Stack Development Tutorial: Visualize Trading Data on Angular SPA (1) Reinforcement Learning: Introduction to Q Learning
[ { "code": null, "e": 213, "s": 172, "text": "(This post is also available in my blog)" }, { "code": null, "e": 615, "s": 213, "text": "In finance, technical analysis is an analysis methodology for forecasting the direction of prices through the study of past market data, primarily price and volume. Technical analysts rely on a combination of technical indicators to study a stock and give insight about trading strategy. Common technical indicators like SMA and Bollinger Band® are widely used. Here is a list of technical indicators." }, { "code": null, "e": 814, "s": 615, "text": "In a previous story, I talked about how to collect such information with Pandas. In this story, I will demonstrate how to compute Bollinger Bands® and use it to provide potential buy / sell signals." }, { "code": null, "e": 831, "s": 814, "text": "Bollinger Bands®" }, { "code": null, "e": 1279, "s": 831, "text": "Bollinger Bands is used to define the prevailing high and low prices in a market to characterize the trading band of a financial instrument or commodity. Bollinger Bands are a volatility indicator. Bands are consists of Moving Average (MA) line, a upper band and lower band. The upper and lower bands are simply MA adding and subtracting standard deviation. Standard deviation is a measurement of volatility. That’s why it’s a volatility indictor." }, { "code": null, "e": 1324, "s": 1279, "text": "Upper Band = (MA + Kσ)Lower Band = (MA − Kσ)" }, { "code": null, "e": 1405, "s": 1324, "text": "MA is typical 20 day moving average and K is 2. I will use them in this example." }, { "code": null, "e": 1464, "s": 1405, "text": "Prerequisite environment setup (follow Step1 in this post)" }, { "code": null, "e": 1470, "s": 1464, "text": "Data:" }, { "code": null, "e": 1553, "s": 1470, "text": "We will use a csv file (AMZN.csv) collected from the previous post in this example" }, { "code": null, "e": 1559, "s": 1553, "text": "Code:" }, { "code": null, "e": 2535, "s": 1559, "text": "import pandas as pdimport matplotlib.pyplot as pltsymbol='AMZN'# read csv file, use date as index and read close as a columndf = pd.read_csv('~/workspace/{}.csv'.format(symbol), index_col='date', parse_dates=True, usecols=['date', 'close'], na_values='nan')# rename the column header with symbol namedf = df.rename(columns={'close': symbol})df.dropna(inplace=True)# calculate Simple Moving Average with 20 days windowsma = df.rolling(window=20).mean()# calculate the standar deviationrstd = df.rolling(window=20).std()upper_band = sma + 2 * rstdupper_band = upper_band.rename(columns={symbol: 'upper'})lower_band = sma - 2 * rstdlower_band = lower_band.rename(columns={symbol: 'lower'})df = df.join(upper_band).join(lower_band)ax = df.plot(title='{} Price and BB'.format(symbol))ax.fill_between(df.index, lower_band['lower'], upper_band['upper'], color='#ADCCFF', alpha='0.4')ax.set_xlabel('date')ax.set_ylabel('SMA and BB')ax.grid()plt.show()" }, { "code": null, "e": 2542, "s": 2535, "text": "Output" }, { "code": null, "e": 2579, "s": 2542, "text": "Interpretation of Buy / Sell signals" }, { "code": null, "e": 3328, "s": 2579, "text": "Approximately 90% of price action between the two bands. Therefore the bands can be used to identify potential overbought or oversold conditions. If stock price breaks out the upper band, it could be an overbought condition (indication of short). Similarly, when it breaks out the lower band, it could be oversold condition (indication of long). But Bollinger Bands is not a standalone system that always gives accurate buy / sell signals. One should consider the overall trend with the bands to identify the signal. Otherwise, with only Bollinger Bands, one could make wrong orders constantly. In the above Amazon example, the trend is up. So one should only take long positions when the lower band is tagged. More information could be found here." }, { "code": null, "e": 3384, "s": 3328, "text": "That’s how easy to compute technical indicators with 🐼!" }, { "code": null, "e": 3563, "s": 3384, "text": "If you would like to learn more about Machine Learning there is a helpful series of courses in educative.io. These courses cover topics like basic ML, NLP, Image Recognition etc." }, { "code": null, "e": 3584, "s": 3563, "text": "Recommended reading:" }, { "code": null, "e": 3610, "s": 3584, "text": "Hands-On Machine Learning" }, { "code": null, "e": 3683, "s": 3610, "text": "Python for Data Analysis: Data Wrangling with Pandas, NumPy, and IPython" }, { "code": null, "e": 3710, "s": 3683, "text": "What Hedge Funds Really Do" }, { "code": null, "e": 3720, "s": 3710, "text": "My posts:" }, { "code": null, "e": 3752, "s": 3720, "text": "My posts about Finance and Tech" }, { "code": null, "e": 3771, "s": 3752, "text": "My YouTube Channel" }, { "code": null, "e": 3802, "s": 3771, "text": "My posts about FAANG interview" }, { "code": null, "e": 3891, "s": 3802, "text": "From CRUD web app dev to SDE in voice assistant — My ongoing Journey to Machine Learning" }, { "code": null, "e": 3981, "s": 3891, "text": "Full Stack Development Tutorial: Integrate AWS Lambda Serverless Service into Angular SPA" }, { "code": null, "e": 4082, "s": 3981, "text": "Full Stack Development Tutorial: Serving Trading Data with Serverless REST API running on AWS Lambda" }, { "code": null, "e": 4157, "s": 4082, "text": "Full Stack Development Tutorial: Visualize Trading Data on Angular SPA (1)" } ]
How to Create a CircularImageView in Android using hdodenhof Library? - GeeksforGeeks
18 Feb, 2021 It is seen that many Android apps use CircularImageView to show the profile images, status, stories, and many other things but doing this with a normal ImageView is a bit difficult. So to do so use hdodenhof CircleImageView Library. It’s a fast circular ImageView perfect for profile images. This is based on RoundedImageView from Vince Mi. So in this article, let’s add a CircleImageView in the Android App. A sample image is given below to get an idea about what we are going to do in this article. Note: To create a CircularImageView in Android without using any library please refer to How to create a Circular image view in Android without using any library? Step 1: Creating a New Project To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that choose Java as language though we are going to implement this project in Java language. Step 2: Before going to the coding section first do some pre-task Go to Gradle Scripts -> build.gradle (Module: app) section and import the following dependencies and click the “sync Now” on the above pop up. implementation ‘de.hdodenhof:circleimageview:3.1.0’ Step 3: Designing the UI Create a CircleImageView inside the activity_main.xml file and set the android:src=”@drawable/mountain”. The complete code of the activity_main.xml file is given below. 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" xmlns:app="http://schemas.android.com/apk/res-auto" tools:context=".MainActivity"> <!-- Circular Image View --> <de.hdodenhof.circleimageview.CircleImageView app:civ_border_width="4dp" android:layout_centerInParent="true" android:src="@drawable/mountain" app:civ_border_color="#FF000000" android:layout_width="300dp" android:layout_height="300dp"/> </RelativeLayout> Step 4: MainActivity.java file Here in this project there is nothing to do with the MainActivity.java file, so keep it as it is. Java import androidx.appcompat.app.AppCompatActivity;import android.os.Bundle; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); }} In this library, the ScaleType is always CENTER_CROP and you will get an exception if you try to change it. Enabling adjustViewBounds is not supported as this requires an unsupported ScaleType. Using a TransitionDrawable with CircleImageView doesn’t work properly and leads to messed-up images. Resources: Download Complete Project from Github Download the Apk file android Android-View Android Java Java Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Flutter - Custom Bottom Navigation Bar Retrofit with Kotlin Coroutine in Android How to Read Data from SQLite Database in Android? How to Change the Background Color After Clicking the Button in Android? Android Listview in Java with Example Arrays in Java Split() String method in Java with examples For-each loop in Java Arrays.sort() in Java with examples Reverse a string in Java
[ { "code": null, "e": 25116, "s": 25088, "text": "\n18 Feb, 2021" }, { "code": null, "e": 25617, "s": 25116, "text": "It is seen that many Android apps use CircularImageView to show the profile images, status, stories, and many other things but doing this with a normal ImageView is a bit difficult. So to do so use hdodenhof CircleImageView Library. It’s a fast circular ImageView perfect for profile images. This is based on RoundedImageView from Vince Mi. So in this article, let’s add a CircleImageView in the Android App. A sample image is given below to get an idea about what we are going to do in this article." }, { "code": null, "e": 25780, "s": 25617, "text": "Note: To create a CircularImageView in Android without using any library please refer to How to create a Circular image view in Android without using any library?" }, { "code": null, "e": 25811, "s": 25780, "text": "Step 1: Creating a New Project" }, { "code": null, "e": 26020, "s": 25811, "text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that choose Java as language though we are going to implement this project in Java language." }, { "code": null, "e": 26086, "s": 26020, "text": "Step 2: Before going to the coding section first do some pre-task" }, { "code": null, "e": 26229, "s": 26086, "text": "Go to Gradle Scripts -> build.gradle (Module: app) section and import the following dependencies and click the “sync Now” on the above pop up." }, { "code": null, "e": 26281, "s": 26229, "text": "implementation ‘de.hdodenhof:circleimageview:3.1.0’" }, { "code": null, "e": 26307, "s": 26281, "text": "Step 3: Designing the UI " }, { "code": null, "e": 26476, "s": 26307, "text": "Create a CircleImageView inside the activity_main.xml file and set the android:src=”@drawable/mountain”. The complete code of the activity_main.xml file is given below." }, { "code": null, "e": 26480, "s": 26476, "text": "XML" }, { "code": "<?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\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" tools:context=\".MainActivity\"> <!-- Circular Image View --> <de.hdodenhof.circleimageview.CircleImageView app:civ_border_width=\"4dp\" android:layout_centerInParent=\"true\" android:src=\"@drawable/mountain\" app:civ_border_color=\"#FF000000\" android:layout_width=\"300dp\" android:layout_height=\"300dp\"/> </RelativeLayout>", "e": 27151, "s": 26480, "text": null }, { "code": null, "e": 27182, "s": 27151, "text": "Step 4: MainActivity.java file" }, { "code": null, "e": 27280, "s": 27182, "text": "Here in this project there is nothing to do with the MainActivity.java file, so keep it as it is." }, { "code": null, "e": 27285, "s": 27280, "text": "Java" }, { "code": "import androidx.appcompat.app.AppCompatActivity;import android.os.Bundle; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); }}", "e": 27583, "s": 27285, "text": null }, { "code": null, "e": 27691, "s": 27583, "text": "In this library, the ScaleType is always CENTER_CROP and you will get an exception if you try to change it." }, { "code": null, "e": 27777, "s": 27691, "text": "Enabling adjustViewBounds is not supported as this requires an unsupported ScaleType." }, { "code": null, "e": 27878, "s": 27777, "text": "Using a TransitionDrawable with CircleImageView doesn’t work properly and leads to messed-up images." }, { "code": null, "e": 27889, "s": 27878, "text": "Resources:" }, { "code": null, "e": 27927, "s": 27889, "text": "Download Complete Project from Github" }, { "code": null, "e": 27949, "s": 27927, "text": "Download the Apk file" }, { "code": null, "e": 27957, "s": 27949, "text": "android" }, { "code": null, "e": 27970, "s": 27957, "text": "Android-View" }, { "code": null, "e": 27978, "s": 27970, "text": "Android" }, { "code": null, "e": 27983, "s": 27978, "text": "Java" }, { "code": null, "e": 27988, "s": 27983, "text": "Java" }, { "code": null, "e": 27996, "s": 27988, "text": "Android" }, { "code": null, "e": 28094, "s": 27996, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28133, "s": 28094, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 28175, "s": 28133, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 28225, "s": 28175, "text": "How to Read Data from SQLite Database in Android?" }, { "code": null, "e": 28298, "s": 28225, "text": "How to Change the Background Color After Clicking the Button in Android?" }, { "code": null, "e": 28336, "s": 28298, "text": "Android Listview in Java with Example" }, { "code": null, "e": 28351, "s": 28336, "text": "Arrays in Java" }, { "code": null, "e": 28395, "s": 28351, "text": "Split() String method in Java with examples" }, { "code": null, "e": 28417, "s": 28395, "text": "For-each loop in Java" }, { "code": null, "e": 28453, "s": 28417, "text": "Arrays.sort() in Java with examples" } ]
Double doubleToLongBits() method in Java with examples - GeeksforGeeks
26 Oct, 2018 The java.lang.Double.doubleToLongBits() method of Java Double class is a built-in function in java that returns a representation of the specified floating-point value according to the IEEE 754 floating-point “double format” bit layout. Syntax: public static long doubleToLongBits(double val) Parameter: The method accepts only one parameter val which specifies a double precision floating-point number. Return Values: The function returns the bits that represent the floating-point number. Below are the special cases: If the argument is positive infinity, the result is 7ff0000000000000L. If the argument is negative infinity, the result is 0xfff0000000000000L. If the argument is NaN, the result is 0x7ff8000000000000L. Below programs illustrates the use of java.lang.Double.doubleToLongBits() method: Program 1: // Java program to demonstrate// Double.doubleToLongBits() method import java.lang.*; class Gfg1 { public static void main(String args[]) { double val = 1.5d; // function call long answer = Double.doubleToLongBits(val); // print System.out.println(val + " in long bits: " + answer); }} 1.5 in long bits: 4609434218613702656 Program 2: // Java program to demonstrate// Double.doubleToLongBits() method import java.lang.*; class Gfg1 { public static void main(String args[]) { double val = Double.POSITIVE_INFINITY; double val1 = Double.NEGATIVE_INFINITY; double val2 = Double.NaN; // function call long answer = Double.doubleToLongBits(val); // print System.out.println(val + " in long bits: " + answer); // function call answer = Double.doubleToLongBits(val1); // print System.out.println(val1 + " in long bits: " + answer); // function call answer = Double.doubleToLongBits(val2); // print System.out.println(val2 + " in long bits: " + answer); }} Infinity in long bits: 9218868437227405312 -Infinity in long bits: -4503599627370496 NaN in long bits: 9221120237041090560 Reference: https://docs.oracle.com/javase/7/docs/api/java/lang/Double.html#doubleToLongBits(double) java-basics Java-Double Java-Functions Java-lang package Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Initialize an ArrayList in Java HashMap in Java with Examples Interfaces in Java ArrayList in Java Multidimensional Arrays in Java Stack Class in Java Stream In Java Singleton Class in Java Set in Java LinkedList in Java
[ { "code": null, "e": 24354, "s": 24326, "text": "\n26 Oct, 2018" }, { "code": null, "e": 24590, "s": 24354, "text": "The java.lang.Double.doubleToLongBits() method of Java Double class is a built-in function in java that returns a representation of the specified floating-point value according to the IEEE 754 floating-point “double format” bit layout." }, { "code": null, "e": 24598, "s": 24590, "text": "Syntax:" }, { "code": null, "e": 24647, "s": 24598, "text": "public static long doubleToLongBits(double val)\n" }, { "code": null, "e": 24758, "s": 24647, "text": "Parameter: The method accepts only one parameter val which specifies a double precision floating-point number." }, { "code": null, "e": 24874, "s": 24758, "text": "Return Values: The function returns the bits that represent the floating-point number. Below are the special cases:" }, { "code": null, "e": 24945, "s": 24874, "text": "If the argument is positive infinity, the result is 7ff0000000000000L." }, { "code": null, "e": 25018, "s": 24945, "text": "If the argument is negative infinity, the result is 0xfff0000000000000L." }, { "code": null, "e": 25077, "s": 25018, "text": "If the argument is NaN, the result is 0x7ff8000000000000L." }, { "code": null, "e": 25159, "s": 25077, "text": "Below programs illustrates the use of java.lang.Double.doubleToLongBits() method:" }, { "code": null, "e": 25170, "s": 25159, "text": "Program 1:" }, { "code": "// Java program to demonstrate// Double.doubleToLongBits() method import java.lang.*; class Gfg1 { public static void main(String args[]) { double val = 1.5d; // function call long answer = Double.doubleToLongBits(val); // print System.out.println(val + \" in long bits: \" + answer); }}", "e": 25536, "s": 25170, "text": null }, { "code": null, "e": 25575, "s": 25536, "text": "1.5 in long bits: 4609434218613702656\n" }, { "code": null, "e": 25586, "s": 25575, "text": "Program 2:" }, { "code": "// Java program to demonstrate// Double.doubleToLongBits() method import java.lang.*; class Gfg1 { public static void main(String args[]) { double val = Double.POSITIVE_INFINITY; double val1 = Double.NEGATIVE_INFINITY; double val2 = Double.NaN; // function call long answer = Double.doubleToLongBits(val); // print System.out.println(val + \" in long bits: \" + answer); // function call answer = Double.doubleToLongBits(val1); // print System.out.println(val1 + \" in long bits: \" + answer); // function call answer = Double.doubleToLongBits(val2); // print System.out.println(val2 + \" in long bits: \" + answer); }}", "e": 26410, "s": 25586, "text": null }, { "code": null, "e": 26534, "s": 26410, "text": "Infinity in long bits: 9218868437227405312\n-Infinity in long bits: -4503599627370496\nNaN in long bits: 9221120237041090560\n" }, { "code": null, "e": 26634, "s": 26534, "text": "Reference: https://docs.oracle.com/javase/7/docs/api/java/lang/Double.html#doubleToLongBits(double)" }, { "code": null, "e": 26646, "s": 26634, "text": "java-basics" }, { "code": null, "e": 26658, "s": 26646, "text": "Java-Double" }, { "code": null, "e": 26673, "s": 26658, "text": "Java-Functions" }, { "code": null, "e": 26691, "s": 26673, "text": "Java-lang package" }, { "code": null, "e": 26696, "s": 26691, "text": "Java" }, { "code": null, "e": 26701, "s": 26696, "text": "Java" }, { "code": null, "e": 26799, "s": 26701, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26831, "s": 26799, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 26861, "s": 26831, "text": "HashMap in Java with Examples" }, { "code": null, "e": 26880, "s": 26861, "text": "Interfaces in Java" }, { "code": null, "e": 26898, "s": 26880, "text": "ArrayList in Java" }, { "code": null, "e": 26930, "s": 26898, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 26950, "s": 26930, "text": "Stack Class in Java" }, { "code": null, "e": 26965, "s": 26950, "text": "Stream In Java" }, { "code": null, "e": 26989, "s": 26965, "text": "Singleton Class in Java" }, { "code": null, "e": 27001, "s": 26989, "text": "Set in Java" } ]
Copying file using FileStreams in Java - GeeksforGeeks
18 Apr, 2022 The main logic of copying a file is to read the file associated with FileInputStream variable and write the read contents into the file associated with FileOutputStream variable. We can copy a file from one location to another using FileInputStream and FileOutputStream classes in Java. Now before adhering forward let us discuss essential methods that will be used in the program. Method 1: read(): Reads a byte of data. Present in FileInputStream. Return type: An integer value Syntax: Other versions int read(byte[] bytearray or int read(byte[] bytearray, int offset, int length) Method 2: write(int b): Writes a byte of data. Present in FileOutputStream Syntax: void write(byte[] bytearray) or void write(byte[] bytearray, int offset, int length) Implementation: We will be creating two files named “demo.rtf” and “outputdemo.rtf” as another file where no content is there. Below is an image of the “demo.rtf” file as a sample input image. First, we will create two objects of the File class, one referring to FileInputClass and the other for FileOutputStream Class. Now we will create objects of FileInputStream class and FileOutputStream class prior to creating variables and assigning null to corresponding datatypes. Pass respective objects of FileInputStream and FileOutputStream objects Now using loops keep reading from a file and write it to another file using FileOuputStream using the read() and write() methods. Tip: It is good practice to close the streams to avoid memory leakage. Example 1: Java // Java Program to Illustrate File InputStream and File // Importing required classesimport java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Creating object of File class // Passing files from directory of local machine File file = new File( "/Users/mayanksolanki/Desktop/demo.rtf"); File oFile = new File( "/Users/mayanksolanki/Desktop/outputdemo.rtf"); // Now creating object of FileInputStream // Here they are variables FileInputStream fis = null; FileOutputStream fos = null; try { // Now we make them as objects of both classes // and passed reference of file in directory fis = new FileInputStream(file); fos = new FileOutputStream(oFile); } // Catch block to handle exceptions catch (FileNotFoundException e) { // Display message if exception occurs // File Not Found or Path is Incorrect System.out.println(e.printStackTrace()); } try { // Now let us check how many bytes are available // inside content of file fis.available(); } catch (Exception e) { e.printStackTrace(); } // Using while loop to // write over outputdemo file int i = 0; while (i = fis.read() != -1) { fos.write(i); } // It will execute no matter what // to close connections which is // always good practice finally { // Closing the file connections // For input stream if (fis != null { fis.clsoe(); } // For output stream if (fos != null) { fos.close(); } } }} Output: The same content will be reflected back in the “outputdemo.rtf” file as seen below in the “demo.rtf” file. Example 2: Java // Java Program Illustrating Copying a src File// to Destination // Importing required classesimport java.io.*; // Main class// src2destclass GFG { // Main driver method public static void main(String args[]) throws FileNotFoundException, IOException { // If file doesnot exist FileInputStream throws // FileNotFoundException and read() write() throws // IOException if I/O error occurs FileInputStream fis = new FileInputStream(args[0]); // Assuming that the file exists and // need not to be checked FileOutputStream fos = new FileOutputStream(args[1]); int b; while ((b = fis.read()) != -1) fos.write(b); // read() method will read only next int so we used // while loop here in order to read upto end of file // and keep writing the read int into dest file fis.close(); fos.close(); }} Output: Output Explanation: The name of the src file and dest file must be provided using command line arguments where args[0] is the name of the source file and args[1] is the name of the destination file. This article is contributed by Parul Dang. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. solankimayank java-file-handling Java-I/O Java School Programming Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Split() String method in Java with examples Arrays.sort() in Java with examples Reverse a string in Java Initialize an ArrayList in Java Object Oriented Programming (OOPs) Concept in Java Python Dictionary Arrays in C/C++ Inheritance in C++ Reverse a string in Java C++ Classes and Objects
[ { "code": null, "e": 27877, "s": 27849, "text": "\n18 Apr, 2022" }, { "code": null, "e": 28260, "s": 27877, "text": "The main logic of copying a file is to read the file associated with FileInputStream variable and write the read contents into the file associated with FileOutputStream variable. We can copy a file from one location to another using FileInputStream and FileOutputStream classes in Java. Now before adhering forward let us discuss essential methods that will be used in the program. " }, { "code": null, "e": 28329, "s": 28260, "text": "Method 1: read(): Reads a byte of data. Present in FileInputStream. " }, { "code": null, "e": 28360, "s": 28329, "text": "Return type: An integer value " }, { "code": null, "e": 28384, "s": 28360, "text": "Syntax: Other versions " }, { "code": null, "e": 28466, "s": 28384, "text": "int read(byte[] bytearray\n\nor\n\nint read(byte[] bytearray, int offset, int length)" }, { "code": null, "e": 28541, "s": 28466, "text": "Method 2: write(int b): Writes a byte of data. Present in FileOutputStream" }, { "code": null, "e": 28549, "s": 28541, "text": "Syntax:" }, { "code": null, "e": 28636, "s": 28549, "text": "void write(byte[] bytearray)\n\nor\n\nvoid write(byte[] bytearray, int offset, int length)" }, { "code": null, "e": 28829, "s": 28636, "text": "Implementation: We will be creating two files named “demo.rtf” and “outputdemo.rtf” as another file where no content is there. Below is an image of the “demo.rtf” file as a sample input image." }, { "code": null, "e": 28956, "s": 28829, "text": "First, we will create two objects of the File class, one referring to FileInputClass and the other for FileOutputStream Class." }, { "code": null, "e": 29110, "s": 28956, "text": "Now we will create objects of FileInputStream class and FileOutputStream class prior to creating variables and assigning null to corresponding datatypes." }, { "code": null, "e": 29182, "s": 29110, "text": "Pass respective objects of FileInputStream and FileOutputStream objects" }, { "code": null, "e": 29312, "s": 29182, "text": "Now using loops keep reading from a file and write it to another file using FileOuputStream using the read() and write() methods." }, { "code": null, "e": 29389, "s": 29312, "text": "Tip: It is good practice to close the streams to avoid memory leakage. " }, { "code": null, "e": 29400, "s": 29389, "text": "Example 1:" }, { "code": null, "e": 29405, "s": 29400, "text": "Java" }, { "code": "// Java Program to Illustrate File InputStream and File // Importing required classesimport java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Creating object of File class // Passing files from directory of local machine File file = new File( \"/Users/mayanksolanki/Desktop/demo.rtf\"); File oFile = new File( \"/Users/mayanksolanki/Desktop/outputdemo.rtf\"); // Now creating object of FileInputStream // Here they are variables FileInputStream fis = null; FileOutputStream fos = null; try { // Now we make them as objects of both classes // and passed reference of file in directory fis = new FileInputStream(file); fos = new FileOutputStream(oFile); } // Catch block to handle exceptions catch (FileNotFoundException e) { // Display message if exception occurs // File Not Found or Path is Incorrect System.out.println(e.printStackTrace()); } try { // Now let us check how many bytes are available // inside content of file fis.available(); } catch (Exception e) { e.printStackTrace(); } // Using while loop to // write over outputdemo file int i = 0; while (i = fis.read() != -1) { fos.write(i); } // It will execute no matter what // to close connections which is // always good practice finally { // Closing the file connections // For input stream if (fis != null { fis.clsoe(); } // For output stream if (fos != null) { fos.close(); } } }}", "e": 31386, "s": 29405, "text": null }, { "code": null, "e": 31502, "s": 31386, "text": "Output: The same content will be reflected back in the “outputdemo.rtf” file as seen below in the “demo.rtf” file. " }, { "code": null, "e": 31513, "s": 31502, "text": "Example 2:" }, { "code": null, "e": 31518, "s": 31513, "text": "Java" }, { "code": "// Java Program Illustrating Copying a src File// to Destination // Importing required classesimport java.io.*; // Main class// src2destclass GFG { // Main driver method public static void main(String args[]) throws FileNotFoundException, IOException { // If file doesnot exist FileInputStream throws // FileNotFoundException and read() write() throws // IOException if I/O error occurs FileInputStream fis = new FileInputStream(args[0]); // Assuming that the file exists and // need not to be checked FileOutputStream fos = new FileOutputStream(args[1]); int b; while ((b = fis.read()) != -1) fos.write(b); // read() method will read only next int so we used // while loop here in order to read upto end of file // and keep writing the read int into dest file fis.close(); fos.close(); }}", "e": 32452, "s": 31518, "text": null }, { "code": null, "e": 32460, "s": 32452, "text": "Output:" }, { "code": null, "e": 32660, "s": 32460, "text": "Output Explanation: The name of the src file and dest file must be provided using command line arguments where args[0] is the name of the source file and args[1] is the name of the destination file. " }, { "code": null, "e": 33079, "s": 32660, "text": "This article is contributed by Parul Dang. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 33093, "s": 33079, "text": "solankimayank" }, { "code": null, "e": 33112, "s": 33093, "text": "java-file-handling" }, { "code": null, "e": 33121, "s": 33112, "text": "Java-I/O" }, { "code": null, "e": 33126, "s": 33121, "text": "Java" }, { "code": null, "e": 33145, "s": 33126, "text": "School Programming" }, { "code": null, "e": 33150, "s": 33145, "text": "Java" }, { "code": null, "e": 33248, "s": 33150, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33292, "s": 33248, "text": "Split() String method in Java with examples" }, { "code": null, "e": 33328, "s": 33292, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 33353, "s": 33328, "text": "Reverse a string in Java" }, { "code": null, "e": 33385, "s": 33353, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 33436, "s": 33385, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 33454, "s": 33436, "text": "Python Dictionary" }, { "code": null, "e": 33470, "s": 33454, "text": "Arrays in C/C++" }, { "code": null, "e": 33489, "s": 33470, "text": "Inheritance in C++" }, { "code": null, "e": 33514, "s": 33489, "text": "Reverse a string in Java" } ]
Display all the numbers from a range of start and end value in JavaScript?
Let’s say the following is our start value − var startValue=10; Let’s say the following is our end value − var endValue=20; Use the for loop to fetch numbers between the start and end value − var startValue=10; var endValue=20; var total=''; function printAllValues(startValue,endValue){ for(var start=startValue;start < endValue ;start++){ total=total+start+","; } } printAllValues(startValue,endValue) var allSequences = total.slice(0, -1); console.log(allSequences); To run the above program, you need to use the following command − node fileName.js. Here, my file name is demo87.js. This will produce the following output − PS C:\Users\Amit\JavaScript-code> node demo87.js 10,11,12,13,14,15,16,17,18,19
[ { "code": null, "e": 1107, "s": 1062, "text": "Let’s say the following is our start value −" }, { "code": null, "e": 1126, "s": 1107, "text": "var startValue=10;" }, { "code": null, "e": 1169, "s": 1126, "text": "Let’s say the following is our end value −" }, { "code": null, "e": 1186, "s": 1169, "text": "var endValue=20;" }, { "code": null, "e": 1254, "s": 1186, "text": "Use the for loop to fetch numbers between the start and end value −" }, { "code": null, "e": 1544, "s": 1254, "text": "var startValue=10;\nvar endValue=20;\nvar total='';\nfunction printAllValues(startValue,endValue){\n for(var start=startValue;start < endValue ;start++){\n total=total+start+\",\";\n }\n}\nprintAllValues(startValue,endValue)\nvar allSequences = total.slice(0, -1);\nconsole.log(allSequences);" }, { "code": null, "e": 1610, "s": 1544, "text": "To run the above program, you need to use the following command −" }, { "code": null, "e": 1628, "s": 1610, "text": "node fileName.js." }, { "code": null, "e": 1661, "s": 1628, "text": "Here, my file name is demo87.js." }, { "code": null, "e": 1702, "s": 1661, "text": "This will produce the following output −" }, { "code": null, "e": 1781, "s": 1702, "text": "PS C:\\Users\\Amit\\JavaScript-code> node demo87.js\n10,11,12,13,14,15,16,17,18,19" } ]
Deepest left leaf node in a binary tree | iterative approach - GeeksforGeeks
31 Mar, 2022 Given a Binary Tree, find the deepest leaf node that is left child of its parent. For example, consider the following tree. The deepest left leaf node is the node with value 9.Examples: Input : 1 / \ 2 3 / / \ 4 5 6 \ \ 7 8 / \ 9 10 Output : 9 Recursive approach to this problem is discussed hereFor iterative approach, idea is similar to Method 2 of level order traversalThe idea is to traverse the tree iteratively and whenever a left tree node is pushed to queue, check if it is leaf node, if it’s leaf node, then update the result. Since we go level by level, the last stored leaf node is deepest one, C++ Java Python3 C# Javascript // CPP program to find deepest left leaf// node of binary tree#include <bits/stdc++.h>using namespace std; // tree nodestruct Node { int data; Node *left, *right;}; // returns a new tree NodeNode* newNode(int data){ Node* temp = new Node(); temp->data = data; temp->left = temp->right = NULL; return temp;} // return the deepest left leaf node// of binary treeNode* getDeepestLeftLeafNode(Node* root){ if (!root) return NULL; // create a queue for level order traversal queue<Node*> q; q.push(root); Node* result = NULL; // traverse until the queue is empty while (!q.empty()) { Node* temp = q.front(); q.pop(); // Since we go level by level, the last // stored left leaf node is deepest one, if (temp->left) { q.push(temp->left); if (!temp->left->left && !temp->left->right) result = temp->left; } if (temp->right) q.push(temp->right); } return result;} // driver programint main(){ // construct a tree Node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->right->left = newNode(5); root->right->right = newNode(6); root->right->left->right = newNode(7); root->right->right->right = newNode(8); root->right->left->right->left = newNode(9); root->right->right->right->right = newNode(10); Node* result = getDeepestLeftLeafNode(root); if (result) cout << "Deepest Left Leaf Node :: " << result->data << endl; else cout << "No result, left leaf not found\n"; return 0;} // Java program to find deepest left leaf// node of binary treeimport java.util.*; class GFG{ // tree nodestatic class Node{ int data; Node left, right;}; // returns a new tree Nodestatic Node newNode(int data){ Node temp = new Node(); temp.data = data; temp.left = temp.right = null; return temp;} // return the deepest left leaf node// of binary treestatic Node getDeepestLeftLeafNode(Node root){ if (root == null) return null; // create a queue for level order traversal Queue<Node> q = new LinkedList<>(); q.add(root); Node result = null; // traverse until the queue is empty while (!q.isEmpty()) { Node temp = q.peek(); q.remove(); // Since we go level by level, the last // stored left leaf node is deepest one, if (temp.left != null) { q.add(temp.left); if (temp.left.left == null && temp.left.right == null) result = temp.left; } if (temp.right != null) q.add(temp.right); } return result;} // Driver Codepublic static void main(String[] args){ // construct a tree Node root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(4); root.right.left = newNode(5); root.right.right = newNode(6); root.right.left.right = newNode(7); root.right.right.right = newNode(8); root.right.left.right.left = newNode(9); root.right.right.right.right = newNode(10); Node result = getDeepestLeftLeafNode(root); if (result != null) System.out.println("Deepest Left Leaf Node :: " + result.data); else System.out.println("No result, " + "left leaf not found"); }} // This code is contributed by Rajput-Ji # Python3 program to find deepest# left leaf Binary search Tree _MIN = -2147483648_MAX = 2147483648 # Helper function that allocates a new# node with the given data and None# left and right pointers. class newnode: # Constructor to create a new node def __init__(self, data): self.data = data self.left = None self.right = None # utility function to return deepest# left leaf nodedef getDeepestLeftLeafNode(root) : if (not root): return None # create a queue for level # order traversal q = [] q.append(root) result = None # traverse until the queue is empty while (len(q)): temp = q[0] q.pop(0) if (temp.left): q.append(temp.left) if (not temp.left.left and not temp.left.right): result = temp.left # Since we go level by level, # the last stored right leaf # node is deepest one if (temp.right): q.append(temp.right) return result # Driver Codeif __name__ == '__main__': # create a binary tree root = newnode(1) root.left = newnode(2) root.right = newnode(3) root.left.Left = newnode(4) root.right.left = newnode(5) root.right.right = newnode(6) root.right.left.right = newnode(7) root.right.right.right = newnode(8) root.right.left.right.left = newnode(9) root.right.right.right.right = newnode(10) result = getDeepestLeftLeafNode(root) if result: print("Deepest Left Leaf Node ::", result.data) else: print("No result, Left leaf not found") # This code is contributed by# Shubham Singh(SHUBHAMSINGH10) // C# program to find deepest left leaf// node of binary treeusing System;using System.Collections.Generic; class GFG{ // tree nodeclass Node{ public int data; public Node left, right;}; // returns a new tree Nodestatic Node newNode(int data){ Node temp = new Node(); temp.data = data; temp.left = temp.right = null; return temp;} // return the deepest left leaf node// of binary treestatic Node getDeepestLeftLeafNode(Node root){ if (root == null) return null; // create a queue for level order traversal Queue<Node> q = new Queue<Node>(); q.Enqueue(root); Node result = null; // traverse until the queue is empty while (q.Count != 0) { Node temp = q.Peek(); q.Dequeue(); // Since we go level by level, the last // stored left leaf node is deepest one, if (temp.left != null) { q.Enqueue(temp.left); if (temp.left.left == null && temp.left.right == null) result = temp.left; } if (temp.right != null) q.Enqueue(temp.right); } return result;} // Driver Codepublic static void Main(String[] args){ // construct a tree Node root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(4); root.right.left = newNode(5); root.right.right = newNode(6); root.right.left.right = newNode(7); root.right.right.right = newNode(8); root.right.left.right.left = newNode(9); root.right.right.right.right = newNode(10); Node result = getDeepestLeftLeafNode(root); if (result != null) Console.WriteLine("Deepest Left Leaf Node :: " + result.data); else Console.WriteLine("No result, " + "left leaf not found"); }} // This code is contributed by Rajput-Ji <script> // JavaScript program to find deepest // left leaf node of binary tree class Node { constructor(data) { this.left = null; this.right = null; this.data = data; } } // returns a new tree Node function newNode(data) { let temp = new Node(data); return temp; } // return the deepest left leaf node // of binary tree function getDeepestLeftLeafNode(root) { if (root == null) return null; // create a queue for level order traversal let q = []; q.push(root); let result = null; // traverse until the queue is empty while (q.length > 0) { let temp = q[0]; q.shift(); // Since we go level by level, the last // stored left leaf node is deepest one, if (temp.left != null) { q.push(temp.left); if (temp.left.left == null && temp.left.right == null) result = temp.left; } if (temp.right != null) q.push(temp.right); } return result; } // construct a tree let root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(4); root.right.left = newNode(5); root.right.right = newNode(6); root.right.left.right = newNode(7); root.right.right.right = newNode(8); root.right.left.right.left = newNode(9); root.right.right.right.right = newNode(10); let result = getDeepestLeftLeafNode(root); if (result != null) document.write("Deepest Left Leaf Node :: " + result.data); else document.write("No result, " + "left leaf not found"); </script> Output: Deepest Left Leaf Node :: 9 YouTubeGeeksforGeeks500K subscribersDeepest left leaf node in a binary tree | Iterative approach | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 3:15•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=cNBNjZwnPaU" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> ?list=PLqM7alHXFySHCXD7r1J0ky9Zg_GBB1dbk SHUBHAMSINGH10 Rajput-Ji mukesh07 surinderdawra388 cpp-queue Tree Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Difference between Min Heap and Max Heap 2-3 Trees | (Search, Insert and Deletion) Write a program to Calculate Size of a tree | Recursion Maximum width of a binary tree Iterative Method to find Height of Binary Tree Construct a Binary Tree from Postorder and Inorder Evaluation of Expression Tree Find the node with minimum value in a Binary Search Tree Flatten a binary tree into linked list Maximum Path Sum in a Binary Tree
[ { "code": null, "e": 24549, "s": 24521, "text": "\n31 Mar, 2022" }, { "code": null, "e": 24737, "s": 24549, "text": "Given a Binary Tree, find the deepest leaf node that is left child of its parent. For example, consider the following tree. The deepest left leaf node is the node with value 9.Examples: " }, { "code": null, "e": 24893, "s": 24737, "text": "Input : \n 1\n / \\\n 2 3\n / / \\ \n 4 5 6\n \\ \\\n 7 8\n / \\\n 9 10\n\n\nOutput : 9" }, { "code": null, "e": 25259, "s": 24895, "text": "Recursive approach to this problem is discussed hereFor iterative approach, idea is similar to Method 2 of level order traversalThe idea is to traverse the tree iteratively and whenever a left tree node is pushed to queue, check if it is leaf node, if it’s leaf node, then update the result. Since we go level by level, the last stored leaf node is deepest one, " }, { "code": null, "e": 25263, "s": 25259, "text": "C++" }, { "code": null, "e": 25268, "s": 25263, "text": "Java" }, { "code": null, "e": 25276, "s": 25268, "text": "Python3" }, { "code": null, "e": 25279, "s": 25276, "text": "C#" }, { "code": null, "e": 25290, "s": 25279, "text": "Javascript" }, { "code": "// CPP program to find deepest left leaf// node of binary tree#include <bits/stdc++.h>using namespace std; // tree nodestruct Node { int data; Node *left, *right;}; // returns a new tree NodeNode* newNode(int data){ Node* temp = new Node(); temp->data = data; temp->left = temp->right = NULL; return temp;} // return the deepest left leaf node// of binary treeNode* getDeepestLeftLeafNode(Node* root){ if (!root) return NULL; // create a queue for level order traversal queue<Node*> q; q.push(root); Node* result = NULL; // traverse until the queue is empty while (!q.empty()) { Node* temp = q.front(); q.pop(); // Since we go level by level, the last // stored left leaf node is deepest one, if (temp->left) { q.push(temp->left); if (!temp->left->left && !temp->left->right) result = temp->left; } if (temp->right) q.push(temp->right); } return result;} // driver programint main(){ // construct a tree Node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->right->left = newNode(5); root->right->right = newNode(6); root->right->left->right = newNode(7); root->right->right->right = newNode(8); root->right->left->right->left = newNode(9); root->right->right->right->right = newNode(10); Node* result = getDeepestLeftLeafNode(root); if (result) cout << \"Deepest Left Leaf Node :: \" << result->data << endl; else cout << \"No result, left leaf not found\\n\"; return 0;}", "e": 26961, "s": 25290, "text": null }, { "code": "// Java program to find deepest left leaf// node of binary treeimport java.util.*; class GFG{ // tree nodestatic class Node{ int data; Node left, right;}; // returns a new tree Nodestatic Node newNode(int data){ Node temp = new Node(); temp.data = data; temp.left = temp.right = null; return temp;} // return the deepest left leaf node// of binary treestatic Node getDeepestLeftLeafNode(Node root){ if (root == null) return null; // create a queue for level order traversal Queue<Node> q = new LinkedList<>(); q.add(root); Node result = null; // traverse until the queue is empty while (!q.isEmpty()) { Node temp = q.peek(); q.remove(); // Since we go level by level, the last // stored left leaf node is deepest one, if (temp.left != null) { q.add(temp.left); if (temp.left.left == null && temp.left.right == null) result = temp.left; } if (temp.right != null) q.add(temp.right); } return result;} // Driver Codepublic static void main(String[] args){ // construct a tree Node root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(4); root.right.left = newNode(5); root.right.right = newNode(6); root.right.left.right = newNode(7); root.right.right.right = newNode(8); root.right.left.right.left = newNode(9); root.right.right.right.right = newNode(10); Node result = getDeepestLeftLeafNode(root); if (result != null) System.out.println(\"Deepest Left Leaf Node :: \" + result.data); else System.out.println(\"No result, \" + \"left leaf not found\"); }} // This code is contributed by Rajput-Ji", "e": 28804, "s": 26961, "text": null }, { "code": "# Python3 program to find deepest# left leaf Binary search Tree _MIN = -2147483648_MAX = 2147483648 # Helper function that allocates a new# node with the given data and None# left and right pointers. class newnode: # Constructor to create a new node def __init__(self, data): self.data = data self.left = None self.right = None # utility function to return deepest# left leaf nodedef getDeepestLeftLeafNode(root) : if (not root): return None # create a queue for level # order traversal q = [] q.append(root) result = None # traverse until the queue is empty while (len(q)): temp = q[0] q.pop(0) if (temp.left): q.append(temp.left) if (not temp.left.left and not temp.left.right): result = temp.left # Since we go level by level, # the last stored right leaf # node is deepest one if (temp.right): q.append(temp.right) return result # Driver Codeif __name__ == '__main__': # create a binary tree root = newnode(1) root.left = newnode(2) root.right = newnode(3) root.left.Left = newnode(4) root.right.left = newnode(5) root.right.right = newnode(6) root.right.left.right = newnode(7) root.right.right.right = newnode(8) root.right.left.right.left = newnode(9) root.right.right.right.right = newnode(10) result = getDeepestLeftLeafNode(root) if result: print(\"Deepest Left Leaf Node ::\", result.data) else: print(\"No result, Left leaf not found\") # This code is contributed by# Shubham Singh(SHUBHAMSINGH10)", "e": 30545, "s": 28804, "text": null }, { "code": "// C# program to find deepest left leaf// node of binary treeusing System;using System.Collections.Generic; class GFG{ // tree nodeclass Node{ public int data; public Node left, right;}; // returns a new tree Nodestatic Node newNode(int data){ Node temp = new Node(); temp.data = data; temp.left = temp.right = null; return temp;} // return the deepest left leaf node// of binary treestatic Node getDeepestLeftLeafNode(Node root){ if (root == null) return null; // create a queue for level order traversal Queue<Node> q = new Queue<Node>(); q.Enqueue(root); Node result = null; // traverse until the queue is empty while (q.Count != 0) { Node temp = q.Peek(); q.Dequeue(); // Since we go level by level, the last // stored left leaf node is deepest one, if (temp.left != null) { q.Enqueue(temp.left); if (temp.left.left == null && temp.left.right == null) result = temp.left; } if (temp.right != null) q.Enqueue(temp.right); } return result;} // Driver Codepublic static void Main(String[] args){ // construct a tree Node root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(4); root.right.left = newNode(5); root.right.right = newNode(6); root.right.left.right = newNode(7); root.right.right.right = newNode(8); root.right.left.right.left = newNode(9); root.right.right.right.right = newNode(10); Node result = getDeepestLeftLeafNode(root); if (result != null) Console.WriteLine(\"Deepest Left Leaf Node :: \" + result.data); else Console.WriteLine(\"No result, \" + \"left leaf not found\"); }} // This code is contributed by Rajput-Ji", "e": 32423, "s": 30545, "text": null }, { "code": "<script> // JavaScript program to find deepest // left leaf node of binary tree class Node { constructor(data) { this.left = null; this.right = null; this.data = data; } } // returns a new tree Node function newNode(data) { let temp = new Node(data); return temp; } // return the deepest left leaf node // of binary tree function getDeepestLeftLeafNode(root) { if (root == null) return null; // create a queue for level order traversal let q = []; q.push(root); let result = null; // traverse until the queue is empty while (q.length > 0) { let temp = q[0]; q.shift(); // Since we go level by level, the last // stored left leaf node is deepest one, if (temp.left != null) { q.push(temp.left); if (temp.left.left == null && temp.left.right == null) result = temp.left; } if (temp.right != null) q.push(temp.right); } return result; } // construct a tree let root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(4); root.right.left = newNode(5); root.right.right = newNode(6); root.right.left.right = newNode(7); root.right.right.right = newNode(8); root.right.left.right.left = newNode(9); root.right.right.right.right = newNode(10); let result = getDeepestLeftLeafNode(root); if (result != null) document.write(\"Deepest Left Leaf Node :: \" + result.data); else document.write(\"No result, \" + \"left leaf not found\"); </script>", "e": 34284, "s": 32423, "text": null }, { "code": null, "e": 34294, "s": 34284, "text": "Output: " }, { "code": null, "e": 34323, "s": 34294, "text": "Deepest Left Leaf Node :: 9 " }, { "code": null, "e": 35182, "s": 34323, "text": "YouTubeGeeksforGeeks500K subscribersDeepest left leaf node in a binary tree | Iterative approach | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 3:15•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=cNBNjZwnPaU\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>" }, { "code": null, "e": 35223, "s": 35182, "text": "?list=PLqM7alHXFySHCXD7r1J0ky9Zg_GBB1dbk" }, { "code": null, "e": 35238, "s": 35223, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 35248, "s": 35238, "text": "Rajput-Ji" }, { "code": null, "e": 35257, "s": 35248, "text": "mukesh07" }, { "code": null, "e": 35274, "s": 35257, "text": "surinderdawra388" }, { "code": null, "e": 35284, "s": 35274, "text": "cpp-queue" }, { "code": null, "e": 35289, "s": 35284, "text": "Tree" }, { "code": null, "e": 35294, "s": 35289, "text": "Tree" }, { "code": null, "e": 35392, "s": 35294, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35401, "s": 35392, "text": "Comments" }, { "code": null, "e": 35414, "s": 35401, "text": "Old Comments" }, { "code": null, "e": 35455, "s": 35414, "text": "Difference between Min Heap and Max Heap" }, { "code": null, "e": 35497, "s": 35455, "text": "2-3 Trees | (Search, Insert and Deletion)" }, { "code": null, "e": 35553, "s": 35497, "text": "Write a program to Calculate Size of a tree | Recursion" }, { "code": null, "e": 35584, "s": 35553, "text": "Maximum width of a binary tree" }, { "code": null, "e": 35631, "s": 35584, "text": "Iterative Method to find Height of Binary Tree" }, { "code": null, "e": 35682, "s": 35631, "text": "Construct a Binary Tree from Postorder and Inorder" }, { "code": null, "e": 35712, "s": 35682, "text": "Evaluation of Expression Tree" }, { "code": null, "e": 35769, "s": 35712, "text": "Find the node with minimum value in a Binary Search Tree" }, { "code": null, "e": 35808, "s": 35769, "text": "Flatten a binary tree into linked list" } ]
Python 3 - List min() Method
The min() method returns the elements from the list with minimum value. Following is the syntax for min() method − min(list) list − This is a list from which min valued element to be returned. This method returns the elements from the list with minimum value. The following example shows the usage of min() method. #!/usr/bin/python3 list1, list2 = ['C++','Java', 'Python'], [456, 700, 200] print ("min value element : ", min(list1)) print ("min value element : ", min(list2)) When we run above program, it produces the following result − min value element : C++ min value element : 200 187 Lectures 17.5 hours Malhar Lathkar 55 Lectures 8 hours Arnab Chakraborty 136 Lectures 11 hours In28Minutes Official 75 Lectures 13 hours Eduonix Learning Solutions 70 Lectures 8.5 hours Lets Kode It 63 Lectures 6 hours Abhilash Nelson Print Add Notes Bookmark this page
[ { "code": null, "e": 2412, "s": 2340, "text": "The min() method returns the elements from the list with minimum value." }, { "code": null, "e": 2455, "s": 2412, "text": "Following is the syntax for min() method −" }, { "code": null, "e": 2466, "s": 2455, "text": "min(list)\n" }, { "code": null, "e": 2534, "s": 2466, "text": "list − This is a list from which min valued element to be returned." }, { "code": null, "e": 2601, "s": 2534, "text": "This method returns the elements from the list with minimum value." }, { "code": null, "e": 2656, "s": 2601, "text": "The following example shows the usage of min() method." }, { "code": null, "e": 2819, "s": 2656, "text": "#!/usr/bin/python3\n\nlist1, list2 = ['C++','Java', 'Python'], [456, 700, 200]\nprint (\"min value element : \", min(list1))\nprint (\"min value element : \", min(list2))" }, { "code": null, "e": 2881, "s": 2819, "text": "When we run above program, it produces the following result −" }, { "code": null, "e": 2932, "s": 2881, "text": "min value element : C++\nmin value element : 200\n" }, { "code": null, "e": 2969, "s": 2932, "text": "\n 187 Lectures \n 17.5 hours \n" }, { "code": null, "e": 2985, "s": 2969, "text": " Malhar Lathkar" }, { "code": null, "e": 3018, "s": 2985, "text": "\n 55 Lectures \n 8 hours \n" }, { "code": null, "e": 3037, "s": 3018, "text": " Arnab Chakraborty" }, { "code": null, "e": 3072, "s": 3037, "text": "\n 136 Lectures \n 11 hours \n" }, { "code": null, "e": 3094, "s": 3072, "text": " In28Minutes Official" }, { "code": null, "e": 3128, "s": 3094, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 3156, "s": 3128, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 3191, "s": 3156, "text": "\n 70 Lectures \n 8.5 hours \n" }, { "code": null, "e": 3205, "s": 3191, "text": " Lets Kode It" }, { "code": null, "e": 3238, "s": 3205, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 3255, "s": 3238, "text": " Abhilash Nelson" }, { "code": null, "e": 3262, "s": 3255, "text": " Print" }, { "code": null, "e": 3273, "s": 3262, "text": " Add Notes" } ]
Python | Holidays library - GeeksforGeeks
17 Jul, 2018 Python Holidays library is an efficient library for determining whether a specific date is a holiday as fast and flexible as possible. For any country, one can find whether that day is a holiday or not. Only fixed days(Public) holidays like Christmas, New Year, etc. can be detected. Installation: pip install holidays Syntax: holidays.HolidayBase(years=[], expand=True, observed=True, prov=None, state=None) Parameters: years : An iterable list of integers specifying the years that the Holiday object should pre-generate. This would generally only be used if setting expand to False. (Default[]) expand : A boolean value which specifies whether or not to append holidays in new years to the holidays object. (Default: True) observed : A boolean value which when set to True will include the observed day of a holiday that falls on a weekend, when appropriate. (Default: True) prov : A string specifying a province that has unique statutory holidays. (Default: Australia=’ACT’, Canada=’ON’, NewZealand=None) state : A string specifying a state that has unique statutory holidays. (Default: UnitedStates=None) Methods: get(key, default=None): Returns a string containing the name of the holiday(s) in date key, which can be of date, datetime, string, unicode, bytes, integer or float type. If multiple holidays fall on the same date the names will be separated by commas. get_list(key): Same as get except returns a list of holiday names instead of a comma-separated string. pop(key, default=None): Same as get, except the key is removed from the holiday object update/append. Accepts dictionary of {date: name} pairs, a list of dates, or even singular date/string/timestamp objects and adds them to the list of holidays. Code #1 : For a Particular Country and Year display all Holidays. from datetime import dateimport holidays # Select countryuk_holidays = holidays.UnitedKingdom() # Print all the holidays in UnitedKingdom in year 2018for ptr in holidays.UnitedKingdom(years = 2018).items(): print(ptr) Output: (datetime.date(2018, 1, 1), "New Year's Day") (datetime.date(2018, 1, 2), 'New Year Holiday [Scotland]') (datetime.date(2018, 3, 17), "St. Patrick's Day [Northern Ireland]") (datetime.date(2018, 3, 19), "St. Patrick's Day [Northern Ireland] (Observed)") (datetime.date(2018, 3, 30), 'Good Friday') (datetime.date(2018, 4, 2), 'Easter Monday [England, Wales, Northern Ireland]') (datetime.date(2018, 5, 7), 'May Day') (datetime.date(2018, 5, 28), 'Spring Bank Holiday') (datetime.date(2018, 7, 12), 'Battle of the Boyne [Northern Ireland]') (datetime.date(2018, 8, 6), 'Summer Bank Holiday [Scotland]') (datetime.date(2018, 8, 27), 'Late Summer Bank Holiday [England, Wales, Northern Ireland]') (datetime.date(2018, 11, 30), "St. Andrew's Day [Scotland]") (datetime.date(2018, 12, 25), 'Christmas Day') (datetime.date(2018, 12, 26), 'Boxing Day') Code #2 : Check whether a given date is holiday or not from datetime import dateimport holidays # Select countryuk_holidays = holidays.UnitedKingdom() # If it is a holidays then it returns True else Falseprint('01-01-2018' in uk_holidays)print('02-01-2018' in uk_holidays) # What holidays is it?print(uk_holidays.get('01-01-2018'))print(uk_holidays.get('02-01-2018')) Output: True False New Year's Day None Code #3 : Holidays in North America from datetime import dateimport holidays # Combining Countriesnorth_america = holidays.CA() + holidays.US() + holidays.MX()# Output list of countries combinedprint(north_america.country) print(north_america.get('07-01-2018'))print(north_america.get('07-04-2018')) Output: ['CA', 'US', 'MX'] Canada Day Independence Day List of Countries included in Holiday Library – In this Library, many countries are missing. So, we can make own Custom Holidays. Code #4 : Custom Holidays adding for India from datetime import dateimport holidays in_holidays = holidays.HolidayBase() # Let's check our republic dayprint('26-01-2019' in in_holidays) # Add Holiday without descriptionin_holidays.append('26-01-2019') # Let's verifyprint('26-01-2019' in in_holidays) # True # Let's Check Descriptionprint(in_holidays.get('26-01-2019')) # Add Holiday with descriptionin_holidays.append({'26-01-2019':'Republic Day India'})print(in_holidays.get('26-01-2019')) # Add list of Dates Togetherin_holidays.append(['02-10-2018', '15-08-2018'])print('15-08-2018' in in_holidays) # Trueprint('02-10-2018' in in_holidays) # True # a single date itemin_holidays.append(date(2018, 12, 25))print('25-12-2018' in in_holidays) # True Output: False True Holiday Republic Day India, Holiday True True True Reference: https://pypi.org/project/holidays/ Python-Library Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install PIP on Windows ? How to drop one or multiple columns in Pandas Dataframe Selecting rows in pandas DataFrame based on conditions How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | os.path.join() method Python | Get unique values from a list Create a directory in Python Defaultdict in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 24316, "s": 24288, "text": "\n17 Jul, 2018" }, { "code": null, "e": 24600, "s": 24316, "text": "Python Holidays library is an efficient library for determining whether a specific date is a holiday as fast and flexible as possible. For any country, one can find whether that day is a holiday or not. Only fixed days(Public) holidays like Christmas, New Year, etc. can be detected." }, { "code": null, "e": 24614, "s": 24600, "text": "Installation:" }, { "code": null, "e": 24635, "s": 24614, "text": "pip install holidays" }, { "code": null, "e": 24643, "s": 24635, "text": "Syntax:" }, { "code": null, "e": 24725, "s": 24643, "text": "holidays.HolidayBase(years=[], expand=True, observed=True, prov=None, state=None)" }, { "code": null, "e": 24737, "s": 24725, "text": "Parameters:" }, { "code": null, "e": 24914, "s": 24737, "text": "years : An iterable list of integers specifying the years that the Holiday object should pre-generate. This would generally only be used if setting expand to False. (Default[])" }, { "code": null, "e": 25042, "s": 24914, "text": "expand : A boolean value which specifies whether or not to append holidays in new years to the holidays object. (Default: True)" }, { "code": null, "e": 25194, "s": 25042, "text": "observed : A boolean value which when set to True will include the observed day of a holiday that falls on a weekend, when appropriate. (Default: True)" }, { "code": null, "e": 25325, "s": 25194, "text": "prov : A string specifying a province that has unique statutory holidays. (Default: Australia=’ACT’, Canada=’ON’, NewZealand=None)" }, { "code": null, "e": 25426, "s": 25325, "text": "state : A string specifying a state that has unique statutory holidays. (Default: UnitedStates=None)" }, { "code": null, "e": 25435, "s": 25426, "text": "Methods:" }, { "code": null, "e": 25688, "s": 25435, "text": "get(key, default=None): Returns a string containing the name of the holiday(s) in date key, which can be of date, datetime, string, unicode, bytes, integer or float type. If multiple holidays fall on the same date the names will be separated by commas." }, { "code": null, "e": 25791, "s": 25688, "text": "get_list(key): Same as get except returns a list of holiday names instead of a comma-separated string." }, { "code": null, "e": 26038, "s": 25791, "text": "pop(key, default=None): Same as get, except the key is removed from the holiday object update/append. Accepts dictionary of {date: name} pairs, a list of dates, or even singular date/string/timestamp objects and adds them to the list of holidays." }, { "code": null, "e": 26104, "s": 26038, "text": "Code #1 : For a Particular Country and Year display all Holidays." }, { "code": "from datetime import dateimport holidays # Select countryuk_holidays = holidays.UnitedKingdom() # Print all the holidays in UnitedKingdom in year 2018for ptr in holidays.UnitedKingdom(years = 2018).items(): print(ptr)", "e": 26327, "s": 26104, "text": null }, { "code": null, "e": 26335, "s": 26327, "text": "Output:" }, { "code": null, "e": 27182, "s": 26335, "text": "(datetime.date(2018, 1, 1), \"New Year's Day\")\n(datetime.date(2018, 1, 2), 'New Year Holiday [Scotland]')\n(datetime.date(2018, 3, 17), \"St. Patrick's Day [Northern Ireland]\")\n(datetime.date(2018, 3, 19), \"St. Patrick's Day [Northern Ireland] (Observed)\")\n(datetime.date(2018, 3, 30), 'Good Friday')\n(datetime.date(2018, 4, 2), 'Easter Monday [England, Wales, Northern Ireland]')\n(datetime.date(2018, 5, 7), 'May Day')\n(datetime.date(2018, 5, 28), 'Spring Bank Holiday')\n(datetime.date(2018, 7, 12), 'Battle of the Boyne [Northern Ireland]')\n(datetime.date(2018, 8, 6), 'Summer Bank Holiday [Scotland]')\n(datetime.date(2018, 8, 27), 'Late Summer Bank Holiday [England, Wales, Northern Ireland]')\n(datetime.date(2018, 11, 30), \"St. Andrew's Day [Scotland]\")\n(datetime.date(2018, 12, 25), 'Christmas Day')\n(datetime.date(2018, 12, 26), 'Boxing Day')\n" }, { "code": null, "e": 27238, "s": 27182, "text": " Code #2 : Check whether a given date is holiday or not" }, { "code": "from datetime import dateimport holidays # Select countryuk_holidays = holidays.UnitedKingdom() # If it is a holidays then it returns True else Falseprint('01-01-2018' in uk_holidays)print('02-01-2018' in uk_holidays) # What holidays is it?print(uk_holidays.get('01-01-2018'))print(uk_holidays.get('02-01-2018'))", "e": 27554, "s": 27238, "text": null }, { "code": null, "e": 27562, "s": 27554, "text": "Output:" }, { "code": null, "e": 27594, "s": 27562, "text": "True\nFalse\nNew Year's Day\nNone\n" }, { "code": null, "e": 27631, "s": 27594, "text": " Code #3 : Holidays in North America" }, { "code": "from datetime import dateimport holidays # Combining Countriesnorth_america = holidays.CA() + holidays.US() + holidays.MX()# Output list of countries combinedprint(north_america.country) print(north_america.get('07-01-2018'))print(north_america.get('07-04-2018'))", "e": 27897, "s": 27631, "text": null }, { "code": null, "e": 27905, "s": 27897, "text": "Output:" }, { "code": null, "e": 27953, "s": 27905, "text": "['CA', 'US', 'MX']\nCanada Day\nIndependence Day\n" }, { "code": null, "e": 28003, "s": 27955, "text": "List of Countries included in Holiday Library –" }, { "code": null, "e": 28085, "s": 28003, "text": "In this Library, many countries are missing. So, we can make own Custom Holidays." }, { "code": null, "e": 28128, "s": 28085, "text": "Code #4 : Custom Holidays adding for India" }, { "code": "from datetime import dateimport holidays in_holidays = holidays.HolidayBase() # Let's check our republic dayprint('26-01-2019' in in_holidays) # Add Holiday without descriptionin_holidays.append('26-01-2019') # Let's verifyprint('26-01-2019' in in_holidays) # True # Let's Check Descriptionprint(in_holidays.get('26-01-2019')) # Add Holiday with descriptionin_holidays.append({'26-01-2019':'Republic Day India'})print(in_holidays.get('26-01-2019')) # Add list of Dates Togetherin_holidays.append(['02-10-2018', '15-08-2018'])print('15-08-2018' in in_holidays) # Trueprint('02-10-2018' in in_holidays) # True # a single date itemin_holidays.append(date(2018, 12, 25))print('25-12-2018' in in_holidays) # True", "e": 28846, "s": 28128, "text": null }, { "code": null, "e": 28854, "s": 28846, "text": "Output:" }, { "code": null, "e": 28923, "s": 28854, "text": "False \nTrue \nHoliday \nRepublic Day India, Holiday\nTrue \nTrue \nTrue \n" }, { "code": null, "e": 28970, "s": 28923, "text": " Reference: https://pypi.org/project/holidays/" }, { "code": null, "e": 28985, "s": 28970, "text": "Python-Library" }, { "code": null, "e": 28992, "s": 28985, "text": "Python" }, { "code": null, "e": 29090, "s": 28992, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29099, "s": 29090, "text": "Comments" }, { "code": null, "e": 29112, "s": 29099, "text": "Old Comments" }, { "code": null, "e": 29144, "s": 29112, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29200, "s": 29144, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 29255, "s": 29200, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 29297, "s": 29255, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 29339, "s": 29297, "text": "Check if element exists in list in Python" }, { "code": null, "e": 29370, "s": 29339, "text": "Python | os.path.join() method" }, { "code": null, "e": 29409, "s": 29370, "text": "Python | Get unique values from a list" }, { "code": null, "e": 29438, "s": 29409, "text": "Create a directory in Python" }, { "code": null, "e": 29460, "s": 29438, "text": "Defaultdict in Python" } ]
Construct an array from GCDs of consecutive elements in given array - GeeksforGeeks
05 May, 2021 Given an array a[] of n elements. The task is to find the array (say b[]) of n + 1 such that Greatest Common Divisor of b[i] and b[i + 1] is equals to a[i]. If multiple solution exists, print the one whose array sum is minimum.Examples: Input : a[] = { 1, 2, 3 } Output : 1 2 6 3 GCD(1, 2) = 1 GCD(2, 6) = 2 GCD(6, 3) = 3 Also, 1 + 2 + 6 + 3 = 12 which is smallest among all possible value of array that can be constructed. Input : a[] = { 5, 10, 5 } Output : 5 10 10 5 Suppose there is only one number in the given array a[]. Let it be K, then both numbers in the constructed array (say b[]) will be K and K.So, the value of the b[0] will be a[0] only. Now consider that, we are done upto index i i.e we have already processed upto index i and calculated b[i + 1].Now the gcd(b[i + 1], b[i + 2]) = a[i + 1] and gcd(b[i + 2], b[i + 3]) = a[i + 2]. So, b[i + 2] >= lcm(a[i + 1], a[i + 2]). Or, b[i + 2] will be multiple of lcm(a[i + 1], a[i + 2]). As we want the minimum sum, so we want the minimum value of b[i + 2]. So, b[i + 2] = lcm(a[i + 2], a[i + 3]).Below is the implementation of this approach: C++ Java Python3 C# PHP Javascript // CPP Program to construct an array whose GCD of// every consecutive element is the given array#include <bits/stdc++.h>using namespace std; // Return the LCM of two numbers.int lcm(int a, int b){ return (a * b) / __gcd(a, b);} // Print the required constructed arrayvoid printArray(int a[], int n){ // printing the first element. cout << a[0] << " "; // finding and printing the LCM of consecutive // element of given array. for (int i = 0; i < n - 1; i++) cout << lcm(a[i], a[i + 1]) << " "; // printing the last element of the given array. cout << a[n - 1] << endl;} // Driven Programint main(){ int a[] = { 1, 2, 3 }; int n = sizeof(a) / sizeof(a[0]); printArray(a, n); return 0;} // Java Program to construct an array whose// GCD of every consecutive element is the// given array import java.io.*; class GFG { // Recursive function to return gcd of // a and b static int __gcd(int a, int b) { // Everything divides 0 if (a == 0 || b == 0) return 0; // base case if (a == b) return a; // a is greater if (a > b) return __gcd(a - b, b); return __gcd(a, b - a); } // Return the LCM of two numbers. static int lcm(int a, int b) { return (a * b) / __gcd(a, b); } // Print the required constructed array static void printArray(int a[], int n) { // printing the first element. System.out.print( a[0] + " "); // finding and printing the LCM of // consecutive element of given array. for (int i = 0; i < n - 1; i++) System.out.print(lcm(a[i], a[i + 1]) + " "); // printing the last element of the // given array. System.out.print(a[n - 1]); } // Driven Program public static void main (String[] args) { int a[] = { 1, 2, 3 }; int n = a.length; printArray(a, n); }} // This code is contributed by anuj_67. # Python Program to construct an array whose# GCD of every consecutive element is the# given array # Recursive function to return gcd of# a and bdef __gcd( a, b): # Everything divides 0 if (a == 0 or b == 0): return 0 # base case if (a == b): return a # a is greater if (a > b): return __gcd(a - b, b) return __gcd(a, b - a) # Return the LCM of two numbers.def lcm(a, b): return (a * b) / __gcd(a, b) # Print the required constructed arraydef printArray(a, n): # printing the first element. print ( str(a[0]) + " ") # finding and printing the LCM of # consecutive element of given array. for i in range(0,n-1): print (str(lcm(a[i],a[i + 1])) + " ") # printing the last element of the # given array. print (a[n - 1]) # Driver codea = [1, 2, 3 ]n = len(a)printArray(a, n) # This code is contributed by Prateek Bajaj // C# Program to construct an array whose// GCD of every consecutive element is the// given arrayusing System;class GFG { // Recursive function to return // gcd of a and b static int __gcd(int a, int b) { // Everything divides 0 if (a == 0 || b == 0) return 0; // base case if (a == b) return a; // a is greater if (a > b) return __gcd(a - b, b); return __gcd(a, b - a); } // Return the LCM of two numbers. static int lcm(int a, int b) { return (a * b) / __gcd(a, b); } // Print the required constructed array static void printArray(int []a, int n) { // printing the first element. Console.Write( a[0] + " "); // finding and printing the LCM of // consecutive element of given array. for (int i = 0; i < n - 1; i++) Console.Write(lcm(a[i], a[i + 1]) + " "); // printing the last element // of the given array. Console.Write(a[n - 1]); } // Driver Code public static void Main () { int []a = {1, 2, 3}; int n = a.Length; printArray(a, n); }} // This code is contributed by anuj_67. <?php// PHP Program to construct// an array whose GCD of// every consecutive element// is the given array // Recursive function to// return gcd of a and bfunction __gcd($a, $b){ // Everything divides 0 if($a == 0 or $b == 0) return 0 ; // base case if($a == $b) return $a ; // a is greater if($a > $b) return __gcd( $a - $b , $b ) ; return __gcd( $a , $b - $a ) ;} // Return the LCM of two numbers.function lcm($a, $b){ return ($a * $b) / __gcd($a, $b);} // Print the required constructed arrayfunction printArray( $a, $n){ // printing the first element. echo $a[0] , " "; // finding and printing // the LCM of consecutive // element of given array. for ( $i = 0; $i < $n - 1; $i++) echo lcm($a[$i], $a[$i + 1]) , " "; // printing the last element // of the given array. echo $a[$n - 1] ,"\n";} // Driver Code $a = array(1, 2, 3); $n = count($a); printArray($a, $n); // This code is contributed by anuj_67.?> <script> // Javascript Program to construct an array whose GCD of// every consecutive element is the given array function __gcd(a, b) { // Everything divides 0 if (a == 0 || b == 0) return 0; // base case if (a == b) return a; // a is greater if (a > b) return __gcd(a - b, b); return __gcd(a, b - a); } // Return the LCM of two numbers.function lcm(a, b){ return (a * b) / __gcd(a, b);} // Print the required constructed arrayfunction printArray(a, n){ // printing the first element. document.write( a[0] + " "); // finding and printing the LCM of consecutive // element of given array. for (var i = 0; i < n - 1; i++) document.write( lcm(a[i], a[i + 1]) + " "); // printing the last element of the given array. document.write( a[n - 1] + "<br>");} // Driven Programvar a = [ 1, 2, 3 ];var n = a.length;printArray(a, n); // This code is contributed by rrrtnx.</script> Output 1 2 6 3 vt_m Prateek Bajaj rrrtnx GCD-LCM Arrays Mathematical Arrays Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Window Sliding Technique Building Heap from Array Trapping Rain Water Reversal algorithm for array rotation Program to find sum of elements in a given array Program for Fibonacci numbers Write a program to print all permutations of a given string C++ Data Types Set in C++ Standard Template Library (STL) Coin Change | DP-7
[ { "code": null, "e": 24820, "s": 24792, "text": "\n05 May, 2021" }, { "code": null, "e": 25059, "s": 24820, "text": "Given an array a[] of n elements. The task is to find the array (say b[]) of n + 1 such that Greatest Common Divisor of b[i] and b[i + 1] is equals to a[i]. If multiple solution exists, print the one whose array sum is minimum.Examples: " }, { "code": null, "e": 25293, "s": 25059, "text": "Input : a[] = { 1, 2, 3 }\nOutput : 1 2 6 3\nGCD(1, 2) = 1\nGCD(2, 6) = 2\nGCD(6, 3) = 3\nAlso, 1 + 2 + 6 + 3 = 12 which is smallest among all\npossible value of array that can be constructed.\n\nInput : a[] = { 5, 10, 5 }\nOutput : 5 10 10 5" }, { "code": null, "e": 25929, "s": 25295, "text": "Suppose there is only one number in the given array a[]. Let it be K, then both numbers in the constructed array (say b[]) will be K and K.So, the value of the b[0] will be a[0] only. Now consider that, we are done upto index i i.e we have already processed upto index i and calculated b[i + 1].Now the gcd(b[i + 1], b[i + 2]) = a[i + 1] and gcd(b[i + 2], b[i + 3]) = a[i + 2]. So, b[i + 2] >= lcm(a[i + 1], a[i + 2]). Or, b[i + 2] will be multiple of lcm(a[i + 1], a[i + 2]). As we want the minimum sum, so we want the minimum value of b[i + 2]. So, b[i + 2] = lcm(a[i + 2], a[i + 3]).Below is the implementation of this approach: " }, { "code": null, "e": 25933, "s": 25929, "text": "C++" }, { "code": null, "e": 25938, "s": 25933, "text": "Java" }, { "code": null, "e": 25946, "s": 25938, "text": "Python3" }, { "code": null, "e": 25949, "s": 25946, "text": "C#" }, { "code": null, "e": 25953, "s": 25949, "text": "PHP" }, { "code": null, "e": 25964, "s": 25953, "text": "Javascript" }, { "code": "// CPP Program to construct an array whose GCD of// every consecutive element is the given array#include <bits/stdc++.h>using namespace std; // Return the LCM of two numbers.int lcm(int a, int b){ return (a * b) / __gcd(a, b);} // Print the required constructed arrayvoid printArray(int a[], int n){ // printing the first element. cout << a[0] << \" \"; // finding and printing the LCM of consecutive // element of given array. for (int i = 0; i < n - 1; i++) cout << lcm(a[i], a[i + 1]) << \" \"; // printing the last element of the given array. cout << a[n - 1] << endl;} // Driven Programint main(){ int a[] = { 1, 2, 3 }; int n = sizeof(a) / sizeof(a[0]); printArray(a, n); return 0;}", "e": 26694, "s": 25964, "text": null }, { "code": "// Java Program to construct an array whose// GCD of every consecutive element is the// given array import java.io.*; class GFG { // Recursive function to return gcd of // a and b static int __gcd(int a, int b) { // Everything divides 0 if (a == 0 || b == 0) return 0; // base case if (a == b) return a; // a is greater if (a > b) return __gcd(a - b, b); return __gcd(a, b - a); } // Return the LCM of two numbers. static int lcm(int a, int b) { return (a * b) / __gcd(a, b); } // Print the required constructed array static void printArray(int a[], int n) { // printing the first element. System.out.print( a[0] + \" \"); // finding and printing the LCM of // consecutive element of given array. for (int i = 0; i < n - 1; i++) System.out.print(lcm(a[i], a[i + 1]) + \" \"); // printing the last element of the // given array. System.out.print(a[n - 1]); } // Driven Program public static void main (String[] args) { int a[] = { 1, 2, 3 }; int n = a.length; printArray(a, n); }} // This code is contributed by anuj_67.", "e": 28028, "s": 26694, "text": null }, { "code": "# Python Program to construct an array whose# GCD of every consecutive element is the# given array # Recursive function to return gcd of# a and bdef __gcd( a, b): # Everything divides 0 if (a == 0 or b == 0): return 0 # base case if (a == b): return a # a is greater if (a > b): return __gcd(a - b, b) return __gcd(a, b - a) # Return the LCM of two numbers.def lcm(a, b): return (a * b) / __gcd(a, b) # Print the required constructed arraydef printArray(a, n): # printing the first element. print ( str(a[0]) + \" \") # finding and printing the LCM of # consecutive element of given array. for i in range(0,n-1): print (str(lcm(a[i],a[i + 1])) + \" \") # printing the last element of the # given array. print (a[n - 1]) # Driver codea = [1, 2, 3 ]n = len(a)printArray(a, n) # This code is contributed by Prateek Bajaj", "e": 28984, "s": 28028, "text": null }, { "code": "// C# Program to construct an array whose// GCD of every consecutive element is the// given arrayusing System;class GFG { // Recursive function to return // gcd of a and b static int __gcd(int a, int b) { // Everything divides 0 if (a == 0 || b == 0) return 0; // base case if (a == b) return a; // a is greater if (a > b) return __gcd(a - b, b); return __gcd(a, b - a); } // Return the LCM of two numbers. static int lcm(int a, int b) { return (a * b) / __gcd(a, b); } // Print the required constructed array static void printArray(int []a, int n) { // printing the first element. Console.Write( a[0] + \" \"); // finding and printing the LCM of // consecutive element of given array. for (int i = 0; i < n - 1; i++) Console.Write(lcm(a[i], a[i + 1]) + \" \"); // printing the last element // of the given array. Console.Write(a[n - 1]); } // Driver Code public static void Main () { int []a = {1, 2, 3}; int n = a.Length; printArray(a, n); }} // This code is contributed by anuj_67.", "e": 30264, "s": 28984, "text": null }, { "code": "<?php// PHP Program to construct// an array whose GCD of// every consecutive element// is the given array // Recursive function to// return gcd of a and bfunction __gcd($a, $b){ // Everything divides 0 if($a == 0 or $b == 0) return 0 ; // base case if($a == $b) return $a ; // a is greater if($a > $b) return __gcd( $a - $b , $b ) ; return __gcd( $a , $b - $a ) ;} // Return the LCM of two numbers.function lcm($a, $b){ return ($a * $b) / __gcd($a, $b);} // Print the required constructed arrayfunction printArray( $a, $n){ // printing the first element. echo $a[0] , \" \"; // finding and printing // the LCM of consecutive // element of given array. for ( $i = 0; $i < $n - 1; $i++) echo lcm($a[$i], $a[$i + 1]) , \" \"; // printing the last element // of the given array. echo $a[$n - 1] ,\"\\n\";} // Driver Code $a = array(1, 2, 3); $n = count($a); printArray($a, $n); // This code is contributed by anuj_67.?>", "e": 31284, "s": 30264, "text": null }, { "code": "<script> // Javascript Program to construct an array whose GCD of// every consecutive element is the given array function __gcd(a, b) { // Everything divides 0 if (a == 0 || b == 0) return 0; // base case if (a == b) return a; // a is greater if (a > b) return __gcd(a - b, b); return __gcd(a, b - a); } // Return the LCM of two numbers.function lcm(a, b){ return (a * b) / __gcd(a, b);} // Print the required constructed arrayfunction printArray(a, n){ // printing the first element. document.write( a[0] + \" \"); // finding and printing the LCM of consecutive // element of given array. for (var i = 0; i < n - 1; i++) document.write( lcm(a[i], a[i + 1]) + \" \"); // printing the last element of the given array. document.write( a[n - 1] + \"<br>\");} // Driven Programvar a = [ 1, 2, 3 ];var n = a.length;printArray(a, n); // This code is contributed by rrrtnx.</script>", "e": 32295, "s": 31284, "text": null }, { "code": null, "e": 32304, "s": 32295, "text": "Output " }, { "code": null, "e": 32312, "s": 32304, "text": "1 2 6 3" }, { "code": null, "e": 32319, "s": 32314, "text": "vt_m" }, { "code": null, "e": 32333, "s": 32319, "text": "Prateek Bajaj" }, { "code": null, "e": 32340, "s": 32333, "text": "rrrtnx" }, { "code": null, "e": 32348, "s": 32340, "text": "GCD-LCM" }, { "code": null, "e": 32355, "s": 32348, "text": "Arrays" }, { "code": null, "e": 32368, "s": 32355, "text": "Mathematical" }, { "code": null, "e": 32375, "s": 32368, "text": "Arrays" }, { "code": null, "e": 32388, "s": 32375, "text": "Mathematical" }, { "code": null, "e": 32486, "s": 32388, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32511, "s": 32486, "text": "Window Sliding Technique" }, { "code": null, "e": 32536, "s": 32511, "text": "Building Heap from Array" }, { "code": null, "e": 32556, "s": 32536, "text": "Trapping Rain Water" }, { "code": null, "e": 32594, "s": 32556, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 32643, "s": 32594, "text": "Program to find sum of elements in a given array" }, { "code": null, "e": 32673, "s": 32643, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 32733, "s": 32673, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 32748, "s": 32733, "text": "C++ Data Types" }, { "code": null, "e": 32791, "s": 32748, "text": "Set in C++ Standard Template Library (STL)" } ]
Extract decimal numbers from a string in Python
Using RegEx module is the fastest way. >>> import re Assuming that the string contains integer and floating point numbers as well as below − >>> s='my age is 25. I have 55.50 percent marks and 9764135408 is my number' the findall() function returns a list of numbers matching given pattern which includes digit before and after decimal point >>> re.findall('\d*\.?\d+',s) Result is a list object of all numbers ['25', '55.50', '9764135408']
[ { "code": null, "e": 1101, "s": 1062, "text": "Using RegEx module is the fastest way." }, { "code": null, "e": 1115, "s": 1101, "text": ">>> import re" }, { "code": null, "e": 1203, "s": 1115, "text": "Assuming that the string contains integer and floating point numbers as well as below −" }, { "code": null, "e": 1280, "s": 1203, "text": ">>> s='my age is 25. I have 55.50 percent marks and 9764135408 is my number'" }, { "code": null, "e": 1404, "s": 1280, "text": "the findall() function returns a list of numbers matching given pattern which includes digit before and after decimal point" }, { "code": null, "e": 1434, "s": 1404, "text": ">>> re.findall('\\d*\\.?\\d+',s)" }, { "code": null, "e": 1473, "s": 1434, "text": "Result is a list object of all numbers" }, { "code": null, "e": 1503, "s": 1473, "text": "['25', '55.50', '9764135408']" } ]
HTML - <spacer> Tag
The HTML <spacer> tag specifies a whitespace. <!DOCTYPE html> <html> <head> <title>HTML spacer Tag</title> </head> <body> Create some space <spacer type = "block" width = "50" /> here. </body> </html> <spacer> tag is available in Netscape 4 and higher version only. This will produce the following result − This tag supports all the global attributes described in − HTML Attribute Reference The HTML <object> tag also supports the following additional attributes − This tag supports all the event attributes described in − HTML Events Reference This tag is available in Netscape 4 and higher version only. 19 Lectures 2 hours Anadi Sharma 16 Lectures 1.5 hours Anadi Sharma 18 Lectures 1.5 hours Frahaan Hussain 57 Lectures 5.5 hours DigiFisk (Programming Is Fun) 54 Lectures 6 hours DigiFisk (Programming Is Fun) 45 Lectures 5.5 hours DigiFisk (Programming Is Fun) Print Add Notes Bookmark this page
[ { "code": null, "e": 2420, "s": 2374, "text": "The HTML <spacer> tag specifies a whitespace." }, { "code": null, "e": 2602, "s": 2420, "text": "<!DOCTYPE html>\n<html>\n\n <head>\n <title>HTML spacer Tag</title>\n </head>\n\n <body>\n Create some space <spacer type = \"block\" width = \"50\" /> here.\n </body>\n\n</html>" }, { "code": null, "e": 2708, "s": 2602, "text": "<spacer> tag is available in Netscape 4 and higher version only. This will produce the following result −" }, { "code": null, "e": 2792, "s": 2708, "text": "This tag supports all the global attributes described in − HTML Attribute Reference" }, { "code": null, "e": 2866, "s": 2792, "text": "The HTML <object> tag also supports the following additional attributes −" }, { "code": null, "e": 2946, "s": 2866, "text": "This tag supports all the event attributes described in − HTML Events Reference" }, { "code": null, "e": 3007, "s": 2946, "text": "This tag is available in Netscape 4 and higher version only." }, { "code": null, "e": 3040, "s": 3007, "text": "\n 19 Lectures \n 2 hours \n" }, { "code": null, "e": 3054, "s": 3040, "text": " Anadi Sharma" }, { "code": null, "e": 3089, "s": 3054, "text": "\n 16 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3103, "s": 3089, "text": " Anadi Sharma" }, { "code": null, "e": 3138, "s": 3103, "text": "\n 18 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3155, "s": 3138, "text": " Frahaan Hussain" }, { "code": null, "e": 3190, "s": 3155, "text": "\n 57 Lectures \n 5.5 hours \n" }, { "code": null, "e": 3221, "s": 3190, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 3254, "s": 3221, "text": "\n 54 Lectures \n 6 hours \n" }, { "code": null, "e": 3285, "s": 3254, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 3320, "s": 3285, "text": "\n 45 Lectures \n 5.5 hours \n" }, { "code": null, "e": 3351, "s": 3320, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 3358, "s": 3351, "text": " Print" }, { "code": null, "e": 3369, "s": 3358, "text": " Add Notes" } ]
Monitor and Find Statistics for Linux Procesess Using pidstat Tool - GeeksforGeeks
01 Feb, 2021 Pidstat is a command-line tool and part of sysstat suite to monitor the Linux system. It is used to monitor every individual task currently being managed by the Linux kernel on the Linux system. Features of pistat: It can monitor every task running on the systemIt can also monitor the child’s task of any task.It shows the total CPU usage by every task.It can monitor read and write data on disk by the task. It can monitor every task running on the system It can also monitor the child’s task of any task. It shows the total CPU usage by every task. It can monitor read and write data on disk by the task. Now, let’s see how to install pidstat on the system. As we see before pidstat is part of sysstat suite therefore we need to install the sysstat on the system. To install on Debian based system like ubuntu or kali Linux run the command: sudo apt-get install sysstat To install on systems like CentOS / Fedora / RHEL Linux run the command: yum install sysstat To monitor specific task running on a system run the pidstat with -p argument and after -p argument write the PID of taste but to monitor all current active task on the system we can use pidstart -p All command which is equivalent to just pidstat command, Now let’s see how will be the output of pistat to see active tasks run the following command on terminal: pidtat Output: Tuple information: The output shows the following information about the system: Kernel: Pidstat show which Linux kernel running on the system. CPU architecture: It shows the architecture of the CPU whether it is 64 bit or 32 bit. No. Of CPUs: This shows the total no. of processors in the system. pidtstat show the following common information about the tasks: UID: UID is a user identifier assigned by the Linux system to every user on the system. 0 UID is reserved for root.PID: PID is the process ID. This is a unique number assigned to every process running on the system by using PID system to identify the processes.%usr: Percentage of CPU usage by the process at the user level.%system: Percentage of CPU usage by the process at system level or kernel level%guest: Percentage of CPU usage by the process Percentage of CPU spent by the task in a virtual machine (running a virtual processor).%CPU: Total Percentage of CPU usage by that task.CPU: This field shows the processor number task on which that task is running.Command: The filed shows the command name of that task. UID: UID is a user identifier assigned by the Linux system to every user on the system. 0 UID is reserved for root. PID: PID is the process ID. This is a unique number assigned to every process running on the system by using PID system to identify the processes. %usr: Percentage of CPU usage by the process at the user level. %system: Percentage of CPU usage by the process at system level or kernel level %guest: Percentage of CPU usage by the process Percentage of CPU spent by the task in a virtual machine (running a virtual processor). %CPU: Total Percentage of CPU usage by that task. CPU: This field shows the processor number task on which that task is running. Command: The filed shows the command name of that task. Now let’s see some options or arguments we can use with pidstat. The following are the arguments we can use with pistat: 1) -C string: This argument shows the tasks which contain the given string in their command name. To use the -C option with the pidstat run the following command: pidstat -C string The following image shows the output of pidstat with the -C option and sys as a string. We can see that this output contains tasks that contain sys in their command name. 2) -d: This option shows the output similar to pidstat command but with some different information about the system. To use the -d option on the system use the following command. pidtstat -d The following image shows the output of the command : Let’s see what are the different terms: kB_rd/s: Number of kilobytes the task has caused to be read from disk per second. kB_wr/s: Number of kilobytes the task has caused to be written to disk per second kB_ccwr/s: Number of kilobytes whose writing to disk has been cancel by the task 3) -w: This is the argument that shows the task switching activity of tasks following is the output of the command In this output there are two different terms we can see: cswch/s: Total number of voluntary context switches the task made per second. nvcswch/s: Total number of non-voluntary context switches the task made per second. 4) -t: This option is used to display statistics for threads associated with selected tasks. The output padstat with this command is In this output, there are two different terms we can see: TGID: TGID is the identification number of the thread group leader. TID: The identification number of the thread being monitored. 5) -p: With this argument, we can see information about the specific task by using its PID. Following is the command to use the -p option. pidstat -p PID Output: Linux-Tools Picked Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. nohup Command in Linux with Examples scp command in Linux with Examples Thread functions in C/C++ mv command in Linux with examples chown command in Linux with Examples SED command in Linux | Set 2 Docker - COPY Instruction Array Basics in Shell Scripting | Set 1 Basic Operators in Shell Scripting nslookup command in Linux with Examples
[ { "code": null, "e": 24406, "s": 24378, "text": "\n01 Feb, 2021" }, { "code": null, "e": 24602, "s": 24406, "text": "Pidstat is a command-line tool and part of sysstat suite to monitor the Linux system. It is used to monitor every individual task currently being managed by the Linux kernel on the Linux system. " }, { "code": null, "e": 24622, "s": 24602, "text": "Features of pistat:" }, { "code": null, "e": 24817, "s": 24622, "text": "It can monitor every task running on the systemIt can also monitor the child’s task of any task.It shows the total CPU usage by every task.It can monitor read and write data on disk by the task." }, { "code": null, "e": 24865, "s": 24817, "text": "It can monitor every task running on the system" }, { "code": null, "e": 24915, "s": 24865, "text": "It can also monitor the child’s task of any task." }, { "code": null, "e": 24959, "s": 24915, "text": "It shows the total CPU usage by every task." }, { "code": null, "e": 25015, "s": 24959, "text": "It can monitor read and write data on disk by the task." }, { "code": null, "e": 25174, "s": 25015, "text": "Now, let’s see how to install pidstat on the system. As we see before pidstat is part of sysstat suite therefore we need to install the sysstat on the system." }, { "code": null, "e": 25251, "s": 25174, "text": "To install on Debian based system like ubuntu or kali Linux run the command:" }, { "code": null, "e": 25280, "s": 25251, "text": "sudo apt-get install sysstat" }, { "code": null, "e": 25353, "s": 25280, "text": "To install on systems like CentOS / Fedora / RHEL Linux run the command:" }, { "code": null, "e": 25373, "s": 25353, "text": "yum install sysstat" }, { "code": null, "e": 25735, "s": 25373, "text": "To monitor specific task running on a system run the pidstat with -p argument and after -p argument write the PID of taste but to monitor all current active task on the system we can use pidstart -p All command which is equivalent to just pidstat command, Now let’s see how will be the output of pistat to see active tasks run the following command on terminal:" }, { "code": null, "e": 25742, "s": 25735, "text": "pidtat" }, { "code": null, "e": 25750, "s": 25742, "text": "Output:" }, { "code": null, "e": 25769, "s": 25750, "text": "Tuple information:" }, { "code": null, "e": 25830, "s": 25769, "text": "The output shows the following information about the system:" }, { "code": null, "e": 25893, "s": 25830, "text": "Kernel: Pidstat show which Linux kernel running on the system." }, { "code": null, "e": 25980, "s": 25893, "text": "CPU architecture: It shows the architecture of the CPU whether it is 64 bit or 32 bit." }, { "code": null, "e": 26047, "s": 25980, "text": "No. Of CPUs: This shows the total no. of processors in the system." }, { "code": null, "e": 26111, "s": 26047, "text": "pidtstat show the following common information about the tasks:" }, { "code": null, "e": 26831, "s": 26111, "text": "UID: UID is a user identifier assigned by the Linux system to every user on the system. 0 UID is reserved for root.PID: PID is the process ID. This is a unique number assigned to every process running on the system by using PID system to identify the processes.%usr: Percentage of CPU usage by the process at the user level.%system: Percentage of CPU usage by the process at system level or kernel level%guest: Percentage of CPU usage by the process Percentage of CPU spent by the task in a virtual machine (running a virtual processor).%CPU: Total Percentage of CPU usage by that task.CPU: This field shows the processor number task on which that task is running.Command: The filed shows the command name of that task." }, { "code": null, "e": 26947, "s": 26831, "text": "UID: UID is a user identifier assigned by the Linux system to every user on the system. 0 UID is reserved for root." }, { "code": null, "e": 27094, "s": 26947, "text": "PID: PID is the process ID. This is a unique number assigned to every process running on the system by using PID system to identify the processes." }, { "code": null, "e": 27158, "s": 27094, "text": "%usr: Percentage of CPU usage by the process at the user level." }, { "code": null, "e": 27238, "s": 27158, "text": "%system: Percentage of CPU usage by the process at system level or kernel level" }, { "code": null, "e": 27373, "s": 27238, "text": "%guest: Percentage of CPU usage by the process Percentage of CPU spent by the task in a virtual machine (running a virtual processor)." }, { "code": null, "e": 27423, "s": 27373, "text": "%CPU: Total Percentage of CPU usage by that task." }, { "code": null, "e": 27502, "s": 27423, "text": "CPU: This field shows the processor number task on which that task is running." }, { "code": null, "e": 27558, "s": 27502, "text": "Command: The filed shows the command name of that task." }, { "code": null, "e": 27679, "s": 27558, "text": "Now let’s see some options or arguments we can use with pidstat. The following are the arguments we can use with pistat:" }, { "code": null, "e": 27842, "s": 27679, "text": "1) -C string: This argument shows the tasks which contain the given string in their command name. To use the -C option with the pidstat run the following command:" }, { "code": null, "e": 27860, "s": 27842, "text": "pidstat -C string" }, { "code": null, "e": 28031, "s": 27860, "text": "The following image shows the output of pidstat with the -C option and sys as a string. We can see that this output contains tasks that contain sys in their command name." }, { "code": null, "e": 28210, "s": 28031, "text": "2) -d: This option shows the output similar to pidstat command but with some different information about the system. To use the -d option on the system use the following command." }, { "code": null, "e": 28223, "s": 28210, "text": "pidtstat -d " }, { "code": null, "e": 28277, "s": 28223, "text": "The following image shows the output of the command :" }, { "code": null, "e": 28317, "s": 28277, "text": "Let’s see what are the different terms:" }, { "code": null, "e": 28399, "s": 28317, "text": "kB_rd/s: Number of kilobytes the task has caused to be read from disk per second." }, { "code": null, "e": 28481, "s": 28399, "text": "kB_wr/s: Number of kilobytes the task has caused to be written to disk per second" }, { "code": null, "e": 28562, "s": 28481, "text": "kB_ccwr/s: Number of kilobytes whose writing to disk has been cancel by the task" }, { "code": null, "e": 28678, "s": 28562, "text": "3) -w: This is the argument that shows the task switching activity of tasks following is the output of the command " }, { "code": null, "e": 28740, "s": 28678, "text": "In this output there are two different terms we can see: " }, { "code": null, "e": 28818, "s": 28740, "text": "cswch/s: Total number of voluntary context switches the task made per second." }, { "code": null, "e": 28902, "s": 28818, "text": "nvcswch/s: Total number of non-voluntary context switches the task made per second." }, { "code": null, "e": 29036, "s": 28902, "text": "4) -t: This option is used to display statistics for threads associated with selected tasks. The output padstat with this command is " }, { "code": null, "e": 29094, "s": 29036, "text": "In this output, there are two different terms we can see:" }, { "code": null, "e": 29162, "s": 29094, "text": "TGID: TGID is the identification number of the thread group leader." }, { "code": null, "e": 29224, "s": 29162, "text": "TID: The identification number of the thread being monitored." }, { "code": null, "e": 29363, "s": 29224, "text": "5) -p: With this argument, we can see information about the specific task by using its PID. Following is the command to use the -p option." }, { "code": null, "e": 29378, "s": 29363, "text": "pidstat -p PID" }, { "code": null, "e": 29386, "s": 29378, "text": "Output:" }, { "code": null, "e": 29398, "s": 29386, "text": "Linux-Tools" }, { "code": null, "e": 29405, "s": 29398, "text": "Picked" }, { "code": null, "e": 29416, "s": 29405, "text": "Linux-Unix" }, { "code": null, "e": 29514, "s": 29416, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29551, "s": 29514, "text": "nohup Command in Linux with Examples" }, { "code": null, "e": 29586, "s": 29551, "text": "scp command in Linux with Examples" }, { "code": null, "e": 29612, "s": 29586, "text": "Thread functions in C/C++" }, { "code": null, "e": 29646, "s": 29612, "text": "mv command in Linux with examples" }, { "code": null, "e": 29683, "s": 29646, "text": "chown command in Linux with Examples" }, { "code": null, "e": 29712, "s": 29683, "text": "SED command in Linux | Set 2" }, { "code": null, "e": 29738, "s": 29712, "text": "Docker - COPY Instruction" }, { "code": null, "e": 29778, "s": 29738, "text": "Array Basics in Shell Scripting | Set 1" }, { "code": null, "e": 29813, "s": 29778, "text": "Basic Operators in Shell Scripting" } ]
Merge Conflicts and How to handle them - GeeksforGeeks
10 Jul, 2020 Conflicts while merging is a frequent part of the Git experience. If there are several developers working on the same file the odds of encountering a merge conflict increases. Most of the time, Git will automatically figure out how to integrate new changes. Conflicts generally arise when two people have changed the same lines in a file, or if one developer deleted a file while another developer was modifying it. In these cases, Git cannot automatically figure out which is correct. Hence, Git will notify the developer performing the merge that conflict is encountered, the rest of the team will be unaware of the conflict. Now, it is the responsibility of the developer performing the merge, to resolve the conflict. While starting the merge: If there are changes in either the working directory or staging area, while merging, then Git will fail to start the merge. This happens because the pending changes could be overridden by the commits that are being merged. This is the error message provided by Git when this type of merge conflict happens : error: Entry '<fileName>' not uptodate. Cannot merge. (Changes in working directory) or, error: Entry '<fileName>' would be overwritten by merge. Cannot merge. (Changes in staging area) This type of conflict can be resolved either by doing git stash save “any_message_to_describe_what_is_saved” (Stashes away any changes in your staging area and working directory in a separate index) OR git checkout <file_name> (throws out your changes), and then the merge can be completed. During the merge: This occurs because you have committed changes that are in conflict with someone else’s committed changes. Git will do its best to merge the files and will leave things for you to resolve manually in the files it lists. This is the error message provided by Git when this type of merge conflict happens : CONFLICT (content): Merge conflict in <fileName> Automatic merge failed; fix conflicts and then commit the result. This type of conflict can be resolved either by manually fixing all the merge conflict for each file OR using git reset ––hard (resets repository in order to back out of merge conflict situation). To show a simple example of how a merge conflict can happen, we can manually trigger a merge conflict from the following set of commands in any UNIX terminal / GIT bash : Step 1: Create a new directory using the mkdir command, and cd into it. Step 2: initialize it as a new Git repository using the git init command and create a new text file using the touch command. Step 3: Open the text file and add some content in it, then add the text file to the repo and commit it. Step 4: Now, its time to create a new branch to use it as the conflicting merge. Use git checkout to create and checkout the new branch. Step 5: Now, overwrite some conflicting changes to the text file from this new branch. Step 6: Add the changes to git and commit it from the new branch. With this new branch: new_branch_for_merge_conflict we have created a commit that overrides the content of test_file.txt Step 7: Again checkout the master branch, and this time append some text to the test_file.txt from the master branch. Step 8: add these new changes to the staging area and commit them. Step 9: Now for the last part, try merging the new branch to the master branch and you will encounter the second type of merge conflict. So, now we have successfully triggered a merge conflict in Git. As we have experienced from the proceeding example, Git will produce some descriptive output letting us know that a CONFLICT has occurred. We can gain further insight by running the git status command. This is what we will get after running the git status command: On branch master You have unmerged paths. (fix conflicts and run "git commit") (use "git merge --abort" to abort the merge) Unmerged paths: (use "git add <file>..." to mark resolution) both modified: test_file.txt no changes added to commit (use "git add" and/or "git commit -a") On opening the test_file.txt we see some “conflict dividers”. This is the content of our test_file.txt : <<<<<<< HEAD Adding some content to mess with it later Append this text to initial commit ======= Changing the contents of text file from new branch >>>>>>> new_branch_for_merge_conflict The ======= line is the “center” of the conflict. All the content between the center and the <<<<<<< HEAD line is content that exists in the current branch master which the HEAD ref is pointing to. Alternatively, all content between the center and >>>>>>> new_branch_for_merge_conflict is content that is present in our merging branch. To resolve our merge conflict, we can manually remove the unnecessary part from any one of the branches, and only consider the content of the branch that is important for further use, along with removing the “conflict dividers” from our file. Once the conflict has been resolved we can use the git add command to move the new changes to the staging area, and then git commit to commit the changes. Picked Git Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference Between Git Push Origin and Git Push Origin Master How to Push Git Branch to Remote? How to Export Eclipse projects to GitHub? Git - Difference Between Git Fetch and Git Pull Top 10 GitHub Alternatives That You Can Consider What is README.md File? How to Add Git Credentials in Eclipse? Git - Merge Using Patches in Git Git Flow vs Github Flow
[ { "code": null, "e": 24668, "s": 24640, "text": "\n10 Jul, 2020" }, { "code": null, "e": 25390, "s": 24668, "text": "Conflicts while merging is a frequent part of the Git experience. If there are several developers working on the same file the odds of encountering a merge conflict increases. Most of the time, Git will automatically figure out how to integrate new changes. Conflicts generally arise when two people have changed the same lines in a file, or if one developer deleted a file while another developer was modifying it. In these cases, Git cannot automatically figure out which is correct. Hence, Git will notify the developer performing the merge that conflict is encountered, the rest of the team will be unaware of the conflict. Now, it is the responsibility of the developer performing the merge, to resolve the conflict." }, { "code": null, "e": 25724, "s": 25390, "text": "While starting the merge: If there are changes in either the working directory or staging area, while merging, then Git will fail to start the merge. This happens because the pending changes could be overridden by the commits that are being merged. This is the error message provided by Git when this type of merge conflict happens :" }, { "code": null, "e": 25910, "s": 25724, "text": "error: Entry '<fileName>' not uptodate. Cannot merge. (Changes in working directory)\nor,\nerror: Entry '<fileName>' would be overwritten by merge. Cannot merge. (Changes in staging area)" }, { "code": null, "e": 26201, "s": 25910, "text": "This type of conflict can be resolved either by doing git stash save “any_message_to_describe_what_is_saved” (Stashes away any changes in your staging area and working directory in a separate index) OR git checkout <file_name> (throws out your changes), and then the merge can be completed." }, { "code": null, "e": 26524, "s": 26201, "text": "During the merge: This occurs because you have committed changes that are in conflict with someone else’s committed changes. Git will do its best to merge the files and will leave things for you to resolve manually in the files it lists. This is the error message provided by Git when this type of merge conflict happens :" }, { "code": null, "e": 26639, "s": 26524, "text": "CONFLICT (content): Merge conflict in <fileName>\nAutomatic merge failed; fix conflicts and then commit the result." }, { "code": null, "e": 26836, "s": 26639, "text": "This type of conflict can be resolved either by manually fixing all the merge conflict for each file OR using git reset ––hard (resets repository in order to back out of merge conflict situation)." }, { "code": null, "e": 27007, "s": 26836, "text": "To show a simple example of how a merge conflict can happen, we can manually trigger a merge conflict from the following set of commands in any UNIX terminal / GIT bash :" }, { "code": null, "e": 27079, "s": 27007, "text": "Step 1: Create a new directory using the mkdir command, and cd into it." }, { "code": null, "e": 27204, "s": 27079, "text": "Step 2: initialize it as a new Git repository using the git init command and create a new text file using the touch command." }, { "code": null, "e": 27309, "s": 27204, "text": "Step 3: Open the text file and add some content in it, then add the text file to the repo and commit it." }, { "code": null, "e": 27446, "s": 27309, "text": "Step 4: Now, its time to create a new branch to use it as the conflicting merge. Use git checkout to create and checkout the new branch." }, { "code": null, "e": 27533, "s": 27446, "text": "Step 5: Now, overwrite some conflicting changes to the text file from this new branch." }, { "code": null, "e": 27599, "s": 27533, "text": "Step 6: Add the changes to git and commit it from the new branch." }, { "code": null, "e": 27720, "s": 27599, "text": "With this new branch: new_branch_for_merge_conflict we have created a commit that overrides the content of test_file.txt" }, { "code": null, "e": 27838, "s": 27720, "text": "Step 7: Again checkout the master branch, and this time append some text to the test_file.txt from the master branch." }, { "code": null, "e": 27905, "s": 27838, "text": "Step 8: add these new changes to the staging area and commit them." }, { "code": null, "e": 28042, "s": 27905, "text": "Step 9: Now for the last part, try merging the new branch to the master branch and you will encounter the second type of merge conflict." }, { "code": null, "e": 28106, "s": 28042, "text": "So, now we have successfully triggered a merge conflict in Git." }, { "code": null, "e": 28371, "s": 28106, "text": "As we have experienced from the proceeding example, Git will produce some descriptive output letting us know that a CONFLICT has occurred. We can gain further insight by running the git status command. This is what we will get after running the git status command:" }, { "code": null, "e": 28665, "s": 28371, "text": "On branch master\nYou have unmerged paths.\n (fix conflicts and run \"git commit\")\n (use \"git merge --abort\" to abort the merge)\n\nUnmerged paths:\n (use \"git add <file>...\" to mark resolution)\n both modified: test_file.txt\n\nno changes added to commit (use \"git add\" and/or \"git commit -a\")" }, { "code": null, "e": 28770, "s": 28665, "text": "On opening the test_file.txt we see some “conflict dividers”. This is the content of our test_file.txt :" }, { "code": null, "e": 28957, "s": 28770, "text": "<<<<<<< HEAD\nAdding some content to mess with it later\nAppend this text to initial commit\n=======\nChanging the contents of text file from new branch\n>>>>>>> new_branch_for_merge_conflict" }, { "code": null, "e": 29293, "s": 28957, "text": "The ======= line is the “center” of the conflict. All the content between the center and the <<<<<<< HEAD line is content that exists in the current branch master which the HEAD ref is pointing to. Alternatively, all content between the center and >>>>>>> new_branch_for_merge_conflict is content that is present in our merging branch." }, { "code": null, "e": 29691, "s": 29293, "text": "To resolve our merge conflict, we can manually remove the unnecessary part from any one of the branches, and only consider the content of the branch that is important for further use, along with removing the “conflict dividers” from our file. Once the conflict has been resolved we can use the git add command to move the new changes to the staging area, and then git commit to commit the changes." }, { "code": null, "e": 29698, "s": 29691, "text": "Picked" }, { "code": null, "e": 29702, "s": 29698, "text": "Git" }, { "code": null, "e": 29800, "s": 29702, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29862, "s": 29800, "text": "Difference Between Git Push Origin and Git Push Origin Master" }, { "code": null, "e": 29896, "s": 29862, "text": "How to Push Git Branch to Remote?" }, { "code": null, "e": 29938, "s": 29896, "text": "How to Export Eclipse projects to GitHub?" }, { "code": null, "e": 29986, "s": 29938, "text": "Git - Difference Between Git Fetch and Git Pull" }, { "code": null, "e": 30035, "s": 29986, "text": "Top 10 GitHub Alternatives That You Can Consider" }, { "code": null, "e": 30059, "s": 30035, "text": "What is README.md File?" }, { "code": null, "e": 30098, "s": 30059, "text": "How to Add Git Credentials in Eclipse?" }, { "code": null, "e": 30110, "s": 30098, "text": "Git - Merge" }, { "code": null, "e": 30131, "s": 30110, "text": "Using Patches in Git" } ]
Understanding FAISS. ....And the world of Similarity Searching | by Vedashree Patil | Towards Data Science
A few weeks back, I stumbled upon FAISS — Facebook’s library for similarity search for very large datasets. My interest piqued, and a few hours of digging around on the internet led me to a treasure trove of knowledge. In this post, I hope to pen down (or rather type down) few basic concepts associated with the library. And in my subsequent post, I will dig a little deeper and explore some more advanced concepts. Usually in similarity searching, there is often a query record that is compared against a stored database of records (documents or images etc). The main aim is to retrieve a set of database records that are similar to the query record. So, if you have a picture of a dog, a similarity search should give you a list of pictures with dogs (not rainbows!) in them. When Machine learning comes into picture, the database corresponds to a collection of vectors. Vectors can be seen as high dimensional representations of the input data generated by machine learning algorithms. Similarity searching in this context means searching for similar vectors for a given query vector based on some similarity or distance measure. A naive way for searching based on similarity is to compare the query vector with every other vector in the database. But what if the database has more than a million vectors? Enter FAISS.... FAISS is a C++ library (with python bindings of course!) that assures faster similarity searching when the number of vectors may go up to millions or billions. At its very heart lies the index. Mind you, the index is everywhere!(albeit in different forms and names). In this post, I’ll elaborate on one: “the inverted file index ” or “IVF” Let me tell you a little story (Bear with me over here, I promise its important...) The queen of Someland had just conquered a new territory and discovered that the natives of this land were segregated in three different tribes who simply couldn’t tolerate each other. So, to avoid feuds, she decided to build three separate cities for each of the tribes. Interestingly, each tribe had a distinctive set of skills that they practised. This helped the queen identify which tribe a person belonged to. The Greens, it seemed, were born with a green thumb and spent most of their time tending to plants. The Tinks were the smart, analytical bunch and mostly comprised of architects, builders and scientists. And finally there were the creative Whims, who were known for their proficiency in the fine arts. They were mostly poets, dancers or artists. The cities were built and the tribe chiefs were appointed as the representatives for their respective tribes. For administrative purposes, the queen’s ministers maintained a “master-book” that recorded the name of the tribe chief along with names of the citizens for each city. One day, a group of travellers arrived in the kingdom and asked for refuge. The queen now had a problem. She had to find suitable volunteers who would agree to accommodate the travellers in their homes. (Apparently there were no inns in the kingdom). She knew that the citizens were quite guarded and only warmed up to people who shared their interests. Finally, a solution was found. For each traveller, the chiefs decided which tribe he or she would belong to depending on how closely the traveller’s characteristics matched the tribe’s characteristics. When the travellers arrived in their respective cities, a few citizens came forth and volunteered to accommodate one of the travellers since they felt that the traveller’s characteristics matched theirs. And well.... Problem solved! (The queen could now sleep in peace). Viola! I just gave you a bird’s eye view of how the inverted index works. Let’s use the story above as an analogy. All the citizens of the kingdom are the vectors in a database and the three tribes correspond to three separate “clusters” or “cells”. The vectors are then assigned to one of these three clusters depending upon a certain similarity measure .(Remember the tribes practised different set of skills that set them apart from each other?). Usually the L2 distance measure along with a clustering algorithm like K-means is used for this. Like the tribe chiefs in our story, each cluster is represented by a cluster centroid or “code” . And just like the ministers’ “master book” , a separate “codebook” is maintained that keeps track of the code (or cluster centroid) and its corresponding vectors for each cluster. This is essentially the “Inverted File” or index. A Quantiser is used to decide which cluster the vector belongs to (I guess this was primarily the queen’s job). So when a query vector comes in (like the travellers in our story), a suitable cluster (or clusters) is found for the query vector based on its similarity with the cluster centres (just like the tribe chiefs who selected the travellers based on their characteristics). Finally, a select number of similar vectors within the selected cluster(s) that are returned as the query result (like the citizens of the city who volunteered to house a traveller). This can be seen as a very basic working of the inverted index. Firstly, install the FAISS library with the python bindings. Just follow the instructions given at : https://github.com/facebookresearch/faiss/blob/master/INSTALL.md Then, import the library and other dependencies in python using: import numpy as np import faiss # this will import the faiss library Now, let’s create some vectors for the database. FAISS requires the dimensions of the database vectors to be predefined. We create about 200 vectors with dimension size 128. This creates a (200 * 128) vector matrix. Note that all vector values are stored in the float 32 type. dimension = 128 # dimensions of each vector n = 200 # number of vectors np.random.seed(1) db_vectors = np.random.random((n, dimension)).astype('float32') We use the ‘IndexIVFFlat’ index type for our vectors. The ‘Flat’ here signifies that the vectors are stored as is without any compression or quantisation (more on that later). The IVF index takes two parameters: nlist : to specify the number of clusters to be formed quantizer : to assign the vectors to a particular cluster. This is usually another index that uses the L2 distance metric (we use the FlatL2 index) nlist = 5 # number of clustersquantiser = faiss.IndexFlatL2(dimension) index = faiss.IndexIVFFlat(quantiser, dimension, nlist, faiss.METRIC_L2) The index has to be trained initially to create ‘nlist’ number of clusters and then the vectors are added to these clusters. the ‘is_trained’ flag denotes whether the index is trained or not and the ‘ntotal’ attribute shows the total number of vectors added to the index. print(index.is_trained) # Falseindex.train(db_vectors) # train on the database vectorsprint(index.ntotal) # 0index.add(db_vectors) # add the vectors and update the indexprint(index.is_trained) # Trueprint(index.ntotal) # 200 Next, we perform a search on the index for 10 query vectors. The ‘nprobe’ parameter specifies the number of clusters to visit during the search operation. This can be seen as hyper-parameter which can be tuned to get different results. Note that ‘nprobe’ cannot exceed ‘nlist’. ‘k’ specifies the number of similar vectors to be returned from the visited clusters. nprobe = 2 # find 2 most similar clustersn_query = 10 k = 3 # return 3 nearest neighboursnp.random.seed(0) query_vectors = np.random.random((n_query, dimension)).astype('float32')distances, indices = index.search(query_vectors, k) The search operation will return the ids (row numbers or index in the vector store) of the k most similar vectors for each query vector along with their respective distances. distances: [[15.770459 16.773014 17.17131 17.439615 17.443993] [16.476107 18.52229 18.811913 18.974785 19.02668 ] [15.520995 16.500256 17.069542 17.483345 17.742079] [16.842718 17.712341 17.828487 18.699772 19.345257] [18.325392 18.495464 18.684456 18.70239 18.904179] [17.531885 18.18179 18.331263 19.429993 19.700233] [16.840158 17.03664 17.091755 17.34306 17.487806] [15.984037 16.380917 17.270592 17.620832 17.663855] [18.018503 18.0761 18.766172 18.956903 18.985767] [17.113918 17.385284 17.65757 18.122086 18.170212]]indices: [[185 35 96 80 75] [118 51 122 108 31] [148 149 173 27 84] [175 177 50 38 81] [ 44 144 174 105 70] [156 74 151 167 182] [ 57 144 18 174 74] [ 82 12 46 64 127] [ 52 73 59 138 131] [ 82 46 90 37 179]] The index can be saved on disk using the write_index() function and can be loaded later using the using the read_index() function faiss.write_index(index,"vector.index") # save the index to diskindex = faiss.read_index("vector.index") # load the index There! A rudimentary code to understand faiss indexes! FAISS has a handful of features including: GPU and multithreaded support for index operations Dimensionality reduction: vectors with large dimensions can be reduced to smaller dimensions using PCA Quantisation: FAISS emphasises on product quantisation for compressing and storing vectors of large dimensions Batch processing i.e searching for multiple queries at a time Similarity searching and information retrieval are old pals! Image retrieval or document retrieval and even recommender systems use similarity searching. Say, for example, when you are shopping online for a watch of a particular brand, you see all kinds of watches similar in nature in your recommended list. Another route to explore is classification. For example, if we take the cliched ‘cats and dogs’ image recognition example, we can actually predict if the given query image is of a cat or a dog, depending on the most similar images returned from a datastore of cat and dog images(hmm....definitely another post for this!) I feel like I have barely scraped the surface! FAISS is an interesting library and theres definitely a lot more to explore. Squeezing everything in one post might make you scroll for ages! Hence, my next post further dives into the library and explains an advanced concept called product quantisation. github.com Thanks for reading!!!
[ { "code": null, "e": 589, "s": 172, "text": "A few weeks back, I stumbled upon FAISS — Facebook’s library for similarity search for very large datasets. My interest piqued, and a few hours of digging around on the internet led me to a treasure trove of knowledge. In this post, I hope to pen down (or rather type down) few basic concepts associated with the library. And in my subsequent post, I will dig a little deeper and explore some more advanced concepts." }, { "code": null, "e": 951, "s": 589, "text": "Usually in similarity searching, there is often a query record that is compared against a stored database of records (documents or images etc). The main aim is to retrieve a set of database records that are similar to the query record. So, if you have a picture of a dog, a similarity search should give you a list of pictures with dogs (not rainbows!) in them." }, { "code": null, "e": 1306, "s": 951, "text": "When Machine learning comes into picture, the database corresponds to a collection of vectors. Vectors can be seen as high dimensional representations of the input data generated by machine learning algorithms. Similarity searching in this context means searching for similar vectors for a given query vector based on some similarity or distance measure." }, { "code": null, "e": 1498, "s": 1306, "text": "A naive way for searching based on similarity is to compare the query vector with every other vector in the database. But what if the database has more than a million vectors? Enter FAISS...." }, { "code": null, "e": 1658, "s": 1498, "text": "FAISS is a C++ library (with python bindings of course!) that assures faster similarity searching when the number of vectors may go up to millions or billions." }, { "code": null, "e": 1838, "s": 1658, "text": "At its very heart lies the index. Mind you, the index is everywhere!(albeit in different forms and names). In this post, I’ll elaborate on one: “the inverted file index ” or “IVF”" }, { "code": null, "e": 1922, "s": 1838, "text": "Let me tell you a little story (Bear with me over here, I promise its important...)" }, { "code": null, "e": 2684, "s": 1922, "text": "The queen of Someland had just conquered a new territory and discovered that the natives of this land were segregated in three different tribes who simply couldn’t tolerate each other. So, to avoid feuds, she decided to build three separate cities for each of the tribes. Interestingly, each tribe had a distinctive set of skills that they practised. This helped the queen identify which tribe a person belonged to. The Greens, it seemed, were born with a green thumb and spent most of their time tending to plants. The Tinks were the smart, analytical bunch and mostly comprised of architects, builders and scientists. And finally there were the creative Whims, who were known for their proficiency in the fine arts. They were mostly poets, dancers or artists." }, { "code": null, "e": 2962, "s": 2684, "text": "The cities were built and the tribe chiefs were appointed as the representatives for their respective tribes. For administrative purposes, the queen’s ministers maintained a “master-book” that recorded the name of the tribe chief along with names of the citizens for each city." }, { "code": null, "e": 3316, "s": 2962, "text": "One day, a group of travellers arrived in the kingdom and asked for refuge. The queen now had a problem. She had to find suitable volunteers who would agree to accommodate the travellers in their homes. (Apparently there were no inns in the kingdom). She knew that the citizens were quite guarded and only warmed up to people who shared their interests." }, { "code": null, "e": 3789, "s": 3316, "text": "Finally, a solution was found. For each traveller, the chiefs decided which tribe he or she would belong to depending on how closely the traveller’s characteristics matched the tribe’s characteristics. When the travellers arrived in their respective cities, a few citizens came forth and volunteered to accommodate one of the travellers since they felt that the traveller’s characteristics matched theirs. And well.... Problem solved! (The queen could now sleep in peace)." }, { "code": null, "e": 3863, "s": 3789, "text": "Viola! I just gave you a bird’s eye view of how the inverted index works." }, { "code": null, "e": 3904, "s": 3863, "text": "Let’s use the story above as an analogy." }, { "code": null, "e": 4336, "s": 3904, "text": "All the citizens of the kingdom are the vectors in a database and the three tribes correspond to three separate “clusters” or “cells”. The vectors are then assigned to one of these three clusters depending upon a certain similarity measure .(Remember the tribes practised different set of skills that set them apart from each other?). Usually the L2 distance measure along with a clustering algorithm like K-means is used for this." }, { "code": null, "e": 4664, "s": 4336, "text": "Like the tribe chiefs in our story, each cluster is represented by a cluster centroid or “code” . And just like the ministers’ “master book” , a separate “codebook” is maintained that keeps track of the code (or cluster centroid) and its corresponding vectors for each cluster. This is essentially the “Inverted File” or index." }, { "code": null, "e": 5292, "s": 4664, "text": "A Quantiser is used to decide which cluster the vector belongs to (I guess this was primarily the queen’s job). So when a query vector comes in (like the travellers in our story), a suitable cluster (or clusters) is found for the query vector based on its similarity with the cluster centres (just like the tribe chiefs who selected the travellers based on their characteristics). Finally, a select number of similar vectors within the selected cluster(s) that are returned as the query result (like the citizens of the city who volunteered to house a traveller). This can be seen as a very basic working of the inverted index." }, { "code": null, "e": 5458, "s": 5292, "text": "Firstly, install the FAISS library with the python bindings. Just follow the instructions given at : https://github.com/facebookresearch/faiss/blob/master/INSTALL.md" }, { "code": null, "e": 5523, "s": 5458, "text": "Then, import the library and other dependencies in python using:" }, { "code": null, "e": 5593, "s": 5523, "text": "import numpy as np import faiss # this will import the faiss library" }, { "code": null, "e": 5870, "s": 5593, "text": "Now, let’s create some vectors for the database. FAISS requires the dimensions of the database vectors to be predefined. We create about 200 vectors with dimension size 128. This creates a (200 * 128) vector matrix. Note that all vector values are stored in the float 32 type." }, { "code": null, "e": 6084, "s": 5870, "text": "dimension = 128 # dimensions of each vector n = 200 # number of vectors np.random.seed(1) db_vectors = np.random.random((n, dimension)).astype('float32')" }, { "code": null, "e": 6296, "s": 6084, "text": "We use the ‘IndexIVFFlat’ index type for our vectors. The ‘Flat’ here signifies that the vectors are stored as is without any compression or quantisation (more on that later). The IVF index takes two parameters:" }, { "code": null, "e": 6351, "s": 6296, "text": "nlist : to specify the number of clusters to be formed" }, { "code": null, "e": 6499, "s": 6351, "text": "quantizer : to assign the vectors to a particular cluster. This is usually another index that uses the L2 distance metric (we use the FlatL2 index)" }, { "code": null, "e": 6647, "s": 6499, "text": "nlist = 5 # number of clustersquantiser = faiss.IndexFlatL2(dimension) index = faiss.IndexIVFFlat(quantiser, dimension, nlist, faiss.METRIC_L2)" }, { "code": null, "e": 6919, "s": 6647, "text": "The index has to be trained initially to create ‘nlist’ number of clusters and then the vectors are added to these clusters. the ‘is_trained’ flag denotes whether the index is trained or not and the ‘ntotal’ attribute shows the total number of vectors added to the index." }, { "code": null, "e": 7154, "s": 6919, "text": "print(index.is_trained) # Falseindex.train(db_vectors) # train on the database vectorsprint(index.ntotal) # 0index.add(db_vectors) # add the vectors and update the indexprint(index.is_trained) # Trueprint(index.ntotal) # 200" }, { "code": null, "e": 7432, "s": 7154, "text": "Next, we perform a search on the index for 10 query vectors. The ‘nprobe’ parameter specifies the number of clusters to visit during the search operation. This can be seen as hyper-parameter which can be tuned to get different results. Note that ‘nprobe’ cannot exceed ‘nlist’." }, { "code": null, "e": 7518, "s": 7432, "text": "‘k’ specifies the number of similar vectors to be returned from the visited clusters." }, { "code": null, "e": 7754, "s": 7518, "text": "nprobe = 2 # find 2 most similar clustersn_query = 10 k = 3 # return 3 nearest neighboursnp.random.seed(0) query_vectors = np.random.random((n_query, dimension)).astype('float32')distances, indices = index.search(query_vectors, k)" }, { "code": null, "e": 7929, "s": 7754, "text": "The search operation will return the ids (row numbers or index in the vector store) of the k most similar vectors for each query vector along with their respective distances." }, { "code": null, "e": 8692, "s": 7929, "text": "distances: [[15.770459 16.773014 17.17131 17.439615 17.443993] [16.476107 18.52229 18.811913 18.974785 19.02668 ] [15.520995 16.500256 17.069542 17.483345 17.742079] [16.842718 17.712341 17.828487 18.699772 19.345257] [18.325392 18.495464 18.684456 18.70239 18.904179] [17.531885 18.18179 18.331263 19.429993 19.700233] [16.840158 17.03664 17.091755 17.34306 17.487806] [15.984037 16.380917 17.270592 17.620832 17.663855] [18.018503 18.0761 18.766172 18.956903 18.985767] [17.113918 17.385284 17.65757 18.122086 18.170212]]indices: [[185 35 96 80 75] [118 51 122 108 31] [148 149 173 27 84] [175 177 50 38 81] [ 44 144 174 105 70] [156 74 151 167 182] [ 57 144 18 174 74] [ 82 12 46 64 127] [ 52 73 59 138 131] [ 82 46 90 37 179]]" }, { "code": null, "e": 8822, "s": 8692, "text": "The index can be saved on disk using the write_index() function and can be loaded later using the using the read_index() function" }, { "code": null, "e": 8946, "s": 8822, "text": "faiss.write_index(index,\"vector.index\") # save the index to diskindex = faiss.read_index(\"vector.index\") # load the index" }, { "code": null, "e": 9001, "s": 8946, "text": "There! A rudimentary code to understand faiss indexes!" }, { "code": null, "e": 9044, "s": 9001, "text": "FAISS has a handful of features including:" }, { "code": null, "e": 9095, "s": 9044, "text": "GPU and multithreaded support for index operations" }, { "code": null, "e": 9198, "s": 9095, "text": "Dimensionality reduction: vectors with large dimensions can be reduced to smaller dimensions using PCA" }, { "code": null, "e": 9309, "s": 9198, "text": "Quantisation: FAISS emphasises on product quantisation for compressing and storing vectors of large dimensions" }, { "code": null, "e": 9371, "s": 9309, "text": "Batch processing i.e searching for multiple queries at a time" }, { "code": null, "e": 9680, "s": 9371, "text": "Similarity searching and information retrieval are old pals! Image retrieval or document retrieval and even recommender systems use similarity searching. Say, for example, when you are shopping online for a watch of a particular brand, you see all kinds of watches similar in nature in your recommended list." }, { "code": null, "e": 10001, "s": 9680, "text": "Another route to explore is classification. For example, if we take the cliched ‘cats and dogs’ image recognition example, we can actually predict if the given query image is of a cat or a dog, depending on the most similar images returned from a datastore of cat and dog images(hmm....definitely another post for this!)" }, { "code": null, "e": 10303, "s": 10001, "text": "I feel like I have barely scraped the surface! FAISS is an interesting library and theres definitely a lot more to explore. Squeezing everything in one post might make you scroll for ages! Hence, my next post further dives into the library and explains an advanced concept called product quantisation." }, { "code": null, "e": 10314, "s": 10303, "text": "github.com" } ]
How to use GridList in ReactJS? - GeeksforGeeks
22 Jan, 2021 Grid lists display a collection of images in an organized grid. Material UI for React has this component available for us and it is very easy to integrate. We can use the GridList component in ReactJS using the following approach. Creating React Application And Installing Module: Step 1: Create a React application using the following command: npx create-react-app foldername Step 2: After creating your project folder i.e. foldername, move to it using the following command: cd foldername Step 3: After creating the ReactJS application, Install the material-ui modules using the following command: npm install @material-ui/core Project Structure: It will look like the following. Project Structure Filename-App.js: Now write down the following code in the App.js file. Here, App is our default component where we have written our code. Javascript import React from 'react';import { makeStyles } from '@material-ui/core/styles';import GridList from '@material-ui/core/GridList';import GridListTile from '@material-ui/core/GridListTile'; const App = () => { return ( <div style={{ width: 300, margin: 'auto' }}> <h3>Grid List ReactJS</h3> <GridList cellHeight={50} cols={3}> <GridListTile rows={6} cols={3}> <img src="https://write.geeksforgeeks.org/static/media/Group%20210.08204759.svg" alt="pic" /> </GridListTile> <GridListTile cols={1}> <img src="https://write.geeksforgeeks.org/static/media/Group%20210.08204759.svg" alt="pic" /> </GridListTile> <GridListTile cols={3}> <img src="https://write.geeksforgeeks.org/static/media/Group%20210.08204759.svg" alt="pic" /> </GridListTile> </GridList> </div> );} export default App; 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: JavaScript ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Difference Between PUT and PATCH Request Remove elements from a JavaScript Array How to get character array from string in JavaScript? How to filter object array based on attributes? How to fetch data from an API in ReactJS ? How to redirect to another page in ReactJS ? How to pass data from child component to its parent in ReactJS ? How to pass data from one component to other component in ReactJS ? ReactJS Functional Components
[ { "code": null, "e": 25312, "s": 25284, "text": "\n22 Jan, 2021" }, { "code": null, "e": 25543, "s": 25312, "text": "Grid lists display a collection of images in an organized grid. Material UI for React has this component available for us and it is very easy to integrate. We can use the GridList component in ReactJS using the following approach." }, { "code": null, "e": 25593, "s": 25543, "text": "Creating React Application And Installing Module:" }, { "code": null, "e": 25657, "s": 25593, "text": "Step 1: Create a React application using the following command:" }, { "code": null, "e": 25689, "s": 25657, "text": "npx create-react-app foldername" }, { "code": null, "e": 25789, "s": 25689, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:" }, { "code": null, "e": 25803, "s": 25789, "text": "cd foldername" }, { "code": null, "e": 25912, "s": 25803, "text": "Step 3: After creating the ReactJS application, Install the material-ui modules using the following command:" }, { "code": null, "e": 25942, "s": 25912, "text": "npm install @material-ui/core" }, { "code": null, "e": 25994, "s": 25942, "text": "Project Structure: It will look like the following." }, { "code": null, "e": 26012, "s": 25994, "text": "Project Structure" }, { "code": null, "e": 26150, "s": 26012, "text": "Filename-App.js: 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": 26161, "s": 26150, "text": "Javascript" }, { "code": "import React from 'react';import { makeStyles } from '@material-ui/core/styles';import GridList from '@material-ui/core/GridList';import GridListTile from '@material-ui/core/GridListTile'; const App = () => { return ( <div style={{ width: 300, margin: 'auto' }}> <h3>Grid List ReactJS</h3> <GridList cellHeight={50} cols={3}> <GridListTile rows={6} cols={3}> <img src=\"https://write.geeksforgeeks.org/static/media/Group%20210.08204759.svg\" alt=\"pic\" /> </GridListTile> <GridListTile cols={1}> <img src=\"https://write.geeksforgeeks.org/static/media/Group%20210.08204759.svg\" alt=\"pic\" /> </GridListTile> <GridListTile cols={3}> <img src=\"https://write.geeksforgeeks.org/static/media/Group%20210.08204759.svg\" alt=\"pic\" /> </GridListTile> </GridList> </div> );} export default App;", "e": 27068, "s": 26161, "text": null }, { "code": null, "e": 27181, "s": 27068, "text": "Step to Run Application: Run the application using the following command from the root directory of the project:" }, { "code": null, "e": 27191, "s": 27181, "text": "npm start" }, { "code": null, "e": 27290, "s": 27191, "text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:" }, { "code": null, "e": 27301, "s": 27290, "text": "JavaScript" }, { "code": null, "e": 27309, "s": 27301, "text": "ReactJS" }, { "code": null, "e": 27326, "s": 27309, "text": "Web Technologies" }, { "code": null, "e": 27424, "s": 27326, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27485, "s": 27424, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 27526, "s": 27485, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 27566, "s": 27526, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 27620, "s": 27566, "text": "How to get character array from string in JavaScript?" }, { "code": null, "e": 27668, "s": 27620, "text": "How to filter object array based on attributes?" }, { "code": null, "e": 27711, "s": 27668, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 27756, "s": 27711, "text": "How to redirect to another page in ReactJS ?" }, { "code": null, "e": 27821, "s": 27756, "text": "How to pass data from child component to its parent in ReactJS ?" }, { "code": null, "e": 27889, "s": 27821, "text": "How to pass data from one component to other component in ReactJS ?" } ]
Find all the queens attacking the king in a chessboard - GeeksforGeeks
13 Nov, 2020 Given a 2D array queens[][] consisting of coordinates of N queens in an 8 * 8 chessboard and an array king[] denoting the coordinates of the king, the task is to find the queens that are attacking the king Examples: Input: queens[][] = {{0, 1}, {1, 0}, {4, 0}, {0, 4}, {3, 3}, {2, 4}}, king[] = {2, 3} Output: {{0, 1}, {2, 4}, {3, 3}} Explanation:The queens at coordinates {0, 1} and {3, 3} are diagonally attacking the king and the queen at {2, 4} is vertically below the king. Input: queens[][]] = {{4, 1}, {1, 0}, {4, 0}}, king[] = {0, 0} Output : {{1, 0}} Approach Follow the steps below to solve the problem: Iterate over the array queens[][]. For every coordinate traversed, check for all possibilities of attacking the king, i.e. horizontally, vertically and diagonally. If found to be attacking the king, check for the following: If no other queen is attacking the king from that direction, including the current king as an attacker.If an attacker is already present in that direction, check if the current queen is the closest attacker or not. If found to be true, including the cent queen as an attacker. Otherwise, proceed to the next coordinates. If no other queen is attacking the king from that direction, including the current king as an attacker. If an attacker is already present in that direction, check if the current queen is the closest attacker or not. If found to be true, including the cent queen as an attacker. Otherwise, proceed to the next coordinates. Finally, print all the coordinates. Below is the implementation of the above approach: C++ Java Python3 // C++ Program to implement// the above approach #include <bits/stdc++.h>using namespace std; // Function to find the queen// closest to king in an// attacking positionint dis(vector<int> ans, vector<int> attacker){ return abs(ans[0] - attacker[0]) + abs(ans[1] - attacker[1]);} // Function to find all the queens// attacking the king in the chessboardvector<vector<int> > findQueens( vector<vector<int> >& queens, vector<int>& king){ vector<vector<int> > sol; vector<vector<int> > attackers(8); // Iterating over the coordinates // of the queens for (int i = 0; i < queens.size(); i++) { // If king is horizontally on // the right of current queen if (king[0] == queens[i][0] && king[1] > queens[i][1]) { // If no attacker is present // in that direction if ((attackers[3].size() == 0) // Or if the current queen is // closest in that direction || (dis(attackers[3], king) > dis(queens[i], king))) // Set current queen as // the attacker attackers[3] = queens[i]; } // If king is horizontally on // the left of current queen if (king[0] == queens[i][0] && king[1] < queens[i][1]) { // If no attacker is present // in that direction if ((attackers[4].size() == 0) // Or if the current queen is // closest in that direction || (dis(attackers[4], king) > dis(queens[i], king))) // Set current queen as // the attacker attackers[4] = queens[i]; } // If the king is attacked by a // queen from the left by a queen // diagonal above if (king[0] - queens[i][0] == king[1] - queens[i][1] && king[0] > queens[i][0]) { // If no attacker is present in // that direction if ((attackers[0].size() == 0) // Or the current queen is // the closest attacker in // that direction || (dis(attackers[0], king) > dis(queens[i], king))) // Set current queen as // the attacker attackers[0] = queens[i]; } // If the king is attacked by a // queen from the left by a queen // diagonally below if (king[0] - queens[i][0] == king[1] - queens[i][1] && king[0] < queens[i][0]) { // If no attacker is present in // that direction if ((attackers[7].size() == 0) // Or the current queen is // the closest attacker in // that direction || (dis(attackers[7], king) > dis(queens[i], king))) // Set current queen as // the attacker attackers[7] = queens[i]; } // If the king is attacked by a // queen from the right by a queen // diagonally above if (king[1] - queens[i][1] == 0 && king[0] > queens[i][0]) { // If no attacker is present in // that direction if ((attackers[1].size() == 0) // Or the current queen is // the closest attacker in // that direction || (dis(attackers[1], king) > dis(queens[i], king))) // Set current queen as // the attacker attackers[1] = queens[i]; } // If the king is attacked by a // queen from the right by a queen // diagonally below if (king[1] - queens[i][1] == 0 && king[0] < queens[i][0]) { // If no attacker is present in // that direction if ((attackers[6].size() == 0) // Or the current queen is // the closest attacker in // that direction || (dis(attackers[6], king) > dis(queens[i], king))) // Set current queen as // the attacker attackers[6] = queens[i]; } // If a king is vertically below // the current queen if (king[0] - queens[i][0] == -(king[1] - queens[i][1]) && king[0] > queens[i][0]) { // If no attacker is present in // that direction if ((attackers[2].size() == 0) // Or the current queen is // the closest attacker in // that direction || (dis(attackers[2], king) > dis(queens[i], king))) // Set current queen as // the attacker attackers[2] = queens[i]; } // If a king is vertically above // the current queen if (king[0] - queens[i][0] == -(king[1] - queens[i][1]) && king[0] < queens[i][0]) { // If no attacker is present in // that direction if ((attackers[5].size() == 0) // Or the current queen is // the closest attacker in // that direction || (dis(attackers[5], king) > dis(queens[i], king))) // Set current queen as // the attacker attackers[5] = queens[i]; } } for (int i = 0; i < 8; i++) if (attackers[i].size()) sol.push_back(attackers[i]); // Return the coordinates return sol;} // Print all the coordinates of the// queens attacking the kingvoid print(vector<vector<int> > ans){ for (int i = 0; i < ans.size(); i++) { for (int j = 0; j < 2; j++) cout << ans[i][j] << " "; cout << "\n"; }} // Driver Codeint main(){ vector<int> king = { 2, 3 }; vector<vector<int> > queens = { { 0, 1 }, { 1, 0 }, { 4, 0 }, { 0, 4 }, { 3, 3 }, { 2, 4 } }; vector<vector<int> > ans = findQueens(queens, king); print(ans);} // Java program to implement// the above approachimport java.io.*;import java.util.*;import java.util.stream.Collectors; class GFG{ // Method to find the queen closest// to king in an attacking positionprivate static int dis(int[] ans, int[] attacker){ return Math.abs(ans[0] - attacker[0]) + Math.abs(ans[1] - attacker[1]);} // Method to find all the queens// attacking the king in the chessboardprivate static List<List<Integer>> findQueens( int[][] queens, int[] king){ List<List<Integer>> sol = new ArrayList<List<Integer>>(); int[][] attackers = new int[8][2]; for(int i = 0; i < 8; i++) { Arrays.fill(attackers[i], -1); } for(int i = 0; i < queens.length; i++) { // If king is horizontally on // the right of current queen if (king[0] == queens[i][0] && king[1] > queens[i][1]) { // If no attacker is present // in that direction if ((attackers[3][0] == -1) || // Or if the current queen is // closest in that direction (dis(attackers[3], king) > dis(queens[i], king))) // Set current queen as // the attacker attackers[3] = queens[i]; } // If king is horizontally on // the left of current queen if (king[0] == queens[i][0] && king[1] < queens[i][1]) { // If no attacker is present // in that direction if ((attackers[4][0] == -1) || // Or if the current queen is // closest in that direction (dis(attackers[4], king) > dis(queens[i], king))) // Set current queen as // the attacker attackers[4] = queens[i]; } // If the king is attacked by a // queen from the left by a queen // diagonal above if (king[0] - queens[i][0] == king[1] - queens[i][1] && king[0] > queens[i][0]) { // If no attacker is present in // that direction if ((attackers[0][0] == -1) || // Or the current queen is // the closest attacker in // that direction (dis(attackers[0], king) > dis(queens[i], king))) // Set current queen as // the attacker attackers[0] = queens[i]; } // If the king is attacked by a // queen from the left by a queen // diagonally below if (king[0] - queens[i][0] == king[1] - queens[i][1] && king[0] < queens[i][0]) { // If no attacker is present in // that direction if ((attackers[7][0] == -1) || // Or the current queen is // the closest attacker in // that direction (dis(attackers[7], king) > dis(queens[i], king))) // Set current queen as // the attacker attackers[7] = queens[i]; } // If the king is attacked by a // queen from the right by a queen // diagonally above if (king[1] - queens[i][1] == 0 && king[0] > queens[i][0]) { // If no attacker is present in // that direction if ((attackers[1][0] == -1) || // Or the current queen is // the closest attacker in // that direction (dis(attackers[1], king) > dis(queens[i], king))) // Set current queen as // the attacker attackers[1] = queens[i]; } // If the king is attacked by a // queen from the right by a queen // diagonally below if (king[1] - queens[i][1] == 0 && king[0] < queens[i][0]) { // If no attacker is present in // that direction if ((attackers[6][0] == -1) || // Or the current queen is // the closest attacker in // that direction (dis(attackers[6], king) > dis(queens[i], king))) // Set current queen as // the attacker attackers[6] = queens[i]; } // If a king is vertically below // the current queen if (king[0] - queens[i][0] == -(king[1] - queens[i][1]) && king[0] > queens[i][0]) { // If no attacker is present in // that direction if ((attackers[2][0] == -1) || // Or the current queen is // the closest attacker in // that direction (dis(attackers[2], king) > dis(queens[i], king))) // Set current queen as // the attacker attackers[2] = queens[i]; } // If a king is vertically above // the current queen if (king[0] - queens[i][0] == -(king[1] - queens[i][1]) && king[0] < queens[i][0]) { // If no attacker is present in // that direction if ((attackers[5][0] == -1) || // Or the current queen is // the closest attacker in // that direction (dis(attackers[5], king) > dis(queens[i], king))) // Set current queen as // the attacker attackers[5] = queens[i]; } } for(int i = 0; i < 8; i++) if (attackers[i][0] != -1) sol.add( Arrays.stream( attackers[i]).boxed().collect( Collectors.toList())); // Return the coordinates return sol;} // Print all the coordinates of the// queens attacking the kingprivate static void print(List<List<Integer>> ans){ for(int i = 0; i < ans.size(); i++) { for(int j = 0; j < 2; j++) System.out.print(ans.get(i).get(j) + " "); System.out.println(); }} // Driver Codepublic static void main(String[] args){ int[] king = { 2, 3 }; int[][] queens = { { 0, 1 }, { 1, 0 }, { 4, 0 }, { 0, 4 }, { 3, 3 }, { 2, 4 } }; List<List<Integer>> ans = findQueens(queens, king); print(ans);}} // This code is contributed by jithin # Python3 program to implement# the above approach # Function to find the queen# closest to king in an# attacking positiondef dis(ans, attacker): return (abs(ans[0] - attacker[0]) + abs(ans[1] - attacker[1])) # Function to find all the# queens attacking the king# in the chessboarddef findQueens(queens, king): sol = [] attackers = [[0 for x in range(8)] for y in range(8)] # Iterating over the coordinates # of the queens for i in range(len(queens)): # If king is horizontally on # the right of current queen if (king[0] == queens[i][0] and king[1] > queens[i][1]): # If no attacker is present # in that direction if ((len(attackers[3]) == 0) # Or if the current queen is # closest in that direction or ((dis(attackers[3], king) > dis(queens[i], king)))): # Set current queen as # the attacker attackers[3] = queens[i]; # If king is horizontally on # the left of current queen if (king[0] == queens[i][0] and king[1] < queens[i][1]): # If no attacker is present # in that direction if ((len(attackers[4]) == 0) # Or if the current queen is # closest in that direction or (dis(attackers[4], king) > dis(queens[i], king))): # Set current queen as # the attacker attackers[4] = queens[i]; # If the king is attacked by a # queen from the left by a queen # diagonal above if (king[0] - queens[i][0] == king[1] - queens[i][1] and king[0] > queens[i][0]): # If no attacker is present in # that direction if ((len(attackers[0]) == 0) # Or the current queen is # the closest attacker in # that direction or (dis(attackers[0], king) > dis(queens[i], king))): # Set current queen as # the attacker attackers[0] = queens[i] # If the king is attacked by a # queen from the left by a queen # diagonally below if (king[0] - queens[i][0] == king[1] - queens[i][1] and king[0] < queens[i][0]): # If no attacker is present in # that direction if ((len(attackers[7]) == 0) # Or the current queen is # the closest attacker in # that direction or (dis(attackers[7], king) > dis(queens[i], king))): # Set current queen as # the attacker attackers[7] = queens[i] # If the king is attacked by a # queen from the right by a queen # diagonally above if (king[1] - queens[i][1] == 0 and king[0] > queens[i][0]): # If no attacker is present in # that direction if ((len(attackers[1]) == 0) # Or the current queen is # the closest attacker in # that direction or (dis(attackers[1], king) > dis(queens[i], king))): # Set current queen as # the attacker attackers[1] = queens[i] # If the king is attacked by a # queen from the right by a queen # diagonally below if (king[1] - queens[i][1] == 0 and king[0] < queens[i][0]): # If no attacker is present in # that direction if ((len(attackers[6]) == 0) # Or the current queen is # the closest attacker in # that direction or (dis(attackers[6], king) > dis(queens[i], king))): # Set current queen as # the attacker attackers[6] = queens[i]; # If a king is vertically below # the current queen if (king[0] - queens[i][0] == -(king[1] - queens[i][1]) and king[0] > queens[i][0]): # If no attacker is present in # that direction if ((len(attackers[2]) == 0) # Or the current queen is # the closest attacker in # that direction or (dis(attackers[2], king) > dis(queens[i], king))): # Set current queen as # the attacker attackers[2] = queens[i] # If a king is vertically above # the current queen if (king[0] - queens[i][0] == -(king[1] - queens[i][1]) and king[0] < queens[i][0]): # If no attacker is present in # that direction if ((len(attackers[5]) == 0) # Or the current queen is # the closest attacker in # that direction or (dis(attackers[5], king) > dis(queens[i], king))): # Set current queen as # the attacker attackers[5] = queens[i] for i in range(8): f = 1 for x in attackers[i]: if x != 0: f = 0 break if f == 0: sol.append(attackers[i]) # Return the coordinates return sol # Print all the coordinates of the# queens attacking the kingdef print_board(ans): for i in range(len(ans)): for j in range(2): print(ans[i][j], end = " ") print() # Driver Codeif __name__ == "__main__": king = [2, 3] queens = [[0, 1], [1, 0], [4, 0], [0, 4], [3, 3], [2, 4]] ans = findQueens(queens, king); print_board(ans); # This code is contributed by Chitranayal 0 1 2 4 3 3 Time Complexity: O(N), where N is the number of queens Auxiliary Space: O(N) ukasp jithin chessboard-problems Technical Scripter 2020 Arrays Matrix Searching Technical Scripter Arrays Searching Matrix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stack Data Structure (Introduction and Program) Top 50 Array Coding Problems for Interviews Multidimensional Arrays in Java Introduction to Arrays Linear Search Matrix Chain Multiplication | DP-8 Program to find largest element in an array Divide and Conquer | Set 5 (Strassen's Matrix Multiplication) Rat in a Maze | Backtracking-2 Print a given matrix in spiral form
[ { "code": null, "e": 25764, "s": 25736, "text": "\n13 Nov, 2020" }, { "code": null, "e": 25970, "s": 25764, "text": "Given a 2D array queens[][] consisting of coordinates of N queens in an 8 * 8 chessboard and an array king[] denoting the coordinates of the king, the task is to find the queens that are attacking the king" }, { "code": null, "e": 25980, "s": 25970, "text": "Examples:" }, { "code": null, "e": 26099, "s": 25980, "text": "Input: queens[][] = {{0, 1}, {1, 0}, {4, 0}, {0, 4}, {3, 3}, {2, 4}}, king[] = {2, 3} Output: {{0, 1}, {2, 4}, {3, 3}}" }, { "code": null, "e": 26243, "s": 26099, "text": "Explanation:The queens at coordinates {0, 1} and {3, 3} are diagonally attacking the king and the queen at {2, 4} is vertically below the king." }, { "code": null, "e": 26325, "s": 26243, "text": "Input: queens[][]] = {{4, 1}, {1, 0}, {4, 0}}, king[] = {0, 0} Output : {{1, 0}} " }, { "code": null, "e": 26379, "s": 26325, "text": "Approach Follow the steps below to solve the problem:" }, { "code": null, "e": 26414, "s": 26379, "text": "Iterate over the array queens[][]." }, { "code": null, "e": 26924, "s": 26414, "text": "For every coordinate traversed, check for all possibilities of attacking the king, i.e. horizontally, vertically and diagonally. If found to be attacking the king, check for the following: If no other queen is attacking the king from that direction, including the current king as an attacker.If an attacker is already present in that direction, check if the current queen is the closest attacker or not. If found to be true, including the cent queen as an attacker. Otherwise, proceed to the next coordinates." }, { "code": null, "e": 27028, "s": 26924, "text": "If no other queen is attacking the king from that direction, including the current king as an attacker." }, { "code": null, "e": 27246, "s": 27028, "text": "If an attacker is already present in that direction, check if the current queen is the closest attacker or not. If found to be true, including the cent queen as an attacker. Otherwise, proceed to the next coordinates." }, { "code": null, "e": 27282, "s": 27246, "text": "Finally, print all the coordinates." }, { "code": null, "e": 27333, "s": 27282, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 27337, "s": 27333, "text": "C++" }, { "code": null, "e": 27342, "s": 27337, "text": "Java" }, { "code": null, "e": 27350, "s": 27342, "text": "Python3" }, { "code": "// C++ Program to implement// the above approach #include <bits/stdc++.h>using namespace std; // Function to find the queen// closest to king in an// attacking positionint dis(vector<int> ans, vector<int> attacker){ return abs(ans[0] - attacker[0]) + abs(ans[1] - attacker[1]);} // Function to find all the queens// attacking the king in the chessboardvector<vector<int> > findQueens( vector<vector<int> >& queens, vector<int>& king){ vector<vector<int> > sol; vector<vector<int> > attackers(8); // Iterating over the coordinates // of the queens for (int i = 0; i < queens.size(); i++) { // If king is horizontally on // the right of current queen if (king[0] == queens[i][0] && king[1] > queens[i][1]) { // If no attacker is present // in that direction if ((attackers[3].size() == 0) // Or if the current queen is // closest in that direction || (dis(attackers[3], king) > dis(queens[i], king))) // Set current queen as // the attacker attackers[3] = queens[i]; } // If king is horizontally on // the left of current queen if (king[0] == queens[i][0] && king[1] < queens[i][1]) { // If no attacker is present // in that direction if ((attackers[4].size() == 0) // Or if the current queen is // closest in that direction || (dis(attackers[4], king) > dis(queens[i], king))) // Set current queen as // the attacker attackers[4] = queens[i]; } // If the king is attacked by a // queen from the left by a queen // diagonal above if (king[0] - queens[i][0] == king[1] - queens[i][1] && king[0] > queens[i][0]) { // If no attacker is present in // that direction if ((attackers[0].size() == 0) // Or the current queen is // the closest attacker in // that direction || (dis(attackers[0], king) > dis(queens[i], king))) // Set current queen as // the attacker attackers[0] = queens[i]; } // If the king is attacked by a // queen from the left by a queen // diagonally below if (king[0] - queens[i][0] == king[1] - queens[i][1] && king[0] < queens[i][0]) { // If no attacker is present in // that direction if ((attackers[7].size() == 0) // Or the current queen is // the closest attacker in // that direction || (dis(attackers[7], king) > dis(queens[i], king))) // Set current queen as // the attacker attackers[7] = queens[i]; } // If the king is attacked by a // queen from the right by a queen // diagonally above if (king[1] - queens[i][1] == 0 && king[0] > queens[i][0]) { // If no attacker is present in // that direction if ((attackers[1].size() == 0) // Or the current queen is // the closest attacker in // that direction || (dis(attackers[1], king) > dis(queens[i], king))) // Set current queen as // the attacker attackers[1] = queens[i]; } // If the king is attacked by a // queen from the right by a queen // diagonally below if (king[1] - queens[i][1] == 0 && king[0] < queens[i][0]) { // If no attacker is present in // that direction if ((attackers[6].size() == 0) // Or the current queen is // the closest attacker in // that direction || (dis(attackers[6], king) > dis(queens[i], king))) // Set current queen as // the attacker attackers[6] = queens[i]; } // If a king is vertically below // the current queen if (king[0] - queens[i][0] == -(king[1] - queens[i][1]) && king[0] > queens[i][0]) { // If no attacker is present in // that direction if ((attackers[2].size() == 0) // Or the current queen is // the closest attacker in // that direction || (dis(attackers[2], king) > dis(queens[i], king))) // Set current queen as // the attacker attackers[2] = queens[i]; } // If a king is vertically above // the current queen if (king[0] - queens[i][0] == -(king[1] - queens[i][1]) && king[0] < queens[i][0]) { // If no attacker is present in // that direction if ((attackers[5].size() == 0) // Or the current queen is // the closest attacker in // that direction || (dis(attackers[5], king) > dis(queens[i], king))) // Set current queen as // the attacker attackers[5] = queens[i]; } } for (int i = 0; i < 8; i++) if (attackers[i].size()) sol.push_back(attackers[i]); // Return the coordinates return sol;} // Print all the coordinates of the// queens attacking the kingvoid print(vector<vector<int> > ans){ for (int i = 0; i < ans.size(); i++) { for (int j = 0; j < 2; j++) cout << ans[i][j] << \" \"; cout << \"\\n\"; }} // Driver Codeint main(){ vector<int> king = { 2, 3 }; vector<vector<int> > queens = { { 0, 1 }, { 1, 0 }, { 4, 0 }, { 0, 4 }, { 3, 3 }, { 2, 4 } }; vector<vector<int> > ans = findQueens(queens, king); print(ans);}", "e": 33619, "s": 27350, "text": null }, { "code": "// Java program to implement// the above approachimport java.io.*;import java.util.*;import java.util.stream.Collectors; class GFG{ // Method to find the queen closest// to king in an attacking positionprivate static int dis(int[] ans, int[] attacker){ return Math.abs(ans[0] - attacker[0]) + Math.abs(ans[1] - attacker[1]);} // Method to find all the queens// attacking the king in the chessboardprivate static List<List<Integer>> findQueens( int[][] queens, int[] king){ List<List<Integer>> sol = new ArrayList<List<Integer>>(); int[][] attackers = new int[8][2]; for(int i = 0; i < 8; i++) { Arrays.fill(attackers[i], -1); } for(int i = 0; i < queens.length; i++) { // If king is horizontally on // the right of current queen if (king[0] == queens[i][0] && king[1] > queens[i][1]) { // If no attacker is present // in that direction if ((attackers[3][0] == -1) || // Or if the current queen is // closest in that direction (dis(attackers[3], king) > dis(queens[i], king))) // Set current queen as // the attacker attackers[3] = queens[i]; } // If king is horizontally on // the left of current queen if (king[0] == queens[i][0] && king[1] < queens[i][1]) { // If no attacker is present // in that direction if ((attackers[4][0] == -1) || // Or if the current queen is // closest in that direction (dis(attackers[4], king) > dis(queens[i], king))) // Set current queen as // the attacker attackers[4] = queens[i]; } // If the king is attacked by a // queen from the left by a queen // diagonal above if (king[0] - queens[i][0] == king[1] - queens[i][1] && king[0] > queens[i][0]) { // If no attacker is present in // that direction if ((attackers[0][0] == -1) || // Or the current queen is // the closest attacker in // that direction (dis(attackers[0], king) > dis(queens[i], king))) // Set current queen as // the attacker attackers[0] = queens[i]; } // If the king is attacked by a // queen from the left by a queen // diagonally below if (king[0] - queens[i][0] == king[1] - queens[i][1] && king[0] < queens[i][0]) { // If no attacker is present in // that direction if ((attackers[7][0] == -1) || // Or the current queen is // the closest attacker in // that direction (dis(attackers[7], king) > dis(queens[i], king))) // Set current queen as // the attacker attackers[7] = queens[i]; } // If the king is attacked by a // queen from the right by a queen // diagonally above if (king[1] - queens[i][1] == 0 && king[0] > queens[i][0]) { // If no attacker is present in // that direction if ((attackers[1][0] == -1) || // Or the current queen is // the closest attacker in // that direction (dis(attackers[1], king) > dis(queens[i], king))) // Set current queen as // the attacker attackers[1] = queens[i]; } // If the king is attacked by a // queen from the right by a queen // diagonally below if (king[1] - queens[i][1] == 0 && king[0] < queens[i][0]) { // If no attacker is present in // that direction if ((attackers[6][0] == -1) || // Or the current queen is // the closest attacker in // that direction (dis(attackers[6], king) > dis(queens[i], king))) // Set current queen as // the attacker attackers[6] = queens[i]; } // If a king is vertically below // the current queen if (king[0] - queens[i][0] == -(king[1] - queens[i][1]) && king[0] > queens[i][0]) { // If no attacker is present in // that direction if ((attackers[2][0] == -1) || // Or the current queen is // the closest attacker in // that direction (dis(attackers[2], king) > dis(queens[i], king))) // Set current queen as // the attacker attackers[2] = queens[i]; } // If a king is vertically above // the current queen if (king[0] - queens[i][0] == -(king[1] - queens[i][1]) && king[0] < queens[i][0]) { // If no attacker is present in // that direction if ((attackers[5][0] == -1) || // Or the current queen is // the closest attacker in // that direction (dis(attackers[5], king) > dis(queens[i], king))) // Set current queen as // the attacker attackers[5] = queens[i]; } } for(int i = 0; i < 8; i++) if (attackers[i][0] != -1) sol.add( Arrays.stream( attackers[i]).boxed().collect( Collectors.toList())); // Return the coordinates return sol;} // Print all the coordinates of the// queens attacking the kingprivate static void print(List<List<Integer>> ans){ for(int i = 0; i < ans.size(); i++) { for(int j = 0; j < 2; j++) System.out.print(ans.get(i).get(j) + \" \"); System.out.println(); }} // Driver Codepublic static void main(String[] args){ int[] king = { 2, 3 }; int[][] queens = { { 0, 1 }, { 1, 0 }, { 4, 0 }, { 0, 4 }, { 3, 3 }, { 2, 4 } }; List<List<Integer>> ans = findQueens(queens, king); print(ans);}} // This code is contributed by jithin", "e": 40279, "s": 33619, "text": null }, { "code": "# Python3 program to implement# the above approach # Function to find the queen# closest to king in an# attacking positiondef dis(ans, attacker): return (abs(ans[0] - attacker[0]) + abs(ans[1] - attacker[1])) # Function to find all the# queens attacking the king# in the chessboarddef findQueens(queens, king): sol = [] attackers = [[0 for x in range(8)] for y in range(8)] # Iterating over the coordinates # of the queens for i in range(len(queens)): # If king is horizontally on # the right of current queen if (king[0] == queens[i][0] and king[1] > queens[i][1]): # If no attacker is present # in that direction if ((len(attackers[3]) == 0) # Or if the current queen is # closest in that direction or ((dis(attackers[3], king) > dis(queens[i], king)))): # Set current queen as # the attacker attackers[3] = queens[i]; # If king is horizontally on # the left of current queen if (king[0] == queens[i][0] and king[1] < queens[i][1]): # If no attacker is present # in that direction if ((len(attackers[4]) == 0) # Or if the current queen is # closest in that direction or (dis(attackers[4], king) > dis(queens[i], king))): # Set current queen as # the attacker attackers[4] = queens[i]; # If the king is attacked by a # queen from the left by a queen # diagonal above if (king[0] - queens[i][0] == king[1] - queens[i][1] and king[0] > queens[i][0]): # If no attacker is present in # that direction if ((len(attackers[0]) == 0) # Or the current queen is # the closest attacker in # that direction or (dis(attackers[0], king) > dis(queens[i], king))): # Set current queen as # the attacker attackers[0] = queens[i] # If the king is attacked by a # queen from the left by a queen # diagonally below if (king[0] - queens[i][0] == king[1] - queens[i][1] and king[0] < queens[i][0]): # If no attacker is present in # that direction if ((len(attackers[7]) == 0) # Or the current queen is # the closest attacker in # that direction or (dis(attackers[7], king) > dis(queens[i], king))): # Set current queen as # the attacker attackers[7] = queens[i] # If the king is attacked by a # queen from the right by a queen # diagonally above if (king[1] - queens[i][1] == 0 and king[0] > queens[i][0]): # If no attacker is present in # that direction if ((len(attackers[1]) == 0) # Or the current queen is # the closest attacker in # that direction or (dis(attackers[1], king) > dis(queens[i], king))): # Set current queen as # the attacker attackers[1] = queens[i] # If the king is attacked by a # queen from the right by a queen # diagonally below if (king[1] - queens[i][1] == 0 and king[0] < queens[i][0]): # If no attacker is present in # that direction if ((len(attackers[6]) == 0) # Or the current queen is # the closest attacker in # that direction or (dis(attackers[6], king) > dis(queens[i], king))): # Set current queen as # the attacker attackers[6] = queens[i]; # If a king is vertically below # the current queen if (king[0] - queens[i][0] == -(king[1] - queens[i][1]) and king[0] > queens[i][0]): # If no attacker is present in # that direction if ((len(attackers[2]) == 0) # Or the current queen is # the closest attacker in # that direction or (dis(attackers[2], king) > dis(queens[i], king))): # Set current queen as # the attacker attackers[2] = queens[i] # If a king is vertically above # the current queen if (king[0] - queens[i][0] == -(king[1] - queens[i][1]) and king[0] < queens[i][0]): # If no attacker is present in # that direction if ((len(attackers[5]) == 0) # Or the current queen is # the closest attacker in # that direction or (dis(attackers[5], king) > dis(queens[i], king))): # Set current queen as # the attacker attackers[5] = queens[i] for i in range(8): f = 1 for x in attackers[i]: if x != 0: f = 0 break if f == 0: sol.append(attackers[i]) # Return the coordinates return sol # Print all the coordinates of the# queens attacking the kingdef print_board(ans): for i in range(len(ans)): for j in range(2): print(ans[i][j], end = \" \") print() # Driver Codeif __name__ == \"__main__\": king = [2, 3] queens = [[0, 1], [1, 0], [4, 0], [0, 4], [3, 3], [2, 4]] ans = findQueens(queens, king); print_board(ans); # This code is contributed by Chitranayal", "e": 46305, "s": 40279, "text": null }, { "code": null, "e": 46337, "s": 46305, "text": "0 1 \n2 4 \n3 3\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n" }, { "code": null, "e": 46416, "s": 46339, "text": "Time Complexity: O(N), where N is the number of queens Auxiliary Space: O(N)" }, { "code": null, "e": 46422, "s": 46416, "text": "ukasp" }, { "code": null, "e": 46429, "s": 46422, "text": "jithin" }, { "code": null, "e": 46449, "s": 46429, "text": "chessboard-problems" }, { "code": null, "e": 46473, "s": 46449, "text": "Technical Scripter 2020" }, { "code": null, "e": 46480, "s": 46473, "text": "Arrays" }, { "code": null, "e": 46487, "s": 46480, "text": "Matrix" }, { "code": null, "e": 46497, "s": 46487, "text": "Searching" }, { "code": null, "e": 46516, "s": 46497, "text": "Technical Scripter" }, { "code": null, "e": 46523, "s": 46516, "text": "Arrays" }, { "code": null, "e": 46533, "s": 46523, "text": "Searching" }, { "code": null, "e": 46540, "s": 46533, "text": "Matrix" }, { "code": null, "e": 46638, "s": 46540, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 46686, "s": 46638, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 46730, "s": 46686, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 46762, "s": 46730, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 46785, "s": 46762, "text": "Introduction to Arrays" }, { "code": null, "e": 46799, "s": 46785, "text": "Linear Search" }, { "code": null, "e": 46834, "s": 46799, "text": "Matrix Chain Multiplication | DP-8" }, { "code": null, "e": 46878, "s": 46834, "text": "Program to find largest element in an array" }, { "code": null, "e": 46940, "s": 46878, "text": "Divide and Conquer | Set 5 (Strassen's Matrix Multiplication)" }, { "code": null, "e": 46971, "s": 46940, "text": "Rat in a Maze | Backtracking-2" } ]
Transformers Explained. An exhaustive explanation of Google’s... | by Rohan Jagtap | Towards Data Science
This post is an in-depth elucidation of the Transformer model from the well-known paper “Attention is all you need” by Google Research. This model has been a pioneer to many SOTA (state of the art) approaches in sequence transduction tasks (any task which involves converting one sequence to another). Following are the contents of this post: Overview of Sequence to Sequence modelsWhy Transformer?Attention? Self-Attention!What is a Transformer?Conclusion Overview of Sequence to Sequence models Why Transformer? Attention? Self-Attention! What is a Transformer? Conclusion This is going to be a long one, so sit tight! The sequence to sequence encoder-decoder architecture is the base for sequence transduction tasks. It essentially suggests encoding the complete sequence at once and then using this encoding as a context for the generation of decoded sequence or the target sequence. One may relate this to the human tendency of first ‘listening’ to a sentence(sequence) completely and then responding accordingly be it a conversation, translation, or any similar task. The seq2seq model consists of separate RNNs at encoder and decoder respectively. The encoded sequence is the hidden state of the RNN at the encoder network. Using this encoded sequence and (usually) word-level generative modeling, seq2seq generates the target sequence. Since encoding is at the word-level, for longer sequences it is difficult to preserve the context at the encoder, hence the well-known attention mechanism was incorporated with seq2seq to ‘pay attention’ at specific words in the sequence that prominently contribute to the generation of the target sequence. Attention is weighing individual words in the input sequence according to the impact they make on the target sequence generation. Sequence to Sequence with RNNs is great, with attention it’s even better. Then what’s so great about Transformers? The main issue with RNNs lies in their inability of providing parallelization while processing. The processing of RNN is sequential, i.e. we cannot compute the value of the next timestep unless we have the output of the current. This makes RNN-based approaches slow. This issue, however, was addressed by Facebook Research wherein they suggested using a convolution-based approach that allows incorporating parallelization with GPU. These models establish hierarchical representation between words, where the words that occur closer in sequences interact at lower levels while the ones appearing far from each other operate at higher levels in the hierarchy. ConvS2S and ByteNet are two such models. The hierarchy is introduced to address long-term dependencies. Although this achieves parallelization, it is still computationally expensive. The number of operations per layer incurred by RNNs and CNNs is way more unreasonable as compared to the quality of results they offer. The original Transformer paper has put forth a comparison of these parameters for the competent models: Here, d (or d_model) is the representation dimension or embedding dimension of a word (usually in the range 128–512), n is the sequence length (usually in the range 40–70), k is the kernel size of the convolution and r is the attention window-size for restricted self-attention. From the table, we can infer the following: Clearly, the per-layer computational complexity of self-attention is way less than that of others. With respect to sequential operations, except RNNs, all other approaches offer parallelization, hence their complexity is O(1). The final metric is maximum path length, which superficially means the complexity for attending long-term dependencies or distant words. Since convolutional models use hierarchical representations, their complexity is nlog(n), while self-attention models attend all the words at the same step, hence their complexity is O(1). The Transformer uses the self-attention mechanism where attention weights are calculated using all the words in the input sequence at once, hence it facilitates parallelization. In addition to that, since the per-layer operations in the Transformer are among words of the same sequence, the complexity does not exceed O(n2d). Hence, the transformer proves to be effective (since it uses attention) and at the same time, a computationally efficient model. In the previous section, we discussed that the Transformer uses self-attention as a means for effective computation. In this section, we will decipher, what exactly is self-attention and how is it used in the Transformer. The attention mechanism as a general convention follows a Query, Key, Value pattern. All three of these are words from the input sequence that are meant to operate with each other in a certain pattern. The query and key initially undergo certain operations, the output is then (usually) multiplied with the value. This will get clearer in the next sub-section where we will see a pictorial depiction of how self-attention works. As mentioned earlier, self-attention is ‘attending’ words from the same sequence. Superficially speaking, self-attention determines the impact a word has on the sentence In the picture above, the working of self-attention is explained with the example of a sentence, “This is Attention”. The word “This” is operated with every other word in the sentence. Similarly, the attention weights for all the words are calculated (here, “is” and “Attention”). There is no concept of ‘hidden state’ here. The inputs are used directly. This removes sequentiality from the architecture, hence allowing parallelization. In case of Transformer, Multi-Head Attention is used, which is covered later in the post. So far, we have seen mechanisms implemented in the Transformer. Hereafter, we will actually see how these adjoining mechanisms and several components specific to the model are incorporated. We will try and build a Transformer bottom-up If you observe, the self-attention computations have no notion of ordering of words among the sequences. Although RNNs are slow, their sequential nature ensures that the order of words is preserved. So, to elicit this notion of positioning of words in the sequence, Positional Encodings are added to the regular input embeddings. The dimension of positional encodings is the same as the embeddings (d_model) for facilitating the summation of both. In the paper, positional encodings are obtained using: Here, i is the dimension and pos is the position of the word. We use sine for even values (2i) of dimensions and cosine for odd values (2i + 1). There are several choices for positional encodings — learned or fixed. This is the fixed way as the paper states learned as well as fixed methods achieved identical results. The general idea behind this is, for a fixed offset k, PEpos+k can be represented as linear function of PEpos. There are two kinds of masks used in the multi-head attention mechanism of the Transformer. Padding Mask: The input vector of the sequences is supposed to be fixed in length. Hence, a max_length parameter defines the maximum length of a sequence that the transformer can accept. All the sequences that are greater in length than max_length are truncated while shorter sequences are padded with zeros. The zero-paddings, however, are not supposed to contribute to the attention calculation nor in the target sequence generation. The working of padding mask is explained in the adjacent figure. This is an optional operation in the Transformer. Look-ahead Mask: While generating target sequences at the decoder, since the Transformer uses self-attention, it tends to include all the words from the decoder inputs. But, practically this is incorrect. Only the words preceding the current word may contribute to the generation of the next word. Masked Multi-Head Attention ensures this. The working of the look-ahead mask is explained in the adjacent figure. The following snippet of code explains how padding helps: >>> a = tf.constant([0.6, 0.2, 0.3, 0.4, 0, 0, 0, 0, 0, 0])>>> tf.nn.softmax(a)<tf.Tensor: shape=(10,), dtype=float32, numpy=array([0.15330984, 0.10276665, 0.11357471, 0.12551947, 0.08413821, 0.08413821, 0.08413821, 0.08413821, 0.08413821, 0.08413821], dtype=float32)>>>> b = tf.constant([0.6, 0.2, 0.3, 0.4, -1e9, -1e9, -1e9, -1e9, -1e9, -1e9])>>> tf.nn.softmax(b)<tf.Tensor: shape=(10,), dtype=float32, numpy=array([0.3096101 , 0.20753784, 0.22936477, 0.25348732, 0. , 0. , 0. , 0. , 0. , 0. ], dtype=float32)> This is the main ‘Attention Computation’ step that we have previously discussed in the Self-Attention section. This involves a few steps: MatMul: This is a matrix dot-product operation. First the Query and Key undergo this operation. The operation can be mathematically represented as follows: MatMul(Q, K) = Q.KT Scale: The output of the dot-product operation can lead to large values which may mess with the softmax in the later part. Hence, we scale them by dividing them by a scaling factor √dk. Mask: The optional padding mask is already discussed in the masking section above. Softmax: The softmax function brings down the values to a probability distribution i.e. [0, 1]. The scaled dot-product attention is a major component of the multi-head attention which we are about to see in the next sub-section. Multi-Head Attention is essentially the integration of all the previously discussed micro-concepts. In the adjacent figure, h is the number of heads. As far as the math is concerned, the initial inputs to the Multi-Head Attention are split into h parts, each having Queries, Keys, and Values, for max_length words in a sequence, for batch_size sequences. The dimensions of Q, K, V are called depth which is calculated as follows: depth = d_model // h This is the reason why d_model needs to be completely divisible by h. So, while splitting, the d_model shaped vectors are split into h vectors of shape depth. These vectors are passed as Q, K, V to the scaled dot product, and the output is ‘Concat’ by again reshaping the h vectors into 1 vector of shape d_model. This reformed vector is then passed through a feed-forward neural network layer. The Point-wise feed-forward network block is essentially a two-layer linear transformation which is used identically throughout the model architecture, usually after attention blocks. For Regularization, a dropout is applied to the output of each sub-layer before it is added to the inputs of the sub-layer and normalized. All the components are assembled together to build the Transformer. The Encoder block is the one in the left and Decoder to the right. The Encoder and the Decoder blocks may be optionally fine-tuned to Nx units to adjust the model. In this post, we’ve seen the issues with RNN-based approaches in sequence transduction tasks and how the revolutionary, Transformer model addresses them. Later, we studied the mechanisms underlying the Transformer and their working. Finally, we saw how various components and the underlying mechanisms work with the Transformer. I have covered the step-by-step implementation of Transformer using TensorFlow for Abstractive Text Summarization here. “Attention is all you need” Original Transformer Paper: https://arxiv.org/abs/1706.03762 Seq2Seq paper: https://arxiv.org/abs/1409.3215 Bahdanau Attention Paper: https://arxiv.org/abs/1409.0473 ConvS2S and ByteNet Papers: https://arxiv.org/abs/1705.03122 , https://arxiv.org/abs/1610.10099 towardsdatascience.com mchromiak.github.io Some Great Visualizations of the Transformer:
[ { "code": null, "e": 515, "s": 172, "text": "This post is an in-depth elucidation of the Transformer model from the well-known paper “Attention is all you need” by Google Research. This model has been a pioneer to many SOTA (state of the art) approaches in sequence transduction tasks (any task which involves converting one sequence to another). Following are the contents of this post:" }, { "code": null, "e": 629, "s": 515, "text": "Overview of Sequence to Sequence modelsWhy Transformer?Attention? Self-Attention!What is a Transformer?Conclusion" }, { "code": null, "e": 669, "s": 629, "text": "Overview of Sequence to Sequence models" }, { "code": null, "e": 686, "s": 669, "text": "Why Transformer?" }, { "code": null, "e": 713, "s": 686, "text": "Attention? Self-Attention!" }, { "code": null, "e": 736, "s": 713, "text": "What is a Transformer?" }, { "code": null, "e": 747, "s": 736, "text": "Conclusion" }, { "code": null, "e": 793, "s": 747, "text": "This is going to be a long one, so sit tight!" }, { "code": null, "e": 1060, "s": 793, "text": "The sequence to sequence encoder-decoder architecture is the base for sequence transduction tasks. It essentially suggests encoding the complete sequence at once and then using this encoding as a context for the generation of decoded sequence or the target sequence." }, { "code": null, "e": 1246, "s": 1060, "text": "One may relate this to the human tendency of first ‘listening’ to a sentence(sequence) completely and then responding accordingly be it a conversation, translation, or any similar task." }, { "code": null, "e": 1954, "s": 1246, "text": "The seq2seq model consists of separate RNNs at encoder and decoder respectively. The encoded sequence is the hidden state of the RNN at the encoder network. Using this encoded sequence and (usually) word-level generative modeling, seq2seq generates the target sequence. Since encoding is at the word-level, for longer sequences it is difficult to preserve the context at the encoder, hence the well-known attention mechanism was incorporated with seq2seq to ‘pay attention’ at specific words in the sequence that prominently contribute to the generation of the target sequence. Attention is weighing individual words in the input sequence according to the impact they make on the target sequence generation." }, { "code": null, "e": 2069, "s": 1954, "text": "Sequence to Sequence with RNNs is great, with attention it’s even better. Then what’s so great about Transformers?" }, { "code": null, "e": 2336, "s": 2069, "text": "The main issue with RNNs lies in their inability of providing parallelization while processing. The processing of RNN is sequential, i.e. we cannot compute the value of the next timestep unless we have the output of the current. This makes RNN-based approaches slow." }, { "code": null, "e": 2832, "s": 2336, "text": "This issue, however, was addressed by Facebook Research wherein they suggested using a convolution-based approach that allows incorporating parallelization with GPU. These models establish hierarchical representation between words, where the words that occur closer in sequences interact at lower levels while the ones appearing far from each other operate at higher levels in the hierarchy. ConvS2S and ByteNet are two such models. The hierarchy is introduced to address long-term dependencies." }, { "code": null, "e": 3151, "s": 2832, "text": "Although this achieves parallelization, it is still computationally expensive. The number of operations per layer incurred by RNNs and CNNs is way more unreasonable as compared to the quality of results they offer. The original Transformer paper has put forth a comparison of these parameters for the competent models:" }, { "code": null, "e": 3474, "s": 3151, "text": "Here, d (or d_model) is the representation dimension or embedding dimension of a word (usually in the range 128–512), n is the sequence length (usually in the range 40–70), k is the kernel size of the convolution and r is the attention window-size for restricted self-attention. From the table, we can infer the following:" }, { "code": null, "e": 3573, "s": 3474, "text": "Clearly, the per-layer computational complexity of self-attention is way less than that of others." }, { "code": null, "e": 3701, "s": 3573, "text": "With respect to sequential operations, except RNNs, all other approaches offer parallelization, hence their complexity is O(1)." }, { "code": null, "e": 4027, "s": 3701, "text": "The final metric is maximum path length, which superficially means the complexity for attending long-term dependencies or distant words. Since convolutional models use hierarchical representations, their complexity is nlog(n), while self-attention models attend all the words at the same step, hence their complexity is O(1)." }, { "code": null, "e": 4482, "s": 4027, "text": "The Transformer uses the self-attention mechanism where attention weights are calculated using all the words in the input sequence at once, hence it facilitates parallelization. In addition to that, since the per-layer operations in the Transformer are among words of the same sequence, the complexity does not exceed O(n2d). Hence, the transformer proves to be effective (since it uses attention) and at the same time, a computationally efficient model." }, { "code": null, "e": 4704, "s": 4482, "text": "In the previous section, we discussed that the Transformer uses self-attention as a means for effective computation. In this section, we will decipher, what exactly is self-attention and how is it used in the Transformer." }, { "code": null, "e": 5133, "s": 4704, "text": "The attention mechanism as a general convention follows a Query, Key, Value pattern. All three of these are words from the input sequence that are meant to operate with each other in a certain pattern. The query and key initially undergo certain operations, the output is then (usually) multiplied with the value. This will get clearer in the next sub-section where we will see a pictorial depiction of how self-attention works." }, { "code": null, "e": 5215, "s": 5133, "text": "As mentioned earlier, self-attention is ‘attending’ words from the same sequence." }, { "code": null, "e": 5303, "s": 5215, "text": "Superficially speaking, self-attention determines the impact a word has on the sentence" }, { "code": null, "e": 5740, "s": 5303, "text": "In the picture above, the working of self-attention is explained with the example of a sentence, “This is Attention”. The word “This” is operated with every other word in the sentence. Similarly, the attention weights for all the words are calculated (here, “is” and “Attention”). There is no concept of ‘hidden state’ here. The inputs are used directly. This removes sequentiality from the architecture, hence allowing parallelization." }, { "code": null, "e": 5830, "s": 5740, "text": "In case of Transformer, Multi-Head Attention is used, which is covered later in the post." }, { "code": null, "e": 6020, "s": 5830, "text": "So far, we have seen mechanisms implemented in the Transformer. Hereafter, we will actually see how these adjoining mechanisms and several components specific to the model are incorporated." }, { "code": null, "e": 6066, "s": 6020, "text": "We will try and build a Transformer bottom-up" }, { "code": null, "e": 6569, "s": 6066, "text": "If you observe, the self-attention computations have no notion of ordering of words among the sequences. Although RNNs are slow, their sequential nature ensures that the order of words is preserved. So, to elicit this notion of positioning of words in the sequence, Positional Encodings are added to the regular input embeddings. The dimension of positional encodings is the same as the embeddings (d_model) for facilitating the summation of both. In the paper, positional encodings are obtained using:" }, { "code": null, "e": 6888, "s": 6569, "text": "Here, i is the dimension and pos is the position of the word. We use sine for even values (2i) of dimensions and cosine for odd values (2i + 1). There are several choices for positional encodings — learned or fixed. This is the fixed way as the paper states learned as well as fixed methods achieved identical results." }, { "code": null, "e": 6999, "s": 6888, "text": "The general idea behind this is, for a fixed offset k, PEpos+k can be represented as linear function of PEpos." }, { "code": null, "e": 7091, "s": 6999, "text": "There are two kinds of masks used in the multi-head attention mechanism of the Transformer." }, { "code": null, "e": 7642, "s": 7091, "text": "Padding Mask: The input vector of the sequences is supposed to be fixed in length. Hence, a max_length parameter defines the maximum length of a sequence that the transformer can accept. All the sequences that are greater in length than max_length are truncated while shorter sequences are padded with zeros. The zero-paddings, however, are not supposed to contribute to the attention calculation nor in the target sequence generation. The working of padding mask is explained in the adjacent figure. This is an optional operation in the Transformer." }, { "code": null, "e": 8054, "s": 7642, "text": "Look-ahead Mask: While generating target sequences at the decoder, since the Transformer uses self-attention, it tends to include all the words from the decoder inputs. But, practically this is incorrect. Only the words preceding the current word may contribute to the generation of the next word. Masked Multi-Head Attention ensures this. The working of the look-ahead mask is explained in the adjacent figure." }, { "code": null, "e": 8112, "s": 8054, "text": "The following snippet of code explains how padding helps:" }, { "code": null, "e": 8689, "s": 8112, "text": ">>> a = tf.constant([0.6, 0.2, 0.3, 0.4, 0, 0, 0, 0, 0, 0])>>> tf.nn.softmax(a)<tf.Tensor: shape=(10,), dtype=float32, numpy=array([0.15330984, 0.10276665, 0.11357471, 0.12551947, 0.08413821, 0.08413821, 0.08413821, 0.08413821, 0.08413821, 0.08413821], dtype=float32)>>>> b = tf.constant([0.6, 0.2, 0.3, 0.4, -1e9, -1e9, -1e9, -1e9, -1e9, -1e9])>>> tf.nn.softmax(b)<tf.Tensor: shape=(10,), dtype=float32, numpy=array([0.3096101 , 0.20753784, 0.22936477, 0.25348732, 0. , 0. , 0. , 0. , 0. , 0. ], dtype=float32)>" }, { "code": null, "e": 8827, "s": 8689, "text": "This is the main ‘Attention Computation’ step that we have previously discussed in the Self-Attention section. This involves a few steps:" }, { "code": null, "e": 8983, "s": 8827, "text": "MatMul: This is a matrix dot-product operation. First the Query and Key undergo this operation. The operation can be mathematically represented as follows:" }, { "code": null, "e": 9003, "s": 8983, "text": "MatMul(Q, K) = Q.KT" }, { "code": null, "e": 9189, "s": 9003, "text": "Scale: The output of the dot-product operation can lead to large values which may mess with the softmax in the later part. Hence, we scale them by dividing them by a scaling factor √dk." }, { "code": null, "e": 9272, "s": 9189, "text": "Mask: The optional padding mask is already discussed in the masking section above." }, { "code": null, "e": 9368, "s": 9272, "text": "Softmax: The softmax function brings down the values to a probability distribution i.e. [0, 1]." }, { "code": null, "e": 9501, "s": 9368, "text": "The scaled dot-product attention is a major component of the multi-head attention which we are about to see in the next sub-section." }, { "code": null, "e": 9601, "s": 9501, "text": "Multi-Head Attention is essentially the integration of all the previously discussed micro-concepts." }, { "code": null, "e": 9931, "s": 9601, "text": "In the adjacent figure, h is the number of heads. As far as the math is concerned, the initial inputs to the Multi-Head Attention are split into h parts, each having Queries, Keys, and Values, for max_length words in a sequence, for batch_size sequences. The dimensions of Q, K, V are called depth which is calculated as follows:" }, { "code": null, "e": 9952, "s": 9931, "text": "depth = d_model // h" }, { "code": null, "e": 10347, "s": 9952, "text": "This is the reason why d_model needs to be completely divisible by h. So, while splitting, the d_model shaped vectors are split into h vectors of shape depth. These vectors are passed as Q, K, V to the scaled dot product, and the output is ‘Concat’ by again reshaping the h vectors into 1 vector of shape d_model. This reformed vector is then passed through a feed-forward neural network layer." }, { "code": null, "e": 10531, "s": 10347, "text": "The Point-wise feed-forward network block is essentially a two-layer linear transformation which is used identically throughout the model architecture, usually after attention blocks." }, { "code": null, "e": 10670, "s": 10531, "text": "For Regularization, a dropout is applied to the output of each sub-layer before it is added to the inputs of the sub-layer and normalized." }, { "code": null, "e": 10805, "s": 10670, "text": "All the components are assembled together to build the Transformer. The Encoder block is the one in the left and Decoder to the right." }, { "code": null, "e": 10902, "s": 10805, "text": "The Encoder and the Decoder blocks may be optionally fine-tuned to Nx units to adjust the model." }, { "code": null, "e": 11231, "s": 10902, "text": "In this post, we’ve seen the issues with RNN-based approaches in sequence transduction tasks and how the revolutionary, Transformer model addresses them. Later, we studied the mechanisms underlying the Transformer and their working. Finally, we saw how various components and the underlying mechanisms work with the Transformer." }, { "code": null, "e": 11351, "s": 11231, "text": "I have covered the step-by-step implementation of Transformer using TensorFlow for Abstractive Text Summarization here." }, { "code": null, "e": 11440, "s": 11351, "text": "“Attention is all you need” Original Transformer Paper: https://arxiv.org/abs/1706.03762" }, { "code": null, "e": 11487, "s": 11440, "text": "Seq2Seq paper: https://arxiv.org/abs/1409.3215" }, { "code": null, "e": 11545, "s": 11487, "text": "Bahdanau Attention Paper: https://arxiv.org/abs/1409.0473" }, { "code": null, "e": 11641, "s": 11545, "text": "ConvS2S and ByteNet Papers: https://arxiv.org/abs/1705.03122 , https://arxiv.org/abs/1610.10099" }, { "code": null, "e": 11664, "s": 11641, "text": "towardsdatascience.com" }, { "code": null, "e": 11684, "s": 11664, "text": "mchromiak.github.io" } ]
Data Hiding in Python
An object's attributes may or may not be visible outside the class definition. You need to name attributes with a double underscore prefix, and those attributes then are not be directly visible to outsiders. Live Demo #!/usr/bin/python class JustCounter: __secretCount = 0 def count(self): self.__secretCount += 1 print self.__secretCount counter = JustCounter() counter.count() counter.count() print counter.__secretCount When the above code is executed, it produces the following result − 1 2 Traceback (most recent call last): File "test.py", line 12, in <module> print counter.__secretCount AttributeError: JustCounter instance has no attribute '__secretCount' Python protects those members by internally changing the name to include the class name. You can access such attributes as object._className__attrName. If you would replace your last line as following, then it works for you − ......................... print counter._JustCounter__secretCount When the above code is executed, it produces the following result − 1 2 2
[ { "code": null, "e": 1270, "s": 1062, "text": "An object's attributes may or may not be visible outside the class definition. You need to name attributes with a double underscore prefix, and those attributes then are not be directly visible to outsiders." }, { "code": null, "e": 1281, "s": 1270, "text": " Live Demo" }, { "code": null, "e": 1504, "s": 1281, "text": "#!/usr/bin/python\nclass JustCounter:\n __secretCount = 0\n def count(self):\n self.__secretCount += 1\n print self.__secretCount\ncounter = JustCounter()\ncounter.count()\ncounter.count()\nprint counter.__secretCount" }, { "code": null, "e": 1572, "s": 1504, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 1755, "s": 1572, "text": "1\n2\nTraceback (most recent call last):\n File \"test.py\", line 12, in <module>\n print counter.__secretCount\nAttributeError: JustCounter instance has no attribute '__secretCount'" }, { "code": null, "e": 1981, "s": 1755, "text": "Python protects those members by internally changing the name to include the class name. You can access such attributes as object._className__attrName. If you would replace your last line as following, then it works for you −" }, { "code": null, "e": 2047, "s": 1981, "text": ".........................\nprint counter._JustCounter__secretCount" }, { "code": null, "e": 2115, "s": 2047, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 2121, "s": 2115, "text": "1\n2\n2" } ]
How to create a unique ID for each object in JavaScript?
Following is the code to create a unique ID for each object − Live Demo <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; } .result { font-size: 18px; font-weight: 500; color: rebeccapurple; } </style> </head> <body> <h1>Create a unique ID for each object</h1> <div class="result"></div> <button class="Btn">CLICK HERE</button&g; <h3>Click on the above button to check if id generated are unique or not</h3> <script> let resEle = document.querySelector(".result"); let BtnEle = document.querySelector(".Btn"); let obj = { id: Symbol("UID"), a: 22, b: 44, }; let obj1 = { id: Symbol("UID"), a: 12, b: 41, }; BtnEle.addEventListener("click", () => { if (obj.id === obj1.id) { resEle.innerHTML = "The id generated are not unique <br>"; } else { resEle.innerHTML = "The id generated is unique for each object"; } }); </script> </body> </html> The above code will produce the following output − On clicking the ‘CLICK HERE’ button −
[ { "code": null, "e": 1124, "s": 1062, "text": "Following is the code to create a unique ID for each object −" }, { "code": null, "e": 1135, "s": 1124, "text": " Live Demo" }, { "code": null, "e": 2229, "s": 1135, "text": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\" />\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n<title>Document</title>\n<style>\n body {\n font-family: \"Segoe UI\", Tahoma, Geneva, Verdana, sans-serif;\n }\n .result {\n font-size: 18px;\n font-weight: 500;\n color: rebeccapurple;\n }\n</style>\n</head>\n<body>\n<h1>Create a unique ID for each object</h1>\n<div class=\"result\"></div>\n<button class=\"Btn\">CLICK HERE</button&g;\n<h3>Click on the above button to check if id generated are unique or not</h3>\n<script>\n let resEle = document.querySelector(\".result\");\n let BtnEle = document.querySelector(\".Btn\");\n let obj = {\n id: Symbol(\"UID\"),\n a: 22,\n b: 44,\n };\n let obj1 = {\n id: Symbol(\"UID\"),\n a: 12,\n b: 41,\n };\n BtnEle.addEventListener(\"click\", () => {\n if (obj.id === obj1.id) {\n resEle.innerHTML = \"The id generated are not unique <br>\";\n }\n else {\n resEle.innerHTML = \"The id generated is unique for each object\";\n }\n });\n</script>\n</body>\n</html>" }, { "code": null, "e": 2280, "s": 2229, "text": "The above code will produce the following output −" }, { "code": null, "e": 2318, "s": 2280, "text": "On clicking the ‘CLICK HERE’ button −" } ]
ExpressJS - Quick Guide
ExpressJS is a web application framework that provides you with a simple API to build websites, web apps and back ends. With ExpressJS, you need not worry about low level protocols, processes, etc. Express provides a minimal interface to build our applications. It provides us the tools that are required to build our app. It is flexible as there are numerous modules available on npm, which can be directly plugged into Express. Express was developed by TJ Holowaychuk and is maintained by the Node.js foundation and numerous open source contributors. Unlike its competitors like Rails and Django, which have an opinionated way of building applications, Express has no "best way" to do something. It is very flexible and pluggable. Pug (earlier known as Jade) is a terse language for writing HTML templates. It − Produces HTML Supports dynamic code Supports reusability (DRY) It is one of the most popular template language used with Express. MongoDB is an open-source, document database designed for ease of development and scaling. This database is also used to store data. Mongoose is a client API for node.js which makes it easy to access our database from our Express application. In this chapter, we will learn how to start developing and using the Express Framework. To start with, you should have the Node and the npm (node package manager) installed. If you don’t already have these, go to the Node setup to install node on your local system. Confirm that node and npm are installed by running the following commands in your terminal. node --version npm --version You should get an output similar to the following. v5.0.0 3.5.2 Now that we have Node and npm set up, let us understand what npm is and how to use it. npm is the package manager for node. The npm Registry is a public collection of packages of open-source code for Node.js, front-end web apps, mobile apps, robots, routers, and countless other needs of the JavaScript community. npm allows us to access all these packages and install them locally. You can browse through the list of packages available on npm at npmJS. There are two ways to install a package using npm: globally and locally. Globally − This method is generally used to install development tools and CLI based packages. To install a package globally, use the following code. Globally − This method is generally used to install development tools and CLI based packages. To install a package globally, use the following code. npm install -g <package-name> Locally − This method is generally used to install frameworks and libraries. A locally installed package can be used only within the directory it is installed. To install a package locally, use the same command as above without the -g flag. Locally − This method is generally used to install frameworks and libraries. A locally installed package can be used only within the directory it is installed. To install a package locally, use the same command as above without the -g flag. npm install <package-name> Whenever we create a project using npm, we need to provide a package.json file, which has all the details about our project. npm makes it easy for us to set up this file. Let us set up our development project. Step 1 − Start your terminal/cmd, create a new folder named hello-world and cd (create directory) into it − Step 2 − Now to create the package.json file using npm, use the following code. npm init It will ask you for the following information. Just keep pressing enter, and enter your name at the “author name” field. Step 3 − Now we have our package.json file set up, we will further install Express. To install Express and add it to our package.json file, use the following command − npm install --save express To confirm that Express has installed correctly, run the following code. ls node_modules #(dir node_modules for windows) Tip − The --save flag can be replaced by the -S flag. This flag ensures that Express is added as a dependency to our package.json file. This has an advantage, the next time we need to install all the dependencies of our project we can just run the command npm install and it will find the dependencies in this file and install them for us. This is all we need to start development using the Express framework. To make our development process a lot easier, we will install a tool from npm, nodemon. This tool restarts our server as soon as we make a change in any of our files, otherwise we need to restart the server manually after each file modification. To install nodemon, use the following command − npm install -g nodemon You can now start working on Express. We have set up the development, now it is time to start developing our first app using Express. Create a new file called index.js and type the following in it. var express = require('express'); var app = express(); app.get('/', function(req, res){ res.send("Hello world!"); }); app.listen(3000); Save the file, go to your terminal and type the following. nodemon index.js This will start the server. To test this app, open your browser and go to http://localhost:3000 and a message will be displayed as in the following screenshot. The first line imports Express in our file, we have access to it through the variable Express. We use it to create an application and assign it to var app. This function tells what to do when a get request at the given route is called. The callback function has 2 parameters, request(req) and response(res). The request object(req) represents the HTTP request and has properties for the request query string, parameters, body, HTTP headers, etc. Similarly, the response object represents the HTTP response that the Express app sends when it receives an HTTP request. This function takes an object as input and it sends this to the requesting client. Here we are sending the string "Hello World!". This function binds and listens for connections on the specified host and port. Port is the only required parameter here. port A port number on which the server should accept incoming requests. host Name of the domain. You need to set it when you deploy your apps to the cloud. backlog The maximum number of queued pending connections. The default is 511. callback An asynchronous function that is called when the server starts listening for requests. Web frameworks provide resources such as HTML pages, scripts, images, etc. at different routes. The following function is used to define routes in an Express application − This METHOD can be applied to any one of the HTTP verbs – get, set, put, delete. An alternate method also exists, which executes independent of the request type. Path is the route at which the request will run. Handler is a callback function that executes when a matching request type is found on the relevant route. For example, var express = require('express'); var app = express(); app.get('/hello', function(req, res){ res.send("Hello World!"); }); app.listen(3000); If we run our application and go to localhost:3000/hello, the server receives a get request at route "/hello", our Express app executes the callback function attached to this route and sends "Hello World!" as the response. We can also have multiple different methods at the same route. For example, var express = require('express'); var app = express(); app.get('/hello', function(req, res){ res.send("Hello World!"); }); app.post('/hello', function(req, res){ res.send("You just called the post method at '/hello'!\n"); }); app.listen(3000); To test this request, open up your terminal and use cURL to execute the following request − curl -X POST "http://localhost:3000/hello" A special method, all, is provided by Express to handle all types of http methods at a particular route using the same function. To use this method, try the following. app.all('/test', function(req, res){ res.send("HTTP method doesn't have any effect on this route!"); }); This method is generally used for defining middleware, which we'll discuss in the middleware chapter. Defining routes like above is very tedious to maintain. To separate the routes from our main index.js file, we will use Express.Router. Create a new file called things.js and type the following in it. var express = require('express'); var router = express.Router(); router.get('/', function(req, res){ res.send('GET route on things.'); }); router.post('/', function(req, res){ res.send('POST route on things.'); }); //export this router to use in our index.js module.exports = router; Now to use this router in our index.js, type in the following before the app.listen function call. var express = require('Express'); var app = express(); var things = require('./things.js'); //both index.js and things.js should be in same directory app.use('/things', things); app.listen(3000); The app.use function call on route '/things' attaches the things router with this route. Now whatever requests our app gets at the '/things', will be handled by our things.js router. The '/' route in things.js is actually a subroute of '/things'. Visit localhost:3000/things/ and you will see the following output. Routers are very helpful in separating concerns and keep relevant portions of our code together. They help in building maintainable code. You should define your routes relating to an entity in a single file and include it using the above method in your index.js file. The HTTP method is supplied in the request and specifies the operation that the client has requested. The following table lists the most used HTTP methods − GET The GET method requests a representation of the specified resource. Requests using GET should only retrieve data and should have no other effect. POST The POST method requests that the server accept the data enclosed in the request as a new object/entity of the resource identified by the URI. PUT The PUT method requests that the server accept the data enclosed in the request as a modification to existing object identified by the URI. If it does not exist then the PUT method should create one. DELETE The DELETE method requests that the server delete the specified resource. These are the most common HTTP methods. To learn more about the methods, visit http://www.tutorialspoint.com/http/http_methods.htm. We can now define routes, but those are static or fixed. To use the dynamic routes, we SHOULD provide different types of routes. Using dynamic routes allows us to pass parameters and process based on them. Here is an example of a dynamic route − var express = require('express'); var app = express(); app.get('/:id', function(req, res){ res.send('The id you specified is ' + req.params.id); }); app.listen(3000); To test this go to http://localhost:3000/123. The following response will be displayed. You can replace '123' in the URL with anything else and the change will reflect in the response. A more complex example of the above is − var express = require('express'); var app = express(); app.get('/things/:name/:id', function(req, res) { res.send('id: ' + req.params.id + ' and name: ' + req.params.name); }); app.listen(3000); To test the above code, go to http://localhost:3000/things/tutorialspoint/12345. You can use the req.params object to access all the parameters you pass in the url. Note that the above 2 are different paths. They will never overlap. Also if you want to execute code when you get '/things' then you need to define it separately. You can also use regex to restrict URL parameter matching. Let us assume you need the id to be a 5-digit long number. You can use the following route definition − var express = require('express'); var app = express(); app.get('/things/:id([0-9]{5})', function(req, res){ res.send('id: ' + req.params.id); }); app.listen(3000); Note that this will only match the requests that have a 5-digit long id. You can use more complex regexes to match/validate your routes. If none of your routes match the request, you'll get a "Cannot GET <your-request-route>" message as response. This message be replaced by a 404 not found page using this simple route − var express = require('express'); var app = express(); //Other routes here app.get('*', function(req, res){ res.send('Sorry, this is an invalid URL.'); }); app.listen(3000); Important − This should be placed after all your routes, as Express matches routes from start to end of the index.js file, including the external routers you required. For example, if we define the same routes as above, on requesting with a valid URL, the following output is displayed. − While for an incorrect URL request, the following output is displayed. Middleware functions are functions that have access to the request object (req), the response object (res), and the next middleware function in the application’s request-response cycle. These functions are used to modify req and res objects for tasks like parsing request bodies, adding response headers, etc. Here is a simple example of a middleware function in action − var express = require('express'); var app = express(); //Simple request time logger app.use(function(req, res, next){ console.log("A new request received at " + Date.now()); //This function call is very important. It tells that more processing is //required for the current request and is in the next middleware function route handler. next(); }); app.listen(3000); The above middleware is called for every request on the server. So after every request, we will get the following message in the console − A new request received at 1467267512545 To restrict it to a specific route (and all its subroutes), provide that route as the first argument of app.use(). For Example, var express = require('express'); var app = express(); //Middleware function to log request protocol app.use('/things', function(req, res, next){ console.log("A request for things received at " + Date.now()); next(); }); // Route handler that sends the response app.get('/things', function(req, res){ res.send('Things'); }); app.listen(3000); Now whenever you request any subroute of '/things', only then it will log the time. One of the most important things about middleware in Express is the order in which they are written/included in your file; the order in which they are executed, given that the route matches also needs to be considered. For example, in the following code snippet, the first function executes first, then the route handler and then the end function. This example summarizes how to use middleware before and after route handler; also how a route handler can be used as a middleware itself. var express = require('express'); var app = express(); //First middleware before response is sent app.use(function(req, res, next){ console.log("Start"); next(); }); //Route handler app.get('/', function(req, res, next){ res.send("Middle"); next(); }); app.use('/', function(req, res){ console.log('End'); }); app.listen(3000); When we visit '/' after running this code, we receive the response as Middle and on our console − Start End The following diagram summarizes what we have learnt about middleware − Now that we have covered how to create our own middleware, let us discuss some of the most commonly used community created middleware. A list of Third party middleware for Express is available here. Following are some of the most commonly used middleware; we will also learn how to use/mount these − This is used to parse the body of requests which have payloads attached to them. To mount body parser, we need to install it using npm install --save body-parser and to mount it, include the following lines in your index.js − var bodyParser = require('body-parser'); //To parse URL encoded data app.use(bodyParser.urlencoded({ extended: false })) //To parse json data app.use(bodyParser.json()) To view all available options for body-parser, visit its github page. It parses Cookie header and populate req.cookies with an object keyed by cookie names. To mount cookie parser, we need to install it using npm install --save cookie-parser and to mount it, include the following lines in your index.js − var cookieParser = require('cookie-parser'); app.use(cookieParser()) It creates a session middleware with the given options. We will discuss its usage in the Sessions section. We have many other third party middleware in ExpressJS. However, we have discussed only a few important ones here. Pug is a templating engine for Express. Templating engines are used to remove the cluttering of our server code with HTML, concatenating strings wildly to existing HTML templates. Pug is a very powerful templating engine which has a variety of features including filters, includes, inheritance, interpolation, etc. There is a lot of ground to cover on this. To use Pug with Express, we need to install it, npm install --save pug Now that Pug is installed, set it as the templating engine for your app. You don't need to 'require' it. Add the following code to your index.js file. app.set('view engine', 'pug'); app.set('views','./views'); Now create a new directory called views. Inside that create a file called first_view.pug, and enter the following data in it. doctype html html head title = "Hello Pug" body p.greetings#people Hello World! To run this page, add the following route to your app − app.get('/first_template', function(req, res){ res.render('first_view'); }); You will get the output as − Hello World! Pug converts this very simple looking markup to html. We don’t need to keep track of closing our tags, no need to use class and id keywords, rather use '.' and '#' to define them. The above code first gets converted to − <!DOCTYPE html> <html> <head> <title>Hello Pug</title> </head> <body> <p class = "greetings" id = "people">Hello World!</p> </body> </html> Pug is capable of doing much more than simplifying HTML markup. Let us now explore a few important features of Pug. Tags are nested according to their indentation. Like in the above example, <title> was indented within the <head> tag, so it was inside it. But the <body> tag was on the same indentation, so it was a sibling of the <head> tag. We don’t need to close tags, as soon as Pug encounters the next tag on same or outer indentation level, it closes the tag for us. To put text inside of a tag, we have 3 methods − Space seperated Space seperated h1 Welcome to Pug Piped text Piped text div | To insert multiline text, | You can use the pipe operator. Block of text Block of text div. But that gets tedious if you have a lot of text. You can use "." at the end of tag to denote block of text. To put tags inside this block, simply enter tag in a new line and indent it accordingly. Pug uses the same syntax as JavaScript(//) for creating comments. These comments are converted to the html comments(<!--comment-->). For example, //This is a Pug comment This comment gets converted to the following. <!--This is a Pug comment--> To define attributes, we use a comma separated list of attributes, in parenthesis. Class and ID attributes have special representations. The following line of code covers defining attributes, classes and id for a given html tag. div.container.column.main#division(width = "100", height = "100") This line of code, gets converted to the following. − <div class = "container column main" id = "division" width = "100" height = "100"></div> When we render a Pug template, we can actually pass it a value from our route handler, which we can then use in our template. Create a new route handler with the following. var express = require('express'); var app = express(); app.get('/dynamic_view', function(req, res){ res.render('dynamic', { name: "TutorialsPoint", url:"http://www.tutorialspoint.com" }); }); app.listen(3000); And create a new view file in views directory, called dynamic.pug, with the following code − html head title=name body h1=name a(href = url) URL Open localhost:3000/dynamic_view in your browser; You should get the following output − We can also use these passed variables within text. To insert passed variables in between text of a tag, we use #{variableName} syntax. For example, in the above example, if we wanted to put Greetings from TutorialsPoint, then we could have done the following. html head title = name body h1 Greetings from #{name} a(href = url) URL This method of using values is called interpolation. The above code will display the following output. − We can use conditional statements and looping constructs as well. Consider the following − If a User is logged in, the page should display "Hi, User" and if not, then the "Login/Sign Up" link. To achieve this, we can define a simple template like − html head title Simple template body if(user) h1 Hi, #{user.name} else a(href = "/sign_up") Sign Up When we render this using our routes, we can pass an object as in the following program − res.render('/dynamic',{ user: {name: "Ayush", age: "20"} }); You will receive a message − Hi, Ayush. But if we don’t pass any object or pass one with no user key, then we will get a signup link. Pug provides a very intuitive way to create components for a web page. For example, if you see a news website, the header with logo and categories is always fixed. Instead of copying that to every view we create, we can use the include feature. Following example shows how we can use this feature − Create 3 views with the following code − HEADER.PUG div.header. I'm the header for this website. CONTENT.PUG html head title Simple template body include ./header.pug h3 I'm the main content include ./footer.pug FOOTER.PUG div.footer. I'm the footer for this website. Create a route for this as follows − var express = require('express'); var app = express(); app.get('/components', function(req, res){ res.render('content'); }); app.listen(3000); Go to localhost:3000/components, you will receive the following output − include can also be used to include plaintext, css and JavaScript. There are many more features of Pug. But those are out of the scope for this tutorial. You can further explore Pug at Pug. Static files are files that clients download as they are from the server. Create a new directory, public. Express, by default does not allow you to serve static files. You need to enable it using the following built-in middleware. app.use(express.static('public')); Note − Express looks up the files relative to the static directory, so the name of the static directory is not part of the URL. Note that the root route is now set to your public dir, so all static files you load will be considering public as root. To test that this is working fine, add any image file in your new public dir and change its name to "testimage.jpg". In your views, create a new view and include this file like − html head body h3 Testing static file serving: img(src = "/testimage.jpg", alt = "Testing Image You should get the following output − We can also set multiple static assets directories using the following program − var express = require('express'); var app = express(); app.use(express.static('public')); app.use(express.static('images')); app.listen(3000); We can also provide a path prefix for serving static files. For example, if you want to provide a path prefix like '/static', you need to include the following code in your index.js file − var express = require('express'); var app = express(); app.use('/static', express.static('public')); app.listen(3000); Now whenever you need to include a file, for example, a script file called main.js residing in your public directory, use the following script tag − <script src = "/static/main.js" /> This technique can come in handy when providing multiple directories as static files. These prefixes can help distinguish between multiple directories. Forms are an integral part of the web. Almost every website we visit offers us forms that submit or fetch some information for us. To get started with forms, we will first install the body-parser(for parsing JSON and url-encoded data) and multer(for parsing multipart/form data) middleware. To install the body-parser and multer, go to your terminal and use − npm install --save body-parser multer Replace your index.js file contents with the following code − var express = require('express'); var bodyParser = require('body-parser'); var multer = require('multer'); var upload = multer(); var app = express(); app.get('/', function(req, res){ res.render('form'); }); app.set('view engine', 'pug'); app.set('views', './views'); // for parsing application/json app.use(bodyParser.json()); // for parsing application/xwww- app.use(bodyParser.urlencoded({ extended: true })); //form-urlencoded // for parsing multipart/form-data app.use(upload.array()); app.use(express.static('public')); app.post('/', function(req, res){ console.log(req.body); res.send("recieved your request!"); }); app.listen(3000); After importing the body parser and multer, we will use the body-parser for parsing json and x-www-form-urlencoded header requests, while we will use multer for parsing multipart/form-data. Let us create an html form to test this out. Create a new view called form.pug with the following code − html html head title Form Tester body form(action = "/", method = "POST") div label(for = "say") Say: input(name = "say" value = "Hi") br div label(for = "to") To: input(name = "to" value = "Express forms") br button(type = "submit") Send my greetings Run your server using the following. nodemon index.js Now go to localhost:3000/ and fill the form as you like, and submit it. The following response will be displayed − Have a look at your console; it will show you the body of your request as a JavaScript object as in the following screenshot − The req.body object contains your parsed request body. To use fields from that object, just use them like normal JS objects. This is the most recommended way to send a request. There are many other ways, but those are irrelevant to cover here, because our Express app will handle all those requests in the same way. To read more about different ways to make a request, have a look at this page. We keep receiving requests, but end up not storing them anywhere. We need a Database to store the data. For this, we will make use of the NoSQL database called MongoDB. To install and read about Mongo, follow this link. In order to use Mongo with Express, we need a client API for node. There are multiple options for us, but for this tutorial, we will stick to mongoose. Mongoose is used for document Modeling in Node for MongoDB. For document modeling, we create a Model (much like a class in document oriented programming), and then we produce documents using this Model (like we create documents of a class in OOP). All our processing will be done on these "documents", then finally, we will write these documents in our database. Now that you have installed Mongo, let us install Mongoose, the same way we have been installing our other node packages − npm install --save mongoose Before we start using mongoose, we have to create a database using the Mongo shell. To create a new database, open your terminal and enter "mongo". A Mongo shell will start, enter the following code − use my_db A new database will be created for you. Whenever you open up the mongo shell, it will default to "test" db and you will have to change to your database using the same command as above. To use Mongoose, we will require it in our index.js file and then connect to the mongodb service running on mongodb://localhost. var mongoose = require('mongoose'); mongoose.connect('mongodb://localhost/my_db'); Now our app is connected to our database, let us create a new Model. This model will act as a collection in our database. To create a new Model, use the following code, before defining any route − var personSchema = mongoose.Schema({ name: String, age: Number, nationality: String }); var Person = mongoose.model("Person", personSchema); The above code defines the schema for a person and is used to create a Mongoose Mode Person. Now, we will create a new html form; this form will help you get the details of a person and save it to our database. To create the form, create a new view file called person.pug in views directory with the following content − html head title Person body form(action = "/person", method = "POST") div label(for = "name") Name: input(name = "name") br div label(for = "age") Age: input(name = "age") br div label(for = "nationality") Nationality: input(name = "nationality") br button(type = "submit") Create new person Also add a new get route in index.js to render this document − app.get('/person', function(req, res){ res.render('person'); }); Go to "localhost:3000/person" to check if the form is displaying the correct output. Note that this is just the UI, it is not working yet. The following screenshot shows how the form is displayed − We will now define a post route handler at '/person' which will handle this request app.post('/person', function(req, res){ var personInfo = req.body; //Get the parsed information if(!personInfo.name || !personInfo.age || !personInfo.nationality){ res.render('show_message', { message: "Sorry, you provided worng info", type: "error"}); } else { var newPerson = new Person({ name: personInfo.name, age: personInfo.age, nationality: personInfo.nationality }); newPerson.save(function(err, Person){ if(err) res.render('show_message', {message: "Database error", type: "error"}); else res.render('show_message', { message: "New person added", type: "success", person: personInfo}); }); } }); In the above code, if we receive any empty field or do not receive any field, we will send an error response. But if we receive a well-formed document, then we create a newPerson document from Person model and save it to our DB using the newPerson.save() function. This is defined in Mongoose and accepts a callback as argument. This callback has 2 arguments – error and response. These arguments will render the show_message view. To show the response from this route, we will also need to create a show_message view. Create a new view with the following code − html head title Person body if(type == "error") h3(style = "color:red") #{message} else h3 New person, name: #{person.name}, age: #{person.age} and nationality: #{person.nationality} added! We will receive the following response on successfully submitting the form(show_message.pug) − We now have an interface to create persons. Mongoose provides a lot of functions for retrieving documents, we will focus on 3 of those. All these functions also take a callback as the last parameter, and just like the save function, their arguments are error and response. The three functions are as follows − This function finds all the documents matching the fields in conditions object. Same operators used in Mongo also work in mongoose. For example, Person.find(function(err, response){ console.log(response); }); This will fetch all the documents from the person's collection. Person.find({name: "Ayush", age: 20}, function(err, response){ console.log(response); }); This will fetch all documents where field name is "Ayush" and age is 20. We can also provide projection we need, i.e., the fields we need. For example, if we want only the names of people whose nationality is "Indian", we use − Person.find({nationality: "Indian"}, "name", function(err, response){ console.log(response); }); This function always fetches a single, most relevant document. It has the same exact arguments as Model.find(). This function takes in the _id(defined by mongo) as the first argument, an optional projection string and a callback to handle the response. For example, Person.findById("507f1f77bcf86cd799439011", function(err, response){ console.log(response); }); Let us now create a route to view all people records − var express = require('express'); var app = express(); var mongoose = require('mongoose'); mongoose.connect('mongodb://localhost/my_db'); var personSchema = mongoose.Schema({ name: String, age: Number, nationality: String }); var Person = mongoose.model("Person", personSchema); app.get('/people', function(req, res){ Person.find(function(err, response){ res.json(response); }); }); app.listen(3000); Mongoose provides 3 functions to update documents. The functions are described below − This function takes a conditions and updates an object as input and applies the changes to all the documents matching the conditions in the collection. For example, following code will update the nationality "American" in all Person documents − Person.update({age: 25}, {nationality: "American"}, function(err, response){ console.log(response); }); It finds one document based on the query and updates that according to the second argument. It also takes a callback as last argument. Let us perform the following example to understand the function Person.findOneAndUpdate({name: "Ayush"}, {age: 40}, function(err, response) { console.log(response); }); This function updates a single document identified by its id. For example, Person.findByIdAndUpdate("507f1f77bcf86cd799439011", {name: "James"}, function(err, response){ console.log(response); }); Let us now create a route to update people. This will be a PUT route with the id as a parameter and details in the payload. var express = require('express'); var app = express(); var mongoose = require('mongoose'); mongoose.connect('mongodb://localhost/my_db'); var personSchema = mongoose.Schema({ name: String, age: Number, nationality: String }); var Person = mongoose.model("Person", personSchema); app.put('/people/:id', function(req, res){ Person.findByIdAndUpdate(req.params.id, req.body, function(err, response){ if(err) res.json({message: "Error in updating person with id " + req.params.id}); res.json(response); }); }); app.listen(3000); To test this route, enter the following in your terminal (replace the id with an id from your created people) − curl -X PUT --data "name = James&age = 20&nationality = American "http://localhost:3000/people/507f1f77bcf86cd799439011 This will update the document associated with the id provided in the route with the above details. We have covered Create, Read and Update, now we will see how Mongoose can be used to Delete documents. We have 3 functions here, exactly like update. This function takes a condition object as input and removes all documents matching the conditions. For example, if we need to remove all people aged 20, use the following syntax − Person.remove({age:20}); This functions removes a single, most relevant document according to conditions object. Let us execute the following code to understand the same. Person.findOneAndRemove({name: "Ayush"}); This function removes a single document identified by its id. For example, Person.findByIdAndRemove("507f1f77bcf86cd799439011"); Let us now create a route to delete people from our database. var express = require('express'); var app = express(); var mongoose = require('mongoose'); mongoose.connect('mongodb://localhost/my_db'); var personSchema = mongoose.Schema({ name: String, age: Number, nationality: String }); var Person = mongoose.model("Person", personSchema); app.delete('/people/:id', function(req, res){ Person.findByIdAndRemove(req.params.id, function(err, response){ if(err) res.json({message: "Error in deleting record id " + req.params.id}); else res.json({message: "Person with id " + req.params.id + " removed."}); }); }); app.listen(3000); To check the output, use the following curl command − curl -X DELETE http://localhost:3000/people/507f1f77bcf86cd799439011 This will remove the person with given id producing the following message − {message: "Person with id 507f1f77bcf86cd799439011 removed."} This wraps up how we can create simple CRUD applications using MongoDB, Mongoose and Express. To explore Mongoose further, read the API docs. Cookies are simple, small files/data that are sent to client with a server request and stored on the client side. Every time the user loads the website back, this cookie is sent with the request. This helps us keep track of the user’s actions. The following are the numerous uses of the HTTP Cookies − Session management Personalization(Recommendation systems) User tracking To use cookies with Express, we need the cookie-parser middleware. To install it, use the following code − npm install --save cookie-parser Now to use cookies with Express, we will require the cookie-parser. cookie-parser is a middleware which parses cookies attached to the client request object. To use it, we will require it in our index.js file; this can be used the same way as we use other middleware. Here, we will use the following code. var cookieParser = require('cookie-parser'); app.use(cookieParser()); cookie-parser parses Cookie header and populates req.cookies with an object keyed by the cookie names. To set a new cookie, let us define a new route in your Express app like − var express = require('express'); var app = express(); app.get('/', function(req, res){ res.cookie('name', 'express').send('cookie set'); //Sets name = express }); app.listen(3000); To check if your cookie is set or not, just go to your browser, fire up the console, and enter − console.log(document.cookie); You will get the output like (you may have more cookies set maybe due to extensions in your browser) − "name = express" The browser also sends back cookies every time it queries the server. To view cookies from your server, on the server console in a route, add the following code to that route. console.log('Cookies: ', req.cookies); Next time you send a request to this route, you will receive the following output. Cookies: { name: 'express' } You can add cookies that expire. To add a cookie that expires, just pass an object with property 'expire' set to the time when you want it to expire. For example, //Expires after 360000 ms from the time it is set. res.cookie(name, 'value', {expire: 360000 + Date.now()}); Another way to set expiration time is using 'maxAge' property. Using this property, we can provide relative time instead of absolute time. Following is an example of this method. //This cookie also expires after 360000 ms from the time it is set. res.cookie(name, 'value', {maxAge: 360000}); To delete a cookie, use the clearCookie function. For example, if you need to clear a cookie named foo, use the following code. var express = require('express'); var app = express(); app.get('/clear_cookie_foo', function(req, res){ res.clearCookie('foo'); res.send('cookie foo cleared'); }); app.listen(3000); In the next chapter, we will see how to use cookies to manage sessions. HTTP is stateless; in order to associate a request to any other request, you need a way to store user data between HTTP requests. Cookies and URL parameters are both suitable ways to transport data between the client and the server. But they are both readable and on the client side. Sessions solve exactly this problem. You assign the client an ID and it makes all further requests using that ID. Information associated with the client is stored on the server linked to this ID. We will need the Express-session, so install it using the following code. npm install --save express-session We will put the session and cookie-parser middleware in place. In this example, we will use the default store for storing sessions, i.e., MemoryStore. Never use this in production environments. The session middleware handles all things for us, i.e., creating the session, setting the session cookie and creating the session object in req object. Whenever we make a request from the same client again, we will have their session information stored with us (given that the server was not restarted). We can add more properties to the session object. In the following example, we will create a view counter for a client. var express = require('express'); var cookieParser = require('cookie-parser'); var session = require('express-session'); var app = express(); app.use(cookieParser()); app.use(session({secret: "Shh, its a secret!"})); app.get('/', function(req, res){ if(req.session.page_views){ req.session.page_views++; res.send("You visited this page " + req.session.page_views + " times"); } else { req.session.page_views = 1; res.send("Welcome to this page for the first time!"); } }); app.listen(3000); What the above code does is, when a user visits the site, it creates a new session for the user and assigns them a cookie. Next time the user comes, the cookie is checked and the page_view session variable is updated accordingly. Now if you run the app and go to localhost:3000, the following output will be displayed. If you revisit the page, the page counter will increase. The page in the following screenshot was refreshed 42 times. Authentication is a process in which the credentials provided are compared to those on file in a database of authorized users' information on a local operating system or within an authentication server. If the credentials match, the process is completed and the user is granted authorization for access. For us to create an authentication system, we will need to create a sign up page and a user-password store. The following code creates an account for us and stores it in memory. This is just for the purpose of demo; it is recommended that a persistent storage (database or files) is always used to store user information. var express = require('express'); var app = express(); var bodyParser = require('body-parser'); var multer = require('multer'); var upload = multer(); var session = require('express-session'); var cookieParser = require('cookie-parser'); app.set('view engine', 'pug'); app.set('views','./views'); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); app.use(upload.array()); app.use(cookieParser()); app.use(session({secret: "Your secret key"})); var Users = []; app.get('/signup', function(req, res){ res.render('signup'); }); app.post('/signup', function(req, res){ if(!req.body.id || !req.body.password){ res.status("400"); res.send("Invalid details!"); } else { Users.filter(function(user){ if(user.id === req.body.id){ res.render('signup', { message: "User Already Exists! Login or choose another user id"}); } }); var newUser = {id: req.body.id, password: req.body.password}; Users.push(newUser); req.session.user = newUser; res.redirect('/protected_page'); } }); app.listen(3000); Now for the signup form, create a new view called signup.jade. html head title Signup body if(message) h4 #{message} form(action = "/signup" method = "POST") input(name = "id" type = "text" required placeholder = "User ID") input(name = "password" type = "password" required placeholder = "Password") button(type = "Submit") Sign me up! Check if this page loads by visiting localhost:3000/signup. We have set the required attribute for both fields, so HTML5 enabled browsers will not let us submit this form until we provide both id and password. If someone tries to register using a curl request without a User ID or Password, an error will be displayed. Create a new file called protected_page.pug in views with the following content − html head title Protected page body div Hey #{id}, How are you doing today? div Want to log out? div Logout This page should only be visible if the user has just signed up or logged in. Let us now define its route and also routes to log in and log out − var express = require('express'); var app = express(); var bodyParser = require('body-parser'); var multer = require('multer'); var upload = multer(); var session = require('express-session'); var cookieParser = require('cookie-parser'); app.set('view engine', 'pug'); app.set('views','./views'); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); app.use(upload.array()); app.use(cookieParser()); app.use(session({secret: "Your secret key"})); var Users = []; app.get('/signup', function(req, res){ res.render('signup'); }); app.post('/signup', function(req, res){ if(!req.body.id || !req.body.password){ res.status("400"); res.send("Invalid details!"); } else { Users.filter(function(user){ if(user.id === req.body.id){ res.render('signup', { message: "User Already Exists! Login or choose another user id"}); } }); var newUser = {id: req.body.id, password: req.body.password}; Users.push(newUser); req.session.user = newUser; res.redirect('/protected_page'); } }); function checkSignIn(req, res){ if(req.session.user){ next(); //If session exists, proceed to page } else { var err = new Error("Not logged in!"); console.log(req.session.user); next(err); //Error, trying to access unauthorized page! } } app.get('/protected_page', checkSignIn, function(req, res){ res.render('protected_page', {id: req.session.user.id}) }); app.get('/login', function(req, res){ res.render('login'); }); app.post('/login', function(req, res){ console.log(Users); if(!req.body.id || !req.body.password){ res.render('login', {message: "Please enter both id and password"}); } else { Users.filter(function(user){ if(user.id === req.body.id && user.password === req.body.password){ req.session.user = user; res.redirect('/protected_page'); } }); res.render('login', {message: "Invalid credentials!"}); } }); app.get('/logout', function(req, res){ req.session.destroy(function(){ console.log("user logged out.") }); res.redirect('/login'); }); app.use('/protected_page', function(err, req, res, next){ console.log(err); //User should be authenticated! Redirect him to log in. res.redirect('/login'); }); app.listen(3000); We have created a middleware function checkSignIn to check if the user is signed in. The protected_page uses this function. To log the user out, we destroy the session. Let us now create the login page. Name the view as login.pug and enter the contents − html head title Signup body if(message) h4 #{message} form(action = "/login" method = "POST") input(name = "id" type = "text" required placeholder = "User ID") input(name = "password" type = "password" required placeholder = "Password") button(type = "Submit") Log in Our simple authentication application is now complete; let us now test the application. Run the app using nodemon index.js, and proceed to localhost:3000/signup. Enter a Username and a password and click sign up. You will be redirected to the protected_page if details are valid/unique − Now log out of the app. This will redirect us to the login page − This route is protected such that if an unauthenticated person tries to visit it, he will be edirected to our login page. This was all about basic user authentication. It is always recommended that we use a persistent session system and use hashes for password transport. There are much better ways to authenticate users now, leveraging JSON tokens. An API is always needed to create mobile applications, single page applications, use AJAX calls and provide data to clients. An popular architectural style of how to structure and name these APIs and the endpoints is called REST(Representational Transfer State). HTTP 1.1 was designed keeping REST principles in mind. REST was introduced by Roy Fielding in 2000 in his Paper Fielding Dissertations. RESTful URIs and methods provide us with almost all information we need to process a request. The table given below summarizes how the various verbs should be used and how URIs should be named. We will be creating a movies API towards the end; let us now discuss how it will be structured. Let us now create this API in Express. We will be using JSON as our transport data format as it is easy to work with in JavaScript and has other benefits. Replace your index.js file with the movies.js file as in the following program. var express = require('express'); var bodyParser = require('body-parser'); var multer = require('multer'); var upload = multer(); var app = express(); app.use(cookieParser()); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); app.use(upload.array()); //Require the Router we defined in movies.js var movies = require('./movies.js'); //Use the Router on the sub route /movies app.use('/movies', movies); app.listen(3000); Now that we have our application set up, let us concentrate on creating the API. Start by setting up the movies.js file. We are not using a database to store the movies but are storing them in memory; so every time the server restarts, the movies added by us will vanish. This can easily be mimicked using a database or a file (using node fs module). Once you import Express then, create a Router and export it using module.exports − var express = require('express'); var router = express.Router(); var movies = [ {id: 101, name: "Fight Club", year: 1999, rating: 8.1}, {id: 102, name: "Inception", year: 2010, rating: 8.7}, {id: 103, name: "The Dark Knight", year: 2008, rating: 9}, {id: 104, name: "12 Angry Men", year: 1957, rating: 8.9} ]; //Routes will go here module.exports = router; Let us define the GET route for getting all the movies − router.get('/', function(req, res){ res.json(movies); }); To test out if this is working fine, run your app, then open your terminal and enter − curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X GET localhost:3000/movies The following response will be displayed − [{"id":101,"name":"Fight Club","year":1999,"rating":8.1}, {"id":102,"name":"Inception","year":2010,"rating":8.7}, {"id":103,"name":"The Dark Knight","year":2008,"rating":9}, {"id":104,"name":"12 Angry Men","year":1957,"rating":8.9}] We have a route to get all the movies. Let us now create a route to get a specific movie by its id. router.get('/:id([0-9]{3,})', function(req, res){ var currMovie = movies.filter(function(movie){ if(movie.id == req.params.id){ return true; } }); if(currMovie.length == 1){ res.json(currMovie[0]) } else { res.status(404);//Set status to 404 as movie was not found res.json({message: "Not Found"}); } }); This will get us the movies according to the id that we provided. To check the output, use the following command in your terminal − curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X GET localhost:3000/movies/101 You'll get the following response − {"id":101,"name":"Fight Club","year":1999,"rating":8.1} If you visit an invalid route, it will produce a cannot GET error while if you visit a valid route with an id that doesn’t exist, it will produce a 404 error. We are done with the GET routes, let us now move on to the POST route. Use the following route to handle the POSTed data − router.post('/', function(req, res){ //Check if all fields are provided and are valid: if(!req.body.name || !req.body.year.toString().match(/^[0-9]{4}$/g) || !req.body.rating.toString().match(/^[0-9]\.[0-9]$/g)){ res.status(400); res.json({message: "Bad Request"}); } else { var newId = movies[movies.length-1].id+1; movies.push({ id: newId, name: req.body.name, year: req.body.year, rating: req.body.rating }); res.json({message: "New movie created.", location: "/movies/" + newId}); } }); This will create a new movie and store it in the movies variable. To check this route, enter the following code in your terminal − curl -X POST --data "name = Toy%20story&year = 1995&rating = 8.5" http://localhost:3000/movies The following response will be displayed − {"message":"New movie created.","location":"/movies/105"} To test if this was added to the movies object, Run the get request for /movies/105 again. The following response will be displayed − {"id":105,"name":"Toy story","year":"1995","rating":"8.5"} Let us move on to create the PUT and DELETE routes. The PUT route is almost the same as the POST route. We will be specifying the id for the object that'll be updated/created. Create the route in the following way. router.put('/:id', function(req, res){ //Check if all fields are provided and are valid: if(!req.body.name || !req.body.year.toString().match(/^[0-9]{4}$/g) || !req.body.rating.toString().match(/^[0-9]\.[0-9]$/g) || !req.params.id.toString().match(/^[0-9]{3,}$/g)){ res.status(400); res.json({message: "Bad Request"}); } else { //Gets us the index of movie with given id. var updateIndex = movies.map(function(movie){ return movie.id; }).indexOf(parseInt(req.params.id)); if(updateIndex === -1){ //Movie not found, create new movies.push({ id: req.params.id, name: req.body.name, year: req.body.year, rating: req.body.rating }); res.json({message: "New movie created.", location: "/movies/" + req.params.id}); } else { //Update existing movie movies[updateIndex] = { id: req.params.id, name: req.body.name, year: req.body.year, rating: req.body.rating }; res.json({message: "Movie id " + req.params.id + " updated.", location: "/movies/" + req.params.id}); } } }); This route will perform the function specified in the above table. It will update the object with new details if it exists. If it doesn't exist, it will create a new object. To check the route, use the following curl command. This will update an existing movie. To create a new Movie, just change the id to a non-existing id. curl -X PUT --data "name = Toy%20story&year = 1995&rating = 8.5" http://localhost:3000/movies/101 Response {"message":"Movie id 101 updated.","location":"/movies/101"} Use the following code to create a delete route. − router.delete('/:id', function(req, res){ var removeIndex = movies.map(function(movie){ return movie.id; }).indexOf(req.params.id); //Gets us the index of movie with given id. if(removeIndex === -1){ res.json({message: "Not found"}); } else { movies.splice(removeIndex, 1); res.send({message: "Movie id " + req.params.id + " removed."}); } }); Check the route in the same way as we checked the other routes. On successful deletion(for example id 105), you will get the following output − {message: "Movie id 105 removed."} Finally, our movies.js file will look like the following. var express = require('express'); var router = express.Router(); var movies = [ {id: 101, name: "Fight Club", year: 1999, rating: 8.1}, {id: 102, name: "Inception", year: 2010, rating: 8.7}, {id: 103, name: "The Dark Knight", year: 2008, rating: 9}, {id: 104, name: "12 Angry Men", year: 1957, rating: 8.9} ]; router.get('/:id([0-9]{3,})', function(req, res){ var currMovie = movies.filter(function(movie){ if(movie.id == req.params.id){ return true; } }); if(currMovie.length == 1){ res.json(currMovie[0]) } else { res.status(404); //Set status to 404 as movie was not found res.json({message: "Not Found"}); } }); router.post('/', function(req, res){ //Check if all fields are provided and are valid: if(!req.body.name || !req.body.year.toString().match(/^[0-9]{4}$/g) || !req.body.rating.toString().match(/^[0-9]\.[0-9]$/g)){ res.status(400); res.json({message: "Bad Request"}); } else { var newId = movies[movies.length-1].id+1; movies.push({ id: newId, name: req.body.name, year: req.body.year, rating: req.body.rating }); res.json({message: "New movie created.", location: "/movies/" + newId}); } }); router.put('/:id', function(req, res) { //Check if all fields are provided and are valid: if(!req.body.name || !req.body.year.toString().match(/^[0-9]{4}$/g) || !req.body.rating.toString().match(/^[0-9]\.[0-9]$/g) || !req.params.id.toString().match(/^[0-9]{3,}$/g)){ res.status(400); res.json({message: "Bad Request"}); } else { //Gets us the index of movie with given id. var updateIndex = movies.map(function(movie){ return movie.id; }).indexOf(parseInt(req.params.id)); if(updateIndex === -1){ //Movie not found, create new movies.push({ id: req.params.id, name: req.body.name, year: req.body.year, rating: req.body.rating }); res.json({ message: "New movie created.", location: "/movies/" + req.params.id}); } else { //Update existing movie movies[updateIndex] = { id: req.params.id, name: req.body.name, year: req.body.year, rating: req.body.rating }; res.json({message: "Movie id " + req.params.id + " updated.", location: "/movies/" + req.params.id}); } } }); router.delete('/:id', function(req, res){ var removeIndex = movies.map(function(movie){ return movie.id; }).indexOf(req.params.id); //Gets us the index of movie with given id. if(removeIndex === -1){ res.json({message: "Not found"}); } else { movies.splice(removeIndex, 1); res.send({message: "Movie id " + req.params.id + " removed."}); } }); module.exports = router; This completes our REST API. Now you can create much more complex applications using this simple architectural style and Express. Scaffolding allows us to easily create a skeleton for a web application. We manually create our public directory, add middleware, create separate route files, etc. A scaffolding tool sets up all these things for us so that we can directly get started with building our application. The scaffolder we will use is called Yeoman. It is a scaffolding tool built for Node.js but also has generators for several other frameworks (like flask, rails, django, etc.). To install Yeoman, enter the following command in your terminal − npm install -g yeoman Yeoman uses generators to scaffold out applications. To check out the generators available on npm to use with Yeoman, you can click on this link. In this tutorial, we will use the 'generator-Express-simple'. To install this generator, enter the following command in your terminal − npm install -g generator-express-simple To use this generator, enter the following command − yo express-simple test-app You will be asked a few simple questions like what things you want to use with your app. Select the following answers, or if you already know about these technologies then go about choosing how you want them to be. express-simple comes with bootstrap and jquery [?] Select the express version you want: 4.x [?] Do you want an mvc express app: Yes [?] Select the css preprocessor you would like to use: sass [?] Select view engine you would like to use: jade [?] Select the build tool you want to use for this project: gulp [?] Select the build tool you want to use for this project: gulp [?] Select the language you want to use for the build tool: javascript create public/sass/styles.scss create public/js/main.js create views/layout.jade create views/index.jade create views/404.jade create app.js create config.js create routes/index.js create package.json create bower.json identical .bowerrc identical .editorconfig identical .gitignore identical .jshintrc create gulpfile.js I'm all done. Running bower install & npm install for you to install the required dependencies. If this fails, try running the command yourself. It will then create a new application for you, install all the dependencies, add few pages to your application(home page, 404 not found page, etc.) and give you a directory structure to work on. This generator creates a very simple structure for us. Explore the many generators available for Express and choose the one that fits you right. Steps to working with all generators is the same. You will need to install a generator, run it using Yeoman; it will ask you some questions and then create a skeleton for your application based on your answers. Error handling in Express is done using middleware. But this middleware has special properties. The error handling middleware are defined in the same way as other middleware functions, except that error-handling functions MUST have four arguments instead of three – err, req, res, next. For example, to send a response on any error, we can use − app.use(function(err, req, res, next) { console.error(err.stack); res.status(500).send('Something broke!'); }); Till now we were handling errors in the routes itself. The error handling middleware allows us to separate our error logic and send responses accordingly. The next() method we discussed in middleware takes us to next middleware/route handler. For error handling, we have the next(err) function. A call to this function skips all middleware and matches us to the next error handler for that route. Let us understand this through an example. var express = require('express'); var app = express(); app.get('/', function(req, res){ //Create an error and pass it to the next function var err = new Error("Something went wrong"); next(err); }); /* * other route handlers and middleware here * .... */ //An error handling middleware app.use(function(err, req, res, next) { res.status(500); res.send("Oops, something went wrong.") }); app.listen(3000); This error handling middleware can be strategically placed after routes or contain conditions to detect error types and respond to the clients accordingly. The above program will display the following output. Express uses the Debug module to internally log information about route matching, middleware functions, application mode, etc. To see all internal logs used in Express, set the DEBUG environment variable to Express:* when starting the app − DEBUG = express:* node index.js The following output will be displayed. These logs are very helpful when a component of your app is not functioning right. This verbose output might be a little overwhelming. You can also restrict the DEBUG variable to specific area to be logged. For example, if you wish to restrict the logger to application and router, you can use the following code. DEBUG = express:application,express:router node index.js Debug is turned off by default and is automatically turned on in production environment. Debug can also be extended to meet your needs, you can read more about it at its npm page. Unlike Django and Rails which have a defined way of doing things, file structure, etc., Express does not follow a defined way. This means you can structure the application the way you like. But as your application grows in size, it is very difficult to maintain it if it doesn't have a well-defined structure. In this chapter, we will look at the generally used directory structures and separation of concerns to build our applications. First, we will discuss the best practices for creating node and Express applications. Always begin a node project using npm init. Always begin a node project using npm init. Always install dependencies with a --save or --save-dev. This will ensure that if you move to a different platform, you can just run npm install to install all dependencies. Always install dependencies with a --save or --save-dev. This will ensure that if you move to a different platform, you can just run npm install to install all dependencies. Stick with lowercase file names and camelCase variables. If you look at any npm module, its named in lowercase and separated with dashes. Whenever you require these modules, use camelCase. Stick with lowercase file names and camelCase variables. If you look at any npm module, its named in lowercase and separated with dashes. Whenever you require these modules, use camelCase. Don’t push node_modules to your repositories. Instead npm installs everything on development machines. Don’t push node_modules to your repositories. Instead npm installs everything on development machines. Use a config file to store variables Use a config file to store variables Group and isolate routes to their own file. For example, take the CRUD operations in the movies example we saw in the REST API page. Group and isolate routes to their own file. For example, take the CRUD operations in the movies example we saw in the REST API page. Let us now discuss the Express’ Directory Structure. Express does not have a community defined structure for creating applications. The following is a majorly used project structure for a website. test-project/ node_modules/ config/ db.js //Database connection and configuration credentials.js //Passwords/API keys for external services used by your app config.js //Other environment variables models/ //For mongoose schemas users.js things.js routes/ //All routes for different entities in different files users.js things.js views/ index.pug 404.pug ... public/ //All static content being served images/ css/ javascript/ app.js routes.js //Require all routes in this and then require this file in app.js package.json There are other approaches to build websites with Express as well. You can build a website using the MVC design pattern. For more information, you can visit the following links. https://code.tutsplus.com/tutorials/build-a-complete-mvc-website-with-expressjs--net-34168 and, https://www.terlici.com/2014/08/25/best-practices-express-structure.html. APIs are simpler to design; they don't need a public or a views directory. Use the following structure to build APIs − test-project/ node_modules/ config/ db.js //Database connection and configuration credentials.js //Passwords/API keys for external services used by your app models/ //For mongoose schemas users.js things.js routes/ //All routes for different entities in different files users.js things.js app.js routes.js //Require all routes in this and then require this file in app.js package.json You can also use a yeoman generator to get a similar structure. This chapter lists down the various resources we used for this tutorial. The most important link is of course the Express API docs − https://expressjs.com/en/4x/api.html The most important link is of course the Express API docs − https://expressjs.com/en/4x/api.html The guides provided on the Express website on different aspects are also quite helpful − Routing Middleware Error Handling Debugging The guides provided on the Express website on different aspects are also quite helpful − Routing Routing Middleware Middleware Error Handling Error Handling Debugging Debugging A list of useful books and blogs on Express is available at https://expressjs.com/en/resources/books-blogs.html A list of useful books and blogs on Express is available at https://expressjs.com/en/resources/books-blogs.html A list of mostly used middleware with Express is available at https://expressjs.com/en/resources/middleware.html A list of mostly used middleware with Express is available at https://expressjs.com/en/resources/middleware.html These blogs with Express tips and tricks may prove helpful − https://derickbailey.com/categories/tips-and-tricks/ https://scotch.io/tutorials/learn-to-use-the-new-router-in+-expressjs-4 These blogs with Express tips and tricks may prove helpful − https://derickbailey.com/categories/tips-and-tricks/ https://derickbailey.com/categories/tips-and-tricks/ https://scotch.io/tutorials/learn-to-use-the-new-router-in+-expressjs-4 https://scotch.io/tutorials/learn-to-use-the-new-router-in+-expressjs-4 Application structure − https://www.terlici.com/2014/08/25/best-practices-express-structure.html Application structure − https://www.terlici.com/2014/08/25/best-practices-express-structure.html RESTful APIs − https://www.thepolyglotdeveloper.com/2015/10/create-a-simple-restful-api-with-node-js/ https://scotch.io/tutorials/build-a-restful-api-using-node-and-express-4 https://devcenter.heroku.com/articles/mean-apps-restful-api https://pixelhandler.com/posts/develop-a-restful-api-using-nodejs-with-express-and-mongoose http://cwbuecheler.com/web/tutorials/2014/restful-web-app-node-express-mongodb/ RESTful APIs − https://www.thepolyglotdeveloper.com/2015/10/create-a-simple-restful-api-with-node-js/ https://www.thepolyglotdeveloper.com/2015/10/create-a-simple-restful-api-with-node-js/ https://scotch.io/tutorials/build-a-restful-api-using-node-and-express-4 https://scotch.io/tutorials/build-a-restful-api-using-node-and-express-4 https://devcenter.heroku.com/articles/mean-apps-restful-api https://devcenter.heroku.com/articles/mean-apps-restful-api https://pixelhandler.com/posts/develop-a-restful-api-using-nodejs-with-express-and-mongoose https://pixelhandler.com/posts/develop-a-restful-api-using-nodejs-with-express-and-mongoose http://cwbuecheler.com/web/tutorials/2014/restful-web-app-node-express-mongodb/ http://cwbuecheler.com/web/tutorials/2014/restful-web-app-node-express-mongodb/ For advanced authentication, use PassportJS − http://passportjs.org For advanced authentication, use PassportJS − http://passportjs.org 16 Lectures 1 hours Anadi Sharma Print Add Notes Bookmark this page
[ { "code": null, "e": 2259, "s": 2061, "text": "ExpressJS is a web application framework that provides you with a simple API to build websites, web apps and back ends. With ExpressJS, you need not worry about low level protocols, processes, etc." }, { "code": null, "e": 2491, "s": 2259, "text": "Express provides a minimal interface to build our applications. It provides us the tools that are required to build our app. It is flexible as there are numerous modules available on npm, which can be directly plugged into Express." }, { "code": null, "e": 2614, "s": 2491, "text": "Express was developed by TJ Holowaychuk and is maintained by the Node.js foundation and numerous open source contributors." }, { "code": null, "e": 2794, "s": 2614, "text": "Unlike its competitors like Rails and Django, which have an opinionated way of building applications, Express has no \"best way\" to do something. It is very flexible and pluggable." }, { "code": null, "e": 2875, "s": 2794, "text": "Pug (earlier known as Jade) is a terse language for writing HTML templates. It −" }, { "code": null, "e": 2889, "s": 2875, "text": "Produces HTML" }, { "code": null, "e": 2911, "s": 2889, "text": "Supports dynamic code" }, { "code": null, "e": 2938, "s": 2911, "text": "Supports reusability (DRY)" }, { "code": null, "e": 3005, "s": 2938, "text": "It is one of the most popular template language used with Express." }, { "code": null, "e": 3138, "s": 3005, "text": "MongoDB is an open-source, document database designed for ease of development and scaling. This database is also used to store data." }, { "code": null, "e": 3248, "s": 3138, "text": "Mongoose is a client API for node.js which makes it easy to access our database from our Express application." }, { "code": null, "e": 3606, "s": 3248, "text": "In this chapter, we will learn how to start developing and using the Express Framework. To start with, you should have the Node and the npm (node package manager) installed. If you don’t already have these, go to the Node setup to install node on your local system. Confirm that node and npm are installed by running the following commands in your terminal." }, { "code": null, "e": 3636, "s": 3606, "text": "node --version\nnpm --version\n" }, { "code": null, "e": 3687, "s": 3636, "text": "You should get an output similar to the following." }, { "code": null, "e": 3701, "s": 3687, "text": "v5.0.0\n3.5.2\n" }, { "code": null, "e": 3788, "s": 3701, "text": "Now that we have Node and npm set up, let us understand what npm is and how to use it." }, { "code": null, "e": 4155, "s": 3788, "text": "npm is the package manager for node. The npm Registry is a public collection of packages of open-source code for Node.js, front-end web apps, mobile apps, robots, routers, and countless other needs of the JavaScript community. npm allows us to access all these packages and install them locally. You can browse through the list of packages available on npm at npmJS." }, { "code": null, "e": 4228, "s": 4155, "text": "There are two ways to install a package using npm: globally and locally." }, { "code": null, "e": 4377, "s": 4228, "text": "Globally − This method is generally used to install development tools and CLI based packages. To install a package globally, use the following code." }, { "code": null, "e": 4526, "s": 4377, "text": "Globally − This method is generally used to install development tools and CLI based packages. To install a package globally, use the following code." }, { "code": null, "e": 4557, "s": 4526, "text": "npm install -g <package-name>\n" }, { "code": null, "e": 4798, "s": 4557, "text": "Locally − This method is generally used to install frameworks and libraries. A locally installed package can be used only within the directory it is installed. To install a package locally, use the same command as above without the -g flag." }, { "code": null, "e": 5039, "s": 4798, "text": "Locally − This method is generally used to install frameworks and libraries. A locally installed package can be used only within the directory it is installed. To install a package locally, use the same command as above without the -g flag." }, { "code": null, "e": 5067, "s": 5039, "text": "npm install <package-name>\n" }, { "code": null, "e": 5277, "s": 5067, "text": "Whenever we create a project using npm, we need to provide a package.json file, which has all the details about our project. npm makes it easy for us to set up this file. Let us set up our development project." }, { "code": null, "e": 5385, "s": 5277, "text": "Step 1 − Start your terminal/cmd, create a new folder named hello-world and cd (create directory) into it −" }, { "code": null, "e": 5465, "s": 5385, "text": "Step 2 − Now to create the package.json file using npm, use the following code." }, { "code": null, "e": 5475, "s": 5465, "text": "npm init\n" }, { "code": null, "e": 5522, "s": 5475, "text": "It will ask you for the following information." }, { "code": null, "e": 5596, "s": 5522, "text": "Just keep pressing enter, and enter your name at the “author name” field." }, { "code": null, "e": 5764, "s": 5596, "text": "Step 3 − Now we have our package.json file set up, we will further install Express. To install Express and add it to our package.json file, use the following command −" }, { "code": null, "e": 5792, "s": 5764, "text": "npm install --save express\n" }, { "code": null, "e": 5865, "s": 5792, "text": "To confirm that Express has installed correctly, run the following code." }, { "code": null, "e": 5914, "s": 5865, "text": "ls node_modules #(dir node_modules for windows)\n" }, { "code": null, "e": 6254, "s": 5914, "text": "Tip − The --save flag can be replaced by the -S flag. This flag ensures that Express is added as a dependency to our package.json file. This has an advantage, the next time we need to install all the dependencies of our project we can just run the command npm install and it will find the dependencies in this file and install them for us." }, { "code": null, "e": 6618, "s": 6254, "text": "This is all we need to start development using the Express framework. To make our development process a lot easier, we will install a tool from npm, nodemon. This tool restarts our server as soon as we make a change in any of our files, otherwise we need to restart the server manually after each file modification. To install nodemon, use the following command −" }, { "code": null, "e": 6642, "s": 6618, "text": "npm install -g nodemon\n" }, { "code": null, "e": 6680, "s": 6642, "text": "You can now start working on Express." }, { "code": null, "e": 6840, "s": 6680, "text": "We have set up the development, now it is time to start developing our first app using Express. Create a new file called index.js and type the following in it." }, { "code": null, "e": 6981, "s": 6840, "text": "var express = require('express');\nvar app = express();\n\napp.get('/', function(req, res){\n res.send(\"Hello world!\");\n});\n\napp.listen(3000);" }, { "code": null, "e": 7040, "s": 6981, "text": "Save the file, go to your terminal and type the following." }, { "code": null, "e": 7058, "s": 7040, "text": "nodemon index.js\n" }, { "code": null, "e": 7218, "s": 7058, "text": "This will start the server. To test this app, open your browser and go to http://localhost:3000 and a message will be displayed as in the following screenshot." }, { "code": null, "e": 7374, "s": 7218, "text": "The first line imports Express in our file, we have access to it through the variable Express. We use it to create an application and assign it to var app." }, { "code": null, "e": 7785, "s": 7374, "text": "This function tells what to do when a get request at the given route is called. The callback function has 2 parameters, request(req) and response(res). The request object(req) represents the HTTP request and has properties for the request query string, parameters, body, HTTP headers, etc. Similarly, the response object represents the HTTP response that the Express app sends when it receives an HTTP request." }, { "code": null, "e": 7915, "s": 7785, "text": "This function takes an object as input and it sends this to the requesting client. Here we are sending the string \"Hello World!\"." }, { "code": null, "e": 8037, "s": 7915, "text": "This function binds and listens for connections on the specified host and port. Port is the only required parameter here." }, { "code": null, "e": 8042, "s": 8037, "text": "port" }, { "code": null, "e": 8109, "s": 8042, "text": "A port number on which the server should accept incoming requests." }, { "code": null, "e": 8114, "s": 8109, "text": "host" }, { "code": null, "e": 8193, "s": 8114, "text": "Name of the domain. You need to set it when you deploy your apps to the cloud." }, { "code": null, "e": 8201, "s": 8193, "text": "backlog" }, { "code": null, "e": 8271, "s": 8201, "text": "The maximum number of queued pending connections. The default is 511." }, { "code": null, "e": 8280, "s": 8271, "text": "callback" }, { "code": null, "e": 8367, "s": 8280, "text": "An asynchronous function that is called when the server starts listening for requests." }, { "code": null, "e": 8463, "s": 8367, "text": "Web frameworks provide resources such as HTML pages, scripts, images, etc. at different routes." }, { "code": null, "e": 8539, "s": 8463, "text": "The following function is used to define routes in an Express application −" }, { "code": null, "e": 8701, "s": 8539, "text": "This METHOD can be applied to any one of the HTTP verbs – get, set, put, delete. An alternate method also exists, which executes independent of the request type." }, { "code": null, "e": 8750, "s": 8701, "text": "Path is the route at which the request will run." }, { "code": null, "e": 8869, "s": 8750, "text": "Handler is a callback function that executes when a matching request type is found on the relevant route. For example," }, { "code": null, "e": 9015, "s": 8869, "text": "var express = require('express');\nvar app = express();\n\napp.get('/hello', function(req, res){\n res.send(\"Hello World!\");\n});\n\napp.listen(3000);" }, { "code": null, "e": 9238, "s": 9015, "text": "If we run our application and go to localhost:3000/hello, the server receives a get request at route \"/hello\", our Express app executes the callback function attached to this route and sends \"Hello World!\" as the response." }, { "code": null, "e": 9314, "s": 9238, "text": "We can also have multiple different methods at the same route. For example," }, { "code": null, "e": 9567, "s": 9314, "text": "var express = require('express');\nvar app = express();\n\napp.get('/hello', function(req, res){\n res.send(\"Hello World!\");\n});\n\napp.post('/hello', function(req, res){\n res.send(\"You just called the post method at '/hello'!\\n\");\n});\n\napp.listen(3000);" }, { "code": null, "e": 9659, "s": 9567, "text": "To test this request, open up your terminal and use cURL to execute the following request −" }, { "code": null, "e": 9703, "s": 9659, "text": "curl -X POST \"http://localhost:3000/hello\"\n" }, { "code": null, "e": 9871, "s": 9703, "text": "A special method, all, is provided by Express to handle all types of http methods at a particular route using the same function. To use this method, try the following." }, { "code": null, "e": 9979, "s": 9871, "text": "app.all('/test', function(req, res){\n res.send(\"HTTP method doesn't have any effect on this route!\");\n});" }, { "code": null, "e": 10081, "s": 9979, "text": "This method is generally used for defining middleware, which we'll discuss in the middleware chapter." }, { "code": null, "e": 10282, "s": 10081, "text": "Defining routes like above is very tedious to maintain. To separate the routes from our main index.js file, we will use Express.Router. Create a new file called things.js and type the following in it." }, { "code": null, "e": 10574, "s": 10282, "text": "var express = require('express');\nvar router = express.Router();\n\nrouter.get('/', function(req, res){\n res.send('GET route on things.');\n});\nrouter.post('/', function(req, res){\n res.send('POST route on things.');\n});\n\n//export this router to use in our index.js\nmodule.exports = router;" }, { "code": null, "e": 10673, "s": 10574, "text": "Now to use this router in our index.js, type in the following before the app.listen function call." }, { "code": null, "e": 10872, "s": 10673, "text": "var express = require('Express');\nvar app = express();\n\nvar things = require('./things.js');\n\n//both index.js and things.js should be in same directory\napp.use('/things', things);\n\napp.listen(3000);" }, { "code": null, "e": 11187, "s": 10872, "text": "The app.use function call on route '/things' attaches the things router with this route. Now whatever requests our app gets at the '/things', will be handled by our things.js router. The '/' route in things.js is actually a subroute of '/things'. Visit localhost:3000/things/ and you will see the following output." }, { "code": null, "e": 11455, "s": 11187, "text": "Routers are very helpful in separating concerns and keep relevant portions of our code together. They help in building maintainable code. You should define your routes relating to an entity in a single file and include it using the above method in your index.js file." }, { "code": null, "e": 11612, "s": 11455, "text": "The HTTP method is supplied in the request and specifies the operation that the client has requested. The following table lists the most used HTTP methods −" }, { "code": null, "e": 11616, "s": 11612, "text": "GET" }, { "code": null, "e": 11762, "s": 11616, "text": "The GET method requests a representation of the specified resource. Requests using GET should only retrieve data and should have no other effect." }, { "code": null, "e": 11767, "s": 11762, "text": "POST" }, { "code": null, "e": 11910, "s": 11767, "text": "The POST method requests that the server accept the data enclosed in the request as a new object/entity of the resource identified by the URI." }, { "code": null, "e": 11914, "s": 11910, "text": "PUT" }, { "code": null, "e": 12114, "s": 11914, "text": "The PUT method requests that the server accept the data enclosed in the request as a modification to existing object identified by the URI. If it does not exist then the PUT method should create one." }, { "code": null, "e": 12121, "s": 12114, "text": "DELETE" }, { "code": null, "e": 12195, "s": 12121, "text": "The DELETE method requests that the server delete the specified resource." }, { "code": null, "e": 12327, "s": 12195, "text": "These are the most common HTTP methods. To learn more about the methods, visit http://www.tutorialspoint.com/http/http_methods.htm." }, { "code": null, "e": 12533, "s": 12327, "text": "We can now define routes, but those are static or fixed. To use the dynamic routes, we SHOULD provide different types of routes. Using dynamic routes allows us to pass parameters and process based on them." }, { "code": null, "e": 12573, "s": 12533, "text": "Here is an example of a dynamic route −" }, { "code": null, "e": 12744, "s": 12573, "text": "var express = require('express');\nvar app = express();\n\napp.get('/:id', function(req, res){\n res.send('The id you specified is ' + req.params.id);\n});\napp.listen(3000);" }, { "code": null, "e": 12832, "s": 12744, "text": "To test this go to http://localhost:3000/123. The following response will be displayed." }, { "code": null, "e": 12970, "s": 12832, "text": "You can replace '123' in the URL with anything else and the change will reflect in the response. A more complex example of the above is −" }, { "code": null, "e": 13169, "s": 12970, "text": "var express = require('express');\nvar app = express();\n\napp.get('/things/:name/:id', function(req, res) {\n res.send('id: ' + req.params.id + ' and name: ' + req.params.name);\n});\napp.listen(3000);" }, { "code": null, "e": 13250, "s": 13169, "text": "To test the above code, go to http://localhost:3000/things/tutorialspoint/12345." }, { "code": null, "e": 13497, "s": 13250, "text": "You can use the req.params object to access all the parameters you pass in the url. Note that the above 2 are different paths. They will never overlap. Also if you want to execute code when you get '/things' then you need to define it separately." }, { "code": null, "e": 13660, "s": 13497, "text": "You can also use regex to restrict URL parameter matching. Let us assume you need the id to be a 5-digit long number. You can use the following route definition −" }, { "code": null, "e": 13829, "s": 13660, "text": "var express = require('express');\nvar app = express();\n\napp.get('/things/:id([0-9]{5})', function(req, res){\n res.send('id: ' + req.params.id);\n});\n\napp.listen(3000);" }, { "code": null, "e": 14151, "s": 13829, "text": "Note that this will only match the requests that have a 5-digit long id. You can use more complex regexes to match/validate your routes. If none of your routes match the request, you'll get a \"Cannot GET <your-request-route>\" message as response. This message be replaced by a 404 not found page using this simple route −" }, { "code": null, "e": 14329, "s": 14151, "text": "var express = require('express');\nvar app = express();\n\n//Other routes here\napp.get('*', function(req, res){\n res.send('Sorry, this is an invalid URL.');\n});\napp.listen(3000);" }, { "code": null, "e": 14497, "s": 14329, "text": "Important − This should be placed after all your routes, as Express matches routes from start to end of the index.js file, including the external routers you required." }, { "code": null, "e": 14618, "s": 14497, "text": "For example, if we define the same routes as above, on requesting with a valid URL, the following output is displayed. −" }, { "code": null, "e": 14689, "s": 14618, "text": "While for an incorrect URL request, the following output is displayed." }, { "code": null, "e": 14999, "s": 14689, "text": "Middleware functions are functions that have access to the request object (req), the response object (res), and the next middleware function in the application’s request-response cycle. These functions are used to modify req and res objects for tasks like parsing request bodies, adding response headers, etc." }, { "code": null, "e": 15061, "s": 14999, "text": "Here is a simple example of a middleware function in action −" }, { "code": null, "e": 15448, "s": 15061, "text": "var express = require('express');\nvar app = express();\n\n//Simple request time logger\napp.use(function(req, res, next){\n console.log(\"A new request received at \" + Date.now());\n \n //This function call is very important. It tells that more processing is\n //required for the current request and is in the next middleware\n function route handler.\n next();\n});\n\napp.listen(3000);" }, { "code": null, "e": 15587, "s": 15448, "text": "The above middleware is called for every request on the server. So after every request, we will get the following message in the console −" }, { "code": null, "e": 15628, "s": 15587, "text": "A new request received at 1467267512545\n" }, { "code": null, "e": 15756, "s": 15628, "text": "To restrict it to a specific route (and all its subroutes), provide that route as the first argument of app.use(). For Example," }, { "code": null, "e": 16111, "s": 15756, "text": "var express = require('express');\nvar app = express();\n\n//Middleware function to log request protocol\napp.use('/things', function(req, res, next){\n console.log(\"A request for things received at \" + Date.now());\n next();\n});\n\n// Route handler that sends the response\napp.get('/things', function(req, res){\n res.send('Things');\n});\n\napp.listen(3000);" }, { "code": null, "e": 16195, "s": 16111, "text": "Now whenever you request any subroute of '/things', only then it will log the time." }, { "code": null, "e": 16414, "s": 16195, "text": "One of the most important things about middleware in Express is the order in which they are written/included in your file; the order in which they are executed, given that the route matches also needs to be considered." }, { "code": null, "e": 16682, "s": 16414, "text": "For example, in the following code snippet, the first function executes first, then the route handler and then the end function. This example summarizes how to use middleware before and after route handler; also how a route handler can be used as a middleware itself." }, { "code": null, "e": 17029, "s": 16682, "text": "var express = require('express');\nvar app = express();\n\n//First middleware before response is sent\napp.use(function(req, res, next){\n console.log(\"Start\");\n next();\n});\n\n//Route handler\napp.get('/', function(req, res, next){\n res.send(\"Middle\");\n next();\n});\n\napp.use('/', function(req, res){\n console.log('End');\n});\n\napp.listen(3000);" }, { "code": null, "e": 17127, "s": 17029, "text": "When we visit '/' after running this code, we receive the response as Middle and on our console −" }, { "code": null, "e": 17138, "s": 17127, "text": "Start\nEnd\n" }, { "code": null, "e": 17210, "s": 17138, "text": "The following diagram summarizes what we have learnt about middleware −" }, { "code": null, "e": 17345, "s": 17210, "text": "Now that we have covered how to create our own middleware, let us discuss some of the most commonly used community created middleware." }, { "code": null, "e": 17510, "s": 17345, "text": "A list of Third party middleware for Express is available here. Following are some of the most commonly used middleware; we will also learn how to use/mount these −" }, { "code": null, "e": 17736, "s": 17510, "text": "This is used to parse the body of requests which have payloads attached to them. To mount body parser, we need to install it using npm install --save body-parser and to mount it, include the following lines in your index.js −" }, { "code": null, "e": 17907, "s": 17736, "text": "var bodyParser = require('body-parser');\n\n//To parse URL encoded data\napp.use(bodyParser.urlencoded({ extended: false }))\n\n//To parse json data\napp.use(bodyParser.json())" }, { "code": null, "e": 17977, "s": 17907, "text": "To view all available options for body-parser, visit its github page." }, { "code": null, "e": 18213, "s": 17977, "text": "It parses Cookie header and populate req.cookies with an object keyed by cookie names. To mount cookie parser, we need to install it using npm install --save cookie-parser and to mount it, include the following lines in your index.js −" }, { "code": null, "e": 18282, "s": 18213, "text": "var cookieParser = require('cookie-parser');\napp.use(cookieParser())" }, { "code": null, "e": 18389, "s": 18282, "text": "It creates a session middleware with the given options. We will discuss its usage in the Sessions section." }, { "code": null, "e": 18504, "s": 18389, "text": "We have many other third party middleware in ExpressJS. However, we have discussed only a few important ones here." }, { "code": null, "e": 18862, "s": 18504, "text": "Pug is a templating engine for Express. Templating engines are used to remove the cluttering of our server code with HTML, concatenating strings wildly to existing HTML templates. Pug is a very powerful templating engine which has a variety of features including filters, includes, inheritance, interpolation, etc. There is a lot of ground to cover on this." }, { "code": null, "e": 18910, "s": 18862, "text": "To use Pug with Express, we need to install it," }, { "code": null, "e": 18934, "s": 18910, "text": "npm install --save pug\n" }, { "code": null, "e": 19085, "s": 18934, "text": "Now that Pug is installed, set it as the templating engine for your app. You don't need to 'require' it. Add the following code to your index.js file." }, { "code": null, "e": 19144, "s": 19085, "text": "app.set('view engine', 'pug');\napp.set('views','./views');" }, { "code": null, "e": 19270, "s": 19144, "text": "Now create a new directory called views. Inside that create a file called first_view.pug, and enter the following data in it." }, { "code": null, "e": 19368, "s": 19270, "text": "doctype html\nhtml\n head\n title = \"Hello Pug\"\n body\n p.greetings#people Hello World!" }, { "code": null, "e": 19424, "s": 19368, "text": "To run this page, add the following route to your app −" }, { "code": null, "e": 19504, "s": 19424, "text": "app.get('/first_template', function(req, res){\n res.render('first_view');\n});" }, { "code": null, "e": 19767, "s": 19504, "text": "You will get the output as − Hello World! Pug converts this very simple looking markup to html. We don’t need to keep track of closing our tags, no need to use class and id keywords, rather use '.' and '#' to define them. The above code first gets converted to −" }, { "code": null, "e": 19935, "s": 19767, "text": "<!DOCTYPE html>\n<html>\n <head>\n <title>Hello Pug</title>\n </head>\n \n <body>\n <p class = \"greetings\" id = \"people\">Hello World!</p>\n </body>\n</html>" }, { "code": null, "e": 19999, "s": 19935, "text": "Pug is capable of doing much more than simplifying HTML markup." }, { "code": null, "e": 20051, "s": 19999, "text": "Let us now explore a few important features of Pug." }, { "code": null, "e": 20278, "s": 20051, "text": "Tags are nested according to their indentation. Like in the above example, <title> was indented within the <head> tag, so it was inside it. But the <body> tag was on the same indentation, so it was a sibling of the <head> tag." }, { "code": null, "e": 20408, "s": 20278, "text": "We don’t need to close tags, as soon as Pug encounters the next tag on same or outer indentation level, it closes the tag for us." }, { "code": null, "e": 20457, "s": 20408, "text": "To put text inside of a tag, we have 3 methods −" }, { "code": null, "e": 20473, "s": 20457, "text": "Space seperated" }, { "code": null, "e": 20489, "s": 20473, "text": "Space seperated" }, { "code": null, "e": 20508, "s": 20489, "text": "h1 Welcome to Pug\n" }, { "code": null, "e": 20519, "s": 20508, "text": "Piped text" }, { "code": null, "e": 20530, "s": 20519, "text": "Piped text" }, { "code": null, "e": 20603, "s": 20530, "text": "div\n | To insert multiline text, \n | You can use the pipe operator.\n" }, { "code": null, "e": 20617, "s": 20603, "text": "Block of text" }, { "code": null, "e": 20631, "s": 20617, "text": "Block of text" }, { "code": null, "e": 20847, "s": 20631, "text": "div.\n But that gets tedious if you have a lot of text.\n You can use \".\" at the end of tag to denote block of text.\n To put tags inside this block, simply enter tag in a new line and \n indent it accordingly.\n" }, { "code": null, "e": 20993, "s": 20847, "text": "Pug uses the same syntax as JavaScript(//) for creating comments. These comments are converted to the html comments(<!--comment-->). For example," }, { "code": null, "e": 21018, "s": 20993, "text": "//This is a Pug comment\n" }, { "code": null, "e": 21064, "s": 21018, "text": "This comment gets converted to the following." }, { "code": null, "e": 21094, "s": 21064, "text": "<!--This is a Pug comment-->\n" }, { "code": null, "e": 21323, "s": 21094, "text": "To define attributes, we use a comma separated list of attributes, in parenthesis. Class and ID attributes have special representations. The following line of code covers defining attributes, classes and id for a given html tag." }, { "code": null, "e": 21390, "s": 21323, "text": "div.container.column.main#division(width = \"100\", height = \"100\")\n" }, { "code": null, "e": 21444, "s": 21390, "text": "This line of code, gets converted to the following. −" }, { "code": null, "e": 21533, "s": 21444, "text": "<div class = \"container column main\" id = \"division\" width = \"100\" height = \"100\"></div>" }, { "code": null, "e": 21706, "s": 21533, "text": "When we render a Pug template, we can actually pass it a value from our route handler, which we can then use in our template. Create a new route handler with the following." }, { "code": null, "e": 21937, "s": 21706, "text": "var express = require('express');\nvar app = express();\n\napp.get('/dynamic_view', function(req, res){\n res.render('dynamic', {\n name: \"TutorialsPoint\", \n url:\"http://www.tutorialspoint.com\"\n });\n});\n\napp.listen(3000);" }, { "code": null, "e": 22030, "s": 21937, "text": "And create a new view file in views directory, called dynamic.pug, with the following code −" }, { "code": null, "e": 22107, "s": 22030, "text": "html\n head\n title=name\n body\n h1=name\n a(href = url) URL\n" }, { "code": null, "e": 22195, "s": 22107, "text": "Open localhost:3000/dynamic_view in your browser; You should get the following output −" }, { "code": null, "e": 22456, "s": 22195, "text": "We can also use these passed variables within text. To insert passed variables in between text of a tag, we use #{variableName} syntax. For example, in the above example, if we wanted to put Greetings from TutorialsPoint, then we could have done the following." }, { "code": null, "e": 22553, "s": 22456, "text": "html\n head\n title = name\n body\n h1 Greetings from #{name}\n a(href = url) URL\n" }, { "code": null, "e": 22658, "s": 22553, "text": "This method of using values is called interpolation. The above code will display the following output. −" }, { "code": null, "e": 22724, "s": 22658, "text": "We can use conditional statements and looping constructs as well." }, { "code": null, "e": 22749, "s": 22724, "text": "Consider the following −" }, { "code": null, "e": 22907, "s": 22749, "text": "If a User is logged in, the page should display \"Hi, User\" and if not, then the \"Login/Sign Up\" link. To achieve this, we can define a simple template like −" }, { "code": null, "e": 23050, "s": 22907, "text": "html\n head\n title Simple template\n body\n if(user)\n h1 Hi, #{user.name}\n else\n a(href = \"/sign_up\") Sign Up\n" }, { "code": null, "e": 23140, "s": 23050, "text": "When we render this using our routes, we can pass an object as in the following program −" }, { "code": null, "e": 23205, "s": 23140, "text": "res.render('/dynamic',{\n user: {name: \"Ayush\", age: \"20\"}\n});\n" }, { "code": null, "e": 23339, "s": 23205, "text": "You will receive a message − Hi, Ayush. But if we don’t pass any object or pass one with no user key, then we will get a signup link." }, { "code": null, "e": 23638, "s": 23339, "text": "Pug provides a very intuitive way to create components for a web page. For example, if you see a news website, the header with logo and categories is always fixed. Instead of copying that to every view we create, we can use the include feature. Following example shows how we can use this feature −" }, { "code": null, "e": 23679, "s": 23638, "text": "Create 3 views with the following code −" }, { "code": null, "e": 23690, "s": 23679, "text": "HEADER.PUG" }, { "code": null, "e": 23739, "s": 23690, "text": "div.header.\n I'm the header for this website.\n" }, { "code": null, "e": 23751, "s": 23739, "text": "CONTENT.PUG" }, { "code": null, "e": 23885, "s": 23751, "text": "html\n head\n title Simple template\n body\n include ./header.pug\n h3 I'm the main content\n include ./footer.pug\n" }, { "code": null, "e": 23896, "s": 23885, "text": "FOOTER.PUG" }, { "code": null, "e": 23945, "s": 23896, "text": "div.footer.\n I'm the footer for this website.\n" }, { "code": null, "e": 23982, "s": 23945, "text": "Create a route for this as follows −" }, { "code": null, "e": 24131, "s": 23982, "text": "var express = require('express');\nvar app = express();\n\napp.get('/components', function(req, res){\n res.render('content');\n});\n\napp.listen(3000);" }, { "code": null, "e": 24204, "s": 24131, "text": "Go to localhost:3000/components, you will receive the following output −" }, { "code": null, "e": 24271, "s": 24204, "text": "include can also be used to include plaintext, css and JavaScript." }, { "code": null, "e": 24394, "s": 24271, "text": "There are many more features of Pug. But those are out of the scope for this tutorial. You can further explore Pug at Pug." }, { "code": null, "e": 24625, "s": 24394, "text": "Static files are files that clients download as they are from the server. Create a new directory, public. Express, by default does not allow you to serve static files. You need to enable it using the following built-in middleware." }, { "code": null, "e": 24661, "s": 24625, "text": "app.use(express.static('public'));\n" }, { "code": null, "e": 24789, "s": 24661, "text": "Note − Express looks up the files relative to the static directory, so the name of the static directory is not part of the URL." }, { "code": null, "e": 25089, "s": 24789, "text": "Note that the root route is now set to your public dir, so all static files you load will be considering public as root. To test that this is working fine, add any image file in your new public dir and change its name to \"testimage.jpg\". In your views, create a new view and include this file like −" }, { "code": null, "e": 25204, "s": 25089, "text": "html\n head\n body\n h3 Testing static file serving:\n img(src = \"/testimage.jpg\", alt = \"Testing Image\n" }, { "code": null, "e": 25242, "s": 25204, "text": "You should get the following output −" }, { "code": null, "e": 25323, "s": 25242, "text": "We can also set multiple static assets directories using the following program −" }, { "code": null, "e": 25468, "s": 25323, "text": "var express = require('express');\nvar app = express();\n\napp.use(express.static('public'));\napp.use(express.static('images'));\n\napp.listen(3000);" }, { "code": null, "e": 25657, "s": 25468, "text": "We can also provide a path prefix for serving static files. For example, if you want to provide a path prefix like '/static', you need to include the following code in your index.js file −" }, { "code": null, "e": 25778, "s": 25657, "text": "var express = require('express');\nvar app = express();\n\napp.use('/static', express.static('public'));\n\napp.listen(3000);" }, { "code": null, "e": 25927, "s": 25778, "text": "Now whenever you need to include a file, for example, a script file called main.js residing in your public directory, use the following script tag −" }, { "code": null, "e": 25963, "s": 25927, "text": "<script src = \"/static/main.js\" />\n" }, { "code": null, "e": 26115, "s": 25963, "text": "This technique can come in handy when providing multiple directories as static files. These prefixes can help distinguish between multiple directories." }, { "code": null, "e": 26406, "s": 26115, "text": "Forms are an integral part of the web. Almost every website we visit offers us forms that submit or fetch some information for us. To get started with forms, we will first install the body-parser(for parsing JSON and url-encoded data) and multer(for parsing multipart/form data) middleware." }, { "code": null, "e": 26475, "s": 26406, "text": "To install the body-parser and multer, go to your terminal and use −" }, { "code": null, "e": 26514, "s": 26475, "text": "npm install --save body-parser multer\n" }, { "code": null, "e": 26576, "s": 26514, "text": "Replace your index.js file contents with the following code −" }, { "code": null, "e": 27235, "s": 26576, "text": "var express = require('express');\nvar bodyParser = require('body-parser');\nvar multer = require('multer');\nvar upload = multer();\nvar app = express();\n\napp.get('/', function(req, res){\n res.render('form');\n});\n\napp.set('view engine', 'pug');\napp.set('views', './views');\n\n// for parsing application/json\napp.use(bodyParser.json()); \n\n// for parsing application/xwww-\napp.use(bodyParser.urlencoded({ extended: true })); \n//form-urlencoded\n\n// for parsing multipart/form-data\napp.use(upload.array()); \napp.use(express.static('public'));\n\napp.post('/', function(req, res){\n console.log(req.body);\n res.send(\"recieved your request!\");\n});\napp.listen(3000);" }, { "code": null, "e": 27425, "s": 27235, "text": "After importing the body parser and multer, we will use the body-parser for parsing json and x-www-form-urlencoded header requests, while we will use multer for parsing multipart/form-data." }, { "code": null, "e": 27530, "s": 27425, "text": "Let us create an html form to test this out. Create a new view called form.pug with the following code −" }, { "code": null, "e": 27894, "s": 27530, "text": "html\nhtml\n head\n title Form Tester\n body\n form(action = \"/\", method = \"POST\")\n div\n label(for = \"say\") Say:\n input(name = \"say\" value = \"Hi\")\n br\n div\n label(for = \"to\") To:\n input(name = \"to\" value = \"Express forms\")\n br\n button(type = \"submit\") Send my greetings\n" }, { "code": null, "e": 27931, "s": 27894, "text": "Run your server using the following." }, { "code": null, "e": 27949, "s": 27931, "text": "nodemon index.js\n" }, { "code": null, "e": 28064, "s": 27949, "text": "Now go to localhost:3000/ and fill the form as you like, and submit it. The following response will be displayed −" }, { "code": null, "e": 28191, "s": 28064, "text": "Have a look at your console; it will show you the body of your request as a JavaScript object as in the following screenshot −" }, { "code": null, "e": 28316, "s": 28191, "text": "The req.body object contains your parsed request body. To use fields from that object, just use them like normal JS objects." }, { "code": null, "e": 28586, "s": 28316, "text": "This is the most recommended way to send a request. There are many other ways, but those are irrelevant to cover here, because our Express app will handle all those requests in the same way. To read more about different ways to make a request, have a look at this page." }, { "code": null, "e": 28755, "s": 28586, "text": "We keep receiving requests, but end up not storing them anywhere. We need a Database to store the data. For this, we will make use of the NoSQL database called MongoDB." }, { "code": null, "e": 28806, "s": 28755, "text": "To install and read about Mongo, follow this link." }, { "code": null, "e": 29321, "s": 28806, "text": "In order to use Mongo with Express, we need a client API for node. There are multiple options for us, but for this tutorial, we will stick to mongoose. Mongoose is used for document Modeling in Node for MongoDB. For document modeling, we create a Model (much like a class in document oriented programming), and then we produce documents using this Model (like we create documents of a class in OOP). All our processing will be done on these \"documents\", then finally, we will write these documents in our database." }, { "code": null, "e": 29444, "s": 29321, "text": "Now that you have installed Mongo, let us install Mongoose, the same way we have been installing our other node packages −" }, { "code": null, "e": 29473, "s": 29444, "text": "npm install --save mongoose\n" }, { "code": null, "e": 29674, "s": 29473, "text": "Before we start using mongoose, we have to create a database using the Mongo shell. To create a new database, open your terminal and enter \"mongo\". A Mongo shell will start, enter the following code −" }, { "code": null, "e": 29685, "s": 29674, "text": "use my_db\n" }, { "code": null, "e": 29870, "s": 29685, "text": "A new database will be created for you. Whenever you open up the mongo shell, it will default to \"test\" db and you will have to change to your database using the same command as above." }, { "code": null, "e": 29999, "s": 29870, "text": "To use Mongoose, we will require it in our index.js file and then connect to the mongodb service running on mongodb://localhost." }, { "code": null, "e": 30083, "s": 29999, "text": "var mongoose = require('mongoose');\nmongoose.connect('mongodb://localhost/my_db');\n" }, { "code": null, "e": 30280, "s": 30083, "text": "Now our app is connected to our database, let us create a new Model. This model will act as a collection in our database. To create a new Model, use the following code, before defining any route −" }, { "code": null, "e": 30430, "s": 30280, "text": "var personSchema = mongoose.Schema({\n name: String,\n age: Number,\n nationality: String\n});\nvar Person = mongoose.model(\"Person\", personSchema);" }, { "code": null, "e": 30523, "s": 30430, "text": "The above code defines the schema for a person and is used to create a Mongoose Mode Person." }, { "code": null, "e": 30750, "s": 30523, "text": "Now, we will create a new html form; this form will help you get the details of a person and save it to our database. To create the form, create a new view file called person.pug in views directory with the following content −" }, { "code": null, "e": 31154, "s": 30750, "text": "html\nhead\n title Person\n body\n form(action = \"/person\", method = \"POST\")\n div\n label(for = \"name\") Name: \n input(name = \"name\")\n br\n div\n label(for = \"age\") Age: \n input(name = \"age\")\n br\n div\n label(for = \"nationality\") Nationality: \n input(name = \"nationality\")\n br\n button(type = \"submit\") Create new person\n" }, { "code": null, "e": 31217, "s": 31154, "text": "Also add a new get route in index.js to render this document −" }, { "code": null, "e": 31285, "s": 31217, "text": "app.get('/person', function(req, res){\n res.render('person');\n});" }, { "code": null, "e": 31483, "s": 31285, "text": "Go to \"localhost:3000/person\" to check if the form is displaying the correct output. Note that this is just the UI, it is not working yet. The following screenshot shows how the form is displayed −" }, { "code": null, "e": 31567, "s": 31483, "text": "We will now define a post route handler at '/person' which will handle this request" }, { "code": null, "e": 32314, "s": 31567, "text": "app.post('/person', function(req, res){\n var personInfo = req.body; //Get the parsed information\n \n if(!personInfo.name || !personInfo.age || !personInfo.nationality){\n res.render('show_message', {\n message: \"Sorry, you provided worng info\", type: \"error\"});\n } else {\n var newPerson = new Person({\n name: personInfo.name,\n age: personInfo.age,\n nationality: personInfo.nationality\n });\n\t\t\n newPerson.save(function(err, Person){\n if(err)\n res.render('show_message', {message: \"Database error\", type: \"error\"});\n else\n res.render('show_message', {\n message: \"New person added\", type: \"success\", person: personInfo});\n });\n }\n});" }, { "code": null, "e": 32746, "s": 32314, "text": "In the above code, if we receive any empty field or do not receive any field, we will send an error response. But if we receive a well-formed document, then we create a newPerson document from Person model and save it to our DB using the newPerson.save() function. This is defined in Mongoose and accepts a callback as argument. This callback has 2 arguments – error and response. These arguments will render the show_message view." }, { "code": null, "e": 32877, "s": 32746, "text": "To show the response from this route, we will also need to create a show_message view. Create a new view with the following code −" }, { "code": null, "e": 33149, "s": 32877, "text": "html\n head\n title Person\n body\n if(type == \"error\")\n h3(style = \"color:red\") #{message}\n else\n h3 New person, \n name: #{person.name}, \n age: #{person.age} and \n nationality: #{person.nationality} added!\n" }, { "code": null, "e": 33244, "s": 33149, "text": "We will receive the following response on successfully submitting the form(show_message.pug) −" }, { "code": null, "e": 33288, "s": 33244, "text": "We now have an interface to create persons." }, { "code": null, "e": 33554, "s": 33288, "text": "Mongoose provides a lot of functions for retrieving documents, we will focus on 3 of those. All these functions also take a callback as the last parameter, and just like the save function, their arguments are error and response. The three functions are as follows −" }, { "code": null, "e": 33699, "s": 33554, "text": "This function finds all the documents matching the fields in conditions object. Same operators used in Mongo also work in mongoose. For example," }, { "code": null, "e": 33766, "s": 33699, "text": "Person.find(function(err, response){\n console.log(response);\n});" }, { "code": null, "e": 33830, "s": 33766, "text": "This will fetch all the documents from the person's collection." }, { "code": null, "e": 33930, "s": 33830, "text": "Person.find({name: \"Ayush\", age: 20}, \n function(err, response){\n console.log(response);\n});" }, { "code": null, "e": 34003, "s": 33930, "text": "This will fetch all documents where field name is \"Ayush\" and age is 20." }, { "code": null, "e": 34158, "s": 34003, "text": "We can also provide projection we need, i.e., the fields we need. For example, if we want only the names of people whose nationality is \"Indian\", we use −" }, { "code": null, "e": 34258, "s": 34158, "text": "Person.find({nationality: \"Indian\"}, \"name\", function(err, response){\n console.log(response);\n});" }, { "code": null, "e": 34370, "s": 34258, "text": "This function always fetches a single, most relevant document. It has the same exact arguments as Model.find()." }, { "code": null, "e": 34524, "s": 34370, "text": "This function takes in the _id(defined by mongo) as the first argument, an optional projection string and a callback to handle the response. For example," }, { "code": null, "e": 34623, "s": 34524, "text": "Person.findById(\"507f1f77bcf86cd799439011\", function(err, response){\n console.log(response);\n});" }, { "code": null, "e": 34678, "s": 34623, "text": "Let us now create a route to view all people records −" }, { "code": null, "e": 35105, "s": 34678, "text": "var express = require('express');\nvar app = express();\n\nvar mongoose = require('mongoose');\nmongoose.connect('mongodb://localhost/my_db');\n\nvar personSchema = mongoose.Schema({\n name: String,\n age: Number,\n nationality: String\n});\n\nvar Person = mongoose.model(\"Person\", personSchema);\n\napp.get('/people', function(req, res){\n Person.find(function(err, response){\n res.json(response);\n });\n});\n\napp.listen(3000);" }, { "code": null, "e": 35192, "s": 35105, "text": "Mongoose provides 3 functions to update documents. The functions are described below −" }, { "code": null, "e": 35437, "s": 35192, "text": "This function takes a conditions and updates an object as input and applies the changes to all the documents matching the conditions in the collection. For example, following code will update the nationality \"American\" in all Person documents −" }, { "code": null, "e": 35544, "s": 35437, "text": "Person.update({age: 25}, {nationality: \"American\"}, function(err, response){\n console.log(response);\n});" }, { "code": null, "e": 35743, "s": 35544, "text": "It finds one document based on the query and updates that according to the second argument. It also takes a callback as last argument. Let us perform the following example to understand the function" }, { "code": null, "e": 35851, "s": 35743, "text": "Person.findOneAndUpdate({name: \"Ayush\"}, {age: 40}, function(err, response) {\n console.log(response);\n});" }, { "code": null, "e": 35926, "s": 35851, "text": "This function updates a single document identified by its id. For example," }, { "code": null, "e": 36058, "s": 35926, "text": "Person.findByIdAndUpdate(\"507f1f77bcf86cd799439011\", {name: \"James\"}, \n function(err, response){\n console.log(response);\n});" }, { "code": null, "e": 36182, "s": 36058, "text": "Let us now create a route to update people. This will be a PUT route with the id as a parameter and details in the payload." }, { "code": null, "e": 36739, "s": 36182, "text": "var express = require('express');\nvar app = express();\n\nvar mongoose = require('mongoose');\nmongoose.connect('mongodb://localhost/my_db');\n\nvar personSchema = mongoose.Schema({\n name: String,\n age: Number,\n nationality: String\n});\n\nvar Person = mongoose.model(\"Person\", personSchema);\n\napp.put('/people/:id', function(req, res){\n Person.findByIdAndUpdate(req.params.id, req.body, function(err, response){\n if(err) res.json({message: \"Error in updating person with id \" + req.params.id});\n res.json(response);\n });\n});\n\napp.listen(3000);" }, { "code": null, "e": 36851, "s": 36739, "text": "To test this route, enter the following in your terminal (replace the id with an id from your created people) −" }, { "code": null, "e": 36972, "s": 36851, "text": "curl -X PUT --data \"name = James&age = 20&nationality = American\n\"http://localhost:3000/people/507f1f77bcf86cd799439011\n" }, { "code": null, "e": 37071, "s": 36972, "text": "This will update the document associated with the id provided in the route with the above details." }, { "code": null, "e": 37221, "s": 37071, "text": "We have covered Create, Read and Update, now we will see how Mongoose can be used to Delete documents. We have 3 functions here, exactly like update." }, { "code": null, "e": 37401, "s": 37221, "text": "This function takes a condition object as input and removes all documents matching the conditions. For example, if we need to remove all people aged 20, use the following syntax −" }, { "code": null, "e": 37427, "s": 37401, "text": "Person.remove({age:20});\n" }, { "code": null, "e": 37573, "s": 37427, "text": "This functions removes a single, most relevant document according to conditions object. Let us execute the following code to understand the same." }, { "code": null, "e": 37616, "s": 37573, "text": "Person.findOneAndRemove({name: \"Ayush\"});\n" }, { "code": null, "e": 37691, "s": 37616, "text": "This function removes a single document identified by its id. For example," }, { "code": null, "e": 37745, "s": 37691, "text": "Person.findByIdAndRemove(\"507f1f77bcf86cd799439011\");" }, { "code": null, "e": 37807, "s": 37745, "text": "Let us now create a route to delete people from our database." }, { "code": null, "e": 38407, "s": 37807, "text": "var express = require('express');\nvar app = express();\n\nvar mongoose = require('mongoose');\nmongoose.connect('mongodb://localhost/my_db');\n\nvar personSchema = mongoose.Schema({\n name: String,\n age: Number,\n nationality: String\n});\n\nvar Person = mongoose.model(\"Person\", personSchema);\n\napp.delete('/people/:id', function(req, res){\n Person.findByIdAndRemove(req.params.id, function(err, response){\n if(err) res.json({message: \"Error in deleting record id \" + req.params.id});\n else res.json({message: \"Person with id \" + req.params.id + \" removed.\"});\n });\n});\n\napp.listen(3000);" }, { "code": null, "e": 38462, "s": 38407, "text": "To check the output, use the following curl command − " }, { "code": null, "e": 38532, "s": 38462, "text": "curl -X DELETE http://localhost:3000/people/507f1f77bcf86cd799439011\n" }, { "code": null, "e": 38608, "s": 38532, "text": "This will remove the person with given id producing the following message −" }, { "code": null, "e": 38671, "s": 38608, "text": "{message: \"Person with id 507f1f77bcf86cd799439011 removed.\"}\n" }, { "code": null, "e": 38813, "s": 38671, "text": "This wraps up how we can create simple CRUD applications using MongoDB, Mongoose and Express. To explore Mongoose further, read the API docs." }, { "code": null, "e": 39057, "s": 38813, "text": "Cookies are simple, small files/data that are sent to client with a server request and stored on the client side. Every time the user loads the website back, this cookie is sent with the request. This helps us keep track of the user’s actions." }, { "code": null, "e": 39115, "s": 39057, "text": "The following are the numerous uses of the HTTP Cookies −" }, { "code": null, "e": 39134, "s": 39115, "text": "Session management" }, { "code": null, "e": 39174, "s": 39134, "text": "Personalization(Recommendation systems)" }, { "code": null, "e": 39188, "s": 39174, "text": "User tracking" }, { "code": null, "e": 39295, "s": 39188, "text": "To use cookies with Express, we need the cookie-parser middleware. To install it, use the following code −" }, { "code": null, "e": 39329, "s": 39295, "text": "npm install --save cookie-parser\n" }, { "code": null, "e": 39635, "s": 39329, "text": "Now to use cookies with Express, we will require the cookie-parser. cookie-parser is a middleware which parses cookies attached to the client request object. To use it, we will require it in our index.js file; this can be used the same way as we use other middleware. Here, we will use the following code." }, { "code": null, "e": 39705, "s": 39635, "text": "var cookieParser = require('cookie-parser');\napp.use(cookieParser());" }, { "code": null, "e": 39882, "s": 39705, "text": "cookie-parser parses Cookie header and populates req.cookies with an object keyed by the cookie names. To set a new cookie, let us define a new route in your Express app like −" }, { "code": null, "e": 40069, "s": 39882, "text": "var express = require('express');\nvar app = express();\n\napp.get('/', function(req, res){\n res.cookie('name', 'express').send('cookie set'); //Sets name = express\n});\n\napp.listen(3000);" }, { "code": null, "e": 40166, "s": 40069, "text": "To check if your cookie is set or not, just go to your browser, fire up the console, and enter −" }, { "code": null, "e": 40197, "s": 40166, "text": "console.log(document.cookie);\n" }, { "code": null, "e": 40300, "s": 40197, "text": "You will get the output like (you may have more cookies set maybe due to extensions in your browser) −" }, { "code": null, "e": 40318, "s": 40300, "text": "\"name = express\"\n" }, { "code": null, "e": 40495, "s": 40318, "text": "The browser also sends back cookies every time it queries the server. To view cookies from your server, on the server console in a route, add the following code to that route. " }, { "code": null, "e": 40535, "s": 40495, "text": "console.log('Cookies: ', req.cookies);\n" }, { "code": null, "e": 40618, "s": 40535, "text": "Next time you send a request to this route, you will receive the following output." }, { "code": null, "e": 40648, "s": 40618, "text": "Cookies: { name: 'express' }\n" }, { "code": null, "e": 40811, "s": 40648, "text": "You can add cookies that expire. To add a cookie that expires, just pass an object with property 'expire' set to the time when you want it to expire. For example," }, { "code": null, "e": 40921, "s": 40811, "text": "//Expires after 360000 ms from the time it is set.\nres.cookie(name, 'value', {expire: 360000 + Date.now()}); " }, { "code": null, "e": 41100, "s": 40921, "text": "Another way to set expiration time is using 'maxAge' property. Using this property, we can provide relative time instead of absolute time. Following is an example of this method." }, { "code": null, "e": 41213, "s": 41100, "text": "//This cookie also expires after 360000 ms from the time it is set.\nres.cookie(name, 'value', {maxAge: 360000});" }, { "code": null, "e": 41341, "s": 41213, "text": "To delete a cookie, use the clearCookie function. For example, if you need to clear a cookie named foo, use the following code." }, { "code": null, "e": 41531, "s": 41341, "text": "var express = require('express');\nvar app = express();\n\napp.get('/clear_cookie_foo', function(req, res){\n res.clearCookie('foo');\n res.send('cookie foo cleared');\n});\n\napp.listen(3000);" }, { "code": null, "e": 41603, "s": 41531, "text": "In the next chapter, we will see how to use cookies to manage sessions." }, { "code": null, "e": 42083, "s": 41603, "text": "HTTP is stateless; in order to associate a request to any other request, you need a way to store user data between HTTP requests. Cookies and URL parameters are both suitable ways to transport data between the client and the server. But they are both readable and on the client side. Sessions solve exactly this problem. You assign the client an ID and it makes all further requests using that ID. Information associated with the client is stored on the server linked to this ID." }, { "code": null, "e": 42157, "s": 42083, "text": "We will need the Express-session, so install it using the following code." }, { "code": null, "e": 42193, "s": 42157, "text": "npm install --save express-session\n" }, { "code": null, "e": 42540, "s": 42193, "text": "We will put the session and cookie-parser middleware in place. In this example, we will use the default store for storing sessions, i.e., MemoryStore. Never use this in production environments. The session middleware handles all things for us, i.e., creating the session, setting the session cookie and creating the session object in req object." }, { "code": null, "e": 42812, "s": 42540, "text": "Whenever we make a request from the same client again, we will have their session information stored with us (given that the server was not restarted). We can add more properties to the session object. In the following example, we will create a view counter for a client." }, { "code": null, "e": 43339, "s": 42812, "text": "var express = require('express');\nvar cookieParser = require('cookie-parser');\nvar session = require('express-session');\n\nvar app = express();\n\napp.use(cookieParser());\napp.use(session({secret: \"Shh, its a secret!\"}));\n\napp.get('/', function(req, res){\n if(req.session.page_views){\n req.session.page_views++;\n res.send(\"You visited this page \" + req.session.page_views + \" times\");\n } else {\n req.session.page_views = 1;\n res.send(\"Welcome to this page for the first time!\");\n }\n});\napp.listen(3000);" }, { "code": null, "e": 43569, "s": 43339, "text": "What the above code does is, when a user visits the site, it creates a new session for the user and assigns them a cookie. Next time the user comes, the cookie is checked and the page_view session variable is updated accordingly." }, { "code": null, "e": 43658, "s": 43569, "text": "Now if you run the app and go to localhost:3000, the following output will be displayed." }, { "code": null, "e": 43776, "s": 43658, "text": "If you revisit the page, the page counter will increase. The page in the following screenshot was refreshed 42 times." }, { "code": null, "e": 44080, "s": 43776, "text": "Authentication is a process in which the credentials provided are compared to those on file in a database of authorized users' information on a local operating system or within an authentication server. If the credentials match, the process is completed and the user is granted authorization for access." }, { "code": null, "e": 44402, "s": 44080, "text": "For us to create an authentication system, we will need to create a sign up page and a user-password store. The following code creates an account for us and stores it in memory. This is just for the purpose of demo; it is recommended that a persistent storage (database or files) is always used to store user information." }, { "code": null, "e": 45530, "s": 44402, "text": "var express = require('express');\nvar app = express();\nvar bodyParser = require('body-parser');\nvar multer = require('multer');\nvar upload = multer(); \nvar session = require('express-session');\nvar cookieParser = require('cookie-parser');\n\napp.set('view engine', 'pug');\napp.set('views','./views');\n\napp.use(bodyParser.json());\napp.use(bodyParser.urlencoded({ extended: true })); \napp.use(upload.array());\napp.use(cookieParser());\napp.use(session({secret: \"Your secret key\"}));\n\nvar Users = [];\n\napp.get('/signup', function(req, res){\n res.render('signup');\n});\n\napp.post('/signup', function(req, res){\n if(!req.body.id || !req.body.password){\n res.status(\"400\");\n res.send(\"Invalid details!\");\n } else {\n Users.filter(function(user){\n if(user.id === req.body.id){\n res.render('signup', {\n message: \"User Already Exists! Login or choose another user id\"});\n }\n });\n var newUser = {id: req.body.id, password: req.body.password};\n Users.push(newUser);\n req.session.user = newUser;\n res.redirect('/protected_page');\n }\n});\n\napp.listen(3000);" }, { "code": null, "e": 45593, "s": 45530, "text": "Now for the signup form, create a new view called signup.jade." }, { "code": null, "e": 45930, "s": 45593, "text": "html\n head\n title Signup\n body\n if(message)\n h4 #{message}\n form(action = \"/signup\" method = \"POST\")\n input(name = \"id\" type = \"text\" required placeholder = \"User ID\")\n input(name = \"password\" type = \"password\" required placeholder = \"Password\")\n button(type = \"Submit\") Sign me up!" }, { "code": null, "e": 45990, "s": 45930, "text": "Check if this page loads by visiting localhost:3000/signup." }, { "code": null, "e": 46331, "s": 45990, "text": "We have set the required attribute for both fields, so HTML5 enabled browsers will not let us submit this form until we provide both id and password. If someone tries to register using a curl request without a User ID or Password, an error will be displayed. Create a new file called protected_page.pug in views with the following content −" }, { "code": null, "e": 46469, "s": 46331, "text": "html\n head\n title Protected page\n body\n div Hey #{id}, How are you doing today?\n div Want to log out?\n div Logout" }, { "code": null, "e": 46615, "s": 46469, "text": "This page should only be visible if the user has just signed up or logged in. Let us now define its route and also routes to log in and log out −" }, { "code": null, "e": 49006, "s": 46615, "text": "var express = require('express');\nvar app = express();\nvar bodyParser = require('body-parser');\nvar multer = require('multer');\nvar upload = multer(); \nvar session = require('express-session');\nvar cookieParser = require('cookie-parser');\n\napp.set('view engine', 'pug');\napp.set('views','./views');\n\napp.use(bodyParser.json());\napp.use(bodyParser.urlencoded({ extended: true })); \napp.use(upload.array());\napp.use(cookieParser());\napp.use(session({secret: \"Your secret key\"}));\n\nvar Users = [];\n\napp.get('/signup', function(req, res){\n res.render('signup');\n});\n\napp.post('/signup', function(req, res){\n if(!req.body.id || !req.body.password){\n res.status(\"400\");\n res.send(\"Invalid details!\");\n } else {\n Users.filter(function(user){\n if(user.id === req.body.id){\n res.render('signup', {\n message: \"User Already Exists! Login or choose another user id\"});\n }\n });\n var newUser = {id: req.body.id, password: req.body.password};\n Users.push(newUser);\n req.session.user = newUser;\n res.redirect('/protected_page');\n }\n});\nfunction checkSignIn(req, res){\n if(req.session.user){\n next(); //If session exists, proceed to page\n } else {\n var err = new Error(\"Not logged in!\");\n console.log(req.session.user);\n next(err); //Error, trying to access unauthorized page!\n }\n}\napp.get('/protected_page', checkSignIn, function(req, res){\n res.render('protected_page', {id: req.session.user.id})\n});\n\napp.get('/login', function(req, res){\n res.render('login');\n});\n\napp.post('/login', function(req, res){\n console.log(Users);\n if(!req.body.id || !req.body.password){\n res.render('login', {message: \"Please enter both id and password\"});\n } else {\n Users.filter(function(user){\n if(user.id === req.body.id && user.password === req.body.password){\n req.session.user = user;\n res.redirect('/protected_page');\n }\n });\n res.render('login', {message: \"Invalid credentials!\"});\n }\n});\n\napp.get('/logout', function(req, res){\n req.session.destroy(function(){\n console.log(\"user logged out.\")\n });\n res.redirect('/login');\n});\n\napp.use('/protected_page', function(err, req, res, next){\nconsole.log(err);\n //User should be authenticated! Redirect him to log in.\n res.redirect('/login');\n});\n\napp.listen(3000);" }, { "code": null, "e": 49175, "s": 49006, "text": "We have created a middleware function checkSignIn to check if the user is signed in. The protected_page uses this function. To log the user out, we destroy the session." }, { "code": null, "e": 49261, "s": 49175, "text": "Let us now create the login page. Name the view as login.pug and enter the contents −" }, { "code": null, "e": 49592, "s": 49261, "text": "html\n head\n title Signup\n body\n if(message)\n h4 #{message}\n form(action = \"/login\" method = \"POST\")\n input(name = \"id\" type = \"text\" required placeholder = \"User ID\")\n input(name = \"password\" type = \"password\" required placeholder = \"Password\")\n button(type = \"Submit\") Log in" }, { "code": null, "e": 49754, "s": 49592, "text": "Our simple authentication application is now complete; let us now test the application. Run the app using nodemon index.js, and proceed to localhost:3000/signup." }, { "code": null, "e": 49880, "s": 49754, "text": "Enter a Username and a password and click sign up. You will be redirected to the protected_page if details are valid/unique −" }, { "code": null, "e": 49946, "s": 49880, "text": "Now log out of the app. This will redirect us to the login page −" }, { "code": null, "e": 50296, "s": 49946, "text": "This route is protected such that if an unauthenticated person tries to visit it, he will be edirected to our login page. This was all about basic user authentication. It is always recommended that we use a persistent session system and use hashes for password transport. There are much better ways to authenticate users now, leveraging JSON tokens." }, { "code": null, "e": 50695, "s": 50296, "text": "An API is always needed to create mobile applications, single page applications, use AJAX calls and provide data to clients. An popular architectural style of how to structure and name these APIs and the endpoints is called REST(Representational Transfer State). HTTP 1.1 was designed keeping REST principles in mind. REST was introduced by Roy Fielding in 2000 in his Paper Fielding Dissertations." }, { "code": null, "e": 50985, "s": 50695, "text": "RESTful URIs and methods provide us with almost all information we need to process a request. The table given below summarizes how the various verbs should be used and how URIs should be named. We will be creating a movies API towards the end; let us now discuss how it will be structured." }, { "code": null, "e": 51220, "s": 50985, "text": "Let us now create this API in Express. We will be using JSON as our transport data format as it is easy to work with in JavaScript and has other benefits. Replace your index.js file with the movies.js file as in the following program." }, { "code": null, "e": 51676, "s": 51220, "text": "var express = require('express');\nvar bodyParser = require('body-parser');\nvar multer = require('multer');\nvar upload = multer();\n\nvar app = express();\n\napp.use(cookieParser());\napp.use(bodyParser.json());\napp.use(bodyParser.urlencoded({ extended: true }));\napp.use(upload.array());\n\n//Require the Router we defined in movies.js\nvar movies = require('./movies.js');\n\n//Use the Router on the sub route /movies\napp.use('/movies', movies);\n\napp.listen(3000);" }, { "code": null, "e": 51757, "s": 51676, "text": "Now that we have our application set up, let us concentrate on creating the API." }, { "code": null, "e": 52027, "s": 51757, "text": "Start by setting up the movies.js file. We are not using a database to store the movies but are storing them in memory; so every time the server restarts, the movies added by us will vanish. This can easily be mimicked using a database or a file (using node fs module)." }, { "code": null, "e": 52110, "s": 52027, "text": "Once you import Express then, create a Router and export it using module.exports −" }, { "code": null, "e": 52480, "s": 52110, "text": "var express = require('express');\nvar router = express.Router();\nvar movies = [\n {id: 101, name: \"Fight Club\", year: 1999, rating: 8.1},\n {id: 102, name: \"Inception\", year: 2010, rating: 8.7},\n {id: 103, name: \"The Dark Knight\", year: 2008, rating: 9},\n {id: 104, name: \"12 Angry Men\", year: 1957, rating: 8.9}\n];\n\n//Routes will go here\nmodule.exports = router;" }, { "code": null, "e": 52537, "s": 52480, "text": "Let us define the GET route for getting all the movies −" }, { "code": null, "e": 52598, "s": 52537, "text": "router.get('/', function(req, res){\n res.json(movies);\n});" }, { "code": null, "e": 52685, "s": 52598, "text": "To test out if this is working fine, run your app, then open your terminal and enter −" }, { "code": null, "e": 52790, "s": 52685, "text": "curl -i -H \"Accept: application/json\" -H \"Content-Type: application/json\" -X GET \nlocalhost:3000/movies\n" }, { "code": null, "e": 52833, "s": 52790, "text": "The following response will be displayed −" }, { "code": null, "e": 53067, "s": 52833, "text": "[{\"id\":101,\"name\":\"Fight Club\",\"year\":1999,\"rating\":8.1},\n{\"id\":102,\"name\":\"Inception\",\"year\":2010,\"rating\":8.7},\n{\"id\":103,\"name\":\"The Dark Knight\",\"year\":2008,\"rating\":9},\n{\"id\":104,\"name\":\"12 Angry Men\",\"year\":1957,\"rating\":8.9}]\n" }, { "code": null, "e": 53167, "s": 53067, "text": "We have a route to get all the movies. Let us now create a route to get a specific movie by its id." }, { "code": null, "e": 53526, "s": 53167, "text": "router.get('/:id([0-9]{3,})', function(req, res){\n var currMovie = movies.filter(function(movie){\n if(movie.id == req.params.id){\n return true;\n }\n });\n if(currMovie.length == 1){\n res.json(currMovie[0])\n } else {\n res.status(404);//Set status to 404 as movie was not found\n res.json({message: \"Not Found\"});\n }\n});" }, { "code": null, "e": 53658, "s": 53526, "text": "This will get us the movies according to the id that we provided. To check the output, use the following command in your terminal −" }, { "code": null, "e": 53767, "s": 53658, "text": "curl -i -H \"Accept: application/json\" -H \"Content-Type: application/json\" -X GET \nlocalhost:3000/movies/101\n" }, { "code": null, "e": 53803, "s": 53767, "text": "You'll get the following response −" }, { "code": null, "e": 53860, "s": 53803, "text": "{\"id\":101,\"name\":\"Fight Club\",\"year\":1999,\"rating\":8.1}\n" }, { "code": null, "e": 54019, "s": 53860, "text": "If you visit an invalid route, it will produce a cannot GET error while if you visit a valid route with an id that doesn’t exist, it will produce a 404 error." }, { "code": null, "e": 54090, "s": 54019, "text": "We are done with the GET routes, let us now move on to the POST route." }, { "code": null, "e": 54142, "s": 54090, "text": "Use the following route to handle the POSTed data −" }, { "code": null, "e": 54736, "s": 54142, "text": "router.post('/', function(req, res){\n //Check if all fields are provided and are valid:\n if(!req.body.name ||\n !req.body.year.toString().match(/^[0-9]{4}$/g) ||\n !req.body.rating.toString().match(/^[0-9]\\.[0-9]$/g)){\n \n res.status(400);\n res.json({message: \"Bad Request\"});\n } else {\n var newId = movies[movies.length-1].id+1;\n movies.push({\n id: newId,\n name: req.body.name,\n year: req.body.year,\n rating: req.body.rating\n });\n res.json({message: \"New movie created.\", location: \"/movies/\" + newId});\n }\n});" }, { "code": null, "e": 54867, "s": 54736, "text": "This will create a new movie and store it in the movies variable. To check this route, enter the following code in your terminal −" }, { "code": null, "e": 54963, "s": 54867, "text": "curl -X POST --data \"name = Toy%20story&year = 1995&rating = 8.5\" http://localhost:3000/movies\n" }, { "code": null, "e": 55006, "s": 54963, "text": "The following response will be displayed −" }, { "code": null, "e": 55065, "s": 55006, "text": "{\"message\":\"New movie created.\",\"location\":\"/movies/105\"}\n" }, { "code": null, "e": 55199, "s": 55065, "text": "To test if this was added to the movies object, Run the get request for /movies/105 again. The following response will be displayed −" }, { "code": null, "e": 55259, "s": 55199, "text": "{\"id\":105,\"name\":\"Toy story\",\"year\":\"1995\",\"rating\":\"8.5\"}\n" }, { "code": null, "e": 55311, "s": 55259, "text": "Let us move on to create the PUT and DELETE routes." }, { "code": null, "e": 55474, "s": 55311, "text": "The PUT route is almost the same as the POST route. We will be specifying the id for the object that'll be updated/created. Create the route in the following way." }, { "code": null, "e": 56721, "s": 55474, "text": "router.put('/:id', function(req, res){\n //Check if all fields are provided and are valid:\n if(!req.body.name ||\n !req.body.year.toString().match(/^[0-9]{4}$/g) ||\n !req.body.rating.toString().match(/^[0-9]\\.[0-9]$/g) ||\n !req.params.id.toString().match(/^[0-9]{3,}$/g)){\n \n res.status(400);\n res.json({message: \"Bad Request\"});\n } else {\n //Gets us the index of movie with given id.\n var updateIndex = movies.map(function(movie){\n return movie.id;\n }).indexOf(parseInt(req.params.id));\n \n if(updateIndex === -1){\n //Movie not found, create new\n movies.push({\n id: req.params.id,\n name: req.body.name,\n year: req.body.year,\n rating: req.body.rating\n });\n res.json({message: \"New movie created.\", location: \"/movies/\" + req.params.id});\n } else {\n //Update existing movie\n movies[updateIndex] = {\n id: req.params.id,\n name: req.body.name,\n year: req.body.year,\n rating: req.body.rating\n };\n res.json({message: \"Movie id \" + req.params.id + \" updated.\", \n location: \"/movies/\" + req.params.id});\n }\n }\n});" }, { "code": null, "e": 57047, "s": 56721, "text": "This route will perform the function specified in the above table. It will update the object with new details if it exists. If it doesn't exist, it will create a new object. To check the route, use the following curl command. This will update an existing movie. To create a new Movie, just change the id to a non-existing id." }, { "code": null, "e": 57147, "s": 57047, "text": "curl -X PUT --data \"name = Toy%20story&year = 1995&rating = 8.5\" \nhttp://localhost:3000/movies/101\n" }, { "code": null, "e": 57156, "s": 57147, "text": "Response" }, { "code": null, "e": 57218, "s": 57156, "text": "{\"message\":\"Movie id 101 updated.\",\"location\":\"/movies/101\"}\n" }, { "code": null, "e": 57269, "s": 57218, "text": "Use the following code to create a delete route. −" }, { "code": null, "e": 57656, "s": 57269, "text": "router.delete('/:id', function(req, res){\n var removeIndex = movies.map(function(movie){\n return movie.id;\n }).indexOf(req.params.id); //Gets us the index of movie with given id.\n \n if(removeIndex === -1){\n res.json({message: \"Not found\"});\n } else {\n movies.splice(removeIndex, 1);\n res.send({message: \"Movie id \" + req.params.id + \" removed.\"});\n }\n});" }, { "code": null, "e": 57800, "s": 57656, "text": "Check the route in the same way as we checked the other routes. On successful deletion(for example id 105), you will get the following output −" }, { "code": null, "e": 57836, "s": 57800, "text": "{message: \"Movie id 105 removed.\"}\n" }, { "code": null, "e": 57894, "s": 57836, "text": "Finally, our movies.js file will look like the following." }, { "code": null, "e": 60835, "s": 57894, "text": "var express = require('express');\nvar router = express.Router();\nvar movies = [\n {id: 101, name: \"Fight Club\", year: 1999, rating: 8.1},\n {id: 102, name: \"Inception\", year: 2010, rating: 8.7},\n {id: 103, name: \"The Dark Knight\", year: 2008, rating: 9},\n {id: 104, name: \"12 Angry Men\", year: 1957, rating: 8.9}\n];\nrouter.get('/:id([0-9]{3,})', function(req, res){\n var currMovie = movies.filter(function(movie){\n if(movie.id == req.params.id){\n return true;\n }\n });\n \n if(currMovie.length == 1){\n res.json(currMovie[0])\n } else {\n res.status(404); //Set status to 404 as movie was not found\n res.json({message: \"Not Found\"});\n }\n});\nrouter.post('/', function(req, res){\n //Check if all fields are provided and are valid:\n if(!req.body.name ||\n !req.body.year.toString().match(/^[0-9]{4}$/g) ||\n !req.body.rating.toString().match(/^[0-9]\\.[0-9]$/g)){\n res.status(400);\n res.json({message: \"Bad Request\"});\n } else {\n var newId = movies[movies.length-1].id+1;\n movies.push({\n id: newId,\n name: req.body.name,\n year: req.body.year,\n rating: req.body.rating\n });\n res.json({message: \"New movie created.\", location: \"/movies/\" + newId});\n }\n});\n\nrouter.put('/:id', function(req, res) {\n //Check if all fields are provided and are valid:\n if(!req.body.name ||\n !req.body.year.toString().match(/^[0-9]{4}$/g) ||\n !req.body.rating.toString().match(/^[0-9]\\.[0-9]$/g) ||\n !req.params.id.toString().match(/^[0-9]{3,}$/g)){\n res.status(400);\n res.json({message: \"Bad Request\"});\n } else {\n //Gets us the index of movie with given id.\n var updateIndex = movies.map(function(movie){\n return movie.id;\n }).indexOf(parseInt(req.params.id));\n \n if(updateIndex === -1){\n //Movie not found, create new\n movies.push({\n id: req.params.id,\n name: req.body.name,\n year: req.body.year,\n rating: req.body.rating\n });\n res.json({\n message: \"New movie created.\", location: \"/movies/\" + req.params.id});\n } else {\n //Update existing movie\n movies[updateIndex] = {\n id: req.params.id,\n name: req.body.name,\n year: req.body.year,\n rating: req.body.rating\n };\n res.json({message: \"Movie id \" + req.params.id + \" updated.\",\n location: \"/movies/\" + req.params.id});\n }\n }\n});\n\nrouter.delete('/:id', function(req, res){\n var removeIndex = movies.map(function(movie){\n return movie.id;\n }).indexOf(req.params.id); //Gets us the index of movie with given id.\n \n if(removeIndex === -1){\n res.json({message: \"Not found\"});\n } else {\n movies.splice(removeIndex, 1);\n res.send({message: \"Movie id \" + req.params.id + \" removed.\"});\n }\n});\nmodule.exports = router;" }, { "code": null, "e": 60965, "s": 60835, "text": "This completes our REST API. Now you can create much more complex applications using this simple architectural style and Express." }, { "code": null, "e": 61248, "s": 60965, "text": "Scaffolding allows us to easily create a skeleton for a web application. We manually create our public directory, add middleware, create separate route files, etc. A scaffolding tool sets up all these things for us so that we can directly get started with building our application. " }, { "code": null, "e": 61490, "s": 61248, "text": "The scaffolder we will use is called Yeoman. It is a scaffolding tool built for Node.js but also has generators for several other frameworks (like flask, rails, django, etc.). To install Yeoman, enter the following command in your terminal −" }, { "code": null, "e": 61513, "s": 61490, "text": "npm install -g yeoman\n" }, { "code": null, "e": 61795, "s": 61513, "text": "Yeoman uses generators to scaffold out applications. To check out the generators available on npm to use with Yeoman, you can click on this link. In this tutorial, we will use the 'generator-Express-simple'. To install this generator, enter the following command in your terminal −" }, { "code": null, "e": 61836, "s": 61795, "text": "npm install -g generator-express-simple\n" }, { "code": null, "e": 61889, "s": 61836, "text": "To use this generator, enter the following command −" }, { "code": null, "e": 61917, "s": 61889, "text": "yo express-simple test-app\n" }, { "code": null, "e": 62132, "s": 61917, "text": "You will be asked a few simple questions like what things you want to use with your app. Select the following answers, or if you already know about these technologies then go about choosing how you want them to be." }, { "code": null, "e": 63078, "s": 62132, "text": "express-simple comes with bootstrap and jquery\n[?] Select the express version you want: 4.x\n[?] Do you want an mvc express app: Yes\n[?] Select the css preprocessor you would like to use: sass\n[?] Select view engine you would like to use: jade\n[?] Select the build tool you want to use for this project: gulp\n[?] Select the build tool you want to use for this project: gulp\n[?] Select the language you want to use for the build tool: javascript\n create public/sass/styles.scss\n create public/js/main.js\n create views/layout.jade\n create views/index.jade\n create views/404.jade\n create app.js\n create config.js\n create routes/index.js\n create package.json\n create bower.json\nidentical .bowerrc\nidentical .editorconfig\nidentical .gitignore\nidentical .jshintrc\n create gulpfile.js\n\nI'm all done. Running bower install & npm install for you to install the\nrequired dependencies. If this fails, try running the command yourself.\n" }, { "code": null, "e": 63273, "s": 63078, "text": "It will then create a new application for you, install all the dependencies, add few pages to your application(home page, 404 not found page, etc.) and give you a directory structure to work on." }, { "code": null, "e": 63629, "s": 63273, "text": "This generator creates a very simple structure for us. Explore the many generators available for Express and choose the one that fits you right. Steps to working with all generators is the same. You will need to install a generator, run it using Yeoman; it will ask you some questions and then create a skeleton for your application based on your answers." }, { "code": null, "e": 63975, "s": 63629, "text": "Error handling in Express is done using middleware. But this middleware has special properties. The error handling middleware are defined in the same way as other middleware functions, except that error-handling functions MUST have four arguments instead of three – err, req, res, next. For example, to send a response on any error, we can use −" }, { "code": null, "e": 64093, "s": 63975, "text": "app.use(function(err, req, res, next) {\n console.error(err.stack);\n res.status(500).send('Something broke!');\n});" }, { "code": null, "e": 64336, "s": 64093, "text": "Till now we were handling errors in the routes itself. The error handling middleware allows us to separate our error logic and send responses accordingly. The next() method we discussed in middleware takes us to next middleware/route handler." }, { "code": null, "e": 64533, "s": 64336, "text": "For error handling, we have the next(err) function. A call to this function skips all middleware and matches us to the next error handler for that route. Let us understand this through an example." }, { "code": null, "e": 64960, "s": 64533, "text": "var express = require('express');\nvar app = express();\n\napp.get('/', function(req, res){\n //Create an error and pass it to the next function\n var err = new Error(\"Something went wrong\");\n next(err);\n});\n\n/*\n * other route handlers and middleware here\n * ....\n */\n\n//An error handling middleware\napp.use(function(err, req, res, next) {\n res.status(500);\n res.send(\"Oops, something went wrong.\")\n});\n\napp.listen(3000);" }, { "code": null, "e": 65169, "s": 64960, "text": "This error handling middleware can be strategically placed after routes or contain conditions to detect error types and respond to the clients accordingly. The above program will display the following output." }, { "code": null, "e": 65296, "s": 65169, "text": "Express uses the Debug module to internally log information about route matching, middleware functions, application mode, etc." }, { "code": null, "e": 65410, "s": 65296, "text": "To see all internal logs used in Express, set the DEBUG environment variable to Express:* when starting the app −" }, { "code": null, "e": 65443, "s": 65410, "text": "DEBUG = express:* node index.js\n" }, { "code": null, "e": 65483, "s": 65443, "text": "The following output will be displayed." }, { "code": null, "e": 65797, "s": 65483, "text": "These logs are very helpful when a component of your app is not functioning right. This verbose output might be a little overwhelming. You can also restrict the DEBUG variable to specific area to be logged. For example, if you wish to restrict the logger to application and router, you can use the following code." }, { "code": null, "e": 65855, "s": 65797, "text": "DEBUG = express:application,express:router node index.js\n" }, { "code": null, "e": 66035, "s": 65855, "text": "Debug is turned off by default and is automatically turned on in production environment. Debug can also be extended to meet your needs, you can read more about it at its npm page." }, { "code": null, "e": 66472, "s": 66035, "text": "Unlike Django and Rails which have a defined way of doing things, file structure, etc., Express does not follow a defined way. This means you can structure the application the way you like. But as your application grows in size, it is very difficult to maintain it if it doesn't have a well-defined structure. In this chapter, we will look at the generally used directory structures and separation of concerns to build our applications." }, { "code": null, "e": 66558, "s": 66472, "text": "First, we will discuss the best practices for creating node and Express applications." }, { "code": null, "e": 66602, "s": 66558, "text": "Always begin a node project using npm init." }, { "code": null, "e": 66646, "s": 66602, "text": "Always begin a node project using npm init." }, { "code": null, "e": 66820, "s": 66646, "text": "Always install dependencies with a --save or --save-dev. This will ensure that if you move to a different platform, you can just run npm install to install all dependencies." }, { "code": null, "e": 66994, "s": 66820, "text": "Always install dependencies with a --save or --save-dev. This will ensure that if you move to a different platform, you can just run npm install to install all dependencies." }, { "code": null, "e": 67183, "s": 66994, "text": "Stick with lowercase file names and camelCase variables. If you look at any npm module, its named in lowercase and separated with dashes. Whenever you require these modules, use camelCase." }, { "code": null, "e": 67372, "s": 67183, "text": "Stick with lowercase file names and camelCase variables. If you look at any npm module, its named in lowercase and separated with dashes. Whenever you require these modules, use camelCase." }, { "code": null, "e": 67475, "s": 67372, "text": "Don’t push node_modules to your repositories. Instead npm installs everything on development machines." }, { "code": null, "e": 67578, "s": 67475, "text": "Don’t push node_modules to your repositories. Instead npm installs everything on development machines." }, { "code": null, "e": 67615, "s": 67578, "text": "Use a config file to store variables" }, { "code": null, "e": 67652, "s": 67615, "text": "Use a config file to store variables" }, { "code": null, "e": 67785, "s": 67652, "text": "Group and isolate routes to their own file. For example, take the CRUD operations in the movies example we saw in the REST API page." }, { "code": null, "e": 67918, "s": 67785, "text": "Group and isolate routes to their own file. For example, take the CRUD operations in the movies example we saw in the REST API page." }, { "code": null, "e": 67971, "s": 67918, "text": "Let us now discuss the Express’ Directory Structure." }, { "code": null, "e": 68115, "s": 67971, "text": "Express does not have a community defined structure for creating applications. The following is a majorly used project structure for a website." }, { "code": null, "e": 68843, "s": 68115, "text": "test-project/\n node_modules/\n config/\n db.js //Database connection and configuration\n credentials.js //Passwords/API keys for external services used by your app\n config.js //Other environment variables\n models/ //For mongoose schemas\n users.js\n things.js\n routes/ //All routes for different entities in different files \n users.js\n things.js\n views/\n index.pug\n 404.pug\n ...\n public/ //All static content being served\n images/\n css/\n javascript/\n app.js\n routes.js //Require all routes in this and then require this file in \n app.js \n package.json" }, { "code": null, "e": 69021, "s": 68843, "text": "There are other approaches to build websites with Express as well. You can build a website using the MVC design pattern. For more information, you can visit the following links." }, { "code": null, "e": 69112, "s": 69021, "text": "https://code.tutsplus.com/tutorials/build-a-complete-mvc-website-with-expressjs--net-34168" }, { "code": null, "e": 69117, "s": 69112, "text": "and," }, { "code": null, "e": 69191, "s": 69117, "text": "https://www.terlici.com/2014/08/25/best-practices-express-structure.html." }, { "code": null, "e": 69310, "s": 69191, "text": "APIs are simpler to design; they don't need a public or a views directory. Use the following structure to build APIs −" }, { "code": null, "e": 69825, "s": 69310, "text": "test-project/\n node_modules/\n config/\n db.js //Database connection and configuration\n credentials.js //Passwords/API keys for external services used by your app\n models/ //For mongoose schemas\n users.js\n things.js\n routes/ //All routes for different entities in different files \n users.js\n things.js\n app.js\n routes.js //Require all routes in this and then require this file in \n app.js \n package.json" }, { "code": null, "e": 69889, "s": 69825, "text": "You can also use a yeoman generator to get a similar structure." }, { "code": null, "e": 69962, "s": 69889, "text": "This chapter lists down the various resources we used for this tutorial." }, { "code": null, "e": 70059, "s": 69962, "text": "The most important link is of course the Express API docs − https://expressjs.com/en/4x/api.html" }, { "code": null, "e": 70156, "s": 70059, "text": "The most important link is of course the Express API docs − https://expressjs.com/en/4x/api.html" }, { "code": null, "e": 70292, "s": 70156, "text": "The guides provided on the Express website on different aspects are also quite helpful −\n\nRouting\nMiddleware\nError Handling\nDebugging\n\n" }, { "code": null, "e": 70381, "s": 70292, "text": "The guides provided on the Express website on different aspects are also quite helpful −" }, { "code": null, "e": 70389, "s": 70381, "text": "Routing" }, { "code": null, "e": 70397, "s": 70389, "text": "Routing" }, { "code": null, "e": 70408, "s": 70397, "text": "Middleware" }, { "code": null, "e": 70419, "s": 70408, "text": "Middleware" }, { "code": null, "e": 70434, "s": 70419, "text": "Error Handling" }, { "code": null, "e": 70449, "s": 70434, "text": "Error Handling" }, { "code": null, "e": 70459, "s": 70449, "text": "Debugging" }, { "code": null, "e": 70469, "s": 70459, "text": "Debugging" }, { "code": null, "e": 70581, "s": 70469, "text": "A list of useful books and blogs on Express is available at https://expressjs.com/en/resources/books-blogs.html" }, { "code": null, "e": 70693, "s": 70581, "text": "A list of useful books and blogs on Express is available at https://expressjs.com/en/resources/books-blogs.html" }, { "code": null, "e": 70806, "s": 70693, "text": "A list of mostly used middleware with Express is available at https://expressjs.com/en/resources/middleware.html" }, { "code": null, "e": 70919, "s": 70806, "text": "A list of mostly used middleware with Express is available at https://expressjs.com/en/resources/middleware.html" }, { "code": null, "e": 71109, "s": 70919, "text": "These blogs with Express tips and tricks may prove helpful −\n\nhttps://derickbailey.com/categories/tips-and-tricks/\n\nhttps://scotch.io/tutorials/learn-to-use-the-new-router-in+-expressjs-4\n\n" }, { "code": null, "e": 71170, "s": 71109, "text": "These blogs with Express tips and tricks may prove helpful −" }, { "code": null, "e": 71223, "s": 71170, "text": "https://derickbailey.com/categories/tips-and-tricks/" }, { "code": null, "e": 71276, "s": 71223, "text": "https://derickbailey.com/categories/tips-and-tricks/" }, { "code": null, "e": 71348, "s": 71276, "text": "https://scotch.io/tutorials/learn-to-use-the-new-router-in+-expressjs-4" }, { "code": null, "e": 71420, "s": 71348, "text": "https://scotch.io/tutorials/learn-to-use-the-new-router-in+-expressjs-4" }, { "code": null, "e": 71517, "s": 71420, "text": "Application structure − https://www.terlici.com/2014/08/25/best-practices-express-structure.html" }, { "code": null, "e": 71614, "s": 71517, "text": "Application structure − https://www.terlici.com/2014/08/25/best-practices-express-structure.html" }, { "code": null, "e": 72024, "s": 71614, "text": "RESTful APIs −\n\nhttps://www.thepolyglotdeveloper.com/2015/10/create-a-simple-restful-api-with-node-js/\nhttps://scotch.io/tutorials/build-a-restful-api-using-node-and-express-4\nhttps://devcenter.heroku.com/articles/mean-apps-restful-api\nhttps://pixelhandler.com/posts/develop-a-restful-api-using-nodejs-with-express-and-mongoose\nhttp://cwbuecheler.com/web/tutorials/2014/restful-web-app-node-express-mongodb/\n\n" }, { "code": null, "e": 72039, "s": 72024, "text": "RESTful APIs −" }, { "code": null, "e": 72126, "s": 72039, "text": "https://www.thepolyglotdeveloper.com/2015/10/create-a-simple-restful-api-with-node-js/" }, { "code": null, "e": 72213, "s": 72126, "text": "https://www.thepolyglotdeveloper.com/2015/10/create-a-simple-restful-api-with-node-js/" }, { "code": null, "e": 72286, "s": 72213, "text": "https://scotch.io/tutorials/build-a-restful-api-using-node-and-express-4" }, { "code": null, "e": 72359, "s": 72286, "text": "https://scotch.io/tutorials/build-a-restful-api-using-node-and-express-4" }, { "code": null, "e": 72419, "s": 72359, "text": "https://devcenter.heroku.com/articles/mean-apps-restful-api" }, { "code": null, "e": 72479, "s": 72419, "text": "https://devcenter.heroku.com/articles/mean-apps-restful-api" }, { "code": null, "e": 72571, "s": 72479, "text": "https://pixelhandler.com/posts/develop-a-restful-api-using-nodejs-with-express-and-mongoose" }, { "code": null, "e": 72663, "s": 72571, "text": "https://pixelhandler.com/posts/develop-a-restful-api-using-nodejs-with-express-and-mongoose" }, { "code": null, "e": 72743, "s": 72663, "text": "http://cwbuecheler.com/web/tutorials/2014/restful-web-app-node-express-mongodb/" }, { "code": null, "e": 72823, "s": 72743, "text": "http://cwbuecheler.com/web/tutorials/2014/restful-web-app-node-express-mongodb/" }, { "code": null, "e": 72891, "s": 72823, "text": "For advanced authentication, use PassportJS − http://passportjs.org" }, { "code": null, "e": 72959, "s": 72891, "text": "For advanced authentication, use PassportJS − http://passportjs.org" }, { "code": null, "e": 72992, "s": 72959, "text": "\n 16 Lectures \n 1 hours \n" }, { "code": null, "e": 73006, "s": 72992, "text": " Anadi Sharma" }, { "code": null, "e": 73013, "s": 73006, "text": " Print" }, { "code": null, "e": 73024, "s": 73013, "text": " Add Notes" } ]
java.time.ZoneId.systemDefault() Method Example
The java.time.ZoneId.systemDefault() method gets the system default time-zone. Following is the declaration for java.time.ZoneId.systemDefault() method. public static ZoneId systemDefault() the zone ID, not null. DateTimeException − if the converted zone ID has an invalid format. DateTimeException − if the converted zone ID has an invalid format. ZoneRulesException − if the converted zone region ID cannot be found. ZoneRulesException − if the converted zone region ID cannot be found. The following example shows the usage of java.time.ZoneId.systemDefault() method. package com.tutorialspoint; import java.time.ZoneId; public class ZoneIdDemo { public static void main(String[] args) { System.out.println(ZoneId.systemDefault()); } } Let us compile and run the above program, this will produce the following result − Asia/Calcutta Print Add Notes Bookmark this page
[ { "code": null, "e": 1994, "s": 1915, "text": "The java.time.ZoneId.systemDefault() method gets the system default time-zone." }, { "code": null, "e": 2068, "s": 1994, "text": "Following is the declaration for java.time.ZoneId.systemDefault() method." }, { "code": null, "e": 2106, "s": 2068, "text": "public static ZoneId systemDefault()\n" }, { "code": null, "e": 2129, "s": 2106, "text": "the zone ID, not null." }, { "code": null, "e": 2197, "s": 2129, "text": "DateTimeException − if the converted zone ID has an invalid format." }, { "code": null, "e": 2265, "s": 2197, "text": "DateTimeException − if the converted zone ID has an invalid format." }, { "code": null, "e": 2335, "s": 2265, "text": "ZoneRulesException − if the converted zone region ID cannot be found." }, { "code": null, "e": 2405, "s": 2335, "text": "ZoneRulesException − if the converted zone region ID cannot be found." }, { "code": null, "e": 2487, "s": 2405, "text": "The following example shows the usage of java.time.ZoneId.systemDefault() method." }, { "code": null, "e": 2673, "s": 2487, "text": "package com.tutorialspoint;\n\nimport java.time.ZoneId;\n\npublic class ZoneIdDemo {\n public static void main(String[] args) {\n \n System.out.println(ZoneId.systemDefault()); \n }\n}" }, { "code": null, "e": 2756, "s": 2673, "text": "Let us compile and run the above program, this will produce the following result −" }, { "code": null, "e": 2771, "s": 2756, "text": "Asia/Calcutta\n" }, { "code": null, "e": 2778, "s": 2771, "text": " Print" }, { "code": null, "e": 2789, "s": 2778, "text": " Add Notes" } ]
Architecture of an Embedded System | Set-3 - GeeksforGeeks
09 Jun, 2020 Typical embedded system mainly has two parts i.e., embedded hardware and embedded software. Embedded hardwares are based around microprocessors and microcontrollers, also include memory, bus, Input/Output, Controller, where as embedded software includes embedded operating systems, different applications and device drivers. Basically these two types of architecture i.e., Havard architecture and Von Neumann architecture are used in embedded systems. Architecture of the Embedded System includes Sensor, Analog to Digital Converter, Memory, Processor, Digital to Analog Converter, and Actuators etc. The below figure illustrates the overview of basic architecture of embedded systems : Embedded Product Development Life Cycle (EDLC) :Developing an embedded system or product mainly goes through this three phases which are – 1. Analysis 2. Design 3. Implementation If we will go a little bit deeper to the development steps it includes these 7 steps : Requirement analysisExamineDesignDevelopTestDeployMaintenance Requirement analysis Examine Design Develop Test Deploy Maintenance Now Let’s discuss some of the advantages and disadvantages of Embedded systems. Advantages of Embedded System : Embedded systems are fast in performance. These systems consumes less power Small in shape and size. These systems are so scalable and reliable. Works on wide variety of sectors and environments. Improve product quality and enhance performance. Performs specific tasks without error. Disadvantages of Embedded System : Difficult to backup of embedded files. Sometimes complex to develop. Integration may be a problem. Offer very limited resources for processing. Troubleshooting may be difficult. Maintenance may be a problem. Computer Organization & Architecture Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Architecture of 8086 Logical and Physical Address in Operating System Addressing modes in 8085 microprocessor 8085 program to add two 8 bit numbers Architecture of 8085 microprocessor Computer Organization | RISC and CISC Interrupts Memory Hierarchy Design and its Characteristics Computer Organization | Instruction Formats (Zero, One, Two and Three Address Instruction) Programmable peripheral interface 8255
[ { "code": null, "e": 24861, "s": 24833, "text": "\n09 Jun, 2020" }, { "code": null, "e": 24953, "s": 24861, "text": "Typical embedded system mainly has two parts i.e., embedded hardware and embedded software." }, { "code": null, "e": 25313, "s": 24953, "text": "Embedded hardwares are based around microprocessors and microcontrollers, also include memory, bus, Input/Output, Controller, where as embedded software includes embedded operating systems, different applications and device drivers. Basically these two types of architecture i.e., Havard architecture and Von Neumann architecture are used in embedded systems." }, { "code": null, "e": 25462, "s": 25313, "text": "Architecture of the Embedded System includes Sensor, Analog to Digital Converter, Memory, Processor, Digital to Analog Converter, and Actuators etc." }, { "code": null, "e": 25548, "s": 25462, "text": "The below figure illustrates the overview of basic architecture of embedded systems :" }, { "code": null, "e": 25687, "s": 25548, "text": "Embedded Product Development Life Cycle (EDLC) :Developing an embedded system or product mainly goes through this three phases which are –" }, { "code": null, "e": 25728, "s": 25687, "text": "1. Analysis\n2. Design\n3. Implementation " }, { "code": null, "e": 25815, "s": 25728, "text": "If we will go a little bit deeper to the development steps it includes these 7 steps :" }, { "code": null, "e": 25877, "s": 25815, "text": "Requirement analysisExamineDesignDevelopTestDeployMaintenance" }, { "code": null, "e": 25898, "s": 25877, "text": "Requirement analysis" }, { "code": null, "e": 25906, "s": 25898, "text": "Examine" }, { "code": null, "e": 25913, "s": 25906, "text": "Design" }, { "code": null, "e": 25921, "s": 25913, "text": "Develop" }, { "code": null, "e": 25926, "s": 25921, "text": "Test" }, { "code": null, "e": 25933, "s": 25926, "text": "Deploy" }, { "code": null, "e": 25945, "s": 25933, "text": "Maintenance" }, { "code": null, "e": 26025, "s": 25945, "text": "Now Let’s discuss some of the advantages and disadvantages of Embedded systems." }, { "code": null, "e": 26057, "s": 26025, "text": "Advantages of Embedded System :" }, { "code": null, "e": 26099, "s": 26057, "text": "Embedded systems are fast in performance." }, { "code": null, "e": 26133, "s": 26099, "text": "These systems consumes less power" }, { "code": null, "e": 26158, "s": 26133, "text": "Small in shape and size." }, { "code": null, "e": 26202, "s": 26158, "text": "These systems are so scalable and reliable." }, { "code": null, "e": 26253, "s": 26202, "text": "Works on wide variety of sectors and environments." }, { "code": null, "e": 26302, "s": 26253, "text": "Improve product quality and enhance performance." }, { "code": null, "e": 26341, "s": 26302, "text": "Performs specific tasks without error." }, { "code": null, "e": 26376, "s": 26341, "text": "Disadvantages of Embedded System :" }, { "code": null, "e": 26415, "s": 26376, "text": "Difficult to backup of embedded files." }, { "code": null, "e": 26445, "s": 26415, "text": "Sometimes complex to develop." }, { "code": null, "e": 26475, "s": 26445, "text": "Integration may be a problem." }, { "code": null, "e": 26520, "s": 26475, "text": "Offer very limited resources for processing." }, { "code": null, "e": 26554, "s": 26520, "text": "Troubleshooting may be difficult." }, { "code": null, "e": 26584, "s": 26554, "text": "Maintenance may be a problem." }, { "code": null, "e": 26621, "s": 26584, "text": "Computer Organization & Architecture" }, { "code": null, "e": 26719, "s": 26621, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26728, "s": 26719, "text": "Comments" }, { "code": null, "e": 26741, "s": 26728, "text": "Old Comments" }, { "code": null, "e": 26762, "s": 26741, "text": "Architecture of 8086" }, { "code": null, "e": 26811, "s": 26762, "text": "Logical and Physical Address in Operating System" }, { "code": null, "e": 26851, "s": 26811, "text": "Addressing modes in 8085 microprocessor" }, { "code": null, "e": 26889, "s": 26851, "text": "8085 program to add two 8 bit numbers" }, { "code": null, "e": 26925, "s": 26889, "text": "Architecture of 8085 microprocessor" }, { "code": null, "e": 26963, "s": 26925, "text": "Computer Organization | RISC and CISC" }, { "code": null, "e": 26974, "s": 26963, "text": "Interrupts" }, { "code": null, "e": 27022, "s": 26974, "text": "Memory Hierarchy Design and its Characteristics" }, { "code": null, "e": 27113, "s": 27022, "text": "Computer Organization | Instruction Formats (Zero, One, Two and Three Address Instruction)" } ]
How to create a directory hierarchy using Java?
The class named File of the java.io package represents a file or directory (path names) in the system. This class provides various methods to perform various operations on files/directories. The mkdir() method of this class creates a directory with the path represented by the current object. To create a hierarchy of new directories you can using the method mkdirs() of the same class. This method creates the directory with the path represented by the current object, including non-existing parent directories. Live Demo import java.io.File; import java.util.Scanner; public class CreateDirectory { public static void main(String args[]) { System.out.println("Enter the path to create a directory: "); Scanner sc = new Scanner(System.in); String path = sc.next(); System.out.println("Enter the name of the desired a directory: "); path = path+sc.next(); //Creating a File object File file = new File(path); //Creating the directory boolean bool = file.mkdirs(); if(bool) { System.out.println("Directory created successfully"); }else { System.out.println("Sorry couldnt create specified directory"); } } } Enter the path to create a directory: D:\test\myDirectories\ Enter the name of the desired a directory: sample_directory Directory created successfully If you verify you can observe see the created directory as −
[ { "code": null, "e": 1253, "s": 1062, "text": "The class named File of the java.io package represents a file or directory (path names) in the system. This class provides various methods to perform various operations on files/directories." }, { "code": null, "e": 1355, "s": 1253, "text": "The mkdir() method of this class creates a directory with the path represented by the current object." }, { "code": null, "e": 1575, "s": 1355, "text": "To create a hierarchy of new directories you can using the method mkdirs() of the same class. This method creates the directory with the path represented by the current object, including non-existing parent directories." }, { "code": null, "e": 1586, "s": 1575, "text": " Live Demo" }, { "code": null, "e": 2266, "s": 1586, "text": "import java.io.File;\nimport java.util.Scanner;\npublic class CreateDirectory {\n public static void main(String args[]) {\n System.out.println(\"Enter the path to create a directory: \");\n Scanner sc = new Scanner(System.in);\n String path = sc.next();\n System.out.println(\"Enter the name of the desired a directory: \");\n path = path+sc.next();\n //Creating a File object\n File file = new File(path);\n //Creating the directory\n boolean bool = file.mkdirs();\n if(bool) {\n System.out.println(\"Directory created successfully\");\n }else {\n System.out.println(\"Sorry couldnt create specified directory\");\n }\n }\n}" }, { "code": null, "e": 2418, "s": 2266, "text": "Enter the path to create a directory:\nD:\\test\\myDirectories\\\nEnter the name of the desired a directory:\nsample_directory\nDirectory created successfully" }, { "code": null, "e": 2479, "s": 2418, "text": "If you verify you can observe see the created directory as −" } ]
How to get current time zone in android using clock API class?
This example demonstrate about How to get current time zone in android using clock API class. 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"?> <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <TextView android:id="@+id/date" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Local Date" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" /> </android.support.constraint.ConstraintLayout> In the above code, we have taken textview to show current time zone. Step 3 − Add the following code to src/MainActivity.java package com.example.myapplication; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.widget.TextView; import java.time.Clock; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); TextView textView = findViewById(R.id.date); if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) { Clock clock = Clock.systemDefaultZone(); textView.setText(String.valueOf(clock.getZone())); } } } 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 − In the above result, it is showing the current time zone. Click here to download the project code
[ { "code": null, "e": 1156, "s": 1062, "text": "This example demonstrate about How to get current time zone in android using clock API class." }, { "code": null, "e": 1285, "s": 1156, "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": 1350, "s": 1285, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2128, "s": 1350, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<android.support.constraint.ConstraintLayout \n xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:app=\"http://schemas.android.com/apk/res-auto\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n tools:context=\".MainActivity\">\n <TextView\n android:id=\"@+id/date\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Local Date\"\n app:layout_constraintBottom_toBottomOf=\"parent\"\n app:layout_constraintLeft_toLeftOf=\"parent\"\n app:layout_constraintRight_toRightOf=\"parent\"\n app:layout_constraintTop_toTopOf=\"parent\" />\n</android.support.constraint.ConstraintLayout>" }, { "code": null, "e": 2197, "s": 2128, "text": "In the above code, we have taken textview to show current time zone." }, { "code": null, "e": 2254, "s": 2197, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 2892, "s": 2254, "text": "package com.example.myapplication;\n\nimport android.os.Bundle;\nimport android.support.v7.app.AppCompatActivity;\nimport android.widget.TextView;\n\nimport java.time.Clock;\n\npublic class MainActivity extends AppCompatActivity {\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n TextView textView = findViewById(R.id.date);\n if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {\n Clock clock = Clock.systemDefaultZone();\n textView.setText(String.valueOf(clock.getZone()));\n }\n }\n}" }, { "code": null, "e": 3239, "s": 2892, "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": 3297, "s": 3239, "text": "In the above result, it is showing the current time zone." }, { "code": null, "e": 3337, "s": 3297, "text": "Click here to download the project code" } ]
How to add a mathematical expression in axis label in a plot created by using plot function in R?
When we create a plot using plot function in R, the axes titles are either chosen by R automatically based on the vectors passed through the function or we can use ylab or xlab for particular axes. To add a mathematical expression in an axis label, we can use title function with expression function to define the mathematical expression. Consider the below vectors and create scatterplot between the two − set.seed(111) x<-rpois(1000,20) y<-rpois(1000,15) plot(x,y) Now suppose, we want to remove y from the Y-axis and put alpha square then it can be done as shown below − plot(x,y,ylab="") title(ylab=expression(alpha^2))
[ { "code": null, "e": 1401, "s": 1062, "text": "When we create a plot using plot function in R, the axes titles are either chosen by R automatically based on the vectors passed through the function or we can use ylab or xlab for particular axes. To add a mathematical expression in an axis label, we can use title function with expression function to define the mathematical expression." }, { "code": null, "e": 1469, "s": 1401, "text": "Consider the below vectors and create scatterplot between the two −" }, { "code": null, "e": 1529, "s": 1469, "text": "set.seed(111)\nx<-rpois(1000,20)\ny<-rpois(1000,15)\nplot(x,y)" }, { "code": null, "e": 1636, "s": 1529, "text": "Now suppose, we want to remove y from the Y-axis and put alpha square then it can be done as shown below −" }, { "code": null, "e": 1686, "s": 1636, "text": "plot(x,y,ylab=\"\")\ntitle(ylab=expression(alpha^2))" } ]
Select iframe using Python and Selenium
We can select iframe with Selenium webdriver. An iframe is identified with a <iframe> tag in an html document. An iframe is an html document containing elements which resides inside another html document. Let us see a html document of a frame. The following methods help to switch between iframes− switch_to.frame(args) – The frame index is put as an argument to the method. The starting index of iframe is 0.Syntax−driver.switch_to.frame(0), switching to the first iframe. switch_to.frame(args) – The frame index is put as an argument to the method. The starting index of iframe is 0. Syntax− driver.switch_to.frame(0), switching to the first iframe. switch_to.frame(args) - The frame name or id is put as an argument to the method.Syntax−driver.switch_to.frame("nm"), switching to the iframe with name nm. switch_to.frame(args) - The frame name or id is put as an argument to the method. Syntax− driver.switch_to.frame("nm"), switching to the iframe with name nm. switch_to.frame(args) - The frame webelement is put as an argument to the method.Syntax−driver.switch_to.frame(f),switching to the iframe with webelement f. switch_to.frame(args) - The frame webelement is put as an argument to the method. Syntax− driver.switch_to.frame(f),switching to the iframe with webelement f. switch_to.default_content() – To shift to the parent page from the iframe.Syntax−driver.switch_to.default_content() switch_to.default_content() – To shift to the parent page from the iframe. Syntax− driver.switch_to.default_content() from selenium import webdriver driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe") driver.get("https://the-internet.herokuapp.com") driver.find_element_by_link_text("Frames").click() driver.find_element_by_link_text("Nested Frames").click() # switch to frame with name driver.switch_to.frame("frame-bottom") # identify element and get text method s = driver.find_element_by_xpath("//body").text print ("Test inside frame: " + s) # move out of frame to parent page driver.switch_to.default_content() driver.quit()
[ { "code": null, "e": 1267, "s": 1062, "text": "We can select iframe with Selenium webdriver. An iframe is identified with a <iframe> tag in an html document. An iframe is an html document containing elements which resides inside another html document." }, { "code": null, "e": 1306, "s": 1267, "text": "Let us see a html document of a frame." }, { "code": null, "e": 1360, "s": 1306, "text": "The following methods help to switch between iframes−" }, { "code": null, "e": 1536, "s": 1360, "text": "switch_to.frame(args) – The frame index is put as an argument to the method. The starting index of iframe is 0.Syntax−driver.switch_to.frame(0), switching to the first iframe." }, { "code": null, "e": 1648, "s": 1536, "text": "switch_to.frame(args) – The frame index is put as an argument to the method. The starting index of iframe is 0." }, { "code": null, "e": 1656, "s": 1648, "text": "Syntax−" }, { "code": null, "e": 1714, "s": 1656, "text": "driver.switch_to.frame(0), switching to the first iframe." }, { "code": null, "e": 1870, "s": 1714, "text": "switch_to.frame(args) - The frame name or id is put as an argument to the method.Syntax−driver.switch_to.frame(\"nm\"), switching to the iframe with name nm." }, { "code": null, "e": 1952, "s": 1870, "text": "switch_to.frame(args) - The frame name or id is put as an argument to the method." }, { "code": null, "e": 1960, "s": 1952, "text": "Syntax−" }, { "code": null, "e": 2028, "s": 1960, "text": "driver.switch_to.frame(\"nm\"), switching to the iframe with name nm." }, { "code": null, "e": 2185, "s": 2028, "text": "switch_to.frame(args) - The frame webelement is put as an argument to the method.Syntax−driver.switch_to.frame(f),switching to the iframe with webelement f." }, { "code": null, "e": 2267, "s": 2185, "text": "switch_to.frame(args) - The frame webelement is put as an argument to the method." }, { "code": null, "e": 2275, "s": 2267, "text": "Syntax−" }, { "code": null, "e": 2344, "s": 2275, "text": "driver.switch_to.frame(f),switching to the iframe with webelement f." }, { "code": null, "e": 2460, "s": 2344, "text": "switch_to.default_content() – To shift to the parent page from the iframe.Syntax−driver.switch_to.default_content()" }, { "code": null, "e": 2535, "s": 2460, "text": "switch_to.default_content() – To shift to the parent page from the iframe." }, { "code": null, "e": 2543, "s": 2535, "text": "Syntax−" }, { "code": null, "e": 2578, "s": 2543, "text": "driver.switch_to.default_content()" }, { "code": null, "e": 3105, "s": 2578, "text": "from selenium import webdriver\ndriver = webdriver.Chrome(executable_path=\"C:\\\\chromedriver.exe\")\ndriver.get(\"https://the-internet.herokuapp.com\")\ndriver.find_element_by_link_text(\"Frames\").click()\ndriver.find_element_by_link_text(\"Nested Frames\").click()\n# switch to frame with name\ndriver.switch_to.frame(\"frame-bottom\")\n# identify element and get text method\ns = driver.find_element_by_xpath(\"//body\").text\nprint (\"Test inside frame: \" + s)\n# move out of frame to parent page\ndriver.switch_to.default_content()\ndriver.quit()" } ]
The Monty Hall Problem. Frequentist Simulations & Bayesian... | by Jeffrey Hanif Watson | Towards Data Science
GitHub Recently, I was asked to code a simulation of the Monty Hall game during a lesson on Bayesian statistics. I found it amusing that I was required to use a frequentist approach to probability for insight into what was explained as a Bayesian problem. I decided to Investigate further and come up with my own Bayesian understanding of what was going on. For those unfamiliar with this famous mental puzzle, allow me to lay out the rules and key assumptions of the game. The Monty Hall problem is named after the host of the Let’s Make A Deal game show and follows similar rules to that game. A contestant is presented with identical three doors, two of which contain goats, and one of which contains a car. The contestant is then asked to announce which door they chose, and one of the other doors is opened. Its contents are revealed to the player, and the host then asks the player if they would like to switch their choice of doors before the car is revealed. Whichever choice the player makes at this point, they win if the car is behind the door they chose. You should take a moment to think about what you would do in this situation, and take note of it. You may be surprised, or have some of your assumptions challenged, by the end of the article. According to wikipedia, although the Monty Hall problem was originally proposed in 1975, it gained notoriety in 1990 after being posed as a question to a columnist in Parade magazine. The columnist’s correct solution sparked a harsh (and largely incorrect) backlash. Before diving into the simulation code and mathematical solution, let’s lay out some key assumptions of the game: The car is placed at random. The player chooses their door at random. The host always opens a door (which contains a goat) that the player didn’t choose. Also, The host makes this choice at random if the player chose the door containing the car at the beginning of the game. The player is always given the choice to change doors after the door containing the goat is opened. These assumptions of random choice are used liberally in the simulation code, and also undergird the mathematical calculation later in the article. If these assumptions are changed, either the calculation would take on a different form, or the underlying probabilities would change. The Monty Hall problem wikipedia article discusses these scenarios in depth for those who wish to explore them more closely. The frequentist definition of the probability of an event is the limit of the relative frequency of that event over many trials. We will use this definition to simulate the probability of winning the Monty Hall game using python. This article assumes some basic knowledge of python coding, but aims to walk beginners through the steps of making the simulator. The code was written for use in a juypter notebook and begins by importing the necessary libraries and setting matplotlibto inline plotting: import numpy as npimport matplotlib.pyplot as plt%matplotlib inline Initializing the empty lists used in our for loop: keep_count = [] # count of simulated wins if door is keptchange_count = [] # count of simulated wins if door is changedP_keep = [] # proportion of keep wins after each game P_change = [] # proportion of a change wins after each game The main for loop (this will be explained piece by piece below): for i in range(number_of_games): doors = [1, 2, 3] # door labels # set the car door car_door = np.random.choice(range(1,4)) # set the player door player_door = np.random.choice(range(1,4)) # set the goats' doors given car door and player door goat_doors = [door for door in doors if\ door != car_door and door != player_door] # set the door Monty reveals given the goat doors revealed_door = np.random.choice(goat_doors) # set the change door given player door and revealed door changed_door = [door for door in doors if\ door != player_door and door\ != revealed_door] if player_door == car_door: # add one to keep wins keep_count.append(1) else: # keep one to losses keep_count.append(0) if changed_door == car_door: # add one to change wins change_count.append(1) else: # add one to change losses change_count.append(0) # proportion of keep wins in i games P_k_i = np.mean(keep_count[:i]) P_keep.append(P_k_i) # proportion of change wins i games P_c_i = np.mean(change_count[:i]) P_change.append(P_c_i) There is a bit going on in the loop, so we’ll break it down piece by piece for clarity. number_of_games will be an integer setting the number of simulations we want to run. For each game simulation, we start by randomly setting the car door value to 1, 2 or 3, using numpy’s random.choice(). for i in range(number_of_games): doors = [1, 2, 3] # door labels # set the car door car_door = np.random.choice(range(1,4)) Next, we set the player door value by the same method. # set the player doorplayer_door = np.random.choice(range(1,4)) We now set the two goat door values using a list comprehension with the values from the two previous steps. We are forming a list of two values that are neither the car door value nor the player door value. # set the goat doors given car door and player doorgoat_doors = [door for door in doors if\ door != car_door and door != player_door] Now, we set the revealed door value by choosing randomly from the two goat door values. # set the door Monty reveals given the goat doorsrevealed_door = np.random.choice(goat_doors) Next, we set the change door value according to the player door value and the revealed door value. # set the change door given player door and revealed doorchanged_door = [door for door in doors if\ door != player_door and door\ != revealed_door] Our next step is to count the number of wins and loses based on the values that were chosen above. We are just checking if either the player door value matches the car door value, or the change door value matches the car door value. From the code in the cell above we see that these are mutually exclusive numbers, so one of them has to match the car door value and win, while the other number loses. if player_door == car_door: # add one to keep wins keep_count.append(1)else: # add one to keep losses keep_count.append(0)if changed_door == car_door: # add one to change wins change_count.append(1)else: # add one to change losses change_count.append(0) Lastly, we calculate the relative frequencies of the wins, for both keep and change, at each iteration of the game we play. Recall that the frequentist definition of probability is the limit of the relative frequencies of an event over many trials. # proportion of keep wins in i gamesP_k_i = np.mean(keep_count[:i]) P_keep.append(P_k_i)# proportion of change wins i gamesP_c_i = np.mean(change_count[:i]) P_change.append(P_c_i) Running the code for 5000 games reveals the following: Simulated Probabilities:Probability of Winning if Door is Kept: 0.34Probability of Winning if Door is Changed: 0.66 We can see from the visualization that the relative frequencies level out to a limiting value fairly quickly (at around 1000 games) and remain steady. These are the probabilities for the keep and change strategies. At the end of the article I’ve wrapped the code above inside of a function monty_hall(number_of_games) that you can copy to run your own simulations and conveniently test the results. In the introduction of the article, when I asked what would your choice be in the Monty Hall game, what did you choose? Did the results surprise you? If they did, you are in esteemed company. During the 1990 controversy, many PhD level mathematicians and statisticians incorrectly calculated the probability of winning to be .5 for both keep and change. What is going on behind the scenes in this seemingly straightforward game that confounds amateur and expert alike? It’s going to take a Bayesian Approach to probability to untangle this mystery. The informal understanding of Bayesian probability is that the probability of an event is not some fixed, objective quantity. For Bayes, if you start with a prior assumption about the probability of an event, and subsequently receive new information that is pertinent to that event, you should update your understanding about the probability of the event. This notion is formalised in Bayes’ Theorem: P(A|B) = P(B|A)P(A)/P(B) Given a prior probability of an event A [P(A)], the posterior probability (updated by new information B) [ P(A|B)] is the prior probability [P(A) ] multiplied by the likelihood of the new information B, given that event A occurs [P(B|A)/P(B)]. Intuitively this approach makes sense, and we perform this type of reasoning every day while navigating our way through life, literally. While walking down a crowded street or driving a car, we are subconsciously assessing and re-assessing the likelihood of events based on a stream of constantly updating information. We are going to take this powerful technique of reasoning and apply it to the Monty Hall problem to see if we can get some clarity into what is going on. Given the conditions of The Monty Hall Problem: Let our events be as follows: A = The event that the car is behind the door chosen by the player. B = The event that a goat is revealed behind a door not chosen by the player. Then, P(A) = 1/3, since there are three doors and one door contains the car. P(A’) = 2/3, since P(A) + P(A’) = 1 by the definition of the complement of an event. P(B|A) = P(B|A’) = 1, since a goat behind a door the player hasn’t chosen is always revealed. Thus formally, P(B) = P(B|A)P(A) + P(B|A’)P(A’) = 1(1/3) + 1(2/3) = 1 So, P(A|B) = P(B|A)P(A)/P(B) = 1(1/3)/1 = 1/3 by Bayes’ Theorem. Since, P(A|B) + P(A’|B) = 1 by the definition of the complement of an event, we have P(A’|B) = 1 — P(A|B) = 1 — (1/3) = 2/3. We have just shown that the probability of the car not being behind the player’s original door is 2/3, so the optimal strategy in the Monty Hall game is to always change doors. This finding is in line with the simulations we ran above. It seems counter-intuitive that with two doors left in the game the probability for either would be anything other than 50–50, but we must take into account the information we gained when the host opened the door and revealed the goat. Since P(A|B) = P(A), we see that event B happening did nothing to update the probability of event A. P(A) remains 1/3, and the probability of A’ remains unchanged at 2/3 as well. However, the event A’ has been reduced to the car being behind the remaining door that the player didn’t pick at the start of the game. Thus, the probability that the alternate door contains the car has doubled from 1/3, at the start of the game, to 2/3 because of the new information provided by event B. Hopefully this post has helped you gain some insight into the Monty Hall Problem and some of math underlying it. I have wrapped the simulation code in a function to make it easy to run multiple tests very quickly. Be forewarned though, for very large numbers of games the function can take a fair bit of time to return a result. def monty_hall(number_of_games): """ A simulation of the monty hall game. Args: number_of_games: An integer n specifying the number of games to be simulated. Returns: Prints the simulated probabilities of winning for each strategy after n games, and a graph of the simulated probabilities of winning for each strategy over n games. """ keep_count = [] # count of simutated wins if door is kept change_count = [] # count of simulated wins if door is changed P_keep = [] # proportion of keep wins after each game P_change = [] # proportion of a change wins after each game for i in range(number_of_games): doors = [1, 2, 3] # door labels # set the car door car_door = np.random.choice(range(1,4)) # set the player door player_door = np.random.choice(range(1,4)) # set the goats' doors given car door and player door goat_doors = [door for door in doors if\ door != car_door and door != player_door] # set the door Monty reveals given the goat doors revealed_door = np.random.choice(goat_doors) # set the change door given player door and revealed door changed_door = [door for door in doors if\ door != player_door and door\ != revealed_door] if player_door == car_door: # add one to keep wins keep_count.append(1) else: # keep one to losses keep_count.append(0) if changed_door == car_door: # add one to change wins change_count.append(1) else: # add one to change losses change_count.append(0) # proportion of keep wins in i games P_k_i = np.mean(keep_count[:i]) P_keep.append(P_k_i) # proportion of change wins i games P_c_i = np.mean(change_count[:i]) P_change.append(P_c_i) # graphing the results fig, ax = plt.subplots(figsize=(10,5)) plt.plot(range(number_of_games), P_keep, label='Keep Door') plt.plot(range(number_of_games), P_change, label='Change Door') plt.ylabel('Probability of Winning', size=15) plt.xlabel('Number of Simulations', size=15) plt.title('Simulated Probabilities of Winning', size=15) plt.xticks(size = 12) plt.yticks(size = 12) plt.legend(prop={'size': 12}) # printing results print('Simulated Probabilities:') print(f'Probability of Winning if Door is Kept’:\t \t\ {round(np.mean(keep_count), 2)}') print(f'Probability of Winning if Door is Changed:\t\ {round(np.mean(change_count), 2)}')
[ { "code": null, "e": 178, "s": 171, "text": "GitHub" }, { "code": null, "e": 529, "s": 178, "text": "Recently, I was asked to code a simulation of the Monty Hall game during a lesson on Bayesian statistics. I found it amusing that I was required to use a frequentist approach to probability for insight into what was explained as a Bayesian problem. I decided to Investigate further and come up with my own Bayesian understanding of what was going on." }, { "code": null, "e": 1430, "s": 529, "text": "For those unfamiliar with this famous mental puzzle, allow me to lay out the rules and key assumptions of the game. The Monty Hall problem is named after the host of the Let’s Make A Deal game show and follows similar rules to that game. A contestant is presented with identical three doors, two of which contain goats, and one of which contains a car. The contestant is then asked to announce which door they chose, and one of the other doors is opened. Its contents are revealed to the player, and the host then asks the player if they would like to switch their choice of doors before the car is revealed. Whichever choice the player makes at this point, they win if the car is behind the door they chose. You should take a moment to think about what you would do in this situation, and take note of it. You may be surprised, or have some of your assumptions challenged, by the end of the article." }, { "code": null, "e": 1811, "s": 1430, "text": "According to wikipedia, although the Monty Hall problem was originally proposed in 1975, it gained notoriety in 1990 after being posed as a question to a columnist in Parade magazine. The columnist’s correct solution sparked a harsh (and largely incorrect) backlash. Before diving into the simulation code and mathematical solution, let’s lay out some key assumptions of the game:" }, { "code": null, "e": 1840, "s": 1811, "text": "The car is placed at random." }, { "code": null, "e": 1881, "s": 1840, "text": "The player chooses their door at random." }, { "code": null, "e": 2086, "s": 1881, "text": "The host always opens a door (which contains a goat) that the player didn’t choose. Also, The host makes this choice at random if the player chose the door containing the car at the beginning of the game." }, { "code": null, "e": 2186, "s": 2086, "text": "The player is always given the choice to change doors after the door containing the goat is opened." }, { "code": null, "e": 2594, "s": 2186, "text": "These assumptions of random choice are used liberally in the simulation code, and also undergird the mathematical calculation later in the article. If these assumptions are changed, either the calculation would take on a different form, or the underlying probabilities would change. The Monty Hall problem wikipedia article discusses these scenarios in depth for those who wish to explore them more closely." }, { "code": null, "e": 2954, "s": 2594, "text": "The frequentist definition of the probability of an event is the limit of the relative frequency of that event over many trials. We will use this definition to simulate the probability of winning the Monty Hall game using python. This article assumes some basic knowledge of python coding, but aims to walk beginners through the steps of making the simulator." }, { "code": null, "e": 3095, "s": 2954, "text": "The code was written for use in a juypter notebook and begins by importing the necessary libraries and setting matplotlibto inline plotting:" }, { "code": null, "e": 3163, "s": 3095, "text": "import numpy as npimport matplotlib.pyplot as plt%matplotlib inline" }, { "code": null, "e": 3214, "s": 3163, "text": "Initializing the empty lists used in our for loop:" }, { "code": null, "e": 3447, "s": 3214, "text": "keep_count = [] # count of simulated wins if door is keptchange_count = [] # count of simulated wins if door is changedP_keep = [] # proportion of keep wins after each game P_change = [] # proportion of a change wins after each game" }, { "code": null, "e": 3512, "s": 3447, "text": "The main for loop (this will be explained piece by piece below):" }, { "code": null, "e": 4835, "s": 3512, "text": "for i in range(number_of_games): doors = [1, 2, 3] # door labels # set the car door car_door = np.random.choice(range(1,4)) # set the player door player_door = np.random.choice(range(1,4)) # set the goats' doors given car door and player door goat_doors = [door for door in doors if\\ door != car_door and door != player_door] # set the door Monty reveals given the goat doors revealed_door = np.random.choice(goat_doors) # set the change door given player door and revealed door changed_door = [door for door in doors if\\ door != player_door and door\\ != revealed_door] if player_door == car_door: # add one to keep wins keep_count.append(1) else: # keep one to losses keep_count.append(0) if changed_door == car_door: # add one to change wins change_count.append(1) else: # add one to change losses change_count.append(0) # proportion of keep wins in i games P_k_i = np.mean(keep_count[:i]) P_keep.append(P_k_i) # proportion of change wins i games P_c_i = np.mean(change_count[:i]) P_change.append(P_c_i)" }, { "code": null, "e": 5127, "s": 4835, "text": "There is a bit going on in the loop, so we’ll break it down piece by piece for clarity. number_of_games will be an integer setting the number of simulations we want to run. For each game simulation, we start by randomly setting the car door value to 1, 2 or 3, using numpy’s random.choice()." }, { "code": null, "e": 5272, "s": 5127, "text": "for i in range(number_of_games): doors = [1, 2, 3] # door labels # set the car door car_door = np.random.choice(range(1,4))" }, { "code": null, "e": 5327, "s": 5272, "text": "Next, we set the player door value by the same method." }, { "code": null, "e": 5391, "s": 5327, "text": "# set the player doorplayer_door = np.random.choice(range(1,4))" }, { "code": null, "e": 5598, "s": 5391, "text": "We now set the two goat door values using a list comprehension with the values from the two previous steps. We are forming a list of two values that are neither the car door value nor the player door value." }, { "code": null, "e": 5745, "s": 5598, "text": "# set the goat doors given car door and player doorgoat_doors = [door for door in doors if\\ door != car_door and door != player_door]" }, { "code": null, "e": 5833, "s": 5745, "text": "Now, we set the revealed door value by choosing randomly from the two goat door values." }, { "code": null, "e": 5927, "s": 5833, "text": "# set the door Monty reveals given the goat doorsrevealed_door = np.random.choice(goat_doors)" }, { "code": null, "e": 6026, "s": 5927, "text": "Next, we set the change door value according to the player door value and the revealed door value." }, { "code": null, "e": 6204, "s": 6026, "text": "# set the change door given player door and revealed doorchanged_door = [door for door in doors if\\ door != player_door and door\\ != revealed_door]" }, { "code": null, "e": 6605, "s": 6204, "text": "Our next step is to count the number of wins and loses based on the values that were chosen above. We are just checking if either the player door value matches the car door value, or the change door value matches the car door value. From the code in the cell above we see that these are mutually exclusive numbers, so one of them has to match the car door value and win, while the other number loses." }, { "code": null, "e": 6919, "s": 6605, "text": "if player_door == car_door: # add one to keep wins keep_count.append(1)else: # add one to keep losses keep_count.append(0)if changed_door == car_door: # add one to change wins change_count.append(1)else: # add one to change losses change_count.append(0)" }, { "code": null, "e": 7168, "s": 6919, "text": "Lastly, we calculate the relative frequencies of the wins, for both keep and change, at each iteration of the game we play. Recall that the frequentist definition of probability is the limit of the relative frequencies of an event over many trials." }, { "code": null, "e": 7348, "s": 7168, "text": "# proportion of keep wins in i gamesP_k_i = np.mean(keep_count[:i]) P_keep.append(P_k_i)# proportion of change wins i gamesP_c_i = np.mean(change_count[:i]) P_change.append(P_c_i)" }, { "code": null, "e": 7403, "s": 7348, "text": "Running the code for 5000 games reveals the following:" }, { "code": null, "e": 7541, "s": 7403, "text": "Simulated Probabilities:Probability of Winning if Door is Kept:\t \t 0.34Probability of Winning if Door is Changed:\t 0.66" }, { "code": null, "e": 7940, "s": 7541, "text": "We can see from the visualization that the relative frequencies level out to a limiting value fairly quickly (at around 1000 games) and remain steady. These are the probabilities for the keep and change strategies. At the end of the article I’ve wrapped the code above inside of a function monty_hall(number_of_games) that you can copy to run your own simulations and conveniently test the results." }, { "code": null, "e": 8489, "s": 7940, "text": "In the introduction of the article, when I asked what would your choice be in the Monty Hall game, what did you choose? Did the results surprise you? If they did, you are in esteemed company. During the 1990 controversy, many PhD level mathematicians and statisticians incorrectly calculated the probability of winning to be .5 for both keep and change. What is going on behind the scenes in this seemingly straightforward game that confounds amateur and expert alike? It’s going to take a Bayesian Approach to probability to untangle this mystery." }, { "code": null, "e": 8890, "s": 8489, "text": "The informal understanding of Bayesian probability is that the probability of an event is not some fixed, objective quantity. For Bayes, if you start with a prior assumption about the probability of an event, and subsequently receive new information that is pertinent to that event, you should update your understanding about the probability of the event. This notion is formalised in Bayes’ Theorem:" }, { "code": null, "e": 8915, "s": 8890, "text": "P(A|B) = P(B|A)P(A)/P(B)" }, { "code": null, "e": 9159, "s": 8915, "text": "Given a prior probability of an event A [P(A)], the posterior probability (updated by new information B) [ P(A|B)] is the prior probability [P(A) ] multiplied by the likelihood of the new information B, given that event A occurs [P(B|A)/P(B)]." }, { "code": null, "e": 9632, "s": 9159, "text": "Intuitively this approach makes sense, and we perform this type of reasoning every day while navigating our way through life, literally. While walking down a crowded street or driving a car, we are subconsciously assessing and re-assessing the likelihood of events based on a stream of constantly updating information. We are going to take this powerful technique of reasoning and apply it to the Monty Hall problem to see if we can get some clarity into what is going on." }, { "code": null, "e": 9680, "s": 9632, "text": "Given the conditions of The Monty Hall Problem:" }, { "code": null, "e": 9710, "s": 9680, "text": "Let our events be as follows:" }, { "code": null, "e": 9778, "s": 9710, "text": "A = The event that the car is behind the door chosen by the player." }, { "code": null, "e": 9856, "s": 9778, "text": "B = The event that a goat is revealed behind a door not chosen by the player." }, { "code": null, "e": 9862, "s": 9856, "text": "Then," }, { "code": null, "e": 9933, "s": 9862, "text": "P(A) = 1/3, since there are three doors and one door contains the car." }, { "code": null, "e": 10018, "s": 9933, "text": "P(A’) = 2/3, since P(A) + P(A’) = 1 by the definition of the complement of an event." }, { "code": null, "e": 10112, "s": 10018, "text": "P(B|A) = P(B|A’) = 1, since a goat behind a door the player hasn’t chosen is always revealed." }, { "code": null, "e": 10127, "s": 10112, "text": "Thus formally," }, { "code": null, "e": 10182, "s": 10127, "text": "P(B) = P(B|A)P(A) + P(B|A’)P(A’) = 1(1/3) + 1(2/3) = 1" }, { "code": null, "e": 10186, "s": 10182, "text": "So," }, { "code": null, "e": 10247, "s": 10186, "text": "P(A|B) = P(B|A)P(A)/P(B) = 1(1/3)/1 = 1/3 by Bayes’ Theorem." }, { "code": null, "e": 10254, "s": 10247, "text": "Since," }, { "code": null, "e": 10324, "s": 10254, "text": "P(A|B) + P(A’|B) = 1 by the definition of the complement of an event," }, { "code": null, "e": 10372, "s": 10324, "text": "we have P(A’|B) = 1 — P(A|B) = 1 — (1/3) = 2/3." }, { "code": null, "e": 10844, "s": 10372, "text": "We have just shown that the probability of the car not being behind the player’s original door is 2/3, so the optimal strategy in the Monty Hall game is to always change doors. This finding is in line with the simulations we ran above. It seems counter-intuitive that with two doors left in the game the probability for either would be anything other than 50–50, but we must take into account the information we gained when the host opened the door and revealed the goat." }, { "code": null, "e": 11329, "s": 10844, "text": "Since P(A|B) = P(A), we see that event B happening did nothing to update the probability of event A. P(A) remains 1/3, and the probability of A’ remains unchanged at 2/3 as well. However, the event A’ has been reduced to the car being behind the remaining door that the player didn’t pick at the start of the game. Thus, the probability that the alternate door contains the car has doubled from 1/3, at the start of the game, to 2/3 because of the new information provided by event B." }, { "code": null, "e": 11658, "s": 11329, "text": "Hopefully this post has helped you gain some insight into the Monty Hall Problem and some of math underlying it. I have wrapped the simulation code in a function to make it easy to run multiple tests very quickly. Be forewarned though, for very large numbers of games the function can take a fair bit of time to return a result." } ]
card-title class in Bootstrap 4
Use the card-title class in Bootstrap 4 to set title for the card like the following example − The card title set above used the card-title class inside the card-body class. In addition, I have used the card-text class to set text inside the Bootstrap card as shown in the below give code snippet − <div class="card-body"> <h4 class="card-title">Company Locations</h4> <p class="card-text">Singapore</p> <p class="card-text">Malaysia</p> <p class="card-text">Australia</p> </div> You can try to run the following code to implement the card-title class − Live Demo <!DOCTYPE html> <html> <head> <title>Bootstrap Example</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script> </head> <body> <div class="container"> <h2>Location</h2> <div class="card"> <div class="card-body"> <h4 class="card-title">Company Locations</h4> <p class="card-text">Singapore</p> <p class="card-text">Malaysia</p> <p class="card-text">Australia</p> </div> </div> </div> </body> </html>
[ { "code": null, "e": 1157, "s": 1062, "text": "Use the card-title class in Bootstrap 4 to set title for the card like the following example −" }, { "code": null, "e": 1361, "s": 1157, "text": "The card title set above used the card-title class inside the card-body class. In addition, I have used the card-text class to set text inside the Bootstrap card as shown in the below give code snippet −" }, { "code": null, "e": 1550, "s": 1361, "text": "<div class=\"card-body\">\n <h4 class=\"card-title\">Company Locations</h4>\n <p class=\"card-text\">Singapore</p>\n <p class=\"card-text\">Malaysia</p>\n <p class=\"card-text\">Australia</p>\n</div>" }, { "code": null, "e": 1624, "s": 1550, "text": "You can try to run the following code to implement the card-title class −" }, { "code": null, "e": 1634, "s": 1624, "text": "Live Demo" }, { "code": null, "e": 2426, "s": 1634, "text": "<!DOCTYPE html>\n<html>\n <head>\n <title>Bootstrap Example</title>\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css\">\n <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js\"></script>\n </head>\n<body>\n\n<div class=\"container\">\n <h2>Location</h2>\n <div class=\"card\">\n <div class=\"card-body\">\n <h4 class=\"card-title\">Company Locations</h4>\n <p class=\"card-text\">Singapore</p>\n <p class=\"card-text\">Malaysia</p>\n <p class=\"card-text\">Australia</p>\n </div>\n </div>\n</div>\n\n</body>\n</html>" } ]
Express.js res.attachment() Function - GeeksforGeeks
19 Oct, 2021 The res.attachment() function is used to set the HTTP response Content-Disposition header field to ‘attachment’. If the name of the file is given as filename, then it sets the Content-Type based on the extension name through res.type() function and finally sets the Content-Disposition ‘filename = ‘ parameter.Syntax: res.attachment( [filename] ) Parameter: The filename parameter describes the the name of the file.Return Value: It returns an Object.Installation of express module: You can visit the link to Install express module. You can install this package by using this command. npm install express After installing the express module, you can check your express version in command prompt using the command. npm version express After that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command. node index.js Example 1: Filename: index.js javascript var express = require('express');var app = express();var PORT = 3000; // Without middlewareapp.get('/', function(req, res){ res.attachment('Hello.txt'); console.log(res.get('Content-Disposition'));}); app.listen(PORT, function(err){ if (err) console.log(err); console.log("Server listening on PORT", PORT);}); Place any file in root directory of the project which can be attached, like here we have used Hello.txt.Steps to run the program: The project structure will look like this: The project structure will look like this: Make sure you have installed express module using the following command: npm install express Run index.js file using below command: node index.js Output: Server listening on PORT 3000 Open your browser and go to http://localhost:3000/, now you can see the following output on your console: Server listening on PORT 3000 attachment; filename="Hello.txt" sweetyty Express.js Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Installation of Node.js on Linux How to update Node.js and NPM to next version ? Node.js fs.readFileSync() Method Node.js fs.readFile() Method How to update NPM ? 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": 29199, "s": 29171, "text": "\n19 Oct, 2021" }, { "code": null, "e": 29519, "s": 29199, "text": "The res.attachment() function is used to set the HTTP response Content-Disposition header field to ‘attachment’. If the name of the file is given as filename, then it sets the Content-Type based on the extension name through res.type() function and finally sets the Content-Disposition ‘filename = ‘ parameter.Syntax: " }, { "code": null, "e": 29548, "s": 29519, "text": "res.attachment( [filename] )" }, { "code": null, "e": 29686, "s": 29548, "text": "Parameter: The filename parameter describes the the name of the file.Return Value: It returns an Object.Installation of express module: " }, { "code": null, "e": 29790, "s": 29686, "text": "You can visit the link to Install express module. You can install this package by using this command. " }, { "code": null, "e": 29810, "s": 29790, "text": "npm install express" }, { "code": null, "e": 29921, "s": 29810, "text": "After installing the express module, you can check your express version in command prompt using the command. " }, { "code": null, "e": 29941, "s": 29921, "text": "npm version express" }, { "code": null, "e": 30078, "s": 29941, "text": "After that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command. " }, { "code": null, "e": 30092, "s": 30078, "text": "node index.js" }, { "code": null, "e": 30124, "s": 30092, "text": "Example 1: Filename: index.js " }, { "code": null, "e": 30135, "s": 30124, "text": "javascript" }, { "code": "var express = require('express');var app = express();var PORT = 3000; // Without middlewareapp.get('/', function(req, res){ res.attachment('Hello.txt'); console.log(res.get('Content-Disposition'));}); app.listen(PORT, function(err){ if (err) console.log(err); console.log(\"Server listening on PORT\", PORT);});", "e": 30457, "s": 30135, "text": null }, { "code": null, "e": 30589, "s": 30457, "text": "Place any file in root directory of the project which can be attached, like here we have used Hello.txt.Steps to run the program: " }, { "code": null, "e": 30634, "s": 30589, "text": "The project structure will look like this: " }, { "code": null, "e": 30679, "s": 30634, "text": "The project structure will look like this: " }, { "code": null, "e": 30753, "s": 30679, "text": "Make sure you have installed express module using the following command: " }, { "code": null, "e": 30773, "s": 30753, "text": "npm install express" }, { "code": null, "e": 30813, "s": 30773, "text": "Run index.js file using below command: " }, { "code": null, "e": 30827, "s": 30813, "text": "node index.js" }, { "code": null, "e": 30836, "s": 30827, "text": "Output: " }, { "code": null, "e": 30866, "s": 30836, "text": "Server listening on PORT 3000" }, { "code": null, "e": 30973, "s": 30866, "text": "Open your browser and go to http://localhost:3000/, now you can see the following output on your console: " }, { "code": null, "e": 31036, "s": 30973, "text": "Server listening on PORT 3000\nattachment; filename=\"Hello.txt\"" }, { "code": null, "e": 31045, "s": 31036, "text": "sweetyty" }, { "code": null, "e": 31056, "s": 31045, "text": "Express.js" }, { "code": null, "e": 31064, "s": 31056, "text": "Node.js" }, { "code": null, "e": 31081, "s": 31064, "text": "Web Technologies" }, { "code": null, "e": 31179, "s": 31081, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31188, "s": 31179, "text": "Comments" }, { "code": null, "e": 31201, "s": 31188, "text": "Old Comments" }, { "code": null, "e": 31234, "s": 31201, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 31282, "s": 31234, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 31315, "s": 31282, "text": "Node.js fs.readFileSync() Method" }, { "code": null, "e": 31344, "s": 31315, "text": "Node.js fs.readFile() Method" }, { "code": null, "e": 31364, "s": 31344, "text": "How to update NPM ?" }, { "code": null, "e": 31420, "s": 31364, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 31453, "s": 31420, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 31515, "s": 31453, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 31558, "s": 31515, "text": "How to fetch data from an API in ReactJS ?" } ]
Convert a list into a tuple in Python.
Sometimes during data analysis using Python, we may need to convert a given list into a tuple. Because some downstream code may be expecting to handle tuple and the current list has the values for that tuple. In this article we will see various ways to do that. This is a straight way of applying the tuple function directly on the list. The list elements get converted to a tuple. Live Demo listA = ["Mon",2,"Tue",3] # Given list print("Given list A: ", listA) # Use zip res = tuple(listA) # Result print("The tuple is : ",res) Running the above code gives us the following result − Given list A: ['Mon', 2, 'Tue', 3] The tuple is : ('Mon', 2, 'Tue', 3) We can apply the * operator we can expand the given list and put the result in a parentheses. listA = ["Mon",2,"Tue",3] # Given list print("Given list A: ", listA) # Use zip res = (* listA,) # Result print("The tuple is : ",res) Running the above code gives us the following result − Given list A: ['Mon', 2, 'Tue', 3] The tuple is : ('Mon', 2, 'Tue', 3)
[ { "code": null, "e": 1324, "s": 1062, "text": "Sometimes during data analysis using Python, we may need to convert a given list into a tuple. Because some downstream code may be expecting to handle tuple and the current list has the values for that tuple. In this article we will see various ways to do that." }, { "code": null, "e": 1444, "s": 1324, "text": "This is a straight way of applying the tuple function directly on the list. The list elements get converted to a tuple." }, { "code": null, "e": 1455, "s": 1444, "text": " Live Demo" }, { "code": null, "e": 1592, "s": 1455, "text": "listA = [\"Mon\",2,\"Tue\",3]\n# Given list\nprint(\"Given list A: \", listA)\n# Use zip\nres = tuple(listA)\n# Result\nprint(\"The tuple is : \",res)" }, { "code": null, "e": 1647, "s": 1592, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 1718, "s": 1647, "text": "Given list A: ['Mon', 2, 'Tue', 3]\nThe tuple is : ('Mon', 2, 'Tue', 3)" }, { "code": null, "e": 1812, "s": 1718, "text": "We can apply the * operator we can expand the given list and put the result in a parentheses." }, { "code": null, "e": 1947, "s": 1812, "text": "listA = [\"Mon\",2,\"Tue\",3]\n# Given list\nprint(\"Given list A: \", listA)\n# Use zip\nres = (* listA,)\n# Result\nprint(\"The tuple is : \",res)" }, { "code": null, "e": 2002, "s": 1947, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 2073, "s": 2002, "text": "Given list A: ['Mon', 2, 'Tue', 3]\nThe tuple is : ('Mon', 2, 'Tue', 3)" } ]
eDEX-UI Terminal for Windows, Mac and Linux - GeeksforGeeks
18 Jul, 2021 eDEX-UI is a fullscreen window, cross-platform terminal emulator, and system monitor which looks and feels like a sci-fi computer interface. It has fully featured terminal emulator Tabs, colors, mouse events, and other features. It supports curses and curses-like applications. It also monitors real-time-time systems (CPU, RAM, swap, processes). It provides optional sound effects made by a talented sound designer to get a Hollywood hacking vibe. It has a directory viewer that follows the CWD (current working directory) of the terminal. Provides advanced customization options, including themes and optional sound effects. Go to your search engine and search for eDEX-UI on Github and then download the binary file according to your OS. Fig 1: Downloading eDEX-UI. Then go to the download directory where the downloaded file is, right-click and select properties. Under properties, go to the permissions tab and check on execute option under owner to give executable permission to the file. Fig 2 : Giving executable permission to the file. Double click on the file and click on yes when asked to integrate eDEX-UI with your system. FIg 3: CLick on yes to integrate. In the image shown below, we can see that eDEX-UI is up and running. Fig 4: eDEX-UI is running. In the top-left corner, we can see the time. Below it there is the CPU usage. The bottom-left corner shows the file system, whereas the top-right shows the network status. To exit eDEX-UI, press ALT+F4. eDEX-UI comes with an integrated settings.json file that stores all your parameters. Setting.json file is located in userData/settings.json. You can access the settings.json file with the Ctrl+Shift+S keyboard shortcut or you can also access it by going to the user data folder in the file system and select settings.json file. Fig 5: Settings.json file. eDEX-UI comes with its own screen keyboard which creates flexibility for users with touch-screen devices. By default, the installed and active keyboard is QWERTY, but one can still modify it to meet one’s requirements. The layout is arranged systematically by default in rows and each row contains an array of keys which will be parsed in order by keyboard.class.js, i.e. from left to right. Fig 6: On-screen keyboard. One can customize it according to one’s needs or requirements. Fig 7: keyboard.class.js file To change theme, go to the theme folder of eDEX-UI. cd 'themes' Fig 6: Changing themes. Then select the theme you want from the bottom-left corner and click on it. Let’s select the red one. Fig 7: Red theme of eDEX-UI. The Matrix theme eDIX-UI is shown below. Fig 8: Matrix theme eDIX-UI. Tron theme eDIX-UI is shown below. Fig 9: Tron theme eDIX-UI. We can access the file system from the bottom-left as shown in the image below. Fig 10: FIle system Click settings.json, then modify themes. Fig 11: settings.json in bottom-left corner. Then, go to modify themes to customize your themes. Fig 12: Modifying themes. Below are some of the keyboard shortcuts which one can use to quickly access things. To exit eDEX-UI, press ALT+F4. Linux-Tools Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments scp command in Linux with Examples nohup Command in Linux with Examples mv command in Linux with examples Thread functions in C/C++ Docker - COPY Instruction chown command in Linux with Examples nslookup command in Linux with Examples SED command in Linux | Set 2 Named Pipe or FIFO with example C program uniq Command in LINUX with examples
[ { "code": null, "e": 24041, "s": 24013, "text": "\n18 Jul, 2021" }, { "code": null, "e": 24182, "s": 24041, "text": "eDEX-UI is a fullscreen window, cross-platform terminal emulator, and system monitor which looks and feels like a sci-fi computer interface." }, { "code": null, "e": 24270, "s": 24182, "text": "It has fully featured terminal emulator Tabs, colors, mouse events, and other features." }, { "code": null, "e": 24319, "s": 24270, "text": "It supports curses and curses-like applications." }, { "code": null, "e": 24388, "s": 24319, "text": "It also monitors real-time-time systems (CPU, RAM, swap, processes)." }, { "code": null, "e": 24490, "s": 24388, "text": "It provides optional sound effects made by a talented sound designer to get a Hollywood hacking vibe." }, { "code": null, "e": 24582, "s": 24490, "text": "It has a directory viewer that follows the CWD (current working directory) of the terminal." }, { "code": null, "e": 24668, "s": 24582, "text": "Provides advanced customization options, including themes and optional sound effects." }, { "code": null, "e": 24782, "s": 24668, "text": "Go to your search engine and search for eDEX-UI on Github and then download the binary file according to your OS." }, { "code": null, "e": 24810, "s": 24782, "text": "Fig 1: Downloading eDEX-UI." }, { "code": null, "e": 25036, "s": 24810, "text": "Then go to the download directory where the downloaded file is, right-click and select properties. Under properties, go to the permissions tab and check on execute option under owner to give executable permission to the file." }, { "code": null, "e": 25086, "s": 25036, "text": "Fig 2 : Giving executable permission to the file." }, { "code": null, "e": 25178, "s": 25086, "text": "Double click on the file and click on yes when asked to integrate eDEX-UI with your system." }, { "code": null, "e": 25212, "s": 25178, "text": "FIg 3: CLick on yes to integrate." }, { "code": null, "e": 25281, "s": 25212, "text": "In the image shown below, we can see that eDEX-UI is up and running." }, { "code": null, "e": 25308, "s": 25281, "text": "Fig 4: eDEX-UI is running." }, { "code": null, "e": 25480, "s": 25308, "text": "In the top-left corner, we can see the time. Below it there is the CPU usage. The bottom-left corner shows the file system, whereas the top-right shows the network status." }, { "code": null, "e": 25511, "s": 25480, "text": "To exit eDEX-UI, press ALT+F4." }, { "code": null, "e": 25839, "s": 25511, "text": "eDEX-UI comes with an integrated settings.json file that stores all your parameters. Setting.json file is located in userData/settings.json. You can access the settings.json file with the Ctrl+Shift+S keyboard shortcut or you can also access it by going to the user data folder in the file system and select settings.json file." }, { "code": null, "e": 25866, "s": 25839, "text": "Fig 5: Settings.json file." }, { "code": null, "e": 26258, "s": 25866, "text": "eDEX-UI comes with its own screen keyboard which creates flexibility for users with touch-screen devices. By default, the installed and active keyboard is QWERTY, but one can still modify it to meet one’s requirements. The layout is arranged systematically by default in rows and each row contains an array of keys which will be parsed in order by keyboard.class.js, i.e. from left to right." }, { "code": null, "e": 26285, "s": 26258, "text": "Fig 6: On-screen keyboard." }, { "code": null, "e": 26348, "s": 26285, "text": "One can customize it according to one’s needs or requirements." }, { "code": null, "e": 26378, "s": 26348, "text": "Fig 7: keyboard.class.js file" }, { "code": null, "e": 26430, "s": 26378, "text": "To change theme, go to the theme folder of eDEX-UI." }, { "code": null, "e": 26442, "s": 26430, "text": "cd 'themes'" }, { "code": null, "e": 26466, "s": 26442, "text": "Fig 6: Changing themes." }, { "code": null, "e": 26568, "s": 26466, "text": "Then select the theme you want from the bottom-left corner and click on it. Let’s select the red one." }, { "code": null, "e": 26597, "s": 26568, "text": "Fig 7: Red theme of eDEX-UI." }, { "code": null, "e": 26638, "s": 26597, "text": "The Matrix theme eDIX-UI is shown below." }, { "code": null, "e": 26667, "s": 26638, "text": "Fig 8: Matrix theme eDIX-UI." }, { "code": null, "e": 26702, "s": 26667, "text": "Tron theme eDIX-UI is shown below." }, { "code": null, "e": 26729, "s": 26702, "text": "Fig 9: Tron theme eDIX-UI." }, { "code": null, "e": 26809, "s": 26729, "text": "We can access the file system from the bottom-left as shown in the image below." }, { "code": null, "e": 26829, "s": 26809, "text": "Fig 10: FIle system" }, { "code": null, "e": 26870, "s": 26829, "text": "Click settings.json, then modify themes." }, { "code": null, "e": 26915, "s": 26870, "text": "Fig 11: settings.json in bottom-left corner." }, { "code": null, "e": 26967, "s": 26915, "text": "Then, go to modify themes to customize your themes." }, { "code": null, "e": 26993, "s": 26967, "text": "Fig 12: Modifying themes." }, { "code": null, "e": 27078, "s": 26993, "text": "Below are some of the keyboard shortcuts which one can use to quickly access things." }, { "code": null, "e": 27109, "s": 27078, "text": "To exit eDEX-UI, press ALT+F4." }, { "code": null, "e": 27121, "s": 27109, "text": "Linux-Tools" }, { "code": null, "e": 27132, "s": 27121, "text": "Linux-Unix" }, { "code": null, "e": 27230, "s": 27132, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27239, "s": 27230, "text": "Comments" }, { "code": null, "e": 27252, "s": 27239, "text": "Old Comments" }, { "code": null, "e": 27287, "s": 27252, "text": "scp command in Linux with Examples" }, { "code": null, "e": 27324, "s": 27287, "text": "nohup Command in Linux with Examples" }, { "code": null, "e": 27358, "s": 27324, "text": "mv command in Linux with examples" }, { "code": null, "e": 27384, "s": 27358, "text": "Thread functions in C/C++" }, { "code": null, "e": 27410, "s": 27384, "text": "Docker - COPY Instruction" }, { "code": null, "e": 27447, "s": 27410, "text": "chown command in Linux with Examples" }, { "code": null, "e": 27487, "s": 27447, "text": "nslookup command in Linux with Examples" }, { "code": null, "e": 27516, "s": 27487, "text": "SED command in Linux | Set 2" }, { "code": null, "e": 27558, "s": 27516, "text": "Named Pipe or FIFO with example C program" } ]
Print elements that can be added to form a given sum - GeeksforGeeks
13 Apr, 2021 Given an array arr[] of positive integers and a sum, the task is to print the elements that will be included to get the given sum. Note: Consider the elements in the form of queue i.e. Elements to be added from starting and up to the sum of elements is lesser or becomes equal to the given sum.Also, it is not necessary that the sum of array elements should be equal to the given sum. Consider the elements in the form of queue i.e. Elements to be added from starting and up to the sum of elements is lesser or becomes equal to the given sum. Also, it is not necessary that the sum of array elements should be equal to the given sum. As the task is to check that element can be included or not. Examples: Input: arr[] = {3, 5, 3, 2, 1}, Sum = 10 Output: 3 5 2 By adding 3, 5 and 3, sum becomes 11 so remove last 3. Then on adding 2, sum becomes 10. So no other element needs to be added. Input: arr[] = {7, 10, 6, 4}, Sum = 12 Output: 7 4 As, 7+10 and 7+6 sums to a higher value than 12 but 7+4 = 11 which is smaller than 12. So, 7 and 4 can be included Approach: Check if on adding the current element, the sum is less than the given sum.If yes, the add it.Else go to next element and repeat the same until their sum is less than or equals to the given sum. Check if on adding the current element, the sum is less than the given sum. If yes, the add it. Else go to next element and repeat the same until their sum is less than or equals to the given sum. Below is the implementation of above approach: C++ Java Python3 C# PHP Javascript // C++ implementation of above approach#include <bits/stdc++.h>using namespace std; // Function that finds whether an element// will be included or notvoid includeElement(int a[], int n, int sum){ for (int i = 0; i < n; i++) { // Check if the current element // will be incuded or not if ((sum - a[i]) >= 0) { sum = sum - a[i]; cout << a[i]<< " "; } }} // Driver Codeint main(){ int arr[] = { 3, 5, 3, 2, 1 }; int n = sizeof(arr) / sizeof(arr[0]); int sum = 10; includeElement(arr, n, sum); return 0;} // Java implementation// of above approachclass GFG{ // Function that finds whether// an element will be included// or notstatic void includeElement(int a[], int n, int sum){ for (int i = 0; i < n; i++) { // Check if the current element // will be included or not if ((sum - a[i]) >= 0) { sum = sum - a[i]; System.out.print(a[i] + " "); } }} // Driver codepublic static void main(String[] args){ int arr[] = { 3, 5, 3, 2, 1 }; int n = arr.length; int sum = 10; includeElement(arr, n, sum);}} // This code is contributed by Bilal # Python 3 implementation of above approach # Function that finds whether an element# will be included or notdef includeElement(a, n, sum) : for i in range(n) : # Check if the current element # will be incuded or not if sum - a[i] >= 0 : sum = sum - a[i] print(a[i],end = " ") # Driver codeif __name__ == "__main__" : arr = [ 3, 5, 3, 2, 1] n = len(arr) sum = 10 includeElement(arr, n, sum) # This code is contributed by ANKITRAI1 // C# implementation// of above approachusing System; class GFG{// Function that finds whether// an element will be included// or notstatic void includeElement(int[] a, int n, int sum){ for (int i = 0; i < n; i++) { // Check if the current element // will be included or not if ((sum - a[i]) >= 0) { sum = sum - a[i]; Console.Write(a[i] + " "); } }} // Driver codestatic void Main(){ int[] arr = new int[]{ 3, 5, 3, 2, 1 }; int n = arr.Length; int sum = 10; includeElement(arr, n, sum);}} // This code is contributed by mits <?php// PHP implementation of above approach // Function that finds whether an// element will be included or notfunction includeElement(&$a, $n, $sum){ for ($i = 0; $i < $n; $i++) { // Check if the current element // will be incuded or not if (($sum - $a[$i]) >= 0) { $sum = $sum - $a[$i]; echo $a[$i] . " "; } }} // Driver Code$arr = array( 3, 5, 3, 2, 1 );$n = sizeof($arr);$sum = 10; includeElement($arr, $n, $sum); // This code is contributed// by ChitraNayal?> <script> // Javascript implementation of above approach // Function that finds whether an element// will be included or notfunction includeElement(a, n, sum){ for(var i = 0; i < n; i++) { // Check if the current element // will be incuded or not if ((sum - a[i]) >= 0) { sum = sum - a[i]; document.write( a[i] + " "); } }} // Driver Codevar arr = [ 3, 5, 3, 2, 1 ];var n = arr.length;var sum = 10; includeElement(arr, n, sum); // This code is contributed by itsok </script> 3 5 2 bilal-hungund ankthon Mithun Kumar ukasp itsok Arrays School Programming Arrays Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Stack Data Structure (Introduction and Program) Top 50 Array Coding Problems for Interviews Introduction to Arrays Multidimensional Arrays in Java Linear Search Python Dictionary Reverse a string in Java Inheritance in C++ C++ Classes and Objects Constructors in C++
[ { "code": null, "e": 24473, "s": 24445, "text": "\n13 Apr, 2021" }, { "code": null, "e": 24611, "s": 24473, "text": "Given an array arr[] of positive integers and a sum, the task is to print the elements that will be included to get the given sum. Note: " }, { "code": null, "e": 24859, "s": 24611, "text": "Consider the elements in the form of queue i.e. Elements to be added from starting and up to the sum of elements is lesser or becomes equal to the given sum.Also, it is not necessary that the sum of array elements should be equal to the given sum." }, { "code": null, "e": 25017, "s": 24859, "text": "Consider the elements in the form of queue i.e. Elements to be added from starting and up to the sum of elements is lesser or becomes equal to the given sum." }, { "code": null, "e": 25108, "s": 25017, "text": "Also, it is not necessary that the sum of array elements should be equal to the given sum." }, { "code": null, "e": 25169, "s": 25108, "text": "As the task is to check that element can be included or not." }, { "code": null, "e": 25181, "s": 25169, "text": "Examples: " }, { "code": null, "e": 25365, "s": 25181, "text": "Input: arr[] = {3, 5, 3, 2, 1}, Sum = 10 Output: 3 5 2 By adding 3, 5 and 3, sum becomes 11 so remove last 3. Then on adding 2, sum becomes 10. So no other element needs to be added. " }, { "code": null, "e": 25533, "s": 25365, "text": "Input: arr[] = {7, 10, 6, 4}, Sum = 12 Output: 7 4 As, 7+10 and 7+6 sums to a higher value than 12 but 7+4 = 11 which is smaller than 12. So, 7 and 4 can be included " }, { "code": null, "e": 25545, "s": 25533, "text": "Approach: " }, { "code": null, "e": 25740, "s": 25545, "text": "Check if on adding the current element, the sum is less than the given sum.If yes, the add it.Else go to next element and repeat the same until their sum is less than or equals to the given sum." }, { "code": null, "e": 25816, "s": 25740, "text": "Check if on adding the current element, the sum is less than the given sum." }, { "code": null, "e": 25836, "s": 25816, "text": "If yes, the add it." }, { "code": null, "e": 25937, "s": 25836, "text": "Else go to next element and repeat the same until their sum is less than or equals to the given sum." }, { "code": null, "e": 25985, "s": 25937, "text": "Below is the implementation of above approach: " }, { "code": null, "e": 25989, "s": 25985, "text": "C++" }, { "code": null, "e": 25994, "s": 25989, "text": "Java" }, { "code": null, "e": 26002, "s": 25994, "text": "Python3" }, { "code": null, "e": 26005, "s": 26002, "text": "C#" }, { "code": null, "e": 26009, "s": 26005, "text": "PHP" }, { "code": null, "e": 26020, "s": 26009, "text": "Javascript" }, { "code": "// C++ implementation of above approach#include <bits/stdc++.h>using namespace std; // Function that finds whether an element// will be included or notvoid includeElement(int a[], int n, int sum){ for (int i = 0; i < n; i++) { // Check if the current element // will be incuded or not if ((sum - a[i]) >= 0) { sum = sum - a[i]; cout << a[i]<< \" \"; } }} // Driver Codeint main(){ int arr[] = { 3, 5, 3, 2, 1 }; int n = sizeof(arr) / sizeof(arr[0]); int sum = 10; includeElement(arr, n, sum); return 0;}", "e": 26595, "s": 26020, "text": null }, { "code": "// Java implementation// of above approachclass GFG{ // Function that finds whether// an element will be included// or notstatic void includeElement(int a[], int n, int sum){ for (int i = 0; i < n; i++) { // Check if the current element // will be included or not if ((sum - a[i]) >= 0) { sum = sum - a[i]; System.out.print(a[i] + \" \"); } }} // Driver codepublic static void main(String[] args){ int arr[] = { 3, 5, 3, 2, 1 }; int n = arr.length; int sum = 10; includeElement(arr, n, sum);}} // This code is contributed by Bilal", "e": 27230, "s": 26595, "text": null }, { "code": "# Python 3 implementation of above approach # Function that finds whether an element# will be included or notdef includeElement(a, n, sum) : for i in range(n) : # Check if the current element # will be incuded or not if sum - a[i] >= 0 : sum = sum - a[i] print(a[i],end = \" \") # Driver codeif __name__ == \"__main__\" : arr = [ 3, 5, 3, 2, 1] n = len(arr) sum = 10 includeElement(arr, n, sum) # This code is contributed by ANKITRAI1", "e": 27748, "s": 27230, "text": null }, { "code": "// C# implementation// of above approachusing System; class GFG{// Function that finds whether// an element will be included// or notstatic void includeElement(int[] a, int n, int sum){ for (int i = 0; i < n; i++) { // Check if the current element // will be included or not if ((sum - a[i]) >= 0) { sum = sum - a[i]; Console.Write(a[i] + \" \"); } }} // Driver codestatic void Main(){ int[] arr = new int[]{ 3, 5, 3, 2, 1 }; int n = arr.Length; int sum = 10; includeElement(arr, n, sum);}} // This code is contributed by mits", "e": 28379, "s": 27748, "text": null }, { "code": "<?php// PHP implementation of above approach // Function that finds whether an// element will be included or notfunction includeElement(&$a, $n, $sum){ for ($i = 0; $i < $n; $i++) { // Check if the current element // will be incuded or not if (($sum - $a[$i]) >= 0) { $sum = $sum - $a[$i]; echo $a[$i] . \" \"; } }} // Driver Code$arr = array( 3, 5, 3, 2, 1 );$n = sizeof($arr);$sum = 10; includeElement($arr, $n, $sum); // This code is contributed// by ChitraNayal?>", "e": 28911, "s": 28379, "text": null }, { "code": "<script> // Javascript implementation of above approach // Function that finds whether an element// will be included or notfunction includeElement(a, n, sum){ for(var i = 0; i < n; i++) { // Check if the current element // will be incuded or not if ((sum - a[i]) >= 0) { sum = sum - a[i]; document.write( a[i] + \" \"); } }} // Driver Codevar arr = [ 3, 5, 3, 2, 1 ];var n = arr.length;var sum = 10; includeElement(arr, n, sum); // This code is contributed by itsok </script>", "e": 29460, "s": 28911, "text": null }, { "code": null, "e": 29466, "s": 29460, "text": "3 5 2" }, { "code": null, "e": 29482, "s": 29468, "text": "bilal-hungund" }, { "code": null, "e": 29490, "s": 29482, "text": "ankthon" }, { "code": null, "e": 29503, "s": 29490, "text": "Mithun Kumar" }, { "code": null, "e": 29509, "s": 29503, "text": "ukasp" }, { "code": null, "e": 29515, "s": 29509, "text": "itsok" }, { "code": null, "e": 29522, "s": 29515, "text": "Arrays" }, { "code": null, "e": 29541, "s": 29522, "text": "School Programming" }, { "code": null, "e": 29548, "s": 29541, "text": "Arrays" }, { "code": null, "e": 29646, "s": 29548, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29655, "s": 29646, "text": "Comments" }, { "code": null, "e": 29668, "s": 29655, "text": "Old Comments" }, { "code": null, "e": 29716, "s": 29668, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 29760, "s": 29716, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 29783, "s": 29760, "text": "Introduction to Arrays" }, { "code": null, "e": 29815, "s": 29783, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 29829, "s": 29815, "text": "Linear Search" }, { "code": null, "e": 29847, "s": 29829, "text": "Python Dictionary" }, { "code": null, "e": 29872, "s": 29847, "text": "Reverse a string in Java" }, { "code": null, "e": 29891, "s": 29872, "text": "Inheritance in C++" }, { "code": null, "e": 29915, "s": 29891, "text": "C++ Classes and Objects" } ]
Circle Generation Algorithm
Drawing a circle on the screen is a little complex than drawing a line. There are two popular algorithms for generating a circle − Bresenham’s Algorithm and Midpoint Circle Algorithm. These algorithms are based on the idea of determining the subsequent points required to draw the circle. Let us discuss the algorithms in detail − The equation of circle is X2+Y2=r2, where r is radius. We cannot display a continuous arc on the raster display. Instead, we have to choose the nearest pixel position to complete the arc. From the following illustration, you can see that we have put the pixel at X,Y location and now need to decide where to put the next pixel − at N X+1,Y or at S X+1,Y−1. This can be decided by the decision parameter d. If d <= 0, then NX+1,Y is to be chosen as next pixel. If d > 0, then SX+1,Y−1 is to be chosen as the next pixel. Step 1 − Get the coordinates of the center of the circle and radius, and store them in x, y, and R respectively. Set P=0 and Q=R. Step 2 − Set decision parameter D = 3 – 2R. Step 3 − Repeat through step-8 while P ≤ Q. Step 4 − Call Draw Circle X,Y,P,Q. Step 5 − Increment the value of P. Step 6 − If D < 0 then D = D + 4P + 6. Step 7 − Else Set R = R - 1, D = D + 4P−Q + 10. Step 8 − Call Draw Circle X,Y,P,Q. Draw Circle Method(X, Y, P, Q). Call Putpixel (X + P, Y + Q). Call Putpixel (X - P, Y + Q). Call Putpixel (X + P, Y - Q). Call Putpixel (X - P, Y - Q). Call Putpixel (X + Q, Y + P). Call Putpixel (X - Q, Y + P). Call Putpixel (X + Q, Y - P). Call Putpixel (X - Q, Y - P). Step 1 − Input radius r and circle center (xc,yc) and obtain the first point on the circumference of the circle centered on the origin as (x0, y0) = (0, r) Step 2 − Calculate the initial value of decision parameter as P0 = 5/4 – r Seethefollowingdescriptionforsimplificationofthisequation. f(x, y) = x2 + y2 - r2 = 0 f(xi - 1/2 + e, yi + 1) = (xi - 1/2 + e)2 + (yi + 1)2 - r2 = (xi- 1/2)2 + (yi + 1)2 - r2 + 2(xi - 1/2)e + e2 = f(xi - 1/2, yi + 1) + 2(xi - 1/2)e + e2 = 0 Let di = f(xi - 1/2, yi + 1) = -2(xi - 1/2)e - e2 Thus, If e < 0 then di > 0 so choose point S = (xi - 1, yi + 1). di+1 = f(xi - 1 - 1/2, yi + 1 + 1) = ((xi - 1/2) - 1)2 + ((yi + 1) + 1)2 - r2 = di - 2(xi - 1) + 2(yi + 1) + 1 = di + 2(yi + 1 - xi + 1) + 1 If e >= 0 then di <= 0 so choose point T = (xi, yi + 1) di+1 = f(xi - 1/2, yi + 1 + 1) = di + 2yi+1 + 1 The initial value of di is d0 = f(r - 1/2, 0 + 1) = (r - 1/2)2 + 12 - r2 = 5/4 - r {1-r can be used if r is an integer} When point S = (xi - 1, yi + 1) is chosen then di+1 = di + -2xi+1 + 2yi+1 + 1 When point T = (xi, yi + 1) is chosen then di+1 = di + 2yi+1 + 1 Step 3 − At each XK position starting at K=0, perform the following test − If PK < 0 then next point on circle (0,0) is (XK+1,YK) and PK+1 = PK + 2XK+1 + 1 Else PK+1 = PK + 2XK+1 + 1 – 2YK+1 Where, 2XK+1 = 2XK+2 and 2YK+1 = 2YK-2. Step 4 − Determine the symmetry points in other seven octants. Step 5 − Move each calculate pixel position X,Y onto the circular path centered on (XC,YC) and plot the coordinate values. X = X + XC, Y = Y + YC Step 6 − Repeat step-3 through 5 until X >= Y. 107 Lectures 13.5 hours Arnab Chakraborty 106 Lectures 8 hours Arnab Chakraborty 99 Lectures 6 hours Arnab Chakraborty 46 Lectures 2.5 hours Shweta 70 Lectures 9 hours Abhilash Nelson 52 Lectures 7 hours Abhishek And Pukhraj Print Add Notes Bookmark this page
[ { "code": null, "e": 2250, "s": 1919, "text": "Drawing a circle on the screen is a little complex than drawing a line. There are two popular algorithms for generating a circle − Bresenham’s Algorithm and Midpoint Circle Algorithm. These algorithms are based on the idea of determining the subsequent points required to draw the circle. Let us discuss the algorithms in detail −" }, { "code": null, "e": 2305, "s": 2250, "text": "The equation of circle is X2+Y2=r2, where r is radius." }, { "code": null, "e": 2438, "s": 2305, "text": "We cannot display a continuous arc on the raster display. Instead, we have to choose the nearest pixel position to complete the arc." }, { "code": null, "e": 2607, "s": 2438, "text": "From the following illustration, you can see that we have put the pixel at X,Y location and now need to decide where to put the next pixel − at N X+1,Y or at S X+1,Y−1." }, { "code": null, "e": 2656, "s": 2607, "text": "This can be decided by the decision parameter d." }, { "code": null, "e": 2710, "s": 2656, "text": "If d <= 0, then NX+1,Y is to be chosen as next pixel." }, { "code": null, "e": 2769, "s": 2710, "text": "If d > 0, then SX+1,Y−1 is to be chosen as the next pixel." }, { "code": null, "e": 2899, "s": 2769, "text": "Step 1 − Get the coordinates of the center of the circle and radius, and store them in x, y, and R respectively. Set P=0 and Q=R." }, { "code": null, "e": 2943, "s": 2899, "text": "Step 2 − Set decision parameter D = 3 – 2R." }, { "code": null, "e": 2987, "s": 2943, "text": "Step 3 − Repeat through step-8 while P ≤ Q." }, { "code": null, "e": 3022, "s": 2987, "text": "Step 4 − Call Draw Circle X,Y,P,Q." }, { "code": null, "e": 3057, "s": 3022, "text": "Step 5 − Increment the value of P." }, { "code": null, "e": 3096, "s": 3057, "text": "Step 6 − If D < 0 then D = D + 4P + 6." }, { "code": null, "e": 3144, "s": 3096, "text": "Step 7 − Else Set R = R - 1, D = D + 4P−Q + 10." }, { "code": null, "e": 3179, "s": 3144, "text": "Step 8 − Call Draw Circle X,Y,P,Q." }, { "code": null, "e": 3453, "s": 3179, "text": "Draw Circle Method(X, Y, P, Q).\n\nCall Putpixel (X + P, Y + Q).\nCall Putpixel (X - P, Y + Q).\nCall Putpixel (X + P, Y - Q).\nCall Putpixel (X - P, Y - Q).\nCall Putpixel (X + Q, Y + P).\nCall Putpixel (X - Q, Y + P).\nCall Putpixel (X + Q, Y - P).\nCall Putpixel (X - Q, Y - P).\n" }, { "code": null, "e": 3591, "s": 3453, "text": "Step 1 − Input radius r and circle center (xc,yc) and obtain the first point on the circumference of the circle centered on the origin as" }, { "code": null, "e": 3610, "s": 3591, "text": "(x0, y0) = (0, r)\n" }, { "code": null, "e": 3672, "s": 3610, "text": "Step 2 − Calculate the initial value of decision parameter as" }, { "code": null, "e": 3744, "s": 3672, "text": "P0 = 5/4 – r Seethefollowingdescriptionforsimplificationofthisequation." }, { "code": null, "e": 3952, "s": 3744, "text": "f(x, y) = x2 + y2 - r2 = 0\n\nf(xi - 1/2 + e, yi + 1)\n = (xi - 1/2 + e)2 + (yi + 1)2 - r2 \n = (xi- 1/2)2 + (yi + 1)2 - r2 + 2(xi - 1/2)e + e2\n = f(xi - 1/2, yi + 1) + 2(xi - 1/2)e + e2 = 0" }, { "code": null, "e": 4635, "s": 3952, "text": "Let di = f(xi - 1/2, yi + 1) = -2(xi - 1/2)e - e2\nThus,\n\nIf e < 0 then di > 0 so choose point S = (xi - 1, yi + 1).\ndi+1 = f(xi - 1 - 1/2, yi + 1 + 1) = ((xi - 1/2) - 1)2 + ((yi + 1) + 1)2 - r2\n = di - 2(xi - 1) + 2(yi + 1) + 1\n = di + 2(yi + 1 - xi + 1) + 1\n\t\t \nIf e >= 0 then di <= 0 so choose point T = (xi, yi + 1)\n di+1 = f(xi - 1/2, yi + 1 + 1)\n = di + 2yi+1 + 1\n\t\t \nThe initial value of di is\n d0 = f(r - 1/2, 0 + 1) = (r - 1/2)2 + 12 - r2\n = 5/4 - r {1-r can be used if r is an integer}\n\t\t\nWhen point S = (xi - 1, yi + 1) is chosen then\n di+1 = di + -2xi+1 + 2yi+1 + 1\n\t\nWhen point T = (xi, yi + 1) is chosen then\n di+1 = di + 2yi+1 + 1" }, { "code": null, "e": 4710, "s": 4635, "text": "Step 3 − At each XK position starting at K=0, perform the following test −" }, { "code": null, "e": 4874, "s": 4710, "text": "If PK < 0 then next point on circle (0,0) is (XK+1,YK) and\n PK+1 = PK + 2XK+1 + 1\nElse\n PK+1 = PK + 2XK+1 + 1 – 2YK+1\n\t\nWhere, 2XK+1 = 2XK+2 and 2YK+1 = 2YK-2." }, { "code": null, "e": 4937, "s": 4874, "text": "Step 4 − Determine the symmetry points in other seven octants." }, { "code": null, "e": 5060, "s": 4937, "text": "Step 5 − Move each calculate pixel position X,Y onto the circular path centered on (XC,YC) and plot the coordinate values." }, { "code": null, "e": 5086, "s": 5060, "text": "X = X + XC, Y = Y + YC\n" }, { "code": null, "e": 5133, "s": 5086, "text": "Step 6 − Repeat step-3 through 5 until X >= Y." }, { "code": null, "e": 5170, "s": 5133, "text": "\n 107 Lectures \n 13.5 hours \n" }, { "code": null, "e": 5189, "s": 5170, "text": " Arnab Chakraborty" }, { "code": null, "e": 5223, "s": 5189, "text": "\n 106 Lectures \n 8 hours \n" }, { "code": null, "e": 5242, "s": 5223, "text": " Arnab Chakraborty" }, { "code": null, "e": 5275, "s": 5242, "text": "\n 99 Lectures \n 6 hours \n" }, { "code": null, "e": 5294, "s": 5275, "text": " Arnab Chakraborty" }, { "code": null, "e": 5329, "s": 5294, "text": "\n 46 Lectures \n 2.5 hours \n" }, { "code": null, "e": 5337, "s": 5329, "text": " Shweta" }, { "code": null, "e": 5370, "s": 5337, "text": "\n 70 Lectures \n 9 hours \n" }, { "code": null, "e": 5387, "s": 5370, "text": " Abhilash Nelson" }, { "code": null, "e": 5420, "s": 5387, "text": "\n 52 Lectures \n 7 hours \n" }, { "code": null, "e": 5442, "s": 5420, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 5449, "s": 5442, "text": " Print" }, { "code": null, "e": 5460, "s": 5449, "text": " Add Notes" } ]
A GIS Pipeline for LIDAR Point Cloud Feature Extraction | by Batran | Towards Data Science
In this article, I will walk you through extracting features from LIDAR point cloud in an automated manner. LIDAR point cloud data is a collection of points that describe a surface or an object. Each point is described with x, y, z coordinates and in some cases is associated with additional attributes such as a classification of the point. LIDAR data is used to extract accurately geo-referenced vector features such as buildings, roads, trees. To realize that there are two main steps as in [1]: Classification: assign a class to each point in the point cloud dataset. One way is using the PointCNN neural network given that there is sufficient training data. The output is a class for each data point.GIS pipeline: extracting relevant features from classified point cloud data in a usable format. In addition to extraction, generating attributes information to the extracted features such as object height, object surface area, centroid latitude/longitude, proximity to other features (e..g how far from the nearest road), and others. Classification: assign a class to each point in the point cloud dataset. One way is using the PointCNN neural network given that there is sufficient training data. The output is a class for each data point. GIS pipeline: extracting relevant features from classified point cloud data in a usable format. In addition to extraction, generating attributes information to the extracted features such as object height, object surface area, centroid latitude/longitude, proximity to other features (e..g how far from the nearest road), and others. This article will expand on point no (2) focusing on the Automated GIS feature extraction assuming the data is already classified and each data point is assigned a class. This section will dive into data acquisition, preprocessing, and visual inspection. It’s an often important step before starting science or development work. There are many services that offer to download LIDAR data. For sample data acquisition to go along with this tutorial, we will download a LIDAR dataset from [3]. When working with geospatial data, it’s always important to know what is the spatial reference system of the dataset. The spatial reference system for this tile is EPSG:7415 [4]. The definition of spatial reference system according to Wikipedia is “A spatial reference system or coordinate reference system is a coordinate-based local, regional or global system used to locate geographical entities.” The server to download the data is not very fast, so downloading may take some time. It took me a few hours to download the dataset, so at the end of this section, I will share a link for downloading a preprocessed version from my google drive. The downloaded file is in Laz format LAZ format is a lossless compression of LIDAR data. It can compress original Las files to only 7 to 25 percent of their size. The speed is one to three million points per second [5]. The downloaded file size is 2.2 GB. To decompress LAZ files to the original Las one option is to use pylas. The extracted Las file is 13 GB. Impressive compression ratio! Below is how to decompress a LAZ file into LAS file in python using pylas python package. #!pip install pylas[lazrs,laszip]input_laz_path = ‘data/C_37EZ2.laz’output_las_path = ‘data/C_37EZ2.las’laz = pylas.read(input_laz_path)las = pylas.convert(laz)las.write(output_las_path) Starting from QGIS 3.18, there is a feature to load and visualize las point cloud data directly in QGIS. It’s pretty straightforward and allows data visualization, overlaying satellite imagery, and rendering high-quality maps. We had to manually define the CRS (Coordinate Reference System) of the point cloud file to appear on the viewer window of QGIS. For satellite imagery overlay, There are many QGIS plugins, one of the best is Quick Map Services developed by NEXTGIS which have the most known base maps xyz urls [6]. The dataset we are using already has most points classified and can be mapped with a legend as below: Looking closely at the classified point cloud with overlaid satellite images, we can see that not all features are exactly classified as in the background satellite image. Only Ground, Building, Water objects are captured and there is no additional information about e.g. Road surface of trees. One reason may be that the date of point cloud data acquisition (2014) is different from the date of the overlaid background map (2021 by Google). Green areas are also misclassified as ground, maybe it was the winter season with a lot of snow? For a POC (proof of concept), we should reduce the data size to the minimum AOI (Area of Interest). However, we should also consider that the output algorithm on the minimum AOI will guarantee the same results when scaled to a bigger dataset. To do that, let’s handpick an AOI that contains most of the classes and draw a polygon with the same CRS on the screen as below: To clip LIDAR point cloud data to a specific AOI, there are many tools and libraries such as LAStools [7] clip or other python options such as PDAL. Why do we need to clip the LIDAR dataset into a smaller area of interest: In the development phase, we need to try out many solutions, and running the script every time on a big dataset and waiting for the solution to validate is a nightmareIn most cases, development happens on local machines, where resources are limited. Then the same code can be used on the cloud or a bigger serverIt’s much easier to visually inspect the quality of the algorithm is the data size is small and can fit in memory. In the development phase, we need to try out many solutions, and running the script every time on a big dataset and waiting for the solution to validate is a nightmare In most cases, development happens on local machines, where resources are limited. Then the same code can be used on the cloud or a bigger server It’s much easier to visually inspect the quality of the algorithm is the data size is small and can fit in memory. The output smaller Area of Interest looks like this: Quick visual investigation shows that data contain classes of three categories: BuildingsGroundWaterUnclassified Buildings Ground Water Unclassified Building features seem very well represented and have easy to identify the geometrical shapes. Water features look incomplete and will probably result in wired polygon pieces if we automate capturing it from this sample. For limiting the scope of this analysis, This work will focus on only Extracting buildings from the classified LIDAR data. According to [1] to extract objects from LIDAR data, There are two techniques to be used, each one of the two can be suitable for a specific use case and depending on the business requirement and acceptance criteria: Raster analysis by rasterizing point cloud layers, then apply raster to polygonUse unsupervised machine learning algorithm DBSCAN to separate each object as a cluster, then apply a bounding polygon operation or other to approximate the boundary of the object. Raster analysis by rasterizing point cloud layers, then apply raster to polygon Use unsupervised machine learning algorithm DBSCAN to separate each object as a cluster, then apply a bounding polygon operation or other to approximate the boundary of the object. In this report, we will explain and apply both techniques. To capture features from LIDAR data points, the first step is converting the 3d vector points (X, Y, Z) into grid-based raster representation. This process is called rasterization, the output raster will be a Digital Surface Model (DSM). and will also contain the corresponding average points height in each pixel. One library that can do that is PDAL[7]. To move forward, we need to specify the resolution of the resulting DSM. In this case, let’s use 4 times the average spacing between points, this is best practice but can vary depending on the use case. The average spacing between points is roughly 30 cm ( manually measuring that on-screen a few times), then we chose pixel size to be 1.2 meters. To install PDAL on mac, use the following command: brew install pdalPip install pdal PDAL has a python API to use in scripting and to create data pipelines from python, the API implementation is as below: pdal_json = { “pipeline”: [ INPUT_LAS_PATH, { “type”: “filters.range”, “limits”: “Classification[6:6]” }, { “filename”: OUTPUT_TIFF_DEM, “gdaldriver”: “GTiff”, “output_type”: “all”, “resolution”: “1.2”, “type”: “writers.gdal” } ] } pdal_json_str = json.dumps(pdal_json) pipeline = pdal.Pipeline(pdal_json_str) count = pipeline.execute() In the above code block, the JSON object pdal_json stores the required pipeline definition. First, we input the las file path as INPUT_LAS_PATH, Then we specify the limit class we want to extract is class no. 6, which is building. After that, we specify the output file name as OUTPUT_TIFF_DEM and the resolution of the output TIFF image. Once we pass that definition document to PDAL Pipeline API, it will start executing based on the input and output the TIFF file from the input list. Pretty straightforward and convenient. This will result in a GeoTIFF file as below, it’s a raster file with a pixel size of 1.2 meters as we specified. Also, each pixel contains the height of the pixel from the point cloud data. The visualization below can be generated using QGIS and quickmapservices plugin for background satellite images. The next step is to extract the building footprint from the resulting DEM. There is more than one tool to do that. For e.g: Using GDAL polygonize implementationUsing rasterio shapes Using GDAL polygonize implementation Using rasterio shapes Both tools create vector polygons for all connected regions of pixels in the raster sharing a common pixel value. Each polygon is created with an attribute indicating the pixel value of that polygon. Since the DEM contains the height of the pixel as a pixel value, extracting polygons from the DEM file will result in multiple small polygons with the same pixel value. It’s not what we are looking for. To extract building footprint, we should treat the DEM as a binary tiff file where building pixels can be set to 1, and no building data are set to np.nan value. This preprocessing step can then feed into another process of rasterio shape extraction or GDAL Polygonize to extract pixels with the same value as one polygon. Finally, having the polygonized coordinates of each polygon, we can use shapely and geopandas to create a geodata frame with every building as a feature. Shapely and geopandas are among of the most famous geospatial data handling libraries in python. Please note, In this step, the CRS of the features should be set to 7415 before saving the output vector file. The total extracted features are 155 buildings in the area of interest import rasteriofrom rasterio.features import shapesimport numpy as npfrom shapely.geometry import Polygonmask = Nonewith rasterio.Env(): with rasterio.open(‘SlopeNew.tif’) as src: image = src.read(1) # first band results = ( {‘properties’: {‘raster_val’: v}, ‘geometry’: s} for i, (s, v) in enumerate( shapes(image.astype(np.float32), mask=mask, transform=src.transform))) geoms = list(results) By doing that, we have iterated through each extracted polygon and saved them all to a list of geometries. Those geometries can be read in geopandas and will appear as geodataframe as bellow, with this, 90% of the hard work is completed. The resulting vectorized building shapes look like below, later in this article, we will apply a post-processing step to extract meaningful features from those buildings, so keep reading. In the previous section, we extracted the building footprint using raster analysis and polygonization. While this method works ok, it requires data transformation to a completely different type (Raster) which loses some important values associated with the original data points. In the following method, we will use an unsupervised machine learning clustering method to cluster all points that are close to each other as one cluster, then extract building boundaries from those points. LIDAR data is stored in a las file (or compressed laz file). To apply clustering, let’s first extract the coordinates of each point X, Y, Z and the associated class per point as below: def return_xyzc(point): x = point[0] y = point[1] z = point[2] c = point[5] return [x, y, z , c]pcloud = pylas.read(input_las_path)points = [return_xyzc(i) for i in pcloud]building_pts = [point for point in points if point[3] == 6] The resulting data format will be an array of points X, Y, Z, C where x is the longitude, y is the latitude, z is the elevation and c is the class of the point. Resulting in total data points are 12,333,019 for the area of interest. To start with building data, let’s filter only the building class which is class no. 6. This result in a total number of 1,992,715 building points [[87972210, 439205417, 699, 6], [87972259, 439205351, 57, 6], [87972267, 439205339, 1716, 6], [87972419, 439205135, -331, 6], [87972319, 439205284, 1030, 6]] The points above can then be visualized on a background map to view how building classes look like in 2d, in this case each data point is stored as a 2d GIS point stored in a shapefile and elevation is an attribute. Which is different from the las file data storage before. The next step after that is applying DBSCAN clustering. DB scan is Density-Based Spatial Clustering of Applications with Noise. Finds core samples of high density and expands clusters from them. Good for data which contains clusters of similar density. In DB scan, there are two core parameters, first one is epsilon which is The maximum distance between two samples for one to be considered as in the neighborhood of the other. The second parameter is min_samples, which is the number of samples (or total weight) in a neighborhood for a point to be considered as a core point. This includes the point itself. Using DBSCAN algorithm, the output is as follows where every point is associated with a cluster label that separates that cluster from other data points, for points that are noise and not close to other points within the epsilon parameter, the algorithm will set its value to -1 as it is not associated to any cluster data point. See how clear the output is below The next step is using data points from each cluster separately to extract the building footprint and the associated attributes of this object. In order to process each cluster individually, the problem statement is as follows: The total number of points in the above building = 35580 points, Just for one single building. Given an object 3d coordinates, the objective of the next step is: Extract the mean elevation of that objectCalculate the 2d boundary of the objectCalculate the associated geometry details such as area and centroid point. Extract the mean elevation of that object Calculate the 2d boundary of the object Calculate the associated geometry details such as area and centroid point. To extract the 2d boundary of an object from its associated vector data points, there are many techniques such as convex hull and alpha shape. We will use Alpha shape for this purpose Alpha Shape algorithm construct a best fit boundary around data points The API usage from python is straightforward, the only parameter needed is alpha. In our case, we will set it to 1 since data points are close to each other and we are interested in the precise boundaries. building = building_pts_gdf[building_pts_gdf.cluster==76]shape = alphashape(building.geometry, alpha=1) The output of The Alpha Shape Algorithm is a well-identified polygon that can be stored in any geometry format such as WKT Let’s take some time to look how clean the borders are based on the input points. If you use convext hull, the output will look like a circle All we have to do now is iterate through all clusters to compute the building boundaries for each cluster separately. Next, for every building shape, we are able to compute the following attributes while is very useful for using the output data file: Boundary geometryElevation of the building by taking the median altitude of pointsTotal AreaPerimeterCentroid x coordinatesCentroid y coordinates Boundary geometry Elevation of the building by taking the median altitude of points Total Area Perimeter Centroid x coordinates Centroid y coordinates This can be done using simple python and shapely functions building = building_pts_gdf[building_pts_gdf.cluster==76]shape = alphashape(building.geometry, alpha=1)height = building.z.median()area = shape.areaperimeter = shape.lengthcentroid_x = shape.centroid.xcentroid_y = shape.centroid.y The resulted extracted building shapes are as below, awesome and clean as if they are drawn manually by an AutoCAD professional. The hard work is done, now we have a data pipeline that can take a point cloud input and output automatically extracted features and the associated geometry attributes. Next is post-processing It’s common to apply post-processing after the main processing pipeline is completed. The purpose of the post-processing work vary from one project and data type to another, broadly speaking those are some post-processing target objectives: Quality check and outlier removal: for example, removing features with unrealistic areas or with small areas, detecting overlapping features and merging them, and so onGeometrical calculation: Computing meaningful information from the object geometry such as area or the perimeter. For example, calculating features centroid, calculating featureEnrichment: Adding more attribute information to features from an external dataset, e.g. attaching distance for all houses from the nearest bus stop by referring to an external data source of bus stops. Quality check and outlier removal: for example, removing features with unrealistic areas or with small areas, detecting overlapping features and merging them, and so on Geometrical calculation: Computing meaningful information from the object geometry such as area or the perimeter. For example, calculating features centroid, calculating feature Enrichment: Adding more attribute information to features from an external dataset, e.g. attaching distance for all houses from the nearest bus stop by referring to an external data source of bus stops. Automating quality check and outlier removal need a fairly good understanding of the permitted applications of the extracted features and collaboration with end-users or the product manager (the end user’s voice) to put together a final product quality acceptance criteria. For our use case, we will limit the scope of quality check and outlier removal to the area of the extracted building where it should be within a reasonable range. For this purpose, we will assume that the smallest building consists of one room 3*3 square meters (9 square meters). This post preprocessing step will eliminate 40 polygons leaving the total extracted buildings in the area of interest to 115. For practical business use, and to create an easy to query dataset, meaningful calculated attributes for each feature can be extracted in the post-processing step. Some examples of those features are area, centroid x, centroid y to name a few. This step will later help nongeospatial data users to query the data for various business use cases and utilization. Geometry calculation is pretty straightforward in geopandas as below building_gdf[‘area_m2’] = building_gdf.areabuilding_gdf[‘centroid_x’] = building_gdf.geometry.centroid.xbuilding_gdf[‘centroid_y’] = building_gdf.geometry.centroid.y Enrichment commonly refers to appending or otherwise enhancing collected data with relevant context obtained from additional sources. Geospatial data enrichment means adding more attributes to the dataset by referring to external data sources. Few common data sources are: Road infrastructure networksPOI databaseDemographics distributionAdministrative boundaries Road infrastructure networks POI database Demographics distribution Administrative boundaries We will skip applying this step in this report since it can expand indefinitely. Writing in notebooks works well for prototyping, but in order to create a data pipeline and collaborate with other team members, few steps need to be applied to the final logically correct script. Below are three quick things for productization. Code formatting Code formatting When someone is prototyping, usually the code is not well styled and indentations and spaces are not a priority at this phase. After finishing the logic, you can use one of the automated styling tools such as YAPF [8 ]by google. Once the library is installed, run it from the command line and let google style your code. yapf building_extractor.py > building_extractor_styled.py 2. Dockerization It’s a good practice to dockerize a python application to avoid dependencies conflicts, especially in this case we used so many libraries and some of them rely on binary data that are separately installed such as PDAL. Reproducing the same environment without docker will be challenging. 3. Unit tests Logical functions such as alpha shape algorithm, geometry calculation should be tested using unit tests before running the output. In addition to static maps, it’s always great to have an interactive map and be able to visualize the input and the output. For this purpose, I’ve used deck.gl with some extra HTML / JS coding. To visualize the input point cloud, I’ve extracted few buildings from the output of DBSCAN classified point cloud data, the interactive map is here: https://xmap.ai/maps/pcloud/dbscan_pcloud_3d.html This is the final product of the GIS data pipeline. The output data is saved as geojson object and visualized using deck.gl and colored by height. https://xmap.ai/maps/pcloud/buildings_vector.html LIDAR data processing is essential for many applications such as mapping and autonomous driving. For most applications, automating object detection and extraction is necessary to ensure the business success of a LIDAR product. While a lot of tools now offer out-of-the-box analytics such as Arcgis, programming one’s own tools give more flexibility to add or adjust to a specific use case. In this article we explored how to extract building footprint from LIDAR dense point cloud using two different techniques: Rasterization and polygonizationUnsupervised machine learning density-based clustering and alpha shape boundary detection Rasterization and polygonization Unsupervised machine learning density-based clustering and alpha shape boundary detection We also explored the standard post-processing techniques such as The geometric calculation to extract essential properties about each geometry such as area, perimeter, and centroidEnrichment to append more entity attributes from external datasets such as road network of POIs database if needed The geometric calculation to extract essential properties about each geometry such as area, perimeter, and centroid Enrichment to append more entity attributes from external datasets such as road network of POIs database if needed Then, we looked into some engineering steps to ensure code reusability such as: Code formatting using automatic formatting toolDockerizationUnit testing Code formatting using automatic formatting tool Dockerization Unit testing Finally, we use interactive geospatial visualization to look at the classified point cloud and the final output building data as in the two links below: xmap.ai xmap.ai The whole analysis in this report can be automated end to end and scheduled as a batch job if needed. I’m here https://mohamedbatran.com, please reach out for any questions or If you want us to collaborate!
[ { "code": null, "e": 280, "s": 172, "text": "In this article, I will walk you through extracting features from LIDAR point cloud in an automated manner." }, { "code": null, "e": 514, "s": 280, "text": "LIDAR point cloud data is a collection of points that describe a surface or an object. Each point is described with x, y, z coordinates and in some cases is associated with additional attributes such as a classification of the point." }, { "code": null, "e": 671, "s": 514, "text": "LIDAR data is used to extract accurately geo-referenced vector features such as buildings, roads, trees. To realize that there are two main steps as in [1]:" }, { "code": null, "e": 1211, "s": 671, "text": "Classification: assign a class to each point in the point cloud dataset. One way is using the PointCNN neural network given that there is sufficient training data. The output is a class for each data point.GIS pipeline: extracting relevant features from classified point cloud data in a usable format. In addition to extraction, generating attributes information to the extracted features such as object height, object surface area, centroid latitude/longitude, proximity to other features (e..g how far from the nearest road), and others." }, { "code": null, "e": 1418, "s": 1211, "text": "Classification: assign a class to each point in the point cloud dataset. One way is using the PointCNN neural network given that there is sufficient training data. The output is a class for each data point." }, { "code": null, "e": 1752, "s": 1418, "text": "GIS pipeline: extracting relevant features from classified point cloud data in a usable format. In addition to extraction, generating attributes information to the extracted features such as object height, object surface area, centroid latitude/longitude, proximity to other features (e..g how far from the nearest road), and others." }, { "code": null, "e": 1923, "s": 1752, "text": "This article will expand on point no (2) focusing on the Automated GIS feature extraction assuming the data is already classified and each data point is assigned a class." }, { "code": null, "e": 2081, "s": 1923, "text": "This section will dive into data acquisition, preprocessing, and visual inspection. It’s an often important step before starting science or development work." }, { "code": null, "e": 2491, "s": 2081, "text": "There are many services that offer to download LIDAR data. For sample data acquisition to go along with this tutorial, we will download a LIDAR dataset from [3]. When working with geospatial data, it’s always important to know what is the spatial reference system of the dataset. The spatial reference system for this tile is EPSG:7415 [4]. The definition of spatial reference system according to Wikipedia is" }, { "code": null, "e": 2644, "s": 2491, "text": "“A spatial reference system or coordinate reference system is a coordinate-based local, regional or global system used to locate geographical entities.”" }, { "code": null, "e": 2729, "s": 2644, "text": "The server to download the data is not very fast, so downloading may take some time." }, { "code": null, "e": 2889, "s": 2729, "text": "It took me a few hours to download the dataset, so at the end of this section, I will share a link for downloading a preprocessed version from my google drive." }, { "code": null, "e": 2926, "s": 2889, "text": "The downloaded file is in Laz format" }, { "code": null, "e": 2978, "s": 2926, "text": "LAZ format is a lossless compression of LIDAR data." }, { "code": null, "e": 3109, "s": 2978, "text": "It can compress original Las files to only 7 to 25 percent of their size. The speed is one to three million points per second [5]." }, { "code": null, "e": 3370, "s": 3109, "text": "The downloaded file size is 2.2 GB. To decompress LAZ files to the original Las one option is to use pylas. The extracted Las file is 13 GB. Impressive compression ratio! Below is how to decompress a LAZ file into LAS file in python using pylas python package." }, { "code": null, "e": 3557, "s": 3370, "text": "#!pip install pylas[lazrs,laszip]input_laz_path = ‘data/C_37EZ2.laz’output_las_path = ‘data/C_37EZ2.las’laz = pylas.read(input_laz_path)las = pylas.convert(laz)las.write(output_las_path)" }, { "code": null, "e": 3784, "s": 3557, "text": "Starting from QGIS 3.18, there is a feature to load and visualize las point cloud data directly in QGIS. It’s pretty straightforward and allows data visualization, overlaying satellite imagery, and rendering high-quality maps." }, { "code": null, "e": 4183, "s": 3784, "text": "We had to manually define the CRS (Coordinate Reference System) of the point cloud file to appear on the viewer window of QGIS. For satellite imagery overlay, There are many QGIS plugins, one of the best is Quick Map Services developed by NEXTGIS which have the most known base maps xyz urls [6]. The dataset we are using already has most points classified and can be mapped with a legend as below:" }, { "code": null, "e": 4478, "s": 4183, "text": "Looking closely at the classified point cloud with overlaid satellite images, we can see that not all features are exactly classified as in the background satellite image. Only Ground, Building, Water objects are captured and there is no additional information about e.g. Road surface of trees." }, { "code": null, "e": 4722, "s": 4478, "text": "One reason may be that the date of point cloud data acquisition (2014) is different from the date of the overlaid background map (2021 by Google). Green areas are also misclassified as ground, maybe it was the winter season with a lot of snow?" }, { "code": null, "e": 4965, "s": 4722, "text": "For a POC (proof of concept), we should reduce the data size to the minimum AOI (Area of Interest). However, we should also consider that the output algorithm on the minimum AOI will guarantee the same results when scaled to a bigger dataset." }, { "code": null, "e": 5094, "s": 4965, "text": "To do that, let’s handpick an AOI that contains most of the classes and draw a polygon with the same CRS on the screen as below:" }, { "code": null, "e": 5317, "s": 5094, "text": "To clip LIDAR point cloud data to a specific AOI, there are many tools and libraries such as LAStools [7] clip or other python options such as PDAL. Why do we need to clip the LIDAR dataset into a smaller area of interest:" }, { "code": null, "e": 5744, "s": 5317, "text": "In the development phase, we need to try out many solutions, and running the script every time on a big dataset and waiting for the solution to validate is a nightmareIn most cases, development happens on local machines, where resources are limited. Then the same code can be used on the cloud or a bigger serverIt’s much easier to visually inspect the quality of the algorithm is the data size is small and can fit in memory." }, { "code": null, "e": 5912, "s": 5744, "text": "In the development phase, we need to try out many solutions, and running the script every time on a big dataset and waiting for the solution to validate is a nightmare" }, { "code": null, "e": 6058, "s": 5912, "text": "In most cases, development happens on local machines, where resources are limited. Then the same code can be used on the cloud or a bigger server" }, { "code": null, "e": 6173, "s": 6058, "text": "It’s much easier to visually inspect the quality of the algorithm is the data size is small and can fit in memory." }, { "code": null, "e": 6226, "s": 6173, "text": "The output smaller Area of Interest looks like this:" }, { "code": null, "e": 6306, "s": 6226, "text": "Quick visual investigation shows that data contain classes of three categories:" }, { "code": null, "e": 6339, "s": 6306, "text": "BuildingsGroundWaterUnclassified" }, { "code": null, "e": 6349, "s": 6339, "text": "Buildings" }, { "code": null, "e": 6356, "s": 6349, "text": "Ground" }, { "code": null, "e": 6362, "s": 6356, "text": "Water" }, { "code": null, "e": 6375, "s": 6362, "text": "Unclassified" }, { "code": null, "e": 6596, "s": 6375, "text": "Building features seem very well represented and have easy to identify the geometrical shapes. Water features look incomplete and will probably result in wired polygon pieces if we automate capturing it from this sample." }, { "code": null, "e": 6719, "s": 6596, "text": "For limiting the scope of this analysis, This work will focus on only Extracting buildings from the classified LIDAR data." }, { "code": null, "e": 6936, "s": 6719, "text": "According to [1] to extract objects from LIDAR data, There are two techniques to be used, each one of the two can be suitable for a specific use case and depending on the business requirement and acceptance criteria:" }, { "code": null, "e": 7196, "s": 6936, "text": "Raster analysis by rasterizing point cloud layers, then apply raster to polygonUse unsupervised machine learning algorithm DBSCAN to separate each object as a cluster, then apply a bounding polygon operation or other to approximate the boundary of the object." }, { "code": null, "e": 7276, "s": 7196, "text": "Raster analysis by rasterizing point cloud layers, then apply raster to polygon" }, { "code": null, "e": 7457, "s": 7276, "text": "Use unsupervised machine learning algorithm DBSCAN to separate each object as a cluster, then apply a bounding polygon operation or other to approximate the boundary of the object." }, { "code": null, "e": 7516, "s": 7457, "text": "In this report, we will explain and apply both techniques." }, { "code": null, "e": 7831, "s": 7516, "text": "To capture features from LIDAR data points, the first step is converting the 3d vector points (X, Y, Z) into grid-based raster representation. This process is called rasterization, the output raster will be a Digital Surface Model (DSM). and will also contain the corresponding average points height in each pixel." }, { "code": null, "e": 8220, "s": 7831, "text": "One library that can do that is PDAL[7]. To move forward, we need to specify the resolution of the resulting DSM. In this case, let’s use 4 times the average spacing between points, this is best practice but can vary depending on the use case. The average spacing between points is roughly 30 cm ( manually measuring that on-screen a few times), then we chose pixel size to be 1.2 meters." }, { "code": null, "e": 8271, "s": 8220, "text": "To install PDAL on mac, use the following command:" }, { "code": null, "e": 8305, "s": 8271, "text": "brew install pdalPip install pdal" }, { "code": null, "e": 8425, "s": 8305, "text": "PDAL has a python API to use in scripting and to create data pipelines from python, the API implementation is as below:" }, { "code": null, "e": 8762, "s": 8425, "text": "pdal_json = { “pipeline”: [ INPUT_LAS_PATH, { “type”: “filters.range”, “limits”: “Classification[6:6]” }, { “filename”: OUTPUT_TIFF_DEM, “gdaldriver”: “GTiff”, “output_type”: “all”, “resolution”: “1.2”, “type”: “writers.gdal” } ] } pdal_json_str = json.dumps(pdal_json) pipeline = pdal.Pipeline(pdal_json_str) count = pipeline.execute()" }, { "code": null, "e": 9101, "s": 8762, "text": "In the above code block, the JSON object pdal_json stores the required pipeline definition. First, we input the las file path as INPUT_LAS_PATH, Then we specify the limit class we want to extract is class no. 6, which is building. After that, we specify the output file name as OUTPUT_TIFF_DEM and the resolution of the output TIFF image." }, { "code": null, "e": 9289, "s": 9101, "text": "Once we pass that definition document to PDAL Pipeline API, it will start executing based on the input and output the TIFF file from the input list. Pretty straightforward and convenient." }, { "code": null, "e": 9592, "s": 9289, "text": "This will result in a GeoTIFF file as below, it’s a raster file with a pixel size of 1.2 meters as we specified. Also, each pixel contains the height of the pixel from the point cloud data. The visualization below can be generated using QGIS and quickmapservices plugin for background satellite images." }, { "code": null, "e": 9716, "s": 9592, "text": "The next step is to extract the building footprint from the resulting DEM. There is more than one tool to do that. For e.g:" }, { "code": null, "e": 9774, "s": 9716, "text": "Using GDAL polygonize implementationUsing rasterio shapes" }, { "code": null, "e": 9811, "s": 9774, "text": "Using GDAL polygonize implementation" }, { "code": null, "e": 9833, "s": 9811, "text": "Using rasterio shapes" }, { "code": null, "e": 10236, "s": 9833, "text": "Both tools create vector polygons for all connected regions of pixels in the raster sharing a common pixel value. Each polygon is created with an attribute indicating the pixel value of that polygon. Since the DEM contains the height of the pixel as a pixel value, extracting polygons from the DEM file will result in multiple small polygons with the same pixel value. It’s not what we are looking for." }, { "code": null, "e": 10559, "s": 10236, "text": "To extract building footprint, we should treat the DEM as a binary tiff file where building pixels can be set to 1, and no building data are set to np.nan value. This preprocessing step can then feed into another process of rasterio shape extraction or GDAL Polygonize to extract pixels with the same value as one polygon." }, { "code": null, "e": 10713, "s": 10559, "text": "Finally, having the polygonized coordinates of each polygon, we can use shapely and geopandas to create a geodata frame with every building as a feature." }, { "code": null, "e": 10810, "s": 10713, "text": "Shapely and geopandas are among of the most famous geospatial data handling libraries in python." }, { "code": null, "e": 10921, "s": 10810, "text": "Please note, In this step, the CRS of the features should be set to 7415 before saving the output vector file." }, { "code": null, "e": 10992, "s": 10921, "text": "The total extracted features are 155 buildings in the area of interest" }, { "code": null, "e": 11388, "s": 10992, "text": "import rasteriofrom rasterio.features import shapesimport numpy as npfrom shapely.geometry import Polygonmask = Nonewith rasterio.Env(): with rasterio.open(‘SlopeNew.tif’) as src: image = src.read(1) # first band results = ( {‘properties’: {‘raster_val’: v}, ‘geometry’: s} for i, (s, v) in enumerate( shapes(image.astype(np.float32), mask=mask, transform=src.transform))) geoms = list(results)" }, { "code": null, "e": 11626, "s": 11388, "text": "By doing that, we have iterated through each extracted polygon and saved them all to a list of geometries. Those geometries can be read in geopandas and will appear as geodataframe as bellow, with this, 90% of the hard work is completed." }, { "code": null, "e": 11814, "s": 11626, "text": "The resulting vectorized building shapes look like below, later in this article, we will apply a post-processing step to extract meaningful features from those buildings, so keep reading." }, { "code": null, "e": 12093, "s": 11814, "text": "In the previous section, we extracted the building footprint using raster analysis and polygonization. While this method works ok, it requires data transformation to a completely different type (Raster) which loses some important values associated with the original data points." }, { "code": null, "e": 12300, "s": 12093, "text": "In the following method, we will use an unsupervised machine learning clustering method to cluster all points that are close to each other as one cluster, then extract building boundaries from those points." }, { "code": null, "e": 12485, "s": 12300, "text": "LIDAR data is stored in a las file (or compressed laz file). To apply clustering, let’s first extract the coordinates of each point X, Y, Z and the associated class per point as below:" }, { "code": null, "e": 12717, "s": 12485, "text": "def return_xyzc(point): x = point[0] y = point[1] z = point[2] c = point[5] return [x, y, z , c]pcloud = pylas.read(input_las_path)points = [return_xyzc(i) for i in pcloud]building_pts = [point for point in points if point[3] == 6]" }, { "code": null, "e": 13097, "s": 12717, "text": "The resulting data format will be an array of points X, Y, Z, C where x is the longitude, y is the latitude, z is the elevation and c is the class of the point. Resulting in total data points are 12,333,019 for the area of interest. To start with building data, let’s filter only the building class which is class no. 6. This result in a total number of 1,992,715 building points" }, { "code": null, "e": 13255, "s": 13097, "text": "[[87972210, 439205417, 699, 6], [87972259, 439205351, 57, 6], [87972267, 439205339, 1716, 6], [87972419, 439205135, -331, 6], [87972319, 439205284, 1030, 6]]" }, { "code": null, "e": 13529, "s": 13255, "text": "The points above can then be visualized on a background map to view how building classes look like in 2d, in this case each data point is stored as a 2d GIS point stored in a shapefile and elevation is an attribute. Which is different from the las file data storage before." }, { "code": null, "e": 13585, "s": 13529, "text": "The next step after that is applying DBSCAN clustering." }, { "code": null, "e": 13782, "s": 13585, "text": "DB scan is Density-Based Spatial Clustering of Applications with Noise. Finds core samples of high density and expands clusters from them. Good for data which contains clusters of similar density." }, { "code": null, "e": 14140, "s": 13782, "text": "In DB scan, there are two core parameters, first one is epsilon which is The maximum distance between two samples for one to be considered as in the neighborhood of the other. The second parameter is min_samples, which is the number of samples (or total weight) in a neighborhood for a point to be considered as a core point. This includes the point itself." }, { "code": null, "e": 14504, "s": 14140, "text": "Using DBSCAN algorithm, the output is as follows where every point is associated with a cluster label that separates that cluster from other data points, for points that are noise and not close to other points within the epsilon parameter, the algorithm will set its value to -1 as it is not associated to any cluster data point. See how clear the output is below" }, { "code": null, "e": 14732, "s": 14504, "text": "The next step is using data points from each cluster separately to extract the building footprint and the associated attributes of this object. In order to process each cluster individually, the problem statement is as follows:" }, { "code": null, "e": 14827, "s": 14732, "text": "The total number of points in the above building = 35580 points, Just for one single building." }, { "code": null, "e": 14894, "s": 14827, "text": "Given an object 3d coordinates, the objective of the next step is:" }, { "code": null, "e": 15049, "s": 14894, "text": "Extract the mean elevation of that objectCalculate the 2d boundary of the objectCalculate the associated geometry details such as area and centroid point." }, { "code": null, "e": 15091, "s": 15049, "text": "Extract the mean elevation of that object" }, { "code": null, "e": 15131, "s": 15091, "text": "Calculate the 2d boundary of the object" }, { "code": null, "e": 15206, "s": 15131, "text": "Calculate the associated geometry details such as area and centroid point." }, { "code": null, "e": 15390, "s": 15206, "text": "To extract the 2d boundary of an object from its associated vector data points, there are many techniques such as convex hull and alpha shape. We will use Alpha shape for this purpose" }, { "code": null, "e": 15461, "s": 15390, "text": "Alpha Shape algorithm construct a best fit boundary around data points" }, { "code": null, "e": 15667, "s": 15461, "text": "The API usage from python is straightforward, the only parameter needed is alpha. In our case, we will set it to 1 since data points are close to each other and we are interested in the precise boundaries." }, { "code": null, "e": 15771, "s": 15667, "text": "building = building_pts_gdf[building_pts_gdf.cluster==76]shape = alphashape(building.geometry, alpha=1)" }, { "code": null, "e": 15894, "s": 15771, "text": "The output of The Alpha Shape Algorithm is a well-identified polygon that can be stored in any geometry format such as WKT" }, { "code": null, "e": 16036, "s": 15894, "text": "Let’s take some time to look how clean the borders are based on the input points. If you use convext hull, the output will look like a circle" }, { "code": null, "e": 16154, "s": 16036, "text": "All we have to do now is iterate through all clusters to compute the building boundaries for each cluster separately." }, { "code": null, "e": 16287, "s": 16154, "text": "Next, for every building shape, we are able to compute the following attributes while is very useful for using the output data file:" }, { "code": null, "e": 16433, "s": 16287, "text": "Boundary geometryElevation of the building by taking the median altitude of pointsTotal AreaPerimeterCentroid x coordinatesCentroid y coordinates" }, { "code": null, "e": 16451, "s": 16433, "text": "Boundary geometry" }, { "code": null, "e": 16517, "s": 16451, "text": "Elevation of the building by taking the median altitude of points" }, { "code": null, "e": 16528, "s": 16517, "text": "Total Area" }, { "code": null, "e": 16538, "s": 16528, "text": "Perimeter" }, { "code": null, "e": 16561, "s": 16538, "text": "Centroid x coordinates" }, { "code": null, "e": 16584, "s": 16561, "text": "Centroid y coordinates" }, { "code": null, "e": 16643, "s": 16584, "text": "This can be done using simple python and shapely functions" }, { "code": null, "e": 16874, "s": 16643, "text": "building = building_pts_gdf[building_pts_gdf.cluster==76]shape = alphashape(building.geometry, alpha=1)height = building.z.median()area = shape.areaperimeter = shape.lengthcentroid_x = shape.centroid.xcentroid_y = shape.centroid.y" }, { "code": null, "e": 17003, "s": 16874, "text": "The resulted extracted building shapes are as below, awesome and clean as if they are drawn manually by an AutoCAD professional." }, { "code": null, "e": 17196, "s": 17003, "text": "The hard work is done, now we have a data pipeline that can take a point cloud input and output automatically extracted features and the associated geometry attributes. Next is post-processing" }, { "code": null, "e": 17437, "s": 17196, "text": "It’s common to apply post-processing after the main processing pipeline is completed. The purpose of the post-processing work vary from one project and data type to another, broadly speaking those are some post-processing target objectives:" }, { "code": null, "e": 17985, "s": 17437, "text": "Quality check and outlier removal: for example, removing features with unrealistic areas or with small areas, detecting overlapping features and merging them, and so onGeometrical calculation: Computing meaningful information from the object geometry such as area or the perimeter. For example, calculating features centroid, calculating featureEnrichment: Adding more attribute information to features from an external dataset, e.g. attaching distance for all houses from the nearest bus stop by referring to an external data source of bus stops." }, { "code": null, "e": 18154, "s": 17985, "text": "Quality check and outlier removal: for example, removing features with unrealistic areas or with small areas, detecting overlapping features and merging them, and so on" }, { "code": null, "e": 18332, "s": 18154, "text": "Geometrical calculation: Computing meaningful information from the object geometry such as area or the perimeter. For example, calculating features centroid, calculating feature" }, { "code": null, "e": 18535, "s": 18332, "text": "Enrichment: Adding more attribute information to features from an external dataset, e.g. attaching distance for all houses from the nearest bus stop by referring to an external data source of bus stops." }, { "code": null, "e": 18809, "s": 18535, "text": "Automating quality check and outlier removal need a fairly good understanding of the permitted applications of the extracted features and collaboration with end-users or the product manager (the end user’s voice) to put together a final product quality acceptance criteria." }, { "code": null, "e": 19216, "s": 18809, "text": "For our use case, we will limit the scope of quality check and outlier removal to the area of the extracted building where it should be within a reasonable range. For this purpose, we will assume that the smallest building consists of one room 3*3 square meters (9 square meters). This post preprocessing step will eliminate 40 polygons leaving the total extracted buildings in the area of interest to 115." }, { "code": null, "e": 19577, "s": 19216, "text": "For practical business use, and to create an easy to query dataset, meaningful calculated attributes for each feature can be extracted in the post-processing step. Some examples of those features are area, centroid x, centroid y to name a few. This step will later help nongeospatial data users to query the data for various business use cases and utilization." }, { "code": null, "e": 19646, "s": 19577, "text": "Geometry calculation is pretty straightforward in geopandas as below" }, { "code": null, "e": 19812, "s": 19646, "text": "building_gdf[‘area_m2’] = building_gdf.areabuilding_gdf[‘centroid_x’] = building_gdf.geometry.centroid.xbuilding_gdf[‘centroid_y’] = building_gdf.geometry.centroid.y" }, { "code": null, "e": 20085, "s": 19812, "text": "Enrichment commonly refers to appending or otherwise enhancing collected data with relevant context obtained from additional sources. Geospatial data enrichment means adding more attributes to the dataset by referring to external data sources. Few common data sources are:" }, { "code": null, "e": 20176, "s": 20085, "text": "Road infrastructure networksPOI databaseDemographics distributionAdministrative boundaries" }, { "code": null, "e": 20205, "s": 20176, "text": "Road infrastructure networks" }, { "code": null, "e": 20218, "s": 20205, "text": "POI database" }, { "code": null, "e": 20244, "s": 20218, "text": "Demographics distribution" }, { "code": null, "e": 20270, "s": 20244, "text": "Administrative boundaries" }, { "code": null, "e": 20351, "s": 20270, "text": "We will skip applying this step in this report since it can expand indefinitely." }, { "code": null, "e": 20597, "s": 20351, "text": "Writing in notebooks works well for prototyping, but in order to create a data pipeline and collaborate with other team members, few steps need to be applied to the final logically correct script. Below are three quick things for productization." }, { "code": null, "e": 20613, "s": 20597, "text": "Code formatting" }, { "code": null, "e": 20629, "s": 20613, "text": "Code formatting" }, { "code": null, "e": 20950, "s": 20629, "text": "When someone is prototyping, usually the code is not well styled and indentations and spaces are not a priority at this phase. After finishing the logic, you can use one of the automated styling tools such as YAPF [8 ]by google. Once the library is installed, run it from the command line and let google style your code." }, { "code": null, "e": 21008, "s": 20950, "text": "yapf building_extractor.py > building_extractor_styled.py" }, { "code": null, "e": 21025, "s": 21008, "text": "2. Dockerization" }, { "code": null, "e": 21313, "s": 21025, "text": "It’s a good practice to dockerize a python application to avoid dependencies conflicts, especially in this case we used so many libraries and some of them rely on binary data that are separately installed such as PDAL. Reproducing the same environment without docker will be challenging." }, { "code": null, "e": 21327, "s": 21313, "text": "3. Unit tests" }, { "code": null, "e": 21458, "s": 21327, "text": "Logical functions such as alpha shape algorithm, geometry calculation should be tested using unit tests before running the output." }, { "code": null, "e": 21652, "s": 21458, "text": "In addition to static maps, it’s always great to have an interactive map and be able to visualize the input and the output. For this purpose, I’ve used deck.gl with some extra HTML / JS coding." }, { "code": null, "e": 21801, "s": 21652, "text": "To visualize the input point cloud, I’ve extracted few buildings from the output of DBSCAN classified point cloud data, the interactive map is here:" }, { "code": null, "e": 21851, "s": 21801, "text": "https://xmap.ai/maps/pcloud/dbscan_pcloud_3d.html" }, { "code": null, "e": 21998, "s": 21851, "text": "This is the final product of the GIS data pipeline. The output data is saved as geojson object and visualized using deck.gl and colored by height." }, { "code": null, "e": 22048, "s": 21998, "text": "https://xmap.ai/maps/pcloud/buildings_vector.html" }, { "code": null, "e": 22561, "s": 22048, "text": "LIDAR data processing is essential for many applications such as mapping and autonomous driving. For most applications, automating object detection and extraction is necessary to ensure the business success of a LIDAR product. While a lot of tools now offer out-of-the-box analytics such as Arcgis, programming one’s own tools give more flexibility to add or adjust to a specific use case. In this article we explored how to extract building footprint from LIDAR dense point cloud using two different techniques:" }, { "code": null, "e": 22683, "s": 22561, "text": "Rasterization and polygonizationUnsupervised machine learning density-based clustering and alpha shape boundary detection" }, { "code": null, "e": 22716, "s": 22683, "text": "Rasterization and polygonization" }, { "code": null, "e": 22806, "s": 22716, "text": "Unsupervised machine learning density-based clustering and alpha shape boundary detection" }, { "code": null, "e": 22871, "s": 22806, "text": "We also explored the standard post-processing techniques such as" }, { "code": null, "e": 23101, "s": 22871, "text": "The geometric calculation to extract essential properties about each geometry such as area, perimeter, and centroidEnrichment to append more entity attributes from external datasets such as road network of POIs database if needed" }, { "code": null, "e": 23217, "s": 23101, "text": "The geometric calculation to extract essential properties about each geometry such as area, perimeter, and centroid" }, { "code": null, "e": 23332, "s": 23217, "text": "Enrichment to append more entity attributes from external datasets such as road network of POIs database if needed" }, { "code": null, "e": 23412, "s": 23332, "text": "Then, we looked into some engineering steps to ensure code reusability such as:" }, { "code": null, "e": 23485, "s": 23412, "text": "Code formatting using automatic formatting toolDockerizationUnit testing" }, { "code": null, "e": 23533, "s": 23485, "text": "Code formatting using automatic formatting tool" }, { "code": null, "e": 23547, "s": 23533, "text": "Dockerization" }, { "code": null, "e": 23560, "s": 23547, "text": "Unit testing" }, { "code": null, "e": 23713, "s": 23560, "text": "Finally, we use interactive geospatial visualization to look at the classified point cloud and the final output building data as in the two links below:" }, { "code": null, "e": 23721, "s": 23713, "text": "xmap.ai" }, { "code": null, "e": 23729, "s": 23721, "text": "xmap.ai" }, { "code": null, "e": 23831, "s": 23729, "text": "The whole analysis in this report can be automated end to end and scheduled as a batch job if needed." } ]
Joining Threads in Java
17 Feb, 2021 java.lang.Thread class provides the join() method which allows one thread to wait until another thread completes its execution. If t is a Thread object whose thread is currently executing, then t.join() will make sure that t is terminated before the next instruction is executed by the program.If there are multiple threads calling the join() methods that means overloading on join allows the programmer to specify a waiting period. However, as with sleep, join is dependent on the OS for timing, so you should not assume that join will wait exactly as long as you specify.There are three overloaded join functions. join(): It will put the current thread on wait until the thread on which it is called is dead. If thread is interrupted then it will throw InterruptedException.Syntax:public final void join() join(long millis) :It will put the current thread on wait until the thread on which it is called is dead or wait for specified time (milliseconds).Syntax:public final synchronized void join(long millis) join(long millis, int nanos): It will put the current thread on wait until the thread on which it is called is dead or wait for specified time (milliseconds + nanos).Syntax:public final synchronized void join(long millis, int nanos) // Java program to explain the// concept of joining a thread.import java.io.*; // Creating thread by creating the// objects of that classclass ThreadJoining extends Thread{ @Override public void run() { for (int i = 0; i < 2; i++) { try { Thread.sleep(500); System.out.println("Current Thread: " + Thread.currentThread().getName()); } catch(Exception ex) { System.out.println("Exception has" + " been caught" + ex); } System.out.println(i); } }} class GFG{ public static void main (String[] args) { // creating two threads ThreadJoining t1 = new ThreadJoining(); ThreadJoining t2 = new ThreadJoining(); ThreadJoining t3 = new ThreadJoining(); // thread t1 starts t1.start(); // starts second thread after when // first thread t1 has died. try { System.out.println("Current Thread: " + Thread.currentThread().getName()); t1.join(); } catch(Exception ex) { System.out.println("Exception has " + "been caught" + ex); } // t2 starts t2.start(); // starts t3 after when thread t2 has died. try { System.out.println("Current Thread: " + Thread.currentThread().getName()); t2.join(); } catch(Exception ex) { System.out.println("Exception has been" + " caught" + ex); } t3.start(); }}output:Current Thread: main Current Thread: Thread-0 0 Current Thread: Thread-0 1 Current Thread: main Current Thread: Thread-1 0 Current Thread: Thread-1 1 Current Thread: Thread-2 0 Current Thread: Thread-2 1 join(): It will put the current thread on wait until the thread on which it is called is dead. If thread is interrupted then it will throw InterruptedException.Syntax:public final void join() public final void join() join(long millis) :It will put the current thread on wait until the thread on which it is called is dead or wait for specified time (milliseconds).Syntax:public final synchronized void join(long millis) public final synchronized void join(long millis) join(long millis, int nanos): It will put the current thread on wait until the thread on which it is called is dead or wait for specified time (milliseconds + nanos).Syntax:public final synchronized void join(long millis, int nanos) // Java program to explain the// concept of joining a thread.import java.io.*; // Creating thread by creating the// objects of that classclass ThreadJoining extends Thread{ @Override public void run() { for (int i = 0; i < 2; i++) { try { Thread.sleep(500); System.out.println("Current Thread: " + Thread.currentThread().getName()); } catch(Exception ex) { System.out.println("Exception has" + " been caught" + ex); } System.out.println(i); } }} class GFG{ public static void main (String[] args) { // creating two threads ThreadJoining t1 = new ThreadJoining(); ThreadJoining t2 = new ThreadJoining(); ThreadJoining t3 = new ThreadJoining(); // thread t1 starts t1.start(); // starts second thread after when // first thread t1 has died. try { System.out.println("Current Thread: " + Thread.currentThread().getName()); t1.join(); } catch(Exception ex) { System.out.println("Exception has " + "been caught" + ex); } // t2 starts t2.start(); // starts t3 after when thread t2 has died. try { System.out.println("Current Thread: " + Thread.currentThread().getName()); t2.join(); } catch(Exception ex) { System.out.println("Exception has been" + " caught" + ex); } t3.start(); }}output:Current Thread: main Current Thread: Thread-0 0 Current Thread: Thread-0 1 Current Thread: main Current Thread: Thread-1 0 Current Thread: Thread-1 1 Current Thread: Thread-2 0 Current Thread: Thread-2 1 public final synchronized void join(long millis, int nanos) // Java program to explain the// concept of joining a thread.import java.io.*; // Creating thread by creating the// objects of that classclass ThreadJoining extends Thread{ @Override public void run() { for (int i = 0; i < 2; i++) { try { Thread.sleep(500); System.out.println("Current Thread: " + Thread.currentThread().getName()); } catch(Exception ex) { System.out.println("Exception has" + " been caught" + ex); } System.out.println(i); } }} class GFG{ public static void main (String[] args) { // creating two threads ThreadJoining t1 = new ThreadJoining(); ThreadJoining t2 = new ThreadJoining(); ThreadJoining t3 = new ThreadJoining(); // thread t1 starts t1.start(); // starts second thread after when // first thread t1 has died. try { System.out.println("Current Thread: " + Thread.currentThread().getName()); t1.join(); } catch(Exception ex) { System.out.println("Exception has " + "been caught" + ex); } // t2 starts t2.start(); // starts t3 after when thread t2 has died. try { System.out.println("Current Thread: " + Thread.currentThread().getName()); t2.join(); } catch(Exception ex) { System.out.println("Exception has been" + " caught" + ex); } t3.start(); }} output: Current Thread: main Current Thread: Thread-0 0 Current Thread: Thread-0 1 Current Thread: main Current Thread: Thread-1 0 Current Thread: Thread-1 1 Current Thread: Thread-2 0 Current Thread: Thread-2 1 In the above example we can see clearly second thread t2 starts after first thread t1 has died and t3 will start its execution after second thread t2 has died.Thread Join | GeeksforGeeks - YouTubeGeeksforGeeks531K subscribersThread Join | GeeksforGeeksWatch laterShareCopy link10/10InfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 6:34•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=ruXbPdOST4A" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>This article is contributed by Nitsdheerendra. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. mucunguzia Ammar Githam Java-Multithreading Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n17 Feb, 2021" }, { "code": null, "e": 670, "s": 54, "text": "java.lang.Thread class provides the join() method which allows one thread to wait until another thread completes its execution. If t is a Thread object whose thread is currently executing, then t.join() will make sure that t is terminated before the next instruction is executed by the program.If there are multiple threads calling the join() methods that means overloading on join allows the programmer to specify a waiting period. However, as with sleep, join is dependent on the OS for timing, so you should not assume that join will wait exactly as long as you specify.There are three overloaded join functions." }, { "code": null, "e": 3257, "s": 670, "text": "join(): It will put the current thread on wait until the thread on which it is called is dead. If thread is interrupted then it will throw InterruptedException.Syntax:public final void join()\njoin(long millis) :It will put the current thread on wait until the thread on which it is called is dead or wait for specified time (milliseconds).Syntax:public final synchronized void join(long millis)\njoin(long millis, int nanos): It will put the current thread on wait until the thread on which it is called is dead or wait for specified time (milliseconds + nanos).Syntax:public final synchronized void join(long millis, int nanos)\n// Java program to explain the// concept of joining a thread.import java.io.*; // Creating thread by creating the// objects of that classclass ThreadJoining extends Thread{ @Override public void run() { for (int i = 0; i < 2; i++) { try { Thread.sleep(500); System.out.println(\"Current Thread: \" + Thread.currentThread().getName()); } catch(Exception ex) { System.out.println(\"Exception has\" + \" been caught\" + ex); } System.out.println(i); } }} class GFG{ public static void main (String[] args) { // creating two threads ThreadJoining t1 = new ThreadJoining(); ThreadJoining t2 = new ThreadJoining(); ThreadJoining t3 = new ThreadJoining(); // thread t1 starts t1.start(); // starts second thread after when // first thread t1 has died. try { System.out.println(\"Current Thread: \" + Thread.currentThread().getName()); t1.join(); } catch(Exception ex) { System.out.println(\"Exception has \" + \"been caught\" + ex); } // t2 starts t2.start(); // starts t3 after when thread t2 has died. try { System.out.println(\"Current Thread: \" + Thread.currentThread().getName()); t2.join(); } catch(Exception ex) { System.out.println(\"Exception has been\" + \" caught\" + ex); } t3.start(); }}output:Current Thread: main\nCurrent Thread: Thread-0\n0\nCurrent Thread: Thread-0\n1\nCurrent Thread: main\nCurrent Thread: Thread-1\n0\nCurrent Thread: Thread-1\n1\nCurrent Thread: Thread-2\n0\nCurrent Thread: Thread-2\n1\n" }, { "code": null, "e": 3450, "s": 3257, "text": "join(): It will put the current thread on wait until the thread on which it is called is dead. If thread is interrupted then it will throw InterruptedException.Syntax:public final void join()\n" }, { "code": null, "e": 3476, "s": 3450, "text": "public final void join()\n" }, { "code": null, "e": 3680, "s": 3476, "text": "join(long millis) :It will put the current thread on wait until the thread on which it is called is dead or wait for specified time (milliseconds).Syntax:public final synchronized void join(long millis)\n" }, { "code": null, "e": 3730, "s": 3680, "text": "public final synchronized void join(long millis)\n" }, { "code": null, "e": 5922, "s": 3730, "text": "join(long millis, int nanos): It will put the current thread on wait until the thread on which it is called is dead or wait for specified time (milliseconds + nanos).Syntax:public final synchronized void join(long millis, int nanos)\n// Java program to explain the// concept of joining a thread.import java.io.*; // Creating thread by creating the// objects of that classclass ThreadJoining extends Thread{ @Override public void run() { for (int i = 0; i < 2; i++) { try { Thread.sleep(500); System.out.println(\"Current Thread: \" + Thread.currentThread().getName()); } catch(Exception ex) { System.out.println(\"Exception has\" + \" been caught\" + ex); } System.out.println(i); } }} class GFG{ public static void main (String[] args) { // creating two threads ThreadJoining t1 = new ThreadJoining(); ThreadJoining t2 = new ThreadJoining(); ThreadJoining t3 = new ThreadJoining(); // thread t1 starts t1.start(); // starts second thread after when // first thread t1 has died. try { System.out.println(\"Current Thread: \" + Thread.currentThread().getName()); t1.join(); } catch(Exception ex) { System.out.println(\"Exception has \" + \"been caught\" + ex); } // t2 starts t2.start(); // starts t3 after when thread t2 has died. try { System.out.println(\"Current Thread: \" + Thread.currentThread().getName()); t2.join(); } catch(Exception ex) { System.out.println(\"Exception has been\" + \" caught\" + ex); } t3.start(); }}output:Current Thread: main\nCurrent Thread: Thread-0\n0\nCurrent Thread: Thread-0\n1\nCurrent Thread: main\nCurrent Thread: Thread-1\n0\nCurrent Thread: Thread-1\n1\nCurrent Thread: Thread-2\n0\nCurrent Thread: Thread-2\n1\n" }, { "code": null, "e": 5983, "s": 5922, "text": "public final synchronized void join(long millis, int nanos)\n" }, { "code": "// Java program to explain the// concept of joining a thread.import java.io.*; // Creating thread by creating the// objects of that classclass ThreadJoining extends Thread{ @Override public void run() { for (int i = 0; i < 2; i++) { try { Thread.sleep(500); System.out.println(\"Current Thread: \" + Thread.currentThread().getName()); } catch(Exception ex) { System.out.println(\"Exception has\" + \" been caught\" + ex); } System.out.println(i); } }} class GFG{ public static void main (String[] args) { // creating two threads ThreadJoining t1 = new ThreadJoining(); ThreadJoining t2 = new ThreadJoining(); ThreadJoining t3 = new ThreadJoining(); // thread t1 starts t1.start(); // starts second thread after when // first thread t1 has died. try { System.out.println(\"Current Thread: \" + Thread.currentThread().getName()); t1.join(); } catch(Exception ex) { System.out.println(\"Exception has \" + \"been caught\" + ex); } // t2 starts t2.start(); // starts t3 after when thread t2 has died. try { System.out.println(\"Current Thread: \" + Thread.currentThread().getName()); t2.join(); } catch(Exception ex) { System.out.println(\"Exception has been\" + \" caught\" + ex); } t3.start(); }}", "e": 7731, "s": 5983, "text": null }, { "code": null, "e": 7739, "s": 7731, "text": "output:" }, { "code": null, "e": 7944, "s": 7739, "text": "Current Thread: main\nCurrent Thread: Thread-0\n0\nCurrent Thread: Thread-0\n1\nCurrent Thread: main\nCurrent Thread: Thread-1\n0\nCurrent Thread: Thread-1\n1\nCurrent Thread: Thread-2\n0\nCurrent Thread: Thread-2\n1\n" }, { "code": null, "e": 9249, "s": 7944, "text": "In the above example we can see clearly second thread t2 starts after first thread t1 has died and t3 will start its execution after second thread t2 has died.Thread Join | GeeksforGeeks - YouTubeGeeksforGeeks531K subscribersThread Join | GeeksforGeeksWatch laterShareCopy link10/10InfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 6:34•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=ruXbPdOST4A\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>This article is contributed by Nitsdheerendra. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 9374, "s": 9249, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 9385, "s": 9374, "text": "mucunguzia" }, { "code": null, "e": 9398, "s": 9385, "text": "Ammar Githam" }, { "code": null, "e": 9418, "s": 9398, "text": "Java-Multithreading" }, { "code": null, "e": 9423, "s": 9418, "text": "Java" }, { "code": null, "e": 9428, "s": 9423, "text": "Java" } ]
Classification in R Programming
28 Feb, 2022 R is a very dynamic and versatile programming language for data science. This article deals with classification in R. Generally classifiers in R are used to predict specific category related information like reviews or ratings such as good, best or worst.Various Classifiers are: Decision Trees Naive Bayes Classifiers K-NN Classifiers Support Vector Machines(SVM’s) It is basically is a graph to represent choices. The nodes or vertices in the graph represent an event and the edges of the graph represent the decision conditions. Its common use is in Machine Learning and Data Mining applications.Applications: Spam/Non-spam classification of email, predicting of a tumor is cancerous or not. Usually, a model is constructed with noted data also called training dataset. Then a set of validation data is used to verify and improve the model. R has packages that are used to create and visualize decision trees. The R package “party” is used to create decision trees. Command: install.packages("party") Python3 # Load the party package. It will automatically load other# dependent packages.library(party) # Create the input data frame.input.data <- readingSkills[c(1:105), ] # Give the chart file a name.png(file = "decision_tree.png") # Create the tree. output.tree <- ctree( nativeSpeaker ~ age + shoeSize + score, data = input.dat) # Plot the tree.plot(output.tree) # Save the file.dev.off() Output: null device 1 Loading required package: methods Loading required package: grid Loading required package: mvtnorm Loading required package: modeltools Loading required package: stats4 Loading required package: strucchange Loading required package: zoo Attaching package: ‘zoo’ The following objects are masked from ‘package:base’: as.Date, as.Date.numeric Loading required package: sandwich Naïve Bayes classification is a general classification method that uses a probability approach, hence also known as a probabilistic approach based on Bayes’ theorem with the assumption of independence between features. The model is trained on training dataset to make predictions by predict() function.Formula: P(A|B)=P(B|A)×P(A)P(B) It is a sample method in machine learning methods but can be useful in some instances. The training is easy and fast that just requires considering each predictor in each class separately.Application: It is used generally in sentimental analysis. Python3 library(caret)## Warning: package 'caret' was built under R version 3.4.3set.seed(7267166)trainIndex = createDataPartition(mydata$prog, p = 0.7)$Resample1train = mydata[trainIndex, ]test = mydata[-trainIndex, ] ## check the balanceprint(table(mydata$prog))#### academic general vocational## 105 45 50print(table(train$prog)) Output: ## Naive Bayes Classifier for Discrete Predictors ## ## Call: ## naiveBayes.default(x = X, y = Y, laplace = laplace) ## ## A-priori probabilities: ## Y ## academic general vocational ## 0.5248227 0.2269504 0.2482270 ## ## Conditional probabilities: ## science ## Y [, 1] [, 2] ## academic 54.21622 9.360761 ## general 52.18750 8.847954 ## vocational 47.31429 9.969871 ## ## socst ## Y [, 1] [, 2] ## academic 56.58108 9.635845 ## general 51.12500 8.377196 ## vocational 44.82857 10.279865 Another used classifier is the K-NN classifier. In pattern recognition, the k-nearest neighbor’s algorithm (k-NN) is a non-parametric method generally used for classification and regression. In both cases, the input consists of the k closest training examples in the feature space. In k-NN classification, the output is a class membership. Applications: Used in a variety of applications such as economic forecasting, data compression, and genetics.Example: Python3 # Write Python3 code hereimport numpy as npimport pandas as pdfrom matplotlib import pyplot as pltfrom sklearn.datasets import load_breast_cancerfrom sklearn.metrics import confusion_matrixfrom sklearn.neighbors import KNeighborsClassifierfrom sklearn.model_selection import train_test_splitimport seaborn as snssns.set()breast_cancer = load_breast_cancer()X = pd.DataFrame(breast_cancer.data, columns = breast_cancer.feature_names)X = X[['mean area', 'mean compactness']]y = pd.Categorical.from_codes(breast_cancer.target, breast_cancer.target_names)y = pd.get_dummies(y, drop_first = True)X_train, X_test, y_train, y_test = train_test_split(X, y, random_state = 1)sns.scatterplot( x ='mean area', y ='mean compactness', hue ='benign', data = X_test.join(y_test, how ='outer')) Output: A support vector machine (SVM) is a supervised binary machine learning algorithm that uses classification algorithms for two-group classification problems. After giving an SVM model sets of labeled training data for each category, they’re able to categorize new text.Mainly SVM is used for text classification problems. It classifies the unseen data. It is widely used than Naive Bayes.SVM id usually a fast and dependable classification algorithm that performs very well with a limited amount of data.Applications: SVMs have a number of applications in several fields like Bioinformatics, to classify genes, etc.Example: Python3 # Load the data from the csv filedataDirectory <- "D:/" # put your own folder heredata <- read.csv(paste(dataDirectory, 'regression.csv', sep =""), header = TRUE) # Plot the dataplot(data, pch = 16) # Create a linear regression modelmodel <- lm(Y ~ X, data) # Add the fitted lineabline(model) Output: varshagumber28 Picked R Language Write From Home Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n28 Feb, 2022" }, { "code": null, "e": 336, "s": 54, "text": "R is a very dynamic and versatile programming language for data science. This article deals with classification in R. Generally classifiers in R are used to predict specific category related information like reviews or ratings such as good, best or worst.Various Classifiers are: " }, { "code": null, "e": 351, "s": 336, "text": "Decision Trees" }, { "code": null, "e": 375, "s": 351, "text": "Naive Bayes Classifiers" }, { "code": null, "e": 392, "s": 375, "text": "K-NN Classifiers" }, { "code": null, "e": 423, "s": 392, "text": "Support Vector Machines(SVM’s)" }, { "code": null, "e": 1037, "s": 425, "text": "It is basically is a graph to represent choices. The nodes or vertices in the graph represent an event and the edges of the graph represent the decision conditions. Its common use is in Machine Learning and Data Mining applications.Applications: Spam/Non-spam classification of email, predicting of a tumor is cancerous or not. Usually, a model is constructed with noted data also called training dataset. Then a set of validation data is used to verify and improve the model. R has packages that are used to create and visualize decision trees. The R package “party” is used to create decision trees. Command: " }, { "code": null, "e": 1063, "s": 1037, "text": "install.packages(\"party\")" }, { "code": null, "e": 1073, "s": 1065, "text": "Python3" }, { "code": "# Load the party package. It will automatically load other# dependent packages.library(party) # Create the input data frame.input.data <- readingSkills[c(1:105), ] # Give the chart file a name.png(file = \"decision_tree.png\") # Create the tree. output.tree <- ctree( nativeSpeaker ~ age + shoeSize + score, data = input.dat) # Plot the tree.plot(output.tree) # Save the file.dev.off()", "e": 1460, "s": 1073, "text": null }, { "code": null, "e": 1470, "s": 1460, "text": "Output: " }, { "code": null, "e": 1879, "s": 1470, "text": "null device \n 1 \nLoading required package: methods\nLoading required package: grid\nLoading required package: mvtnorm\nLoading required package: modeltools\nLoading required package: stats4\nLoading required package: strucchange\nLoading required package: zoo\n\nAttaching package: ‘zoo’\n\nThe following objects are masked from ‘package:base’:\n\n as.Date, as.Date.numeric\n\nLoading required package: sandwich" }, { "code": null, "e": 2195, "s": 1881, "text": "Naïve Bayes classification is a general classification method that uses a probability approach, hence also known as a probabilistic approach based on Bayes’ theorem with the assumption of independence between features. The model is trained on training dataset to make predictions by predict() function.Formula: " }, { "code": null, "e": 2218, "s": 2195, "text": "P(A|B)=P(B|A)×P(A)P(B)" }, { "code": null, "e": 2467, "s": 2218, "text": "It is a sample method in machine learning methods but can be useful in some instances. The training is easy and fast that just requires considering each predictor in each class separately.Application: It is used generally in sentimental analysis. " }, { "code": null, "e": 2475, "s": 2467, "text": "Python3" }, { "code": "library(caret)## Warning: package 'caret' was built under R version 3.4.3set.seed(7267166)trainIndex = createDataPartition(mydata$prog, p = 0.7)$Resample1train = mydata[trainIndex, ]test = mydata[-trainIndex, ] ## check the balanceprint(table(mydata$prog))#### academic general vocational## 105 45 50print(table(train$prog))", "e": 2819, "s": 2475, "text": null }, { "code": null, "e": 2829, "s": 2819, "text": "Output: " }, { "code": null, "e": 3419, "s": 2829, "text": "## Naive Bayes Classifier for Discrete Predictors\n## \n## Call:\n## naiveBayes.default(x = X, y = Y, laplace = laplace)\n## \n## A-priori probabilities:\n## Y\n## academic general vocational \n## 0.5248227 0.2269504 0.2482270 \n## \n## Conditional probabilities:\n## science\n## Y [, 1] [, 2]\n## academic 54.21622 9.360761\n## general 52.18750 8.847954\n## vocational 47.31429 9.969871\n## \n## socst\n## Y [, 1] [, 2]\n## academic 56.58108 9.635845\n## general 51.12500 8.377196\n## vocational 44.82857 10.279865" }, { "code": null, "e": 3881, "s": 3421, "text": "Another used classifier is the K-NN classifier. In pattern recognition, the k-nearest neighbor’s algorithm (k-NN) is a non-parametric method generally used for classification and regression. In both cases, the input consists of the k closest training examples in the feature space. In k-NN classification, the output is a class membership. Applications: Used in a variety of applications such as economic forecasting, data compression, and genetics.Example: " }, { "code": null, "e": 3889, "s": 3881, "text": "Python3" }, { "code": "# Write Python3 code hereimport numpy as npimport pandas as pdfrom matplotlib import pyplot as pltfrom sklearn.datasets import load_breast_cancerfrom sklearn.metrics import confusion_matrixfrom sklearn.neighbors import KNeighborsClassifierfrom sklearn.model_selection import train_test_splitimport seaborn as snssns.set()breast_cancer = load_breast_cancer()X = pd.DataFrame(breast_cancer.data, columns = breast_cancer.feature_names)X = X[['mean area', 'mean compactness']]y = pd.Categorical.from_codes(breast_cancer.target, breast_cancer.target_names)y = pd.get_dummies(y, drop_first = True)X_train, X_test, y_train, y_test = train_test_split(X, y, random_state = 1)sns.scatterplot( x ='mean area', y ='mean compactness', hue ='benign', data = X_test.join(y_test, how ='outer'))", "e": 4680, "s": 3889, "text": null }, { "code": null, "e": 4690, "s": 4680, "text": "Output: " }, { "code": null, "e": 5316, "s": 4692, "text": "A support vector machine (SVM) is a supervised binary machine learning algorithm that uses classification algorithms for two-group classification problems. After giving an SVM model sets of labeled training data for each category, they’re able to categorize new text.Mainly SVM is used for text classification problems. It classifies the unseen data. It is widely used than Naive Bayes.SVM id usually a fast and dependable classification algorithm that performs very well with a limited amount of data.Applications: SVMs have a number of applications in several fields like Bioinformatics, to classify genes, etc.Example: " }, { "code": null, "e": 5324, "s": 5316, "text": "Python3" }, { "code": "# Load the data from the csv filedataDirectory <- \"D:/\" # put your own folder heredata <- read.csv(paste(dataDirectory, 'regression.csv', sep =\"\"), header = TRUE) # Plot the dataplot(data, pch = 16) # Create a linear regression modelmodel <- lm(Y ~ X, data) # Add the fitted lineabline(model)", "e": 5617, "s": 5324, "text": null }, { "code": null, "e": 5627, "s": 5617, "text": "Output: " }, { "code": null, "e": 5644, "s": 5629, "text": "varshagumber28" }, { "code": null, "e": 5651, "s": 5644, "text": "Picked" }, { "code": null, "e": 5662, "s": 5651, "text": "R Language" }, { "code": null, "e": 5678, "s": 5662, "text": "Write From Home" } ]
Combine multiple images using one dockerfile
When you are working on a large project on docker, you need to go through certain phases of the development cycle. Maintaining a different dockerfile for each cycle such as build, release, testing etc. eats up a lot of resources and is highly inefficient when it comes to productivity. In the later versions of docker, it allows us to use what is called multi-stage Dockerfile with the help of two particular commands - FROM and AS. We can use multiple FROM commands combined with AS commands in our Dockerfile where the last FROM command will actually build the image. All the FROM commands before that, will lead to the creation of intermediate images which are cached regularly. The AS command when used with the FROM command allows us to provide a virtual name for our intermediate images. Let us consider an example below for better understanding. #We create a base image. FROM ubuntu AS base #Install packages RUN apt-get -y update RUN apt-get -y vim #Create intermediate image layer Dependencies FROM base AS dependencies #Install dependencies using a requirements file RUN pip3 install -r requirements.txt #Create intermediate image layer for Testing FROM dependencies AS test #Set your work directory WORKDIR /usr/src/app COPY . . #Build the final image by running the test file CMD [“python3”, “./test.py”] As we can see in the above dockerfile, we have created two intermediate images called base and dependencies. The base intermediate image is an ubuntu image and we update it and install vim editor inside it. Using that base image, to create an intermediate image called dependencies, we install certain dependencies for our project which we can define in a separate file called requirements.txt. The final image is created by the test image layer where we define the working directory, copy the files and run the test.py file. The order of building the images is base, then dependencies and at last test. We also have to note that in case, any of the intermediate images fails to build, the final image cannot be created. Thus, creating a multi-stage dockerfile helps when you are working on a large scale project development with various phases of development surely helps us track the changes and progress efficiently.
[ { "code": null, "e": 1473, "s": 1187, "text": "When you are working on a large project on docker, you need to go through certain phases of the development cycle. Maintaining a different dockerfile for each cycle such as build, release, testing etc. eats up a lot of resources and is highly inefficient when it comes to productivity." }, { "code": null, "e": 1620, "s": 1473, "text": "In the later versions of docker, it allows us to use what is called multi-stage Dockerfile with the help of two particular commands - FROM and AS." }, { "code": null, "e": 1869, "s": 1620, "text": "We can use multiple FROM commands combined with AS commands in our Dockerfile where the last FROM command will actually build the image. All the FROM commands before that, will lead to the creation of intermediate images which are cached regularly." }, { "code": null, "e": 1981, "s": 1869, "text": "The AS command when used with the FROM command allows us to provide a virtual name for our intermediate images." }, { "code": null, "e": 2040, "s": 1981, "text": "Let us consider an example below for better understanding." }, { "code": null, "e": 2511, "s": 2040, "text": "#We create a base image.\nFROM ubuntu AS base\n\n#Install packages\nRUN apt-get -y update\nRUN apt-get -y vim\n\n#Create intermediate image layer Dependencies\nFROM base AS dependencies\n\n#Install dependencies using a requirements file\nRUN pip3 install -r requirements.txt\n\n#Create intermediate image layer for Testing\nFROM dependencies AS test\n\n#Set your work directory\nWORKDIR /usr/src/app\n\nCOPY . .\n\n#Build the final image by running the test file\nCMD [“python3”, “./test.py”]" }, { "code": null, "e": 3037, "s": 2511, "text": "As we can see in the above dockerfile, we have created two intermediate images called base and dependencies. The base intermediate image is an ubuntu image and we update it and install vim editor inside it. Using that base image, to create an intermediate image called dependencies, we install certain dependencies for our project which we can define in a separate file called requirements.txt. The final image is created by the test image layer where we define the working directory, copy the files and run the test.py file." }, { "code": null, "e": 3232, "s": 3037, "text": "The order of building the images is base, then dependencies and at last test. We also have to note that in case, any of the intermediate images fails to build, the final image cannot be created." }, { "code": null, "e": 3431, "s": 3232, "text": "Thus, creating a multi-stage dockerfile helps when you are working on a large scale project development with various phases of development surely helps us track the changes and progress efficiently." } ]
How to iterate over a JavaScript object ?
24 Oct, 2019 There are two methods to iterate over an object which are discussed below: Method 1: Using for...in loop: The properties of the object can be iterated over using a for..in loop. This loop is used to iterate over all non-Symbol iterable properties of an object. Some objects may contain properties that may be inherited from their prototypes. The hasOwnProperty() method can be used to check if the property belongs to the object itself. The value of each key of the object can be found by using the key as the index of the object. Syntax: for (let key in exampleObj) { if (exampleObj.hasOwnProperty(key)) { value = exampleObj[key]; console.log(key, value); }} Example: <!DOCTYPE html><html> <head> <title> How to iterate over a JavaScript object? </title></head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b> How to iterate over a JavaScript object? </b> <p> Click on the button to iterate through the javascript object. </p> <p> Check the console for the output </p> <button onclick="iterateObject()"> Iterate Object </button> <script type="text/javascript"> function iterateObject() { let exampleObj = { book: "Sherlock Holmes", author: "Arthur Conan Doyle", genre: "Mystery" }; for (let key in exampleObj) { if (exampleObj.hasOwnProperty(key)) { value = exampleObj[key]; console.log(key, value); } } } </script></body> </html> Output: Before clicking the button: After clicking the button: Method 2: Object.entries() map: The Object.entries() method is used to return an array of the object’s own enumerable string-keyed property pairs. The returned array is used with the map() method to extract the key and value from the pairs.The key and values from the key-value pair can be extracted by accessing the first and second index of the array pair. The first index corresponds to the key and the second index corresponds to the value of the pair. Syntax: Object.entries(exampleObj).map(entry => { let key = entry[0]; let value = entry[1]; console.log(key, value);}); Example: <!DOCTYPE html><html> <head> <title> How to iterate over a JavaScript object? </title></head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b> How to iterate over a JavaScript object? </b> <p> Click on the button to iterate through the javascript object. </p> <p> Check the console for the output </p> <button onclick="iterateObject()"> Iterate Object </button> <script type="text/javascript"> function iterateObject() { let exampleObj = { book: "Sherlock Holmes", author: "Arthur Conan Doyle", genre: "Mystery" }; Object.entries(exampleObj).map(entry => { let key = entry[0]; let value = entry[1]; console.log(key, value); }); } </script></body> </html> Output: Before clicking the button: After clicking the button: javascript-object Picked JavaScript Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array Hide or show elements in HTML using display property How to append HTML code to a div using JavaScript ? 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": "\n24 Oct, 2019" }, { "code": null, "e": 103, "s": 28, "text": "There are two methods to iterate over an object which are discussed below:" }, { "code": null, "e": 559, "s": 103, "text": "Method 1: Using for...in loop: The properties of the object can be iterated over using a for..in loop. This loop is used to iterate over all non-Symbol iterable properties of an object. Some objects may contain properties that may be inherited from their prototypes. The hasOwnProperty() method can be used to check if the property belongs to the object itself. The value of each key of the object can be found by using the key as the index of the object." }, { "code": null, "e": 567, "s": 559, "text": "Syntax:" }, { "code": "for (let key in exampleObj) { if (exampleObj.hasOwnProperty(key)) { value = exampleObj[key]; console.log(key, value); }}", "e": 708, "s": 567, "text": null }, { "code": null, "e": 717, "s": 708, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <title> How to iterate over a JavaScript object? </title></head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b> How to iterate over a JavaScript object? </b> <p> Click on the button to iterate through the javascript object. </p> <p> Check the console for the output </p> <button onclick=\"iterateObject()\"> Iterate Object </button> <script type=\"text/javascript\"> function iterateObject() { let exampleObj = { book: \"Sherlock Holmes\", author: \"Arthur Conan Doyle\", genre: \"Mystery\" }; for (let key in exampleObj) { if (exampleObj.hasOwnProperty(key)) { value = exampleObj[key]; console.log(key, value); } } } </script></body> </html>", "e": 1727, "s": 717, "text": null }, { "code": null, "e": 1735, "s": 1727, "text": "Output:" }, { "code": null, "e": 1763, "s": 1735, "text": "Before clicking the button:" }, { "code": null, "e": 1790, "s": 1763, "text": "After clicking the button:" }, { "code": null, "e": 2247, "s": 1790, "text": "Method 2: Object.entries() map: The Object.entries() method is used to return an array of the object’s own enumerable string-keyed property pairs. The returned array is used with the map() method to extract the key and value from the pairs.The key and values from the key-value pair can be extracted by accessing the first and second index of the array pair. The first index corresponds to the key and the second index corresponds to the value of the pair." }, { "code": null, "e": 2255, "s": 2247, "text": "Syntax:" }, { "code": "Object.entries(exampleObj).map(entry => { let key = entry[0]; let value = entry[1]; console.log(key, value);});", "e": 2376, "s": 2255, "text": null }, { "code": null, "e": 2385, "s": 2376, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <title> How to iterate over a JavaScript object? </title></head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b> How to iterate over a JavaScript object? </b> <p> Click on the button to iterate through the javascript object. </p> <p> Check the console for the output </p> <button onclick=\"iterateObject()\"> Iterate Object </button> <script type=\"text/javascript\"> function iterateObject() { let exampleObj = { book: \"Sherlock Holmes\", author: \"Arthur Conan Doyle\", genre: \"Mystery\" }; Object.entries(exampleObj).map(entry => { let key = entry[0]; let value = entry[1]; console.log(key, value); }); } </script></body> </html>", "e": 3353, "s": 2385, "text": null }, { "code": null, "e": 3361, "s": 3353, "text": "Output:" }, { "code": null, "e": 3389, "s": 3361, "text": "Before clicking the button:" }, { "code": null, "e": 3416, "s": 3389, "text": "After clicking the button:" }, { "code": null, "e": 3434, "s": 3416, "text": "javascript-object" }, { "code": null, "e": 3441, "s": 3434, "text": "Picked" }, { "code": null, "e": 3452, "s": 3441, "text": "JavaScript" }, { "code": null, "e": 3469, "s": 3452, "text": "Web Technologies" }, { "code": null, "e": 3496, "s": 3469, "text": "Web technologies Questions" }, { "code": null, "e": 3594, "s": 3496, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3655, "s": 3594, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 3727, "s": 3655, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 3767, "s": 3727, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 3820, "s": 3767, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 3872, "s": 3820, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 3934, "s": 3872, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 3967, "s": 3934, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 4028, "s": 3967, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 4078, "s": 4028, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Python program to check if lowercase letters exist in a string
23 Jun, 2022 Given a String, the task is to write a Python program to check if the string has lowercase letters or not. Examples: Input: "Live life to the fullest" Output: true Input: "LIVE LIFE TO THe FULLEST" Output: true Input: "LIVE LIFE TO THE FULLEST" Output: false Methods 1#: Using islower() It Returns true if all cased characters in the string are lowercase and there is at least one cased character, false otherwise. Python # Python code to demonstrate working of# is.lower() method in strings #Take any stringstr = "Live life to the Fullest" # Traversing Each character of# the string to check whether# it is in lowercasefor char in str: k = char.islower() if k == True: print('True') # Break the Loop when you # get any lowercase character. break # Default condition if the string# does not have any lowercase character.if(k != 1): print('False') Output: True Methods 2#: Using isupper() It Returns true if all cased characters in the string are uppercase and there is at least one cased character, false otherwise. Python # Python Program to demonstrate the# is.upper() method in strings#Take a stringstr = "GEEKS" # Traversing Each character# to check whether it is in uppercasefor char in str: k = char.isupper() if k == False: print('False') # Break the Loop # when you get any # uppercase character. break # Default condition if the string# does not have any uppercase character.if(k == 1): print('True') Output: True Methods 3#: Using ASCII Value to check whether a given character is in uppercase or lowercase. The ord() function returns an integer representing the Unicode character. Example: print(ord('A')) # 65 print(ord('a')) # 97 Python3 # Python Program to Demonstrate the strings# methods to check whether given Character# is in uppercase or lowercase with the help# of ASCII values #Input by geeksx = "GEeK" # countercounter = 0 for char in x: if(ord(char) >= 65 and ord(char) <= 90): counter = counter + 1 # Check for the condition # if the ASCII value is Between 97 and 122 # if condition is True print the # corresponding result if(ord(char) >= 97 and ord(char) <= 122): print("Lower Character found") breakif counter == len(x): print(True) Output: Lower Character found Method#4: Using re.search() re.search module is used to search for the pattern in string. We can use the lower case as a patter to search in string. Python3 # Python code to find the existence of# lower case in string# importing re moduleimport re #Take any stringstr1 = "Live life to the Fullest" # Searching lower case char in string using re.searchk = re.search('[a-z]',str1) # Default condition if search does not find# any lower case# else have lower case in stringif(k is None): print('False')else: print('True') Output: True satyam00so Python string-programs Technical Scripter 2020 Python Python Programs 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 OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python Program for Fibonacci numbers Python | Convert string dictionary to dictionary
[ { "code": null, "e": 28, "s": 0, "text": "\n23 Jun, 2022" }, { "code": null, "e": 135, "s": 28, "text": "Given a String, the task is to write a Python program to check if the string has lowercase letters or not." }, { "code": null, "e": 145, "s": 135, "text": "Examples:" }, { "code": null, "e": 289, "s": 145, "text": "Input: \"Live life to the fullest\"\nOutput: true\n\nInput: \"LIVE LIFE TO THe FULLEST\"\nOutput: true\n\nInput: \"LIVE LIFE TO THE FULLEST\"\nOutput: false" }, { "code": null, "e": 317, "s": 289, "text": "Methods 1#: Using islower()" }, { "code": null, "e": 445, "s": 317, "text": "It Returns true if all cased characters in the string are lowercase and there is at least one cased character, false otherwise." }, { "code": null, "e": 452, "s": 445, "text": "Python" }, { "code": "# Python code to demonstrate working of# is.lower() method in strings #Take any stringstr = \"Live life to the Fullest\" # Traversing Each character of# the string to check whether# it is in lowercasefor char in str: k = char.islower() if k == True: print('True') # Break the Loop when you # get any lowercase character. break # Default condition if the string# does not have any lowercase character.if(k != 1): print('False')", "e": 918, "s": 452, "text": null }, { "code": null, "e": 926, "s": 918, "text": "Output:" }, { "code": null, "e": 931, "s": 926, "text": "True" }, { "code": null, "e": 959, "s": 931, "text": "Methods 2#: Using isupper()" }, { "code": null, "e": 1087, "s": 959, "text": "It Returns true if all cased characters in the string are uppercase and there is at least one cased character, false otherwise." }, { "code": null, "e": 1094, "s": 1087, "text": "Python" }, { "code": "# Python Program to demonstrate the# is.upper() method in strings#Take a stringstr = \"GEEKS\" # Traversing Each character# to check whether it is in uppercasefor char in str: k = char.isupper() if k == False: print('False') # Break the Loop # when you get any # uppercase character. break # Default condition if the string# does not have any uppercase character.if(k == 1): print('True')", "e": 1535, "s": 1094, "text": null }, { "code": null, "e": 1543, "s": 1535, "text": "Output:" }, { "code": null, "e": 1548, "s": 1543, "text": "True" }, { "code": null, "e": 1643, "s": 1548, "text": "Methods 3#: Using ASCII Value to check whether a given character is in uppercase or lowercase." }, { "code": null, "e": 1717, "s": 1643, "text": "The ord() function returns an integer representing the Unicode character." }, { "code": null, "e": 1728, "s": 1717, "text": "Example: " }, { "code": null, "e": 1776, "s": 1728, "text": "print(ord('A')) # 65\nprint(ord('a')) # 97" }, { "code": null, "e": 1784, "s": 1776, "text": "Python3" }, { "code": "# Python Program to Demonstrate the strings# methods to check whether given Character# is in uppercase or lowercase with the help# of ASCII values #Input by geeksx = \"GEeK\" # countercounter = 0 for char in x: if(ord(char) >= 65 and ord(char) <= 90): counter = counter + 1 # Check for the condition # if the ASCII value is Between 97 and 122 # if condition is True print the # corresponding result if(ord(char) >= 97 and ord(char) <= 122): print(\"Lower Character found\") breakif counter == len(x): print(True)", "e": 2351, "s": 1784, "text": null }, { "code": null, "e": 2359, "s": 2351, "text": "Output:" }, { "code": null, "e": 2381, "s": 2359, "text": "Lower Character found" }, { "code": null, "e": 2531, "s": 2381, "text": "Method#4: Using re.search() re.search module is used to search for the pattern in string. We can use the lower case as a patter to search in string. " }, { "code": null, "e": 2539, "s": 2531, "text": "Python3" }, { "code": "# Python code to find the existence of# lower case in string# importing re moduleimport re #Take any stringstr1 = \"Live life to the Fullest\" # Searching lower case char in string using re.searchk = re.search('[a-z]',str1) # Default condition if search does not find# any lower case# else have lower case in stringif(k is None): print('False')else: print('True')", "e": 2915, "s": 2539, "text": null }, { "code": null, "e": 2923, "s": 2915, "text": "Output:" }, { "code": null, "e": 2928, "s": 2923, "text": "True" }, { "code": null, "e": 2939, "s": 2928, "text": "satyam00so" }, { "code": null, "e": 2962, "s": 2939, "text": "Python string-programs" }, { "code": null, "e": 2986, "s": 2962, "text": "Technical Scripter 2020" }, { "code": null, "e": 2993, "s": 2986, "text": "Python" }, { "code": null, "e": 3009, "s": 2993, "text": "Python Programs" }, { "code": null, "e": 3028, "s": 3009, "text": "Technical Scripter" }, { "code": null, "e": 3126, "s": 3028, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3158, "s": 3126, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 3185, "s": 3158, "text": "Python Classes and Objects" }, { "code": null, "e": 3206, "s": 3185, "text": "Python OOPs Concepts" }, { "code": null, "e": 3229, "s": 3206, "text": "Introduction To PYTHON" }, { "code": null, "e": 3285, "s": 3229, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 3307, "s": 3285, "text": "Defaultdict in Python" }, { "code": null, "e": 3346, "s": 3307, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 3384, "s": 3346, "text": "Python | Convert a list to dictionary" }, { "code": null, "e": 3421, "s": 3384, "text": "Python Program for Fibonacci numbers" } ]
Python | Stemming words with NLTK
08 Jun, 2022 Stemming is the process of producing morphological variants of a root/base word. Stemming programs are commonly referred to as stemming algorithms or stemmers. A stemming algorithm reduces the words “chocolates”, “chocolatey”, and “choco” to the root word, “chocolate” and “retrieval”, “retrieved”, “retrieves” reduce to the stem “retrieve”. Prerequisite: Introduction to Stemming Some more example of stemming for root word "like" include: -> "likes" -> "liked" -> "likely" -> "liking" Errors in Stemming: There are mainly two errors in stemming – Overstemming and Understemming. Overstemming occurs when two words are stemmed from the same root that are of different stems. Under-stemming occurs when two words are stemmed from the same root that is not of different stems. Applications of stemming are: Stemming is used in information retrieval systems like search engines. It is used to determine domain vocabularies in domain analysis. Stemming is desirable as it may reduce redundancy as most of the time the word stem and their inflected/derived words mean the same. Below is the implementation of stemming words using NLTK: Code #1: Python3 # import these modulesfrom nltk.stem import PorterStemmerfrom nltk.tokenize import word_tokenize ps = PorterStemmer() # choose some words to be stemmedwords = ["program", "programs", "programmer", "programming", "programmers"] for w in words: print(w, " : ", ps.stem(w)) Output: program : program programs : program programmer : program programming : program programmers : program Code #2: Stemming words from sentences Python3 # importing modulesfrom nltk.stem import PorterStemmerfrom nltk.tokenize import word_tokenize ps = PorterStemmer() sentence = "Programmers program with programming languages"words = word_tokenize(sentence) for w in words: print(w, " : ", ps.stem(w)) Output : Programmers : program program : program with : with programming : program languages : language sumitgumber28 sooda367 Code_r Machine Learning Python Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Getting started with Machine Learning Introduction to Recurrent Neural Network ML | Monte Carlo Tree Search (MCTS) Support Vector Machine Algorithm Random Forest Regression in Python Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe
[ { "code": null, "e": 53, "s": 25, "text": "\n08 Jun, 2022" }, { "code": null, "e": 395, "s": 53, "text": "Stemming is the process of producing morphological variants of a root/base word. Stemming programs are commonly referred to as stemming algorithms or stemmers. A stemming algorithm reduces the words “chocolates”, “chocolatey”, and “choco” to the root word, “chocolate” and “retrieval”, “retrieved”, “retrieves” reduce to the stem “retrieve”." }, { "code": null, "e": 434, "s": 395, "text": "Prerequisite: Introduction to Stemming" }, { "code": null, "e": 541, "s": 434, "text": "Some more example of stemming for root word \"like\" include:\n\n-> \"likes\"\n-> \"liked\"\n-> \"likely\"\n-> \"liking\"" }, { "code": null, "e": 830, "s": 541, "text": "Errors in Stemming: There are mainly two errors in stemming – Overstemming and Understemming. Overstemming occurs when two words are stemmed from the same root that are of different stems. Under-stemming occurs when two words are stemmed from the same root that is not of different stems." }, { "code": null, "e": 862, "s": 830, "text": "Applications of stemming are: " }, { "code": null, "e": 933, "s": 862, "text": "Stemming is used in information retrieval systems like search engines." }, { "code": null, "e": 997, "s": 933, "text": "It is used to determine domain vocabularies in domain analysis." }, { "code": null, "e": 1130, "s": 997, "text": "Stemming is desirable as it may reduce redundancy as most of the time the word stem and their inflected/derived words mean the same." }, { "code": null, "e": 1188, "s": 1130, "text": "Below is the implementation of stemming words using NLTK:" }, { "code": null, "e": 1199, "s": 1188, "text": "Code #1: " }, { "code": null, "e": 1207, "s": 1199, "text": "Python3" }, { "code": "# import these modulesfrom nltk.stem import PorterStemmerfrom nltk.tokenize import word_tokenize ps = PorterStemmer() # choose some words to be stemmedwords = [\"program\", \"programs\", \"programmer\", \"programming\", \"programmers\"] for w in words: print(w, \" : \", ps.stem(w))", "e": 1481, "s": 1207, "text": null }, { "code": null, "e": 1490, "s": 1481, "text": "Output: " }, { "code": null, "e": 1602, "s": 1490, "text": "program : program\nprograms : program\nprogrammer : program\nprogramming : program\nprogrammers : program" }, { "code": null, "e": 1641, "s": 1602, "text": "Code #2: Stemming words from sentences" }, { "code": null, "e": 1649, "s": 1641, "text": "Python3" }, { "code": "# importing modulesfrom nltk.stem import PorterStemmerfrom nltk.tokenize import word_tokenize ps = PorterStemmer() sentence = \"Programmers program with programming languages\"words = word_tokenize(sentence) for w in words: print(w, \" : \", ps.stem(w))", "e": 1902, "s": 1649, "text": null }, { "code": null, "e": 1912, "s": 1902, "text": "Output : " }, { "code": null, "e": 2017, "s": 1912, "text": "Programmers : program\nprogram : program\nwith : with\nprogramming : program\nlanguages : language" }, { "code": null, "e": 2031, "s": 2017, "text": "sumitgumber28" }, { "code": null, "e": 2040, "s": 2031, "text": "sooda367" }, { "code": null, "e": 2047, "s": 2040, "text": "Code_r" }, { "code": null, "e": 2064, "s": 2047, "text": "Machine Learning" }, { "code": null, "e": 2071, "s": 2064, "text": "Python" }, { "code": null, "e": 2088, "s": 2071, "text": "Machine Learning" }, { "code": null, "e": 2186, "s": 2088, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2224, "s": 2186, "text": "Getting started with Machine Learning" }, { "code": null, "e": 2265, "s": 2224, "text": "Introduction to Recurrent Neural Network" }, { "code": null, "e": 2301, "s": 2265, "text": "ML | Monte Carlo Tree Search (MCTS)" }, { "code": null, "e": 2334, "s": 2301, "text": "Support Vector Machine Algorithm" }, { "code": null, "e": 2369, "s": 2334, "text": "Random Forest Regression in Python" }, { "code": null, "e": 2397, "s": 2369, "text": "Read JSON file using Python" }, { "code": null, "e": 2447, "s": 2397, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 2469, "s": 2447, "text": "Python map() function" } ]
How to multiply a matrix by its transpose while ignoring missing values in R ?
21 Apr, 2021 In this article, we will discuss how to multiply a matrix by its transpose while ignoring the missing values in R Programming Language. It can be done by replacing all the NAs by 0 in the matrix The replacement of values, can be performed in O(n*m), where n is the number of rows and m is the number of columns. Replacing by 0s doesn’t affect the multiplicative product, and therefore, this is an effective solution. The transpose can then be calculated by using t(matrix). The product can be calculated by the following syntax in R : m1 %*% m2 , where m1 and m2 are the matrices involved. If m1 is the matrix of n*m dimensions and m2 of m*n (since it’s the transpose), the product matrix obtained is a square matrix is n * n . Example 1: R # declaring matrix mat = matrix(c(1, NA, 2, 3, NA, 4), ncol = 2) # replacing matrix NA with 0smat[is.na(mat)] = 0 # printing original matrixprint ("Original Matrix")print (mat) # calculating transpose of the# matrixtransmat = t(mat)print ("Transpose Matrix")print (transmat) # calculating product of matricesprod = mat%*%transmatprint ("Product Matrix")print (prod) Output: [1] "Original Matrix" [,1] [,2] [1,] 1 3 [2,] 0 0 [3,] 2 4 [1] "Transpose Matrix" [,1] [,2] [,3] [1,] 1 0 2 [2,] 3 0 4 [1] "Product Matrix" [,1] [,2] [,3] [1,] 10 0 14 [2,] 0 0 0 [3,] 14 0 20 The original matrix is of the dimensions 3 x 2 and the transpose is of the dimension 2×3. On replacing the missing values with 0 and multiplying these two together, we obtain the product matrix equivalent to 3×3 square matrix. Example 2: The original matrix is of the dimensions 1 x 3 and the transpose is of the dimension 3×1. On replacing the missing values with 0 and multiplying these two together, we obtain the product matrix equivalent to 1×1 square matrix, which is basically a singular cell matrix. R # declaring matrix mat = matrix(c(10, NA, 7), ncol = 3) # replacing matrix NA with 0smat[is.na(mat)] = 0 # printing original matrixprint ("Original Matrix")print (mat) # calculating transpose of the# matrixtransmat = t(mat)print ("Transpose Matrix")print (transmat) # calculating product of matricesprod = mat%*%transmatprint ("Product Matrix")print (prod) Output [1] "Original Matrix" [,1] [,2] [,3] [1,] 10 0 7 [1] "Transpose Matrix" [,1] [1,] 10 [2,] 0 [3,] 7 [1] "Product Matrix" [,1] [1,] 149 Picked R Matrix-Programs R-Matrix R Language R Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Filter data by multiple conditions in R using Dplyr How to Replace specific values in column in R DataFrame ? Change Color of Bars in Barchart using ggplot2 in R How to Split Column Into Multiple Columns in R DataFrame? Loops in R (for, while, repeat) How to Replace specific values in column in R DataFrame ? How to Split Column Into Multiple Columns in R DataFrame? How to change Row Names of DataFrame in R ? How to filter R DataFrame by values in a column? Replace Specific Characters in String in R
[ { "code": null, "e": 28, "s": 0, "text": "\n21 Apr, 2021" }, { "code": null, "e": 223, "s": 28, "text": "In this article, we will discuss how to multiply a matrix by its transpose while ignoring the missing values in R Programming Language. It can be done by replacing all the NAs by 0 in the matrix" }, { "code": null, "e": 564, "s": 223, "text": "The replacement of values, can be performed in O(n*m), where n is the number of rows and m is the number of columns. Replacing by 0s doesn’t affect the multiplicative product, and therefore, this is an effective solution. The transpose can then be calculated by using t(matrix). The product can be calculated by the following syntax in R : " }, { "code": null, "e": 620, "s": 564, "text": "m1 %*% m2 , where m1 and m2 are the matrices involved. " }, { "code": null, "e": 758, "s": 620, "text": "If m1 is the matrix of n*m dimensions and m2 of m*n (since it’s the transpose), the product matrix obtained is a square matrix is n * n ." }, { "code": null, "e": 769, "s": 758, "text": "Example 1:" }, { "code": null, "e": 771, "s": 769, "text": "R" }, { "code": "# declaring matrix mat = matrix(c(1, NA, 2, 3, NA, 4), ncol = 2) # replacing matrix NA with 0smat[is.na(mat)] = 0 # printing original matrixprint (\"Original Matrix\")print (mat) # calculating transpose of the# matrixtransmat = t(mat)print (\"Transpose Matrix\")print (transmat) # calculating product of matricesprod = mat%*%transmatprint (\"Product Matrix\")print (prod)", "e": 1141, "s": 771, "text": null }, { "code": null, "e": 1149, "s": 1141, "text": "Output:" }, { "code": null, "e": 1412, "s": 1149, "text": "[1] \"Original Matrix\"\n [,1] [,2]\n[1,] 1 3\n[2,] 0 0\n[3,] 2 4\n[1] \"Transpose Matrix\"\n [,1] [,2] [,3]\n[1,] 1 0 2\n[2,] 3 0 4\n[1] \"Product Matrix\"\n [,1] [,2] [,3]\n[1,] 10 0 14\n[2,] 0 0 0\n[3,] 14 0 20" }, { "code": null, "e": 1640, "s": 1412, "text": "The original matrix is of the dimensions 3 x 2 and the transpose is of the dimension 2×3. On replacing the missing values with 0 and multiplying these two together, we obtain the product matrix equivalent to 3×3 square matrix. " }, { "code": null, "e": 1922, "s": 1640, "text": "Example 2: The original matrix is of the dimensions 1 x 3 and the transpose is of the dimension 3×1. On replacing the missing values with 0 and multiplying these two together, we obtain the product matrix equivalent to 1×1 square matrix, which is basically a singular cell matrix. " }, { "code": null, "e": 1924, "s": 1922, "text": "R" }, { "code": "# declaring matrix mat = matrix(c(10, NA, 7), ncol = 3) # replacing matrix NA with 0smat[is.na(mat)] = 0 # printing original matrixprint (\"Original Matrix\")print (mat) # calculating transpose of the# matrixtransmat = t(mat)print (\"Transpose Matrix\")print (transmat) # calculating product of matricesprod = mat%*%transmatprint (\"Product Matrix\")print (prod)", "e": 2285, "s": 1924, "text": null }, { "code": null, "e": 2292, "s": 2285, "text": "Output" }, { "code": null, "e": 2455, "s": 2292, "text": "[1] \"Original Matrix\"\n [,1] [,2] [,3]\n[1,] 10 0 7\n[1] \"Transpose Matrix\"\n [,1]\n[1,] 10\n[2,] 0\n[3,] 7\n[1] \"Product Matrix\"\n [,1]\n[1,] 149" }, { "code": null, "e": 2462, "s": 2455, "text": "Picked" }, { "code": null, "e": 2480, "s": 2462, "text": "R Matrix-Programs" }, { "code": null, "e": 2489, "s": 2480, "text": "R-Matrix" }, { "code": null, "e": 2500, "s": 2489, "text": "R Language" }, { "code": null, "e": 2511, "s": 2500, "text": "R Programs" }, { "code": null, "e": 2609, "s": 2511, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2661, "s": 2609, "text": "Filter data by multiple conditions in R using Dplyr" }, { "code": null, "e": 2719, "s": 2661, "text": "How to Replace specific values in column in R DataFrame ?" }, { "code": null, "e": 2771, "s": 2719, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 2829, "s": 2771, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 2861, "s": 2829, "text": "Loops in R (for, while, repeat)" }, { "code": null, "e": 2919, "s": 2861, "text": "How to Replace specific values in column in R DataFrame ?" }, { "code": null, "e": 2977, "s": 2919, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 3021, "s": 2977, "text": "How to change Row Names of DataFrame in R ?" }, { "code": null, "e": 3070, "s": 3021, "text": "How to filter R DataFrame by values in a column?" } ]
Node.js http.ServerResponse.end() Method
25 Dec, 2020 The httpServerResponse.end() is an inbuilt application programming interface of class Server Response within http module which is used to send the signal to the server that all the header has been sent. Syntax: response.end(data, Encodingtype, Callbackfunction) Parameters: This method takes three Parameters Data: Chunk of data that has to be sent Encoding Type: Type encoding for the data Callback: Callback function for further operation if necessary. Return Value: This method returns this Server Response object. Example 1: Filename: index.js Javascript // Node.js program to demonstrate the // response.end() method // Importing http module var http = require('http'); // Setting up PORT const PORT = process.env.PORT || 3000; // Creating http Server var httpServer = http.createServer( function(request, response){ // Getting connection by using // response.connection method const value = response.connection; // Ending the response response.end( "port address : " + value.address().port, 'utf8', () => { console.log("displaying the result..."); // Closing the server httpServer.close(()=>{ console.log("server is closed") }) }); }); // Listening to http Server httpServer.listen(PORT, () => { console.log("Server is running at port 3000..."); }); Execution command: node index.js Console output: Server is running at port 3000... displaying the result... displaying the result... server is closed server is closed Browser Output: Paste the localhost address http://localhost:3000/. In the search bar of the browser. port address : 3000 Example 2: Filename: index.js Javascript // Node.js program to demonstrate the // response.end() method // Importing http module var http = require('http'); // Request and response handler const http2Handlers = (request, response) => { // Getting connection // by using response.connection Api const value = response.connection; // Display result by using end() // api and ending the response response.end( "family : " + value.address().family, 'utf8', () => { console.log("displaying the result..."); httpServer.close(()=>{ console.log("server is closed") }) }); }; // Creating http Server and listening// on the 3000 portvar httpServer = http.createServer( http2Handlers).listen(3000, () => { console.log("Server is running at port 3000..."); }); Execution command: node index.js Console output: Server is running at port 3000... displaying the result... displaying the result... server is closed server is closed Browser Output: Paste the localhost address http://localhost:3000/. In the search bar of the browser. family : IPv6 Reference: https://nodejs.org/dist/latest-v12.x/docs/api/http.html#http_response_end_data_encoding_callback Node.js-Methods Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. JWT Authentication with Node.js Installation of Node.js on Windows Difference between dependencies, devDependencies and peerDependencies Mongoose Populate() Method Mongoose find() Function Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ? Differences between Functional Components and Class Components in React
[ { "code": null, "e": 28, "s": 0, "text": "\n25 Dec, 2020" }, { "code": null, "e": 231, "s": 28, "text": "The httpServerResponse.end() is an inbuilt application programming interface of class Server Response within http module which is used to send the signal to the server that all the header has been sent." }, { "code": null, "e": 239, "s": 231, "text": "Syntax:" }, { "code": null, "e": 290, "s": 239, "text": "response.end(data, Encodingtype, Callbackfunction)" }, { "code": null, "e": 337, "s": 290, "text": "Parameters: This method takes three Parameters" }, { "code": null, "e": 377, "s": 337, "text": "Data: Chunk of data that has to be sent" }, { "code": null, "e": 419, "s": 377, "text": "Encoding Type: Type encoding for the data" }, { "code": null, "e": 483, "s": 419, "text": "Callback: Callback function for further operation if necessary." }, { "code": null, "e": 546, "s": 483, "text": "Return Value: This method returns this Server Response object." }, { "code": null, "e": 576, "s": 546, "text": "Example 1: Filename: index.js" }, { "code": null, "e": 587, "s": 576, "text": "Javascript" }, { "code": "// Node.js program to demonstrate the // response.end() method // Importing http module var http = require('http'); // Setting up PORT const PORT = process.env.PORT || 3000; // Creating http Server var httpServer = http.createServer( function(request, response){ // Getting connection by using // response.connection method const value = response.connection; // Ending the response response.end( \"port address : \" + value.address().port, 'utf8', () => { console.log(\"displaying the result...\"); // Closing the server httpServer.close(()=>{ console.log(\"server is closed\") }) }); }); // Listening to http Server httpServer.listen(PORT, () => { console.log(\"Server is running at port 3000...\"); });", "e": 1353, "s": 587, "text": null }, { "code": null, "e": 1372, "s": 1353, "text": "Execution command:" }, { "code": null, "e": 1386, "s": 1372, "text": "node index.js" }, { "code": null, "e": 1402, "s": 1386, "text": "Console output:" }, { "code": null, "e": 1520, "s": 1402, "text": "Server is running at port 3000...\ndisplaying the result...\ndisplaying the result...\nserver is closed\nserver is closed" }, { "code": null, "e": 1536, "s": 1520, "text": "Browser Output:" }, { "code": null, "e": 1622, "s": 1536, "text": "Paste the localhost address http://localhost:3000/. In the search bar of the browser." }, { "code": null, "e": 1642, "s": 1622, "text": "port address : 3000" }, { "code": null, "e": 1672, "s": 1642, "text": "Example 2: Filename: index.js" }, { "code": null, "e": 1683, "s": 1672, "text": "Javascript" }, { "code": "// Node.js program to demonstrate the // response.end() method // Importing http module var http = require('http'); // Request and response handler const http2Handlers = (request, response) => { // Getting connection // by using response.connection Api const value = response.connection; // Display result by using end() // api and ending the response response.end( \"family : \" + value.address().family, 'utf8', () => { console.log(\"displaying the result...\"); httpServer.close(()=>{ console.log(\"server is closed\") }) }); }; // Creating http Server and listening// on the 3000 portvar httpServer = http.createServer( http2Handlers).listen(3000, () => { console.log(\"Server is running at port 3000...\"); });", "e": 2459, "s": 1683, "text": null }, { "code": null, "e": 2478, "s": 2459, "text": "Execution command:" }, { "code": null, "e": 2492, "s": 2478, "text": "node index.js" }, { "code": null, "e": 2508, "s": 2492, "text": "Console output:" }, { "code": null, "e": 2626, "s": 2508, "text": "Server is running at port 3000...\ndisplaying the result...\ndisplaying the result...\nserver is closed\nserver is closed" }, { "code": null, "e": 2642, "s": 2626, "text": "Browser Output:" }, { "code": null, "e": 2728, "s": 2642, "text": "Paste the localhost address http://localhost:3000/. In the search bar of the browser." }, { "code": null, "e": 2743, "s": 2728, "text": "family : IPv6" }, { "code": null, "e": 2851, "s": 2743, "text": "Reference: https://nodejs.org/dist/latest-v12.x/docs/api/http.html#http_response_end_data_encoding_callback" }, { "code": null, "e": 2867, "s": 2851, "text": "Node.js-Methods" }, { "code": null, "e": 2875, "s": 2867, "text": "Node.js" }, { "code": null, "e": 2892, "s": 2875, "text": "Web Technologies" }, { "code": null, "e": 2990, "s": 2892, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3022, "s": 2990, "text": "JWT Authentication with Node.js" }, { "code": null, "e": 3057, "s": 3022, "text": "Installation of Node.js on Windows" }, { "code": null, "e": 3127, "s": 3057, "text": "Difference between dependencies, devDependencies and peerDependencies" }, { "code": null, "e": 3154, "s": 3127, "text": "Mongoose Populate() Method" }, { "code": null, "e": 3179, "s": 3154, "text": "Mongoose find() Function" }, { "code": null, "e": 3241, "s": 3179, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 3302, "s": 3241, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 3352, "s": 3302, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 3395, "s": 3352, "text": "How to fetch data from an API in ReactJS ?" } ]
Student management system in Python
29 Dec, 2020 Prerequisite: Classes and objects in python Problem Statement:Write a program to build a simple Student Management System using Python which can perform following operations: AcceptDisplaySearchDeleteUpdate Accept Display Search Delete Update Approach: Below is the approach to do the above operations: Accept – This method takes details from the user like name, roll number, and marks for two different subjects.# Method to enter new student details def accept(self, Name, Rollno, marks1, marks2 ): # Creates a new class constructor # and pass the details ob = Student(Name, Rollno, marks1, marks2 ) # list containing objects of student class ls.append(ob) Display – This method displays the details of every student.# Function to display student details def display(self, ob): print("Name : ", ob.name) print("RollNo : ", ob.rollno) print("Marks1 : ", ob.m1) print("Marks2 : ", ob.m2) print("\n") Search – This method searches for a particular student from the list of students.This method will ask the user for roll number and then search according to the roll number# Search Function def search(self, rn): for i in range(ls.__len__()): # iterate through the list containing # student object and checks through # roll no of each object if(ls[i].rollno == rn): # returns the object with matching # roll number return i Delete – This method deletes the record of a particular student with a matching roll number.# Delete Function def delete(self, rn): # Calls the search function # created above i = obj.search(rn) del ls[i] Update – This method updates the roll number of the student.This method will ask for the old roll number and new roll number. It will replace the old roll number with new roll number.# Update Function def update(self, rn, No): # calling the search function # of student class i = obj.search(rn) ls[i].rollno = No Below is the implementation of the above approach:# This is simplest Student data management program in python# Create class "Student"class Student: # Constructor def __init__(self, name, rollno, m1, m2): self.name = name self.rollno = rollno self.m1 = m1 self.m2 = m2 # Function to create and append new student def accept(self, Name, Rollno, marks1, marks2 ): # use ' int(input()) ' method to take input from user ob = Student(Name, Rollno, marks1, marks2 ) ls.append(ob) # Function to display student details def display(self, ob): print("Name : ", ob.name) print("RollNo : ", ob.rollno) print("Marks1 : ", ob.m1) print("Marks2 : ", ob.m2) print("\n") # Search Function def search(self, rn): for i in range(ls.__len__()): if(ls[i].rollno == rn): return i # Delete Function def delete(self, rn): i = obj.search(rn) del ls[i] # Update Function def update(self, rn, No): i = obj.search(rn) roll = No ls[i].rollno = roll; # Create a list to add Studentsls =[]# an object of Student classobj = Student('', 0, 0, 0) print("\nOperations used, ")print("\n1.Accept Student details\n2.Display Student Details\n" / / "3.Search Details of a Student\n4.Delete Details of Student" / / "\n5.Update Student Details\n6.Exit") # ch = int(input("Enter choice:"))# if(ch == 1):obj.accept("A", 1, 100, 100)obj.accept("B", 2, 90, 90)obj.accept("C", 3, 80, 80) # elif(ch == 2):print("\n")print("\nList of Students\n")for i in range(ls.__len__()): obj.display(ls[i]) # elif(ch == 3):print("\n Student Found, ")s = obj.search(2)obj.display(ls[s]) # elif(ch == 4):obj.delete(2)print(ls.__len__())print("List after deletion")for i in range(ls.__len__()): obj.display(ls[i]) # elif(ch == 5):obj.update(3, 2)print(ls.__len__())print("List after updation")for i in range(ls.__len__()): obj.display(ls[i]) # else:print("Thank You !") Output:Operations used, 1.Accept Student details 2.Display Student Details 3.Search Details of a Student 4.Delete Details of Student 5.Update Student Details 6.Exit List of Students Name : A RollNo : 1 Marks1 : 100 Marks2 : 100 Name : B RollNo : 2 Marks1 : 90 Marks2 : 90 Name : C RollNo : 3 Marks1 : 80 Marks2 : 80 Student Found, Name : B RollNo : 2 Marks1 : 90 Marks2 : 90 2 List after deletion Name : A RollNo : 1 Marks1 : 100 Marks2 : 100 Name : C RollNo : 3 Marks1 : 80 Marks2 : 80 2 List after updation Name : A RollNo : 1 Marks1 : 100 Marks2 : 100 Name : C RollNo : 2 Marks1 : 80 Marks2 : 80 Thank You ! My Personal Notes arrow_drop_upSave Accept – This method takes details from the user like name, roll number, and marks for two different subjects.# Method to enter new student details def accept(self, Name, Rollno, marks1, marks2 ): # Creates a new class constructor # and pass the details ob = Student(Name, Rollno, marks1, marks2 ) # list containing objects of student class ls.append(ob) # Method to enter new student details def accept(self, Name, Rollno, marks1, marks2 ): # Creates a new class constructor # and pass the details ob = Student(Name, Rollno, marks1, marks2 ) # list containing objects of student class ls.append(ob) Display – This method displays the details of every student.# Function to display student details def display(self, ob): print("Name : ", ob.name) print("RollNo : ", ob.rollno) print("Marks1 : ", ob.m1) print("Marks2 : ", ob.m2) print("\n") # Function to display student details def display(self, ob): print("Name : ", ob.name) print("RollNo : ", ob.rollno) print("Marks1 : ", ob.m1) print("Marks2 : ", ob.m2) print("\n") Search – This method searches for a particular student from the list of students.This method will ask the user for roll number and then search according to the roll number# Search Function def search(self, rn): for i in range(ls.__len__()): # iterate through the list containing # student object and checks through # roll no of each object if(ls[i].rollno == rn): # returns the object with matching # roll number return i # Search Function def search(self, rn): for i in range(ls.__len__()): # iterate through the list containing # student object and checks through # roll no of each object if(ls[i].rollno == rn): # returns the object with matching # roll number return i Delete – This method deletes the record of a particular student with a matching roll number.# Delete Function def delete(self, rn): # Calls the search function # created above i = obj.search(rn) del ls[i] # Delete Function def delete(self, rn): # Calls the search function # created above i = obj.search(rn) del ls[i] Update – This method updates the roll number of the student.This method will ask for the old roll number and new roll number. It will replace the old roll number with new roll number.# Update Function def update(self, rn, No): # calling the search function # of student class i = obj.search(rn) ls[i].rollno = No Below is the implementation of the above approach:# This is simplest Student data management program in python# Create class "Student"class Student: # Constructor def __init__(self, name, rollno, m1, m2): self.name = name self.rollno = rollno self.m1 = m1 self.m2 = m2 # Function to create and append new student def accept(self, Name, Rollno, marks1, marks2 ): # use ' int(input()) ' method to take input from user ob = Student(Name, Rollno, marks1, marks2 ) ls.append(ob) # Function to display student details def display(self, ob): print("Name : ", ob.name) print("RollNo : ", ob.rollno) print("Marks1 : ", ob.m1) print("Marks2 : ", ob.m2) print("\n") # Search Function def search(self, rn): for i in range(ls.__len__()): if(ls[i].rollno == rn): return i # Delete Function def delete(self, rn): i = obj.search(rn) del ls[i] # Update Function def update(self, rn, No): i = obj.search(rn) roll = No ls[i].rollno = roll; # Create a list to add Studentsls =[]# an object of Student classobj = Student('', 0, 0, 0) print("\nOperations used, ")print("\n1.Accept Student details\n2.Display Student Details\n" / / "3.Search Details of a Student\n4.Delete Details of Student" / / "\n5.Update Student Details\n6.Exit") # ch = int(input("Enter choice:"))# if(ch == 1):obj.accept("A", 1, 100, 100)obj.accept("B", 2, 90, 90)obj.accept("C", 3, 80, 80) # elif(ch == 2):print("\n")print("\nList of Students\n")for i in range(ls.__len__()): obj.display(ls[i]) # elif(ch == 3):print("\n Student Found, ")s = obj.search(2)obj.display(ls[s]) # elif(ch == 4):obj.delete(2)print(ls.__len__())print("List after deletion")for i in range(ls.__len__()): obj.display(ls[i]) # elif(ch == 5):obj.update(3, 2)print(ls.__len__())print("List after updation")for i in range(ls.__len__()): obj.display(ls[i]) # else:print("Thank You !") Output:Operations used, 1.Accept Student details 2.Display Student Details 3.Search Details of a Student 4.Delete Details of Student 5.Update Student Details 6.Exit List of Students Name : A RollNo : 1 Marks1 : 100 Marks2 : 100 Name : B RollNo : 2 Marks1 : 90 Marks2 : 90 Name : C RollNo : 3 Marks1 : 80 Marks2 : 80 Student Found, Name : B RollNo : 2 Marks1 : 90 Marks2 : 90 2 List after deletion Name : A RollNo : 1 Marks1 : 100 Marks2 : 100 Name : C RollNo : 3 Marks1 : 80 Marks2 : 80 2 List after updation Name : A RollNo : 1 Marks1 : 100 Marks2 : 100 Name : C RollNo : 2 Marks1 : 80 Marks2 : 80 Thank You ! My Personal Notes arrow_drop_upSave # Update Function def update(self, rn, No): # calling the search function # of student class i = obj.search(rn) ls[i].rollno = No Below is the implementation of the above approach: # This is simplest Student data management program in python# Create class "Student"class Student: # Constructor def __init__(self, name, rollno, m1, m2): self.name = name self.rollno = rollno self.m1 = m1 self.m2 = m2 # Function to create and append new student def accept(self, Name, Rollno, marks1, marks2 ): # use ' int(input()) ' method to take input from user ob = Student(Name, Rollno, marks1, marks2 ) ls.append(ob) # Function to display student details def display(self, ob): print("Name : ", ob.name) print("RollNo : ", ob.rollno) print("Marks1 : ", ob.m1) print("Marks2 : ", ob.m2) print("\n") # Search Function def search(self, rn): for i in range(ls.__len__()): if(ls[i].rollno == rn): return i # Delete Function def delete(self, rn): i = obj.search(rn) del ls[i] # Update Function def update(self, rn, No): i = obj.search(rn) roll = No ls[i].rollno = roll; # Create a list to add Studentsls =[]# an object of Student classobj = Student('', 0, 0, 0) print("\nOperations used, ")print("\n1.Accept Student details\n2.Display Student Details\n" / / "3.Search Details of a Student\n4.Delete Details of Student" / / "\n5.Update Student Details\n6.Exit") # ch = int(input("Enter choice:"))# if(ch == 1):obj.accept("A", 1, 100, 100)obj.accept("B", 2, 90, 90)obj.accept("C", 3, 80, 80) # elif(ch == 2):print("\n")print("\nList of Students\n")for i in range(ls.__len__()): obj.display(ls[i]) # elif(ch == 3):print("\n Student Found, ")s = obj.search(2)obj.display(ls[s]) # elif(ch == 4):obj.delete(2)print(ls.__len__())print("List after deletion")for i in range(ls.__len__()): obj.display(ls[i]) # elif(ch == 5):obj.update(3, 2)print(ls.__len__())print("List after updation")for i in range(ls.__len__()): obj.display(ls[i]) # else:print("Thank You !") Operations used, 1.Accept Student details 2.Display Student Details 3.Search Details of a Student 4.Delete Details of Student 5.Update Student Details 6.Exit List of Students Name : A RollNo : 1 Marks1 : 100 Marks2 : 100 Name : B RollNo : 2 Marks1 : 90 Marks2 : 90 Name : C RollNo : 3 Marks1 : 80 Marks2 : 80 Student Found, Name : B RollNo : 2 Marks1 : 90 Marks2 : 90 2 List after deletion Name : A RollNo : 1 Marks1 : 100 Marks2 : 100 Name : C RollNo : 3 Marks1 : 80 Marks2 : 80 2 List after updation Name : A RollNo : 1 Marks1 : 100 Marks2 : 100 Name : C RollNo : 2 Marks1 : 80 Marks2 : 80 Thank You ! Akanksha_Rai Python Oops-programs Python-OOP Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Iterate over a list in Python Python OOPs Concepts
[ { "code": null, "e": 54, "s": 26, "text": "\n29 Dec, 2020" }, { "code": null, "e": 98, "s": 54, "text": "Prerequisite: Classes and objects in python" }, { "code": null, "e": 229, "s": 98, "text": "Problem Statement:Write a program to build a simple Student Management System using Python which can perform following operations:" }, { "code": null, "e": 261, "s": 229, "text": "AcceptDisplaySearchDeleteUpdate" }, { "code": null, "e": 268, "s": 261, "text": "Accept" }, { "code": null, "e": 276, "s": 268, "text": "Display" }, { "code": null, "e": 283, "s": 276, "text": "Search" }, { "code": null, "e": 290, "s": 283, "text": "Delete" }, { "code": null, "e": 297, "s": 290, "text": "Update" }, { "code": null, "e": 357, "s": 297, "text": "Approach: Below is the approach to do the above operations:" }, { "code": null, "e": 5012, "s": 357, "text": "Accept – This method takes details from the user like name, roll number, and marks for two different subjects.# Method to enter new student details\ndef accept(self, Name, Rollno, marks1, marks2 ):\n # Creates a new class constructor\n # and pass the details\n ob = Student(Name, Rollno, marks1, marks2 )\n\n # list containing objects of student class\n ls.append(ob)\nDisplay – This method displays the details of every student.# Function to display student details \ndef display(self, ob):\n print(\"Name : \", ob.name)\n print(\"RollNo : \", ob.rollno)\n print(\"Marks1 : \", ob.m1)\n print(\"Marks2 : \", ob.m2)\n print(\"\\n\") \nSearch – This method searches for a particular student from the list of students.This method will ask the user for roll number and then search according to the roll number# Search Function \ndef search(self, rn):\n for i in range(ls.__len__()):\n # iterate through the list containing\n # student object and checks through\n # roll no of each object\n if(ls[i].rollno == rn):\n # returns the object with matching \n # roll number\n return i \nDelete – This method deletes the record of a particular student with a matching roll number.# Delete Function \ndef delete(self, rn):\n # Calls the search function \n # created above\n i = obj.search(rn) \n del ls[i]\nUpdate – This method updates the roll number of the student.This method will ask for the old roll number and new roll number. It will replace the old roll number with new roll number.# Update Function \ndef update(self, rn, No):\n # calling the search function\n # of student class\n i = obj.search(rn)\n ls[i].rollno = No\nBelow is the implementation of the above approach:# This is simplest Student data management program in python# Create class \"Student\"class Student: # Constructor def __init__(self, name, rollno, m1, m2): self.name = name self.rollno = rollno self.m1 = m1 self.m2 = m2 # Function to create and append new student def accept(self, Name, Rollno, marks1, marks2 ): # use ' int(input()) ' method to take input from user ob = Student(Name, Rollno, marks1, marks2 ) ls.append(ob) # Function to display student details def display(self, ob): print(\"Name : \", ob.name) print(\"RollNo : \", ob.rollno) print(\"Marks1 : \", ob.m1) print(\"Marks2 : \", ob.m2) print(\"\\n\") # Search Function def search(self, rn): for i in range(ls.__len__()): if(ls[i].rollno == rn): return i # Delete Function def delete(self, rn): i = obj.search(rn) del ls[i] # Update Function def update(self, rn, No): i = obj.search(rn) roll = No ls[i].rollno = roll; # Create a list to add Studentsls =[]# an object of Student classobj = Student('', 0, 0, 0) print(\"\\nOperations used, \")print(\"\\n1.Accept Student details\\n2.Display Student Details\\n\" / / \"3.Search Details of a Student\\n4.Delete Details of Student\" / / \"\\n5.Update Student Details\\n6.Exit\") # ch = int(input(\"Enter choice:\"))# if(ch == 1):obj.accept(\"A\", 1, 100, 100)obj.accept(\"B\", 2, 90, 90)obj.accept(\"C\", 3, 80, 80) # elif(ch == 2):print(\"\\n\")print(\"\\nList of Students\\n\")for i in range(ls.__len__()): obj.display(ls[i]) # elif(ch == 3):print(\"\\n Student Found, \")s = obj.search(2)obj.display(ls[s]) # elif(ch == 4):obj.delete(2)print(ls.__len__())print(\"List after deletion\")for i in range(ls.__len__()): obj.display(ls[i]) # elif(ch == 5):obj.update(3, 2)print(ls.__len__())print(\"List after updation\")for i in range(ls.__len__()): obj.display(ls[i]) # else:print(\"Thank You !\") Output:Operations used,\n\n1.Accept Student details\n2.Display Student Details\n3.Search Details of a Student\n4.Delete Details of Student\n5.Update Student Details\n6.Exit\n\n\n\nList of Students\n\nName : A\nRollNo : 1\nMarks1 : 100\nMarks2 : 100\n\n\nName : B\nRollNo : 2\nMarks1 : 90\nMarks2 : 90\n\n\nName : C\nRollNo : 3\nMarks1 : 80\nMarks2 : 80\n\n\n\n Student Found,\nName : B\nRollNo : 2\nMarks1 : 90\nMarks2 : 90\n\n\n2\nList after deletion\nName : A\nRollNo : 1\nMarks1 : 100\nMarks2 : 100\n\n\nName : C\nRollNo : 3\nMarks1 : 80\nMarks2 : 80\n\n\n2\nList after updation\nName : A\nRollNo : 1\nMarks1 : 100\nMarks2 : 100\n\n\nName : C\nRollNo : 2\nMarks1 : 80\nMarks2 : 80\n\n\nThank You !\nMy Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 5389, "s": 5012, "text": "Accept – This method takes details from the user like name, roll number, and marks for two different subjects.# Method to enter new student details\ndef accept(self, Name, Rollno, marks1, marks2 ):\n # Creates a new class constructor\n # and pass the details\n ob = Student(Name, Rollno, marks1, marks2 )\n\n # list containing objects of student class\n ls.append(ob)\n" }, { "code": null, "e": 5656, "s": 5389, "text": "# Method to enter new student details\ndef accept(self, Name, Rollno, marks1, marks2 ):\n # Creates a new class constructor\n # and pass the details\n ob = Student(Name, Rollno, marks1, marks2 )\n\n # list containing objects of student class\n ls.append(ob)\n" }, { "code": null, "e": 5929, "s": 5656, "text": "Display – This method displays the details of every student.# Function to display student details \ndef display(self, ob):\n print(\"Name : \", ob.name)\n print(\"RollNo : \", ob.rollno)\n print(\"Marks1 : \", ob.m1)\n print(\"Marks2 : \", ob.m2)\n print(\"\\n\") \n" }, { "code": null, "e": 6142, "s": 5929, "text": "# Function to display student details \ndef display(self, ob):\n print(\"Name : \", ob.name)\n print(\"RollNo : \", ob.rollno)\n print(\"Marks1 : \", ob.m1)\n print(\"Marks2 : \", ob.m2)\n print(\"\\n\") \n" }, { "code": null, "e": 6643, "s": 6142, "text": "Search – This method searches for a particular student from the list of students.This method will ask the user for roll number and then search according to the roll number# Search Function \ndef search(self, rn):\n for i in range(ls.__len__()):\n # iterate through the list containing\n # student object and checks through\n # roll no of each object\n if(ls[i].rollno == rn):\n # returns the object with matching \n # roll number\n return i \n" }, { "code": null, "e": 6973, "s": 6643, "text": "# Search Function \ndef search(self, rn):\n for i in range(ls.__len__()):\n # iterate through the list containing\n # student object and checks through\n # roll no of each object\n if(ls[i].rollno == rn):\n # returns the object with matching \n # roll number\n return i \n" }, { "code": null, "e": 7232, "s": 6973, "text": "Delete – This method deletes the record of a particular student with a matching roll number.# Delete Function \ndef delete(self, rn):\n # Calls the search function \n # created above\n i = obj.search(rn) \n del ls[i]\n" }, { "code": null, "e": 7399, "s": 7232, "text": "# Delete Function \ndef delete(self, rn):\n # Calls the search function \n # created above\n i = obj.search(rn) \n del ls[i]\n" }, { "code": null, "e": 10648, "s": 7399, "text": "Update – This method updates the roll number of the student.This method will ask for the old roll number and new roll number. It will replace the old roll number with new roll number.# Update Function \ndef update(self, rn, No):\n # calling the search function\n # of student class\n i = obj.search(rn)\n ls[i].rollno = No\nBelow is the implementation of the above approach:# This is simplest Student data management program in python# Create class \"Student\"class Student: # Constructor def __init__(self, name, rollno, m1, m2): self.name = name self.rollno = rollno self.m1 = m1 self.m2 = m2 # Function to create and append new student def accept(self, Name, Rollno, marks1, marks2 ): # use ' int(input()) ' method to take input from user ob = Student(Name, Rollno, marks1, marks2 ) ls.append(ob) # Function to display student details def display(self, ob): print(\"Name : \", ob.name) print(\"RollNo : \", ob.rollno) print(\"Marks1 : \", ob.m1) print(\"Marks2 : \", ob.m2) print(\"\\n\") # Search Function def search(self, rn): for i in range(ls.__len__()): if(ls[i].rollno == rn): return i # Delete Function def delete(self, rn): i = obj.search(rn) del ls[i] # Update Function def update(self, rn, No): i = obj.search(rn) roll = No ls[i].rollno = roll; # Create a list to add Studentsls =[]# an object of Student classobj = Student('', 0, 0, 0) print(\"\\nOperations used, \")print(\"\\n1.Accept Student details\\n2.Display Student Details\\n\" / / \"3.Search Details of a Student\\n4.Delete Details of Student\" / / \"\\n5.Update Student Details\\n6.Exit\") # ch = int(input(\"Enter choice:\"))# if(ch == 1):obj.accept(\"A\", 1, 100, 100)obj.accept(\"B\", 2, 90, 90)obj.accept(\"C\", 3, 80, 80) # elif(ch == 2):print(\"\\n\")print(\"\\nList of Students\\n\")for i in range(ls.__len__()): obj.display(ls[i]) # elif(ch == 3):print(\"\\n Student Found, \")s = obj.search(2)obj.display(ls[s]) # elif(ch == 4):obj.delete(2)print(ls.__len__())print(\"List after deletion\")for i in range(ls.__len__()): obj.display(ls[i]) # elif(ch == 5):obj.update(3, 2)print(ls.__len__())print(\"List after updation\")for i in range(ls.__len__()): obj.display(ls[i]) # else:print(\"Thank You !\") Output:Operations used,\n\n1.Accept Student details\n2.Display Student Details\n3.Search Details of a Student\n4.Delete Details of Student\n5.Update Student Details\n6.Exit\n\n\n\nList of Students\n\nName : A\nRollNo : 1\nMarks1 : 100\nMarks2 : 100\n\n\nName : B\nRollNo : 2\nMarks1 : 90\nMarks2 : 90\n\n\nName : C\nRollNo : 3\nMarks1 : 80\nMarks2 : 80\n\n\n\n Student Found,\nName : B\nRollNo : 2\nMarks1 : 90\nMarks2 : 90\n\n\n2\nList after deletion\nName : A\nRollNo : 1\nMarks1 : 100\nMarks2 : 100\n\n\nName : C\nRollNo : 3\nMarks1 : 80\nMarks2 : 80\n\n\n2\nList after updation\nName : A\nRollNo : 1\nMarks1 : 100\nMarks2 : 100\n\n\nName : C\nRollNo : 2\nMarks1 : 80\nMarks2 : 80\n\n\nThank You !\nMy Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 10798, "s": 10648, "text": "# Update Function \ndef update(self, rn, No):\n # calling the search function\n # of student class\n i = obj.search(rn)\n ls[i].rollno = No\n" }, { "code": null, "e": 10849, "s": 10798, "text": "Below is the implementation of the above approach:" }, { "code": "# This is simplest Student data management program in python# Create class \"Student\"class Student: # Constructor def __init__(self, name, rollno, m1, m2): self.name = name self.rollno = rollno self.m1 = m1 self.m2 = m2 # Function to create and append new student def accept(self, Name, Rollno, marks1, marks2 ): # use ' int(input()) ' method to take input from user ob = Student(Name, Rollno, marks1, marks2 ) ls.append(ob) # Function to display student details def display(self, ob): print(\"Name : \", ob.name) print(\"RollNo : \", ob.rollno) print(\"Marks1 : \", ob.m1) print(\"Marks2 : \", ob.m2) print(\"\\n\") # Search Function def search(self, rn): for i in range(ls.__len__()): if(ls[i].rollno == rn): return i # Delete Function def delete(self, rn): i = obj.search(rn) del ls[i] # Update Function def update(self, rn, No): i = obj.search(rn) roll = No ls[i].rollno = roll; # Create a list to add Studentsls =[]# an object of Student classobj = Student('', 0, 0, 0) print(\"\\nOperations used, \")print(\"\\n1.Accept Student details\\n2.Display Student Details\\n\" / / \"3.Search Details of a Student\\n4.Delete Details of Student\" / / \"\\n5.Update Student Details\\n6.Exit\") # ch = int(input(\"Enter choice:\"))# if(ch == 1):obj.accept(\"A\", 1, 100, 100)obj.accept(\"B\", 2, 90, 90)obj.accept(\"C\", 3, 80, 80) # elif(ch == 2):print(\"\\n\")print(\"\\nList of Students\\n\")for i in range(ls.__len__()): obj.display(ls[i]) # elif(ch == 3):print(\"\\n Student Found, \")s = obj.search(2)obj.display(ls[s]) # elif(ch == 4):obj.delete(2)print(ls.__len__())print(\"List after deletion\")for i in range(ls.__len__()): obj.display(ls[i]) # elif(ch == 5):obj.update(3, 2)print(ls.__len__())print(\"List after updation\")for i in range(ls.__len__()): obj.display(ls[i]) # else:print(\"Thank You !\") ", "e": 12999, "s": 10849, "text": null }, { "code": null, "e": 13675, "s": 12999, "text": "Operations used,\n\n1.Accept Student details\n2.Display Student Details\n3.Search Details of a Student\n4.Delete Details of Student\n5.Update Student Details\n6.Exit\n\n\n\nList of Students\n\nName : A\nRollNo : 1\nMarks1 : 100\nMarks2 : 100\n\n\nName : B\nRollNo : 2\nMarks1 : 90\nMarks2 : 90\n\n\nName : C\nRollNo : 3\nMarks1 : 80\nMarks2 : 80\n\n\n\n Student Found,\nName : B\nRollNo : 2\nMarks1 : 90\nMarks2 : 90\n\n\n2\nList after deletion\nName : A\nRollNo : 1\nMarks1 : 100\nMarks2 : 100\n\n\nName : C\nRollNo : 3\nMarks1 : 80\nMarks2 : 80\n\n\n2\nList after updation\nName : A\nRollNo : 1\nMarks1 : 100\nMarks2 : 100\n\n\nName : C\nRollNo : 2\nMarks1 : 80\nMarks2 : 80\n\n\nThank You !\n" }, { "code": null, "e": 13688, "s": 13675, "text": "Akanksha_Rai" }, { "code": null, "e": 13709, "s": 13688, "text": "Python Oops-programs" }, { "code": null, "e": 13720, "s": 13709, "text": "Python-OOP" }, { "code": null, "e": 13727, "s": 13720, "text": "Python" }, { "code": null, "e": 13825, "s": 13727, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 13843, "s": 13825, "text": "Python Dictionary" }, { "code": null, "e": 13885, "s": 13843, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 13907, "s": 13885, "text": "Enumerate() in Python" }, { "code": null, "e": 13942, "s": 13907, "text": "Read a file line by line in Python" }, { "code": null, "e": 13968, "s": 13942, "text": "Python String | replace()" }, { "code": null, "e": 14000, "s": 13968, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 14029, "s": 14000, "text": "*args and **kwargs in Python" }, { "code": null, "e": 14056, "s": 14029, "text": "Python Classes and Objects" }, { "code": null, "e": 14086, "s": 14056, "text": "Iterate over a list in Python" } ]
How to Install and Configure Fish Shell in Ubuntu?
05 Oct, 2021 Fish Shell is a unique user-friendly command-line shell for the different operating systems. fish includes some smart features like syntax highlighting, fancy tab completions and autosuggest-as-we-type that just works by default with no configuration required. fish is mostly written in shell script and in C++. Step 1: Install fish repository in ubuntu $ sudo apt-add-repository ppa:fish-shell/release-3 Step 2: Update and upgrade repository $ sudo apt-get update && sudo apt-get upgrade Step 3: Install fish shell $ sudo apt-get install fish Step 4: Make fish shell as default shell $ sudo chsh -s /usr/local/bin/fish To get back to bash, use $ sudo chsh -s 'which bash' how-to-install GBlog How To Installation Guide Linux-Unix Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. GEEK-O-LYMPICS 2022 - May The Geeks Force Be With You! Geek Streak - 24 Days POTD Challenge What is Hashing | A Complete Tutorial GeeksforGeeks Jobathon - Are You Ready For This Hiring Challenge? GeeksforGeeks Job-A-Thon Exclusive - Hiring Challenge For Amazon Alexa How to Install PIP on Windows ? How to Find the Wi-Fi Password Using CMD in Windows? How to install Jupyter Notebook on Windows? Java Tutorial How to filter object array based on attributes?
[ { "code": null, "e": 54, "s": 26, "text": "\n05 Oct, 2021" }, { "code": null, "e": 366, "s": 54, "text": "Fish Shell is a unique user-friendly command-line shell for the different operating systems. fish includes some smart features like syntax highlighting, fancy tab completions and autosuggest-as-we-type that just works by default with no configuration required. fish is mostly written in shell script and in C++." }, { "code": null, "e": 408, "s": 366, "text": "Step 1: Install fish repository in ubuntu" }, { "code": null, "e": 460, "s": 408, "text": "$ sudo apt-add-repository ppa:fish-shell/release-3 " }, { "code": null, "e": 498, "s": 460, "text": "Step 2: Update and upgrade repository" }, { "code": null, "e": 544, "s": 498, "text": "$ sudo apt-get update && sudo apt-get upgrade" }, { "code": null, "e": 571, "s": 544, "text": "Step 3: Install fish shell" }, { "code": null, "e": 599, "s": 571, "text": "$ sudo apt-get install fish" }, { "code": null, "e": 640, "s": 599, "text": "Step 4: Make fish shell as default shell" }, { "code": null, "e": 675, "s": 640, "text": "$ sudo chsh -s /usr/local/bin/fish" }, { "code": null, "e": 700, "s": 675, "text": "To get back to bash, use" }, { "code": null, "e": 728, "s": 700, "text": "$ sudo chsh -s 'which bash'" }, { "code": null, "e": 743, "s": 728, "text": "how-to-install" }, { "code": null, "e": 749, "s": 743, "text": "GBlog" }, { "code": null, "e": 756, "s": 749, "text": "How To" }, { "code": null, "e": 775, "s": 756, "text": "Installation Guide" }, { "code": null, "e": 786, "s": 775, "text": "Linux-Unix" }, { "code": null, "e": 805, "s": 786, "text": "Technical Scripter" }, { "code": null, "e": 903, "s": 805, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 958, "s": 903, "text": "GEEK-O-LYMPICS 2022 - May The Geeks Force Be With You!" }, { "code": null, "e": 995, "s": 958, "text": "Geek Streak - 24 Days POTD Challenge" }, { "code": null, "e": 1033, "s": 995, "text": "What is Hashing | A Complete Tutorial" }, { "code": null, "e": 1099, "s": 1033, "text": "GeeksforGeeks Jobathon - Are You Ready For This Hiring Challenge?" }, { "code": null, "e": 1170, "s": 1099, "text": "GeeksforGeeks Job-A-Thon Exclusive - Hiring Challenge For Amazon Alexa" }, { "code": null, "e": 1202, "s": 1170, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1255, "s": 1202, "text": "How to Find the Wi-Fi Password Using CMD in Windows?" }, { "code": null, "e": 1299, "s": 1255, "text": "How to install Jupyter Notebook on Windows?" }, { "code": null, "e": 1313, "s": 1299, "text": "Java Tutorial" } ]
Perfect cubes in a range
23 Jun, 2022 Given two given numbers a and b where 1 <= a <= b, find perfect cubes between a and b (a and b inclusive).Examples: Input : a = 1, b = 100 Output : 1 8 27 64 Perfect cubes in the given range are 1, 8, 27, 64 Input : a = 24, b = 576 Output : 27 64 125 216 343 512 Perfect cubes in the given range are 27, 64, 125, 216, 343, 512 This problem is similar to Perfect squares between two numbers.Method 1 (Naive) : One naive approach is to check all the numbers between a and b (inclusive a and b) and print the perfect cube. Following is the code for the above approach: C++ Java Python3 C# PHP Javascript // A Simple Method to count cubes between a and b#include <bits/stdc++.h>using namespace std; void printCubes(int a, int b){ // Traverse through all numbers in given range // and one by one check if number is prime for (int i = a; i <= b; i++) { // Check if current number 'i' // is perfect cube for (int j = 1; j * j * j <= i; j++) { if (j * j * j == i) { cout << j * j * j << " "; break; } } }} // Driver codeint main(){ int a = 1, b = 100; cout << "Perfect cubes in given range:\n "; printCubes(a, b); return 0;} // A Simple Method to count cubes between a and b class Test { static void printCubes(int a, int b) { // Traverse through all numbers in given range // and one by one check if number is prime for (int i = a; i <= b; i++) { // Check if current number 'i' // is perfect cube for (int j = 1; j * j * j <= i; j++) { if (j * j * j == i) { System.out.print(j * j * j + " "); break; } } } } // Driver method public static void main(String[] args) { int a = 1, b = 100; System.out.println("Perfect cubes in given range:"); printCubes(a, b); }} # A Simple Method to count cubes between a and b def printCubes(a, b) : # Traverse through all numbers in given range # and one by one check if number is prime for i in range(a, b + 1) : # Check if current number 'i' # is perfect cube j = 1 for j in range(j ** 3, i + 1 ) : if (j ** 3 == i) : print( j ** 3, end = " ") break # Driver code a = 1; b = 100print("Perfect cubes in given range: ")printCubes(a, b) # This code is contributed by Nikita Tiwari. // A Simple Method to count cubes// between a and busing System; class GFG { static void printCubes(int a, int b) { // Traverse through all numbers // in given range and one by // one check if number is prime for (int i = a; i <= b; i++) { // Check if current number 'i' // is perfect cube for (int j = 1; j * j * j <= i; j++) { if (j * j * j == i) { Console.Write(j * j * j + " "); break; } } } } // Driver method public static void Main() { int a = 1, b = 100; Console.WriteLine("Perfect cubes in" + " given range:"); printCubes(a, b); }} // This code contribute by parashar. <?php// A Simple Method to count// cubes between a and b function printCubes($a, $b){ // Traverse through all // numbers in given range // and one by one check // if number is prime for ($i = $a; $i <= $b; $i++) { // Check if current number 'i' // is perfect cube for ($j = 1; $j * $j * $j <= $i; $j++) { if ($j * $j * $j == $i) { echo $j * $j * $j, " "; break; } } }} // Driver Code $a = 1; $b = 100; echo "Perfect cubes in given range:\n "; printCubes($a, $b); // This code is contributed by ajit?> <script>// A Simple Method to count// cubes between a and bfunction printCubes(a, b){ // Traverse through all // numbers in given range // and one by one check // if number is prime for (let i = a; i <= b; i++) { // Check if current number 'i' // is perfect cube for (let j = 1; j * j * j <= i; j++) { if (j * j * j == i) { document.write(j * j * j + " "); break; } } }} // Driver Code let a = 1; let b = 100; document.write("Perfect cubes in given range: <br> "); printCubes(a, b); // This code is contributed by gfgking. </script> Output : Perfect cubes in given range: 1 8 27 64 Method 2 (Efficient): We can simply take cube root of ‘a’ and cube root of ‘b’ and print the cubes of number between them. 1- Given a = 24 b = 576 2- acr = cbrt(a)) bcr = cbrt(b) acr = 3 and bcr = 8 3- Print cubes of 3 to 8 that comes under the range of a and b(including a and b both) 27, 64, 125, 216, 343, 512 Below is implementation of above steps. C++ Java Python3 C# PHP Javascript // Efficient method to print cubes// between a and b#include <cmath>#include <iostream>using namespace std; // An efficient solution to print perfect// cubes between a and bvoid printCubes(int a, int b){ // Find cube root of both a and b int acrt = cbrt(a); int bcrt = cbrt(b); // Print cubes between acrt and bcrt for (int i = acrt; i <= bcrt; i++) if (i * i * i >= a && i * i * i <= b) cout << i * i * i << " ";} // Driver codeint main(){ int a = 24, b = 576; cout << "Perfect cubes in given range:\n"; printCubes(a, b); return 0;}// improved by prophet1999 // Java progroam for Efficient method// to print cubes between a and b class Test { // An efficient solution to print perfect // cubes between a and b static void printCubes(int a, int b) { // Find cube root of both a and b int acrt = (int)Math.cbrt(a); int bcrt = (int)Math.cbrt(b); // Print cubes between acrt and bcrt for (int i = acrt; i <= bcrt; i++) if (i * i * i >= a && i * i * i <= b) System.out.print(i * i * i + " "); } // Driver method public static void main(String[] args) { int a = 24, b = 576; System.out.println("Perfect cubes in given range:"); printCubes(a, b); }} # Python3 code for Efficient method # to print cubes between a and b def cbrt(n) : return (int)( n ** (1. / 3)) # An efficient solution to print# perfect cubes between a and bdef printCubes(a, b) : # Find cube root of # both a and b acrt = cbrt(a) bcrt = cbrt(b) # Print cubes between acrt and bcrt for i in range(acrt, bcrt + 1) : if (i * i * i >= a and i * i * i <= b) : print(i * i * i, " ", end ="") # Driver codea = 24b = 576print("Perfect cubes in given range:")printCubes(a, b) # This code is contributed# by Nikita Tiwari. // C# progroam for Efficient// method to print cubes// between a and busing System; class GFG{ // An efficient solution // to print perfect // cubes between a and b static void printCubes(int a, int b) { // Find cube root of // both a and b int acrt = (int)Math.Pow(a, (double)1 / 3); int bcrt = (int)Math.Pow(b, (double)1 / 3); // Print cubes between // acrt and bcrt for (int i = acrt; i <= bcrt; i++) if (i * i * i >= a && i * i * i <= b) Console.Write(i * i * i + " "); } // Driver Code static public void Main () { int a = 24; int b = 576; Console.WriteLine("Perfect cubes " + "in given range:"); printCubes(a, b); }} // This code is contributed// by ajit <?php// Efficient method to print// cubes between a and b // An efficient solution// to print perfect// cubes between a and b function printCubes($a, $b){ // Find cube root // of both a and b $acrt = (int)pow($a, 1 / 3); $bcrt = (int)pow($b, 1 / 3); // Print cubes between // acrt and bcrt for ($i = $acrt; $i <= $bcrt; $i++) if ($i * $i * $i >= $a && $i * $i * $i <= $b) echo $i * $i * $i , " ";} // Driver code$a = 24; $b = 576;echo "Perfect cubes in given range:\n", printCubes($a, $b); // This code is contributed by ajit?> <script> // Javascript progroam for Efficient // method to print cubes // between a and b // An efficient solution // to print perfect // cubes between a and b function printCubes(a, b) { // Find cube root of // both a and b let acrt = parseInt(Math.pow(a, 1 / 3), 10); let bcrt = parseInt(Math.pow(b, 1 / 3), 10); // Print cubes between // acrt and bcrt for (let i = acrt; i <= bcrt; i++) if (i * i * i >= a && i * i * i <= b) document.write((i * i * i) + " "); } let a = 24; let b = 576; document.write("Perfect cubes " + "in given range:" + "</br>"); printCubes(a, b); // This code is contributed by rameshtravel07.</script> Output: Perfect cubes in given range: 27 64 125 216 343 512 This article is contributed by Sahil Chhabra and improved by prophet1999. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. parashar jit_t gfgking rameshtravel07 prophet1999 maths-cube Mathematical Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Merge two sorted arrays Operators in C / C++ Sieve of Eratosthenes Prime Numbers Program to find GCD or HCF of two numbers Find minimum number of coins that make a given value Minimum number of jumps to reach end Algorithm to solve Rubik's Cube The Knight's tour problem | Backtracking-1 Program for Decimal to Binary Conversion
[ { "code": null, "e": 53, "s": 25, "text": "\n23 Jun, 2022" }, { "code": null, "e": 171, "s": 53, "text": "Given two given numbers a and b where 1 <= a <= b, find perfect cubes between a and b (a and b inclusive).Examples: " }, { "code": null, "e": 388, "s": 171, "text": "Input : a = 1, b = 100\nOutput : 1 8 27 64\nPerfect cubes in the given range are \n1, 8, 27, 64\n\nInput : a = 24, b = 576\nOutput : 27 64 125 216 343 512\nPerfect cubes in the given range are \n27, 64, 125, 216, 343, 512" }, { "code": null, "e": 631, "s": 390, "text": "This problem is similar to Perfect squares between two numbers.Method 1 (Naive) : One naive approach is to check all the numbers between a and b (inclusive a and b) and print the perfect cube. Following is the code for the above approach: " }, { "code": null, "e": 635, "s": 631, "text": "C++" }, { "code": null, "e": 640, "s": 635, "text": "Java" }, { "code": null, "e": 648, "s": 640, "text": "Python3" }, { "code": null, "e": 651, "s": 648, "text": "C#" }, { "code": null, "e": 655, "s": 651, "text": "PHP" }, { "code": null, "e": 666, "s": 655, "text": "Javascript" }, { "code": "// A Simple Method to count cubes between a and b#include <bits/stdc++.h>using namespace std; void printCubes(int a, int b){ // Traverse through all numbers in given range // and one by one check if number is prime for (int i = a; i <= b; i++) { // Check if current number 'i' // is perfect cube for (int j = 1; j * j * j <= i; j++) { if (j * j * j == i) { cout << j * j * j << \" \"; break; } } }} // Driver codeint main(){ int a = 1, b = 100; cout << \"Perfect cubes in given range:\\n \"; printCubes(a, b); return 0;}", "e": 1287, "s": 666, "text": null }, { "code": "// A Simple Method to count cubes between a and b class Test { static void printCubes(int a, int b) { // Traverse through all numbers in given range // and one by one check if number is prime for (int i = a; i <= b; i++) { // Check if current number 'i' // is perfect cube for (int j = 1; j * j * j <= i; j++) { if (j * j * j == i) { System.out.print(j * j * j + \" \"); break; } } } } // Driver method public static void main(String[] args) { int a = 1, b = 100; System.out.println(\"Perfect cubes in given range:\"); printCubes(a, b); }}", "e": 2009, "s": 1287, "text": null }, { "code": "# A Simple Method to count cubes between a and b def printCubes(a, b) : # Traverse through all numbers in given range # and one by one check if number is prime for i in range(a, b + 1) : # Check if current number 'i' # is perfect cube j = 1 for j in range(j ** 3, i + 1 ) : if (j ** 3 == i) : print( j ** 3, end = \" \") break # Driver code a = 1; b = 100print(\"Perfect cubes in given range: \")printCubes(a, b) # This code is contributed by Nikita Tiwari.", "e": 2577, "s": 2009, "text": null }, { "code": "// A Simple Method to count cubes// between a and busing System; class GFG { static void printCubes(int a, int b) { // Traverse through all numbers // in given range and one by // one check if number is prime for (int i = a; i <= b; i++) { // Check if current number 'i' // is perfect cube for (int j = 1; j * j * j <= i; j++) { if (j * j * j == i) { Console.Write(j * j * j + \" \"); break; } } } } // Driver method public static void Main() { int a = 1, b = 100; Console.WriteLine(\"Perfect cubes in\" + \" given range:\"); printCubes(a, b); }} // This code contribute by parashar.", "e": 3374, "s": 2577, "text": null }, { "code": "<?php// A Simple Method to count// cubes between a and b function printCubes($a, $b){ // Traverse through all // numbers in given range // and one by one check // if number is prime for ($i = $a; $i <= $b; $i++) { // Check if current number 'i' // is perfect cube for ($j = 1; $j * $j * $j <= $i; $j++) { if ($j * $j * $j == $i) { echo $j * $j * $j, \" \"; break; } } }} // Driver Code $a = 1; $b = 100; echo \"Perfect cubes in given range:\\n \"; printCubes($a, $b); // This code is contributed by ajit?>", "e": 4028, "s": 3374, "text": null }, { "code": "<script>// A Simple Method to count// cubes between a and bfunction printCubes(a, b){ // Traverse through all // numbers in given range // and one by one check // if number is prime for (let i = a; i <= b; i++) { // Check if current number 'i' // is perfect cube for (let j = 1; j * j * j <= i; j++) { if (j * j * j == i) { document.write(j * j * j + \" \"); break; } } }} // Driver Code let a = 1; let b = 100; document.write(\"Perfect cubes in given range: <br> \"); printCubes(a, b); // This code is contributed by gfgking. </script>", "e": 4714, "s": 4028, "text": null }, { "code": null, "e": 4725, "s": 4714, "text": "Output : " }, { "code": null, "e": 4766, "s": 4725, "text": "Perfect cubes in given range:\n 1 8 27 64" }, { "code": null, "e": 4890, "s": 4766, "text": "Method 2 (Efficient): We can simply take cube root of ‘a’ and cube root of ‘b’ and print the cubes of number between them. " }, { "code": null, "e": 5103, "s": 4890, "text": "1- Given a = 24 b = 576\n\n2- acr = cbrt(a)) bcr = cbrt(b)\n acr = 3 and bcr = 8\n\n3- Print cubes of 3 to 8 that comes under \n the range of a and b(including a and b\n both)\n 27, 64, 125, 216, 343, 512" }, { "code": null, "e": 5145, "s": 5103, "text": "Below is implementation of above steps. " }, { "code": null, "e": 5149, "s": 5145, "text": "C++" }, { "code": null, "e": 5154, "s": 5149, "text": "Java" }, { "code": null, "e": 5162, "s": 5154, "text": "Python3" }, { "code": null, "e": 5165, "s": 5162, "text": "C#" }, { "code": null, "e": 5169, "s": 5165, "text": "PHP" }, { "code": null, "e": 5180, "s": 5169, "text": "Javascript" }, { "code": "// Efficient method to print cubes// between a and b#include <cmath>#include <iostream>using namespace std; // An efficient solution to print perfect// cubes between a and bvoid printCubes(int a, int b){ // Find cube root of both a and b int acrt = cbrt(a); int bcrt = cbrt(b); // Print cubes between acrt and bcrt for (int i = acrt; i <= bcrt; i++) if (i * i * i >= a && i * i * i <= b) cout << i * i * i << \" \";} // Driver codeint main(){ int a = 24, b = 576; cout << \"Perfect cubes in given range:\\n\"; printCubes(a, b); return 0;}// improved by prophet1999", "e": 5787, "s": 5180, "text": null }, { "code": "// Java progroam for Efficient method// to print cubes between a and b class Test { // An efficient solution to print perfect // cubes between a and b static void printCubes(int a, int b) { // Find cube root of both a and b int acrt = (int)Math.cbrt(a); int bcrt = (int)Math.cbrt(b); // Print cubes between acrt and bcrt for (int i = acrt; i <= bcrt; i++) if (i * i * i >= a && i * i * i <= b) System.out.print(i * i * i + \" \"); } // Driver method public static void main(String[] args) { int a = 24, b = 576; System.out.println(\"Perfect cubes in given range:\"); printCubes(a, b); }}", "e": 6482, "s": 5787, "text": null }, { "code": "# Python3 code for Efficient method # to print cubes between a and b def cbrt(n) : return (int)( n ** (1. / 3)) # An efficient solution to print# perfect cubes between a and bdef printCubes(a, b) : # Find cube root of # both a and b acrt = cbrt(a) bcrt = cbrt(b) # Print cubes between acrt and bcrt for i in range(acrt, bcrt + 1) : if (i * i * i >= a and i * i * i <= b) : print(i * i * i, \" \", end =\"\") # Driver codea = 24b = 576print(\"Perfect cubes in given range:\")printCubes(a, b) # This code is contributed# by Nikita Tiwari.", "e": 7059, "s": 6482, "text": null }, { "code": "// C# progroam for Efficient// method to print cubes// between a and busing System; class GFG{ // An efficient solution // to print perfect // cubes between a and b static void printCubes(int a, int b) { // Find cube root of // both a and b int acrt = (int)Math.Pow(a, (double)1 / 3); int bcrt = (int)Math.Pow(b, (double)1 / 3); // Print cubes between // acrt and bcrt for (int i = acrt; i <= bcrt; i++) if (i * i * i >= a && i * i * i <= b) Console.Write(i * i * i + \" \"); } // Driver Code static public void Main () { int a = 24; int b = 576; Console.WriteLine(\"Perfect cubes \" + \"in given range:\"); printCubes(a, b); }} // This code is contributed// by ajit", "e": 8022, "s": 7059, "text": null }, { "code": "<?php// Efficient method to print// cubes between a and b // An efficient solution// to print perfect// cubes between a and b function printCubes($a, $b){ // Find cube root // of both a and b $acrt = (int)pow($a, 1 / 3); $bcrt = (int)pow($b, 1 / 3); // Print cubes between // acrt and bcrt for ($i = $acrt; $i <= $bcrt; $i++) if ($i * $i * $i >= $a && $i * $i * $i <= $b) echo $i * $i * $i , \" \";} // Driver code$a = 24; $b = 576;echo \"Perfect cubes in given range:\\n\", printCubes($a, $b); // This code is contributed by ajit?>", "e": 8624, "s": 8022, "text": null }, { "code": "<script> // Javascript progroam for Efficient // method to print cubes // between a and b // An efficient solution // to print perfect // cubes between a and b function printCubes(a, b) { // Find cube root of // both a and b let acrt = parseInt(Math.pow(a, 1 / 3), 10); let bcrt = parseInt(Math.pow(b, 1 / 3), 10); // Print cubes between // acrt and bcrt for (let i = acrt; i <= bcrt; i++) if (i * i * i >= a && i * i * i <= b) document.write((i * i * i) + \" \"); } let a = 24; let b = 576; document.write(\"Perfect cubes \" + \"in given range:\" + \"</br>\"); printCubes(a, b); // This code is contributed by rameshtravel07.</script>", "e": 9386, "s": 8624, "text": null }, { "code": null, "e": 9396, "s": 9386, "text": "Output: " }, { "code": null, "e": 9448, "s": 9396, "text": "Perfect cubes in given range:\n27 64 125 216 343 512" }, { "code": null, "e": 9898, "s": 9448, "text": "This article is contributed by Sahil Chhabra and improved by prophet1999. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 9907, "s": 9898, "text": "parashar" }, { "code": null, "e": 9913, "s": 9907, "text": "jit_t" }, { "code": null, "e": 9921, "s": 9913, "text": "gfgking" }, { "code": null, "e": 9936, "s": 9921, "text": "rameshtravel07" }, { "code": null, "e": 9948, "s": 9936, "text": "prophet1999" }, { "code": null, "e": 9959, "s": 9948, "text": "maths-cube" }, { "code": null, "e": 9972, "s": 9959, "text": "Mathematical" }, { "code": null, "e": 9985, "s": 9972, "text": "Mathematical" }, { "code": null, "e": 10083, "s": 9985, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 10107, "s": 10083, "text": "Merge two sorted arrays" }, { "code": null, "e": 10128, "s": 10107, "text": "Operators in C / C++" }, { "code": null, "e": 10150, "s": 10128, "text": "Sieve of Eratosthenes" }, { "code": null, "e": 10164, "s": 10150, "text": "Prime Numbers" }, { "code": null, "e": 10206, "s": 10164, "text": "Program to find GCD or HCF of two numbers" }, { "code": null, "e": 10259, "s": 10206, "text": "Find minimum number of coins that make a given value" }, { "code": null, "e": 10296, "s": 10259, "text": "Minimum number of jumps to reach end" }, { "code": null, "e": 10328, "s": 10296, "text": "Algorithm to solve Rubik's Cube" }, { "code": null, "e": 10371, "s": 10328, "text": "The Knight's tour problem | Backtracking-1" } ]
Morgan Stanley Interview Preparation - GeeksforGeeks
Beat the competition and land yourself a top job. Register for Job-a-thon now! TCS Recruitment Process Infosys Recruitment Process Wipro Recruitment Process IBM Recruitment Process Cognizant Recruitment Process SAP Labs Interview Preparation Morgan Stanley Interview Preparation Accenture Recruitment Process Swiggy Recruitment Process Flipkart Interview Preparation Paytm Interview Preparation Samsung Interview Preparation Walmart Labs Recruitment Process Directi Interview Preparation Qualcomm Recruitment Process MakeMyTrip Recruitment Process Company Preparation Amazon Interview Preparation Microsoft Interview Preparation Google Interview Preparation D E Shaw Interview Preparation Goldman Sachs Interview Preparation Morgan-Stanley Interview Preparation Popular Articles Sort an array of 0s, 1s and 2s Swap Kth node from beginning with Kth node from end in a Linked List Dynamic Programming | Set 14 (Maximum Sum Increasing Subsequence) Dynamic Programming | Set 7 (Coin Change) Largest Sum Contiguous Subarray Print a given matrix in spiral form Maximum Product Subarray Count numbers from 1 to n that have 4 as a a digit Write your own atoi() Remove duplicates from sorted array Largest subarray with equal number of 0s and 1s Show All Articles Popular Coding Problems Kadane's Algorithm Sort an array of 0s, 1s and 2s 0 - 1 Knapsack Problem Minimum element in a sorted and rotated array Maximum sum increasing subsequence Level order traversal Line by Line Implement Atoi Largest subarray of 0's and 1's Remove duplicate elements from sorted Array Clone a linked list with next and random pointer Show All Coding Problems Popular Video Tutorials Recent Interview Experiences Morgan Stanley Interview Experience | Set 32 (On-Campus) Morgan Stanley Interview Experience | Set 31 (On-Campus) Morgan Stanley Interview Experience | Set 30 (On-Campus) Morgan Stanley Interview Experience | Set 29 (On-Campus) Morgan Stanley Interview Experience | Set 28 (On-Campus) Largest even number possible by using one swap operation in given number Morgan Stanley Interview | Set 27 (For 2.5 Years Experienced) Morgan Stanley Interview | Set 26 (Off-Campus) Morgan Stanley Interview | Set 25 (Off-Campus) Morgan Stanley Interview | Set 24 (On-Campus for Internship) Show All Interview Experiences Binary Tree Iterator for Inorder Traversal How to get JSON response in Ajax ? Different ways to access characters in a given String in C++ How to Install iPython on Linux? Pure CSS Form Read-Only Inputs Failure Classification in DBMS Difference Between VB.NET and C# How to add emoji in HTML document ? Git - Difference Between Git Fetch and Git Pull Bulma Centering Columns Option
[ { "code": null, "e": 24209, "s": 24130, "text": "Beat the competition and land yourself a top job. Register for Job-a-thon now!" }, { "code": null, "e": 24233, "s": 24209, "text": "TCS Recruitment Process" }, { "code": null, "e": 24261, "s": 24233, "text": "Infosys Recruitment Process" }, { "code": null, "e": 24287, "s": 24261, "text": "Wipro Recruitment Process" }, { "code": null, "e": 24311, "s": 24287, "text": "IBM Recruitment Process" }, { "code": null, "e": 24341, "s": 24311, "text": "Cognizant Recruitment Process" }, { "code": null, "e": 24372, "s": 24341, "text": "SAP Labs Interview Preparation" }, { "code": null, "e": 24409, "s": 24372, "text": "Morgan Stanley Interview Preparation" }, { "code": null, "e": 24439, "s": 24409, "text": "Accenture Recruitment Process" }, { "code": null, "e": 24466, "s": 24439, "text": "Swiggy Recruitment Process" }, { "code": null, "e": 24497, "s": 24466, "text": "Flipkart Interview Preparation" }, { "code": null, "e": 24525, "s": 24497, "text": "Paytm Interview Preparation" }, { "code": null, "e": 24555, "s": 24525, "text": "Samsung Interview Preparation" }, { "code": null, "e": 24588, "s": 24555, "text": "Walmart Labs Recruitment Process" }, { "code": null, "e": 24618, "s": 24588, "text": "Directi Interview Preparation" }, { "code": null, "e": 24647, "s": 24618, "text": "Qualcomm Recruitment Process" }, { "code": null, "e": 24678, "s": 24647, "text": "MakeMyTrip Recruitment Process" }, { "code": null, "e": 24698, "s": 24678, "text": "Company Preparation" }, { "code": null, "e": 24727, "s": 24698, "text": "Amazon Interview Preparation" }, { "code": null, "e": 24759, "s": 24727, "text": "Microsoft Interview Preparation" }, { "code": null, "e": 24788, "s": 24759, "text": "Google Interview Preparation" }, { "code": null, "e": 24819, "s": 24788, "text": "D E Shaw Interview Preparation" }, { "code": null, "e": 24855, "s": 24819, "text": "Goldman Sachs Interview Preparation" }, { "code": null, "e": 24892, "s": 24855, "text": "Morgan-Stanley Interview Preparation" }, { "code": null, "e": 24909, "s": 24892, "text": "Popular Articles" }, { "code": null, "e": 24940, "s": 24909, "text": "Sort an array of 0s, 1s and 2s" }, { "code": null, "e": 25009, "s": 24940, "text": "Swap Kth node from beginning with Kth node from end in a Linked List" }, { "code": null, "e": 25075, "s": 25009, "text": "Dynamic Programming | Set 14 (Maximum Sum Increasing Subsequence)" }, { "code": null, "e": 25117, "s": 25075, "text": "Dynamic Programming | Set 7 (Coin Change)" }, { "code": null, "e": 25149, "s": 25117, "text": "Largest Sum Contiguous Subarray" }, { "code": null, "e": 25185, "s": 25149, "text": "Print a given matrix in spiral form" }, { "code": null, "e": 25210, "s": 25185, "text": "Maximum Product Subarray" }, { "code": null, "e": 25261, "s": 25210, "text": "Count numbers from 1 to n that have 4 as a a digit" }, { "code": null, "e": 25283, "s": 25261, "text": "Write your own atoi()" }, { "code": null, "e": 25319, "s": 25283, "text": "Remove duplicates from sorted array" }, { "code": null, "e": 25367, "s": 25319, "text": "Largest subarray with equal number of 0s and 1s" }, { "code": null, "e": 25385, "s": 25367, "text": "Show All Articles" }, { "code": null, "e": 25409, "s": 25385, "text": "Popular Coding Problems" }, { "code": null, "e": 25428, "s": 25409, "text": "Kadane's Algorithm" }, { "code": null, "e": 25459, "s": 25428, "text": "Sort an array of 0s, 1s and 2s" }, { "code": null, "e": 25482, "s": 25459, "text": "0 - 1 Knapsack Problem" }, { "code": null, "e": 25528, "s": 25482, "text": "Minimum element in a sorted and rotated array" }, { "code": null, "e": 25563, "s": 25528, "text": "Maximum sum increasing subsequence" }, { "code": null, "e": 25598, "s": 25563, "text": "Level order traversal Line by Line" }, { "code": null, "e": 25613, "s": 25598, "text": "Implement Atoi" }, { "code": null, "e": 25645, "s": 25613, "text": "Largest subarray of 0's and 1's" }, { "code": null, "e": 25689, "s": 25645, "text": "Remove duplicate elements from sorted Array" }, { "code": null, "e": 25738, "s": 25689, "text": "Clone a linked list with next and random pointer" }, { "code": null, "e": 25763, "s": 25738, "text": "Show All Coding Problems" }, { "code": null, "e": 25787, "s": 25763, "text": "Popular Video Tutorials" }, { "code": null, "e": 25816, "s": 25787, "text": "Recent Interview Experiences" }, { "code": null, "e": 25873, "s": 25816, "text": "Morgan Stanley Interview Experience | Set 32 (On-Campus)" }, { "code": null, "e": 25930, "s": 25873, "text": "Morgan Stanley Interview Experience | Set 31 (On-Campus)" }, { "code": null, "e": 25987, "s": 25930, "text": "Morgan Stanley Interview Experience | Set 30 (On-Campus)" }, { "code": null, "e": 26044, "s": 25987, "text": "Morgan Stanley Interview Experience | Set 29 (On-Campus)" }, { "code": null, "e": 26101, "s": 26044, "text": "Morgan Stanley Interview Experience | Set 28 (On-Campus)" }, { "code": null, "e": 26174, "s": 26101, "text": "Largest even number possible by using one swap operation in given number" }, { "code": null, "e": 26236, "s": 26174, "text": "Morgan Stanley Interview | Set 27 (For 2.5 Years Experienced)" }, { "code": null, "e": 26283, "s": 26236, "text": "Morgan Stanley Interview | Set 26 (Off-Campus)" }, { "code": null, "e": 26330, "s": 26283, "text": "Morgan Stanley Interview | Set 25 (Off-Campus)" }, { "code": null, "e": 26391, "s": 26330, "text": "Morgan Stanley Interview | Set 24 (On-Campus for Internship)" }, { "code": null, "e": 26422, "s": 26391, "text": "Show All Interview Experiences" }, { "code": null, "e": 26465, "s": 26422, "text": "Binary Tree Iterator for Inorder Traversal" }, { "code": null, "e": 26500, "s": 26465, "text": "How to get JSON response in Ajax ?" }, { "code": null, "e": 26561, "s": 26500, "text": "Different ways to access characters in a given String in C++" }, { "code": null, "e": 26594, "s": 26561, "text": "How to Install iPython on Linux?" }, { "code": null, "e": 26625, "s": 26594, "text": "Pure CSS Form Read-Only Inputs" }, { "code": null, "e": 26656, "s": 26625, "text": "Failure Classification in DBMS" }, { "code": null, "e": 26689, "s": 26656, "text": "Difference Between VB.NET and C#" }, { "code": null, "e": 26725, "s": 26689, "text": "How to add emoji in HTML document ?" }, { "code": null, "e": 26773, "s": 26725, "text": "Git - Difference Between Git Fetch and Git Pull" } ]
MoviePy – Creating Animation Using Matplotlib
17 Nov, 2021 In this article we will see how we create animations in MoviePy using matplotlib. MoviePy is a Python module for video editing, which can be used for basic operations on videos and GIF’s. Video is formed by the frames, combination of frames creates a video each frame is an individual image. Matplotlib is a plotting library for the Python programming language and its numerical mathematics extension NumPy. It provides an object-oriented API for embedding plots into applications using general-purpose GUI toolkits like Tkinter, wxPython, Qt, or GTK+. In order to do this we have to do the following 1. Import matplotlib modules 2. Import moviepy modules 3. Create a numpy array 4. Create a subplot using matplotlib 5. Create a Video clip file by calling the make_frame method 6. Inside the the make frame method 7. Clear the plot and create a new plot using trigonometry methods according to the frame time 8. Return the plot after converting it into numpy image. Below is the implementation Python3 # importing matplot libimport matplotlib.pyplot as pltimport numpy as np # importing movie py librariesfrom moviepy.editor import VideoClipfrom moviepy.video.io.bindings import mplfig_to_npimage # numpy arrayx = np.linspace(-2, 2, 200) # duration of the videoduration = 2 # matplot subplotfig, ax = plt.subplots() # method to get framesdef make_frame(t): # clear ax.clear() # plotting line ax.plot(x, np.sinc(x**2) + np.sin(x + 2 * np.pi / duration * t), lw = 3) ax.set_ylim(-1.5, 2.5) # returning numpy image return mplfig_to_npimage(fig) # creating animationanimation = VideoClip(make_frame, duration = duration) # displaying animation with auto play and loopinganimation.ipython_display(fps = 20, loop = True, autoplay = True) Output : Moviepy - Building video __temp__.mp4. Moviepy - Writing video __temp__.mp4 Moviepy - Done ! Moviepy - video ready __temp__.mp4 Another example Python3 # importing matplot libimport matplotlib.pyplot as pltimport numpy as np # importing movie py librariesfrom moviepy.editor import VideoClipfrom moviepy.video.io.bindings import mplfig_to_npimage # numpy arrayx = np.linspace(-5, 5, 100) # duration of the videoduration = 2 # matplot subplotfig, ax = plt.subplots() # method to get framesdef make_frame(t): # clear ax.clear() # plotting line ax.plot(x, np.sinc(x**2) + np.cos(x + 10 * np.pi / duration * t), lw = 3) ax.set_ylim(-1.5, 2.5) # returning numpy image return mplfig_to_npimage(fig) # creating animationanimation = VideoClip(make_frame, duration = duration) # displaying animation with auto play and loopinganimation.ipython_display(fps = 20, loop = True, autoplay = True) Output : Moviepy - Building video __temp__.mp4. Moviepy - Writing video __temp__.mp4 Moviepy - Done ! Moviepy - video ready __temp__.mp4 sweetyty prachisoda1234 Python-MoviePy 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": "\n17 Nov, 2021" }, { "code": null, "e": 582, "s": 28, "text": "In this article we will see how we create animations in MoviePy using matplotlib. MoviePy is a Python module for video editing, which can be used for basic operations on videos and GIF’s. Video is formed by the frames, combination of frames creates a video each frame is an individual image. Matplotlib is a plotting library for the Python programming language and its numerical mathematics extension NumPy. It provides an object-oriented API for embedding plots into applications using general-purpose GUI toolkits like Tkinter, wxPython, Qt, or GTK+. " }, { "code": null, "e": 997, "s": 582, "text": "In order to do this we have to do the following 1. Import matplotlib modules 2. Import moviepy modules 3. Create a numpy array 4. Create a subplot using matplotlib 5. Create a Video clip file by calling the make_frame method 6. Inside the the make frame method 7. Clear the plot and create a new plot using trigonometry methods according to the frame time 8. Return the plot after converting it into numpy image. " }, { "code": null, "e": 1027, "s": 997, "text": "Below is the implementation " }, { "code": null, "e": 1035, "s": 1027, "text": "Python3" }, { "code": "# importing matplot libimport matplotlib.pyplot as pltimport numpy as np # importing movie py librariesfrom moviepy.editor import VideoClipfrom moviepy.video.io.bindings import mplfig_to_npimage # numpy arrayx = np.linspace(-2, 2, 200) # duration of the videoduration = 2 # matplot subplotfig, ax = plt.subplots() # method to get framesdef make_frame(t): # clear ax.clear() # plotting line ax.plot(x, np.sinc(x**2) + np.sin(x + 2 * np.pi / duration * t), lw = 3) ax.set_ylim(-1.5, 2.5) # returning numpy image return mplfig_to_npimage(fig) # creating animationanimation = VideoClip(make_frame, duration = duration) # displaying animation with auto play and loopinganimation.ipython_display(fps = 20, loop = True, autoplay = True)", "e": 1801, "s": 1035, "text": null }, { "code": null, "e": 1812, "s": 1801, "text": "Output : " }, { "code": null, "e": 2061, "s": 1812, "text": "Moviepy - Building video __temp__.mp4.\nMoviepy - Writing video __temp__.mp4\n\n \nMoviepy - Done !\nMoviepy - video ready __temp__.mp4" }, { "code": null, "e": 2083, "s": 2065, "text": "Another example " }, { "code": null, "e": 2091, "s": 2083, "text": "Python3" }, { "code": "# importing matplot libimport matplotlib.pyplot as pltimport numpy as np # importing movie py librariesfrom moviepy.editor import VideoClipfrom moviepy.video.io.bindings import mplfig_to_npimage # numpy arrayx = np.linspace(-5, 5, 100) # duration of the videoduration = 2 # matplot subplotfig, ax = plt.subplots() # method to get framesdef make_frame(t): # clear ax.clear() # plotting line ax.plot(x, np.sinc(x**2) + np.cos(x + 10 * np.pi / duration * t), lw = 3) ax.set_ylim(-1.5, 2.5) # returning numpy image return mplfig_to_npimage(fig) # creating animationanimation = VideoClip(make_frame, duration = duration) # displaying animation with auto play and loopinganimation.ipython_display(fps = 20, loop = True, autoplay = True)", "e": 2858, "s": 2091, "text": null }, { "code": null, "e": 2869, "s": 2858, "text": "Output : " }, { "code": null, "e": 3118, "s": 2869, "text": "Moviepy - Building video __temp__.mp4.\nMoviepy - Writing video __temp__.mp4\n\n \nMoviepy - Done !\nMoviepy - video ready __temp__.mp4" }, { "code": null, "e": 3133, "s": 3124, "text": "sweetyty" }, { "code": null, "e": 3148, "s": 3133, "text": "prachisoda1234" }, { "code": null, "e": 3163, "s": 3148, "text": "Python-MoviePy" }, { "code": null, "e": 3170, "s": 3163, "text": "Python" }, { "code": null, "e": 3268, "s": 3170, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3300, "s": 3268, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 3327, "s": 3300, "text": "Python Classes and Objects" }, { "code": null, "e": 3348, "s": 3327, "text": "Python OOPs Concepts" }, { "code": null, "e": 3371, "s": 3348, "text": "Introduction To PYTHON" }, { "code": null, "e": 3427, "s": 3371, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 3458, "s": 3427, "text": "Python | os.path.join() method" }, { "code": null, "e": 3500, "s": 3458, "text": "Check if element exists in list in Python" }, { "code": null, "e": 3542, "s": 3500, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 3581, "s": 3542, "text": "Python | Get unique values from a list" } ]
HTML | DOM Local Storage clear() Method
26 Jul, 2019 The clear() method removes all the Storage Object items for the current domain.Syntax: localStorage.clear() Property Values:No Property Values Example: Set item, clear and display for the current domain. <!DOCTYPE html><html> <head> <style> body { text-align: center; } h1 { color: green; } </style></head> <body> <h1>GeeksforGeeks</h1> <h2>HTML DOM Storage clear() Method</h2> <p> Example to demonstrate the use of storage clear() method to delete all the local storage items for this domain. </p> <p> Script to create some local storage items. Click the button to create the items: </p> <button onclick="createItems()"> Create local storage items </button> <h2>Display Items</h2> <p> Click the button to display all the items: </p> <button onclick="displayItems()"> Display items </button> <p id="demo"></p> <h2>Remove Items</h2> <p> Click the button to clear the storage: </p> <button onclick="deleteItems()"> Clear </button> <h2>Display Items Again</h2> <p> Click the button to display all the items: </p> <button onclick="displayItems()"> Display again </button> <p id="demo"></p> <script> function createItems() { // Set item in local storage. localStorage.setItem("GeeksForGeeks", ""); localStorage.setItem("HTML DOM", ""); localStorage.setItem("Storage Clear() Method", ""); } function deleteItems() { // Clear local storage items. localStorage.clear(); } function displayItems() { var l, i; // Display items. document.getElementById("demo").innerHTML = ""; for (i = 0; i < localStorage.length; i++) { x = localStorage.key(i); document.getElementById("demo").innerHTML += x; } } </script> </body> </html> Output: Supported Browsers: The browser supported by DOM Local Storage clear() are listed below: Google Chrome 4.0 Internet Explorer 8.0 Mizilla Firefox 3.5 Opera 10.5 Safari 4.0 HTML-DOM Picked HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n26 Jul, 2019" }, { "code": null, "e": 115, "s": 28, "text": "The clear() method removes all the Storage Object items for the current domain.Syntax:" }, { "code": null, "e": 136, "s": 115, "text": "localStorage.clear()" }, { "code": null, "e": 171, "s": 136, "text": "Property Values:No Property Values" }, { "code": null, "e": 232, "s": 171, "text": "Example: Set item, clear and display for the current domain." }, { "code": "<!DOCTYPE html><html> <head> <style> body { text-align: center; } h1 { color: green; } </style></head> <body> <h1>GeeksforGeeks</h1> <h2>HTML DOM Storage clear() Method</h2> <p> Example to demonstrate the use of storage clear() method to delete all the local storage items for this domain. </p> <p> Script to create some local storage items. Click the button to create the items: </p> <button onclick=\"createItems()\"> Create local storage items </button> <h2>Display Items</h2> <p> Click the button to display all the items: </p> <button onclick=\"displayItems()\"> Display items </button> <p id=\"demo\"></p> <h2>Remove Items</h2> <p> Click the button to clear the storage: </p> <button onclick=\"deleteItems()\"> Clear </button> <h2>Display Items Again</h2> <p> Click the button to display all the items: </p> <button onclick=\"displayItems()\"> Display again </button> <p id=\"demo\"></p> <script> function createItems() { // Set item in local storage. localStorage.setItem(\"GeeksForGeeks\", \"\"); localStorage.setItem(\"HTML DOM\", \"\"); localStorage.setItem(\"Storage Clear() Method\", \"\"); } function deleteItems() { // Clear local storage items. localStorage.clear(); } function displayItems() { var l, i; // Display items. document.getElementById(\"demo\").innerHTML = \"\"; for (i = 0; i < localStorage.length; i++) { x = localStorage.key(i); document.getElementById(\"demo\").innerHTML += x; } } </script> </body> </html>", "e": 2082, "s": 232, "text": null }, { "code": null, "e": 2090, "s": 2082, "text": "Output:" }, { "code": null, "e": 2179, "s": 2090, "text": "Supported Browsers: The browser supported by DOM Local Storage clear() are listed below:" }, { "code": null, "e": 2197, "s": 2179, "text": "Google Chrome 4.0" }, { "code": null, "e": 2219, "s": 2197, "text": "Internet Explorer 8.0" }, { "code": null, "e": 2239, "s": 2219, "text": "Mizilla Firefox 3.5" }, { "code": null, "e": 2250, "s": 2239, "text": "Opera 10.5" }, { "code": null, "e": 2261, "s": 2250, "text": "Safari 4.0" }, { "code": null, "e": 2270, "s": 2261, "text": "HTML-DOM" }, { "code": null, "e": 2277, "s": 2270, "text": "Picked" }, { "code": null, "e": 2282, "s": 2277, "text": "HTML" }, { "code": null, "e": 2299, "s": 2282, "text": "Web Technologies" }, { "code": null, "e": 2304, "s": 2299, "text": "HTML" } ]
Matplotlib.axes.Axes.set_yticklabels() in Python
30 Jun, 2022 Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute. The Axes.set_yticklabels() function in axes module of matplotlib library is used to Set the y-tick labels with list of string labels. Syntax: Axes.set_yticklabels(self, labels, fontdict=None, minor=False, **kwargs) Parameters: This method accepts the following parameters. labels : This parameter is the list of string labels. fontdict : This parameter is the dictionary controlling the appearance of the ticklabels. minor : This parameter is used whether set major ticks or to set minor ticks Return value: This method returns a list of Text instances. Below examples illustrate the matplotlib.axes.Axes.set_yticklabels() function in matplotlib.axes: Example 1: Python3 # Implementation of matplotlib functionimport matplotlib.pyplot as pltimport matplotlib.transforms as mtransforms fig, ax = plt.subplots()ax.plot(range(12, 24), range(12))ax.set_yticks((2, 5, 7, 10))ax.set_yticklabels(("Label-1", "Label-2", "Label-3", "Label-4")) fig.suptitle('matplotlib.axes.Axes.set_yticklabels()\ function Example\n\n', fontweight ="bold")fig.canvas.draw()plt.show() Output: Example 2: Python3 # Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as plt # Fixing random state for reproducibilitynp.random.seed(19680801) x = np.linspace(0, 2 * np.pi, 100)y = np.sin(x)y2 = y + 0.2 * np.random.normal(size = x.shape) fig, ax = plt.subplots()ax.plot(x, y)ax.plot(x, y2) ax.set_yticks([-1, 0, 1]) ax.spines['left'].set_bounds(-1, 1)ax.spines['right'].set_visible(False)ax.spines['top'].set_visible(False) ax.set_yticklabels(("Val-1", "Val-2", "Val-3")) fig.suptitle('matplotlib.axes.Axes.set_yticklabels()\ function Example\n\n', fontweight ="bold")fig.canvas.draw()plt.show() Output: simmytarika5 Python-matplotlib Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Python OOPs Concepts Iterate over a list in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n30 Jun, 2022" }, { "code": null, "e": 328, "s": 28, "text": "Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute." }, { "code": null, "e": 462, "s": 328, "text": "The Axes.set_yticklabels() function in axes module of matplotlib library is used to Set the y-tick labels with list of string labels." }, { "code": null, "e": 544, "s": 462, "text": "Syntax: Axes.set_yticklabels(self, labels, fontdict=None, minor=False, **kwargs) " }, { "code": null, "e": 602, "s": 544, "text": "Parameters: This method accepts the following parameters." }, { "code": null, "e": 656, "s": 602, "text": "labels : This parameter is the list of string labels." }, { "code": null, "e": 746, "s": 656, "text": "fontdict : This parameter is the dictionary controlling the appearance of the ticklabels." }, { "code": null, "e": 823, "s": 746, "text": "minor : This parameter is used whether set major ticks or to set minor ticks" }, { "code": null, "e": 883, "s": 823, "text": "Return value: This method returns a list of Text instances." }, { "code": null, "e": 982, "s": 883, "text": "Below examples illustrate the matplotlib.axes.Axes.set_yticklabels() function in matplotlib.axes: " }, { "code": null, "e": 994, "s": 982, "text": "Example 1: " }, { "code": null, "e": 1002, "s": 994, "text": "Python3" }, { "code": "# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport matplotlib.transforms as mtransforms fig, ax = plt.subplots()ax.plot(range(12, 24), range(12))ax.set_yticks((2, 5, 7, 10))ax.set_yticklabels((\"Label-1\", \"Label-2\", \"Label-3\", \"Label-4\")) fig.suptitle('matplotlib.axes.Axes.set_yticklabels()\\ function Example\\n\\n', fontweight =\"bold\")fig.canvas.draw()plt.show()", "e": 1411, "s": 1002, "text": null }, { "code": null, "e": 1419, "s": 1411, "text": "Output:" }, { "code": null, "e": 1434, "s": 1422, "text": "Example 2: " }, { "code": null, "e": 1442, "s": 1434, "text": "Python3" }, { "code": "# Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as plt # Fixing random state for reproducibilitynp.random.seed(19680801) x = np.linspace(0, 2 * np.pi, 100)y = np.sin(x)y2 = y + 0.2 * np.random.normal(size = x.shape) fig, ax = plt.subplots()ax.plot(x, y)ax.plot(x, y2) ax.set_yticks([-1, 0, 1]) ax.spines['left'].set_bounds(-1, 1)ax.spines['right'].set_visible(False)ax.spines['top'].set_visible(False) ax.set_yticklabels((\"Val-1\", \"Val-2\", \"Val-3\")) fig.suptitle('matplotlib.axes.Axes.set_yticklabels()\\ function Example\\n\\n', fontweight =\"bold\")fig.canvas.draw()plt.show()", "e": 2057, "s": 1442, "text": null }, { "code": null, "e": 2065, "s": 2057, "text": "Output:" }, { "code": null, "e": 2080, "s": 2067, "text": "simmytarika5" }, { "code": null, "e": 2098, "s": 2080, "text": "Python-matplotlib" }, { "code": null, "e": 2105, "s": 2098, "text": "Python" }, { "code": null, "e": 2203, "s": 2105, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2221, "s": 2203, "text": "Python Dictionary" }, { "code": null, "e": 2263, "s": 2221, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2285, "s": 2263, "text": "Enumerate() in Python" }, { "code": null, "e": 2320, "s": 2285, "text": "Read a file line by line in Python" }, { "code": null, "e": 2346, "s": 2320, "text": "Python String | replace()" }, { "code": null, "e": 2378, "s": 2346, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2407, "s": 2378, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2434, "s": 2407, "text": "Python Classes and Objects" }, { "code": null, "e": 2455, "s": 2434, "text": "Python OOPs Concepts" } ]
Cursors in DBMS – Definition, Types, Attributes, Uses
07 Dec, 2021 Database Management System(DBMS) supports Data Manipulation Language statements like Insert, Update and Delete queries. Each database syntactically differs but the functionality remains the same in the mentioned operations. In this article, let us see about performing insert, update and delete queries using the cursor. Cursors Whenever DML statements are executed, a temporary work area is created in the system memory and it is called a cursor. A cursor can have more than one row, but processing wise only 1 row is taken into account. Cursors are very helpful in all kinds of databases like Oracle, SQL Server, MySQL, etc. They can be used well with DML statements like Update, Insert and Delete. Especially Implicit cursors are there with these operations. From time to time it changes the values and hence the implicit cursor attribute values need to be assigned in a local variable for further use. In PL/SQL, two different types of cursors are available. Implicit cursors Explicit cursors Explicit cursors Explicit cursors are defined by the programmers to have more control area on the context area. It has to be defined in the declaration section of the PL/SQL Block. Usually, It is defined on a SELECT Statement and it returns more than one row as output. We can iterate over the rows of data and perform the required operations. Steps involved in creating explicit cursors: Cursor Declaration for initializing the memory CURSOR <cursorName> IS SELECT <Required fields> FROM <tableName>; Cursor Opening to allocate the memory OPEN <cursorName>; Cursor Fetching to retrieve the data FETCH <cursorName> INTO <Respective columns> Cursor Closing to release the allocated memory CLOSE <cursorName>; Example: DECLARE empId employees.EMPLOYEEID%type; empName employees.EMPLOYEENAME%type; empCity employees.EMPLOYEECITY%type; CURSOR c_employees is SELECT EMPLOYEEID, EMPLOYEENAME, EMPLOYEECITY FROM employees; BEGIN OPEN c_employees; LOOP FETCH c_employees into empId , empName , empCity; EXIT WHEN c_employees %notfound; dbms_output.put_line(empId || ' ' || empName || ' ' || empCity); END LOOP; CLOSE c_employees ; END; / Output: Implicit cursors For DML statements, implicit cursors are available in PL/SQL i.e. no need to declare the cursor, and even for the queries that return 1 row, implicit cursors are available. Through the cursor attributes, we can track the information about the execution of an implicit cursor. Attributes of Implicit Cursors: Implicit cursor attributes provide the results about the execution of INSERT, UPDATE, and DELETE. We have different Cursor attributes like “%FOUND”, “%ISOPEN”, “%NOTFOUND”, and %ROWCOUNT. The most recently executed SQL statement result will be available in Cursor. Initially cursor value will be null. Let us see the different cursor attributes one by one with regards to the DML statements. So let us create a sample table named “employees” in oracle: CREATE TABLE employees ( EMPLOYEEID number(10) NOT NULL, EMPLOYEENAME varchar2(50) NOT NULL, EMPLOYEECITY varchar2(50) ); Insert the records in “employees” table INSERT INTO employees (employeeId,employeeName,employeeCity) VALUES (1,'XXX','CHENNAI'); INSERT INTO employees (employeeId,employeeName,employeeCity) VALUES (2,'XYZ','MUMBAI'); INSERT INTO employees (employeeId,employeeName,employeeCity) VALUES (3,'YYY','CALCUTTA'); Existence of records in “employees” table SELECT * FROM employees; %FOUND attribute CREATE TABLE tempory_employee AS SELECT * FROM employees; DECLARE employeeNo NUMBER(4) := 2; BEGIN DELETE FROM tempory_employee WHERE employeeId = employeeNo ; IF SQL%FOUND THEN -- delete succeeded INSERT INTO tempory_employee (employeeId,employeeName,employeeCity) VALUES (2, 'ZZZ', 'Delhi'); END IF; END; / Now check for the details present in the tempory_employee table SELECT * FROM tempory_employee; Output: %FOUND attribute and performing update operation example CREATE TABLE tempory_employee1 AS SELECT * FROM employees; DECLARE employeeNo NUMBER(4) := 2; BEGIN DELETE FROM tempory_employee WHERE employeeId = employeeNo ; IF SQL%FOUND THEN -- delete succeeded UPDATE employees SET employeeCity = 'Chandigarh' WHERE employeeId = 1; END IF; END; / Output from SELECT * FROM employees: %FOUND attribute upon update operation and then performing delete operation example CREATE TABLE tempory_employee2 AS SELECT * FROM employees; DECLARE employeeNo NUMBER(4) := 2; BEGIN UPDATE tempory_employee2 SET employeeCity = 'Gurgaon' WHERE employeeId = employeeNo; IF SQL%FOUND THEN -- update succeeded DELETE FROM tempory_employee2 WHERE employeeId = 1 ; -- Then delete a specific row END IF; END; / Output: After doing above operations %ISOPEN Attribute: For Implicit Cursors, always the result is False. The reason is Oracle closes immediately after executing the DML result. Hence the result is FALSE. %NOTFOUND Attribute: It is just the opposite of %FOUND. %NOTFOUND is the logical opposite of %FOUND. %NOTFOUND results in TRUE value for an INSERT, UPDATE, or DELETE statement which affected no rows. By default, it returns False. %ROWCOUNT Attribute: A number of rows affected by an INSERT, UPDATE or DELETE statement are given by %ROWCOUNT. When there are no rows are affected, %ROWCOUNT gives 0 as the result, otherwise, it returns the number of rows that have been deleted. CREATE TABLE tempory_employee3 AS SELECT * FROM employees; DECLARE employeeNo NUMBER(4) := 2; BEGIN DELETE FROM tempory_employee3 WHERE employeeId = employeeNo ; DBMS_OUTPUT.PUT_LINE('Number of employees deleted: ' || TO_CHAR(SQL%ROWCOUNT)); END; Output: The values of the cursor attribute have to be saved in a local variable and those variables can be used in future uses. The reason is while doing multiple database operations in different blocks, cursor attribute values keep on changing and hence this is much required. The %NOTFOUND attribute is better used only with DML statements but not with SELECT INTO statement. Picked Class 12 School Learning School Programming Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n07 Dec, 2021" }, { "code": null, "e": 349, "s": 28, "text": "Database Management System(DBMS) supports Data Manipulation Language statements like Insert, Update and Delete queries. Each database syntactically differs but the functionality remains the same in the mentioned operations. In this article, let us see about performing insert, update and delete queries using the cursor." }, { "code": null, "e": 357, "s": 349, "text": "Cursors" }, { "code": null, "e": 991, "s": 357, "text": "Whenever DML statements are executed, a temporary work area is created in the system memory and it is called a cursor. A cursor can have more than one row, but processing wise only 1 row is taken into account. Cursors are very helpful in all kinds of databases like Oracle, SQL Server, MySQL, etc. They can be used well with DML statements like Update, Insert and Delete. Especially Implicit cursors are there with these operations. From time to time it changes the values and hence the implicit cursor attribute values need to be assigned in a local variable for further use. In PL/SQL, two different types of cursors are available." }, { "code": null, "e": 1009, "s": 991, "text": "Implicit cursors " }, { "code": null, "e": 1026, "s": 1009, "text": "Explicit cursors" }, { "code": null, "e": 1043, "s": 1026, "text": "Explicit cursors" }, { "code": null, "e": 1370, "s": 1043, "text": "Explicit cursors are defined by the programmers to have more control area on the context area. It has to be defined in the declaration section of the PL/SQL Block. Usually, It is defined on a SELECT Statement and it returns more than one row as output. We can iterate over the rows of data and perform the required operations." }, { "code": null, "e": 1415, "s": 1370, "text": "Steps involved in creating explicit cursors:" }, { "code": null, "e": 1462, "s": 1415, "text": "Cursor Declaration for initializing the memory" }, { "code": null, "e": 1532, "s": 1462, "text": "CURSOR <cursorName> IS \n SELECT <Required fields> FROM <tableName>;" }, { "code": null, "e": 1570, "s": 1532, "text": "Cursor Opening to allocate the memory" }, { "code": null, "e": 1590, "s": 1570, "text": "OPEN <cursorName>; " }, { "code": null, "e": 1627, "s": 1590, "text": "Cursor Fetching to retrieve the data" }, { "code": null, "e": 1672, "s": 1627, "text": "FETCH <cursorName> INTO <Respective columns>" }, { "code": null, "e": 1719, "s": 1672, "text": "Cursor Closing to release the allocated memory" }, { "code": null, "e": 1739, "s": 1719, "text": "CLOSE <cursorName>;" }, { "code": null, "e": 1748, "s": 1739, "text": "Example:" }, { "code": null, "e": 2221, "s": 1748, "text": "DECLARE \n empId employees.EMPLOYEEID%type; \n empName employees.EMPLOYEENAME%type; \n empCity employees.EMPLOYEECITY%type; \n CURSOR c_employees is \n SELECT EMPLOYEEID, EMPLOYEENAME, EMPLOYEECITY FROM employees; \nBEGIN \n OPEN c_employees; \n LOOP \n FETCH c_employees into empId , empName , empCity; \n EXIT WHEN c_employees %notfound; \n dbms_output.put_line(empId || ' ' || empName || ' ' || empCity); \n END LOOP; \n CLOSE c_employees ; \nEND; \n/" }, { "code": null, "e": 2229, "s": 2221, "text": "Output:" }, { "code": null, "e": 2246, "s": 2229, "text": "Implicit cursors" }, { "code": null, "e": 2522, "s": 2246, "text": "For DML statements, implicit cursors are available in PL/SQL i.e. no need to declare the cursor, and even for the queries that return 1 row, implicit cursors are available. Through the cursor attributes, we can track the information about the execution of an implicit cursor." }, { "code": null, "e": 2554, "s": 2522, "text": "Attributes of Implicit Cursors:" }, { "code": null, "e": 2857, "s": 2554, "text": "Implicit cursor attributes provide the results about the execution of INSERT, UPDATE, and DELETE. We have different Cursor attributes like “%FOUND”, “%ISOPEN”, “%NOTFOUND”, and %ROWCOUNT. The most recently executed SQL statement result will be available in Cursor. Initially cursor value will be null." }, { "code": null, "e": 3008, "s": 2857, "text": "Let us see the different cursor attributes one by one with regards to the DML statements. So let us create a sample table named “employees” in oracle:" }, { "code": null, "e": 3141, "s": 3008, "text": "CREATE TABLE employees\n( EMPLOYEEID number(10) NOT NULL, \n EMPLOYEENAME varchar2(50) NOT NULL, \n EMPLOYEECITY varchar2(50) \n); " }, { "code": null, "e": 3181, "s": 3141, "text": "Insert the records in “employees” table" }, { "code": null, "e": 3448, "s": 3181, "text": "INSERT INTO employees (employeeId,employeeName,employeeCity) VALUES (1,'XXX','CHENNAI');\nINSERT INTO employees (employeeId,employeeName,employeeCity) VALUES (2,'XYZ','MUMBAI');\nINSERT INTO employees (employeeId,employeeName,employeeCity) VALUES (3,'YYY','CALCUTTA');" }, { "code": null, "e": 3490, "s": 3448, "text": "Existence of records in “employees” table" }, { "code": null, "e": 3515, "s": 3490, "text": "SELECT * FROM employees;" }, { "code": null, "e": 3532, "s": 3515, "text": "%FOUND attribute" }, { "code": null, "e": 3857, "s": 3532, "text": "CREATE TABLE tempory_employee AS SELECT * FROM employees;\nDECLARE\n employeeNo NUMBER(4) := 2;\nBEGIN\n DELETE FROM tempory_employee WHERE employeeId = employeeNo ;\n IF SQL%FOUND THEN -- delete succeeded\n INSERT INTO tempory_employee (employeeId,employeeName,employeeCity) VALUES (2, 'ZZZ', 'Delhi');\n END IF;\nEND;\n/" }, { "code": null, "e": 3922, "s": 3857, "text": "Now check for the details present in the tempory_employee table" }, { "code": null, "e": 3954, "s": 3922, "text": "SELECT * FROM tempory_employee;" }, { "code": null, "e": 3962, "s": 3954, "text": "Output:" }, { "code": null, "e": 4019, "s": 3962, "text": "%FOUND attribute and performing update operation example" }, { "code": null, "e": 4319, "s": 4019, "text": "CREATE TABLE tempory_employee1 AS SELECT * FROM employees;\nDECLARE\n employeeNo NUMBER(4) := 2;\nBEGIN\n DELETE FROM tempory_employee WHERE employeeId = employeeNo ;\n IF SQL%FOUND THEN -- delete succeeded\n UPDATE employees SET employeeCity = 'Chandigarh' WHERE employeeId = 1;\n END IF;\nEND;\n/" }, { "code": null, "e": 4356, "s": 4319, "text": "Output from SELECT * FROM employees:" }, { "code": null, "e": 4440, "s": 4356, "text": "%FOUND attribute upon update operation and then performing delete operation example" }, { "code": null, "e": 4777, "s": 4440, "text": "CREATE TABLE tempory_employee2 AS SELECT * FROM employees;\nDECLARE\n employeeNo NUMBER(4) := 2;\nBEGIN\n UPDATE tempory_employee2 SET employeeCity = 'Gurgaon' WHERE employeeId = employeeNo;\n IF SQL%FOUND THEN -- update succeeded\n DELETE FROM tempory_employee2 WHERE employeeId = 1 ; -- Then delete a specific row\n END IF;\nEND;\n/" }, { "code": null, "e": 4785, "s": 4777, "text": "Output:" }, { "code": null, "e": 4814, "s": 4785, "text": "After doing above operations" }, { "code": null, "e": 4983, "s": 4814, "text": "%ISOPEN Attribute: For Implicit Cursors, always the result is False. The reason is Oracle closes immediately after executing the DML result. Hence the result is FALSE." }, { "code": null, "e": 5213, "s": 4983, "text": "%NOTFOUND Attribute: It is just the opposite of %FOUND. %NOTFOUND is the logical opposite of %FOUND. %NOTFOUND results in TRUE value for an INSERT, UPDATE, or DELETE statement which affected no rows. By default, it returns False." }, { "code": null, "e": 5460, "s": 5213, "text": "%ROWCOUNT Attribute: A number of rows affected by an INSERT, UPDATE or DELETE statement are given by %ROWCOUNT. When there are no rows are affected, %ROWCOUNT gives 0 as the result, otherwise, it returns the number of rows that have been deleted." }, { "code": null, "e": 5713, "s": 5460, "text": "CREATE TABLE tempory_employee3 AS SELECT * FROM employees;\nDECLARE employeeNo NUMBER(4) := 2;\nBEGIN\n DELETE FROM tempory_employee3 WHERE employeeId = employeeNo ;\n DBMS_OUTPUT.PUT_LINE('Number of employees deleted: ' || TO_CHAR(SQL%ROWCOUNT));\nEND;" }, { "code": null, "e": 5721, "s": 5713, "text": "Output:" }, { "code": null, "e": 5991, "s": 5721, "text": "The values of the cursor attribute have to be saved in a local variable and those variables can be used in future uses. The reason is while doing multiple database operations in different blocks, cursor attribute values keep on changing and hence this is much required." }, { "code": null, "e": 6092, "s": 5991, "text": " The %NOTFOUND attribute is better used only with DML statements but not with SELECT INTO statement." }, { "code": null, "e": 6099, "s": 6092, "text": "Picked" }, { "code": null, "e": 6108, "s": 6099, "text": "Class 12" }, { "code": null, "e": 6124, "s": 6108, "text": "School Learning" }, { "code": null, "e": 6143, "s": 6124, "text": "School Programming" } ]
Maximum Subarray Sum using Divide and Conquer algorithm
21 Jun, 2022 You are given a one dimensional array that may contain both positive and negative integers, find the sum of contiguous subarray of numbers which has the largest sum. For example, if the given array is {-2, -5, 6, -2, -3, 1, 5, -6}, then the maximum subarray sum is 7 (see highlighted elements). 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. The naive method is to run two loops. The outer loop picks the beginning element, the inner loop finds the maximum possible sum with first element picked by outer loop and compares this maximum with the overall maximum. Finally, return the overall maximum. The time complexity of the Naive method is O(n^2). Using Divide and Conquer approach, we can find the maximum subarray sum in O(nLogn) time. Following is the Divide and Conquer algorithm. Divide the given array in two halvesReturn the maximum of following threeMaximum subarray sum in left half (Make a recursive call)Maximum subarray sum in right half (Make a recursive call)Maximum subarray sum such that the subarray crosses the midpoint Divide the given array in two halves Return the maximum of following threeMaximum subarray sum in left half (Make a recursive call)Maximum subarray sum in right half (Make a recursive call)Maximum subarray sum such that the subarray crosses the midpoint Maximum subarray sum in left half (Make a recursive call) Maximum subarray sum in right half (Make a recursive call) Maximum subarray sum such that the subarray crosses the midpoint The lines 2.a and 2.b are simple recursive calls. How to find maximum subarray sum such that the subarray crosses the midpoint? We can easily find the crossing sum in linear time. The idea is simple, find the maximum sum starting from mid point and ending at some point on left of mid, then find the maximum sum starting from mid + 1 and ending with some point on right of mid + 1. Finally, combine the two and return the maximum among left, right and combination of both. Below is the implementation of the above approach: C++ Java Python C# PHP Javascript // A Divide and Conquer based program for maximum subarray// sum problem#include <limits.h>#include <stdio.h> // A utility function to find maximum of two integersint max(int a, int b) { return (a > b) ? a : b; } // A utility function to find maximum of three integersint max(int a, int b, int c) { return max(max(a, b), c); } // Find the maximum possible sum in arr[] such that arr[m]// is part of itint maxCrossingSum(int arr[], int l, int m, int h){ // Include elements on left of mid. int sum = 0; int left_sum = INT_MIN; for (int i = m; i >= l; i--) { sum = sum + arr[i]; if (sum > left_sum) left_sum = sum; } // Include elements on right of mid sum = 0; int right_sum = INT_MIN; for (int i = m + 1; i <= h; i++) { sum = sum + arr[i]; if (sum > right_sum) right_sum = sum; } // Return sum of elements on left and right of mid // returning only left_sum + right_sum will fail for // [-2, 1] return max(left_sum + right_sum, left_sum, right_sum);} // Returns sum of maximum sum subarray in aa[l..h]int maxSubArraySum(int arr[], int l, int h){ // Base Case: Only one element if (l == h) return arr[l]; // Find middle point int m = (l + h) / 2; /* Return maximum of following three possible cases a) Maximum subarray sum in left half b) Maximum subarray sum in right half c) Maximum subarray sum such that the subarray crosses the midpoint */ return max(maxSubArraySum(arr, l, m), maxSubArraySum(arr, m + 1, h), maxCrossingSum(arr, l, m, h));} /*Driver program to test maxSubArraySum*/int main(){ int arr[] = { 2, 3, 4, 5, 7 }; int n = sizeof(arr) / sizeof(arr[0]); int max_sum = maxSubArraySum(arr, 0, n - 1); printf("Maximum contiguous sum is %d\n", max_sum); getchar(); return 0;} // A Divide and Conquer based Java// program for maximum subarray sum// problemimport java.util.*; class GFG { // Find the maximum possible sum in arr[] // such that arr[m] is part of it static int maxCrossingSum(int arr[], int l, int m, int h) { // Include elements on left of mid. int sum = 0; int left_sum = Integer.MIN_VALUE; for (int i = m; i >= l; i--) { sum = sum + arr[i]; if (sum > left_sum) left_sum = sum; } // Include elements on right of mid sum = 0; int right_sum = Integer.MIN_VALUE; for (int i = m + 1; i <= h; i++) { sum = sum + arr[i]; if (sum > right_sum) right_sum = sum; } // Return sum of elements on left // and right of mid // returning only left_sum + right_sum will fail for // [-2, 1] return Math.max(left_sum + right_sum, Math.max(left_sum, right_sum)); } // Returns sum of maximum sum subarray // in aa[l..h] static int maxSubArraySum(int arr[], int l, int h) { // Base Case: Only one element if (l == h) return arr[l]; // Find middle point int m = (l + h) / 2; /* Return maximum of following three possible cases: a) Maximum subarray sum in left half b) Maximum subarray sum in right half c) Maximum subarray sum such that the subarray crosses the midpoint */ return Math.max( Math.max(maxSubArraySum(arr, l, m), maxSubArraySum(arr, m + 1, h)), maxCrossingSum(arr, l, m, h)); } /* Driver program to test maxSubArraySum */ public static void main(String[] args) { int arr[] = { 2, 3, 4, 5, 7 }; int n = arr.length; int max_sum = maxSubArraySum(arr, 0, n - 1); System.out.println("Maximum contiguous sum is " + max_sum); }}// This code is contributed by Prerna Saini # A Divide and Conquer based program# for maximum subarray sum problem # Find the maximum possible sum in# arr[] auch that arr[m] is part of it def maxCrossingSum(arr, l, m, h): # Include elements on left of mid. sm = 0 left_sum = -10000 for i in range(m, l-1, -1): sm = sm + arr[i] if (sm > left_sum): left_sum = sm # Include elements on right of mid sm = 0 right_sum = -1000 for i in range(m + 1, h + 1): sm = sm + arr[i] if (sm > right_sum): right_sum = sm # Return sum of elements on left and right of mid # returning only left_sum + right_sum will fail for [-2, 1] return max(left_sum + right_sum, left_sum, right_sum) # Returns sum of maximum sum subarray in aa[l..h]def maxSubArraySum(arr, l, h): # Base Case: Only one element if (l == h): return arr[l] # Find middle point m = (l + h) // 2 # Return maximum of following three possible cases # a) Maximum subarray sum in left half # b) Maximum subarray sum in right half # c) Maximum subarray sum such that the # subarray crosses the midpoint return max(maxSubArraySum(arr, l, m), maxSubArraySum(arr, m+1, h), maxCrossingSum(arr, l, m, h)) # Driver Codearr = [2, 3, 4, 5, 7]n = len(arr) max_sum = maxSubArraySum(arr, 0, n-1)print("Maximum contiguous sum is ", max_sum) # This code is contributed by Nikita Tiwari. // A Divide and Conquer based C#// program for maximum subarray sum// problemusing System; class GFG { // Find the maximum possible sum in arr[] // such that arr[m] is part of it static int maxCrossingSum(int[] arr, int l, int m, int h) { // Include elements on left of mid. int sum = 0; int left_sum = int.MinValue; for (int i = m; i >= l; i--) { sum = sum + arr[i]; if (sum > left_sum) left_sum = sum; } // Include elements on right of mid sum = 0; int right_sum = int.MinValue; ; for (int i = m + 1; i <= h; i++) { sum = sum + arr[i]; if (sum > right_sum) right_sum = sum; } // Return sum of elements on left // and right of mid // returning only left_sum + right_sum will fail for // [-2, 1] return Math.Max(left_sum + right_sum, Math.Max(left_sum, right_sum)); } // Returns sum of maximum sum subarray // in aa[l..h] static int maxSubArraySum(int[] arr, int l, int h) { // Base Case: Only one element if (l == h) return arr[l]; // Find middle point int m = (l + h) / 2; /* Return maximum of following three possible cases: a) Maximum subarray sum in left half b) Maximum subarray sum in right half c) Maximum subarray sum such that the subarray crosses the midpoint */ return Math.Max( Math.Max(maxSubArraySum(arr, l, m), maxSubArraySum(arr, m + 1, h)), maxCrossingSum(arr, l, m, h)); } /* Driver program to test maxSubArraySum */ public static void Main() { int[] arr = { 2, 3, 4, 5, 7 }; int n = arr.Length; int max_sum = maxSubArraySum(arr, 0, n - 1); Console.Write("Maximum contiguous sum is " + max_sum); }} // This code is contributed by vt_m. <?php // A Divide and Conquer based program // for maximum subarray sum problem // Find the maximum possible sum in arr[] // such that arr[m] is part of it function maxCrossingSum(&$arr, $l, $m, $h) { // Include elements on left of mid. $sum = 0; $left_sum = PHP_INT_MIN; for ($i = $m; $i >= $l; $i--) { $sum = $sum + $arr[$i]; if ($sum > $left_sum) $left_sum = $sum; } // Include elements on right of mid $sum = 0; $right_sum = PHP_INT_MIN; for ($i = $m + 1; $i <= $h; $i++) { $sum = $sum + $arr[$i]; if ($sum > $right_sum) $right_sum = $sum; } // Return sum of elements on left // and right of mid // returning only left_sum + right_sum will fail for [-2, 1] return max($left_sum + $right_sum, $left_sum, $right_sum); } // Returns sum of maximum sum // subarray in aa[l..h] function maxSubArraySum(&$arr, $l, $h) { // Base Case: Only one element if ($l == $h) return $arr[$l]; // Find middle point $m = intval(($l + $h) / 2); /* Return maximum of following three possible cases a) Maximum subarray sum in left half b) Maximum subarray sum in right half c) Maximum subarray sum such that the subarray crosses the midpoint */ return max(maxSubArraySum($arr, $l, $m), maxSubArraySum($arr, $m + 1, $h), maxCrossingSum($arr, $l, $m, $h)); } // Driver Code $arr = array(2, 3, 4, 5, 7); $n = count($arr); $max_sum = maxSubArraySum($arr, 0, $n - 1); echo "Maximum contiguous sum is " . $max_sum; // This code is contributed by rathbhupendra, Aadil ?> <script> // A Divide and Conquer based program for maximum subarray // sum problem // A utility function to find maximum of two integers function max(a,b) { return (a > b) ? a : b; } // A utility function to find maximum of three integers function max(a,b,c) { return Math.max(Math.max(a, b), c); } // Find the maximum possible sum in arr[] auch that arr[m] // is part of it function maxCrossingSum(arr, l, m,h) { // Include elements on left of mid. let sum = 0; let left_sum = Number.MIN_VALUE; for (let i = m; i >= l; i--) { sum = sum + arr[i]; if (sum > left_sum) left_sum = sum; } // Include elements on right of mid sum = 0; let right_sum = Number.MIN_VALUE; for (let i = m + 1; i <= h; i++) { sum = sum + arr[i]; if (sum > right_sum) right_sum = sum; } // Return sum of elements on left and right of mid // returning only left_sum + right_sum will fail for // [-2, 1] return max(left_sum + right_sum, left_sum, right_sum); } // Returns sum of maximum sum subarray in aa[l..h] function maxSubArraySum(arr, l,h) { // Base Case: Only one element if (l == h) return arr[l]; // Find middle point let m = parseInt((l + h) / 2, 10); /* Return maximum of following three possible cases a) Maximum subarray sum in left half b) Maximum subarray sum in right half c) Maximum subarray sum such that the subarray crosses the midpoint */ return max(maxSubArraySum(arr, l, m), maxSubArraySum(arr, m + 1, h), maxCrossingSum(arr, l, m, h)); } let arr = [ 2, 3, 4, 5, 7 ]; let n = arr.length; let max_sum = maxSubArraySum(arr, 0, n - 1); document.write("Maximum contiguous sum is " + max_sum); // This code is contributed by vaibhavrabadiya117. </script> Maximum contiguous sum is 21n Time Complexity: maxSubArraySum() is a recursive method and time complexity can be expressed as following recurrence relation. T(n) = 2T(n/2) + Θ(n) Time Complexity : O(nlogn) Auxiliary Space: O(1).The above recurrence is similar to Merge Sort and can be solved either using Recurrence Tree method or Master method. It falls in case II of Master Method and solution of the recurrence is Θ(nLogn). The Kadane’s Algorithm for this problem takes O(n) time. Therefore the Kadane’s algorithm is better than the Divide and Conquer approach, but this problem can be considered as a good example to show power of Divide and Conquer. The above simple approach where we divide the array in two halves, reduces the time complexity from O(n^2) to O(nLogn). References: Introduction to Algorithms by Clifford Stein, Thomas H. Cormen, Charles E. Leiserson, Ronald L. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. rathbhupendra MohammedAadil mayanktyagi1709 vaibhavrabadiya117 ankitayan surindertarika1234 gabaa406 dspartho1998 arpita4086 srm_ anandkumarshivam2266 resonance443731 Amazon Junglee Games subarray subarray-sum Arrays Divide and Conquer Dynamic Programming Amazon Junglee Games Arrays Dynamic Programming Divide and Conquer Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n21 Jun, 2022" }, { "code": null, "e": 220, "s": 54, "text": "You are given a one dimensional array that may contain both positive and negative integers, find the sum of contiguous subarray of numbers which has the largest sum." }, { "code": null, "e": 349, "s": 220, "text": "For example, if the given array is {-2, -5, 6, -2, -3, 1, 5, -6}, then the maximum subarray sum is 7 (see highlighted elements)." }, { "code": null, "e": 358, "s": 349, "text": "Chapters" }, { "code": null, "e": 385, "s": 358, "text": "descriptions off, selected" }, { "code": null, "e": 435, "s": 385, "text": "captions settings, opens captions settings dialog" }, { "code": null, "e": 458, "s": 435, "text": "captions off, selected" }, { "code": null, "e": 466, "s": 458, "text": "English" }, { "code": null, "e": 490, "s": 466, "text": "This is a modal window." }, { "code": null, "e": 559, "s": 490, "text": "Beginning of dialog window. Escape will cancel and close the window." }, { "code": null, "e": 581, "s": 559, "text": "End of dialog window." }, { "code": null, "e": 889, "s": 581, "text": "The naive method is to run two loops. The outer loop picks the beginning element, the inner loop finds the maximum possible sum with first element picked by outer loop and compares this maximum with the overall maximum. Finally, return the overall maximum. The time complexity of the Naive method is O(n^2)." }, { "code": null, "e": 1027, "s": 889, "text": "Using Divide and Conquer approach, we can find the maximum subarray sum in O(nLogn) time. Following is the Divide and Conquer algorithm. " }, { "code": null, "e": 1280, "s": 1027, "text": "Divide the given array in two halvesReturn the maximum of following threeMaximum subarray sum in left half (Make a recursive call)Maximum subarray sum in right half (Make a recursive call)Maximum subarray sum such that the subarray crosses the midpoint" }, { "code": null, "e": 1317, "s": 1280, "text": "Divide the given array in two halves" }, { "code": null, "e": 1534, "s": 1317, "text": "Return the maximum of following threeMaximum subarray sum in left half (Make a recursive call)Maximum subarray sum in right half (Make a recursive call)Maximum subarray sum such that the subarray crosses the midpoint" }, { "code": null, "e": 1592, "s": 1534, "text": "Maximum subarray sum in left half (Make a recursive call)" }, { "code": null, "e": 1651, "s": 1592, "text": "Maximum subarray sum in right half (Make a recursive call)" }, { "code": null, "e": 1716, "s": 1651, "text": "Maximum subarray sum such that the subarray crosses the midpoint" }, { "code": null, "e": 2189, "s": 1716, "text": "The lines 2.a and 2.b are simple recursive calls. How to find maximum subarray sum such that the subarray crosses the midpoint? We can easily find the crossing sum in linear time. The idea is simple, find the maximum sum starting from mid point and ending at some point on left of mid, then find the maximum sum starting from mid + 1 and ending with some point on right of mid + 1. Finally, combine the two and return the maximum among left, right and combination of both." }, { "code": null, "e": 2241, "s": 2189, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 2245, "s": 2241, "text": "C++" }, { "code": null, "e": 2250, "s": 2245, "text": "Java" }, { "code": null, "e": 2257, "s": 2250, "text": "Python" }, { "code": null, "e": 2260, "s": 2257, "text": "C#" }, { "code": null, "e": 2264, "s": 2260, "text": "PHP" }, { "code": null, "e": 2275, "s": 2264, "text": "Javascript" }, { "code": "// A Divide and Conquer based program for maximum subarray// sum problem#include <limits.h>#include <stdio.h> // A utility function to find maximum of two integersint max(int a, int b) { return (a > b) ? a : b; } // A utility function to find maximum of three integersint max(int a, int b, int c) { return max(max(a, b), c); } // Find the maximum possible sum in arr[] such that arr[m]// is part of itint maxCrossingSum(int arr[], int l, int m, int h){ // Include elements on left of mid. int sum = 0; int left_sum = INT_MIN; for (int i = m; i >= l; i--) { sum = sum + arr[i]; if (sum > left_sum) left_sum = sum; } // Include elements on right of mid sum = 0; int right_sum = INT_MIN; for (int i = m + 1; i <= h; i++) { sum = sum + arr[i]; if (sum > right_sum) right_sum = sum; } // Return sum of elements on left and right of mid // returning only left_sum + right_sum will fail for // [-2, 1] return max(left_sum + right_sum, left_sum, right_sum);} // Returns sum of maximum sum subarray in aa[l..h]int maxSubArraySum(int arr[], int l, int h){ // Base Case: Only one element if (l == h) return arr[l]; // Find middle point int m = (l + h) / 2; /* Return maximum of following three possible cases a) Maximum subarray sum in left half b) Maximum subarray sum in right half c) Maximum subarray sum such that the subarray crosses the midpoint */ return max(maxSubArraySum(arr, l, m), maxSubArraySum(arr, m + 1, h), maxCrossingSum(arr, l, m, h));} /*Driver program to test maxSubArraySum*/int main(){ int arr[] = { 2, 3, 4, 5, 7 }; int n = sizeof(arr) / sizeof(arr[0]); int max_sum = maxSubArraySum(arr, 0, n - 1); printf(\"Maximum contiguous sum is %d\\n\", max_sum); getchar(); return 0;}", "e": 4175, "s": 2275, "text": null }, { "code": "// A Divide and Conquer based Java// program for maximum subarray sum// problemimport java.util.*; class GFG { // Find the maximum possible sum in arr[] // such that arr[m] is part of it static int maxCrossingSum(int arr[], int l, int m, int h) { // Include elements on left of mid. int sum = 0; int left_sum = Integer.MIN_VALUE; for (int i = m; i >= l; i--) { sum = sum + arr[i]; if (sum > left_sum) left_sum = sum; } // Include elements on right of mid sum = 0; int right_sum = Integer.MIN_VALUE; for (int i = m + 1; i <= h; i++) { sum = sum + arr[i]; if (sum > right_sum) right_sum = sum; } // Return sum of elements on left // and right of mid // returning only left_sum + right_sum will fail for // [-2, 1] return Math.max(left_sum + right_sum, Math.max(left_sum, right_sum)); } // Returns sum of maximum sum subarray // in aa[l..h] static int maxSubArraySum(int arr[], int l, int h) { // Base Case: Only one element if (l == h) return arr[l]; // Find middle point int m = (l + h) / 2; /* Return maximum of following three possible cases: a) Maximum subarray sum in left half b) Maximum subarray sum in right half c) Maximum subarray sum such that the subarray crosses the midpoint */ return Math.max( Math.max(maxSubArraySum(arr, l, m), maxSubArraySum(arr, m + 1, h)), maxCrossingSum(arr, l, m, h)); } /* Driver program to test maxSubArraySum */ public static void main(String[] args) { int arr[] = { 2, 3, 4, 5, 7 }; int n = arr.length; int max_sum = maxSubArraySum(arr, 0, n - 1); System.out.println(\"Maximum contiguous sum is \" + max_sum); }}// This code is contributed by Prerna Saini", "e": 6244, "s": 4175, "text": null }, { "code": "# A Divide and Conquer based program# for maximum subarray sum problem # Find the maximum possible sum in# arr[] auch that arr[m] is part of it def maxCrossingSum(arr, l, m, h): # Include elements on left of mid. sm = 0 left_sum = -10000 for i in range(m, l-1, -1): sm = sm + arr[i] if (sm > left_sum): left_sum = sm # Include elements on right of mid sm = 0 right_sum = -1000 for i in range(m + 1, h + 1): sm = sm + arr[i] if (sm > right_sum): right_sum = sm # Return sum of elements on left and right of mid # returning only left_sum + right_sum will fail for [-2, 1] return max(left_sum + right_sum, left_sum, right_sum) # Returns sum of maximum sum subarray in aa[l..h]def maxSubArraySum(arr, l, h): # Base Case: Only one element if (l == h): return arr[l] # Find middle point m = (l + h) // 2 # Return maximum of following three possible cases # a) Maximum subarray sum in left half # b) Maximum subarray sum in right half # c) Maximum subarray sum such that the # subarray crosses the midpoint return max(maxSubArraySum(arr, l, m), maxSubArraySum(arr, m+1, h), maxCrossingSum(arr, l, m, h)) # Driver Codearr = [2, 3, 4, 5, 7]n = len(arr) max_sum = maxSubArraySum(arr, 0, n-1)print(\"Maximum contiguous sum is \", max_sum) # This code is contributed by Nikita Tiwari.", "e": 7697, "s": 6244, "text": null }, { "code": "// A Divide and Conquer based C#// program for maximum subarray sum// problemusing System; class GFG { // Find the maximum possible sum in arr[] // such that arr[m] is part of it static int maxCrossingSum(int[] arr, int l, int m, int h) { // Include elements on left of mid. int sum = 0; int left_sum = int.MinValue; for (int i = m; i >= l; i--) { sum = sum + arr[i]; if (sum > left_sum) left_sum = sum; } // Include elements on right of mid sum = 0; int right_sum = int.MinValue; ; for (int i = m + 1; i <= h; i++) { sum = sum + arr[i]; if (sum > right_sum) right_sum = sum; } // Return sum of elements on left // and right of mid // returning only left_sum + right_sum will fail for // [-2, 1] return Math.Max(left_sum + right_sum, Math.Max(left_sum, right_sum)); } // Returns sum of maximum sum subarray // in aa[l..h] static int maxSubArraySum(int[] arr, int l, int h) { // Base Case: Only one element if (l == h) return arr[l]; // Find middle point int m = (l + h) / 2; /* Return maximum of following three possible cases: a) Maximum subarray sum in left half b) Maximum subarray sum in right half c) Maximum subarray sum such that the subarray crosses the midpoint */ return Math.Max( Math.Max(maxSubArraySum(arr, l, m), maxSubArraySum(arr, m + 1, h)), maxCrossingSum(arr, l, m, h)); } /* Driver program to test maxSubArraySum */ public static void Main() { int[] arr = { 2, 3, 4, 5, 7 }; int n = arr.Length; int max_sum = maxSubArraySum(arr, 0, n - 1); Console.Write(\"Maximum contiguous sum is \" + max_sum); }} // This code is contributed by vt_m.", "e": 9731, "s": 7697, "text": null }, { "code": "<?php // A Divide and Conquer based program // for maximum subarray sum problem // Find the maximum possible sum in arr[] // such that arr[m] is part of it function maxCrossingSum(&$arr, $l, $m, $h) { // Include elements on left of mid. $sum = 0; $left_sum = PHP_INT_MIN; for ($i = $m; $i >= $l; $i--) { $sum = $sum + $arr[$i]; if ($sum > $left_sum) $left_sum = $sum; } // Include elements on right of mid $sum = 0; $right_sum = PHP_INT_MIN; for ($i = $m + 1; $i <= $h; $i++) { $sum = $sum + $arr[$i]; if ($sum > $right_sum) $right_sum = $sum; } // Return sum of elements on left // and right of mid // returning only left_sum + right_sum will fail for [-2, 1] return max($left_sum + $right_sum, $left_sum, $right_sum); } // Returns sum of maximum sum // subarray in aa[l..h] function maxSubArraySum(&$arr, $l, $h) { // Base Case: Only one element if ($l == $h) return $arr[$l]; // Find middle point $m = intval(($l + $h) / 2); /* Return maximum of following three possible cases a) Maximum subarray sum in left half b) Maximum subarray sum in right half c) Maximum subarray sum such that the subarray crosses the midpoint */ return max(maxSubArraySum($arr, $l, $m), maxSubArraySum($arr, $m + 1, $h), maxCrossingSum($arr, $l, $m, $h)); } // Driver Code $arr = array(2, 3, 4, 5, 7); $n = count($arr); $max_sum = maxSubArraySum($arr, 0, $n - 1); echo \"Maximum contiguous sum is \" . $max_sum; // This code is contributed by rathbhupendra, Aadil ?> ", "e": 11400, "s": 9731, "text": null }, { "code": "<script> // A Divide and Conquer based program for maximum subarray // sum problem // A utility function to find maximum of two integers function max(a,b) { return (a > b) ? a : b; } // A utility function to find maximum of three integers function max(a,b,c) { return Math.max(Math.max(a, b), c); } // Find the maximum possible sum in arr[] auch that arr[m] // is part of it function maxCrossingSum(arr, l, m,h) { // Include elements on left of mid. let sum = 0; let left_sum = Number.MIN_VALUE; for (let i = m; i >= l; i--) { sum = sum + arr[i]; if (sum > left_sum) left_sum = sum; } // Include elements on right of mid sum = 0; let right_sum = Number.MIN_VALUE; for (let i = m + 1; i <= h; i++) { sum = sum + arr[i]; if (sum > right_sum) right_sum = sum; } // Return sum of elements on left and right of mid // returning only left_sum + right_sum will fail for // [-2, 1] return max(left_sum + right_sum, left_sum, right_sum); } // Returns sum of maximum sum subarray in aa[l..h] function maxSubArraySum(arr, l,h) { // Base Case: Only one element if (l == h) return arr[l]; // Find middle point let m = parseInt((l + h) / 2, 10); /* Return maximum of following three possible cases a) Maximum subarray sum in left half b) Maximum subarray sum in right half c) Maximum subarray sum such that the subarray crosses the midpoint */ return max(maxSubArraySum(arr, l, m), maxSubArraySum(arr, m + 1, h), maxCrossingSum(arr, l, m, h)); } let arr = [ 2, 3, 4, 5, 7 ]; let n = arr.length; let max_sum = maxSubArraySum(arr, 0, n - 1); document.write(\"Maximum contiguous sum is \" + max_sum); // This code is contributed by vaibhavrabadiya117. </script>", "e": 13435, "s": 11400, "text": null }, { "code": null, "e": 13465, "s": 13435, "text": "Maximum contiguous sum is 21n" }, { "code": null, "e": 13615, "s": 13465, "text": "Time Complexity: maxSubArraySum() is a recursive method and time complexity can be expressed as following recurrence relation. T(n) = 2T(n/2) + Θ(n) " }, { "code": null, "e": 13642, "s": 13615, "text": "Time Complexity : O(nlogn)" }, { "code": null, "e": 13864, "s": 13642, "text": "Auxiliary Space: O(1).The above recurrence is similar to Merge Sort and can be solved either using Recurrence Tree method or Master method. It falls in case II of Master Method and solution of the recurrence is Θ(nLogn). " }, { "code": null, "e": 14212, "s": 13864, "text": "The Kadane’s Algorithm for this problem takes O(n) time. Therefore the Kadane’s algorithm is better than the Divide and Conquer approach, but this problem can be considered as a good example to show power of Divide and Conquer. The above simple approach where we divide the array in two halves, reduces the time complexity from O(n^2) to O(nLogn)." }, { "code": null, "e": 14446, "s": 14212, "text": "References: Introduction to Algorithms by Clifford Stein, Thomas H. Cormen, Charles E. Leiserson, Ronald L. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 14460, "s": 14446, "text": "rathbhupendra" }, { "code": null, "e": 14474, "s": 14460, "text": "MohammedAadil" }, { "code": null, "e": 14490, "s": 14474, "text": "mayanktyagi1709" }, { "code": null, "e": 14509, "s": 14490, "text": "vaibhavrabadiya117" }, { "code": null, "e": 14519, "s": 14509, "text": "ankitayan" }, { "code": null, "e": 14538, "s": 14519, "text": "surindertarika1234" }, { "code": null, "e": 14547, "s": 14538, "text": "gabaa406" }, { "code": null, "e": 14560, "s": 14547, "text": "dspartho1998" }, { "code": null, "e": 14571, "s": 14560, "text": "arpita4086" }, { "code": null, "e": 14576, "s": 14571, "text": "srm_" }, { "code": null, "e": 14597, "s": 14576, "text": "anandkumarshivam2266" }, { "code": null, "e": 14613, "s": 14597, "text": "resonance443731" }, { "code": null, "e": 14620, "s": 14613, "text": "Amazon" }, { "code": null, "e": 14634, "s": 14620, "text": "Junglee Games" }, { "code": null, "e": 14643, "s": 14634, "text": "subarray" }, { "code": null, "e": 14656, "s": 14643, "text": "subarray-sum" }, { "code": null, "e": 14663, "s": 14656, "text": "Arrays" }, { "code": null, "e": 14682, "s": 14663, "text": "Divide and Conquer" }, { "code": null, "e": 14702, "s": 14682, "text": "Dynamic Programming" }, { "code": null, "e": 14709, "s": 14702, "text": "Amazon" }, { "code": null, "e": 14723, "s": 14709, "text": "Junglee Games" }, { "code": null, "e": 14730, "s": 14723, "text": "Arrays" }, { "code": null, "e": 14750, "s": 14730, "text": "Dynamic Programming" }, { "code": null, "e": 14769, "s": 14750, "text": "Divide and Conquer" } ]
Program to find the number of days between two dates in PHP
03 Dec, 2021 In this article, we will see how to get the date difference in the number of days in PHP, along with will also understand the various ways to get the total count of difference in 2 dates & see their implementation through the examples. We have given two dates & our task is to find the number of days between these given dates. For this, we will be following the below 2 methods: Using strtotime() Function Using date_diff() Function Consider the following example: Input : date1 = "2-05-2017" date2 = "25-12-2017" Output: Difference between two dates: 237 Days Explanation: Calculating the total number of days between the start & end date. Note: The dates can be taken in any format. In the above example, the date is taken in dd-mm-yyyy format. Method 1: Using strtotime() Function This is a built-in function in PHP that is used to convert an English textual date-time description to a UNIX timestamp. The function accepts a string parameter in English which represents the description of date-time. For e.g., “now” refers to the current date in the English date-time description. The function returns the time in seconds since the Unix Epoch Example 1: In this example, we have taken two dates and calculated their differences. PHP <?php // Function to find the difference // between two dates. function dateDiffInDays($date1, $date2) { // Calculating the difference in timestamps $diff = strtotime($date2) - strtotime($date1); // 1 day = 24 hours // 24 * 60 * 60 = 86400 seconds return abs(round($diff / 86400)); } // Start date $date1 = "17-09-2018"; // End date $date2 = "31-09-2018"; // Function call to find date difference $dateDiff = dateDiffInDays($date1, $date2); // Display the result printf("Difference between two dates: " . $dateDiff . " Days ");?> Difference between two dates: 14 Days Method 2: Using date_diff() Function The date_diff() function is an inbuilt function in PHP that is used to calculate the difference between two dates. This function returns a DateInterval object on the success and returns FALSE on failure. Example: This example describes calculating the number of days between the 2 dates in PHP. PHP <?php // Creates DateTime objects $datetime1 = date_create('17-09-2018'); $datetime2 = date_create('25-09-2018'); // Calculates the difference between DateTime objects $interval = date_diff($datetime1, $datetime2); // Display the result echo $interval->format('Difference between two dates: %R%a days');?> Difference between two dates: +8 days PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples. nidhi_biet bhaskargeeksforgeeks PHP-function PHP-Questions Picked PHP Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n03 Dec, 2021" }, { "code": null, "e": 432, "s": 52, "text": "In this article, we will see how to get the date difference in the number of days in PHP, along with will also understand the various ways to get the total count of difference in 2 dates & see their implementation through the examples. We have given two dates & our task is to find the number of days between these given dates. For this, we will be following the below 2 methods:" }, { "code": null, "e": 459, "s": 432, "text": "Using strtotime() Function" }, { "code": null, "e": 486, "s": 459, "text": "Using date_diff() Function" }, { "code": null, "e": 518, "s": 486, "text": "Consider the following example:" }, { "code": null, "e": 702, "s": 518, "text": "Input : date1 = \"2-05-2017\"\n date2 = \"25-12-2017\"\nOutput: Difference between two dates: 237 Days\nExplanation: Calculating the total number of days between the start & end date." }, { "code": null, "e": 808, "s": 702, "text": "Note: The dates can be taken in any format. In the above example, the date is taken in dd-mm-yyyy format." }, { "code": null, "e": 845, "s": 808, "text": "Method 1: Using strtotime() Function" }, { "code": null, "e": 1207, "s": 845, "text": "This is a built-in function in PHP that is used to convert an English textual date-time description to a UNIX timestamp. The function accepts a string parameter in English which represents the description of date-time. For e.g., “now” refers to the current date in the English date-time description. The function returns the time in seconds since the Unix Epoch" }, { "code": null, "e": 1293, "s": 1207, "text": "Example 1: In this example, we have taken two dates and calculated their differences." }, { "code": null, "e": 1297, "s": 1293, "text": "PHP" }, { "code": "<?php // Function to find the difference // between two dates. function dateDiffInDays($date1, $date2) { // Calculating the difference in timestamps $diff = strtotime($date2) - strtotime($date1); // 1 day = 24 hours // 24 * 60 * 60 = 86400 seconds return abs(round($diff / 86400)); } // Start date $date1 = \"17-09-2018\"; // End date $date2 = \"31-09-2018\"; // Function call to find date difference $dateDiff = dateDiffInDays($date1, $date2); // Display the result printf(\"Difference between two dates: \" . $dateDiff . \" Days \");?>", "e": 1883, "s": 1297, "text": null }, { "code": null, "e": 1921, "s": 1883, "text": "Difference between two dates: 14 Days" }, { "code": null, "e": 1960, "s": 1923, "text": "Method 2: Using date_diff() Function" }, { "code": null, "e": 2164, "s": 1960, "text": "The date_diff() function is an inbuilt function in PHP that is used to calculate the difference between two dates. This function returns a DateInterval object on the success and returns FALSE on failure." }, { "code": null, "e": 2255, "s": 2164, "text": "Example: This example describes calculating the number of days between the 2 dates in PHP." }, { "code": null, "e": 2259, "s": 2255, "text": "PHP" }, { "code": "<?php // Creates DateTime objects $datetime1 = date_create('17-09-2018'); $datetime2 = date_create('25-09-2018'); // Calculates the difference between DateTime objects $interval = date_diff($datetime1, $datetime2); // Display the result echo $interval->format('Difference between two dates: %R%a days');?>", "e": 2578, "s": 2259, "text": null }, { "code": null, "e": 2616, "s": 2578, "text": "Difference between two dates: +8 days" }, { "code": null, "e": 2787, "s": 2618, "text": "PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples." }, { "code": null, "e": 2798, "s": 2787, "text": "nidhi_biet" }, { "code": null, "e": 2819, "s": 2798, "text": "bhaskargeeksforgeeks" }, { "code": null, "e": 2832, "s": 2819, "text": "PHP-function" }, { "code": null, "e": 2846, "s": 2832, "text": "PHP-Questions" }, { "code": null, "e": 2853, "s": 2846, "text": "Picked" }, { "code": null, "e": 2857, "s": 2853, "text": "PHP" }, { "code": null, "e": 2874, "s": 2857, "text": "Web Technologies" }, { "code": null, "e": 2878, "s": 2874, "text": "PHP" } ]
make_heap() in C++ STL
13 Jun, 2020 make_heap() is used to transform a sequence into a heap. A heap is a data structure which points to highest( or lowest) element and making its access in O(1) time. Order of all the other elements depends upon particular implementation, but remains consistent throughout. This function is defined in the header “algorithm“. There are two implementations of make_heap() function. Both of them are explained through this article.Syntax 1 : make_heap(iter_first, iter_last) Template :void make_heap (RandomAccessIterator first, RandomAccessIterator last);Parameters :first : The pointer to the starting element of sequence that has tobe transformed into heap.last : The pointer to the next address to last element of sequence thathas to be transformed into heap. Below is the demonstrating code : // C++ code to demonstrate the working of // make_heap() using syntax 1 #include<iostream>#include<algorithm> // for heap #include<vector>using namespace std; int main(){ // initializing vector; vector<int> vi = { 4, 6, 7, 9, 11, 4 }; // using make_heap() to transform vector into // a max heap make_heap(vi.begin(),vi.end()); //checking if heap using // front() function cout << "The maximum element of heap is : "; cout << vi.front() << endl; } Output: The maximum element of heap is : 11 Syntax 2 : make_heap(iter_first, iter_last, comp) Template :void make_heap (RandomAccessIterator first, RandomAccessIterator last, comp);Parameters :first : The pointer to the starting element of sequence that has to be transformed into heap.last : The pointer to the next address to last element of sequence that has to be transformed into heap.comp : The comparator function that returns a boolean true/false of the each elements compared. This function accepts two arguments. This can be function pointer or function object and cannot change values. Below is the demonstrating code : // C++ code to demonstrate the working of // make_heap() using syntax 2 #include<iostream> #include<algorithm> // for heap #include<vector> using namespace std; // comparator function to make min heap struct greaters{ bool operator()(const long& a,const long& b) const{ return a>b; } }; int main() { // initializing vector; vector<int> vi = { 15, 6, 7, 9, 11, 45 }; // using make_heap() to transform vector into // a min heap make_heap(vi.begin(),vi.end(), greaters()); // checking if heap using // front() function cout << "The minimum element of heap is : "; cout << vi.front() << endl; } Output: The minimum element of heap is : 6 Possible application : This function can be used in scheduling. In scheduling, a new element is inserted dynamically in iterations. Sorting again and again to get maximum takes much complexity O(nlogn), instead of that we use “push_heap()” function to heapify the heap made in O(logn) time . The code below depicts its implementation. // C++ code to demonstrate // application of make_heap() (max_heap)// priority scheduling #include<iostream>#include<algorithm> // for heap #include<vector>using namespace std; int main(){ // initializing vector; // initial job priorities vector<int> vi = { 15, 6, 7, 9, 11, 19}; // No. of incoming jobs. int k = 3; // using make_heap() to transform vector into // a min heap make_heap(vi.begin(),vi.end()); // initializing job variable int a = 10; for ( int i=0; i<k; i++) { // push a job with priority level vi.push_back(a); // transform into heap ( using push_heap() ) push_heap(vi.begin(), vi.end()); //checking top priority job // front() function cout << "Job with maximum priority is : "; cout << vi.front() << endl; // increasing job priority level a = a + 10; } } Output: Job with maximum priority is : 19 Job with maximum priority is : 20 Job with maximum priority is : 30 This article is contributed by Manjeet 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 [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. shubham_singh BhavitJain STL C++ Heap Heap STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Sorting a vector in C++ Polymorphism in C++ std::string class in C++ Friend class and function in C++ Pair in C++ Standard Template Library (STL) HeapSort K'th Smallest/Largest Element in Unsorted Array | Set 1 Binary Heap Introduction to Data Structures Huffman Coding | Greedy Algo-3
[ { "code": null, "e": 54, "s": 26, "text": "\n13 Jun, 2020" }, { "code": null, "e": 524, "s": 54, "text": "make_heap() is used to transform a sequence into a heap. A heap is a data structure which points to highest( or lowest) element and making its access in O(1) time. Order of all the other elements depends upon particular implementation, but remains consistent throughout. This function is defined in the header “algorithm“. There are two implementations of make_heap() function. Both of them are explained through this article.Syntax 1 : make_heap(iter_first, iter_last)" }, { "code": null, "e": 813, "s": 524, "text": "Template :void make_heap (RandomAccessIterator first, RandomAccessIterator last);Parameters :first : The pointer to the starting element of sequence that has tobe transformed into heap.last : The pointer to the next address to last element of sequence thathas to be transformed into heap." }, { "code": null, "e": 847, "s": 813, "text": "Below is the demonstrating code :" }, { "code": "// C++ code to demonstrate the working of // make_heap() using syntax 1 #include<iostream>#include<algorithm> // for heap #include<vector>using namespace std; int main(){ // initializing vector; vector<int> vi = { 4, 6, 7, 9, 11, 4 }; // using make_heap() to transform vector into // a max heap make_heap(vi.begin(),vi.end()); //checking if heap using // front() function cout << \"The maximum element of heap is : \"; cout << vi.front() << endl; }", "e": 1341, "s": 847, "text": null }, { "code": null, "e": 1349, "s": 1341, "text": "Output:" }, { "code": null, "e": 1386, "s": 1349, "text": "The maximum element of heap is : 11\n" }, { "code": null, "e": 1436, "s": 1386, "text": "Syntax 2 : make_heap(iter_first, iter_last, comp)" }, { "code": null, "e": 1939, "s": 1436, "text": "Template :void make_heap (RandomAccessIterator first, RandomAccessIterator last, comp);Parameters :first : The pointer to the starting element of sequence that has to be transformed into heap.last : The pointer to the next address to last element of sequence that has to be transformed into heap.comp : The comparator function that returns a boolean true/false of the each elements compared. This function accepts two arguments. This can be function pointer or function object and cannot change values." }, { "code": null, "e": 1973, "s": 1939, "text": "Below is the demonstrating code :" }, { "code": "// C++ code to demonstrate the working of // make_heap() using syntax 2 #include<iostream> #include<algorithm> // for heap #include<vector> using namespace std; // comparator function to make min heap struct greaters{ bool operator()(const long& a,const long& b) const{ return a>b; } }; int main() { // initializing vector; vector<int> vi = { 15, 6, 7, 9, 11, 45 }; // using make_heap() to transform vector into // a min heap make_heap(vi.begin(),vi.end(), greaters()); // checking if heap using // front() function cout << \"The minimum element of heap is : \"; cout << vi.front() << endl; } ", "e": 2629, "s": 1973, "text": null }, { "code": null, "e": 2637, "s": 2629, "text": "Output:" }, { "code": null, "e": 2673, "s": 2637, "text": "The minimum element of heap is : 6\n" }, { "code": null, "e": 3008, "s": 2673, "text": "Possible application : This function can be used in scheduling. In scheduling, a new element is inserted dynamically in iterations. Sorting again and again to get maximum takes much complexity O(nlogn), instead of that we use “push_heap()” function to heapify the heap made in O(logn) time . The code below depicts its implementation." }, { "code": "// C++ code to demonstrate // application of make_heap() (max_heap)// priority scheduling #include<iostream>#include<algorithm> // for heap #include<vector>using namespace std; int main(){ // initializing vector; // initial job priorities vector<int> vi = { 15, 6, 7, 9, 11, 19}; // No. of incoming jobs. int k = 3; // using make_heap() to transform vector into // a min heap make_heap(vi.begin(),vi.end()); // initializing job variable int a = 10; for ( int i=0; i<k; i++) { // push a job with priority level vi.push_back(a); // transform into heap ( using push_heap() ) push_heap(vi.begin(), vi.end()); //checking top priority job // front() function cout << \"Job with maximum priority is : \"; cout << vi.front() << endl; // increasing job priority level a = a + 10; } }", "e": 3913, "s": 3008, "text": null }, { "code": null, "e": 3921, "s": 3913, "text": "Output:" }, { "code": null, "e": 4024, "s": 3921, "text": "Job with maximum priority is : 19\nJob with maximum priority is : 20\nJob with maximum priority is : 30\n" }, { "code": null, "e": 4325, "s": 4024, "text": "This article is contributed by Manjeet 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 [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 4450, "s": 4325, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 4464, "s": 4450, "text": "shubham_singh" }, { "code": null, "e": 4475, "s": 4464, "text": "BhavitJain" }, { "code": null, "e": 4479, "s": 4475, "text": "STL" }, { "code": null, "e": 4483, "s": 4479, "text": "C++" }, { "code": null, "e": 4488, "s": 4483, "text": "Heap" }, { "code": null, "e": 4493, "s": 4488, "text": "Heap" }, { "code": null, "e": 4497, "s": 4493, "text": "STL" }, { "code": null, "e": 4501, "s": 4497, "text": "CPP" }, { "code": null, "e": 4599, "s": 4501, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4623, "s": 4599, "text": "Sorting a vector in C++" }, { "code": null, "e": 4643, "s": 4623, "text": "Polymorphism in C++" }, { "code": null, "e": 4668, "s": 4643, "text": "std::string class in C++" }, { "code": null, "e": 4701, "s": 4668, "text": "Friend class and function in C++" }, { "code": null, "e": 4745, "s": 4701, "text": "Pair in C++ Standard Template Library (STL)" }, { "code": null, "e": 4754, "s": 4745, "text": "HeapSort" }, { "code": null, "e": 4810, "s": 4754, "text": "K'th Smallest/Largest Element in Unsorted Array | Set 1" }, { "code": null, "e": 4822, "s": 4810, "text": "Binary Heap" }, { "code": null, "e": 4854, "s": 4822, "text": "Introduction to Data Structures" } ]
What is EventEmitter in Node.js ?
28 Oct, 2021 EventEmitter is a class in node.js that is responsible for handling the events created using the ‘events’ module in node.js. Events are created to make custom operations while a set of operations is performed. EventEmitter can return two properties namely newListener if we want to create a new event listener and removeListener when we want to remove existing event listeners. Both of these mentioned properties emit an event whenever called to perform the operation. In order to perform operations on EventEmitter, we need to create a reference using the ‘events’ module and then we need to initialize an instance of the EventEmitter so that we can use it further. Syntax: // Creating a constant reference of EventEmitter const EventEmittter = require('events'); // Initializing instance of EventEmitter var emitter = new EventEmitter(); Creating a listening event using addListener: Before we emit an event we have to create a listener who will listen to the callbacks emitted, then the listener will proceed with the further actions that are required to comply with the event. We can create an event listener with the help of the addListener property of EventEmitter. The addListener appends the event to the end of the array so we can call it multiple times to call multiple instances of the event and is very useful as we don’t require to write an event multiple times. Syntax: emitter.addListener(eventName, listener); Emitting event: As every event is a named event in node.js we can trigger an event by using the emit method and we can pass arbitrary arguments to listen in the event. Syntax: emitter.emit(eventName, arg1,arg2,...) Example: Code for creating an EventEmitter and adding events using addListener method. Javascript // Importing the events moduleconst EventEmitter = require('events'); // Initializing instance of EventEmitter to be usedvar emitter = new EventEmitter(); // Adding listener to the eventemitter.addListener('welcomeEvent', (name) => { console.log("welcome " + name);}); // Emitting the welcomeEventemitter.emit('myEvent', "Geek"); Output: welcome Geek Removing an instance of an event: We can remove an event using two methods removeListener if we want to remove a specific listener from the event or removeAllListeners if we want to remove an instance of all listeners from an event. Syntax: // For removing any single listener form the event emitter.removeListener(eventName, listener) // For removing all listeners of the event emitter.removeAllListeners(eventName) Example: Code for removing the event listener of an event. Javascript // Importing the events moduleconst EventEmitter = require('events'); // Initializing instance of EventEmitter to be usedvar emitter = new EventEmitter(); // Creating events var robot1 = (msg) => { console.log("Message from person1: " + msg);}; var person2 = (msg) => { console.log("Message from person2: " + msg);}; // Registering person1 and person2 with the printEventemitter.addListener('printEvent', person1);emitter.addListener('printEvent', person2); // Triggering the created eventemitter.emit('printEvent', "Event occurred"); // Removing all the listeners associated with the eventemitter.removeAllListeners('printEvent'); // Triggering the event again but no output// as all listeners are removedemitter.emit('printEvent', "Event occurred"); Output: Message from person1: Event occurred Message from person2: Event occurred As you can see in the above output event was triggered twice but the output came only once as we deleted the event listeners so no listeners were present while emitting the event a second time. surinderdawra388 NodeJS-Questions Picked Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Oct, 2021" }, { "code": null, "e": 497, "s": 28, "text": "EventEmitter is a class in node.js that is responsible for handling the events created using the ‘events’ module in node.js. Events are created to make custom operations while a set of operations is performed. EventEmitter can return two properties namely newListener if we want to create a new event listener and removeListener when we want to remove existing event listeners. Both of these mentioned properties emit an event whenever called to perform the operation." }, { "code": null, "e": 695, "s": 497, "text": "In order to perform operations on EventEmitter, we need to create a reference using the ‘events’ module and then we need to initialize an instance of the EventEmitter so that we can use it further." }, { "code": null, "e": 703, "s": 695, "text": "Syntax:" }, { "code": null, "e": 869, "s": 703, "text": "// Creating a constant reference of EventEmitter\nconst EventEmittter = require('events');\n\n// Initializing instance of EventEmitter\nvar emitter = new EventEmitter();" }, { "code": null, "e": 1406, "s": 869, "text": "Creating a listening event using addListener: Before we emit an event we have to create a listener who will listen to the callbacks emitted, then the listener will proceed with the further actions that are required to comply with the event. We can create an event listener with the help of the addListener property of EventEmitter. The addListener appends the event to the end of the array so we can call it multiple times to call multiple instances of the event and is very useful as we don’t require to write an event multiple times. " }, { "code": null, "e": 1414, "s": 1406, "text": "Syntax:" }, { "code": null, "e": 1456, "s": 1414, "text": "emitter.addListener(eventName, listener);" }, { "code": null, "e": 1624, "s": 1456, "text": "Emitting event: As every event is a named event in node.js we can trigger an event by using the emit method and we can pass arbitrary arguments to listen in the event." }, { "code": null, "e": 1632, "s": 1624, "text": "Syntax:" }, { "code": null, "e": 1671, "s": 1632, "text": "emitter.emit(eventName, arg1,arg2,...)" }, { "code": null, "e": 1758, "s": 1671, "text": "Example: Code for creating an EventEmitter and adding events using addListener method." }, { "code": null, "e": 1769, "s": 1758, "text": "Javascript" }, { "code": "// Importing the events moduleconst EventEmitter = require('events'); // Initializing instance of EventEmitter to be usedvar emitter = new EventEmitter(); // Adding listener to the eventemitter.addListener('welcomeEvent', (name) => { console.log(\"welcome \" + name);}); // Emitting the welcomeEventemitter.emit('myEvent', \"Geek\");", "e": 2108, "s": 1769, "text": null }, { "code": null, "e": 2116, "s": 2108, "text": "Output:" }, { "code": null, "e": 2129, "s": 2116, "text": "welcome Geek" }, { "code": null, "e": 2362, "s": 2129, "text": "Removing an instance of an event: We can remove an event using two methods removeListener if we want to remove a specific listener from the event or removeAllListeners if we want to remove an instance of all listeners from an event." }, { "code": null, "e": 2370, "s": 2362, "text": "Syntax:" }, { "code": null, "e": 2547, "s": 2370, "text": "// For removing any single listener form the event\nemitter.removeListener(eventName, listener)\n\n// For removing all listeners of the event\nemitter.removeAllListeners(eventName)" }, { "code": null, "e": 2606, "s": 2547, "text": "Example: Code for removing the event listener of an event." }, { "code": null, "e": 2617, "s": 2606, "text": "Javascript" }, { "code": "// Importing the events moduleconst EventEmitter = require('events'); // Initializing instance of EventEmitter to be usedvar emitter = new EventEmitter(); // Creating events var robot1 = (msg) => { console.log(\"Message from person1: \" + msg);}; var person2 = (msg) => { console.log(\"Message from person2: \" + msg);}; // Registering person1 and person2 with the printEventemitter.addListener('printEvent', person1);emitter.addListener('printEvent', person2); // Triggering the created eventemitter.emit('printEvent', \"Event occurred\"); // Removing all the listeners associated with the eventemitter.removeAllListeners('printEvent'); // Triggering the event again but no output// as all listeners are removedemitter.emit('printEvent', \"Event occurred\");", "e": 3392, "s": 2617, "text": null }, { "code": null, "e": 3400, "s": 3392, "text": "Output:" }, { "code": null, "e": 3474, "s": 3400, "text": "Message from person1: Event occurred\nMessage from person2: Event occurred" }, { "code": null, "e": 3669, "s": 3474, "text": "As you can see in the above output event was triggered twice but the output came only once as we deleted the event listeners so no listeners were present while emitting the event a second time. " }, { "code": null, "e": 3686, "s": 3669, "text": "surinderdawra388" }, { "code": null, "e": 3703, "s": 3686, "text": "NodeJS-Questions" }, { "code": null, "e": 3710, "s": 3703, "text": "Picked" }, { "code": null, "e": 3718, "s": 3710, "text": "Node.js" }, { "code": null, "e": 3735, "s": 3718, "text": "Web Technologies" } ]
Pretty-Printing in BeautifulSoup
25 Feb, 2021 Prerequisite: requests BeautifulSoup In this article, we will learn about how to print pretty in BeautifulSoup Using Python. The requests library is an integral part of Python for making HTTP requests to a specified URL. Whether it be REST APIs or Web Scrapping, requests are must be learned for proceeding further with these technologies. When one makes a request to a URI, it returns a response. Python requests provide inbuilt functionalities for managing both the request and response. pip install requests Beautiful Soup is a Python library designed for quick turnaround projects like screen-scraping. pip install beautifulsoup4 In simple words we can say, It prettifies the HTML with proper indents and everything. Let’s Understand Step by step implementation:- Import Required Module Python3 # Import Required Moduleimport requestsfrom bs4 import BeautifulSoup Parse HTML Content Python3 # Web URLWeb_url = "Enter WEB URL" # Get URL Contentr = requests.get(Web_url) # Parse HTML Codesoup = BeautifulSoup(r.content, 'html.parser') Pretty the HTML Code. BeautifulSoup has a prettify() method. The prettify() method will turn a Beautiful Soup parse tree into a nicely formatted Unicode string, with a separate line for each tag and each string: Python3 print(soup.prettify()) Below is the implementation: Python3 # Import Required Moduleimport requestsfrom bs4 import BeautifulSoup # Web URLWeb_url = "https://www.geeksforgeeks.org/transparent-window-in-tkinter/" # Get URL Contentr = requests.get(Web_url) # Parse HTML Codesoup = BeautifulSoup(r.content, 'html.parser')print(soup.prettify()) Output: Picked Python BeautifulSoup Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON Python | os.path.join() method How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | datetime.timedelta() function Python | Get unique values from a list
[ { "code": null, "e": 28, "s": 0, "text": "\n25 Feb, 2021" }, { "code": null, "e": 42, "s": 28, "text": "Prerequisite:" }, { "code": null, "e": 51, "s": 42, "text": "requests" }, { "code": null, "e": 65, "s": 51, "text": "BeautifulSoup" }, { "code": null, "e": 518, "s": 65, "text": "In this article, we will learn about how to print pretty in BeautifulSoup Using Python. The requests library is an integral part of Python for making HTTP requests to a specified URL. Whether it be REST APIs or Web Scrapping, requests are must be learned for proceeding further with these technologies. When one makes a request to a URI, it returns a response. Python requests provide inbuilt functionalities for managing both the request and response." }, { "code": null, "e": 539, "s": 518, "text": "pip install requests" }, { "code": null, "e": 635, "s": 539, "text": "Beautiful Soup is a Python library designed for quick turnaround projects like screen-scraping." }, { "code": null, "e": 662, "s": 635, "text": "pip install beautifulsoup4" }, { "code": null, "e": 749, "s": 662, "text": "In simple words we can say, It prettifies the HTML with proper indents and everything." }, { "code": null, "e": 796, "s": 749, "text": "Let’s Understand Step by step implementation:-" }, { "code": null, "e": 819, "s": 796, "text": "Import Required Module" }, { "code": null, "e": 827, "s": 819, "text": "Python3" }, { "code": "# Import Required Moduleimport requestsfrom bs4 import BeautifulSoup", "e": 896, "s": 827, "text": null }, { "code": null, "e": 915, "s": 896, "text": "Parse HTML Content" }, { "code": null, "e": 923, "s": 915, "text": "Python3" }, { "code": "# Web URLWeb_url = \"Enter WEB URL\" # Get URL Contentr = requests.get(Web_url) # Parse HTML Codesoup = BeautifulSoup(r.content, 'html.parser')", "e": 1067, "s": 923, "text": null }, { "code": null, "e": 1128, "s": 1067, "text": "Pretty the HTML Code. BeautifulSoup has a prettify() method." }, { "code": null, "e": 1279, "s": 1128, "text": "The prettify() method will turn a Beautiful Soup parse tree into a nicely formatted Unicode string, with a separate line for each tag and each string:" }, { "code": null, "e": 1287, "s": 1279, "text": "Python3" }, { "code": "print(soup.prettify())", "e": 1310, "s": 1287, "text": null }, { "code": null, "e": 1339, "s": 1310, "text": "Below is the implementation:" }, { "code": null, "e": 1347, "s": 1339, "text": "Python3" }, { "code": "# Import Required Moduleimport requestsfrom bs4 import BeautifulSoup # Web URLWeb_url = \"https://www.geeksforgeeks.org/transparent-window-in-tkinter/\" # Get URL Contentr = requests.get(Web_url) # Parse HTML Codesoup = BeautifulSoup(r.content, 'html.parser')print(soup.prettify())", "e": 1630, "s": 1347, "text": null }, { "code": null, "e": 1638, "s": 1630, "text": "Output:" }, { "code": null, "e": 1645, "s": 1638, "text": "Picked" }, { "code": null, "e": 1666, "s": 1645, "text": "Python BeautifulSoup" }, { "code": null, "e": 1673, "s": 1666, "text": "Python" }, { "code": null, "e": 1771, "s": 1673, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1803, "s": 1771, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1830, "s": 1803, "text": "Python Classes and Objects" }, { "code": null, "e": 1851, "s": 1830, "text": "Python OOPs Concepts" }, { "code": null, "e": 1874, "s": 1851, "text": "Introduction To PYTHON" }, { "code": null, "e": 1905, "s": 1874, "text": "Python | os.path.join() method" }, { "code": null, "e": 1961, "s": 1905, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 2003, "s": 1961, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 2045, "s": 2003, "text": "Check if element exists in list in Python" }, { "code": null, "e": 2084, "s": 2045, "text": "Python | datetime.timedelta() function" } ]
Place Value of a given digit in a number
03 May, 2022 Place value can be defined as the value represented by a digit in a number on the basis of its position in the number. Here is the illustration of place value with an example: Let’s take another example to illustrate the place value for N = 45876 Problem: Given a positive integer N and a digit D. The task is to find out the place value of a digit D in the given number N. If multiple occurrences of digit occur then find the minimum place value.Example: Input: N = 3928, D = 3 Output: 3000 Explanation: Place value of 3 in this number is 3*1000 = 3000Input: N = 67849, D = 6 Output: 60000 Solution Approach: Find the position of the digit from the right side of the input number. In order to find the position take the mod of that number by 10 and check for the number and divide the number by 10.When the position of the digit is found then just multiply the digit with the 10 position. Find the position of the digit from the right side of the input number. In order to find the position take the mod of that number by 10 and check for the number and divide the number by 10. When the position of the digit is found then just multiply the digit with the 10 position. Here is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation to find// place value of a number#include<bits/stdc++.h>using namespace std; // Function to find place valueint placeValue(int N, int num){ int total = 1, value = 0, rem = 0; while (true) { rem = N % 10; N = N / 10; if (rem == num) { value = total * rem; break; } total = total * 10; } return value;} // Driver Codeint main(){ // Digit, which we want // to find place value. int D = 5; // Number from where we // want to find place value. int N = 85932; cout << (placeValue(N, D));} // This code is contributed by Ritik Bansal // Java implementation to find// place value of a number import java.util.*;import java.io.*;import java.lang.*; class GFG { // function to find place value static int placeValue(int N, int num) { int total = 1, value = 0, rem = 0; while (true) { rem = N % 10; N = N / 10; if (rem == num) { value = total * rem; break; } total = total * 10; } return value; } // Driver Code public static void main(String[] args) { // Digit, which we want // to find place value. int D = 5; // Number from where we // want to find place value. int N = 85932; System.out.println(placeValue(N, D)); }} # Python3 implementation to find# place value of a number # Function to find place valuedef placeValue(N, num): total = 1 value = 0 rem = 0 while (True): rem = N % 10 N = N // 10 if (rem == num): value = total * rem break total = total * 10 return value # Driver Code # Digit, which we want# to find place value.D = 5 # Number from where we# want to find place value.N = 85932 print(placeValue(N, D)) # This code is contributed by divyamohan123 // C# implementation to find// place value of a numberusing System;class GFG{ // function to find place valuestatic int placeValue(int N, int num){ int total = 1, value = 0, rem = 0; while (true) { rem = N % 10; N = N / 10; if (rem == num) { value = total * rem; break; } total = total * 10; } return value;} // Driver Codepublic static void Main(){ // Digit, which we want // to find place value. int D = 5; // Number from where we // want to find place value. int N = 85932; Console.Write(placeValue(N, D));}} // This code is contributed by Code_Mech <script> // JavaScript implementation to find // place value of a number // Function to find place value function placeValue(N, num) { var total = 1, value = 0, rem = 0; while (true) { rem = N % 10; N = parseInt(N / 10); if (rem == num) { value = total * rem; break; } total = total * 10; } return value; } // Driver Code // Digit, which we want // to find place value. var D = 5; // Number from where we // want to find place value. var N = 85932; document.write(placeValue(N, D)); </script> 5000 Time Complexity: O(log N) Auxiliary space: O(1) divyamohan123 Code_Mech bansal_rtk_ rdtank avtarkumar719 number-digits Mathematical School Programming Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n03 May, 2022" }, { "code": null, "e": 205, "s": 28, "text": "Place value can be defined as the value represented by a digit in a number on the basis of its position in the number. Here is the illustration of place value with an example: " }, { "code": null, "e": 278, "s": 205, "text": "Let’s take another example to illustrate the place value for N = 45876 " }, { "code": null, "e": 488, "s": 278, "text": "Problem: Given a positive integer N and a digit D. The task is to find out the place value of a digit D in the given number N. If multiple occurrences of digit occur then find the minimum place value.Example: " }, { "code": null, "e": 625, "s": 488, "text": "Input: N = 3928, D = 3 Output: 3000 Explanation: Place value of 3 in this number is 3*1000 = 3000Input: N = 67849, D = 6 Output: 60000 " }, { "code": null, "e": 648, "s": 627, "text": "Solution Approach: " }, { "code": null, "e": 928, "s": 648, "text": "Find the position of the digit from the right side of the input number. In order to find the position take the mod of that number by 10 and check for the number and divide the number by 10.When the position of the digit is found then just multiply the digit with the 10 position." }, { "code": null, "e": 1118, "s": 928, "text": "Find the position of the digit from the right side of the input number. In order to find the position take the mod of that number by 10 and check for the number and divide the number by 10." }, { "code": null, "e": 1209, "s": 1118, "text": "When the position of the digit is found then just multiply the digit with the 10 position." }, { "code": null, "e": 1261, "s": 1209, "text": "Here is the implementation of the above approach: " }, { "code": null, "e": 1265, "s": 1261, "text": "C++" }, { "code": null, "e": 1270, "s": 1265, "text": "Java" }, { "code": null, "e": 1278, "s": 1270, "text": "Python3" }, { "code": null, "e": 1281, "s": 1278, "text": "C#" }, { "code": null, "e": 1292, "s": 1281, "text": "Javascript" }, { "code": "// C++ implementation to find// place value of a number#include<bits/stdc++.h>using namespace std; // Function to find place valueint placeValue(int N, int num){ int total = 1, value = 0, rem = 0; while (true) { rem = N % 10; N = N / 10; if (rem == num) { value = total * rem; break; } total = total * 10; } return value;} // Driver Codeint main(){ // Digit, which we want // to find place value. int D = 5; // Number from where we // want to find place value. int N = 85932; cout << (placeValue(N, D));} // This code is contributed by Ritik Bansal", "e": 1945, "s": 1292, "text": null }, { "code": "// Java implementation to find// place value of a number import java.util.*;import java.io.*;import java.lang.*; class GFG { // function to find place value static int placeValue(int N, int num) { int total = 1, value = 0, rem = 0; while (true) { rem = N % 10; N = N / 10; if (rem == num) { value = total * rem; break; } total = total * 10; } return value; } // Driver Code public static void main(String[] args) { // Digit, which we want // to find place value. int D = 5; // Number from where we // want to find place value. int N = 85932; System.out.println(placeValue(N, D)); }}", "e": 2721, "s": 1945, "text": null }, { "code": "# Python3 implementation to find# place value of a number # Function to find place valuedef placeValue(N, num): total = 1 value = 0 rem = 0 while (True): rem = N % 10 N = N // 10 if (rem == num): value = total * rem break total = total * 10 return value # Driver Code # Digit, which we want# to find place value.D = 5 # Number from where we# want to find place value.N = 85932 print(placeValue(N, D)) # This code is contributed by divyamohan123", "e": 3251, "s": 2721, "text": null }, { "code": "// C# implementation to find// place value of a numberusing System;class GFG{ // function to find place valuestatic int placeValue(int N, int num){ int total = 1, value = 0, rem = 0; while (true) { rem = N % 10; N = N / 10; if (rem == num) { value = total * rem; break; } total = total * 10; } return value;} // Driver Codepublic static void Main(){ // Digit, which we want // to find place value. int D = 5; // Number from where we // want to find place value. int N = 85932; Console.Write(placeValue(N, D));}} // This code is contributed by Code_Mech", "e": 3909, "s": 3251, "text": null }, { "code": "<script> // JavaScript implementation to find // place value of a number // Function to find place value function placeValue(N, num) { var total = 1, value = 0, rem = 0; while (true) { rem = N % 10; N = parseInt(N / 10); if (rem == num) { value = total * rem; break; } total = total * 10; } return value; } // Driver Code // Digit, which we want // to find place value. var D = 5; // Number from where we // want to find place value. var N = 85932; document.write(placeValue(N, D)); </script>", "e": 4592, "s": 3909, "text": null }, { "code": null, "e": 4597, "s": 4592, "text": "5000" }, { "code": null, "e": 4648, "s": 4599, "text": "Time Complexity: O(log N) Auxiliary space: O(1) " }, { "code": null, "e": 4662, "s": 4648, "text": "divyamohan123" }, { "code": null, "e": 4672, "s": 4662, "text": "Code_Mech" }, { "code": null, "e": 4684, "s": 4672, "text": "bansal_rtk_" }, { "code": null, "e": 4691, "s": 4684, "text": "rdtank" }, { "code": null, "e": 4705, "s": 4691, "text": "avtarkumar719" }, { "code": null, "e": 4719, "s": 4705, "text": "number-digits" }, { "code": null, "e": 4732, "s": 4719, "text": "Mathematical" }, { "code": null, "e": 4751, "s": 4732, "text": "School Programming" }, { "code": null, "e": 4764, "s": 4751, "text": "Mathematical" } ]
Bucket Sort To Sort an Array with Negative Numbers
10 Jun, 2022 We have discussed bucket sort in the main post on Bucket Sort . Bucket sort is mainly useful when input is uniformly distributed over a range. For example, consider the problem of sorting a large set of floating point numbers which are in range from 0.0 to 1.0 and are uniformly distributed across the range. In the above post, we have discussed Bucket Sort to sort numbers which are greater than zero. How to modify Bucket Sort to sort both positive and negative numbers? Example: Input : arr[] = { -0.897, 0.565, 0.656, -0.1234, 0, 0.3434 } Output : -0.897 -0.1234 0 0.3434 0.565 0.656 Here we considering number is in range -1.0 to 1.0 (floating point number) Algorithm : sortMixed(arr[], n) 1) Split array into two parts create two Empty vector Neg[], Pos[] (for negative and positive element respectively) Store all negative element in Neg[] by converting into positive (Neg[i] = -1 * Arr[i] ) Store all +ve in pos[] (pos[i] = Arr[i]) 2) Call function bucketSortPositive(Pos, pos.size()) Call function bucketSortPositive(Neg, Neg.size()) bucketSortPositive(arr[], n) 3) Create n empty buckets (Or lists). 4) Do following for every array element arr[i]. a) Insert arr[i] into bucket[n*array[i]] 5) Sort individual buckets using insertion sort. 6) Concatenate all sorted buckets. Below is implementation of above idea (for floating point number ) CPP Java Python3 C# // C++ program to sort an array of positive// and negative numbers using bucket sort#include <bits/stdc++.h>using namespace std; // Function to sort arr[] of size n using// bucket sortvoid bucketSort(vector<float> &arr, int n){ // 1) Create n empty buckets vector<float> b[n]; // 2) Put array elements in different // buckets for (int i=0; i<n; i++) { int bi = n*arr[i]; // Index in bucket b[bi].push_back(arr[i]); } // 3) Sort individual buckets for (int i=0; i<n; i++) sort(b[i].begin(), b[i].end()); // 4) Concatenate all buckets into arr[] int index = 0; arr.clear(); for (int i = 0; i < n; i++) for (int j = 0; j < b[i].size(); j++) arr.push_back(b[i][j]);} // This function mainly splits array into two// and then calls bucketSort() for two arrays.void sortMixed(float arr[], int n){ vector<float>Neg ; vector<float>Pos; // traverse array elements for (int i=0; i<n; i++) { if (arr[i] < 0) // store -Ve elements by // converting into +ve element Neg.push_back (-1 * arr[i]) ; else // store +ve elements Pos.push_back (arr[i]) ; } bucketSort(Neg, (int)Neg.size()); bucketSort(Pos, (int)Pos.size()); // First store elements of Neg[] array // by converting into -ve for (int i=0; i < Neg.size(); i++) arr[i] = -1 * Neg[ Neg.size() -1 - i]; // store +ve element for(int j=Neg.size(); j < n; j++) arr[j] = Pos[j - Neg.size()];} /* Driver program to test above function */int main(){ float arr[] = {-0.897, 0.565, 0.656, -0.1234, 0, 0.3434}; int n = sizeof(arr)/sizeof(arr[0]); sortMixed(arr, n); cout << "Sorted array is \n"; for (int i=0; i<n; i++) cout << arr[i] << " "; return 0;} // Java program to sort an array of positive// and negative numbers using bucket sortimport java.util.*;class GFG{ // Function to sort arr[] of size n using // bucket sort static void bucketSort(Vector<Double> arr, int n) { // 1) Create n empty buckets @SuppressWarnings("unchecked") Vector<Double> b[] = new Vector[n]; for (int i = 0; i < b.length; i++) b[i] = new Vector<Double>(); // 2) Put array elements in different // buckets for (int i = 0; i < n; i++) { int bi = (int)(n*arr.get(i)); // Index in bucket b[bi].add(arr.get(i)); } // 3) Sort individual buckets for (int i = 0; i < n; i++) Collections.sort(b[i]); // 4) Concatenate all buckets into arr[] int index = 0; arr.clear(); for (int i = 0; i < n; i++) for (int j = 0; j < b[i].size(); j++) arr.add(b[i].get(j)); } // This function mainly splits array into two // and then calls bucketSort() for two arrays. static void sortMixed(double arr[], int n) { Vector<Double>Neg = new Vector<>(); Vector<Double>Pos = new Vector<>(); // traverse array elements for (int i = 0; i < n; i++) { if (arr[i] < 0) // store -Ve elements by // converting into +ve element Neg.add (-1 * arr[i]) ; else // store +ve elements Pos.add (arr[i]) ; } bucketSort(Neg, (int)Neg.size()); bucketSort(Pos, (int)Pos.size()); // First store elements of Neg[] array // by converting into -ve for (int i = 0; i < Neg.size(); i++) arr[i] = -1 * Neg.get( Neg.size() -1 - i); // store +ve element for(int j = Neg.size(); j < n; j++) arr[j] = Pos.get(j - Neg.size()); } /* Driver program to test above function */ public static void main(String[] args) { double arr[] = {-0.897, 0.565, 0.656, -0.1234, 0, 0.3434}; int n = arr.length; sortMixed(arr, n); System.out.print("Sorted array is \n"); for (int i = 0; i < n; i++) System.out.print(arr[i] + " "); }} // This code is contributed by Rajput-Ji # Python3 program to sort an array of positive# and negative numbers using bucket sort # Function to sort arr[] of size n using# bucket sortdef bucketSort(arr, n): # 1) Create n empty buckets b = [] for i in range(n): b.append([]) # 2) Put array elements in different # buckets for i in range(n): bi = int(n*arr[i]) b[bi].append(arr[i]) # 3) Sort individual buckets for i in range(n): b[i].sort() # 4) Concatenate all buckets into arr[] index = 0 arr.clear() for i in range(n): for j in range(len(b[i])): arr.append(b[i][j]) # This function mainly splits array into two# and then calls bucketSort() for two arrays.def sortMixed(arr, n): Neg = [] Pos = [] # traverse array elements for i in range(n): if(arr[i]<0): # store -Ve elements by # converting into +ve element Neg.append(-1*arr[i]) else: # store +ve elements Pos.append(arr[i]) bucketSort(Neg,len(Neg)) bucketSort(Pos,len(Pos)) # First store elements of Neg[] array # by converting into -ve for i in range(len(Neg)): arr[i]=-1*Neg[len(Neg)-1-i] # store +ve element for i in range(len(Neg),n): arr[i]= Pos[i-len(Neg)] # Driver program to test above functionarr = [-0.897, 0.565, 0.656, -0.1234, 0, 0.3434]sortMixed(arr, len(arr))print("Sorted Array is")print(arr) # This code is contributed by Pushpesh raj // C# program to sort an array of positive// and negative numbers using bucket sortusing System;using System.Collections.Generic; public class GFG{ // Function to sort []arr of size n using // bucket sort static void bucketSort(List<Double> arr, int n) { // 1) Create n empty buckets List<Double> []b = new List<Double>[n]; for (int i = 0; i < b.Length; i++) b[i] = new List<Double>(); // 2) Put array elements in different // buckets for (int i = 0; i < n; i++) { int bi = (int)(n*arr[i]); // Index in bucket b[bi].Add(arr[i]); } // 3) Sort individual buckets for (int i = 0; i < n; i++) b[i].Sort(); // 4) Concatenate all buckets into []arr int index = 0; arr.Clear(); for (int i = 0; i < n; i++) for (int j = 0; j < b[i].Count; j++) arr.Add(b[i][j]); } // This function mainly splits array into two // and then calls bucketSort() for two arrays. static void sortMixed(double []arr, int n) { List<Double>Neg = new List<Double>(); List<Double>Pos = new List<Double>(); // traverse array elements for (int i = 0; i < n; i++) { if (arr[i] < 0) // store -Ve elements by // converting into +ve element Neg.Add (-1 * arr[i]) ; else // store +ve elements Pos.Add (arr[i]) ; } bucketSort(Neg, (int)Neg.Count); bucketSort(Pos, (int)Pos.Count); // First store elements of Neg[] array // by converting into -ve for (int i = 0; i < Neg.Count; i++) arr[i] = -1 * Neg[ Neg.Count -1 - i]; // store +ve element for(int j = Neg.Count; j < n; j++) arr[j] = Pos[j - Neg.Count]; } /* Driver program to test above function */ public static void Main(String[] args) { double []arr = {-0.897, 0.565, 0.656, -0.1234, 0, 0.3434}; int n = arr.Length; sortMixed(arr, n); Console.Write("Sorted array is \n"); for (int i = 0; i < n; i++) Console.Write(arr[i] + " "); }} // This code is contributed by Rajput-Ji Output: Sorted array is -0.897 -0.1234 0 0.3434 0.565 0.656 This article is contributed by Nishant Singh . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Rajput-Ji kalrap615 pushpeshrajdx01 Sorting Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n10 Jun, 2022" }, { "code": null, "e": 538, "s": 54, "text": "We have discussed bucket sort in the main post on Bucket Sort . Bucket sort is mainly useful when input is uniformly distributed over a range. For example, consider the problem of sorting a large set of floating point numbers which are in range from 0.0 to 1.0 and are uniformly distributed across the range. In the above post, we have discussed Bucket Sort to sort numbers which are greater than zero. How to modify Bucket Sort to sort both positive and negative numbers? Example: " }, { "code": null, "e": 647, "s": 538, "text": "Input : arr[] = { -0.897, 0.565, 0.656, -0.1234, 0, 0.3434 } \nOutput : -0.897 -0.1234 0 0.3434 0.565 0.656 " }, { "code": null, "e": 738, "s": 649, "text": "Here we considering number is in range -1.0 to 1.0 (floating point number) Algorithm : " }, { "code": null, "e": 1378, "s": 738, "text": "sortMixed(arr[], n)\n1) Split array into two parts \n create two Empty vector Neg[], Pos[] \n (for negative and positive element respectively)\n Store all negative element in Neg[] by converting\n into positive (Neg[i] = -1 * Arr[i] )\n Store all +ve in pos[] (pos[i] = Arr[i])\n2) Call function bucketSortPositive(Pos, pos.size())\n Call function bucketSortPositive(Neg, Neg.size())\n\nbucketSortPositive(arr[], n)\n3) Create n empty buckets (Or lists).\n4) Do following for every array element arr[i]. \n a) Insert arr[i] into bucket[n*array[i]]\n5) Sort individual buckets using insertion sort.\n6) Concatenate all sorted buckets. " }, { "code": null, "e": 1446, "s": 1378, "text": "Below is implementation of above idea (for floating point number ) " }, { "code": null, "e": 1450, "s": 1446, "text": "CPP" }, { "code": null, "e": 1455, "s": 1450, "text": "Java" }, { "code": null, "e": 1463, "s": 1455, "text": "Python3" }, { "code": null, "e": 1466, "s": 1463, "text": "C#" }, { "code": "// C++ program to sort an array of positive// and negative numbers using bucket sort#include <bits/stdc++.h>using namespace std; // Function to sort arr[] of size n using// bucket sortvoid bucketSort(vector<float> &arr, int n){ // 1) Create n empty buckets vector<float> b[n]; // 2) Put array elements in different // buckets for (int i=0; i<n; i++) { int bi = n*arr[i]; // Index in bucket b[bi].push_back(arr[i]); } // 3) Sort individual buckets for (int i=0; i<n; i++) sort(b[i].begin(), b[i].end()); // 4) Concatenate all buckets into arr[] int index = 0; arr.clear(); for (int i = 0; i < n; i++) for (int j = 0; j < b[i].size(); j++) arr.push_back(b[i][j]);} // This function mainly splits array into two// and then calls bucketSort() for two arrays.void sortMixed(float arr[], int n){ vector<float>Neg ; vector<float>Pos; // traverse array elements for (int i=0; i<n; i++) { if (arr[i] < 0) // store -Ve elements by // converting into +ve element Neg.push_back (-1 * arr[i]) ; else // store +ve elements Pos.push_back (arr[i]) ; } bucketSort(Neg, (int)Neg.size()); bucketSort(Pos, (int)Pos.size()); // First store elements of Neg[] array // by converting into -ve for (int i=0; i < Neg.size(); i++) arr[i] = -1 * Neg[ Neg.size() -1 - i]; // store +ve element for(int j=Neg.size(); j < n; j++) arr[j] = Pos[j - Neg.size()];} /* Driver program to test above function */int main(){ float arr[] = {-0.897, 0.565, 0.656, -0.1234, 0, 0.3434}; int n = sizeof(arr)/sizeof(arr[0]); sortMixed(arr, n); cout << \"Sorted array is \\n\"; for (int i=0; i<n; i++) cout << arr[i] << \" \"; return 0;}", "e": 3306, "s": 1466, "text": null }, { "code": "// Java program to sort an array of positive// and negative numbers using bucket sortimport java.util.*;class GFG{ // Function to sort arr[] of size n using // bucket sort static void bucketSort(Vector<Double> arr, int n) { // 1) Create n empty buckets @SuppressWarnings(\"unchecked\") Vector<Double> b[] = new Vector[n]; for (int i = 0; i < b.length; i++) b[i] = new Vector<Double>(); // 2) Put array elements in different // buckets for (int i = 0; i < n; i++) { int bi = (int)(n*arr.get(i)); // Index in bucket b[bi].add(arr.get(i)); } // 3) Sort individual buckets for (int i = 0; i < n; i++) Collections.sort(b[i]); // 4) Concatenate all buckets into arr[] int index = 0; arr.clear(); for (int i = 0; i < n; i++) for (int j = 0; j < b[i].size(); j++) arr.add(b[i].get(j)); } // This function mainly splits array into two // and then calls bucketSort() for two arrays. static void sortMixed(double arr[], int n) { Vector<Double>Neg = new Vector<>(); Vector<Double>Pos = new Vector<>(); // traverse array elements for (int i = 0; i < n; i++) { if (arr[i] < 0) // store -Ve elements by // converting into +ve element Neg.add (-1 * arr[i]) ; else // store +ve elements Pos.add (arr[i]) ; } bucketSort(Neg, (int)Neg.size()); bucketSort(Pos, (int)Pos.size()); // First store elements of Neg[] array // by converting into -ve for (int i = 0; i < Neg.size(); i++) arr[i] = -1 * Neg.get( Neg.size() -1 - i); // store +ve element for(int j = Neg.size(); j < n; j++) arr[j] = Pos.get(j - Neg.size()); } /* Driver program to test above function */ public static void main(String[] args) { double arr[] = {-0.897, 0.565, 0.656, -0.1234, 0, 0.3434}; int n = arr.length; sortMixed(arr, n); System.out.print(\"Sorted array is \\n\"); for (int i = 0; i < n; i++) System.out.print(arr[i] + \" \"); }} // This code is contributed by Rajput-Ji", "e": 5366, "s": 3306, "text": null }, { "code": "# Python3 program to sort an array of positive# and negative numbers using bucket sort # Function to sort arr[] of size n using# bucket sortdef bucketSort(arr, n): # 1) Create n empty buckets b = [] for i in range(n): b.append([]) # 2) Put array elements in different # buckets for i in range(n): bi = int(n*arr[i]) b[bi].append(arr[i]) # 3) Sort individual buckets for i in range(n): b[i].sort() # 4) Concatenate all buckets into arr[] index = 0 arr.clear() for i in range(n): for j in range(len(b[i])): arr.append(b[i][j]) # This function mainly splits array into two# and then calls bucketSort() for two arrays.def sortMixed(arr, n): Neg = [] Pos = [] # traverse array elements for i in range(n): if(arr[i]<0): # store -Ve elements by # converting into +ve element Neg.append(-1*arr[i]) else: # store +ve elements Pos.append(arr[i]) bucketSort(Neg,len(Neg)) bucketSort(Pos,len(Pos)) # First store elements of Neg[] array # by converting into -ve for i in range(len(Neg)): arr[i]=-1*Neg[len(Neg)-1-i] # store +ve element for i in range(len(Neg),n): arr[i]= Pos[i-len(Neg)] # Driver program to test above functionarr = [-0.897, 0.565, 0.656, -0.1234, 0, 0.3434]sortMixed(arr, len(arr))print(\"Sorted Array is\")print(arr) # This code is contributed by Pushpesh raj", "e": 6891, "s": 5366, "text": null }, { "code": "// C# program to sort an array of positive// and negative numbers using bucket sortusing System;using System.Collections.Generic; public class GFG{ // Function to sort []arr of size n using // bucket sort static void bucketSort(List<Double> arr, int n) { // 1) Create n empty buckets List<Double> []b = new List<Double>[n]; for (int i = 0; i < b.Length; i++) b[i] = new List<Double>(); // 2) Put array elements in different // buckets for (int i = 0; i < n; i++) { int bi = (int)(n*arr[i]); // Index in bucket b[bi].Add(arr[i]); } // 3) Sort individual buckets for (int i = 0; i < n; i++) b[i].Sort(); // 4) Concatenate all buckets into []arr int index = 0; arr.Clear(); for (int i = 0; i < n; i++) for (int j = 0; j < b[i].Count; j++) arr.Add(b[i][j]); } // This function mainly splits array into two // and then calls bucketSort() for two arrays. static void sortMixed(double []arr, int n) { List<Double>Neg = new List<Double>(); List<Double>Pos = new List<Double>(); // traverse array elements for (int i = 0; i < n; i++) { if (arr[i] < 0) // store -Ve elements by // converting into +ve element Neg.Add (-1 * arr[i]) ; else // store +ve elements Pos.Add (arr[i]) ; } bucketSort(Neg, (int)Neg.Count); bucketSort(Pos, (int)Pos.Count); // First store elements of Neg[] array // by converting into -ve for (int i = 0; i < Neg.Count; i++) arr[i] = -1 * Neg[ Neg.Count -1 - i]; // store +ve element for(int j = Neg.Count; j < n; j++) arr[j] = Pos[j - Neg.Count]; } /* Driver program to test above function */ public static void Main(String[] args) { double []arr = {-0.897, 0.565, 0.656, -0.1234, 0, 0.3434}; int n = arr.Length; sortMixed(arr, n); Console.Write(\"Sorted array is \\n\"); for (int i = 0; i < n; i++) Console.Write(arr[i] + \" \"); }} // This code is contributed by Rajput-Ji", "e": 8911, "s": 6891, "text": null }, { "code": null, "e": 8921, "s": 8911, "text": "Output: " }, { "code": null, "e": 8976, "s": 8921, "text": "Sorted array is \n-0.897 -0.1234 0 0.3434 0.565 0.656 " }, { "code": null, "e": 9399, "s": 8976, "text": "This article is contributed by Nishant Singh . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 9409, "s": 9399, "text": "Rajput-Ji" }, { "code": null, "e": 9419, "s": 9409, "text": "kalrap615" }, { "code": null, "e": 9435, "s": 9419, "text": "pushpeshrajdx01" }, { "code": null, "e": 9443, "s": 9435, "text": "Sorting" }, { "code": null, "e": 9451, "s": 9443, "text": "Sorting" } ]
Python PIL | tobytes() Method
02 Aug, 2019 PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. The Image module provides a class with the same name which is used to represent a PIL image. The module also provides a number of factory functions, including functions to load images from files, and to create new images. Image.tobytes() Return image as a bytes object Syntax: Image.tobytes(encoder_name=’raw’, *args) Parameters: encoder_name – What encoder to use. The default is to use the standard “raw” encoder.args – Extra arguments to the encoder. Returns: A bytes object. Image Used: # Importing Image module from PIL packagefrom PIL import Image # creating a image objectimg = Image.open(r"C:\Users\System-Pc\Desktop\tree.jpg") # using tobytesimg.tobytes("xbm", "rgb")print(img) Output: PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=259x194 at 0x2D39DED2BE0 Another Example: Here using same image with change in encoder name to hex. Image Used: # Importing Image module from PIL packagefrom PIL import Image # creating a image objectimg = Image.open(r"C:\Users\System-Pc\Desktop\tree.jpg") # using tobytesimg.tobytes("hex", "rgb")print(img) Output: PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=259x194 at 0x27845B91BE0 Python-pil Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python OOPs Concepts Python Classes and Objects Introduction To PYTHON Python | os.path.join() method How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python - Pandas dataframe.append() Python | datetime.timedelta() function
[ { "code": null, "e": 28, "s": 0, "text": "\n02 Aug, 2019" }, { "code": null, "e": 355, "s": 28, "text": "PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. The Image module provides a class with the same name which is used to represent a PIL image. The module also provides a number of factory functions, including functions to load images from files, and to create new images." }, { "code": null, "e": 402, "s": 355, "text": "Image.tobytes() Return image as a bytes object" }, { "code": null, "e": 451, "s": 402, "text": "Syntax: Image.tobytes(encoder_name=’raw’, *args)" }, { "code": null, "e": 463, "s": 451, "text": "Parameters:" }, { "code": null, "e": 587, "s": 463, "text": "encoder_name – What encoder to use. The default is to use the standard “raw” encoder.args – Extra arguments to the encoder." }, { "code": null, "e": 612, "s": 587, "text": "Returns: A bytes object." }, { "code": null, "e": 624, "s": 612, "text": "Image Used:" }, { "code": " # Importing Image module from PIL packagefrom PIL import Image # creating a image objectimg = Image.open(r\"C:\\Users\\System-Pc\\Desktop\\tree.jpg\") # using tobytesimg.tobytes(\"xbm\", \"rgb\")print(img)", "e": 827, "s": 624, "text": null }, { "code": null, "e": 835, "s": 827, "text": "Output:" }, { "code": null, "e": 915, "s": 835, "text": "PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=259x194 at 0x2D39DED2BE0\n" }, { "code": null, "e": 990, "s": 915, "text": "Another Example: Here using same image with change in encoder name to hex." }, { "code": null, "e": 1002, "s": 990, "text": "Image Used:" }, { "code": " # Importing Image module from PIL packagefrom PIL import Image # creating a image objectimg = Image.open(r\"C:\\Users\\System-Pc\\Desktop\\tree.jpg\") # using tobytesimg.tobytes(\"hex\", \"rgb\")print(img)", "e": 1205, "s": 1002, "text": null }, { "code": null, "e": 1213, "s": 1205, "text": "Output:" }, { "code": null, "e": 1293, "s": 1213, "text": "PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=259x194 at 0x27845B91BE0\n" }, { "code": null, "e": 1304, "s": 1293, "text": "Python-pil" }, { "code": null, "e": 1311, "s": 1304, "text": "Python" }, { "code": null, "e": 1409, "s": 1311, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1441, "s": 1409, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1462, "s": 1441, "text": "Python OOPs Concepts" }, { "code": null, "e": 1489, "s": 1462, "text": "Python Classes and Objects" }, { "code": null, "e": 1512, "s": 1489, "text": "Introduction To PYTHON" }, { "code": null, "e": 1543, "s": 1512, "text": "Python | os.path.join() method" }, { "code": null, "e": 1599, "s": 1543, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 1641, "s": 1599, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 1683, "s": 1641, "text": "Check if element exists in list in Python" }, { "code": null, "e": 1718, "s": 1683, "text": "Python - Pandas dataframe.append()" } ]
How to remove all line breaks from a string using JavaScript?
23 May, 2019 Line breaks in strings vary from platform to platform, but the most common ones are the following: Windows: \r\n carriage return followed by newline character. Linux: \n just a newline character. Older Macs: \r just a carriage return character. There are two methods to accomplish this task. One of the ways is by using traditional programming loop and visiting every character one at a time. Another is using Regular Expressions. The slice and stitch method: It is the basic way to realize the solution to this problem. Visit each character of the string and slice them in such a way that it removes the newline and carriage return characters. Code snippet: var newstr = "";for( var i = 0; i < str.length; i++ ) if( !(str[i] == '\n' || str[i] == '\r') ) newstr += str[i]; All this code snippet does it just copy all the characters that are not “newline” or “carriage return” to another variable. However, there are a lot of overheads in this solution and therefore not an optimal way to remove newlines. Regular Expression: This method uses regular expressions to detect and replace newlines in the string. It is fed into replace function along with string to replace with, which in our case is an empty string. String.replace( regex / substr, replace with ) The regular expression to cover all types of newlines is /\r\n|\n|\r/gm As you can see that this regex has covered all cases separated by | operator. This can be reduced to /[\r\n]+/gm where g and m are for global and multiline flags. Code snippet: function remove_linebreaks( var str ) { return str.replace( /[\r\n]+/gm, "" );} The best part is that this method performed almost 10 times better than the previous one. Example: <!DOCTYPE html><html> <head> <title> Remove all line breaks from a string using JavaScript </title> <script> // Method 1 // Slice and Stitch function remove_linebreaks_ss( str ) { var newstr = ""; for( var i = 0; i < str.length; i++ ) if( !(str[i] == '\n' || str[i] == '\r') ) newstr += str[i]; return newstr; } // Method 2 // Regular Expression function remove_linebreaks( str ) { return str.replace( /[\r\n]+/gm, "" ); } function removeNewLines() { var sample_str = document.getElementById('raw-text').value; console.time(); // For printing time taken on console. document.getElementById('res-1').innerHTML = remove_linebreaks_ss( sample_str ); console.timeEnd(); console.time(); document.getElementById('res-2').innerHTML = remove_linebreaks( sample_str); console.timeEnd(); } </script></head> <body> <center> <textarea id="raw-text"></textarea> <br> <button onclick="removeNewLines()"> Remove Newlines </button> <h6>Method 1:</h6> <p id='res-1'></p> <h6>Method 2:</h6> <p id='res-2'></p> </center></body> </html> Output: Before Clicking on the button: After Clicking on the button: javascript-string Picked JavaScript Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n23 May, 2019" }, { "code": null, "e": 127, "s": 28, "text": "Line breaks in strings vary from platform to platform, but the most common ones are the following:" }, { "code": null, "e": 188, "s": 127, "text": "Windows: \\r\\n carriage return followed by newline character." }, { "code": null, "e": 224, "s": 188, "text": "Linux: \\n just a newline character." }, { "code": null, "e": 273, "s": 224, "text": "Older Macs: \\r just a carriage return character." }, { "code": null, "e": 459, "s": 273, "text": "There are two methods to accomplish this task. One of the ways is by using traditional programming loop and visiting every character one at a time. Another is using Regular Expressions." }, { "code": null, "e": 673, "s": 459, "text": "The slice and stitch method: It is the basic way to realize the solution to this problem. Visit each character of the string and slice them in such a way that it removes the newline and carriage return characters." }, { "code": null, "e": 687, "s": 673, "text": "Code snippet:" }, { "code": "var newstr = \"\";for( var i = 0; i < str.length; i++ ) if( !(str[i] == '\\n' || str[i] == '\\r') ) newstr += str[i];", "e": 812, "s": 687, "text": null }, { "code": null, "e": 1044, "s": 812, "text": "All this code snippet does it just copy all the characters that are not “newline” or “carriage return” to another variable. However, there are a lot of overheads in this solution and therefore not an optimal way to remove newlines." }, { "code": null, "e": 1252, "s": 1044, "text": "Regular Expression: This method uses regular expressions to detect and replace newlines in the string. It is fed into replace function along with string to replace with, which in our case is an empty string." }, { "code": null, "e": 1299, "s": 1252, "text": "String.replace( regex / substr, replace with )" }, { "code": null, "e": 1356, "s": 1299, "text": "The regular expression to cover all types of newlines is" }, { "code": null, "e": 1371, "s": 1356, "text": "/\\r\\n|\\n|\\r/gm" }, { "code": null, "e": 1472, "s": 1371, "text": "As you can see that this regex has covered all cases separated by | operator. This can be reduced to" }, { "code": null, "e": 1484, "s": 1472, "text": "/[\\r\\n]+/gm" }, { "code": null, "e": 1534, "s": 1484, "text": "where g and m are for global and multiline flags." }, { "code": null, "e": 1548, "s": 1534, "text": "Code snippet:" }, { "code": "function remove_linebreaks( var str ) { return str.replace( /[\\r\\n]+/gm, \"\" );}", "e": 1631, "s": 1548, "text": null }, { "code": null, "e": 1721, "s": 1631, "text": "The best part is that this method performed almost 10 times better than the previous one." }, { "code": null, "e": 1730, "s": 1721, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <title> Remove all line breaks from a string using JavaScript </title> <script> // Method 1 // Slice and Stitch function remove_linebreaks_ss( str ) { var newstr = \"\"; for( var i = 0; i < str.length; i++ ) if( !(str[i] == '\\n' || str[i] == '\\r') ) newstr += str[i]; return newstr; } // Method 2 // Regular Expression function remove_linebreaks( str ) { return str.replace( /[\\r\\n]+/gm, \"\" ); } function removeNewLines() { var sample_str = document.getElementById('raw-text').value; console.time(); // For printing time taken on console. document.getElementById('res-1').innerHTML = remove_linebreaks_ss( sample_str ); console.timeEnd(); console.time(); document.getElementById('res-2').innerHTML = remove_linebreaks( sample_str); console.timeEnd(); } </script></head> <body> <center> <textarea id=\"raw-text\"></textarea> <br> <button onclick=\"removeNewLines()\"> Remove Newlines </button> <h6>Method 1:</h6> <p id='res-1'></p> <h6>Method 2:</h6> <p id='res-2'></p> </center></body> </html> ", "e": 3163, "s": 1730, "text": null }, { "code": null, "e": 3171, "s": 3163, "text": "Output:" }, { "code": null, "e": 3202, "s": 3171, "text": "Before Clicking on the button:" }, { "code": null, "e": 3232, "s": 3202, "text": "After Clicking on the button:" }, { "code": null, "e": 3250, "s": 3232, "text": "javascript-string" }, { "code": null, "e": 3257, "s": 3250, "text": "Picked" }, { "code": null, "e": 3268, "s": 3257, "text": "JavaScript" }, { "code": null, "e": 3285, "s": 3268, "text": "Web Technologies" }, { "code": null, "e": 3312, "s": 3285, "text": "Web technologies Questions" } ]
Get the Minimum and Maximum element of a Vector in R Programming - range() Function - GeeksforGeeks
16 Dec, 2021 range() function in R Programming Language is used to get the minimum and maximum values of the vector passed to it as an argument. Syntax: range(x, na.rm, finite) Parameters: x: Numeric Vector na.rm: Boolean value to remove NA finite: Boolean value to exclude non-finite elements R # R program to find the# minimum and maximum element of a vector # Creating a vectorx <- c(8, 2, 5, 4, 9, 6, 54, 18) # Calling range() functionrange(x) Output: [1] 2 54 R # R program to find the# minimum and maximum element of a vector # Creating a vectorx <- c(8, 2, Inf, 5, 4, NA, 9, 54, 18) # Calling range() functionrange(x) # Calling range() function# excluding NA valuesrange(x, na.rm = TRUE) # Calling range() function# excluding finite valuesrange(x, na.rm = TRUE, finite = TRUE) Output: [1] NA NA [1] 2 Inf [1] 2 54 kumar_satyam R Vector-Function R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Control Statements in R Programming Change Color of Bars in Barchart using ggplot2 in R Data Visualization in R Group by function in R using Dplyr How to Change Axis Scales in R Plots? Logistic Regression in R Programming Linear Discriminant Analysis in R Programming How to filter R DataFrame by values in a column? How to change Colors in ggplot2 Line Plot in R ? How to import an Excel File into R ?
[ { "code": null, "e": 24851, "s": 24823, "text": "\n16 Dec, 2021" }, { "code": null, "e": 24983, "s": 24851, "text": "range() function in R Programming Language is used to get the minimum and maximum values of the vector passed to it as an argument." }, { "code": null, "e": 25015, "s": 24983, "text": "Syntax: range(x, na.rm, finite)" }, { "code": null, "e": 25028, "s": 25015, "text": "Parameters: " }, { "code": null, "e": 25046, "s": 25028, "text": "x: Numeric Vector" }, { "code": null, "e": 25080, "s": 25046, "text": "na.rm: Boolean value to remove NA" }, { "code": null, "e": 25133, "s": 25080, "text": "finite: Boolean value to exclude non-finite elements" }, { "code": null, "e": 25135, "s": 25133, "text": "R" }, { "code": "# R program to find the# minimum and maximum element of a vector # Creating a vectorx <- c(8, 2, 5, 4, 9, 6, 54, 18) # Calling range() functionrange(x)", "e": 25287, "s": 25135, "text": null }, { "code": null, "e": 25296, "s": 25287, "text": "Output: " }, { "code": null, "e": 25306, "s": 25296, "text": "[1] 2 54" }, { "code": null, "e": 25308, "s": 25306, "text": "R" }, { "code": "# R program to find the# minimum and maximum element of a vector # Creating a vectorx <- c(8, 2, Inf, 5, 4, NA, 9, 54, 18) # Calling range() functionrange(x) # Calling range() function# excluding NA valuesrange(x, na.rm = TRUE) # Calling range() function# excluding finite valuesrange(x, na.rm = TRUE, finite = TRUE)", "e": 25625, "s": 25308, "text": null }, { "code": null, "e": 25634, "s": 25625, "text": "Output: " }, { "code": null, "e": 25666, "s": 25634, "text": "[1] NA NA\n[1] 2 Inf\n[1] 2 54" }, { "code": null, "e": 25679, "s": 25666, "text": "kumar_satyam" }, { "code": null, "e": 25697, "s": 25679, "text": "R Vector-Function" }, { "code": null, "e": 25708, "s": 25697, "text": "R Language" }, { "code": null, "e": 25806, "s": 25708, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25815, "s": 25806, "text": "Comments" }, { "code": null, "e": 25828, "s": 25815, "text": "Old Comments" }, { "code": null, "e": 25864, "s": 25828, "text": "Control Statements in R Programming" }, { "code": null, "e": 25916, "s": 25864, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 25940, "s": 25916, "text": "Data Visualization in R" }, { "code": null, "e": 25975, "s": 25940, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 26013, "s": 25975, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 26050, "s": 26013, "text": "Logistic Regression in R Programming" }, { "code": null, "e": 26096, "s": 26050, "text": "Linear Discriminant Analysis in R Programming" }, { "code": null, "e": 26145, "s": 26096, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 26194, "s": 26145, "text": "How to change Colors in ggplot2 Line Plot in R ?" } ]
How to set a particular color as background to a JavaFX chart?
The javafx.scene.chart package provides classes to create various charts namely − line chart, area chart, bar chart, pie chart, bubble chart, scatter chart, etc. You can create the required chart by instantiating the respective class. The -fx-background-color class of JavaFX CSS is used to set a colored background to a chart. The -fx-background-color class of JavaFX CSS is used to set a colored background to a chart. The -fx-background-color (of the region chart-plot-background) class of JavaFX CSS is used to set the back ground color. The -fx-background-color (of the region chart-plot-background) class of JavaFX CSS is used to set the back ground color. JavaFX Scene class has an observable list to hold all the required style sheets. You can get this list using the getStylesheets() method. JavaFX Scene class has an observable list to hold all the required style sheets. You can get this list using the getStylesheets() method. To set an image as a background to a chart − Create a CSS file in the current package of the project sheet (say LineChart.css). Create a CSS file in the current package of the project sheet (say LineChart.css). Set the background image using the -fx-background-color CSS class as − Set the background image using the -fx-background-color CSS class as − .chart-plot-background { -fx-background-color: DIMGRAY; } Set the plot color as transparent using the -fx-background-color CSS class as − Set the plot color as transparent using the -fx-background-color CSS class as − .chart-plot-background { -fx-background-color: transparent; } In the program, get the observable list of style sheets using the getStylesheets() method. In the program, get the observable list of style sheets using the getStylesheets() method. Add the created CSS file to the list using the add() method. Add the created CSS file to the list using the add() method. color.CSS − .chart { -fx-padding: 10px; -fx-background-color: DIMGRAY; } .chart-plot-background { -fx-background-color: transparent; } .chart-vertical-grid-lines { -fx-stroke: #dedddc; -fx-stroke-width: 2; } .chart-horizontal-grid-lines { -fx-stroke: #dedddc; -fx-stroke-width: 2; } JavaFX Program − import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.chart.AreaChart; import javafx.scene.chart.CategoryAxis; import javafx.stage.Stage; import javafx.scene.chart.NumberAxis; import javafx.scene.chart.XYChart; import javafx.scene.layout.StackPane; public class AreaChartExample extends Application { public void start(Stage stage) { //Defining the X and Y axes CategoryAxis xAxis = new CategoryAxis(); NumberAxis yAxis = new NumberAxis(); //Setting labels to the axes xAxis.setLabel("Months"); yAxis.setLabel("Rainfall (mm)"); //Creating the Area chart AreaChart<String, Number> areaChart = new AreaChart(xAxis, yAxis); //Prepare data for the area chart XYChart.Series series = new XYChart.Series(); series.getData().add(new XYChart.Data("Jan", 13.2)); series.getData().add(new XYChart.Data("Feb", 7.9)); series.getData().add(new XYChart.Data("Mar", 15.3)); series.getData().add(new XYChart.Data("Apr", 20.2)); series.getData().add(new XYChart.Data("May", 35.7)); series.getData().add(new XYChart.Data("June", 103.8)); series.getData().add(new XYChart.Data("July", 169.9)); series.getData().add(new XYChart.Data("Aug", 178.7)); series.getData().add(new XYChart.Data("Sep", 158.3)); series.getData().add(new XYChart.Data("Oct", 97.2)); series.getData().add(new XYChart.Data("Nov", 22.4)); series.getData().add(new XYChart.Data("Dec", 5.9)); //Setting the name to the line (series) series.setName("Rainfall In Hyderabad"); //Setting data to the area chart areaChart.getData().addAll(series); //Creating a stack pane to hold the chart StackPane pane = new StackPane(areaChart); //Setting the Scene Scene scene = new Scene(pane, 595, 300); stage.setTitle("Area Chart"); stage.setScene(scene); scene.getStylesheets().add("javafx_transformastions/color.css"); stage.show(); } public static void main(String args[]){ launch(args); } }
[ { "code": null, "e": 1224, "s": 1062, "text": "The javafx.scene.chart package provides classes to create various charts namely − line chart, area chart, bar chart, pie chart, bubble chart, scatter chart, etc." }, { "code": null, "e": 1297, "s": 1224, "text": "You can create the required chart by instantiating the respective class." }, { "code": null, "e": 1390, "s": 1297, "text": "The -fx-background-color class of JavaFX CSS is used to set a colored background to a chart." }, { "code": null, "e": 1483, "s": 1390, "text": "The -fx-background-color class of JavaFX CSS is used to set a colored background to a chart." }, { "code": null, "e": 1604, "s": 1483, "text": "The -fx-background-color (of the region chart-plot-background) class\nof JavaFX CSS is used to set the back ground color." }, { "code": null, "e": 1725, "s": 1604, "text": "The -fx-background-color (of the region chart-plot-background) class\nof JavaFX CSS is used to set the back ground color." }, { "code": null, "e": 1863, "s": 1725, "text": "JavaFX Scene class has an observable list to hold all the required style sheets. You can get this list using the getStylesheets() method." }, { "code": null, "e": 2001, "s": 1863, "text": "JavaFX Scene class has an observable list to hold all the required style sheets. You can get this list using the getStylesheets() method." }, { "code": null, "e": 2046, "s": 2001, "text": "To set an image as a background to a chart −" }, { "code": null, "e": 2129, "s": 2046, "text": "Create a CSS file in the current package of the project sheet (say\nLineChart.css)." }, { "code": null, "e": 2212, "s": 2129, "text": "Create a CSS file in the current package of the project sheet (say\nLineChart.css)." }, { "code": null, "e": 2283, "s": 2212, "text": "Set the background image using the -fx-background-color CSS class as −" }, { "code": null, "e": 2354, "s": 2283, "text": "Set the background image using the -fx-background-color CSS class as −" }, { "code": null, "e": 2415, "s": 2354, "text": ".chart-plot-background {\n -fx-background-color: DIMGRAY;\n}" }, { "code": null, "e": 2495, "s": 2415, "text": "Set the plot color as transparent using the -fx-background-color CSS class as −" }, { "code": null, "e": 2575, "s": 2495, "text": "Set the plot color as transparent using the -fx-background-color CSS class as −" }, { "code": null, "e": 2640, "s": 2575, "text": ".chart-plot-background {\n -fx-background-color: transparent;\n}" }, { "code": null, "e": 2731, "s": 2640, "text": "In the program, get the observable list of style sheets using the getStylesheets() method." }, { "code": null, "e": 2822, "s": 2731, "text": "In the program, get the observable list of style sheets using the getStylesheets() method." }, { "code": null, "e": 2883, "s": 2822, "text": "Add the created CSS file to the list using the add() method." }, { "code": null, "e": 2944, "s": 2883, "text": "Add the created CSS file to the list using the add() method." }, { "code": null, "e": 2956, "s": 2944, "text": "color.CSS −" }, { "code": null, "e": 3242, "s": 2956, "text": ".chart {\n -fx-padding: 10px;\n -fx-background-color: DIMGRAY;\n}\n.chart-plot-background {\n -fx-background-color: transparent;\n}\n.chart-vertical-grid-lines {\n -fx-stroke: #dedddc; -fx-stroke-width: 2;\n}\n.chart-horizontal-grid-lines {\n -fx-stroke: #dedddc; -fx-stroke-width: 2;\n}" }, { "code": null, "e": 3259, "s": 3242, "text": "JavaFX Program −" }, { "code": null, "e": 5342, "s": 3259, "text": "import javafx.application.Application;\nimport javafx.scene.Scene;\nimport javafx.scene.chart.AreaChart;\nimport javafx.scene.chart.CategoryAxis;\nimport javafx.stage.Stage;\nimport javafx.scene.chart.NumberAxis;\nimport javafx.scene.chart.XYChart;\nimport javafx.scene.layout.StackPane;\npublic class AreaChartExample extends Application {\n public void start(Stage stage) {\n //Defining the X and Y axes\n CategoryAxis xAxis = new CategoryAxis();\n NumberAxis yAxis = new NumberAxis();\n //Setting labels to the axes\n xAxis.setLabel(\"Months\");\n yAxis.setLabel(\"Rainfall (mm)\");\n //Creating the Area chart\n AreaChart<String, Number> areaChart = new AreaChart(xAxis, yAxis);\n //Prepare data for the area chart\n XYChart.Series series = new XYChart.Series();\n series.getData().add(new XYChart.Data(\"Jan\", 13.2));\n series.getData().add(new XYChart.Data(\"Feb\", 7.9));\n series.getData().add(new XYChart.Data(\"Mar\", 15.3));\n series.getData().add(new XYChart.Data(\"Apr\", 20.2));\n series.getData().add(new XYChart.Data(\"May\", 35.7));\n series.getData().add(new XYChart.Data(\"June\", 103.8));\n series.getData().add(new XYChart.Data(\"July\", 169.9));\n series.getData().add(new XYChart.Data(\"Aug\", 178.7));\n series.getData().add(new XYChart.Data(\"Sep\", 158.3));\n series.getData().add(new XYChart.Data(\"Oct\", 97.2));\n series.getData().add(new XYChart.Data(\"Nov\", 22.4));\n series.getData().add(new XYChart.Data(\"Dec\", 5.9));\n //Setting the name to the line (series)\n series.setName(\"Rainfall In Hyderabad\");\n //Setting data to the area chart\n areaChart.getData().addAll(series);\n //Creating a stack pane to hold the chart\n StackPane pane = new StackPane(areaChart);\n //Setting the Scene\n Scene scene = new Scene(pane, 595, 300);\n stage.setTitle(\"Area Chart\");\n stage.setScene(scene);\n scene.getStylesheets().add(\"javafx_transformastions/color.css\");\n stage.show();\n }\n public static void main(String args[]){\n launch(args);\n }\n}" } ]
Real-time Object Tracking with TensorFlow, Raspberry Pi, and Pan-Tilt HAT | by Leigh Johnson | Towards Data Science
Are you just getting started with machine/deep learning, TensorFlow, or Raspberry Pi? Perfect, this blog post is for you! I created rpi-deep-pantilt as an interactive demo of object detection in the wild. 🦁 UPDATE — Face detection and tracking added! I’ll show you how to reproduce the video below, which depicts a camera panning and tilting to track my movement across a room. I will cover the following: Build materials and hardware assembly instructions.Deploy a TensorFlow Lite object detection model (MobileNetV3-SSD) to a Raspberry Pi.Send tracking instructions to pan / tilt servo motors using a proportional–integral–derivative controller (PID) controller.Accelerate inferences of any TensorFlow Lite model with Coral’s USB Edge TPU Accelerator and Edge TPU Compiler. Build materials and hardware assembly instructions. Deploy a TensorFlow Lite object detection model (MobileNetV3-SSD) to a Raspberry Pi. Send tracking instructions to pan / tilt servo motors using a proportional–integral–derivative controller (PID) controller. Accelerate inferences of any TensorFlow Lite model with Coral’s USB Edge TPU Accelerator and Edge TPU Compiler. Raspberry Pi — a small, affordable computer popular with educators, hardware hobbyists and robot enthusiasts. 🤖 Raspbian — the Raspberry Pi Foundation’s official operating system for the Pi. Raspbian is derived from Debian Linux. TensorFlow — an open-source framework for dataflow programming, used for machine learning and deep neural learning. TensorFlow Lite — an open-source framework for deploying TensorFlow models on mobile and embedded devices. Convolutional Neural Network — a type of neural network architecture that is well-suited for image classification and object detection tasks. Single Shot Detector (SSD) — a type of convolutional neural network (CNN) architecture, specialized for real-time object detection, classification, and bounding box localization. MobileNetV3 — a state-of-the-art computer vision model optimized for performance on modest mobile phone processors. MobileNetV3-SSD — a single-shot detector based on MobileNet architecture. This tutorial will be using MobileNetV3-SSD models available through TensorFlow’s object detection model zoo. Edge TPU — a tensor processing unit (TPU) is an integrated circuit for accelerating computations performed by TensorFlow. The Edge TPU was developed with a small footprint, for mobile and embedded devices “at the edge” Raspberry Pi 4 (4GB recommended) Raspberry Pi Camera V2 Pimoroni Pan-tilt HAT Kit Micro SD card 16+ GB Micro HDMI Cable 12" CSI/DSI ribbon for Raspberry Pi Camera. The Pi Camera’s stock cable is too short for the Pan-tilt HAT’s full range of motion. RGB NeoPixel StickThis component adds a consistent light source to your project. Coral Edge TPU USB AcceleratorAccelerates inference (prediction) speed on the Raspberry Pi. You don’t need this to reproduce the demo. 👋 Looking for a project with fewer moving pieces? Check out Portable Computer Vision: TensorFlow 2.0 on a Raspberry Pi to create a hand-held image classier. ✨ There are two ways you can install Raspbian to your Micro SD card: NOOBS (New Out Of the Box Software) is a GUI operation system installation manager. If this is your first Raspberry Pi project, I’d recommend starting here.Write Raspbian Image to SD Card. NOOBS (New Out Of the Box Software) is a GUI operation system installation manager. If this is your first Raspberry Pi project, I’d recommend starting here. Write Raspbian Image to SD Card. This tutorial and supporting software were written using Raspbian (Buster). If you’re using a different version of Raspbian or another platform, you’ll probably experience some pains. Before proceeding, you’ll need to: Connect your Pi to the internet (doc) SSH into your Raspberry Pi (doc) Install system dependencies Install system dependencies $ sudo apt-get update && sudo apt-get install -y python3-dev libjpeg-dev libatlas-base-dev raspi-gpio libhdf5-dev python3-smbus 2. Create a new project directory $ mkdir rpi-deep-pantilt && cd rpi-deep-pantilt 3. Create a new virtual environment $ python3 -m venv .venv 4. Activate the virtual environment $ source .venv/bin/activate && python3 -m pip install --upgrade pip 5. Install TensorFlow 2.0 from a community-built wheel. $ pip install https://github.com/bitsy-ai/tensorflow-arm-bin/releases/download/v2.4.0/tensorflow-2.4.0-cp37-none-linux_armv7l.whl 6. Install the rpi-deep-pantilt Python package $ python3 -m pip install rpi-deep-pantilt If you purchased a pre-assembled Pan-Tilt HAT kit, you can skip to the next section. Otherwise, follow the steps in Assembling Pan-Tilt HAT before proceeding. Turn off the Raspberry PiLocate the Camera Module, between the USB Module and HDMI modules.Unlock the black plastic clip by (gently) pulling upwardsInsert the Camera Module ribbon cable (metal connectors facing away from the ethernet / USB ports on a Raspberry Pi 4)Lock the black plastic clip Turn off the Raspberry Pi Locate the Camera Module, between the USB Module and HDMI modules. Unlock the black plastic clip by (gently) pulling upwards Insert the Camera Module ribbon cable (metal connectors facing away from the ethernet / USB ports on a Raspberry Pi 4) Lock the black plastic clip Turn the Raspberry Pi onRun sudo raspi-config and select Interfacing Options from the Raspberry Pi Software Configuration Tool’s main menu. Press ENTER. Turn the Raspberry Pi on Run sudo raspi-config and select Interfacing Options from the Raspberry Pi Software Configuration Tool’s main menu. Press ENTER. 3. Select the Enable Camera menu option and press ENTER. 4. In the next menu, use the right arrow key to highlight ENABLE and press ENTER. Next, test the installation and setup of your Pan-Tilt HAT module. SSH into your Raspberry PiActivate your Virtual Environment: source .venv/bin/activateRun the following command: rpi-deep-pantilt test pantiltExit the test with Ctrl+C SSH into your Raspberry Pi Activate your Virtual Environment: source .venv/bin/activate Run the following command: rpi-deep-pantilt test pantilt Exit the test with Ctrl+C If you installed the HAT correctly, you should see both servos moving in a smooth sinusoidal motion while the test is running. Next, verify the Pi Camera is installed correctly by starting the camera’s preview overlay. The overlay will render on the Pi’s primary display (HDMI). Plug your Raspberry Pi into an HDMI screenSSH into your Raspberry PiActivate your Virtual Environment: $ source .venv/bin/activateRun the following command: $ rpi-deep-pantilt test cameraExit the test with Ctrl+C Plug your Raspberry Pi into an HDMI screen SSH into your Raspberry Pi Activate your Virtual Environment: $ source .venv/bin/activate Run the following command: $ rpi-deep-pantilt test camera Exit the test with Ctrl+C If you installed the Pi Camera correctly, you should see footage from the camera rendered to your HDMI or composite display. Next, verify you can run an object detection model (MobileNetV3-SSD) on your Raspberry Pi. SSH into your Raspberry PiActivate your Virtual Environment: $ source .venv/bin/activateRun the following command: SSH into your Raspberry Pi Activate your Virtual Environment: $ source .venv/bin/activate Run the following command: $ rpi-deep-pantilt detect Your Raspberry Pi should detect objects, attempt to classify the object, and draw a bounding box around it. $ rpi-deep-pantilt face-detect $ rpi-deep-pantilt list-labels[‘person’, ‘bicycle’, ‘car’, ‘motorcycle’, ‘airplane’, ‘bus’, ‘train’, ‘truck’, ‘boat’, ‘traffic light’, ‘fire hydrant’, ‘stop sign’, ‘parking meter’, ‘bench’, ‘bird’, ‘cat’, ‘dog’, ‘horse’, ‘sheep’, ‘cow’, ‘elephant’, ‘bear’, ‘zebra’, ‘giraffe’, ‘backpack’, ‘umbrella’, ‘handbag’, ‘tie’, ‘suitcase’, ‘frisbee’, ‘skis’, ‘snowboard’, ‘sports ball’, ‘kite’, ‘baseball bat’, ‘baseball glove’, ‘skateboard’, ‘surfboard’, ‘tennis racket’, ‘bottle’, ‘wine glass’, ‘cup’, ‘fork’, ‘knife’, ‘spoon’, ‘bowl’, ‘banana’, ‘apple’, ‘sandwich’, ‘orange’, ‘broccoli’, ‘carrot’, ‘hot dog’, ‘pizza’, ‘donut’, ‘cake’, ‘chair’, ‘couch’, ‘potted plant’, ‘bed’, ‘dining table’, ‘toilet’, ‘tv’, ‘laptop’, ‘mouse’, ‘remote’, ‘keyboard’, ‘cell phone’, ‘microwave’, ‘oven’, ‘toaster’, ‘sink’, ‘refrigerator’, ‘book’, ‘clock’, ‘vase’, ‘scissors’, ‘teddy bear’, ‘hair drier’, ‘toothbrush’] This is the moment we’ve all been waiting for! Take the following steps to track an object at roughly 8 frames / second using the Pan-Tilt HAT. SSH into your Raspberry PiActivate your Virtual Environment: $source .venv/bin/activateRun the following command: $ rpi-deep-pantilt track SSH into your Raspberry Pi Activate your Virtual Environment: $source .venv/bin/activate Run the following command: $ rpi-deep-pantilt track By default, this will track objects with the label person. You can track a different type of object using the --label parameter. For example, to track a banana you would run: $ rpi-deep-pantilt track --label=banana On a Raspberry Pi 4 (4 GB), I benchmarked my model at roughly 8 frames per second. INFO:root:FPS: 8.100870481091935INFO:root:FPS: 8.130448201926173INFO:root:FPS: 7.6518234817241355INFO:root:FPS: 7.657477766009717INFO:root:FPS: 7.861758172395542INFO:root:FPS: 7.8549541944597INFO:root:FPS: 7.907857699044301 We can accelerate model inference speed with Coral’s USB Accelerator. The USB Accelerator contains an Edge TPU, which is an ASIC chip specialized for TensorFlow Lite operations. For more info, check out Getting Started with the USB Accelerator. SSH into your Raspberry PiInstall the Edge TPU runtime SSH into your Raspberry Pi Install the Edge TPU runtime $ echo "deb https://packages.cloud.google.com/apt coral-edgetpu-stable main" | sudo tee /etc/apt/sources.list.d/coral-edgetpu.list$ curl https://packages.cloud.google.com/apt/doc/apt-key.gpg | sudo apt-key add -$ sudo apt-get update && sudo apt-get install libedgetpu1-std 3. Plug in the Edge TPU (prefer a USB 3.0 port). If your Edge TPU was already plugged in, remove and re-plug it so the udev device manager can detect it. 4. Try the detect command with --edge-tpuoption. You should be able to detect objects in real-time! 🎉 $ rpi-deep-pantilt detect --edge-tpu --loglevel=INFO Note: loglevel=INFO will show you the FPS at which objects are detected and bounding boxes are rendered to the Raspberry Pi Camera’s overlay. You should see around ~24 FPS, which is the rate at which frames are sampled from the Pi Camera into a frame buffer. INFO:root:FPS: 24.716493958392558INFO:root:FPS: 24.836166606505206INFO:root:FPS: 23.031063233367547INFO:root:FPS: 25.467177106703623INFO:root:FPS: 27.480438524486594INFO:root:FPS: 25.41399952505432 5. Try the track command with --edge-tpu option. $ rpi-deep-pantilt track --edge-tpu I’ve added a brand new face detection model in version v1.1.x of rpi-deep-pantilt 🎉 The model is derived from facessd_mobilenet_v2_quantized_320x320_open_image_v4 in TensorFlow’s research model zoo. The new commands are rpi-deep-pantilt face-detect (detect all faces) and rpi-deep-pantilt face-track (track faces with Pantilt HAT). Both commands support the --edge-tpu option, which will accelerate inferences if using the Edge TPU USB Accelerator. rpi-deep-pantilt face-detect --helpUsage: cli.py face-detect [OPTIONS]Options: --loglevel TEXT Run object detection without pan-tilt controls. Pass --loglevel=DEBUG to inspect FPS. --edge-tpu Accelerate inferences using Coral USB Edge TPU --help Show this message and exit. rpi-deep-pantilt face-track --helpUsage: cli.py face-track [OPTIONS]Options: --loglevel TEXT Run object detection without pan-tilt controls. Pass --loglevel=DEBUG to inspect FPS. --edge-tpu Accelerate inferences using Coral USB Edge TPU --help Show this message and exit. Congratulations! You’re now the proud owner of a DIY object tracking system, which uses a single-shot-detector (a type of convolutional neural network) to classify and localize objects. The pan / tilt tracking system uses a proportional–integral–derivative controller (PID) controller to smoothly track the centroid of a bounding box. The models in this tutorial are derived from ssd_mobilenet_v3_small_coco and ssd_mobilenet_edgetpu_coco in the TensorFlow Detection Model Zoo. 🦁🦄🐼 My models are available for download via Github releases notes @ leigh-johnson/rpi-deep-pantilt. I added the custom TFLite_Detection_PostProcess operation, which implements a variation of Non-maximum Suppression (NMS) on model output. Non-maximum Suppression is technique that filters many bounding box proposals using set operations. Looking for more hands-on examples of Machine Learning for Raspberry Pi and other small device? Sign up for my newsletter! I publish examples of real-world ML applications (with full source code) and nifty tricks like automating away the pains of bounding-box annotation. MobileNetEdgeTPU SSDLite contributors: Yunyang Xiong, Bo Chen, Suyog Gupta, Hanxiao Liu, Gabriel Bender, Mingxing Tan, Berkin Akin, Zhichao Lu, Quoc Le. MobileNetV3 SSDLite contributors: Bo Chen, Zhichao Lu, Vivek Rathod, Jonathan Huang. Special thanks to Adrian Rosebrock for writing Pan/tilt face tracking with a Raspberry Pi and OpenCV, which was the inspiration for this whole project! Special thanks to Jason Zaman for reviewing this article and early release candidates. 💪
[ { "code": null, "e": 378, "s": 171, "text": "Are you just getting started with machine/deep learning, TensorFlow, or Raspberry Pi? Perfect, this blog post is for you! I created rpi-deep-pantilt as an interactive demo of object detection in the wild. 🦁" }, { "code": null, "e": 422, "s": 378, "text": "UPDATE — Face detection and tracking added!" }, { "code": null, "e": 549, "s": 422, "text": "I’ll show you how to reproduce the video below, which depicts a camera panning and tilting to track my movement across a room." }, { "code": null, "e": 577, "s": 549, "text": "I will cover the following:" }, { "code": null, "e": 947, "s": 577, "text": "Build materials and hardware assembly instructions.Deploy a TensorFlow Lite object detection model (MobileNetV3-SSD) to a Raspberry Pi.Send tracking instructions to pan / tilt servo motors using a proportional–integral–derivative controller (PID) controller.Accelerate inferences of any TensorFlow Lite model with Coral’s USB Edge TPU Accelerator and Edge TPU Compiler." }, { "code": null, "e": 999, "s": 947, "text": "Build materials and hardware assembly instructions." }, { "code": null, "e": 1084, "s": 999, "text": "Deploy a TensorFlow Lite object detection model (MobileNetV3-SSD) to a Raspberry Pi." }, { "code": null, "e": 1208, "s": 1084, "text": "Send tracking instructions to pan / tilt servo motors using a proportional–integral–derivative controller (PID) controller." }, { "code": null, "e": 1320, "s": 1208, "text": "Accelerate inferences of any TensorFlow Lite model with Coral’s USB Edge TPU Accelerator and Edge TPU Compiler." }, { "code": null, "e": 1432, "s": 1320, "text": "Raspberry Pi — a small, affordable computer popular with educators, hardware hobbyists and robot enthusiasts. 🤖" }, { "code": null, "e": 1550, "s": 1432, "text": "Raspbian — the Raspberry Pi Foundation’s official operating system for the Pi. Raspbian is derived from Debian Linux." }, { "code": null, "e": 1666, "s": 1550, "text": "TensorFlow — an open-source framework for dataflow programming, used for machine learning and deep neural learning." }, { "code": null, "e": 1773, "s": 1666, "text": "TensorFlow Lite — an open-source framework for deploying TensorFlow models on mobile and embedded devices." }, { "code": null, "e": 1915, "s": 1773, "text": "Convolutional Neural Network — a type of neural network architecture that is well-suited for image classification and object detection tasks." }, { "code": null, "e": 2094, "s": 1915, "text": "Single Shot Detector (SSD) — a type of convolutional neural network (CNN) architecture, specialized for real-time object detection, classification, and bounding box localization." }, { "code": null, "e": 2210, "s": 2094, "text": "MobileNetV3 — a state-of-the-art computer vision model optimized for performance on modest mobile phone processors." }, { "code": null, "e": 2394, "s": 2210, "text": "MobileNetV3-SSD — a single-shot detector based on MobileNet architecture. This tutorial will be using MobileNetV3-SSD models available through TensorFlow’s object detection model zoo." }, { "code": null, "e": 2613, "s": 2394, "text": "Edge TPU — a tensor processing unit (TPU) is an integrated circuit for accelerating computations performed by TensorFlow. The Edge TPU was developed with a small footprint, for mobile and embedded devices “at the edge”" }, { "code": null, "e": 2646, "s": 2613, "text": "Raspberry Pi 4 (4GB recommended)" }, { "code": null, "e": 2669, "s": 2646, "text": "Raspberry Pi Camera V2" }, { "code": null, "e": 2695, "s": 2669, "text": "Pimoroni Pan-tilt HAT Kit" }, { "code": null, "e": 2716, "s": 2695, "text": "Micro SD card 16+ GB" }, { "code": null, "e": 2733, "s": 2716, "text": "Micro HDMI Cable" }, { "code": null, "e": 2863, "s": 2733, "text": "12\" CSI/DSI ribbon for Raspberry Pi Camera. The Pi Camera’s stock cable is too short for the Pan-tilt HAT’s full range of motion." }, { "code": null, "e": 2944, "s": 2863, "text": "RGB NeoPixel StickThis component adds a consistent light source to your project." }, { "code": null, "e": 3079, "s": 2944, "text": "Coral Edge TPU USB AcceleratorAccelerates inference (prediction) speed on the Raspberry Pi. You don’t need this to reproduce the demo." }, { "code": null, "e": 3129, "s": 3079, "text": "👋 Looking for a project with fewer moving pieces?" }, { "code": null, "e": 3238, "s": 3129, "text": "Check out Portable Computer Vision: TensorFlow 2.0 on a Raspberry Pi to create a hand-held image classier. ✨" }, { "code": null, "e": 3305, "s": 3238, "text": "There are two ways you can install Raspbian to your Micro SD card:" }, { "code": null, "e": 3494, "s": 3305, "text": "NOOBS (New Out Of the Box Software) is a GUI operation system installation manager. If this is your first Raspberry Pi project, I’d recommend starting here.Write Raspbian Image to SD Card." }, { "code": null, "e": 3651, "s": 3494, "text": "NOOBS (New Out Of the Box Software) is a GUI operation system installation manager. If this is your first Raspberry Pi project, I’d recommend starting here." }, { "code": null, "e": 3684, "s": 3651, "text": "Write Raspbian Image to SD Card." }, { "code": null, "e": 3868, "s": 3684, "text": "This tutorial and supporting software were written using Raspbian (Buster). If you’re using a different version of Raspbian or another platform, you’ll probably experience some pains." }, { "code": null, "e": 3903, "s": 3868, "text": "Before proceeding, you’ll need to:" }, { "code": null, "e": 3941, "s": 3903, "text": "Connect your Pi to the internet (doc)" }, { "code": null, "e": 3974, "s": 3941, "text": "SSH into your Raspberry Pi (doc)" }, { "code": null, "e": 4002, "s": 3974, "text": "Install system dependencies" }, { "code": null, "e": 4030, "s": 4002, "text": "Install system dependencies" }, { "code": null, "e": 4158, "s": 4030, "text": "$ sudo apt-get update && sudo apt-get install -y python3-dev libjpeg-dev libatlas-base-dev raspi-gpio libhdf5-dev python3-smbus" }, { "code": null, "e": 4192, "s": 4158, "text": "2. Create a new project directory" }, { "code": null, "e": 4240, "s": 4192, "text": "$ mkdir rpi-deep-pantilt && cd rpi-deep-pantilt" }, { "code": null, "e": 4276, "s": 4240, "text": "3. Create a new virtual environment" }, { "code": null, "e": 4300, "s": 4276, "text": "$ python3 -m venv .venv" }, { "code": null, "e": 4336, "s": 4300, "text": "4. Activate the virtual environment" }, { "code": null, "e": 4404, "s": 4336, "text": "$ source .venv/bin/activate && python3 -m pip install --upgrade pip" }, { "code": null, "e": 4460, "s": 4404, "text": "5. Install TensorFlow 2.0 from a community-built wheel." }, { "code": null, "e": 4590, "s": 4460, "text": "$ pip install https://github.com/bitsy-ai/tensorflow-arm-bin/releases/download/v2.4.0/tensorflow-2.4.0-cp37-none-linux_armv7l.whl" }, { "code": null, "e": 4637, "s": 4590, "text": "6. Install the rpi-deep-pantilt Python package" }, { "code": null, "e": 4679, "s": 4637, "text": "$ python3 -m pip install rpi-deep-pantilt" }, { "code": null, "e": 4764, "s": 4679, "text": "If you purchased a pre-assembled Pan-Tilt HAT kit, you can skip to the next section." }, { "code": null, "e": 4838, "s": 4764, "text": "Otherwise, follow the steps in Assembling Pan-Tilt HAT before proceeding." }, { "code": null, "e": 5132, "s": 4838, "text": "Turn off the Raspberry PiLocate the Camera Module, between the USB Module and HDMI modules.Unlock the black plastic clip by (gently) pulling upwardsInsert the Camera Module ribbon cable (metal connectors facing away from the ethernet / USB ports on a Raspberry Pi 4)Lock the black plastic clip" }, { "code": null, "e": 5158, "s": 5132, "text": "Turn off the Raspberry Pi" }, { "code": null, "e": 5225, "s": 5158, "text": "Locate the Camera Module, between the USB Module and HDMI modules." }, { "code": null, "e": 5283, "s": 5225, "text": "Unlock the black plastic clip by (gently) pulling upwards" }, { "code": null, "e": 5402, "s": 5283, "text": "Insert the Camera Module ribbon cable (metal connectors facing away from the ethernet / USB ports on a Raspberry Pi 4)" }, { "code": null, "e": 5430, "s": 5402, "text": "Lock the black plastic clip" }, { "code": null, "e": 5583, "s": 5430, "text": "Turn the Raspberry Pi onRun sudo raspi-config and select Interfacing Options from the Raspberry Pi Software Configuration Tool’s main menu. Press ENTER." }, { "code": null, "e": 5608, "s": 5583, "text": "Turn the Raspberry Pi on" }, { "code": null, "e": 5737, "s": 5608, "text": "Run sudo raspi-config and select Interfacing Options from the Raspberry Pi Software Configuration Tool’s main menu. Press ENTER." }, { "code": null, "e": 5794, "s": 5737, "text": "3. Select the Enable Camera menu option and press ENTER." }, { "code": null, "e": 5876, "s": 5794, "text": "4. In the next menu, use the right arrow key to highlight ENABLE and press ENTER." }, { "code": null, "e": 5943, "s": 5876, "text": "Next, test the installation and setup of your Pan-Tilt HAT module." }, { "code": null, "e": 6111, "s": 5943, "text": "SSH into your Raspberry PiActivate your Virtual Environment: source .venv/bin/activateRun the following command: rpi-deep-pantilt test pantiltExit the test with Ctrl+C" }, { "code": null, "e": 6138, "s": 6111, "text": "SSH into your Raspberry Pi" }, { "code": null, "e": 6199, "s": 6138, "text": "Activate your Virtual Environment: source .venv/bin/activate" }, { "code": null, "e": 6256, "s": 6199, "text": "Run the following command: rpi-deep-pantilt test pantilt" }, { "code": null, "e": 6282, "s": 6256, "text": "Exit the test with Ctrl+C" }, { "code": null, "e": 6409, "s": 6282, "text": "If you installed the HAT correctly, you should see both servos moving in a smooth sinusoidal motion while the test is running." }, { "code": null, "e": 6561, "s": 6409, "text": "Next, verify the Pi Camera is installed correctly by starting the camera’s preview overlay. The overlay will render on the Pi’s primary display (HDMI)." }, { "code": null, "e": 6774, "s": 6561, "text": "Plug your Raspberry Pi into an HDMI screenSSH into your Raspberry PiActivate your Virtual Environment: $ source .venv/bin/activateRun the following command: $ rpi-deep-pantilt test cameraExit the test with Ctrl+C" }, { "code": null, "e": 6817, "s": 6774, "text": "Plug your Raspberry Pi into an HDMI screen" }, { "code": null, "e": 6844, "s": 6817, "text": "SSH into your Raspberry Pi" }, { "code": null, "e": 6907, "s": 6844, "text": "Activate your Virtual Environment: $ source .venv/bin/activate" }, { "code": null, "e": 6965, "s": 6907, "text": "Run the following command: $ rpi-deep-pantilt test camera" }, { "code": null, "e": 6991, "s": 6965, "text": "Exit the test with Ctrl+C" }, { "code": null, "e": 7116, "s": 6991, "text": "If you installed the Pi Camera correctly, you should see footage from the camera rendered to your HDMI or composite display." }, { "code": null, "e": 7207, "s": 7116, "text": "Next, verify you can run an object detection model (MobileNetV3-SSD) on your Raspberry Pi." }, { "code": null, "e": 7322, "s": 7207, "text": "SSH into your Raspberry PiActivate your Virtual Environment: $ source .venv/bin/activateRun the following command:" }, { "code": null, "e": 7349, "s": 7322, "text": "SSH into your Raspberry Pi" }, { "code": null, "e": 7412, "s": 7349, "text": "Activate your Virtual Environment: $ source .venv/bin/activate" }, { "code": null, "e": 7439, "s": 7412, "text": "Run the following command:" }, { "code": null, "e": 7465, "s": 7439, "text": "$ rpi-deep-pantilt detect" }, { "code": null, "e": 7573, "s": 7465, "text": "Your Raspberry Pi should detect objects, attempt to classify the object, and draw a bounding box around it." }, { "code": null, "e": 7604, "s": 7573, "text": "$ rpi-deep-pantilt face-detect" }, { "code": null, "e": 8496, "s": 7604, "text": "$ rpi-deep-pantilt list-labels[‘person’, ‘bicycle’, ‘car’, ‘motorcycle’, ‘airplane’, ‘bus’, ‘train’, ‘truck’, ‘boat’, ‘traffic light’, ‘fire hydrant’, ‘stop sign’, ‘parking meter’, ‘bench’, ‘bird’, ‘cat’, ‘dog’, ‘horse’, ‘sheep’, ‘cow’, ‘elephant’, ‘bear’, ‘zebra’, ‘giraffe’, ‘backpack’, ‘umbrella’, ‘handbag’, ‘tie’, ‘suitcase’, ‘frisbee’, ‘skis’, ‘snowboard’, ‘sports ball’, ‘kite’, ‘baseball bat’, ‘baseball glove’, ‘skateboard’, ‘surfboard’, ‘tennis racket’, ‘bottle’, ‘wine glass’, ‘cup’, ‘fork’, ‘knife’, ‘spoon’, ‘bowl’, ‘banana’, ‘apple’, ‘sandwich’, ‘orange’, ‘broccoli’, ‘carrot’, ‘hot dog’, ‘pizza’, ‘donut’, ‘cake’, ‘chair’, ‘couch’, ‘potted plant’, ‘bed’, ‘dining table’, ‘toilet’, ‘tv’, ‘laptop’, ‘mouse’, ‘remote’, ‘keyboard’, ‘cell phone’, ‘microwave’, ‘oven’, ‘toaster’, ‘sink’, ‘refrigerator’, ‘book’, ‘clock’, ‘vase’, ‘scissors’, ‘teddy bear’, ‘hair drier’, ‘toothbrush’]" }, { "code": null, "e": 8640, "s": 8496, "text": "This is the moment we’ve all been waiting for! Take the following steps to track an object at roughly 8 frames / second using the Pan-Tilt HAT." }, { "code": null, "e": 8779, "s": 8640, "text": "SSH into your Raspberry PiActivate your Virtual Environment: $source .venv/bin/activateRun the following command: $ rpi-deep-pantilt track" }, { "code": null, "e": 8806, "s": 8779, "text": "SSH into your Raspberry Pi" }, { "code": null, "e": 8868, "s": 8806, "text": "Activate your Virtual Environment: $source .venv/bin/activate" }, { "code": null, "e": 8920, "s": 8868, "text": "Run the following command: $ rpi-deep-pantilt track" }, { "code": null, "e": 9049, "s": 8920, "text": "By default, this will track objects with the label person. You can track a different type of object using the --label parameter." }, { "code": null, "e": 9095, "s": 9049, "text": "For example, to track a banana you would run:" }, { "code": null, "e": 9135, "s": 9095, "text": "$ rpi-deep-pantilt track --label=banana" }, { "code": null, "e": 9218, "s": 9135, "text": "On a Raspberry Pi 4 (4 GB), I benchmarked my model at roughly 8 frames per second." }, { "code": null, "e": 9442, "s": 9218, "text": "INFO:root:FPS: 8.100870481091935INFO:root:FPS: 8.130448201926173INFO:root:FPS: 7.6518234817241355INFO:root:FPS: 7.657477766009717INFO:root:FPS: 7.861758172395542INFO:root:FPS: 7.8549541944597INFO:root:FPS: 7.907857699044301" }, { "code": null, "e": 9687, "s": 9442, "text": "We can accelerate model inference speed with Coral’s USB Accelerator. The USB Accelerator contains an Edge TPU, which is an ASIC chip specialized for TensorFlow Lite operations. For more info, check out Getting Started with the USB Accelerator." }, { "code": null, "e": 9742, "s": 9687, "text": "SSH into your Raspberry PiInstall the Edge TPU runtime" }, { "code": null, "e": 9769, "s": 9742, "text": "SSH into your Raspberry Pi" }, { "code": null, "e": 9798, "s": 9769, "text": "Install the Edge TPU runtime" }, { "code": null, "e": 10071, "s": 9798, "text": "$ echo \"deb https://packages.cloud.google.com/apt coral-edgetpu-stable main\" | sudo tee /etc/apt/sources.list.d/coral-edgetpu.list$ curl https://packages.cloud.google.com/apt/doc/apt-key.gpg | sudo apt-key add -$ sudo apt-get update && sudo apt-get install libedgetpu1-std" }, { "code": null, "e": 10225, "s": 10071, "text": "3. Plug in the Edge TPU (prefer a USB 3.0 port). If your Edge TPU was already plugged in, remove and re-plug it so the udev device manager can detect it." }, { "code": null, "e": 10327, "s": 10225, "text": "4. Try the detect command with --edge-tpuoption. You should be able to detect objects in real-time! 🎉" }, { "code": null, "e": 10380, "s": 10327, "text": "$ rpi-deep-pantilt detect --edge-tpu --loglevel=INFO" }, { "code": null, "e": 10522, "s": 10380, "text": "Note: loglevel=INFO will show you the FPS at which objects are detected and bounding boxes are rendered to the Raspberry Pi Camera’s overlay." }, { "code": null, "e": 10639, "s": 10522, "text": "You should see around ~24 FPS, which is the rate at which frames are sampled from the Pi Camera into a frame buffer." }, { "code": null, "e": 10837, "s": 10639, "text": "INFO:root:FPS: 24.716493958392558INFO:root:FPS: 24.836166606505206INFO:root:FPS: 23.031063233367547INFO:root:FPS: 25.467177106703623INFO:root:FPS: 27.480438524486594INFO:root:FPS: 25.41399952505432" }, { "code": null, "e": 10886, "s": 10837, "text": "5. Try the track command with --edge-tpu option." }, { "code": null, "e": 10922, "s": 10886, "text": "$ rpi-deep-pantilt track --edge-tpu" }, { "code": null, "e": 11006, "s": 10922, "text": "I’ve added a brand new face detection model in version v1.1.x of rpi-deep-pantilt 🎉" }, { "code": null, "e": 11121, "s": 11006, "text": "The model is derived from facessd_mobilenet_v2_quantized_320x320_open_image_v4 in TensorFlow’s research model zoo." }, { "code": null, "e": 11371, "s": 11121, "text": "The new commands are rpi-deep-pantilt face-detect (detect all faces) and rpi-deep-pantilt face-track (track faces with Pantilt HAT). Both commands support the --edge-tpu option, which will accelerate inferences if using the Edge TPU USB Accelerator." }, { "code": null, "e": 11683, "s": 11371, "text": "rpi-deep-pantilt face-detect --helpUsage: cli.py face-detect [OPTIONS]Options: --loglevel TEXT Run object detection without pan-tilt controls. Pass --loglevel=DEBUG to inspect FPS. --edge-tpu Accelerate inferences using Coral USB Edge TPU --help Show this message and exit." }, { "code": null, "e": 11993, "s": 11683, "text": "rpi-deep-pantilt face-track --helpUsage: cli.py face-track [OPTIONS]Options: --loglevel TEXT Run object detection without pan-tilt controls. Pass --loglevel=DEBUG to inspect FPS. --edge-tpu Accelerate inferences using Coral USB Edge TPU --help Show this message and exit." }, { "code": null, "e": 12179, "s": 11993, "text": "Congratulations! You’re now the proud owner of a DIY object tracking system, which uses a single-shot-detector (a type of convolutional neural network) to classify and localize objects." }, { "code": null, "e": 12328, "s": 12179, "text": "The pan / tilt tracking system uses a proportional–integral–derivative controller (PID) controller to smoothly track the centroid of a bounding box." }, { "code": null, "e": 12475, "s": 12328, "text": "The models in this tutorial are derived from ssd_mobilenet_v3_small_coco and ssd_mobilenet_edgetpu_coco in the TensorFlow Detection Model Zoo. 🦁🦄🐼" }, { "code": null, "e": 12572, "s": 12475, "text": "My models are available for download via Github releases notes @ leigh-johnson/rpi-deep-pantilt." }, { "code": null, "e": 12810, "s": 12572, "text": "I added the custom TFLite_Detection_PostProcess operation, which implements a variation of Non-maximum Suppression (NMS) on model output. Non-maximum Suppression is technique that filters many bounding box proposals using set operations." }, { "code": null, "e": 12933, "s": 12810, "text": "Looking for more hands-on examples of Machine Learning for Raspberry Pi and other small device? Sign up for my newsletter!" }, { "code": null, "e": 13082, "s": 12933, "text": "I publish examples of real-world ML applications (with full source code) and nifty tricks like automating away the pains of bounding-box annotation." }, { "code": null, "e": 13235, "s": 13082, "text": "MobileNetEdgeTPU SSDLite contributors: Yunyang Xiong, Bo Chen, Suyog Gupta, Hanxiao Liu, Gabriel Bender, Mingxing Tan, Berkin Akin, Zhichao Lu, Quoc Le." }, { "code": null, "e": 13320, "s": 13235, "text": "MobileNetV3 SSDLite contributors: Bo Chen, Zhichao Lu, Vivek Rathod, Jonathan Huang." }, { "code": null, "e": 13472, "s": 13320, "text": "Special thanks to Adrian Rosebrock for writing Pan/tilt face tracking with a Raspberry Pi and OpenCV, which was the inspiration for this whole project!" } ]
Collocations in NLP using NLTK library | by Shubhanshu Gupta | Towards Data Science
Collocations are phrases or expressions containing multiple words, that are highly likely to co-occur. For example — ‘social media’, ‘school holiday’, ‘machine learning’, ‘Universal Studios Singapore’, etc. Imagine, having a requirement wherein you want to understand the text reviews left by your customers. You want to understand the behavioural insights like who are your customers, how many of them visit your place, what are they interested in, what do they buy, what activities do they engage with, etc. For more simplicity, let’s consider that you have a restaurant and you have several thousand reviews. Thus, as a restaurant owner you need to understand the behavioural insights of your customers, as discussed above. Using Named Entity Recognition, I extracted certain interesting entities in the PERSON, EVENT, DATE, PRODUCT categories. Such as, ‘Saturday’ in DATE. I then wanted to find out what people are writing around ‘Saturday’ in their reviews! Thus, I narrowed down on several such broad themes such as ‘family’, ‘couple’, ‘holiday’, ‘brunch’, etc. Collocations helped me in fetching the two or three words that are highly likely to co-occur around these themes. These two or three words that occur together are also known as BiGram and TriGram. The set of two words that co-occur as BiGrams, and the set of three words that co-occur as TriGrams, may not give us meaningful phrases. For example, the sentence ‘He applied machine learning’ contains bigrams: ‘He applied’, ‘applied machine’, ‘machine learning’. ‘He applied’ and ‘applied machine’ do not mean anything, while ‘machine learning’ is a meaningful bigram. Just considering co-occurring words may not be a good idea, since phrases such as ‘of the’ may co-occur frequently, but are actually not meaningful. Thus, the need for collocations from NLTK library. It only gives us the meaningful BiGrams and TriGrams. Oh! So you basically want to know how the scoring works? Well, I used Pointwise Mutual Information or PMI score. Discussing what’s PMI and how is it computed is not the scope of this blog, but here are some great articles which you can read to understand more: Article 1 and Article 2. I used the PMI scores to quantify and rank the BiGrams, TriGrams churned out by Collocations library. As I mentioned earlier, I wanted to find out what do people write around certain themes such as some particular dates or events or person. So, from my code you will be able to see BiGrams, TriGrams around specific words. That is, I want to know BiGrams, TriGrams that are highly likely to formulate besides a ‘specific word’ of my choice. That specific word is nothing but the theme that we got from Named Entity Recognition. import nltkfrom nltk.collocations import *bigram_measures = nltk.collocations.BigramAssocMeasures()# Ngrams with 'creature' as a membercreature_filter = lambda *w: 'kids' not in w## Bigramsfinder = BigramCollocationFinder.from_words( filtered_sentences)# only bigrams that appear 3+ timesfinder.apply_freq_filter(3)# only bigrams that contain 'creature'finder.apply_ngram_filter(creature_filter)# return the 10 n-grams with the highest PMI# print (finder.nbest(bigram_measures.likelihood_ratio, 10))for i in finder.score_ngrams(bigram_measures.likelihood_ratio): print (i) The result shows that people write about ‘kids menu’, ‘kids running’, ‘kids meal’ in their reviews. Now let’s see the TriGrams around ‘kids’. ## Trigramstrigram_measures = nltk.collocations.TrigramAssocMeasures()# Ngrams with 'creature' as a membercreature_filter = lambda *w: 'kids' not in wfinder = TrigramCollocationFinder.from_words( filtered_sentences)# only trigrams that appear 3+ timesfinder.apply_freq_filter(3)# only trigrams that contain 'creature'finder.apply_ngram_filter(creature_filter)# return the 10 n-grams with the highest PMI# print (finder.nbest(trigram_measures.likelihood_ratio, 10))for i in finder.score_ngrams(trigram_measures.likelihood_ratio): print (i) The code output gives a deeper insight into the BiGrams we just mined above. So, ‘kids menu available’ and ‘Great kids menu’ is an extension of ‘kids menu’, which shows that people applaud a restaurant for having a kids menu. Similarly, ‘kids running’ is associated with a negative connotation ‘kids running screaming’. That means, the guests in the restaurants are probably not having the best of their time when there are kids running and screaming around. This wraps up my demo and explanation for application of Collocations in NLP provided by NLTK library. I hope this blog was helpful to you. Please let me know if you used a different approach for scoring or extracting Collocations. Thanks for reading and I have written other posts related to software engineering and data science as well. You might want to check them out here. You can also subscribe to my blog to receive relevant blogs straight in your inbox.
[ { "code": null, "e": 379, "s": 172, "text": "Collocations are phrases or expressions containing multiple words, that are highly likely to co-occur. For example — ‘social media’, ‘school holiday’, ‘machine learning’, ‘Universal Studios Singapore’, etc." }, { "code": null, "e": 682, "s": 379, "text": "Imagine, having a requirement wherein you want to understand the text reviews left by your customers. You want to understand the behavioural insights like who are your customers, how many of them visit your place, what are they interested in, what do they buy, what activities do they engage with, etc." }, { "code": null, "e": 899, "s": 682, "text": "For more simplicity, let’s consider that you have a restaurant and you have several thousand reviews. Thus, as a restaurant owner you need to understand the behavioural insights of your customers, as discussed above." }, { "code": null, "e": 1135, "s": 899, "text": "Using Named Entity Recognition, I extracted certain interesting entities in the PERSON, EVENT, DATE, PRODUCT categories. Such as, ‘Saturday’ in DATE. I then wanted to find out what people are writing around ‘Saturday’ in their reviews!" }, { "code": null, "e": 1437, "s": 1135, "text": "Thus, I narrowed down on several such broad themes such as ‘family’, ‘couple’, ‘holiday’, ‘brunch’, etc. Collocations helped me in fetching the two or three words that are highly likely to co-occur around these themes. These two or three words that occur together are also known as BiGram and TriGram." }, { "code": null, "e": 2061, "s": 1437, "text": "The set of two words that co-occur as BiGrams, and the set of three words that co-occur as TriGrams, may not give us meaningful phrases. For example, the sentence ‘He applied machine learning’ contains bigrams: ‘He applied’, ‘applied machine’, ‘machine learning’. ‘He applied’ and ‘applied machine’ do not mean anything, while ‘machine learning’ is a meaningful bigram. Just considering co-occurring words may not be a good idea, since phrases such as ‘of the’ may co-occur frequently, but are actually not meaningful. Thus, the need for collocations from NLTK library. It only gives us the meaningful BiGrams and TriGrams." }, { "code": null, "e": 2449, "s": 2061, "text": "Oh! So you basically want to know how the scoring works? Well, I used Pointwise Mutual Information or PMI score. Discussing what’s PMI and how is it computed is not the scope of this blog, but here are some great articles which you can read to understand more: Article 1 and Article 2. I used the PMI scores to quantify and rank the BiGrams, TriGrams churned out by Collocations library." }, { "code": null, "e": 2875, "s": 2449, "text": "As I mentioned earlier, I wanted to find out what do people write around certain themes such as some particular dates or events or person. So, from my code you will be able to see BiGrams, TriGrams around specific words. That is, I want to know BiGrams, TriGrams that are highly likely to formulate besides a ‘specific word’ of my choice. That specific word is nothing but the theme that we got from Named Entity Recognition." }, { "code": null, "e": 3453, "s": 2875, "text": "import nltkfrom nltk.collocations import *bigram_measures = nltk.collocations.BigramAssocMeasures()# Ngrams with 'creature' as a membercreature_filter = lambda *w: 'kids' not in w## Bigramsfinder = BigramCollocationFinder.from_words( filtered_sentences)# only bigrams that appear 3+ timesfinder.apply_freq_filter(3)# only bigrams that contain 'creature'finder.apply_ngram_filter(creature_filter)# return the 10 n-grams with the highest PMI# print (finder.nbest(bigram_measures.likelihood_ratio, 10))for i in finder.score_ngrams(bigram_measures.likelihood_ratio): print (i)" }, { "code": null, "e": 3595, "s": 3453, "text": "The result shows that people write about ‘kids menu’, ‘kids running’, ‘kids meal’ in their reviews. Now let’s see the TriGrams around ‘kids’." }, { "code": null, "e": 4139, "s": 3595, "text": "## Trigramstrigram_measures = nltk.collocations.TrigramAssocMeasures()# Ngrams with 'creature' as a membercreature_filter = lambda *w: 'kids' not in wfinder = TrigramCollocationFinder.from_words( filtered_sentences)# only trigrams that appear 3+ timesfinder.apply_freq_filter(3)# only trigrams that contain 'creature'finder.apply_ngram_filter(creature_filter)# return the 10 n-grams with the highest PMI# print (finder.nbest(trigram_measures.likelihood_ratio, 10))for i in finder.score_ngrams(trigram_measures.likelihood_ratio): print (i)" }, { "code": null, "e": 4598, "s": 4139, "text": "The code output gives a deeper insight into the BiGrams we just mined above. So, ‘kids menu available’ and ‘Great kids menu’ is an extension of ‘kids menu’, which shows that people applaud a restaurant for having a kids menu. Similarly, ‘kids running’ is associated with a negative connotation ‘kids running screaming’. That means, the guests in the restaurants are probably not having the best of their time when there are kids running and screaming around." }, { "code": null, "e": 4830, "s": 4598, "text": "This wraps up my demo and explanation for application of Collocations in NLP provided by NLTK library. I hope this blog was helpful to you. Please let me know if you used a different approach for scoring or extracting Collocations." } ]
Output of Java Program | Set 11 - GeeksforGeeks
09 Jun, 2020 Predict the output of following Java programs: Question 1 : public class Base{ private int data; public Base() { data = 5; } public int getData() { return this.data; }} class Derived extends Base{ private int data; public Derived() { data = 6; } private int getData() { return data; } public static void main(String[] args) { Derived myData = new Derived(); System.out.println(myData.getData()); }} a) 6b) 5c) Compile time errord) Run time error Answer (c)Explanation: When overriding a method of superclass, the method declaration in subclass cannot be more restrictive than that declared in the superclass. Question 2 : public class Test{ private int data = 5; public int getData() { return this.data; } public int getData(int value) { return (data+1); } public int getData(int... value) { return (data+2); } public static void main(String[] args) { Test temp = new Test(); System.out.println(temp.getData(7, 8, 12)); }} a) Either Compile time or Runtime errorb) 8c) 10d) 7 Answer (d)Explanation : (int... values) is passed as parameter to a method when you are not aware of the number of input parameter but know that the type of parameter(in this case it is int). When a new object is made in the main method, variable data is initialized to 5. A call to getData() method with attributes (7, 8 ,12), makes a call to the third getData() method, which increments the value of data variable by 2 and return 7. Question 3: public class Base{ private int multiplier(int data) { return data*5; }} class Derived extends Base{ private static int data; public Derived() { data = 25; } public static void main(String[] args) { Base temp = new Derived(); System.out.println(temp.multiplier(data)); }} a) 125b) 25c) Runtime errord) Compile time error Answer (d)Explanation: Since the method multiplier is marked as private, it isn’t inherited and therefore is not visible to the Derived. Question 4:Which of the following is FALSE about finally block?a) For each try block, there can be only 1 finally block.b) finally block will not be executed if program exits by calling System.exit();c) If an exception is not handled in the catch statement, before terminating the program, JVM executes the finally blockd) finally block contains important code segment and so the code inside finally block is executed with/without the presence of try block in java code. Answer (d)Explanation:Statement (d) is false because finally blocks can exist only if it succeeds try or a catch block. Using a finally block without try block would give a compile time error. Question 5: import java.io.IOException;import java.util.EmptyStackException; public class newclass{ public static void main(String[] args) { try { System.out.printf("%d", 1); throw(new Exception()); } catch(IOException e) { System.out.printf("%d", 2); } catch(EmptyStackException e) { System.out.printf("%d", 3); } catch(Exception e) { System.out.printf("%d", 4); } finally { System.out.printf("%d", 5); } }} a) 12345b) 15c) 135d) 145 Answer (d)Explanation: The catch statements are written in the order: more specific to more general. In the code above, a new exception of type Exception is thrown. First the code jumps to first catch block to look for exception handler. But since the IOException is notof the same type it is moves down to second catch block and finally to the third, wherethe exception is caught and 4 is printed. Therefore, the answer is 145, as the orderof execution in terms of blocks is: try->catch->finally. Question 6: public class javaclass{ static { System.out.printf("%d", 1); } static { System.out.printf("%d", 2); } static { System.out.printf("%d", 3); } private static int myMethod() { return 4; } private int function() { return 5; } public static void main(String[] args) { System.out.printf("%d", (new javaclass()).function() + myMethod()); }} a) 123b) 45c) 12345d) 1239 Answer (d)Explanation:static blocks in Java are executed even before the call to main is made by the compiler. In the main method, a new object of javaclass is made and its function() method is called which return 5 and the static method myMethod() returns 4 i.e., 4+5 = 9. Therefore, the output of the program is 1239, because 123 is printed on the console even before main method executes and main method on execution returns 9. This article is contributed by Mayank. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. user_blzg Java-Output Java Program Output Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Interfaces in Java ArrayList in Java Stack Class in Java Singleton Class in Java Arrow operator -> in C/C++ with Examples Output of Java Program | Set 1 delete keyword in C++ Output of C Programs | Set 1 Different ways to copy a string in C/C++
[ { "code": null, "e": 25805, "s": 25777, "text": "\n09 Jun, 2020" }, { "code": null, "e": 25852, "s": 25805, "text": "Predict the output of following Java programs:" }, { "code": null, "e": 25865, "s": 25852, "text": "Question 1 :" }, { "code": "public class Base{ private int data; public Base() { data = 5; } public int getData() { return this.data; }} class Derived extends Base{ private int data; public Derived() { data = 6; } private int getData() { return data; } public static void main(String[] args) { Derived myData = new Derived(); System.out.println(myData.getData()); }}", "e": 26304, "s": 25865, "text": null }, { "code": null, "e": 26351, "s": 26304, "text": "a) 6b) 5c) Compile time errord) Run time error" }, { "code": null, "e": 26514, "s": 26351, "text": "Answer (c)Explanation: When overriding a method of superclass, the method declaration in subclass cannot be more restrictive than that declared in the superclass." }, { "code": null, "e": 26527, "s": 26514, "text": "Question 2 :" }, { "code": "public class Test{ private int data = 5; public int getData() { return this.data; } public int getData(int value) { return (data+1); } public int getData(int... value) { return (data+2); } public static void main(String[] args) { Test temp = new Test(); System.out.println(temp.getData(7, 8, 12)); }}", "e": 26907, "s": 26527, "text": null }, { "code": null, "e": 26960, "s": 26907, "text": "a) Either Compile time or Runtime errorb) 8c) 10d) 7" }, { "code": null, "e": 27395, "s": 26960, "text": "Answer (d)Explanation : (int... values) is passed as parameter to a method when you are not aware of the number of input parameter but know that the type of parameter(in this case it is int). When a new object is made in the main method, variable data is initialized to 5. A call to getData() method with attributes (7, 8 ,12), makes a call to the third getData() method, which increments the value of data variable by 2 and return 7." }, { "code": null, "e": 27407, "s": 27395, "text": "Question 3:" }, { "code": "public class Base{ private int multiplier(int data) { return data*5; }} class Derived extends Base{ private static int data; public Derived() { data = 25; } public static void main(String[] args) { Base temp = new Derived(); System.out.println(temp.multiplier(data)); }}", "e": 27737, "s": 27407, "text": null }, { "code": null, "e": 27786, "s": 27737, "text": "a) 125b) 25c) Runtime errord) Compile time error" }, { "code": null, "e": 27923, "s": 27786, "text": "Answer (d)Explanation: Since the method multiplier is marked as private, it isn’t inherited and therefore is not visible to the Derived." }, { "code": null, "e": 28394, "s": 27923, "text": "Question 4:Which of the following is FALSE about finally block?a) For each try block, there can be only 1 finally block.b) finally block will not be executed if program exits by calling System.exit();c) If an exception is not handled in the catch statement, before terminating the program, JVM executes the finally blockd) finally block contains important code segment and so the code inside finally block is executed with/without the presence of try block in java code." }, { "code": null, "e": 28587, "s": 28394, "text": "Answer (d)Explanation:Statement (d) is false because finally blocks can exist only if it succeeds try or a catch block. Using a finally block without try block would give a compile time error." }, { "code": null, "e": 28599, "s": 28587, "text": "Question 5:" }, { "code": "import java.io.IOException;import java.util.EmptyStackException; public class newclass{ public static void main(String[] args) { try { System.out.printf(\"%d\", 1); throw(new Exception()); } catch(IOException e) { System.out.printf(\"%d\", 2); } catch(EmptyStackException e) { System.out.printf(\"%d\", 3); } catch(Exception e) { System.out.printf(\"%d\", 4); } finally { System.out.printf(\"%d\", 5); } }}", "e": 29177, "s": 28599, "text": null }, { "code": null, "e": 29203, "s": 29177, "text": "a) 12345b) 15c) 135d) 145" }, { "code": null, "e": 29701, "s": 29203, "text": "Answer (d)Explanation: The catch statements are written in the order: more specific to more general. In the code above, a new exception of type Exception is thrown. First the code jumps to first catch block to look for exception handler. But since the IOException is notof the same type it is moves down to second catch block and finally to the third, wherethe exception is caught and 4 is printed. Therefore, the answer is 145, as the orderof execution in terms of blocks is: try->catch->finally." }, { "code": null, "e": 29713, "s": 29701, "text": "Question 6:" }, { "code": "public class javaclass{ static { System.out.printf(\"%d\", 1); } static { System.out.printf(\"%d\", 2); } static { System.out.printf(\"%d\", 3); } private static int myMethod() { return 4; } private int function() { return 5; } public static void main(String[] args) { System.out.printf(\"%d\", (new javaclass()).function() + myMethod()); }}", "e": 30145, "s": 29713, "text": null }, { "code": null, "e": 30172, "s": 30145, "text": "a) 123b) 45c) 12345d) 1239" }, { "code": null, "e": 30603, "s": 30172, "text": "Answer (d)Explanation:static blocks in Java are executed even before the call to main is made by the compiler. In the main method, a new object of javaclass is made and its function() method is called which return 5 and the static method myMethod() returns 4 i.e., 4+5 = 9. Therefore, the output of the program is 1239, because 123 is printed on the console even before main method executes and main method on execution returns 9." }, { "code": null, "e": 30897, "s": 30603, "text": "This article is contributed by Mayank. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 31022, "s": 30897, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 31032, "s": 31022, "text": "user_blzg" }, { "code": null, "e": 31044, "s": 31032, "text": "Java-Output" }, { "code": null, "e": 31049, "s": 31044, "text": "Java" }, { "code": null, "e": 31064, "s": 31049, "text": "Program Output" }, { "code": null, "e": 31069, "s": 31064, "text": "Java" }, { "code": null, "e": 31167, "s": 31069, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31182, "s": 31167, "text": "Stream In Java" }, { "code": null, "e": 31201, "s": 31182, "text": "Interfaces in Java" }, { "code": null, "e": 31219, "s": 31201, "text": "ArrayList in Java" }, { "code": null, "e": 31239, "s": 31219, "text": "Stack Class in Java" }, { "code": null, "e": 31263, "s": 31239, "text": "Singleton Class in Java" }, { "code": null, "e": 31304, "s": 31263, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 31335, "s": 31304, "text": "Output of Java Program | Set 1" }, { "code": null, "e": 31357, "s": 31335, "text": "delete keyword in C++" }, { "code": null, "e": 31386, "s": 31357, "text": "Output of C Programs | Set 1" } ]
Maximum number on 7-segment display using N segments : Recursive - GeeksforGeeks
10 Jun, 2021 Given an integer N, the task is to find the largest number that can be shown with the help of N segments using any number of 7 segment displays.Examples: Input: N = 4 Output: 11 Explanation: Largest number that can be displayed with the help of 4 segments using 2 seven segment displays turned is 11. Input: N = 7 Output: 711 Explanation: Largest number that can be displayed by turning on seven segments is 711 with the help of 3 segments display set. Approach: The key observation in seven segment display is to turn on any number from 0 to 9 takes certain amounts of segments, which is described below: If the problem is observed carefully, then the number N can be of two types that is even or odd and each of them should be solved separately as follows: For Even: As in the above image, There are 6 numbers that can be displayed using even number of segments which is 0 - 6 1 - 2 2 - 5 4 - 4 6 - 6 9 - 6 As it is observed number 1 uses the minimum count of segments to display a digit. Then, even the number of segments can be displayed using 1 with 2 counts of segments in each digit. For Odd: As in the above image, there are 5 numbers that can be displayed using an odd number of segments which is 3 - 5 5 - 5 7 - 3 8 - 7 As it is observed number 7 uses the minimum number of odd segments to display a digit. Then an odd number of segments can be displayed using 7 with 3 counts of segments in each digit. Algorithm: If the given number N is 0 or 1, then any number cannot be displayed with this much of bits. If the given number N is odd then the most significant digit will be 7 and the rest of the digits can be displayed with the help of the (N – 3) segments because to display 7 it takes 3 segments. If given number N is even then the most significant digit will be 1 and the rest of the digits can be displayed with the help of the (N – 2) segments because to display 1, it takes 2 segments only. The number N is processed digit by digit recursively. Explanation with Example: Given number N be – 11 Then, the largest number will be 71111.Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation to find the// maximum number that can be// using the N segments in// N segments display #include <iostream>using namespace std; // Function to find the maximum// number that can be displayed// using the N segmentsvoid segments(int n){ // Condition to check base case if (n == 1 || n == 0) { return; } // Condition to check if the // number is even if (n % 2 == 0) { cout << "1"; segments(n - 2); } // Condition to check if the // number is odd else if (n % 2 == 1) { cout << "7"; segments(n - 3); }} // Driver Codeint main(){ int n; n = 11; segments(n); return 0;} // Java implementation to find the// maximum number that can be// using the N segments in// N segments displayclass GFG { // Function to find the maximum // number that can be displayed // using the N segments static void segments(int n) { // Condition to check base case if (n == 1 || n == 0) { return; } // Condition to check if the // number is even if (n % 2 == 0) { System.out.print("1"); segments(n - 2); } // Condition to check if the // number is odd else if (n % 2 == 1) { System.out.print("7"); segments(n - 3); } } // Driver Code public static void main (String[] args) { int n; n = 11; segments(n); }} // This code is contributed by AnkitRai01 # Python3 implementation to find the# maximum number that can be# using the N segments in# N segments display # Function to find the maximum# number that can be displayed# using the N segmentsdef segments(n) : # Condition to check base case if (n == 1 or n == 0) : return; # Condition to check if the # number is even if (n % 2 == 0) : print("1",end=""); segments(n - 2); # Condition to check if the # number is odd elif (n % 2 == 1) : print("7",end=""); segments(n - 3); # Driver Codeif __name__ == "__main__" : n = 11; segments(n); # This code is contributed by AnkitRai01 // C# implementation to find the// maximum number that can be// using the N segments in// N segments displayusing System; class GFG { // Function to find the maximum // number that can be displayed // using the N segments static void segments(int n) { // Condition to check base case if (n == 1 || n == 0) { return; } // Condition to check if the // number is even if (n % 2 == 0) { Console.Write("1"); segments(n - 2); } // Condition to check if the // number is odd else if (n % 2 == 1) { Console.Write("7"); segments(n - 3); } } // Driver Code public static void Main() { int n; n = 11; segments(n); }} // This code is contributed by AnkitRai01 <script> // Javascript implementation to find the // maximum number that can be // using the N segments in // N segments display // Function to find the maximum // number that can be displayed // using the N segments function segments(n) { // Condition to check base case if (n == 1 || n == 0) { return; } // Condition to check if the // number is even if (n % 2 == 0) { document.write("1"); segments(n - 2); } // Condition to check if the // number is odd else if (n % 2 == 1) { document.write("7"); segments(n - 3); } } let n; n = 11; segments(n); // This code is contributed by divyesh072019.</script> 71111 Performance Analysis: Time Complexity: As in the above approach, there is recursive call which takes O(N) time in worst case, Hence the Time Complexity will be O(N). Auxiliary Space Complexity: As in the above approach, taking consideration of the stack space used in recursive call then the auxiliary space complexity will be O(N) ankthon Akanksha_Rai divyesh072019 Greedy Recursion Greedy Recursion Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Huffman Coding | Greedy Algo-3 Coin Change | DP-7 Program for Shortest Job First (or SJF) CPU Scheduling | Set 1 (Non- preemptive) Fractional Knapsack Problem Activity Selection Problem | Greedy Algo-1 Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) Recursion Program for Tower of Hanoi Backtracking | Introduction Print all possible combinations of r elements in a given array of size n
[ { "code": null, "e": 27312, "s": 27284, "text": "\n10 Jun, 2021" }, { "code": null, "e": 27468, "s": 27312, "text": "Given an integer N, the task is to find the largest number that can be shown with the help of N segments using any number of 7 segment displays.Examples: " }, { "code": null, "e": 27617, "s": 27468, "text": "Input: N = 4 Output: 11 Explanation: Largest number that can be displayed with the help of 4 segments using 2 seven segment displays turned is 11. " }, { "code": null, "e": 27771, "s": 27617, "text": "Input: N = 7 Output: 711 Explanation: Largest number that can be displayed by turning on seven segments is 711 with the help of 3 segments display set. " }, { "code": null, "e": 27928, "s": 27773, "text": "Approach: The key observation in seven segment display is to turn on any number from 0 to 9 takes certain amounts of segments, which is described below: " }, { "code": null, "e": 28083, "s": 27928, "text": "If the problem is observed carefully, then the number N can be of two types that is even or odd and each of them should be solved separately as follows: " }, { "code": null, "e": 28199, "s": 28083, "text": "For Even: As in the above image, There are 6 numbers that can be displayed using even number of segments which is " }, { "code": null, "e": 28235, "s": 28199, "text": "0 - 6\n1 - 2\n2 - 5\n4 - 4\n6 - 6\n9 - 6" }, { "code": null, "e": 28419, "s": 28235, "text": "As it is observed number 1 uses the minimum count of segments to display a digit. Then, even the number of segments can be displayed using 1 with 2 counts of segments in each digit. " }, { "code": null, "e": 28536, "s": 28419, "text": "For Odd: As in the above image, there are 5 numbers that can be displayed using an odd number of segments which is " }, { "code": null, "e": 28560, "s": 28536, "text": "3 - 5\n5 - 5\n7 - 3\n8 - 7" }, { "code": null, "e": 28746, "s": 28560, "text": "As it is observed number 7 uses the minimum number of odd segments to display a digit. Then an odd number of segments can be displayed using 7 with 3 counts of segments in each digit. " }, { "code": null, "e": 28759, "s": 28746, "text": "Algorithm: " }, { "code": null, "e": 28852, "s": 28759, "text": "If the given number N is 0 or 1, then any number cannot be displayed with this much of bits." }, { "code": null, "e": 29047, "s": 28852, "text": "If the given number N is odd then the most significant digit will be 7 and the rest of the digits can be displayed with the help of the (N – 3) segments because to display 7 it takes 3 segments." }, { "code": null, "e": 29245, "s": 29047, "text": "If given number N is even then the most significant digit will be 1 and the rest of the digits can be displayed with the help of the (N – 2) segments because to display 1, it takes 2 segments only." }, { "code": null, "e": 29299, "s": 29245, "text": "The number N is processed digit by digit recursively." }, { "code": null, "e": 29350, "s": 29299, "text": "Explanation with Example: Given number N be – 11 " }, { "code": null, "e": 29441, "s": 29350, "text": "Then, the largest number will be 71111.Below is the implementation of the above approach: " }, { "code": null, "e": 29445, "s": 29441, "text": "C++" }, { "code": null, "e": 29450, "s": 29445, "text": "Java" }, { "code": null, "e": 29458, "s": 29450, "text": "Python3" }, { "code": null, "e": 29461, "s": 29458, "text": "C#" }, { "code": null, "e": 29472, "s": 29461, "text": "Javascript" }, { "code": "// C++ implementation to find the// maximum number that can be// using the N segments in// N segments display #include <iostream>using namespace std; // Function to find the maximum// number that can be displayed// using the N segmentsvoid segments(int n){ // Condition to check base case if (n == 1 || n == 0) { return; } // Condition to check if the // number is even if (n % 2 == 0) { cout << \"1\"; segments(n - 2); } // Condition to check if the // number is odd else if (n % 2 == 1) { cout << \"7\"; segments(n - 3); }} // Driver Codeint main(){ int n; n = 11; segments(n); return 0;}", "e": 30145, "s": 29472, "text": null }, { "code": "// Java implementation to find the// maximum number that can be// using the N segments in// N segments displayclass GFG { // Function to find the maximum // number that can be displayed // using the N segments static void segments(int n) { // Condition to check base case if (n == 1 || n == 0) { return; } // Condition to check if the // number is even if (n % 2 == 0) { System.out.print(\"1\"); segments(n - 2); } // Condition to check if the // number is odd else if (n % 2 == 1) { System.out.print(\"7\"); segments(n - 3); } } // Driver Code public static void main (String[] args) { int n; n = 11; segments(n); }} // This code is contributed by AnkitRai01", "e": 31008, "s": 30145, "text": null }, { "code": "# Python3 implementation to find the# maximum number that can be# using the N segments in# N segments display # Function to find the maximum# number that can be displayed# using the N segmentsdef segments(n) : # Condition to check base case if (n == 1 or n == 0) : return; # Condition to check if the # number is even if (n % 2 == 0) : print(\"1\",end=\"\"); segments(n - 2); # Condition to check if the # number is odd elif (n % 2 == 1) : print(\"7\",end=\"\"); segments(n - 3); # Driver Codeif __name__ == \"__main__\" : n = 11; segments(n); # This code is contributed by AnkitRai01", "e": 31661, "s": 31008, "text": null }, { "code": "// C# implementation to find the// maximum number that can be// using the N segments in// N segments displayusing System; class GFG { // Function to find the maximum // number that can be displayed // using the N segments static void segments(int n) { // Condition to check base case if (n == 1 || n == 0) { return; } // Condition to check if the // number is even if (n % 2 == 0) { Console.Write(\"1\"); segments(n - 2); } // Condition to check if the // number is odd else if (n % 2 == 1) { Console.Write(\"7\"); segments(n - 3); } } // Driver Code public static void Main() { int n; n = 11; segments(n); }} // This code is contributed by AnkitRai01", "e": 32516, "s": 31661, "text": null }, { "code": "<script> // Javascript implementation to find the // maximum number that can be // using the N segments in // N segments display // Function to find the maximum // number that can be displayed // using the N segments function segments(n) { // Condition to check base case if (n == 1 || n == 0) { return; } // Condition to check if the // number is even if (n % 2 == 0) { document.write(\"1\"); segments(n - 2); } // Condition to check if the // number is odd else if (n % 2 == 1) { document.write(\"7\"); segments(n - 3); } } let n; n = 11; segments(n); // This code is contributed by divyesh072019.</script>", "e": 33320, "s": 32516, "text": null }, { "code": null, "e": 33326, "s": 33320, "text": "71111" }, { "code": null, "e": 33352, "s": 33328, "text": "Performance Analysis: " }, { "code": null, "e": 33496, "s": 33352, "text": "Time Complexity: As in the above approach, there is recursive call which takes O(N) time in worst case, Hence the Time Complexity will be O(N)." }, { "code": null, "e": 33662, "s": 33496, "text": "Auxiliary Space Complexity: As in the above approach, taking consideration of the stack space used in recursive call then the auxiliary space complexity will be O(N)" }, { "code": null, "e": 33672, "s": 33664, "text": "ankthon" }, { "code": null, "e": 33685, "s": 33672, "text": "Akanksha_Rai" }, { "code": null, "e": 33699, "s": 33685, "text": "divyesh072019" }, { "code": null, "e": 33706, "s": 33699, "text": "Greedy" }, { "code": null, "e": 33716, "s": 33706, "text": "Recursion" }, { "code": null, "e": 33723, "s": 33716, "text": "Greedy" }, { "code": null, "e": 33733, "s": 33723, "text": "Recursion" }, { "code": null, "e": 33831, "s": 33733, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33862, "s": 33831, "text": "Huffman Coding | Greedy Algo-3" }, { "code": null, "e": 33881, "s": 33862, "text": "Coin Change | DP-7" }, { "code": null, "e": 33962, "s": 33881, "text": "Program for Shortest Job First (or SJF) CPU Scheduling | Set 1 (Non- preemptive)" }, { "code": null, "e": 33990, "s": 33962, "text": "Fractional Knapsack Problem" }, { "code": null, "e": 34033, "s": 33990, "text": "Activity Selection Problem | Greedy Algo-1" }, { "code": null, "e": 34118, "s": 34033, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 34128, "s": 34118, "text": "Recursion" }, { "code": null, "e": 34155, "s": 34128, "text": "Program for Tower of Hanoi" }, { "code": null, "e": 34183, "s": 34155, "text": "Backtracking | Introduction" } ]
C# Program for Count set bits in an integer - GeeksforGeeks
02 Jan, 2019 Write an efficient program to count number of 1s in binary representation of an integer. Examples : Input : n = 6 Output : 2 Binary representation of 6 is 110 and has 2 set bits Input : n = 13 Output : 3 Binary representation of 11 is 1101 and has 3 set bits 1. Simple Method Loop through all bits in an integer, check if a bit is set and if it is then increment the set bit count. See below program. C# // C# program to Count set// bits in an integerusing System; class GFG { // Function to get no of set // bits in binary representation // of positive integer n static int countSetBits(int n) { int count = 0; while (n > 0) { count += n & 1; n >>= 1; } return count; } // Driver Code public static void Main() { int i = 9; Console.Write(countSetBits(i)); }} // This code is contributed by Sam007 2 Recursive Approach : C# // C# implementation of recursive// approach to find the number of// set bits in binary representation// of positive integer nusing System; class GFG { // recursive function // to count set bits public static int countSetBits(int n) { // base case if (n == 0) return 0; else // if last bit set // add 1 else add 0 return (n & 1) + countSetBits(n >> 1); } // Driver code static public void Main() { // get value // from user int n = 9; // function calling Console.WriteLine(countSetBits(n)); }} // This code is contributed by aj_36 2 Please refer complete article on Count set bits in an integer for more details! C# Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C# Program to Check a Specified Type is an Enum or Not C# Program to Sort a List of Integers Using the LINQ OrderBy() Method C# Program to Read and Write a Byte Array to File using FileStream Class How to Sort Object Array By Specific Property in C#? C# Program to Delete an Empty and a Non-Empty Directory C# Program to Print the Current Assembly Name Using GetExecutingAssembly() Method C# Program to Implement IComparable Interface C# Program to Check a Specified Type is a Primitive Data Type or Not C# - Reading Lines From a File Until the End of File is Reached C# - Copying the Contents From One File to Another File
[ { "code": null, "e": 26519, "s": 26491, "text": "\n02 Jan, 2019" }, { "code": null, "e": 26608, "s": 26519, "text": "Write an efficient program to count number of 1s in binary representation of an integer." }, { "code": null, "e": 26619, "s": 26608, "text": "Examples :" }, { "code": null, "e": 26780, "s": 26619, "text": "Input : n = 6\nOutput : 2\nBinary representation of 6 is 110 and has 2 set bits\n\nInput : n = 13\nOutput : 3\nBinary representation of 11 is 1101 and has 3 set bits\n" }, { "code": null, "e": 26922, "s": 26780, "text": "1. Simple Method Loop through all bits in an integer, check if a bit is set and if it is then increment the set bit count. See below program." }, { "code": null, "e": 26925, "s": 26922, "text": "C#" }, { "code": "// C# program to Count set// bits in an integerusing System; class GFG { // Function to get no of set // bits in binary representation // of positive integer n static int countSetBits(int n) { int count = 0; while (n > 0) { count += n & 1; n >>= 1; } return count; } // Driver Code public static void Main() { int i = 9; Console.Write(countSetBits(i)); }} // This code is contributed by Sam007", "e": 27417, "s": 26925, "text": null }, { "code": null, "e": 27420, "s": 27417, "text": "2\n" }, { "code": null, "e": 27441, "s": 27420, "text": "Recursive Approach :" }, { "code": null, "e": 27444, "s": 27441, "text": "C#" }, { "code": "// C# implementation of recursive// approach to find the number of// set bits in binary representation// of positive integer nusing System; class GFG { // recursive function // to count set bits public static int countSetBits(int n) { // base case if (n == 0) return 0; else // if last bit set // add 1 else add 0 return (n & 1) + countSetBits(n >> 1); } // Driver code static public void Main() { // get value // from user int n = 9; // function calling Console.WriteLine(countSetBits(n)); }} // This code is contributed by aj_36", "e": 28118, "s": 27444, "text": null }, { "code": null, "e": 28121, "s": 28118, "text": "2\n" }, { "code": null, "e": 28201, "s": 28121, "text": "Please refer complete article on Count set bits in an integer for more details!" }, { "code": null, "e": 28213, "s": 28201, "text": "C# Programs" }, { "code": null, "e": 28311, "s": 28213, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28366, "s": 28311, "text": "C# Program to Check a Specified Type is an Enum or Not" }, { "code": null, "e": 28436, "s": 28366, "text": "C# Program to Sort a List of Integers Using the LINQ OrderBy() Method" }, { "code": null, "e": 28509, "s": 28436, "text": "C# Program to Read and Write a Byte Array to File using FileStream Class" }, { "code": null, "e": 28562, "s": 28509, "text": "How to Sort Object Array By Specific Property in C#?" }, { "code": null, "e": 28618, "s": 28562, "text": "C# Program to Delete an Empty and a Non-Empty Directory" }, { "code": null, "e": 28700, "s": 28618, "text": "C# Program to Print the Current Assembly Name Using GetExecutingAssembly() Method" }, { "code": null, "e": 28746, "s": 28700, "text": "C# Program to Implement IComparable Interface" }, { "code": null, "e": 28815, "s": 28746, "text": "C# Program to Check a Specified Type is a Primitive Data Type or Not" }, { "code": null, "e": 28879, "s": 28815, "text": "C# - Reading Lines From a File Until the End of File is Reached" } ]
Convert Python Script to .exe File - GeeksforGeeks
01 Feb, 2021 We create lots of Python programs per day and want to share them with the world. It is not that you share that Python program with everyone, and they will run this script in some IDLE shell. But you want everyone to run your Python script without the installation of Python. So for this work, you can convert the .py file to .exe file. In this article, you will learn how you can convert .py file to .exe file. Follow the below steps for the same. Step 1: Install the library pyinstaller. Type below command in the command prompt. pip install pyinstaller Step 2: Go into the directory where your ‘.py’ file is located. Step 3: Press the shift⇧ button and simultaneously right-click at the same location. You will get the below box. Step 4: Click on ‘Open PowerShell window here’. You will get a window shown below. Step 5: Type the command given below in that PowerShell window. pyinstaller --onefile -w 'filename.py' Here the ‘.py’ file name is ‘1’. See below: In case you get an error at this point in the PowerShell window like this: The correction while typing the above command: .\pyinstaller --onefile -w 'filename.py' For any missing package: pyinstaller --hidden-import 'package_name' --onefile 'filename.py' Step 6: After typing the command ‘Hit the Enter’. It will take some time to finish the process depending on the size of the file and how big is your project. After the processing has been finished, the window will look as below: Step 7: See the directory it should look like this: ‘build’ folder and ‘1.spec’ is of no use. You can delete these if you want, it will not affect your ‘.exe’ file. Step 8: Open ‘dist’ folder above. Here you will get your ‘.exe’ file. Right-click on the file and check the properties. shanmalan python-utility Technical Scripter 2019 Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace() Reading and Writing to text files in Python Create a Pandas DataFrame from Lists *args and **kwargs in Python
[ { "code": null, "e": 24498, "s": 24470, "text": "\n01 Feb, 2021" }, { "code": null, "e": 24947, "s": 24498, "text": "We create lots of Python programs per day and want to share them with the world. It is not that you share that Python program with everyone, and they will run this script in some IDLE shell. But you want everyone to run your Python script without the installation of Python. So for this work, you can convert the .py file to .exe file. In this article, you will learn how you can convert .py file to .exe file. Follow the below steps for the same. " }, { "code": null, "e": 25032, "s": 24947, "text": "Step 1: Install the library pyinstaller. Type below command in the command prompt. " }, { "code": null, "e": 25056, "s": 25032, "text": "pip install pyinstaller" }, { "code": null, "e": 25121, "s": 25056, "text": "Step 2: Go into the directory where your ‘.py’ file is located. " }, { "code": null, "e": 25238, "s": 25123, "text": "Step 3: Press the shift⇧ button and simultaneously right-click at the same location. You will get the below box. " }, { "code": null, "e": 25287, "s": 25238, "text": "Step 4: Click on ‘Open PowerShell window here’. " }, { "code": null, "e": 25325, "s": 25289, "text": "You will get a window shown below. " }, { "code": null, "e": 25393, "s": 25327, "text": "Step 5: Type the command given below in that PowerShell window. " }, { "code": null, "e": 25432, "s": 25393, "text": "pyinstaller --onefile -w 'filename.py'" }, { "code": null, "e": 25477, "s": 25432, "text": "Here the ‘.py’ file name is ‘1’. See below: " }, { "code": null, "e": 25555, "s": 25479, "text": "In case you get an error at this point in the PowerShell window like this: " }, { "code": null, "e": 25606, "s": 25557, "text": "The correction while typing the above command: " }, { "code": null, "e": 25740, "s": 25606, "text": ".\\pyinstaller --onefile -w 'filename.py'\n\nFor any missing package:\npyinstaller --hidden-import 'package_name' --onefile 'filename.py'" }, { "code": null, "e": 25972, "s": 25742, "text": "Step 6: After typing the command ‘Hit the Enter’. It will take some time to finish the process depending on the size of the file and how big is your project. After the processing has been finished, the window will look as below: " }, { "code": null, "e": 26027, "s": 25974, "text": "Step 7: See the directory it should look like this: " }, { "code": null, "e": 26143, "s": 26029, "text": "‘build’ folder and ‘1.spec’ is of no use. You can delete these if you want, it will not affect your ‘.exe’ file. " }, { "code": null, "e": 26216, "s": 26145, "text": "Step 8: Open ‘dist’ folder above. Here you will get your ‘.exe’ file. " }, { "code": null, "e": 26269, "s": 26218, "text": "Right-click on the file and check the properties. " }, { "code": null, "e": 26283, "s": 26273, "text": "shanmalan" }, { "code": null, "e": 26298, "s": 26283, "text": "python-utility" }, { "code": null, "e": 26322, "s": 26298, "text": "Technical Scripter 2019" }, { "code": null, "e": 26329, "s": 26322, "text": "Python" }, { "code": null, "e": 26348, "s": 26329, "text": "Technical Scripter" }, { "code": null, "e": 26446, "s": 26348, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26464, "s": 26446, "text": "Python Dictionary" }, { "code": null, "e": 26499, "s": 26464, "text": "Read a file line by line in Python" }, { "code": null, "e": 26531, "s": 26499, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26553, "s": 26531, "text": "Enumerate() in Python" }, { "code": null, "e": 26595, "s": 26553, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 26625, "s": 26595, "text": "Iterate over a list in Python" }, { "code": null, "e": 26651, "s": 26625, "text": "Python String | replace()" }, { "code": null, "e": 26695, "s": 26651, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 26732, "s": 26695, "text": "Create a Pandas DataFrame from Lists" } ]
Gray to Binary equivalent | Practice | GeeksforGeeks
Given N in Gray Code, find its binary equivalent. Return the decimal representation of the binary equivalent. Example 1: Input: N = 4 Output: 7 Explanation: Given 4 representing gray code 110. Binary equivalent of gray code 110 is 100. Return 7 representing gray code 100. Example 2: Input: N = 15 Output: 10 Explanation: Given 15 representing gray code 1000. Binary equivalent of gray code 1000 is 1111. Return 10 representing gray code 1111 ie binary 1010. Example 3: Input: N = 0 Output: 0 Explanation: Zero remains the same in all systems. Your Task: You don't need to read input or print anything. Your task is to complete the function grayToBinary() which accepts an integer n as an input parameter and returns decimal of the binary equivalent of the given gray code. Expected Time Complexity: O(log N) Expected Auxiliary Space: O(1) Constraints: 0 <= N <= 108 0 anasuya26677Premium1 day ago //Back-end complete function Template for Java class Solution{ // function to convert a given Gray equivalent n to Binary equivalent. public static int grayToBinary(int n) { int b=0; //We use a loop and Right shift n everytime until it becomes 0. for(n=n;n>0;n=n>>1) //We use XOR operation which stores the result of conversion in b. b^=n; //returning the Binary equivalent. return b; } } 0 crawler2 weeks ago class Solution{ public: // function to convert a given Gray equivalent n to Binary equivalent. int grayToBinary(int n) { int result = 0; for(int i=30; i>= 0; i--){ if(result == 0){ if(n & (1 << i)){ result |= (1<<i); } } else{ int significant = (result & (1 << (i+1))); significant >>= 1; if(n & (1 << i)){ significant ^= (1 << i); } result = result | significant; } } return result; } }; 0 sanapalavenkatesh20014 weeks ago int val=n<<1; vector<int>v; // v.push_back(val); while(n) { if(n&1) v.push_back(1); else v.push_back(0); n >>=1; } reverse(v.begin(),v.end()); for(int i=1;i<v.size();i++) { v[i]=v[i-1]^v[i]; } reverse(v.begin(),v.end()); int sumi=0; for(int i=0;i<v.size();i++) { if(v[i]==1) { sumi +=pow(2,i); } } return sumi +2 1ashishchauhan20021 month ago int t=0; while(n){ t=t^n; n=n>>1; } return t; +2 singhisha7181 month ago int grayToBinary(int n) { int x=0; while(n){ x=x^n; n=n>>1; } return x; } 0 raunakmishra12432 months ago int grayToBinary(int n) { if(n==0) return 0; vector<int>bin; while(n) { bin.push_back(n%2); n=n/2; } reverse(bin.begin(),bin.end()); for(int i=1;i<bin.size();i++) { bin[i]=bin[i]^bin[i-1]; } int ans=0; int k=0; for(int i=bin.size()-1;i>=0;i--) { ans=ans+pow(2,k++)*bin[i]; } return ans; } +3 naitikrajyaguru3 months ago // take xor of bit and privious bit will be result into binary to gray or reverse int grayToBinary(int n) { vector <int> binary; if(n==0){ return 0; } //binary while(n){ binary.push_back(n%2); n/=2; } reverse(binary.begin(), binary.end()); //xor for(int i=1; i<=binary.size()-1; i++){ binary[i]= binary[i] ^ binary[i-1]; } int ans=0; reverse(binary.begin(), binary.end()); //decimal for(int i=0; i<=binary.size()-1; i++){ ans+= binary[i]*pow(2,i); } return ans; 0 chessnoobdj4 months ago Easy C++ int grayToBinary(int num){ num ^= num >> 16; num ^= num >> 8; num ^= num >> 4; num ^= num >> 2; num ^= num >> 1; return num; } int grayToBinary(int num){ int mask = num; while (mask) { mask >>= 1; num ^= mask; } return num; } +2 codxzaheer4 months ago Let b0, b1, b2 and b3 be the bits representing the binary numbers, where b0 is the LSB and b3 is the MSB, andLet g0, g1, g2 and g3 be the bits representing the gray code of the binary numbers, where g0 is the LSB and g3 is the MSB. b0=g3^g2^g1^g0 b1=g3^g2^g1 b2=g3^g2 b3=g3 So, start a loop and keep doing Right Shift untill n becomes 0 and keep storing the result of XOR operation. // Your code here int ans= 0; while(n) { ans = ans ^ n; n = n>>1; } return ans; 0 salmanmajeed245 months ago int ans=0; while(n){ ans = ans ^ n; n = n>>1; } return ans; We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 348, "s": 238, "text": "Given N in Gray Code, find its binary equivalent. Return the decimal representation of the binary equivalent." }, { "code": null, "e": 359, "s": 348, "text": "Example 1:" }, { "code": null, "e": 512, "s": 359, "text": "Input: N = 4\nOutput: 7\nExplanation:\nGiven 4 representing gray code 110.\nBinary equivalent of gray code 110 is 100.\nReturn 7 representing gray code 100.\n" }, { "code": null, "e": 523, "s": 512, "text": "Example 2:" }, { "code": null, "e": 699, "s": 523, "text": "Input: N = 15\nOutput: 10\nExplanation:\nGiven 15 representing gray code 1000.\nBinary equivalent of gray code 1000 is 1111.\nReturn 10 representing gray code 1111 \nie binary 1010." }, { "code": null, "e": 710, "s": 699, "text": "Example 3:" }, { "code": null, "e": 785, "s": 710, "text": "Input: N = 0\nOutput: 0\nExplanation: \nZero remains the same in all systems." }, { "code": null, "e": 1113, "s": 785, "text": "\nYour Task: \nYou don't need to read input or print anything. Your task is to complete the function grayToBinary() which accepts an integer n as an input parameter and returns decimal of the binary equivalent of the given gray code. \n\nExpected Time Complexity: O(log N)\nExpected Auxiliary Space: O(1)\n\nConstraints:\n0 <= N <= 108" }, { "code": null, "e": 1115, "s": 1113, "text": "0" }, { "code": null, "e": 1144, "s": 1115, "text": "anasuya26677Premium1 day ago" }, { "code": null, "e": 1208, "s": 1144, "text": "//Back-end complete function Template for Java\n\nclass Solution{" }, { "code": null, "e": 1287, "s": 1208, "text": "\n // function to convert a given Gray equivalent n to Binary equivalent.\n " }, { "code": null, "e": 1330, "s": 1287, "text": " public static int grayToBinary(int n) {\n" }, { "code": null, "e": 1353, "s": 1330, "text": " int b=0;\n " }, { "code": null, "e": 1433, "s": 1353, "text": " \n //We use a loop and Right shift n everytime until it becomes 0.\n " }, { "code": null, "e": 1557, "s": 1433, "text": " for(n=n;n>0;n=n>>1)\n //We use XOR operation which stores the result of conversion in b.\n b^=n;\n " }, { "code": null, "e": 1631, "s": 1557, "text": " \n //returning the Binary equivalent.\n return b;\n " }, { "code": null, "e": 1635, "s": 1631, "text": " }\n" }, { "code": null, "e": 1638, "s": 1635, "text": "\n}" }, { "code": null, "e": 1640, "s": 1638, "text": "0" }, { "code": null, "e": 1659, "s": 1640, "text": "crawler2 weeks ago" }, { "code": null, "e": 2301, "s": 1659, "text": "class Solution{\n public:\n // function to convert a given Gray equivalent n to Binary equivalent.\n int grayToBinary(int n)\n {\n int result = 0;\n for(int i=30; i>= 0; i--){\n if(result == 0){\n if(n & (1 << i)){\n result |= (1<<i);\n }\n }\n else{\n int significant = (result & (1 << (i+1)));\n significant >>= 1;\n if(n & (1 << i)){\n significant ^= (1 << i);\n }\n result = result | significant;\n }\n }\n return result;\n }\n};\n" }, { "code": null, "e": 2303, "s": 2301, "text": "0" }, { "code": null, "e": 2336, "s": 2303, "text": "sanapalavenkatesh20014 weeks ago" }, { "code": null, "e": 2901, "s": 2336, "text": " int val=n<<1; vector<int>v; // v.push_back(val); while(n) { if(n&1) v.push_back(1); else v.push_back(0); n >>=1; } reverse(v.begin(),v.end()); for(int i=1;i<v.size();i++) { v[i]=v[i-1]^v[i]; } reverse(v.begin(),v.end()); int sumi=0; for(int i=0;i<v.size();i++) { if(v[i]==1) { sumi +=pow(2,i); } } return sumi" }, { "code": null, "e": 2904, "s": 2901, "text": "+2" }, { "code": null, "e": 2934, "s": 2904, "text": "1ashishchauhan20021 month ago" }, { "code": null, "e": 3025, "s": 2934, "text": " int t=0; while(n){ t=t^n; n=n>>1; } return t;" }, { "code": null, "e": 3028, "s": 3025, "text": "+2" }, { "code": null, "e": 3052, "s": 3028, "text": "singhisha7181 month ago" }, { "code": null, "e": 3199, "s": 3052, "text": " int grayToBinary(int n)\n {\n int x=0;\n while(n){\n x=x^n;\n n=n>>1;\n }\n return x;\n \n }" }, { "code": null, "e": 3201, "s": 3199, "text": "0" }, { "code": null, "e": 3230, "s": 3201, "text": "raunakmishra12432 months ago" }, { "code": null, "e": 3812, "s": 3230, "text": "int grayToBinary(int n)\n {\n \n if(n==0)\n return 0;\n vector<int>bin;\n while(n)\n {\n bin.push_back(n%2);\n n=n/2;\n \n \n \n }\n reverse(bin.begin(),bin.end());\n for(int i=1;i<bin.size();i++)\n {\n \n bin[i]=bin[i]^bin[i-1];\n \n }\n int ans=0;\n int k=0;\n for(int i=bin.size()-1;i>=0;i--)\n {\n ans=ans+pow(2,k++)*bin[i];\n \n \n }\n return ans;\n \n }" }, { "code": null, "e": 3815, "s": 3812, "text": "+3" }, { "code": null, "e": 3843, "s": 3815, "text": "naitikrajyaguru3 months ago" }, { "code": null, "e": 4465, "s": 3843, "text": "// take xor of bit and privious bit will be result into binary to gray or reverse int grayToBinary(int n) { vector <int> binary; if(n==0){ return 0; } //binary while(n){ binary.push_back(n%2); n/=2; } reverse(binary.begin(), binary.end()); //xor for(int i=1; i<=binary.size()-1; i++){ binary[i]= binary[i] ^ binary[i-1]; } int ans=0; reverse(binary.begin(), binary.end()); //decimal for(int i=0; i<=binary.size()-1; i++){ ans+= binary[i]*pow(2,i); } return ans;" }, { "code": null, "e": 4467, "s": 4465, "text": "0" }, { "code": null, "e": 4491, "s": 4467, "text": "chessnoobdj4 months ago" }, { "code": null, "e": 4500, "s": 4491, "text": "Easy C++" }, { "code": null, "e": 4683, "s": 4500, "text": "int grayToBinary(int num){\n num ^= num >> 16;\n num ^= num >> 8;\n num ^= num >> 4;\n num ^= num >> 2;\n num ^= num >> 1;\n return num;\n }" }, { "code": null, "e": 4854, "s": 4683, "text": "int grayToBinary(int num){\n int mask = num;\n while (mask) { \n mask >>= 1;\n num ^= mask;\n }\n return num;\n }" }, { "code": null, "e": 4857, "s": 4854, "text": "+2" }, { "code": null, "e": 4880, "s": 4857, "text": "codxzaheer4 months ago" }, { "code": null, "e": 5112, "s": 4880, "text": "Let b0, b1, b2 and b3 be the bits representing the binary numbers, where b0 is the LSB and b3 is the MSB, andLet g0, g1, g2 and g3 be the bits representing the gray code of the binary numbers, where g0 is the LSB and g3 is the MSB." }, { "code": null, "e": 5127, "s": 5112, "text": "b0=g3^g2^g1^g0" }, { "code": null, "e": 5139, "s": 5127, "text": "b1=g3^g2^g1" }, { "code": null, "e": 5148, "s": 5139, "text": "b2=g3^g2" }, { "code": null, "e": 5154, "s": 5148, "text": "b3=g3" }, { "code": null, "e": 5263, "s": 5154, "text": "So, start a loop and keep doing Right Shift untill n becomes 0 and keep storing the result of XOR operation." }, { "code": null, "e": 5401, "s": 5263, "text": " // Your code here int ans= 0; while(n) { ans = ans ^ n; n = n>>1; } return ans;" }, { "code": null, "e": 5405, "s": 5403, "text": "0" }, { "code": null, "e": 5432, "s": 5405, "text": "salmanmajeed245 months ago" }, { "code": null, "e": 5554, "s": 5432, "text": " int ans=0;\n while(n){\n ans = ans ^ n;\n n = n>>1;\n \n }\n return ans;" }, { "code": null, "e": 5700, "s": 5554, "text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?" }, { "code": null, "e": 5736, "s": 5700, "text": " Login to access your submissions. " }, { "code": null, "e": 5746, "s": 5736, "text": "\nProblem\n" }, { "code": null, "e": 5756, "s": 5746, "text": "\nContest\n" }, { "code": null, "e": 5819, "s": 5756, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 5967, "s": 5819, "text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 6175, "s": 5967, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints." }, { "code": null, "e": 6281, "s": 6175, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Why We Use Unsupervised Learning (With K-means Clustering From Scratch) | by Emmett Boudreau | Towards Data Science
Unsupervised learning is an interesting topic in the Data-Science world that isn’t often highlighted by those who aren’t doing Data-Science, and furthermore is often an idea neglected by many Data-Scientists themselves. There is an explanation for this, as for many employment opportunities, unsupervised learning simply isn’t significant. There might certainly be times where it will come into play, but for the most part, a business is not going to invest in doing research where they will never know the results. Doing research whilst not knowing the results is exactly what the unsupervised adjective applies in this situation, so if we don’t know what our model is putting out, then how can we find value in its predictions and findings? The primary function of unsupervised learning algorithms is analysis. Using an unsupervised learning algorithm to explore your data can tell you a lot about certain attributes of said data. Clustering, for example, can show how grouped certain continuous values might be, whether related or unrelated. You can use unsupervised learning to find natural patterns in data that aren’t immediately obvious with just statistical analysis or comparing values. Unsupervised learning algorithms also hold their own in image recognition and genomics as well. In genomics, they can be used to cluster together genetics or analyse sequences of genome data. Unsupervised learning is used to model probability densities, which is incredibly useful to the Bioinformatics discipline. Another great thing about unsupervised is that it can be incredibly easy to gather analytics without any human interaction whatsoever. Typical machine-learning, whether reinforced or supervised, will require manually drawn labels in order to properly understand the outcome of the model. The differences that distinguish supervised and unsupervised learning are as follows: Less Accurate No labeled data required Minimal human effort Highly accurate Has a consistent target Labeled data is required Requires human effort in the loop Clustering is the most commonly used unsupervised learning method. This is because typically it is one of the best ways to explore and find out more about data visually. There are several different types of clustering, including: Hierarchical clustering: builds a multilevel hierarchy of clusters by creating a cluster tree. k-Means clustering: partitions data into k distinct clusters based on distance to the centroid of a cluster. Gaussian mixture models: models clusters as a mixture of multivariate normal density components. Self-organizing maps: uses neural networks that learn the topology and distribution of the data. Hidden Markov models: uses observed data to recover the sequence of states. For today’s example, we are going to be looking at Kmeans clustering, which is available in Sklearn. In K-means clustering, for each point x: Find the nearest centroid c assign the point x to cluster j and then for each cluster j (=1 .. K): The new centroid c is equal to the mean of all points x assigned to the cluster j in the previous step. While this model is available in sklearn.cluster under the class KMeans, today I am going to be writing my own function to calculate the K-means clusters. We’re going to start this by creating a function that has the ability to measure euclidian length. This is as simple as using linalg from Numpy. import numpy as npdef euclidian(a, b): return np.linalg.norm(a-b) I also went ahead and imported Matplotlib.pyplot and Matplotlib.animation for some visualizations of our clusters in the future: import matplotlib.pyplot as plt# animationimport matplotlib.animation as animation Since I’m going to be using text data, I used this function from numpy to load it: def load_dataset(name): return np.loadtxt(name) Now it’s time to make our actual K-means function. To start, we will add the parameters, k, epsilon, and distance (which will be euclidean in our case.) After that, we will make an empty list for our centroids, and setup the distance algorithm to use our euclidian function from before. def kmeans(k, epsilon=0, distance='euclidian'): history_centroids = [] #set the distance calculation type if distance == 'euclidian': dist_method = euclidian Next, we will load our data-set and check the data-set’s shape to get the number of instances (observations), and the number of features dataset = load_dataset('durudataset.txt')num_instances, num_features = dataset.shape Now we will define our k-prototypes using a random number from Numpy.random: prototypes = dataset[np.random.randint(0, num_instances - 1, size=k)] After that, we will append them to our centroid history list: history_centroids.append(prototypes) Now I created these lists to store our centroid clusters and keep track of them at each iteration: prototypes_old = np.zeros(prototypes.shape)belongs_to = np.zeros((num_instances, 1))norm = dist_method(prototypes, prototypes_old)iteration = 0 Then we will do our for loop, following the formula I stated before: while norm > epsilon: iteration += 1 norm = dist_method(prototypes, prototypes_old) for index_instance, instance in enumerate(dataset): dist_vec = np.zeros((k,1)) for index_prototype, prototype in enumerate(prototypes): #compute the distance between x and centroid dist_vec[index_prototype] = dist_method(prototype, instance) belongs_to[index_instance, 0] = np.argmin(dist_vec) tmp_prototypes = np.zeros((k, num_features)) While the norm is greater than epsilon, for each instance in the data-set we will define a distance vector that is the size of k. Then for each centroid, we will calculate the difference between our x and the centroid. Next, we will loop through our list of prototypes and get all of the points that are assigned to said prototype. Then we will find the mean of those points, which will give us our new centroid. Last but not least, we will add that corresponding value to the index of our list. for index in range(len(prototypes)): instances_close = [i for i in range(len(belongs_to)) if belongs_to[i] == index] prototype = np.mean(dataset[instances_close], axis=0) #add our new centroid to our new temporary list tmp_prototypes[index, :] = prototype Finally, we can set our temporary prototypes equal to our final list of centroids. For the sake of creating a Matplotlib animation, I will also add the history of centroids list to the mix here. prototypes = tmp_prototypeshistory_centroids.append(tmp_prototypes)return prototypes, history_centroids, belongs_to For a final function that looks like this: def kmeans(k, epsilon=0, distance='euclidian'): history_centroids = [] if distance == 'euclidian': dist_method = euclidian #set the dataset dataset = load_dataset('durudataset.txt') num_instances, num_features = dataset.shape prototypes = dataset[np.random.randint(0, num_instances - 1, size=k)] history_centroids.append(prototypes) prototypes_old = np.zeros(prototypes.shape) belongs_to = np.zeros((num_instances, 1)) norm = dist_method(prototypes, prototypes_old) iteration = 0 while norm > epsilon: iteration += 1 norm = dist_method(prototypes, prototypes_old) for index_instance, instance in enumerate(dataset): dist_vec = np.zeros((k,1)) for index_prototype, prototype in enumerate(prototypes): dist_vec[index_prototype] = dist_method(prototype, instance) belongs_to[index_instance, 0] = np.argmin(dist_vec) tmp_prototypes = np.zeros((k, num_features)) for index in range(len(prototypes)): instances_close = [i for i in range(len(belongs_to)) if belongs_to[i] == index] prototype = np.mean(dataset[instances_close], axis=0) #add our new centroid to our new temporary list tmp_prototypes[index, :] = prototype prototypes = tmp_prototypes history_centroids.append(tmp_prototypes) return prototypes, history_centroids, belongs_to Now if we decide to plot it, my results looked a little something like this: Pretty cool, right? While unsupervised learning might not get the love or the use that most supervised learning models enjoy, just because the results aren’t labeled doesn’t mean that there can’t be a lot of information learned about the data from it. Unsupervised learning is a great tool for exploring and truly understanding how data is grouped and how different features interact with one another. Although in a lot of cases, Data-Scientists might stray a bit far away from using unsupervised learning, it’s easy to see why it could be quite beneficial sometimes!
[ { "code": null, "e": 915, "s": 172, "text": "Unsupervised learning is an interesting topic in the Data-Science world that isn’t often highlighted by those who aren’t doing Data-Science, and furthermore is often an idea neglected by many Data-Scientists themselves. There is an explanation for this, as for many employment opportunities, unsupervised learning simply isn’t significant. There might certainly be times where it will come into play, but for the most part, a business is not going to invest in doing research where they will never know the results. Doing research whilst not knowing the results is exactly what the unsupervised adjective applies in this situation, so if we don’t know what our model is putting out, then how can we find value in its predictions and findings?" }, { "code": null, "e": 1368, "s": 915, "text": "The primary function of unsupervised learning algorithms is analysis. Using an unsupervised learning algorithm to explore your data can tell you a lot about certain attributes of said data. Clustering, for example, can show how grouped certain continuous values might be, whether related or unrelated. You can use unsupervised learning to find natural patterns in data that aren’t immediately obvious with just statistical analysis or comparing values." }, { "code": null, "e": 1683, "s": 1368, "text": "Unsupervised learning algorithms also hold their own in image recognition and genomics as well. In genomics, they can be used to cluster together genetics or analyse sequences of genome data. Unsupervised learning is used to model probability densities, which is incredibly useful to the Bioinformatics discipline." }, { "code": null, "e": 2057, "s": 1683, "text": "Another great thing about unsupervised is that it can be incredibly easy to gather analytics without any human interaction whatsoever. Typical machine-learning, whether reinforced or supervised, will require manually drawn labels in order to properly understand the outcome of the model. The differences that distinguish supervised and unsupervised learning are as follows:" }, { "code": null, "e": 2071, "s": 2057, "text": "Less Accurate" }, { "code": null, "e": 2096, "s": 2071, "text": "No labeled data required" }, { "code": null, "e": 2117, "s": 2096, "text": "Minimal human effort" }, { "code": null, "e": 2133, "s": 2117, "text": "Highly accurate" }, { "code": null, "e": 2157, "s": 2133, "text": "Has a consistent target" }, { "code": null, "e": 2182, "s": 2157, "text": "Labeled data is required" }, { "code": null, "e": 2216, "s": 2182, "text": "Requires human effort in the loop" }, { "code": null, "e": 2446, "s": 2216, "text": "Clustering is the most commonly used unsupervised learning method. This is because typically it is one of the best ways to explore and find out more about data visually. There are several different types of clustering, including:" }, { "code": null, "e": 2541, "s": 2446, "text": "Hierarchical clustering: builds a multilevel hierarchy of clusters by creating a cluster tree." }, { "code": null, "e": 2650, "s": 2541, "text": "k-Means clustering: partitions data into k distinct clusters based on distance to the centroid of a cluster." }, { "code": null, "e": 2747, "s": 2650, "text": "Gaussian mixture models: models clusters as a mixture of multivariate normal density components." }, { "code": null, "e": 2844, "s": 2747, "text": "Self-organizing maps: uses neural networks that learn the topology and distribution of the data." }, { "code": null, "e": 2920, "s": 2844, "text": "Hidden Markov models: uses observed data to recover the sequence of states." }, { "code": null, "e": 3062, "s": 2920, "text": "For today’s example, we are going to be looking at Kmeans clustering, which is available in Sklearn. In K-means clustering, for each point x:" }, { "code": null, "e": 3090, "s": 3062, "text": "Find the nearest centroid c" }, { "code": null, "e": 3122, "s": 3090, "text": "assign the point x to cluster j" }, { "code": null, "e": 3161, "s": 3122, "text": "and then for each cluster j (=1 .. K):" }, { "code": null, "e": 3265, "s": 3161, "text": "The new centroid c is equal to the mean of all points x assigned to the cluster j in the previous step." }, { "code": null, "e": 3565, "s": 3265, "text": "While this model is available in sklearn.cluster under the class KMeans, today I am going to be writing my own function to calculate the K-means clusters. We’re going to start this by creating a function that has the ability to measure euclidian length. This is as simple as using linalg from Numpy." }, { "code": null, "e": 3634, "s": 3565, "text": "import numpy as npdef euclidian(a, b): return np.linalg.norm(a-b)" }, { "code": null, "e": 3763, "s": 3634, "text": "I also went ahead and imported Matplotlib.pyplot and Matplotlib.animation for some visualizations of our clusters in the future:" }, { "code": null, "e": 3846, "s": 3763, "text": "import matplotlib.pyplot as plt# animationimport matplotlib.animation as animation" }, { "code": null, "e": 3929, "s": 3846, "text": "Since I’m going to be using text data, I used this function from numpy to load it:" }, { "code": null, "e": 3980, "s": 3929, "text": "def load_dataset(name): return np.loadtxt(name)" }, { "code": null, "e": 4267, "s": 3980, "text": "Now it’s time to make our actual K-means function. To start, we will add the parameters, k, epsilon, and distance (which will be euclidean in our case.) After that, we will make an empty list for our centroids, and setup the distance algorithm to use our euclidian function from before." }, { "code": null, "e": 4442, "s": 4267, "text": "def kmeans(k, epsilon=0, distance='euclidian'): history_centroids = [] #set the distance calculation type if distance == 'euclidian': dist_method = euclidian" }, { "code": null, "e": 4579, "s": 4442, "text": "Next, we will load our data-set and check the data-set’s shape to get the number of instances (observations), and the number of features" }, { "code": null, "e": 4664, "s": 4579, "text": "dataset = load_dataset('durudataset.txt')num_instances, num_features = dataset.shape" }, { "code": null, "e": 4741, "s": 4664, "text": "Now we will define our k-prototypes using a random number from Numpy.random:" }, { "code": null, "e": 4811, "s": 4741, "text": "prototypes = dataset[np.random.randint(0, num_instances - 1, size=k)]" }, { "code": null, "e": 4873, "s": 4811, "text": "After that, we will append them to our centroid history list:" }, { "code": null, "e": 4910, "s": 4873, "text": "history_centroids.append(prototypes)" }, { "code": null, "e": 5009, "s": 4910, "text": "Now I created these lists to store our centroid clusters and keep track of them at each iteration:" }, { "code": null, "e": 5153, "s": 5009, "text": "prototypes_old = np.zeros(prototypes.shape)belongs_to = np.zeros((num_instances, 1))norm = dist_method(prototypes, prototypes_old)iteration = 0" }, { "code": null, "e": 5222, "s": 5153, "text": "Then we will do our for loop, following the formula I stated before:" }, { "code": null, "e": 5748, "s": 5222, "text": "while norm > epsilon: iteration += 1 norm = dist_method(prototypes, prototypes_old) for index_instance, instance in enumerate(dataset): dist_vec = np.zeros((k,1)) for index_prototype, prototype in enumerate(prototypes): #compute the distance between x and centroid dist_vec[index_prototype] = dist_method(prototype, instance) belongs_to[index_instance, 0] = np.argmin(dist_vec) tmp_prototypes = np.zeros((k, num_features))" }, { "code": null, "e": 6244, "s": 5748, "text": "While the norm is greater than epsilon, for each instance in the data-set we will define a distance vector that is the size of k. Then for each centroid, we will calculate the difference between our x and the centroid. Next, we will loop through our list of prototypes and get all of the points that are assigned to said prototype. Then we will find the mean of those points, which will give us our new centroid. Last but not least, we will add that corresponding value to the index of our list." }, { "code": null, "e": 6544, "s": 6244, "text": "for index in range(len(prototypes)): instances_close = [i for i in range(len(belongs_to)) if belongs_to[i] == index] prototype = np.mean(dataset[instances_close], axis=0) #add our new centroid to our new temporary list tmp_prototypes[index, :] = prototype" }, { "code": null, "e": 6739, "s": 6544, "text": "Finally, we can set our temporary prototypes equal to our final list of centroids. For the sake of creating a Matplotlib animation, I will also add the history of centroids list to the mix here." }, { "code": null, "e": 6855, "s": 6739, "text": "prototypes = tmp_prototypeshistory_centroids.append(tmp_prototypes)return prototypes, history_centroids, belongs_to" }, { "code": null, "e": 6898, "s": 6855, "text": "For a final function that looks like this:" }, { "code": null, "e": 8330, "s": 6898, "text": "def kmeans(k, epsilon=0, distance='euclidian'): history_centroids = [] if distance == 'euclidian': dist_method = euclidian #set the dataset dataset = load_dataset('durudataset.txt') num_instances, num_features = dataset.shape prototypes = dataset[np.random.randint(0, num_instances - 1, size=k)] history_centroids.append(prototypes) prototypes_old = np.zeros(prototypes.shape) belongs_to = np.zeros((num_instances, 1)) norm = dist_method(prototypes, prototypes_old) iteration = 0 while norm > epsilon: iteration += 1 norm = dist_method(prototypes, prototypes_old) for index_instance, instance in enumerate(dataset): dist_vec = np.zeros((k,1)) for index_prototype, prototype in enumerate(prototypes): dist_vec[index_prototype] = dist_method(prototype, instance) belongs_to[index_instance, 0] = np.argmin(dist_vec) tmp_prototypes = np.zeros((k, num_features)) for index in range(len(prototypes)): instances_close = [i for i in range(len(belongs_to)) if belongs_to[i] == index] prototype = np.mean(dataset[instances_close], axis=0) #add our new centroid to our new temporary list tmp_prototypes[index, :] = prototype prototypes = tmp_prototypes history_centroids.append(tmp_prototypes) return prototypes, history_centroids, belongs_to" }, { "code": null, "e": 8407, "s": 8330, "text": "Now if we decide to plot it, my results looked a little something like this:" }, { "code": null, "e": 8427, "s": 8407, "text": "Pretty cool, right?" } ]
Tryit Editor v3.6 - Show Python
f = open("demofile.txt", "r")
[]
What is the difference between Getters and Setters in JavaScript?
Getters and setters allow us to define Object Accessors. The difference between them is that the former is used to get the property from the object whereas the latter is used to set a property in an object. Let's discuss them through examples. In the following example, an object named "business" is created and using "Getter" a property called "company" is displayed in the output. Live Demo <html> <body> <script> var business= { Name: "Musk", Country : "America", Company : "PayPal", get comp() { return this.company; } }; document.write(business.company); </script> </body> </html> paypal In the following example, an object named "business" is created and using "Setter" the value of property called "company" is changed from PayPal to SolarCity as shown in the output. Live Demo <html> <body> <script> var business = { Name: "Musk", Country : "America", company : "PayPal", set comp(val) { this.company = val; } }; business.comp = "SolarCity"; document.write(business.company); </script> </body> </html> SolarCity
[ { "code": null, "e": 1306, "s": 1062, "text": "Getters and setters allow us to define Object Accessors. The difference between them is that the former is used to get the property from the object whereas the latter is used to set a property in an object. Let's discuss them through examples." }, { "code": null, "e": 1445, "s": 1306, "text": "In the following example, an object named \"business\" is created and using \"Getter\" a property called \"company\" is displayed in the output." }, { "code": null, "e": 1456, "s": 1445, "text": " Live Demo" }, { "code": null, "e": 1697, "s": 1456, "text": "<html>\n<body>\n<script>\n var business= {\n Name: \"Musk\",\n Country : \"America\",\n Company : \"PayPal\",\n get comp() {\n return this.company;\n }\n };\n document.write(business.company);\n</script>\n</body>\n</html>" }, { "code": null, "e": 1704, "s": 1697, "text": "paypal" }, { "code": null, "e": 1886, "s": 1704, "text": "In the following example, an object named \"business\" is created and using \"Setter\" the value of property called \"company\" is changed from PayPal to SolarCity as shown in the output." }, { "code": null, "e": 1897, "s": 1886, "text": " Live Demo" }, { "code": null, "e": 2173, "s": 1897, "text": "<html>\n<body>\n<script>\n var business = {\n Name: \"Musk\",\n Country : \"America\",\n company : \"PayPal\",\n set comp(val) {\n this.company = val;\n }\n };\n business.comp = \"SolarCity\";\n document.write(business.company);\n</script>\n</body>\n</html>" }, { "code": null, "e": 2183, "s": 2173, "text": "SolarCity" } ]
Python - Window size Adjustment in Kivy
Kivy is a platform independent GUI tool in Python. As it can be run on Android, IOS, linux and Windows etc. Kivy provides you the functionality to write the code for once and run it on different platforms. It is basically used to develop the Android application, but it does not mean that it can not be used on Desktops applications. Kivy is that platform where the size does not matter a lot as it is self-adjusting accordingly but What if we want to fix the size to some extent whether its hight wise or width wise or free from boundation depends on the user requirement. # When there is no fix window size i.e fully resizable according to user: from kivy.config import Config # 0 being off 1 being on as in true / false you can use 0 or 1 && True or False Config.set('graphics', 'resizable', True) # import kivy module import kivy # this restrict the kivy version i.e below this kivy version you cannot use the app kivy.require("1.9.1") # base Class of your App inherits from the App class. app:always refers to the instance of your #application from kivy.app import App # if you not import label and use it through error from kivy.uix.label import Label # defining the App class class MyLabelApp(App): def build(self): # label display the text on screen # markup text with different colour l2 = Label(text ="[color = ff3333][b]Hello !!!!!!!!!!![/b] [/color]\n [color = 3333ff]World!!! !!:):):):)[/color]", font_size ='20sp', markup = True) return l2 # creating the object label = MyLabelApp() # run the window label.run() # No resizing, fixed size with the width: from kivy.config import Config # 0 being off 1 being on as in true / false # you can use 0 or 1 && True or False Config.set('graphics', 'resizable', '0') # fix the width of the window Config.set('graphics', 'width', '500') #fixing the height of the window from kivy.config import Config # 0 being off 1 being on as in true / false # you can use 0 or 1 && True or False Config.set('graphics', 'resizable', '0') # fix the height of the window Config.set('graphics', 'height', '400')
[ { "code": null, "e": 1396, "s": 1062, "text": "Kivy is a platform independent GUI tool in Python. As it can be run on Android, IOS, linux and Windows etc. Kivy provides you the functionality to write the code for once and run it on different platforms. It is basically used to develop the Android application, but it does not mean that it can not be used on Desktops applications." }, { "code": null, "e": 1636, "s": 1396, "text": "Kivy is that platform where the size does not matter a lot as it is self-adjusting accordingly but What if we want to fix the size to some extent whether its hight wise or width wise or free from boundation depends on the user requirement." }, { "code": null, "e": 3171, "s": 1636, "text": "# When there is no fix window size i.e fully resizable according to user:\nfrom kivy.config import Config\n# 0 being off 1 being on as in true / false you can use 0 or 1 && True or False\nConfig.set('graphics', 'resizable', True)\n# import kivy module\nimport kivy\n# this restrict the kivy version i.e below this kivy version you cannot use the app\nkivy.require(\"1.9.1\")\n# base Class of your App inherits from the App class. app:always refers to the instance of your #application\nfrom kivy.app import App\n# if you not import label and use it through error\nfrom kivy.uix.label import Label\n# defining the App class\nclass MyLabelApp(App):\n def build(self):\n # label display the text on screen\n # markup text with different colour\n l2 = Label(text =\"[color = ff3333][b]Hello !!!!!!!!!!![/b]\n [/color]\\n [color = 3333ff]World!!! !!:):):):)[/color]\",\n font_size ='20sp', markup = True)\n return l2\n# creating the object\nlabel = MyLabelApp()\n# run the window\nlabel.run()\n# No resizing, fixed size with the width:\nfrom kivy.config import Config\n# 0 being off 1 being on as in true / false\n# you can use 0 or 1 && True or False\nConfig.set('graphics', 'resizable', '0')\n# fix the width of the window\nConfig.set('graphics', 'width', '500')\n#fixing the height of the window\nfrom kivy.config import Config\n# 0 being off 1 being on as in true / false\n# you can use 0 or 1 && True or False\nConfig.set('graphics', 'resizable', '0')\n# fix the height of the window\nConfig.set('graphics', 'height', '400')" } ]
Teradata - Date/Time Functions
This chapter discusses the date/time functions available in Teradata. Dates are stored as integer internally using the following formula. ((YEAR - 1900) * 10000) + (MONTH * 100) + DAY You can use the following query to check how the dates are stored. SELECT CAST(CURRENT_DATE AS INTEGER); Since the dates are stored as integer, you can perform some arithmetic operations on them. Teradata provides functions to perform these operations. EXTRACT function extracts portions of day, month and year from a DATE value. This function is also used to extract hour, minute and second from TIME/TIMESTAMP value. Following examples show how to extract Year, Month, Date, Hour, Minute and second values from Date and Timestamp values. SELECT EXTRACT(YEAR FROM CURRENT_DATE); EXTRACT(YEAR FROM Date) ----------------------- 2016 SELECT EXTRACT(MONTH FROM CURRENT_DATE); EXTRACT(MONTH FROM Date) ------------------------ 1 SELECT EXTRACT(DAY FROM CURRENT_DATE); EXTRACT(DAY FROM Date) ------------------------ 1 SELECT EXTRACT(HOUR FROM CURRENT_TIMESTAMP); EXTRACT(HOUR FROM Current TimeStamp(6)) --------------------------------------- 4 SELECT EXTRACT(MINUTE FROM CURRENT_TIMESTAMP); EXTRACT(MINUTE FROM Current TimeStamp(6)) ----------------------------------------- 54 SELECT EXTRACT(SECOND FROM CURRENT_TIMESTAMP); EXTRACT(SECOND FROM Current TimeStamp(6)) ----------------------------------------- 27.140000 Teradata provides INTERVAL function to perform arithmetic operations on DATE and TIME values. There are two types of INTERVAL functions. YEAR YEAR TO MONTH MONTH DAY DAY TO HOUR DAY TO MINUTE DAY TO SECOND HOUR HOUR TO MINUTE HOUR TO SECOND MINUTE MINUTE TO SECOND SECOND The following example adds 3 years to current date. SELECT CURRENT_DATE, CURRENT_DATE + INTERVAL '03' YEAR; Date (Date+ 3) -------- --------- 16/01/01 19/01/01 The following example adds 3 years and 01 month to current date. SELECT CURRENT_DATE, CURRENT_DATE + INTERVAL '03-01' YEAR TO MONTH; Date (Date+ 3-01) -------- ------------ 16/01/01 19/02/01 The following example adds 01 day, 05 hours and 10 minutes to current timestamp. SELECT CURRENT_TIMESTAMP,CURRENT_TIMESTAMP + INTERVAL '01 05:10' DAY TO MINUTE; Current TimeStamp(6) (Current TimeStamp(6)+ 1 05:10) -------------------------------- -------------------------------- 2016-01-01 04:57:26.360000+00:00 2016-01-02 10:07:26.360000+00:00 Print Add Notes Bookmark this page
[ { "code": null, "e": 2700, "s": 2630, "text": "This chapter discusses the date/time functions available in Teradata." }, { "code": null, "e": 2768, "s": 2700, "text": "Dates are stored as integer internally using the following formula." }, { "code": null, "e": 2815, "s": 2768, "text": "((YEAR - 1900) * 10000) + (MONTH * 100) + DAY\n" }, { "code": null, "e": 2882, "s": 2815, "text": "You can use the following query to check how the dates are stored." }, { "code": null, "e": 2921, "s": 2882, "text": "SELECT CAST(CURRENT_DATE AS INTEGER);\n" }, { "code": null, "e": 3069, "s": 2921, "text": "Since the dates are stored as integer, you can perform some arithmetic operations on them. Teradata provides functions to perform these operations." }, { "code": null, "e": 3235, "s": 3069, "text": "EXTRACT function extracts portions of day, month and year from a DATE value. This function is also used to extract hour, minute and second from TIME/TIMESTAMP value." }, { "code": null, "e": 3356, "s": 3235, "text": "Following examples show how to extract Year, Month, Date, Hour, Minute and second values from Date and Timestamp values." }, { "code": null, "e": 4163, "s": 3356, "text": "SELECT EXTRACT(YEAR FROM CURRENT_DATE); \nEXTRACT(YEAR FROM Date) \n----------------------- \n 2016 \nSELECT EXTRACT(MONTH FROM CURRENT_DATE); \nEXTRACT(MONTH FROM Date) \n------------------------ \n 1 \nSELECT EXTRACT(DAY FROM CURRENT_DATE); \nEXTRACT(DAY FROM Date) \n------------------------ \n 1 \n \nSELECT EXTRACT(HOUR FROM CURRENT_TIMESTAMP); \nEXTRACT(HOUR FROM Current TimeStamp(6)) \n--------------------------------------- \n 4 \nSELECT EXTRACT(MINUTE FROM CURRENT_TIMESTAMP); \nEXTRACT(MINUTE FROM Current TimeStamp(6)) \n----------------------------------------- \n 54 \nSELECT EXTRACT(SECOND FROM CURRENT_TIMESTAMP); \nEXTRACT(SECOND FROM Current TimeStamp(6)) \n----------------------------------------- \n 27.140000" }, { "code": null, "e": 4300, "s": 4163, "text": "Teradata provides INTERVAL function to perform arithmetic operations on DATE and TIME values. There are two types of INTERVAL functions." }, { "code": null, "e": 4305, "s": 4300, "text": "YEAR" }, { "code": null, "e": 4319, "s": 4305, "text": "YEAR TO MONTH" }, { "code": null, "e": 4325, "s": 4319, "text": "MONTH" }, { "code": null, "e": 4329, "s": 4325, "text": "DAY" }, { "code": null, "e": 4341, "s": 4329, "text": "DAY TO HOUR" }, { "code": null, "e": 4355, "s": 4341, "text": "DAY TO MINUTE" }, { "code": null, "e": 4369, "s": 4355, "text": "DAY TO SECOND" }, { "code": null, "e": 4374, "s": 4369, "text": "HOUR" }, { "code": null, "e": 4389, "s": 4374, "text": "HOUR TO MINUTE" }, { "code": null, "e": 4404, "s": 4389, "text": "HOUR TO SECOND" }, { "code": null, "e": 4411, "s": 4404, "text": "MINUTE" }, { "code": null, "e": 4428, "s": 4411, "text": "MINUTE TO SECOND" }, { "code": null, "e": 4435, "s": 4428, "text": "SECOND" }, { "code": null, "e": 4487, "s": 4435, "text": "The following example adds 3 years to current date." }, { "code": null, "e": 4606, "s": 4487, "text": "SELECT CURRENT_DATE, CURRENT_DATE + INTERVAL '03' YEAR; \n Date (Date+ 3) \n-------- --------- \n16/01/01 19/01/01" }, { "code": null, "e": 4671, "s": 4606, "text": "The following example adds 3 years and 01 month to current date." }, { "code": null, "e": 4809, "s": 4671, "text": "SELECT CURRENT_DATE, CURRENT_DATE + INTERVAL '03-01' YEAR TO MONTH; \n Date (Date+ 3-01) \n-------- ------------ \n16/01/01 19/02/01" }, { "code": null, "e": 4890, "s": 4809, "text": "The following example adds 01 day, 05 hours and 10 minutes to current timestamp." }, { "code": null, "e": 5173, "s": 4890, "text": "SELECT CURRENT_TIMESTAMP,CURRENT_TIMESTAMP + INTERVAL '01 05:10' DAY TO MINUTE; \n Current TimeStamp(6) (Current TimeStamp(6)+ 1 05:10) \n-------------------------------- -------------------------------- \n2016-01-01 04:57:26.360000+00:00 2016-01-02 10:07:26.360000+00:00" }, { "code": null, "e": 5180, "s": 5173, "text": " Print" }, { "code": null, "e": 5191, "s": 5180, "text": " Add Notes" } ]
Cognos - Quick Guide
A Data Warehouse consists of data from multiple heterogeneous data sources and is used for analytical reporting and decision making. Data Warehouse is a central place where data is stored from different data sources and applications. The term Data Warehouse was first invented by Bill Inmom in 1990. A Data Warehouse is always kept separate from an Operational Database. The data in a DW system is loaded from operational transaction systems like − Sales Marketing HR SCM, etc. It may pass through operational data store or other transformations before it is loaded to the DW system for information processing. A Data Warehouse is used for reporting and analyzing of information and stores both historical and current data. The data in DW system is used for Analytical reporting, which is later used by Business Analysts, Sales Managers or Knowledge workers for decision-making. In the above image, you can see that the data is coming from multiple heterogeneous data sources to a Data Warehouse. Common data sources for a data warehouse includes − Operational databases SAP and non-SAP Applications Flat Files (xls, csv, txt files) Data in data warehouse is accessed by BI (Business Intelligence) users for Analytical Reporting, Data Mining and Analysis. This is used for decision making by Business Users, Sales Manager, Analysts to define future strategy. It is a central data repository where data is stored from one or more heterogeneous data sources. A DW system stores both current and historical data. Normally a DW system stores 5-10 years of historical data. A DW system is always kept separate from an operational transaction system. The data in a DW system is used for different types of analytical reporting range from Quarterly to Annual comparison. The differences between a Data Warehouse and Operational Database are as follows − An Operational System is designed for known workloads and transactions like updating a user record, searching a record, etc. However, Data Warehouse transactions are more complex and present a general form of data. An Operational System is designed for known workloads and transactions like updating a user record, searching a record, etc. However, Data Warehouse transactions are more complex and present a general form of data. An Operational System contains the current data of an organization and Data warehouse normally contains the historical data. An Operational System contains the current data of an organization and Data warehouse normally contains the historical data. An Operational Database supports parallel processing of multiple transactions. Concurrency control and recovery mechanisms are required to maintain consistency of the database. An Operational Database supports parallel processing of multiple transactions. Concurrency control and recovery mechanisms are required to maintain consistency of the database. An Operational Database query allows to read and modify operations (insert, delete and Update) while an OLAP query needs only read-only access of stored data (Select statement). An Operational Database query allows to read and modify operations (insert, delete and Update) while an OLAP query needs only read-only access of stored data (Select statement). Data Warehousing involves data cleaning, data integration, and data consolidations. A Data Warehouse has a 3-layer architecture − It defines how the data comes to a Data Warehouse. It involves various data sources and operational transaction systems, flat files, applications, etc. It consists of Operational Data Store and Staging area. Staging area is used to perform data cleansing, data transformation and loading data from different sources to a data warehouse. As multiple data sources are available for extraction at different time zones, staging area is used to store the data and later to apply transformations on data. This is used to perform BI reporting by end users. The data in a DW system is accessed by BI users and used for reporting and analysis. The following illustration shows the common architecture of a Data Warehouse System. The following are the key characteristics of a Data Warehouse − Subject Oriented − In a DW system, the data is categorized and stored by a business subject rather than by application like equity plans, shares, loans, etc. Subject Oriented − In a DW system, the data is categorized and stored by a business subject rather than by application like equity plans, shares, loans, etc. Integrated − Data from multiple data sources are integrated in a Data Warehouse. Integrated − Data from multiple data sources are integrated in a Data Warehouse. Non Volatile − Data in data warehouse is non-volatile. It means when data is loaded in DW system, it is not altered. Non Volatile − Data in data warehouse is non-volatile. It means when data is loaded in DW system, it is not altered. Time Variant − A DW system contains historical data as compared to Transactional system which contains only current data. In a Data warehouse you can see data for 3 months, 6 months, 1 year, 5 years, etc. Time Variant − A DW system contains historical data as compared to Transactional system which contains only current data. In a Data warehouse you can see data for 3 months, 6 months, 1 year, 5 years, etc. Firstly, OLTP stands for Online Transaction Processing, while OLAP stands for Online Analytical Processing In an OLTP system, there are a large number of short online transactions such as INSERT, UPDATE, and DELETE. Whereas, in an OLTP system, an effective measure is the processing time of short transactions and is very less. It controls data integrity in multi-access environments. For an OLTP system, the number of transactions per second measures the effectiveness. An OLTP Data Warehouse System contains current and detailed data and is maintained in the schemas in the entity model (3NF). For Example − A Day-to-Day transaction system in a retail store, where the customer records are inserted, updated and deleted on a daily basis. It provides faster query processing. OLTP databases contain detailed and current data. The schema used to store OLTP database is the Entity model. In an OLAP system, there are lesser number of transactions as compared to a transactional system. The queries executed are complex in nature and involves data aggregations. We save tables with aggregated data like yearly (1 row), quarterly (4 rows), monthly (12 rows) or so, if someone has to do a year to year comparison, only one row will be processed. However, in an un-aggregated table it will compare all the rows. This is called Aggregation. There are various Aggregation functions that can be used in an OLAP system like Sum, Avg, Max, Min, etc. For Example − SELECT Avg(salary) FROM employee WHERE title = 'Programmer'; These are the major differences between an OLAP and an OLTP system. Indexes − An OLTP system has only few indexes while in an OLAP system there are many indexes for performance optimization. Indexes − An OLTP system has only few indexes while in an OLAP system there are many indexes for performance optimization. Joins − In an OLTP system, large number of joins and data are normalized. However, in an OLAP system there are less joins and are de-normalized. Joins − In an OLTP system, large number of joins and data are normalized. However, in an OLAP system there are less joins and are de-normalized. Aggregation − In an OLTP system, data is not aggregated while in an OLAP database more aggregations are used. Aggregation − In an OLTP system, data is not aggregated while in an OLAP database more aggregations are used. Normalization − An OLTP system contains normalized data however data is not normalized in an OLAP system. Normalization − An OLTP system contains normalized data however data is not normalized in an OLAP system. Data mart focuses on a single functional area and represents the simplest form of a Data Warehouse. Consider a Data Warehouse that contains data for Sales, Marketing, HR, and Finance. A Data mart focuses on a single functional area like Sales or Marketing. In the above image, you can see the difference between a Data Warehouse and a data mart. A fact table represents the measures on which analysis is performed. It also contains foreign keys for the dimension keys. For example − Every sale is a fact. The Dimension table represents the characteristics of a dimension. A Customer dimension can have Customer_Name, Phone_No, Sex, etc. A schema is defined as a logical description of database where fact and dimension tables are joined in a logical manner. Data Warehouse is maintained in the form of Star, Snow flakes, and Fact Constellation schema. A Star schema contains a fact table and multiple dimension tables. Each dimension is represented with only one-dimension table and they are not normalized. The Dimension table contains a set of attributes. In a Star schema, there is only one fact table and multiple dimension tables. In a Star schema, each dimension is represented by one-dimension table. Dimension tables are not normalized in a Star schema. Each Dimension table is joined to a key in a fact table. The following illustration shows the sales data of a company with respect to the four dimensions, namely Time, Item, Branch, and Location. There is a fact table at the center. It contains the keys to each of four dimensions. The fact table also contains the attributes, namely dollars sold and units sold. Note − Each dimension has only one-dimension table and each table holds a set of attributes. For example, the location dimension table contains the attribute set {location_key, street, city, province_or_state, country}. This constraint may cause data redundancy. For example − "Vancouver" and "Victoria" both the cities are in the Canadian province of British Columbia. The entries for such cities may cause data redundancy along the attributes province_or_state and country. Some dimension tables in the Snowflake schema are normalized. The normalization splits up the data into additional tables as shown in the following illustration. Unlike in the Star schema, the dimension’s table in a snowflake schema are normalized. For example − The item dimension table in a star schema is normalized and split into two dimension tables, namely item and supplier table. Now the item dimension table contains the attributes item_key, item_name, type, brand, and supplier-key. The supplier key is linked to the supplier dimension table. The supplier dimension table contains the attributes supplier_key and supplier_type. Note − Due to the normalization in the Snowflake schema, the redundancy is reduced and therefore, it becomes easy to maintain and the save storage space. A fact constellation has multiple fact tables. It is also known as a Galaxy Schema. The following illustration shows two fact tables, namely Sales and Shipping − The sales fact table is the same as that in the Star Schema. The shipping fact table has five dimensions, namely item_key, time_key, shipper_key, from_location, to_location. The shipping fact table also contains two measures, namely dollars sold and units sold. It is also possible to share dimension tables between fact tables. For example − Time, item, and location dimension tables are shared between the sales and shipping fact table. An ETL tool extracts the data from all these heterogeneous data sources, transforms the data (like applying calculations, joining fields, keys, removing incorrect data fields, etc.), and loads it into a Data Warehouse. A staging area is required during the ETL load. There are various reasons why staging area is required. The source systems are only available for specific period of time to extract data. This period of time is less than the total data-load time. Therefore, staging area allows you to extract the data from the source system and keeps it in the staging area before the time slot ends. The staging area is required when you want to get the data from multiple data sources together or if you want to join two or more systems together. For example − You will not be able to perform an SQL Query joining two tables from two physically different databases. The data extractions’ time slot for different systems vary as per the time zone and operational hours. The data extracted from the source systems can be used in multiple Data Warehouse Systems, Operation Data Stores, etc. ETL allows you to perform complex transformations and requires extra area to store the data. In data transformation, you apply a set of functions on extracted data to load it into the target system. The data that does not require any transformation is known as a direct move or pass through data. You can apply different transformations on extracted data from the source system. For example, you can perform customized calculations. If you want sum-of-sales revenue and this is not in database, you can apply the SUM formula during transformation and load the data. For example − If you have the first name and the last name in a table in different columns, you can use concatenate before loading. During the Load phase, data is loaded into the end-target system and it can be a flat file or a Data Warehouse system. BI (Business Intelligence) tools are used by business users to create basic, medium, and complex reports from the transactional data in data warehouse and by creating Universes using the Information Design Tool/UDT. Various SAP and non-SAP data sources can be used to create reports. There are quite a few BI Reporting, Dashboard and Data Visualization Tools available in the market. Some of which are as follows − SAP Business Objects Web Intelligence (WebI) Crystal Reports SAP Lumira Dashboard Designer IBM Cognos Microsoft BI Platform Tableau Business Intelligence JasperSoft Oracle BI OBIEE Pentaho QlickView SAP BW SAS Business Intelligence Necto Tibco Spotfire IBM Cognos Business Intelligence is a web based reporting and analytic tool. It is used to perform data aggregation and create user friendly detailed reports. Reports can contain Graphs, Multiple Pages, Different Tabs and Interactive Prompts. These reports can be viewed on web browsers, or on hand held devices like tablets and smartphones. Cognos also provides you an option to export the report in XML or PDF format or you can view the reports in XML format. You can also schedule the report to run in the background at specific time period so it saves the time to view the daily report as you don’t need to run the report every time. IBM Cognos provides a wide range of features and can be considered as an enterprise software to provide flexible reporting environment and can be used for large and medium enterprises. It meets the need of Power Users, Analysts, Business Managers and Company Executives. Power users and analysts want to create adhoc reports and can create multiple views of the same data. Business Executives want to see summarize data in dashboard styles, cross tabs and visualizations. Cognos allows both the options for all set of users. Cognos BI reporting allows you to bring the data from multiple databases into a single set of reports. IBM Cognos provides wide range of features as compared to other BI tools in the market. You can create and schedule the reports and complex report can be designed easily in the Cognos BI Reporting Tool. The Cognos BI Reporting Tool allows to create a report for a set of users like – Power users, Analysts, and Business Executives, etc. IBM Cognos can handle a large volume of data and is suitable for medium and large enterprises to fulfil BI needs. Cognos BI is considered to be a 3-tier architecture layout. At the top, there is a Web Client or a Web Server. The 2nd tier consists of a Web Application Server. While the bottom tier consists of a Data layer. These tiers are separated by firewalls and communication between these tiers happens using SOAP and HTTP protocols. The web client allows BI users to access TM1 data and interact with data in any of the supported browsers. Tier 1 is responsible to manage the gateway and is used for encryption and decryption of passwords, extract information needed to submit a request to the BI server, authentication of server and to pass the request to Cognos BI dispatcher for processing. This tier hosts the Cognos BI server and its associated services. Application server contains Application Tier Components, Content Manager and Bootstrap service. Cognos TM1 Web Application Server runs on Java based Apache Tomcat server. Using this tier, Microsoft Excel worksheets can be converted to TM1 Web sheets and also allows to export web sheets back to Excel and PDF format. This tier contains content and data sources. It contains TM1 Admin server and at least one TM1 server. TM1 Admin server can be installed on any computer on your LAN and it must reside on same network as TM1 server. The version of TM1 server should be equal or most recent then the version of Cognos TM1 web. In this section we will discuss the different versions of Cognos. And then there were different sub-versions of the – Cognos Business Intelligence 10, which were − IBM Cognos Business Intelligence 10.1 IBM Cognos Business Intelligence 10.1.1 IBM Cognos Business Intelligence 10.2 IBM Cognos Business Intelligence 10.2.1 IBM Cognos Business Intelligence 10.2.2 IBM Cognos Business Intelligence 11.0.0 There are various other BI reporting tools in the market that are used in medium and large enterprise for analytics and reporting purpose. Some of them are described here along with its key features. Following are the key features that are supported by both the tools − Standard Reporting Ad-hoc Reporting Report output and Scheduling Data Discovery and Visualization Access Control and Security Mobile Capabilities Cognos can be considered as a robust solution which allows you to create a variety of reports like Cross tabs, Active reports (latest feature in Cognos 10), and other report structure. You can create user prompts, scheduling of report is easy and you can export and view reports in different formats. The Microsoft BI provides easy visualization of business data as well as Easy integration with Microsoft Excel. SAP BO supports its own ETL tool SAP Data Services. IBM Cognos doesn’t support its own ETL tool. The IBM Cognos 8 doesn’t provide offline reporting features however it is there in SAP Business Objects reporting tools. In Cognos the entire functionality is divided into multiple tools Query studio, Analysis studio, event studio etc. It is a tough task to learn all the tools. In SAP Business Objects, you have multiple tools like Web Intelligence for reporting, IDT for Universe Designer, Dashboard Designer so users feel that it is a tough task to manage and learn all the tools. In IBM Cognos, data generated can be transformed in various formats (for instance, HTML, PDF, etc.) and can also be accessed from multiple locations (e-mail, mobile, office, etc.). IBM provides several planning capabilities such as forecasts, budgets, advance scenario modelling etc. Selection of BI tool depends on various factors like need of company, software version, features supported and the license cost. There are various components in Cognos that communicate with each other using BI Bus and are known as Simple Object Access Protocol (SOAP) and supports WSDL. BI Bus in Cognos architecture is not a software component but consists of a set of protocols that allows communication between Cognos Services. The processes enabled by the BI Bus protocol includes − Messaging and dispatching Log message processing Database connection management Microsoft .NET Framework interactions Port usage Request flow processing Portal Pages When you install Cognos 8 using the Installation wizard, you specify where to install each of these components − The Cognos 8 Web server tier contains one or more Cognos 8 gateways. The web communication in Cognos 8 is typically through gateways, which reside on one or more web servers. A gateway is an extension of a web server program that transfers information from the web server to another server. Web communication can also occur directly with a Cognos 8 dispatcher but this option is less common. Cognos 8 supports several types of Web gateways, including − CGI − The default gateway, CGI can be used for all supported Web servers. However, for enhanced performance or throughput, you may choose one of the other supported gateway types. ISAPI − This can be used for the Microsoft Internet Information Services (IIS) Web server. It delivers faster performance for IIS. apache_mod − You can use an apache_mod gateway with the Apache Web server. Servlet − If your Web server infrastructure supports servlets or you are using an application server, you can use a servlet gateway. This component consists of a dispatcher that is responsible to operate services and route requests. The dispatcher is a multithreaded application that uses one or more threads per request. The configuration changes are routinely communicated to all the running dispatchers. This dispatcher includes Cognos Application Firewall to provide security for Cognos 8. The dispatcher can route requests to a local service, such as the report service, presentation service, job service, or monitor service. A dispatcher can also route requests to a specific dispatcher to run a given request. These requests can be routed to specific dispatchers based on load-balancing needs, or package or user group requirements. Content Manager contains Access Manager, the primary security component of Cognos 8. Access Manager leverages your existing security providers for use with Cognos 8. It provides Cognos 8 with a consistent set of security capabilities and APIs, including user authentication, authorization, and encryption. It also provides support for the Cognos namespace. You can report interactive user reports in Cognos Studio on the top of various data sources by creating relational and OLAP connections in web administration interface which are later used for data modeling in Framework Manager known as packages. All the reports and dashboards that are created in Cognos Studio they are published to Cognos Connection and portal for distribution. The report studio can be used to run the complex report and to view the Business Intelligence information or this can also be accessed from different portals where they are published. Cognos Connections are used to access reports, queries, analysis, and packages. They can also be used to create report shortcuts, URLs and pages and to organize entries and they can also be customized for other use. A data source defines the physical connection to a database and different connection parameters like connection time out, location of database, etc. A data source connection contains credential and sign on information. You can create a new database connection or can also edit an existing data source connection. You can also combine one or more data source connections and create packages and published them using Framework manager. The dynamic query mode is used to provide communication to data source using XMLA/Java connections. To connect to the Relation database, you can use type4 JDBC connection which converts JDBC calls into vendor specific format. It provides improved performance over type 2 drivers because there is no need to convert calls to ODBC or database API. Dynamic query mode in Cognos connection can support the following types of Relational databases − Microsoft SQL Server Oracle IBM DB2 Teradata Netezza To support OLAP data sources, Java/XMLA connectivity provides optimized and enhanced MDX for different OLAP versions and technology. The Dynamic query mode in Cognos can be used with the following OLAP data sources − SAP Business Information Warehouse (SAP BW) Oracle Essbase Microsoft Analysis Services IBM Cognos TM1 IBM Cognos Real-time Monitoring The DB2 connection type are used to connect to DB2 Windows, Unix and Linux, Db2 zOS, etc. The common connection parameters used in DB2 data source includes − Database Name Timeouts Signon DB2 connect string Collation Sequence To create models in IBM Cognos Framework Manager, there is a need to create a data source connection. When defining the data source connection, you need to enter the connection parameters – location of database, timeout interval, Sign-on, etc. In IBM Cognos Connection → click on the Launch IBM Cognos Administration In the Configuration tab, click Data Source Connections. In this window, navigate to the New Data Source button. Enter the unique connection name and description. You can add a description related to the data source to uniquely identify the connection and click the next button. Select the type of connection from the drop down list and click on the next button as shown in the following screenshot. In the next screen that appears, enter the connection details as shown in the following screenshot. You can use the Test connection to test the connectivity to the data source using connection parameters that you have defined. Click on the finish button once done. Data Source Security can be defined using IBM Cognos authentication. As per the data source, different types of authentication can be configured in the Cognos connection − No Authentication − This allows login to the data source without using any sign-on credentials. This type of connection doesn’t provide data source security in connection. IBM Cognos Software Service Credential − In this type of a sign-on, you log in to the data source using a logon specified for the IBM Cognos Service and the user does not require a separate database sign-on. In a live environment, it is advisable to use individual database sign on. External Name Space − It requires the same BI logon credentials that are used to authenticate the external authentication namespace. The user must be logged into the name space before logging in to the data source and it should be active. All the data sources also support data source sign-on defined for everyone in the group or for individual users, group or roles. If the data source requires a data source sign-on, but you don't have the access to a sign-on for this data source, you will be prompted to log on each time you access the data source. IBM Cognos also supports security at cube level. If you are using cubes, security may be set at the cube level. For Microsoft Analysis Service, security is defined at the cube level roles. In this chapter, we will discuss how to create a package using COGNOS. In IBM Cognos, you can create packages for SAP BW or power cube data sources. Packages are available in the Public folder or in My folder as shown in the following screenshot. Once a package is deployed, the default configuration is applied on the package. You can configure a package to use different settings or you can modify the settings of the existing package. To configure a package, you should have administrator privilege. Locate the package in the Public folder, click on More button under the Action tab as shown in the following screenshot. Click on Modify the package configuration and Click Select an analysis. Select the default analysis to be used for this package when a new analysis is created. Click OK and change the package settings as required and click Finish. In the Package tab, Public folder, you can also create a new Package using the IBM Cognos connection. Select the data source that you want to use in the package and click OK. You can also schedule the reports in IBM Cognos as per your business requirements. Scheduling a report allows you to save the refresh time. You can define various scheduling properties like frequency, time zone, start and end date, etc. To schedule a report, select the report and go to More button as shown in the following screenshot. You have an option to add a new schedule. Select the New Schedule button as shown in the following screenshot. You can select the following options under the Schedule tab − Frequency Start and End Priority Daily Frequency, etc. When the scheduling properties are defined, you can save it by clicking the OK button at the bottom. Disabling the Schedule options allows you to make the schedule inactive but the schedule will be saved for the report. You can remove this option any time to enable the schedule again. To edit an existing schedule, select the report and go to More. You can modify an existing schedule or remove the schedule permanently. In this chapter, we will discuss regarding what a Framework Manager is and about its various other components. IBM Cognos Framework Manager is used to create business model of metadata derived from one or more data sources. It is a Windows based tool which is used to publish the business models to Cognos BI in the form of packages which can be used for analytical reporting and analysis. Before you start a new project in Framework Manager, it is necessary that you go through BI reporting requirements that helps you to identify data strategies, metadata, report package delivery, etc. This helps you to identify which data sources are required in the Framework Manager to get the required data in the BI report. You should consider the following factors before starting a new project in the Framework manager. Data Sources required to meet BI needs. Types of DW system Data refresh in Data Warehouse BI Reporting- Daily, Weekly, or monthly. A Metadata model is defined as the collection of database objects (tables, columns and relationship between objects) imported from the database. When you run the report, metadata published in BI Cognos portal generates a SQL statement according to the query. The IBM Cognos Framework manager can hide the complexity of data in the data source and also alter the way how data is shown to users. It provides a view that is easy for BI users to understand and perform analysis and reporting. The following screenshot shows the IBM Cognos BI Framework Manager User Interface. Following are the various components of the above screenshot that are explained in detail for better understanding − Project Viewer − This pane on left side allows you to access all the existing projects in a tree format. Project Viewer − This pane on left side allows you to access all the existing projects in a tree format. Project Info − This is the center pane that is used to manage objects of an existing project. This has three tabs: Explorer, Diagram and Dimension. Project Info − This is the center pane that is used to manage objects of an existing project. This has three tabs: Explorer, Diagram and Dimension. Properties − This pane at the bottom is used to set the value of different properties of an object in a project. Properties − This pane at the bottom is used to set the value of different properties of an object in a project. Tools − This pane on the right side provides you various important useful tools. You can perform a search, or display an object and its dependent objects, changing project language, etc. Tools − This pane on the right side provides you various important useful tools. You can perform a search, or display an object and its dependent objects, changing project language, etc. For importing Metadata from a Relational Database, you map the database objects to the Framework manager objects. In the Framework Manager, you can import all the objects or you can select particular objects like tables, columns, functions, stored procedures, views, etc. Only user defined Stored procedures are supported. To create a metadata model, run metadata wizard from the Action menu. Select a data source connection and click the Next button. Select the check boxes for the objects you want to import. Specify how the import should handle duplicate object names. Choose either to import and create a unique name, or not to import. If you choose to create a unique name, the imported object appears with a number. For example − When you see QuerySubject and QuerySubject1 in your project. Then click Import. Import statistics including a list of objects that could not be imported and a count of objects that were imported are shown. The next step is to click on the Finish button. After importing Metadata, you must check the imported Metadata for the following areas − Relationships and Cardinality Determinants Usage property for query items Regular Aggregate property for query items In the Framework Manager, you can also import metadata from an existing Cognos 8 Model. To import Metadata from the Cognos 8 model, go to Actions → Run Metadata wizard. Click on the Cognos 8 Model and then the Next button. Navigate to the .cpf file from Cognos 8 Model and the click on Next. Select the check boxes for objects you want to import and then click on Next and then on Finish. Once you import the metadata, next is to validate the objects for reporting requirement. You can select the objects that appear in the report and test them. You can create two views of the Metadata Model − Import View Business View The Import view shows you the metadata imported from the data source. To validate the data as per your BI reporting, you can perform the following steps − Ensure that the relationships reflect the reporting requirements. Ensure that the relationships reflect the reporting requirements. Optimize and customize the data retrieved by the query subjects. Optimize and customize the data retrieved by the query subjects. Optimize and customize the data retrieved by dimensions. You may want to store dimensions in a separate dimensional view. Optimize and customize the data retrieved by dimensions. You may want to store dimensions in a separate dimensional view. Handle support for multilingual metadata. Handle support for multilingual metadata. Control how data is used and formatted by checking query item properties. Control how data is used and formatted by checking query item properties. Business view is used to provide the information in metadata. You can perform calculations, aggregations and apply filters in Business view and easily allow users to build the report. You can add business rules such as custom calculations and filters that define the information users can retrieve. Organize the model by creating separate views for each user group that reflect the business concepts familiar to your users. Relationships are used to create queries on multiple objects in a metadata model. Relationships can be bidirectional and without creating relationship, objects are individual entities with no use in metadata model. Each object in metadata model is connected using primary or foreign key in the data source. You can create or remove relationships in the metadata model to meet the business requirements. There are different relationships which are possible, some of them are − One to One − When an instance of one query subject is related to another instance. For example: Each customer has one customer id. One to One − When an instance of one query subject is related to another instance. For example: Each customer has one customer id. One to Many − This relationship occurs when one instance of query subject relates to multiple instances. For example: Each doctor has many patients. One to Many − This relationship occurs when one instance of query subject relates to multiple instances. For example: Each doctor has many patients. Many to Many − This relationship occurs when many instances of a query subject relates to multiple instances. For example: Each patient has many doctors. Many to Many − This relationship occurs when many instances of a query subject relates to multiple instances. For example: Each patient has many doctors. It is defined as the number of related rows for each of the two query subjects. Cardinality is used in the following ways − Loop Joins in Star schema Optimized access to data source Avoid double counting fact data While using the Relational database as a data source, Cardinality can be defined considering the following rules − Primary and Foreign keys Match query item names represent uniquely indexed columns Matching query item names The most common ways to define Cardinality is by using the primary and foreign key. To view the key information that was imported, right click on the query subject → Edit Definition. You can import many to many relationships, optional relationships, and outer joins from the data source. In the Framework manager, a relation is represented by Merise notation. The first part of this notation represents the type of join for this relationship. 0..1 represents zero or one match 1..1 represents one to one match 0..n represents Zero or no matches 1..n represents One or more matches 1 − An inner join with all matching rows from both objects. 0 − An Outer join with all objects from both, including the items that don’t match. To create a Relationship or to combine logically related objects which are not joined in metadata import. You can manually create relationship between objects or can automatically define relationship between objects based on selected criteria. To create a Relationship, use CTRL key to select one or more query items, subjects or dimensions. Then go to Action Menu → Create Relationship. If this is a valid Relationship, the Framework manager wants to create a shortcut to the relationship. You can then click on the OK button. Once you create a relationship after the metadata import, you can also modify the relationship or Cardinality in the Framework manager. To edit a Relationship, click a relationship and from Action menu → click Edit Definition. From the Relationship Expression tab → Select Query items, Cardinalities and Operators. To create an additional Join, go to the Relationship Expression tab → New Link and Define New Relationship. To test this Relationship, go to Relationship SQL tab → rows to be returned → Test. Click on OK button. A Relationship shortcut is defined as the pointer to an existing relationship and to reuse the definition of an existing relationship. When you make any change to the source Relationship, they are automatically updated in shortcuts. Relationship shortcuts are also used to resolve ambiguous relationship between query subjects. The Framework Manager asks whether you want to create a relationship shortcut whenever you create a relationship and both these conditions are true. At least one end for the new relationship is a shortcut. A relationship exists between the original objects. Go to Action Menu → Create Relationship. If this is a valid Relationship, Framework manager wants to create a shortcut to the relationship. Click YES. A list appears of all relationships in which one end is a model object and the other end is either another model object or a shortcut to another model object. Click OK. A query subject is defined as a set of query items that have an inherent relationship. A query subject can be used to customize the data they retrieve using a Framework Manager. The following are the query subject types in a Framework Manager − Data Source Query Subject − These are based on the Relational metadata defined by the SQL statements and are automatically created for each table and view when you import metadata into model. Note − The data source query subject references the data from only one data source at a time, but you can directly edit the SQL that defines the retrieve data to edit the query subject. Data Source Query Subject − These are based on the Relational metadata defined by the SQL statements and are automatically created for each table and view when you import metadata into model. Note − The data source query subject references the data from only one data source at a time, but you can directly edit the SQL that defines the retrieve data to edit the query subject. Model Query Subjects − They are not directly created from a data source but are based on the query items defined in other query subjects or dimensions. Using the model query subject, it allows you to create more abstract and business view of data source. Model Query Subjects − They are not directly created from a data source but are based on the query items defined in other query subjects or dimensions. Using the model query subject, it allows you to create more abstract and business view of data source. Stored Procedure Query Subjects − They are created when a Procedure is imported from a Relational data source. IBM Cognos Framework Manager only supports user defined Stored Procedures and system stored procedures are not supported. Stored Procedure Query Subjects − They are created when a Procedure is imported from a Relational data source. IBM Cognos Framework Manager only supports user defined Stored Procedures and system stored procedures are not supported. From Actions Menu → Create → Query Subject. Enter the name of a new Query Subject. Click on Data Source → OK to open new Query Subject wizard. Follow the steps till the Finish button appears → Finish Right click on Query Subject → Edit Definition. Click on the SQL tab → Available database objects box, drag objects to the SQL box. You can also insert a data source reference, insert a macro, embed a calculation and embed a filter. Select the actions from the list and click OK. When you edit any Relation database source, create or query a Relation database, then SQL is used in the background. You can use the following options − Cognos SQL Native SQL Pass through SQL To edit SQL of the model query subject, copy SQL from query Information tab and paste to the new data source query subject. It is possible to convert a model query subject to data source query subject. Click Data Source query subject and Action menu → Edit Definition. Click on SQL button, drag objects or type in SQL you want. Click OK. You can select the type of SQL to be used when you define data source query subject. These factors should be considered while considering type of SQL − Improved performance Work on all supported database Performance Optimized Specific to Database SQL doesn’t work on different database. You can’t use SQL that data source doesn’t support for subqueries. No option for Framework Manager to optimize performance automatically Also note that it is not possible to change the type of SQL for query subjects based on the OLAP data sources. To change SQL type, go to Query subject you want to change. Go to Actions menu → Edit Definition and go to Query Information button. Go to Options → SQL Settings tab. To change the type of SQL, click on SQL Type List. Then, click OK. Query Studio is defined as a web based tool for creating queries and reports in Cognos 8. It is also used to run simple queries and reports as well. In Query Studio, the following functions can be performed − Viewing Data − Using Query Studio, you can connect to data source to view the data in a tree hierarchy. You can see query subject, query item details, etc. Viewing Data − Using Query Studio, you can connect to data source to view the data in a tree hierarchy. You can see query subject, query item details, etc. Creating BI Reports − You can use Query studio to create simple reports by using the data source. You can also refer existing reports to create a new report. Creating BI Reports − You can use Query studio to create simple reports by using the data source. You can also refer existing reports to create a new report. Changing Existing Reports − You can also change existing reports by editing report layout – Add charts, titles, headings, border styles, etc. Changing Existing Reports − You can also change existing reports by editing report layout – Add charts, titles, headings, border styles, etc. Data Customization in Report − You can apply various customizations in reports- Filters, Calculations and aggregations to perform data analysis, drill up and drill down, etc. Data Customization in Report − You can apply various customizations in reports- Filters, Calculations and aggregations to perform data analysis, drill up and drill down, etc. Using ad-hoc reporting, a user can create queries or reports for ad-hoc analysis. Ad-hoc reporting feature allows business users to create simple queries and reports on the top of fact and dimension table in data Warehouse. The Query Studio in Cognos BI, provides the following features − View data and perform ad-hoc data analysis. Save the report for future use. Work with data in the report by applying filters, summaries and calculations. To create ad-hoc report using query studio, login to IBM Cognos software and click on Query my data. Select the report package. Next time you visit this page; you will see your selection under the recently used packages. Click on the package name. In the next screen, you can add Dimension elements, filters and prompts, facts and calculation, etc. You should insert the objects in this order. To insert object in the report, you can use Insert button at the bottom. Insert and filter dimension elements Insert filters and prompts Insert facts and calculations Apply finishing touches Save, run, collaborate, and share At the top, you have the tool bar, where you can create a new report, save existing report, cut, paste, insert charts, drill up and down, etc. When you insert all the objects to a report, you can click on the Run option () at the top. You can use different report types in the Cognos Query Studio to meet the business requirements. You can create the following report types in the Query Studio − List Reports − These reports are used to show your entire customer base as shown in the following screenshot. Crosstab Reports − These are used to show quantity sold with product and region on different axis. Charts − You can insert charts to show data graphically. You can combine a chart with a Crosstab or also with a list report. You can create a new report by inserting objects from the data source in the Query Studio. You can also change an existing report and save it with different name. You can open Query Studio by going to Query my data option on the home page or you can go to Launch → Query Studio. In the next screen, you will be prompted to select a package to add objects in the reports. You can select a recently used package or any other package created in the Framework Manager. You can see Query items listed on the left side. You can add data and save the report. You can open an existing report in the Query Studio and save it with a different name after making changes. To open an existing report, locate and click the name of the report you want to open. The report opens in the Query Studio. You can use the Open with Query Studio to identify a Query Studio report in the Cognos Connection. Or you can launch Query Studio and go to open option at the top. Search the report in the list of Available folders → OK You can add objects from a data source. Each object has a representative icon and can insert all the following objects to a report. When you save a report in the Query Studio, it saves the query definition. It doesn’t save the data while saving the report. When you run a report saved a week back, the data in that report reflects the recent changes in the data source. To save a report, click on the Save icon at the top. In the next screen, enter the name, description and location where you want to save the report → OK. You can use Save as option to save a report with different name or at a different location as shown in the following screenshot. Specify a name and location − To include a description, type the information you want to add in the Description box. Click OK. A report in the Query Studio runs when you update data from data source in the report. When you open an existing report or make any changes to a report, Query Studio again runs the report. You can use the following options to run a report − Run with Prompt − You can run a report using a user prompt. When you run the report, you are prompted to select the value. Run with Prompt − You can run a report using a user prompt. When you run the report, you are prompted to select the value. Run with all Data − The Run with all data command runs the report using the full data source. Running a report can take a long time. If you plan to make several changes to a report, run the report in preview mode to save time and computer resources by limiting the rows of data that your report retrieves. Run with all Data − The Run with all data command runs the report using the full data source. Running a report can take a long time. If you plan to make several changes to a report, run the report in preview mode to save time and computer resources by limiting the rows of data that your report retrieves. Preview Report with no Data − You can use the preview option when you want to see how the report will look like. This is useful when you want to make formatting changes. Preview Report with no Data − You can use the preview option when you want to see how the report will look like. This is useful when you want to make formatting changes. Open the report that you want in Query Studio. From the Run Report menu, choose how to run the report − To run the report using all the data, click Run with All Data as shown in the following screenshot. To run the report using limited data, click Preview with Limited Data. If the package that the report is based on contains a design filter, performance is improved. To run the report using no data, click Preview with No Data. You can run a report in PDF, XML or in a CSV format. To run a report in different formats, select the report and click on Run with options. Select the format in which you want to run the report. You can choose from the following formats. Select the format and click Run at the bottom as shown in the following screenshot. You can also print a report to get a copy on paper. You can directly enter the Printer location while running the report or you can run the report in a PDF format and later you can take a printout of the report. To take the print of the report directly, select the report and click on Run with options. In the Delivery mode, select print the report and enter the location as shown in the following screenshot. Report Studio is a web-based tool that is used by report developers to create multi pages, complex reports on top of multiple data sources. You can create sales reports, inventory reports, account statements, balance sheets, etc. To create Reports in Report Studio, you should have a good understanding on user interface. Report Studio user interface is divided into two parts − Explorer Bar on the Left Side. Work area for report design. The above screenshot has three major blocks, which are as follows − Insertable Object Pane − The Insertable Objects pane contains objects that you can add to a report. These objects can be added by dragging them to the work area. It can contain − Source tab (That contains item from the package). Data Items (Queries created in the report). Toolbox (different objects like graphics that can be added to the report) Insertable Object Pane − The Insertable Objects pane contains objects that you can add to a report. These objects can be added by dragging them to the work area. It can contain − Source tab (That contains item from the package). Source tab (That contains item from the package). Data Items (Queries created in the report). Data Items (Queries created in the report). Toolbox (different objects like graphics that can be added to the report) Toolbox (different objects like graphics that can be added to the report) Properties Pane − The Properties pane lists the properties that you can set for an object in a report. To get the help, select the property and use keyboard key F1. Properties Pane − The Properties pane lists the properties that you can set for an object in a report. To get the help, select the property and use keyboard key F1. Work Area − The work area is known as the area where the report is designed. Work Area − The work area is known as the area where the report is designed. On the home page, go to Launch → Report Studio → Select a Package or in the IBM Cognos Welcome page, click on Author advanced reports to open Report Studio. On the home screen of Report Studio, you have an option to create a new report or open an existing report. You will be prompted to select the type of report you want to create. You have the option to select different report types. In Report Studio, you can create different types of reports. They allow you to present the data in different formats like a list report can be used to show the customer information. The following reports can be created in Report Studio − This report is used to show the data in detailed format. Data is shown in rows and columns and each column contains all the values of a data item. Like list report, a cross tab report also shows the data in row and columns, but the data is compact and not detailed. At the intersection points of rows and columns, you show the summarized data. You can use the Report Studio to create many chart types, including column, bar, area, and line charts. You can also create custom charts that combine these chart types. You can also use maps in the Report Studio to present data for a particular region, country or a location. A map report consists of three parts − Region Layer Point Layer Display Layer Repeaters are used to add repeat items in a report while running the report. To add a Repeater, drag a repeater from the tool box to work area. A list report that shows the data in rows and columns and each cell shows the data in the database or you can also add custom calculations in a list report. To create a new list report, go to New → Blank as shown in the following screenshot. When you select a list report, you get the following structure of the report in the Report Studio. You have to drag the objects from the package on the left side to the report structure. You can also edit the title of the report that will appear once you run the report. You can use different tools at the top for the report formatting. To save a report, click on the save button. To run a report, click on Run report. Once you save the report, you have an option to save it in the Public folder or My folder. When you click on the Run option, you can select different formats to run the report. You will be prompted to select the type of report you want to create. You have option to select from different report types. Select Crosstab as type of the report and click OK. The structure of a Crosstab report is opened as shown in the following screenshot. In the Insertable Objects pane, on the Source tab, click the data item you want to add to the crosstab and drag it to the Rows or Columns. A black bar indicates where you can drop the data item. Repeat the above given steps to insert additional data items. You add dimensions to rows or columns and to add measures to the crosstab, drag the measures you want to Measures. When you run the report, a crosstab report is generated that has one edge. You can also format the crosstab to give them appearance as per the requirement. When you specify formatting for all rows, columns, fact cells, or the crosstab, the formatting is automatically applied to any new items you add. When you apply styles such as font color, rows and columns, intersections this is applied in the following order. Crosstab fact cells Fact cells in the outermost rows Fact cells in the innermost rows Fact cells in the outermost columns Fact cells in the innermost columns Crosstab intersections To do formatting of crosstab, click anywhere in the Crosstab. Click the select ancestor button in the title bar of the Properties pane and then click Crosstab as shown in the following screenshot. In the Properties pane, click the property you want and then specify a value. For example, if you want to specify a background color, click on Background Color and choose the color you want to use. You can also right-click the row or column and click Select Member Fact Cells. In the Properties pane, click the property you want and then specify a value. In Report Studio, you can create many chart types like column, bar, area, line charts or a custom chart that combines these chart types. In the Source tab, expand the query. Drag Revenue to the Measure (y-axis) drop zone. Drag Current year to the Series drop zone. Drag Order to the Categories (x-axis) drop zone. Drag the objects as shown in the above screenshot. Save the chart using the tool bar at the top. Save it to Public or My Folder as mentioned in the previous topic. Run the report to see the result in a chart format. You can also create a Repeater table or a map report in Cognos Report Studio. There are various Report functions that can be used in a Cognos report. Some of these different report functions include − This function is used to return a positive or a negative number representing the number of days between the two datetime expressions. If a timestamp_exp1 < timestamp_exp2 then the result will be a –ve number. _days_between(timestamp_exp1, timestamp_exp2) This function is used to return a number representing the number of days remaining in the month represented by the datetime expression timestamp_exp. _days_to_end_of_month(timestamp_exp) This function is used to return a datetime that is the first day of the month represented by timestamp_exp. This function is used to return the datetime resulting from adding integer_exp days to timestamp_exp. _add_days(timestamp_exp, integer_exp) This function is used to return the datetime resulting from adding integer_exp months to timestamp_exp. _add_months(timestamp_exp, integer_exp) This function is used to return the datetime resulting from adding integer_exp years to timestamp_exp. _add_years(timestamp_exp, integer_exp) This function is used to return a number that is obtained from subtracting timestamp_exp from today's date in YYYYMMDD format (years, months, days). _age(timestamp_exp) This function is used to return the day of week (between 1 and 7), where 1 is the first day of the week as indicated by integer_exp (between 1 and 7, 1 being Monday and 7 being Sunday). Note that in ISO 8601 standard, a week begins with Monday being day 1. In North America where Sunday is the first day of the week being day 7. _day_of_week(timestamp_exp, integer_exp) This function is used to return the ordinal for the day of the year in date_ exp (1 to 366). Also known as the Julian day. _day_of_year(timestamp_exp) Like these, there are various other Report functions as well that can be used. This is used to ensure that your report doesn’t contain any error. When a report created in the older version of Cognos is upgraded it is automatically validated. To validate a report, go to the Tools menu and click on the Validate button as shown in the following screenshot. There are different Validation levels − Error − To retrieve all errors returned from the query. Error − To retrieve all errors returned from the query. Warning − To retrieve all errors and warnings returned from the query. Warning − To retrieve all errors and warnings returned from the query. Key Transformation − To retrieve important transformation steps. Key Transformation − To retrieve important transformation steps. Information − To retrieve other information related to query planning and execution. Information − To retrieve other information related to query planning and execution. You can run the report with different options. To set the report options, go to Run options. You get different options − Format − You can select from different format. Format − You can select from different format. To select Paper size − You can select from different paper sizes, orientation. To select Paper size − You can select from different paper sizes, orientation. Select Data mode − All data, limited data, and no data. Select Data mode − All data, limited data, and no data. Language − Select language in which you want to run the report. Language − Select language in which you want to run the report. Rows per page and prompt option, etc. Rows per page and prompt option, etc. Report Administration allows you to give permissions to different users on the report level. You can define various other properties like output versions, permissions, general properties, etc. To open Report Properties and the permissions tab, go to More Options in the IBM Cognos home page. You can select the following actions in more options − In the permission tab, you can specify access permissions for this entry. By default, an entry acquires its access permissions from a parent. You can override those permissions with the permissions set explicitly for this entry. You can also move, copy or delete a report in More Options. You can create a shortcut entry or report view of the report. Filters are used to limit the data that you want in your report. You can apply one or more filters in a Cognos report and the report returns the data that meet the filter conditions. You can create various custom filters in a report as per the requirement. Select the column to filter by. Click the drop down list from the Filter button. Choose Create Custom Filter. The Filter Condition dialog displays. In the next window, define the filter’s parameters. Condition − click the list arrow to see your choices (Show or Don’t show the following values). Condition − click the list arrow to see your choices (Show or Don’t show the following values). Values − click the list arrow to see your choices. Values − click the list arrow to see your choices. Keywords − allows you to search for specific values within the values list. Keywords − allows you to search for specific values within the values list. Values List − shows the field values which you can use as filter values. You can select one or many. Use the arrow button to add multiple values. Values List − shows the field values which you can use as filter values. You can select one or many. Use the arrow button to add multiple values. Select a value and click the right pointing arrow to move the value into the selected column. You can use the Ctrl key to add multiple values at tone time. Click OK when the filter is defined. Note − You can view filters in the Query Explorer page and not the page explorer. You can go to the query explorer and view the filters. A filter can be deleted by using the following steps − Go to the Query Explorer as shown in the above screenshot Go to the Query Explorer as shown in the above screenshot Click on Query and Locate the Detail Filters pane in the upper right side of the window as shown in above screenshot Click on Query and Locate the Detail Filters pane in the upper right side of the window as shown in above screenshot Select the filter that you want to delete and press the delete button Select the filter that you want to delete and press the delete button You can also cut/copy a filter You can also cut/copy a filter You can add custom calculations to your report as per the business requirement. With the help of operators, different calculations can be added like if you want to add a new value salary*0.2 as a Bonus. To create Calculations in a Report − Select the item in the report. Click the insert calculation button and select the calculation to perform. Note − Calculations that are not applicable to the items you selected are greyed out. To change the order of the operands or the name of the calculated item added to the report, click Custom. The calculation appears as a new row or a column in your report. Drill up and drill down is used to perform analysis by moving between levels of information. Drill down is used to see more detailed information to lowest level and drill up is used to compare the results. To drill down or up in a single row or column, pause the pointer over the label text until the icon with the plus sign (+) and caret drill down drill up icon appears and the text is underlined, and then click. To drill down or up in both a row and column simultaneously, click on the value at the intersection of the row and the column, and then click again. Analysis Studio is used to focus on the items that are important for the business. You can do comparisons, trend analysis and analysis like top and bottom performers and also allow you to share your analysis with others. Analysis Studio is not only used by BI Analysts but also by business users who understand business and want to find answers to business queries using historical data. You can use Analysis Studio to compare and manipulate data to understand the relationships between data and its relative importance. Whether you want to assess revenue growth or to identify top performers, Analysis Studio provides the filtering, calculating, and sorting support you need for analysis. The Analysis Studio consists of several areas that are shown in the following areas and are explain in detail as well. Insertable Object Pane − The Source tab of the Insertable Objects pane contains the source tree for the package selected for the analysis. Insertable Object Pane − The Source tab of the Insertable Objects pane contains the source tree for the package selected for the analysis. Information Pane − The Information pane shows the name, level, attributes (if any), and aggregation associated with the selected item in the source tree, as well as any additional information provided by the data modeler. Information Pane − The Information pane shows the name, level, attributes (if any), and aggregation associated with the selected item in the source tree, as well as any additional information provided by the data modeler. Properties Pane − You can use Properties pane to make several changes and apply them at the same time, instead of running different commands. Properties Pane − You can use Properties pane to make several changes and apply them at the same time, instead of running different commands. Work Area − This area contains the crosstab or charts to perform the analysis. You can display analysis in the form a Crosstab, chart or a combination of both. Work Area − This area contains the crosstab or charts to perform the analysis. You can display analysis in the form a Crosstab, chart or a combination of both. And lastly there is the Overview Area as well. To create an analysis in the Analysis studio, you have to select a package as data source. You can create a new analysis or use an existing analysis as reference to create a new analysis by changing its name before saving it. To create an Analysis − Select the Package you want to use from the Public folder. Go to Report Studio as shown in the following screenshot. In a new dialog window, select a Blank Analysis or Default Analysis. Blank Analysis − A blank analysis starts with a blank crosstab in the work area. Blank Analysis − A blank analysis starts with a blank crosstab in the work area. Default Analysis − A default analysis uses the default analysis for the package as defined in Cognos Connection or the first two dimensions in the data source for the crosstab rows and columns and the first measure in the data source for the crosstab measure. Default Analysis − A default analysis uses the default analysis for the package as defined in Cognos Connection or the first two dimensions in the data source for the crosstab rows and columns and the first measure in the data source for the crosstab measure. After selecting, click OK. The Analysis Studio starts. The items that you can use in the analysis are listed in the Insertable Objects pane. To save an analysis, you can click on the save button at the top as shown in the following screenshot. Enter a name of the analysis and location → then click OK. To open an existing Analysis, locate the name of the analysis that you want to open and click it. It is opened in Analysis Studio. You can make any changes as per the requirement. Save the analysis. You can also open a new analysis while working in an existing analysis, click the new button on the toolbar. The new analysis maintains the state of the source tree in the Insertable Objects pane and maintains any items on the Analysis Items tab. Cognos Event Studio is a Web-based tool that allows you to create and manage agents to monitor data and perform tasks when the data meets predefined thresholds. You can specify an event condition to perform a task. An event is defined as query expression in a data package. When a record matches the event condition, it causes an agent to perform tasks. When an agent runs, it checks the data for any event instances. An agent monitors data, each event instance is detected. Task execution rules are followed to determine if an agent will perform the task. Task frequency defines that a task should be performed once or repeated for each event instance. You can categorize the event as per the task performed. The event list shows all the events that are executed by an agent. Different event categorization includes − New Ongoing and Changed Ongoing and Unchanged Ceased An event key is used to determine whether an event is new, ongoing but changed, ongoing and unchanged, or ceased. Event Studio compares the event instances detected in each agent run with those detected in the previous run. To ensure it correctly matches the event instances for comparison, you must define an event key. The event key is the combination of data items that uniquely defines an event instance. An agent runs to check occurrences of the event. An agent performs a task for events that meet the execution rules. A task can be used to notify users about a change in business event. Users can take appropriate actions as per the event. You can create a task for the following functions − Add an Item Send an Email Publish a new item Run a Job Run an import Run an Export and many more. An agent can use different notification methods to notify business users. An agent can notify business users by − An email to business users. Publishing a news item to a folder frequently used by users. You can notify people by email using either a report task or an email task. To help you decide which method to use, you should understand how they differ. You can use either a report task or an email task − To send a single email text message. To attach a single report in the specified output formats. If you attach only one HTML report and leave the body field empty, the report appears in the message body. To add links to a single report for the specified output formats. In this, you can publish a news item/headline to a folder whose content can be viewed in a Cognos Navigator portlet and in any folder view. When a Business user clicks on the headline, it can open the content or view it as a web page. Print Add Notes Bookmark this page
[ { "code": null, "e": 2801, "s": 2567, "text": "A Data Warehouse consists of data from multiple heterogeneous data sources and is used for analytical reporting and decision making. Data Warehouse is a central place where data is stored from different data sources and applications." }, { "code": null, "e": 2938, "s": 2801, "text": "The term Data Warehouse was first invented by Bill Inmom in 1990. A Data Warehouse is always kept separate from an Operational Database." }, { "code": null, "e": 3016, "s": 2938, "text": "The data in a DW system is loaded from operational transaction systems like −" }, { "code": null, "e": 3022, "s": 3016, "text": "Sales" }, { "code": null, "e": 3032, "s": 3022, "text": "Marketing" }, { "code": null, "e": 3035, "s": 3032, "text": "HR" }, { "code": null, "e": 3045, "s": 3035, "text": "SCM, etc." }, { "code": null, "e": 3178, "s": 3045, "text": "It may pass through operational data store or other transformations before it is loaded to the DW system for information processing." }, { "code": null, "e": 3446, "s": 3178, "text": "A Data Warehouse is used for reporting and analyzing of information and stores both historical and current data. The data in DW system is used for Analytical reporting, which is later used by Business Analysts, Sales Managers or Knowledge workers for decision-making." }, { "code": null, "e": 3616, "s": 3446, "text": "In the above image, you can see that the data is coming from multiple heterogeneous data sources to a Data Warehouse. Common data sources for a data warehouse includes −" }, { "code": null, "e": 3638, "s": 3616, "text": "Operational databases" }, { "code": null, "e": 3667, "s": 3638, "text": "SAP and non-SAP Applications" }, { "code": null, "e": 3700, "s": 3667, "text": "Flat Files (xls, csv, txt files)" }, { "code": null, "e": 3926, "s": 3700, "text": "Data in data warehouse is accessed by BI (Business Intelligence) users for Analytical Reporting, Data Mining and Analysis. This is used for decision making by Business Users, Sales Manager, Analysts to define future strategy." }, { "code": null, "e": 4212, "s": 3926, "text": "It is a central data repository where data is stored from one or more heterogeneous data sources. A DW system stores both current and historical data. Normally a DW system stores 5-10 years of historical data. A DW system is always kept separate from an operational transaction system." }, { "code": null, "e": 4331, "s": 4212, "text": "The data in a DW system is used for different types of analytical reporting range from Quarterly to Annual comparison." }, { "code": null, "e": 4414, "s": 4331, "text": "The differences between a Data Warehouse and Operational Database are as follows −" }, { "code": null, "e": 4629, "s": 4414, "text": "An Operational System is designed for known workloads and transactions like updating a user record, searching a record, etc. However, Data Warehouse transactions are more complex and present a general form of data." }, { "code": null, "e": 4844, "s": 4629, "text": "An Operational System is designed for known workloads and transactions like updating a user record, searching a record, etc. However, Data Warehouse transactions are more complex and present a general form of data." }, { "code": null, "e": 4969, "s": 4844, "text": "An Operational System contains the current data of an organization and Data warehouse normally contains the historical data." }, { "code": null, "e": 5094, "s": 4969, "text": "An Operational System contains the current data of an organization and Data warehouse normally contains the historical data." }, { "code": null, "e": 5271, "s": 5094, "text": "An Operational Database supports parallel processing of multiple transactions. Concurrency control and recovery mechanisms are required to maintain consistency of the database." }, { "code": null, "e": 5448, "s": 5271, "text": "An Operational Database supports parallel processing of multiple transactions. Concurrency control and recovery mechanisms are required to maintain consistency of the database." }, { "code": null, "e": 5626, "s": 5448, "text": "An Operational Database query allows to read and modify operations (insert, delete and Update) while an OLAP query needs only read-only access of stored data (Select statement)." }, { "code": null, "e": 5804, "s": 5626, "text": "An Operational Database query allows to read and modify operations (insert, delete and Update) while an OLAP query needs only read-only access of stored data (Select statement)." }, { "code": null, "e": 5934, "s": 5804, "text": "Data Warehousing involves data cleaning, data integration, and data consolidations. A Data Warehouse has a 3-layer architecture −" }, { "code": null, "e": 6086, "s": 5934, "text": "It defines how the data comes to a Data Warehouse. It involves various data sources and operational transaction systems, flat files, applications, etc." }, { "code": null, "e": 6433, "s": 6086, "text": "It consists of Operational Data Store and Staging area. Staging area is used to perform data cleansing, data transformation and loading data from different sources to a data warehouse. As multiple data sources are available for extraction at different time zones, staging area is used to store the data and later to apply transformations on data." }, { "code": null, "e": 6569, "s": 6433, "text": "This is used to perform BI reporting by end users. The data in a DW system is accessed by BI users and used for reporting and analysis." }, { "code": null, "e": 6654, "s": 6569, "text": "The following illustration shows the common architecture of a Data Warehouse System." }, { "code": null, "e": 6718, "s": 6654, "text": "The following are the key characteristics of a Data Warehouse −" }, { "code": null, "e": 6876, "s": 6718, "text": "Subject Oriented − In a DW system, the data is categorized and stored by a business subject rather than by application like equity plans, shares, loans, etc." }, { "code": null, "e": 7034, "s": 6876, "text": "Subject Oriented − In a DW system, the data is categorized and stored by a business subject rather than by application like equity plans, shares, loans, etc." }, { "code": null, "e": 7115, "s": 7034, "text": "Integrated − Data from multiple data sources are integrated in a Data Warehouse." }, { "code": null, "e": 7196, "s": 7115, "text": "Integrated − Data from multiple data sources are integrated in a Data Warehouse." }, { "code": null, "e": 7313, "s": 7196, "text": "Non Volatile − Data in data warehouse is non-volatile. It means when data is loaded in DW system, it is not altered." }, { "code": null, "e": 7430, "s": 7313, "text": "Non Volatile − Data in data warehouse is non-volatile. It means when data is loaded in DW system, it is not altered." }, { "code": null, "e": 7635, "s": 7430, "text": "Time Variant − A DW system contains historical data as compared to Transactional system which contains only current data. In a Data warehouse you can see data for 3 months, 6 months, 1 year, 5 years, etc." }, { "code": null, "e": 7840, "s": 7635, "text": "Time Variant − A DW system contains historical data as compared to Transactional system which contains only current data. In a Data warehouse you can see data for 3 months, 6 months, 1 year, 5 years, etc." }, { "code": null, "e": 7947, "s": 7840, "text": "Firstly, OLTP stands for Online Transaction Processing, while OLAP stands for Online Analytical Processing" }, { "code": null, "e": 8056, "s": 7947, "text": "In an OLTP system, there are a large number of short online transactions such as INSERT, UPDATE, and DELETE." }, { "code": null, "e": 8436, "s": 8056, "text": "Whereas, in an OLTP system, an effective measure is the processing time of short transactions and is very less. It controls data integrity in multi-access environments. For an OLTP system, the number of transactions per second measures the effectiveness. An OLTP Data Warehouse System contains current and detailed data and is maintained in the schemas in the entity model (3NF)." }, { "code": null, "e": 8450, "s": 8436, "text": "For Example −" }, { "code": null, "e": 8727, "s": 8450, "text": "A Day-to-Day transaction system in a retail store, where the customer records are inserted, updated and deleted on a daily basis. It provides faster query processing. OLTP databases contain detailed and current data. The schema used to store OLTP database is the Entity model." }, { "code": null, "e": 8900, "s": 8727, "text": "In an OLAP system, there are lesser number of transactions as compared to a transactional system. The queries executed are complex in nature and involves data aggregations." }, { "code": null, "e": 9175, "s": 8900, "text": "We save tables with aggregated data like yearly (1 row), quarterly (4 rows), monthly (12 rows) or so, if someone has to do a year to year comparison, only one row will be processed. However, in an un-aggregated table it will compare all the rows. This is called Aggregation." }, { "code": null, "e": 9280, "s": 9175, "text": "There are various Aggregation functions that can be used in an OLAP system like Sum, Avg, Max, Min, etc." }, { "code": null, "e": 9294, "s": 9280, "text": "For Example −" }, { "code": null, "e": 9356, "s": 9294, "text": "SELECT Avg(salary)\nFROM employee\nWHERE title = 'Programmer';\n" }, { "code": null, "e": 9424, "s": 9356, "text": "These are the major differences between an OLAP and an OLTP system." }, { "code": null, "e": 9547, "s": 9424, "text": "Indexes − An OLTP system has only few indexes while in an OLAP system there are many indexes for performance optimization." }, { "code": null, "e": 9670, "s": 9547, "text": "Indexes − An OLTP system has only few indexes while in an OLAP system there are many indexes for performance optimization." }, { "code": null, "e": 9815, "s": 9670, "text": "Joins − In an OLTP system, large number of joins and data are normalized. However, in an OLAP system there are less joins and are de-normalized." }, { "code": null, "e": 9960, "s": 9815, "text": "Joins − In an OLTP system, large number of joins and data are normalized. However, in an OLAP system there are less joins and are de-normalized." }, { "code": null, "e": 10070, "s": 9960, "text": "Aggregation − In an OLTP system, data is not aggregated while in an OLAP database more aggregations are used." }, { "code": null, "e": 10180, "s": 10070, "text": "Aggregation − In an OLTP system, data is not aggregated while in an OLAP database more aggregations are used." }, { "code": null, "e": 10286, "s": 10180, "text": "Normalization − An OLTP system contains normalized data however data is not normalized in an OLAP system." }, { "code": null, "e": 10392, "s": 10286, "text": "Normalization − An OLTP system contains normalized data however data is not normalized in an OLAP system." }, { "code": null, "e": 10649, "s": 10392, "text": "Data mart focuses on a single functional area and represents the simplest form of a Data Warehouse. Consider a Data Warehouse that contains data for Sales, Marketing, HR, and Finance. A Data mart focuses on a single functional area like Sales or Marketing." }, { "code": null, "e": 10738, "s": 10649, "text": "In the above image, you can see the difference between a Data Warehouse and a data mart." }, { "code": null, "e": 10861, "s": 10738, "text": "A fact table represents the measures on which analysis is performed. It also contains foreign keys for the dimension keys." }, { "code": null, "e": 10897, "s": 10861, "text": "For example − Every sale is a fact." }, { "code": null, "e": 11029, "s": 10897, "text": "The Dimension table represents the characteristics of a dimension. A Customer dimension can have Customer_Name, Phone_No, Sex, etc." }, { "code": null, "e": 11244, "s": 11029, "text": "A schema is defined as a logical description of database where fact and dimension tables are joined in a logical manner. Data Warehouse is maintained in the form of Star, Snow flakes, and Fact Constellation schema." }, { "code": null, "e": 11450, "s": 11244, "text": "A Star schema contains a fact table and multiple dimension tables. Each dimension is represented with only one-dimension table and they are not normalized. The Dimension table contains a set of attributes." }, { "code": null, "e": 11528, "s": 11450, "text": "In a Star schema, there is only one fact table and multiple dimension tables." }, { "code": null, "e": 11600, "s": 11528, "text": "In a Star schema, each dimension is represented by one-dimension table." }, { "code": null, "e": 11654, "s": 11600, "text": "Dimension tables are not normalized in a Star schema." }, { "code": null, "e": 11711, "s": 11654, "text": "Each Dimension table is joined to a key in a fact table." }, { "code": null, "e": 11850, "s": 11711, "text": "The following illustration shows the sales data of a company with respect to the four dimensions, namely Time, Item, Branch, and Location." }, { "code": null, "e": 12017, "s": 11850, "text": "There is a fact table at the center. It contains the keys to each of four dimensions. The fact table also contains the attributes, namely dollars sold and units sold." }, { "code": null, "e": 12280, "s": 12017, "text": "Note − Each dimension has only one-dimension table and each table holds a set of attributes. For example, the location dimension table contains the attribute set {location_key, street, city, province_or_state, country}. This constraint may cause data redundancy." }, { "code": null, "e": 12493, "s": 12280, "text": "For example − \"Vancouver\" and \"Victoria\" both the cities are in the Canadian province of British Columbia. The entries for such cities may cause data redundancy along the attributes province_or_state and country." }, { "code": null, "e": 12655, "s": 12493, "text": "Some dimension tables in the Snowflake schema are normalized. The normalization splits up the data into additional tables as shown in the following illustration." }, { "code": null, "e": 12742, "s": 12655, "text": "Unlike in the Star schema, the dimension’s table in a snowflake schema are normalized." }, { "code": null, "e": 12986, "s": 12742, "text": "For example − The item dimension table in a star schema is normalized and split into two dimension tables, namely item and supplier table. Now the item dimension table contains the attributes item_key, item_name, type, brand, and supplier-key." }, { "code": null, "e": 13131, "s": 12986, "text": "The supplier key is linked to the supplier dimension table. The supplier dimension table contains the attributes supplier_key and supplier_type." }, { "code": null, "e": 13285, "s": 13131, "text": "Note − Due to the normalization in the Snowflake schema, the redundancy is reduced and therefore, it becomes easy to maintain and the save storage space." }, { "code": null, "e": 13369, "s": 13285, "text": "A fact constellation has multiple fact tables. It is also known as a Galaxy Schema." }, { "code": null, "e": 13447, "s": 13369, "text": "The following illustration shows two fact tables, namely Sales and Shipping −" }, { "code": null, "e": 13776, "s": 13447, "text": "The sales fact table is the same as that in the Star Schema. The shipping fact table has five dimensions, namely item_key, time_key, shipper_key, from_location, to_location. The shipping fact table also contains two measures, namely dollars sold and units sold. It is also possible to share dimension tables between fact tables." }, { "code": null, "e": 13886, "s": 13776, "text": "For example − Time, item, and location dimension tables are shared between the sales and shipping fact table." }, { "code": null, "e": 14105, "s": 13886, "text": "An ETL tool extracts the data from all these heterogeneous data sources, transforms the data (like applying calculations, joining fields, keys, removing incorrect data fields, etc.), and loads it into a Data Warehouse." }, { "code": null, "e": 14489, "s": 14105, "text": "A staging area is required during the ETL load. There are various reasons why staging area is required. The source systems are only available for specific period of time to extract data. This period of time is less than the total data-load time. Therefore, staging area allows you to extract the data from the source system and keeps it in the staging area before the time slot ends." }, { "code": null, "e": 14637, "s": 14489, "text": "The staging area is required when you want to get the data from multiple data sources together or if you want to join two or more systems together." }, { "code": null, "e": 14756, "s": 14637, "text": "For example − You will not be able to perform an SQL Query joining two tables from two physically different databases." }, { "code": null, "e": 14978, "s": 14756, "text": "The data extractions’ time slot for different systems vary as per the time zone and operational hours. The data extracted from the source systems can be used in multiple Data Warehouse Systems, Operation Data Stores, etc." }, { "code": null, "e": 15071, "s": 14978, "text": "ETL allows you to perform complex transformations and requires extra area to store the data." }, { "code": null, "e": 15275, "s": 15071, "text": "In data transformation, you apply a set of functions on extracted data to load it into the target system. The data that does not require any transformation is known as a direct move or pass through data." }, { "code": null, "e": 15544, "s": 15275, "text": "You can apply different transformations on extracted data from the source system. For example, you can perform customized calculations. If you want sum-of-sales revenue and this is not in database, you can apply the SUM formula during transformation and load the data." }, { "code": null, "e": 15676, "s": 15544, "text": "For example − If you have the first name and the last name in a table in different columns, you can use concatenate before loading." }, { "code": null, "e": 15795, "s": 15676, "text": "During the Load phase, data is loaded into the end-target system and it can be a flat file or a Data Warehouse system." }, { "code": null, "e": 16079, "s": 15795, "text": "BI (Business Intelligence) tools are used by business users to create basic, medium, and complex reports from the transactional data in data warehouse and by creating Universes using the Information Design Tool/UDT. Various SAP and non-SAP data sources can be used to create reports." }, { "code": null, "e": 16211, "s": 16079, "text": "There are quite a few BI Reporting, Dashboard and Data Visualization Tools available in the market. Some of which are as follows − " }, { "code": null, "e": 16256, "s": 16211, "text": "SAP Business Objects Web Intelligence (WebI)" }, { "code": null, "e": 16272, "s": 16256, "text": "Crystal Reports" }, { "code": null, "e": 16283, "s": 16272, "text": "SAP Lumira" }, { "code": null, "e": 16302, "s": 16283, "text": "Dashboard Designer" }, { "code": null, "e": 16313, "s": 16302, "text": "IBM Cognos" }, { "code": null, "e": 16335, "s": 16313, "text": "Microsoft BI Platform" }, { "code": null, "e": 16365, "s": 16335, "text": "Tableau Business Intelligence" }, { "code": null, "e": 16376, "s": 16365, "text": "JasperSoft" }, { "code": null, "e": 16392, "s": 16376, "text": "Oracle BI OBIEE" }, { "code": null, "e": 16400, "s": 16392, "text": "Pentaho" }, { "code": null, "e": 16410, "s": 16400, "text": "QlickView" }, { "code": null, "e": 16417, "s": 16410, "text": "SAP BW" }, { "code": null, "e": 16443, "s": 16417, "text": "SAS Business Intelligence" }, { "code": null, "e": 16449, "s": 16443, "text": "Necto" }, { "code": null, "e": 16464, "s": 16449, "text": "Tibco Spotfire" }, { "code": null, "e": 16806, "s": 16464, "text": "IBM Cognos Business Intelligence is a web based reporting and analytic tool. It is used to perform data aggregation and create user friendly detailed reports. Reports can contain Graphs, Multiple Pages, Different Tabs and Interactive Prompts. These reports can be viewed on web browsers, or on hand held devices like tablets and smartphones." }, { "code": null, "e": 17102, "s": 16806, "text": "Cognos also provides you an option to export the report in XML or PDF format or you can view the reports in XML format. You can also schedule the report to run in the background at specific time period so it saves the time to view the daily report as you don’t need to run the report every time." }, { "code": null, "e": 17627, "s": 17102, "text": "IBM Cognos provides a wide range of features and can be considered as an enterprise software to provide flexible reporting environment and can be used for large and medium enterprises. It meets the need of Power Users, Analysts, Business Managers and Company Executives. Power users and analysts want to create adhoc reports and can create multiple views of the same data. Business Executives want to see summarize data in dashboard styles, cross tabs and visualizations. Cognos allows both the options for all set of users." }, { "code": null, "e": 17933, "s": 17627, "text": "Cognos BI reporting allows you to bring the data from multiple databases into a single set of reports. IBM Cognos provides wide range of features as compared to other BI tools in the market. You can create and schedule the reports and complex report can be designed easily in the Cognos BI Reporting Tool." }, { "code": null, "e": 18181, "s": 17933, "text": "The Cognos BI Reporting Tool allows to create a report for a set of users like – Power users, Analysts, and Business Executives, etc. IBM Cognos can handle a large volume of data and is suitable for medium and large enterprises to fulfil BI needs." }, { "code": null, "e": 18391, "s": 18181, "text": "Cognos BI is considered to be a 3-tier architecture layout. At the top, there is a Web Client or a Web Server. The 2nd tier consists of a Web Application Server. While the bottom tier consists of a Data layer." }, { "code": null, "e": 18507, "s": 18391, "text": "These tiers are separated by firewalls and communication between these tiers happens using SOAP and HTTP protocols." }, { "code": null, "e": 18868, "s": 18507, "text": "The web client allows BI users to access TM1 data and interact with data in any of the supported browsers. Tier 1 is responsible to manage the gateway and is used for encryption and decryption of passwords, extract information needed to submit a request to the BI server, authentication of server and to pass the request to Cognos BI dispatcher for processing." }, { "code": null, "e": 19030, "s": 18868, "text": "This tier hosts the Cognos BI server and its associated services. Application server contains Application Tier Components, Content Manager and Bootstrap service." }, { "code": null, "e": 19251, "s": 19030, "text": "Cognos TM1 Web Application Server runs on Java based Apache Tomcat server. Using this tier, Microsoft Excel worksheets can be converted to TM1 Web sheets and also allows to export web sheets back to Excel and PDF format." }, { "code": null, "e": 19354, "s": 19251, "text": "This tier contains content and data sources. It contains TM1 Admin server and at least one TM1 server." }, { "code": null, "e": 19559, "s": 19354, "text": "TM1 Admin server can be installed on any computer on your LAN and it must reside on same network as TM1 server. The version of TM1 server should be equal or most recent then the version of Cognos TM1 web." }, { "code": null, "e": 19625, "s": 19559, "text": "In this section we will discuss the different versions of Cognos." }, { "code": null, "e": 19723, "s": 19625, "text": "And then there were different sub-versions of the – Cognos Business Intelligence 10, which were −" }, { "code": null, "e": 19761, "s": 19723, "text": "IBM Cognos Business Intelligence 10.1" }, { "code": null, "e": 19801, "s": 19761, "text": "IBM Cognos Business Intelligence 10.1.1" }, { "code": null, "e": 19839, "s": 19801, "text": "IBM Cognos Business Intelligence 10.2" }, { "code": null, "e": 19879, "s": 19839, "text": "IBM Cognos Business Intelligence 10.2.1" }, { "code": null, "e": 19919, "s": 19879, "text": "IBM Cognos Business Intelligence 10.2.2" }, { "code": null, "e": 19959, "s": 19919, "text": "IBM Cognos Business Intelligence 11.0.0" }, { "code": null, "e": 20159, "s": 19959, "text": "There are various other BI reporting tools in the market that are used in medium and large enterprise for analytics and reporting purpose. Some of them are described here along with its key features." }, { "code": null, "e": 20229, "s": 20159, "text": "Following are the key features that are supported by both the tools −" }, { "code": null, "e": 20248, "s": 20229, "text": "Standard Reporting" }, { "code": null, "e": 20265, "s": 20248, "text": "Ad-hoc Reporting" }, { "code": null, "e": 20294, "s": 20265, "text": "Report output and Scheduling" }, { "code": null, "e": 20327, "s": 20294, "text": "Data Discovery and Visualization" }, { "code": null, "e": 20355, "s": 20327, "text": "Access Control and Security" }, { "code": null, "e": 20375, "s": 20355, "text": "Mobile Capabilities" }, { "code": null, "e": 20788, "s": 20375, "text": "Cognos can be considered as a robust solution which allows you to create a variety of reports like Cross tabs, Active reports (latest feature in Cognos 10), and other report structure. You can create user prompts, scheduling of report is easy and you can export and view reports in different formats. The Microsoft BI provides easy visualization of business data as well as Easy integration with Microsoft Excel." }, { "code": null, "e": 21006, "s": 20788, "text": "SAP BO supports its own ETL tool SAP Data Services. IBM Cognos doesn’t support its own ETL tool. The IBM Cognos 8 doesn’t provide offline reporting features however it is there in SAP Business Objects reporting tools." }, { "code": null, "e": 21369, "s": 21006, "text": "In Cognos the entire functionality is divided into multiple tools Query studio, Analysis studio, event studio etc. It is a tough task to learn all the tools. In SAP Business Objects, you have multiple tools like Web Intelligence for reporting, IDT for Universe Designer, Dashboard Designer so users feel that it is a tough task to manage and learn all the tools." }, { "code": null, "e": 21782, "s": 21369, "text": "In IBM Cognos, data generated can be transformed in various formats (for instance, HTML, PDF, etc.) and can also be accessed from multiple locations (e-mail, mobile, office, etc.). IBM provides several planning capabilities such as forecasts, budgets, advance scenario modelling etc. Selection of BI tool depends on various factors like need of company, software version, features supported and the license cost." }, { "code": null, "e": 22084, "s": 21782, "text": "There are various components in Cognos that communicate with each other using BI Bus and are known as Simple Object Access Protocol (SOAP) and supports WSDL. BI Bus in Cognos architecture is not a software component but consists of a set of protocols that allows communication between Cognos Services." }, { "code": null, "e": 22140, "s": 22084, "text": "The processes enabled by the BI Bus protocol includes −" }, { "code": null, "e": 22166, "s": 22140, "text": "Messaging and dispatching" }, { "code": null, "e": 22189, "s": 22166, "text": "Log message processing" }, { "code": null, "e": 22220, "s": 22189, "text": "Database connection management" }, { "code": null, "e": 22258, "s": 22220, "text": "Microsoft .NET Framework interactions" }, { "code": null, "e": 22269, "s": 22258, "text": "Port usage" }, { "code": null, "e": 22293, "s": 22269, "text": "Request flow processing" }, { "code": null, "e": 22306, "s": 22293, "text": "Portal Pages" }, { "code": null, "e": 22419, "s": 22306, "text": "When you install Cognos 8 using the Installation wizard, you specify where to install each of these components −" }, { "code": null, "e": 22811, "s": 22419, "text": "The Cognos 8 Web server tier contains one or more Cognos 8 gateways. The web communication in Cognos 8 is typically through gateways, which reside on one or more web servers. A gateway is an extension of a web server program that transfers information from the web server to another server. Web communication can also occur directly with a Cognos 8 dispatcher but this option is less common." }, { "code": null, "e": 22872, "s": 22811, "text": "Cognos 8 supports several types of Web gateways, including −" }, { "code": null, "e": 23052, "s": 22872, "text": "CGI − The default gateway, CGI can be used for all supported Web servers. However, for enhanced performance or throughput, you may choose one of the other supported gateway types." }, { "code": null, "e": 23183, "s": 23052, "text": "ISAPI − This can be used for the Microsoft Internet Information Services (IIS) Web server. It delivers faster performance for IIS." }, { "code": null, "e": 23258, "s": 23183, "text": "apache_mod − You can use an apache_mod gateway with the Apache Web server." }, { "code": null, "e": 23391, "s": 23258, "text": "Servlet − If your Web server infrastructure supports servlets or you are using an application server, you can use a servlet gateway." }, { "code": null, "e": 23752, "s": 23391, "text": "This component consists of a dispatcher that is responsible to operate services and route requests. The dispatcher is a multithreaded application that uses one or more threads per request. The configuration changes are routinely communicated to all the running dispatchers. This dispatcher includes Cognos Application Firewall to provide security for Cognos 8." }, { "code": null, "e": 24098, "s": 23752, "text": "The dispatcher can route requests to a local service, such as the report service, presentation service, job service, or monitor service. A dispatcher can also route requests to a specific dispatcher to run a given request. These requests can be routed to specific dispatchers based on load-balancing needs, or package or user group requirements." }, { "code": null, "e": 24455, "s": 24098, "text": "Content Manager contains Access Manager, the primary security component of Cognos 8. Access Manager leverages your existing security providers for use with Cognos 8. It provides Cognos 8 with a consistent set of security capabilities and APIs, including user authentication, authorization, and encryption. It also provides support for the Cognos namespace." }, { "code": null, "e": 25020, "s": 24455, "text": "You can report interactive user reports in Cognos Studio on the top of various data sources by creating relational and OLAP connections in web administration interface which are later used for data modeling in Framework Manager known as packages. All the reports and dashboards that are created in Cognos Studio they are published to Cognos Connection and portal for distribution. The report studio can be used to run the complex report and to view the Business Intelligence information or this can also be accessed from different portals where they are published." }, { "code": null, "e": 25236, "s": 25020, "text": "Cognos Connections are used to access reports, queries, analysis, and packages. They can also be used to create report shortcuts, URLs and pages and to organize entries and they can also be customized for other use." }, { "code": null, "e": 25549, "s": 25236, "text": "A data source defines the physical connection to a database and different connection parameters like connection time out, location of database, etc. A data source connection contains credential and sign on information. You can create a new database connection or can also edit an existing data source connection." }, { "code": null, "e": 25670, "s": 25549, "text": "You can also combine one or more data source connections and create packages and published them using Framework manager." }, { "code": null, "e": 26114, "s": 25670, "text": "The dynamic query mode is used to provide communication to data source using XMLA/Java connections. To connect to the Relation database, you can use type4 JDBC connection which converts JDBC calls into vendor specific format. It provides improved performance over type 2 drivers because there is no need to convert calls to ODBC or database API. Dynamic query mode in Cognos connection can support the following types of Relational databases −" }, { "code": null, "e": 26135, "s": 26114, "text": "Microsoft SQL Server" }, { "code": null, "e": 26142, "s": 26135, "text": "Oracle" }, { "code": null, "e": 26150, "s": 26142, "text": "IBM DB2" }, { "code": null, "e": 26159, "s": 26150, "text": "Teradata" }, { "code": null, "e": 26167, "s": 26159, "text": "Netezza" }, { "code": null, "e": 26384, "s": 26167, "text": "To support OLAP data sources, Java/XMLA connectivity provides optimized and enhanced MDX for different OLAP versions and technology. The Dynamic query mode in Cognos can be used with the following OLAP data sources −" }, { "code": null, "e": 26428, "s": 26384, "text": "SAP Business Information Warehouse (SAP BW)" }, { "code": null, "e": 26443, "s": 26428, "text": "Oracle Essbase" }, { "code": null, "e": 26471, "s": 26443, "text": "Microsoft Analysis Services" }, { "code": null, "e": 26486, "s": 26471, "text": "IBM Cognos TM1" }, { "code": null, "e": 26518, "s": 26486, "text": "IBM Cognos Real-time Monitoring" }, { "code": null, "e": 26608, "s": 26518, "text": "The DB2 connection type are used to connect to DB2 Windows, Unix and Linux, Db2 zOS, etc." }, { "code": null, "e": 26676, "s": 26608, "text": "The common connection parameters used in DB2 data source includes −" }, { "code": null, "e": 26690, "s": 26676, "text": "Database Name" }, { "code": null, "e": 26699, "s": 26690, "text": "Timeouts" }, { "code": null, "e": 26706, "s": 26699, "text": "Signon" }, { "code": null, "e": 26725, "s": 26706, "text": "DB2 connect string" }, { "code": null, "e": 26744, "s": 26725, "text": "Collation Sequence" }, { "code": null, "e": 26988, "s": 26744, "text": "To create models in IBM Cognos Framework Manager, there is a need to create a data source connection. When defining the data source connection, you need to enter the connection parameters – location of database, timeout interval, Sign-on, etc." }, { "code": null, "e": 27061, "s": 26988, "text": "In IBM Cognos Connection → click on the Launch IBM Cognos Administration" }, { "code": null, "e": 27174, "s": 27061, "text": "In the Configuration tab, click Data Source Connections. In this window, navigate to the New Data Source button." }, { "code": null, "e": 27224, "s": 27174, "text": "Enter the unique connection name and description." }, { "code": null, "e": 27340, "s": 27224, "text": "You can add a description related to the data source to uniquely identify the connection and click the next button." }, { "code": null, "e": 27461, "s": 27340, "text": "Select the type of connection from the drop down list and click on the next button as shown in the following screenshot." }, { "code": null, "e": 27561, "s": 27461, "text": "In the next screen that appears, enter the connection details as shown in the following screenshot." }, { "code": null, "e": 27726, "s": 27561, "text": "You can use the Test connection to test the connectivity to the data source using connection parameters that you have defined. Click on the finish button once done." }, { "code": null, "e": 27898, "s": 27726, "text": "Data Source Security can be defined using IBM Cognos authentication. As per the data source, different types of authentication can be configured in the Cognos connection −" }, { "code": null, "e": 28070, "s": 27898, "text": "No Authentication − This allows login to the data source without using any sign-on credentials. This type of connection doesn’t provide data source security in connection." }, { "code": null, "e": 28353, "s": 28070, "text": "IBM Cognos Software Service Credential − In this type of a sign-on, you log in to the data source using a logon specified for the IBM Cognos Service and the user does not require a separate database sign-on. In a live environment, it is advisable to use individual database sign on." }, { "code": null, "e": 28592, "s": 28353, "text": "External Name Space − It requires the same BI logon credentials that are used to authenticate the external authentication namespace. The user must be logged into the name space before logging in to the data source and it should be active." }, { "code": null, "e": 28906, "s": 28592, "text": "All the data sources also support data source sign-on defined for everyone in the group or for individual users, group or roles. If the data source requires a data source sign-on, but you don't have the access to a sign-on for this data source, you will be prompted to log on each time you access the data source." }, { "code": null, "e": 29095, "s": 28906, "text": "IBM Cognos also supports security at cube level. If you are using cubes, security may be set at the cube level. For Microsoft Analysis Service, security is defined at the cube level roles." }, { "code": null, "e": 29166, "s": 29095, "text": "In this chapter, we will discuss how to create a package using COGNOS." }, { "code": null, "e": 29342, "s": 29166, "text": "In IBM Cognos, you can create packages for SAP BW or power cube data sources. Packages are available in the Public folder or in My folder as shown in the following screenshot." }, { "code": null, "e": 29533, "s": 29342, "text": "Once a package is deployed, the default configuration is applied on the package. You can configure a package to use different settings or you can modify the settings of the existing package." }, { "code": null, "e": 29598, "s": 29533, "text": "To configure a package, you should have administrator privilege." }, { "code": null, "e": 29719, "s": 29598, "text": "Locate the package in the Public folder, click on More button under the Action tab as shown in the following screenshot." }, { "code": null, "e": 29950, "s": 29719, "text": "Click on Modify the package configuration and Click Select an analysis. Select the default analysis to be used for this package when a new analysis is created. Click OK and change the package settings as required and click Finish." }, { "code": null, "e": 30052, "s": 29950, "text": "In the Package tab, Public folder, you can also create a new Package using the IBM Cognos connection." }, { "code": null, "e": 30125, "s": 30052, "text": "Select the data source that you want to use in the package and click OK." }, { "code": null, "e": 30362, "s": 30125, "text": "You can also schedule the reports in IBM Cognos as per your business requirements. Scheduling a report allows you to save the refresh time. You can define various scheduling properties like frequency, time zone, start and end date, etc." }, { "code": null, "e": 30462, "s": 30362, "text": "To schedule a report, select the report and go to More button as shown in the following screenshot." }, { "code": null, "e": 30573, "s": 30462, "text": "You have an option to add a new schedule. Select the New Schedule button as shown in the following screenshot." }, { "code": null, "e": 30635, "s": 30573, "text": "You can select the following options under the Schedule tab −" }, { "code": null, "e": 30645, "s": 30635, "text": "Frequency" }, { "code": null, "e": 30659, "s": 30645, "text": "Start and End" }, { "code": null, "e": 30668, "s": 30659, "text": "Priority" }, { "code": null, "e": 30690, "s": 30668, "text": "Daily Frequency, etc." }, { "code": null, "e": 30976, "s": 30690, "text": "When the scheduling properties are defined, you can save it by clicking the OK button at the bottom. Disabling the Schedule options allows you to make the schedule inactive but the schedule will be saved for the report. You can remove this option any time to enable the schedule again." }, { "code": null, "e": 31112, "s": 30976, "text": "To edit an existing schedule, select the report and go to More. You can modify an existing schedule or remove the schedule permanently." }, { "code": null, "e": 31223, "s": 31112, "text": "In this chapter, we will discuss regarding what a Framework Manager is and about its various other components." }, { "code": null, "e": 31502, "s": 31223, "text": "IBM Cognos Framework Manager is used to create business model of metadata derived from one or more data sources. It is a Windows based tool which is used to publish the business models to Cognos BI in the form of packages which can be used for analytical reporting and analysis." }, { "code": null, "e": 31926, "s": 31502, "text": "Before you start a new project in Framework Manager, it is necessary that you go through BI reporting requirements that helps you to identify data strategies, metadata, report package delivery, etc. This helps you to identify which data sources are required in the Framework Manager to get the required data in the BI report. You should consider the following factors before starting a new project in the Framework manager." }, { "code": null, "e": 31966, "s": 31926, "text": "Data Sources required to meet BI needs." }, { "code": null, "e": 31985, "s": 31966, "text": "Types of DW system" }, { "code": null, "e": 32016, "s": 31985, "text": "Data refresh in Data Warehouse" }, { "code": null, "e": 32057, "s": 32016, "text": "BI Reporting- Daily, Weekly, or monthly." }, { "code": null, "e": 32316, "s": 32057, "text": "A Metadata model is defined as the collection of database objects (tables, columns and relationship between objects) imported from the database. When you run the report, metadata published in BI Cognos portal generates a SQL statement according to the query." }, { "code": null, "e": 32546, "s": 32316, "text": "The IBM Cognos Framework manager can hide the complexity of data in the data source and also alter the way how data is shown to users. It provides a view that is easy for BI users to understand and perform analysis and reporting." }, { "code": null, "e": 32629, "s": 32546, "text": "The following screenshot shows the IBM Cognos BI Framework Manager User Interface." }, { "code": null, "e": 32746, "s": 32629, "text": "Following are the various components of the above screenshot that are explained in detail for better understanding −" }, { "code": null, "e": 32851, "s": 32746, "text": "Project Viewer − This pane on left side allows you to access all the existing projects in a tree format." }, { "code": null, "e": 32956, "s": 32851, "text": "Project Viewer − This pane on left side allows you to access all the existing projects in a tree format." }, { "code": null, "e": 33104, "s": 32956, "text": "Project Info − This is the center pane that is used to manage objects of an existing project. This has three tabs: Explorer, Diagram and Dimension." }, { "code": null, "e": 33252, "s": 33104, "text": "Project Info − This is the center pane that is used to manage objects of an existing project. This has three tabs: Explorer, Diagram and Dimension." }, { "code": null, "e": 33365, "s": 33252, "text": "Properties − This pane at the bottom is used to set the value of different properties of an object in a project." }, { "code": null, "e": 33478, "s": 33365, "text": "Properties − This pane at the bottom is used to set the value of different properties of an object in a project." }, { "code": null, "e": 33665, "s": 33478, "text": "Tools − This pane on the right side provides you various important useful tools. You can perform a search, or display an object and its dependent objects, changing project language, etc." }, { "code": null, "e": 33852, "s": 33665, "text": "Tools − This pane on the right side provides you various important useful tools. You can perform a search, or display an object and its dependent objects, changing project language, etc." }, { "code": null, "e": 34124, "s": 33852, "text": "For importing Metadata from a Relational Database, you map the database objects to the Framework manager objects. In the Framework Manager, you can import all the objects or you can select particular objects like tables, columns, functions, stored procedures, views, etc." }, { "code": null, "e": 34175, "s": 34124, "text": "Only user defined Stored procedures are supported." }, { "code": null, "e": 34363, "s": 34175, "text": "To create a metadata model, run metadata wizard from the Action menu. Select a data source connection and click the Next button. Select the check boxes for the objects you want to import." }, { "code": null, "e": 34574, "s": 34363, "text": "Specify how the import should handle duplicate object names. Choose either to import and create a unique name, or not to import. If you choose to create a unique name, the imported object appears with a number." }, { "code": null, "e": 34668, "s": 34574, "text": "For example − When you see QuerySubject and QuerySubject1 in your project. Then click Import." }, { "code": null, "e": 34794, "s": 34668, "text": "Import statistics including a list of objects that could not be imported and a count of objects that were imported are shown." }, { "code": null, "e": 34842, "s": 34794, "text": "The next step is to click on the Finish button." }, { "code": null, "e": 34931, "s": 34842, "text": "After importing Metadata, you must check the imported Metadata for the following areas −" }, { "code": null, "e": 34961, "s": 34931, "text": "Relationships and Cardinality" }, { "code": null, "e": 34974, "s": 34961, "text": "Determinants" }, { "code": null, "e": 35005, "s": 34974, "text": "Usage property for query items" }, { "code": null, "e": 35048, "s": 35005, "text": "Regular Aggregate property for query items" }, { "code": null, "e": 35217, "s": 35048, "text": "In the Framework Manager, you can also import metadata from an existing Cognos 8 Model. To import Metadata from the Cognos 8 model, go to Actions → Run Metadata wizard." }, { "code": null, "e": 35340, "s": 35217, "text": "Click on the Cognos 8 Model and then the Next button. Navigate to the .cpf file from Cognos 8 Model and the click on Next." }, { "code": null, "e": 35437, "s": 35340, "text": "Select the check boxes for objects you want to import and then click on Next and then on Finish." }, { "code": null, "e": 35643, "s": 35437, "text": "Once you import the metadata, next is to validate the objects for reporting requirement. You can select the objects that appear in the report and test them. You can create two views of the Metadata Model −" }, { "code": null, "e": 35655, "s": 35643, "text": "Import View" }, { "code": null, "e": 35669, "s": 35655, "text": "Business View" }, { "code": null, "e": 35824, "s": 35669, "text": "The Import view shows you the metadata imported from the data source. To validate the data as per your BI reporting, you can perform the following steps −" }, { "code": null, "e": 35890, "s": 35824, "text": "Ensure that the relationships reflect the reporting requirements." }, { "code": null, "e": 35956, "s": 35890, "text": "Ensure that the relationships reflect the reporting requirements." }, { "code": null, "e": 36021, "s": 35956, "text": "Optimize and customize the data retrieved by the query subjects." }, { "code": null, "e": 36086, "s": 36021, "text": "Optimize and customize the data retrieved by the query subjects." }, { "code": null, "e": 36208, "s": 36086, "text": "Optimize and customize the data retrieved by dimensions. You may want to store dimensions in a separate dimensional view." }, { "code": null, "e": 36330, "s": 36208, "text": "Optimize and customize the data retrieved by dimensions. You may want to store dimensions in a separate dimensional view." }, { "code": null, "e": 36372, "s": 36330, "text": "Handle support for multilingual metadata." }, { "code": null, "e": 36414, "s": 36372, "text": "Handle support for multilingual metadata." }, { "code": null, "e": 36488, "s": 36414, "text": "Control how data is used and formatted by checking query item properties." }, { "code": null, "e": 36562, "s": 36488, "text": "Control how data is used and formatted by checking query item properties." }, { "code": null, "e": 36861, "s": 36562, "text": "Business view is used to provide the information in metadata. You can perform calculations, aggregations and apply filters in Business view and easily allow users to build the report. You can add business rules such as custom calculations and filters that define the information users can retrieve." }, { "code": null, "e": 36986, "s": 36861, "text": "Organize the model by creating separate views for each user group that reflect the business concepts familiar to your users." }, { "code": null, "e": 37201, "s": 36986, "text": "Relationships are used to create queries on multiple objects in a metadata model. Relationships can be bidirectional and without creating relationship, objects are individual entities with no use in metadata model." }, { "code": null, "e": 37389, "s": 37201, "text": "Each object in metadata model is connected using primary or foreign key in the data source. You can create or remove relationships in the metadata model to meet the business requirements." }, { "code": null, "e": 37462, "s": 37389, "text": "There are different relationships which are possible, some of them are −" }, { "code": null, "e": 37593, "s": 37462, "text": "One to One − When an instance of one query subject is related to another instance. For example: Each customer has one customer id." }, { "code": null, "e": 37724, "s": 37593, "text": "One to One − When an instance of one query subject is related to another instance. For example: Each customer has one customer id." }, { "code": null, "e": 37873, "s": 37724, "text": "One to Many − This relationship occurs when one instance of query subject relates to multiple instances. For example: Each doctor has many patients." }, { "code": null, "e": 38022, "s": 37873, "text": "One to Many − This relationship occurs when one instance of query subject relates to multiple instances. For example: Each doctor has many patients." }, { "code": null, "e": 38176, "s": 38022, "text": "Many to Many − This relationship occurs when many instances of a query subject relates to multiple instances. For example: Each patient has many doctors." }, { "code": null, "e": 38330, "s": 38176, "text": "Many to Many − This relationship occurs when many instances of a query subject relates to multiple instances. For example: Each patient has many doctors." }, { "code": null, "e": 38454, "s": 38330, "text": "It is defined as the number of related rows for each of the two query subjects. Cardinality is used in the following ways −" }, { "code": null, "e": 38480, "s": 38454, "text": "Loop Joins in Star schema" }, { "code": null, "e": 38512, "s": 38480, "text": "Optimized access to data source" }, { "code": null, "e": 38544, "s": 38512, "text": "Avoid double counting fact data" }, { "code": null, "e": 38659, "s": 38544, "text": "While using the Relational database as a data source, Cardinality can be defined considering the following rules −" }, { "code": null, "e": 38684, "s": 38659, "text": "Primary and Foreign keys" }, { "code": null, "e": 38742, "s": 38684, "text": "Match query item names represent uniquely indexed columns" }, { "code": null, "e": 38768, "s": 38742, "text": "Matching query item names" }, { "code": null, "e": 39056, "s": 38768, "text": "The most common ways to define Cardinality is by using the primary and foreign key. To view the key information that was imported, right click on the query subject → Edit Definition. You can import many to many relationships, optional relationships, and outer joins from the data source." }, { "code": null, "e": 39211, "s": 39056, "text": "In the Framework manager, a relation is represented by Merise notation. The first part of this notation represents the type of join for this relationship." }, { "code": null, "e": 39245, "s": 39211, "text": "0..1 represents zero or one match" }, { "code": null, "e": 39278, "s": 39245, "text": "1..1 represents one to one match" }, { "code": null, "e": 39313, "s": 39278, "text": "0..n represents Zero or no matches" }, { "code": null, "e": 39349, "s": 39313, "text": "1..n represents One or more matches" }, { "code": null, "e": 39409, "s": 39349, "text": "1 − An inner join with all matching rows from both objects." }, { "code": null, "e": 39493, "s": 39409, "text": "0 − An Outer join with all objects from both, including the items that don’t match." }, { "code": null, "e": 39737, "s": 39493, "text": "To create a Relationship or to combine logically related objects which are not joined in metadata import. You can manually create relationship between objects or can automatically define relationship between objects based on selected criteria." }, { "code": null, "e": 39881, "s": 39737, "text": "To create a Relationship, use CTRL key to select one or more query items, subjects or dimensions. Then go to Action Menu → Create Relationship." }, { "code": null, "e": 40021, "s": 39881, "text": "If this is a valid Relationship, the Framework manager wants to create a shortcut to the relationship. You can then click on the OK button." }, { "code": null, "e": 40157, "s": 40021, "text": "Once you create a relationship after the metadata import, you can also modify the relationship or Cardinality in the Framework manager." }, { "code": null, "e": 40248, "s": 40157, "text": "To edit a Relationship, click a relationship and from Action menu → click Edit Definition." }, { "code": null, "e": 40336, "s": 40248, "text": "From the Relationship Expression tab → Select Query items, Cardinalities and Operators." }, { "code": null, "e": 40444, "s": 40336, "text": "To create an additional Join, go to the Relationship Expression tab → New Link and Define New Relationship." }, { "code": null, "e": 40528, "s": 40444, "text": "To test this Relationship, go to Relationship SQL tab → rows to be returned → Test." }, { "code": null, "e": 40548, "s": 40528, "text": "Click on OK button." }, { "code": null, "e": 40876, "s": 40548, "text": "A Relationship shortcut is defined as the pointer to an existing relationship and to reuse the definition of an existing relationship. When you make any change to the source Relationship, they are automatically updated in shortcuts. Relationship shortcuts are also used to resolve ambiguous relationship between query subjects." }, { "code": null, "e": 41025, "s": 40876, "text": "The Framework Manager asks whether you want to create a relationship shortcut whenever you create a relationship and both these conditions are true." }, { "code": null, "e": 41082, "s": 41025, "text": "At least one end for the new relationship is a shortcut." }, { "code": null, "e": 41134, "s": 41082, "text": "A relationship exists between the original objects." }, { "code": null, "e": 41175, "s": 41134, "text": "Go to Action Menu → Create Relationship." }, { "code": null, "e": 41444, "s": 41175, "text": "If this is a valid Relationship, Framework manager wants to create a shortcut to the relationship. Click YES. A list appears of all relationships in which one end is a model object and the other end is either another model object or a shortcut to another model object." }, { "code": null, "e": 41454, "s": 41444, "text": "Click OK." }, { "code": null, "e": 41632, "s": 41454, "text": "A query subject is defined as a set of query items that have an inherent relationship. A query subject can be used to customize the data they retrieve using a Framework Manager." }, { "code": null, "e": 41699, "s": 41632, "text": "The following are the query subject types in a Framework Manager −" }, { "code": null, "e": 42078, "s": 41699, "text": "Data Source Query Subject − These are based on the Relational metadata defined by the SQL statements and are automatically created for each table and view when you import metadata into model.\nNote − The data source query subject references the data from only one data source at a time, but you can directly edit the SQL that defines the retrieve data to edit the query subject.\n" }, { "code": null, "e": 42270, "s": 42078, "text": "Data Source Query Subject − These are based on the Relational metadata defined by the SQL statements and are automatically created for each table and view when you import metadata into model." }, { "code": null, "e": 42456, "s": 42270, "text": "Note − The data source query subject references the data from only one data source at a time, but you can directly edit the SQL that defines the retrieve data to edit the query subject." }, { "code": null, "e": 42711, "s": 42456, "text": "Model Query Subjects − They are not directly created from a data source but are based on the query items defined in other query subjects or dimensions. Using the model query subject, it allows you to create more abstract and business view of data source." }, { "code": null, "e": 42966, "s": 42711, "text": "Model Query Subjects − They are not directly created from a data source but are based on the query items defined in other query subjects or dimensions. Using the model query subject, it allows you to create more abstract and business view of data source." }, { "code": null, "e": 43199, "s": 42966, "text": "Stored Procedure Query Subjects − They are created when a Procedure is imported from a Relational data source. IBM Cognos Framework Manager only supports user defined Stored Procedures and system stored procedures are not supported." }, { "code": null, "e": 43432, "s": 43199, "text": "Stored Procedure Query Subjects − They are created when a Procedure is imported from a Relational data source. IBM Cognos Framework Manager only supports user defined Stored Procedures and system stored procedures are not supported." }, { "code": null, "e": 43476, "s": 43432, "text": "From Actions Menu → Create → Query Subject." }, { "code": null, "e": 43515, "s": 43476, "text": "Enter the name of a new Query Subject." }, { "code": null, "e": 43575, "s": 43515, "text": "Click on Data Source → OK to open new Query Subject wizard." }, { "code": null, "e": 43632, "s": 43575, "text": "Follow the steps till the Finish button appears → Finish" }, { "code": null, "e": 43764, "s": 43632, "text": "Right click on Query Subject → Edit Definition. Click on the SQL tab → Available database objects box, drag objects to the SQL box." }, { "code": null, "e": 43865, "s": 43764, "text": "You can also insert a data source reference, insert a macro, embed a calculation and embed a filter." }, { "code": null, "e": 43912, "s": 43865, "text": "Select the actions from the list and click OK." }, { "code": null, "e": 44065, "s": 43912, "text": "When you edit any Relation database source, create or query a Relation database, then SQL is used in the background. You can use the following options −" }, { "code": null, "e": 44076, "s": 44065, "text": "Cognos SQL" }, { "code": null, "e": 44087, "s": 44076, "text": "Native SQL" }, { "code": null, "e": 44104, "s": 44087, "text": "Pass through SQL" }, { "code": null, "e": 44306, "s": 44104, "text": "To edit SQL of the model query subject, copy SQL from query Information tab and paste to the new data source query subject. It is possible to convert a model query subject to data source query subject." }, { "code": null, "e": 44373, "s": 44306, "text": "Click Data Source query subject and Action menu → Edit Definition." }, { "code": null, "e": 44432, "s": 44373, "text": "Click on SQL button, drag objects or type in SQL you want." }, { "code": null, "e": 44442, "s": 44432, "text": "Click OK." }, { "code": null, "e": 44594, "s": 44442, "text": "You can select the type of SQL to be used when you define data source query subject. These factors should be considered while considering type of SQL −" }, { "code": null, "e": 44615, "s": 44594, "text": "Improved performance" }, { "code": null, "e": 44646, "s": 44615, "text": "Work on all supported database" }, { "code": null, "e": 44668, "s": 44646, "text": "Performance Optimized" }, { "code": null, "e": 44689, "s": 44668, "text": "Specific to Database" }, { "code": null, "e": 44729, "s": 44689, "text": "SQL doesn’t work on different database." }, { "code": null, "e": 44796, "s": 44729, "text": "You can’t use SQL that data source doesn’t support for subqueries." }, { "code": null, "e": 44820, "s": 44796, "text": "No option for Framework" }, { "code": null, "e": 44840, "s": 44820, "text": "Manager to optimize" }, { "code": null, "e": 44866, "s": 44840, "text": "performance automatically" }, { "code": null, "e": 44977, "s": 44866, "text": "Also note that it is not possible to change the type of SQL for query subjects based on the OLAP data sources." }, { "code": null, "e": 45037, "s": 44977, "text": "To change SQL type, go to Query subject you want to change." }, { "code": null, "e": 45110, "s": 45037, "text": "Go to Actions menu → Edit Definition and go to Query Information button." }, { "code": null, "e": 45144, "s": 45110, "text": "Go to Options → SQL Settings tab." }, { "code": null, "e": 45211, "s": 45144, "text": "To change the type of SQL, click on SQL Type List. Then, click OK." }, { "code": null, "e": 45360, "s": 45211, "text": "Query Studio is defined as a web based tool for creating queries and reports in Cognos 8. It is also used to run simple queries and reports as well." }, { "code": null, "e": 45420, "s": 45360, "text": "In Query Studio, the following functions can be performed −" }, { "code": null, "e": 45576, "s": 45420, "text": "Viewing Data − Using Query Studio, you can connect to data source to view the data in a tree hierarchy. You can see query subject, query item details, etc." }, { "code": null, "e": 45732, "s": 45576, "text": "Viewing Data − Using Query Studio, you can connect to data source to view the data in a tree hierarchy. You can see query subject, query item details, etc." }, { "code": null, "e": 45890, "s": 45732, "text": "Creating BI Reports − You can use Query studio to create simple reports by using the data source. You can also refer existing reports to create a new report." }, { "code": null, "e": 46048, "s": 45890, "text": "Creating BI Reports − You can use Query studio to create simple reports by using the data source. You can also refer existing reports to create a new report." }, { "code": null, "e": 46190, "s": 46048, "text": "Changing Existing Reports − You can also change existing reports by editing report layout – Add charts, titles, headings, border styles, etc." }, { "code": null, "e": 46332, "s": 46190, "text": "Changing Existing Reports − You can also change existing reports by editing report layout – Add charts, titles, headings, border styles, etc." }, { "code": null, "e": 46507, "s": 46332, "text": "Data Customization in Report − You can apply various customizations in reports- Filters, Calculations and aggregations to perform data analysis, drill up and drill down, etc." }, { "code": null, "e": 46682, "s": 46507, "text": "Data Customization in Report − You can apply various customizations in reports- Filters, Calculations and aggregations to perform data analysis, drill up and drill down, etc." }, { "code": null, "e": 46906, "s": 46682, "text": "Using ad-hoc reporting, a user can create queries or reports for ad-hoc analysis. Ad-hoc reporting feature allows business users to create simple queries and reports on the top of fact and dimension table in data Warehouse." }, { "code": null, "e": 46971, "s": 46906, "text": "The Query Studio in Cognos BI, provides the following features −" }, { "code": null, "e": 47015, "s": 46971, "text": "View data and perform ad-hoc data analysis." }, { "code": null, "e": 47047, "s": 47015, "text": "Save the report for future use." }, { "code": null, "e": 47125, "s": 47047, "text": "Work with data in the report by applying filters, summaries and calculations." }, { "code": null, "e": 47226, "s": 47125, "text": "To create ad-hoc report using query studio, login to IBM Cognos software and click on Query my data." }, { "code": null, "e": 47373, "s": 47226, "text": "Select the report package. Next time you visit this page; you will see your selection under the recently used packages. Click on the package name." }, { "code": null, "e": 47474, "s": 47373, "text": "In the next screen, you can add Dimension elements, filters and prompts, facts and calculation, etc." }, { "code": null, "e": 47592, "s": 47474, "text": "You should insert the objects in this order. To insert object in the report, you can use Insert button at the bottom." }, { "code": null, "e": 47629, "s": 47592, "text": "Insert and filter dimension elements" }, { "code": null, "e": 47656, "s": 47629, "text": "Insert filters and prompts" }, { "code": null, "e": 47686, "s": 47656, "text": "Insert facts and calculations" }, { "code": null, "e": 47710, "s": 47686, "text": "Apply finishing touches" }, { "code": null, "e": 47744, "s": 47710, "text": "Save, run, collaborate, and share" }, { "code": null, "e": 47887, "s": 47744, "text": "At the top, you have the tool bar, where you can create a new report, save existing report, cut, paste, insert charts, drill up and down, etc." }, { "code": null, "e": 47979, "s": 47887, "text": "When you insert all the objects to a report, you can click on the Run option () at the top." }, { "code": null, "e": 48140, "s": 47979, "text": "You can use different report types in the Cognos Query Studio to meet the business requirements. You can create the following report types in the Query Studio −" }, { "code": null, "e": 48250, "s": 48140, "text": "List Reports − These reports are used to show your entire customer base as shown in the following screenshot." }, { "code": null, "e": 48349, "s": 48250, "text": "Crosstab Reports − These are used to show quantity sold with product and region on different axis." }, { "code": null, "e": 48474, "s": 48349, "text": "Charts − You can insert charts to show data graphically. You can combine a chart with a Crosstab or also with a list report." }, { "code": null, "e": 48637, "s": 48474, "text": "You can create a new report by inserting objects from the data source in the Query Studio. You can also change an existing report and save it with different name." }, { "code": null, "e": 48753, "s": 48637, "text": "You can open Query Studio by going to Query my data option on the home page or you can go to Launch → Query Studio." }, { "code": null, "e": 48939, "s": 48753, "text": "In the next screen, you will be prompted to select a package to add objects in the reports. You can select a recently used package or any other package created in the Framework Manager." }, { "code": null, "e": 49026, "s": 48939, "text": "You can see Query items listed on the left side. You can add data and save the report." }, { "code": null, "e": 49134, "s": 49026, "text": "You can open an existing report in the Query Studio and save it with a different name after making changes." }, { "code": null, "e": 49220, "s": 49134, "text": "To open an existing report, locate and click the name of the report you want to open." }, { "code": null, "e": 49358, "s": 49220, "text": "The report opens in the Query Studio. You can use the Open with Query Studio to identify a Query Studio report in the Cognos Connection." }, { "code": null, "e": 49423, "s": 49358, "text": "Or you can launch Query Studio and go to open option at the top." }, { "code": null, "e": 49479, "s": 49423, "text": "Search the report in the list of Available folders → OK" }, { "code": null, "e": 49611, "s": 49479, "text": "You can add objects from a data source. Each object has a representative icon and can insert all the following objects to a report." }, { "code": null, "e": 49849, "s": 49611, "text": "When you save a report in the Query Studio, it saves the query definition. It doesn’t save the data while saving the report. When you run a report saved a week back, the data in that report reflects the recent changes in the data source." }, { "code": null, "e": 49902, "s": 49849, "text": "To save a report, click on the Save icon at the top." }, { "code": null, "e": 50003, "s": 49902, "text": "In the next screen, enter the name, description and location where you want to save the report → OK." }, { "code": null, "e": 50132, "s": 50003, "text": "You can use Save as option to save a report with different name or at a different location as shown in the following screenshot." }, { "code": null, "e": 50249, "s": 50132, "text": "Specify a name and location − To include a description, type the information you want to add in the Description box." }, { "code": null, "e": 50259, "s": 50249, "text": "Click OK." }, { "code": null, "e": 50448, "s": 50259, "text": "A report in the Query Studio runs when you update data from data source in the report. When you open an existing report or make any changes to a report, Query Studio again runs the report." }, { "code": null, "e": 50500, "s": 50448, "text": "You can use the following options to run a report −" }, { "code": null, "e": 50623, "s": 50500, "text": "Run with Prompt − You can run a report using a user prompt. When you run the report, you are prompted to select the value." }, { "code": null, "e": 50746, "s": 50623, "text": "Run with Prompt − You can run a report using a user prompt. When you run the report, you are prompted to select the value." }, { "code": null, "e": 51052, "s": 50746, "text": "Run with all Data − The Run with all data command runs the report using the full data source. Running a report can take a long time. If you plan to make several changes to a report, run the report in preview mode to save time and computer resources by limiting the rows of data that your report retrieves." }, { "code": null, "e": 51358, "s": 51052, "text": "Run with all Data − The Run with all data command runs the report using the full data source. Running a report can take a long time. If you plan to make several changes to a report, run the report in preview mode to save time and computer resources by limiting the rows of data that your report retrieves." }, { "code": null, "e": 51528, "s": 51358, "text": "Preview Report with no Data − You can use the preview option when you want to see how the report will look like. This is useful when you want to make formatting changes." }, { "code": null, "e": 51698, "s": 51528, "text": "Preview Report with no Data − You can use the preview option when you want to see how the report will look like. This is useful when you want to make formatting changes." }, { "code": null, "e": 51802, "s": 51698, "text": "Open the report that you want in Query Studio. From the Run Report menu, choose how to run the report −" }, { "code": null, "e": 51902, "s": 51802, "text": "To run the report using all the data, click Run with All Data as shown in the following screenshot." }, { "code": null, "e": 51973, "s": 51902, "text": "To run the report using limited data, click Preview with Limited Data." }, { "code": null, "e": 52067, "s": 51973, "text": "If the package that the report is based on contains a design filter, performance is improved." }, { "code": null, "e": 52128, "s": 52067, "text": "To run the report using no data, click Preview with No Data." }, { "code": null, "e": 52268, "s": 52128, "text": "You can run a report in PDF, XML or in a CSV format. To run a report in different formats, select the report and click on Run with options." }, { "code": null, "e": 52450, "s": 52268, "text": "Select the format in which you want to run the report. You can choose from the following formats. Select the format and click Run at the bottom as shown in the following screenshot." }, { "code": null, "e": 52662, "s": 52450, "text": "You can also print a report to get a copy on paper. You can directly enter the Printer location while running the report or you can run the report in a PDF format and later you can take a printout of the report." }, { "code": null, "e": 52753, "s": 52662, "text": "To take the print of the report directly, select the report and click on Run with options." }, { "code": null, "e": 52860, "s": 52753, "text": "In the Delivery mode, select print the report and enter the location as shown in the following screenshot." }, { "code": null, "e": 53090, "s": 52860, "text": "Report Studio is a web-based tool that is used by report developers to create multi pages, complex reports on top of multiple data sources. You can create sales reports, inventory reports, account statements, balance sheets, etc." }, { "code": null, "e": 53239, "s": 53090, "text": "To create Reports in Report Studio, you should have a good understanding on user interface. Report Studio user interface is divided into two parts −" }, { "code": null, "e": 53270, "s": 53239, "text": "Explorer Bar on the Left Side." }, { "code": null, "e": 53299, "s": 53270, "text": "Work area for report design." }, { "code": null, "e": 53367, "s": 53299, "text": "The above screenshot has three major blocks, which are as follows −" }, { "code": null, "e": 53717, "s": 53367, "text": "Insertable Object Pane − The Insertable Objects pane contains objects that you can add to a report. These objects can be added by dragging them to the work area. It can contain −\n\nSource tab (That contains item from the package).\nData Items (Queries created in the report).\nToolbox (different objects like graphics that can be added to the report)\n\n" }, { "code": null, "e": 53896, "s": 53717, "text": "Insertable Object Pane − The Insertable Objects pane contains objects that you can add to a report. These objects can be added by dragging them to the work area. It can contain −" }, { "code": null, "e": 53946, "s": 53896, "text": "Source tab (That contains item from the package)." }, { "code": null, "e": 53996, "s": 53946, "text": "Source tab (That contains item from the package)." }, { "code": null, "e": 54040, "s": 53996, "text": "Data Items (Queries created in the report)." }, { "code": null, "e": 54084, "s": 54040, "text": "Data Items (Queries created in the report)." }, { "code": null, "e": 54158, "s": 54084, "text": "Toolbox (different objects like graphics that can be added to the report)" }, { "code": null, "e": 54232, "s": 54158, "text": "Toolbox (different objects like graphics that can be added to the report)" }, { "code": null, "e": 54397, "s": 54232, "text": "Properties Pane − The Properties pane lists the properties that you can set for an object in a report. To get the help, select the property and use keyboard key F1." }, { "code": null, "e": 54562, "s": 54397, "text": "Properties Pane − The Properties pane lists the properties that you can set for an object in a report. To get the help, select the property and use keyboard key F1." }, { "code": null, "e": 54639, "s": 54562, "text": "Work Area − The work area is known as the area where the report is designed." }, { "code": null, "e": 54716, "s": 54639, "text": "Work Area − The work area is known as the area where the report is designed." }, { "code": null, "e": 54873, "s": 54716, "text": "On the home page, go to Launch → Report Studio → Select a Package or in the IBM Cognos Welcome page, click on Author advanced reports to open Report Studio." }, { "code": null, "e": 54980, "s": 54873, "text": "On the home screen of Report Studio, you have an option to create a new report or open an existing report." }, { "code": null, "e": 55104, "s": 54980, "text": "You will be prompted to select the type of report you want to create. You have the option to select different report types." }, { "code": null, "e": 55286, "s": 55104, "text": "In Report Studio, you can create different types of reports. They allow you to present the data in different formats like a list report can be used to show the customer information." }, { "code": null, "e": 55342, "s": 55286, "text": "The following reports can be created in Report Studio −" }, { "code": null, "e": 55489, "s": 55342, "text": "This report is used to show the data in detailed format. Data is shown in rows and columns and each column contains all the values of a data item." }, { "code": null, "e": 55686, "s": 55489, "text": "Like list report, a cross tab report also shows the data in row and columns, but the data is compact and not detailed. At the intersection points of rows and columns, you show the summarized data." }, { "code": null, "e": 55856, "s": 55686, "text": "You can use the Report Studio to create many chart types, including column, bar, area, and line charts. You can also create custom charts that combine these chart types." }, { "code": null, "e": 55963, "s": 55856, "text": "You can also use maps in the Report Studio to present data for a particular region, country or a location." }, { "code": null, "e": 56002, "s": 55963, "text": "A map report consists of three parts −" }, { "code": null, "e": 56015, "s": 56002, "text": "Region Layer" }, { "code": null, "e": 56027, "s": 56015, "text": "Point Layer" }, { "code": null, "e": 56041, "s": 56027, "text": "Display Layer" }, { "code": null, "e": 56185, "s": 56041, "text": "Repeaters are used to add repeat items in a report while running the report. To add a Repeater, drag a repeater from the tool box to work area." }, { "code": null, "e": 56342, "s": 56185, "text": "A list report that shows the data in rows and columns and each cell shows the data in the database or you can also add custom calculations in a list report." }, { "code": null, "e": 56427, "s": 56342, "text": "To create a new list report, go to New → Blank as shown in the following screenshot." }, { "code": null, "e": 56614, "s": 56427, "text": "When you select a list report, you get the following structure of the report in the Report Studio. You have to drag the objects from the package on the left side to the report structure." }, { "code": null, "e": 56698, "s": 56614, "text": "You can also edit the title of the report that will appear once you run the report." }, { "code": null, "e": 56847, "s": 56698, "text": "You can use different tools at the top for the report formatting. To save a report, click on the save button. To run a report, click on Run report." }, { "code": null, "e": 56938, "s": 56847, "text": "Once you save the report, you have an option to save it in the Public folder or My folder." }, { "code": null, "e": 57024, "s": 56938, "text": "When you click on the Run option, you can select different formats to run the report." }, { "code": null, "e": 57149, "s": 57024, "text": "You will be prompted to select the type of report you want to create. You have option to select from different report types." }, { "code": null, "e": 57201, "s": 57149, "text": "Select Crosstab as type of the report and click OK." }, { "code": null, "e": 57284, "s": 57201, "text": "The structure of a Crosstab report is opened as shown in the following screenshot." }, { "code": null, "e": 57423, "s": 57284, "text": "In the Insertable Objects pane, on the Source tab, click the data item you want to add to the crosstab and drag it to the Rows or Columns." }, { "code": null, "e": 57541, "s": 57423, "text": "A black bar indicates where you can drop the data item. Repeat the above given steps to insert additional data items." }, { "code": null, "e": 57656, "s": 57541, "text": "You add dimensions to rows or columns and to add measures to the crosstab, drag the measures you want to Measures." }, { "code": null, "e": 57731, "s": 57656, "text": "When you run the report, a crosstab report is generated that has one edge." }, { "code": null, "e": 57958, "s": 57731, "text": "You can also format the crosstab to give them appearance as per the requirement. When you specify formatting for all rows, columns, fact cells, or the crosstab, the formatting is automatically applied to any new items you add." }, { "code": null, "e": 58072, "s": 57958, "text": "When you apply styles such as font color, rows and columns, intersections this is applied in the following order." }, { "code": null, "e": 58092, "s": 58072, "text": "Crosstab fact cells" }, { "code": null, "e": 58125, "s": 58092, "text": "Fact cells in the outermost rows" }, { "code": null, "e": 58158, "s": 58125, "text": "Fact cells in the innermost rows" }, { "code": null, "e": 58194, "s": 58158, "text": "Fact cells in the outermost columns" }, { "code": null, "e": 58230, "s": 58194, "text": "Fact cells in the innermost columns" }, { "code": null, "e": 58253, "s": 58230, "text": "Crosstab intersections" }, { "code": null, "e": 58450, "s": 58253, "text": "To do formatting of crosstab, click anywhere in the Crosstab. Click the select ancestor button in the title bar of the Properties pane and then click Crosstab as shown in the following screenshot." }, { "code": null, "e": 58648, "s": 58450, "text": "In the Properties pane, click the property you want and then specify a value. For example, if you want to specify a background color, click on Background Color and choose the color you want to use." }, { "code": null, "e": 58805, "s": 58648, "text": "You can also right-click the row or column and click Select Member Fact Cells. In the Properties pane, click the property you want and then specify a value." }, { "code": null, "e": 58942, "s": 58805, "text": "In Report Studio, you can create many chart types like column, bar, area, line charts or a custom chart that combines these chart types." }, { "code": null, "e": 58979, "s": 58942, "text": "In the Source tab, expand the query." }, { "code": null, "e": 59027, "s": 58979, "text": "Drag Revenue to the Measure (y-axis) drop zone." }, { "code": null, "e": 59070, "s": 59027, "text": "Drag Current year to the Series drop zone." }, { "code": null, "e": 59119, "s": 59070, "text": "Drag Order to the Categories (x-axis) drop zone." }, { "code": null, "e": 59170, "s": 59119, "text": "Drag the objects as shown in the above screenshot." }, { "code": null, "e": 59335, "s": 59170, "text": "Save the chart using the tool bar at the top. Save it to Public or My Folder as mentioned in the previous topic. Run the report to see the result in a chart format." }, { "code": null, "e": 59413, "s": 59335, "text": "You can also create a Repeater table or a map report in Cognos Report Studio." }, { "code": null, "e": 59485, "s": 59413, "text": "There are various Report functions that can be used in a Cognos report." }, { "code": null, "e": 59536, "s": 59485, "text": "Some of these different report functions include −" }, { "code": null, "e": 59745, "s": 59536, "text": "This function is used to return a positive or a negative number representing the number of days between the two datetime expressions. If a timestamp_exp1 < timestamp_exp2 then the result will be a –ve number." }, { "code": null, "e": 59792, "s": 59745, "text": "_days_between(timestamp_exp1, timestamp_exp2)\n" }, { "code": null, "e": 59942, "s": 59792, "text": "This function is used to return a number representing the number of days remaining in the month represented by the datetime expression timestamp_exp." }, { "code": null, "e": 59980, "s": 59942, "text": "_days_to_end_of_month(timestamp_exp)\n" }, { "code": null, "e": 60088, "s": 59980, "text": "This function is used to return a datetime that is the first day of the month represented by timestamp_exp." }, { "code": null, "e": 60190, "s": 60088, "text": "This function is used to return the datetime resulting from adding integer_exp days to timestamp_exp." }, { "code": null, "e": 60229, "s": 60190, "text": "_add_days(timestamp_exp, integer_exp)\n" }, { "code": null, "e": 60333, "s": 60229, "text": "This function is used to return the datetime resulting from adding integer_exp months to timestamp_exp." }, { "code": null, "e": 60374, "s": 60333, "text": "_add_months(timestamp_exp, integer_exp)\n" }, { "code": null, "e": 60477, "s": 60374, "text": "This function is used to return the datetime resulting from adding integer_exp years to timestamp_exp." }, { "code": null, "e": 60517, "s": 60477, "text": "_add_years(timestamp_exp, integer_exp)\n" }, { "code": null, "e": 60666, "s": 60517, "text": "This function is used to return a number that is obtained from subtracting timestamp_exp from today's date in YYYYMMDD format (years, months, days)." }, { "code": null, "e": 60687, "s": 60666, "text": "_age(timestamp_exp)\n" }, { "code": null, "e": 61016, "s": 60687, "text": "This function is used to return the day of week (between 1 and 7), where 1 is the first day of the week as indicated by integer_exp (between 1 and 7, 1 being Monday and 7 being Sunday). Note that in ISO 8601 standard, a week begins with Monday being day 1. In North America where Sunday is the first day of the week being day 7." }, { "code": null, "e": 61058, "s": 61016, "text": "_day_of_week(timestamp_exp, integer_exp)\n" }, { "code": null, "e": 61181, "s": 61058, "text": "This function is used to return the ordinal for the day of the year in date_ exp (1 to 366). Also known as the Julian day." }, { "code": null, "e": 61210, "s": 61181, "text": "_day_of_year(timestamp_exp)\n" }, { "code": null, "e": 61289, "s": 61210, "text": "Like these, there are various other Report functions as well that can be used." }, { "code": null, "e": 61452, "s": 61289, "text": "This is used to ensure that your report doesn’t contain any error. When a report created in the older version of Cognos is upgraded it is automatically validated." }, { "code": null, "e": 61566, "s": 61452, "text": "To validate a report, go to the Tools menu and click on the Validate button as shown in the following screenshot." }, { "code": null, "e": 61606, "s": 61566, "text": "There are different Validation levels −" }, { "code": null, "e": 61662, "s": 61606, "text": "Error − To retrieve all errors returned from the query." }, { "code": null, "e": 61718, "s": 61662, "text": "Error − To retrieve all errors returned from the query." }, { "code": null, "e": 61789, "s": 61718, "text": "Warning − To retrieve all errors and warnings returned from the query." }, { "code": null, "e": 61860, "s": 61789, "text": "Warning − To retrieve all errors and warnings returned from the query." }, { "code": null, "e": 61925, "s": 61860, "text": "Key Transformation − To retrieve important transformation steps." }, { "code": null, "e": 61990, "s": 61925, "text": "Key Transformation − To retrieve important transformation steps." }, { "code": null, "e": 62075, "s": 61990, "text": "Information − To retrieve other information related to query planning and execution." }, { "code": null, "e": 62160, "s": 62075, "text": "Information − To retrieve other information related to query planning and execution." }, { "code": null, "e": 62253, "s": 62160, "text": "You can run the report with different options. To set the report options, go to Run options." }, { "code": null, "e": 62282, "s": 62253, "text": "You get different options − " }, { "code": null, "e": 62329, "s": 62282, "text": "Format − You can select from different format." }, { "code": null, "e": 62376, "s": 62329, "text": "Format − You can select from different format." }, { "code": null, "e": 62455, "s": 62376, "text": "To select Paper size − You can select from different paper sizes, orientation." }, { "code": null, "e": 62534, "s": 62455, "text": "To select Paper size − You can select from different paper sizes, orientation." }, { "code": null, "e": 62590, "s": 62534, "text": "Select Data mode − All data, limited data, and no data." }, { "code": null, "e": 62646, "s": 62590, "text": "Select Data mode − All data, limited data, and no data." }, { "code": null, "e": 62710, "s": 62646, "text": "Language − Select language in which you want to run the report." }, { "code": null, "e": 62774, "s": 62710, "text": "Language − Select language in which you want to run the report." }, { "code": null, "e": 62812, "s": 62774, "text": "Rows per page and prompt option, etc." }, { "code": null, "e": 62850, "s": 62812, "text": "Rows per page and prompt option, etc." }, { "code": null, "e": 63043, "s": 62850, "text": "Report Administration allows you to give permissions to different users on the report level. You can define various other properties like output versions, permissions, general properties, etc." }, { "code": null, "e": 63142, "s": 63043, "text": "To open Report Properties and the permissions tab, go to More Options in the IBM Cognos home page." }, { "code": null, "e": 63197, "s": 63142, "text": "You can select the following actions in more options −" }, { "code": null, "e": 63426, "s": 63197, "text": "In the permission tab, you can specify access permissions for this entry. By default, an entry acquires its access permissions from a parent. You can override those permissions with the permissions set explicitly for this entry." }, { "code": null, "e": 63548, "s": 63426, "text": "You can also move, copy or delete a report in More Options. You can create a shortcut entry or report view of the report." }, { "code": null, "e": 63805, "s": 63548, "text": "Filters are used to limit the data that you want in your report. You can apply one or more filters in a Cognos report and the report returns the data that meet the filter conditions. You can create various custom filters in a report as per the requirement." }, { "code": null, "e": 63837, "s": 63805, "text": "Select the column to filter by." }, { "code": null, "e": 63886, "s": 63837, "text": "Click the drop down list from the Filter button." }, { "code": null, "e": 63915, "s": 63886, "text": "Choose Create Custom Filter." }, { "code": null, "e": 63953, "s": 63915, "text": "The Filter Condition dialog displays." }, { "code": null, "e": 64005, "s": 63953, "text": "In the next window, define the filter’s parameters." }, { "code": null, "e": 64101, "s": 64005, "text": "Condition − click the list arrow to see your choices (Show or Don’t show the following values)." }, { "code": null, "e": 64197, "s": 64101, "text": "Condition − click the list arrow to see your choices (Show or Don’t show the following values)." }, { "code": null, "e": 64248, "s": 64197, "text": "Values − click the list arrow to see your choices." }, { "code": null, "e": 64299, "s": 64248, "text": "Values − click the list arrow to see your choices." }, { "code": null, "e": 64375, "s": 64299, "text": "Keywords − allows you to search for specific values within the values list." }, { "code": null, "e": 64451, "s": 64375, "text": "Keywords − allows you to search for specific values within the values list." }, { "code": null, "e": 64597, "s": 64451, "text": "Values List − shows the field values which you can use as filter values. You can select one or many. Use the arrow button to add multiple values." }, { "code": null, "e": 64743, "s": 64597, "text": "Values List − shows the field values which you can use as filter values. You can select one or many. Use the arrow button to add multiple values." }, { "code": null, "e": 64936, "s": 64743, "text": "Select a value and click the right pointing arrow to move the value into the selected column. You can use the Ctrl key to add multiple values at tone time. Click OK when the filter is defined." }, { "code": null, "e": 65073, "s": 64936, "text": "Note − You can view filters in the Query Explorer page and not the page explorer. You can go to the query explorer and view the filters." }, { "code": null, "e": 65128, "s": 65073, "text": "A filter can be deleted by using the following steps −" }, { "code": null, "e": 65186, "s": 65128, "text": "Go to the Query Explorer as shown in the above screenshot" }, { "code": null, "e": 65244, "s": 65186, "text": "Go to the Query Explorer as shown in the above screenshot" }, { "code": null, "e": 65361, "s": 65244, "text": "Click on Query and Locate the Detail Filters pane in the upper right side of the window as shown in above screenshot" }, { "code": null, "e": 65478, "s": 65361, "text": "Click on Query and Locate the Detail Filters pane in the upper right side of the window as shown in above screenshot" }, { "code": null, "e": 65548, "s": 65478, "text": "Select the filter that you want to delete and press the delete button" }, { "code": null, "e": 65618, "s": 65548, "text": "Select the filter that you want to delete and press the delete button" }, { "code": null, "e": 65649, "s": 65618, "text": "You can also cut/copy a filter" }, { "code": null, "e": 65680, "s": 65649, "text": "You can also cut/copy a filter" }, { "code": null, "e": 65883, "s": 65680, "text": "You can add custom calculations to your report as per the business requirement. With the help of operators, different calculations can be added like if you want to add a new value salary*0.2 as a Bonus." }, { "code": null, "e": 65920, "s": 65883, "text": "To create Calculations in a Report −" }, { "code": null, "e": 65951, "s": 65920, "text": "Select the item in the report." }, { "code": null, "e": 66026, "s": 65951, "text": "Click the insert calculation button and select the calculation to perform." }, { "code": null, "e": 66112, "s": 66026, "text": "Note − Calculations that are not applicable to the items you selected are greyed out." }, { "code": null, "e": 66283, "s": 66112, "text": "To change the order of the operands or the name of the calculated item added to the report, click Custom. The calculation appears as a new row or a column in your report." }, { "code": null, "e": 66489, "s": 66283, "text": "Drill up and drill down is used to perform analysis by moving between levels of information. Drill down is used to see more detailed information to lowest level and drill up is used to compare the results." }, { "code": null, "e": 66699, "s": 66489, "text": "To drill down or up in a single row or column, pause the pointer over the label text until the icon with the plus sign (+) and caret drill down drill up icon appears and the text is underlined, and then click." }, { "code": null, "e": 66848, "s": 66699, "text": "To drill down or up in both a row and column simultaneously, click on the value at the intersection of the row and the column, and then click again." }, { "code": null, "e": 67069, "s": 66848, "text": "Analysis Studio is used to focus on the items that are important for the business. You can do comparisons, trend analysis and analysis like top and bottom performers and also allow you to share your analysis with others." }, { "code": null, "e": 67236, "s": 67069, "text": "Analysis Studio is not only used by BI Analysts but also by business users who understand business and want to find answers to business queries using historical data." }, { "code": null, "e": 67538, "s": 67236, "text": "You can use Analysis Studio to compare and manipulate data to understand the relationships between data and its relative importance. Whether you want to assess revenue growth or to identify top performers, Analysis Studio provides the filtering, calculating, and sorting support you need for analysis." }, { "code": null, "e": 67657, "s": 67538, "text": "The Analysis Studio consists of several areas that are shown in the following areas and are explain in detail as well." }, { "code": null, "e": 67796, "s": 67657, "text": "Insertable Object Pane − The Source tab of the Insertable Objects pane contains the source tree for the package selected for the analysis." }, { "code": null, "e": 67935, "s": 67796, "text": "Insertable Object Pane − The Source tab of the Insertable Objects pane contains the source tree for the package selected for the analysis." }, { "code": null, "e": 68157, "s": 67935, "text": "Information Pane − The Information pane shows the name, level, attributes (if any), and aggregation associated with the selected item in the source tree, as well as any additional information provided by the data modeler." }, { "code": null, "e": 68379, "s": 68157, "text": "Information Pane − The Information pane shows the name, level, attributes (if any), and aggregation associated with the selected item in the source tree, as well as any additional information provided by the data modeler." }, { "code": null, "e": 68521, "s": 68379, "text": "Properties Pane − You can use Properties pane to make several changes and apply them at the same time, instead of running different commands." }, { "code": null, "e": 68663, "s": 68521, "text": "Properties Pane − You can use Properties pane to make several changes and apply them at the same time, instead of running different commands." }, { "code": null, "e": 68823, "s": 68663, "text": "Work Area − This area contains the crosstab or charts to perform the analysis. You can display analysis in the form a Crosstab, chart or a combination of both." }, { "code": null, "e": 68983, "s": 68823, "text": "Work Area − This area contains the crosstab or charts to perform the analysis. You can display analysis in the form a Crosstab, chart or a combination of both." }, { "code": null, "e": 69030, "s": 68983, "text": "And lastly there is the Overview Area as well." }, { "code": null, "e": 69256, "s": 69030, "text": "To create an analysis in the Analysis studio, you have to select a package as data source. You can create a new analysis or use an existing analysis as reference to create a new analysis by changing its name before saving it." }, { "code": null, "e": 69397, "s": 69256, "text": "To create an Analysis − Select the Package you want to use from the Public folder. Go to Report Studio as shown in the following screenshot." }, { "code": null, "e": 69466, "s": 69397, "text": "In a new dialog window, select a Blank Analysis or Default Analysis." }, { "code": null, "e": 69547, "s": 69466, "text": "Blank Analysis − A blank analysis starts with a blank crosstab in the work area." }, { "code": null, "e": 69628, "s": 69547, "text": "Blank Analysis − A blank analysis starts with a blank crosstab in the work area." }, { "code": null, "e": 69888, "s": 69628, "text": "Default Analysis − A default analysis uses the default analysis for the package as defined in Cognos Connection or the first two dimensions in the data source for the crosstab rows and columns and the first measure in the data source for the crosstab measure." }, { "code": null, "e": 70148, "s": 69888, "text": "Default Analysis − A default analysis uses the default analysis for the package as defined in Cognos Connection or the first two dimensions in the data source for the crosstab rows and columns and the first measure in the data source for the crosstab measure." }, { "code": null, "e": 70289, "s": 70148, "text": "After selecting, click OK. The Analysis Studio starts. The items that you can use in the analysis are listed in the Insertable Objects pane." }, { "code": null, "e": 70392, "s": 70289, "text": "To save an analysis, you can click on the save button at the top as shown in the following screenshot." }, { "code": null, "e": 70451, "s": 70392, "text": "Enter a name of the analysis and location → then click OK." }, { "code": null, "e": 70582, "s": 70451, "text": "To open an existing Analysis, locate the name of the analysis that you want to open and click it. It is opened in Analysis Studio." }, { "code": null, "e": 70650, "s": 70582, "text": "You can make any changes as per the requirement. Save the analysis." }, { "code": null, "e": 70897, "s": 70650, "text": "You can also open a new analysis while working in an existing analysis, click the new button on the toolbar. The new analysis maintains the state of the source tree in the Insertable Objects pane and maintains any items on the Analysis Items tab." }, { "code": null, "e": 71058, "s": 70897, "text": "Cognos Event Studio is a Web-based tool that allows you to create and manage agents to monitor data and perform tasks when the data meets predefined thresholds." }, { "code": null, "e": 71171, "s": 71058, "text": "You can specify an event condition to perform a task. An event is defined as query expression in a data package." }, { "code": null, "e": 71315, "s": 71171, "text": "When a record matches the event condition, it causes an agent to perform tasks. When an agent runs, it checks the data for any event instances." }, { "code": null, "e": 71551, "s": 71315, "text": "An agent monitors data, each event instance is detected. Task execution rules are followed to determine if an agent will perform the task. Task frequency defines that a task should be performed once or repeated for each event instance." }, { "code": null, "e": 71716, "s": 71551, "text": "You can categorize the event as per the task performed. The event list shows all the events that are executed by an agent. Different event categorization includes −" }, { "code": null, "e": 71720, "s": 71716, "text": "New" }, { "code": null, "e": 71740, "s": 71720, "text": "Ongoing and Changed" }, { "code": null, "e": 71762, "s": 71740, "text": "Ongoing and Unchanged" }, { "code": null, "e": 71769, "s": 71762, "text": "Ceased" }, { "code": null, "e": 72178, "s": 71769, "text": "An event key is used to determine whether an event is new, ongoing but changed, ongoing and unchanged, or ceased. Event Studio compares the event instances detected in each agent run with those detected in the previous run. To ensure it correctly matches the event instances for comparison, you must define an event key. The event key is the combination of data items that uniquely defines an event instance." }, { "code": null, "e": 72294, "s": 72178, "text": "An agent runs to check occurrences of the event. An agent performs a task for events that meet the execution rules." }, { "code": null, "e": 72416, "s": 72294, "text": "A task can be used to notify users about a change in business event. Users can take appropriate actions as per the event." }, { "code": null, "e": 72468, "s": 72416, "text": "You can create a task for the following functions −" }, { "code": null, "e": 72480, "s": 72468, "text": "Add an Item" }, { "code": null, "e": 72494, "s": 72480, "text": "Send an Email" }, { "code": null, "e": 72513, "s": 72494, "text": "Publish a new item" }, { "code": null, "e": 72523, "s": 72513, "text": "Run a Job" }, { "code": null, "e": 72537, "s": 72523, "text": "Run an import" }, { "code": null, "e": 72566, "s": 72537, "text": "Run an Export and many more." }, { "code": null, "e": 72680, "s": 72566, "text": "An agent can use different notification methods to notify business users. An agent can notify business users by −" }, { "code": null, "e": 72708, "s": 72680, "text": "An email to business users." }, { "code": null, "e": 72769, "s": 72708, "text": "Publishing a news item to a folder frequently used by users." }, { "code": null, "e": 72924, "s": 72769, "text": "You can notify people by email using either a report task or an email task. To help you decide which method to use, you should understand how they differ." }, { "code": null, "e": 72976, "s": 72924, "text": "You can use either a report task or an email task −" }, { "code": null, "e": 73013, "s": 72976, "text": "To send a single email text message." }, { "code": null, "e": 73072, "s": 73013, "text": "To attach a single report in the specified output formats." }, { "code": null, "e": 73179, "s": 73072, "text": "If you attach only one HTML report and leave the body field empty, the report appears in the message body." }, { "code": null, "e": 73245, "s": 73179, "text": "To add links to a single report for the specified output formats." }, { "code": null, "e": 73480, "s": 73245, "text": "In this, you can publish a news item/headline to a folder whose content can be viewed in a Cognos Navigator portlet and in any folder view. When a Business user clicks on the headline, it can open the content or view it as a web page." }, { "code": null, "e": 73487, "s": 73480, "text": " Print" }, { "code": null, "e": 73498, "s": 73487, "text": " Add Notes" } ]
fork() to execute processes from bottom to up using wait() in C++
We know that the fork() system call is used to divide the process into two processes. If the function fork() returns 0, then it is child process, and otherwise it is parent process. In this example we will see how to split processes four times, and use them in bottom up manner. So at first we will use fork() function two times. So it will generate a child process, then from the next fork it will generate another child. After that from the inner fork it will automatically generates a grandchild of them. We will use wait() function to generate some delay and execute the processes as bottom up manner. #include <iostream> #include <sys/wait.h> #include <unistd.h> using namespace std; int main() { pid_t id1 = fork(); //make 4 process using two consecutive fork. The main process, two children and one grand child pid_t id2 = fork(); if (id1 > 0 && id2 > 0) { //when both ids are non zero, then it is parent process wait(NULL); wait(NULL); cout << "Ending of parent process" << endl; }else if (id1 == 0 && id2 > 0) { //When first id is 0, then it is first child sleep(2); //wait 2 seconds to execute second child first wait(NULL); cout << "Ending of First Child" << endl; }else if (id1 > 0 && id2 == 0) { //When second id is 0, then it is second child sleep(1); //wait 2 seconds cout << "Ending of Second child process" << endl; }else { cout << "Ending of grand child" << endl; } return 0; } soumyadeep@soumyadeep-VirtualBox:~$ ./a.out Ending of grand child Ending of Second child process Ending of First Child Ending of parent process soumyadeep@soumyadeep-VirtualBox:~$
[ { "code": null, "e": 1244, "s": 1062, "text": "We know that the fork() system call is used to divide the process into two processes. If the function fork() returns 0, then it is child process, and otherwise it is parent process." }, { "code": null, "e": 1570, "s": 1244, "text": "In this example we will see how to split processes four times, and use them in bottom up manner. So at first we will use fork() function two times. So it will generate a child process, then from the next fork it will generate another child. After that from the inner fork it will automatically generates a grandchild of them." }, { "code": null, "e": 1668, "s": 1570, "text": "We will use wait() function to generate some delay and execute the processes as bottom up manner." }, { "code": null, "e": 2536, "s": 1668, "text": "#include <iostream>\n#include <sys/wait.h>\n#include <unistd.h>\nusing namespace std;\nint main() {\n pid_t id1 = fork(); //make 4 process using two consecutive fork. The main process, two children and one grand child\n pid_t id2 = fork();\n if (id1 > 0 && id2 > 0) { //when both ids are non zero, then it is parent process\n wait(NULL);\n wait(NULL);\n cout << \"Ending of parent process\" << endl;\n }else if (id1 == 0 && id2 > 0) { //When first id is 0, then it is first child\n sleep(2); //wait 2 seconds to execute second child first\n wait(NULL);\n cout << \"Ending of First Child\" << endl;\n }else if (id1 > 0 && id2 == 0) { //When second id is 0, then it is second child\n sleep(1); //wait 2 seconds\n cout << \"Ending of Second child process\" << endl;\n }else {\n cout << \"Ending of grand child\" << endl;\n }\n return 0;\n}" }, { "code": null, "e": 2716, "s": 2536, "text": "soumyadeep@soumyadeep-VirtualBox:~$ ./a.out\nEnding of grand child\nEnding of Second child process\nEnding of First Child\nEnding of parent process\nsoumyadeep@soumyadeep-VirtualBox:~$" } ]
OOAD - Implementation Strategies
Implementing an object-oriented design generally involves using a standard object oriented programming language (OOPL) or mapping object designs to databases. In most cases, it involves both. Usually, the task of transforming an object design into code is a straightforward process. Any object-oriented programming language like C++, Java, Smalltalk, C# and Python, includes provision for representing classes. In this chapter, we exemplify the concept using C++. The following figure shows the representation of the class Circle using C++. Most programming languages do not provide constructs to implement associations directly. So the task of implementing associations needs considerable thought. Associations may be either unidirectional or bidirectional. Besides, each association may be either one–to–one, one–to–many, or many–to–many. For implementing unidirectional associations, care should be taken so that unidirectionality is maintained. The implementations for different multiplicity are as follows − Optional Associations − Here, a link may or may not exist between the participating objects. For example, in the association between Customer and Current Account in the figure below, a customer may or may not have a current account. Optional Associations − Here, a link may or may not exist between the participating objects. For example, in the association between Customer and Current Account in the figure below, a customer may or may not have a current account. For implementation, an object of Current Account is included as an attribute in Customer that may be NULL. Implementation using C++ − class Customer { private: // attributes Current_Account c; //an object of Current_Account as attribute public: Customer() { c = NULL; } // assign c as NULL Current_Account getCurrAc() { return c; } void setCurrAc( Current_Account myacc) { c = myacc; } void removeAcc() { c = NULL; } }; One–to–one Associations − Here, one instance of a class is related to exactly one instance of the associated class. For example, Department and Manager have one–to–one association as shown in the figure below. One–to–one Associations − Here, one instance of a class is related to exactly one instance of the associated class. For example, Department and Manager have one–to–one association as shown in the figure below. This is implemented by including in Department, an object of Manager that should not be NULL. Implementation using C++ − class Department { private: // attributes Manager mgr; //an object of Manager as attribute public: Department (/*parameters*/, Manager m) { //m is not NULL // assign parameters to variables mgr = m; } Manager getMgr() { return mgr; } }; One–to–many Associations − Here, one instance of a class is related to more than one instances of the associated class. For example, consider the association between Employee and Dependent in the following figure. One–to–many Associations − Here, one instance of a class is related to more than one instances of the associated class. For example, consider the association between Employee and Dependent in the following figure. This is implemented by including a list of Dependents in class Employee. Implementation using C++ STL list container − class Employee { private: char * deptName; list <Dependent> dep; //a list of Dependents as attribute public: void addDependent ( Dependent d) { dep.push_back(d); } // adds an employee to the department void removeDeoendent( Dependent d) { int index = find ( d, dep ); // find() function returns the index of d in list dep dep.erase(index); } }; To implement bi-directional association, links in both directions require to be maintained. Optional or one–to–one Associations − Consider the relationship between Project and Project Manager having one–to–one bidirectional association as shown in the figure below. Optional or one–to–one Associations − Consider the relationship between Project and Project Manager having one–to–one bidirectional association as shown in the figure below. Implementation using C++ − Class Project { private: // attributes Project_Manager pmgr; public: void setManager ( Project_Manager pm); Project_Manager changeManager(); }; class Project_Manager { private: // attributes Project pj; public: void setProject(Project p); Project removeProject(); }; One–to–many Associations − Consider the relationship between Department and Employee having one–to–many association as shown in the figure below. One–to–many Associations − Consider the relationship between Department and Employee having one–to–many association as shown in the figure below. class Department { private: char * deptName; list <Employee> emp; //a list of Employees as attribute public: void addEmployee ( Employee e) { emp.push_back(e); } // adds an employee to the department void removeEmployee( Employee e) { int index = find ( e, emp ); // find function returns the index of e in list emp emp.erase(index); } }; class Employee { private: //attributes Department d; public: void addDept(); void removeDept(); }; If an association has some attributes associated, it should be implemented using a separate class. For example, consider the one–to–one association between Employee and Project as shown in the figure below. class WorksOn { private: Employee e; Project p; Hours h; char * date; public: // class methods }; Constraints in classes restrict the range and type of values that the attributes may take. In order to implement constraints, a valid default value is assigned to the attribute when an object is instantiated from the class. Whenever the value is changed at runtime, it is checked whether the value is valid or not. An invalid value may be handled by an exception handling routine or other methods. Example Consider an Employee class where age is an attribute that may have values in the range of 18 to 60. The following C++ code incorporates it − class Employee { private: char * name; int age; // other attributes public: Employee() { // default constructor strcpy(name, ""); age = 18; // default value } class AgeError {}; // Exception class void changeAge( int a) { // method that changes age if ( a < 18 || a > 60 ) // check for invalid condition throw AgeError(); // throw exception age = a; } }; There are two alternative implementation strategies to implement states in state chart diagrams. In this approach, the states are represented by different values of a data member (or set of data members). The values are explicitly defined by an enumeration within the class. The transitions are represented by member functions that change the value of the concerned data member. In this approach, the states are arranged in a generalization hierarchy in a manner that they can be referred by a common pointer variable. The following figure shows a transformation from state chart diagram to a generalization hierarchy. An important aspect of developing object-oriented systems is persistency of data. Through persistency, objects have longer lifespan than the program that created it. Persistent data is saved on secondary storage medium from where it can be reloaded when required. A database is an ordered collection of related data. A database management system (DBMS) is a collection of software that facilitates the processes of defining, creating, storing, manipulating, retrieving, sharing, and removing data in databases. In relational database management systems (RDBMS), data is stored as relations or tables, where each column or field represents an attribute and each row or tuple represents a record of an instance. Each row is uniquely identified by a chosen set of minimal attributes called primary key. A foreign key is an attribute that is the primary key of a related table. To map a class to a database table, each attribute is represented as a field in the table. Either an existing attribute(s) is assigned as a primary key or a separate ID field is added as a primary key. The class may be partitioned horizontally or vertically as per requirement. For example, the Circle class can be converted to table as shown in the figure below. Schema for Circle Table: CIRCLE(CID, X_COORD, Y_COORD, RADIUS, COLOR) Creating a Table Circle using SQL command: CREATE TABLE CIRCLE ( CID VARCHAR2(4) PRIMARY KEY, X_COORD INTEGER NOT NULL, Y_COORD INTEGER NOT NULL, Z_COORD INTEGER NOT NULL, COLOR ); To implement 1:1 associations, the primary key of any one table is assigned as the foreign key of the other table. For example, consider the association between Department and Manager − CREATE TABLE DEPARTMENT ( DEPT_ID INTEGER PRIMARY KEY, DNAME VARCHAR2(30) NOT NULL, LOCATION VARCHAR2(20), EMPID INTEGER REFERENCES MANAGER ); CREATE TABLE MANAGER ( EMPID INTEGER PRIMARY KEY, ENAME VARCHAR2(50) NOT NULL, ADDRESS VARCHAR2(70), ); To implement 1:N associations, the primary key of the table in the 1-side of the association is assigned as the foreign key of the table at the N-side of the association. For example, consider the association between Department and Employee − CREATE TABLE DEPARTMENT ( DEPT_ID INTEGER PRIMARY KEY, DNAME VARCHAR2(30) NOT NULL, LOCATION VARCHAR2(20), ); CREATE TABLE EMPLOYEE ( EMPID INTEGER PRIMARY KEY, ENAME VARCHAR2(50) NOT NULL, ADDRESS VARCHAR2(70), D_ID INTEGER REFERENCES DEPARTMENT ); To implement M:N associations, a new relation is created that represents the association. For example, consider the following association between Employee and Project − Schema for Works_On Table − WORKS_ON (EMPID, PID, HOURS, START_DATE) SQL command to create Works_On association − CREATE TABLE WORKS_ON ( EMPID INTEGER, PID INTEGER, HOURS INTEGER, START_DATE DATE, PRIMARY KEY (EMPID, PID), FOREIGN KEY (EMPID) REFERENCES EMPLOYEE, FOREIGN KEY (PID) REFERENCES PROJECT ); To map inheritance, the primary key of the base table(s) is assigned as the primary key as well as the foreign key in the derived table(s). Example 14 Lectures 1.5 hours Harshit Srivastava 60 Lectures 8 hours DigiFisk (Programming Is Fun) 11 Lectures 35 mins Sandip Bhattacharya 21 Lectures 2 hours Pranjal Srivastava 6 Lectures 43 mins Frahaan Hussain 49 Lectures 4.5 hours Abhilash Nelson Print Add Notes Bookmark this page
[ { "code": null, "e": 2179, "s": 1987, "text": "Implementing an object-oriented design generally involves using a standard object oriented programming language (OOPL) or mapping object designs to databases. In most cases, it involves both." }, { "code": null, "e": 2451, "s": 2179, "text": "Usually, the task of transforming an object design into code is a straightforward process. Any object-oriented programming language like C++, Java, Smalltalk, C# and Python, includes provision for representing classes. In this chapter, we exemplify the concept using C++." }, { "code": null, "e": 2528, "s": 2451, "text": "The following figure shows the representation of the class Circle using C++." }, { "code": null, "e": 2686, "s": 2528, "text": "Most programming languages do not provide constructs to implement associations directly. So the task of implementing associations needs considerable thought." }, { "code": null, "e": 2828, "s": 2686, "text": "Associations may be either unidirectional or bidirectional. Besides, each association may be either one–to–one, one–to–many, or many–to–many." }, { "code": null, "e": 3000, "s": 2828, "text": "For implementing unidirectional associations, care should be taken so that unidirectionality is maintained. The implementations for different multiplicity are as follows −" }, { "code": null, "e": 3233, "s": 3000, "text": "Optional Associations − Here, a link may or may not exist between the participating objects. For example, in the association between Customer and Current Account in the figure below, a customer may or may not have a current account." }, { "code": null, "e": 3466, "s": 3233, "text": "Optional Associations − Here, a link may or may not exist between the participating objects. For example, in the association between Customer and Current Account in the figure below, a customer may or may not have a current account." }, { "code": null, "e": 3600, "s": 3466, "text": "For implementation, an object of Current Account is included as an attribute in Customer that may be NULL. Implementation using C++ −" }, { "code": null, "e": 3963, "s": 3600, "text": "class Customer {\n private:\n // attributes\n Current_Account c; //an object of Current_Account as attribute\n \n public: \n\n Customer() {\n c = NULL; \n } // assign c as NULL\n\n Current_Account getCurrAc() {\n return c;\n }\n \n void setCurrAc( Current_Account myacc) {\n c = myacc;\n }\n\n void removeAcc() { \n c = NULL;\n } \n};" }, { "code": null, "e": 4173, "s": 3963, "text": "One–to–one Associations − Here, one instance of a class is related to exactly one instance of the associated class. For example, Department and Manager have one–to–one association as shown in the figure below." }, { "code": null, "e": 4383, "s": 4173, "text": "One–to–one Associations − Here, one instance of a class is related to exactly one instance of the associated class. For example, Department and Manager have one–to–one association as shown in the figure below." }, { "code": null, "e": 4504, "s": 4383, "text": "This is implemented by including in Department, an object of Manager that should not be NULL. Implementation using C++ −" }, { "code": null, "e": 4802, "s": 4504, "text": "class Department {\n private:\n // attributes\n Manager mgr; //an object of Manager as attribute\n \n public: \n Department (/*parameters*/, Manager m) { //m is not NULL \n // assign parameters to variables\n mgr = m;\n } \n\n Manager getMgr() { \n return mgr; \n } \n};" }, { "code": null, "e": 5016, "s": 4802, "text": "One–to–many Associations − Here, one instance of a class is related to more than one instances of the associated class. For example, consider the association between Employee and Dependent in the following figure." }, { "code": null, "e": 5230, "s": 5016, "text": "One–to–many Associations − Here, one instance of a class is related to more than one instances of the associated class. For example, consider the association between Employee and Dependent in the following figure." }, { "code": null, "e": 5349, "s": 5230, "text": "This is implemented by including a list of Dependents in class Employee. Implementation using C++ STL list container −" }, { "code": null, "e": 5764, "s": 5349, "text": "class Employee {\n private:\n char * deptName;\n list <Dependent> dep; //a list of Dependents as attribute\n\n public: \n void addDependent ( Dependent d) { \n dep.push_back(d); \n } // adds an employee to the department\n\n void removeDeoendent( Dependent d) { \n int index = find ( d, dep );\n // find() function returns the index of d in list dep\n dep.erase(index);\n } \n};" }, { "code": null, "e": 5856, "s": 5764, "text": "To implement bi-directional association, links in both directions require to be maintained." }, { "code": null, "e": 6030, "s": 5856, "text": "Optional or one–to–one Associations − Consider the relationship between Project and Project Manager having one–to–one bidirectional association as shown in the figure below." }, { "code": null, "e": 6204, "s": 6030, "text": "Optional or one–to–one Associations − Consider the relationship between Project and Project Manager having one–to–one bidirectional association as shown in the figure below." }, { "code": null, "e": 6231, "s": 6204, "text": "Implementation using C++ −" }, { "code": null, "e": 6562, "s": 6231, "text": "Class Project {\n private:\n // attributes\n Project_Manager pmgr; \n public: \n void setManager ( Project_Manager pm); \n Project_Manager changeManager(); \n};\n\nclass Project_Manager {\n private:\n // attributes\n Project pj; \n\n public: \n void setProject(Project p); \n Project removeProject(); \n};" }, { "code": null, "e": 6708, "s": 6562, "text": "One–to–many Associations − Consider the relationship between Department and Employee having one–to–many association as shown in the figure below." }, { "code": null, "e": 6854, "s": 6708, "text": "One–to–many Associations − Consider the relationship between Department and Employee having one–to–many association as shown in the figure below." }, { "code": null, "e": 7382, "s": 6854, "text": "class Department {\n private:\n char * deptName;\n list <Employee> emp; //a list of Employees as attribute\n\n public: \n void addEmployee ( Employee e) { \n emp.push_back(e); \n } // adds an employee to the department\n\n void removeEmployee( Employee e) { \n int index = find ( e, emp );\n // find function returns the index of e in list emp\n emp.erase(index);\n } \n};\n\nclass Employee {\n private:\n //attributes\n Department d;\n\n public:\n void addDept();\n void removeDept();\n};" }, { "code": null, "e": 7589, "s": 7382, "text": "If an association has some attributes associated, it should be implemented using a separate class. For example, consider the one–to–one association between Employee and Project as shown in the figure below." }, { "code": null, "e": 7713, "s": 7589, "text": "class WorksOn {\n private:\n Employee e; \n Project p;\n Hours h;\n char * date;\n\n public:\n // class methods\n};\t " }, { "code": null, "e": 8111, "s": 7713, "text": "Constraints in classes restrict the range and type of values that the attributes may take. In order to implement constraints, a valid default value is assigned to the attribute when an object is instantiated from the class. Whenever the value is changed at runtime, it is checked whether the value is valid or not. An invalid value may be handled by an exception handling routine or other methods." }, { "code": null, "e": 8119, "s": 8111, "text": "Example" }, { "code": null, "e": 8260, "s": 8119, "text": "Consider an Employee class where age is an attribute that may have values in the range of 18 to 60. The following C++ code incorporates it −" }, { "code": null, "e": 8732, "s": 8260, "text": "class Employee {\n private: char * name;\n int age;\n // other attributes\n\n public:\n Employee() { // default constructor \n strcpy(name, \"\");\n age = 18; // default value\n }\n \n class AgeError {}; // Exception class\n void changeAge( int a) { // method that changes age \n if ( a < 18 || a > 60 ) // check for invalid condition\n throw AgeError(); // throw exception\n age = a;\t\t\t\n }\n};" }, { "code": null, "e": 8829, "s": 8732, "text": "There are two alternative implementation strategies to implement states in state chart diagrams." }, { "code": null, "e": 9111, "s": 8829, "text": "In this approach, the states are represented by different values of a data member (or set of data members). The values are explicitly defined by an enumeration within the class. The transitions are represented by member functions that change the value of the concerned data member." }, { "code": null, "e": 9351, "s": 9111, "text": "In this approach, the states are arranged in a generalization hierarchy in a manner that they can be referred by a common pointer variable. The following figure shows a transformation from state chart diagram to a generalization hierarchy." }, { "code": null, "e": 9615, "s": 9351, "text": "An important aspect of developing object-oriented systems is persistency of data. Through persistency, objects have longer lifespan than the program that created it. Persistent data is saved on secondary storage medium from where it can be reloaded when required." }, { "code": null, "e": 9668, "s": 9615, "text": "A database is an ordered collection of related data." }, { "code": null, "e": 9862, "s": 9668, "text": "A database management system (DBMS) is a collection of software that facilitates the processes of defining, creating, storing, manipulating, retrieving, sharing, and removing data in databases." }, { "code": null, "e": 10061, "s": 9862, "text": "In relational database management systems (RDBMS), data is stored as relations or tables, where each column or field represents an attribute and each row or tuple represents a record of an instance." }, { "code": null, "e": 10151, "s": 10061, "text": "Each row is uniquely identified by a chosen set of minimal attributes called primary key." }, { "code": null, "e": 10225, "s": 10151, "text": "A foreign key is an attribute that is the primary key of a related table." }, { "code": null, "e": 10503, "s": 10225, "text": "To map a class to a database table, each attribute is represented as a field in the table. Either an existing attribute(s) is assigned as a primary key or a separate ID field is added as a primary key. The class may be partitioned horizontally or vertically as per requirement." }, { "code": null, "e": 10589, "s": 10503, "text": "For example, the Circle class can be converted to table as shown in the figure below." }, { "code": null, "e": 10859, "s": 10589, "text": "Schema for Circle Table: CIRCLE(CID, X_COORD, Y_COORD, RADIUS, COLOR)\nCreating a Table Circle using SQL command:\nCREATE TABLE CIRCLE ( \n CID\tVARCHAR2(4) PRIMARY KEY,\n X_COORD INTEGER NOT NULL,\n Y_COORD INTEGER NOT NULL,\n Z_COORD INTEGER NOT NULL,\n COLOR \n);" }, { "code": null, "e": 11045, "s": 10859, "text": "To implement 1:1 associations, the primary key of any one table is assigned as the foreign key of the other table. For example, consider the association between Department and Manager −" }, { "code": null, "e": 11317, "s": 11045, "text": "CREATE TABLE DEPARTMENT ( \n DEPT_ID INTEGER PRIMARY KEY,\n DNAME VARCHAR2(30) NOT NULL,\n LOCATION VARCHAR2(20),\n EMPID INTEGER REFERENCES MANAGER \n);\n\nCREATE TABLE MANAGER ( \n EMPID INTEGER PRIMARY KEY,\n ENAME VARCHAR2(50) NOT NULL,\n ADDRESS VARCHAR2(70),\n);" }, { "code": null, "e": 11560, "s": 11317, "text": "To implement 1:N associations, the primary key of the table in the 1-side of the association is assigned as the foreign key of the table at the N-side of the association. For example, consider the association between Department and Employee −" }, { "code": null, "e": 11834, "s": 11560, "text": "CREATE TABLE DEPARTMENT ( \n DEPT_ID INTEGER PRIMARY KEY,\n DNAME VARCHAR2(30) NOT NULL,\n LOCATION VARCHAR2(20),\n);\n\nCREATE TABLE EMPLOYEE ( \n EMPID INTEGER PRIMARY KEY,\n ENAME VARCHAR2(50) NOT NULL,\n ADDRESS VARCHAR2(70),\n D_ID INTEGER REFERENCES DEPARTMENT\n);" }, { "code": null, "e": 12003, "s": 11834, "text": "To implement M:N associations, a new relation is created that represents the association. For example, consider the following association between Employee and Project −" }, { "code": null, "e": 12072, "s": 12003, "text": "Schema for Works_On Table − WORKS_ON (EMPID, PID, HOURS, START_DATE)" }, { "code": null, "e": 12139, "s": 12072, "text": "SQL command to create Works_On association − CREATE TABLE WORKS_ON" }, { "code": null, "e": 12332, "s": 12139, "text": "( \n EMPID INTEGER,\n PID INTEGER, \n HOURS INTEGER,\n START_DATE DATE,\n PRIMARY KEY (EMPID, PID),\n FOREIGN KEY (EMPID) REFERENCES EMPLOYEE,\n FOREIGN KEY (PID) REFERENCES PROJECT \n);" }, { "code": null, "e": 12472, "s": 12332, "text": "To map inheritance, the primary key of the base table(s) is assigned as the primary key as well as the foreign key in the derived table(s)." }, { "code": null, "e": 12480, "s": 12472, "text": "Example" }, { "code": null, "e": 12515, "s": 12480, "text": "\n 14 Lectures \n 1.5 hours \n" }, { "code": null, "e": 12535, "s": 12515, "text": " Harshit Srivastava" }, { "code": null, "e": 12568, "s": 12535, "text": "\n 60 Lectures \n 8 hours \n" }, { "code": null, "e": 12599, "s": 12568, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 12631, "s": 12599, "text": "\n 11 Lectures \n 35 mins\n" }, { "code": null, "e": 12652, "s": 12631, "text": " Sandip Bhattacharya" }, { "code": null, "e": 12685, "s": 12652, "text": "\n 21 Lectures \n 2 hours \n" }, { "code": null, "e": 12705, "s": 12685, "text": " Pranjal Srivastava" }, { "code": null, "e": 12736, "s": 12705, "text": "\n 6 Lectures \n 43 mins\n" }, { "code": null, "e": 12753, "s": 12736, "text": " Frahaan Hussain" }, { "code": null, "e": 12788, "s": 12753, "text": "\n 49 Lectures \n 4.5 hours \n" }, { "code": null, "e": 12805, "s": 12788, "text": " Abhilash Nelson" }, { "code": null, "e": 12812, "s": 12805, "text": " Print" }, { "code": null, "e": 12823, "s": 12812, "text": " Add Notes" } ]
Make the button size extra small with Bootstrap
Use the .btn-xs class to create a button size extra small than the standard button. You can try to run the following code to make the size of a button extra small Live Demo <!DOCTYPE html> <html> <head> <title>Bootstrap Example</title> <meta name = "viewport" content = "width = device-width, initial-scale = 1"> <link rel = "stylesheet" href = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css"> <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script> </head> <body> <p>The following are extra small buttons:</p> <button type = "button" class = "btn btn-primary btn-xs"> Exra Small Primary button </button> <button type = "button" class = "btn btn-default btn-xs"> Extra Small button </button> </body> </html>
[ { "code": null, "e": 1146, "s": 1062, "text": "Use the .btn-xs class to create a button size extra small than the standard button." }, { "code": null, "e": 1225, "s": 1146, "text": "You can try to run the following code to make the size of a button extra small" }, { "code": null, "e": 1235, "s": 1225, "text": "Live Demo" }, { "code": null, "e": 2019, "s": 1235, "text": "<!DOCTYPE html>\n<html>\n <head>\n <title>Bootstrap Example</title>\n <meta name = \"viewport\" content = \"width = device-width, initial-scale = 1\">\n <link rel = \"stylesheet\" href = \"https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css\">\n <script src = \"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n <script src = \"https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js\"></script>\n </head>\n <body>\n <p>The following are extra small buttons:</p>\n <button type = \"button\" class = \"btn btn-primary btn-xs\">\n Exra Small Primary button\n </button>\n <button type = \"button\" class = \"btn btn-default btn-xs\">\n Extra Small button\n </button>\n </body>\n</html>" } ]
ArangoDB - Example Case Scenarios
In this chapter, we will consider two example scenarios. These examples are easier to comprehend and will help us understand the way the ArangoDB functionality works. To demonstrate the APIs, ArangoDB comes preloaded with a set of easily understandable graphs. There are two methods to create instances of these graphs in your ArangoDB − Add Example tab in the create graph window in the web interface, or load the module @arangodb/graph-examples/example-graph in Arangosh. To start with, let us load a graph with the help of web interface. For that, launch the web interface and click on the graphs tab. The Create Graph dialog box appears. The Wizard contains two tabs – Examples and Graph. The Graph tab is open by default; supposing we want to create a new graph, it will ask for the name and other definitions for the graph. Now, we will upload the already created graph. For this, we will select the Examples tab. We can see the three example graphs. Select the Knows_Graph and click on the green button Create. Once you have created them, you can inspect them in the web interface - which was used to create the pictures below. Let us now see how the Knows_Graph works. Select the Knows_Graph, and it will fetch the graph data. The Knows_Graph consists of one vertex collection persons connected via one edge collection knows. It will contain five persons Alice, Bob, Charlie, Dave and Eve as vertices. We will have the following directed relations Alice knows Bob Bob knows Charlie Bob knows Dave Eve knows Alice Eve knows Bob If you click a node (vertex), say ‘bob’, it will show the ID (persons/bob) attribute name. And on clicking any of the edge, it will show the ID (knows/4590) attributes. This is how we create it, inspect its vertices and edges. Let us add another graph, this time using Arangosh. For that, we need to include another endpoint in the ArangoDB configuration file. Open the configuration file − # vim /etc/arangodb3/arangod.conf Add another endpoint as shown in the terminal screenshot below. Restart the ArangoDB − # service arangodb3 restart Launch the Arangosh − # arangosh Please specify a password: _ __ _ _ __ __ _ _ __ __ _ ___ ___| |__ / _` | '__/ _` | '_ \ / _` |/ _ \/ __| '_ \ | (_| | | | (_| | | | | (_| | (_) \__ \ | | | \__,_|_| \__,_|_| |_|\__, |\___/|___/_| |_| |___/ arangosh (ArangoDB 3.1.27 [linux] 64bit, using VPack 0.1.30, ICU 54.1, V8 5.0.71.39, OpenSSL 1.0.2g 1 Mar 2016) Copyright (c) ArangoDB GmbH Pretty printing values. Connected to ArangoDB 'http+tcp://127.0.0.1:8529' version: 3.1.27 [server], database: '_system', username: 'root' Please note that a new minor version '3.2.2' is available Type 'tutorial' for a tutorial or 'help' to see common examples 127.0.0.1:8529@_system> Let us now understand what a Social_Graph is and how it works. The graph shows a set of persons and their relations − This example has female and male persons as vertices in two vertex collections - female and male. The edges are their connections in the relation edge collection. We have described how to create this graph using Arangosh. The reader can work around it and explore its attributes, as we did with the Knows_Graph. Print Add Notes Bookmark this page
[ { "code": null, "e": 2147, "s": 1980, "text": "In this chapter, we will consider two example scenarios. These examples are easier to comprehend and will help us understand the way the ArangoDB functionality works." }, { "code": null, "e": 2318, "s": 2147, "text": "To demonstrate the APIs, ArangoDB comes preloaded with a set of easily understandable graphs. There are two methods to create instances of these graphs in your ArangoDB −" }, { "code": null, "e": 2383, "s": 2318, "text": "Add Example tab in the create graph window in the web interface," }, { "code": null, "e": 2454, "s": 2383, "text": "or load the module @arangodb/graph-examples/example-graph in Arangosh." }, { "code": null, "e": 2585, "s": 2454, "text": "To start with, let us load a graph with the help of web interface. For that, launch the web interface and click on the graphs tab." }, { "code": null, "e": 2810, "s": 2585, "text": "The Create Graph dialog box appears. The Wizard contains two tabs – Examples and Graph. The Graph tab is open by default; supposing we want to create a new graph, it will ask for the name and other definitions for the graph." }, { "code": null, "e": 2900, "s": 2810, "text": "Now, we will upload the already created graph. For this, we will select the Examples tab." }, { "code": null, "e": 2998, "s": 2900, "text": "We can see the three example graphs. Select the Knows_Graph and click on the green button Create." }, { "code": null, "e": 3115, "s": 2998, "text": "Once you have created them, you can inspect them in the web interface - which was used to create the pictures below." }, { "code": null, "e": 3215, "s": 3115, "text": "Let us now see how the Knows_Graph works. Select the Knows_Graph, and it will fetch the graph data." }, { "code": null, "e": 3436, "s": 3215, "text": "The Knows_Graph consists of one vertex collection persons connected via one edge collection knows. It will contain five persons Alice, Bob, Charlie, Dave and Eve as vertices. We will have the following directed relations" }, { "code": null, "e": 3516, "s": 3436, "text": "Alice knows Bob\nBob knows Charlie\nBob knows Dave\nEve knows Alice\nEve knows Bob\n" }, { "code": null, "e": 3607, "s": 3516, "text": "If you click a node (vertex), say ‘bob’, it will show the ID (persons/bob) attribute name." }, { "code": null, "e": 3685, "s": 3607, "text": "And on clicking any of the edge, it will show the ID (knows/4590) attributes." }, { "code": null, "e": 3743, "s": 3685, "text": "This is how we create it, inspect its vertices and edges." }, { "code": null, "e": 3877, "s": 3743, "text": "Let us add another graph, this time using Arangosh. For that, we need to include another endpoint in the ArangoDB configuration file." }, { "code": null, "e": 3907, "s": 3877, "text": "Open the configuration file −" }, { "code": null, "e": 3942, "s": 3907, "text": "# vim /etc/arangodb3/arangod.conf\n" }, { "code": null, "e": 4006, "s": 3942, "text": "Add another endpoint as shown in the terminal screenshot below." }, { "code": null, "e": 4029, "s": 4006, "text": "Restart the ArangoDB −" }, { "code": null, "e": 4058, "s": 4029, "text": "# service arangodb3 restart\n" }, { "code": null, "e": 4080, "s": 4058, "text": "Launch the Arangosh −" }, { "code": null, "e": 4723, "s": 4080, "text": "# arangosh\nPlease specify a password:\n_\n__ _ _ __ __ _ _ __ __ _ ___ ___| |__\n/ _` | '__/ _` | '_ \\ / _` |/ _ \\/ __| '_ \\\n| (_| | | | (_| | | | | (_| | (_) \\__ \\ | | |\n\\__,_|_| \\__,_|_| |_|\\__, |\\___/|___/_| |_|\n|___/\narangosh (ArangoDB 3.1.27 [linux] 64bit, using VPack 0.1.30, ICU 54.1, V8\n5.0.71.39, OpenSSL 1.0.2g 1 Mar 2016)\nCopyright (c) ArangoDB GmbH\nPretty printing values.\nConnected to ArangoDB 'http+tcp://127.0.0.1:8529' version: 3.1.27\n[server], database: '_system', username: 'root'\nPlease note that a new minor version '3.2.2' is available\nType 'tutorial' for a tutorial or 'help' to see common examples\n127.0.0.1:8529@_system>\n" }, { "code": null, "e": 4841, "s": 4723, "text": "Let us now understand what a Social_Graph is and how it works. The graph shows a set of persons and their relations −" }, { "code": null, "e": 5153, "s": 4841, "text": "This example has female and male persons as vertices in two vertex collections - female and male. The edges are their connections in the relation edge collection. We have described how to create this graph using Arangosh. The reader can work around it and explore its attributes, as we did with the Knows_Graph." }, { "code": null, "e": 5160, "s": 5153, "text": " Print" }, { "code": null, "e": 5171, "s": 5160, "text": " Add Notes" } ]