title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Gnome Sort
14 Jun, 2022 Gnome Sort also called Stupid sort is based on the concept of a Garden Gnome sorting his flower pots. A garden gnome sorts the flower pots by the following method- He looks at the flower pot next to him and the previous one; if they are in the right order he steps one pot forward, otherwise he swaps them and steps one pot backwards. If there is no previous pot (he is at the starting of the pot line), he steps forwards; if there is no pot next to him (he is at the end of the pot line), he is done. Input – Array- arr[] Total elements – n Lets consider an example: arr[] = {34, 2, 10, -9} Underlined elements are the pair under consideration. “Red” colored are the pair which needs to be swapped. Result of the swapping is colored as “blue” Algorithm Steps: If you are at the start of the array then go to the right element (from arr[0] to arr[1]). If the current array element is larger or equal to the previous array element then go one step right if (arr[i] >= arr[i-1]) i++; If the current array element is smaller than the previous array element then swap these two elements and go one step backwards if (arr[i] < arr[i-1]){swap(arr[i], arr[i-1]); i–;} Repeat steps 2) and 3) till ‘i’ reaches the end of the array (i.e- ‘n-1’) If the end of the array is reached then stop and the array is sorted. Below is the implementation of the algorithm. C++ Java Python C# PHP Javascript // A C++ Program to implement Gnome Sort#include <iostream>using namespace std; // A function to sort the algorithm using gnome sortvoid gnomeSort(int arr[], int n){ int index = 0; while (index < n) { if (index == 0) index++; if (arr[index] >= arr[index - 1]) index++; else { swap(arr[index], arr[index - 1]); index--; } } return;} // A utility function ot print an array of size nvoid printArray(int arr[], int n){ cout << "Sorted sequence after Gnome sort: "; for (int i = 0; i < n; i++) cout << arr[i] << " "; cout << "\n";} // Driver program to test above functions.int main(){ int arr[] = { 34, 2, 10, -9 }; int n = sizeof(arr) / sizeof(arr[0]); gnomeSort(arr, n); printArray(arr, n); return (0);} // Java Program to implement Gnome Sort import java.util.Arrays;public class GFG { static void gnomeSort(int arr[], int n) { int index = 0; while (index < n) { if (index == 0) index++; if (arr[index] >= arr[index - 1]) index++; else { int temp = 0; temp = arr[index]; arr[index] = arr[index - 1]; arr[index - 1] = temp; index--; } } return; } // Driver program to test above functions. public static void main(String[] args) { int arr[] = { 34, 2, 10, -9 }; gnomeSort(arr, arr.length); System.out.print("Sorted sequence after applying Gnome sort: "); System.out.println(Arrays.toString(arr)); }} // Code Contributed by Mohit Gupta_OMG # Python program to implement Gnome Sort # A function to sort the given list using Gnome sortdef gnomeSort( arr, n): index = 0 while index < n: if index == 0: index = index + 1 if arr[index] >= arr[index - 1]: index = index + 1 else: arr[index], arr[index-1] = arr[index-1], arr[index] index = index - 1 return arr # Driver Codearr = [ 34, 2, 10, -9]n = len(arr) arr = gnomeSort(arr, n)print "Sorted sequence after applying Gnome Sort :",for i in arr: print i, # Contributed By Harshit Agrawal // C# Program to implement Gnome Sortusing System; class GFG { static void gnomeSort(int[] arr, int n) { int index = 0; while (index < n) { if (index == 0) index++; if (arr[index] >= arr[index - 1]) index++; else { int temp = 0; temp = arr[index]; arr[index] = arr[index - 1]; arr[index - 1] = temp; index--; } } return; } // Driver program to test above functions. public static void Main() { int[] arr = { 34, 2, 10, -9 }; // Function calling gnomeSort(arr, arr.Length); Console.Write("Sorted sequence after applying Gnome sort: "); for (int i = 0; i < arr.Length; i++) Console.Write(arr[i] + " "); }} // This code is contributed by Sam007 <?php// PHP Program to implement// Gnome Sort // A function to sort the // algorithm using gnome sortfunction gnomeSort($arr, $n){ $index = 0; while ($index < $n) { if ($index == 0) $index++; if ($arr[$index] >= $arr[$index - 1]) $index++; else { $temp = 0; $temp = $arr[$index]; $arr[$index] = $arr[$index - 1]; $arr[$index - 1] = $temp; $index--; } } echo "Sorted sequence ", "after Gnome sort: "; for ($i = 0; $i < $n; $i++) echo $arr[$i] . " "; echo "\n"; } // Driver Code$arr = array(34, 2, 10, -9);$n = count($arr); gnomeSort($arr, $n); // This code is contributed// by Sam007?> <script> // Javascript Program to implement Gnome Sort function gnomeSort(arr, n) { let index = 0; while (index < n) { if (index == 0) index++; if (arr[index] >= arr[index - 1]) index++; else { let temp = 0; temp = arr[index]; arr[index] = arr[index - 1]; arr[index - 1] = temp; index--; } } return; } // Driver Code let arr = [34, 2, 10, -9 ]; gnomeSort(arr, arr.length); document.write("Sorted sequence after applying Gnome sort: "); document.write(arr.toString()); </script> Sorted sequence after Gnome sort: -9 2 10 34 Time Complexity: As there are no nested loop (only one while) it may seem that this is a linear O(N) time algorithm. But the time complexity is O(N^2). This is because: The variable – ‘index’ in our program doesn’t always gets incremented, it gets decremented too. However this sorting algorithm is adaptive and performs better if the array is already/partially sorted. Auxiliary Space: This is an in-place algorithm. So O(1) auxiliary space is needed. This article is contributed by Rachit Belwariar. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above Sam007 splevel62 simmytarika5 kashishkumar2 Sorting Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n14 Jun, 2022" }, { "code": null, "e": 219, "s": 53, "text": "Gnome Sort also called Stupid sort is based on the concept of a Garden Gnome sorting his flower pots. A garden gnome sorts the flower pots by the following method- " }, { "code": null, "e": 390, "s": 219, "text": "He looks at the flower pot next to him and the previous one; if they are in the right order he steps one pot forward, otherwise he swaps them and steps one pot backwards." }, { "code": null, "e": 557, "s": 390, "text": "If there is no previous pot (he is at the starting of the pot line), he steps forwards; if there is no pot next to him (he is at the end of the pot line), he is done." }, { "code": null, "e": 567, "s": 557, "text": "Input – " }, { "code": null, "e": 600, "s": 567, "text": "Array- arr[] Total elements – n" }, { "code": null, "e": 650, "s": 600, "text": "Lets consider an example: arr[] = {34, 2, 10, -9}" }, { "code": null, "e": 704, "s": 650, "text": "Underlined elements are the pair under consideration." }, { "code": null, "e": 758, "s": 704, "text": "“Red” colored are the pair which needs to be swapped." }, { "code": null, "e": 802, "s": 758, "text": "Result of the swapping is colored as “blue”" }, { "code": null, "e": 821, "s": 804, "text": "Algorithm Steps:" }, { "code": null, "e": 912, "s": 821, "text": "If you are at the start of the array then go to the right element (from arr[0] to arr[1])." }, { "code": null, "e": 1013, "s": 912, "text": "If the current array element is larger or equal to the previous array element then go one step right" }, { "code": null, "e": 1043, "s": 1013, "text": " if (arr[i] >= arr[i-1]) i++;" }, { "code": null, "e": 1170, "s": 1043, "text": "If the current array element is smaller than the previous array element then swap these two elements and go one step backwards" }, { "code": null, "e": 1224, "s": 1170, "text": " if (arr[i] < arr[i-1]){swap(arr[i], arr[i-1]); i–;} " }, { "code": null, "e": 1298, "s": 1224, "text": "Repeat steps 2) and 3) till ‘i’ reaches the end of the array (i.e- ‘n-1’)" }, { "code": null, "e": 1368, "s": 1298, "text": "If the end of the array is reached then stop and the array is sorted." }, { "code": null, "e": 1414, "s": 1368, "text": "Below is the implementation of the algorithm." }, { "code": null, "e": 1418, "s": 1414, "text": "C++" }, { "code": null, "e": 1423, "s": 1418, "text": "Java" }, { "code": null, "e": 1430, "s": 1423, "text": "Python" }, { "code": null, "e": 1433, "s": 1430, "text": "C#" }, { "code": null, "e": 1437, "s": 1433, "text": "PHP" }, { "code": null, "e": 1448, "s": 1437, "text": "Javascript" }, { "code": "// A C++ Program to implement Gnome Sort#include <iostream>using namespace std; // A function to sort the algorithm using gnome sortvoid gnomeSort(int arr[], int n){ int index = 0; while (index < n) { if (index == 0) index++; if (arr[index] >= arr[index - 1]) index++; else { swap(arr[index], arr[index - 1]); index--; } } return;} // A utility function ot print an array of size nvoid printArray(int arr[], int n){ cout << \"Sorted sequence after Gnome sort: \"; for (int i = 0; i < n; i++) cout << arr[i] << \" \"; cout << \"\\n\";} // Driver program to test above functions.int main(){ int arr[] = { 34, 2, 10, -9 }; int n = sizeof(arr) / sizeof(arr[0]); gnomeSort(arr, n); printArray(arr, n); return (0);}", "e": 2275, "s": 1448, "text": null }, { "code": "// Java Program to implement Gnome Sort import java.util.Arrays;public class GFG { static void gnomeSort(int arr[], int n) { int index = 0; while (index < n) { if (index == 0) index++; if (arr[index] >= arr[index - 1]) index++; else { int temp = 0; temp = arr[index]; arr[index] = arr[index - 1]; arr[index - 1] = temp; index--; } } return; } // Driver program to test above functions. public static void main(String[] args) { int arr[] = { 34, 2, 10, -9 }; gnomeSort(arr, arr.length); System.out.print(\"Sorted sequence after applying Gnome sort: \"); System.out.println(Arrays.toString(arr)); }} // Code Contributed by Mohit Gupta_OMG", "e": 3146, "s": 2275, "text": null }, { "code": "# Python program to implement Gnome Sort # A function to sort the given list using Gnome sortdef gnomeSort( arr, n): index = 0 while index < n: if index == 0: index = index + 1 if arr[index] >= arr[index - 1]: index = index + 1 else: arr[index], arr[index-1] = arr[index-1], arr[index] index = index - 1 return arr # Driver Codearr = [ 34, 2, 10, -9]n = len(arr) arr = gnomeSort(arr, n)print \"Sorted sequence after applying Gnome Sort :\",for i in arr: print i, # Contributed By Harshit Agrawal", "e": 3723, "s": 3146, "text": null }, { "code": "// C# Program to implement Gnome Sortusing System; class GFG { static void gnomeSort(int[] arr, int n) { int index = 0; while (index < n) { if (index == 0) index++; if (arr[index] >= arr[index - 1]) index++; else { int temp = 0; temp = arr[index]; arr[index] = arr[index - 1]; arr[index - 1] = temp; index--; } } return; } // Driver program to test above functions. public static void Main() { int[] arr = { 34, 2, 10, -9 }; // Function calling gnomeSort(arr, arr.Length); Console.Write(\"Sorted sequence after applying Gnome sort: \"); for (int i = 0; i < arr.Length; i++) Console.Write(arr[i] + \" \"); }} // This code is contributed by Sam007", "e": 4643, "s": 3723, "text": null }, { "code": "<?php// PHP Program to implement// Gnome Sort // A function to sort the // algorithm using gnome sortfunction gnomeSort($arr, $n){ $index = 0; while ($index < $n) { if ($index == 0) $index++; if ($arr[$index] >= $arr[$index - 1]) $index++; else { $temp = 0; $temp = $arr[$index]; $arr[$index] = $arr[$index - 1]; $arr[$index - 1] = $temp; $index--; } } echo \"Sorted sequence \", \"after Gnome sort: \"; for ($i = 0; $i < $n; $i++) echo $arr[$i] . \" \"; echo \"\\n\"; } // Driver Code$arr = array(34, 2, 10, -9);$n = count($arr); gnomeSort($arr, $n); // This code is contributed// by Sam007?>", "e": 5385, "s": 4643, "text": null }, { "code": "<script> // Javascript Program to implement Gnome Sort function gnomeSort(arr, n) { let index = 0; while (index < n) { if (index == 0) index++; if (arr[index] >= arr[index - 1]) index++; else { let temp = 0; temp = arr[index]; arr[index] = arr[index - 1]; arr[index - 1] = temp; index--; } } return; } // Driver Code let arr = [34, 2, 10, -9 ]; gnomeSort(arr, arr.length); document.write(\"Sorted sequence after applying Gnome sort: \"); document.write(arr.toString()); </script>", "e": 6109, "s": 5385, "text": null }, { "code": null, "e": 6155, "s": 6109, "text": "Sorted sequence after Gnome sort: -9 2 10 34 " }, { "code": null, "e": 6307, "s": 6155, "text": "Time Complexity: As there are no nested loop (only one while) it may seem that this is a linear O(N) time algorithm. But the time complexity is O(N^2)." }, { "code": null, "e": 6325, "s": 6307, "text": "This is because: " }, { "code": null, "e": 6422, "s": 6325, "text": "The variable – ‘index’ in our program doesn’t always gets incremented, it gets decremented too. " }, { "code": null, "e": 6527, "s": 6422, "text": "However this sorting algorithm is adaptive and performs better if the array is already/partially sorted." }, { "code": null, "e": 6610, "s": 6527, "text": "Auxiliary Space: This is an in-place algorithm. So O(1) auxiliary space is needed." }, { "code": null, "e": 7004, "s": 6610, "text": "This article is contributed by Rachit Belwariar. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above" }, { "code": null, "e": 7011, "s": 7004, "text": "Sam007" }, { "code": null, "e": 7021, "s": 7011, "text": "splevel62" }, { "code": null, "e": 7034, "s": 7021, "text": "simmytarika5" }, { "code": null, "e": 7048, "s": 7034, "text": "kashishkumar2" }, { "code": null, "e": 7056, "s": 7048, "text": "Sorting" }, { "code": null, "e": 7064, "s": 7056, "text": "Sorting" } ]
Figuring out a Fair Price of a Used Car in a Data Science Way | by Kirill Lepchenkov | Towards Data Science
What is an ordinary way of figuring out the price for a used car? You search for similar vehicles, estimate the rough baseline price and then fine-tune it depending on the current mileage, color, number of options, etc. You use both domain knowledge and current market state analysis. If you go deeper, you may consider selling the car in a different region of the country where the average price is higher. You may even investigate for how long cars are listed in the catalog and detect overpriced samples to make more informed decision. So there is a lot to think about, and the question I faced here was “Is it possible that using data science methods (collecting and cleaning the data, training ML models, etc.) can save your time and mental effort in a painful decision making process?” I opened a laptop, created a new project and turned the timer on. Without going into too much details: I’ve managed to collect a dataset containing roughly 40,000 car ads with 35 features (mostly categorical) in two days. Collecting the data itself wasn’t too much pain, but structuring it in an organized way took a bit of time. I’ve used Python, Requests, Pandas, NumPy, SciPy, etc. What is interesting about this particular dataset is that most of the categorical features are not encoded in any way and thus can be easily interpreted (like engine_fuel = “diesel”). Initial data analysis quickly revealed suspicious samples with 8 million kilometers odometer state, 10 liter engine hatchbacks, hybrid diesel vehicles for $600, etc. I’ve spent roughly 6 hours writing scripts to detect these issues and process them. Visualizing the data (I’ve used MatPlotlib and Seaborn) gave me a good sense of the overall market situation. The majority of the cars are pretty heavily used with mean odometer_value of 250,000 kilometers, and that is a lot! I’ve also noticed that people prefer to assign nice numbers to odometer_value like 250,000 km, 300,000 km, 350,000 km, etc. A bunch of cars have one million kilometers odometer_value and it does not make much sense if you look at the values distribution. I may presume that 1 million kilometers is more like a statement “This car have seen a lot, the exact number of kilometers on it I honestly don’t know.” The general trend behind car pricing is pretty intuitive: the older the car — the lower the price. I’ve expected the age of the car to be number one feature in overall feature hierarchy. Also, the older the car, the higher its odometer_value in general, and that is reasonable. To build price_usd scatter plot I’ve limited maximum car price for roughly $50,000 and removed several million-level kilometer odometer_value outliers. Actually cars that have price below $50,000 constitute 99.9 % of the catalog, so scatter plot gives a good sense of pricing trend. Regarding car age: most of the cars have been used for a while, with the mean year_produced value of 2002. I believe that the distribution of production year (depicted below) was heavily influenced by policies around customs duties for importing cars from abroad. Prices distribution (price_usd is going to be the target value in this project during model training) is highly skewed to the right with the mean and median price of $7,275 and $4,900 accordingly. Some features like up_counter (number of times the ad has been promoted manually) don’t reflect parameters of the car at all, but since this data has been available, I decided to include it into the project. The distribution was so skewed that the only way to properly plot it was to use log scale. The distribution of brands popularity wasn’t a surprise for me with the most popular model in the catalog being VW Passat, the legendary source of transportation in Belarus. I also used Tableau to get nicer visual representation of manufacturer’s marketshare and average price for each brand. The shape of distribution of number_of_photos that cars have is similar to price_usd distribution (distribution is skewed to the right). Maybe the higher the price for a car, the higher number of photos? I’ve made a joint plot, which shows a slight correlation, but more importantly, it clearly shows that the the majority of cars are cheap and have less than 15 photos. Some features like drivetrain were just interesting to explore. On the histogram below you can see how the percentage of rear-wheel drive cars decreased over the last 30 years. The whole correlation matrix for the dataset is depicted below (most of the features in the dataset are self-explanatory, except feature_0 ... feature_9: these are boolean columns which indicate that car has features like alloy wheels, air conditioner, etc.) I’m not going to publish full exploratory analysis here, you can check it out in the kernel. I’ve spent approximately six hours (and I need 60 more hours to fix problematic samples in the dataset) digging into the data, engineering features and only then I moved into model training. Since I’ve already cleaned the dataset and applied some feature engineering with future machine learning in mind, building and training a baseline model was a breeze. To get maximum results with the least effort I’ve used CatBoost (gradient boosting on decision trees library with comprehensive categorical feature support developed and open sourced by Yandex). I’ve already spent too much time on the project, so I just threw the data into the model, tweaked the learning rate, tree depth and a number trees in the ensemble, trained several models and started exploring model decision making with SHAP (developed by Scott Lundberg et al). Total time spent: 4 hours. Fun fact: during initial prediction exploration phase I was disappointed in the performance of the model, started exploring the mistakes and found out that price column in my dataset had been parsed incorrectly, some prices had US dollars currency and some had the national currency of Belarus: BYN. I’ve fixed the code of the parser, gathered data again, then run cleaning, feature engineering and analytics jobs and started training models with much better results. To train and evaluate the first model I’ve filtered out cars with prices above $30,000 (during exploration phase I’ve discovered that these samples need a separate model). I had no time and computational resources to run proper grid search and sequential feature selection (SFS) jobs, so I’ve just tweaked number of trees and learning rate several time and used 5-fold cross-validation to estimate the performance of the model (check full kernel). The first decent CatBoost model got me to approximately $1,000 MAE (mean absolute error), which is 15 % of the mean value of price_usd target. To be exact on the scoring: Best validation MAE score: $1019.18 on iteration 6413 with std $12.84 I’ve also used early_stopping parameter to skip further training when the validation score stops getting better. Without trying to improve the model in any way I moved into prediction analysis. Looking at the distribution of errors and 2d histograms plots for true and predicted values does not tell you much about the quality of predictions. The hierarchy of SHAP values (only top 20 features displayed) for features in the dataset didn’t seem surprising to me, apart from low position of odometer_value feature. You can find good explanation on non-parametric model interpretation in articles like this. Age of the car, brand, type of the body, engine capacity and drivetrain are at the top of the hierarchy and that seems very reasonable. State feature turned out to be an interesting one: the vast majority of cars are “owned”, but there is a small percentage of “new” cars (they are expensive) and a number of “emergency” vehicles which are damaged. The problem with damaged cars is obvious: the column is boolean and there is no degree of this “emergency state” (more on this later). Exploring individual predictions quickly gave me a sense of both model and data limitations. I’ll shortlist some of the samples to give a better sense of a model’s decision making process. Sample 0: VW T5 Caravelle, 2009, mechanical gearbox, 287,000 km, diesel. Listed price is $13,600 . The prediction is lower by $1,200 (MAE for the model is about a $1,000, so that is rather typical case). You can see that Volkswagen brand and minivan body_type make individual contributions to make the predicted price of a sample higher. Using SHAP we can plot decision making interpretation in even nicer way by using “decision plot” functionality. Decision plots were recently added to the library and provide even more detailed view of a model’s inner workings. The main benefit of decision plots in comparison to force plots is that they are able to showcase a larger number of features clearly. You can read more about this type of plots here. Sample 1: Mercedes-Benz E270, 2000, mechanical gearbox, 465,000 km, diesel. Listed price is $4,999 . The prediction is higher by $198. That is not bad at all! Sample 2: Jeep Grand Cherokee, 2007, automatic gearbox, 166,000 km, diesel. Listed price is $14,500. The prediction is lower by $2,796. Poor prediction, at a first glance, but the model has been listed in the catalog for 498 days! Feels like the price for this particular sample had been set really too high. It is also listed in the poorest region of the country, where cars are cheaper in general and listed for a longer period of time. Sample 3: VW Passat, 2012, automatic gearbox, 102,000 km, gasoline. Listed price is $11,499. The prediction is lower by $64. Sample 4: VAZ 2107 (Russian car), 1987, mechanical gearbox, 120,000 km, gasoline. Listed price is $399. The prediction is higher by $34. That is the one from a lower end of the price spectrum. We can see how basically all feature values of this sample contribute negatively to the predicted price. Sample 5: VW Passat, 1992, mechanical gearbox, 398,000 km, gasoline. Listed price is $750. The prediction is higher by $721(almost two times the listed value)! Why? If we look closer to the model interpretation we can see that state = emergency is an important contributor to the predicted price. Further manual investigation of this particular case revealed that a car has been damaged by a fallen tree. That is clearly a limitation of existing data: boolean state column simply can’t reflect the overall spectrum of levels of damage. I believe this issue can be fixed “easily” by applying two more mechanisms: image analysis with some kind of pre-trained deep CNN and entity extraction from sample description using RNNs. I will end this sample selection with a luxury BMW 3-series. Sample 6: BMW 316, 1994, mechanical gearbox, 320,000 km, gasoline. Listed price is $1,650. The prediction is higher by $55. We can clearly see that being a luxury brand gives some points to the sample. I’ve spent roughly 3 hours digging into model’s predictions and manually exploring the samples. I’ve got approximately $1,000 MAE using CatBoost Regressor on the whole dataset. But I’ve also tried to use the same approach for separate models and immediately halved the error to $500. I believe that the performance of the model will be even better if we divide the dataset in sub-datasets based on year_produced feature and train multiple models on these sub-datasets. I’ve been also thinking that duration_listed feature may be used to penalize sample weights in the dataset. For example, if the car is listed for a year that probably means that the price is set to be too high, so we can set the weight of this sample to be lower using pooling functionality. In general I feel like the model I’ve trained performs reasonably well, but there is a big room for further improvement. Regarding technologies used in this project: CatBoost seems to be exactly the right choice because it provides great out-of-the-box categorical feature support. Training with 5-fold cross validation took about 13 minutes on a 2019 MacBook pro, but if I had millions of samples in a dataset, that wouldn’t be an issue because CatBoost supports training on GPU. It also has very fast prediction time which helps when models move into production. The question I’ve tried to answer in this adventure is “Can using data science methods be justified if you are going to sell your own car?” The obvious answer for this is no: you would make a much better progress figuring out the price if you just manually search for similar vehicles online. It took me several days to complete the project in a simple way and there is so much more I could do to improve the performance of the model like apply proper feature selection, grid search, etc. At the same time, the answer is definitely yes if you have hundreds or thousands vehicles to sell. Using Python and rich ecosystem of data science packages you can automate jobs of gathering data, building analytics and training predictive models. You can also discover trends and forecast the future of the market. You can hide models behind some APIs so they can serve the business in a reliable and convenient way. And there is so much more. If you run business that imports used cars from abroad, you can train separate ML models to rank samples based on their profitability for the company. You can also forecast the duration these sample are going to be listed before the actual deal. You can even choose the right region for sale. The possibilities are unlimited if you just have enough data. But if you are just doing this kind of side projects for yourself you are going to have great fun like I did! Thanks for reading, I hope you enjoyed this article, you can check my kernels and a dataset. If you have any feedback, you can reach out to me via LinkedIn.
[ { "code": null, "e": 457, "s": 172, "text": "What is an ordinary way of figuring out the price for a used car? You search for similar vehicles, estimate the rough baseline price and then fine-tune it depending on the current mileage, color, number of options, etc. You use both domain knowledge and current market state analysis." }, { "code": null, "e": 711, "s": 457, "text": "If you go deeper, you may consider selling the car in a different region of the country where the average price is higher. You may even investigate for how long cars are listed in the catalog and detect overpriced samples to make more informed decision." }, { "code": null, "e": 964, "s": 711, "text": "So there is a lot to think about, and the question I faced here was “Is it possible that using data science methods (collecting and cleaning the data, training ML models, etc.) can save your time and mental effort in a painful decision making process?”" }, { "code": null, "e": 1030, "s": 964, "text": "I opened a laptop, created a new project and turned the timer on." }, { "code": null, "e": 1349, "s": 1030, "text": "Without going into too much details: I’ve managed to collect a dataset containing roughly 40,000 car ads with 35 features (mostly categorical) in two days. Collecting the data itself wasn’t too much pain, but structuring it in an organized way took a bit of time. I’ve used Python, Requests, Pandas, NumPy, SciPy, etc." }, { "code": null, "e": 1533, "s": 1349, "text": "What is interesting about this particular dataset is that most of the categorical features are not encoded in any way and thus can be easily interpreted (like engine_fuel = “diesel”)." }, { "code": null, "e": 1783, "s": 1533, "text": "Initial data analysis quickly revealed suspicious samples with 8 million kilometers odometer state, 10 liter engine hatchbacks, hybrid diesel vehicles for $600, etc. I’ve spent roughly 6 hours writing scripts to detect these issues and process them." }, { "code": null, "e": 1893, "s": 1783, "text": "Visualizing the data (I’ve used MatPlotlib and Seaborn) gave me a good sense of the overall market situation." }, { "code": null, "e": 2417, "s": 1893, "text": "The majority of the cars are pretty heavily used with mean odometer_value of 250,000 kilometers, and that is a lot! I’ve also noticed that people prefer to assign nice numbers to odometer_value like 250,000 km, 300,000 km, 350,000 km, etc. A bunch of cars have one million kilometers odometer_value and it does not make much sense if you look at the values distribution. I may presume that 1 million kilometers is more like a statement “This car have seen a lot, the exact number of kilometers on it I honestly don’t know.”" }, { "code": null, "e": 2604, "s": 2417, "text": "The general trend behind car pricing is pretty intuitive: the older the car — the lower the price. I’ve expected the age of the car to be number one feature in overall feature hierarchy." }, { "code": null, "e": 2695, "s": 2604, "text": "Also, the older the car, the higher its odometer_value in general, and that is reasonable." }, { "code": null, "e": 2847, "s": 2695, "text": "To build price_usd scatter plot I’ve limited maximum car price for roughly $50,000 and removed several million-level kilometer odometer_value outliers." }, { "code": null, "e": 2978, "s": 2847, "text": "Actually cars that have price below $50,000 constitute 99.9 % of the catalog, so scatter plot gives a good sense of pricing trend." }, { "code": null, "e": 3242, "s": 2978, "text": "Regarding car age: most of the cars have been used for a while, with the mean year_produced value of 2002. I believe that the distribution of production year (depicted below) was heavily influenced by policies around customs duties for importing cars from abroad." }, { "code": null, "e": 3439, "s": 3242, "text": "Prices distribution (price_usd is going to be the target value in this project during model training) is highly skewed to the right with the mean and median price of $7,275 and $4,900 accordingly." }, { "code": null, "e": 3738, "s": 3439, "text": "Some features like up_counter (number of times the ad has been promoted manually) don’t reflect parameters of the car at all, but since this data has been available, I decided to include it into the project. The distribution was so skewed that the only way to properly plot it was to use log scale." }, { "code": null, "e": 3912, "s": 3738, "text": "The distribution of brands popularity wasn’t a surprise for me with the most popular model in the catalog being VW Passat, the legendary source of transportation in Belarus." }, { "code": null, "e": 4031, "s": 3912, "text": "I also used Tableau to get nicer visual representation of manufacturer’s marketshare and average price for each brand." }, { "code": null, "e": 4168, "s": 4031, "text": "The shape of distribution of number_of_photos that cars have is similar to price_usd distribution (distribution is skewed to the right)." }, { "code": null, "e": 4235, "s": 4168, "text": "Maybe the higher the price for a car, the higher number of photos?" }, { "code": null, "e": 4402, "s": 4235, "text": "I’ve made a joint plot, which shows a slight correlation, but more importantly, it clearly shows that the the majority of cars are cheap and have less than 15 photos." }, { "code": null, "e": 4579, "s": 4402, "text": "Some features like drivetrain were just interesting to explore. On the histogram below you can see how the percentage of rear-wheel drive cars decreased over the last 30 years." }, { "code": null, "e": 4838, "s": 4579, "text": "The whole correlation matrix for the dataset is depicted below (most of the features in the dataset are self-explanatory, except feature_0 ... feature_9: these are boolean columns which indicate that car has features like alloy wheels, air conditioner, etc.)" }, { "code": null, "e": 5122, "s": 4838, "text": "I’m not going to publish full exploratory analysis here, you can check it out in the kernel. I’ve spent approximately six hours (and I need 60 more hours to fix problematic samples in the dataset) digging into the data, engineering features and only then I moved into model training." }, { "code": null, "e": 5289, "s": 5122, "text": "Since I’ve already cleaned the dataset and applied some feature engineering with future machine learning in mind, building and training a baseline model was a breeze." }, { "code": null, "e": 5789, "s": 5289, "text": "To get maximum results with the least effort I’ve used CatBoost (gradient boosting on decision trees library with comprehensive categorical feature support developed and open sourced by Yandex). I’ve already spent too much time on the project, so I just threw the data into the model, tweaked the learning rate, tree depth and a number trees in the ensemble, trained several models and started exploring model decision making with SHAP (developed by Scott Lundberg et al). Total time spent: 4 hours." }, { "code": null, "e": 6257, "s": 5789, "text": "Fun fact: during initial prediction exploration phase I was disappointed in the performance of the model, started exploring the mistakes and found out that price column in my dataset had been parsed incorrectly, some prices had US dollars currency and some had the national currency of Belarus: BYN. I’ve fixed the code of the parser, gathered data again, then run cleaning, feature engineering and analytics jobs and started training models with much better results." }, { "code": null, "e": 6429, "s": 6257, "text": "To train and evaluate the first model I’ve filtered out cars with prices above $30,000 (during exploration phase I’ve discovered that these samples need a separate model)." }, { "code": null, "e": 6705, "s": 6429, "text": "I had no time and computational resources to run proper grid search and sequential feature selection (SFS) jobs, so I’ve just tweaked number of trees and learning rate several time and used 5-fold cross-validation to estimate the performance of the model (check full kernel)." }, { "code": null, "e": 6876, "s": 6705, "text": "The first decent CatBoost model got me to approximately $1,000 MAE (mean absolute error), which is 15 % of the mean value of price_usd target. To be exact on the scoring:" }, { "code": null, "e": 6946, "s": 6876, "text": "Best validation MAE score: $1019.18 on iteration 6413 with std $12.84" }, { "code": null, "e": 7140, "s": 6946, "text": "I’ve also used early_stopping parameter to skip further training when the validation score stops getting better. Without trying to improve the model in any way I moved into prediction analysis." }, { "code": null, "e": 7289, "s": 7140, "text": "Looking at the distribution of errors and 2d histograms plots for true and predicted values does not tell you much about the quality of predictions." }, { "code": null, "e": 7552, "s": 7289, "text": "The hierarchy of SHAP values (only top 20 features displayed) for features in the dataset didn’t seem surprising to me, apart from low position of odometer_value feature. You can find good explanation on non-parametric model interpretation in articles like this." }, { "code": null, "e": 7688, "s": 7552, "text": "Age of the car, brand, type of the body, engine capacity and drivetrain are at the top of the hierarchy and that seems very reasonable." }, { "code": null, "e": 7901, "s": 7688, "text": "State feature turned out to be an interesting one: the vast majority of cars are “owned”, but there is a small percentage of “new” cars (they are expensive) and a number of “emergency” vehicles which are damaged." }, { "code": null, "e": 8036, "s": 7901, "text": "The problem with damaged cars is obvious: the column is boolean and there is no degree of this “emergency state” (more on this later)." }, { "code": null, "e": 8225, "s": 8036, "text": "Exploring individual predictions quickly gave me a sense of both model and data limitations. I’ll shortlist some of the samples to give a better sense of a model’s decision making process." }, { "code": null, "e": 8429, "s": 8225, "text": "Sample 0: VW T5 Caravelle, 2009, mechanical gearbox, 287,000 km, diesel. Listed price is $13,600 . The prediction is lower by $1,200 (MAE for the model is about a $1,000, so that is rather typical case)." }, { "code": null, "e": 8563, "s": 8429, "text": "You can see that Volkswagen brand and minivan body_type make individual contributions to make the predicted price of a sample higher." }, { "code": null, "e": 8675, "s": 8563, "text": "Using SHAP we can plot decision making interpretation in even nicer way by using “decision plot” functionality." }, { "code": null, "e": 8790, "s": 8675, "text": "Decision plots were recently added to the library and provide even more detailed view of a model’s inner workings." }, { "code": null, "e": 8925, "s": 8790, "text": "The main benefit of decision plots in comparison to force plots is that they are able to showcase a larger number of features clearly." }, { "code": null, "e": 8974, "s": 8925, "text": "You can read more about this type of plots here." }, { "code": null, "e": 9133, "s": 8974, "text": "Sample 1: Mercedes-Benz E270, 2000, mechanical gearbox, 465,000 km, diesel. Listed price is $4,999 . The prediction is higher by $198. That is not bad at all!" }, { "code": null, "e": 9572, "s": 9133, "text": "Sample 2: Jeep Grand Cherokee, 2007, automatic gearbox, 166,000 km, diesel. Listed price is $14,500. The prediction is lower by $2,796. Poor prediction, at a first glance, but the model has been listed in the catalog for 498 days! Feels like the price for this particular sample had been set really too high. It is also listed in the poorest region of the country, where cars are cheaper in general and listed for a longer period of time." }, { "code": null, "e": 9697, "s": 9572, "text": "Sample 3: VW Passat, 2012, automatic gearbox, 102,000 km, gasoline. Listed price is $11,499. The prediction is lower by $64." }, { "code": null, "e": 9890, "s": 9697, "text": "Sample 4: VAZ 2107 (Russian car), 1987, mechanical gearbox, 120,000 km, gasoline. Listed price is $399. The prediction is higher by $34. That is the one from a lower end of the price spectrum." }, { "code": null, "e": 9995, "s": 9890, "text": "We can see how basically all feature values of this sample contribute negatively to the predicted price." }, { "code": null, "e": 10160, "s": 9995, "text": "Sample 5: VW Passat, 1992, mechanical gearbox, 398,000 km, gasoline. Listed price is $750. The prediction is higher by $721(almost two times the listed value)! Why?" }, { "code": null, "e": 10400, "s": 10160, "text": "If we look closer to the model interpretation we can see that state = emergency is an important contributor to the predicted price. Further manual investigation of this particular case revealed that a car has been damaged by a fallen tree." }, { "code": null, "e": 10719, "s": 10400, "text": "That is clearly a limitation of existing data: boolean state column simply can’t reflect the overall spectrum of levels of damage. I believe this issue can be fixed “easily” by applying two more mechanisms: image analysis with some kind of pre-trained deep CNN and entity extraction from sample description using RNNs." }, { "code": null, "e": 10780, "s": 10719, "text": "I will end this sample selection with a luxury BMW 3-series." }, { "code": null, "e": 10982, "s": 10780, "text": "Sample 6: BMW 316, 1994, mechanical gearbox, 320,000 km, gasoline. Listed price is $1,650. The prediction is higher by $55. We can clearly see that being a luxury brand gives some points to the sample." }, { "code": null, "e": 11078, "s": 10982, "text": "I’ve spent roughly 3 hours digging into model’s predictions and manually exploring the samples." }, { "code": null, "e": 11451, "s": 11078, "text": "I’ve got approximately $1,000 MAE using CatBoost Regressor on the whole dataset. But I’ve also tried to use the same approach for separate models and immediately halved the error to $500. I believe that the performance of the model will be even better if we divide the dataset in sub-datasets based on year_produced feature and train multiple models on these sub-datasets." }, { "code": null, "e": 11743, "s": 11451, "text": "I’ve been also thinking that duration_listed feature may be used to penalize sample weights in the dataset. For example, if the car is listed for a year that probably means that the price is set to be too high, so we can set the weight of this sample to be lower using pooling functionality." }, { "code": null, "e": 11864, "s": 11743, "text": "In general I feel like the model I’ve trained performs reasonably well, but there is a big room for further improvement." }, { "code": null, "e": 12308, "s": 11864, "text": "Regarding technologies used in this project: CatBoost seems to be exactly the right choice because it provides great out-of-the-box categorical feature support. Training with 5-fold cross validation took about 13 minutes on a 2019 MacBook pro, but if I had millions of samples in a dataset, that wouldn’t be an issue because CatBoost supports training on GPU. It also has very fast prediction time which helps when models move into production." }, { "code": null, "e": 12797, "s": 12308, "text": "The question I’ve tried to answer in this adventure is “Can using data science methods be justified if you are going to sell your own car?” The obvious answer for this is no: you would make a much better progress figuring out the price if you just manually search for similar vehicles online. It took me several days to complete the project in a simple way and there is so much more I could do to improve the performance of the model like apply proper feature selection, grid search, etc." }, { "code": null, "e": 13215, "s": 12797, "text": "At the same time, the answer is definitely yes if you have hundreds or thousands vehicles to sell. Using Python and rich ecosystem of data science packages you can automate jobs of gathering data, building analytics and training predictive models. You can also discover trends and forecast the future of the market. You can hide models behind some APIs so they can serve the business in a reliable and convenient way." }, { "code": null, "e": 13597, "s": 13215, "text": "And there is so much more. If you run business that imports used cars from abroad, you can train separate ML models to rank samples based on their profitability for the company. You can also forecast the duration these sample are going to be listed before the actual deal. You can even choose the right region for sale. The possibilities are unlimited if you just have enough data." }, { "code": null, "e": 13707, "s": 13597, "text": "But if you are just doing this kind of side projects for yourself you are going to have great fun like I did!" } ]
Diagonal Sum In Binary Tree | Practice | GeeksforGeeks
Consider Red lines of slope -1 passing between nodes (in following diagram). The diagonal sum in a binary tree is the sum of all node’s data lying between these lines. Given a Binary Tree of size N, print all diagonal sums. For the following input tree, output should be 9, 19, 42. 9 is sum of 1, 3 and 5. 19 is sum of 2, 6, 4 and 7. 42 is sum of 9, 10, 11 and 12. Example 1: Input: 4 / \ 1 3 / 3 Output: 7 4 Example 2: Input: 10 / \ 8 2 / \ / 3 5 2 Output: 12 15 3 Your Task: You don't need to take input. Just complete the function diagonalSum() that takes root node of the tree as parameter and returns an array containing the diagonal sums for every diagonal present in the tree with slope -1. Expected Time Complexity: O(N). Expected Auxiliary Space: O(N). Constraints: 1<=Number of nodes<=105 Note: The Input/Ouput format and Example given are used for system's internal purpose, and should be used by a user for Expected Output only. As it is a function problem, hence a user should not read any input from stdin/console. The task is to complete the function specified, and not to write the full code. +2 forcer2 months ago vector<int>v; if(!root) return {}; queue<Node*>q; q.push(root); while(!q.empty()) { int n=q.size(); int sum=0; for(int i=0;i<n;i++) { Node *t=q.front();q.pop(); while(t) { sum+=t->data; if(t->left) q.push(t->left); t=t->right; } } v.push_back(sum); } return v; 0 sufyankhan96782 months ago void help(vector<int>&v,Node* root,int start){ if(root==nullptr) return; int dt=root->data; if(v.size()+1==start) v.push_back(dt); else if(v.size()>=start) v[start-1]+=dt; if(root->left!=nullptr){ help(v,root->left,start+1); } if(root->right!=nullptr){ help(v,root->right,start); } } vector <int> diagonalSum(Node* root) { vector<int>v; help(v,root,1); return v; } 0 rahulroy123 months ago void di(Node *root, map<int,int,greater<int>>&mp, int l ){ if(!root)return; mp[l]+=root->data; di(root->left,mp,l-1); di(root->right,mp,l);}vector <int> diagonalSum(Node* root) { map<int,int,greater<int>>mp; vector<int>v; di(root,mp,0); for(auto it:mp){ v.push_back(it.second); } return v;} 0 abrajput15063 months ago void dSum(Node* root,int d,vector<int> &v){ if(!root) return; if(!root->left && !root->right){ v[d] += root->data; return; } //cout<<d<<" "<<root->data<<endl; v[d] += root->data; dSum(root->left,d+1,v); dSum(root->right,d,v); }int noOfDiagonal(Node* root,int d){ if(!root) return d; return max(noOfDiagonal(root->left,d+1),noOfDiagonal(root->right,d));}vector <int> diagonalSum(Node* root) { // Add your code here int n = noOfDiagonal(root,0); vector<int> v(n); for(int i=0;i<n;i++) v[i] =0; dSum(root,0,v); return v;} 0 shubhamvast53 months ago We can solve it by using 2 queue by following method public static ArrayList <Integer> diagonalSum(Node root) { ArrayList<Integer> list = new ArrayList<>(); if (root == null) return list; Queue<Node> q1 = new LinkedList<>(); Queue<Node> q2 = new LinkedList<>(); q1.offer(root); while (!q1.isEmpty()) { int sum = 0; while (!q1.isEmpty()) { Node n = q1.poll(); if(n.right != null) q1.offer(n.right); sum += n.data; q2.offer(n); } list.add(sum); while (!q2.isEmpty()) { Node n = q2.poll(); if (n.left != null) q1.offer(n.left); } } return list; } 0 aharshit3503 months ago JAVA :EASIEST LinkedList<Node>q=new LinkedList<>(); ArrayList<Integer>list=new ArrayList<>(); if(root==null)list.add(0); q.add(root); while(!q.isEmpty()){ ArrayList<Integer>small=new ArrayList<>(); int size=q.size(); int res=0; while(size-->0){ Node rn=q.removeFirst(); while(rn!=null){ small.add(rn.data); if(rn.left!=null)q.add(rn.left); rn=rn.right; } }for(int i=0;i<small.size();i++){ res+=small.get(i); }list.add(res); }return list; 0 17vineet This comment was deleted. 0 nekhatperveen3 months ago JAVA public static ArrayList <Integer> diagonalSum(Node root) { ArrayList<Integer> arrList = new ArrayList<>(); int level = 0; calculateSum(arrList, level, root); return arrList; } static void calculateSum(ArrayList<Integer> arrList, int level, Node root) { if(root==null) return; else { if(arrList.size()<level+1) { arrList.add(root.data); } else { int oldSum = arrList.get(level); arrList.set(level, oldSum+ root.data); } calculateSum(arrList, level, root.right); calculateSum(arrList, level + 1, root.left); } } +1 radheshyamnitj3 months ago queue<Node*>q; vector<int>ans; if(!root) return ans; q.push(root); q.push(NULL); int sum=0; while(!q.empty()){ if(q.front()==NULL) { ans.push_back(sum); sum=0; q.push(NULL); q.pop(); } Node *temp=q.front(); q.pop(); while(temp){ sum+=temp->data; if(temp->left) q.push(temp->left); temp=temp->right; } } +3 imsaiful6 months ago Soln of Problem: think like when we go to left it will start a new diagonal. Right side will continue for same diagonal and add them. 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": 462, "s": 238, "text": "Consider Red lines of slope -1 passing between nodes (in following diagram). The diagonal sum in a binary tree is the sum of all node’s data lying between these lines. Given a Binary Tree of size N, print all diagonal sums." }, { "code": null, "e": 603, "s": 462, "text": "For the following input tree, output should be 9, 19, 42.\n9 is sum of 1, 3 and 5.\n19 is sum of 2, 6, 4 and 7.\n42 is sum of 9, 10, 11 and 12." }, { "code": null, "e": 614, "s": 603, "text": "Example 1:" }, { "code": null, "e": 698, "s": 614, "text": "Input:\n 4\n / \\\n 1 3\n /\n 3\nOutput: 7 4 \n" }, { "code": null, "e": 709, "s": 698, "text": "Example 2:" }, { "code": null, "e": 812, "s": 709, "text": "Input:\n 10\n / \\\n 8 2\n / \\ /\n 3 5 2\nOutput: 12 15 3 \n" }, { "code": null, "e": 1044, "s": 812, "text": "Your Task:\nYou don't need to take input. Just complete the function diagonalSum() that takes root node of the tree as parameter and returns an array containing the diagonal sums for every diagonal present in the tree with slope -1." }, { "code": null, "e": 1108, "s": 1044, "text": "Expected Time Complexity: O(N).\nExpected Auxiliary Space: O(N)." }, { "code": null, "e": 1456, "s": 1108, "text": "Constraints:\n1<=Number of nodes<=105\n\nNote: The Input/Ouput format and Example given are used for system's internal purpose, and should be used by a user for Expected Output only. As it is a function problem, hence a user should not read any input from stdin/console. The task is to complete the function specified, and not to write the full code." }, { "code": null, "e": 1459, "s": 1456, "text": "+2" }, { "code": null, "e": 1478, "s": 1459, "text": "forcer2 months ago" }, { "code": null, "e": 1885, "s": 1478, "text": "vector<int>v; if(!root) return {}; queue<Node*>q; q.push(root); while(!q.empty()) { int n=q.size(); int sum=0; for(int i=0;i<n;i++) { Node *t=q.front();q.pop(); while(t) { sum+=t->data; if(t->left) q.push(t->left); t=t->right; } } v.push_back(sum); } return v;" }, { "code": null, "e": 1889, "s": 1887, "text": "0" }, { "code": null, "e": 1916, "s": 1889, "text": "sufyankhan96782 months ago" }, { "code": null, "e": 2356, "s": 1916, "text": "void help(vector<int>&v,Node* root,int start){\n \n if(root==nullptr) return;\n int dt=root->data;\n if(v.size()+1==start) v.push_back(dt);\n else if(v.size()>=start) v[start-1]+=dt;\n \n if(root->left!=nullptr){\n help(v,root->left,start+1);\n }\n if(root->right!=nullptr){\n help(v,root->right,start);\n }\n \n}\nvector <int> diagonalSum(Node* root) {\n vector<int>v;\n help(v,root,1);\n return v;\n}" }, { "code": null, "e": 2358, "s": 2356, "text": "0" }, { "code": null, "e": 2381, "s": 2358, "text": "rahulroy123 months ago" }, { "code": null, "e": 2707, "s": 2381, "text": "void di(Node *root, map<int,int,greater<int>>&mp, int l ){ if(!root)return; mp[l]+=root->data; di(root->left,mp,l-1); di(root->right,mp,l);}vector <int> diagonalSum(Node* root) { map<int,int,greater<int>>mp; vector<int>v; di(root,mp,0); for(auto it:mp){ v.push_back(it.second); } return v;}" }, { "code": null, "e": 2709, "s": 2707, "text": "0" }, { "code": null, "e": 2734, "s": 2709, "text": "abrajput15063 months ago" }, { "code": null, "e": 3316, "s": 2734, "text": "void dSum(Node* root,int d,vector<int> &v){ if(!root) return; if(!root->left && !root->right){ v[d] += root->data; return; } //cout<<d<<\" \"<<root->data<<endl; v[d] += root->data; dSum(root->left,d+1,v); dSum(root->right,d,v); }int noOfDiagonal(Node* root,int d){ if(!root) return d; return max(noOfDiagonal(root->left,d+1),noOfDiagonal(root->right,d));}vector <int> diagonalSum(Node* root) { // Add your code here int n = noOfDiagonal(root,0); vector<int> v(n); for(int i=0;i<n;i++) v[i] =0; dSum(root,0,v); return v;}" }, { "code": null, "e": 3318, "s": 3316, "text": "0" }, { "code": null, "e": 3343, "s": 3318, "text": "shubhamvast53 months ago" }, { "code": null, "e": 3396, "s": 3343, "text": "We can solve it by using 2 queue by following method" }, { "code": null, "e": 4186, "s": 3396, "text": " public static ArrayList <Integer> diagonalSum(Node root) \n {\n ArrayList<Integer> list = new ArrayList<>();\n if (root == null)\n return list;\n Queue<Node> q1 = new LinkedList<>();\n Queue<Node> q2 = new LinkedList<>();\n q1.offer(root);\n while (!q1.isEmpty())\n {\n int sum = 0;\n while (!q1.isEmpty())\n {\n Node n = q1.poll();\n if(n.right != null)\n q1.offer(n.right);\n sum += n.data;\n q2.offer(n);\n }\n list.add(sum);\n while (!q2.isEmpty())\n {\n Node n = q2.poll();\n if (n.left != null)\n q1.offer(n.left);\n }\n }\n return list;\n }" }, { "code": null, "e": 4188, "s": 4186, "text": "0" }, { "code": null, "e": 4212, "s": 4188, "text": "aharshit3503 months ago" }, { "code": null, "e": 4226, "s": 4212, "text": "JAVA :EASIEST" }, { "code": null, "e": 4860, "s": 4226, "text": " LinkedList<Node>q=new LinkedList<>(); ArrayList<Integer>list=new ArrayList<>(); if(root==null)list.add(0); q.add(root); while(!q.isEmpty()){ ArrayList<Integer>small=new ArrayList<>(); int size=q.size(); int res=0; while(size-->0){ Node rn=q.removeFirst(); while(rn!=null){ small.add(rn.data); if(rn.left!=null)q.add(rn.left); rn=rn.right; } }for(int i=0;i<small.size();i++){ res+=small.get(i); }list.add(res); }return list;" }, { "code": null, "e": 4862, "s": 4860, "text": "0" }, { "code": null, "e": 4871, "s": 4862, "text": "17vineet" }, { "code": null, "e": 4897, "s": 4871, "text": "This comment was deleted." }, { "code": null, "e": 4899, "s": 4897, "text": "0" }, { "code": null, "e": 4925, "s": 4899, "text": "nekhatperveen3 months ago" }, { "code": null, "e": 4930, "s": 4925, "text": "JAVA" }, { "code": null, "e": 5516, "s": 4930, "text": " public static ArrayList <Integer> diagonalSum(Node root) { ArrayList<Integer> arrList = new ArrayList<>(); int level = 0; calculateSum(arrList, level, root); return arrList; } static void calculateSum(ArrayList<Integer> arrList, int level, Node root) { if(root==null) return; else { if(arrList.size()<level+1) { arrList.add(root.data); } else { int oldSum = arrList.get(level); arrList.set(level, oldSum+ root.data); }" }, { "code": null, "e": 5636, "s": 5516, "text": " calculateSum(arrList, level, root.right); calculateSum(arrList, level + 1, root.left); } }" }, { "code": null, "e": 5639, "s": 5636, "text": "+1" }, { "code": null, "e": 5666, "s": 5639, "text": "radheshyamnitj3 months ago" }, { "code": null, "e": 6112, "s": 5666, "text": "queue<Node*>q;\n vector<int>ans;\n if(!root) return ans;\n q.push(root);\n q.push(NULL);\n int sum=0;\n \n while(!q.empty()){\n \n if(q.front()==NULL)\n {\n ans.push_back(sum);\n sum=0;\n q.push(NULL);\n q.pop();\n }\n \n Node *temp=q.front();\n q.pop();\n\n while(temp){\n sum+=temp->data;\n if(temp->left) q.push(temp->left);\n temp=temp->right;\n }\n }" }, { "code": null, "e": 6115, "s": 6112, "text": "+3" }, { "code": null, "e": 6136, "s": 6115, "text": "imsaiful6 months ago" }, { "code": null, "e": 6153, "s": 6136, "text": "Soln of Problem:" }, { "code": null, "e": 6214, "s": 6153, "text": "think like when we go to left it will start a new diagonal. " }, { "code": null, "e": 6272, "s": 6214, "text": "Right side will continue for same diagonal and add them. " }, { "code": null, "e": 6418, "s": 6272, "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": 6454, "s": 6418, "text": " Login to access your submissions. " }, { "code": null, "e": 6464, "s": 6454, "text": "\nProblem\n" }, { "code": null, "e": 6474, "s": 6464, "text": "\nContest\n" }, { "code": null, "e": 6537, "s": 6474, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 6685, "s": 6537, "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": 6893, "s": 6685, "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": 6999, "s": 6893, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Understand Local Receptive Fields In Convolutional Neural Networks | by Richmond Alake | Towards Data Science
Learn the basics of AI and Deep Learning with TensorFlow and Keras in this Live Training Session hosted by Me. This article is aimed at all levels of individuals that practice machine learning or more specifically deep learning. Convolutional Neural Networks (CNN) have characteristics that enable invariance to the affine transformations of images that are fed through the network. This provides the ability to recognize patterns that are shifted, tilted or slightly warped within images. These characteristics of affine invariance are introduced due to three main properties of the CNN architecture. Local Receptive FieldsShared WeightsSpatial Sub-sampling Local Receptive Fields Shared Weights Spatial Sub-sampling In this article, we’ll be exploring local receptive fields and understand their purpose and the advantages they serve within CNN architecture. Within a CNN architecture, there are compositions of several layers which have within them a set of units or neurons. These units receive inputs from corresponding units from a similar subsection in the previous layer. In the traditional fully connected feed-forward neural network, units/neuron within a layer receives input from all units of the prior layer. Ever wondered why aren’t all the neurons in a convolutional neural network connected? Well, it’s rather impractical to connect all units from the previous layer to units within the current layer. The computation resource to train such a network will be vast due to the increase in connections. Also, such a network will require a more extensive set of training data to utilize the full capacity of the network. But more importantly, each neuron within a CNN is responsible for a defined region of the input data, and this enables neurons to learn patterns such as lines, edges and small details that make up the image. This defined region of space that a neuron or unit is exposed to in the input data is called the Local Receptive Field. Receptive fields are defined portion of space or spatial construct containing units that provide input to a set of units within a corresponding layer. The receptive field is defined by the filter size of a layer within a convolution neural network. The receptive field is also an indication of the extent of the scope of input data a neuron or unit within a layer can be exposed to (see image below). The image below illustrates an input data(red) with an input volume of 32x32x3. The input volume essentially tells us that the images within the input data have the dimensions 32x32 (height/width), along three colour channels: Red, Green, and Blue. The second object in the image(blue) represents a convolutional layer. The conv layer has a filter size of 5x5, which corresponds to the area of the local receptive field of each neuron in the layer has on the input data. The receptive field does not only act on the area of the input volume, but it’s also imposed on the depth, which in this case is 3. We can derive the number of trainable parameters that each neuron has based on the input volume for the example in the image below. This is the receptive field multiplied by the depth of the input volume (5x5x3 = 75 trainable parameters). Supposedly we have an input volume of (32,32,3), and the receptive field of a convolutional layer is 5x5 then each neuron in the convolutional layer will have weights 5x5x3 region, which is 75 weights within the neurons. The output of convolutional layers are feature maps, the number of feature maps within a layer is a defined hyperparameter, and it’s possible to derive the number of connections within a feature map by multiplying the feature map dimensions by the number of trainable parameters. The local receptive field is a defined segmented area that is occupied by the content of input data that a neuron within a convolutional layer is exposed to during the process of convolution. The LeNet paper introduced the first use case of the utilization of the convolutional neural network for character recognition. It also introduced the idea and implementation of local receptive fields within CNN. But the idea of local receptive fields or rather subsequent units only exposed to a segment of input data — local connections, was introduced as early as the 1960s within a study that explored the visual cortex of a cat. Advantages of local receptive fields in recognizing visual patterns lie in the fact that the units or neurons within a layer are directly tasked with learning visual features from a small region of the input data — this isn’t the case in fully connected neural networks, where a unit receives input from units within the previous layer. In the lower layers within a CNN, the units/neurons learn low-level features within the image such as lines, edges, contours etc. The higher layers learn more abstract features of the image such as shapes, since the region of the image a unit within a higher layer is exposed to is larger as a result of the accumulated receptive fields of previous lower layers. To conclude below is a snippet of code that shows how a convolutional layer is defined using the TensorFlow deep learning python library. The Conv2D class constructor takes in argument ‘filter’ which corresponds to the number of output produced by the filter, which is also the number of feature maps. The argument ‘kernel_size’ takes an integer that represents the height and width dimensions of the kernel/filter; in this case, the integer 5 corresponds to the dimensions 5x5. simple_conv_layer = tf.keras.layers.Conv2D(filters=6, kernel_size=5, activation='relu', input_shape=(28,28,1)) To connect with me or find more content similar to this article, do the following: Subscribe to my YouTube channel for video contents coming soon hereFollow me on MediumConnect and reach me on LinkedIn Subscribe to my YouTube channel for video contents coming soon here Follow me on Medium Connect and reach me on LinkedIn
[ { "code": null, "e": 283, "s": 172, "text": "Learn the basics of AI and Deep Learning with TensorFlow and Keras in this Live Training Session hosted by Me." }, { "code": null, "e": 401, "s": 283, "text": "This article is aimed at all levels of individuals that practice machine learning or more specifically deep learning." }, { "code": null, "e": 662, "s": 401, "text": "Convolutional Neural Networks (CNN) have characteristics that enable invariance to the affine transformations of images that are fed through the network. This provides the ability to recognize patterns that are shifted, tilted or slightly warped within images." }, { "code": null, "e": 774, "s": 662, "text": "These characteristics of affine invariance are introduced due to three main properties of the CNN architecture." }, { "code": null, "e": 831, "s": 774, "text": "Local Receptive FieldsShared WeightsSpatial Sub-sampling" }, { "code": null, "e": 854, "s": 831, "text": "Local Receptive Fields" }, { "code": null, "e": 869, "s": 854, "text": "Shared Weights" }, { "code": null, "e": 890, "s": 869, "text": "Spatial Sub-sampling" }, { "code": null, "e": 1033, "s": 890, "text": "In this article, we’ll be exploring local receptive fields and understand their purpose and the advantages they serve within CNN architecture." }, { "code": null, "e": 1151, "s": 1033, "text": "Within a CNN architecture, there are compositions of several layers which have within them a set of units or neurons." }, { "code": null, "e": 1394, "s": 1151, "text": "These units receive inputs from corresponding units from a similar subsection in the previous layer. In the traditional fully connected feed-forward neural network, units/neuron within a layer receives input from all units of the prior layer." }, { "code": null, "e": 1480, "s": 1394, "text": "Ever wondered why aren’t all the neurons in a convolutional neural network connected?" }, { "code": null, "e": 1805, "s": 1480, "text": "Well, it’s rather impractical to connect all units from the previous layer to units within the current layer. The computation resource to train such a network will be vast due to the increase in connections. Also, such a network will require a more extensive set of training data to utilize the full capacity of the network." }, { "code": null, "e": 2013, "s": 1805, "text": "But more importantly, each neuron within a CNN is responsible for a defined region of the input data, and this enables neurons to learn patterns such as lines, edges and small details that make up the image." }, { "code": null, "e": 2133, "s": 2013, "text": "This defined region of space that a neuron or unit is exposed to in the input data is called the Local Receptive Field." }, { "code": null, "e": 2284, "s": 2133, "text": "Receptive fields are defined portion of space or spatial construct containing units that provide input to a set of units within a corresponding layer." }, { "code": null, "e": 2534, "s": 2284, "text": "The receptive field is defined by the filter size of a layer within a convolution neural network. The receptive field is also an indication of the extent of the scope of input data a neuron or unit within a layer can be exposed to (see image below)." }, { "code": null, "e": 2614, "s": 2534, "text": "The image below illustrates an input data(red) with an input volume of 32x32x3." }, { "code": null, "e": 2783, "s": 2614, "text": "The input volume essentially tells us that the images within the input data have the dimensions 32x32 (height/width), along three colour channels: Red, Green, and Blue." }, { "code": null, "e": 3005, "s": 2783, "text": "The second object in the image(blue) represents a convolutional layer. The conv layer has a filter size of 5x5, which corresponds to the area of the local receptive field of each neuron in the layer has on the input data." }, { "code": null, "e": 3137, "s": 3005, "text": "The receptive field does not only act on the area of the input volume, but it’s also imposed on the depth, which in this case is 3." }, { "code": null, "e": 3376, "s": 3137, "text": "We can derive the number of trainable parameters that each neuron has based on the input volume for the example in the image below. This is the receptive field multiplied by the depth of the input volume (5x5x3 = 75 trainable parameters)." }, { "code": null, "e": 3597, "s": 3376, "text": "Supposedly we have an input volume of (32,32,3), and the receptive field of a convolutional layer is 5x5 then each neuron in the convolutional layer will have weights 5x5x3 region, which is 75 weights within the neurons." }, { "code": null, "e": 3877, "s": 3597, "text": "The output of convolutional layers are feature maps, the number of feature maps within a layer is a defined hyperparameter, and it’s possible to derive the number of connections within a feature map by multiplying the feature map dimensions by the number of trainable parameters." }, { "code": null, "e": 4069, "s": 3877, "text": "The local receptive field is a defined segmented area that is occupied by the content of input data that a neuron within a convolutional layer is exposed to during the process of convolution." }, { "code": null, "e": 4282, "s": 4069, "text": "The LeNet paper introduced the first use case of the utilization of the convolutional neural network for character recognition. It also introduced the idea and implementation of local receptive fields within CNN." }, { "code": null, "e": 4503, "s": 4282, "text": "But the idea of local receptive fields or rather subsequent units only exposed to a segment of input data — local connections, was introduced as early as the 1960s within a study that explored the visual cortex of a cat." }, { "code": null, "e": 4840, "s": 4503, "text": "Advantages of local receptive fields in recognizing visual patterns lie in the fact that the units or neurons within a layer are directly tasked with learning visual features from a small region of the input data — this isn’t the case in fully connected neural networks, where a unit receives input from units within the previous layer." }, { "code": null, "e": 5203, "s": 4840, "text": "In the lower layers within a CNN, the units/neurons learn low-level features within the image such as lines, edges, contours etc. The higher layers learn more abstract features of the image such as shapes, since the region of the image a unit within a higher layer is exposed to is larger as a result of the accumulated receptive fields of previous lower layers." }, { "code": null, "e": 5341, "s": 5203, "text": "To conclude below is a snippet of code that shows how a convolutional layer is defined using the TensorFlow deep learning python library." }, { "code": null, "e": 5682, "s": 5341, "text": "The Conv2D class constructor takes in argument ‘filter’ which corresponds to the number of output produced by the filter, which is also the number of feature maps. The argument ‘kernel_size’ takes an integer that represents the height and width dimensions of the kernel/filter; in this case, the integer 5 corresponds to the dimensions 5x5." }, { "code": null, "e": 5793, "s": 5682, "text": "simple_conv_layer = tf.keras.layers.Conv2D(filters=6, kernel_size=5, activation='relu', input_shape=(28,28,1))" }, { "code": null, "e": 5876, "s": 5793, "text": "To connect with me or find more content similar to this article, do the following:" }, { "code": null, "e": 5995, "s": 5876, "text": "Subscribe to my YouTube channel for video contents coming soon hereFollow me on MediumConnect and reach me on LinkedIn" }, { "code": null, "e": 6063, "s": 5995, "text": "Subscribe to my YouTube channel for video contents coming soon here" }, { "code": null, "e": 6083, "s": 6063, "text": "Follow me on Medium" } ]
Using Azure Log Analytics Workspaces to collect Custom Logs from your VM | by Sulabh Shrestha | Towards Data Science
We all have seen the Monitoring Tab Key Metrics on the VM Page. Yes, it is useful to see whether the CPU has been running or not through the CPU metrics, to check when the VM is getting the data from the outside world through Network In metrics and if the VM is doing any kind of write operation using Disk Operations/Sec metrics but it’s not effective for the custom services that we build on VM. So, in this blog, I will be giving you an example of how to create your own log based on customer service, bring it to Azure Log Analytics Workspace using its default agent, and query it according to our needs, even better create an alert on it. An Azure AccountAzure Virtual Machine ServiceAzure Log Analytics Workspace ServiceAzure Alert Service An Azure Account Azure Virtual Machine Service Azure Log Analytics Workspace Service Azure Alert Service Let’s start with the VM itself. You already have the service running on the VM but don't know how to get those logs into the portal or even create a log for your services. So, let’s assume that you have not created the logs for your services. So for this blog, I will be taking a simple flask app as my example for the service. To get it up and running we must download the flask library from pip and then create a flask app similar to this below: Nothing much, just a simple flask app running on default port 5000. Let’s run it by this command below: python app.py The service must be running. Now that’s done let’s move to the log part. The trick that we are going to use all depends on the grep. As the grep command will help us find the running service, we will leverage it to know whether the app service is working or not. So, I create this bash script to know if the app service is running or not. If it is running I would give it a 200 success code and if it’s not then 500 error code shall it get. Pretty neat and easy until here. Now try to run the script and it will show 200 or 500 according to your service status. But we cannot do this manually forever. So for the automation, I used crontab to run the script for me every minute. Open your crontab by ‘crontab -e’ and then enter this command To explain it, the first part deals with where your bash script lies and the second part deals with where you want to place the generated log files. I suggest you create the file and folder and give appropriate permissions ‘chmod’ before placing it in on the crontab. Now let’s wait for 5 minutes and check whether the logs are written or not. Seems like it’s working as expected as I had closed my service before running it on the crontab. Copy 5 of those messages and save them on a new file and we will need to submit a sample of it to the Log Analytics Workspace. Now, let’s move onto the Azure portal. Go to your VM and then select ‘Logs’ and click on the ‘Enable’ button. You will be prompted to create a new workspace. The workspace takes 5–10 minutes so be patient. After the workspace has been created go to the Insights tab What we are doing right now is installing the Azure Log Analytics Workspace with some click of our button. We can also create using the CLI but I would prefer the portal way. If and only if the portal doesn’t work then I would go for the CLI way. Now let’s configure our machine to take the custom logs. Go to the Logs Analytics Workspace that you created and click on ‘Advanced Settings’ which will prompt you to a new page. Click on ‘Data’ and ‘Custom Logs’. There you will see an ‘Add +’ button. Click on it and you will be prompted with a new tab. Upload that sample log that you saved above and click ‘Next’. you will see the option for ‘new line’ and ‘timestamp’. Select ‘new line’ and click on ‘Next’ Give the path that you have on the crontab and hit ‘Next’ Give appropriate Name as we will be using this name for our query if needed. Don’t forget to select the ‘Apply below configuration to my Linux machines’. Now let’s see whether the logs arrived or not. Azure documentation says that it may take 1 hour for the logs to arrive but in my case, it arrived in like 20 minutes. So please follow the steps well and wait for the logs to arrive. Now, click on the ‘Logs’ and you will be prompted with a window to enter some SQL-like commands. It’s actually Kusto Query Language which is similar to SQL so we can use it using the references that Azure has provided. I will also link the guide in the Resources section below. As you can see that it worked. Congratulation if you have made it this far cause you have done a pretty good job bringing your custom logs into the Azure Portal. Now you can play with it, query it, analyze it, and much more. In this next section, I am going to create an alert based on the custom logs. So far we brought the custom logs to the Azure portal, which is a pretty big job already, but still, we want to do more. So, let’s create an alert based on the Custom Logs. As you have already realized that the custom logs are messy so what we are going to do is clean it first using Kusto Query Language (KQL). What we have done here is just extracted the status code out of our custom logs. Pretty neat should I say. Now, what we are going to do is create an alert based on the status code. If the service doesn’t run we will get a 500 error code, so we are going to create an alert if the service is not working using the 500 error code. Click on the ‘New alert rule’ which will prompt you to a new page. Enter the selection that I have made. We are using the Aggregation type as Maximum because there is only two status code for us and the alert logic is descriptive itself. Click on Next and ‘Create action group’ to enter your phone number or your email. After creating the Action group go back and you will see your newly created action group. Give your alert name and ‘Review + Create’. Now let’s wait for 5 minutes and see whether an email will pop up or not. Yayy, the alert got triggered and we got an email. Congratulation if you have made it this far because this was not an easy task. We created a service, generated a log out of it every minute, brought it to the Azure portal, and created an alert based on it. This same logic can be applied for GPU metrics if you want to create a log of your GPU to know its status while training a model for a machine learning task. It can also be applied to different web services to know their status and much more. The possibilities are endless, the choices are endless and it’s up to you for what you want to make it. If you encounter any problems or have difficulty following the steps, comment below on this post or message me at tsulabh4@gmail.com. You can also connect with me on Linkedin and GitHub. Resources: [1]: KQL-1: https://docs.microsoft.com/en-us/azure/data-explorer/kusto/query/extractfunction [2] KQL-2: https://docs.microsoft.com/en-us/azure/data-explorer/kusto/query/re2 [3] KQL-3: https://docs.microsoft.com/en-us/azure/data-explorer/kusto/query/samples?pivots=azuredataexplorer [4] KQL-4: https://docs.microsoft.com/en-us/azure/data-explorer/kusto/query/sqlcheatsheet [5] Azure Log Analytics Workspace: https://docs.microsoft.com/en-us/azure/azure-monitor/agents/data-sources-custom-logs
[ { "code": null, "e": 816, "s": 172, "text": "We all have seen the Monitoring Tab Key Metrics on the VM Page. Yes, it is useful to see whether the CPU has been running or not through the CPU metrics, to check when the VM is getting the data from the outside world through Network In metrics and if the VM is doing any kind of write operation using Disk Operations/Sec metrics but it’s not effective for the custom services that we build on VM. So, in this blog, I will be giving you an example of how to create your own log based on customer service, bring it to Azure Log Analytics Workspace using its default agent, and query it according to our needs, even better create an alert on it." }, { "code": null, "e": 918, "s": 816, "text": "An Azure AccountAzure Virtual Machine ServiceAzure Log Analytics Workspace ServiceAzure Alert Service" }, { "code": null, "e": 935, "s": 918, "text": "An Azure Account" }, { "code": null, "e": 965, "s": 935, "text": "Azure Virtual Machine Service" }, { "code": null, "e": 1003, "s": 965, "text": "Azure Log Analytics Workspace Service" }, { "code": null, "e": 1023, "s": 1003, "text": "Azure Alert Service" }, { "code": null, "e": 1471, "s": 1023, "text": "Let’s start with the VM itself. You already have the service running on the VM but don't know how to get those logs into the portal or even create a log for your services. So, let’s assume that you have not created the logs for your services. So for this blog, I will be taking a simple flask app as my example for the service. To get it up and running we must download the flask library from pip and then create a flask app similar to this below:" }, { "code": null, "e": 1575, "s": 1471, "text": "Nothing much, just a simple flask app running on default port 5000. Let’s run it by this command below:" }, { "code": null, "e": 1589, "s": 1575, "text": "python app.py" }, { "code": null, "e": 2030, "s": 1589, "text": "The service must be running. Now that’s done let’s move to the log part. The trick that we are going to use all depends on the grep. As the grep command will help us find the running service, we will leverage it to know whether the app service is working or not. So, I create this bash script to know if the app service is running or not. If it is running I would give it a 200 success code and if it’s not then 500 error code shall it get." }, { "code": null, "e": 2330, "s": 2030, "text": "Pretty neat and easy until here. Now try to run the script and it will show 200 or 500 according to your service status. But we cannot do this manually forever. So for the automation, I used crontab to run the script for me every minute. Open your crontab by ‘crontab -e’ and then enter this command" }, { "code": null, "e": 2674, "s": 2330, "text": "To explain it, the first part deals with where your bash script lies and the second part deals with where you want to place the generated log files. I suggest you create the file and folder and give appropriate permissions ‘chmod’ before placing it in on the crontab. Now let’s wait for 5 minutes and check whether the logs are written or not." }, { "code": null, "e": 2937, "s": 2674, "text": "Seems like it’s working as expected as I had closed my service before running it on the crontab. Copy 5 of those messages and save them on a new file and we will need to submit a sample of it to the Log Analytics Workspace. Now, let’s move onto the Azure portal." }, { "code": null, "e": 3056, "s": 2937, "text": "Go to your VM and then select ‘Logs’ and click on the ‘Enable’ button. You will be prompted to create a new workspace." }, { "code": null, "e": 3164, "s": 3056, "text": "The workspace takes 5–10 minutes so be patient. After the workspace has been created go to the Insights tab" }, { "code": null, "e": 3590, "s": 3164, "text": "What we are doing right now is installing the Azure Log Analytics Workspace with some click of our button. We can also create using the CLI but I would prefer the portal way. If and only if the portal doesn’t work then I would go for the CLI way. Now let’s configure our machine to take the custom logs. Go to the Logs Analytics Workspace that you created and click on ‘Advanced Settings’ which will prompt you to a new page." }, { "code": null, "e": 3716, "s": 3590, "text": "Click on ‘Data’ and ‘Custom Logs’. There you will see an ‘Add +’ button. Click on it and you will be prompted with a new tab." }, { "code": null, "e": 3872, "s": 3716, "text": "Upload that sample log that you saved above and click ‘Next’. you will see the option for ‘new line’ and ‘timestamp’. Select ‘new line’ and click on ‘Next’" }, { "code": null, "e": 3930, "s": 3872, "text": "Give the path that you have on the crontab and hit ‘Next’" }, { "code": null, "e": 4007, "s": 3930, "text": "Give appropriate Name as we will be using this name for our query if needed." }, { "code": null, "e": 4593, "s": 4007, "text": "Don’t forget to select the ‘Apply below configuration to my Linux machines’. Now let’s see whether the logs arrived or not. Azure documentation says that it may take 1 hour for the logs to arrive but in my case, it arrived in like 20 minutes. So please follow the steps well and wait for the logs to arrive. Now, click on the ‘Logs’ and you will be prompted with a window to enter some SQL-like commands. It’s actually Kusto Query Language which is similar to SQL so we can use it using the references that Azure has provided. I will also link the guide in the Resources section below." }, { "code": null, "e": 4896, "s": 4593, "text": "As you can see that it worked. Congratulation if you have made it this far cause you have done a pretty good job bringing your custom logs into the Azure Portal. Now you can play with it, query it, analyze it, and much more. In this next section, I am going to create an alert based on the custom logs." }, { "code": null, "e": 5208, "s": 4896, "text": "So far we brought the custom logs to the Azure portal, which is a pretty big job already, but still, we want to do more. So, let’s create an alert based on the Custom Logs. As you have already realized that the custom logs are messy so what we are going to do is clean it first using Kusto Query Language (KQL)." }, { "code": null, "e": 5604, "s": 5208, "text": "What we have done here is just extracted the status code out of our custom logs. Pretty neat should I say. Now, what we are going to do is create an alert based on the status code. If the service doesn’t run we will get a 500 error code, so we are going to create an alert if the service is not working using the 500 error code. Click on the ‘New alert rule’ which will prompt you to a new page." }, { "code": null, "e": 5857, "s": 5604, "text": "Enter the selection that I have made. We are using the Aggregation type as Maximum because there is only two status code for us and the alert logic is descriptive itself. Click on Next and ‘Create action group’ to enter your phone number or your email." }, { "code": null, "e": 6065, "s": 5857, "text": "After creating the Action group go back and you will see your newly created action group. Give your alert name and ‘Review + Create’. Now let’s wait for 5 minutes and see whether an email will pop up or not." }, { "code": null, "e": 6195, "s": 6065, "text": "Yayy, the alert got triggered and we got an email. Congratulation if you have made it this far because this was not an easy task." }, { "code": null, "e": 6857, "s": 6195, "text": "We created a service, generated a log out of it every minute, brought it to the Azure portal, and created an alert based on it. This same logic can be applied for GPU metrics if you want to create a log of your GPU to know its status while training a model for a machine learning task. It can also be applied to different web services to know their status and much more. The possibilities are endless, the choices are endless and it’s up to you for what you want to make it. If you encounter any problems or have difficulty following the steps, comment below on this post or message me at tsulabh4@gmail.com. You can also connect with me on Linkedin and GitHub." }, { "code": null, "e": 6868, "s": 6857, "text": "Resources:" }, { "code": null, "e": 6961, "s": 6868, "text": "[1]: KQL-1: https://docs.microsoft.com/en-us/azure/data-explorer/kusto/query/extractfunction" }, { "code": null, "e": 7041, "s": 6961, "text": "[2] KQL-2: https://docs.microsoft.com/en-us/azure/data-explorer/kusto/query/re2" }, { "code": null, "e": 7150, "s": 7041, "text": "[3] KQL-3: https://docs.microsoft.com/en-us/azure/data-explorer/kusto/query/samples?pivots=azuredataexplorer" }, { "code": null, "e": 7240, "s": 7150, "text": "[4] KQL-4: https://docs.microsoft.com/en-us/azure/data-explorer/kusto/query/sqlcheatsheet" } ]
Program to check whether two sentences are similar or not in Python
Suppose we have two sentences s and t. We have to check whether they are similar or not. Here sentence has only English letters. Two sentences are said to be similar when it is possible to add an arbitrary sentence (possibly empty) inside one of these given sentences such that the two sentences become equal. So, if the input is like s = "we live at city Kolkata" t = "city Kolkata", then the output will be True because we can get s from t by adding sentence "we live in". To solve this, we will follow these steps − s1 := a list of words in s s1 := a list of words in s s2 := a list of words in t s2 := a list of words in t if size of s1 > size of s2, thenswap s1 and s2 if size of s1 > size of s2, then swap s1 and s2 swap s1 and s2 while s1 is not empty, doif s2[0] is same as s1[0], thendelete first word from s2delete first word from s1otherwise when last word of s2 is same as last word of s1, thendelete last word from s2delete last word from s1otherwise,return false while s1 is not empty, do if s2[0] is same as s1[0], thendelete first word from s2delete first word from s1 if s2[0] is same as s1[0], then delete first word from s2 delete first word from s2 delete first word from s1 delete first word from s1 otherwise when last word of s2 is same as last word of s1, thendelete last word from s2delete last word from s1 otherwise when last word of s2 is same as last word of s1, then delete last word from s2 delete last word from s2 delete last word from s1 delete last word from s1 otherwise,return false otherwise, return false return false return true return true Let us see the following implementation to get better understanding − def solve(s, t): s1 = s.split() s2 = t.split() if len(s1) > len(s2): s1,s2 = s2,s1 while(s1): if(s2[0]==s1[0]): s2.pop(0) s1.pop(0) elif(s2[-1]==s1[-1]): s2.pop() s1.pop() else: return(False) return(True) s = "we live at city Kolkata" t = "city Kolkata" print(solve(s, t)) "we live at city Kolkata", "city Kolkata" True
[ { "code": null, "e": 1372, "s": 1062, "text": "Suppose we have two sentences s and t. We have to check whether they are similar or not. Here sentence has only English letters. Two sentences are said to be similar when it is possible to add an arbitrary sentence (possibly empty) inside one of these given sentences such that the two sentences become equal." }, { "code": null, "e": 1537, "s": 1372, "text": "So, if the input is like s = \"we live at city Kolkata\" t = \"city Kolkata\", then the output will be True because we can get s from t by adding sentence \"we live in\"." }, { "code": null, "e": 1581, "s": 1537, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1608, "s": 1581, "text": "s1 := a list of words in s" }, { "code": null, "e": 1635, "s": 1608, "text": "s1 := a list of words in s" }, { "code": null, "e": 1662, "s": 1635, "text": "s2 := a list of words in t" }, { "code": null, "e": 1689, "s": 1662, "text": "s2 := a list of words in t" }, { "code": null, "e": 1736, "s": 1689, "text": "if size of s1 > size of s2, thenswap s1 and s2" }, { "code": null, "e": 1769, "s": 1736, "text": "if size of s1 > size of s2, then" }, { "code": null, "e": 1784, "s": 1769, "text": "swap s1 and s2" }, { "code": null, "e": 1799, "s": 1784, "text": "swap s1 and s2" }, { "code": null, "e": 2039, "s": 1799, "text": "while s1 is not empty, doif s2[0] is same as s1[0], thendelete first word from s2delete first word from s1otherwise when last word of s2 is same as last word of s1, thendelete last word from s2delete last word from s1otherwise,return false" }, { "code": null, "e": 2065, "s": 2039, "text": "while s1 is not empty, do" }, { "code": null, "e": 2147, "s": 2065, "text": "if s2[0] is same as s1[0], thendelete first word from s2delete first word from s1" }, { "code": null, "e": 2179, "s": 2147, "text": "if s2[0] is same as s1[0], then" }, { "code": null, "e": 2205, "s": 2179, "text": "delete first word from s2" }, { "code": null, "e": 2231, "s": 2205, "text": "delete first word from s2" }, { "code": null, "e": 2257, "s": 2231, "text": "delete first word from s1" }, { "code": null, "e": 2283, "s": 2257, "text": "delete first word from s1" }, { "code": null, "e": 2395, "s": 2283, "text": "otherwise when last word of s2 is same as last word of s1, thendelete last word from s2delete last word from s1" }, { "code": null, "e": 2459, "s": 2395, "text": "otherwise when last word of s2 is same as last word of s1, then" }, { "code": null, "e": 2484, "s": 2459, "text": "delete last word from s2" }, { "code": null, "e": 2509, "s": 2484, "text": "delete last word from s2" }, { "code": null, "e": 2534, "s": 2509, "text": "delete last word from s1" }, { "code": null, "e": 2559, "s": 2534, "text": "delete last word from s1" }, { "code": null, "e": 2582, "s": 2559, "text": "otherwise,return false" }, { "code": null, "e": 2593, "s": 2582, "text": "otherwise," }, { "code": null, "e": 2606, "s": 2593, "text": "return false" }, { "code": null, "e": 2619, "s": 2606, "text": "return false" }, { "code": null, "e": 2631, "s": 2619, "text": "return true" }, { "code": null, "e": 2643, "s": 2631, "text": "return true" }, { "code": null, "e": 2713, "s": 2643, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 3071, "s": 2713, "text": "def solve(s, t):\n s1 = s.split()\n s2 = t.split()\n if len(s1) > len(s2):\n s1,s2 = s2,s1\n while(s1):\n if(s2[0]==s1[0]):\n s2.pop(0)\n s1.pop(0)\n elif(s2[-1]==s1[-1]):\n s2.pop()\n s1.pop()\n else:\n return(False)\n return(True)\n\ns = \"we live at city Kolkata\"\nt = \"city Kolkata\"\nprint(solve(s, t))" }, { "code": null, "e": 3114, "s": 3071, "text": "\"we live at city Kolkata\", \"city Kolkata\"\n" }, { "code": null, "e": 3119, "s": 3114, "text": "True" } ]
Explain narrowing with object in Java.
Java provides various datatypes to store various data values. It provides 7 primitive datatypes (stores single values) namely, boolean, byte, char, short, int, long, float, double and, reference datatypes (arrays and objects). Type Casting/type conversion −Converting one primitive datatype into another is known as type casting (type conversion) in Java. You can cast the primitive datatypes in two ways namely, Widening and, Narrowing. Narrowing − Converting a higher datatype to a lower datatype is known as narrowing. In this case the casting/conversion is not done automatically, you need to convert explicitly using the cast operator “( )” explicitly. Therefore, it is known as explicit type casting. In this case both datatypes need not be compatible with each other. import java.util.Scanner; public class NarrowingExample { public static void main(String args[]){ Scanner sc = new Scanner(System.in); System.out.println("Enter an integer value: "); int i = sc.nextInt(); char ch = (char) i; System.out.println("Character value of the given integer: "+ch); } } Enter an integer value: 67 Character value of the given integer: C you can cast the reference(object) of one (class) type to other. But, one of the two classes should inherit the other. Therefore, if a class inherits the properties of the other conversion of super class object in to sub class type is considered as, narrowing with respect to objects. But unlike widening in case narrowing you need to use the cast operator. In the following Java example, we have two classes namely Person and Student. The Person class has two instance variables name and age and one instance method displayPerson() which displays the name and age. The Student extends the person class and in addition to the inherited name and age it has two more variables branch and student_id. It has a method displayData() which displays all four values. In the main method, we have created the objects of the both classes separately and we are trying to convert the sub class object into the super class type. class Person{ private String name; private int age; public Person(String name, int age){ this.name = name; this.age = age; } public void displayPerson() { System.out.println("Data of the Person class: "); System.out.println("Name: "+this.name); System.out.println("Age: "+this.age); } } public class Student extends Person { public String branch; public int Student_id; public Student(String name, int age, String branch, int Student_id){ super(name, age); this.branch = branch; this.Student_id = Student_id; } public void displayStudent() { System.out.println("Data of the Student class: "); System.out.println("Name: "+this.name); System.out.println("Age: "+this.age); System.out.println("Branch: "+this.branch); System.out.println("Student ID: "+this.Student_id); } public static void main(String[] args) { //Creating an object of the Student class Student student = new Student("Krishna", 20, "IT", 1256); //Converting the object of Student to Person Person person = new Person("Krishna", 20); //Converting the object of person to student student = (Student) person; student.displayPerson(); student.displayStudent(); } } To this reference, members of both classes are available and the program gets compiled successfully. But, when you try to execute it, an exception will be raised as shown below − Exception in thread "main" java.lang.ClassCastException: ther.Person cannot be cast to ther.Student at ther.Student.main(Student.java:41) To resolve this issue, first of all you need to create the super class reference using the sub class object and then, convert this (super) reference type to sub class type using the cast operator. public static void main(String[] args) { //Converting the object of Student to Person Person person = new Student("Krishna", 20, "IT", 1256); //Converting the object of person to student Student student = (Student) person; student.displayPerson(); student.displayStudent(); } Data of the Person class: Name: Krishna Age: 20 Data of the Student class: Name: Krishna Age: 20 Branch: IT Student ID: 1256
[ { "code": null, "e": 1289, "s": 1062, "text": "Java provides various datatypes to store various data values. It provides 7 primitive datatypes (stores single values) namely, boolean, byte, char, short, int, long, float, double and, reference datatypes (arrays and objects)." }, { "code": null, "e": 1500, "s": 1289, "text": "Type Casting/type conversion −Converting one primitive datatype into another is known as type casting (type conversion) in Java. You can cast the primitive datatypes in two ways namely, Widening and, Narrowing." }, { "code": null, "e": 1837, "s": 1500, "text": "Narrowing − Converting a higher datatype to a lower datatype is known as narrowing. In this case the casting/conversion is not done automatically, you need to convert explicitly using the cast operator “( )” explicitly. Therefore, it is known as explicit type casting. In this case both datatypes need not be compatible with each other." }, { "code": null, "e": 2167, "s": 1837, "text": "import java.util.Scanner;\npublic class NarrowingExample {\n public static void main(String args[]){\n Scanner sc = new Scanner(System.in);\n System.out.println(\"Enter an integer value: \");\n int i = sc.nextInt();\n char ch = (char) i;\n System.out.println(\"Character value of the given integer: \"+ch);\n }\n}" }, { "code": null, "e": 2234, "s": 2167, "text": "Enter an integer value:\n67\nCharacter value of the given integer: C" }, { "code": null, "e": 2353, "s": 2234, "text": "you can cast the reference(object) of one (class) type to other. But, one of the two classes should inherit the other." }, { "code": null, "e": 2519, "s": 2353, "text": "Therefore, if a class inherits the properties of the other conversion of super class object in to sub class type is considered as, narrowing with respect to objects." }, { "code": null, "e": 2592, "s": 2519, "text": "But unlike widening in case narrowing you need to use the cast operator." }, { "code": null, "e": 2800, "s": 2592, "text": "In the following Java example, we have two classes namely Person and Student. The Person class has two instance variables name and age and one instance method displayPerson() which displays the name and age." }, { "code": null, "e": 2994, "s": 2800, "text": "The Student extends the person class and in addition to the inherited name and age it has two more variables branch and student_id. It has a method displayData() which displays all four values." }, { "code": null, "e": 3150, "s": 2994, "text": "In the main method, we have created the objects of the both classes separately and we are trying to convert the sub class object into the super class type." }, { "code": null, "e": 4444, "s": 3150, "text": "class Person{\n private String name;\n private int age;\n public Person(String name, int age){\n this.name = name;\n this.age = age;\n }\n public void displayPerson() {\n System.out.println(\"Data of the Person class: \");\n System.out.println(\"Name: \"+this.name);\n System.out.println(\"Age: \"+this.age);\n }\n}\npublic class Student extends Person {\n public String branch;\n public int Student_id;\n public Student(String name, int age, String branch, int Student_id){\n super(name, age);\n this.branch = branch;\n this.Student_id = Student_id;\n }\n public void displayStudent() {\n System.out.println(\"Data of the Student class: \");\n System.out.println(\"Name: \"+this.name);\n System.out.println(\"Age: \"+this.age);\n System.out.println(\"Branch: \"+this.branch);\n System.out.println(\"Student ID: \"+this.Student_id);\n }\n public static void main(String[] args) {\n //Creating an object of the Student class\n Student student = new Student(\"Krishna\", 20, \"IT\", 1256);\n //Converting the object of Student to Person\n Person person = new Person(\"Krishna\", 20);\n //Converting the object of person to student\n student = (Student) person;\n student.displayPerson();\n student.displayStudent();\n }\n}" }, { "code": null, "e": 4623, "s": 4444, "text": "To this reference, members of both classes are available and the program gets compiled successfully. But, when you try to execute it, an exception will be raised as shown below −" }, { "code": null, "e": 4761, "s": 4623, "text": "Exception in thread \"main\" java.lang.ClassCastException: ther.Person cannot be cast to ther.Student\nat ther.Student.main(Student.java:41)" }, { "code": null, "e": 4958, "s": 4761, "text": "To resolve this issue, first of all you need to create the super class reference using the sub class object and then, convert this (super) reference type to sub class type using the cast operator." }, { "code": null, "e": 5252, "s": 4958, "text": "public static void main(String[] args) {\n //Converting the object of Student to Person\n Person person = new Student(\"Krishna\", 20, \"IT\", 1256);\n //Converting the object of person to student\n Student student = (Student) person;\n student.displayPerson();\n student.displayStudent();\n}" }, { "code": null, "e": 5377, "s": 5252, "text": "Data of the Person class:\nName: Krishna\nAge: 20\nData of the Student class:\nName: Krishna\nAge: 20\nBranch: IT\nStudent ID: 1256" } ]
How to create a default constructor in Java?
A no-arg constructor doesn’t accepts any parameters, it instantiates the class variables with their respective default values (i.e. null for objects, 0.0 for float and double, false for Boolean, 0 for byte, short, int and, long). There is no need to invoke constructors explicitly these are automatically invoked at the time of instantiation. While defining the constructors you should keep the following points in mind. A constructor does not have return type. The name of the constructor is same as the name of the class. A constructor cannot be abstract, final, static and Synchronized. You can use the access specifiers public, protected & private with constructors. Live Demo class NumberValue { private int num; public void display() { System.out.println("The number is: " + num); } } public class Demo { public static void main(String[] args) { NumberValue obj = new NumberValue(); obj.display(); } } The number is: 0 Live Demo public class Student { public final String name; public final int age; public Student(){ this.name = "Raju"; this.age = 20; } public void display(){ System.out.println("Name of the Student: "+this.name ); System.out.println("Age of the Student: "+this.age ); } public static void main(String args[]) { new Student().display(); } } Name of the Student: Raju Age of the Student: 20
[ { "code": null, "e": 1292, "s": 1062, "text": "A no-arg constructor doesn’t accepts any parameters, it instantiates the class variables with their respective default values (i.e. null for objects, 0.0 for float and double, false for Boolean, 0 for byte, short, int and, long)." }, { "code": null, "e": 1405, "s": 1292, "text": "There is no need to invoke constructors explicitly these are automatically invoked at the time of instantiation." }, { "code": null, "e": 1483, "s": 1405, "text": "While defining the constructors you should keep the following points in mind." }, { "code": null, "e": 1524, "s": 1483, "text": "A constructor does not have return type." }, { "code": null, "e": 1586, "s": 1524, "text": "The name of the constructor is same as the name of the class." }, { "code": null, "e": 1652, "s": 1586, "text": "A constructor cannot be abstract, final, static and Synchronized." }, { "code": null, "e": 1733, "s": 1652, "text": "You can use the access specifiers public, protected & private with constructors." }, { "code": null, "e": 1743, "s": 1733, "text": "Live Demo" }, { "code": null, "e": 2003, "s": 1743, "text": "class NumberValue {\n private int num;\n public void display() {\n System.out.println(\"The number is: \" + num);\n }\n}\npublic class Demo {\n public static void main(String[] args) {\n NumberValue obj = new NumberValue();\n obj.display();\n }\n}" }, { "code": null, "e": 2020, "s": 2003, "text": "The number is: 0" }, { "code": null, "e": 2030, "s": 2020, "text": "Live Demo" }, { "code": null, "e": 2417, "s": 2030, "text": "public class Student {\n public final String name;\n public final int age; \n public Student(){\n this.name = \"Raju\";\n this.age = 20;\n }\n public void display(){\n System.out.println(\"Name of the Student: \"+this.name );\n System.out.println(\"Age of the Student: \"+this.age );\n }\n public static void main(String args[]) {\n new Student().display();\n }\n}" }, { "code": null, "e": 2466, "s": 2417, "text": "Name of the Student: Raju\nAge of the Student: 20" } ]
How to use SearchView in Android?
This example demonstrates how do I use SearchView in android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <ListView android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/listView" android:divider="#ad5" android:dividerHeight="2dp" android:layout_below="@+id/searchView"/> <SearchView android:id="@+id/searchView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:queryHint="Search Here" android:iconifiedByDefault="false" android:layout_alignParentTop="true"/> </RelativeLayout> Step 3 − Add the following code to src/MainActivity.java import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.SearchView; import android.widget.Toast; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { SearchView searchView; ListView listView; ArrayList list; ArrayAdapter adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); searchView = findViewById(R.id.searchView); listView = findViewById(R.id.listView); list = new ArrayList<>(); list.add("Apple"); list.add("Banana"); list.add("Pineapple"); list.add("Orange"); list.add("Mango"); list.add("Grapes"); list.add("Lemon"); list.add("Melon"); list.add("Watermelon"); list.add("Papaya"); adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,list); listView.setAdapter(adapter); searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String query) { if(list.contains(query)){ adapter.getFilter().filter(query); }else{ Toast.makeText(MainActivity.this, "No Match found",Toast.LENGTH_LONG).show(); } return false; } @Override public boolean onQueryTextChange(String newText) { adapter.getFilter().filter(newText); return false; } }); } } Step 4 − Add the following code to androidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen − Click here to download the project code.
[ { "code": null, "e": 1124, "s": 1062, "text": "This example demonstrates how do I use SearchView in android." }, { "code": null, "e": 1252, "s": 1124, "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": 1317, "s": 1252, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2115, "s": 1317, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout\n xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n tools:context=\".MainActivity\">\n <ListView\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:id=\"@+id/listView\"\n android:divider=\"#ad5\"\n android:dividerHeight=\"2dp\"\n android:layout_below=\"@+id/searchView\"/>\n <SearchView\n android:id=\"@+id/searchView\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:queryHint=\"Search Here\"\n android:iconifiedByDefault=\"false\"\n android:layout_alignParentTop=\"true\"/>\n</RelativeLayout>" }, { "code": null, "e": 2172, "s": 2115, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 3815, "s": 2172, "text": "import android.support.v7.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.widget.ArrayAdapter;\nimport android.widget.ListView;\nimport android.widget.SearchView;\nimport android.widget.Toast;\nimport java.util.ArrayList;\npublic class MainActivity extends AppCompatActivity {\n SearchView searchView;\n ListView listView;\n ArrayList list;\n ArrayAdapter adapter;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n searchView = findViewById(R.id.searchView);\n listView = findViewById(R.id.listView);\n list = new ArrayList<>();\n list.add(\"Apple\");\n list.add(\"Banana\");\n list.add(\"Pineapple\");\n list.add(\"Orange\");\n list.add(\"Mango\");\n list.add(\"Grapes\");\n list.add(\"Lemon\");\n list.add(\"Melon\");\n list.add(\"Watermelon\");\n list.add(\"Papaya\");\n adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,list);\n listView.setAdapter(adapter);\n searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {\n @Override\n public boolean onQueryTextSubmit(String query) {\n if(list.contains(query)){\n adapter.getFilter().filter(query);\n }else{\n Toast.makeText(MainActivity.this, \"No Match found\",Toast.LENGTH_LONG).show();\n }\n return false;\n }\n @Override\n public boolean onQueryTextChange(String newText) {\n adapter.getFilter().filter(newText);\n return false;\n }\n });\n }\n}" }, { "code": null, "e": 3870, "s": 3815, "text": "Step 4 − Add the following code to androidManifest.xml" }, { "code": null, "e": 4540, "s": 3870, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"app.com.sample\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>" }, { "code": null, "e": 4887, "s": 4540, "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": 4928, "s": 4887, "text": "Click here to download the project code." } ]
New in Hadoop: You should know the Various File Format in Hadoop. | by Sahil Dhankhad | Towards Data Science
A few weeks ago, I wrote an article about Hadoop and talked about the different parts of it. And how it plays an essential role in data engineering. In this article, I’m going to give a summary of the different file format in Hadoop. This topic is going to be a short and quick one. If you are trying to understand, how’s Hadoop work and it’s a vital role in Data Engineer, please visit my Article on Hadoop here or happy to skip it. towardsdatascience.com The file format in Hadoop roughly divided into two categories: row-oriented and column-oriented: Row-oriented: The same row of data stored together that is continuous storage: SequenceFile, MapFile, Avro Datafile. In this way, if only a small amount of data of the row needs to be accessed, the entire row needs to be read into the memory. Delaying the serialization can lighten the problem to a certain amount, but the overhead of reading the whole row of data from the disk cannot be withdrawn. Row-oriented storage is suitable for situations where the entire row of data needs to be processed simultaneously. Column-oriented: The entire file cut into several columns of data, and each column of data stored together: Parquet, RCFile, ORCFile. The column-oriented format makes it possible to skip unneeded columns when reading data, suitable for situations where only a small portion of the rows are in the field. But this format of reading and write requires more memory space because the cache line needs to be in memory (to get a column in multiple rows). At the same time, it is not suitable for streaming to write, because once the write fails, the current file cannot be recovered, and the line-oriented data can be resynchronized to the last synchronization point when the write fails, so Flume uses the line-oriented storage format. If it still not clear what is row and column oriented, don’t worry, you can visit this link and know the difference between them. Here are a few related file formats that are widely used on the Hadoop system: The storage format differs depending on whether it is compressed, and whether it uses record compression or block compression: No compression: Store in order according to record length, Key length, Value degree, Key value, and Value value. The range is the number of bytes. Serialization is performed using the specified Serialization. Record compression: Only the value is compressed, and the compressed codec stored in the header. Block compression: Multiple records are compressed together to take advantage of the similarities between records and save space. The synchronization flag is added before and after the block. The minimum value of the block is io.seqfile.compress.blocksizeset by the attribute. MapFile is a variant of SequenceFile. It is MapFile after adding an index to SequenceFile and sorting it. The index is stored as a separate file, typically storing an index for every 128 records. Indexes can be loaded into memory for quick lookups — the files storing the data arranged in the order defined by Key. MapFile records must be written in order. Otherwise, an IOException is thrown. Derived type of MapFile: SetFile : A special MapFile for storing a sequence of keys of type Writable. Key is written in order.ArrayFile: Key is an integer representing the position in the array, and value is Writable.BloomMapFile: Optimized for the MapFile get() method using dynamic Bloom filters. The filter stored in memory, and only when the key value exists, the regular get() method is called to perform the read operation. SetFile : A special MapFile for storing a sequence of keys of type Writable. Key is written in order. ArrayFile: Key is an integer representing the position in the array, and value is Writable. BloomMapFile: Optimized for the MapFile get() method using dynamic Bloom filters. The filter stored in memory, and only when the key value exists, the regular get() method is called to perform the read operation. The files listed below the Hadoop system include RCFile, ORCFile, and Parquet. The column-oriented version of Avro is Trevni. Hive’s Record Columnar File, this type of file first divides the data into Row Group by row, and inside the Row Group, the data is stored in columns. Its structure is as follows: Compared to purely row-oriented and column-oriented: ORCFile (Optimized Record Columnar File) provides a more efficient file format than RCFile. It internally divides the data into Stripe with a default size of 250M. Each stripe includes an index, data, and Footer. The index stores the maximum and minimum values ​​of each column, as well as the position of each row in the column. In Hive, the following command is used to use ORCFile: CREATE TABLE ...STORED AAS ORC ALTER TABLE ... SET FILEFORMAT ORC SET hive.default.fileformat=ORC A generic column-oriented storage format based on Google’s Dremel. Especially good at handling deeply nested data. For nested structures, Parquet converts it into a flat column store, which is represented by Repeat Level and Definition Level (R and D) and uses metadata to reconstruct the record when reading the data to rebuild the entire file. Structure. The following is an example of R and D: AddressBook { contacts: { phoneNumber: "555 987 6543" } contacts: { } } AddressBook { } That it, Now, you know different file format in Hadoop. If you find any mistakes and have suggestions, Please feel free to contact me. You can contact me on my LinkedIn.
[ { "code": null, "e": 606, "s": 172, "text": "A few weeks ago, I wrote an article about Hadoop and talked about the different parts of it. And how it plays an essential role in data engineering. In this article, I’m going to give a summary of the different file format in Hadoop. This topic is going to be a short and quick one. If you are trying to understand, how’s Hadoop work and it’s a vital role in Data Engineer, please visit my Article on Hadoop here or happy to skip it." }, { "code": null, "e": 629, "s": 606, "text": "towardsdatascience.com" }, { "code": null, "e": 726, "s": 629, "text": "The file format in Hadoop roughly divided into two categories: row-oriented and column-oriented:" }, { "code": null, "e": 1241, "s": 726, "text": "Row-oriented: The same row of data stored together that is continuous storage: SequenceFile, MapFile, Avro Datafile. In this way, if only a small amount of data of the row needs to be accessed, the entire row needs to be read into the memory. Delaying the serialization can lighten the problem to a certain amount, but the overhead of reading the whole row of data from the disk cannot be withdrawn. Row-oriented storage is suitable for situations where the entire row of data needs to be processed simultaneously." }, { "code": null, "e": 1972, "s": 1241, "text": "Column-oriented: The entire file cut into several columns of data, and each column of data stored together: Parquet, RCFile, ORCFile. The column-oriented format makes it possible to skip unneeded columns when reading data, suitable for situations where only a small portion of the rows are in the field. But this format of reading and write requires more memory space because the cache line needs to be in memory (to get a column in multiple rows). At the same time, it is not suitable for streaming to write, because once the write fails, the current file cannot be recovered, and the line-oriented data can be resynchronized to the last synchronization point when the write fails, so Flume uses the line-oriented storage format." }, { "code": null, "e": 2102, "s": 1972, "text": "If it still not clear what is row and column oriented, don’t worry, you can visit this link and know the difference between them." }, { "code": null, "e": 2181, "s": 2102, "text": "Here are a few related file formats that are widely used on the Hadoop system:" }, { "code": null, "e": 2308, "s": 2181, "text": "The storage format differs depending on whether it is compressed, and whether it uses record compression or block compression:" }, { "code": null, "e": 2517, "s": 2308, "text": "No compression: Store in order according to record length, Key length, Value degree, Key value, and Value value. The range is the number of bytes. Serialization is performed using the specified Serialization." }, { "code": null, "e": 2614, "s": 2517, "text": "Record compression: Only the value is compressed, and the compressed codec stored in the header." }, { "code": null, "e": 2891, "s": 2614, "text": "Block compression: Multiple records are compressed together to take advantage of the similarities between records and save space. The synchronization flag is added before and after the block. The minimum value of the block is io.seqfile.compress.blocksizeset by the attribute." }, { "code": null, "e": 3285, "s": 2891, "text": "MapFile is a variant of SequenceFile. It is MapFile after adding an index to SequenceFile and sorting it. The index is stored as a separate file, typically storing an index for every 128 records. Indexes can be loaded into memory for quick lookups — the files storing the data arranged in the order defined by Key. MapFile records must be written in order. Otherwise, an IOException is thrown." }, { "code": null, "e": 3310, "s": 3285, "text": "Derived type of MapFile:" }, { "code": null, "e": 3715, "s": 3310, "text": "SetFile : A special MapFile for storing a sequence of keys of type Writable. Key is written in order.ArrayFile: Key is an integer representing the position in the array, and value is Writable.BloomMapFile: Optimized for the MapFile get() method using dynamic Bloom filters. The filter stored in memory, and only when the key value exists, the regular get() method is called to perform the read operation." }, { "code": null, "e": 3817, "s": 3715, "text": "SetFile : A special MapFile for storing a sequence of keys of type Writable. Key is written in order." }, { "code": null, "e": 3909, "s": 3817, "text": "ArrayFile: Key is an integer representing the position in the array, and value is Writable." }, { "code": null, "e": 4122, "s": 3909, "text": "BloomMapFile: Optimized for the MapFile get() method using dynamic Bloom filters. The filter stored in memory, and only when the key value exists, the regular get() method is called to perform the read operation." }, { "code": null, "e": 4248, "s": 4122, "text": "The files listed below the Hadoop system include RCFile, ORCFile, and Parquet. The column-oriented version of Avro is Trevni." }, { "code": null, "e": 4427, "s": 4248, "text": "Hive’s Record Columnar File, this type of file first divides the data into Row Group by row, and inside the Row Group, the data is stored in columns. Its structure is as follows:" }, { "code": null, "e": 4480, "s": 4427, "text": "Compared to purely row-oriented and column-oriented:" }, { "code": null, "e": 4810, "s": 4480, "text": "ORCFile (Optimized Record Columnar File) provides a more efficient file format than RCFile. It internally divides the data into Stripe with a default size of 250M. Each stripe includes an index, data, and Footer. The index stores the maximum and minimum values ​​of each column, as well as the position of each row in the column." }, { "code": null, "e": 4865, "s": 4810, "text": "In Hive, the following command is used to use ORCFile:" }, { "code": null, "e": 4963, "s": 4865, "text": "CREATE TABLE ...STORED AAS ORC ALTER TABLE ... SET FILEFORMAT ORC SET hive.default.fileformat=ORC" }, { "code": null, "e": 5078, "s": 4963, "text": "A generic column-oriented storage format based on Google’s Dremel. Especially good at handling deeply nested data." }, { "code": null, "e": 5360, "s": 5078, "text": "For nested structures, Parquet converts it into a flat column store, which is represented by Repeat Level and Definition Level (R and D) and uses metadata to reconstruct the record when reading the data to rebuild the entire file. Structure. The following is an example of R and D:" }, { "code": null, "e": 5473, "s": 5360, "text": "AddressBook { contacts: { phoneNumber: \"555 987 6543\" } contacts: { } } AddressBook { }" } ]
Conversational AI Chatbot with Pretrained Transformers Using Pytorch | by Raymond Cheng | Towards Data Science
Conversational systems, or dialogue systems, have garnered huge interest in the modern Natural Language Processing (NLP) community. It is simply exciting to see how closely bots can mimic our thoughts, logic, and emotions as shown from their language. Today, we know that there are digital assistants right at the palm of our hands in our smartphones, such as Apple Siri, Google Assistant, and Microsoft Cortana. They are all able to listen and respond to the user’s language although not perfect. In this post, we teach you how you can leverage pretrained transformers such as DialoGPT to implement your own conversational chatbot. We will be using the Transformers library provided by Huggingface to build this system. So without further ado, let’s begin! Step 1: Install Library Step 2: Import Library Step 3: Build Conversational Pipeline Step 4: Add starting conversations Step 5: Add continuing conversations The library we are using is Huggingface Transformers. To install it, you can simply do: pip install transformers Make sure to have a working version of Pytorch or Tensorflow, so that Transformers can use one of them as the backend. After installing Transformers, now it’s time to import it in a Python script. Instead of using the entire Transformers library, we introduce a pipeline module that basically provides a very simple API to do a variety of NLP tasks without needing to understand complex code. We also import the Conversation object, which we will use later on for the conversational pipeline. To import them, you can do: from transformers import pipeline, Conversation After importing the relevant components, now we can start building the pipeline for the conversation system by: conversational_pipeline = pipeline(“conversational”) This line of code will setup the conversation pipeline using DialoGPT as the model, a GPT2 model trained on a dialogue dataset. Now, we can start talking to the bot! First, let’s open up two conversations with the bot and ask it for movie recommendations and what it’s favorite book is: Conversation 1: Let’s watch a movie tonight — any recommendations? Conversation 2: What’s your favorite book? conv1_start = “Let’s watch a movie tonight — any recommendations?”conv2_start = “What’s your favorite book?” Then, we construct two conversations using the defined variables: conv1 = Conversation(conv1_start)conv2 = Conversation(conv2_start) After that, we put both of the conversations into the list and then feed it to the conversational pipeline: conversational_pipeline([conv1, conv2]) Finally, we can see the results of each conversation returned by the bot: [Conversation id: a9bae572-cc11–48c8-b36f-d88bcd49b8c0 user >> Let’s watch a movie tonight — any recommendations? bot >> The Big Lebowski , Conversation id: e6ee2d97–5ee7–404b-b2e5–4dd527f9e9dd user >> What’s your favorite book? bot >> The Hunger Games ] We can continue the conversation with the bot by adding new user inputs to the previous conversations and then process the conversational pipeline again. Imagine we want to follow up the bot by asking what the movie is about in Conversation 1 and what the genre of the book is in Conversation 2. Conversation 1: What is it about? Conversation 2: Cool, what is the genre of the book? conv1_next = “What is it about?”conv2_next = “Cool, what is the genre of the book?” To add new user inputs to previous conversations, we can first do: conv1.add_user_input(conv1_next)conv2.add_user_input(conv2_next) After that, we can simply reuse the prior code to update the conversational pipeline with the new set of conversations: conversational_pipeline([conv1, conv2]) Finally, you should see that the bot is able to return new responses which are quite on topic: [Conversation id: a9bae572-cc11–48c8-b36f-d88bcd49b8c0 user >> Let’s watch a movie tonight — any recommendations? bot >> The Big Lebowski user >> What is it about? bot >> It’s a comedy about a guy who gets a job at a movie theater and gets a bunch of jobs. , Conversation id: e6ee2d97–5ee7–404b-b2e5–4dd527f9e9dd user >> What’s your favorite book? bot >> The Hunger Games user >> Cool, what is the genre of the book? bot >> I’m not sure, but I think it’s fantasy. ] And that’s all for this article! Hope you learned something useful. In this post, we went through how you can implement your own conversational bot using a pretrained model provided by Huggingface. In case you are looking for it, I have attached a Jupyter version of the entire code down below, for your convenience: from transformers import pipeline, Conversation conversational_pipeline = pipeline("conversational") conv1_start = "Let's watch a movie tonight - any recommendations?" conv2_start = "What's your favorite book?" conv1 = Conversation(conv1_start) conv2 = Conversation(conv2_start) conversational_pipeline([conv1, conv2]) Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. [Conversation id: a9bae572-cc11-48c8-b36f-d88bcd49b8c0 user >> Let's watch a movie tonight - any recommendations? bot >> The Big Lebowski , Conversation id: e6ee2d97-5ee7-404b-b2e5-4dd527f9e9dd user >> What's your favorite book? bot >> The Hunger Games ] conv1_next = "What is it about?" conv2_next = "Cool, what is the genre of the book?" conv1.add_user_input(conv1_next) conv2.add_user_input(conv2_next) conversational_pipeline([conv1, conv2]) Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation. [Conversation id: a9bae572-cc11-48c8-b36f-d88bcd49b8c0 user >> Let's watch a movie tonight - any recommendations? bot >> The Big Lebowski user >> What is it about? bot >> It's a comedy about a guy who gets a job at a movie theater and gets a bunch of jobs. , Conversation id: e6ee2d97-5ee7-404b-b2e5-4dd527f9e9dd user >> What's your favorite book? bot >> The Hunger Games user >> Cool, what is the genre of the book? bot >> I'm not sure, but I think it's fantasy. ] Hope you enjoyed the article! If you like my work, please subscribe to the email list so you can receive updates whenever I create new content! Feel free to also browse my other posts if interested: towardsdatascience.com towardsdatascience.com towardsdatascience.com towardsdatascience.com towardsdatascience.com [1] Apple Siri Official Website, Apple [2] Google Assistant Official Website, Google [3] Microsoft Cortana Official Website, Microsoft [4] Transformers Github, Huggingface [5] Transformers Official Documentation, Huggingface [6] Pytorch Official Website, Facebook AI Research [7] Tensorflow Official Website, Google Brain [8] Zhang, Yizhe, et al. “Dialogpt: Large-scale generative pre-training for conversational response generation.” arXiv preprint arXiv:1911.00536 (2019). [9] Radford, Alec, et al. “Language models are unsupervised multitask learners.” OpenAI blog 1.8 (2019): 9.
[ { "code": null, "e": 670, "s": 172, "text": "Conversational systems, or dialogue systems, have garnered huge interest in the modern Natural Language Processing (NLP) community. It is simply exciting to see how closely bots can mimic our thoughts, logic, and emotions as shown from their language. Today, we know that there are digital assistants right at the palm of our hands in our smartphones, such as Apple Siri, Google Assistant, and Microsoft Cortana. They are all able to listen and respond to the user’s language although not perfect." }, { "code": null, "e": 893, "s": 670, "text": "In this post, we teach you how you can leverage pretrained transformers such as DialoGPT to implement your own conversational chatbot. We will be using the Transformers library provided by Huggingface to build this system." }, { "code": null, "e": 930, "s": 893, "text": "So without further ado, let’s begin!" }, { "code": null, "e": 954, "s": 930, "text": "Step 1: Install Library" }, { "code": null, "e": 977, "s": 954, "text": "Step 2: Import Library" }, { "code": null, "e": 1015, "s": 977, "text": "Step 3: Build Conversational Pipeline" }, { "code": null, "e": 1050, "s": 1015, "text": "Step 4: Add starting conversations" }, { "code": null, "e": 1087, "s": 1050, "text": "Step 5: Add continuing conversations" }, { "code": null, "e": 1175, "s": 1087, "text": "The library we are using is Huggingface Transformers. To install it, you can simply do:" }, { "code": null, "e": 1200, "s": 1175, "text": "pip install transformers" }, { "code": null, "e": 1319, "s": 1200, "text": "Make sure to have a working version of Pytorch or Tensorflow, so that Transformers can use one of them as the backend." }, { "code": null, "e": 1693, "s": 1319, "text": "After installing Transformers, now it’s time to import it in a Python script. Instead of using the entire Transformers library, we introduce a pipeline module that basically provides a very simple API to do a variety of NLP tasks without needing to understand complex code. We also import the Conversation object, which we will use later on for the conversational pipeline." }, { "code": null, "e": 1721, "s": 1693, "text": "To import them, you can do:" }, { "code": null, "e": 1769, "s": 1721, "text": "from transformers import pipeline, Conversation" }, { "code": null, "e": 1881, "s": 1769, "text": "After importing the relevant components, now we can start building the pipeline for the conversation system by:" }, { "code": null, "e": 1934, "s": 1881, "text": "conversational_pipeline = pipeline(“conversational”)" }, { "code": null, "e": 2062, "s": 1934, "text": "This line of code will setup the conversation pipeline using DialoGPT as the model, a GPT2 model trained on a dialogue dataset." }, { "code": null, "e": 2221, "s": 2062, "text": "Now, we can start talking to the bot! First, let’s open up two conversations with the bot and ask it for movie recommendations and what it’s favorite book is:" }, { "code": null, "e": 2288, "s": 2221, "text": "Conversation 1: Let’s watch a movie tonight — any recommendations?" }, { "code": null, "e": 2331, "s": 2288, "text": "Conversation 2: What’s your favorite book?" }, { "code": null, "e": 2440, "s": 2331, "text": "conv1_start = “Let’s watch a movie tonight — any recommendations?”conv2_start = “What’s your favorite book?”" }, { "code": null, "e": 2506, "s": 2440, "text": "Then, we construct two conversations using the defined variables:" }, { "code": null, "e": 2573, "s": 2506, "text": "conv1 = Conversation(conv1_start)conv2 = Conversation(conv2_start)" }, { "code": null, "e": 2681, "s": 2573, "text": "After that, we put both of the conversations into the list and then feed it to the conversational pipeline:" }, { "code": null, "e": 2721, "s": 2681, "text": "conversational_pipeline([conv1, conv2])" }, { "code": null, "e": 2795, "s": 2721, "text": "Finally, we can see the results of each conversation returned by the bot:" }, { "code": null, "e": 3054, "s": 2795, "text": "[Conversation id: a9bae572-cc11–48c8-b36f-d88bcd49b8c0 user >> Let’s watch a movie tonight — any recommendations? bot >> The Big Lebowski , Conversation id: e6ee2d97–5ee7–404b-b2e5–4dd527f9e9dd user >> What’s your favorite book? bot >> The Hunger Games ]" }, { "code": null, "e": 3208, "s": 3054, "text": "We can continue the conversation with the bot by adding new user inputs to the previous conversations and then process the conversational pipeline again." }, { "code": null, "e": 3350, "s": 3208, "text": "Imagine we want to follow up the bot by asking what the movie is about in Conversation 1 and what the genre of the book is in Conversation 2." }, { "code": null, "e": 3384, "s": 3350, "text": "Conversation 1: What is it about?" }, { "code": null, "e": 3437, "s": 3384, "text": "Conversation 2: Cool, what is the genre of the book?" }, { "code": null, "e": 3521, "s": 3437, "text": "conv1_next = “What is it about?”conv2_next = “Cool, what is the genre of the book?”" }, { "code": null, "e": 3588, "s": 3521, "text": "To add new user inputs to previous conversations, we can first do:" }, { "code": null, "e": 3653, "s": 3588, "text": "conv1.add_user_input(conv1_next)conv2.add_user_input(conv2_next)" }, { "code": null, "e": 3773, "s": 3653, "text": "After that, we can simply reuse the prior code to update the conversational pipeline with the new set of conversations:" }, { "code": null, "e": 3813, "s": 3773, "text": "conversational_pipeline([conv1, conv2])" }, { "code": null, "e": 3908, "s": 3813, "text": "Finally, you should see that the bot is able to return new responses which are quite on topic:" }, { "code": null, "e": 4382, "s": 3908, "text": "[Conversation id: a9bae572-cc11–48c8-b36f-d88bcd49b8c0 user >> Let’s watch a movie tonight — any recommendations? bot >> The Big Lebowski user >> What is it about? bot >> It’s a comedy about a guy who gets a job at a movie theater and gets a bunch of jobs. , Conversation id: e6ee2d97–5ee7–404b-b2e5–4dd527f9e9dd user >> What’s your favorite book? bot >> The Hunger Games user >> Cool, what is the genre of the book? bot >> I’m not sure, but I think it’s fantasy. ]" }, { "code": null, "e": 4699, "s": 4382, "text": "And that’s all for this article! Hope you learned something useful. In this post, we went through how you can implement your own conversational bot using a pretrained model provided by Huggingface. In case you are looking for it, I have attached a Jupyter version of the entire code down below, for your convenience:" }, { "code": null, "e": 4748, "s": 4699, "text": "from transformers import pipeline, Conversation\n" }, { "code": null, "e": 4802, "s": 4748, "text": "conversational_pipeline = pipeline(\"conversational\")\n" }, { "code": null, "e": 5023, "s": 4802, "text": "conv1_start = \"Let's watch a movie tonight - any recommendations?\"\nconv2_start = \"What's your favorite book?\"\n\nconv1 = Conversation(conv1_start)\nconv2 = Conversation(conv2_start)\n\nconversational_pipeline([conv1, conv2])\n" }, { "code": null, "e": 5096, "s": 5023, "text": "Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation.\n" }, { "code": null, "e": 5360, "s": 5096, "text": "[Conversation id: a9bae572-cc11-48c8-b36f-d88bcd49b8c0 \n user >> Let's watch a movie tonight - any recommendations? \n bot >> The Big Lebowski ,\n Conversation id: e6ee2d97-5ee7-404b-b2e5-4dd527f9e9dd \n user >> What's your favorite book? \n bot >> The Hunger Games ]" }, { "code": null, "e": 5554, "s": 5360, "text": "conv1_next = \"What is it about?\"\nconv2_next = \"Cool, what is the genre of the book?\"\n\nconv1.add_user_input(conv1_next)\nconv2.add_user_input(conv2_next)\n\nconversational_pipeline([conv1, conv2])\n" }, { "code": null, "e": 5627, "s": 5554, "text": "Setting `pad_token_id` to `eos_token_id`:50256 for open-end generation.\n" }, { "code": null, "e": 6110, "s": 5627, "text": "[Conversation id: a9bae572-cc11-48c8-b36f-d88bcd49b8c0 \n user >> Let's watch a movie tonight - any recommendations? \n bot >> The Big Lebowski \n user >> What is it about? \n bot >> It's a comedy about a guy who gets a job at a movie theater and gets a bunch of jobs. ,\n Conversation id: e6ee2d97-5ee7-404b-b2e5-4dd527f9e9dd \n user >> What's your favorite book? \n bot >> The Hunger Games \n user >> Cool, what is the genre of the book? \n bot >> I'm not sure, but I think it's fantasy. ]" }, { "code": null, "e": 6309, "s": 6110, "text": "Hope you enjoyed the article! If you like my work, please subscribe to the email list so you can receive updates whenever I create new content! Feel free to also browse my other posts if interested:" }, { "code": null, "e": 6332, "s": 6309, "text": "towardsdatascience.com" }, { "code": null, "e": 6355, "s": 6332, "text": "towardsdatascience.com" }, { "code": null, "e": 6378, "s": 6355, "text": "towardsdatascience.com" }, { "code": null, "e": 6401, "s": 6378, "text": "towardsdatascience.com" }, { "code": null, "e": 6424, "s": 6401, "text": "towardsdatascience.com" }, { "code": null, "e": 6463, "s": 6424, "text": "[1] Apple Siri Official Website, Apple" }, { "code": null, "e": 6509, "s": 6463, "text": "[2] Google Assistant Official Website, Google" }, { "code": null, "e": 6559, "s": 6509, "text": "[3] Microsoft Cortana Official Website, Microsoft" }, { "code": null, "e": 6596, "s": 6559, "text": "[4] Transformers Github, Huggingface" }, { "code": null, "e": 6649, "s": 6596, "text": "[5] Transformers Official Documentation, Huggingface" }, { "code": null, "e": 6700, "s": 6649, "text": "[6] Pytorch Official Website, Facebook AI Research" }, { "code": null, "e": 6746, "s": 6700, "text": "[7] Tensorflow Official Website, Google Brain" }, { "code": null, "e": 6899, "s": 6746, "text": "[8] Zhang, Yizhe, et al. “Dialogpt: Large-scale generative pre-training for conversational response generation.” arXiv preprint arXiv:1911.00536 (2019)." } ]
Walrus Operator in Python 3.8 - GeeksforGeeks
26 Aug, 2019 Python 3.8 is still in development. But many alpha versions have been released. One of the latest features in Python 3.8 is the Walrus Operator. In this article, we’re going to discuss the Walrus operator and explain it with an example. Introduction Walrus-operator is another name for assignment expressions. According to the official documentation, it is a way to assign to variables within an expression using the notation NAME := expr. The Assignment expressions allow a value to be assigned to a variable, even a variable that doesn’t exist yet, in the context of expression rather than as a stand-alone statement. Code : a = [1, 2, 3, 4]if (n := len(a)) > 3: print(f"List is too long ({n} elements, expected <= 3)") Output : Here’s instead of using “len(a)” in two places we have assigned it to a variable called “n”, which can be used later. This helps us to resolve code duplication and improves readability. Example – Let’s try to understand Assignment Expressions more clearly with the help of an example using both Python 3.7 and Python 3.8. Here we have a list of dictionaries called “sample_data”, which contains the userId, name and a boolean called completed. sample_data = [ {"userId": 1, "name": "rahul", "completed": False}, {"userId": 1, "name": "rohit", "completed": False}, {"userId": 1, "name": "ram", "completed": False}, {"userId": 1, "name": "ravan", "completed": True}] print("With Python 3.8 Walrus Operator:") for entry in sample_data: if name := entry.get("name"): print(f'Found name: "{name}"') print("Without Walrus operator:")for entry in sample_data: name = entry.get("name") if name: print(f'Found name: "{name}"') Output: Programming Language Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Top 10 Programming Languages to Learn in 2022 Difference between Shallow and Deep copy of a class Kotlin Array C# | Data Types Advantages and Disadvantages of OOP 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": 24617, "s": 24589, "text": "\n26 Aug, 2019" }, { "code": null, "e": 24854, "s": 24617, "text": "Python 3.8 is still in development. But many alpha versions have been released. One of the latest features in Python 3.8 is the Walrus Operator. In this article, we’re going to discuss the Walrus operator and explain it with an example." }, { "code": null, "e": 24867, "s": 24854, "text": "Introduction" }, { "code": null, "e": 25237, "s": 24867, "text": "Walrus-operator is another name for assignment expressions. According to the official documentation, it is a way to assign to variables within an expression using the notation NAME := expr. The Assignment expressions allow a value to be assigned to a variable, even a variable that doesn’t exist yet, in the context of expression rather than as a stand-alone statement." }, { "code": null, "e": 25244, "s": 25237, "text": "Code :" }, { "code": "a = [1, 2, 3, 4]if (n := len(a)) > 3: print(f\"List is too long ({n} elements, expected <= 3)\")", "e": 25342, "s": 25244, "text": null }, { "code": null, "e": 25351, "s": 25342, "text": "Output :" }, { "code": null, "e": 25537, "s": 25351, "text": "Here’s instead of using “len(a)” in two places we have assigned it to a variable called “n”, which can be used later. This helps us to resolve code duplication and improves readability." }, { "code": null, "e": 25547, "s": 25537, "text": "Example –" }, { "code": null, "e": 25795, "s": 25547, "text": "Let’s try to understand Assignment Expressions more clearly with the help of an example using both Python 3.7 and Python 3.8. Here we have a list of dictionaries called “sample_data”, which contains the userId, name and a boolean called completed." }, { "code": "sample_data = [ {\"userId\": 1, \"name\": \"rahul\", \"completed\": False}, {\"userId\": 1, \"name\": \"rohit\", \"completed\": False}, {\"userId\": 1, \"name\": \"ram\", \"completed\": False}, {\"userId\": 1, \"name\": \"ravan\", \"completed\": True}] print(\"With Python 3.8 Walrus Operator:\") for entry in sample_data: if name := entry.get(\"name\"): print(f'Found name: \"{name}\"') print(\"Without Walrus operator:\")for entry in sample_data: name = entry.get(\"name\") if name: print(f'Found name: \"{name}\"')", "e": 26310, "s": 25795, "text": null }, { "code": null, "e": 26318, "s": 26310, "text": "Output:" }, { "code": null, "e": 26339, "s": 26318, "text": "Programming Language" }, { "code": null, "e": 26346, "s": 26339, "text": "Python" }, { "code": null, "e": 26444, "s": 26346, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26453, "s": 26444, "text": "Comments" }, { "code": null, "e": 26466, "s": 26453, "text": "Old Comments" }, { "code": null, "e": 26512, "s": 26466, "text": "Top 10 Programming Languages to Learn in 2022" }, { "code": null, "e": 26564, "s": 26512, "text": "Difference between Shallow and Deep copy of a class" }, { "code": null, "e": 26577, "s": 26564, "text": "Kotlin Array" }, { "code": null, "e": 26593, "s": 26577, "text": "C# | Data Types" }, { "code": null, "e": 26629, "s": 26593, "text": "Advantages and Disadvantages of OOP" }, { "code": null, "e": 26657, "s": 26629, "text": "Read JSON file using Python" }, { "code": null, "e": 26707, "s": 26657, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 26729, "s": 26707, "text": "Python map() function" } ]
3D Mesh Plots using Plotly in Python - GeeksforGeeks
01 Oct, 2020 Plotly is a Python library that is used to design graphs, especially interactive graphs. It can plot various graphs and charts like histogram, barplot, boxplot, spreadplot, and many more. It is mainly used in data analysis as well as financial analysis. plotly is an interactive visualization library A Mesh plot is a plot that has three dimensions surface and has solid edges and no face colors. A Mesh plot is a way to create a 3D set of triangles with vertices given by x, y, and z. If there are only coordinates, then algorithm such as Delaunay triangulation is used to form a triangle. I, J, and K parameters can also be used to create a triangle. Syntax: class plotly.graph_objects.Mesh3d(arg=None, hoverinfo=None, x=None, y=None, z=None, **kwargs) Parameters: arg: dict of properties compatible with this constructor or an instance of plotly.graph_objects.Mesh3d hoverinfo: Determines which trace information appear on hover. If none or skip are set, no information is displayed upon hovering. But, if none is set, click and hover events are still fired. x: Sets the X coordinates of the vertices. The nth element of vectors x, y and z jointly represent the X, Y and Z coordinates of the nth vertex. y: Sets the Y coordinates of the vertices. The nth element of vectors x, y and z jointly represent the X, Y and Z coordinates of the nth vertex. z: Sets the Z coordinates of the vertices. The nth element of vectors x, y and z jointly represent the X, Y and Z coordinates of the nth vertex. Example 1: Python3 import plotly.graph_objects as goimport numpy as np # Data for three-dimensional scattered pointsz = 15 * np.random.random(100)x = np.sin(z) + 0.1 * np.random.randn(100)y = np.cos(z) + 0.1 * np.random.randn(100) fig = go.Figure(data=[go.Mesh3d( x=x, y=y, z=z, color='green', opacity=0.20)]) fig.show() Output: Example 2: 3D Mesh example with Alphahull parameter In plotly, the alphahull parameter is used to set the shape of the mesh plot. It Determines how the mesh surface triangles are derived from the set of vertices (points) represented by the x, y, and z arrays, if the i, j, k arrays are not supplied. For general use of mesh3d, it is preferred that i, j, k are supplied. If “-1”, Delaunay triangulation is used, which is mainly suitable if the mesh is a single, more or less layer surface that is perpendicular to delaunayaxis. In case the delaunayaxis intersects the mesh surface at more than one point it will result in triangles that are very long in the dimension of delaunayaxis. If “>0”, the alpha-shape algorithm is used. In this case, the positive alphahull value signals the use of the alpha-shape algorithm, _and_ its value acts as the parameter for the mesh fitting. If 0, the convex-hull algorithm is used. It is suitable for convex bodies or if the intention is to enclose the x, y, and z points set into a convex hull. Example: Python3 import plotly.graph_objects as goimport numpy as np # Data for three-dimensional scattered pointsz = 15 * np.random.random(100)x = np.sin(z) + 0.1 * np.random.randn(100)y = np.cos(z) + 0.1 * np.random.randn(100) fig = go.Figure(data=[go.Mesh3d(x=x, y=y, z=z, color='green', opacity=0.20, alphahull=3)]) fig.show() Output: In mesh tetrahedron i,j, and k parameters can be used to manually specify the geometry of the triangles of the mesh. Example: Python3 import plotly.graph_objects as goimport numpy as np # Data for three-dimensional scattered pointsz = 15 * np.random.random(100)x = np.sin(z) + 0.1 * np.random.randn(100)y = np.cos(z) + 0.1 * np.random.randn(100) fig = go.Figure(data=[go.Mesh3d(x=x, y=y, z=z, color='green', opacity=0.20, alphahull=3, i=[1, 0, 0, 1], j=[1, 2, 3, 4], k=[4, 3, 1, 3],)]) fig.show() Output: Python-Plotly Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe Python Dictionary Taking input in Python How to Install PIP on Windows ? Read a file line by line in Python Enumerate() in Python Iterate over a list in Python
[ { "code": null, "e": 23834, "s": 23806, "text": "\n01 Oct, 2020" }, { "code": null, "e": 24135, "s": 23834, "text": "Plotly is a Python library that is used to design graphs, especially interactive graphs. It can plot various graphs and charts like histogram, barplot, boxplot, spreadplot, and many more. It is mainly used in data analysis as well as financial analysis. plotly is an interactive visualization library" }, { "code": null, "e": 24487, "s": 24135, "text": "A Mesh plot is a plot that has three dimensions surface and has solid edges and no face colors. A Mesh plot is a way to create a 3D set of triangles with vertices given by x, y, and z. If there are only coordinates, then algorithm such as Delaunay triangulation is used to form a triangle. I, J, and K parameters can also be used to create a triangle." }, { "code": null, "e": 24589, "s": 24487, "text": "Syntax: class plotly.graph_objects.Mesh3d(arg=None, hoverinfo=None, x=None, y=None, z=None, **kwargs)" }, { "code": null, "e": 24601, "s": 24589, "text": "Parameters:" }, { "code": null, "e": 24704, "s": 24601, "text": "arg: dict of properties compatible with this constructor or an instance of plotly.graph_objects.Mesh3d" }, { "code": null, "e": 24897, "s": 24704, "text": "hoverinfo: Determines which trace information appear on hover. If none or skip are set, no information is displayed upon hovering. But, if none is set, click and hover events are still fired." }, { "code": null, "e": 25042, "s": 24897, "text": "x: Sets the X coordinates of the vertices. The nth element of vectors x, y and z jointly represent the X, Y and Z coordinates of the nth vertex." }, { "code": null, "e": 25187, "s": 25042, "text": "y: Sets the Y coordinates of the vertices. The nth element of vectors x, y and z jointly represent the X, Y and Z coordinates of the nth vertex." }, { "code": null, "e": 25332, "s": 25187, "text": "z: Sets the Z coordinates of the vertices. The nth element of vectors x, y and z jointly represent the X, Y and Z coordinates of the nth vertex." }, { "code": null, "e": 25343, "s": 25332, "text": "Example 1:" }, { "code": null, "e": 25351, "s": 25343, "text": "Python3" }, { "code": "import plotly.graph_objects as goimport numpy as np # Data for three-dimensional scattered pointsz = 15 * np.random.random(100)x = np.sin(z) + 0.1 * np.random.randn(100)y = np.cos(z) + 0.1 * np.random.randn(100) fig = go.Figure(data=[go.Mesh3d( x=x, y=y, z=z, color='green', opacity=0.20)]) fig.show()", "e": 25657, "s": 25351, "text": null }, { "code": null, "e": 25665, "s": 25657, "text": "Output:" }, { "code": null, "e": 25717, "s": 25665, "text": "Example 2: 3D Mesh example with Alphahull parameter" }, { "code": null, "e": 26697, "s": 25717, "text": "In plotly, the alphahull parameter is used to set the shape of the mesh plot. It Determines how the mesh surface triangles are derived from the set of vertices (points) represented by the x, y, and z arrays, if the i, j, k arrays are not supplied. For general use of mesh3d, it is preferred that i, j, k are supplied. If “-1”, Delaunay triangulation is used, which is mainly suitable if the mesh is a single, more or less layer surface that is perpendicular to delaunayaxis. In case the delaunayaxis intersects the mesh surface at more than one point it will result in triangles that are very long in the dimension of delaunayaxis. If “>0”, the alpha-shape algorithm is used. In this case, the positive alphahull value signals the use of the alpha-shape algorithm, _and_ its value acts as the parameter for the mesh fitting. If 0, the convex-hull algorithm is used. It is suitable for convex bodies or if the intention is to enclose the x, y, and z points set into a convex hull." }, { "code": null, "e": 26706, "s": 26697, "text": "Example:" }, { "code": null, "e": 26714, "s": 26706, "text": "Python3" }, { "code": "import plotly.graph_objects as goimport numpy as np # Data for three-dimensional scattered pointsz = 15 * np.random.random(100)x = np.sin(z) + 0.1 * np.random.randn(100)y = np.cos(z) + 0.1 * np.random.randn(100) fig = go.Figure(data=[go.Mesh3d(x=x, y=y, z=z, color='green', opacity=0.20, alphahull=3)]) fig.show()", "e": 27062, "s": 26714, "text": null }, { "code": null, "e": 27070, "s": 27062, "text": "Output:" }, { "code": null, "e": 27187, "s": 27070, "text": "In mesh tetrahedron i,j, and k parameters can be used to manually specify the geometry of the triangles of the mesh." }, { "code": null, "e": 27196, "s": 27187, "text": "Example:" }, { "code": null, "e": 27204, "s": 27196, "text": "Python3" }, { "code": "import plotly.graph_objects as goimport numpy as np # Data for three-dimensional scattered pointsz = 15 * np.random.random(100)x = np.sin(z) + 0.1 * np.random.randn(100)y = np.cos(z) + 0.1 * np.random.randn(100) fig = go.Figure(data=[go.Mesh3d(x=x, y=y, z=z, color='green', opacity=0.20, alphahull=3, i=[1, 0, 0, 1], j=[1, 2, 3, 4], k=[4, 3, 1, 3],)]) fig.show()", "e": 27694, "s": 27204, "text": null }, { "code": null, "e": 27702, "s": 27694, "text": "Output:" }, { "code": null, "e": 27716, "s": 27702, "text": "Python-Plotly" }, { "code": null, "e": 27723, "s": 27716, "text": "Python" }, { "code": null, "e": 27821, "s": 27723, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27830, "s": 27821, "text": "Comments" }, { "code": null, "e": 27843, "s": 27830, "text": "Old Comments" }, { "code": null, "e": 27871, "s": 27843, "text": "Read JSON file using Python" }, { "code": null, "e": 27921, "s": 27871, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 27943, "s": 27921, "text": "Python map() function" }, { "code": null, "e": 27987, "s": 27943, "text": "How to get column names in Pandas dataframe" }, { "code": null, "e": 28005, "s": 27987, "text": "Python Dictionary" }, { "code": null, "e": 28028, "s": 28005, "text": "Taking input in Python" }, { "code": null, "e": 28060, "s": 28028, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28095, "s": 28060, "text": "Read a file line by line in Python" }, { "code": null, "e": 28117, "s": 28095, "text": "Enumerate() in Python" } ]
How to use singleton class in android?
Before getting into example, we should know what singleton design pattern is. A singleton is a design pattern that restricts the instantiation of a class to only one instance. Notable uses include controlling concurrency and creating a central point of access for an application to access its data store. This example demonstrate about How to use singleton class in android Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version = "1.0" encoding = "utf-8"?> <LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android" xmlns:tools = "http://schemas.android.com/tools" android:layout_width = "match_parent" android:layout_height = "match_parent" tools:context = ".MainActivity" android:orientation = "vertical"> <EditText android:id = "@+id/editText" android:layout_width = "match_parent" android:layout_height = "wrap_content" android:hint = "Enter text" /> <Button android:id = "@+id/save" android:text = "save in singleTone" android:layout_width = "wrap_content" android:layout_height = "wrap_content" /> </LinearLayout> In the above code, we have taken edit Ext and button. When user click on a button, it will take data from edit text and store in a singleton class and display value from singleton class in a toast. Step 3 − Add the following code to src/MainActivity.java package com.example.andy.myapplication; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; public class MainActivity extends AppCompatActivity { EditText editText; Button save; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); editText = findViewById(R.id.editText); save = findViewById(R.id.save); save.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(editText.getText().toString().isEmpty()) { editText.setError("Enter text"); }else{ String editValue = editText.getText().toString(); singleTonExample singletonexample = com.example.andy.myapplication.singleTonExample.getInstance(); singletonexample.setText(editValue); Toast.makeText(MainActivity.this,singletonexample.getText(),Toast.LENGTH_LONG).show(); } } }); } } In the above code, we have used singleTonExample as singleton class so create a call as singleTonExample.java and add the following code- package com.example.andy.myapplication; import java.security.Identity; public class singleTonExample { String editValue; private static final singleTonExample ourInstance = new singleTonExample(); public static singleTonExample getInstance() { return ourInstance; } private singleTonExample() { } public void setText(String editValue) { this.editValue = editValue; } public String getText() { return editValue; } } 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, we have written as tutorialspoint.com” now click on the button it will take data from singleton class and show in the toast as shown below – Click here to download the project code
[ { "code": null, "e": 1367, "s": 1062, "text": "Before getting into example, we should know what singleton design pattern is. A singleton is a design pattern that restricts the instantiation of a class to only one instance. Notable uses include controlling concurrency and creating a central point of access for an application to access its data store." }, { "code": null, "e": 1436, "s": 1367, "text": "This example demonstrate about How to use singleton class in android" }, { "code": null, "e": 1565, "s": 1436, "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": 1630, "s": 1565, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2321, "s": 1630, "text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<LinearLayout xmlns:android = \"http://schemas.android.com/apk/res/android\"\n xmlns:tools = \"http://schemas.android.com/tools\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"match_parent\"\n tools:context = \".MainActivity\"\n android:orientation = \"vertical\">\n <EditText\n android:id = \"@+id/editText\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"wrap_content\"\n android:hint = \"Enter text\" />\n <Button\n android:id = \"@+id/save\"\n android:text = \"save in singleTone\"\n android:layout_width = \"wrap_content\"\n android:layout_height = \"wrap_content\" />\n</LinearLayout>" }, { "code": null, "e": 2519, "s": 2321, "text": "In the above code, we have taken edit Ext and button. When user click on a button, it will take data from edit text and store in a singleton class and display value from singleton class in a toast." }, { "code": null, "e": 2576, "s": 2519, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 3758, "s": 2576, "text": "package com.example.andy.myapplication;\nimport android.support.v7.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.view.View;\nimport android.widget.Button;\nimport android.widget.EditText;\nimport android.widget.Toast;\npublic class MainActivity extends AppCompatActivity {\n EditText editText;\n Button save;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n editText = findViewById(R.id.editText);\n save = findViewById(R.id.save);\n save.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n if(editText.getText().toString().isEmpty()) {\n editText.setError(\"Enter text\");\n }else{\n String editValue = editText.getText().toString();\n singleTonExample singletonexample = com.example.andy.myapplication.singleTonExample.getInstance();\n singletonexample.setText(editValue);\n Toast.makeText(MainActivity.this,singletonexample.getText(),Toast.LENGTH_LONG).show();\n }\n }\n });\n }\n}" }, { "code": null, "e": 3896, "s": 3758, "text": "In the above code, we have used singleTonExample as singleton class so create a call as singleTonExample.java and add the following code-" }, { "code": null, "e": 4356, "s": 3896, "text": "package com.example.andy.myapplication;\nimport java.security.Identity;\npublic class singleTonExample {\n String editValue;\n private static final singleTonExample ourInstance = new singleTonExample();\n public static singleTonExample getInstance() {\n return ourInstance;\n }\n private singleTonExample() { }\n public void setText(String editValue) {\n this.editValue = editValue;\n }\n public String getText() {\n return editValue;\n }\n}" }, { "code": null, "e": 4703, "s": 4356, "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": 4865, "s": 4703, "text": "In the above result, we have written as tutorialspoint.com” now click on the button it will take data from singleton class and show in the toast as shown below –" }, { "code": null, "e": 4905, "s": 4865, "text": "Click here to download the project code" } ]
Hotel Housekeeping - Quick Guide
I consider housekeeping to be the heart of hotels and it is only when something goes wrong that it is recognized – just like our hearts. − Sheila Perera FIH Glenmor Manager, Gleneagles Hotel. The housekeeping department, in any hotel business, contributes to major amount of profit though it is considered as an ancillary service. The simple reason being, a customer demands a clean, tidy, and pleasing ambience. Housekeeping generates the first impression on a guest’s mind. The housekeeping efforts clearly show how the hotel will take care of its guests. Housekeeping means performing all the duties towards cleaning, maintaining orderliness, and running a house or a business property. In case of hotels, the housekeeping duties involve maintaining the hotel to the best possible state in terms of cleanliness, and keeping it at highly desirable ambience. The main objectives of hotel housekeeping are − To maintain overall cleanliness of the entire hotel at all times. To perform cleanliness duties most efficiently and effectively. To use good quality, safe cleaning equipment and chemicals. To manage laundry and linen. To control pests. To keep up the hotel with classy interior decoration. To take care of the furniture, fittings, and fixtures of the entire hotel. To understand the expanse or scope of housekeeping, it is better to understand the divisions of hotel a hotel, first. There are various divisions (or departments) of a hotel. They are given below. It is responsible for guest check-in and check-out, mail and information services, and concierge services such as tour booking, reserving theatre and restaurants, providing airport taxi service, etc. Food and Beverage department is responsible for preparing menus, foods, and managing inventory of food and beverage items. It includes food and beverage preparation and service for restaurant, lounge, coffee shops, bars, parties, and room service. It includes parking and door attendants, drivers, porters, and bell attendants. Housekeeping includes the duties of keeping the areas of the hotel clean, tidy, hygienic, and pleasant. It also performs the duties pertaining to decoration of hotel premises. All sales, services, advertising, promotions, and public relations are taken care of by this team. Security manager and security workers work to keep the property safe and secured from external hazards. It conducts all financial activities like producing bills and receiving payments, computing employees’ compensations and delivering payments. They also carry out the activities such as compiling monthly and annual income statements, depositing and securing cash, and controlling and monitoring assets. The Maintenance department is responsible for the maintenance of the property. It takes care of repairing furniture and fixtures, and painting the required area. When the hotel is small, these works are contracted from an outside agency. It is responsible for keeping all of its equipment operational. The duties include maintaining telephone, hotel management software, internet etc. It is also responsible for implementing any new changes required such as upgrading the software and hardware. Human Resource department is responsible for interviewing and recruiting qualified staff to be placed at appropriate positions. They also conduct exit interviews for the employees who wish to quit the work. HRD works to set wages and salaries based on regional market rates and ensures that the hotel business meets safety and health administration standards. In all these departments, the efforts of housekeeping department are overt. They are directly visible to the guests even before they try food or avail other amenities. Housekeeping creates the first impression about the hotel in the guests’ minds. Hence this department can be said as the heart of the hotel business. The layout of the housekeeping department depends on the total number of Guestrooms, Outlets, and Required Staff. The following areas of the department are the most prominent ones − Office of the Executive Housekeeper − The administrative work of the department is carried out here. Office of the Executive Housekeeper − The administrative work of the department is carried out here. Housekeeping Control Desk −It is accessible and operational 24 hours a day. The housekeeping staff reports at the start and end of the shift here. There are notice boards, storage shelves, registers, lost and found cupboard, and key-hanger matrix. Housekeeping Control Desk −It is accessible and operational 24 hours a day. The housekeeping staff reports at the start and end of the shift here. There are notice boards, storage shelves, registers, lost and found cupboard, and key-hanger matrix. Laundry Area − Washing, ironing, dry cleaning, folding of linen and staff uniform takes place here. Laundry Area − Washing, ironing, dry cleaning, folding of linen and staff uniform takes place here. Linen Room − Here, the linen of the hotel such as bed-sheets, towels, pillow cases, etc., are stored, collected, and carried to the required places in the hotel. Linen Room − Here, the linen of the hotel such as bed-sheets, towels, pillow cases, etc., are stored, collected, and carried to the required places in the hotel. Uniform Room − The staff uniforms are collected, stored, and distributed from here. Uniform Room − The staff uniforms are collected, stored, and distributed from here. Tailor Room − Here, stitching and repairing of linen and uniforms takes place. Tailor Room − Here, stitching and repairing of linen and uniforms takes place. Housekeeping Stores − It is a storage area where the cleaning equipment and items, and guest supplies are securely stored. Housekeeping Stores − It is a storage area where the cleaning equipment and items, and guest supplies are securely stored. Flower Room − It is an air-conditioned room with worktables, sink and water supply, cupboards to store vases and stones, and a counter. Flower Room − It is an air-conditioned room with worktables, sink and water supply, cupboards to store vases and stones, and a counter. Lost and found −stores all the items left by the guests. It directly communicates with the front office desk, as there the guests tend to first enquire about their lost articles. Lost and found −stores all the items left by the guests. It directly communicates with the front office desk, as there the guests tend to first enquire about their lost articles. The housekeeping department is responsible to keep the following areas clean and tidy. Guest Rooms Guest Bathrooms Public Areas such as Lobby and Lifts Banquets and Conference Halls Parking Area Sales and Admin Offices Garden Apart from the cleaning task, the housekeeping is also responsible for handling keys of each floor. In addition, it manages the laundry, which is often at some places considered as a sub-department of housekeeping. It is a multi-course meal or feast, usually given by the host on occasions like a charitable gathering, a ceremony, or a celebration, often precedes or succeeds by honoring speeches. It is a detailed information prepared by the manufacturer or importer of a chemical that describes the physical and chemical properties, health hazards, routes of exposure, precautions for safe handling and use, and first-aid procedures in case any accident happens. The status of room is not ready for selling because of some problem such as clogged basin/toilet, nonfunctioning shower, or broken bed. The supervisor needs to know for how long it will be out of order and is responsible to get it into order as fast as possible. The housekeeping also practices general abbreviations such as As Soon As Possible (ASAP), Not Yet (NY), Follow Up (FU), and For Your Information (FYI), which are also used commonly in the industry. A new broom sweeps clean; but an old broom knows the corners. − An Irish Saying. There is a huge workload on the hotel housekeeping staff. The housekeeping work is carried out at various levels such as managerial level, supervisory level, and operational level. Let us see more about the staff and qualities they should possess. The general structure of housekeeping staff is as shown below − Let us see the work and responsibilities at each level. The Executive Manager is the chief of housekeeping department. The Deputy Housekeeper and Assistant Manager of Housekeeping report to him. Their responsibilities include − Ensuring overall cleanliness and aesthetics of the hotel. Ensuring overall cleanliness and aesthetics of the hotel. Ensuring overall sanitation, comfort, and ambience of the hotel. Ensuring overall sanitation, comfort, and ambience of the hotel. Training the new joiners and motivate the existing employees. Training the new joiners and motivate the existing employees. Modelling and establishing Standard Operating Procedures (SOPs) for cleaning and decorating. Modelling and establishing Standard Operating Procedures (SOPs) for cleaning and decorating. Monitoring regular inventory of guest supplies and linen. Monitoring regular inventory of guest supplies and linen. Monitoring housekeeping equipment and hotel property. Monitoring housekeeping equipment and hotel property. Evaluating employee performance, and handling their training, promotions, and transfers. Evaluating employee performance, and handling their training, promotions, and transfers. Organize flower arrangements for events. Organize flower arrangements for events. Presenting the estimate of the required budget to the General Manager of the hotel. Presenting the estimate of the required budget to the General Manager of the hotel. The supervisors report to the Assistant Housekeeper. Their positions and their respective responsibilities include − Issuing keys to the room attendants. Coordinating floor operations and tray clearance with room attendants. Inspecting rooms for readiness and reporting to the front office for the same. Catering for VIP facilities and providing special supplies such as hot drinking water, baby-sitting provision. Catering for VIP facilities and providing special supplies such as hot drinking water, baby-sitting provision. Ensuring that cleanliness is maintained at all times in public areas such as lobby, lifts, parking, swimming pool, coffee shop, conference hall, banquet hall, and restaurant. Ensuring that cleanliness is maintained at all times in public areas such as lobby, lifts, parking, swimming pool, coffee shop, conference hall, banquet hall, and restaurant. Ensuring banquet and conference halls are well kept and ready. Ensuring the concerned operating staff is available as per the schedule. Ensuring provision of guest supplies such as water, extra bed, fans, or towels. Ensuring provision of guest supplies such as water, extra bed, fans, or towels. Ensuring the operating staff working at night is following all cleaning SOPs. Ensuring the operating staff working at night is following all cleaning SOPs. Supervising hotel area at night and ensuring cleanliness in all areas of hotel. Supervising hotel area at night and ensuring cleanliness in all areas of hotel. Providing clean, ironed, and fresh uniforms to the hotel staff. Suggesting procurement of any uniforms required. Checking repaired linen from tailor room. Keeping track of number and condition of uniforms. Inspecting linen and sending it to the laundry. Checking linen from laundry and sending it for ironing. Maintaining linen influx and out flux register. Checking repaired linen from tailor room. Suggesting linen replacements if required. The positions and responsibilities of the Operating Staff/Attendants are explained below. Collecting uniforms of staff at the end of every shift and maintaining them to be used for the next time. Collecting uniforms of staff at the end of every shift and maintaining them to be used for the next time. Maintaining the shelves of uniforms and linens clearly. Maintaining the shelves of uniforms and linens clearly. Giving and taking back the uniforms from the staff. Giving and taking back the uniforms from the staff. Segregating the dirty linen according to its type and sending it to the laundry. Segregating the dirty linen according to its type and sending it to the laundry. Keeping the track of linen count before and after laundry. Keeping the track of linen count before and after laundry. Stacking towels, bed sheets, pillowcases, table napkins separately into different sections of shelves. Stacking towels, bed sheets, pillowcases, table napkins separately into different sections of shelves. Reporting to the floor supervisor. Cleaning the guest rooms, guest bathrooms, and the corridors. Changing the linen of the guest room and guest bathrooms. Topping up the guest supplies. Making guest-room beds. Replenishing the hotel cleaner’s trolley with supplies and linens for the next shift staff. Replenishing the hotel cleaner’s trolley with supplies and linens for the next shift staff. Reporting to the floor supervisor. Keeping the count of cleaning equipment and items such as cleaners and detergents. Keeping the count of cleaning equipment and items such as cleaners and detergents. Generating requisition to purchase the required material. Reporting to public area supervisor. Keeping the parking, lobbies, guest rooms, lifts, and corridors in best maintained status. Keeping the parking, lobbies, guest rooms, lifts, and corridors in best maintained status. Keeping these areas smelling fresh and clean. Reporting any hotel safety issues to the night supervisor. Performing housekeeping duties during night. There are certain professional qualities the housekeeping staff is required to possess − The housekeeping staff on duty must − Be well-groomed with high degree of personal hygiene. Have trimmed nails and hair, and clean uniform. Have a clean and pleasant appearance. The housekeeping staff must − Conduct themselves with a cooperative attitude. Speak in a friendly but sincere tone. Speak clearly in audible voice of moderate pitch. Maintain polite eye contact while interacting with the hotel guests. For serving the guest and working for cleanliness, the housekeeping staff must Possess right attitude. Have good listening skills to avoid any miscommunication. Be a good team player. The housekeeping staff must − Be able to retain and pursue the demand of the guest until it is fulfilled. Be sincere and physically fit. Respect each hotel guest they are dealing with. They must conduct themselves confidently and courteously. Respect each hotel guest they are dealing with. They must conduct themselves confidently and courteously. Have high integrity. There are practical little things in housekeeping which no man really understands. − Eleanor Roosevelt, American Politician, Diplomat, and Activist. There are various principles followed by the housekeeping staff. They are cleaning and hygiene principles, safety and security principles, comfort and privacy principles, and finally, the decor. For understanding the housekeeping principles, first let us go through what advantages it offers to the hotel. Here are some prominent advantages, the housekeeping department offers to its guests − Clean and hygienic atmosphere Comfortable and convenient stay Privacy Safety and security Provision of amenities Making guests Feel good Having seen the advantages, let us see the principles of housekeeping towards providing these to the guests while working safely. Cleaning is conducted to remove harmful bacteria present in the dust deposited on the hotel property because of air pollution. This may cause unhealthy effects on the working staff as well as the guests. Cleanliness reduces the threat of any infections and offers comfortable stay to the guests in the hotel. The worker must follow the given principles while cleaning − Carry out the cleaning procedures in sequence. Say, sweeping → Dusting → Mopping/Suction Cleaning → Disinfecting → Air Freshening. Carry out the cleaning procedures in sequence. Say, sweeping → Dusting → Mopping/Suction Cleaning → Disinfecting → Air Freshening. Must take care while cleaning and polishing; not to damage various surfaces and hamper their appearance. Must take care while cleaning and polishing; not to damage various surfaces and hamper their appearance. Should start cleaning from extreme inner end continuing towards exit. Should start cleaning from extreme inner end continuing towards exit. Should park the chambermaid’s trolley such that it leaves space for corridor traffic. Should park the chambermaid’s trolley such that it leaves space for corridor traffic. Must take proper precautions while handling cleaning equipment, detergents, and guest luggage. Must take proper precautions while handling cleaning equipment, detergents, and guest luggage. Must remove hard water stains and spider webs as soon as they occur. Must remove hard water stains and spider webs as soon as they occur. Must never use guest room linen for cleaning or blocking room entry. Must never use guest room linen for cleaning or blocking room entry. The workers must follow the safety rules mentioned below − Protect their body from harmful chemicals by wearing thick gloves. Protect their body from harmful chemicals by wearing thick gloves. Protect their eyes by wearing masks or goggles if required. Protect their eyes by wearing masks or goggles if required. Must use caution sign to mark wet floors. Must use caution sign to mark wet floors. Clean spilled liquids immediately to reduce chances of slipping. Clean spilled liquids immediately to reduce chances of slipping. Handle cleaning chemicals carefully while transporting, disposing, or refilling the containers. Handle cleaning chemicals carefully while transporting, disposing, or refilling the containers. Mix any chemicals required in the presence of proper ventilation. Mix any chemicals required in the presence of proper ventilation. Must not open unlabeled chemical containers. Must not open unlabeled chemical containers. Use swivel head mops to avoid inappropriate body posture while cleaning. Use swivel head mops to avoid inappropriate body posture while cleaning. Wear close toe-non slip footwear while working. Wear close toe-non slip footwear while working. Use appropriate body postures while working to avoid cramps. Use appropriate body postures while working to avoid cramps. Request for peer assistance while moving heavy loads such as furniture. Request for peer assistance while moving heavy loads such as furniture. Report to the supervisor in case of any accident due to mishandling of flammable liquids or otherwise. Report to the supervisor in case of any accident due to mishandling of flammable liquids or otherwise. Keep the guests safe with the help of security department. Keep the guests safe with the help of security department. Keep the guests’ documents, ornaments, or other articles safe. Keep the guests’ documents, ornaments, or other articles safe. The housekeeping staff must follow the given principles with regard to comfort and privacy of the guest. Always remember comfort and privacy of the guests always comes first. Always remember comfort and privacy of the guests always comes first. Clean the premises or rooms in the least destructive and disturbing manner. Clean the premises or rooms in the least destructive and disturbing manner. Enter the guest rooms by following appropriate procedure. Enter the guest rooms by following appropriate procedure. Work towards the guests’ satisfaction. Work towards the guests’ satisfaction. The housekeeping staff needs to know various types of fires and fire extinguishers. The staff must be trained to handle small fires. Fire is classified into the following types − Class A − Class A fire consists of ordinary combustibles such as wood, paper, trash or anything else that leaves ash behind. It needs water under high pressure to extinguish this fire. Class A − Class A fire consists of ordinary combustibles such as wood, paper, trash or anything else that leaves ash behind. It needs water under high pressure to extinguish this fire. Class B − This fire occurs in inflammable liquids such as oil and grease, and needs blankets or sand to extinguish. Class B − This fire occurs in inflammable liquids such as oil and grease, and needs blankets or sand to extinguish. Class C − This fire occurs in electrical equipment. Use of non-conductive agent is required for extinguishing this fire. Class C − This fire occurs in electrical equipment. Use of non-conductive agent is required for extinguishing this fire. Class K − Class K Fires are fires that involve cooking oils, grease or animal fat and can be extinguished using Purple K, a typical agent found in kitchen or galley extinguishers. Class K − Class K Fires are fires that involve cooking oils, grease or animal fat and can be extinguished using Purple K, a typical agent found in kitchen or galley extinguishers. Soda Acid extinguisher is used to put out class A fire. It sprays the compound with gaseous pressure. Only good for small intensity fires. For large intensity and widely spread fire, water must be sprayed directly on the affected area with high pressure through the hoses. For putting out class B fires, Carbon Di-Oxide extinguishers are used. Carbon Di-Oxide fog extinguishers are well-places in case of small class C fires. The housekeeping staff must place appropriate extinguishers near the fire prone areas and must know to operate them under challenging conditions. The housekeeping staff is responsible for creating pleasant ambience in the hotel. This needs aesthetic sense and an eye for detail. A guest is keen to visit the hotel if he finds classy and catchy ambience with fresh air. Housekeeping staff must intelligently use artificial waterfalls, large vases with neat and eye-catching flower arrangements, paintings, wall pieces, murals, lighting with appropriate luminance, candles, electric lamps or any rare antic pieces. The housekeeping staff is required to know various materials such as wood, organic and artificial fibers, stone, sand, glass, plastic, and pigments to maintain the expensive hotel property. Hotel decors can be conducted thematically depending on the local/international prominent festivals and cultures. Décor is yet another important task that elevates guests’ experience with the hotel. The housekeepers represent the hotel staff and create an image of the hotel by working towards keeping the hotel at high standards plus conducting themselves well while on job. There are certain rules the housekeepers need to follow. The housekeepers must − Enter the floor with clean and tidy uniform, in a properly groomed manner. Enter the floor with clean and tidy uniform, in a properly groomed manner. Only use the service lifts. Only use the service lifts. Speak to the other working staff only when necessary. Speak to the other working staff only when necessary. Not walk by stamping the feet, run, or jump in the hotel premises. Not walk by stamping the feet, run, or jump in the hotel premises. Eat only in meal hours, not while cleaning. Eat only in meal hours, not while cleaning. Stand outside the guest room while speaking to the guest to respect their privacy. Stand outside the guest room while speaking to the guest to respect their privacy. Always keep the room doors open while cleaning. Always keep the room doors open while cleaning. Greet the guests with smile according to the time of the day. Greet the guests with smile according to the time of the day. Never answer the guest room phone. Never answer the guest room phone. Never use guest room phone of floor desk phones for making private calls. Never use guest room phone of floor desk phones for making private calls. Never use guest bathrooms. Never use guest bathrooms. Familiarize themselves with the faces of guests. This is especially important for the security purpose. Familiarize themselves with the faces of guests. This is especially important for the security purpose. Never use a guest room for unauthorized person. Never use a guest room for unauthorized person. Not accept any gift from the guests and politely deny them. If the guest insists to take and feels offended on denial, then mention the gift to the floor supervisor who can permit the attendant to take the gift out of the hotel. Not accept any gift from the guests and politely deny them. If the guest insists to take and feels offended on denial, then mention the gift to the floor supervisor who can permit the attendant to take the gift out of the hotel. Chilling out on the bed in your hotel room watching television while wearing your own pajamas, is sometimes the best part of your vacation. − Laura Marano, an American Actress. Housekeeping is the primary task the hotels need to cater for while providing service to its guests. The hotel management and especially executive of housekeeping department must ensure that the housekeeping functions are performed well in the hotel irrespective of the target guest type, size of hotel, and its location. The guest rooms are the primary source of hotel revenue. There are higher chances of retaining the guests if the guest rooms are absolutely clean. The hotels can be categorized depending upon their size, location, target market, and ownership. Hotels are categorized by the number of rooms to which service is provided. For example − Below 200 rooms – Very Small Up to 200 rooms – Small 200 to 399 rooms – Medium 400 to 700 rooms – Large More than 700 rooms – Mega This category is useful if the management needs to compare different hotels within the same size. They are categorized by considering their location with respect to city. Airport Hotels − They are located near airport. The guests in transit use them for short stay. Airport Hotels − They are located near airport. The guests in transit use them for short stay. Boatels − They are on the houseboats such as Shikara in Kashmir. Boatels − They are on the houseboats such as Shikara in Kashmir. City Center − Located in the heart of the city near commercial area. City Center − Located in the heart of the city near commercial area. Motel − They are small hotels usually located on highways. Transit guests use them. Motel − They are small hotels usually located on highways. Transit guests use them. Suburb Hotels − They are located near urban area. Budget guests use them. Suburb Hotels − They are located near urban area. Budget guests use them. Floating Hotels − They are on the cruise ships, large lakes, or rivers. Floating Hotels − They are on the cruise ships, large lakes, or rivers. Resorts − They are on the beaches, mountains, islands, or on the river banks. Resorts − They are on the beaches, mountains, islands, or on the river banks. Rotels − They are hotels on wheels such as Deccan Odyssey train. Rotels − They are hotels on wheels such as Deccan Odyssey train. Self-Catering Hotels − They are located at the same premises where the owner stays. Self-Catering Hotels − They are located at the same premises where the owner stays. Here, the hotels are categorized depending upon the target market they serve. Airport Hotels − They target the business clientele, airline passengers, or any guests with cancelled or delayed flights. Airport Hotels − They target the business clientele, airline passengers, or any guests with cancelled or delayed flights. Business Hotels − They primarily cater for the guests who are on business travel. Business Hotels − They primarily cater for the guests who are on business travel. Bed and Breakfast (B&B) − They are small hotels who target guests in transit or on leisure tour. The owner of B&B usually stays in the same premises and is responsible for serving breakfast to the guests. Bed and Breakfast (B&B) − They are small hotels who target guests in transit or on leisure tour. The owner of B&B usually stays in the same premises and is responsible for serving breakfast to the guests. Casino Hotels − They target the guests interested in gambling. Their functions of housekeeping is primary but food and beverage functions are just supportive. Casino Hotels − They target the guests interested in gambling. Their functions of housekeeping is primary but food and beverage functions are just supportive. Resorts − They target high-income busy professionals who wish to spend time away from city, noise, and crowd. They offer facilities such as spa, tennis court, fitness and center, sailing, snorkeling, and swimming. Resorts − They target high-income busy professionals who wish to spend time away from city, noise, and crowd. They offer facilities such as spa, tennis court, fitness and center, sailing, snorkeling, and swimming. Self-Catering Hotels − They target long stayers who prefer to cook themselves. They offer a small kitchen and kitchen amenities with the guest room. Self-Catering Hotels − They target long stayers who prefer to cook themselves. They offer a small kitchen and kitchen amenities with the guest room. Service Apartments − They are located in residential colonies. They provide long-term accommodation for guests. They need to execute an agreement with the guests for the stay of at least one month. All basic amenities such as kitchen, washing machine, dish washer, and beds are provided with once a week housekeeping service. Service Apartments − They are located in residential colonies. They provide long-term accommodation for guests. They need to execute an agreement with the guests for the stay of at least one month. All basic amenities such as kitchen, washing machine, dish washer, and beds are provided with once a week housekeeping service. Suite Hotels − These hotels offer a living room and an en suite bedroom. The professionals who need to interact with their clients/customers find these hotels a good choice because they can interact with their guests in small meetings without any interruption and sacrificing privacy. Suite Hotels − These hotels offer a living room and an en suite bedroom. The professionals who need to interact with their clients/customers find these hotels a good choice because they can interact with their guests in small meetings without any interruption and sacrificing privacy. B&B and Self Catering hotels are generally family owned hotels and are not governed or run by corporate policies and procedures. A chain of hotels or group of hotels such as Taj, Ramada, can have management affiliation with their other properties in the same group. They strictly are governed by predetermined policies. The star rating system is a guideline for a customer that denotes what to expect from the hotel service at the time of booking. However, there is no clear distinguishing method to divide hotels into various star rating categories till today; but a guest can assume that more the number of stars, more is the luxury provided by the hotel. One Star − A guest can expect a small hotel operated and managed by the owner and family. The ambience as more personal and the guest rooms with basic amenities. The restaurant would be at a walking distance. There would be a small commercial area and a nearby public transportation hub. One Star − A guest can expect a small hotel operated and managed by the owner and family. The ambience as more personal and the guest rooms with basic amenities. The restaurant would be at a walking distance. There would be a small commercial area and a nearby public transportation hub. Two-Star − These hotels are mostly part of a chain of hotels that offer consistent quality but limited amenities. They are either small or medium size hotels with a phone and TV. They lack the convenience of room service, but provide a small on-site restaurant at a walking distance within the hotel premises. Two-Star − These hotels are mostly part of a chain of hotels that offer consistent quality but limited amenities. They are either small or medium size hotels with a phone and TV. They lack the convenience of room service, but provide a small on-site restaurant at a walking distance within the hotel premises. Three-Star − These hotels are usually located near a major business center, express way, and/or shopping area. The rooms are clean and spacious rooms, and decorative lobbies. An on-site restaurant offers all meals such as breakfast, lunch, and dinner. The facilities such as valet and room service, fitness center, and a swimming pool are also available. Three-Star − These hotels are usually located near a major business center, express way, and/or shopping area. The rooms are clean and spacious rooms, and decorative lobbies. An on-site restaurant offers all meals such as breakfast, lunch, and dinner. The facilities such as valet and room service, fitness center, and a swimming pool are also available. Four-Star − This hotel would be large, often standing as a part of a cluster of similar hotels with a formal appearance and very good services. The hotel would be located in the prime area of the city around shopping, dining, and entertainment joints. The guest can expect furnished and clean rooms, restaurants, room service, valet parking, and a fitness center within the hotel premises. Four-Star − This hotel would be large, often standing as a part of a cluster of similar hotels with a formal appearance and very good services. The hotel would be located in the prime area of the city around shopping, dining, and entertainment joints. The guest can expect furnished and clean rooms, restaurants, room service, valet parking, and a fitness center within the hotel premises. Five-Star − This hotel would be large and luxurious, which offers the highest degree of room and personal service. It is built with beautiful architecture, and is managed keeping elegance and style in mind. The guest rooms are equipped with high quality linens, TV, bathtubs, and special outside view from the room. The hotel provides multiple eating joints in its premises such as coffee shops, restaurants, poolside snack joint, and bar. They also provide 24X7 room service, valet service, and personal protection service. Five-Star − This hotel would be large and luxurious, which offers the highest degree of room and personal service. It is built with beautiful architecture, and is managed keeping elegance and style in mind. The guest rooms are equipped with high quality linens, TV, bathtubs, and special outside view from the room. The hotel provides multiple eating joints in its premises such as coffee shops, restaurants, poolside snack joint, and bar. They also provide 24X7 room service, valet service, and personal protection service. The condition of guest rooms maintained by housekeeping is the most vital factor as far as the customer satisfaction in the hotel business is concerned. Single Room − A room with the facility of single bed. It is meant for single occupancy. It has an attached bathroom, a small dressing table, a small bedside table, and a small writing table. Sometimes it has a single chair too. Single Room − A room with the facility of single bed. It is meant for single occupancy. It has an attached bathroom, a small dressing table, a small bedside table, and a small writing table. Sometimes it has a single chair too. Double Room − A room with the facility of double bed. There are two variants in this type depending upon the size of the bed King Double Room (with king size double bed) Queen Double Room (with queen size double bed) It is equipped with adequate furniture such as dressing table and a writing table, a TV, and a small fridge. Double Room − A room with the facility of double bed. There are two variants in this type depending upon the size of the bed King Double Room (with king size double bed) Queen Double Room (with queen size double bed) It is equipped with adequate furniture such as dressing table and a writing table, a TV, and a small fridge. Deluxe Room − They are available in Single Deluxe and Double Deluxe variants. Deluxe room is well furnished. Some amenities are attached bathroom, a dressing table, a bedside table, a small writing table, a TV, and a small fridge. The floor is covered with carpet and most suitable for small families. Deluxe Room − They are available in Single Deluxe and Double Deluxe variants. Deluxe room is well furnished. Some amenities are attached bathroom, a dressing table, a bedside table, a small writing table, a TV, and a small fridge. The floor is covered with carpet and most suitable for small families. Double-Double (Twin Double) Room − This room provides two double beds with separate headboards. It is ideal for a family with two children below 12 years. Double-Double (Twin Double) Room − This room provides two double beds with separate headboards. It is ideal for a family with two children below 12 years. Twin Room − This room provides two single beds with separate headboards. It is meant for two independent people. It also has a single bedside table shared between the two beds. Twin Room − This room provides two single beds with separate headboards. It is meant for two independent people. It also has a single bedside table shared between the two beds. Hollywood Twin Room − This room provides two single beds with a common headboard. If a need arises, the two beds can be brought together to form a double bed. Hollywood Twin Room − This room provides two single beds with a common headboard. If a need arises, the two beds can be brought together to form a double bed. Duplex Room − This type is composed of two rooms located on two different floors, connected with internal stairs. Duplex Room − This type is composed of two rooms located on two different floors, connected with internal stairs. Cabana − This type of room faces water body, beach, or a swimming pool. It generally has a large balcony. Cabana − This type of room faces water body, beach, or a swimming pool. It generally has a large balcony. Studio − They are twin adjacent rooms: A living room with sofa, coffee table and chairs, and a bedroom. It is also equipped with fan/air conditioner, a small kitchen corner, and a dining area. The furniture is often compact. Studio − They are twin adjacent rooms: A living room with sofa, coffee table and chairs, and a bedroom. It is also equipped with fan/air conditioner, a small kitchen corner, and a dining area. The furniture is often compact. Lanai − This room faces a landscape, a waterfall, or a garden. Lanai − This room faces a landscape, a waterfall, or a garden. Suite −It is composed of one or more bedrooms, a living room, and a dining area. It is excellent for the guests who prefer more space, wish to entertain their guests without interruption and giving up privacy.There are various types of suites − Regular Suite − Best for business travelers. Penthouse Suite − Luxurious than the regular suite. It is provided with the access to terrace space above the suite. It is aloof from crowd and provides abird’s eye view of the city. It has all the amenities and structure similar to a regular suite. Presidential Suite − The best possible suite in the hotel. Suite −It is composed of one or more bedrooms, a living room, and a dining area. It is excellent for the guests who prefer more space, wish to entertain their guests without interruption and giving up privacy.There are various types of suites − Regular Suite − Best for business travelers. Regular Suite − Best for business travelers. Penthouse Suite − Luxurious than the regular suite. It is provided with the access to terrace space above the suite. It is aloof from crowd and provides abird’s eye view of the city. It has all the amenities and structure similar to a regular suite. Penthouse Suite − Luxurious than the regular suite. It is provided with the access to terrace space above the suite. It is aloof from crowd and provides abird’s eye view of the city. It has all the amenities and structure similar to a regular suite. Presidential Suite − The best possible suite in the hotel. Presidential Suite − The best possible suite in the hotel. Sico − This is a kind of multipurpose room, which can be used as a meeting room during the day and as a bedroom during the night. These rooms have special beds called Murphy Bed that can be folded entirely against a wall. This bed may or may not have headboard. The lower face of the bed which becomes visible after folding or placing upright, has a decorative wall paper, mirror, or a painting. After folding the bed, the room can accommodate sitting for five to ten people. Sico − This is a kind of multipurpose room, which can be used as a meeting room during the day and as a bedroom during the night. These rooms have special beds called Murphy Bed that can be folded entirely against a wall. This bed may or may not have headboard. The lower face of the bed which becomes visible after folding or placing upright, has a decorative wall paper, mirror, or a painting. After folding the bed, the room can accommodate sitting for five to ten people. VIP amenities are always something like the cherry on the cake. The VIPs are treated with extra attention, pamper, and care. Hotels provide the following amenities to the VIPs depending upon their policies − Executive Front Desk or Executive Housekeeper escorting the guest up to the room. Executive Front Desk or Executive Housekeeper escorting the guest up to the room. A welcome document kit containing note from a General Manager (GM) of the hotel, spa card, and a hotel map. A welcome document kit containing note from a General Manager (GM) of the hotel, spa card, and a hotel map. Complete housekeeping service with daily linen change. Complete housekeeping service with daily linen change. A snack kit often containing packed snacks, assorted nuts, fruits, cheese, or cookies, and beverages. A snack kit often containing packed snacks, assorted nuts, fruits, cheese, or cookies, and beverages. A vanity kit containing cotton balls, makeup removers, lip balm, and au-de-cologne. A vanity kit containing cotton balls, makeup removers, lip balm, and au-de-cologne. A bathroom kit with soap dispenser, upgraded robe, tissue box, face mist, after-shower gel, cotton slippers, toilet mat, and a terry mat. A bathroom kit with soap dispenser, upgraded robe, tissue box, face mist, after-shower gel, cotton slippers, toilet mat, and a terry mat. In special cases, a romance kit containing a bottle of wine or Champaign, paired with chocolate dipped strawberries or bite size chocolates. In special cases, a romance kit containing a bottle of wine or Champaign, paired with chocolate dipped strawberries or bite size chocolates. Small bag packs for the kids below 12 years. Small bag packs for the kids below 12 years. A number of servings of award winning dessert. A number of servings of award winning dessert. Spring cleaning doesn’t have to be a dreaded list of chores. It can be a rewarding experience that helps provide some structure and organization in your life. − Peter Walsh, Professional Organizer, Writer, and Media Personality. Cleaning is one of the major tasks the housekeeping force performs. It carries out cleanings when the guests are about to occupy their room, while they are staying in the hotel, and immediately after the guests vacate the room. The housekeeping also cleans the public area, which is often shared by a large number of guests. The Check in rooms are cleaned when the guest is about to occupy the room. A checklist of room readiness is shared between the guest room supervisor and the guest room attendants. The supervisor inspects the readiness of the room for occupancy. The guest room attendant performs the following cleanings − Checking power switches, air conditioner, TV, and other electronic appliances for healthy condition. Checking power switches, air conditioner, TV, and other electronic appliances for healthy condition. Making bed with the fresh linen, pillow cases, and bedside mat. Making bed with the fresh linen, pillow cases, and bedside mat. Cleaning ashtrays and dustbins, replacing if required; and putting fresh paper stripes. Cleaning ashtrays and dustbins, replacing if required; and putting fresh paper stripes. Checking stationery and vanity supplies.Replacing/refilling if required. Checking stationery and vanity supplies.Replacing/refilling if required. Cleaning the bathroom: floor, walls, toilet, shower area, and tub. Cleaning the bathroom: floor, walls, toilet, shower area, and tub. Checking bathroom supplies. Replacing the used supplies with the new ones. Checking bathroom supplies. Replacing the used supplies with the new ones. Checking the room curtains and drapes for stains, replacing if needed, and closing. Checking the room curtains and drapes for stains, replacing if needed, and closing. Discarding the used supplies in the guest room. Discarding the used supplies in the guest room. Spraying the room freshener. Spraying the room freshener. The room is cleaned when the guest is occupying the room. It includes cleaning and keeping all occupied rooms twice per day on guests’ requests and convenience. Entering the guest room by following the set procedure. Entering the guest room by following the set procedure. Clearing the dustbins. Clearing the dustbins. Collecting the used linen and putting it in the linen bag. Collecting the used linen and putting it in the linen bag. Making the bed. Making the bed. Carrying out the guest room dusting. Carrying out the guest room dusting. Vacuuming of carpet and bedside mats. Vacuuming of carpet and bedside mats. Cleaning the bathroom and replenishing the bathroom supplies. Cleaning the bathroom and replenishing the bathroom supplies. Checking the functionality of light bulbs, television, electric kettle, and intercom device. Checking the functionality of light bulbs, television, electric kettle, and intercom device. This cleaning is performed when the guest vacates the guest room and proceeds for hotel check-out formalities. The cleaning involves − Assembling bed, chairs, settees, and other furniture and placing it appropriately. Assembling bed, chairs, settees, and other furniture and placing it appropriately. Wiping guest room floor with wet mop. Wiping guest room floor with wet mop. Cleaning the writing tables, assembling and placing stationery appropriately. Cleaning the writing tables, assembling and placing stationery appropriately. Checking under the beds and chairs, and in the locker for any articles the guest left behind. Checking under the beds and chairs, and in the locker for any articles the guest left behind. All personal stuff, documents, articles left in the room (if any) are removed and deposited to Lost and Found desk. All personal stuff, documents, articles left in the room (if any) are removed and deposited to Lost and Found desk. Cleaning all walls of bathroom with wet wipe. Cleaning all walls of bathroom with wet wipe. Cleaning all electric appliances such as microwave, fan, refrigerator and others. Cleaning all electric appliances such as microwave, fan, refrigerator and others. Keeping heaters/air conditioners at lowest power consuming option. Keeping heaters/air conditioners at lowest power consuming option. Switching off the room light and television. Switching off the room light and television. Locking the guest room door and cleaning area outside it. Locking the guest room door and cleaning area outside it. Depositing the keys at front office desk. Depositing the keys at front office desk. The task of cleaning is very exhausting. It is divided among a number of housekeeping staff depending upon expertise. Some cleaning such as occupied guest room cleaning requires to be carried out twice on daily basis. The check-in and check-out cleanings are little less frequent. Further, the cleaning of air-conditioner and refrigerator is less frequent. Thus, depending upon frequency of use of a particular area or device, the frequency of cleaning varies. This type of cleaning is practiced in the hotels located in cold as well as warm regions. The name depicts cleaning the house in the first few warm days of spring when there is adequate sunlight to reach the corners and the floors of the room. The areas, which are not much accessed, are also cleaned during the Spring Cleaning. Spring cleaning is generally performed once a year by moving furniture and cleaning the guest rooms entirely for dust, stains, broken furniture, and garbage. It is also called as Deep Cleaning as it is ensured that no portion of the area is left uncleaned. The public areas are shared commonly among guests. They include − Front Office and Lobby is highly frequented. It must be clean at all hours of the day. The housekeeping staff needs to clean desks, fans, ceiling, chairs, and computers. The staff also cleans and disinfects the telephone devices, keyboards, flooring, corridors, and glass doors at the entrance of the lobby. The dining area is the next most frequently visited area. The housekeeping staff puts in good efforts for lighting, chandeliers, and cleaning the ceiling, furniture, and décor items. It also includes spreading the clean dining linen on the dining tables and keeping the floor clean. It is generally done when the area is not busy. The house keeping staff cleans lifts preferably early morning to avoid rush for use. They stop it at the ground floor, its doors are kept open, and it is then cleaned starting from top and working towards bottom. Cleaning of the swimming pools is highly required during summer. It can be conducted by the hotel if it has an in-house expertise, or it can be contracted with an agency. Cleaning of swimming pool involves catching any leaves, purifying the pool water, and cleaning the areas surrounding the pool; including shower and changing rooms. These days, the hotels keep their private team of gardeners. Watering and trimming the trees and shrubs, fertilizing the plants, raking the fall leaves, and Arbosculpture (an art of shaping trees into wonderful shapes), is taken care by this team. It mostly involves hard sweeping the parking space, removing the cobwebs under the parking shades, and putting up appropriate guiding signs. My father was a general manager with Hyatt, so we lived in the hotel so he would be close by if there were any problems. My mum was always adamant about us not abusing it. So I still had to clean my room. Housekeeping would never come and do it. − Dianna Agron, American Actress, Singer, and Dancer. The housekeeping staff needs to clean various guest rooms, guest bathrooms, and a number of public areas in the hotel. The staff needs to take the help of various cleaning equipment while trying to keep the hotel premises to the highest standard of appearance. Today, there is a wide range of cleaning products available in the market. The cleaning equipment are advantageous in multiple ways − Equally effective for general as well as tougher cleaning tasks. Equally effective for general as well as tougher cleaning tasks. High cleaning capability. High cleaning capability. Reduce work fatigue and increaseproductivity. Reduce work fatigue and increaseproductivity. Save the time of hotel housekeeping staff. Save the time of hotel housekeeping staff. High maneuverability.They can reach any corner or height of the room, which is otherwise difficult to reach. High maneuverability.They can reach any corner or height of the room, which is otherwise difficult to reach. Eco-friendly, widely available, and easy to operate. Eco-friendly, widely available, and easy to operate. They give protection from injuries occurring while cleaning when they are handled by using proper instructions. They give protection from injuries occurring while cleaning when they are handled by using proper instructions. There are broadly categorized as follows − As the name suggests, they are used manually to keep the surfaces clean. Some commonly used manual equipment are − Abrasives − They are the sharpening stones or grit papers used to polish metal or wooden surfaces. There are various abrasives depending upon the size of grit and adhesion of grit particles on the paper. Abrasives − They are the sharpening stones or grit papers used to polish metal or wooden surfaces. There are various abrasives depending upon the size of grit and adhesion of grit particles on the paper. Brushes − They are handheld flat brushes with bristles to dust the plain surfaces as well as the corners. They come with non-slip handles and stiff scratch-free bristles. They help removing stubborn dust. Brushes − They are handheld flat brushes with bristles to dust the plain surfaces as well as the corners. They come with non-slip handles and stiff scratch-free bristles. They help removing stubborn dust. Chambermaid’s Trolley/Housekeeping Trolley − This trolley is large enough to keep all the guest room and guest bathroom supplies in an organized manner. It makes the housekeeping staff to move it around and carry large number of items in one go while keeping and cleaning the guest rooms. Chambermaid’s Trolley/Housekeeping Trolley − This trolley is large enough to keep all the guest room and guest bathroom supplies in an organized manner. It makes the housekeeping staff to move it around and carry large number of items in one go while keeping and cleaning the guest rooms. Dustbins − They are used to collect daily garbage produced in the hotel. Dustbins − They are used to collect daily garbage produced in the hotel. Dusting Cloths − They are soft cloths used for wiping the surface dust. Dusting Cloths − They are soft cloths used for wiping the surface dust. Dustpans − They are used to collect dust and garbage from the floor and putting it into the dustbin. Dustpans − They are used to collect dust and garbage from the floor and putting it into the dustbin. Janitor’s trolley − It is a trolley that stores cleaning supplies such as detergents, spray bottles, dustbin, mop, and dusting cloths, all in a compact manner. It can be moved around easily. It fulfills the challenge of modern day housekeeping in hotels. Janitor’s trolley − It is a trolley that stores cleaning supplies such as detergents, spray bottles, dustbin, mop, and dusting cloths, all in a compact manner. It can be moved around easily. It fulfills the challenge of modern day housekeeping in hotels. Mops − There are various types of mops such as string mops, flat mops, dust mops, and synthetic mops. Mops are generally made of flat cotton strings or heavy-duty sponges fixed on the metal frames. The cotton mops have high absorbing ability but need more care unlike the synthetic mops that offer almost zero absorbing ability and very less maintenance. Mops − There are various types of mops such as string mops, flat mops, dust mops, and synthetic mops. Mops are generally made of flat cotton strings or heavy-duty sponges fixed on the metal frames. The cotton mops have high absorbing ability but need more care unlike the synthetic mops that offer almost zero absorbing ability and very less maintenance. Mop Wringer trolley − A mop bucket cart (or mop trolley) is a wheeled bucket that allows its user to wring out a wet mop without getting the hands dirty. The mops are squeezed between two surfaces to remove dirty water from it. Mop Wringer trolley − A mop bucket cart (or mop trolley) is a wheeled bucket that allows its user to wring out a wet mop without getting the hands dirty. The mops are squeezed between two surfaces to remove dirty water from it. Scarifying machine − It is used for keeping gardens, golf courts, and lawn in the hotel premises. It cuts through the turf, and removes moss and dead grass. It helps grow spongy lawn. Scarifiers have fixed knife blades attached to the rotary cylinder. They cut through the grass by which the offshoots are separated into lots of individual plants. This helps to thicken up the turf and improve its health. Scarifying machine − It is used for keeping gardens, golf courts, and lawn in the hotel premises. It cuts through the turf, and removes moss and dead grass. It helps grow spongy lawn. Scarifiers have fixed knife blades attached to the rotary cylinder. They cut through the grass by which the offshoots are separated into lots of individual plants. This helps to thicken up the turf and improve its health. Spray Bottles − They are used to spray water or chemical solutions on the surface that needs cleaning. They are also used to spray water on the delicate flowers or leaves of flower arrangement. Spray Bottles − They are used to spray water or chemical solutions on the surface that needs cleaning. They are also used to spray water on the delicate flowers or leaves of flower arrangement. As the name depicts, these equipment require electrical power to operate. They are operated either on AC power or on the battery. Some important electric equipment are − Box Sweeper − It is electric sweeper that consists of a friction brush. The brush often is fit to revolve vertically or horizontally, when the equipment moves on the surface. It can clean floors as well as carpets. The wider the better is the box sweeper brush. Box Sweeper − It is electric sweeper that consists of a friction brush. The brush often is fit to revolve vertically or horizontally, when the equipment moves on the surface. It can clean floors as well as carpets. The wider the better is the box sweeper brush. Vacuum Cleaner − It is again a majorly used equipment in hotel housekeeping. It comes with a suction motor fit in a case, a hose, and various attachment for delicate as well as tough cleaning requirements. Vacuum Cleaner − It is again a majorly used equipment in hotel housekeeping. It comes with a suction motor fit in a case, a hose, and various attachment for delicate as well as tough cleaning requirements. Polishing Machine − They are used to add a shine to the floors of most frequented areas of the hotel. Polishing Machine − They are used to add a shine to the floors of most frequented areas of the hotel. Scrubber − It is a floor care accessory that comes with handheld electrically operated scrubber. It is used where only mopping doesn’t suffice. It can scrub stubborn and sticky stains on the floors of cafeterias, restaurants, lobbies, and fitness areas where people can take food and beverages. Scrubber − It is a floor care accessory that comes with handheld electrically operated scrubber. It is used where only mopping doesn’t suffice. It can scrub stubborn and sticky stains on the floors of cafeterias, restaurants, lobbies, and fitness areas where people can take food and beverages. Vapor Cleaning Machine − They are used where the chemical odors are not desired. They are equipped for continuous operation. They heat up quickly and work with low amount of moisture. They kill the beg bugs and their eggs, the yielding a completely clean environment. Vapor Cleaning Machine − They are used where the chemical odors are not desired. They are equipped for continuous operation. They heat up quickly and work with low amount of moisture. They kill the beg bugs and their eggs, the yielding a completely clean environment. Apart from water and regular detergents, the housekeeping staff also uses cleaning chemicals, which are often available in the form of liquids, blocks, and powders. Water − It is the most commonly used medium for cleaning and rinsing. The housekeeping staff needs to use only soft water because hard water cannot dilute detergents properly. Non-oily and non-greasy stains such as ink stains can be removed using water. Water − It is the most commonly used medium for cleaning and rinsing. The housekeeping staff needs to use only soft water because hard water cannot dilute detergents properly. Non-oily and non-greasy stains such as ink stains can be removed using water. Vinegar − It is used in removing light stains in the bath. Vinegar − It is used in removing light stains in the bath. Bathroom Cleaners − They come in liquid form for easy cleaning. They clean, descale, and disinfect the bathroom walls, bathtubs, bathroom flooring, sinks, and showers. They often contain phosphoric acid. Bathroom Cleaners − They come in liquid form for easy cleaning. They clean, descale, and disinfect the bathroom walls, bathtubs, bathroom flooring, sinks, and showers. They often contain phosphoric acid. Clean Air Sprays − They are best for freshening the hotel corridors, washrooms, bathrooms, and reception areas. These sprays remove the pungent smell of tobacco, smoke, and organic wastes. Clean Air Sprays − They are best for freshening the hotel corridors, washrooms, bathrooms, and reception areas. These sprays remove the pungent smell of tobacco, smoke, and organic wastes. Degreaser − This is mainly used in bars to remove the marks of grease and lipstick that cannot be removed by traditional washing of glasses and cups. Degreaser restores the surface shine and transparency of the glasses and bowls. Degreaser − This is mainly used in bars to remove the marks of grease and lipstick that cannot be removed by traditional washing of glasses and cups. Degreaser restores the surface shine and transparency of the glasses and bowls. Floor Cleaners and Sealers − One of the important tasks of hotel housekeeping is cleaning the floor periodically and keeping it sealed with the help of sealer of the right consistency for optimum maintenance. Some areas in the hotel are busy and bear heavy traffic such as lobby, corridors, parking areas, restaurants, and dining halls. Their floorings loses smoothness and shine. In such a case, the floor cleaners and sealers are used for restoring their look and shine. Floor Cleaners and Sealers − One of the important tasks of hotel housekeeping is cleaning the floor periodically and keeping it sealed with the help of sealer of the right consistency for optimum maintenance. Some areas in the hotel are busy and bear heavy traffic such as lobby, corridors, parking areas, restaurants, and dining halls. Their floorings loses smoothness and shine. In such a case, the floor cleaners and sealers are used for restoring their look and shine. Laundry Cleaners − They are liquid concentrates with variable amount of peroxide that removes tough stains, bleaches the linen, and enhances its whiteness. A number of chemicals are used in dry-cleaning. They are camphor oil, turpentine spirits, benzene, kerosene and white gasoline, petroleum solvents such as naphtha blends, chloroform, carbon tetrachloride, and liquid carbon dioxide. They remove the stains from silk tapestry without damaging the fibers. Laundry Cleaners − They are liquid concentrates with variable amount of peroxide that removes tough stains, bleaches the linen, and enhances its whiteness. A number of chemicals are used in dry-cleaning. They are camphor oil, turpentine spirits, benzene, kerosene and white gasoline, petroleum solvents such as naphtha blends, chloroform, carbon tetrachloride, and liquid carbon dioxide. They remove the stains from silk tapestry without damaging the fibers. Surface Sanitizers − They often come in the form of liquid concentrate. They are water-based and sanitize the surfaces without damaging their appearance. The sanitizers reduce the presence of bacteria to a great extent. They come with different concentrations and fragrances. Surface Sanitizers − They often come in the form of liquid concentrate. They are water-based and sanitize the surfaces without damaging their appearance. The sanitizers reduce the presence of bacteria to a great extent. They come with different concentrations and fragrances. Toilet Blocks − They deodorize the toilets and leave them with a fresh smell. They come with two variants: continuous action and instant action. They contain oxidizing agents such as ozone, hydrogen peroxide, or chlorine that removes unpleasant organic odor from the surface of a material. Toilet Blocks − They deodorize the toilets and leave them with a fresh smell. They come with two variants: continuous action and instant action. They contain oxidizing agents such as ozone, hydrogen peroxide, or chlorine that removes unpleasant organic odor from the surface of a material. Toilet Cleaners − They are available in liquid form containing strong hydrochloric acid. They remove stains and plumbing scales easily, and restore the shine of their surface. Toilet Cleaners − They are available in liquid form containing strong hydrochloric acid. They remove stains and plumbing scales easily, and restore the shine of their surface. Carpet Cleaning Agents − Cleaning and maintaining the carpets are important tasks of hotel housekeeping. As suggested by the Carpet and Rug Institute (CRI), carpet cleaning is complete when the following issues are tackled − Soil containment Vacuuming Spotting Interim cleaning Restorative cleaning Carpet cleaning chemicals are often low-moisture, fast-drying cleaners that take care of the above said issues effectively Carpet Cleaning Agents − Cleaning and maintaining the carpets are important tasks of hotel housekeeping. As suggested by the Carpet and Rug Institute (CRI), carpet cleaning is complete when the following issues are tackled − Soil containment Vacuuming Spotting Interim cleaning Restorative cleaning Carpet cleaning chemicals are often low-moisture, fast-drying cleaners that take care of the above said issues effectively Swimming Pool Cleaners − They are used for cleaning the swimming pool water. Some of them are TCCA-90 granules or tablets, SDIC, hydrochloric acid (HCL), liquid chlorine, and alum. The pool cleaning chemicals kill the bacterial and algae growth in the water. Swimming Pool Cleaners − They are used for cleaning the swimming pool water. Some of them are TCCA-90 granules or tablets, SDIC, hydrochloric acid (HCL), liquid chlorine, and alum. The pool cleaning chemicals kill the bacterial and algae growth in the water. The chemicals like Sodium Dichloroisocyanurate (SDIC) has 60% of chlorine content and is used worldwide for disinfecting water. The pool cleaning chemicals dissolve fast in water and provide quick cleaning results. The housekeeping staff needs to take extra care while cleaning baby pools using these cleaners. People will forget what you said. People will forget what you did, but people will never forget how you made them feel. − Maya Angelou, American Author, Poet, and Civil Rights Activist. It is the most important duty of the housekeeping staff to prepare the guest room and the other places in the hotel so that the guest is most comfortable. Due to this, the housekeeping staff places some necessary supplies in the guest rooms and guest bathrooms. The idea behind is, the guest need not pack and carry each and every essential article while travelling. As per the hotel policy, and the standard of the room, the lists of these supplies may change. The housekeeping staff needs to ensure that those supplies are kept in appropriate numbers and condition while preparing room for guest check-in. Let us see more on the guest supplies. The guest room supplies are considered as guest essentials. The housekeeping staff places the following standard supplies in the guest room − Furniture − It includes bed, bedside table, chairs, wardrobe with locker facility, writing table, dressing table, center table, and a magazine holder. Furniture − It includes bed, bedside table, chairs, wardrobe with locker facility, writing table, dressing table, center table, and a magazine holder. Bedding − It includes mattress, bed sheet, bed cover, quilt, quilt cover, pillows, and pillow cases. Bedding − It includes mattress, bed sheet, bed cover, quilt, quilt cover, pillows, and pillow cases. Bedside Supplies − They include non-slip mats on the either sides of the bed. Bedside Supplies − They include non-slip mats on the either sides of the bed. Bedside Table Supplies − They involve a telephone device, and a printed compiled list of important intercom numbers such as reception, restaurant, and laundry of the hotel. The housekeeping staff also provides a copy of Bible, Geeta, or Koran, depending upon the prior knowledge of the guest’s religious orientation. Bedside Table Supplies − They involve a telephone device, and a printed compiled list of important intercom numbers such as reception, restaurant, and laundry of the hotel. The housekeeping staff also provides a copy of Bible, Geeta, or Koran, depending upon the prior knowledge of the guest’s religious orientation. Center Table Supplies −It includes room service, laundry service, and spa and health club rate cards. It also has an ash tray and a small decorative center piece. Center Table Supplies −It includes room service, laundry service, and spa and health club rate cards. It also has an ash tray and a small decorative center piece. Clothing and Clothing Care − It involves bathrobe, coffee table cover, rocking chair cover, and hangers for clothes and ties. Clothing and Clothing Care − It involves bathrobe, coffee table cover, rocking chair cover, and hangers for clothes and ties. Hospitality Tray − It is a small tray with compartments that holds sachets of coffee, tea, cocoa powder, creamer, and sugar. Some hotels also offer the sachets of condiments like black and white pepper powder, and salt. They also keep an electric kettle, a couple of cups, saucers, spoons, and water bottle so that the guest can make the beverage of his choice once in a day. Hospitality Tray − It is a small tray with compartments that holds sachets of coffee, tea, cocoa powder, creamer, and sugar. Some hotels also offer the sachets of condiments like black and white pepper powder, and salt. They also keep an electric kettle, a couple of cups, saucers, spoons, and water bottle so that the guest can make the beverage of his choice once in a day. Mini Bar Supplies − It includes a small personal refrigerator filled with a couple of soft drinks, alcoholic drinks, soda, and ice cubes. It also involves a couple of personal servings of salted peanuts, cashew nuts, or chips. Mini Bar Supplies − It includes a small personal refrigerator filled with a couple of soft drinks, alcoholic drinks, soda, and ice cubes. It also involves a couple of personal servings of salted peanuts, cashew nuts, or chips. Writing Desk Supplies − A writing pad, a pencil, an eraser, promotional brochures, La carte menu, and the short list of places of historical and commercial importance in the city for guest’s reference. Writing Desk Supplies − A writing pad, a pencil, an eraser, promotional brochures, La carte menu, and the short list of places of historical and commercial importance in the city for guest’s reference. They are also considered as guest essentials. The guests are expected to use these supplies or take them away on departure. Depending upon the type of room, the list of supplies for guest bathroom are − Bathroom Attachments − Bath area with shower and handheld shower attachments, a bath tub with hot-cold water mixer and handheld shower attachment, soap dispenser, toilet paper attachment, towel holder, and a basin with hot-cold water mixer attachment. Bathroom Attachments − Bath area with shower and handheld shower attachments, a bath tub with hot-cold water mixer and handheld shower attachment, soap dispenser, toilet paper attachment, towel holder, and a basin with hot-cold water mixer attachment. Towels − The couple of pairs of a large and a small towels each for the guests to be used according to their requirement. Towels − The couple of pairs of a large and a small towels each for the guests to be used according to their requirement. Dustbin − A small dustbin with lid, which can be often, opened by the foot and lined with a plastic bag from inside. Dustbin − A small dustbin with lid, which can be often, opened by the foot and lined with a plastic bag from inside. Non-slip Foot-mat − It is often, kept near the bathtub. Non-slip Foot-mat − It is often, kept near the bathtub. Slippers − Flat non-slip slippers for the guest. Slippers − Flat non-slip slippers for the guest. Mirror − A large mirror is often, fit on the wall above the basin. Mirror − A large mirror is often, fit on the wall above the basin. Hair Dryer − A wall mounted fixed hair dryer for the guest is kept in the bathrooms. Hair Dryer − A wall mounted fixed hair dryer for the guest is kept in the bathrooms. Vanity Tray − It contains small bottles of shower gel, shampoo, and conditioner. Some hotels also provide moisturizer, shower cap, hand and foot cream, ear buds, and a small manicure kit. It may also contain a couple of empty glasses, disposable toothbrushes, and a small bottle of mouthwash. Vanity Tray − It contains small bottles of shower gel, shampoo, and conditioner. Some hotels also provide moisturizer, shower cap, hand and foot cream, ear buds, and a small manicure kit. It may also contain a couple of empty glasses, disposable toothbrushes, and a small bottle of mouthwash. The items provided on request are given to the guests when they ask for them. These are the supplies apart from regular supplies required by some guests. These are often provided as the guest expendables. Some of them are − Alarm clock Comb Crib or Cradle Disposable Diapers Disposable razor Electric blanket Electric fan Extra blankets First aid medical kit Handheld shower attachment Hearing equipment Hot water bag Iron Ironing board Pillow Potty Ring for toilet Raised toilet seat Sanitary napkins Sewing kit Stationery items Tampons Wipes It all comes back to the basics. Serve customers the best-tasting food at a good value in a clean, comfortable restaurant, and they’ll keep coming back. − Dave Thomas, CEO of Windy’s, a fast-food restaurant chain. The efforts of housekeeping speak for themselves. The result of sincere as well as faux housekeeping efforts are noticeable. The housekeeping staff needs to execute cleaning and maintenance tasks at various places inside the hotel. The most important task is cleaning and maintaining guest rooms and guest bathrooms. The guests assess the cleanliness in this area critically. By following the best cleaning and maintenance practices, the housekeeping staff can contribute to retain the satisfied guests as well as to generate new guests willing to repeat their visit to the hotel. This brings in more revenue to the hotel business. To perform towards guest satisfaction and work productivity together, the housekeeping staff needs to structure the cleaning and maintenance procedures and follow them appropriately. The chambermaid’s trolley can be viewed as a large tool box on wheels to aid the hotel housekeeping staff. It has a number of compartments and shelves of various sizes. This trolley is filled with the supplies from the housekeeping supplies store at the end of each shift so that the next shift staff can access it immediately. The staff considers the following points while loading chambermaid’s trolley. Loading the trolley with adequate supplies depending upon the number and types of the rooms on the floor. Loading the trolley with adequate supplies depending upon the number and types of the rooms on the floor. Avoiding to overload the trolley that may lead to any accidents. Avoiding to overload the trolley that may lead to any accidents. Avoiding to underload the trolley that may lead to make unnecessary trips to supplies store. Avoiding to underload the trolley that may lead to make unnecessary trips to supplies store. The SOP is given as follows − Empty the trolley. Empty the trolley. Check rapidly for any broken parts. Check rapidly for any broken parts. Clean it by dusting and wiping any stains. Clean it by dusting and wiping any stains. Place the items according to their weight: heaviest items at the bottom and lighter items at the top section of the trolley. Place the items according to their weight: heaviest items at the bottom and lighter items at the top section of the trolley. Place the linen for different purpose separately. Place the linen for different purpose separately. Close the lids of cleaner bottles and liquid cans tightly. Close the lids of cleaner bottles and liquid cans tightly. Record the numbers and types of the items loaded in the trolley for the rooms. Record the numbers and types of the items loaded in the trolley for the rooms. Collect the room keys. Collect the room keys. Take the trolley to the assigned duty floor. Take the trolley to the assigned duty floor. Park it outside the room such that the linen side faces outside and the room entrance is blocked. Park it outside the room such that the linen side faces outside and the room entrance is blocked. The housekeeping staff should follow the SOP given below for entering the guest room. Leave the DND (Do not Disturb) rooms undisturbed. Leave the DND (Do not Disturb) rooms undisturbed. Knock the door with knuckles and announce in pleasant voice, “Housekeeping...”. Knock the door with knuckles and announce in pleasant voice, “Housekeeping...”. Wait for five seconds to hear the guest’s response. Wait for five seconds to hear the guest’s response. In case of no response, announce the same again. In case of no response, announce the same again. In there is no answer second time too, open the door with the key. In there is no answer second time too, open the door with the key. Enter the room. Enter the room. If the guest is found sleeping, withdraw from the room quietly. If the guest is found sleeping, withdraw from the room quietly. In case the guest answers, ask politely when would he like to service the room. In case the guest answers, ask politely when would he like to service the room. In case the guest wants it later, acknowledge his reply and withdraw from the room. In case the guest wants it later, acknowledge his reply and withdraw from the room. If the housekeeping work is in progress and the guest returns from outside, greet him and ask if the guest would like to return in some time. If the housekeeping work is in progress and the guest returns from outside, greet him and ask if the guest would like to return in some time. The SOP for cleaning the guest room is given below. Once the staff enters the room and starts the housekeeping work, he must − Not use guest room linen as a door stopper or for cleaning and dusting the room. Not use guest room linen as a door stopper or for cleaning and dusting the room. Keep the guest room door open while working. Keep the guest room door open while working. Open the curtains and patio door. Open the curtains and patio door. Assemble the furniture and place appropriately. Assemble the furniture and place appropriately. Keep the vacuum cleaner and other cleaning apparatus in the room. Keep the vacuum cleaner and other cleaning apparatus in the room. Check the type of bed. Check the type of bed. Take the bed linen of appropriate size and place it on the nearest chair. Take the bed linen of appropriate size and place it on the nearest chair. Remove previous bedspread and place on the chair. Remove previous bedspread and place on the chair. Inspect the bed and pillows for their condition as well as for any lost-and-found. Inspect the bed and pillows for their condition as well as for any lost-and-found. In case of checkout room, deposit the left guest items to the floor supervisor. If the room is still occupied by the guest, place the item such that it is safe as well as visible to the guest. In case of checkout room, deposit the left guest items to the floor supervisor. If the room is still occupied by the guest, place the item such that it is safe as well as visible to the guest. Put soiled sheets and pillow covers in the soiled linen cart of the trolley. Put soiled sheets and pillow covers in the soiled linen cart of the trolley. Empty ashtrays and rubbish from the guest room and bathroom dustbins into the trash cart of the trolley. Empty ashtrays and rubbish from the guest room and bathroom dustbins into the trash cart of the trolley. Pick up used glasses, mugs, ashtray, trays, and place them on bathroom platform. Pick up used glasses, mugs, ashtray, trays, and place them on bathroom platform. Spray the bathtub, basin, glasses, mugs, and trays with cleaning liquid. Let them soak the chemicals from the liquid. Spray the bathtub, basin, glasses, mugs, and trays with cleaning liquid. Let them soak the chemicals from the liquid. Make the bed. Make the bed. Start dusting from an extreme inside corner of the room and work outwards. Start dusting from an extreme inside corner of the room and work outwards. Clean wipe TV. Clean wipe TV. Straighten the guest items. Straighten the guest items. Sweep the room and patio floor. Sweep the room and patio floor. Mop the room and patio floor. Mop the room and patio floor. Clean the glasses, mugs, and tray. Clean the glasses, mugs, and tray. Sanitize glasses, mugs, telephone device, and TV remote. Sanitize glasses, mugs, telephone device, and TV remote. Inspect the condition of bathroom slippers and bathrobe. Replace if soiled. Inspect the condition of bathroom slippers and bathrobe. Replace if soiled. Close the patio door. Close the patio door. Close all the curtains. Close all the curtains. Clean the entrance door. Clean the entrance door. Close and lock the room door. Close and lock the room door. Report any damage spotted to the supervisor. Report any damage spotted to the supervisor. The SOP for cleaning the guest bathroom is given below. Open bathroom ventilation. Sweep the bathroom floor. Scrub and finish the platform, bathtub, and basin. Scrub and finish the toilet bowl, rim, ring, and hinge. Wipe the mirror. Clean bathroom walls using wet mop or sponge. Replace amenities such as toilet roll, toilet block, shampoo, conditioners, and moisturizers. Replace bathroom mat. Wipe down shower curtain working from top to bottom with a dry cloth. Replace bath towels and hand towels. Replace the dustbin liner. Close the bathroom ventilation. Clean the bathroom door. Keep the bathroom door open after cleaning. Check bathroom doormat. Replace if required. Report any damage spotted to the supervisor. The balcony or the patio are the extensions of the guest room. The SOPs for cleaning them are given below. Enter the balcony. Spray walls, railings Scrub and clean the bird droppings Wipe down rocking or sitting chairs and table Clean the door tracks appeared on the floor. Sweep the floor. Mop the floor. Every room has to be entered at least once a day by any housekeeping staff. The guests who do not want to get disturbed by any housekeeping service tag their rooms with a Do-Not-Disturb (DND) sign. The SOP for these rooms is as given below. Do not disturb by placing a call until 2:00 o’clock in the noon. Do not disturb by placing a call until 2:00 o’clock in the noon. After 2:00 p.m., the Supervisor calls the room to know the guest’s needs. After 2:00 p.m., the Supervisor calls the room to know the guest’s needs. The housekeeping staff contacts the supervisor to make sure whether to service the room. The housekeeping staff contacts the supervisor to make sure whether to service the room. If the call was not answered by the guest after two calling attempts, the room is serviced. If the call was not answered by the guest after two calling attempts, the room is serviced. To his best judgement, the housekeeping staff enters the room and continues with the usual housekeeping work. To his best judgement, the housekeeping staff enters the room and continues with the usual housekeeping work. There are various public areas frequented by the hotel guests. The areas and their respective SOPs for housekeeping are as given − Carry out the lift cleaning task early morning when the least number of guests are expected to use it. Call the elevator on the ground floor. Open its door. Put appropriate signboard near it. Clean the lift using the appropriate cleaning liquid according to the wall material of the lift cabin. Wipe the lift doors. Work from top to bottom while cleaning a lift cabin. Keep the lift door open till the floor and walls are dried completely. Spray clean air freshener. The lobby is active 24 hours. The furniture, carpets, flooring, and ceiling; everything needs to be kept extremely clean at any given time. The SOPs are as follows − Clear all ashtrays into the trash ensuring no cigarettes are burning. Clear all ashtrays into the trash ensuring no cigarettes are burning. Clean and restore them to proper places. Clean and restore them to proper places. Clear the dustbins near front office desk. Clear the dustbins near front office desk. Replace their lining and keep them as they were. Replace their lining and keep them as they were. Dust and wipe the telephone device, fax machine, Computers, and kiosks. Sanitize the telephone device, computer key board, and touchpad of the kiosk. Dust and wipe the telephone device, fax machine, Computers, and kiosks. Sanitize the telephone device, computer key board, and touchpad of the kiosk. Remove spider webs from ceiling. Remove spider webs from ceiling. Remove the dust deposited on walls, windows, furniture, and floor. Remove the dust deposited on walls, windows, furniture, and floor. Remove stains on the carpet and furniture. Remove stains on the carpet and furniture. Clean all artifacts using damp and soft cloth carefully. Clean all artifacts using damp and soft cloth carefully. Sweep and mop the flooring of lobby and front office desk area. Sweep and mop the flooring of lobby and front office desk area. Dust and polish any vases, paintings, and art pieces. Dust and polish any vases, paintings, and art pieces. Spray the air clean spray with signature aroma. Spray the air clean spray with signature aroma. Play a very light and soothing instrumental music. Play a very light and soothing instrumental music. The parking area takes the load of pollution created by hotel owned vehicles and guests’ private vehicles. It is heavily polluted with dirt and dust. The parking area needs cleanliness with respect to the following terms − Control the ventilation. Control pollutant discharges occurring from broken drainage or water systems of the hotel. Remove fine-grained sediment particles on parking floor. Clean the area near lift. Hard-sweep the parking floor using street sweeping equipment. Collect and dispose the debris appropriately. Bringing presence of any unusual debris to the notice of public area supervisor. The gardener or the team of gardeners work to keep the garden looking beautiful. They must − Water the plants regularly according to the season and requirement of the plants; generally early morning. Water the plants regularly according to the season and requirement of the plants; generally early morning. Remove the weed and fall leaves daily. Remove the weed and fall leaves daily. Implement the art of Arbosculpture to enhance the beauty of the trees and bushes. Implement the art of Arbosculpture to enhance the beauty of the trees and bushes. Keep the gardening tools clean and safe. Keep the gardening tools clean and safe. Report any damage or requirement of tools or plants to the public area supervisor. Report any damage or requirement of tools or plants to the public area supervisor. Keep the lawn grass in healthy condition by periodic cutting with the help of scarifying machine. Keep the lawn grass in healthy condition by periodic cutting with the help of scarifying machine. Keep any artificial waterfalls or artificial water body clean. Keep any artificial waterfalls or artificial water body clean. Fertilizing and manuring the plants as per the schedule. Fertilizing and manuring the plants as per the schedule. Recycle the food wastage in the hotel to prepare organic fertilizer. Recycle the food wastage in the hotel to prepare organic fertilizer. The dining areas need daily cleaning before their working hours start as well as when the restaurant staff requests cleaning. The SOP is given below. Collect all the cleaning equipment and dining area keys. Switch on all the electric lamps. Open all the drapes and blinds for letting in the natural light. Observer the entire area to plan the work. Align all the chairs away from the table to make room for cleaning. Clean the carpet area, using vacuum cleaner. Remove any food stains from the carpet using appropriate cleaner. If there is no carpet on the floor, sweep and mop it. Dust all the furniture in the dining area. Polish the furniture if required. Using a feather duster, dust all the pictures, paintings, artworks, and corners. Clean and disinfect the telephone devices. Polish metal, glass, and wood items if required. Clean the mirrors and windows by wiping them with wet sponge. If requirement of maintenance is spotted, consult engineering department. If any guest items are found then deposit it with housekeeping control desk. Collect all dirty table linens and replace with the fresh ones. Return the keys to the security department. Record in the housekeeping register. The swimming pool cleaning activity can be conducted in-house by training and employing housekeeping staff; as there could be separate swimming pools such as indoor and outdoor as well as for adults and for children. The following steps are taken to clean and maintain the swimming pool − Check water quality more than once a week. Check any broken tiles/pipes inside the swimming pool. Clean the water as soon as possible when required. Check the pool water for contamination daily. Remove leaves using leaf catchers. Check for slippery floor area and the pool bottom. Apply and maintain the anti-slip mats near the pool. Scrub and clean the bottom of the pool. Keep the life-saving and floating apparatus ready all time. Keep poolside area and basking chairs clean. Keep an appropriate and noticeable signage showing the depth of the swimming pool. Check and keep changing rooms up to good quality. Keep the changing room door open when it is not occupied. Employee lifeguards to provide general safety check for swimming pool once a day during the operating hours. Add adequate amount of chlorine in the pool water. Since Spring-cleaning is a time taking process, it is conducted during low occupancy period. The standard procedures are − Request a spring-cleaning date the front office desk. (The housekeeping department needs to honor whatever date they give, as it is the matter of revenue generation.) Request a spring-cleaning date the front office desk. (The housekeeping department needs to honor whatever date they give, as it is the matter of revenue generation.) Tag the room as "Not for Sale". Tag the room as "Not for Sale". Remove the guest amenities, curtains, and art pieces from the room. Remove the guest amenities, curtains, and art pieces from the room. Send the curtains to the laundry for dry cleaning. Send the curtains to the laundry for dry cleaning. Empty the mini bar and send the beverage items to Food and Beverage store. Empty the mini bar and send the beverage items to Food and Beverage store. Roll the curtains and cover them with dustsheet. Roll the curtains and cover them with dustsheet. Inspect the furniture and send to the furniture yard for repair or upholstery. Inspect the furniture and send to the furniture yard for repair or upholstery. Inspect the locks, knobs, latches, leaking pipes, and bathroom. Inspect the locks, knobs, latches, leaking pipes, and bathroom. Hand over the room to maintenance department for any painting, sealing, and repairing work required. Hand over the room to maintenance department for any painting, sealing, and repairing work required. Once the maintenance work is complete, remove any residual smell of paint and varnish by airing the room. Once the maintenance work is complete, remove any residual smell of paint and varnish by airing the room. Polish and clean the permanent fixtures. Polish and clean the permanent fixtures. Open, lay, and shampoo the carpet. Open, lay, and shampoo the carpet. Check the bathroom sealing and clean the bathroom. Check the bathroom sealing and clean the bathroom. Make the bed using fresh bed linen. Make the bed using fresh bed linen. Restore the art pieces, furniture, and guest supplies. Restore the art pieces, furniture, and guest supplies. Call room service for restoring mini bar, glasses, and trays. Call room service for restoring mini bar, glasses, and trays. Show the room to the floor supervisor. Show the room to the floor supervisor. Release it to the front office desk for selling. Release it to the front office desk for selling. The floor supervisor closes the shift formally by ensuring the following points from the attendants − Empty garbage bags of the chambermaid’s trolley into the garbage receptacle. Empty garbage bags of the chambermaid’s trolley into the garbage receptacle. Ensure they the soiled linen collected into chambermaid’s trolley bags are sent to laundry. Ensure they the soiled linen collected into chambermaid’s trolley bags are sent to laundry. Remove the chambermaid’s trolley and check it for ant damage and dirt accumulation. Remove the chambermaid’s trolley and check it for ant damage and dirt accumulation. Empty the vacuum cleaner bags and replace them with new ones. Empty the vacuum cleaner bags and replace them with new ones. Tidy the housekeeping department area by stacking the items at their appropriate places. Tidy the housekeeping department area by stacking the items at their appropriate places. Clean the toilet brushes with hot water for ten minutes every week. Clean the toilet brushes with hot water for ten minutes every week. Rinse mops in light detergents and hang for drying. Rinse mops in light detergents and hang for drying. Close the doors and handover the keys to the housekeeping control desk. Close the doors and handover the keys to the housekeeping control desk. Sign off the shift. Sign off the shift. In the range of small to large hotels, the guest room linen, guest bathroom linen, staff uniforms, all continue to accumulate in large amount. It is essential for the housekeeping staff to launder the linen and make it readily available at all times so that the staff can receive their well-laundered uniforms before work, and the guests are provided with good quality linen. It is definitely required to purchase good quality linen; but the life, appearance, and the quality of linen largely depends upon the treatment it receives at the laundry by the laundry staff. Small hotels can contract with the commercial laundry services located outside the hotel. Large hotel establishments prefer to install their private on-premises laundry. Let us understand on-premises laundry operated by housekeeping − The following advantages are seen if housekeeping staff works at on-premise laundry − On-premise laundry provides more use in comparatively less investment. On-premise laundry provides more use in comparatively less investment. The time, energy, and effort to take the clothes outside at a commercial laundry service is eliminated hence the staff can work better. The time, energy, and effort to take the clothes outside at a commercial laundry service is eliminated hence the staff can work better. The housekeeping staff can easily access the On-premise laundry. The housekeeping staff can easily access the On-premise laundry. Pilferage is reduced. Pilferage is reduced. The staff can have complete control over the wash cycles, and wear and tear of the linen. Thus, life of the fabric can be prolonged by using specific washing for the linen depending upon degree of their soiling. The staff can have complete control over the wash cycles, and wear and tear of the linen. Thus, life of the fabric can be prolonged by using specific washing for the linen depending upon degree of their soiling. On-premise laundry is the game of conservation of water and electricity and generation of high throughput. These equipment speed up the housekeeping work. The laundry equipment mainly include − They are automatic machines which are used to wash the linen in large amount. They provide high laundry room productivity by using less water and electricity. They dry the linen in less time than conventional drying methods. They deliver fast drying without consuming much electrical energy. They save energy, cost, and efforts to press the large number of linen by delivering them ironed and pressed. They are easy and safe to operate. They are yet another automatic laundry devices that can deliver a perfectly folded and finished linen. They can also help to stack the folded linen neatly. The housekeeping staff that handles laundry section is expected to know each device and its operation. The laundry consists of bath and bed linen, dining are linen, staff uniforms, cleaning cloths, curtains, drapes, blankets, and rugs. The guest laundry is handled by the most experienced staff. The staff in the laundry room is expected to be aware of the chemicals, detergents, dry cleaning agents, and the stages of laundry cycle. No sooner than the soiled laundry arrives, the laundering work starts quickly. The reason behind it are − The soiled linen must be cleaned as early as possible. The stains may get permanent. The stains may get transferred to other linen. The soiled linen should not provide a breeding ground for bacteria. To avoid the chances of linen misplacing or loss. The laundry goes through the following stages − This cycle depicts the typical operating procedures. The laundry management is carried out on daily basis. Here are some standard procedures given − Collect Dirty Linen − Collect the dirty linen from various sections in the hotel such as guest rooms, guest bathrooms, and dining area. Put the soiled linen separately. The principle is, whatever linen it is, it must not hang over the edge of the collection basket. Transfer the collected linen to the laundry department. Collect Dirty Linen − Collect the dirty linen from various sections in the hotel such as guest rooms, guest bathrooms, and dining area. Put the soiled linen separately. The principle is, whatever linen it is, it must not hang over the edge of the collection basket. Transfer the collected linen to the laundry department. Sort the Linen − Segregate the linen carefully according to type of fabric, domain of item use, degree of soiling, and type of soiling. Keep the staff uniforms, guest room and bathroom linen, dining area linen, butchery aprons, and guests’ personal clothes all separately. Always handle the linen using gloves. Sort the Linen − Segregate the linen carefully according to type of fabric, domain of item use, degree of soiling, and type of soiling. Keep the staff uniforms, guest room and bathroom linen, dining area linen, butchery aprons, and guests’ personal clothes all separately. Always handle the linen using gloves. Pre-treat the Stains − Before the putting the linen into the washer, inspect it for stains such as grease or oil. Remove the stains using stain cleaning chemicals. If instructed before, use detergents and cleaning chemicals at the time of washing only, to save the time and efforts. Pre-treat the Stains − Before the putting the linen into the washer, inspect it for stains such as grease or oil. Remove the stains using stain cleaning chemicals. If instructed before, use detergents and cleaning chemicals at the time of washing only, to save the time and efforts. Wash/Extract the Linen − Put the linen into washers. Weigh the linen before washing process to ensure the washers are not overloaded. The housekeeping staff need to handle many washers and dryers depending on the size of hotel and occupancy of rooms. Set the automatic washers to different wash cycles depending upon the type of linen. For example, embroidered pillow covers need soft wash cycle and the curtains need harder wash cycles. The following wash cycle is most effective − Wash/Extract the Linen − Put the linen into washers. Weigh the linen before washing process to ensure the washers are not overloaded. The housekeeping staff need to handle many washers and dryers depending on the size of hotel and occupancy of rooms. Set the automatic washers to different wash cycles depending upon the type of linen. For example, embroidered pillow covers need soft wash cycle and the curtains need harder wash cycles. The following wash cycle is most effective − Soak → Flush → Suds → Bleach → Rinse → Extract → Starch Remove as much as possible water content from the linen by using extractors. The linen are then starched to make it little stiff and shiny. Remove as much as possible water content from the linen by using extractors. The linen are then starched to make it little stiff and shiny. Dry the Linen − Put the linen into dryers for removing any moisture still left. Be careful while transferring the linen from washers to dryers because the weight of the linen increases after washing. Use automatic dryer that provides drying by hot air blows. The lint comes off from the linen surface in the process of drying yielding a finished surface. These dryers operate on less electricity and yield fresh and completely dry linen. Dry the Linen − Put the linen into dryers for removing any moisture still left. Be careful while transferring the linen from washers to dryers because the weight of the linen increases after washing. Use automatic dryer that provides drying by hot air blows. The lint comes off from the linen surface in the process of drying yielding a finished surface. These dryers operate on less electricity and yield fresh and completely dry linen. Iron/Repair the Linen − At this stage, check the linen for any wear and tear. Separate the worn out linen to be given to the tailor. Some linen such as towels, bed linen, and dining area linen require Ironing. Pass these linen through the ironer. Hand-iron a few linen such as uniforms. Iron/Repair the Linen − At this stage, check the linen for any wear and tear. Separate the worn out linen to be given to the tailor. Some linen such as towels, bed linen, and dining area linen require Ironing. Pass these linen through the ironer. Hand-iron a few linen such as uniforms. Fold and Stack the Linen − Automatic folding and stacking machines come to the aid of housekeeping staff to save them from the large effort of folding and stacking the linen accurately. Some sort of linen such as staff uniforms and guest personal clothes still need manual efforts for folding. Operate the folding/stacking machines that ascertains finished appearance and makes the linen easy for storage and handling. Fold and Stack the Linen − Automatic folding and stacking machines come to the aid of housekeeping staff to save them from the large effort of folding and stacking the linen accurately. Some sort of linen such as staff uniforms and guest personal clothes still need manual efforts for folding. Operate the folding/stacking machines that ascertains finished appearance and makes the linen easy for storage and handling. Deliver the Linen − Transport the ready laundered linen to the uniform room and linen room. Send the linen that need repair to the tailor room. Then subsequently deliver the linen at the time of keeping and cleaning the various premises such as guest rooms, dining area, and banquet halls. Deliver the Linen − Transport the ready laundered linen to the uniform room and linen room. Send the linen that need repair to the tailor room. Then subsequently deliver the linen at the time of keeping and cleaning the various premises such as guest rooms, dining area, and banquet halls. Give away the guests’ personal clothes according to the rooms they are staying in. Success is not created by one person but by a team that comes together as one. − Jillan Farrar, American Singer-Songwriter, Author, Publisher, and Film Producer. If various departments are seen as organs of the body then the housekeeping department can be seen as a mesh of the nerves that keeps coordination with various organs to achieve its objectives. No work in the industry is complete without coordination and documentation. The housekeeping department is not an exception either. It needs to coordinate within the department itself and with the other departments in the hotel business for while working on daily basis and completing documentation formalities while working. Let us see more on housekeeping communication. The housekeeping control desk is the hub or a single point of contact for all hotel housekeeping staff. At the control desk, the new information is fetched and it is distributed among the relevant staff. As the housekeeping work is mainly oriented towards providing the best service to the guests, this department needs to work towards sharing information without any communication gaps. This desk also needs to ensure that the coordination among the housekeeping staff and with all other departments of the hotel goes smooth. The hotel housekeeping performs the following functions − Collecting all requests made by the guests. Collecting all requests made by the guests. Briefing the staff about the routine or special event preparation before the staff turns up their sleeves. Briefing the staff about the routine or special event preparation before the staff turns up their sleeves. Assigning routine duties / changed duties to the housekeeping staff. Assigning routine duties / changed duties to the housekeeping staff. Collecting work reports from staff. Collecting work reports from staff. Collecting check-out room number and updating it to the floor supervisor. Collecting check-out room number and updating it to the floor supervisor. Handling key cabinet that contains the keys of all floors’ master keys and housekeeping store keys. Handling key cabinet that contains the keys of all floors’ master keys and housekeeping store keys. Maintaining various records of forms and registers. Maintaining various records of forms and registers. While working, the housekeeping department needs to coordinate with the following departments − Sharing occupancy information that helps to estimate future occupancy, budget, and required number of staff. Sharing occupancy information that helps to estimate future occupancy, budget, and required number of staff. Cleaning public areas of hotel premises. Cleaning public areas of hotel premises. Special attention requirements like VIP guests, corporate or large family groups, or airline crews as occupants. Special attention requirements like VIP guests, corporate or large family groups, or airline crews as occupants. Collection of soiled uniforms from and provision of ready uniforms to the front-office staff daily. Collection of soiled uniforms from and provision of ready uniforms to the front-office staff daily. Forthcoming banquet events and parties. Forthcoming banquet events and parties. Pest control in kitchen. Pest control in kitchen. Collection of soiled linen and uniforms from the F&B department and provision of ready linen and uniforms to the F&B staff daily. Collection of soiled linen and uniforms from the F&B department and provision of ready linen and uniforms to the F&B staff daily. Clearance of trays from guest corridors. Clearance of trays from guest corridors. Placement of special guest amenities in guest rooms such as VIP amenities or welcome drink. Placement of special guest amenities in guest rooms such as VIP amenities or welcome drink. Supply of promotional brochures, rate cards, or other items such as pen stand in the guest rooms. Supply of promotional brochures, rate cards, or other items such as pen stand in the guest rooms. Collection of soiled uniforms from the S&M department and provision of ready uniforms to the S&M staff daily. Collection of soiled uniforms from the S&M department and provision of ready uniforms to the S&M staff daily. Acquisition of new staff for the housekeeping department. Acquisition of new staff for the housekeeping department. Compensation of housekeeping staff members such as salary, over time, medical treatment, etc. Compensation of housekeeping staff members such as salary, over time, medical treatment, etc. Motivation for staff performance by appraisal or reward, induction and training program for new staff. Motivation for staff performance by appraisal or reward, induction and training program for new staff. Collection of soiled uniforms from the HRD and provision of ready uniforms to the HRD staff daily. Collection of soiled uniforms from the HRD and provision of ready uniforms to the HRD staff daily. Safety of hotel property, and keys. Safety of hotel property, and keys. Prevention of fire and thefts in the hotel. Prevention of fire and thefts in the hotel. Prevention of any anti-social activities such as any suspicious activities, gambling, or smuggling performed by guests in the guest rooms or hotel premises. Prevention of any anti-social activities such as any suspicious activities, gambling, or smuggling performed by guests in the guest rooms or hotel premises. Collection of soiled uniforms from the HRD and provision of ready uniforms to the HRD staff daily. Collection of soiled uniforms from the HRD and provision of ready uniforms to the HRD staff daily. Collection of soiled uniforms from the porters, doormen, drivers, and provision of ready uniforms to them daily. Collection of soiled uniforms from the porters, doormen, drivers, and provision of ready uniforms to them daily. It takes place regarding − The issues related to payments of housekeeping staff. The issues related to payments of housekeeping staff. Collection of soiled uniforms from the Accounts department and provision of ready uniforms to the accounts staff daily. Collection of soiled uniforms from the Accounts department and provision of ready uniforms to the accounts staff daily. The issues related to erroneous functioning of cleaning and gardening equipment, faulty electric power points, leaning pipes, air-conditioning maintenance, or any other such work. The issues related to erroneous functioning of cleaning and gardening equipment, faulty electric power points, leaning pipes, air-conditioning maintenance, or any other such work. Collection of soiled uniforms from the Engineering and Technology staff and provision of ready uniforms to them daily. Collection of soiled uniforms from the Engineering and Technology staff and provision of ready uniforms to them daily. The repairing and maintenance of broken furniture and fixtures. The painting of the required area in the hotel. Repairing pipes and electric points in the guest rooms. Collection of soiled uniforms from the Maintenance staff and provision of ready uniforms to them daily. The registers are used to record important information. They are very helpful when the shifts and staff on duty changes, and while working too. The registers serve the purpose of keeping clear and timely records thereby fostering good communication. Here are some important registers maintained by housekeeping control desk − It is kept to track the changes of guest room status such as V, VD, or VC after the guest has checked out. It also tracks the amount of Mini bar beverages consumption in the CO guest rooms. It keeps the track of pre-registered guests and their profile as Regular/VIP/Other, Marital status, expected check-in time, and any special request to be fulfilled. This register records the list of all rooms and their current status such as V, VC, OOO, OOS, etc. It records the instructions or notes relevant to the guest rooms and adjacent area. It is very useful in keeping the track of activities and their durations. This register is maintained to record the delivery and recovery of the loan items given to the guests. The general format of this register is as follows − If any article owned by the hotel (other than consumable items) is found missing in a Check-Out room, then it is recorded in this Register. This register is maintained to record guest supplies. The general format is as shown below − If any hotel property placed in the guest room is found damaged or broken, it is recorded in this Register. Here is a sample register − If a housekeeping guest room attendant finds any guest-owned article left in the Check-Out room then it is recorded into the Lost/Found Register and sent to the same cell of the housekeeping department. It also records any personal article found in the hotel premises. It is a register for noting down the issued keys of the guest rooms, mater keys of the rooms and important safes, and floor keys. It records the movement of linen between the laundry and the guest rooms or dining area. It makes the housekeeping staff easy to keep the track of clean and soiled laundry. There are various housekeeping checklists and reports automatically generated by the hotel management software. Checklists help to ensure all work is done appropriately without anything left to be completed. There are various checklists referred and filled by the housekeeping staff. Some important ones are − Guest Supplies Checklist Guest Room Cleaning Checklist Guest Bathroom Cleaning Checklist Beach Area Cleaning Checklist Swimming Pool Cleaning Checklist Garden Keeping Checklist Housekeeping Standard Checklist for SPA Housekeeping Standard Checklist for Fitness Center The reports are useful to study past records of occupancy, cleaning schedules, and predict the future status of the rooms. Let us see the reports generated for housekeeping department − Housekeeping Report This can be generated at the end of each shift to report the housekeeping status of each room. Housekeeping Assignment Report It is required for scheduling the room attendants and recording the room inspections. Housekeeping Occupancy Report This report shows the list of guests who have checked-in the hotel with details such as number of adults and children, number of nights, and housekeeping status. This report is generated for the occupied rooms, rooms expected to be occupied, checked-out rooms, and vacant or blocked rooms. This report is generated for scheduling rooms for cleaning. 5 Lectures 2 hours Manish Gupta 18 Lectures 2 hours Manish Gupta 31 Lectures 2.5 hours Manish Gupta 15 Lectures 1 hours Manish Gupta 10 Lectures 2 hours Manish Gupta 35 Lectures 2.5 hours Manish Gupta Print Add Notes Bookmark this page
[ { "code": null, "e": 2094, "s": 1957, "text": "I consider housekeeping to be the heart of hotels and it is only when something goes wrong that it is recognized – just like our hearts." }, { "code": null, "e": 2149, "s": 2094, "text": "− Sheila Perera FIH Glenmor Manager, Gleneagles Hotel." }, { "code": null, "e": 2370, "s": 2149, "text": "The housekeeping department, in any hotel business, contributes to major amount of profit though it is considered as an ancillary service. The simple reason being, a customer demands a clean, tidy, and pleasing ambience." }, { "code": null, "e": 2515, "s": 2370, "text": "Housekeeping generates the first impression on a guest’s mind. The housekeeping efforts clearly show how the hotel will take care of its guests." }, { "code": null, "e": 2817, "s": 2515, "text": "Housekeeping means performing all the duties towards cleaning, maintaining orderliness, and running a house or a business property. In case of hotels, the housekeeping duties involve maintaining the hotel to the best possible state in terms of cleanliness, and keeping it at highly desirable ambience." }, { "code": null, "e": 2865, "s": 2817, "text": "The main objectives of hotel housekeeping are −" }, { "code": null, "e": 2931, "s": 2865, "text": "To maintain overall cleanliness of the entire hotel at all times." }, { "code": null, "e": 2995, "s": 2931, "text": "To perform cleanliness duties most efficiently and effectively." }, { "code": null, "e": 3055, "s": 2995, "text": "To use good quality, safe cleaning equipment and chemicals." }, { "code": null, "e": 3084, "s": 3055, "text": "To manage laundry and linen." }, { "code": null, "e": 3102, "s": 3084, "text": "To control pests." }, { "code": null, "e": 3156, "s": 3102, "text": "To keep up the hotel with classy interior decoration." }, { "code": null, "e": 3231, "s": 3156, "text": "To take care of the furniture, fittings, and fixtures of the entire hotel." }, { "code": null, "e": 3349, "s": 3231, "text": "To understand the expanse or scope of housekeeping, it is better to understand the divisions of hotel a hotel, first." }, { "code": null, "e": 3428, "s": 3349, "text": "There are various divisions (or departments) of a hotel. They are given below." }, { "code": null, "e": 3628, "s": 3428, "text": "It is responsible for guest check-in and check-out, mail and information services, and concierge services such as tour booking, reserving theatre and restaurants, providing airport taxi service, etc." }, { "code": null, "e": 3876, "s": 3628, "text": "Food and Beverage department is responsible for preparing menus, foods, and managing inventory of food and beverage items. It includes food and beverage preparation and service for restaurant, lounge, coffee shops, bars, parties, and room service." }, { "code": null, "e": 3956, "s": 3876, "text": "It includes parking and door attendants, drivers, porters, and bell attendants." }, { "code": null, "e": 4132, "s": 3956, "text": "Housekeeping includes the duties of keeping the areas of the hotel clean, tidy, hygienic, and pleasant. It also performs the duties pertaining to decoration of hotel premises." }, { "code": null, "e": 4231, "s": 4132, "text": "All sales, services, advertising, promotions, and public relations are taken care of by this team." }, { "code": null, "e": 4335, "s": 4231, "text": "Security manager and security workers work to keep the property safe and secured from external hazards." }, { "code": null, "e": 4637, "s": 4335, "text": "It conducts all financial activities like producing bills and receiving payments, computing employees’ compensations and delivering payments. They also carry out the activities such as compiling monthly and annual income statements, depositing and securing cash, and controlling and monitoring assets." }, { "code": null, "e": 4875, "s": 4637, "text": "The Maintenance department is responsible for the maintenance of the property. It takes care of repairing furniture and fixtures, and painting the required area. When the hotel is small, these works are contracted from an outside agency." }, { "code": null, "e": 5132, "s": 4875, "text": "It is responsible for keeping all of its equipment operational. The duties include maintaining telephone, hotel management software, internet etc. It is also responsible for implementing any new changes required such as upgrading the software and hardware." }, { "code": null, "e": 5492, "s": 5132, "text": "Human Resource department is responsible for interviewing and recruiting qualified staff to be placed at appropriate positions. They also conduct exit interviews for the employees who wish to quit the work. HRD works to set wages and salaries based on regional market rates and ensures that the hotel business meets safety and health administration standards." }, { "code": null, "e": 5810, "s": 5492, "text": "In all these departments, the efforts of housekeeping department are overt. They are directly visible to the guests even before they try food or avail other amenities. Housekeeping creates the first impression about the hotel in the guests’ minds. Hence this department can be said as the heart of the hotel business." }, { "code": null, "e": 5992, "s": 5810, "text": "The layout of the housekeeping department depends on the total number of Guestrooms, Outlets, and Required Staff. The following areas of the department are the most prominent ones −" }, { "code": null, "e": 6093, "s": 5992, "text": "Office of the Executive Housekeeper − The administrative work of the department is carried out here." }, { "code": null, "e": 6194, "s": 6093, "text": "Office of the Executive Housekeeper − The administrative work of the department is carried out here." }, { "code": null, "e": 6442, "s": 6194, "text": "Housekeeping Control Desk −It is accessible and operational 24 hours a day. The housekeeping staff reports at the start and end of the shift here. There are notice boards, storage shelves, registers, lost and found cupboard, and key-hanger matrix." }, { "code": null, "e": 6690, "s": 6442, "text": "Housekeeping Control Desk −It is accessible and operational 24 hours a day. The housekeeping staff reports at the start and end of the shift here. There are notice boards, storage shelves, registers, lost and found cupboard, and key-hanger matrix." }, { "code": null, "e": 6790, "s": 6690, "text": "Laundry Area − Washing, ironing, dry cleaning, folding of linen and staff uniform takes place here." }, { "code": null, "e": 6890, "s": 6790, "text": "Laundry Area − Washing, ironing, dry cleaning, folding of linen and staff uniform takes place here." }, { "code": null, "e": 7052, "s": 6890, "text": "Linen Room − Here, the linen of the hotel such as bed-sheets, towels, pillow cases, etc., are stored, collected, and carried to the required places in the hotel." }, { "code": null, "e": 7214, "s": 7052, "text": "Linen Room − Here, the linen of the hotel such as bed-sheets, towels, pillow cases, etc., are stored, collected, and carried to the required places in the hotel." }, { "code": null, "e": 7298, "s": 7214, "text": "Uniform Room − The staff uniforms are collected, stored, and distributed from here." }, { "code": null, "e": 7382, "s": 7298, "text": "Uniform Room − The staff uniforms are collected, stored, and distributed from here." }, { "code": null, "e": 7461, "s": 7382, "text": "Tailor Room − Here, stitching and repairing of linen and uniforms takes place." }, { "code": null, "e": 7540, "s": 7461, "text": "Tailor Room − Here, stitching and repairing of linen and uniforms takes place." }, { "code": null, "e": 7663, "s": 7540, "text": "Housekeeping Stores − It is a storage area where the cleaning equipment and items, and guest supplies are securely stored." }, { "code": null, "e": 7786, "s": 7663, "text": "Housekeeping Stores − It is a storage area where the cleaning equipment and items, and guest supplies are securely stored." }, { "code": null, "e": 7922, "s": 7786, "text": "Flower Room − It is an air-conditioned room with worktables, sink and water supply, cupboards to store vases and stones, and a counter." }, { "code": null, "e": 8058, "s": 7922, "text": "Flower Room − It is an air-conditioned room with worktables, sink and water supply, cupboards to store vases and stones, and a counter." }, { "code": null, "e": 8237, "s": 8058, "text": "Lost and found −stores all the items left by the guests. It directly communicates with the front office desk, as there the guests tend to first enquire about their lost articles." }, { "code": null, "e": 8416, "s": 8237, "text": "Lost and found −stores all the items left by the guests. It directly communicates with the front office desk, as there the guests tend to first enquire about their lost articles." }, { "code": null, "e": 8503, "s": 8416, "text": "The housekeeping department is responsible to keep the following areas clean and tidy." }, { "code": null, "e": 8515, "s": 8503, "text": "Guest Rooms" }, { "code": null, "e": 8531, "s": 8515, "text": "Guest Bathrooms" }, { "code": null, "e": 8568, "s": 8531, "text": "Public Areas such as Lobby and Lifts" }, { "code": null, "e": 8598, "s": 8568, "text": "Banquets and Conference Halls" }, { "code": null, "e": 8611, "s": 8598, "text": "Parking Area" }, { "code": null, "e": 8635, "s": 8611, "text": "Sales and Admin Offices" }, { "code": null, "e": 8642, "s": 8635, "text": "Garden" }, { "code": null, "e": 8857, "s": 8642, "text": "Apart from the cleaning task, the housekeeping is also responsible for handling keys of each floor. In addition, it manages the laundry, which is often at some places considered as a sub-department of housekeeping." }, { "code": null, "e": 9040, "s": 8857, "text": "It is a multi-course meal or feast, usually given by the host on occasions like a charitable gathering, a ceremony, or a celebration, often precedes or succeeds by honoring speeches." }, { "code": null, "e": 9307, "s": 9040, "text": "It is a detailed information prepared by the manufacturer or importer of a chemical that describes the physical and chemical properties, health hazards, routes of exposure, precautions for safe handling and use, and first-aid procedures in case any accident happens." }, { "code": null, "e": 9570, "s": 9307, "text": "The status of room is not ready for selling because of some problem such as clogged basin/toilet, nonfunctioning shower, or broken bed. The supervisor needs to know for how long it will be out of order and is responsible to get it into order as fast as possible." }, { "code": null, "e": 9768, "s": 9570, "text": "The housekeeping also practices general abbreviations such as As Soon As Possible (ASAP), Not Yet (NY), Follow Up (FU), and For Your Information (FYI), which are also used commonly in the industry." }, { "code": null, "e": 9830, "s": 9768, "text": "A new broom sweeps clean; but an old broom knows the corners." }, { "code": null, "e": 9849, "s": 9830, "text": "− An Irish Saying." }, { "code": null, "e": 10097, "s": 9849, "text": "There is a huge workload on the hotel housekeeping staff. The housekeeping work is carried out at various levels such as managerial level, supervisory level, and operational level. Let us see more about the staff and qualities they should possess." }, { "code": null, "e": 10161, "s": 10097, "text": "The general structure of housekeeping staff is as shown below −" }, { "code": null, "e": 10217, "s": 10161, "text": "Let us see the work and responsibilities at each level." }, { "code": null, "e": 10389, "s": 10217, "text": "The Executive Manager is the chief of housekeeping department. The Deputy Housekeeper and Assistant Manager of Housekeeping report to him. Their responsibilities include −" }, { "code": null, "e": 10447, "s": 10389, "text": "Ensuring overall cleanliness and aesthetics of the hotel." }, { "code": null, "e": 10505, "s": 10447, "text": "Ensuring overall cleanliness and aesthetics of the hotel." }, { "code": null, "e": 10570, "s": 10505, "text": "Ensuring overall sanitation, comfort, and ambience of the hotel." }, { "code": null, "e": 10635, "s": 10570, "text": "Ensuring overall sanitation, comfort, and ambience of the hotel." }, { "code": null, "e": 10697, "s": 10635, "text": "Training the new joiners and motivate the existing employees." }, { "code": null, "e": 10759, "s": 10697, "text": "Training the new joiners and motivate the existing employees." }, { "code": null, "e": 10852, "s": 10759, "text": "Modelling and establishing Standard Operating Procedures (SOPs) for cleaning and decorating." }, { "code": null, "e": 10945, "s": 10852, "text": "Modelling and establishing Standard Operating Procedures (SOPs) for cleaning and decorating." }, { "code": null, "e": 11003, "s": 10945, "text": "Monitoring regular inventory of guest supplies and linen." }, { "code": null, "e": 11061, "s": 11003, "text": "Monitoring regular inventory of guest supplies and linen." }, { "code": null, "e": 11115, "s": 11061, "text": "Monitoring housekeeping equipment and hotel property." }, { "code": null, "e": 11169, "s": 11115, "text": "Monitoring housekeeping equipment and hotel property." }, { "code": null, "e": 11258, "s": 11169, "text": "Evaluating employee performance, and handling their training, promotions, and transfers." }, { "code": null, "e": 11347, "s": 11258, "text": "Evaluating employee performance, and handling their training, promotions, and transfers." }, { "code": null, "e": 11388, "s": 11347, "text": "Organize flower arrangements for events." }, { "code": null, "e": 11429, "s": 11388, "text": "Organize flower arrangements for events." }, { "code": null, "e": 11513, "s": 11429, "text": "Presenting the estimate of the required budget to the General Manager of the hotel." }, { "code": null, "e": 11597, "s": 11513, "text": "Presenting the estimate of the required budget to the General Manager of the hotel." }, { "code": null, "e": 11714, "s": 11597, "text": "The supervisors report to the Assistant Housekeeper. Their positions and their respective responsibilities include −" }, { "code": null, "e": 11751, "s": 11714, "text": "Issuing keys to the room attendants." }, { "code": null, "e": 11822, "s": 11751, "text": "Coordinating floor operations and tray clearance with room attendants." }, { "code": null, "e": 11901, "s": 11822, "text": "Inspecting rooms for readiness and reporting to the front office for the same." }, { "code": null, "e": 12012, "s": 11901, "text": "Catering for VIP facilities and providing special supplies such as hot drinking water, baby-sitting provision." }, { "code": null, "e": 12123, "s": 12012, "text": "Catering for VIP facilities and providing special supplies such as hot drinking water, baby-sitting provision." }, { "code": null, "e": 12298, "s": 12123, "text": "Ensuring that cleanliness is maintained at all times in public areas such as lobby, lifts, parking, swimming pool, coffee shop, conference hall, banquet hall, and restaurant." }, { "code": null, "e": 12473, "s": 12298, "text": "Ensuring that cleanliness is maintained at all times in public areas such as lobby, lifts, parking, swimming pool, coffee shop, conference hall, banquet hall, and restaurant." }, { "code": null, "e": 12536, "s": 12473, "text": "Ensuring banquet and conference halls are well kept and ready." }, { "code": null, "e": 12609, "s": 12536, "text": "Ensuring the concerned operating staff is available as per the schedule." }, { "code": null, "e": 12689, "s": 12609, "text": "Ensuring provision of guest supplies such as water, extra bed, fans, or towels." }, { "code": null, "e": 12769, "s": 12689, "text": "Ensuring provision of guest supplies such as water, extra bed, fans, or towels." }, { "code": null, "e": 12847, "s": 12769, "text": "Ensuring the operating staff working at night is following all cleaning SOPs." }, { "code": null, "e": 12925, "s": 12847, "text": "Ensuring the operating staff working at night is following all cleaning SOPs." }, { "code": null, "e": 13005, "s": 12925, "text": "Supervising hotel area at night and ensuring cleanliness in all areas of hotel." }, { "code": null, "e": 13085, "s": 13005, "text": "Supervising hotel area at night and ensuring cleanliness in all areas of hotel." }, { "code": null, "e": 13149, "s": 13085, "text": "Providing clean, ironed, and fresh uniforms to the hotel staff." }, { "code": null, "e": 13198, "s": 13149, "text": "Suggesting procurement of any uniforms required." }, { "code": null, "e": 13240, "s": 13198, "text": "Checking repaired linen from tailor room." }, { "code": null, "e": 13291, "s": 13240, "text": "Keeping track of number and condition of uniforms." }, { "code": null, "e": 13339, "s": 13291, "text": "Inspecting linen and sending it to the laundry." }, { "code": null, "e": 13395, "s": 13339, "text": "Checking linen from laundry and sending it for ironing." }, { "code": null, "e": 13443, "s": 13395, "text": "Maintaining linen influx and out flux register." }, { "code": null, "e": 13485, "s": 13443, "text": "Checking repaired linen from tailor room." }, { "code": null, "e": 13528, "s": 13485, "text": "Suggesting linen replacements if required." }, { "code": null, "e": 13618, "s": 13528, "text": "The positions and responsibilities of the Operating Staff/Attendants are explained below." }, { "code": null, "e": 13724, "s": 13618, "text": "Collecting uniforms of staff at the end of every shift and maintaining them to be used for the next time." }, { "code": null, "e": 13830, "s": 13724, "text": "Collecting uniforms of staff at the end of every shift and maintaining them to be used for the next time." }, { "code": null, "e": 13886, "s": 13830, "text": "Maintaining the shelves of uniforms and linens clearly." }, { "code": null, "e": 13942, "s": 13886, "text": "Maintaining the shelves of uniforms and linens clearly." }, { "code": null, "e": 13994, "s": 13942, "text": "Giving and taking back the uniforms from the staff." }, { "code": null, "e": 14046, "s": 13994, "text": "Giving and taking back the uniforms from the staff." }, { "code": null, "e": 14127, "s": 14046, "text": "Segregating the dirty linen according to its type and sending it to the laundry." }, { "code": null, "e": 14208, "s": 14127, "text": "Segregating the dirty linen according to its type and sending it to the laundry." }, { "code": null, "e": 14267, "s": 14208, "text": "Keeping the track of linen count before and after laundry." }, { "code": null, "e": 14326, "s": 14267, "text": "Keeping the track of linen count before and after laundry." }, { "code": null, "e": 14429, "s": 14326, "text": "Stacking towels, bed sheets, pillowcases, table napkins separately into different sections of shelves." }, { "code": null, "e": 14532, "s": 14429, "text": "Stacking towels, bed sheets, pillowcases, table napkins separately into different sections of shelves." }, { "code": null, "e": 14567, "s": 14532, "text": "Reporting to the floor supervisor." }, { "code": null, "e": 14629, "s": 14567, "text": "Cleaning the guest rooms, guest bathrooms, and the corridors." }, { "code": null, "e": 14687, "s": 14629, "text": "Changing the linen of the guest room and guest bathrooms." }, { "code": null, "e": 14718, "s": 14687, "text": "Topping up the guest supplies." }, { "code": null, "e": 14742, "s": 14718, "text": "Making guest-room beds." }, { "code": null, "e": 14834, "s": 14742, "text": "Replenishing the hotel cleaner’s trolley with supplies and linens for the next shift staff." }, { "code": null, "e": 14926, "s": 14834, "text": "Replenishing the hotel cleaner’s trolley with supplies and linens for the next shift staff." }, { "code": null, "e": 14961, "s": 14926, "text": "Reporting to the floor supervisor." }, { "code": null, "e": 15044, "s": 14961, "text": "Keeping the count of cleaning equipment and items such as cleaners and detergents." }, { "code": null, "e": 15127, "s": 15044, "text": "Keeping the count of cleaning equipment and items such as cleaners and detergents." }, { "code": null, "e": 15185, "s": 15127, "text": "Generating requisition to purchase the required material." }, { "code": null, "e": 15222, "s": 15185, "text": "Reporting to public area supervisor." }, { "code": null, "e": 15313, "s": 15222, "text": "Keeping the parking, lobbies, guest rooms, lifts, and corridors in best maintained status." }, { "code": null, "e": 15404, "s": 15313, "text": "Keeping the parking, lobbies, guest rooms, lifts, and corridors in best maintained status." }, { "code": null, "e": 15450, "s": 15404, "text": "Keeping these areas smelling fresh and clean." }, { "code": null, "e": 15509, "s": 15450, "text": "Reporting any hotel safety issues to the night supervisor." }, { "code": null, "e": 15554, "s": 15509, "text": "Performing housekeeping duties during night." }, { "code": null, "e": 15643, "s": 15554, "text": "There are certain professional qualities the housekeeping staff is required to possess −" }, { "code": null, "e": 15681, "s": 15643, "text": "The housekeeping staff on duty must −" }, { "code": null, "e": 15735, "s": 15681, "text": "Be well-groomed with high degree of personal hygiene." }, { "code": null, "e": 15783, "s": 15735, "text": "Have trimmed nails and hair, and clean uniform." }, { "code": null, "e": 15821, "s": 15783, "text": "Have a clean and pleasant appearance." }, { "code": null, "e": 15851, "s": 15821, "text": "The housekeeping staff must −" }, { "code": null, "e": 15899, "s": 15851, "text": "Conduct themselves with a cooperative attitude." }, { "code": null, "e": 15937, "s": 15899, "text": "Speak in a friendly but sincere tone." }, { "code": null, "e": 15987, "s": 15937, "text": "Speak clearly in audible voice of moderate pitch." }, { "code": null, "e": 16056, "s": 15987, "text": "Maintain polite eye contact while interacting with the hotel guests." }, { "code": null, "e": 16135, "s": 16056, "text": "For serving the guest and working for cleanliness, the housekeeping staff must" }, { "code": null, "e": 16159, "s": 16135, "text": "Possess right attitude." }, { "code": null, "e": 16217, "s": 16159, "text": "Have good listening skills to avoid any miscommunication." }, { "code": null, "e": 16240, "s": 16217, "text": "Be a good team player." }, { "code": null, "e": 16270, "s": 16240, "text": "The housekeeping staff must −" }, { "code": null, "e": 16346, "s": 16270, "text": "Be able to retain and pursue the demand of the guest until it is fulfilled." }, { "code": null, "e": 16377, "s": 16346, "text": "Be sincere and physically fit." }, { "code": null, "e": 16483, "s": 16377, "text": "Respect each hotel guest they are dealing with. They must conduct themselves confidently and courteously." }, { "code": null, "e": 16589, "s": 16483, "text": "Respect each hotel guest they are dealing with. They must conduct themselves confidently and courteously." }, { "code": null, "e": 16610, "s": 16589, "text": "Have high integrity." }, { "code": null, "e": 16693, "s": 16610, "text": "There are practical little things in housekeeping which no man really understands." }, { "code": null, "e": 16759, "s": 16693, "text": "− Eleanor Roosevelt, American Politician, Diplomat, and Activist." }, { "code": null, "e": 17065, "s": 16759, "text": "There are various principles followed by the housekeeping staff. They are cleaning and hygiene principles, safety and security principles, comfort and privacy principles, and finally, the decor. For understanding the housekeeping principles, first let us go through what advantages it offers to the hotel." }, { "code": null, "e": 17152, "s": 17065, "text": "Here are some prominent advantages, the housekeeping department offers to its guests −" }, { "code": null, "e": 17182, "s": 17152, "text": "Clean and hygienic atmosphere" }, { "code": null, "e": 17214, "s": 17182, "text": "Comfortable and convenient stay" }, { "code": null, "e": 17222, "s": 17214, "text": "Privacy" }, { "code": null, "e": 17242, "s": 17222, "text": "Safety and security" }, { "code": null, "e": 17265, "s": 17242, "text": "Provision of amenities" }, { "code": null, "e": 17289, "s": 17265, "text": "Making guests Feel good" }, { "code": null, "e": 17419, "s": 17289, "text": "Having seen the advantages, let us see the principles of housekeeping towards providing these to the guests while working safely." }, { "code": null, "e": 17728, "s": 17419, "text": "Cleaning is conducted to remove harmful bacteria present in the dust deposited on the hotel property because of air pollution. This may cause unhealthy effects on the working staff as well as the guests. Cleanliness reduces the threat of any infections and offers comfortable stay to the guests in the hotel." }, { "code": null, "e": 17789, "s": 17728, "text": "The worker must follow the given principles while cleaning −" }, { "code": null, "e": 17920, "s": 17789, "text": "Carry out the cleaning procedures in sequence. Say, sweeping → Dusting → Mopping/Suction Cleaning → Disinfecting → Air Freshening." }, { "code": null, "e": 18051, "s": 17920, "text": "Carry out the cleaning procedures in sequence. Say, sweeping → Dusting → Mopping/Suction Cleaning → Disinfecting → Air Freshening." }, { "code": null, "e": 18156, "s": 18051, "text": "Must take care while cleaning and polishing; not to damage various surfaces and hamper their appearance." }, { "code": null, "e": 18261, "s": 18156, "text": "Must take care while cleaning and polishing; not to damage various surfaces and hamper their appearance." }, { "code": null, "e": 18331, "s": 18261, "text": "Should start cleaning from extreme inner end continuing towards exit." }, { "code": null, "e": 18401, "s": 18331, "text": "Should start cleaning from extreme inner end continuing towards exit." }, { "code": null, "e": 18487, "s": 18401, "text": "Should park the chambermaid’s trolley such that it leaves space for corridor traffic." }, { "code": null, "e": 18573, "s": 18487, "text": "Should park the chambermaid’s trolley such that it leaves space for corridor traffic." }, { "code": null, "e": 18668, "s": 18573, "text": "Must take proper precautions while handling cleaning equipment, detergents, and guest luggage." }, { "code": null, "e": 18763, "s": 18668, "text": "Must take proper precautions while handling cleaning equipment, detergents, and guest luggage." }, { "code": null, "e": 18832, "s": 18763, "text": "Must remove hard water stains and spider webs as soon as they occur." }, { "code": null, "e": 18901, "s": 18832, "text": "Must remove hard water stains and spider webs as soon as they occur." }, { "code": null, "e": 18970, "s": 18901, "text": "Must never use guest room linen for cleaning or blocking room entry." }, { "code": null, "e": 19039, "s": 18970, "text": "Must never use guest room linen for cleaning or blocking room entry." }, { "code": null, "e": 19098, "s": 19039, "text": "The workers must follow the safety rules mentioned below −" }, { "code": null, "e": 19165, "s": 19098, "text": "Protect their body from harmful chemicals by wearing thick gloves." }, { "code": null, "e": 19232, "s": 19165, "text": "Protect their body from harmful chemicals by wearing thick gloves." }, { "code": null, "e": 19292, "s": 19232, "text": "Protect their eyes by wearing masks or goggles if required." }, { "code": null, "e": 19352, "s": 19292, "text": "Protect their eyes by wearing masks or goggles if required." }, { "code": null, "e": 19394, "s": 19352, "text": "Must use caution sign to mark wet floors." }, { "code": null, "e": 19436, "s": 19394, "text": "Must use caution sign to mark wet floors." }, { "code": null, "e": 19501, "s": 19436, "text": "Clean spilled liquids immediately to reduce chances of slipping." }, { "code": null, "e": 19566, "s": 19501, "text": "Clean spilled liquids immediately to reduce chances of slipping." }, { "code": null, "e": 19662, "s": 19566, "text": "Handle cleaning chemicals carefully while transporting, disposing, or refilling the containers." }, { "code": null, "e": 19758, "s": 19662, "text": "Handle cleaning chemicals carefully while transporting, disposing, or refilling the containers." }, { "code": null, "e": 19824, "s": 19758, "text": "Mix any chemicals required in the presence of proper ventilation." }, { "code": null, "e": 19890, "s": 19824, "text": "Mix any chemicals required in the presence of proper ventilation." }, { "code": null, "e": 19935, "s": 19890, "text": "Must not open unlabeled chemical containers." }, { "code": null, "e": 19980, "s": 19935, "text": "Must not open unlabeled chemical containers." }, { "code": null, "e": 20053, "s": 19980, "text": "Use swivel head mops to avoid inappropriate body posture while cleaning." }, { "code": null, "e": 20126, "s": 20053, "text": "Use swivel head mops to avoid inappropriate body posture while cleaning." }, { "code": null, "e": 20174, "s": 20126, "text": "Wear close toe-non slip footwear while working." }, { "code": null, "e": 20222, "s": 20174, "text": "Wear close toe-non slip footwear while working." }, { "code": null, "e": 20283, "s": 20222, "text": "Use appropriate body postures while working to avoid cramps." }, { "code": null, "e": 20344, "s": 20283, "text": "Use appropriate body postures while working to avoid cramps." }, { "code": null, "e": 20416, "s": 20344, "text": "Request for peer assistance while moving heavy loads such as furniture." }, { "code": null, "e": 20488, "s": 20416, "text": "Request for peer assistance while moving heavy loads such as furniture." }, { "code": null, "e": 20591, "s": 20488, "text": "Report to the supervisor in case of any accident due to mishandling of flammable liquids or otherwise." }, { "code": null, "e": 20694, "s": 20591, "text": "Report to the supervisor in case of any accident due to mishandling of flammable liquids or otherwise." }, { "code": null, "e": 20753, "s": 20694, "text": "Keep the guests safe with the help of security department." }, { "code": null, "e": 20812, "s": 20753, "text": "Keep the guests safe with the help of security department." }, { "code": null, "e": 20875, "s": 20812, "text": "Keep the guests’ documents, ornaments, or other articles safe." }, { "code": null, "e": 20938, "s": 20875, "text": "Keep the guests’ documents, ornaments, or other articles safe." }, { "code": null, "e": 21043, "s": 20938, "text": "The housekeeping staff must follow the given principles with regard to comfort and privacy of the guest." }, { "code": null, "e": 21113, "s": 21043, "text": "Always remember comfort and privacy of the guests always comes first." }, { "code": null, "e": 21183, "s": 21113, "text": "Always remember comfort and privacy of the guests always comes first." }, { "code": null, "e": 21259, "s": 21183, "text": "Clean the premises or rooms in the least destructive and disturbing manner." }, { "code": null, "e": 21335, "s": 21259, "text": "Clean the premises or rooms in the least destructive and disturbing manner." }, { "code": null, "e": 21393, "s": 21335, "text": "Enter the guest rooms by following appropriate procedure." }, { "code": null, "e": 21451, "s": 21393, "text": "Enter the guest rooms by following appropriate procedure." }, { "code": null, "e": 21490, "s": 21451, "text": "Work towards the guests’ satisfaction." }, { "code": null, "e": 21529, "s": 21490, "text": "Work towards the guests’ satisfaction." }, { "code": null, "e": 21662, "s": 21529, "text": "The housekeeping staff needs to know various types of fires and fire extinguishers. The staff must be trained to handle small fires." }, { "code": null, "e": 21709, "s": 21662, "text": "Fire is classified into the following types − " }, { "code": null, "e": 21894, "s": 21709, "text": "Class A − Class A fire consists of ordinary combustibles such as wood, paper, trash or anything else that leaves ash behind. It needs water under high pressure to extinguish this fire." }, { "code": null, "e": 22079, "s": 21894, "text": "Class A − Class A fire consists of ordinary combustibles such as wood, paper, trash or anything else that leaves ash behind. It needs water under high pressure to extinguish this fire." }, { "code": null, "e": 22195, "s": 22079, "text": "Class B − This fire occurs in inflammable liquids such as oil and grease, and needs blankets or sand to extinguish." }, { "code": null, "e": 22311, "s": 22195, "text": "Class B − This fire occurs in inflammable liquids such as oil and grease, and needs blankets or sand to extinguish." }, { "code": null, "e": 22433, "s": 22311, "text": "Class C − This fire occurs in electrical equipment. Use of non-conductive agent is required for extinguishing this fire." }, { "code": null, "e": 22555, "s": 22433, "text": "Class C − This fire occurs in electrical equipment. Use of non-conductive agent is required for extinguishing this fire." }, { "code": null, "e": 22735, "s": 22555, "text": "Class K − Class K Fires are fires that involve cooking oils, grease or animal fat and can be extinguished using Purple K, a typical agent found in kitchen or galley extinguishers." }, { "code": null, "e": 22915, "s": 22735, "text": "Class K − Class K Fires are fires that involve cooking oils, grease or animal fat and can be extinguished using Purple K, a typical agent found in kitchen or galley extinguishers." }, { "code": null, "e": 23188, "s": 22915, "text": "Soda Acid extinguisher is used to put out class A fire. It sprays the compound with gaseous pressure. Only good for small intensity fires. For large intensity and widely spread fire, water must be sprayed directly on the affected area with high pressure through the hoses." }, { "code": null, "e": 23341, "s": 23188, "text": "For putting out class B fires, Carbon Di-Oxide extinguishers are used. Carbon Di-Oxide fog extinguishers are well-places in case of small class C fires." }, { "code": null, "e": 23487, "s": 23341, "text": "The housekeeping staff must place appropriate extinguishers near the fire prone areas and must know to operate them under challenging conditions." }, { "code": null, "e": 23710, "s": 23487, "text": "The housekeeping staff is responsible for creating pleasant ambience in the hotel. This needs aesthetic sense and an eye for detail. A guest is keen to visit the hotel if he finds classy and catchy ambience with fresh air." }, { "code": null, "e": 23954, "s": 23710, "text": "Housekeeping staff must intelligently use artificial waterfalls, large vases with neat and eye-catching flower arrangements, paintings, wall pieces, murals, lighting with appropriate luminance, candles, electric lamps or any rare antic pieces." }, { "code": null, "e": 24144, "s": 23954, "text": "The housekeeping staff is required to know various materials such as wood, organic and artificial fibers, stone, sand, glass, plastic, and pigments to maintain the expensive hotel property." }, { "code": null, "e": 24344, "s": 24144, "text": "Hotel decors can be conducted thematically depending on the local/international prominent festivals and cultures. Décor is yet another important task that elevates guests’ experience with the hotel." }, { "code": null, "e": 24578, "s": 24344, "text": "The housekeepers represent the hotel staff and create an image of the hotel by working towards keeping the hotel at high standards plus conducting themselves well while on job. There are certain rules the housekeepers need to follow." }, { "code": null, "e": 24602, "s": 24578, "text": "The housekeepers must −" }, { "code": null, "e": 24677, "s": 24602, "text": "Enter the floor with clean and tidy uniform, in a properly groomed manner." }, { "code": null, "e": 24752, "s": 24677, "text": "Enter the floor with clean and tidy uniform, in a properly groomed manner." }, { "code": null, "e": 24780, "s": 24752, "text": "Only use the service lifts." }, { "code": null, "e": 24808, "s": 24780, "text": "Only use the service lifts." }, { "code": null, "e": 24862, "s": 24808, "text": "Speak to the other working staff only when necessary." }, { "code": null, "e": 24916, "s": 24862, "text": "Speak to the other working staff only when necessary." }, { "code": null, "e": 24983, "s": 24916, "text": "Not walk by stamping the feet, run, or jump in the hotel premises." }, { "code": null, "e": 25050, "s": 24983, "text": "Not walk by stamping the feet, run, or jump in the hotel premises." }, { "code": null, "e": 25094, "s": 25050, "text": "Eat only in meal hours, not while cleaning." }, { "code": null, "e": 25138, "s": 25094, "text": "Eat only in meal hours, not while cleaning." }, { "code": null, "e": 25221, "s": 25138, "text": "Stand outside the guest room while speaking to the guest to respect their privacy." }, { "code": null, "e": 25304, "s": 25221, "text": "Stand outside the guest room while speaking to the guest to respect their privacy." }, { "code": null, "e": 25352, "s": 25304, "text": "Always keep the room doors open while cleaning." }, { "code": null, "e": 25400, "s": 25352, "text": "Always keep the room doors open while cleaning." }, { "code": null, "e": 25462, "s": 25400, "text": "Greet the guests with smile according to the time of the day." }, { "code": null, "e": 25524, "s": 25462, "text": "Greet the guests with smile according to the time of the day." }, { "code": null, "e": 25559, "s": 25524, "text": "Never answer the guest room phone." }, { "code": null, "e": 25594, "s": 25559, "text": "Never answer the guest room phone." }, { "code": null, "e": 25668, "s": 25594, "text": "Never use guest room phone of floor desk phones for making private calls." }, { "code": null, "e": 25742, "s": 25668, "text": "Never use guest room phone of floor desk phones for making private calls." }, { "code": null, "e": 25769, "s": 25742, "text": "Never use guest bathrooms." }, { "code": null, "e": 25796, "s": 25769, "text": "Never use guest bathrooms." }, { "code": null, "e": 25900, "s": 25796, "text": "Familiarize themselves with the faces of guests. This is especially important for the security purpose." }, { "code": null, "e": 26004, "s": 25900, "text": "Familiarize themselves with the faces of guests. This is especially important for the security purpose." }, { "code": null, "e": 26052, "s": 26004, "text": "Never use a guest room for unauthorized person." }, { "code": null, "e": 26100, "s": 26052, "text": "Never use a guest room for unauthorized person." }, { "code": null, "e": 26329, "s": 26100, "text": "Not accept any gift from the guests and politely deny them. If the guest insists to take and feels offended on denial, then mention the gift to the floor supervisor who can permit the attendant to take the gift out of the hotel." }, { "code": null, "e": 26558, "s": 26329, "text": "Not accept any gift from the guests and politely deny them. If the guest insists to take and feels offended on denial, then mention the gift to the floor supervisor who can permit the attendant to take the gift out of the hotel." }, { "code": null, "e": 26698, "s": 26558, "text": "Chilling out on the bed in your hotel room watching television while wearing your own pajamas, is sometimes the best part of your vacation." }, { "code": null, "e": 26735, "s": 26698, "text": "− Laura Marano, an American Actress." }, { "code": null, "e": 27057, "s": 26735, "text": "Housekeeping is the primary task the hotels need to cater for while providing service to its guests. The hotel management and especially executive of housekeeping department must ensure that the housekeeping functions are performed well in the hotel irrespective of the target guest type, size of hotel, and its location." }, { "code": null, "e": 27204, "s": 27057, "text": "The guest rooms are the primary source of hotel revenue. There are higher chances of retaining the guests if the guest rooms are absolutely clean." }, { "code": null, "e": 27301, "s": 27204, "text": "The hotels can be categorized depending upon their size, location, target market, and ownership." }, { "code": null, "e": 27391, "s": 27301, "text": "Hotels are categorized by the number of rooms to which service is provided. For example −" }, { "code": null, "e": 27420, "s": 27391, "text": "Below 200 rooms – Very Small" }, { "code": null, "e": 27444, "s": 27420, "text": "Up to 200 rooms – Small" }, { "code": null, "e": 27470, "s": 27444, "text": "200 to 399 rooms – Medium" }, { "code": null, "e": 27495, "s": 27470, "text": "400 to 700 rooms – Large" }, { "code": null, "e": 27522, "s": 27495, "text": "More than 700 rooms – Mega" }, { "code": null, "e": 27620, "s": 27522, "text": "This category is useful if the management needs to compare different hotels within the same size." }, { "code": null, "e": 27693, "s": 27620, "text": "They are categorized by considering their location with respect to city." }, { "code": null, "e": 27788, "s": 27693, "text": "Airport Hotels − They are located near airport. The guests in transit use them for short stay." }, { "code": null, "e": 27883, "s": 27788, "text": "Airport Hotels − They are located near airport. The guests in transit use them for short stay." }, { "code": null, "e": 27948, "s": 27883, "text": "Boatels − They are on the houseboats such as Shikara in Kashmir." }, { "code": null, "e": 28013, "s": 27948, "text": "Boatels − They are on the houseboats such as Shikara in Kashmir." }, { "code": null, "e": 28082, "s": 28013, "text": "City Center − Located in the heart of the city near commercial area." }, { "code": null, "e": 28151, "s": 28082, "text": "City Center − Located in the heart of the city near commercial area." }, { "code": null, "e": 28235, "s": 28151, "text": "Motel − They are small hotels usually located on highways. Transit guests use them." }, { "code": null, "e": 28319, "s": 28235, "text": "Motel − They are small hotels usually located on highways. Transit guests use them." }, { "code": null, "e": 28393, "s": 28319, "text": "Suburb Hotels − They are located near urban area. Budget guests use them." }, { "code": null, "e": 28467, "s": 28393, "text": "Suburb Hotels − They are located near urban area. Budget guests use them." }, { "code": null, "e": 28539, "s": 28467, "text": "Floating Hotels − They are on the cruise ships, large lakes, or rivers." }, { "code": null, "e": 28611, "s": 28539, "text": "Floating Hotels − They are on the cruise ships, large lakes, or rivers." }, { "code": null, "e": 28689, "s": 28611, "text": "Resorts − They are on the beaches, mountains, islands, or on the river banks." }, { "code": null, "e": 28767, "s": 28689, "text": "Resorts − They are on the beaches, mountains, islands, or on the river banks." }, { "code": null, "e": 28832, "s": 28767, "text": "Rotels − They are hotels on wheels such as Deccan Odyssey train." }, { "code": null, "e": 28897, "s": 28832, "text": "Rotels − They are hotels on wheels such as Deccan Odyssey train." }, { "code": null, "e": 28981, "s": 28897, "text": "Self-Catering Hotels − They are located at the same premises where the owner stays." }, { "code": null, "e": 29065, "s": 28981, "text": "Self-Catering Hotels − They are located at the same premises where the owner stays." }, { "code": null, "e": 29143, "s": 29065, "text": "Here, the hotels are categorized depending upon the target market they serve." }, { "code": null, "e": 29265, "s": 29143, "text": "Airport Hotels − They target the business clientele, airline passengers, or any guests with cancelled or delayed flights." }, { "code": null, "e": 29387, "s": 29265, "text": "Airport Hotels − They target the business clientele, airline passengers, or any guests with cancelled or delayed flights." }, { "code": null, "e": 29469, "s": 29387, "text": "Business Hotels − They primarily cater for the guests who are on business travel." }, { "code": null, "e": 29551, "s": 29469, "text": "Business Hotels − They primarily cater for the guests who are on business travel." }, { "code": null, "e": 29756, "s": 29551, "text": "Bed and Breakfast (B&B) − They are small hotels who target guests in transit or on leisure tour. The owner of B&B usually stays in the same premises and is responsible for serving breakfast to the guests." }, { "code": null, "e": 29961, "s": 29756, "text": "Bed and Breakfast (B&B) − They are small hotels who target guests in transit or on leisure tour. The owner of B&B usually stays in the same premises and is responsible for serving breakfast to the guests." }, { "code": null, "e": 30120, "s": 29961, "text": "Casino Hotels − They target the guests interested in gambling. Their functions of housekeeping is primary but food and beverage functions are just supportive." }, { "code": null, "e": 30279, "s": 30120, "text": "Casino Hotels − They target the guests interested in gambling. Their functions of housekeeping is primary but food and beverage functions are just supportive." }, { "code": null, "e": 30493, "s": 30279, "text": "Resorts − They target high-income busy professionals who wish to spend time away from city, noise, and crowd. They offer facilities such as spa, tennis court, fitness and center, sailing, snorkeling, and swimming." }, { "code": null, "e": 30707, "s": 30493, "text": "Resorts − They target high-income busy professionals who wish to spend time away from city, noise, and crowd. They offer facilities such as spa, tennis court, fitness and center, sailing, snorkeling, and swimming." }, { "code": null, "e": 30856, "s": 30707, "text": "Self-Catering Hotels − They target long stayers who prefer to cook themselves. They offer a small kitchen and kitchen amenities with the guest room." }, { "code": null, "e": 31005, "s": 30856, "text": "Self-Catering Hotels − They target long stayers who prefer to cook themselves. They offer a small kitchen and kitchen amenities with the guest room." }, { "code": null, "e": 31331, "s": 31005, "text": "Service Apartments − They are located in residential colonies. They provide long-term accommodation for guests. They need to execute an agreement with the guests for the stay of at least one month. All basic amenities such as kitchen, washing machine, dish washer, and beds are provided with once a week housekeeping service." }, { "code": null, "e": 31657, "s": 31331, "text": "Service Apartments − They are located in residential colonies. They provide long-term accommodation for guests. They need to execute an agreement with the guests for the stay of at least one month. All basic amenities such as kitchen, washing machine, dish washer, and beds are provided with once a week housekeeping service." }, { "code": null, "e": 31942, "s": 31657, "text": "Suite Hotels − These hotels offer a living room and an en suite bedroom. The professionals who need to interact with their clients/customers find these hotels a good choice because they can interact with their guests in small meetings without any interruption and sacrificing privacy." }, { "code": null, "e": 32227, "s": 31942, "text": "Suite Hotels − These hotels offer a living room and an en suite bedroom. The professionals who need to interact with their clients/customers find these hotels a good choice because they can interact with their guests in small meetings without any interruption and sacrificing privacy." }, { "code": null, "e": 32356, "s": 32227, "text": "B&B and Self Catering hotels are generally family owned hotels and are not governed or run by corporate policies and procedures." }, { "code": null, "e": 32547, "s": 32356, "text": "A chain of hotels or group of hotels such as Taj, Ramada, can have management affiliation with their other properties in the same group. They strictly are governed by predetermined policies." }, { "code": null, "e": 32885, "s": 32547, "text": "The star rating system is a guideline for a customer that denotes what to expect from the hotel service at the time of booking. However, there is no clear distinguishing method to divide hotels into various star rating categories till today; but a guest can assume that more the number of stars, more is the luxury provided by the hotel." }, { "code": null, "e": 33173, "s": 32885, "text": "One Star − A guest can expect a small hotel operated and managed by the owner and family. The ambience as more personal and the guest rooms with basic amenities. The restaurant would be at a walking distance. There would be a small commercial area and a nearby public transportation hub." }, { "code": null, "e": 33461, "s": 33173, "text": "One Star − A guest can expect a small hotel operated and managed by the owner and family. The ambience as more personal and the guest rooms with basic amenities. The restaurant would be at a walking distance. There would be a small commercial area and a nearby public transportation hub." }, { "code": null, "e": 33771, "s": 33461, "text": "Two-Star − These hotels are mostly part of a chain of hotels that offer consistent quality but limited amenities. They are either small or medium size hotels with a phone and TV. They lack the convenience of room service, but provide a small on-site restaurant at a walking distance within the hotel premises." }, { "code": null, "e": 34081, "s": 33771, "text": "Two-Star − These hotels are mostly part of a chain of hotels that offer consistent quality but limited amenities. They are either small or medium size hotels with a phone and TV. They lack the convenience of room service, but provide a small on-site restaurant at a walking distance within the hotel premises." }, { "code": null, "e": 34436, "s": 34081, "text": "Three-Star − These hotels are usually located near a major business center, express way, and/or shopping area. The rooms are clean and spacious rooms, and decorative lobbies. An on-site restaurant offers all meals such as breakfast, lunch, and dinner. The facilities such as valet and room service, fitness center, and a swimming pool are also available." }, { "code": null, "e": 34791, "s": 34436, "text": "Three-Star − These hotels are usually located near a major business center, express way, and/or shopping area. The rooms are clean and spacious rooms, and decorative lobbies. An on-site restaurant offers all meals such as breakfast, lunch, and dinner. The facilities such as valet and room service, fitness center, and a swimming pool are also available." }, { "code": null, "e": 35181, "s": 34791, "text": "Four-Star − This hotel would be large, often standing as a part of a cluster of similar hotels with a formal appearance and very good services. The hotel would be located in the prime area of the city around shopping, dining, and entertainment joints. The guest can expect furnished and clean rooms, restaurants, room service, valet parking, and a fitness center within the hotel premises." }, { "code": null, "e": 35571, "s": 35181, "text": "Four-Star − This hotel would be large, often standing as a part of a cluster of similar hotels with a formal appearance and very good services. The hotel would be located in the prime area of the city around shopping, dining, and entertainment joints. The guest can expect furnished and clean rooms, restaurants, room service, valet parking, and a fitness center within the hotel premises." }, { "code": null, "e": 36096, "s": 35571, "text": "Five-Star − This hotel would be large and luxurious, which offers the highest degree of room and personal service. It is built with beautiful architecture, and is managed keeping elegance and style in mind. The guest rooms are equipped with high quality linens, TV, bathtubs, and special outside view from the room. The hotel provides multiple eating joints in its premises such as coffee shops, restaurants, poolside snack joint, and bar. They also provide 24X7 room service, valet service, and personal protection service." }, { "code": null, "e": 36621, "s": 36096, "text": "Five-Star − This hotel would be large and luxurious, which offers the highest degree of room and personal service. It is built with beautiful architecture, and is managed keeping elegance and style in mind. The guest rooms are equipped with high quality linens, TV, bathtubs, and special outside view from the room. The hotel provides multiple eating joints in its premises such as coffee shops, restaurants, poolside snack joint, and bar. They also provide 24X7 room service, valet service, and personal protection service." }, { "code": null, "e": 36774, "s": 36621, "text": "The condition of guest rooms maintained by housekeeping is the most vital factor as far as the customer satisfaction in the hotel business is concerned." }, { "code": null, "e": 37002, "s": 36774, "text": "Single Room − A room with the facility of single bed. It is meant for single occupancy. It has an attached bathroom, a small dressing table, a small bedside table, and a small writing table. Sometimes it has a single chair too." }, { "code": null, "e": 37230, "s": 37002, "text": "Single Room − A room with the facility of single bed. It is meant for single occupancy. It has an attached bathroom, a small dressing table, a small bedside table, and a small writing table. Sometimes it has a single chair too." }, { "code": null, "e": 37559, "s": 37230, "text": "Double Room − A room with the facility of double bed. There are two variants in this type depending upon the size of the bed\n\nKing Double Room (with king size double bed)\nQueen Double Room (with queen size double bed)\n\nIt is equipped with adequate furniture such as dressing table and a writing table, a TV, and a small fridge.\n" }, { "code": null, "e": 37684, "s": 37559, "text": "Double Room − A room with the facility of double bed. There are two variants in this type depending upon the size of the bed" }, { "code": null, "e": 37729, "s": 37684, "text": "King Double Room (with king size double bed)" }, { "code": null, "e": 37776, "s": 37729, "text": "Queen Double Room (with queen size double bed)" }, { "code": null, "e": 37885, "s": 37776, "text": "It is equipped with adequate furniture such as dressing table and a writing table, a TV, and a small fridge." }, { "code": null, "e": 38187, "s": 37885, "text": "Deluxe Room − They are available in Single Deluxe and Double Deluxe variants. Deluxe room is well furnished. Some amenities are attached bathroom, a dressing table, a bedside table, a small writing table, a TV, and a small fridge. The floor is covered with carpet and most suitable for small families." }, { "code": null, "e": 38489, "s": 38187, "text": "Deluxe Room − They are available in Single Deluxe and Double Deluxe variants. Deluxe room is well furnished. Some amenities are attached bathroom, a dressing table, a bedside table, a small writing table, a TV, and a small fridge. The floor is covered with carpet and most suitable for small families." }, { "code": null, "e": 38644, "s": 38489, "text": "Double-Double (Twin Double) Room − This room provides two double beds with separate headboards. It is ideal for a family with two children below 12 years." }, { "code": null, "e": 38799, "s": 38644, "text": "Double-Double (Twin Double) Room − This room provides two double beds with separate headboards. It is ideal for a family with two children below 12 years." }, { "code": null, "e": 38976, "s": 38799, "text": "Twin Room − This room provides two single beds with separate headboards. It is meant for two independent people. It also has a single bedside table shared between the two beds." }, { "code": null, "e": 39153, "s": 38976, "text": "Twin Room − This room provides two single beds with separate headboards. It is meant for two independent people. It also has a single bedside table shared between the two beds." }, { "code": null, "e": 39312, "s": 39153, "text": "Hollywood Twin Room − This room provides two single beds with a common headboard. If a need arises, the two beds can be brought together to form a double bed." }, { "code": null, "e": 39471, "s": 39312, "text": "Hollywood Twin Room − This room provides two single beds with a common headboard. If a need arises, the two beds can be brought together to form a double bed." }, { "code": null, "e": 39585, "s": 39471, "text": "Duplex Room − This type is composed of two rooms located on two different floors, connected with internal stairs." }, { "code": null, "e": 39699, "s": 39585, "text": "Duplex Room − This type is composed of two rooms located on two different floors, connected with internal stairs." }, { "code": null, "e": 39805, "s": 39699, "text": "Cabana − This type of room faces water body, beach, or a swimming pool. It generally has a large balcony." }, { "code": null, "e": 39911, "s": 39805, "text": "Cabana − This type of room faces water body, beach, or a swimming pool. It generally has a large balcony." }, { "code": null, "e": 40136, "s": 39911, "text": "Studio − They are twin adjacent rooms: A living room with sofa, coffee table and chairs, and a bedroom. It is also equipped with fan/air conditioner, a small kitchen corner, and a dining area. The furniture is often compact." }, { "code": null, "e": 40361, "s": 40136, "text": "Studio − They are twin adjacent rooms: A living room with sofa, coffee table and chairs, and a bedroom. It is also equipped with fan/air conditioner, a small kitchen corner, and a dining area. The furniture is often compact." }, { "code": null, "e": 40424, "s": 40361, "text": "Lanai − This room faces a landscape, a waterfall, or a garden." }, { "code": null, "e": 40487, "s": 40424, "text": "Lanai − This room faces a landscape, a waterfall, or a garden." }, { "code": null, "e": 41090, "s": 40487, "text": "Suite −It is composed of one or more bedrooms, a living room, and a dining area. It is excellent for the guests who prefer more space, wish to entertain their guests without interruption and giving up privacy.There are various types of suites −\n\nRegular Suite − Best for business travelers.\nPenthouse Suite − Luxurious than the regular suite. It is provided with the access to terrace space above the suite. It is aloof from crowd and provides abird’s eye view of the city. It has all the amenities and structure similar to a regular suite.\nPresidential Suite − The best possible suite in the hotel.\n\n\n" }, { "code": null, "e": 41335, "s": 41090, "text": "Suite −It is composed of one or more bedrooms, a living room, and a dining area. It is excellent for the guests who prefer more space, wish to entertain their guests without interruption and giving up privacy.There are various types of suites −" }, { "code": null, "e": 41380, "s": 41335, "text": "Regular Suite − Best for business travelers." }, { "code": null, "e": 41425, "s": 41380, "text": "Regular Suite − Best for business travelers." }, { "code": null, "e": 41675, "s": 41425, "text": "Penthouse Suite − Luxurious than the regular suite. It is provided with the access to terrace space above the suite. It is aloof from crowd and provides abird’s eye view of the city. It has all the amenities and structure similar to a regular suite." }, { "code": null, "e": 41925, "s": 41675, "text": "Penthouse Suite − Luxurious than the regular suite. It is provided with the access to terrace space above the suite. It is aloof from crowd and provides abird’s eye view of the city. It has all the amenities and structure similar to a regular suite." }, { "code": null, "e": 41985, "s": 41925, "text": "Presidential Suite − The best possible suite in the hotel.\n" }, { "code": null, "e": 42044, "s": 41985, "text": "Presidential Suite − The best possible suite in the hotel." }, { "code": null, "e": 42520, "s": 42044, "text": "Sico − This is a kind of multipurpose room, which can be used as a meeting room during the day and as a bedroom during the night. These rooms have special beds called Murphy Bed that can be folded entirely against a wall. This bed may or may not have headboard. The lower face of the bed which becomes visible after folding or placing upright, has a decorative wall paper, mirror, or a painting. After folding the bed, the room can accommodate sitting for five to ten people." }, { "code": null, "e": 42996, "s": 42520, "text": "Sico − This is a kind of multipurpose room, which can be used as a meeting room during the day and as a bedroom during the night. These rooms have special beds called Murphy Bed that can be folded entirely against a wall. This bed may or may not have headboard. The lower face of the bed which becomes visible after folding or placing upright, has a decorative wall paper, mirror, or a painting. After folding the bed, the room can accommodate sitting for five to ten people." }, { "code": null, "e": 43204, "s": 42996, "text": "VIP amenities are always something like the cherry on the cake. The VIPs are treated with extra attention, pamper, and care. Hotels provide the following amenities to the VIPs depending upon their policies −" }, { "code": null, "e": 43286, "s": 43204, "text": "Executive Front Desk or Executive Housekeeper escorting the guest up to the room." }, { "code": null, "e": 43368, "s": 43286, "text": "Executive Front Desk or Executive Housekeeper escorting the guest up to the room." }, { "code": null, "e": 43476, "s": 43368, "text": "A welcome document kit containing note from a General Manager (GM) of the hotel, spa card, and a hotel map." }, { "code": null, "e": 43584, "s": 43476, "text": "A welcome document kit containing note from a General Manager (GM) of the hotel, spa card, and a hotel map." }, { "code": null, "e": 43639, "s": 43584, "text": "Complete housekeeping service with daily linen change." }, { "code": null, "e": 43694, "s": 43639, "text": "Complete housekeeping service with daily linen change." }, { "code": null, "e": 43796, "s": 43694, "text": "A snack kit often containing packed snacks, assorted nuts, fruits, cheese, or cookies, and beverages." }, { "code": null, "e": 43898, "s": 43796, "text": "A snack kit often containing packed snacks, assorted nuts, fruits, cheese, or cookies, and beverages." }, { "code": null, "e": 43982, "s": 43898, "text": "A vanity kit containing cotton balls, makeup removers, lip balm, and au-de-cologne." }, { "code": null, "e": 44066, "s": 43982, "text": "A vanity kit containing cotton balls, makeup removers, lip balm, and au-de-cologne." }, { "code": null, "e": 44204, "s": 44066, "text": "A bathroom kit with soap dispenser, upgraded robe, tissue box, face mist, after-shower gel, cotton slippers, toilet mat, and a terry mat." }, { "code": null, "e": 44342, "s": 44204, "text": "A bathroom kit with soap dispenser, upgraded robe, tissue box, face mist, after-shower gel, cotton slippers, toilet mat, and a terry mat." }, { "code": null, "e": 44483, "s": 44342, "text": "In special cases, a romance kit containing a bottle of wine or Champaign, paired with chocolate dipped strawberries or bite size chocolates." }, { "code": null, "e": 44624, "s": 44483, "text": "In special cases, a romance kit containing a bottle of wine or Champaign, paired with chocolate dipped strawberries or bite size chocolates." }, { "code": null, "e": 44669, "s": 44624, "text": "Small bag packs for the kids below 12 years." }, { "code": null, "e": 44714, "s": 44669, "text": "Small bag packs for the kids below 12 years." }, { "code": null, "e": 44761, "s": 44714, "text": "A number of servings of award winning dessert." }, { "code": null, "e": 44808, "s": 44761, "text": "A number of servings of award winning dessert." }, { "code": null, "e": 44967, "s": 44808, "text": "Spring cleaning doesn’t have to be a dreaded list of chores. It can be a rewarding experience that helps provide some structure and organization in your life." }, { "code": null, "e": 45037, "s": 44967, "text": "− Peter Walsh, Professional Organizer, Writer, and Media Personality." }, { "code": null, "e": 45362, "s": 45037, "text": "Cleaning is one of the major tasks the housekeeping force performs. It carries out cleanings when the guests are about to occupy their room, while they are staying in the hotel, and immediately after the guests vacate the room. The housekeeping also cleans the public area, which is often shared by a large number of guests." }, { "code": null, "e": 45607, "s": 45362, "text": "The Check in rooms are cleaned when the guest is about to occupy the room. A checklist of room readiness is shared between the guest room supervisor and the guest room attendants. The supervisor inspects the readiness of the room for occupancy." }, { "code": null, "e": 45667, "s": 45607, "text": "The guest room attendant performs the following cleanings −" }, { "code": null, "e": 45768, "s": 45667, "text": "Checking power switches, air conditioner, TV, and other electronic appliances for healthy condition." }, { "code": null, "e": 45869, "s": 45768, "text": "Checking power switches, air conditioner, TV, and other electronic appliances for healthy condition." }, { "code": null, "e": 45933, "s": 45869, "text": "Making bed with the fresh linen, pillow cases, and bedside mat." }, { "code": null, "e": 45997, "s": 45933, "text": "Making bed with the fresh linen, pillow cases, and bedside mat." }, { "code": null, "e": 46085, "s": 45997, "text": "Cleaning ashtrays and dustbins, replacing if required; and putting fresh paper stripes." }, { "code": null, "e": 46173, "s": 46085, "text": "Cleaning ashtrays and dustbins, replacing if required; and putting fresh paper stripes." }, { "code": null, "e": 46246, "s": 46173, "text": "Checking stationery and vanity supplies.Replacing/refilling if required." }, { "code": null, "e": 46319, "s": 46246, "text": "Checking stationery and vanity supplies.Replacing/refilling if required." }, { "code": null, "e": 46386, "s": 46319, "text": "Cleaning the bathroom: floor, walls, toilet, shower area, and tub." }, { "code": null, "e": 46453, "s": 46386, "text": "Cleaning the bathroom: floor, walls, toilet, shower area, and tub." }, { "code": null, "e": 46528, "s": 46453, "text": "Checking bathroom supplies. Replacing the used supplies with the new ones." }, { "code": null, "e": 46603, "s": 46528, "text": "Checking bathroom supplies. Replacing the used supplies with the new ones." }, { "code": null, "e": 46687, "s": 46603, "text": "Checking the room curtains and drapes for stains, replacing if needed, and closing." }, { "code": null, "e": 46771, "s": 46687, "text": "Checking the room curtains and drapes for stains, replacing if needed, and closing." }, { "code": null, "e": 46819, "s": 46771, "text": "Discarding the used supplies in the guest room." }, { "code": null, "e": 46867, "s": 46819, "text": "Discarding the used supplies in the guest room." }, { "code": null, "e": 46896, "s": 46867, "text": "Spraying the room freshener." }, { "code": null, "e": 46925, "s": 46896, "text": "Spraying the room freshener." }, { "code": null, "e": 47086, "s": 46925, "text": "The room is cleaned when the guest is occupying the room. It includes cleaning and keeping all occupied rooms twice per day on guests’ requests and convenience." }, { "code": null, "e": 47142, "s": 47086, "text": "Entering the guest room by following the set procedure." }, { "code": null, "e": 47198, "s": 47142, "text": "Entering the guest room by following the set procedure." }, { "code": null, "e": 47221, "s": 47198, "text": "Clearing the dustbins." }, { "code": null, "e": 47244, "s": 47221, "text": "Clearing the dustbins." }, { "code": null, "e": 47303, "s": 47244, "text": "Collecting the used linen and putting it in the linen bag." }, { "code": null, "e": 47362, "s": 47303, "text": "Collecting the used linen and putting it in the linen bag." }, { "code": null, "e": 47378, "s": 47362, "text": "Making the bed." }, { "code": null, "e": 47394, "s": 47378, "text": "Making the bed." }, { "code": null, "e": 47431, "s": 47394, "text": "Carrying out the guest room dusting." }, { "code": null, "e": 47468, "s": 47431, "text": "Carrying out the guest room dusting." }, { "code": null, "e": 47506, "s": 47468, "text": "Vacuuming of carpet and bedside mats." }, { "code": null, "e": 47544, "s": 47506, "text": "Vacuuming of carpet and bedside mats." }, { "code": null, "e": 47606, "s": 47544, "text": "Cleaning the bathroom and replenishing the bathroom supplies." }, { "code": null, "e": 47668, "s": 47606, "text": "Cleaning the bathroom and replenishing the bathroom supplies." }, { "code": null, "e": 47761, "s": 47668, "text": "Checking the functionality of light bulbs, television, electric kettle, and intercom device." }, { "code": null, "e": 47854, "s": 47761, "text": "Checking the functionality of light bulbs, television, electric kettle, and intercom device." }, { "code": null, "e": 47989, "s": 47854, "text": "This cleaning is performed when the guest vacates the guest room and proceeds for hotel check-out formalities. The cleaning involves −" }, { "code": null, "e": 48072, "s": 47989, "text": "Assembling bed, chairs, settees, and other furniture and placing it appropriately." }, { "code": null, "e": 48155, "s": 48072, "text": "Assembling bed, chairs, settees, and other furniture and placing it appropriately." }, { "code": null, "e": 48193, "s": 48155, "text": "Wiping guest room floor with wet mop." }, { "code": null, "e": 48231, "s": 48193, "text": "Wiping guest room floor with wet mop." }, { "code": null, "e": 48309, "s": 48231, "text": "Cleaning the writing tables, assembling and placing stationery appropriately." }, { "code": null, "e": 48387, "s": 48309, "text": "Cleaning the writing tables, assembling and placing stationery appropriately." }, { "code": null, "e": 48481, "s": 48387, "text": "Checking under the beds and chairs, and in the locker for any articles the guest left behind." }, { "code": null, "e": 48575, "s": 48481, "text": "Checking under the beds and chairs, and in the locker for any articles the guest left behind." }, { "code": null, "e": 48691, "s": 48575, "text": "All personal stuff, documents, articles left in the room (if any) are removed and deposited to Lost and Found desk." }, { "code": null, "e": 48807, "s": 48691, "text": "All personal stuff, documents, articles left in the room (if any) are removed and deposited to Lost and Found desk." }, { "code": null, "e": 48853, "s": 48807, "text": "Cleaning all walls of bathroom with wet wipe." }, { "code": null, "e": 48899, "s": 48853, "text": "Cleaning all walls of bathroom with wet wipe." }, { "code": null, "e": 48981, "s": 48899, "text": "Cleaning all electric appliances such as microwave, fan, refrigerator and others." }, { "code": null, "e": 49063, "s": 48981, "text": "Cleaning all electric appliances such as microwave, fan, refrigerator and others." }, { "code": null, "e": 49130, "s": 49063, "text": "Keeping heaters/air conditioners at lowest power consuming option." }, { "code": null, "e": 49197, "s": 49130, "text": "Keeping heaters/air conditioners at lowest power consuming option." }, { "code": null, "e": 49242, "s": 49197, "text": "Switching off the room light and television." }, { "code": null, "e": 49287, "s": 49242, "text": "Switching off the room light and television." }, { "code": null, "e": 49345, "s": 49287, "text": "Locking the guest room door and cleaning area outside it." }, { "code": null, "e": 49403, "s": 49345, "text": "Locking the guest room door and cleaning area outside it." }, { "code": null, "e": 49445, "s": 49403, "text": "Depositing the keys at front office desk." }, { "code": null, "e": 49487, "s": 49445, "text": "Depositing the keys at front office desk." }, { "code": null, "e": 49768, "s": 49487, "text": "The task of cleaning is very exhausting. It is divided among a number of housekeeping staff depending upon expertise. Some cleaning such as occupied guest room cleaning requires to be carried out twice on daily basis. The check-in and check-out cleanings are little less frequent." }, { "code": null, "e": 49948, "s": 49768, "text": "Further, the cleaning of air-conditioner and refrigerator is less frequent. Thus, depending upon frequency of use of a particular area or device, the frequency of cleaning varies." }, { "code": null, "e": 50277, "s": 49948, "text": "This type of cleaning is practiced in the hotels located in cold as well as warm regions. The name depicts cleaning the house in the first few warm days of spring when there is adequate sunlight to reach the corners and the floors of the room. The areas, which are not much accessed, are also cleaned during the Spring Cleaning." }, { "code": null, "e": 50534, "s": 50277, "text": "Spring cleaning is generally performed once a year by moving furniture and cleaning the guest rooms entirely for dust, stains, broken furniture, and garbage. It is also called as Deep Cleaning as it is ensured that no portion of the area is left uncleaned." }, { "code": null, "e": 50601, "s": 50534, "text": "The public areas are shared commonly among guests. They include − " }, { "code": null, "e": 50909, "s": 50601, "text": "Front Office and Lobby is highly frequented. It must be clean at all hours of the day. The housekeeping staff needs to clean desks, fans, ceiling, chairs, and computers. The staff also cleans and disinfects the telephone devices, keyboards, flooring, corridors, and glass doors at the entrance of the lobby." }, { "code": null, "e": 51241, "s": 50909, "text": "The dining area is the next most frequently visited area. The housekeeping staff puts in good efforts for lighting, chandeliers, and cleaning the ceiling, furniture, and décor items. It also includes spreading the clean dining linen on the dining tables and keeping the floor clean. It is generally done when the area is not busy." }, { "code": null, "e": 51454, "s": 51241, "text": "The house keeping staff cleans lifts preferably early morning to avoid rush for use. They stop it at the ground floor, its doors are kept open, and it is then cleaned starting from top and working towards bottom." }, { "code": null, "e": 51789, "s": 51454, "text": "Cleaning of the swimming pools is highly required during summer. It can be conducted by the hotel if it has an in-house expertise, or it can be contracted with an agency. Cleaning of swimming pool involves catching any leaves, purifying the pool water, and cleaning the areas surrounding the pool; including shower and changing rooms." }, { "code": null, "e": 52037, "s": 51789, "text": "These days, the hotels keep their private team of gardeners. Watering and trimming the trees and shrubs, fertilizing the plants, raking the fall leaves, and Arbosculpture (an art of shaping trees into wonderful shapes), is taken care by this team." }, { "code": null, "e": 52178, "s": 52037, "text": "It mostly involves hard sweeping the parking space, removing the cobwebs under the parking shades, and putting up appropriate guiding signs." }, { "code": null, "e": 52424, "s": 52178, "text": "My father was a general manager with Hyatt, so we lived in the hotel so he would be close by if there were any problems. My mum was always adamant about us not abusing it. So I still had to clean my room. Housekeeping would never come and do it." }, { "code": null, "e": 52478, "s": 52424, "text": "− Dianna Agron, American Actress, Singer, and Dancer." }, { "code": null, "e": 52739, "s": 52478, "text": "The housekeeping staff needs to clean various guest rooms, guest bathrooms, and a number of public areas in the hotel. The staff needs to take the help of various cleaning equipment while trying to keep the hotel premises to the highest standard of appearance." }, { "code": null, "e": 52814, "s": 52739, "text": "Today, there is a wide range of cleaning products available in the market." }, { "code": null, "e": 52873, "s": 52814, "text": "The cleaning equipment are advantageous in multiple ways −" }, { "code": null, "e": 52938, "s": 52873, "text": "Equally effective for general as well as tougher cleaning tasks." }, { "code": null, "e": 53003, "s": 52938, "text": "Equally effective for general as well as tougher cleaning tasks." }, { "code": null, "e": 53029, "s": 53003, "text": "High cleaning capability." }, { "code": null, "e": 53055, "s": 53029, "text": "High cleaning capability." }, { "code": null, "e": 53101, "s": 53055, "text": "Reduce work fatigue and increaseproductivity." }, { "code": null, "e": 53147, "s": 53101, "text": "Reduce work fatigue and increaseproductivity." }, { "code": null, "e": 53190, "s": 53147, "text": "Save the time of hotel housekeeping staff." }, { "code": null, "e": 53233, "s": 53190, "text": "Save the time of hotel housekeeping staff." }, { "code": null, "e": 53342, "s": 53233, "text": "High maneuverability.They can reach any corner or height of the room, which is otherwise difficult to reach." }, { "code": null, "e": 53451, "s": 53342, "text": "High maneuverability.They can reach any corner or height of the room, which is otherwise difficult to reach." }, { "code": null, "e": 53504, "s": 53451, "text": "Eco-friendly, widely available, and easy to operate." }, { "code": null, "e": 53557, "s": 53504, "text": "Eco-friendly, widely available, and easy to operate." }, { "code": null, "e": 53669, "s": 53557, "text": "They give protection from injuries occurring while cleaning when they are handled by using proper instructions." }, { "code": null, "e": 53781, "s": 53669, "text": "They give protection from injuries occurring while cleaning when they are handled by using proper instructions." }, { "code": null, "e": 53824, "s": 53781, "text": "There are broadly categorized as follows −" }, { "code": null, "e": 53939, "s": 53824, "text": "As the name suggests, they are used manually to keep the surfaces clean. Some commonly used manual equipment are −" }, { "code": null, "e": 54143, "s": 53939, "text": "Abrasives − They are the sharpening stones or grit papers used to polish metal or wooden surfaces. There are various abrasives depending upon the size of grit and adhesion of grit particles on the paper." }, { "code": null, "e": 54347, "s": 54143, "text": "Abrasives − They are the sharpening stones or grit papers used to polish metal or wooden surfaces. There are various abrasives depending upon the size of grit and adhesion of grit particles on the paper." }, { "code": null, "e": 54552, "s": 54347, "text": "Brushes − They are handheld flat brushes with bristles to dust the plain surfaces as well as the corners. They come with non-slip handles and stiff scratch-free bristles. They help removing stubborn dust." }, { "code": null, "e": 54757, "s": 54552, "text": "Brushes − They are handheld flat brushes with bristles to dust the plain surfaces as well as the corners. They come with non-slip handles and stiff scratch-free bristles. They help removing stubborn dust." }, { "code": null, "e": 55046, "s": 54757, "text": "Chambermaid’s Trolley/Housekeeping Trolley − This trolley is large enough to keep all the guest room and guest bathroom supplies in an organized manner. It makes the housekeeping staff to move it around and carry large number of items in one go while keeping and cleaning the guest rooms." }, { "code": null, "e": 55335, "s": 55046, "text": "Chambermaid’s Trolley/Housekeeping Trolley − This trolley is large enough to keep all the guest room and guest bathroom supplies in an organized manner. It makes the housekeeping staff to move it around and carry large number of items in one go while keeping and cleaning the guest rooms." }, { "code": null, "e": 55408, "s": 55335, "text": "Dustbins − They are used to collect daily garbage produced in the hotel." }, { "code": null, "e": 55481, "s": 55408, "text": "Dustbins − They are used to collect daily garbage produced in the hotel." }, { "code": null, "e": 55553, "s": 55481, "text": "Dusting Cloths − They are soft cloths used for wiping the surface dust." }, { "code": null, "e": 55625, "s": 55553, "text": "Dusting Cloths − They are soft cloths used for wiping the surface dust." }, { "code": null, "e": 55726, "s": 55625, "text": "Dustpans − They are used to collect dust and garbage from the floor and putting it into the dustbin." }, { "code": null, "e": 55827, "s": 55726, "text": "Dustpans − They are used to collect dust and garbage from the floor and putting it into the dustbin." }, { "code": null, "e": 56082, "s": 55827, "text": "Janitor’s trolley − It is a trolley that stores cleaning supplies such as detergents, spray bottles, dustbin, mop, and dusting cloths, all in a compact manner. It can be moved around easily. It fulfills the challenge of modern day housekeeping in hotels." }, { "code": null, "e": 56337, "s": 56082, "text": "Janitor’s trolley − It is a trolley that stores cleaning supplies such as detergents, spray bottles, dustbin, mop, and dusting cloths, all in a compact manner. It can be moved around easily. It fulfills the challenge of modern day housekeeping in hotels." }, { "code": null, "e": 56692, "s": 56337, "text": "Mops − There are various types of mops such as string mops, flat mops, dust mops, and synthetic mops. Mops are generally made of flat cotton strings or heavy-duty sponges fixed on the metal frames. The cotton mops have high absorbing ability but need more care unlike the synthetic mops that offer almost zero absorbing ability and very less maintenance." }, { "code": null, "e": 57047, "s": 56692, "text": "Mops − There are various types of mops such as string mops, flat mops, dust mops, and synthetic mops. Mops are generally made of flat cotton strings or heavy-duty sponges fixed on the metal frames. The cotton mops have high absorbing ability but need more care unlike the synthetic mops that offer almost zero absorbing ability and very less maintenance." }, { "code": null, "e": 57275, "s": 57047, "text": "Mop Wringer trolley − A mop bucket cart (or mop trolley) is a wheeled bucket that allows its user to wring out a wet mop without getting the hands dirty. The mops are squeezed between two surfaces to remove dirty water from it." }, { "code": null, "e": 57503, "s": 57275, "text": "Mop Wringer trolley − A mop bucket cart (or mop trolley) is a wheeled bucket that allows its user to wring out a wet mop without getting the hands dirty. The mops are squeezed between two surfaces to remove dirty water from it." }, { "code": null, "e": 57909, "s": 57503, "text": "Scarifying machine − It is used for keeping gardens, golf courts, and lawn in the hotel premises. It cuts through the turf, and removes moss and dead grass. It helps grow spongy lawn. Scarifiers have fixed knife blades attached to the rotary cylinder. They cut through the grass by which the offshoots are separated into lots of individual plants. This helps to thicken up the turf and improve its health." }, { "code": null, "e": 58315, "s": 57909, "text": "Scarifying machine − It is used for keeping gardens, golf courts, and lawn in the hotel premises. It cuts through the turf, and removes moss and dead grass. It helps grow spongy lawn. Scarifiers have fixed knife blades attached to the rotary cylinder. They cut through the grass by which the offshoots are separated into lots of individual plants. This helps to thicken up the turf and improve its health." }, { "code": null, "e": 58509, "s": 58315, "text": "Spray Bottles − They are used to spray water or chemical solutions on the surface that needs cleaning. They are also used to spray water on the delicate flowers or leaves of flower arrangement." }, { "code": null, "e": 58703, "s": 58509, "text": "Spray Bottles − They are used to spray water or chemical solutions on the surface that needs cleaning. They are also used to spray water on the delicate flowers or leaves of flower arrangement." }, { "code": null, "e": 58873, "s": 58703, "text": "As the name depicts, these equipment require electrical power to operate. They are operated either on AC power or on the battery. Some important electric equipment are −" }, { "code": null, "e": 59135, "s": 58873, "text": "Box Sweeper − It is electric sweeper that consists of a friction brush. The brush often is fit to revolve vertically or horizontally, when the equipment moves on the surface. It can clean floors as well as carpets. The wider the better is the box sweeper brush." }, { "code": null, "e": 59397, "s": 59135, "text": "Box Sweeper − It is electric sweeper that consists of a friction brush. The brush often is fit to revolve vertically or horizontally, when the equipment moves on the surface. It can clean floors as well as carpets. The wider the better is the box sweeper brush." }, { "code": null, "e": 59603, "s": 59397, "text": "Vacuum Cleaner − It is again a majorly used equipment in hotel housekeeping. It comes with a suction motor fit in a case, a hose, and various attachment for delicate as well as tough cleaning requirements." }, { "code": null, "e": 59809, "s": 59603, "text": "Vacuum Cleaner − It is again a majorly used equipment in hotel housekeeping. It comes with a suction motor fit in a case, a hose, and various attachment for delicate as well as tough cleaning requirements." }, { "code": null, "e": 59911, "s": 59809, "text": "Polishing Machine − They are used to add a shine to the floors of most frequented areas of the hotel." }, { "code": null, "e": 60013, "s": 59911, "text": "Polishing Machine − They are used to add a shine to the floors of most frequented areas of the hotel." }, { "code": null, "e": 60308, "s": 60013, "text": "Scrubber − It is a floor care accessory that comes with handheld electrically operated scrubber. It is used where only mopping doesn’t suffice. It can scrub stubborn and sticky stains on the floors of cafeterias, restaurants, lobbies, and fitness areas where people can take food and beverages." }, { "code": null, "e": 60603, "s": 60308, "text": "Scrubber − It is a floor care accessory that comes with handheld electrically operated scrubber. It is used where only mopping doesn’t suffice. It can scrub stubborn and sticky stains on the floors of cafeterias, restaurants, lobbies, and fitness areas where people can take food and beverages." }, { "code": null, "e": 60871, "s": 60603, "text": "Vapor Cleaning Machine − They are used where the chemical odors are not desired. They are equipped for continuous operation. They heat up quickly and work with low amount of moisture. They kill the beg bugs and their eggs, the yielding a completely clean environment." }, { "code": null, "e": 61139, "s": 60871, "text": "Vapor Cleaning Machine − They are used where the chemical odors are not desired. They are equipped for continuous operation. They heat up quickly and work with low amount of moisture. They kill the beg bugs and their eggs, the yielding a completely clean environment." }, { "code": null, "e": 61304, "s": 61139, "text": "Apart from water and regular detergents, the housekeeping staff also uses cleaning chemicals, which are often available in the form of liquids, blocks, and powders." }, { "code": null, "e": 61558, "s": 61304, "text": "Water − It is the most commonly used medium for cleaning and rinsing. The housekeeping staff needs to use only soft water because hard water cannot dilute detergents properly. Non-oily and non-greasy stains such as ink stains can be removed using water." }, { "code": null, "e": 61812, "s": 61558, "text": "Water − It is the most commonly used medium for cleaning and rinsing. The housekeeping staff needs to use only soft water because hard water cannot dilute detergents properly. Non-oily and non-greasy stains such as ink stains can be removed using water." }, { "code": null, "e": 61871, "s": 61812, "text": "Vinegar − It is used in removing light stains in the bath." }, { "code": null, "e": 61930, "s": 61871, "text": "Vinegar − It is used in removing light stains in the bath." }, { "code": null, "e": 62134, "s": 61930, "text": "Bathroom Cleaners − They come in liquid form for easy cleaning. They clean, descale, and disinfect the bathroom walls, bathtubs, bathroom flooring, sinks, and showers. They often contain phosphoric acid." }, { "code": null, "e": 62338, "s": 62134, "text": "Bathroom Cleaners − They come in liquid form for easy cleaning. They clean, descale, and disinfect the bathroom walls, bathtubs, bathroom flooring, sinks, and showers. They often contain phosphoric acid." }, { "code": null, "e": 62527, "s": 62338, "text": "Clean Air Sprays − They are best for freshening the hotel corridors, washrooms, bathrooms, and reception areas. These sprays remove the pungent smell of tobacco, smoke, and organic wastes." }, { "code": null, "e": 62716, "s": 62527, "text": "Clean Air Sprays − They are best for freshening the hotel corridors, washrooms, bathrooms, and reception areas. These sprays remove the pungent smell of tobacco, smoke, and organic wastes." }, { "code": null, "e": 62946, "s": 62716, "text": "Degreaser − This is mainly used in bars to remove the marks of grease and lipstick that cannot be removed by traditional washing of glasses and cups. Degreaser restores the surface shine and transparency of the glasses and bowls." }, { "code": null, "e": 63176, "s": 62946, "text": "Degreaser − This is mainly used in bars to remove the marks of grease and lipstick that cannot be removed by traditional washing of glasses and cups. Degreaser restores the surface shine and transparency of the glasses and bowls." }, { "code": null, "e": 63649, "s": 63176, "text": "Floor Cleaners and Sealers − One of the important tasks of hotel housekeeping is cleaning the floor periodically and keeping it sealed with the help of sealer of the right consistency for optimum maintenance. Some areas in the hotel are busy and bear heavy traffic such as lobby, corridors, parking areas, restaurants, and dining halls. Their floorings loses smoothness and shine. In such a case, the floor cleaners and sealers are used for restoring their look and shine." }, { "code": null, "e": 64122, "s": 63649, "text": "Floor Cleaners and Sealers − One of the important tasks of hotel housekeeping is cleaning the floor periodically and keeping it sealed with the help of sealer of the right consistency for optimum maintenance. Some areas in the hotel are busy and bear heavy traffic such as lobby, corridors, parking areas, restaurants, and dining halls. Their floorings loses smoothness and shine. In such a case, the floor cleaners and sealers are used for restoring their look and shine." }, { "code": null, "e": 64581, "s": 64122, "text": "Laundry Cleaners − They are liquid concentrates with variable amount of peroxide that removes tough stains, bleaches the linen, and enhances its whiteness.\nA number of chemicals are used in dry-cleaning. They are camphor oil, turpentine spirits, benzene, kerosene and white gasoline, petroleum solvents such as naphtha blends, chloroform, carbon tetrachloride, and liquid carbon dioxide. They remove the stains from silk tapestry without damaging the fibers." }, { "code": null, "e": 64737, "s": 64581, "text": "Laundry Cleaners − They are liquid concentrates with variable amount of peroxide that removes tough stains, bleaches the linen, and enhances its whiteness." }, { "code": null, "e": 65040, "s": 64737, "text": "A number of chemicals are used in dry-cleaning. They are camphor oil, turpentine spirits, benzene, kerosene and white gasoline, petroleum solvents such as naphtha blends, chloroform, carbon tetrachloride, and liquid carbon dioxide. They remove the stains from silk tapestry without damaging the fibers." }, { "code": null, "e": 65316, "s": 65040, "text": "Surface Sanitizers − They often come in the form of liquid concentrate. They are water-based and sanitize the surfaces without damaging their appearance. The sanitizers reduce the presence of bacteria to a great extent. They come with different concentrations and fragrances." }, { "code": null, "e": 65592, "s": 65316, "text": "Surface Sanitizers − They often come in the form of liquid concentrate. They are water-based and sanitize the surfaces without damaging their appearance. The sanitizers reduce the presence of bacteria to a great extent. They come with different concentrations and fragrances." }, { "code": null, "e": 65882, "s": 65592, "text": "Toilet Blocks − They deodorize the toilets and leave them with a fresh smell. They come with two variants: continuous action and instant action. They contain oxidizing agents such as ozone, hydrogen peroxide, or chlorine that removes unpleasant organic odor from the surface of a material." }, { "code": null, "e": 66172, "s": 65882, "text": "Toilet Blocks − They deodorize the toilets and leave them with a fresh smell. They come with two variants: continuous action and instant action. They contain oxidizing agents such as ozone, hydrogen peroxide, or chlorine that removes unpleasant organic odor from the surface of a material." }, { "code": null, "e": 66348, "s": 66172, "text": "Toilet Cleaners − They are available in liquid form containing strong hydrochloric acid. They remove stains and plumbing scales easily, and restore the shine of their surface." }, { "code": null, "e": 66524, "s": 66348, "text": "Toilet Cleaners − They are available in liquid form containing strong hydrochloric acid. They remove stains and plumbing scales easily, and restore the shine of their surface." }, { "code": null, "e": 66950, "s": 66524, "text": "Carpet Cleaning Agents − Cleaning and maintaining the carpets are important tasks of hotel housekeeping. As suggested by the Carpet and Rug Institute (CRI), carpet cleaning is complete when the following issues are tackled − \n\nSoil containment\nVacuuming\nSpotting\nInterim cleaning\nRestorative cleaning\n\nCarpet cleaning chemicals are often low-moisture, fast-drying cleaners that take care of the above said issues effectively\n" }, { "code": null, "e": 67176, "s": 66950, "text": "Carpet Cleaning Agents − Cleaning and maintaining the carpets are important tasks of hotel housekeeping. As suggested by the Carpet and Rug Institute (CRI), carpet cleaning is complete when the following issues are tackled − " }, { "code": null, "e": 67193, "s": 67176, "text": "Soil containment" }, { "code": null, "e": 67203, "s": 67193, "text": "Vacuuming" }, { "code": null, "e": 67212, "s": 67203, "text": "Spotting" }, { "code": null, "e": 67229, "s": 67212, "text": "Interim cleaning" }, { "code": null, "e": 67250, "s": 67229, "text": "Restorative cleaning" }, { "code": null, "e": 67373, "s": 67250, "text": "Carpet cleaning chemicals are often low-moisture, fast-drying cleaners that take care of the above said issues effectively" }, { "code": null, "e": 67632, "s": 67373, "text": "Swimming Pool Cleaners − They are used for cleaning the swimming pool water. Some of them are TCCA-90 granules or tablets, SDIC, hydrochloric acid (HCL), liquid chlorine, and alum. The pool cleaning chemicals kill the bacterial and algae growth in the water." }, { "code": null, "e": 67891, "s": 67632, "text": "Swimming Pool Cleaners − They are used for cleaning the swimming pool water. Some of them are TCCA-90 granules or tablets, SDIC, hydrochloric acid (HCL), liquid chlorine, and alum. The pool cleaning chemicals kill the bacterial and algae growth in the water." }, { "code": null, "e": 68202, "s": 67891, "text": "The chemicals like Sodium Dichloroisocyanurate (SDIC) has 60% of chlorine content and is used worldwide for disinfecting water. The pool cleaning chemicals dissolve fast in water and provide quick cleaning results. The housekeeping staff needs to take extra care while cleaning baby pools using these cleaners." }, { "code": null, "e": 68322, "s": 68202, "text": "People will forget what you said. People will forget what you did, but people will never forget how you made them feel." }, { "code": null, "e": 68388, "s": 68322, "text": "− Maya Angelou, American Author, Poet, and Civil Rights Activist." }, { "code": null, "e": 68755, "s": 68388, "text": "It is the most important duty of the housekeeping staff to prepare the guest room and the other places in the hotel so that the guest is most comfortable. Due to this, the housekeeping staff places some necessary supplies in the guest rooms and guest bathrooms. The idea behind is, the guest need not pack and carry each and every essential article while travelling." }, { "code": null, "e": 68996, "s": 68755, "text": "As per the hotel policy, and the standard of the room, the lists of these supplies may change. The housekeeping staff needs to ensure that those supplies are kept in appropriate numbers and condition while preparing room for guest check-in." }, { "code": null, "e": 69035, "s": 68996, "text": "Let us see more on the guest supplies." }, { "code": null, "e": 69177, "s": 69035, "text": "The guest room supplies are considered as guest essentials. The housekeeping staff places the following standard supplies in the guest room −" }, { "code": null, "e": 69328, "s": 69177, "text": "Furniture − It includes bed, bedside table, chairs, wardrobe with locker facility, writing table, dressing table, center table, and a magazine holder." }, { "code": null, "e": 69479, "s": 69328, "text": "Furniture − It includes bed, bedside table, chairs, wardrobe with locker facility, writing table, dressing table, center table, and a magazine holder." }, { "code": null, "e": 69580, "s": 69479, "text": "Bedding − It includes mattress, bed sheet, bed cover, quilt, quilt cover, pillows, and pillow cases." }, { "code": null, "e": 69681, "s": 69580, "text": "Bedding − It includes mattress, bed sheet, bed cover, quilt, quilt cover, pillows, and pillow cases." }, { "code": null, "e": 69759, "s": 69681, "text": "Bedside Supplies − They include non-slip mats on the either sides of the bed." }, { "code": null, "e": 69837, "s": 69759, "text": "Bedside Supplies − They include non-slip mats on the either sides of the bed." }, { "code": null, "e": 70154, "s": 69837, "text": "Bedside Table Supplies − They involve a telephone device, and a printed compiled list of important intercom numbers such as reception, restaurant, and laundry of the hotel. The housekeeping staff also provides a copy of Bible, Geeta, or Koran, depending upon the prior knowledge of the guest’s religious orientation." }, { "code": null, "e": 70471, "s": 70154, "text": "Bedside Table Supplies − They involve a telephone device, and a printed compiled list of important intercom numbers such as reception, restaurant, and laundry of the hotel. The housekeeping staff also provides a copy of Bible, Geeta, or Koran, depending upon the prior knowledge of the guest’s religious orientation." }, { "code": null, "e": 70634, "s": 70471, "text": "Center Table Supplies −It includes room service, laundry service, and spa and health club rate cards. It also has an ash tray and a small decorative center piece." }, { "code": null, "e": 70797, "s": 70634, "text": "Center Table Supplies −It includes room service, laundry service, and spa and health club rate cards. It also has an ash tray and a small decorative center piece." }, { "code": null, "e": 70923, "s": 70797, "text": "Clothing and Clothing Care − It involves bathrobe, coffee table cover, rocking chair cover, and hangers for clothes and ties." }, { "code": null, "e": 71049, "s": 70923, "text": "Clothing and Clothing Care − It involves bathrobe, coffee table cover, rocking chair cover, and hangers for clothes and ties." }, { "code": null, "e": 71425, "s": 71049, "text": "Hospitality Tray − It is a small tray with compartments that holds sachets of coffee, tea, cocoa powder, creamer, and sugar. Some hotels also offer the sachets of condiments like black and white pepper powder, and salt. They also keep an electric kettle, a couple of cups, saucers, spoons, and water bottle so that the guest can make the beverage of his choice once in a day." }, { "code": null, "e": 71801, "s": 71425, "text": "Hospitality Tray − It is a small tray with compartments that holds sachets of coffee, tea, cocoa powder, creamer, and sugar. Some hotels also offer the sachets of condiments like black and white pepper powder, and salt. They also keep an electric kettle, a couple of cups, saucers, spoons, and water bottle so that the guest can make the beverage of his choice once in a day." }, { "code": null, "e": 72028, "s": 71801, "text": "Mini Bar Supplies − It includes a small personal refrigerator filled with a couple of soft drinks, alcoholic drinks, soda, and ice cubes. It also involves a couple of personal servings of salted peanuts, cashew nuts, or chips." }, { "code": null, "e": 72255, "s": 72028, "text": "Mini Bar Supplies − It includes a small personal refrigerator filled with a couple of soft drinks, alcoholic drinks, soda, and ice cubes. It also involves a couple of personal servings of salted peanuts, cashew nuts, or chips." }, { "code": null, "e": 72457, "s": 72255, "text": "Writing Desk Supplies − A writing pad, a pencil, an eraser, promotional brochures, La carte menu, and the short list of places of historical and commercial importance in the city for guest’s reference." }, { "code": null, "e": 72659, "s": 72457, "text": "Writing Desk Supplies − A writing pad, a pencil, an eraser, promotional brochures, La carte menu, and the short list of places of historical and commercial importance in the city for guest’s reference." }, { "code": null, "e": 72862, "s": 72659, "text": "They are also considered as guest essentials. The guests are expected to use these supplies or take them away on departure. Depending upon the type of room, the list of supplies for guest bathroom are −" }, { "code": null, "e": 73114, "s": 72862, "text": "Bathroom Attachments − Bath area with shower and handheld shower attachments, a bath tub with hot-cold water mixer and handheld shower attachment, soap dispenser, toilet paper attachment, towel holder, and a basin with hot-cold water mixer attachment." }, { "code": null, "e": 73366, "s": 73114, "text": "Bathroom Attachments − Bath area with shower and handheld shower attachments, a bath tub with hot-cold water mixer and handheld shower attachment, soap dispenser, toilet paper attachment, towel holder, and a basin with hot-cold water mixer attachment." }, { "code": null, "e": 73488, "s": 73366, "text": "Towels − The couple of pairs of a large and a small towels each for the guests to be used according to their requirement." }, { "code": null, "e": 73610, "s": 73488, "text": "Towels − The couple of pairs of a large and a small towels each for the guests to be used according to their requirement." }, { "code": null, "e": 73727, "s": 73610, "text": "Dustbin − A small dustbin with lid, which can be often, opened by the foot and lined with a plastic bag from inside." }, { "code": null, "e": 73844, "s": 73727, "text": "Dustbin − A small dustbin with lid, which can be often, opened by the foot and lined with a plastic bag from inside." }, { "code": null, "e": 73900, "s": 73844, "text": "Non-slip Foot-mat − It is often, kept near the bathtub." }, { "code": null, "e": 73956, "s": 73900, "text": "Non-slip Foot-mat − It is often, kept near the bathtub." }, { "code": null, "e": 74005, "s": 73956, "text": "Slippers − Flat non-slip slippers for the guest." }, { "code": null, "e": 74054, "s": 74005, "text": "Slippers − Flat non-slip slippers for the guest." }, { "code": null, "e": 74121, "s": 74054, "text": "Mirror − A large mirror is often, fit on the wall above the basin." }, { "code": null, "e": 74188, "s": 74121, "text": "Mirror − A large mirror is often, fit on the wall above the basin." }, { "code": null, "e": 74273, "s": 74188, "text": "Hair Dryer − A wall mounted fixed hair dryer for the guest is kept in the bathrooms." }, { "code": null, "e": 74358, "s": 74273, "text": "Hair Dryer − A wall mounted fixed hair dryer for the guest is kept in the bathrooms." }, { "code": null, "e": 74651, "s": 74358, "text": "Vanity Tray − It contains small bottles of shower gel, shampoo, and conditioner. Some hotels also provide moisturizer, shower cap, hand and foot cream, ear buds, and a small manicure kit. It may also contain a couple of empty glasses, disposable toothbrushes, and a small bottle of mouthwash." }, { "code": null, "e": 74944, "s": 74651, "text": "Vanity Tray − It contains small bottles of shower gel, shampoo, and conditioner. Some hotels also provide moisturizer, shower cap, hand and foot cream, ear buds, and a small manicure kit. It may also contain a couple of empty glasses, disposable toothbrushes, and a small bottle of mouthwash." }, { "code": null, "e": 75168, "s": 74944, "text": "The items provided on request are given to the guests when they ask for them. These are the supplies apart from regular supplies required by some guests. These are often provided as the guest expendables. Some of them are −" }, { "code": null, "e": 75180, "s": 75168, "text": "Alarm clock" }, { "code": null, "e": 75185, "s": 75180, "text": "Comb" }, { "code": null, "e": 75200, "s": 75185, "text": "Crib or Cradle" }, { "code": null, "e": 75219, "s": 75200, "text": "Disposable Diapers" }, { "code": null, "e": 75236, "s": 75219, "text": "Disposable razor" }, { "code": null, "e": 75253, "s": 75236, "text": "Electric blanket" }, { "code": null, "e": 75266, "s": 75253, "text": "Electric fan" }, { "code": null, "e": 75281, "s": 75266, "text": "Extra blankets" }, { "code": null, "e": 75303, "s": 75281, "text": "First aid medical kit" }, { "code": null, "e": 75330, "s": 75303, "text": "Handheld shower attachment" }, { "code": null, "e": 75348, "s": 75330, "text": "Hearing equipment" }, { "code": null, "e": 75362, "s": 75348, "text": "Hot water bag" }, { "code": null, "e": 75367, "s": 75362, "text": "Iron" }, { "code": null, "e": 75381, "s": 75367, "text": "Ironing board" }, { "code": null, "e": 75388, "s": 75381, "text": "Pillow" }, { "code": null, "e": 75410, "s": 75388, "text": "Potty Ring for toilet" }, { "code": null, "e": 75429, "s": 75410, "text": "Raised toilet seat" }, { "code": null, "e": 75446, "s": 75429, "text": "Sanitary napkins" }, { "code": null, "e": 75457, "s": 75446, "text": "Sewing kit" }, { "code": null, "e": 75474, "s": 75457, "text": "Stationery items" }, { "code": null, "e": 75482, "s": 75474, "text": "Tampons" }, { "code": null, "e": 75488, "s": 75482, "text": "Wipes" }, { "code": null, "e": 75641, "s": 75488, "text": "It all comes back to the basics. Serve customers the best-tasting food at a good value in a clean, comfortable restaurant, and they’ll keep coming back." }, { "code": null, "e": 75702, "s": 75641, "text": "− Dave Thomas, CEO of Windy’s, a fast-food restaurant chain." }, { "code": null, "e": 76078, "s": 75702, "text": "The efforts of housekeeping speak for themselves. The result of sincere as well as faux housekeeping efforts are noticeable. The housekeeping staff needs to execute cleaning and maintenance tasks at various places inside the hotel. The most important task is cleaning and maintaining guest rooms and guest bathrooms. The guests assess the cleanliness in this area critically." }, { "code": null, "e": 76517, "s": 76078, "text": "By following the best cleaning and maintenance practices, the housekeeping staff can contribute to retain the satisfied guests as well as to generate new guests willing to repeat their visit to the hotel. This brings in more revenue to the hotel business. To perform towards guest satisfaction and work productivity together, the housekeeping staff needs to structure the cleaning and maintenance procedures and follow them appropriately." }, { "code": null, "e": 76845, "s": 76517, "text": "The chambermaid’s trolley can be viewed as a large tool box on wheels to aid the hotel housekeeping staff. It has a number of compartments and shelves of various sizes. This trolley is filled with the supplies from the housekeeping supplies store at the end of each shift so that the next shift staff can access it immediately." }, { "code": null, "e": 76923, "s": 76845, "text": "The staff considers the following points while loading chambermaid’s trolley." }, { "code": null, "e": 77029, "s": 76923, "text": "Loading the trolley with adequate supplies depending upon the number and types of the rooms on the floor." }, { "code": null, "e": 77135, "s": 77029, "text": "Loading the trolley with adequate supplies depending upon the number and types of the rooms on the floor." }, { "code": null, "e": 77200, "s": 77135, "text": "Avoiding to overload the trolley that may lead to any accidents." }, { "code": null, "e": 77265, "s": 77200, "text": "Avoiding to overload the trolley that may lead to any accidents." }, { "code": null, "e": 77358, "s": 77265, "text": "Avoiding to underload the trolley that may lead to make unnecessary trips to supplies store." }, { "code": null, "e": 77451, "s": 77358, "text": "Avoiding to underload the trolley that may lead to make unnecessary trips to supplies store." }, { "code": null, "e": 77482, "s": 77451, "text": "The SOP is given as follows − " }, { "code": null, "e": 77501, "s": 77482, "text": "Empty the trolley." }, { "code": null, "e": 77520, "s": 77501, "text": "Empty the trolley." }, { "code": null, "e": 77556, "s": 77520, "text": "Check rapidly for any broken parts." }, { "code": null, "e": 77592, "s": 77556, "text": "Check rapidly for any broken parts." }, { "code": null, "e": 77635, "s": 77592, "text": "Clean it by dusting and wiping any stains." }, { "code": null, "e": 77678, "s": 77635, "text": "Clean it by dusting and wiping any stains." }, { "code": null, "e": 77803, "s": 77678, "text": "Place the items according to their weight: heaviest items at the bottom and lighter items at the top section of the trolley." }, { "code": null, "e": 77928, "s": 77803, "text": "Place the items according to their weight: heaviest items at the bottom and lighter items at the top section of the trolley." }, { "code": null, "e": 77978, "s": 77928, "text": "Place the linen for different purpose separately." }, { "code": null, "e": 78028, "s": 77978, "text": "Place the linen for different purpose separately." }, { "code": null, "e": 78087, "s": 78028, "text": "Close the lids of cleaner bottles and liquid cans tightly." }, { "code": null, "e": 78146, "s": 78087, "text": "Close the lids of cleaner bottles and liquid cans tightly." }, { "code": null, "e": 78225, "s": 78146, "text": "Record the numbers and types of the items loaded in the trolley for the rooms." }, { "code": null, "e": 78304, "s": 78225, "text": "Record the numbers and types of the items loaded in the trolley for the rooms." }, { "code": null, "e": 78327, "s": 78304, "text": "Collect the room keys." }, { "code": null, "e": 78350, "s": 78327, "text": "Collect the room keys." }, { "code": null, "e": 78395, "s": 78350, "text": "Take the trolley to the assigned duty floor." }, { "code": null, "e": 78440, "s": 78395, "text": "Take the trolley to the assigned duty floor." }, { "code": null, "e": 78538, "s": 78440, "text": "Park it outside the room such that the linen side faces outside and the room entrance is blocked." }, { "code": null, "e": 78636, "s": 78538, "text": "Park it outside the room such that the linen side faces outside and the room entrance is blocked." }, { "code": null, "e": 78722, "s": 78636, "text": "The housekeeping staff should follow the SOP given below for entering the guest room." }, { "code": null, "e": 78772, "s": 78722, "text": "Leave the DND (Do not Disturb) rooms undisturbed." }, { "code": null, "e": 78822, "s": 78772, "text": "Leave the DND (Do not Disturb) rooms undisturbed." }, { "code": null, "e": 78902, "s": 78822, "text": "Knock the door with knuckles and announce in pleasant voice, “Housekeeping...”." }, { "code": null, "e": 78982, "s": 78902, "text": "Knock the door with knuckles and announce in pleasant voice, “Housekeeping...”." }, { "code": null, "e": 79034, "s": 78982, "text": "Wait for five seconds to hear the guest’s response." }, { "code": null, "e": 79086, "s": 79034, "text": "Wait for five seconds to hear the guest’s response." }, { "code": null, "e": 79135, "s": 79086, "text": "In case of no response, announce the same again." }, { "code": null, "e": 79184, "s": 79135, "text": "In case of no response, announce the same again." }, { "code": null, "e": 79251, "s": 79184, "text": "In there is no answer second time too, open the door with the key." }, { "code": null, "e": 79318, "s": 79251, "text": "In there is no answer second time too, open the door with the key." }, { "code": null, "e": 79334, "s": 79318, "text": "Enter the room." }, { "code": null, "e": 79350, "s": 79334, "text": "Enter the room." }, { "code": null, "e": 79414, "s": 79350, "text": "If the guest is found sleeping, withdraw from the room quietly." }, { "code": null, "e": 79478, "s": 79414, "text": "If the guest is found sleeping, withdraw from the room quietly." }, { "code": null, "e": 79558, "s": 79478, "text": "In case the guest answers, ask politely when would he like to service the room." }, { "code": null, "e": 79638, "s": 79558, "text": "In case the guest answers, ask politely when would he like to service the room." }, { "code": null, "e": 79722, "s": 79638, "text": "In case the guest wants it later, acknowledge his reply and withdraw from the room." }, { "code": null, "e": 79806, "s": 79722, "text": "In case the guest wants it later, acknowledge his reply and withdraw from the room." }, { "code": null, "e": 79948, "s": 79806, "text": "If the housekeeping work is in progress and the guest returns from outside, greet him and ask if the guest would like to return in some time." }, { "code": null, "e": 80090, "s": 79948, "text": "If the housekeeping work is in progress and the guest returns from outside, greet him and ask if the guest would like to return in some time." }, { "code": null, "e": 80217, "s": 80090, "text": "The SOP for cleaning the guest room is given below. Once the staff enters the room and starts the housekeeping work, he must −" }, { "code": null, "e": 80298, "s": 80217, "text": "Not use guest room linen as a door stopper or for cleaning and dusting the room." }, { "code": null, "e": 80379, "s": 80298, "text": "Not use guest room linen as a door stopper or for cleaning and dusting the room." }, { "code": null, "e": 80424, "s": 80379, "text": "Keep the guest room door open while working." }, { "code": null, "e": 80469, "s": 80424, "text": "Keep the guest room door open while working." }, { "code": null, "e": 80503, "s": 80469, "text": "Open the curtains and patio door." }, { "code": null, "e": 80537, "s": 80503, "text": "Open the curtains and patio door." }, { "code": null, "e": 80585, "s": 80537, "text": "Assemble the furniture and place appropriately." }, { "code": null, "e": 80633, "s": 80585, "text": "Assemble the furniture and place appropriately." }, { "code": null, "e": 80699, "s": 80633, "text": "Keep the vacuum cleaner and other cleaning apparatus in the room." }, { "code": null, "e": 80765, "s": 80699, "text": "Keep the vacuum cleaner and other cleaning apparatus in the room." }, { "code": null, "e": 80788, "s": 80765, "text": "Check the type of bed." }, { "code": null, "e": 80811, "s": 80788, "text": "Check the type of bed." }, { "code": null, "e": 80885, "s": 80811, "text": "Take the bed linen of appropriate size and place it on the nearest chair." }, { "code": null, "e": 80959, "s": 80885, "text": "Take the bed linen of appropriate size and place it on the nearest chair." }, { "code": null, "e": 81009, "s": 80959, "text": "Remove previous bedspread and place on the chair." }, { "code": null, "e": 81059, "s": 81009, "text": "Remove previous bedspread and place on the chair." }, { "code": null, "e": 81142, "s": 81059, "text": "Inspect the bed and pillows for their condition as well as for any lost-and-found." }, { "code": null, "e": 81225, "s": 81142, "text": "Inspect the bed and pillows for their condition as well as for any lost-and-found." }, { "code": null, "e": 81418, "s": 81225, "text": "In case of checkout room, deposit the left guest items to the floor supervisor. If the room is still occupied by the guest, place the item such that it is safe as well as visible to the guest." }, { "code": null, "e": 81611, "s": 81418, "text": "In case of checkout room, deposit the left guest items to the floor supervisor. If the room is still occupied by the guest, place the item such that it is safe as well as visible to the guest." }, { "code": null, "e": 81688, "s": 81611, "text": "Put soiled sheets and pillow covers in the soiled linen cart of the trolley." }, { "code": null, "e": 81765, "s": 81688, "text": "Put soiled sheets and pillow covers in the soiled linen cart of the trolley." }, { "code": null, "e": 81870, "s": 81765, "text": "Empty ashtrays and rubbish from the guest room and bathroom dustbins into the trash cart of the trolley." }, { "code": null, "e": 81975, "s": 81870, "text": "Empty ashtrays and rubbish from the guest room and bathroom dustbins into the trash cart of the trolley." }, { "code": null, "e": 82056, "s": 81975, "text": "Pick up used glasses, mugs, ashtray, trays, and place them on bathroom platform." }, { "code": null, "e": 82137, "s": 82056, "text": "Pick up used glasses, mugs, ashtray, trays, and place them on bathroom platform." }, { "code": null, "e": 82255, "s": 82137, "text": "Spray the bathtub, basin, glasses, mugs, and trays with cleaning liquid. Let them soak the chemicals from the liquid." }, { "code": null, "e": 82373, "s": 82255, "text": "Spray the bathtub, basin, glasses, mugs, and trays with cleaning liquid. Let them soak the chemicals from the liquid." }, { "code": null, "e": 82387, "s": 82373, "text": "Make the bed." }, { "code": null, "e": 82401, "s": 82387, "text": "Make the bed." }, { "code": null, "e": 82476, "s": 82401, "text": "Start dusting from an extreme inside corner of the room and work outwards." }, { "code": null, "e": 82551, "s": 82476, "text": "Start dusting from an extreme inside corner of the room and work outwards." }, { "code": null, "e": 82566, "s": 82551, "text": "Clean wipe TV." }, { "code": null, "e": 82581, "s": 82566, "text": "Clean wipe TV." }, { "code": null, "e": 82609, "s": 82581, "text": "Straighten the guest items." }, { "code": null, "e": 82637, "s": 82609, "text": "Straighten the guest items." }, { "code": null, "e": 82669, "s": 82637, "text": "Sweep the room and patio floor." }, { "code": null, "e": 82701, "s": 82669, "text": "Sweep the room and patio floor." }, { "code": null, "e": 82731, "s": 82701, "text": "Mop the room and patio floor." }, { "code": null, "e": 82761, "s": 82731, "text": "Mop the room and patio floor." }, { "code": null, "e": 82796, "s": 82761, "text": "Clean the glasses, mugs, and tray." }, { "code": null, "e": 82831, "s": 82796, "text": "Clean the glasses, mugs, and tray." }, { "code": null, "e": 82888, "s": 82831, "text": "Sanitize glasses, mugs, telephone device, and TV remote." }, { "code": null, "e": 82945, "s": 82888, "text": "Sanitize glasses, mugs, telephone device, and TV remote." }, { "code": null, "e": 83021, "s": 82945, "text": "Inspect the condition of bathroom slippers and bathrobe. Replace if soiled." }, { "code": null, "e": 83097, "s": 83021, "text": "Inspect the condition of bathroom slippers and bathrobe. Replace if soiled." }, { "code": null, "e": 83119, "s": 83097, "text": "Close the patio door." }, { "code": null, "e": 83141, "s": 83119, "text": "Close the patio door." }, { "code": null, "e": 83165, "s": 83141, "text": "Close all the curtains." }, { "code": null, "e": 83189, "s": 83165, "text": "Close all the curtains." }, { "code": null, "e": 83214, "s": 83189, "text": "Clean the entrance door." }, { "code": null, "e": 83239, "s": 83214, "text": "Clean the entrance door." }, { "code": null, "e": 83269, "s": 83239, "text": "Close and lock the room door." }, { "code": null, "e": 83299, "s": 83269, "text": "Close and lock the room door." }, { "code": null, "e": 83344, "s": 83299, "text": "Report any damage spotted to the supervisor." }, { "code": null, "e": 83389, "s": 83344, "text": "Report any damage spotted to the supervisor." }, { "code": null, "e": 83445, "s": 83389, "text": "The SOP for cleaning the guest bathroom is given below." }, { "code": null, "e": 83472, "s": 83445, "text": "Open bathroom ventilation." }, { "code": null, "e": 83498, "s": 83472, "text": "Sweep the bathroom floor." }, { "code": null, "e": 83549, "s": 83498, "text": "Scrub and finish the platform, bathtub, and basin." }, { "code": null, "e": 83605, "s": 83549, "text": "Scrub and finish the toilet bowl, rim, ring, and hinge." }, { "code": null, "e": 83622, "s": 83605, "text": "Wipe the mirror." }, { "code": null, "e": 83668, "s": 83622, "text": "Clean bathroom walls using wet mop or sponge." }, { "code": null, "e": 83762, "s": 83668, "text": "Replace amenities such as toilet roll, toilet block, shampoo, conditioners, and moisturizers." }, { "code": null, "e": 83784, "s": 83762, "text": "Replace bathroom mat." }, { "code": null, "e": 83854, "s": 83784, "text": "Wipe down shower curtain working from top to bottom with a dry cloth." }, { "code": null, "e": 83891, "s": 83854, "text": "Replace bath towels and hand towels." }, { "code": null, "e": 83918, "s": 83891, "text": "Replace the dustbin liner." }, { "code": null, "e": 83950, "s": 83918, "text": "Close the bathroom ventilation." }, { "code": null, "e": 83975, "s": 83950, "text": "Clean the bathroom door." }, { "code": null, "e": 84019, "s": 83975, "text": "Keep the bathroom door open after cleaning." }, { "code": null, "e": 84064, "s": 84019, "text": "Check bathroom doormat. Replace if required." }, { "code": null, "e": 84109, "s": 84064, "text": "Report any damage spotted to the supervisor." }, { "code": null, "e": 84216, "s": 84109, "text": "The balcony or the patio are the extensions of the guest room. The SOPs for cleaning them are given below." }, { "code": null, "e": 84235, "s": 84216, "text": "Enter the balcony." }, { "code": null, "e": 84257, "s": 84235, "text": "Spray walls, railings" }, { "code": null, "e": 84292, "s": 84257, "text": "Scrub and clean the bird droppings" }, { "code": null, "e": 84338, "s": 84292, "text": "Wipe down rocking or sitting chairs and table" }, { "code": null, "e": 84383, "s": 84338, "text": "Clean the door tracks appeared on the floor." }, { "code": null, "e": 84400, "s": 84383, "text": "Sweep the floor." }, { "code": null, "e": 84415, "s": 84400, "text": "Mop the floor." }, { "code": null, "e": 84613, "s": 84415, "text": "Every room has to be entered at least once a day by any housekeeping staff. The guests who do not want to get disturbed by any housekeeping service tag their rooms with a Do-Not-Disturb (DND) sign." }, { "code": null, "e": 84656, "s": 84613, "text": "The SOP for these rooms is as given below." }, { "code": null, "e": 84721, "s": 84656, "text": "Do not disturb by placing a call until 2:00 o’clock in the noon." }, { "code": null, "e": 84786, "s": 84721, "text": "Do not disturb by placing a call until 2:00 o’clock in the noon." }, { "code": null, "e": 84860, "s": 84786, "text": "After 2:00 p.m., the Supervisor calls the room to know the guest’s needs." }, { "code": null, "e": 84934, "s": 84860, "text": "After 2:00 p.m., the Supervisor calls the room to know the guest’s needs." }, { "code": null, "e": 85023, "s": 84934, "text": "The housekeeping staff contacts the supervisor to make sure whether to service the room." }, { "code": null, "e": 85112, "s": 85023, "text": "The housekeeping staff contacts the supervisor to make sure whether to service the room." }, { "code": null, "e": 85204, "s": 85112, "text": "If the call was not answered by the guest after two calling attempts, the room is serviced." }, { "code": null, "e": 85296, "s": 85204, "text": "If the call was not answered by the guest after two calling attempts, the room is serviced." }, { "code": null, "e": 85406, "s": 85296, "text": "To his best judgement, the housekeeping staff enters the room and continues with the usual housekeeping work." }, { "code": null, "e": 85516, "s": 85406, "text": "To his best judgement, the housekeeping staff enters the room and continues with the usual housekeeping work." }, { "code": null, "e": 85647, "s": 85516, "text": "There are various public areas frequented by the hotel guests. The areas and their respective SOPs for housekeeping are as given −" }, { "code": null, "e": 85750, "s": 85647, "text": "Carry out the lift cleaning task early morning when the least number of guests are expected to use it." }, { "code": null, "e": 85789, "s": 85750, "text": "Call the elevator on the ground floor." }, { "code": null, "e": 85804, "s": 85789, "text": "Open its door." }, { "code": null, "e": 85839, "s": 85804, "text": "Put appropriate signboard near it." }, { "code": null, "e": 85942, "s": 85839, "text": "Clean the lift using the appropriate cleaning liquid according to the wall material of the lift cabin." }, { "code": null, "e": 85963, "s": 85942, "text": "Wipe the lift doors." }, { "code": null, "e": 86016, "s": 85963, "text": "Work from top to bottom while cleaning a lift cabin." }, { "code": null, "e": 86087, "s": 86016, "text": "Keep the lift door open till the floor and walls are dried completely." }, { "code": null, "e": 86114, "s": 86087, "text": "Spray clean air freshener." }, { "code": null, "e": 86280, "s": 86114, "text": "The lobby is active 24 hours. The furniture, carpets, flooring, and ceiling; everything needs to be kept extremely clean at any given time. The SOPs are as follows −" }, { "code": null, "e": 86350, "s": 86280, "text": "Clear all ashtrays into the trash ensuring no cigarettes are burning." }, { "code": null, "e": 86420, "s": 86350, "text": "Clear all ashtrays into the trash ensuring no cigarettes are burning." }, { "code": null, "e": 86461, "s": 86420, "text": "Clean and restore them to proper places." }, { "code": null, "e": 86502, "s": 86461, "text": "Clean and restore them to proper places." }, { "code": null, "e": 86545, "s": 86502, "text": "Clear the dustbins near front office desk." }, { "code": null, "e": 86588, "s": 86545, "text": "Clear the dustbins near front office desk." }, { "code": null, "e": 86637, "s": 86588, "text": "Replace their lining and keep them as they were." }, { "code": null, "e": 86686, "s": 86637, "text": "Replace their lining and keep them as they were." }, { "code": null, "e": 86836, "s": 86686, "text": "Dust and wipe the telephone device, fax machine, Computers, and kiosks. Sanitize the telephone device, computer key board, and touchpad of the kiosk." }, { "code": null, "e": 86986, "s": 86836, "text": "Dust and wipe the telephone device, fax machine, Computers, and kiosks. Sanitize the telephone device, computer key board, and touchpad of the kiosk." }, { "code": null, "e": 87019, "s": 86986, "text": "Remove spider webs from ceiling." }, { "code": null, "e": 87052, "s": 87019, "text": "Remove spider webs from ceiling." }, { "code": null, "e": 87119, "s": 87052, "text": "Remove the dust deposited on walls, windows, furniture, and floor." }, { "code": null, "e": 87186, "s": 87119, "text": "Remove the dust deposited on walls, windows, furniture, and floor." }, { "code": null, "e": 87229, "s": 87186, "text": "Remove stains on the carpet and furniture." }, { "code": null, "e": 87272, "s": 87229, "text": "Remove stains on the carpet and furniture." }, { "code": null, "e": 87329, "s": 87272, "text": "Clean all artifacts using damp and soft cloth carefully." }, { "code": null, "e": 87386, "s": 87329, "text": "Clean all artifacts using damp and soft cloth carefully." }, { "code": null, "e": 87450, "s": 87386, "text": "Sweep and mop the flooring of lobby and front office desk area." }, { "code": null, "e": 87514, "s": 87450, "text": "Sweep and mop the flooring of lobby and front office desk area." }, { "code": null, "e": 87568, "s": 87514, "text": "Dust and polish any vases, paintings, and art pieces." }, { "code": null, "e": 87622, "s": 87568, "text": "Dust and polish any vases, paintings, and art pieces." }, { "code": null, "e": 87670, "s": 87622, "text": "Spray the air clean spray with signature aroma." }, { "code": null, "e": 87718, "s": 87670, "text": "Spray the air clean spray with signature aroma." }, { "code": null, "e": 87769, "s": 87718, "text": "Play a very light and soothing instrumental music." }, { "code": null, "e": 87820, "s": 87769, "text": "Play a very light and soothing instrumental music." }, { "code": null, "e": 88043, "s": 87820, "text": "The parking area takes the load of pollution created by hotel owned vehicles and guests’ private vehicles. It is heavily polluted with dirt and dust. The parking area needs cleanliness with respect to the following terms −" }, { "code": null, "e": 88068, "s": 88043, "text": "Control the ventilation." }, { "code": null, "e": 88159, "s": 88068, "text": "Control pollutant discharges occurring from broken drainage or water systems of the hotel." }, { "code": null, "e": 88216, "s": 88159, "text": "Remove fine-grained sediment particles on parking floor." }, { "code": null, "e": 88242, "s": 88216, "text": "Clean the area near lift." }, { "code": null, "e": 88304, "s": 88242, "text": "Hard-sweep the parking floor using street sweeping equipment." }, { "code": null, "e": 88350, "s": 88304, "text": "Collect and dispose the debris appropriately." }, { "code": null, "e": 88431, "s": 88350, "text": "Bringing presence of any unusual debris to the notice of public area supervisor." }, { "code": null, "e": 88524, "s": 88431, "text": "The gardener or the team of gardeners work to keep the garden looking beautiful. They must −" }, { "code": null, "e": 88631, "s": 88524, "text": "Water the plants regularly according to the season and requirement of the plants; generally early morning." }, { "code": null, "e": 88738, "s": 88631, "text": "Water the plants regularly according to the season and requirement of the plants; generally early morning." }, { "code": null, "e": 88777, "s": 88738, "text": "Remove the weed and fall leaves daily." }, { "code": null, "e": 88816, "s": 88777, "text": "Remove the weed and fall leaves daily." }, { "code": null, "e": 88898, "s": 88816, "text": "Implement the art of Arbosculpture to enhance the beauty of the trees and bushes." }, { "code": null, "e": 88980, "s": 88898, "text": "Implement the art of Arbosculpture to enhance the beauty of the trees and bushes." }, { "code": null, "e": 89021, "s": 88980, "text": "Keep the gardening tools clean and safe." }, { "code": null, "e": 89062, "s": 89021, "text": "Keep the gardening tools clean and safe." }, { "code": null, "e": 89145, "s": 89062, "text": "Report any damage or requirement of tools or plants to the public area supervisor." }, { "code": null, "e": 89228, "s": 89145, "text": "Report any damage or requirement of tools or plants to the public area supervisor." }, { "code": null, "e": 89326, "s": 89228, "text": "Keep the lawn grass in healthy condition by periodic cutting with the help of scarifying machine." }, { "code": null, "e": 89424, "s": 89326, "text": "Keep the lawn grass in healthy condition by periodic cutting with the help of scarifying machine." }, { "code": null, "e": 89487, "s": 89424, "text": "Keep any artificial waterfalls or artificial water body clean." }, { "code": null, "e": 89550, "s": 89487, "text": "Keep any artificial waterfalls or artificial water body clean." }, { "code": null, "e": 89607, "s": 89550, "text": "Fertilizing and manuring the plants as per the schedule." }, { "code": null, "e": 89664, "s": 89607, "text": "Fertilizing and manuring the plants as per the schedule." }, { "code": null, "e": 89733, "s": 89664, "text": "Recycle the food wastage in the hotel to prepare organic fertilizer." }, { "code": null, "e": 89802, "s": 89733, "text": "Recycle the food wastage in the hotel to prepare organic fertilizer." }, { "code": null, "e": 89952, "s": 89802, "text": "The dining areas need daily cleaning before their working hours start as well as when the restaurant staff requests cleaning. The SOP is given below." }, { "code": null, "e": 90009, "s": 89952, "text": "Collect all the cleaning equipment and dining area keys." }, { "code": null, "e": 90043, "s": 90009, "text": "Switch on all the electric lamps." }, { "code": null, "e": 90108, "s": 90043, "text": "Open all the drapes and blinds for letting in the natural light." }, { "code": null, "e": 90151, "s": 90108, "text": "Observer the entire area to plan the work." }, { "code": null, "e": 90219, "s": 90151, "text": "Align all the chairs away from the table to make room for cleaning." }, { "code": null, "e": 90264, "s": 90219, "text": "Clean the carpet area, using vacuum cleaner." }, { "code": null, "e": 90330, "s": 90264, "text": "Remove any food stains from the carpet using appropriate cleaner." }, { "code": null, "e": 90384, "s": 90330, "text": "If there is no carpet on the floor, sweep and mop it." }, { "code": null, "e": 90427, "s": 90384, "text": "Dust all the furniture in the dining area." }, { "code": null, "e": 90461, "s": 90427, "text": "Polish the furniture if required." }, { "code": null, "e": 90542, "s": 90461, "text": "Using a feather duster, dust all the pictures, paintings, artworks, and corners." }, { "code": null, "e": 90585, "s": 90542, "text": "Clean and disinfect the telephone devices." }, { "code": null, "e": 90634, "s": 90585, "text": "Polish metal, glass, and wood items if required." }, { "code": null, "e": 90696, "s": 90634, "text": "Clean the mirrors and windows by wiping them with wet sponge." }, { "code": null, "e": 90770, "s": 90696, "text": "If requirement of maintenance is spotted, consult engineering department." }, { "code": null, "e": 90847, "s": 90770, "text": "If any guest items are found then deposit it with housekeeping control desk." }, { "code": null, "e": 90911, "s": 90847, "text": "Collect all dirty table linens and replace with the fresh ones." }, { "code": null, "e": 90955, "s": 90911, "text": "Return the keys to the security department." }, { "code": null, "e": 90992, "s": 90955, "text": "Record in the housekeeping register." }, { "code": null, "e": 91281, "s": 90992, "text": "The swimming pool cleaning activity can be conducted in-house by training and employing housekeeping staff; as there could be separate swimming pools such as indoor and outdoor as well as for adults and for children. The following steps are taken to clean and maintain the swimming pool −" }, { "code": null, "e": 91324, "s": 91281, "text": "Check water quality more than once a week." }, { "code": null, "e": 91379, "s": 91324, "text": "Check any broken tiles/pipes inside the swimming pool." }, { "code": null, "e": 91430, "s": 91379, "text": "Clean the water as soon as possible when required." }, { "code": null, "e": 91511, "s": 91430, "text": "Check the pool water for contamination daily. Remove leaves using leaf catchers." }, { "code": null, "e": 91655, "s": 91511, "text": "Check for slippery floor area and the pool bottom. Apply and maintain the anti-slip mats near the pool. Scrub and clean the bottom of the pool." }, { "code": null, "e": 91715, "s": 91655, "text": "Keep the life-saving and floating apparatus ready all time." }, { "code": null, "e": 91760, "s": 91715, "text": "Keep poolside area and basking chairs clean." }, { "code": null, "e": 91843, "s": 91760, "text": "Keep an appropriate and noticeable signage showing the depth of the swimming pool." }, { "code": null, "e": 91893, "s": 91843, "text": "Check and keep changing rooms up to good quality." }, { "code": null, "e": 91951, "s": 91893, "text": "Keep the changing room door open when it is not occupied." }, { "code": null, "e": 92060, "s": 91951, "text": "Employee lifeguards to provide general safety check for swimming pool once a day during the operating hours." }, { "code": null, "e": 92111, "s": 92060, "text": "Add adequate amount of chlorine in the pool water." }, { "code": null, "e": 92234, "s": 92111, "text": "Since Spring-cleaning is a time taking process, it is conducted during low occupancy period. The standard procedures are −" }, { "code": null, "e": 92401, "s": 92234, "text": "Request a spring-cleaning date the front office desk. (The housekeeping department needs to honor whatever date they give, as it is the matter of revenue generation.)" }, { "code": null, "e": 92568, "s": 92401, "text": "Request a spring-cleaning date the front office desk. (The housekeeping department needs to honor whatever date they give, as it is the matter of revenue generation.)" }, { "code": null, "e": 92600, "s": 92568, "text": "Tag the room as \"Not for Sale\"." }, { "code": null, "e": 92632, "s": 92600, "text": "Tag the room as \"Not for Sale\"." }, { "code": null, "e": 92700, "s": 92632, "text": "Remove the guest amenities, curtains, and art pieces from the room." }, { "code": null, "e": 92768, "s": 92700, "text": "Remove the guest amenities, curtains, and art pieces from the room." }, { "code": null, "e": 92819, "s": 92768, "text": "Send the curtains to the laundry for dry cleaning." }, { "code": null, "e": 92870, "s": 92819, "text": "Send the curtains to the laundry for dry cleaning." }, { "code": null, "e": 92945, "s": 92870, "text": "Empty the mini bar and send the beverage items to Food and Beverage store." }, { "code": null, "e": 93020, "s": 92945, "text": "Empty the mini bar and send the beverage items to Food and Beverage store." }, { "code": null, "e": 93069, "s": 93020, "text": "Roll the curtains and cover them with dustsheet." }, { "code": null, "e": 93118, "s": 93069, "text": "Roll the curtains and cover them with dustsheet." }, { "code": null, "e": 93197, "s": 93118, "text": "Inspect the furniture and send to the furniture yard for repair or upholstery." }, { "code": null, "e": 93276, "s": 93197, "text": "Inspect the furniture and send to the furniture yard for repair or upholstery." }, { "code": null, "e": 93340, "s": 93276, "text": "Inspect the locks, knobs, latches, leaking pipes, and bathroom." }, { "code": null, "e": 93404, "s": 93340, "text": "Inspect the locks, knobs, latches, leaking pipes, and bathroom." }, { "code": null, "e": 93505, "s": 93404, "text": "Hand over the room to maintenance department for any painting, sealing, and repairing work required." }, { "code": null, "e": 93606, "s": 93505, "text": "Hand over the room to maintenance department for any painting, sealing, and repairing work required." }, { "code": null, "e": 93712, "s": 93606, "text": "Once the maintenance work is complete, remove any residual smell of paint and varnish by airing the room." }, { "code": null, "e": 93818, "s": 93712, "text": "Once the maintenance work is complete, remove any residual smell of paint and varnish by airing the room." }, { "code": null, "e": 93859, "s": 93818, "text": "Polish and clean the permanent fixtures." }, { "code": null, "e": 93900, "s": 93859, "text": "Polish and clean the permanent fixtures." }, { "code": null, "e": 93935, "s": 93900, "text": "Open, lay, and shampoo the carpet." }, { "code": null, "e": 93970, "s": 93935, "text": "Open, lay, and shampoo the carpet." }, { "code": null, "e": 94021, "s": 93970, "text": "Check the bathroom sealing and clean the bathroom." }, { "code": null, "e": 94072, "s": 94021, "text": "Check the bathroom sealing and clean the bathroom." }, { "code": null, "e": 94108, "s": 94072, "text": "Make the bed using fresh bed linen." }, { "code": null, "e": 94144, "s": 94108, "text": "Make the bed using fresh bed linen." }, { "code": null, "e": 94199, "s": 94144, "text": "Restore the art pieces, furniture, and guest supplies." }, { "code": null, "e": 94254, "s": 94199, "text": "Restore the art pieces, furniture, and guest supplies." }, { "code": null, "e": 94316, "s": 94254, "text": "Call room service for restoring mini bar, glasses, and trays." }, { "code": null, "e": 94378, "s": 94316, "text": "Call room service for restoring mini bar, glasses, and trays." }, { "code": null, "e": 94417, "s": 94378, "text": "Show the room to the floor supervisor." }, { "code": null, "e": 94456, "s": 94417, "text": "Show the room to the floor supervisor." }, { "code": null, "e": 94505, "s": 94456, "text": "Release it to the front office desk for selling." }, { "code": null, "e": 94554, "s": 94505, "text": "Release it to the front office desk for selling." }, { "code": null, "e": 94656, "s": 94554, "text": "The floor supervisor closes the shift formally by ensuring the following points from the attendants −" }, { "code": null, "e": 94733, "s": 94656, "text": "Empty garbage bags of the chambermaid’s trolley into the garbage receptacle." }, { "code": null, "e": 94810, "s": 94733, "text": "Empty garbage bags of the chambermaid’s trolley into the garbage receptacle." }, { "code": null, "e": 94902, "s": 94810, "text": "Ensure they the soiled linen collected into chambermaid’s trolley bags are sent to laundry." }, { "code": null, "e": 94994, "s": 94902, "text": "Ensure they the soiled linen collected into chambermaid’s trolley bags are sent to laundry." }, { "code": null, "e": 95078, "s": 94994, "text": "Remove the chambermaid’s trolley and check it for ant damage and dirt accumulation." }, { "code": null, "e": 95162, "s": 95078, "text": "Remove the chambermaid’s trolley and check it for ant damage and dirt accumulation." }, { "code": null, "e": 95224, "s": 95162, "text": "Empty the vacuum cleaner bags and replace them with new ones." }, { "code": null, "e": 95286, "s": 95224, "text": "Empty the vacuum cleaner bags and replace them with new ones." }, { "code": null, "e": 95375, "s": 95286, "text": "Tidy the housekeeping department area by stacking the items at their appropriate places." }, { "code": null, "e": 95464, "s": 95375, "text": "Tidy the housekeeping department area by stacking the items at their appropriate places." }, { "code": null, "e": 95532, "s": 95464, "text": "Clean the toilet brushes with hot water for ten minutes every week." }, { "code": null, "e": 95600, "s": 95532, "text": "Clean the toilet brushes with hot water for ten minutes every week." }, { "code": null, "e": 95652, "s": 95600, "text": "Rinse mops in light detergents and hang for drying." }, { "code": null, "e": 95704, "s": 95652, "text": "Rinse mops in light detergents and hang for drying." }, { "code": null, "e": 95776, "s": 95704, "text": "Close the doors and handover the keys to the housekeeping control desk." }, { "code": null, "e": 95848, "s": 95776, "text": "Close the doors and handover the keys to the housekeeping control desk." }, { "code": null, "e": 95868, "s": 95848, "text": "Sign off the shift." }, { "code": null, "e": 95888, "s": 95868, "text": "Sign off the shift." }, { "code": null, "e": 96264, "s": 95888, "text": "In the range of small to large hotels, the guest room linen, guest bathroom linen, staff uniforms, all continue to accumulate in large amount. It is essential for the housekeeping staff to launder the linen and make it readily available at all times so that the staff can receive their well-laundered uniforms before work, and the guests are provided with good quality linen." }, { "code": null, "e": 96692, "s": 96264, "text": "It is definitely required to purchase good quality linen; but the life, appearance, and the quality of linen largely depends upon the treatment it receives at the laundry by the laundry staff. Small hotels can contract with the commercial laundry services located outside the hotel. Large hotel establishments prefer to install their private on-premises laundry. Let us understand on-premises laundry operated by housekeeping −" }, { "code": null, "e": 96778, "s": 96692, "text": "The following advantages are seen if housekeeping staff works at on-premise laundry −" }, { "code": null, "e": 96849, "s": 96778, "text": "On-premise laundry provides more use in comparatively less investment." }, { "code": null, "e": 96920, "s": 96849, "text": "On-premise laundry provides more use in comparatively less investment." }, { "code": null, "e": 97056, "s": 96920, "text": "The time, energy, and effort to take the clothes outside at a commercial laundry service is eliminated hence the staff can work better." }, { "code": null, "e": 97192, "s": 97056, "text": "The time, energy, and effort to take the clothes outside at a commercial laundry service is eliminated hence the staff can work better." }, { "code": null, "e": 97257, "s": 97192, "text": "The housekeeping staff can easily access the On-premise laundry." }, { "code": null, "e": 97322, "s": 97257, "text": "The housekeeping staff can easily access the On-premise laundry." }, { "code": null, "e": 97344, "s": 97322, "text": "Pilferage is reduced." }, { "code": null, "e": 97366, "s": 97344, "text": "Pilferage is reduced." }, { "code": null, "e": 97578, "s": 97366, "text": "The staff can have complete control over the wash cycles, and wear and tear of the linen. Thus, life of the fabric can be prolonged by using specific washing for the linen depending upon degree of their soiling." }, { "code": null, "e": 97790, "s": 97578, "text": "The staff can have complete control over the wash cycles, and wear and tear of the linen. Thus, life of the fabric can be prolonged by using specific washing for the linen depending upon degree of their soiling." }, { "code": null, "e": 97984, "s": 97790, "text": "On-premise laundry is the game of conservation of water and electricity and generation of high throughput. These equipment speed up the housekeeping work. The laundry equipment mainly include −" }, { "code": null, "e": 98143, "s": 97984, "text": "They are automatic machines which are used to wash the linen in large amount. They provide high laundry room productivity by using less water and electricity." }, { "code": null, "e": 98276, "s": 98143, "text": "They dry the linen in less time than conventional drying methods. They deliver fast drying without consuming much electrical energy." }, { "code": null, "e": 98421, "s": 98276, "text": "They save energy, cost, and efforts to press the large number of linen by delivering them ironed and pressed. They are easy and safe to operate." }, { "code": null, "e": 98577, "s": 98421, "text": "They are yet another automatic laundry devices that can deliver a perfectly folded and finished linen. They can also help to stack the folded linen neatly." }, { "code": null, "e": 98680, "s": 98577, "text": "The housekeeping staff that handles laundry section is expected to know each device and its operation." }, { "code": null, "e": 99011, "s": 98680, "text": "The laundry consists of bath and bed linen, dining are linen, staff uniforms, cleaning cloths, curtains, drapes, blankets, and rugs. The guest laundry is handled by the most experienced staff. The staff in the laundry room is expected to be aware of the chemicals, detergents, dry cleaning agents, and the stages of laundry cycle." }, { "code": null, "e": 99117, "s": 99011, "text": "No sooner than the soiled laundry arrives, the laundering work starts quickly. The reason behind it are −" }, { "code": null, "e": 99172, "s": 99117, "text": "The soiled linen must be cleaned as early as possible." }, { "code": null, "e": 99202, "s": 99172, "text": "The stains may get permanent." }, { "code": null, "e": 99249, "s": 99202, "text": "The stains may get transferred to other linen." }, { "code": null, "e": 99317, "s": 99249, "text": "The soiled linen should not provide a breeding ground for bacteria." }, { "code": null, "e": 99367, "s": 99317, "text": "To avoid the chances of linen misplacing or loss." }, { "code": null, "e": 99415, "s": 99367, "text": "The laundry goes through the following stages −" }, { "code": null, "e": 99468, "s": 99415, "text": "This cycle depicts the typical operating procedures." }, { "code": null, "e": 99564, "s": 99468, "text": "The laundry management is carried out on daily basis. Here are some standard procedures given −" }, { "code": null, "e": 99886, "s": 99564, "text": "Collect Dirty Linen − Collect the dirty linen from various sections in the hotel such as guest rooms, guest bathrooms, and dining area. Put the soiled linen separately. The principle is, whatever linen it is, it must not hang over the edge of the collection basket. Transfer the collected linen to the laundry department." }, { "code": null, "e": 100208, "s": 99886, "text": "Collect Dirty Linen − Collect the dirty linen from various sections in the hotel such as guest rooms, guest bathrooms, and dining area. Put the soiled linen separately. The principle is, whatever linen it is, it must not hang over the edge of the collection basket. Transfer the collected linen to the laundry department." }, { "code": null, "e": 100519, "s": 100208, "text": "Sort the Linen − Segregate the linen carefully according to type of fabric, domain of item use, degree of soiling, and type of soiling. Keep the staff uniforms, guest room and bathroom linen, dining area linen, butchery aprons, and guests’ personal clothes all separately. Always handle the linen using gloves." }, { "code": null, "e": 100830, "s": 100519, "text": "Sort the Linen − Segregate the linen carefully according to type of fabric, domain of item use, degree of soiling, and type of soiling. Keep the staff uniforms, guest room and bathroom linen, dining area linen, butchery aprons, and guests’ personal clothes all separately. Always handle the linen using gloves." }, { "code": null, "e": 101113, "s": 100830, "text": "Pre-treat the Stains − Before the putting the linen into the washer, inspect it for stains such as grease or oil. Remove the stains using stain cleaning chemicals. If instructed before, use detergents and cleaning chemicals at the time of washing only, to save the time and efforts." }, { "code": null, "e": 101396, "s": 101113, "text": "Pre-treat the Stains − Before the putting the linen into the washer, inspect it for stains such as grease or oil. Remove the stains using stain cleaning chemicals. If instructed before, use detergents and cleaning chemicals at the time of washing only, to save the time and efforts." }, { "code": null, "e": 101880, "s": 101396, "text": "Wash/Extract the Linen − Put the linen into washers. Weigh the linen before washing process to ensure the washers are not overloaded.\nThe housekeeping staff need to handle many washers and dryers depending on the size of hotel and occupancy of rooms. Set the automatic washers to different wash cycles depending upon the type of linen. For example, embroidered pillow covers need soft wash cycle and the curtains need harder wash cycles. The following wash cycle is most effective − " }, { "code": null, "e": 102014, "s": 101880, "text": "Wash/Extract the Linen − Put the linen into washers. Weigh the linen before washing process to ensure the washers are not overloaded." }, { "code": null, "e": 102364, "s": 102014, "text": "The housekeeping staff need to handle many washers and dryers depending on the size of hotel and occupancy of rooms. Set the automatic washers to different wash cycles depending upon the type of linen. For example, embroidered pillow covers need soft wash cycle and the curtains need harder wash cycles. The following wash cycle is most effective − " }, { "code": null, "e": 102421, "s": 102364, "text": "Soak → Flush → Suds → Bleach → Rinse → Extract → Starch\n" }, { "code": null, "e": 102561, "s": 102421, "text": "Remove as much as possible water content from the linen by using extractors. The linen are then starched to make it little stiff and shiny." }, { "code": null, "e": 102701, "s": 102561, "text": "Remove as much as possible water content from the linen by using extractors. The linen are then starched to make it little stiff and shiny." }, { "code": null, "e": 103139, "s": 102701, "text": "Dry the Linen − Put the linen into dryers for removing any moisture still left. Be careful while transferring the linen from washers to dryers because the weight of the linen increases after washing. Use automatic dryer that provides drying by hot air blows. The lint comes off from the linen surface in the process of drying yielding a finished surface. These dryers operate on less electricity and yield fresh and completely dry linen." }, { "code": null, "e": 103577, "s": 103139, "text": "Dry the Linen − Put the linen into dryers for removing any moisture still left. Be careful while transferring the linen from washers to dryers because the weight of the linen increases after washing. Use automatic dryer that provides drying by hot air blows. The lint comes off from the linen surface in the process of drying yielding a finished surface. These dryers operate on less electricity and yield fresh and completely dry linen." }, { "code": null, "e": 103864, "s": 103577, "text": "Iron/Repair the Linen − At this stage, check the linen for any wear and tear. Separate the worn out linen to be given to the tailor. Some linen such as towels, bed linen, and dining area linen require Ironing. Pass these linen through the ironer. Hand-iron a few linen such as uniforms." }, { "code": null, "e": 104151, "s": 103864, "text": "Iron/Repair the Linen − At this stage, check the linen for any wear and tear. Separate the worn out linen to be given to the tailor. Some linen such as towels, bed linen, and dining area linen require Ironing. Pass these linen through the ironer. Hand-iron a few linen such as uniforms." }, { "code": null, "e": 104570, "s": 104151, "text": "Fold and Stack the Linen − Automatic folding and stacking machines come to the aid of housekeeping staff to save them from the large effort of folding and stacking the linen accurately. Some sort of linen such as staff uniforms and guest personal clothes still need manual efforts for folding. Operate the folding/stacking machines that ascertains finished appearance and makes the linen easy for storage and handling." }, { "code": null, "e": 104989, "s": 104570, "text": "Fold and Stack the Linen − Automatic folding and stacking machines come to the aid of housekeeping staff to save them from the large effort of folding and stacking the linen accurately. Some sort of linen such as staff uniforms and guest personal clothes still need manual efforts for folding. Operate the folding/stacking machines that ascertains finished appearance and makes the linen easy for storage and handling." }, { "code": null, "e": 105279, "s": 104989, "text": "Deliver the Linen − Transport the ready laundered linen to the uniform room and linen room. Send the linen that need repair to the tailor room. Then subsequently deliver the linen at the time of keeping and cleaning the various premises such as guest rooms, dining area, and banquet halls." }, { "code": null, "e": 105569, "s": 105279, "text": "Deliver the Linen − Transport the ready laundered linen to the uniform room and linen room. Send the linen that need repair to the tailor room. Then subsequently deliver the linen at the time of keeping and cleaning the various premises such as guest rooms, dining area, and banquet halls." }, { "code": null, "e": 105652, "s": 105569, "text": "Give away the guests’ personal clothes according to the rooms they are staying in." }, { "code": null, "e": 105731, "s": 105652, "text": "Success is not created by one person but by a team that comes together as one." }, { "code": null, "e": 105814, "s": 105731, "text": "− Jillan Farrar, American Singer-Songwriter, Author, Publisher, and Film Producer." }, { "code": null, "e": 106008, "s": 105814, "text": "If various departments are seen as organs of the body then the housekeeping department can be seen as a mesh of the nerves that keeps coordination with various organs to achieve its objectives." }, { "code": null, "e": 106334, "s": 106008, "text": "No work in the industry is complete without coordination and documentation. The housekeeping department is not an exception either. It needs to coordinate within the department itself and with the other departments in the hotel business for while working on daily basis and completing documentation formalities while working." }, { "code": null, "e": 106381, "s": 106334, "text": "Let us see more on housekeeping communication." }, { "code": null, "e": 106585, "s": 106381, "text": "The housekeeping control desk is the hub or a single point of contact for all hotel housekeeping staff. At the control desk, the new information is fetched and it is distributed among the relevant staff." }, { "code": null, "e": 106908, "s": 106585, "text": "As the housekeeping work is mainly oriented towards providing the best service to the guests, this department needs to work towards sharing information without any communication gaps. This desk also needs to ensure that the coordination among the housekeeping staff and with all other departments of the hotel goes smooth." }, { "code": null, "e": 106966, "s": 106908, "text": "The hotel housekeeping performs the following functions −" }, { "code": null, "e": 107010, "s": 106966, "text": "Collecting all requests made by the guests." }, { "code": null, "e": 107054, "s": 107010, "text": "Collecting all requests made by the guests." }, { "code": null, "e": 107161, "s": 107054, "text": "Briefing the staff about the routine or special event preparation before the staff turns up their sleeves." }, { "code": null, "e": 107268, "s": 107161, "text": "Briefing the staff about the routine or special event preparation before the staff turns up their sleeves." }, { "code": null, "e": 107337, "s": 107268, "text": "Assigning routine duties / changed duties to the housekeeping staff." }, { "code": null, "e": 107406, "s": 107337, "text": "Assigning routine duties / changed duties to the housekeeping staff." }, { "code": null, "e": 107442, "s": 107406, "text": "Collecting work reports from staff." }, { "code": null, "e": 107478, "s": 107442, "text": "Collecting work reports from staff." }, { "code": null, "e": 107552, "s": 107478, "text": "Collecting check-out room number and updating it to the floor supervisor." }, { "code": null, "e": 107626, "s": 107552, "text": "Collecting check-out room number and updating it to the floor supervisor." }, { "code": null, "e": 107726, "s": 107626, "text": "Handling key cabinet that contains the keys of all floors’ master keys and housekeeping store keys." }, { "code": null, "e": 107826, "s": 107726, "text": "Handling key cabinet that contains the keys of all floors’ master keys and housekeeping store keys." }, { "code": null, "e": 107878, "s": 107826, "text": "Maintaining various records of forms and registers." }, { "code": null, "e": 107930, "s": 107878, "text": "Maintaining various records of forms and registers." }, { "code": null, "e": 108026, "s": 107930, "text": "While working, the housekeeping department needs to coordinate with the following departments −" }, { "code": null, "e": 108135, "s": 108026, "text": "Sharing occupancy information that helps to estimate future occupancy, budget, and required number of staff." }, { "code": null, "e": 108244, "s": 108135, "text": "Sharing occupancy information that helps to estimate future occupancy, budget, and required number of staff." }, { "code": null, "e": 108285, "s": 108244, "text": "Cleaning public areas of hotel premises." }, { "code": null, "e": 108326, "s": 108285, "text": "Cleaning public areas of hotel premises." }, { "code": null, "e": 108439, "s": 108326, "text": "Special attention requirements like VIP guests, corporate or large family groups, or airline crews as occupants." }, { "code": null, "e": 108552, "s": 108439, "text": "Special attention requirements like VIP guests, corporate or large family groups, or airline crews as occupants." }, { "code": null, "e": 108652, "s": 108552, "text": "Collection of soiled uniforms from and provision of ready uniforms to the front-office staff daily." }, { "code": null, "e": 108752, "s": 108652, "text": "Collection of soiled uniforms from and provision of ready uniforms to the front-office staff daily." }, { "code": null, "e": 108792, "s": 108752, "text": "Forthcoming banquet events and parties." }, { "code": null, "e": 108832, "s": 108792, "text": "Forthcoming banquet events and parties." }, { "code": null, "e": 108857, "s": 108832, "text": "Pest control in kitchen." }, { "code": null, "e": 108882, "s": 108857, "text": "Pest control in kitchen." }, { "code": null, "e": 109012, "s": 108882, "text": "Collection of soiled linen and uniforms from the F&B department and provision of ready linen and uniforms to the F&B staff daily." }, { "code": null, "e": 109142, "s": 109012, "text": "Collection of soiled linen and uniforms from the F&B department and provision of ready linen and uniforms to the F&B staff daily." }, { "code": null, "e": 109183, "s": 109142, "text": "Clearance of trays from guest corridors." }, { "code": null, "e": 109224, "s": 109183, "text": "Clearance of trays from guest corridors." }, { "code": null, "e": 109316, "s": 109224, "text": "Placement of special guest amenities in guest rooms such as VIP amenities or welcome drink." }, { "code": null, "e": 109408, "s": 109316, "text": "Placement of special guest amenities in guest rooms such as VIP amenities or welcome drink." }, { "code": null, "e": 109506, "s": 109408, "text": "Supply of promotional brochures, rate cards, or other items such as pen stand in the guest rooms." }, { "code": null, "e": 109604, "s": 109506, "text": "Supply of promotional brochures, rate cards, or other items such as pen stand in the guest rooms." }, { "code": null, "e": 109714, "s": 109604, "text": "Collection of soiled uniforms from the S&M department and provision of ready uniforms to the S&M staff daily." }, { "code": null, "e": 109824, "s": 109714, "text": "Collection of soiled uniforms from the S&M department and provision of ready uniforms to the S&M staff daily." }, { "code": null, "e": 109882, "s": 109824, "text": "Acquisition of new staff for the housekeeping department." }, { "code": null, "e": 109940, "s": 109882, "text": "Acquisition of new staff for the housekeeping department." }, { "code": null, "e": 110034, "s": 109940, "text": "Compensation of housekeeping staff members such as salary, over time, medical treatment, etc." }, { "code": null, "e": 110128, "s": 110034, "text": "Compensation of housekeeping staff members such as salary, over time, medical treatment, etc." }, { "code": null, "e": 110231, "s": 110128, "text": "Motivation for staff performance by appraisal or reward, induction and training program for new staff." }, { "code": null, "e": 110334, "s": 110231, "text": "Motivation for staff performance by appraisal or reward, induction and training program for new staff." }, { "code": null, "e": 110433, "s": 110334, "text": "Collection of soiled uniforms from the HRD and provision of ready uniforms to the HRD staff daily." }, { "code": null, "e": 110532, "s": 110433, "text": "Collection of soiled uniforms from the HRD and provision of ready uniforms to the HRD staff daily." }, { "code": null, "e": 110568, "s": 110532, "text": "Safety of hotel property, and keys." }, { "code": null, "e": 110604, "s": 110568, "text": "Safety of hotel property, and keys." }, { "code": null, "e": 110648, "s": 110604, "text": "Prevention of fire and thefts in the hotel." }, { "code": null, "e": 110692, "s": 110648, "text": "Prevention of fire and thefts in the hotel." }, { "code": null, "e": 110849, "s": 110692, "text": "Prevention of any anti-social activities such as any suspicious activities, gambling, or smuggling performed by guests in the guest rooms or hotel premises." }, { "code": null, "e": 111006, "s": 110849, "text": "Prevention of any anti-social activities such as any suspicious activities, gambling, or smuggling performed by guests in the guest rooms or hotel premises." }, { "code": null, "e": 111105, "s": 111006, "text": "Collection of soiled uniforms from the HRD and provision of ready uniforms to the HRD staff daily." }, { "code": null, "e": 111204, "s": 111105, "text": "Collection of soiled uniforms from the HRD and provision of ready uniforms to the HRD staff daily." }, { "code": null, "e": 111317, "s": 111204, "text": "Collection of soiled uniforms from the porters, doormen, drivers, and provision of ready uniforms to them daily." }, { "code": null, "e": 111430, "s": 111317, "text": "Collection of soiled uniforms from the porters, doormen, drivers, and provision of ready uniforms to them daily." }, { "code": null, "e": 111457, "s": 111430, "text": "It takes place regarding −" }, { "code": null, "e": 111511, "s": 111457, "text": "The issues related to payments of housekeeping staff." }, { "code": null, "e": 111565, "s": 111511, "text": "The issues related to payments of housekeeping staff." }, { "code": null, "e": 111685, "s": 111565, "text": "Collection of soiled uniforms from the Accounts department and provision of ready uniforms to the accounts staff daily." }, { "code": null, "e": 111805, "s": 111685, "text": "Collection of soiled uniforms from the Accounts department and provision of ready uniforms to the accounts staff daily." }, { "code": null, "e": 111985, "s": 111805, "text": "The issues related to erroneous functioning of cleaning and gardening equipment, faulty electric power points, leaning pipes, air-conditioning maintenance, or any other such work." }, { "code": null, "e": 112165, "s": 111985, "text": "The issues related to erroneous functioning of cleaning and gardening equipment, faulty electric power points, leaning pipes, air-conditioning maintenance, or any other such work." }, { "code": null, "e": 112284, "s": 112165, "text": "Collection of soiled uniforms from the Engineering and Technology staff and provision of ready uniforms to them daily." }, { "code": null, "e": 112403, "s": 112284, "text": "Collection of soiled uniforms from the Engineering and Technology staff and provision of ready uniforms to them daily." }, { "code": null, "e": 112467, "s": 112403, "text": "The repairing and maintenance of broken furniture and fixtures." }, { "code": null, "e": 112515, "s": 112467, "text": "The painting of the required area in the hotel." }, { "code": null, "e": 112571, "s": 112515, "text": "Repairing pipes and electric points in the guest rooms." }, { "code": null, "e": 112675, "s": 112571, "text": "Collection of soiled uniforms from the Maintenance staff and provision of ready uniforms to them daily." }, { "code": null, "e": 113002, "s": 112675, "text": "The registers are used to record important information. They are very helpful when the shifts and staff on duty changes, and while working too. The registers serve the purpose of keeping clear and timely records thereby fostering good communication. Here are some important registers maintained by housekeeping control desk − " }, { "code": null, "e": 113192, "s": 113002, "text": "It is kept to track the changes of guest room status such as V, VD, or VC after the guest has checked out. It also tracks the amount of Mini bar beverages consumption in the CO guest rooms." }, { "code": null, "e": 113357, "s": 113192, "text": "It keeps the track of pre-registered guests and their profile as Regular/VIP/Other, Marital status, expected check-in time, and any special request to be fulfilled." }, { "code": null, "e": 113456, "s": 113357, "text": "This register records the list of all rooms and their current status such as V, VC, OOO, OOS, etc." }, { "code": null, "e": 113614, "s": 113456, "text": "It records the instructions or notes relevant to the guest rooms and adjacent area. It is very useful in keeping the track of activities and their durations." }, { "code": null, "e": 113770, "s": 113614, "text": "This register is maintained to record the delivery and recovery of the loan items given to the guests. The general format of this register is as follows − " }, { "code": null, "e": 113910, "s": 113770, "text": "If any article owned by the hotel (other than consumable items) is found missing in a Check-Out room, then it is recorded in this Register." }, { "code": null, "e": 114004, "s": 113910, "text": "This register is maintained to record guest supplies. The general format is as shown below − " }, { "code": null, "e": 114141, "s": 114004, "text": "If any hotel property placed in the guest room is found damaged or broken, it is recorded in this Register. Here is a sample register − " }, { "code": null, "e": 114410, "s": 114141, "text": "If a housekeeping guest room attendant finds any guest-owned article left in the Check-Out room then it is recorded into the Lost/Found Register and sent to the same cell of the housekeeping department. It also records any personal article found in the hotel premises." }, { "code": null, "e": 114540, "s": 114410, "text": "It is a register for noting down the issued keys of the guest rooms, mater keys of the rooms and important safes, and floor keys." }, { "code": null, "e": 114713, "s": 114540, "text": "It records the movement of linen between the laundry and the guest rooms or dining area. It makes the housekeeping staff easy to keep the track of clean and soiled laundry." }, { "code": null, "e": 114825, "s": 114713, "text": "There are various housekeeping checklists and reports automatically generated by the hotel management software." }, { "code": null, "e": 115024, "s": 114825, "text": "Checklists help to ensure all work is done appropriately without anything left to be completed. There are various checklists referred and filled by the housekeeping staff. Some important ones are − " }, { "code": null, "e": 115049, "s": 115024, "text": "Guest Supplies Checklist" }, { "code": null, "e": 115079, "s": 115049, "text": "Guest Room Cleaning Checklist" }, { "code": null, "e": 115113, "s": 115079, "text": "Guest Bathroom Cleaning Checklist" }, { "code": null, "e": 115143, "s": 115113, "text": "Beach Area Cleaning Checklist" }, { "code": null, "e": 115176, "s": 115143, "text": "Swimming Pool Cleaning Checklist" }, { "code": null, "e": 115201, "s": 115176, "text": "Garden Keeping Checklist" }, { "code": null, "e": 115241, "s": 115201, "text": "Housekeeping Standard Checklist for SPA" }, { "code": null, "e": 115292, "s": 115241, "text": "Housekeeping Standard Checklist for Fitness Center" }, { "code": null, "e": 115479, "s": 115292, "text": "The reports are useful to study past records of occupancy, cleaning schedules, and predict the future status of the rooms. Let us see the reports generated for housekeeping department − " }, { "code": null, "e": 115499, "s": 115479, "text": "Housekeeping Report" }, { "code": null, "e": 115594, "s": 115499, "text": "This can be generated at the end of each shift to report the housekeeping status of each room." }, { "code": null, "e": 115625, "s": 115594, "text": "Housekeeping Assignment Report" }, { "code": null, "e": 115711, "s": 115625, "text": "It is required for scheduling the room attendants and recording the room inspections." }, { "code": null, "e": 115741, "s": 115711, "text": "Housekeeping Occupancy Report" }, { "code": null, "e": 116091, "s": 115741, "text": "This report shows the list of guests who have checked-in the hotel with details such as number of adults and children, number of nights, and housekeeping status. This report is generated for the occupied rooms, rooms expected to be occupied, checked-out rooms, and vacant or blocked rooms. This report is generated for scheduling rooms for cleaning." }, { "code": null, "e": 116123, "s": 116091, "text": "\n 5 Lectures \n 2 hours \n" }, { "code": null, "e": 116137, "s": 116123, "text": " Manish Gupta" }, { "code": null, "e": 116170, "s": 116137, "text": "\n 18 Lectures \n 2 hours \n" }, { "code": null, "e": 116184, "s": 116170, "text": " Manish Gupta" }, { "code": null, "e": 116219, "s": 116184, "text": "\n 31 Lectures \n 2.5 hours \n" }, { "code": null, "e": 116233, "s": 116219, "text": " Manish Gupta" }, { "code": null, "e": 116266, "s": 116233, "text": "\n 15 Lectures \n 1 hours \n" }, { "code": null, "e": 116280, "s": 116266, "text": " Manish Gupta" }, { "code": null, "e": 116313, "s": 116280, "text": "\n 10 Lectures \n 2 hours \n" }, { "code": null, "e": 116327, "s": 116313, "text": " Manish Gupta" }, { "code": null, "e": 116362, "s": 116327, "text": "\n 35 Lectures \n 2.5 hours \n" }, { "code": null, "e": 116376, "s": 116362, "text": " Manish Gupta" }, { "code": null, "e": 116383, "s": 116376, "text": " Print" }, { "code": null, "e": 116394, "s": 116383, "text": " Add Notes" } ]
Writing code faster in C++ STL - GeeksforGeeks
20 Jul, 2017 You are wondering some time coder write his code in 2 min or less how? No kidding! Although this tip may not be very useful for competitions such as ICPC or IOI. But there are recent ICPCs ranks where rank i and rank i + 1 are just separated by few minutes. When you can solve the same number of problems as your competitor, it is now down to coding skill and ... typing speed. Try this typing test at typingtest.com and follow the instructions there on how to improve your typing skill. Many of them uses typedefs, shortcuts, or macros that are commonly used by competitive programmers to speed up the coding time. In this short section, we list down several examples as below. // C++ STL shortcuts for// typing codes fast#include <bits/stdc++.h> // Shortcuts for "common" data types in conteststypedef long long ll;typedef vector<int> vi;typedef pair<int, int> ii;typedef vector<ii> vii;typedef set<int> si;typedef map<string, int> msi; // To simplify repetitions/loops, Note: define your// loop style and stick with it!#define REP(i, a, b) \for(int i = int(a); i <= int(b); i++) // a to b, and variable i is local!#define TRvi(c, it) \for(vi::iterator it = (c).begin(); it != (c).end(); it++)#define TRvii(c, it) \for(vii::iterator it = (c).begin(); it != (c).end(); it++)#define TRmsi(c, it) \for(msi::iterator it = (c).begin(); it != (c).end(); it++) #define INF 2000000000 // 2 billion // If you need to recall how to use memset:#define MEMSET_INF 127 // about 2B#define MEMSET_HALF_INF 63 // about 1B // memset(dist, MEMSET_INF, sizeof dist); // useful to initialize shortest path distances// memset(dp_memo, -1, sizeof dp_memo); // useful to initialize DP memoization table// memset(arr, 0, sizeof arr); // useful to clear array of integers int main(){ ios_base::sync_with_stdio(false); cin.tie(NULL); // YOUR CODE GOES HERE return 0;} Here, typedef and #define are used to short the code and you can use as per your need in main method ios_base::sync_with_stdio(false); and cin.tie(NULL); use for fast io which is reduce the time of running code. Related Articles: Writing C/C++ code efficiently in Competitive programming How to begin with Competitive Programming? Tips and Tricks for Competitive Programmers | Set 1 (For Beginners) This article is contributed by Dhavalkumar Prajapati. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Competitive Programming Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Multistage Graph (Shortest Path) Breadth First Traversal ( BFS ) on a 2D array Shortest path in a directed graph by Dijkstra’s algorithm 5 Best Books for Competitive Programming Check whether bitwise AND of a number with any subset of an array is zero or not 5 Best Languages for Competitive Programming Most important type of Algorithms Difference between Backtracking and Branch-N-Bound technique String hashing using Polynomial rolling hash function Graph implementation using STL for competitive programming | Set 2 (Weighted graph)
[ { "code": null, "e": 26279, "s": 26251, "text": "\n20 Jul, 2017" }, { "code": null, "e": 26657, "s": 26279, "text": "You are wondering some time coder write his code in 2 min or less how? No kidding! Although this tip may not be very useful for competitions such as ICPC or IOI. But there are recent ICPCs ranks where rank i and rank i + 1 are just separated by few minutes. When you can solve the same number of problems as your competitor, it is now down to coding skill and ... typing speed." }, { "code": null, "e": 26767, "s": 26657, "text": "Try this typing test at typingtest.com and follow the instructions there on how to improve your typing skill." }, { "code": null, "e": 26958, "s": 26767, "text": "Many of them uses typedefs, shortcuts, or macros that are commonly used by competitive programmers to speed up the coding time. In this short section, we list down several examples as below." }, { "code": "// C++ STL shortcuts for// typing codes fast#include <bits/stdc++.h> // Shortcuts for \"common\" data types in conteststypedef long long ll;typedef vector<int> vi;typedef pair<int, int> ii;typedef vector<ii> vii;typedef set<int> si;typedef map<string, int> msi; // To simplify repetitions/loops, Note: define your// loop style and stick with it!#define REP(i, a, b) \\for(int i = int(a); i <= int(b); i++) // a to b, and variable i is local!#define TRvi(c, it) \\for(vi::iterator it = (c).begin(); it != (c).end(); it++)#define TRvii(c, it) \\for(vii::iterator it = (c).begin(); it != (c).end(); it++)#define TRmsi(c, it) \\for(msi::iterator it = (c).begin(); it != (c).end(); it++) #define INF 2000000000 // 2 billion // If you need to recall how to use memset:#define MEMSET_INF 127 // about 2B#define MEMSET_HALF_INF 63 // about 1B // memset(dist, MEMSET_INF, sizeof dist); // useful to initialize shortest path distances// memset(dp_memo, -1, sizeof dp_memo); // useful to initialize DP memoization table// memset(arr, 0, sizeof arr); // useful to clear array of integers int main(){ ios_base::sync_with_stdio(false); cin.tie(NULL); // YOUR CODE GOES HERE return 0;}", "e": 28145, "s": 26958, "text": null }, { "code": null, "e": 28357, "s": 28145, "text": "Here, typedef and #define are used to short the code and you can use as per your need in main method ios_base::sync_with_stdio(false); and cin.tie(NULL); use for fast io which is reduce the time of running code." }, { "code": null, "e": 28375, "s": 28357, "text": "Related Articles:" }, { "code": null, "e": 28433, "s": 28375, "text": "Writing C/C++ code efficiently in Competitive programming" }, { "code": null, "e": 28476, "s": 28433, "text": "How to begin with Competitive Programming?" }, { "code": null, "e": 28544, "s": 28476, "text": "Tips and Tricks for Competitive Programmers | Set 1 (For Beginners)" }, { "code": null, "e": 28853, "s": 28544, "text": "This article is contributed by Dhavalkumar Prajapati. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 28978, "s": 28853, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 29002, "s": 28978, "text": "Competitive Programming" }, { "code": null, "e": 29100, "s": 29002, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29133, "s": 29100, "text": "Multistage Graph (Shortest Path)" }, { "code": null, "e": 29179, "s": 29133, "text": "Breadth First Traversal ( BFS ) on a 2D array" }, { "code": null, "e": 29237, "s": 29179, "text": "Shortest path in a directed graph by Dijkstra’s algorithm" }, { "code": null, "e": 29278, "s": 29237, "text": "5 Best Books for Competitive Programming" }, { "code": null, "e": 29359, "s": 29278, "text": "Check whether bitwise AND of a number with any subset of an array is zero or not" }, { "code": null, "e": 29404, "s": 29359, "text": "5 Best Languages for Competitive Programming" }, { "code": null, "e": 29438, "s": 29404, "text": "Most important type of Algorithms" }, { "code": null, "e": 29499, "s": 29438, "text": "Difference between Backtracking and Branch-N-Bound technique" }, { "code": null, "e": 29553, "s": 29499, "text": "String hashing using Polynomial rolling hash function" } ]
Program to calculate the Round Trip Time (RTT) - GeeksforGeeks
27 Sep, 2021 Round trip time(RTT) is the length of time it takes for a signal to be sent plus the length of time it takes for an acknowledgment of that signal to be received. This time, therefore, consists of the propagation times between the two-point of the signal. On the Internet, an end-user can determine the RTT to and from an IP(Internet Protocol) address by pinging that address. The result depends on various factors:- The data rate transfer of the source’s internet connection. The nature of transmission medium. The physical distance between source and destination. The number of nodes between source and destination. The amount of traffic on the LAN(Local Area Network) to which end-user is connected. The number of other requests being handled by intermediate nodes and the remote server. The speed with which the intermediate node and the remote server function. The presence of Interference in the circuit. Examples: Input : www.geeksforgeeks.org Output : Time in seconds : 0.212174892426 Input : www.cricbuzz.com Output : Time in seconds : 0.55425786972 Python # Python program to calculate RTT import timeimport requests # Function to calculate the RTTdef RTT(url): # time when the signal is sent t1 = time.time() r = requests.get(url) # time when acknowledgement of signal # is received t2 = time.time() # total time taken tim = str(t2-t1) print("Time in seconds :" + tim) # driver program# url addressurl = "http://www.google.com"RTT(url) Output: Time in seconds :0.0579478740692 This article is contributed by Pramod Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. jeevanyasa Computer Networks Python Computer Networks Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Differences between IPv4 and IPv6 Socket Programming in Python Caesar Cipher in Cryptography UDP Server-Client implementation in C Socket Programming in Java 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": 37839, "s": 37811, "text": "\n27 Sep, 2021" }, { "code": null, "e": 38095, "s": 37839, "text": "Round trip time(RTT) is the length of time it takes for a signal to be sent plus the length of time it takes for an acknowledgment of that signal to be received. This time, therefore, consists of the propagation times between the two-point of the signal. " }, { "code": null, "e": 38257, "s": 38095, "text": "On the Internet, an end-user can determine the RTT to and from an IP(Internet Protocol) address by pinging that address. The result depends on various factors:- " }, { "code": null, "e": 38317, "s": 38257, "text": "The data rate transfer of the source’s internet connection." }, { "code": null, "e": 38352, "s": 38317, "text": "The nature of transmission medium." }, { "code": null, "e": 38406, "s": 38352, "text": "The physical distance between source and destination." }, { "code": null, "e": 38458, "s": 38406, "text": "The number of nodes between source and destination." }, { "code": null, "e": 38543, "s": 38458, "text": "The amount of traffic on the LAN(Local Area Network) to which end-user is connected." }, { "code": null, "e": 38631, "s": 38543, "text": "The number of other requests being handled by intermediate nodes and the remote server." }, { "code": null, "e": 38706, "s": 38631, "text": "The speed with which the intermediate node and the remote server function." }, { "code": null, "e": 38751, "s": 38706, "text": "The presence of Interference in the circuit." }, { "code": null, "e": 38763, "s": 38751, "text": "Examples: " }, { "code": null, "e": 38902, "s": 38763, "text": "Input : www.geeksforgeeks.org\nOutput : Time in seconds : 0.212174892426\n\nInput : www.cricbuzz.com\nOutput : Time in seconds : 0.55425786972" }, { "code": null, "e": 38909, "s": 38902, "text": "Python" }, { "code": "# Python program to calculate RTT import timeimport requests # Function to calculate the RTTdef RTT(url): # time when the signal is sent t1 = time.time() r = requests.get(url) # time when acknowledgement of signal # is received t2 = time.time() # total time taken tim = str(t2-t1) print(\"Time in seconds :\" + tim) # driver program# url addressurl = \"http://www.google.com\"RTT(url)", "e": 39322, "s": 38909, "text": null }, { "code": null, "e": 39331, "s": 39322, "text": "Output: " }, { "code": null, "e": 39366, "s": 39331, "text": " Time in seconds :0.0579478740692" }, { "code": null, "e": 39787, "s": 39366, "text": "This article is contributed by Pramod Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 39798, "s": 39787, "text": "jeevanyasa" }, { "code": null, "e": 39816, "s": 39798, "text": "Computer Networks" }, { "code": null, "e": 39823, "s": 39816, "text": "Python" }, { "code": null, "e": 39841, "s": 39823, "text": "Computer Networks" }, { "code": null, "e": 39939, "s": 39841, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 39973, "s": 39939, "text": "Differences between IPv4 and IPv6" }, { "code": null, "e": 40002, "s": 39973, "text": "Socket Programming in Python" }, { "code": null, "e": 40032, "s": 40002, "text": "Caesar Cipher in Cryptography" }, { "code": null, "e": 40070, "s": 40032, "text": "UDP Server-Client implementation in C" }, { "code": null, "e": 40097, "s": 40070, "text": "Socket Programming in Java" }, { "code": null, "e": 40125, "s": 40097, "text": "Read JSON file using Python" }, { "code": null, "e": 40175, "s": 40125, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 40197, "s": 40175, "text": "Python map() function" } ]
Processes in Linux/Unix - GeeksforGeeks
29 Jun, 2021 A program/command when executed, a special instance is provided by the system to the process. This instance consists of all the services/resources that may be utilized by the process under execution. Whenever a command is issued in Unix/Linux, it creates/starts a new process. For example, pwd when issued which is used to list the current directory location the user is in, a process starts. Through a 5 digit ID number Unix/Linux keeps an account of the processes, this number is call process ID or PID. Each process in the system has a unique PID. Used up pid’s can be used in again for a newer process since all the possible combinations are used. At any point of time, no two processes with the same pid exist in the system because it is the pid that Unix uses to track each process. Method 1: Foreground Process : Every process when started runs in foreground by default, receives input from the keyboard, and sends output to the screen. When issuing pwd command $ ls pwd Output: $ /home/geeksforgeeks/root When a command/process is running in the foreground and is taking a lot of time, no other processes can be run or started because the prompt would not be available until the program finishes processing and comes out. Method 2: Background Process: It runs in the background without keyboard input and waits till keyboard input is required. Thus, other processes can be done in parallel with the process running in the background since they do not have to wait for the previous process to be completed. Adding & along with the command starts it as a background process $ pwd & Since pwd does not want any input from the keyboard, it goes to the stop state until moved to the foreground and given any data input. Thus, on pressing Enter:Output: [1] + Done pwd $ That first line contains information about the background process – the job number and the process ID. It tells you that the ls command background process finishes successfully. The second is a prompt for another command. ps (Process status) can be used to see/list all the running processes. $ ps PID TTY TIME CMD 19 pts/1 00:00:00 sh 24 pts/1 00:00:00 ps For more information -f (full) can be used along with ps $ ps –f UID PID PPID C STIME TTY TIME CMD 52471 19 1 0 07:20 pts/1 00:00:00f sh 52471 25 19 0 08:04 pts/1 00:00:00 ps -f For single-process information, ps along with process id is used $ ps 19 PID TTY TIME CMD 19 pts/1 00:00:00 sh For a running program (named process) Pidof finds the process id’s (pids) Fields described by ps are described as: UID: User ID that this process belongs to (the person running it) PID: Process ID PPID: Parent process ID (the ID of the process that started it) C: CPU utilization of process STIME: Process start time TTY: Terminal type associated with the process TIME: CPU time is taken by the process CMD: The command that started this process There are other options which can be used along with ps command : -a: Shows information about all users -x: Shows information about processes without terminals -u: Shows additional information like -f option -e: Displays extended information Stopping a process:When running in foreground, hitting Ctrl + c (interrupt character) will exit the command. For processes running in background kill command can be used if it’s pid is known. $ ps –f UID PID PPID C STIME TTY TIME CMD 52471 19 1 0 07:20 pts/1 00:00:00 sh 52471 25 19 0 08:04 pts/1 00:00:00 ps –f $ kill 19 Terminated If a process ignores a regular kill command, you can use kill -9 followed by the process ID. $ kill -9 19 Terminated bg: A job control command that resumes suspended jobs while keeping them running in the background Syntax: bg [ job ] For example: bg %19 fg: It continues a stopped job by running it in the foreground. Syntax: fg [ %job_id ] For example fg 19 top: This command is used to show all the running processes within the working environment of Linux. Syntax: top nice: It starts a new process (job) and assigns it a priority (nice) value at the same time. Syntax: nice [-nice value] nice value ranges from -20 to 19, where -20 is of the highest priority. renice : To change the priority of an already running process renice is used. Syntax: renice [-nice value] [process id] df: It shows the amount of available disk space being used by file systems Syntax: df Output: Filesystem 1K-blocks Used Available Use% Mounted on /dev/loop0 18761008 15246876 2554440 86% / none 4 0 4 0% /sys/fs/cgroup udev 493812 4 493808 1% /dev tmpfs 100672 1364 99308 2% /run none 5120 0 5120 0% /run/lock none 503352 1764 501588 1% /run/shm none 102400 20 102380 1% /run/user /dev/sda3 174766076 164417964 10348112 95% /host free: It shows the total amount of free and used physical and swap memory in the system, as well as the buffers used by the kernel Syntax: free Output: total used free shared buffers cached Mem: 1006708 935872 70836 0 148244 346656 -/+ buffers/cache: 440972 565736 Swap: 262140 130084 132056 Parent and Child process : The 2nd and 3rd column of the ps –f command shows process id and parent’s process id number. For each user process, there’s a parent process in the system, with most of the commands having shell as their parent.Zombie and Orphan process : After completing its execution a child process is terminated or killed and SIGCHLD updates the parent process about the termination and thus can continue the task assigned to it. But at times when the parent process is killed before the termination of the child process, the child processes become orphan processes, with the parent of all processes “init” process, becomes their new pid. A process which is killed but still shows its entry in the process status or the process table is called a zombie process, they are dead and are not used.Daemon process : They are system-related background processes that often run with the permissions of root and services requests from other processes, they most of the time run in the background and wait for processes it can work along with for ex print daemon. When ps –ef is executed, the process with ? in the tty field are daemon processes. Parent and Child process : The 2nd and 3rd column of the ps –f command shows process id and parent’s process id number. For each user process, there’s a parent process in the system, with most of the commands having shell as their parent. Zombie and Orphan process : After completing its execution a child process is terminated or killed and SIGCHLD updates the parent process about the termination and thus can continue the task assigned to it. But at times when the parent process is killed before the termination of the child process, the child processes become orphan processes, with the parent of all processes “init” process, becomes their new pid. A process which is killed but still shows its entry in the process status or the process table is called a zombie process, they are dead and are not used. Daemon process : They are system-related background processes that often run with the permissions of root and services requests from other processes, they most of the time run in the background and wait for processes it can work along with for ex print daemon. When ps –ef is executed, the process with ? in the tty field are daemon processes. eshaangupta101 rajeev0719singh Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. TCP Server-Client implementation in C tar command in Linux with examples curl command in Linux with Examples Conditional Statements | Shell Script UDP Server-Client implementation in C Tail command in Linux with examples Cat command in Linux with examples touch command in Linux with Examples echo command in Linux with Examples Compiling with g++
[ { "code": null, "e": 25253, "s": 25225, "text": "\n29 Jun, 2021" }, { "code": null, "e": 25454, "s": 25253, "text": "A program/command when executed, a special instance is provided by the system to the process. This instance consists of all the services/resources that may be utilized by the process under execution. " }, { "code": null, "e": 25647, "s": 25454, "text": "Whenever a command is issued in Unix/Linux, it creates/starts a new process. For example, pwd when issued which is used to list the current directory location the user is in, a process starts." }, { "code": null, "e": 25805, "s": 25647, "text": "Through a 5 digit ID number Unix/Linux keeps an account of the processes, this number is call process ID or PID. Each process in the system has a unique PID." }, { "code": null, "e": 25906, "s": 25805, "text": "Used up pid’s can be used in again for a newer process since all the possible combinations are used." }, { "code": null, "e": 26044, "s": 25906, "text": "At any point of time, no two processes with the same pid exist in the system because it is the pid that Unix uses to track each process. " }, { "code": null, "e": 26226, "s": 26044, "text": "Method 1: Foreground Process : Every process when started runs in foreground by default, receives input from the keyboard, and sends output to the screen. When issuing pwd command " }, { "code": null, "e": 26235, "s": 26226, "text": "$ ls pwd" }, { "code": null, "e": 26244, "s": 26235, "text": "Output: " }, { "code": null, "e": 26271, "s": 26244, "text": "$ /home/geeksforgeeks/root" }, { "code": null, "e": 26490, "s": 26271, "text": "When a command/process is running in the foreground and is taking a lot of time, no other processes can be run or started because the prompt would not be available until the program finishes processing and comes out. " }, { "code": null, "e": 26841, "s": 26490, "text": "Method 2: Background Process: It runs in the background without keyboard input and waits till keyboard input is required. Thus, other processes can be done in parallel with the process running in the background since they do not have to wait for the previous process to be completed. Adding & along with the command starts it as a background process " }, { "code": null, "e": 26850, "s": 26841, "text": " $ pwd &" }, { "code": null, "e": 27018, "s": 26850, "text": "Since pwd does not want any input from the keyboard, it goes to the stop state until moved to the foreground and given any data input. Thus, on pressing Enter:Output: " }, { "code": null, "e": 27055, "s": 27018, "text": "[1] + Done pwd\n$" }, { "code": null, "e": 27278, "s": 27055, "text": "That first line contains information about the background process – the job number and the process ID. It tells you that the ls command background process finishes successfully. The second is a prompt for another command. " }, { "code": null, "e": 27350, "s": 27278, "text": "ps (Process status) can be used to see/list all the running processes. " }, { "code": null, "e": 27459, "s": 27350, "text": "$ ps\n\nPID TTY TIME CMD\n19 pts/1 00:00:00 sh\n24 pts/1 00:00:00 ps" }, { "code": null, "e": 27518, "s": 27459, "text": "For more information -f (full) can be used along with ps " }, { "code": null, "e": 27688, "s": 27518, "text": "$ ps –f\n\nUID PID PPID C STIME TTY TIME CMD\n52471 19 1 0 07:20 pts/1 00:00:00f sh\n52471 25 19 0 08:04 pts/1 00:00:00 ps -f" }, { "code": null, "e": 27755, "s": 27688, "text": "For single-process information, ps along with process id is used " }, { "code": null, "e": 27833, "s": 27755, "text": "$ ps 19\n\nPID TTY TIME CMD\n19 pts/1 00:00:00 sh" }, { "code": null, "e": 27949, "s": 27833, "text": "For a running program (named process) Pidof finds the process id’s (pids) Fields described by ps are described as: " }, { "code": null, "e": 28015, "s": 27949, "text": "UID: User ID that this process belongs to (the person running it)" }, { "code": null, "e": 28031, "s": 28015, "text": "PID: Process ID" }, { "code": null, "e": 28095, "s": 28031, "text": "PPID: Parent process ID (the ID of the process that started it)" }, { "code": null, "e": 28125, "s": 28095, "text": "C: CPU utilization of process" }, { "code": null, "e": 28151, "s": 28125, "text": "STIME: Process start time" }, { "code": null, "e": 28198, "s": 28151, "text": "TTY: Terminal type associated with the process" }, { "code": null, "e": 28237, "s": 28198, "text": "TIME: CPU time is taken by the process" }, { "code": null, "e": 28280, "s": 28237, "text": "CMD: The command that started this process" }, { "code": null, "e": 28347, "s": 28280, "text": "There are other options which can be used along with ps command : " }, { "code": null, "e": 28385, "s": 28347, "text": "-a: Shows information about all users" }, { "code": null, "e": 28441, "s": 28385, "text": "-x: Shows information about processes without terminals" }, { "code": null, "e": 28489, "s": 28441, "text": "-u: Shows additional information like -f option" }, { "code": null, "e": 28523, "s": 28489, "text": "-e: Displays extended information" }, { "code": null, "e": 28716, "s": 28523, "text": "Stopping a process:When running in foreground, hitting Ctrl + c (interrupt character) will exit the command. For processes running in background kill command can be used if it’s pid is known. " }, { "code": null, "e": 28908, "s": 28716, "text": "$ ps –f\n\nUID PID PPID C STIME TTY TIME CMD\n52471 19 1 0 07:20 pts/1 00:00:00 sh\n52471 25 19 0 08:04 pts/1 00:00:00 ps –f\n\n$ kill 19\nTerminated" }, { "code": null, "e": 29002, "s": 28908, "text": "If a process ignores a regular kill command, you can use kill -9 followed by the process ID. " }, { "code": null, "e": 29026, "s": 29002, "text": "$ kill -9 19\nTerminated" }, { "code": null, "e": 29133, "s": 29026, "text": "bg: A job control command that resumes suspended jobs while keeping them running in the background Syntax:" }, { "code": null, "e": 29144, "s": 29133, "text": "bg [ job ]" }, { "code": null, "e": 29158, "s": 29144, "text": "For example: " }, { "code": null, "e": 29165, "s": 29158, "text": "bg %19" }, { "code": null, "e": 29239, "s": 29165, "text": "fg: It continues a stopped job by running it in the foreground. Syntax: " }, { "code": null, "e": 29254, "s": 29239, "text": "fg [ %job_id ]" }, { "code": null, "e": 29268, "s": 29254, "text": "For example " }, { "code": null, "e": 29274, "s": 29268, "text": "fg 19" }, { "code": null, "e": 29385, "s": 29274, "text": "top: This command is used to show all the running processes within the working environment of Linux. Syntax: " }, { "code": null, "e": 29389, "s": 29385, "text": "top" }, { "code": null, "e": 29492, "s": 29389, "text": "nice: It starts a new process (job) and assigns it a priority (nice) value at the same time. Syntax: " }, { "code": null, "e": 29512, "s": 29492, "text": "nice [-nice value] " }, { "code": null, "e": 29585, "s": 29512, "text": "nice value ranges from -20 to 19, where -20 is of the highest priority. " }, { "code": null, "e": 29673, "s": 29585, "text": "renice : To change the priority of an already running process renice is used. Syntax: " }, { "code": null, "e": 29707, "s": 29673, "text": "renice [-nice value] [process id]" }, { "code": null, "e": 29792, "s": 29707, "text": "df: It shows the amount of available disk space being used by file systems Syntax: " }, { "code": null, "e": 29795, "s": 29792, "text": "df" }, { "code": null, "e": 29805, "s": 29795, "text": "Output: " }, { "code": null, "e": 30328, "s": 29805, "text": "Filesystem 1K-blocks Used Available Use% Mounted on\n/dev/loop0 18761008 15246876 2554440 86% /\nnone 4 0 4 0% /sys/fs/cgroup\nudev 493812 4 493808 1% /dev\ntmpfs 100672 1364 99308 2% /run\nnone 5120 0 5120 0% /run/lock\nnone 503352 1764 501588 1% /run/shm\nnone 102400 20 102380 1% /run/user\n/dev/sda3 174766076 164417964 10348112 95% /host" }, { "code": null, "e": 30469, "s": 30328, "text": "free: It shows the total amount of free and used physical and swap memory in the system, as well as the buffers used by the kernel Syntax: " }, { "code": null, "e": 30474, "s": 30469, "text": "free" }, { "code": null, "e": 30484, "s": 30474, "text": "Output: " }, { "code": null, "e": 30714, "s": 30484, "text": " total used free shared buffers cached\nMem: 1006708 935872 70836 0 148244 346656\n-/+ buffers/cache: 440972 565736\nSwap: 262140 130084 132056" }, { "code": null, "e": 31866, "s": 30714, "text": "Parent and Child process : The 2nd and 3rd column of the ps –f command shows process id and parent’s process id number. For each user process, there’s a parent process in the system, with most of the commands having shell as their parent.Zombie and Orphan process : After completing its execution a child process is terminated or killed and SIGCHLD updates the parent process about the termination and thus can continue the task assigned to it. But at times when the parent process is killed before the termination of the child process, the child processes become orphan processes, with the parent of all processes “init” process, becomes their new pid. A process which is killed but still shows its entry in the process status or the process table is called a zombie process, they are dead and are not used.Daemon process : They are system-related background processes that often run with the permissions of root and services requests from other processes, they most of the time run in the background and wait for processes it can work along with for ex print daemon. When ps –ef is executed, the process with ? in the tty field are daemon processes." }, { "code": null, "e": 32105, "s": 31866, "text": "Parent and Child process : The 2nd and 3rd column of the ps –f command shows process id and parent’s process id number. For each user process, there’s a parent process in the system, with most of the commands having shell as their parent." }, { "code": null, "e": 32676, "s": 32105, "text": "Zombie and Orphan process : After completing its execution a child process is terminated or killed and SIGCHLD updates the parent process about the termination and thus can continue the task assigned to it. But at times when the parent process is killed before the termination of the child process, the child processes become orphan processes, with the parent of all processes “init” process, becomes their new pid. A process which is killed but still shows its entry in the process status or the process table is called a zombie process, they are dead and are not used." }, { "code": null, "e": 33020, "s": 32676, "text": "Daemon process : They are system-related background processes that often run with the permissions of root and services requests from other processes, they most of the time run in the background and wait for processes it can work along with for ex print daemon. When ps –ef is executed, the process with ? in the tty field are daemon processes." }, { "code": null, "e": 33037, "s": 33022, "text": "eshaangupta101" }, { "code": null, "e": 33053, "s": 33037, "text": "rajeev0719singh" }, { "code": null, "e": 33064, "s": 33053, "text": "Linux-Unix" }, { "code": null, "e": 33162, "s": 33064, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33200, "s": 33162, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 33235, "s": 33200, "text": "tar command in Linux with examples" }, { "code": null, "e": 33271, "s": 33235, "text": "curl command in Linux with Examples" }, { "code": null, "e": 33309, "s": 33271, "text": "Conditional Statements | Shell Script" }, { "code": null, "e": 33347, "s": 33309, "text": "UDP Server-Client implementation in C" }, { "code": null, "e": 33383, "s": 33347, "text": "Tail command in Linux with examples" }, { "code": null, "e": 33418, "s": 33383, "text": "Cat command in Linux with examples" }, { "code": null, "e": 33455, "s": 33418, "text": "touch command in Linux with Examples" }, { "code": null, "e": 33491, "s": 33455, "text": "echo command in Linux with Examples" } ]
Compute average of two numbers without overflow - GeeksforGeeks
28 Apr, 2021 Given two numbers, a and b. Compute the average of the two numbers.The well know formula (a + b) / 2 may fail at the following case : If, a = b = (2^31) – 1; i.e. INT_MAX. Now, (a+b) will cause overflow and hence formula (a + b) / 2 wont work Below is the implementation : C++ Java Python3 C# Javascript // C++ code to compute average of two numbers#include <bits/stdc++.h>using namespace std; // Function to compute average of two numbersint compute_average(int a, int b){ return (a + b) / 2;} // Driver codeint main(){ // Assigning maximum integer value int a = INT_MAX, b = INT_MAX; // Average of two equal numbers is the same number cout << "Actual average : " << INT_MAX << endl; // Function to get the average of 2 numbers cout << "Computed average : " << compute_average(a, b); return 0;} // Java code to compute average of two numbers import java.io.*; class GFG { // Function to compute average of two numbersstatic int compute_average(int a, int b){ return (a + b) / 2;} // Driver code public static void main (String[] args) { // Assigning maximum integer value int a = Integer.MAX_VALUE; int b = Integer.MAX_VALUE; // Average of two equal numbers is the same number System.out.println("Actual average : " + Integer.MAX_VALUE); // Function to get the average of 2 numbers System.out.println("Computed average : " + compute_average(a, b)); }// This code is contributed by ajit. } # Python 3 code to compute# average of two numbersimport sysfrom math import floor INT_MAX = 2147483647 # Function to compute# average of two numbersdef compute_average(a, b): return floor((a + b) / 2) # Driver codeif __name__ == '__main__': # Assigning maximum integer value a = INT_MAX b = -INT_MAX - 1 # Average of two equal numbers # is the same number print("Actual average : ", INT_MAX) # Function to get the # average of 2 numbers print("Computed average : ", compute_average(a, b)) # This code is contributed by# Surendra_Gangwar // C# code to compute average of two numbersusing System; public class GFG{ // Function to compute average of two numbersstatic int compute_average(int a, int b){ return (a + b) / 2;} // Driver code static public void Main (){ // Assigning maximum integer value int a =int.MaxValue; int b = int.MaxValue; // Average of two equal numbers is the same number Console.WriteLine("Actual average : " + int.MaxValue); // Function to get the average of 2 numbers Console.WriteLine("Computed average : " + compute_average(a, b)); }//This code is contributed by akt_mit } <script> // Javascript code to compute average of two numbers const INT_MAX = 2147483647; // Function to compute average of two numbers function compute_average(a, b) { return Math.floor((a + b) / 2); } // Assigning maximum integer value let a = INT_MAX; let b = -INT_MAX-1; // Average of two equal numbers is the same number document.write("Actual average : " + INT_MAX + "</br>"); // Function to get the average of 2 numbers document.write("Computed average : " + compute_average(a, b) + "</br>"); </script> Output: Actual average : 2147483647 Computed average : -1 Improved Formula that does not cause overflow : Average = (a / 2) + (b / 2) + (((a % 2) + (b % 2)) / 2)Below is the implementation : C++ Java Python3 C# PHP Javascript // C++ code to compute average of two numbers#include <bits/stdc++.h>using namespace std; // Function to compute average of two numbersint compute_average(int a, int b){ return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);} // Driver codeint main(){ // Assigning maximum integer value int a = INT_MAX, b = INT_MAX; // Average of two equal numbers is the same number cout << "Actual average : " << INT_MAX << endl; // Function to get the average of 2 numbers cout << "Computed average : " << compute_average(a, b); return 0;} // Java code to compute// average of two numbersimport java.io.*; class GFG{ // Function to compute// average of two numbersstatic int compute_average(int a, int b){ return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);} // Driver codepublic static void main (String[] args){ // Assigning maximum// integer valueint a = Integer.MAX_VALUE;int b = Integer.MAX_VALUE; // Average of two equal// numbers is the same numberSystem.out.println("Actual average : " + Integer.MAX_VALUE); // Function to get the// average of 2 numbersSystem.out.print("Computed average : ");System.out.println(compute_average(a, b));}} // This code is contributed by ajit # Python code to compute# average of two numbersINT_MAX=2147483647 # Function to compute# average of two numbersdef compute_average(a,b): return (a // 2) + (b // 2) + ((a % 2 + b % 2) // 2) # Driver codeif __name__ =="__main__": # Assigning maximum integer value a = INT_MAX b = INT_MAX # Average of two equal # numbers is the same number print( "Actual average : ",INT_MAX) # Function to get the # average of 2 numbers print( "Computed average : ", compute_average(a, b)) # This code is contributed# Shubham Singh(SHUBHAMSINGH10) // C# code to compute// average of two numbers using System; class GFG{ // Function to compute// average of two numbersstatic int compute_average(int a, int b){ return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);} // Driver codepublic static void Main (){ // Assigning maximum// integer valueint a = int.MaxValue;int b = int.MaxValue; // Average of two equal// numbers is the same numberConsole.Write("Actual average : " + int.MaxValue+"\n"); // Function to get the// average of 2 numbersConsole.Write("Computed average : ");Console.Write(compute_average(a, b));}} <?php// PHP code to compute// average of two numbers// Function to compute// average of two numbersfunction compute_average($a,$b){ return ($a / 2) + ($b / 2) + (($a % 2 + $b % 2) / 2);} // Driver code // Assigning maximum// integer value$a = 2147483648;$b = 2147483648; // Average of two equal// numbers is the same number$x = 2147483648;print("Actual average : ".$x); // Function to get the// average of 2 numbersprint("\nComputed average : ");print(compute_average($a, $b)); // This code is contributed by princiraj1992?> <script> // javascript code to compute average of two numbersconst INT_MAX = 2147483647; // Function to compute average of two numbersfunction compute_average( a, b){ return parseInt(a / 2) + parseInt(b / 2) + ((a % 2 + b % 2) / 2);} // Driver code // Assigning maximum integer value let a = INT_MAX, b = INT_MAX; // Average of two equal numbers is the same number document.write( "Actual average : " + INT_MAX +"<br/>"); // Function to get the average of 2 numbers document.write( "Computed average : " + compute_average(a, b)); // This code is contributed by todaysgaurav </script> Output: Actual average : 2147483647 Computed average : 2147483647 This article is contributed by Rohit Thapliyal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. jit_t ukasp SHUBHAMSINGH10 SURENDRA_GANGWAR princiraj1992 todaysgaurav rameshtravel07 Nvidia Mathematical Nvidia Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Modulo Operator (%) in C/C++ with Examples Print all possible combinations of r elements in a given array of size n Operators in C / C++ The Knight's tour problem | Backtracking-1 Program for factorial of a number Find minimum number of coins that make a given value Program to find sum of elements in a given array Euclidean algorithms (Basic and Extended) Program to print prime numbers from 1 to N. Minimum number of jumps to reach end
[ { "code": null, "e": 25881, "s": 25853, "text": "\n28 Apr, 2021" }, { "code": null, "e": 26156, "s": 25881, "text": "Given two numbers, a and b. Compute the average of the two numbers.The well know formula (a + b) / 2 may fail at the following case : If, a = b = (2^31) – 1; i.e. INT_MAX. Now, (a+b) will cause overflow and hence formula (a + b) / 2 wont work Below is the implementation : " }, { "code": null, "e": 26160, "s": 26156, "text": "C++" }, { "code": null, "e": 26165, "s": 26160, "text": "Java" }, { "code": null, "e": 26173, "s": 26165, "text": "Python3" }, { "code": null, "e": 26176, "s": 26173, "text": "C#" }, { "code": null, "e": 26187, "s": 26176, "text": "Javascript" }, { "code": "// C++ code to compute average of two numbers#include <bits/stdc++.h>using namespace std; // Function to compute average of two numbersint compute_average(int a, int b){ return (a + b) / 2;} // Driver codeint main(){ // Assigning maximum integer value int a = INT_MAX, b = INT_MAX; // Average of two equal numbers is the same number cout << \"Actual average : \" << INT_MAX << endl; // Function to get the average of 2 numbers cout << \"Computed average : \" << compute_average(a, b); return 0;}", "e": 26706, "s": 26187, "text": null }, { "code": "// Java code to compute average of two numbers import java.io.*; class GFG { // Function to compute average of two numbersstatic int compute_average(int a, int b){ return (a + b) / 2;} // Driver code public static void main (String[] args) { // Assigning maximum integer value int a = Integer.MAX_VALUE; int b = Integer.MAX_VALUE; // Average of two equal numbers is the same number System.out.println(\"Actual average : \" + Integer.MAX_VALUE); // Function to get the average of 2 numbers System.out.println(\"Computed average : \" + compute_average(a, b)); }// This code is contributed by ajit. }", "e": 27357, "s": 26706, "text": null }, { "code": "# Python 3 code to compute# average of two numbersimport sysfrom math import floor INT_MAX = 2147483647 # Function to compute# average of two numbersdef compute_average(a, b): return floor((a + b) / 2) # Driver codeif __name__ == '__main__': # Assigning maximum integer value a = INT_MAX b = -INT_MAX - 1 # Average of two equal numbers # is the same number print(\"Actual average : \", INT_MAX) # Function to get the # average of 2 numbers print(\"Computed average : \", compute_average(a, b)) # This code is contributed by# Surendra_Gangwar", "e": 27942, "s": 27357, "text": null }, { "code": "// C# code to compute average of two numbersusing System; public class GFG{ // Function to compute average of two numbersstatic int compute_average(int a, int b){ return (a + b) / 2;} // Driver code static public void Main (){ // Assigning maximum integer value int a =int.MaxValue; int b = int.MaxValue; // Average of two equal numbers is the same number Console.WriteLine(\"Actual average : \" + int.MaxValue); // Function to get the average of 2 numbers Console.WriteLine(\"Computed average : \" + compute_average(a, b)); }//This code is contributed by akt_mit }", "e": 28556, "s": 27942, "text": null }, { "code": "<script> // Javascript code to compute average of two numbers const INT_MAX = 2147483647; // Function to compute average of two numbers function compute_average(a, b) { return Math.floor((a + b) / 2); } // Assigning maximum integer value let a = INT_MAX; let b = -INT_MAX-1; // Average of two equal numbers is the same number document.write(\"Actual average : \" + INT_MAX + \"</br>\"); // Function to get the average of 2 numbers document.write(\"Computed average : \" + compute_average(a, b) + \"</br>\"); </script>", "e": 29135, "s": 28556, "text": null }, { "code": null, "e": 29145, "s": 29135, "text": "Output: " }, { "code": null, "e": 29195, "s": 29145, "text": "Actual average : 2147483647\nComputed average : -1" }, { "code": null, "e": 29329, "s": 29195, "text": "Improved Formula that does not cause overflow : Average = (a / 2) + (b / 2) + (((a % 2) + (b % 2)) / 2)Below is the implementation : " }, { "code": null, "e": 29333, "s": 29329, "text": "C++" }, { "code": null, "e": 29338, "s": 29333, "text": "Java" }, { "code": null, "e": 29346, "s": 29338, "text": "Python3" }, { "code": null, "e": 29349, "s": 29346, "text": "C#" }, { "code": null, "e": 29353, "s": 29349, "text": "PHP" }, { "code": null, "e": 29364, "s": 29353, "text": "Javascript" }, { "code": "// C++ code to compute average of two numbers#include <bits/stdc++.h>using namespace std; // Function to compute average of two numbersint compute_average(int a, int b){ return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);} // Driver codeint main(){ // Assigning maximum integer value int a = INT_MAX, b = INT_MAX; // Average of two equal numbers is the same number cout << \"Actual average : \" << INT_MAX << endl; // Function to get the average of 2 numbers cout << \"Computed average : \" << compute_average(a, b); return 0;}", "e": 29913, "s": 29364, "text": null }, { "code": "// Java code to compute// average of two numbersimport java.io.*; class GFG{ // Function to compute// average of two numbersstatic int compute_average(int a, int b){ return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);} // Driver codepublic static void main (String[] args){ // Assigning maximum// integer valueint a = Integer.MAX_VALUE;int b = Integer.MAX_VALUE; // Average of two equal// numbers is the same numberSystem.out.println(\"Actual average : \" + Integer.MAX_VALUE); // Function to get the// average of 2 numbersSystem.out.print(\"Computed average : \");System.out.println(compute_average(a, b));}} // This code is contributed by ajit", "e": 30616, "s": 29913, "text": null }, { "code": "# Python code to compute# average of two numbersINT_MAX=2147483647 # Function to compute# average of two numbersdef compute_average(a,b): return (a // 2) + (b // 2) + ((a % 2 + b % 2) // 2) # Driver codeif __name__ ==\"__main__\": # Assigning maximum integer value a = INT_MAX b = INT_MAX # Average of two equal # numbers is the same number print( \"Actual average : \",INT_MAX) # Function to get the # average of 2 numbers print( \"Computed average : \", compute_average(a, b)) # This code is contributed# Shubham Singh(SHUBHAMSINGH10)", "e": 31196, "s": 30616, "text": null }, { "code": "// C# code to compute// average of two numbers using System; class GFG{ // Function to compute// average of two numbersstatic int compute_average(int a, int b){ return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);} // Driver codepublic static void Main (){ // Assigning maximum// integer valueint a = int.MaxValue;int b = int.MaxValue; // Average of two equal// numbers is the same numberConsole.Write(\"Actual average : \" + int.MaxValue+\"\\n\"); // Function to get the// average of 2 numbersConsole.Write(\"Computed average : \");Console.Write(compute_average(a, b));}}", "e": 31828, "s": 31196, "text": null }, { "code": "<?php// PHP code to compute// average of two numbers// Function to compute// average of two numbersfunction compute_average($a,$b){ return ($a / 2) + ($b / 2) + (($a % 2 + $b % 2) / 2);} // Driver code // Assigning maximum// integer value$a = 2147483648;$b = 2147483648; // Average of two equal// numbers is the same number$x = 2147483648;print(\"Actual average : \".$x); // Function to get the// average of 2 numbersprint(\"\\nComputed average : \");print(compute_average($a, $b)); // This code is contributed by princiraj1992?>", "e": 32363, "s": 31828, "text": null }, { "code": "<script> // javascript code to compute average of two numbersconst INT_MAX = 2147483647; // Function to compute average of two numbersfunction compute_average( a, b){ return parseInt(a / 2) + parseInt(b / 2) + ((a % 2 + b % 2) / 2);} // Driver code // Assigning maximum integer value let a = INT_MAX, b = INT_MAX; // Average of two equal numbers is the same number document.write( \"Actual average : \" + INT_MAX +\"<br/>\"); // Function to get the average of 2 numbers document.write( \"Computed average : \" + compute_average(a, b)); // This code is contributed by todaysgaurav </script>", "e": 32978, "s": 32363, "text": null }, { "code": null, "e": 32988, "s": 32978, "text": "Output: " }, { "code": null, "e": 33046, "s": 32988, "text": "Actual average : 2147483647\nComputed average : 2147483647" }, { "code": null, "e": 33474, "s": 33046, "text": "This article is contributed by Rohit Thapliyal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 33480, "s": 33474, "text": "jit_t" }, { "code": null, "e": 33486, "s": 33480, "text": "ukasp" }, { "code": null, "e": 33501, "s": 33486, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 33518, "s": 33501, "text": "SURENDRA_GANGWAR" }, { "code": null, "e": 33532, "s": 33518, "text": "princiraj1992" }, { "code": null, "e": 33545, "s": 33532, "text": "todaysgaurav" }, { "code": null, "e": 33560, "s": 33545, "text": "rameshtravel07" }, { "code": null, "e": 33567, "s": 33560, "text": "Nvidia" }, { "code": null, "e": 33580, "s": 33567, "text": "Mathematical" }, { "code": null, "e": 33587, "s": 33580, "text": "Nvidia" }, { "code": null, "e": 33600, "s": 33587, "text": "Mathematical" }, { "code": null, "e": 33698, "s": 33600, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33741, "s": 33698, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 33814, "s": 33741, "text": "Print all possible combinations of r elements in a given array of size n" }, { "code": null, "e": 33835, "s": 33814, "text": "Operators in C / C++" }, { "code": null, "e": 33878, "s": 33835, "text": "The Knight's tour problem | Backtracking-1" }, { "code": null, "e": 33912, "s": 33878, "text": "Program for factorial of a number" }, { "code": null, "e": 33965, "s": 33912, "text": "Find minimum number of coins that make a given value" }, { "code": null, "e": 34014, "s": 33965, "text": "Program to find sum of elements in a given array" }, { "code": null, "e": 34056, "s": 34014, "text": "Euclidean algorithms (Basic and Extended)" }, { "code": null, "e": 34100, "s": 34056, "text": "Program to print prime numbers from 1 to N." } ]
Python Program to Check Whether a Number is Positive or Negative or zero - GeeksforGeeks
29 Aug, 2020 Given a number. The task is to check whether the number is positive or negative or zero. Examples: Input: 5 Output: Positive Input: -5 Output: Negative Approach: We will use the if-elif statements in Python. We will check whether the number is greater than zero or smaller than zero or equal to zero. Below is the implementation. Python3 # Python program to check whether# the number is positive, negative# or equal to zero def check(n): # if the number is positive if n > 0: print("Positive") # if the number is negative elif n < 0: print("Negative") # if the number is equal to # zero else: print("Equal to zero") # Driver Codecheck(5)check(0)check(-5) Output: Positive Equal to zero Negative python-basics Python Python Programs 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 Python program to convert a list to string Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary
[ { "code": null, "e": 26663, "s": 26635, "text": "\n29 Aug, 2020" }, { "code": null, "e": 26752, "s": 26663, "text": "Given a number. The task is to check whether the number is positive or negative or zero." }, { "code": null, "e": 26762, "s": 26752, "text": "Examples:" }, { "code": null, "e": 26817, "s": 26762, "text": "Input: 5\nOutput: Positive\n\nInput: -5\nOutput: Negative\n" }, { "code": null, "e": 26827, "s": 26817, "text": "Approach:" }, { "code": null, "e": 26966, "s": 26827, "text": "We will use the if-elif statements in Python. We will check whether the number is greater than zero or smaller than zero or equal to zero." }, { "code": null, "e": 26995, "s": 26966, "text": "Below is the implementation." }, { "code": null, "e": 27003, "s": 26995, "text": "Python3" }, { "code": "# Python program to check whether# the number is positive, negative# or equal to zero def check(n): # if the number is positive if n > 0: print(\"Positive\") # if the number is negative elif n < 0: print(\"Negative\") # if the number is equal to # zero else: print(\"Equal to zero\") # Driver Codecheck(5)check(0)check(-5)", "e": 27398, "s": 27003, "text": null }, { "code": null, "e": 27406, "s": 27398, "text": "Output:" }, { "code": null, "e": 27439, "s": 27406, "text": "Positive\nEqual to zero\nNegative\n" }, { "code": null, "e": 27453, "s": 27439, "text": "python-basics" }, { "code": null, "e": 27460, "s": 27453, "text": "Python" }, { "code": null, "e": 27476, "s": 27460, "text": "Python Programs" }, { "code": null, "e": 27574, "s": 27476, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27592, "s": 27574, "text": "Python Dictionary" }, { "code": null, "e": 27627, "s": 27592, "text": "Read a file line by line in Python" }, { "code": null, "e": 27659, "s": 27627, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27681, "s": 27659, "text": "Enumerate() in Python" }, { "code": null, "e": 27723, "s": 27681, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 27766, "s": 27723, "text": "Python program to convert a list to string" }, { "code": null, "e": 27788, "s": 27766, "text": "Defaultdict in Python" }, { "code": null, "e": 27827, "s": 27788, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 27873, "s": 27827, "text": "Python | Split string into list of characters" } ]
Netcat - Basic Usage and Overview - GeeksforGeeks
13 Aug, 2020 Netcat is a Unix utility which reads and writes data across network connections using TCP or UDP protocol. Following tasks can be done easily with Netcat: Connect to a port of a target host. Listen to a certain port for any inbound connections. Send data across client and server once the connection is established. Transfer files across the network once the connection is established. Can execute programs and scripts of the client on the server and vice versa. Can Provide remote shell access of server to a client where shell commands can be executed. A simple client-server connection: Type this command on the server machine. nc -l -p 1234 Here, nc stands for Netcat, that we are calling the Netcat program. -l option tells the program to listen on a port specified by -p option. In this case, it is 1234. So the command can also be written as, Now type the following on the client machine or on the other terminal:- nc 127.0.0.1 1234 This will create a TCP connection with the IP address(that is, 127.0.0.1) on the specified port(that is, 1234). Some important options that can be used with Netcat: 1. Verbose, prints additional information about the connection. #command for terminal 1 nc -vlp 1234 #command for terminal 2 nc -v 127.0.0.1 1234 The above command on the client is showing it has successfully connected to the server. This command can also be used to scan a port of the server if it is open or not. 2. After data transfer wait w seconds before terminating the connection. #command for terminal 1 nc -w 20 -lp 1234 #command for terminal 2 nc -w 2 127.0.0.1 1234 3. To perform simple chat and data transfer #command for terminal 1 nc -lp 1234 #command for terminal 2 nc 127.0.0.1 1234 Use the above sequence of command to send the messages or data from one terminal and one ip to the other 4. To perform file transfer #command for terminal 1 nc -v -w 30 -l -p 1234 >manav.txt #command for terminal 2 nc -v -w 2 127.0.0.1 1234<manav.txt In this example, the server will terminate the connection 30 seconds after receiving the file. If the file is not in the current directory, then specify the entire path. 5. To execute shell command after successful establishment of connection #command for terminal 1 nc -lp 1234 -c /bin/sh #command for terminal 2 nc 127.0.0.1 1234 /bin/sh is a Unix command which provides a shell to execute shell commands. This will provide a remote shell to the client, from where the client can execute shell command on the server. Some important points on Netcat By default, Netcat uses TCP connection. To establish a UDP connection -u option is used.Without the -w option the connection doesn’t terminate until quitting the Netcat program.-n option specifies a numerical IP address, not a domain name. That is, -n option allows only an IP address with which to connect but cannot resolve a domain name to IP address.-k option is used in listen mode to accept multiple connections. By default, Netcat uses TCP connection. To establish a UDP connection -u option is used. Without the -w option the connection doesn’t terminate until quitting the Netcat program. -n option specifies a numerical IP address, not a domain name. That is, -n option allows only an IP address with which to connect but cannot resolve a domain name to IP address. -k option is used in listen mode to accept multiple connections. linux-command Linux-networking-commands Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. ZIP command in Linux with examples TCP Server-Client implementation in C SORT command in Linux/Unix with examples tar command in Linux with examples curl command in Linux with Examples Conditional Statements | Shell Script 'crontab' in Linux with Examples diff command in Linux with examples UDP Server-Client implementation in C Tail command in Linux with examples
[ { "code": null, "e": 26109, "s": 26081, "text": "\n13 Aug, 2020" }, { "code": null, "e": 26264, "s": 26109, "text": "Netcat is a Unix utility which reads and writes data across network connections using TCP or UDP protocol. Following tasks can be done easily with Netcat:" }, { "code": null, "e": 26300, "s": 26264, "text": "Connect to a port of a target host." }, { "code": null, "e": 26354, "s": 26300, "text": "Listen to a certain port for any inbound connections." }, { "code": null, "e": 26425, "s": 26354, "text": "Send data across client and server once the connection is established." }, { "code": null, "e": 26495, "s": 26425, "text": "Transfer files across the network once the connection is established." }, { "code": null, "e": 26572, "s": 26495, "text": "Can execute programs and scripts of the client on the server and vice versa." }, { "code": null, "e": 26664, "s": 26572, "text": "Can Provide remote shell access of server to a client where shell commands can be executed." }, { "code": null, "e": 26741, "s": 26664, "text": "A simple client-server connection: Type this command on the server machine. " }, { "code": null, "e": 26757, "s": 26741, "text": "nc -l -p 1234\n\n" }, { "code": null, "e": 26963, "s": 26757, "text": "Here, nc stands for Netcat, that we are calling the Netcat program. -l option tells the program to listen on a port specified by -p option. In this case, it is 1234. So the command can also be written as, " }, { "code": null, "e": 27035, "s": 26963, "text": "Now type the following on the client machine or on the other terminal:-" }, { "code": null, "e": 27054, "s": 27035, "text": "nc 127.0.0.1 1234\n" }, { "code": null, "e": 27167, "s": 27054, "text": "This will create a TCP connection with the IP address(that is, 127.0.0.1) on the specified port(that is, 1234). " }, { "code": null, "e": 27220, "s": 27167, "text": "Some important options that can be used with Netcat:" }, { "code": null, "e": 27284, "s": 27220, "text": "1. Verbose, prints additional information about the connection." }, { "code": null, "e": 27367, "s": 27284, "text": "#command for terminal 1\nnc -vlp 1234\n#command for terminal 2\nnc -v 127.0.0.1 1234\n" }, { "code": null, "e": 27537, "s": 27367, "text": "The above command on the client is showing it has successfully connected to the server. This command can also be used to scan a port of the server if it is open or not. " }, { "code": null, "e": 27611, "s": 27537, "text": "2. After data transfer wait w seconds before terminating the connection." }, { "code": null, "e": 27701, "s": 27611, "text": "#command for terminal 1\nnc -w 20 -lp 1234\n#command for terminal 2\nnc -w 2 127.0.0.1 1234\n" }, { "code": null, "e": 27745, "s": 27701, "text": "3. To perform simple chat and data transfer" }, { "code": null, "e": 27824, "s": 27745, "text": "#command for terminal 1\nnc -lp 1234\n#command for terminal 2\nnc 127.0.0.1 1234\n" }, { "code": null, "e": 27929, "s": 27824, "text": "Use the above sequence of command to send the messages or data from one terminal and one ip to the other" }, { "code": null, "e": 27958, "s": 27929, "text": "4. To perform file transfer" }, { "code": null, "e": 28078, "s": 27958, "text": "#command for terminal 1 \nnc -v -w 30 -l -p 1234 >manav.txt\n#command for terminal 2\nnc -v -w 2 127.0.0.1 1234<manav.txt\n" }, { "code": null, "e": 28249, "s": 28078, "text": "In this example, the server will terminate the connection 30 seconds after receiving the file. If the file is not in the current directory, then specify the entire path. " }, { "code": null, "e": 28322, "s": 28249, "text": "5. To execute shell command after successful establishment of connection" }, { "code": null, "e": 28412, "s": 28322, "text": "#command for terminal 1\nnc -lp 1234 -c /bin/sh\n#command for terminal 2\nnc 127.0.0.1 1234\n" }, { "code": null, "e": 28601, "s": 28412, "text": "/bin/sh is a Unix command which provides a shell to execute shell commands. This will provide a remote shell to the client, from where the client can execute shell command on the server. " }, { "code": null, "e": 28633, "s": 28601, "text": "Some important points on Netcat" }, { "code": null, "e": 29052, "s": 28633, "text": "By default, Netcat uses TCP connection. To establish a UDP connection -u option is used.Without the -w option the connection doesn’t terminate until quitting the Netcat program.-n option specifies a numerical IP address, not a domain name. That is, -n option allows only an IP address with which to connect but cannot resolve a domain name to IP address.-k option is used in listen mode to accept multiple connections." }, { "code": null, "e": 29141, "s": 29052, "text": "By default, Netcat uses TCP connection. To establish a UDP connection -u option is used." }, { "code": null, "e": 29231, "s": 29141, "text": "Without the -w option the connection doesn’t terminate until quitting the Netcat program." }, { "code": null, "e": 29409, "s": 29231, "text": "-n option specifies a numerical IP address, not a domain name. That is, -n option allows only an IP address with which to connect but cannot resolve a domain name to IP address." }, { "code": null, "e": 29474, "s": 29409, "text": "-k option is used in listen mode to accept multiple connections." }, { "code": null, "e": 29488, "s": 29474, "text": "linux-command" }, { "code": null, "e": 29514, "s": 29488, "text": "Linux-networking-commands" }, { "code": null, "e": 29525, "s": 29514, "text": "Linux-Unix" }, { "code": null, "e": 29623, "s": 29525, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29658, "s": 29623, "text": "ZIP command in Linux with examples" }, { "code": null, "e": 29696, "s": 29658, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 29737, "s": 29696, "text": "SORT command in Linux/Unix with examples" }, { "code": null, "e": 29772, "s": 29737, "text": "tar command in Linux with examples" }, { "code": null, "e": 29808, "s": 29772, "text": "curl command in Linux with Examples" }, { "code": null, "e": 29846, "s": 29808, "text": "Conditional Statements | Shell Script" }, { "code": null, "e": 29879, "s": 29846, "text": "'crontab' in Linux with Examples" }, { "code": null, "e": 29915, "s": 29879, "text": "diff command in Linux with examples" }, { "code": null, "e": 29953, "s": 29915, "text": "UDP Server-Client implementation in C" } ]
Count number of unique ways to paint a N x 3 grid - GeeksforGeeks
13 Jul, 2021 Given an integer N, the task is to paint a grid of size N x 3 using colors Red, Yellow, or Green while making such that no pair of adjacent cells has the same color. Print the number of distinct ways in which it is possible Examples: Input: N = 1Output: 12Explanation: Following 12 possible ways to paint the grid exists: Red, Yellow, RedYellow, Red, YellowGreen, Red, YellowRed, Yellow, GreenYellow, Red, GreenGreen, Red, GreenRed, Green, RedYellow, Green, RedGreen, Yellow, RedRed, Green, YellowYellow, Green, YellowGreen, Yellow, Green Red, Yellow, Red Yellow, Red, Yellow Green, Red, Yellow Red, Yellow, Green Yellow, Red, Green Green, Red, Green Red, Green, Red Yellow, Green, Red Green, Yellow, Red Red, Green, Yellow Yellow, Green, Yellow Green, Yellow, Green Input: N = 2Output: 102 Approach: Follow the steps below to solve the problem: Ways to color a row can be split into the following two categories:The leftmost and rightmost cells are of the same color.The leftmost and rightmost cells are of different colors. The leftmost and rightmost cells are of the same color. The leftmost and rightmost cells are of different colors. Considering the first case:Six possible ways exist to paint the row such that the leftmost and rightmost colors are of the same.For every color occupying both the leftmost and rightmost cell, there exists two different colors with which the middle row can be colored. Six possible ways exist to paint the row such that the leftmost and rightmost colors are of the same. For every color occupying both the leftmost and rightmost cell, there exists two different colors with which the middle row can be colored. Considering the second case:Six possible ways exist to paint the leftmost and rightmost colors are different.Three choices for the left cell, two choices for the middle, and fill the rightmost cell with the only remaining color. Therefore, the total number of possibilities is 3*2*1 = 6. Six possible ways exist to paint the leftmost and rightmost colors are different. Three choices for the left cell, two choices for the middle, and fill the rightmost cell with the only remaining color. Therefore, the total number of possibilities is 3*2*1 = 6. Now, for the subsequent cells, look at the following example:If the previous row is painted as Red Green Red, then there are the following five valid ways to color the current row:{Green Red Green}{Green Red Yellow}{Green Yellow Green}{Yellow Red Green}{Yellow Red Yellow}From the above observation, it is clear that three possibilities have ends with the same color, and two possibilities have ends with different colors.If the previous row is colored Red Green Yellow, the following four possibilities of coloring the current row exists:{Green Red Green}{Green Yellow Red}{Green Yellow Green}{Yellow Red Green}From the above observation, it is clear that possibilities have ends the same color, and two possibilities have ends with different colors. If the previous row is painted as Red Green Red, then there are the following five valid ways to color the current row:{Green Red Green}{Green Red Yellow}{Green Yellow Green}{Yellow Red Green}{Yellow Red Yellow} {Green Red Green} {Green Red Yellow} {Green Yellow Green} {Yellow Red Green} {Yellow Red Yellow} From the above observation, it is clear that three possibilities have ends with the same color, and two possibilities have ends with different colors. If the previous row is colored Red Green Yellow, the following four possibilities of coloring the current row exists:{Green Red Green}{Green Yellow Red}{Green Yellow Green}{Yellow Red Green} {Green Red Green} {Green Yellow Red} {Green Yellow Green} {Yellow Red Green} From the above observation, it is clear that possibilities have ends the same color, and two possibilities have ends with different colors. Therefore, based on the above observations, the following recurrence relation can be defined for the number of ways to paint the N rows: Count of ways to color current row having ends of same color SN+1 = 3 * SN + 2DN Count of ways to color current row having ends of different colors DN+1 = 2 * SN + 2DN Total number of ways to paint all N rows is equal to the sum of SN and DN. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to count the number// of ways to paint N * 3 grid// based on given conditionsvoid waysToPaint(int n){ // Count of ways to pain a // row with same colored ends int same = 6; // Count of ways to pain a row // with different colored ends int diff = 6; // Traverse up to (N - 1)th row for (int i = 0; i < n - 1; i++) { // Calculate the count of ways // to paint the current row // For same colored ends long sameTmp = 3 * same + 2 * diff; // For different colored ends long diffTmp = 2 * same + 2 * diff; same = sameTmp; diff = diffTmp; } // Print the total number of ways cout << (same + diff);} // Driver Codeint main(){ int N = 2; waysToPaint(N);} // This code is contributed by ukasp. // Java program for the above approachimport java.io.*;import java.lang.*;import java.util.*; class GFG { // Function to count the number // of ways to paint N * 3 grid // based on given conditions static void waysToPaint(int n) { // Count of ways to pain a // row with same colored ends long same = 6; // Count of ways to pain a row // with different colored ends long diff = 6; // Traverse up to (N - 1)th row for (int i = 0; i < n - 1; i++) { // Calculate the count of ways // to paint the current row // For same colored ends long sameTmp = 3 * same + 2 * diff; // For different colored ends long diffTmp = 2 * same + 2 * diff; same = sameTmp; diff = diffTmp; } // Print the total number of ways System.out.println(same + diff); } // Driver code public static void main(String[] args) { int N = 2; // Function call waysToPaint(N); }} # Python3 program for the above approach # Function to count the number# of ways to paint N * 3 grid# based on given conditions def waysToPaint(n): # Count of ways to pain a # row with same colored ends same = 6 # Count of ways to pain a row # with different colored ends diff = 6 # Traverse up to (N - 1)th row for _ in range(n - 1): # Calculate the count of ways # to paint the current row # For same colored ends sameTmp = 3 * same + 2 * diff # For different colored ends diffTmp = 2 * same + 2 * diff same = sameTmp diff = diffTmp # Print the total number of ways print(same + diff) # Driver Code N = 2waysToPaint(N) // C# program for the above approachusing System; class GFG { // Function to count the number // of ways to paint N * 3 grid // based on given conditions static void waysToPaint(int n) { // Count of ways to pain a // row with same colored ends long same = 6; // Count of ways to pain a row // with different colored ends long diff = 6; // Traverse up to (N - 1)th row for (int i = 0; i < n - 1; i++) { // Calculate the count of ways // to paint the current row // For same colored ends long sameTmp = 3 * same + 2 * diff; // For different colored ends long diffTmp = 2 * same + 2 * diff; same = sameTmp; diff = diffTmp; } // Print the total number of ways Console.WriteLine(same + diff); } // Driver code static public void Main() { int N = 2; waysToPaint(N); }} // This code is contributed by offbeat <script> // Javascript program for the above approach // Function to count the number// of ways to paint N * 3 grid// based on given conditionsfunction waysToPaint(n){ // Count of ways to pain a // row with same colored ends var same = 6; // Count of ways to pain a row // with different colored ends var diff = 6; // Traverse up to (N - 1)th row for(var i = 0; i < n - 1; i++) { // Calculate the count of ways // to paint the current row // For same colored ends var sameTmp = 3 * same + 2 * diff; // For different colored ends var diffTmp = 2 * same + 2 * diff; same = sameTmp; diff = diffTmp; } // Print the total number of ways document.write(same + diff);} // Driver codevar N = 2; // Function callwaysToPaint(N); // This code is contributed by Khushboogoyal499 </script> 12 Time Complexity: O(N)Auxiliary Space: O(1) ukasp Kingash offbeat khushboogoyal499 sankcan55 combionatrics Combinatorial Dynamic Programming Mathematical Dynamic Programming Mathematical Combinatorial Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Count of subsets with sum equal to X Python program to get all subsets of given size of a set Heap's Algorithm for generating permutations Distinct permutations of the string | Set 2 Make all combinations of size k 0-1 Knapsack Problem | DP-10 Program for Fibonacci numbers Largest Sum Contiguous Subarray Longest Common Subsequence | DP-4 Bellman–Ford Algorithm | DP-23
[ { "code": null, "e": 26349, "s": 26321, "text": "\n13 Jul, 2021" }, { "code": null, "e": 26573, "s": 26349, "text": "Given an integer N, the task is to paint a grid of size N x 3 using colors Red, Yellow, or Green while making such that no pair of adjacent cells has the same color. Print the number of distinct ways in which it is possible" }, { "code": null, "e": 26583, "s": 26573, "text": "Examples:" }, { "code": null, "e": 26671, "s": 26583, "text": "Input: N = 1Output: 12Explanation: Following 12 possible ways to paint the grid exists:" }, { "code": null, "e": 26888, "s": 26671, "text": "Red, Yellow, RedYellow, Red, YellowGreen, Red, YellowRed, Yellow, GreenYellow, Red, GreenGreen, Red, GreenRed, Green, RedYellow, Green, RedGreen, Yellow, RedRed, Green, YellowYellow, Green, YellowGreen, Yellow, Green" }, { "code": null, "e": 26905, "s": 26888, "text": "Red, Yellow, Red" }, { "code": null, "e": 26925, "s": 26905, "text": "Yellow, Red, Yellow" }, { "code": null, "e": 26944, "s": 26925, "text": "Green, Red, Yellow" }, { "code": null, "e": 26963, "s": 26944, "text": "Red, Yellow, Green" }, { "code": null, "e": 26982, "s": 26963, "text": "Yellow, Red, Green" }, { "code": null, "e": 27000, "s": 26982, "text": "Green, Red, Green" }, { "code": null, "e": 27016, "s": 27000, "text": "Red, Green, Red" }, { "code": null, "e": 27035, "s": 27016, "text": "Yellow, Green, Red" }, { "code": null, "e": 27054, "s": 27035, "text": "Green, Yellow, Red" }, { "code": null, "e": 27073, "s": 27054, "text": "Red, Green, Yellow" }, { "code": null, "e": 27095, "s": 27073, "text": "Yellow, Green, Yellow" }, { "code": null, "e": 27116, "s": 27095, "text": "Green, Yellow, Green" }, { "code": null, "e": 27140, "s": 27116, "text": "Input: N = 2Output: 102" }, { "code": null, "e": 27195, "s": 27140, "text": "Approach: Follow the steps below to solve the problem:" }, { "code": null, "e": 27375, "s": 27195, "text": "Ways to color a row can be split into the following two categories:The leftmost and rightmost cells are of the same color.The leftmost and rightmost cells are of different colors." }, { "code": null, "e": 27431, "s": 27375, "text": "The leftmost and rightmost cells are of the same color." }, { "code": null, "e": 27489, "s": 27431, "text": "The leftmost and rightmost cells are of different colors." }, { "code": null, "e": 27757, "s": 27489, "text": "Considering the first case:Six possible ways exist to paint the row such that the leftmost and rightmost colors are of the same.For every color occupying both the leftmost and rightmost cell, there exists two different colors with which the middle row can be colored." }, { "code": null, "e": 27859, "s": 27757, "text": "Six possible ways exist to paint the row such that the leftmost and rightmost colors are of the same." }, { "code": null, "e": 27999, "s": 27859, "text": "For every color occupying both the leftmost and rightmost cell, there exists two different colors with which the middle row can be colored." }, { "code": null, "e": 28287, "s": 27999, "text": "Considering the second case:Six possible ways exist to paint the leftmost and rightmost colors are different.Three choices for the left cell, two choices for the middle, and fill the rightmost cell with the only remaining color. Therefore, the total number of possibilities is 3*2*1 = 6." }, { "code": null, "e": 28369, "s": 28287, "text": "Six possible ways exist to paint the leftmost and rightmost colors are different." }, { "code": null, "e": 28548, "s": 28369, "text": "Three choices for the left cell, two choices for the middle, and fill the rightmost cell with the only remaining color. Therefore, the total number of possibilities is 3*2*1 = 6." }, { "code": null, "e": 29301, "s": 28548, "text": "Now, for the subsequent cells, look at the following example:If the previous row is painted as Red Green Red, then there are the following five valid ways to color the current row:{Green Red Green}{Green Red Yellow}{Green Yellow Green}{Yellow Red Green}{Yellow Red Yellow}From the above observation, it is clear that three possibilities have ends with the same color, and two possibilities have ends with different colors.If the previous row is colored Red Green Yellow, the following four possibilities of coloring the current row exists:{Green Red Green}{Green Yellow Red}{Green Yellow Green}{Yellow Red Green}From the above observation, it is clear that possibilities have ends the same color, and two possibilities have ends with different colors." }, { "code": null, "e": 29514, "s": 29301, "text": "If the previous row is painted as Red Green Red, then there are the following five valid ways to color the current row:{Green Red Green}{Green Red Yellow}{Green Yellow Green}{Yellow Red Green}{Yellow Red Yellow}" }, { "code": null, "e": 29532, "s": 29514, "text": "{Green Red Green}" }, { "code": null, "e": 29552, "s": 29532, "text": "{Green Red Yellow}" }, { "code": null, "e": 29573, "s": 29552, "text": "{Green Yellow Green}" }, { "code": null, "e": 29592, "s": 29573, "text": "{Yellow Red Green}" }, { "code": null, "e": 29612, "s": 29592, "text": "{Yellow Red Yellow}" }, { "code": null, "e": 29763, "s": 29612, "text": "From the above observation, it is clear that three possibilities have ends with the same color, and two possibilities have ends with different colors." }, { "code": null, "e": 29954, "s": 29763, "text": "If the previous row is colored Red Green Yellow, the following four possibilities of coloring the current row exists:{Green Red Green}{Green Yellow Red}{Green Yellow Green}{Yellow Red Green}" }, { "code": null, "e": 29972, "s": 29954, "text": "{Green Red Green}" }, { "code": null, "e": 29991, "s": 29972, "text": "{Green Yellow Red}" }, { "code": null, "e": 30012, "s": 29991, "text": "{Green Yellow Green}" }, { "code": null, "e": 30031, "s": 30012, "text": "{Yellow Red Green}" }, { "code": null, "e": 30171, "s": 30031, "text": "From the above observation, it is clear that possibilities have ends the same color, and two possibilities have ends with different colors." }, { "code": null, "e": 30308, "s": 30171, "text": "Therefore, based on the above observations, the following recurrence relation can be defined for the number of ways to paint the N rows:" }, { "code": null, "e": 30389, "s": 30308, "text": "Count of ways to color current row having ends of same color SN+1 = 3 * SN + 2DN" }, { "code": null, "e": 30476, "s": 30389, "text": "Count of ways to color current row having ends of different colors DN+1 = 2 * SN + 2DN" }, { "code": null, "e": 30551, "s": 30476, "text": "Total number of ways to paint all N rows is equal to the sum of SN and DN." }, { "code": null, "e": 30602, "s": 30551, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 30606, "s": 30602, "text": "C++" }, { "code": null, "e": 30611, "s": 30606, "text": "Java" }, { "code": null, "e": 30619, "s": 30611, "text": "Python3" }, { "code": null, "e": 30622, "s": 30619, "text": "C#" }, { "code": null, "e": 30633, "s": 30622, "text": "Javascript" }, { "code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to count the number// of ways to paint N * 3 grid// based on given conditionsvoid waysToPaint(int n){ // Count of ways to pain a // row with same colored ends int same = 6; // Count of ways to pain a row // with different colored ends int diff = 6; // Traverse up to (N - 1)th row for (int i = 0; i < n - 1; i++) { // Calculate the count of ways // to paint the current row // For same colored ends long sameTmp = 3 * same + 2 * diff; // For different colored ends long diffTmp = 2 * same + 2 * diff; same = sameTmp; diff = diffTmp; } // Print the total number of ways cout << (same + diff);} // Driver Codeint main(){ int N = 2; waysToPaint(N);} // This code is contributed by ukasp.", "e": 31516, "s": 30633, "text": null }, { "code": "// Java program for the above approachimport java.io.*;import java.lang.*;import java.util.*; class GFG { // Function to count the number // of ways to paint N * 3 grid // based on given conditions static void waysToPaint(int n) { // Count of ways to pain a // row with same colored ends long same = 6; // Count of ways to pain a row // with different colored ends long diff = 6; // Traverse up to (N - 1)th row for (int i = 0; i < n - 1; i++) { // Calculate the count of ways // to paint the current row // For same colored ends long sameTmp = 3 * same + 2 * diff; // For different colored ends long diffTmp = 2 * same + 2 * diff; same = sameTmp; diff = diffTmp; } // Print the total number of ways System.out.println(same + diff); } // Driver code public static void main(String[] args) { int N = 2; // Function call waysToPaint(N); }}", "e": 32583, "s": 31516, "text": null }, { "code": "# Python3 program for the above approach # Function to count the number# of ways to paint N * 3 grid# based on given conditions def waysToPaint(n): # Count of ways to pain a # row with same colored ends same = 6 # Count of ways to pain a row # with different colored ends diff = 6 # Traverse up to (N - 1)th row for _ in range(n - 1): # Calculate the count of ways # to paint the current row # For same colored ends sameTmp = 3 * same + 2 * diff # For different colored ends diffTmp = 2 * same + 2 * diff same = sameTmp diff = diffTmp # Print the total number of ways print(same + diff) # Driver Code N = 2waysToPaint(N)", "e": 33301, "s": 32583, "text": null }, { "code": "// C# program for the above approachusing System; class GFG { // Function to count the number // of ways to paint N * 3 grid // based on given conditions static void waysToPaint(int n) { // Count of ways to pain a // row with same colored ends long same = 6; // Count of ways to pain a row // with different colored ends long diff = 6; // Traverse up to (N - 1)th row for (int i = 0; i < n - 1; i++) { // Calculate the count of ways // to paint the current row // For same colored ends long sameTmp = 3 * same + 2 * diff; // For different colored ends long diffTmp = 2 * same + 2 * diff; same = sameTmp; diff = diffTmp; } // Print the total number of ways Console.WriteLine(same + diff); } // Driver code static public void Main() { int N = 2; waysToPaint(N); }} // This code is contributed by offbeat", "e": 34323, "s": 33301, "text": null }, { "code": "<script> // Javascript program for the above approach // Function to count the number// of ways to paint N * 3 grid// based on given conditionsfunction waysToPaint(n){ // Count of ways to pain a // row with same colored ends var same = 6; // Count of ways to pain a row // with different colored ends var diff = 6; // Traverse up to (N - 1)th row for(var i = 0; i < n - 1; i++) { // Calculate the count of ways // to paint the current row // For same colored ends var sameTmp = 3 * same + 2 * diff; // For different colored ends var diffTmp = 2 * same + 2 * diff; same = sameTmp; diff = diffTmp; } // Print the total number of ways document.write(same + diff);} // Driver codevar N = 2; // Function callwaysToPaint(N); // This code is contributed by Khushboogoyal499 </script>", "e": 35231, "s": 34323, "text": null }, { "code": null, "e": 35234, "s": 35231, "text": "12" }, { "code": null, "e": 35279, "s": 35236, "text": "Time Complexity: O(N)Auxiliary Space: O(1)" }, { "code": null, "e": 35285, "s": 35279, "text": "ukasp" }, { "code": null, "e": 35293, "s": 35285, "text": "Kingash" }, { "code": null, "e": 35301, "s": 35293, "text": "offbeat" }, { "code": null, "e": 35318, "s": 35301, "text": "khushboogoyal499" }, { "code": null, "e": 35328, "s": 35318, "text": "sankcan55" }, { "code": null, "e": 35342, "s": 35328, "text": "combionatrics" }, { "code": null, "e": 35356, "s": 35342, "text": "Combinatorial" }, { "code": null, "e": 35376, "s": 35356, "text": "Dynamic Programming" }, { "code": null, "e": 35389, "s": 35376, "text": "Mathematical" }, { "code": null, "e": 35409, "s": 35389, "text": "Dynamic Programming" }, { "code": null, "e": 35422, "s": 35409, "text": "Mathematical" }, { "code": null, "e": 35436, "s": 35422, "text": "Combinatorial" }, { "code": null, "e": 35534, "s": 35436, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35571, "s": 35534, "text": "Count of subsets with sum equal to X" }, { "code": null, "e": 35628, "s": 35571, "text": "Python program to get all subsets of given size of a set" }, { "code": null, "e": 35673, "s": 35628, "text": "Heap's Algorithm for generating permutations" }, { "code": null, "e": 35717, "s": 35673, "text": "Distinct permutations of the string | Set 2" }, { "code": null, "e": 35749, "s": 35717, "text": "Make all combinations of size k" }, { "code": null, "e": 35778, "s": 35749, "text": "0-1 Knapsack Problem | DP-10" }, { "code": null, "e": 35808, "s": 35778, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 35840, "s": 35808, "text": "Largest Sum Contiguous Subarray" }, { "code": null, "e": 35874, "s": 35840, "text": "Longest Common Subsequence | DP-4" } ]
Weibull Hazard Plot - GeeksforGeeks
16 Mar, 2021 Before getting into the Weibull Hazard plot, let us first understand what a hazard function is. Hazard function (h(t)): It tells us about the measure of risk of failure. It gives us information on the probability of failure of the object in a study in (t+1) time, assuming it has survived till time t. So the higher the hazard value, the higher is the risk of failure of the object in the study. A Hazard function for any object is represented as: Cumulative Hazard Plot: It is a graphical representation that provides information on the reliability of the fitted model on the given dataset. (i.e. by looking at this plot, we can easily find the appropriate time of failure for a model. The cumulative hazard function for Weibull distribution is given by: where, H(t) -> failure rate t -> failure at time t γ -> shape parameter α -> scale parameter Weibull Hazard function The weibull distribution also has a hazard function h(t), that essentially tells us prior information about an event that is yet to take place. Let’s take an example for better understanding. Let us take an example for better understanding. Let’s say we have a torch that we have been using for time t. The probability that it will fail at some time between t and t + dt hours of operation is given by the weibull hazard function. Based on the Weibull hazard plot, the hazard function for the torch can be described as: Just as in Weibull PPCC plot, hazard function h(t) also varies with the change in the shape parameter (γ) of the distribution. (See Fig 1) Fig 1: H(t) vs t plot This plot works really well for 2-parameter weibull distributions that haven been discussed in the ‘Weibull Plot’ article. Structure The weibull hazard plot has the following parameters on the axes: (See Fig 2) y-axis: Logarithm of hazard function, ln(H(t)).x-axis: Logarithm of time, ln(t/α). γ serves as the slope of this linear graph. Fig 2: Structure of Weibull Hazard plot Manually Plotting a Weibull Hazard Plot We know, that the Weibull hazard function is By calculating the logarithmic values and plotting ln(H(t)) vs ln(t) plot, we get a linear-like plot. Hence we can determine a good estimate for the value of the shape parameter γ as it becomes the slope of that plot. Code Implementation Here is the code implementation showing a weibull plot and a corresponding weibull hazard plot. import weibull as wb# Creating a custom random data for failure points.fails = [5002.7, 6203.4, 14367.2, 11144.6, 7332.0, 3044.4, 12330.2, 1234.5, 2553.9, 3632.1] # analysis contains the data to be fit into the weibull plot.Weibull_Analysis = wb.Analysis(fails, unit='minutes') # fit() method used for fitting # the data into weibull plot.Weibull_Analysis.fit() # printing the values of beta and eta (instances of Weibull_Analysis)print(f'beta: {Weibull_Analysis.beta: .03f}')print(f'eta: {Weibull_Analysis.eta: .03f}') # probplot() method used # for plotting the weibull distributionWeibull_Analysis.probplot() # hazard() method used for plotting# Weibull Hazard Plotprint(Weibull_Analysis.hazard()) Output Output 1 : Weibull Plot Output 2 : Weibull Hazard Plot ML-Statistics Machine Learning Python Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Recurrent Neural Network Support Vector Machine Algorithm Intuition of Adam Optimizer CNN | Introduction to Pooling Layer Convolutional Neural Network (CNN) in Machine Learning 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": 25589, "s": 25561, "text": "\n16 Mar, 2021" }, { "code": null, "e": 25686, "s": 25589, "text": "Before getting into the Weibull Hazard plot, let us first understand what a hazard function is. " }, { "code": null, "e": 26041, "s": 25686, "text": "Hazard function (h(t)): It tells us about the measure of risk of failure. It gives us information on the probability of failure of the object in a study in (t+1) time, assuming it has survived till time t. So the higher the hazard value, the higher is the risk of failure of the object in the study. A Hazard function for any object is represented as: " }, { "code": null, "e": 26349, "s": 26041, "text": "Cumulative Hazard Plot: It is a graphical representation that provides information on the reliability of the fitted model on the given dataset. (i.e. by looking at this plot, we can easily find the appropriate time of failure for a model. The cumulative hazard function for Weibull distribution is given by:" }, { "code": null, "e": 26443, "s": 26349, "text": "where, \nH(t) -> failure rate\nt -> failure at time t\nγ -> shape parameter\nα -> scale parameter" }, { "code": null, "e": 26467, "s": 26443, "text": "Weibull Hazard function" }, { "code": null, "e": 26709, "s": 26467, "text": "The weibull distribution also has a hazard function h(t), that essentially tells us prior information about an event that is yet to take place. Let’s take an example for better understanding. Let us take an example for better understanding. " }, { "code": null, "e": 26989, "s": 26709, "text": "Let’s say we have a torch that we have been using for time t. The probability that it will fail at some time between t and t + dt hours of operation is given by the weibull hazard function. Based on the Weibull hazard plot, the hazard function for the torch can be described as: " }, { "code": null, "e": 27128, "s": 26989, "text": "Just as in Weibull PPCC plot, hazard function h(t) also varies with the change in the shape parameter (γ) of the distribution. (See Fig 1)" }, { "code": null, "e": 27150, "s": 27128, "text": "Fig 1: H(t) vs t plot" }, { "code": null, "e": 27273, "s": 27150, "text": "This plot works really well for 2-parameter weibull distributions that haven been discussed in the ‘Weibull Plot’ article." }, { "code": null, "e": 27283, "s": 27273, "text": "Structure" }, { "code": null, "e": 27361, "s": 27283, "text": "The weibull hazard plot has the following parameters on the axes: (See Fig 2)" }, { "code": null, "e": 27444, "s": 27361, "text": "y-axis: Logarithm of hazard function, ln(H(t)).x-axis: Logarithm of time, ln(t/α)." }, { "code": null, "e": 27489, "s": 27444, "text": "γ serves as the slope of this linear graph. " }, { "code": null, "e": 27529, "s": 27489, "text": "Fig 2: Structure of Weibull Hazard plot" }, { "code": null, "e": 27569, "s": 27529, "text": "Manually Plotting a Weibull Hazard Plot" }, { "code": null, "e": 27614, "s": 27569, "text": "We know, that the Weibull hazard function is" }, { "code": null, "e": 27832, "s": 27614, "text": "By calculating the logarithmic values and plotting ln(H(t)) vs ln(t) plot, we get a linear-like plot. Hence we can determine a good estimate for the value of the shape parameter γ as it becomes the slope of that plot." }, { "code": null, "e": 27852, "s": 27832, "text": "Code Implementation" }, { "code": null, "e": 27949, "s": 27852, "text": "Here is the code implementation showing a weibull plot and a corresponding weibull hazard plot. " }, { "code": "import weibull as wb# Creating a custom random data for failure points.fails = [5002.7, 6203.4, 14367.2, 11144.6, 7332.0, 3044.4, 12330.2, 1234.5, 2553.9, 3632.1] # analysis contains the data to be fit into the weibull plot.Weibull_Analysis = wb.Analysis(fails, unit='minutes') # fit() method used for fitting # the data into weibull plot.Weibull_Analysis.fit() # printing the values of beta and eta (instances of Weibull_Analysis)print(f'beta: {Weibull_Analysis.beta: .03f}')print(f'eta: {Weibull_Analysis.eta: .03f}') # probplot() method used # for plotting the weibull distributionWeibull_Analysis.probplot() # hazard() method used for plotting# Weibull Hazard Plotprint(Weibull_Analysis.hazard())", "e": 28663, "s": 27949, "text": null }, { "code": null, "e": 28670, "s": 28663, "text": "Output" }, { "code": null, "e": 28694, "s": 28670, "text": "Output 1 : Weibull Plot" }, { "code": null, "e": 28725, "s": 28694, "text": "Output 2 : Weibull Hazard Plot" }, { "code": null, "e": 28739, "s": 28725, "text": "ML-Statistics" }, { "code": null, "e": 28756, "s": 28739, "text": "Machine Learning" }, { "code": null, "e": 28763, "s": 28756, "text": "Python" }, { "code": null, "e": 28780, "s": 28763, "text": "Machine Learning" }, { "code": null, "e": 28878, "s": 28780, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28919, "s": 28878, "text": "Introduction to Recurrent Neural Network" }, { "code": null, "e": 28952, "s": 28919, "text": "Support Vector Machine Algorithm" }, { "code": null, "e": 28980, "s": 28952, "text": "Intuition of Adam Optimizer" }, { "code": null, "e": 29016, "s": 28980, "text": "CNN | Introduction to Pooling Layer" }, { "code": null, "e": 29071, "s": 29016, "text": "Convolutional Neural Network (CNN) in Machine Learning" }, { "code": null, "e": 29099, "s": 29071, "text": "Read JSON file using Python" }, { "code": null, "e": 29149, "s": 29099, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 29171, "s": 29149, "text": "Python map() function" } ]
Printing Longest Common Subsequence - GeeksforGeeks
12 Apr, 2022 Given two sequences, print the longest subsequence present in both of them. Examples: LCS for input Sequences “ABCDGH” and “AEDFHR” is “ADH” of length 3. LCS for input Sequences “AGGTAB” and “GXTXAYB” is “GTAB” of length 4.We have discussed Longest Common Subsequence (LCS) problem in a previous post. The function discussed there was mainly to find the length of LCS. To find length of LCS, a 2D table L[][] was constructed. In this post, the function to construct and print LCS is discussed.Following is detailed algorithm to print the LCS. It uses the same 2D table L[][].1) Construct L[m+1][n+1] using the steps discussed in previous post.2) The value L[m][n] contains length of LCS. Create a character array lcs[] of length equal to the length of lcs plus 1 (one extra to store \0).3) Traverse the 2D array starting from L[m][n]. Do following for every cell L[i][j] .....a) If characters (in X and Y) corresponding to L[i][j] are same (Or X[i-1] == Y[j-1]), then include this character as part of LCS. .....b) Else compare values of L[i-1][j] and L[i][j-1] and go in direction of greater value.The following table (taken from Wiki) shows steps (highlighted) followed by the above algorithm. Following is the implementation of above approach. C++14 Java Python3 C# PHP Javascript /* Dynamic Programming implementation of LCS problem */#include <cstdlib>#include <cstring>#include <iostream>using namespace std; /* Returns length of LCS for X[0..m-1], Y[0..n-1] */void lcs(char* X, char* Y, int m, int n){ int L[m + 1][n + 1]; /* Following steps build L[m+1][n+1] in bottom up fashion. Note that L[i][j] contains length of LCS of X[0..i-1] and Y[0..j-1] */ for (int i = 0; i <= m; i++) { for (int j = 0; j <= n; j++) { if (i == 0 || j == 0) L[i][j] = 0; else if (X[i - 1] == Y[j - 1]) L[i][j] = L[i - 1][j - 1] + 1; else L[i][j] = max(L[i - 1][j], L[i][j - 1]); } } // Following code is used to print LCS int index = L[m][n]; // Create a character array to store the lcs string char lcs[index + 1]; lcs[index] = '\0'; // Set the terminating character // Start from the right-most-bottom-most corner and // one by one store characters in lcs[] int i = m, j = n; while (i > 0 && j > 0) { // If current character in X[] and Y are same, then // current character is part of LCS if (X[i - 1] == Y[j - 1]) { lcs[index - 1] = X[i - 1]; // Put current character in result i--; j--; index--; // reduce values of i, j and index } // If not same, then find the larger of two and // go in the direction of larger value else if (L[i - 1][j] > L[i][j - 1]) i--; else j--; } // Print the lcs cout << "LCS of " << X << " and " << Y << " is " << lcs;} /* Driver program to test above function */int main(){ char X[] = "AGGTAB"; char Y[] = "GXTXAYB"; int m = strlen(X); int n = strlen(Y); lcs(X, Y, m, n); return 0;} // Dynamic Programming implementation of LCS problem in Javaimport java.io.*; class LongestCommonSubsequence { // Returns length of LCS for X[0..m-1], Y[0..n-1] static void lcs(String X, String Y, int m, int n) { int[][] L = new int[m + 1][n + 1]; // Following steps build L[m+1][n+1] in bottom up // fashion. Note that L[i][j] contains length of LCS // of X[0..i-1] and Y[0..j-1] for (int i = 0; i <= m; i++) { for (int j = 0; j <= n; j++) { if (i == 0 || j == 0) L[i][j] = 0; else if (X.charAt(i - 1) == Y.charAt(j - 1)) L[i][j] = L[i - 1][j - 1] + 1; else L[i][j] = Math.max(L[i - 1][j], L[i][j - 1]); } } // Following code is used to print LCS int index = L[m][n]; int temp = index; // Create a character array to store the lcs string char[] lcs = new char[index + 1]; lcs[index] = '\u0000'; // Set the terminating character // Start from the right-most-bottom-most corner and // one by one store characters in lcs[] int i = m; int j = n; while (i > 0 && j > 0) { // If current character in X[] and Y are same, // then current character is part of LCS if (X.charAt(i - 1) == Y.charAt(j - 1)) { // Put current character in result lcs[index - 1] = X.charAt(i - 1); // reduce values of i, j and index i--; j--; index--; } // If not same, then find the larger of two and // go in the direction of larger value else if (L[i - 1][j] > L[i][j - 1]) i--; else j--; } // Print the lcs System.out.print("LCS of " + X + " and " + Y + " is "); for (int k = 0; k <= temp; k++) System.out.print(lcs[k]); } // driver program public static void main(String[] args) { String X = "AGGTAB"; String Y = "GXTXAYB"; int m = X.length(); int n = Y.length(); lcs(X, Y, m, n); }} // Contributed by Pramod Kumar # Dynamic programming implementation of LCS problem # Returns length of LCS for X[0..m-1], Y[0..n-1] def lcs(X, Y, m, n): L = [[0 for i in range(n+1)] for j in range(m+1)] # Following steps build L[m+1][n+1] in bottom up fashion. Note # that L[i][j] contains length of LCS of X[0..i-1] and Y[0..j-1] for i in range(m+1): for j in range(n+1): if i == 0 or j == 0: L[i][j] = 0 elif X[i-1] == Y[j-1]: L[i][j] = L[i-1][j-1] + 1 else: L[i][j] = max(L[i-1][j], L[i][j-1]) # Create a string variable to store the lcs string lcs = "" # Start from the right-most-bottom-most corner and # one by one store characters in lcs[] i = m j = n while i > 0 and j > 0: # If current character in X[] and Y are same, then # current character is part of LCS if X[i-1] == Y[j-1]: lcs += X[i-1] i -= 1 j -= 1 # If not same, then find the larger of two and # go in the direction of larger value elif L[i-1][j] > L[i][j-1]: i -= 1 else: j -= 1 # We traversed the table in reverse order # LCS is the reverse of what we got lcs = lcs[::-1] print("LCS of " + X + " and " + Y + " is " + lcs) # Driver programX = "AGGTAB"Y = "GXTXAYB"m = len(X)n = len(Y)lcs(X, Y, m, n) # This code is contributed by AMAN ASATI // Dynamic Programming implementation// of LCS problem in C#using System; class GFG { // Returns length of LCS for X[0..m-1], Y[0..n-1] static void lcs(String X, String Y, int m, int n) { int[, ] L = new int[m + 1, n + 1]; // Following steps build L[m+1][n+1] in // bottom up fashion. Note that L[i][j] // contains length of LCS of X[0..i-1] // and Y[0..j-1] for (int i = 0; i <= m; i++) { for (int j = 0; j <= n; j++) { if (i == 0 || j == 0) L[i, j] = 0; else if (X[i - 1] == Y[j - 1]) L[i, j] = L[i - 1, j - 1] + 1; else L[i, j] = Math.Max(L[i - 1, j], L[i, j - 1]); } } // Following code is used to print LCS int index = L[m, n]; int temp = index; // Create a character array // to store the lcs string char[] lcs = new char[index + 1]; // Set the terminating character lcs[index] = '\0'; // Start from the right-most-bottom-most corner // and one by one store characters in lcs[] int k = m, l = n; while (k > 0 && l > 0) { // If current character in X[] and Y // are same, then current character // is part of LCS if (X[k - 1] == Y[l - 1]) { // Put current character in result lcs[index - 1] = X[k - 1]; // reduce values of i, j and index k--; l--; index--; } // If not same, then find the larger of two and // go in the direction of larger value else if (L[k - 1, l] > L[k, l - 1]) k--; else l--; } // Print the lcs Console.Write("LCS of " + X + " and " + Y + " is "); for (int q = 0; q <= temp; q++) Console.Write(lcs[q]); } // Driver program public static void Main() { String X = "AGGTAB"; String Y = "GXTXAYB"; int m = X.Length; int n = Y.Length; lcs(X, Y, m, n); }} // This code is contributed by Sam007 <?php// Dynamic Programming implementation of LCS problem // Returns length of LCS for X[0..m-1], Y[0..n-1]function lcs( $X, $Y, $m, $n ){ $L = array_fill(0, $m + 1, array_fill(0, $n + 1, NULL)); /* Following steps build L[m+1][n+1] in bottom up fashion. Note that L[i][j] contains length of LCS of X[0..i-1] and Y[0..j-1] */ for ($i = 0; $i <= $m; $i++) { for ($j = 0; $j <= $n; $j++) { if ($i == 0 || $j == 0) $L[$i][$j] = 0; else if ($X[$i - 1] == $Y[$j - 1]) $L[$i][$j] = $L[$i - 1][$j - 1] + 1; else $L[$i][$j] = max($L[$i - 1][$j], $L[$i][$j - 1]); } } // Following code is used to print LCS $index = $L[$m][$n]; $temp = $index; // Create a character array to store the lcs string $lcs = array_fill(0, $index + 1, NULL); $lcs[$index] = ''; // Set the terminating character // Start from the right-most-bottom-most corner // and one by one store characters in lcs[] $i = $m; $j = $n; while ($i > 0 && $j > 0) { // If current character in X[] and Y are same, // then current character is part of LCS if ($X[$i - 1] == $Y[$j - 1]) { // Put current character in result $lcs[$index - 1] = $X[$i - 1]; $i--; $j--; $index--; // reduce values of i, j and index } // If not same, then find the larger of two // and go in the direction of larger value else if ($L[$i - 1][$j] > $L[$i][$j - 1]) $i--; else $j--; } // Print the lcs echo "LCS of " . $X . " and " . $Y . " is "; for($k = 0; $k < $temp; $k++) echo $lcs[$k];} // Driver Code$X = "AGGTAB";$Y = "GXTXAYB";$m = strlen($X);$n = strlen($Y);lcs($X, $Y, $m, $n); // This code is contributed by ita_c?> <script>function ReverseString(str) { return str.split('').reverse().join('')} function max(a, b){ if (a > b) return a; else return b;}function printLCS(str1, str2) { var len1 = str1.length; var len2 = str2.length; var lcs = new Array(len1 + 1); for (var i = 0; i <= len1; i++) { lcs[i] = new Array(len2 + 1) } for (var i = 0; i <= len1; i++) { for (var j = 0; j <= len2; j++) { if (i == 0 || j == 0) { lcs[i][j] = 0; } else { if (str1[i - 1] == str2[j - 1]) { lcs[i][j] = 1 + lcs[i - 1][j - 1]; } else { lcs[i][j] = max(lcs[i][j - 1], lcs[i - 1][j]); } } }} var n = lcs[len1][len2]; document.write("Length of common subsequence is: " + n + "<br>" + "The subsequence is : "); var str=""; var i = len1; var j = len2; while(i>0&&j>0) { if(str1[i - 1] == str2[j - 1]) { str += str1[i - 1]; i--; j--; } else{ if(lcs[i][j-1]>lcs[i-1][j]) { j--; } else { i--; } } } return ReverseString(str); } var str1 = "AGGTAB"; var str2 = "GXTXAYB"; document.write(printLCS(str1, str2)); // This code is contributed by akshitsaxenaa09</script> LCS of AGGTAB and GXTXAYB is GTAB Output: LCS of AGGTAB and GXTXAYB is GTAB YouTubeGeeksforGeeks507K subscribersDynamic Programming | Set 4 (Longest Common Subsequence) | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 8:14•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=HgUOWB0StNE" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> References: http://en.wikipedia.org/wiki/Longest_common_subsequence_problemPlease write comments if you find anything incorrect, or you want to share more information about the topic discussed above Sam007 ukasp abhishek_987 divamkachoria surinderdawra388 akshitsaxenaa09 amartyaghoshgfg amanasati1 LCS subsequence Strings Strings LCS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Check for Balanced Brackets in an expression (well-formedness) using Stack Python program to check if a string is palindrome or not KMP Algorithm for Pattern Searching Array of Strings in C++ (5 Different Ways to Create) Different methods to reverse a string in C/C++ Convert string to char array in C++ Longest Palindromic Substring | Set 1 Caesar Cipher in Cryptography Check whether two strings are anagram of each other Length of the longest substring without repeating characters
[ { "code": null, "e": 26403, "s": 26375, "text": "\n12 Apr, 2022" }, { "code": null, "e": 27600, "s": 26403, "text": "Given two sequences, print the longest subsequence present in both of them. Examples: LCS for input Sequences “ABCDGH” and “AEDFHR” is “ADH” of length 3. LCS for input Sequences “AGGTAB” and “GXTXAYB” is “GTAB” of length 4.We have discussed Longest Common Subsequence (LCS) problem in a previous post. The function discussed there was mainly to find the length of LCS. To find length of LCS, a 2D table L[][] was constructed. In this post, the function to construct and print LCS is discussed.Following is detailed algorithm to print the LCS. It uses the same 2D table L[][].1) Construct L[m+1][n+1] using the steps discussed in previous post.2) The value L[m][n] contains length of LCS. Create a character array lcs[] of length equal to the length of lcs plus 1 (one extra to store \\0).3) Traverse the 2D array starting from L[m][n]. Do following for every cell L[i][j] .....a) If characters (in X and Y) corresponding to L[i][j] are same (Or X[i-1] == Y[j-1]), then include this character as part of LCS. .....b) Else compare values of L[i-1][j] and L[i][j-1] and go in direction of greater value.The following table (taken from Wiki) shows steps (highlighted) followed by the above algorithm. " }, { "code": null, "e": 27655, "s": 27602, "text": "Following is the implementation of above approach. " }, { "code": null, "e": 27661, "s": 27655, "text": "C++14" }, { "code": null, "e": 27666, "s": 27661, "text": "Java" }, { "code": null, "e": 27674, "s": 27666, "text": "Python3" }, { "code": null, "e": 27677, "s": 27674, "text": "C#" }, { "code": null, "e": 27681, "s": 27677, "text": "PHP" }, { "code": null, "e": 27692, "s": 27681, "text": "Javascript" }, { "code": "/* Dynamic Programming implementation of LCS problem */#include <cstdlib>#include <cstring>#include <iostream>using namespace std; /* Returns length of LCS for X[0..m-1], Y[0..n-1] */void lcs(char* X, char* Y, int m, int n){ int L[m + 1][n + 1]; /* Following steps build L[m+1][n+1] in bottom up fashion. Note that L[i][j] contains length of LCS of X[0..i-1] and Y[0..j-1] */ for (int i = 0; i <= m; i++) { for (int j = 0; j <= n; j++) { if (i == 0 || j == 0) L[i][j] = 0; else if (X[i - 1] == Y[j - 1]) L[i][j] = L[i - 1][j - 1] + 1; else L[i][j] = max(L[i - 1][j], L[i][j - 1]); } } // Following code is used to print LCS int index = L[m][n]; // Create a character array to store the lcs string char lcs[index + 1]; lcs[index] = '\\0'; // Set the terminating character // Start from the right-most-bottom-most corner and // one by one store characters in lcs[] int i = m, j = n; while (i > 0 && j > 0) { // If current character in X[] and Y are same, then // current character is part of LCS if (X[i - 1] == Y[j - 1]) { lcs[index - 1] = X[i - 1]; // Put current character in result i--; j--; index--; // reduce values of i, j and index } // If not same, then find the larger of two and // go in the direction of larger value else if (L[i - 1][j] > L[i][j - 1]) i--; else j--; } // Print the lcs cout << \"LCS of \" << X << \" and \" << Y << \" is \" << lcs;} /* Driver program to test above function */int main(){ char X[] = \"AGGTAB\"; char Y[] = \"GXTXAYB\"; int m = strlen(X); int n = strlen(Y); lcs(X, Y, m, n); return 0;}", "e": 29521, "s": 27692, "text": null }, { "code": "// Dynamic Programming implementation of LCS problem in Javaimport java.io.*; class LongestCommonSubsequence { // Returns length of LCS for X[0..m-1], Y[0..n-1] static void lcs(String X, String Y, int m, int n) { int[][] L = new int[m + 1][n + 1]; // Following steps build L[m+1][n+1] in bottom up // fashion. Note that L[i][j] contains length of LCS // of X[0..i-1] and Y[0..j-1] for (int i = 0; i <= m; i++) { for (int j = 0; j <= n; j++) { if (i == 0 || j == 0) L[i][j] = 0; else if (X.charAt(i - 1) == Y.charAt(j - 1)) L[i][j] = L[i - 1][j - 1] + 1; else L[i][j] = Math.max(L[i - 1][j], L[i][j - 1]); } } // Following code is used to print LCS int index = L[m][n]; int temp = index; // Create a character array to store the lcs string char[] lcs = new char[index + 1]; lcs[index] = '\\u0000'; // Set the terminating character // Start from the right-most-bottom-most corner and // one by one store characters in lcs[] int i = m; int j = n; while (i > 0 && j > 0) { // If current character in X[] and Y are same, // then current character is part of LCS if (X.charAt(i - 1) == Y.charAt(j - 1)) { // Put current character in result lcs[index - 1] = X.charAt(i - 1); // reduce values of i, j and index i--; j--; index--; } // If not same, then find the larger of two and // go in the direction of larger value else if (L[i - 1][j] > L[i][j - 1]) i--; else j--; } // Print the lcs System.out.print(\"LCS of \" + X + \" and \" + Y + \" is \"); for (int k = 0; k <= temp; k++) System.out.print(lcs[k]); } // driver program public static void main(String[] args) { String X = \"AGGTAB\"; String Y = \"GXTXAYB\"; int m = X.length(); int n = Y.length(); lcs(X, Y, m, n); }} // Contributed by Pramod Kumar", "e": 31840, "s": 29521, "text": null }, { "code": "# Dynamic programming implementation of LCS problem # Returns length of LCS for X[0..m-1], Y[0..n-1] def lcs(X, Y, m, n): L = [[0 for i in range(n+1)] for j in range(m+1)] # Following steps build L[m+1][n+1] in bottom up fashion. Note # that L[i][j] contains length of LCS of X[0..i-1] and Y[0..j-1] for i in range(m+1): for j in range(n+1): if i == 0 or j == 0: L[i][j] = 0 elif X[i-1] == Y[j-1]: L[i][j] = L[i-1][j-1] + 1 else: L[i][j] = max(L[i-1][j], L[i][j-1]) # Create a string variable to store the lcs string lcs = \"\" # Start from the right-most-bottom-most corner and # one by one store characters in lcs[] i = m j = n while i > 0 and j > 0: # If current character in X[] and Y are same, then # current character is part of LCS if X[i-1] == Y[j-1]: lcs += X[i-1] i -= 1 j -= 1 # If not same, then find the larger of two and # go in the direction of larger value elif L[i-1][j] > L[i][j-1]: i -= 1 else: j -= 1 # We traversed the table in reverse order # LCS is the reverse of what we got lcs = lcs[::-1] print(\"LCS of \" + X + \" and \" + Y + \" is \" + lcs) # Driver programX = \"AGGTAB\"Y = \"GXTXAYB\"m = len(X)n = len(Y)lcs(X, Y, m, n) # This code is contributed by AMAN ASATI", "e": 33280, "s": 31840, "text": null }, { "code": "// Dynamic Programming implementation// of LCS problem in C#using System; class GFG { // Returns length of LCS for X[0..m-1], Y[0..n-1] static void lcs(String X, String Y, int m, int n) { int[, ] L = new int[m + 1, n + 1]; // Following steps build L[m+1][n+1] in // bottom up fashion. Note that L[i][j] // contains length of LCS of X[0..i-1] // and Y[0..j-1] for (int i = 0; i <= m; i++) { for (int j = 0; j <= n; j++) { if (i == 0 || j == 0) L[i, j] = 0; else if (X[i - 1] == Y[j - 1]) L[i, j] = L[i - 1, j - 1] + 1; else L[i, j] = Math.Max(L[i - 1, j], L[i, j - 1]); } } // Following code is used to print LCS int index = L[m, n]; int temp = index; // Create a character array // to store the lcs string char[] lcs = new char[index + 1]; // Set the terminating character lcs[index] = '\\0'; // Start from the right-most-bottom-most corner // and one by one store characters in lcs[] int k = m, l = n; while (k > 0 && l > 0) { // If current character in X[] and Y // are same, then current character // is part of LCS if (X[k - 1] == Y[l - 1]) { // Put current character in result lcs[index - 1] = X[k - 1]; // reduce values of i, j and index k--; l--; index--; } // If not same, then find the larger of two and // go in the direction of larger value else if (L[k - 1, l] > L[k, l - 1]) k--; else l--; } // Print the lcs Console.Write(\"LCS of \" + X + \" and \" + Y + \" is \"); for (int q = 0; q <= temp; q++) Console.Write(lcs[q]); } // Driver program public static void Main() { String X = \"AGGTAB\"; String Y = \"GXTXAYB\"; int m = X.Length; int n = Y.Length; lcs(X, Y, m, n); }} // This code is contributed by Sam007", "e": 35515, "s": 33280, "text": null }, { "code": "<?php// Dynamic Programming implementation of LCS problem // Returns length of LCS for X[0..m-1], Y[0..n-1]function lcs( $X, $Y, $m, $n ){ $L = array_fill(0, $m + 1, array_fill(0, $n + 1, NULL)); /* Following steps build L[m+1][n+1] in bottom up fashion. Note that L[i][j] contains length of LCS of X[0..i-1] and Y[0..j-1] */ for ($i = 0; $i <= $m; $i++) { for ($j = 0; $j <= $n; $j++) { if ($i == 0 || $j == 0) $L[$i][$j] = 0; else if ($X[$i - 1] == $Y[$j - 1]) $L[$i][$j] = $L[$i - 1][$j - 1] + 1; else $L[$i][$j] = max($L[$i - 1][$j], $L[$i][$j - 1]); } } // Following code is used to print LCS $index = $L[$m][$n]; $temp = $index; // Create a character array to store the lcs string $lcs = array_fill(0, $index + 1, NULL); $lcs[$index] = ''; // Set the terminating character // Start from the right-most-bottom-most corner // and one by one store characters in lcs[] $i = $m; $j = $n; while ($i > 0 && $j > 0) { // If current character in X[] and Y are same, // then current character is part of LCS if ($X[$i - 1] == $Y[$j - 1]) { // Put current character in result $lcs[$index - 1] = $X[$i - 1]; $i--; $j--; $index--; // reduce values of i, j and index } // If not same, then find the larger of two // and go in the direction of larger value else if ($L[$i - 1][$j] > $L[$i][$j - 1]) $i--; else $j--; } // Print the lcs echo \"LCS of \" . $X . \" and \" . $Y . \" is \"; for($k = 0; $k < $temp; $k++) echo $lcs[$k];} // Driver Code$X = \"AGGTAB\";$Y = \"GXTXAYB\";$m = strlen($X);$n = strlen($Y);lcs($X, $Y, $m, $n); // This code is contributed by ita_c?>", "e": 37461, "s": 35515, "text": null }, { "code": "<script>function ReverseString(str) { return str.split('').reverse().join('')} function max(a, b){ if (a > b) return a; else return b;}function printLCS(str1, str2) { var len1 = str1.length; var len2 = str2.length; var lcs = new Array(len1 + 1); for (var i = 0; i <= len1; i++) { lcs[i] = new Array(len2 + 1) } for (var i = 0; i <= len1; i++) { for (var j = 0; j <= len2; j++) { if (i == 0 || j == 0) { lcs[i][j] = 0; } else { if (str1[i - 1] == str2[j - 1]) { lcs[i][j] = 1 + lcs[i - 1][j - 1]; } else { lcs[i][j] = max(lcs[i][j - 1], lcs[i - 1][j]); } } }} var n = lcs[len1][len2]; document.write(\"Length of common subsequence is: \" + n + \"<br>\" + \"The subsequence is : \"); var str=\"\"; var i = len1; var j = len2; while(i>0&&j>0) { if(str1[i - 1] == str2[j - 1]) { str += str1[i - 1]; i--; j--; } else{ if(lcs[i][j-1]>lcs[i-1][j]) { j--; } else { i--; } } } return ReverseString(str); } var str1 = \"AGGTAB\"; var str2 = \"GXTXAYB\"; document.write(printLCS(str1, str2)); // This code is contributed by akshitsaxenaa09</script>", "e": 38998, "s": 37461, "text": null }, { "code": null, "e": 39032, "s": 38998, "text": "LCS of AGGTAB and GXTXAYB is GTAB" }, { "code": null, "e": 39041, "s": 39032, "text": "Output: " }, { "code": null, "e": 39075, "s": 39041, "text": "LCS of AGGTAB and GXTXAYB is GTAB" }, { "code": null, "e": 39932, "s": 39077, "text": "YouTubeGeeksforGeeks507K subscribersDynamic Programming | Set 4 (Longest Common Subsequence) | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 8:14•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=HgUOWB0StNE\" 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": 40132, "s": 39932, "text": "References: http://en.wikipedia.org/wiki/Longest_common_subsequence_problemPlease write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 40139, "s": 40132, "text": "Sam007" }, { "code": null, "e": 40145, "s": 40139, "text": "ukasp" }, { "code": null, "e": 40158, "s": 40145, "text": "abhishek_987" }, { "code": null, "e": 40172, "s": 40158, "text": "divamkachoria" }, { "code": null, "e": 40189, "s": 40172, "text": "surinderdawra388" }, { "code": null, "e": 40205, "s": 40189, "text": "akshitsaxenaa09" }, { "code": null, "e": 40221, "s": 40205, "text": "amartyaghoshgfg" }, { "code": null, "e": 40232, "s": 40221, "text": "amanasati1" }, { "code": null, "e": 40236, "s": 40232, "text": "LCS" }, { "code": null, "e": 40248, "s": 40236, "text": "subsequence" }, { "code": null, "e": 40256, "s": 40248, "text": "Strings" }, { "code": null, "e": 40264, "s": 40256, "text": "Strings" }, { "code": null, "e": 40268, "s": 40264, "text": "LCS" }, { "code": null, "e": 40366, "s": 40268, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 40441, "s": 40366, "text": "Check for Balanced Brackets in an expression (well-formedness) using Stack" }, { "code": null, "e": 40498, "s": 40441, "text": "Python program to check if a string is palindrome or not" }, { "code": null, "e": 40534, "s": 40498, "text": "KMP Algorithm for Pattern Searching" }, { "code": null, "e": 40587, "s": 40534, "text": "Array of Strings in C++ (5 Different Ways to Create)" }, { "code": null, "e": 40634, "s": 40587, "text": "Different methods to reverse a string in C/C++" }, { "code": null, "e": 40670, "s": 40634, "text": "Convert string to char array in C++" }, { "code": null, "e": 40708, "s": 40670, "text": "Longest Palindromic Substring | Set 1" }, { "code": null, "e": 40738, "s": 40708, "text": "Caesar Cipher in Cryptography" }, { "code": null, "e": 40790, "s": 40738, "text": "Check whether two strings are anagram of each other" } ]
LocalDateTime minus() method in Java with Examples - GeeksforGeeks
28 Jan, 2022 In LocalDateTime class, there are two types of minus() method depending upon the parameters passed to it. minus() method of a LocalDateTime class used to returns a copy of this LocalDateTime with the specified amount of unit subtracted.If it is not possible to subtract the amount, because the unit is not supported or for some other reason, an exception is thrown.Syntax: public LocalDateTime minus(long amountToSubtract, TemporalUnit unit) Parameters: This method accepts two parameters amountToSubtract which is the amount of the unit to subtract to the result, may be negative and unit which is the unit of the amount to subtract, not null.Return value: This method returns LocalDateTime based on this LocalDateTime with the specified amount subtracted.Exception: This method throws following Exceptions: DateTimeException – if the subtraction cannot be made UnsupportedTemporalTypeException – if the unit is not supported ArithmeticException – if numeric overflow occurs Below programs illustrate the minus() method: Program 1: Java // Java program to demonstrate// LocalDateTime.minus() method import java.time.*;import java.time.temporal.ChronoUnit; public class GFG { public static void main(String[] args) { // Get the LocalDateTime instance LocalDateTime ldt = LocalDateTime .parse("2019-12-31T19:15:30"); // Get the String representation of this LocalDateTime System.out.println("Original LocalDateTime: " + ldt.toString()); // subtract 200 DAYS to LocalDateTime LocalDateTime value = ldt.minus(200, ChronoUnit.DAYS); // print result System.out.println("LocalDateTime after subtracting DAYS: " + value); }} Original LocalDateTime: 2019-12-31T19:15:30 LocalDateTime after subtracting DAYS: 2019-06-14T19:15:30 minus() method of a LocalDateTime class used to returns a copy of this LocalDateTime with the specified amount subtracted to date-time.The amount is typically Period or Duration but may be any other type implementing the TemporalAmount interface.Syntax: public LocalDateTime minus(TemporalAmount amountTosubtract) Parameters: This method accepts one single parameter amountTosubtract which is the amount to subtract, It should not be null.Return value: This method returns LocalDateTime based on this date-time with the subtraction made, not null.Exception: This method throws following Exceptions: DateTimeException – if the subtraction cannot be made ArithmeticException – if numeric overflow occurs Below programs illustrate the minus() method: Program 1: Java // Java program to demonstrate// LocalDateTime.minus() method import java.time.*;public class GFG { public static void main(String[] args) { // Get the LocalDateTime instance LocalDateTime ldt = LocalDateTime .parse("2019-12-31T19:15:30"); // Get the String representation of this LocalDateTime System.out.println("Original LocalDateTime: " + ldt.toString()); // subtract 10 Days to LocalDateTime LocalDateTime value = ldt.minus(Period.ofDays(10)); // print result System.out.println("LocalDateTime after subtracting Days: " + value); }} Original LocalDateTime: 2019-12-31T19:15:30 LocalDateTime after subtracting Days: 2019-12-21T19:15:30 References: https://docs.oracle.com/javase/10/docs/api/java/time/LocalDateTime.html#minus(java.time.temporal.TemporalAmount) https://docs.oracle.com/javase/10/docs/api/java/time/LocalDateTime.html#minus(long, java.time.temporal.TemporalUnit) saurabh1990aror Java-Functions Java-LocalDateTime Java-time package Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java HashMap in Java with Examples Interfaces in Java Stream In Java How to iterate any Map in Java ArrayList in Java Initialize an ArrayList in Java Stack Class in Java Multidimensional Arrays in Java Singleton Class in Java
[ { "code": null, "e": 25605, "s": 25577, "text": "\n28 Jan, 2022" }, { "code": null, "e": 25712, "s": 25605, "text": "In LocalDateTime class, there are two types of minus() method depending upon the parameters passed to it. " }, { "code": null, "e": 25981, "s": 25712, "text": "minus() method of a LocalDateTime class used to returns a copy of this LocalDateTime with the specified amount of unit subtracted.If it is not possible to subtract the amount, because the unit is not supported or for some other reason, an exception is thrown.Syntax: " }, { "code": null, "e": 26077, "s": 25981, "text": "public LocalDateTime minus(long amountToSubtract,\n TemporalUnit unit)" }, { "code": null, "e": 26446, "s": 26077, "text": "Parameters: This method accepts two parameters amountToSubtract which is the amount of the unit to subtract to the result, may be negative and unit which is the unit of the amount to subtract, not null.Return value: This method returns LocalDateTime based on this LocalDateTime with the specified amount subtracted.Exception: This method throws following Exceptions: " }, { "code": null, "e": 26500, "s": 26446, "text": "DateTimeException – if the subtraction cannot be made" }, { "code": null, "e": 26564, "s": 26500, "text": "UnsupportedTemporalTypeException – if the unit is not supported" }, { "code": null, "e": 26613, "s": 26564, "text": "ArithmeticException – if numeric overflow occurs" }, { "code": null, "e": 26672, "s": 26613, "text": "Below programs illustrate the minus() method: Program 1: " }, { "code": null, "e": 26677, "s": 26672, "text": "Java" }, { "code": "// Java program to demonstrate// LocalDateTime.minus() method import java.time.*;import java.time.temporal.ChronoUnit; public class GFG { public static void main(String[] args) { // Get the LocalDateTime instance LocalDateTime ldt = LocalDateTime .parse(\"2019-12-31T19:15:30\"); // Get the String representation of this LocalDateTime System.out.println(\"Original LocalDateTime: \" + ldt.toString()); // subtract 200 DAYS to LocalDateTime LocalDateTime value = ldt.minus(200, ChronoUnit.DAYS); // print result System.out.println(\"LocalDateTime after subtracting DAYS: \" + value); }}", "e": 27417, "s": 26677, "text": null }, { "code": null, "e": 27519, "s": 27417, "text": "Original LocalDateTime: 2019-12-31T19:15:30\nLocalDateTime after subtracting DAYS: 2019-06-14T19:15:30" }, { "code": null, "e": 27777, "s": 27521, "text": "minus() method of a LocalDateTime class used to returns a copy of this LocalDateTime with the specified amount subtracted to date-time.The amount is typically Period or Duration but may be any other type implementing the TemporalAmount interface.Syntax: " }, { "code": null, "e": 27837, "s": 27777, "text": "public LocalDateTime minus(TemporalAmount amountTosubtract)" }, { "code": null, "e": 28122, "s": 27837, "text": "Parameters: This method accepts one single parameter amountTosubtract which is the amount to subtract, It should not be null.Return value: This method returns LocalDateTime based on this date-time with the subtraction made, not null.Exception: This method throws following Exceptions:" }, { "code": null, "e": 28176, "s": 28122, "text": "DateTimeException – if the subtraction cannot be made" }, { "code": null, "e": 28225, "s": 28176, "text": "ArithmeticException – if numeric overflow occurs" }, { "code": null, "e": 28284, "s": 28225, "text": "Below programs illustrate the minus() method: Program 1: " }, { "code": null, "e": 28289, "s": 28284, "text": "Java" }, { "code": "// Java program to demonstrate// LocalDateTime.minus() method import java.time.*;public class GFG { public static void main(String[] args) { // Get the LocalDateTime instance LocalDateTime ldt = LocalDateTime .parse(\"2019-12-31T19:15:30\"); // Get the String representation of this LocalDateTime System.out.println(\"Original LocalDateTime: \" + ldt.toString()); // subtract 10 Days to LocalDateTime LocalDateTime value = ldt.minus(Period.ofDays(10)); // print result System.out.println(\"LocalDateTime after subtracting Days: \" + value); }}", "e": 28987, "s": 28289, "text": null }, { "code": null, "e": 29089, "s": 28987, "text": "Original LocalDateTime: 2019-12-31T19:15:30\nLocalDateTime after subtracting Days: 2019-12-21T19:15:30" }, { "code": null, "e": 29334, "s": 29091, "text": "References: https://docs.oracle.com/javase/10/docs/api/java/time/LocalDateTime.html#minus(java.time.temporal.TemporalAmount) https://docs.oracle.com/javase/10/docs/api/java/time/LocalDateTime.html#minus(long, java.time.temporal.TemporalUnit) " }, { "code": null, "e": 29350, "s": 29334, "text": "saurabh1990aror" }, { "code": null, "e": 29365, "s": 29350, "text": "Java-Functions" }, { "code": null, "e": 29384, "s": 29365, "text": "Java-LocalDateTime" }, { "code": null, "e": 29402, "s": 29384, "text": "Java-time package" }, { "code": null, "e": 29407, "s": 29402, "text": "Java" }, { "code": null, "e": 29412, "s": 29407, "text": "Java" }, { "code": null, "e": 29510, "s": 29412, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29561, "s": 29510, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 29591, "s": 29561, "text": "HashMap in Java with Examples" }, { "code": null, "e": 29610, "s": 29591, "text": "Interfaces in Java" }, { "code": null, "e": 29625, "s": 29610, "text": "Stream In Java" }, { "code": null, "e": 29656, "s": 29625, "text": "How to iterate any Map in Java" }, { "code": null, "e": 29674, "s": 29656, "text": "ArrayList in Java" }, { "code": null, "e": 29706, "s": 29674, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 29726, "s": 29706, "text": "Stack Class in Java" }, { "code": null, "e": 29758, "s": 29726, "text": "Multidimensional Arrays in Java" } ]
How DORA Works? - GeeksforGeeks
16 Dec, 2021 Dynamic Host Configuration Protocol(DHCP) uses the DORA. Dynamic Host Configuration Protocol is the protocol of the application layer. It is used to provide Subnet Mask, Router Address, DNS Address, and Vendor Class Identifier. In fact, DHCP provides an automatic IP address to Hosts which want to connect to a network. DORA is the process that is used by DHCP. DORA helps in providing an IP address to hosts or client machines. DORA is the process that follows some steps between the server and client. It gets the IP address from the centralized server. It consists of four-stage: Discover Offer Request Acknowledge Now let’s see what happens when DHCP clients request a DHCP server an IP address. Let’s see what messages are exchanged between them in the process. Note: In the network layer, DHCP messages are always broadcast. In the data link layer also DHCP messages are broadcast. This is the first message in the DORA process which helps in finding the DHCP server of the network. DHCP client will find the server by sending DHCP discover message. The broadcast message is sent to the network. As the DHCP client doesn’t know the IP address of the server so the message is broadcast with a destination IP is 255.255.255.255. And the source IP will be 0.0.0.0 as the client does not have any IP address. Here the DHCP discover message in the data link layer and network layer is always broadcast. Source IP address: 0.0.0.0 Destination IP address: 255.255.255.255 Source MAC address: MAC address of DHCP clients Destination MAC address: FF:FF:FF:FF:FF:FF DHCP server receives the discover message and it replays the DHCP client with the DHCP offer request. The server sends a DHCP offer message with filled information. It has information about the IP address and duration of time that a host can use. Here destination IP address will be 255.255.255.255 as the DHCP client still does not have its IP address. But this DHCP offer message is broadcast in the network layer and unicast in the data link layer. Source IP address: IP Address of DHCP Server Destination IP address: 255.255.255.255 Source MAC address: MAC address of DHCP Server Destination MAC address: MAC address of DHCP clients DHCP clients send the request message to the server when it receives a DHCP offer message from the server. This message tells the server that it accepts the IP address given by the server. Here destination address will be 255.255.255.255 means it’s again broadcast. The reason for this is there might be many DHCP servers in the network so the client may receive multiple offer messages and it will accept the request that reaches him first and send a broadcast message to eliminate other DHCP servers. Here source IP address will be 0.0.0.0 as the DHCP server hasn’t yet assigned an IP address to the client. DHCP Request Message is also a broadcast message. Source IP address: 0.0.0.0 Destination IP address: 255.255.255.255 Source MAC address: MAC address of DHCP clients Destination MAC address: MAC address of DHCP server This is the last step or message in the DORA process. The DHCP server sends Acknowledge Message to the client when it receives the request message from the DHCP client. This message will contain the IP address and subnet mask that the server assigns to the client. Source IP address will be the IP address of the server. This will be again broadcast message as the destination IP address is 255.255.255.255. But it is unicast in the case of the data link layer. Source IP address: IP Address of DHCP Server Destination IP address: 255.255.255.255 Source MAC address: MAC address of DHCP server Destination MAC address: MAC address of DHCP clients So, this is the DORA process and when this process is over DHCP client will get its IP address. Here things to remember is DHCP Discover Message – Broadcast DHCP Offer Message – Broadcast in the network layer and unicast in the data link layer DHCP Request Message – Broadcast in the network layer and unicast in the data link layer DHCP Acknowledge Message – Broadcast in the network layer and unicast in the data link layer Picked Computer Networks Computer Subject Computer Networks Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Advanced Encryption Standard (AES) Introduction and IPv4 Datagram Header Intrusion Detection System (IDS) Secure Socket Layer (SSL) Cryptography and its Types SDE SHEET - A Complete Guide for SDE Preparation Introduction to Algorithms Software Engineering | Coupling and Cohesion Difference between NP hard and NP complete problem Software Engineering | Prototyping Model
[ { "code": null, "e": 25755, "s": 25727, "text": "\n16 Dec, 2021" }, { "code": null, "e": 26075, "s": 25755, "text": "Dynamic Host Configuration Protocol(DHCP) uses the DORA. Dynamic Host Configuration Protocol is the protocol of the application layer. It is used to provide Subnet Mask, Router Address, DNS Address, and Vendor Class Identifier. In fact, DHCP provides an automatic IP address to Hosts which want to connect to a network." }, { "code": null, "e": 26338, "s": 26075, "text": "DORA is the process that is used by DHCP. DORA helps in providing an IP address to hosts or client machines. DORA is the process that follows some steps between the server and client. It gets the IP address from the centralized server. It consists of four-stage:" }, { "code": null, "e": 26347, "s": 26338, "text": "Discover" }, { "code": null, "e": 26353, "s": 26347, "text": "Offer" }, { "code": null, "e": 26361, "s": 26353, "text": "Request" }, { "code": null, "e": 26373, "s": 26361, "text": "Acknowledge" }, { "code": null, "e": 26522, "s": 26373, "text": "Now let’s see what happens when DHCP clients request a DHCP server an IP address. Let’s see what messages are exchanged between them in the process." }, { "code": null, "e": 26643, "s": 26522, "text": "Note: In the network layer, DHCP messages are always broadcast. In the data link layer also DHCP messages are broadcast." }, { "code": null, "e": 27160, "s": 26643, "text": "This is the first message in the DORA process which helps in finding the DHCP server of the network. DHCP client will find the server by sending DHCP discover message. The broadcast message is sent to the network. As the DHCP client doesn’t know the IP address of the server so the message is broadcast with a destination IP is 255.255.255.255. And the source IP will be 0.0.0.0 as the client does not have any IP address. Here the DHCP discover message in the data link layer and network layer is always broadcast. " }, { "code": null, "e": 27320, "s": 27160, "text": "Source IP address: 0.0.0.0 \nDestination IP address: 255.255.255.255\nSource MAC address: MAC address of DHCP clients\nDestination MAC address: FF:FF:FF:FF:FF:FF" }, { "code": null, "e": 27773, "s": 27320, "text": "DHCP server receives the discover message and it replays the DHCP client with the DHCP offer request. The server sends a DHCP offer message with filled information. It has information about the IP address and duration of time that a host can use. Here destination IP address will be 255.255.255.255 as the DHCP client still does not have its IP address. But this DHCP offer message is broadcast in the network layer and unicast in the data link layer. " }, { "code": null, "e": 27958, "s": 27773, "text": "Source IP address: IP Address of DHCP Server\nDestination IP address: 255.255.255.255\nSource MAC address: MAC address of DHCP Server\nDestination MAC address: MAC address of DHCP clients" }, { "code": null, "e": 28618, "s": 27958, "text": "DHCP clients send the request message to the server when it receives a DHCP offer message from the server. This message tells the server that it accepts the IP address given by the server. Here destination address will be 255.255.255.255 means it’s again broadcast. The reason for this is there might be many DHCP servers in the network so the client may receive multiple offer messages and it will accept the request that reaches him first and send a broadcast message to eliminate other DHCP servers. Here source IP address will be 0.0.0.0 as the DHCP server hasn’t yet assigned an IP address to the client. DHCP Request Message is also a broadcast message." }, { "code": null, "e": 28785, "s": 28618, "text": "Source IP address: 0.0.0.0\nDestination IP address: 255.255.255.255\nSource MAC address: MAC address of DHCP clients\nDestination MAC address: MAC address of DHCP server" }, { "code": null, "e": 29248, "s": 28785, "text": "This is the last step or message in the DORA process. The DHCP server sends Acknowledge Message to the client when it receives the request message from the DHCP client. This message will contain the IP address and subnet mask that the server assigns to the client. Source IP address will be the IP address of the server. This will be again broadcast message as the destination IP address is 255.255.255.255. But it is unicast in the case of the data link layer. " }, { "code": null, "e": 29433, "s": 29248, "text": "Source IP address: IP Address of DHCP Server\nDestination IP address: 255.255.255.255\nSource MAC address: MAC address of DHCP server\nDestination MAC address: MAC address of DHCP clients" }, { "code": null, "e": 29556, "s": 29433, "text": "So, this is the DORA process and when this process is over DHCP client will get its IP address. Here things to remember is" }, { "code": null, "e": 29590, "s": 29556, "text": "DHCP Discover Message – Broadcast" }, { "code": null, "e": 29677, "s": 29590, "text": "DHCP Offer Message – Broadcast in the network layer and unicast in the data link layer" }, { "code": null, "e": 29766, "s": 29677, "text": "DHCP Request Message – Broadcast in the network layer and unicast in the data link layer" }, { "code": null, "e": 29859, "s": 29766, "text": "DHCP Acknowledge Message – Broadcast in the network layer and unicast in the data link layer" }, { "code": null, "e": 29866, "s": 29859, "text": "Picked" }, { "code": null, "e": 29884, "s": 29866, "text": "Computer Networks" }, { "code": null, "e": 29901, "s": 29884, "text": "Computer Subject" }, { "code": null, "e": 29919, "s": 29901, "text": "Computer Networks" }, { "code": null, "e": 30017, "s": 29919, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30052, "s": 30017, "text": "Advanced Encryption Standard (AES)" }, { "code": null, "e": 30090, "s": 30052, "text": "Introduction and IPv4 Datagram Header" }, { "code": null, "e": 30123, "s": 30090, "text": "Intrusion Detection System (IDS)" }, { "code": null, "e": 30149, "s": 30123, "text": "Secure Socket Layer (SSL)" }, { "code": null, "e": 30176, "s": 30149, "text": "Cryptography and its Types" }, { "code": null, "e": 30225, "s": 30176, "text": "SDE SHEET - A Complete Guide for SDE Preparation" }, { "code": null, "e": 30252, "s": 30225, "text": "Introduction to Algorithms" }, { "code": null, "e": 30297, "s": 30252, "text": "Software Engineering | Coupling and Cohesion" }, { "code": null, "e": 30348, "s": 30297, "text": "Difference between NP hard and NP complete problem" } ]
How to check whether an image is loaded or not ? - GeeksforGeeks
12 May, 2022 While inserting images in HTML pages sometimes the image may fail to load due to: Getting the image URL wrong poor internet connection So we may want to check if the image is not loading due to these reasons. To check we can use the below methods Method 1: Using attributes of <img> to check whether an image is loaded or not. The attributes we will use are: onload: The onload event is triggered when an image is loaded and is executed onerror: The onerror event is triggered if an error occurs during the execution Example: html <!DOCTYPE html><html> <head> <title>Image load check</title> </head> <body> <img src="https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-6.png" onload="javascript: alert('The image has been loaded')" onerror="javascript: alert('The image has failed to load')" /> </body></html> Output: when image is successfully loaded when image loading fails Method 2: Using the image complete property in HTML DOM This property returns a boolean value if the image is loaded it returns true else it returns false Example: html <!DOCTYPE html><html> <head> <title>Checking if image is loaded</title> </head> <script type="text/javascript"> window.addEventListener("load", event => { var image = document.querySelector('img'); var load = image.complete; alert(load);}); </script> <body> <img src="https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-6.png"> </body></html> Here the variable load checks if the image is loaded or not. If an image is loaded then true is alerted else false is alerted. Output: when image is successfully loaded when image load fails Supported Browsers: Google Chrome Firefox Internet Explorer Safari Opera Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. sumitgumber28 ankita_saini HTML-Attributes HTML JavaScript Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to insert spaces/tabs in text using HTML/CSS? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to update Node.js and NPM to next version ? How to set the default value for an HTML <select> element ? Hide or show elements in HTML using display property Remove elements from a JavaScript Array Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React How to calculate the number of days between two dates in javascript?
[ { "code": null, "e": 33003, "s": 32975, "text": "\n12 May, 2022" }, { "code": null, "e": 33085, "s": 33003, "text": "While inserting images in HTML pages sometimes the image may fail to load due to:" }, { "code": null, "e": 33113, "s": 33085, "text": "Getting the image URL wrong" }, { "code": null, "e": 33138, "s": 33113, "text": "poor internet connection" }, { "code": null, "e": 33250, "s": 33138, "text": "So we may want to check if the image is not loading due to these reasons. To check we can use the below methods" }, { "code": null, "e": 33261, "s": 33250, "text": "Method 1: " }, { "code": null, "e": 33364, "s": 33261, "text": "Using attributes of <img> to check whether an image is loaded or not. The attributes we will use are: " }, { "code": null, "e": 33442, "s": 33364, "text": "onload: The onload event is triggered when an image is loaded and is executed" }, { "code": null, "e": 33522, "s": 33442, "text": "onerror: The onerror event is triggered if an error occurs during the execution" }, { "code": null, "e": 33532, "s": 33522, "text": "Example: " }, { "code": null, "e": 33537, "s": 33532, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title>Image load check</title> </head> <body> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-6.png\" onload=\"javascript: alert('The image has been loaded')\" onerror=\"javascript: alert('The image has failed to load')\" /> </body></html>", "e": 33847, "s": 33537, "text": null }, { "code": null, "e": 33855, "s": 33847, "text": "Output:" }, { "code": null, "e": 33889, "s": 33855, "text": "when image is successfully loaded" }, { "code": null, "e": 33914, "s": 33889, "text": "when image loading fails" }, { "code": null, "e": 33925, "s": 33914, "text": "Method 2: " }, { "code": null, "e": 33971, "s": 33925, "text": "Using the image complete property in HTML DOM" }, { "code": null, "e": 34071, "s": 33971, "text": "This property returns a boolean value if the image is loaded it returns true else it returns false" }, { "code": null, "e": 34081, "s": 34071, "text": "Example: " }, { "code": null, "e": 34086, "s": 34081, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title>Checking if image is loaded</title> </head> <script type=\"text/javascript\"> window.addEventListener(\"load\", event => { var image = document.querySelector('img'); var load = image.complete; alert(load);}); </script> <body> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-6.png\"> </body></html>", "e": 34458, "s": 34086, "text": null }, { "code": null, "e": 34585, "s": 34458, "text": "Here the variable load checks if the image is loaded or not. If an image is loaded then true is alerted else false is alerted." }, { "code": null, "e": 34593, "s": 34585, "text": "Output:" }, { "code": null, "e": 34627, "s": 34593, "text": "when image is successfully loaded" }, { "code": null, "e": 34649, "s": 34627, "text": "when image load fails" }, { "code": null, "e": 34669, "s": 34649, "text": "Supported Browsers:" }, { "code": null, "e": 34683, "s": 34669, "text": "Google Chrome" }, { "code": null, "e": 34691, "s": 34683, "text": "Firefox" }, { "code": null, "e": 34709, "s": 34691, "text": "Internet Explorer" }, { "code": null, "e": 34716, "s": 34709, "text": "Safari" }, { "code": null, "e": 34722, "s": 34716, "text": "Opera" }, { "code": null, "e": 34859, "s": 34722, "text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course." }, { "code": null, "e": 34873, "s": 34859, "text": "sumitgumber28" }, { "code": null, "e": 34886, "s": 34873, "text": "ankita_saini" }, { "code": null, "e": 34902, "s": 34886, "text": "HTML-Attributes" }, { "code": null, "e": 34907, "s": 34902, "text": "HTML" }, { "code": null, "e": 34918, "s": 34907, "text": "JavaScript" }, { "code": null, "e": 34935, "s": 34918, "text": "Web Technologies" }, { "code": null, "e": 34940, "s": 34935, "text": "HTML" }, { "code": null, "e": 35038, "s": 34940, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35088, "s": 35038, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 35150, "s": 35088, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 35198, "s": 35150, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 35258, "s": 35198, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 35311, "s": 35258, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 35351, "s": 35311, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 35396, "s": 35351, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 35457, "s": 35396, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 35529, "s": 35457, "text": "Differences between Functional Components and Class Components in React" } ]
Python super() - GeeksforGeeks
07 Feb, 2022 One of the important OOP features is Inheritance in Python. When a class inherits some or all of the behaviors from another class is known as Inheritance. In such a case, the inherited class is the subclass and the latter class is the parent class. In an inherited subclass, a parent class can be referred to with the use of the super() function. The super function returns a temporary object of the superclass that allows access to all of its methods to its child class. Note: For more information, refer to Inheritance in Python Furthermore, The benefits of using a super function are:- Need not remember or specify the parent class name to access its methods. This function can be used both in single and multiple inheritances. This implements modularity (isolating changes) and code reusability as there is no need to rewrite the entire function. Super function in Python is called dynamically because Python is a dynamic language unlike other languages. There are 3 constraints to use the super function:- The class and its methods which are referred by the super function The arguments of the super function and the called function should match. Every occurrence of the method must include super() after you use it. Super function in single inheritance Example: Let’s take an example of animals. Dogs, cats and cows are part of animals. They also share common characteristics like – They are mammals. They have a tail and four legs. They are domestic animals. So, the classes dogs, cats and horses are subclass of animal class. This is an example of single inheritance because many subclass are inherited from a single parent class. Python3 # Python program to demonstrate# super function class Animals: # Initializing constructor def __init__(self): self.legs = 4 self.domestic = True self.tail = True self.mammals = True def isMammal(self): if self.mammals: print("It is a mammal.") def isDomestic(self): if self.domestic: print("It is a domestic animal.") class Dogs(Animals): def __init__(self): super().__init__() def isMammal(self): super().isMammal() class Horses(Animals): def __init__(self): super().__init__() def hasTailandLegs(self): if self.tail and self.legs == 4: print("Has legs and tail") # Driver codeTom = Dogs()Tom.isMammal()Bruno = Horses()Bruno.hasTailandLegs() Output: It is a mammal. Has legs and tail Super function in multiple inheritance Example: Let’s take another example. Suppose a class canfly and canswim inherit from a mammal class and these classes are inherited by the animal class. So the animal class inherits from the multiple base classes. Let’s see the use of super in this case. Python3 class Mammal(): def __init__(self, name): print(name, "Is a mammal") class canFly(Mammal): def __init__(self, canFly_name): print(canFly_name, "cannot fly") # Calling Parent class # Constructor super().__init__(canFly_name) class canSwim(Mammal): def __init__(self, canSwim_name): print(canSwim_name, "cannot swim") super().__init__(canSwim_name) class Animal(canFly, canSwim): def __init__(self, name): # Calling the constructor # of both the parent # class in the order of # their inheritance super().__init__(name) # Driver CodeCarol = Animal("Dog") Output: Dog cannot fly Dog cannot swim Dog Is a mammal The class Animal inherits from two-parent classes – canFly and canSwim. So, the subclass instance Carol can access both of the parent class constructors. Akanksha_Rai vivhon simmytarika5 varshagumber28 Python-OOP python-oop-concepts Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | Get unique values from a list Python | os.path.join() method Defaultdict in Python Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25561, "s": 25533, "text": "\n07 Feb, 2022" }, { "code": null, "e": 26033, "s": 25561, "text": "One of the important OOP features is Inheritance in Python. When a class inherits some or all of the behaviors from another class is known as Inheritance. In such a case, the inherited class is the subclass and the latter class is the parent class. In an inherited subclass, a parent class can be referred to with the use of the super() function. The super function returns a temporary object of the superclass that allows access to all of its methods to its child class." }, { "code": null, "e": 26092, "s": 26033, "text": "Note: For more information, refer to Inheritance in Python" }, { "code": null, "e": 26152, "s": 26092, "text": "Furthermore, The benefits of using a super function are:- " }, { "code": null, "e": 26294, "s": 26152, "text": "Need not remember or specify the parent class name to access its methods. This function can be used both in single and multiple inheritances." }, { "code": null, "e": 26414, "s": 26294, "text": "This implements modularity (isolating changes) and code reusability as there is no need to rewrite the entire function." }, { "code": null, "e": 26522, "s": 26414, "text": "Super function in Python is called dynamically because Python is a dynamic language unlike other languages." }, { "code": null, "e": 26576, "s": 26522, "text": "There are 3 constraints to use the super function:- " }, { "code": null, "e": 26643, "s": 26576, "text": "The class and its methods which are referred by the super function" }, { "code": null, "e": 26717, "s": 26643, "text": "The arguments of the super function and the called function should match." }, { "code": null, "e": 26787, "s": 26717, "text": "Every occurrence of the method must include super() after you use it." }, { "code": null, "e": 26825, "s": 26787, "text": "Super function in single inheritance " }, { "code": null, "e": 26957, "s": 26825, "text": "Example: Let’s take an example of animals. Dogs, cats and cows are part of animals. They also share common characteristics like – " }, { "code": null, "e": 26975, "s": 26957, "text": "They are mammals." }, { "code": null, "e": 27007, "s": 26975, "text": "They have a tail and four legs." }, { "code": null, "e": 27034, "s": 27007, "text": "They are domestic animals." }, { "code": null, "e": 27207, "s": 27034, "text": "So, the classes dogs, cats and horses are subclass of animal class. This is an example of single inheritance because many subclass are inherited from a single parent class." }, { "code": null, "e": 27215, "s": 27207, "text": "Python3" }, { "code": "# Python program to demonstrate# super function class Animals: # Initializing constructor def __init__(self): self.legs = 4 self.domestic = True self.tail = True self.mammals = True def isMammal(self): if self.mammals: print(\"It is a mammal.\") def isDomestic(self): if self.domestic: print(\"It is a domestic animal.\") class Dogs(Animals): def __init__(self): super().__init__() def isMammal(self): super().isMammal() class Horses(Animals): def __init__(self): super().__init__() def hasTailandLegs(self): if self.tail and self.legs == 4: print(\"Has legs and tail\") # Driver codeTom = Dogs()Tom.isMammal()Bruno = Horses()Bruno.hasTailandLegs()", "e": 28007, "s": 27215, "text": null }, { "code": null, "e": 28015, "s": 28007, "text": "Output:" }, { "code": null, "e": 28049, "s": 28015, "text": "It is a mammal.\nHas legs and tail" }, { "code": null, "e": 28089, "s": 28049, "text": "Super function in multiple inheritance " }, { "code": null, "e": 28344, "s": 28089, "text": "Example: Let’s take another example. Suppose a class canfly and canswim inherit from a mammal class and these classes are inherited by the animal class. So the animal class inherits from the multiple base classes. Let’s see the use of super in this case." }, { "code": null, "e": 28352, "s": 28344, "text": "Python3" }, { "code": "class Mammal(): def __init__(self, name): print(name, \"Is a mammal\") class canFly(Mammal): def __init__(self, canFly_name): print(canFly_name, \"cannot fly\") # Calling Parent class # Constructor super().__init__(canFly_name) class canSwim(Mammal): def __init__(self, canSwim_name): print(canSwim_name, \"cannot swim\") super().__init__(canSwim_name) class Animal(canFly, canSwim): def __init__(self, name): # Calling the constructor # of both the parent # class in the order of # their inheritance super().__init__(name) # Driver CodeCarol = Animal(\"Dog\")", "e": 29090, "s": 28352, "text": null }, { "code": null, "e": 29098, "s": 29090, "text": "Output:" }, { "code": null, "e": 29145, "s": 29098, "text": "Dog cannot fly\nDog cannot swim\nDog Is a mammal" }, { "code": null, "e": 29300, "s": 29145, "text": "The class Animal inherits from two-parent classes – canFly and canSwim. So, the subclass instance Carol can access both of the parent class constructors. " }, { "code": null, "e": 29313, "s": 29300, "text": "Akanksha_Rai" }, { "code": null, "e": 29320, "s": 29313, "text": "vivhon" }, { "code": null, "e": 29333, "s": 29320, "text": "simmytarika5" }, { "code": null, "e": 29348, "s": 29333, "text": "varshagumber28" }, { "code": null, "e": 29359, "s": 29348, "text": "Python-OOP" }, { "code": null, "e": 29379, "s": 29359, "text": "python-oop-concepts" }, { "code": null, "e": 29386, "s": 29379, "text": "Python" }, { "code": null, "e": 29484, "s": 29386, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29516, "s": 29484, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29558, "s": 29516, "text": "Check if element exists in list in Python" }, { "code": null, "e": 29600, "s": 29558, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 29656, "s": 29600, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 29683, "s": 29656, "text": "Python Classes and Objects" }, { "code": null, "e": 29722, "s": 29683, "text": "Python | Get unique values from a list" }, { "code": null, "e": 29753, "s": 29722, "text": "Python | os.path.join() method" }, { "code": null, "e": 29775, "s": 29753, "text": "Defaultdict in Python" }, { "code": null, "e": 29804, "s": 29775, "text": "Create a directory in Python" } ]
Find a N-digit number such that it is not divisible by any of its digits - GeeksforGeeks
15 Nov, 2021 Given an integer N, the task is to find any N-digit positive number (except for zeros) such that it is not divisible by any of its digits. If it is not possible to find any such number then print -1.Note: There can be more than one such number for the same N-digit.Examples: Input: N = 2 Output: 23 23 is not divisible by 2 or 3 Input: N = 3 Output: 239 Approach: The easiest solution to this problem can be thought of with the help of digits ‘4’ and ‘5’. Since, in order for a number to be divisible by 5, the number must end with 0 or 5; and in order for it to be divisible by 4, the last two digits if the number must be divisible by 4.Therefore, a shortcut method can be applied to prevent both of the divisibility criteria of 4 and as well as of 5, as: To prevent a number from being divisible by 5, the number can contain 5 for every other digit except for last digit. Since, in order for a number to be divisible by 5, the number must end with 0 or 5; and in order for it to be divisible by 4, the last two digits if the number must be divisible by 4. Therefore, a shortcut method can be applied to prevent both of the divisibility criteria of 4 and as well as of 5, as: To prevent a number from being divisible by 5, the number can contain 5 for every other digit except for last digit. To prevent a number from being divisible by 5, the number can contain 5 for every other digit except for last digit. Therefore for N digit number, (N - 1) digits must be 5 = 5555...(N-1 times)d where d is the Nth digit To prevent a number from being divisible by 4, the number can contain 5 at the second last digit and 4 at the last digit. Therefore for N digit number, Last digit must be 4 = 5555...(N-1 times)4 Below is the implementation of the above approach: CPP Java Python3 C# Javascript // CPP program to find N digit number such// that it is not divisible by any of its digits #include <bits/stdc++.h>using namespace std; // Function that print the answervoid findTheNumber(int n){ // if n == 1 then it is // not possible if (n == 1) { cout << "Impossible" << endl; return; } // loop to n-1 times for (int i = 0; i < n - 1; i++) { cout << "5"; } // print 4 as last digit of // the number cout << "4";} // Driver codeint main(){ int n = 12; // Function call findTheNumber(n); return 0;} // JAVA program to find N digit number such// that it is not divisible by any of its digitsclass GFG{ // Function that print the answerstatic void findTheNumber(int n){ // if n == 1 then it is // not possible if (n == 1) { System.out.print("Impossible" +"\n"); return; } // loop to n-1 times for (int i = 0; i < n - 1; i++) { System.out.print("5"); } // print 4 as last digit of // the number System.out.print("4");} // Driver codepublic static void main(String[] args){ int n = 12; // Function call findTheNumber(n); }} // This code is contributed by 29AjayKumar # Python3 program to find N digit number such# that it is not divisible by any of its digits # Function that print answerdef findTheNumber(n): # if n == 1 then it is # not possible if (n == 1): print("Impossible") return # loop to n-1 times for i in range(n-1): print("5",end="") # print as last digit of # the number print("4") # Driver codeif __name__ == '__main__': n = 12 #Function call findTheNumber(n) # This code is contributed by mohit kumar 29 // C# program to find N digit number such// that it is not divisible by any of its digitsusing System; class GFG{ // Function that print the answerstatic void findTheNumber(int n){ // if n == 1 then it is // not possible if (n == 1) { Console.Write("Impossible" +"\n"); return; } // loop to n-1 times for (int i = 0; i < n - 1; i++) { Console.Write("5"); } // print 4 as last digit of // the number Console.Write("4");} // Driver codepublic static void Main(String[] args){ int n = 12; // Function call findTheNumber(n);}} // This code is contributed by 29AjayKumar <script> // Javascript program to find N digit number such// that it is not divisible by any of its digits // Function that print the answerfunction findTheNumber(n){ // if n == 1 then it is // not possible if (n == 1) { document.write( "Impossible" ); return; } // loop to n-1 times for (var i = 0; i < n - 1; i++) { document.write( "5"); } // print 4 as last digit of // the number document.write( "4");} // Driver codevar n = 12;// Function callfindTheNumber(n); // This code is contributed by rutvik_56.</script> 555555555554 Time complexity: 0(N) mohit kumar 29 29AjayKumar rutvik_56 khushboogoyal499 Number Divisibility number-digits Analysis Mathematical Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Understanding Time Complexity with Simple Examples NP-Completeness | Set 1 (Introduction) Time Complexity and Space Complexity Cyclomatic Complexity Time Complexity of building a heap Program for Fibonacci numbers Write a program to print all permutations of a given string Set in C++ Standard Template Library (STL) C++ Data Types Coin Change | DP-7
[ { "code": null, "e": 26799, "s": 26771, "text": "\n15 Nov, 2021" }, { "code": null, "e": 27076, "s": 26799, "text": "Given an integer N, the task is to find any N-digit positive number (except for zeros) such that it is not divisible by any of its digits. If it is not possible to find any such number then print -1.Note: There can be more than one such number for the same N-digit.Examples: " }, { "code": null, "e": 27158, "s": 27076, "text": "Input: N = 2 \nOutput: 23\n23 is not divisible by 2 or 3\n\nInput: N = 3\nOutput: 239" }, { "code": null, "e": 27264, "s": 27160, "text": "Approach: The easiest solution to this problem can be thought of with the help of digits ‘4’ and ‘5’. " }, { "code": null, "e": 27685, "s": 27264, "text": "Since, in order for a number to be divisible by 5, the number must end with 0 or 5; and in order for it to be divisible by 4, the last two digits if the number must be divisible by 4.Therefore, a shortcut method can be applied to prevent both of the divisibility criteria of 4 and as well as of 5, as: To prevent a number from being divisible by 5, the number can contain 5 for every other digit except for last digit. " }, { "code": null, "e": 27869, "s": 27685, "text": "Since, in order for a number to be divisible by 5, the number must end with 0 or 5; and in order for it to be divisible by 4, the last two digits if the number must be divisible by 4." }, { "code": null, "e": 28107, "s": 27869, "text": "Therefore, a shortcut method can be applied to prevent both of the divisibility criteria of 4 and as well as of 5, as: To prevent a number from being divisible by 5, the number can contain 5 for every other digit except for last digit. " }, { "code": null, "e": 28226, "s": 28107, "text": "To prevent a number from being divisible by 5, the number can contain 5 for every other digit except for last digit. " }, { "code": null, "e": 28328, "s": 28226, "text": "Therefore for N digit number,\n(N - 1) digits must be 5 = 5555...(N-1 times)d\nwhere d is the Nth digit" }, { "code": null, "e": 28454, "s": 28330, "text": "To prevent a number from being divisible by 4, the number can contain 5 at the second last digit and 4 at the last digit. " }, { "code": null, "e": 28527, "s": 28454, "text": "Therefore for N digit number,\nLast digit must be 4 = 5555...(N-1 times)4" }, { "code": null, "e": 28580, "s": 28527, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 28584, "s": 28580, "text": "CPP" }, { "code": null, "e": 28589, "s": 28584, "text": "Java" }, { "code": null, "e": 28597, "s": 28589, "text": "Python3" }, { "code": null, "e": 28600, "s": 28597, "text": "C#" }, { "code": null, "e": 28611, "s": 28600, "text": "Javascript" }, { "code": "// CPP program to find N digit number such// that it is not divisible by any of its digits #include <bits/stdc++.h>using namespace std; // Function that print the answervoid findTheNumber(int n){ // if n == 1 then it is // not possible if (n == 1) { cout << \"Impossible\" << endl; return; } // loop to n-1 times for (int i = 0; i < n - 1; i++) { cout << \"5\"; } // print 4 as last digit of // the number cout << \"4\";} // Driver codeint main(){ int n = 12; // Function call findTheNumber(n); return 0;}", "e": 29185, "s": 28611, "text": null }, { "code": "// JAVA program to find N digit number such// that it is not divisible by any of its digitsclass GFG{ // Function that print the answerstatic void findTheNumber(int n){ // if n == 1 then it is // not possible if (n == 1) { System.out.print(\"Impossible\" +\"\\n\"); return; } // loop to n-1 times for (int i = 0; i < n - 1; i++) { System.out.print(\"5\"); } // print 4 as last digit of // the number System.out.print(\"4\");} // Driver codepublic static void main(String[] args){ int n = 12; // Function call findTheNumber(n); }} // This code is contributed by 29AjayKumar", "e": 29825, "s": 29185, "text": null }, { "code": "# Python3 program to find N digit number such# that it is not divisible by any of its digits # Function that print answerdef findTheNumber(n): # if n == 1 then it is # not possible if (n == 1): print(\"Impossible\") return # loop to n-1 times for i in range(n-1): print(\"5\",end=\"\") # print as last digit of # the number print(\"4\") # Driver codeif __name__ == '__main__': n = 12 #Function call findTheNumber(n) # This code is contributed by mohit kumar 29", "e": 30346, "s": 29825, "text": null }, { "code": "// C# program to find N digit number such// that it is not divisible by any of its digitsusing System; class GFG{ // Function that print the answerstatic void findTheNumber(int n){ // if n == 1 then it is // not possible if (n == 1) { Console.Write(\"Impossible\" +\"\\n\"); return; } // loop to n-1 times for (int i = 0; i < n - 1; i++) { Console.Write(\"5\"); } // print 4 as last digit of // the number Console.Write(\"4\");} // Driver codepublic static void Main(String[] args){ int n = 12; // Function call findTheNumber(n);}} // This code is contributed by 29AjayKumar", "e": 30982, "s": 30346, "text": null }, { "code": "<script> // Javascript program to find N digit number such// that it is not divisible by any of its digits // Function that print the answerfunction findTheNumber(n){ // if n == 1 then it is // not possible if (n == 1) { document.write( \"Impossible\" ); return; } // loop to n-1 times for (var i = 0; i < n - 1; i++) { document.write( \"5\"); } // print 4 as last digit of // the number document.write( \"4\");} // Driver codevar n = 12;// Function callfindTheNumber(n); // This code is contributed by rutvik_56.</script>", "e": 31558, "s": 30982, "text": null }, { "code": null, "e": 31571, "s": 31558, "text": "555555555554" }, { "code": null, "e": 31596, "s": 31573, "text": "Time complexity: 0(N) " }, { "code": null, "e": 31611, "s": 31596, "text": "mohit kumar 29" }, { "code": null, "e": 31623, "s": 31611, "text": "29AjayKumar" }, { "code": null, "e": 31633, "s": 31623, "text": "rutvik_56" }, { "code": null, "e": 31650, "s": 31633, "text": "khushboogoyal499" }, { "code": null, "e": 31670, "s": 31650, "text": "Number Divisibility" }, { "code": null, "e": 31684, "s": 31670, "text": "number-digits" }, { "code": null, "e": 31693, "s": 31684, "text": "Analysis" }, { "code": null, "e": 31706, "s": 31693, "text": "Mathematical" }, { "code": null, "e": 31719, "s": 31706, "text": "Mathematical" }, { "code": null, "e": 31817, "s": 31719, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31868, "s": 31817, "text": "Understanding Time Complexity with Simple Examples" }, { "code": null, "e": 31907, "s": 31868, "text": "NP-Completeness | Set 1 (Introduction)" }, { "code": null, "e": 31944, "s": 31907, "text": "Time Complexity and Space Complexity" }, { "code": null, "e": 31966, "s": 31944, "text": "Cyclomatic Complexity" }, { "code": null, "e": 32001, "s": 31966, "text": "Time Complexity of building a heap" }, { "code": null, "e": 32031, "s": 32001, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 32091, "s": 32031, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 32134, "s": 32091, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 32149, "s": 32134, "text": "C++ Data Types" } ]
Number of rows and columns in a Matrix that contain repeated values - GeeksforGeeks
17 May, 2020 Given a N x N square matrix arr[][] which contains only integers between 1 and N, the task is to compute the number of rows and the number of columns in the matrix that contain repeated values. Examples: Input: N = 4, arr[][] = {{1, 2, 3, 4}, {2, 1, 4, 3}, {3, 4, 1, 2}, {4, 3, 2, 1}}Output: 0 0Explanation:None of the rows or columns contain repeated values. Input: N = 4, arr[][]= {{2, 2, 2, 2}, {2, 3, 2, 3}, {2, 2, 2, 3}, {2, 2, 2, 2}}Output: 4 4Explanation:In every column and every row of the square matrix, the values are repeated.Therefore, the total count is 4 for both rows and columns. Approach: The idea is to use the NumPy library. Make a NumPy array of every row and every column in the square matrix. Find the length of the unique elements. If the length is equal to N then, there are no repeated values present in that particular row or column. Below is the implementation of the above approach: # Python program to count the number of # rows and columns in a square matrix # that contain repeated values import numpy as np # Function to count the number of rows# and number of columns that contain # repeated values in a square matrix.def repeated_val(N, matrix): column = 0 row = 0 for i in range (N): # For every row, an array is formed. # The length of the unique elements # is calculated, which if not equal # to 'N' then the row has repeated values. if (len(np.unique(np.array(matrix[i])))!= N): row += 1 # For every column, an array is formed. # The length of the unique elements # is calculated, which if not equal # to N then the column has repeated values. for j in range (N): if (len(np.unique(np.array([m[j] for m in matrix])))!= N): column += 1 # Returning the count of # rows and columns return row, column # Driver codeif __name__ == '__main__': N = 3 matrix = [ [ 2, 1, 3 ], [ 1, 3, 2 ], [ 1, 2, 3 ] ] print(repeated_val(N, matrix)) (0, 2) Python numpy-Matrix Function Matrix Matrix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Efficiently compute sums of diagonals of a matrix Flood fill Algorithm - how to implement fill() in paint? Check for possible path in 2D matrix Zigzag (or diagonal) traversal of Matrix Mathematics | L U Decomposition of a System of Linear Equations Python program to add two Matrices Unique paths in a Grid with Obstacles A Boolean Matrix Question Shortest distance between two cells in a matrix or grid Breadth First Traversal ( BFS ) on a 2D array
[ { "code": null, "e": 26141, "s": 26113, "text": "\n17 May, 2020" }, { "code": null, "e": 26335, "s": 26141, "text": "Given a N x N square matrix arr[][] which contains only integers between 1 and N, the task is to compute the number of rows and the number of columns in the matrix that contain repeated values." }, { "code": null, "e": 26345, "s": 26335, "text": "Examples:" }, { "code": null, "e": 26501, "s": 26345, "text": "Input: N = 4, arr[][] = {{1, 2, 3, 4}, {2, 1, 4, 3}, {3, 4, 1, 2}, {4, 3, 2, 1}}Output: 0 0Explanation:None of the rows or columns contain repeated values." }, { "code": null, "e": 26738, "s": 26501, "text": "Input: N = 4, arr[][]= {{2, 2, 2, 2}, {2, 3, 2, 3}, {2, 2, 2, 3}, {2, 2, 2, 2}}Output: 4 4Explanation:In every column and every row of the square matrix, the values are repeated.Therefore, the total count is 4 for both rows and columns." }, { "code": null, "e": 26786, "s": 26738, "text": "Approach: The idea is to use the NumPy library." }, { "code": null, "e": 26857, "s": 26786, "text": "Make a NumPy array of every row and every column in the square matrix." }, { "code": null, "e": 26897, "s": 26857, "text": "Find the length of the unique elements." }, { "code": null, "e": 27002, "s": 26897, "text": "If the length is equal to N then, there are no repeated values present in that particular row or column." }, { "code": null, "e": 27053, "s": 27002, "text": "Below is the implementation of the above approach:" }, { "code": "# Python program to count the number of # rows and columns in a square matrix # that contain repeated values import numpy as np # Function to count the number of rows# and number of columns that contain # repeated values in a square matrix.def repeated_val(N, matrix): column = 0 row = 0 for i in range (N): # For every row, an array is formed. # The length of the unique elements # is calculated, which if not equal # to 'N' then the row has repeated values. if (len(np.unique(np.array(matrix[i])))!= N): row += 1 # For every column, an array is formed. # The length of the unique elements # is calculated, which if not equal # to N then the column has repeated values. for j in range (N): if (len(np.unique(np.array([m[j] for m in matrix])))!= N): column += 1 # Returning the count of # rows and columns return row, column # Driver codeif __name__ == '__main__': N = 3 matrix = [ [ 2, 1, 3 ], [ 1, 3, 2 ], [ 1, 2, 3 ] ] print(repeated_val(N, matrix)) ", "e": 28138, "s": 27053, "text": null }, { "code": null, "e": 28146, "s": 28138, "text": "(0, 2)\n" }, { "code": null, "e": 28175, "s": 28146, "text": "Python numpy-Matrix Function" }, { "code": null, "e": 28182, "s": 28175, "text": "Matrix" }, { "code": null, "e": 28189, "s": 28182, "text": "Matrix" }, { "code": null, "e": 28287, "s": 28189, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28337, "s": 28287, "text": "Efficiently compute sums of diagonals of a matrix" }, { "code": null, "e": 28394, "s": 28337, "text": "Flood fill Algorithm - how to implement fill() in paint?" }, { "code": null, "e": 28431, "s": 28394, "text": "Check for possible path in 2D matrix" }, { "code": null, "e": 28472, "s": 28431, "text": "Zigzag (or diagonal) traversal of Matrix" }, { "code": null, "e": 28536, "s": 28472, "text": "Mathematics | L U Decomposition of a System of Linear Equations" }, { "code": null, "e": 28571, "s": 28536, "text": "Python program to add two Matrices" }, { "code": null, "e": 28609, "s": 28571, "text": "Unique paths in a Grid with Obstacles" }, { "code": null, "e": 28635, "s": 28609, "text": "A Boolean Matrix Question" }, { "code": null, "e": 28691, "s": 28635, "text": "Shortest distance between two cells in a matrix or grid" } ]
Python String splitlines() Method - GeeksforGeeks
19 Aug, 2021 Python String splitlines() method is used to split the lines at line boundaries. The function returns a list of lines in the string, including the line break(optional). Syntax: string.splitlines([keepends]) Parameters: keepends (optional): When set to True line breaks are included in the resulting list. This can be a number, specifying the position of line break or, can be any Unicode characters, like “\n”, “\r”, “\r\n”, etc as boundaries for strings. Return Value: Returns a list of the lines in the string, breaking at line boundaries. splitlines() splits on the following line boundaries: Representation Description Python3 # Python code to illustrate splitlines()string = "Welcome everyone to\rthe world of Geeks\nGeeksforGeeks" # No parameters has been passedprint (string.splitlines( )) # A specified number is passedprint (string.splitlines(0)) # True has been passed print (string.splitlines(True)) Output: ['Welcome everyone to', 'the world of Geeks', 'GeeksforGeeks'] ['Welcome everyone to', 'the world of Geeks', 'GeeksforGeeks'] ['Welcome everyone to\r', 'the world of Geeks\n', 'GeeksforGeeks'] Python3 # Python code to illustrate splitlines()string = "Cat\nBat\nSat\nMat\nXat\nEat" # No parameters has been passedprint (string.splitlines( )) # splitlines() in one lineprint('India\nJapan\nUSA\nUK\nCanada\n'.splitlines()) Output: ['Cat', 'Bat', 'Sat', 'Mat', 'Xat', 'Eat'] ['India', 'Japan', 'USA', 'UK', 'Canada'] In this code, we will understand how to use the concept of splitlines() to calculate the length of each word in a string. Python3 # Python code to get length of each wordsdef Cal_len(string): # Using splitlines() divide into a list li = string.splitlines() print (li) # Calculate length of each word l = [len(element) for element in li] return l # Driver Code string = "Welcome\rto\rGeeksforGeeks"print(Cal_len(string)) Output: ['Welcome', 'to', 'GeeksforGeeks'] [7, 2, 13] AmiyaRanjanRout Python-Built-in-functions python-string Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe Python Dictionary Read a file line by line in Python Taking input in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe
[ { "code": null, "e": 24719, "s": 24691, "text": "\n19 Aug, 2021" }, { "code": null, "e": 24888, "s": 24719, "text": "Python String splitlines() method is used to split the lines at line boundaries. The function returns a list of lines in the string, including the line break(optional)." }, { "code": null, "e": 24897, "s": 24888, "text": "Syntax: " }, { "code": null, "e": 24927, "s": 24897, "text": "string.splitlines([keepends])" }, { "code": null, "e": 24939, "s": 24927, "text": "Parameters:" }, { "code": null, "e": 25176, "s": 24939, "text": "keepends (optional): When set to True line breaks are included in the resulting list. This can be a number, specifying the position of line break or, can be any Unicode characters, like “\\n”, “\\r”, “\\r\\n”, etc as boundaries for strings." }, { "code": null, "e": 25191, "s": 25176, "text": "Return Value: " }, { "code": null, "e": 25263, "s": 25191, "text": "Returns a list of the lines in the string, breaking at line boundaries." }, { "code": null, "e": 25317, "s": 25263, "text": "splitlines() splits on the following line boundaries:" }, { "code": null, "e": 25332, "s": 25317, "text": "Representation" }, { "code": null, "e": 25344, "s": 25332, "text": "Description" }, { "code": null, "e": 25352, "s": 25344, "text": "Python3" }, { "code": "# Python code to illustrate splitlines()string = \"Welcome everyone to\\rthe world of Geeks\\nGeeksforGeeks\" # No parameters has been passedprint (string.splitlines( )) # A specified number is passedprint (string.splitlines(0)) # True has been passed print (string.splitlines(True))", "e": 25635, "s": 25352, "text": null }, { "code": null, "e": 25644, "s": 25635, "text": "Output: " }, { "code": null, "e": 25837, "s": 25644, "text": "['Welcome everyone to', 'the world of Geeks', 'GeeksforGeeks']\n['Welcome everyone to', 'the world of Geeks', 'GeeksforGeeks']\n['Welcome everyone to\\r', 'the world of Geeks\\n', 'GeeksforGeeks']" }, { "code": null, "e": 25845, "s": 25837, "text": "Python3" }, { "code": "# Python code to illustrate splitlines()string = \"Cat\\nBat\\nSat\\nMat\\nXat\\nEat\" # No parameters has been passedprint (string.splitlines( )) # splitlines() in one lineprint('India\\nJapan\\nUSA\\nUK\\nCanada\\n'.splitlines())", "e": 26067, "s": 25845, "text": null }, { "code": null, "e": 26076, "s": 26067, "text": "Output: " }, { "code": null, "e": 26161, "s": 26076, "text": "['Cat', 'Bat', 'Sat', 'Mat', 'Xat', 'Eat']\n['India', 'Japan', 'USA', 'UK', 'Canada']" }, { "code": null, "e": 26284, "s": 26161, "text": "In this code, we will understand how to use the concept of splitlines() to calculate the length of each word in a string. " }, { "code": null, "e": 26292, "s": 26284, "text": "Python3" }, { "code": "# Python code to get length of each wordsdef Cal_len(string): # Using splitlines() divide into a list li = string.splitlines() print (li) # Calculate length of each word l = [len(element) for element in li] return l # Driver Code string = \"Welcome\\rto\\rGeeksforGeeks\"print(Cal_len(string))", "e": 26616, "s": 26292, "text": null }, { "code": null, "e": 26625, "s": 26616, "text": "Output: " }, { "code": null, "e": 26671, "s": 26625, "text": "['Welcome', 'to', 'GeeksforGeeks']\n[7, 2, 13]" }, { "code": null, "e": 26687, "s": 26671, "text": "AmiyaRanjanRout" }, { "code": null, "e": 26713, "s": 26687, "text": "Python-Built-in-functions" }, { "code": null, "e": 26727, "s": 26713, "text": "python-string" }, { "code": null, "e": 26734, "s": 26727, "text": "Python" }, { "code": null, "e": 26832, "s": 26734, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26860, "s": 26832, "text": "Read JSON file using Python" }, { "code": null, "e": 26910, "s": 26860, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 26932, "s": 26910, "text": "Python map() function" }, { "code": null, "e": 26976, "s": 26932, "text": "How to get column names in Pandas dataframe" }, { "code": null, "e": 26994, "s": 26976, "text": "Python Dictionary" }, { "code": null, "e": 27029, "s": 26994, "text": "Read a file line by line in Python" }, { "code": null, "e": 27052, "s": 27029, "text": "Taking input in Python" }, { "code": null, "e": 27084, "s": 27052, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27106, "s": 27084, "text": "Enumerate() in Python" } ]
DoubleConsumer Interface in Java with Examples - GeeksforGeeks
09 Oct, 2018 The DoubleConsumer Interface is a part of the java.util.function package which has been introduced since Java 8, to implement functional programming in Java. It represents a function which takes in one double-valued argument but does not return any value. The lambda expression assigned to an object of DoubleConsumer type is used to define its accept() which eventually applies the given operation on its only argument. It is similar to using an object of type Consumer<Double> The DoubleConsumer interface consists of the following two functions: This method accepts one value and performs the operation on its only argument. Syntax: void accept(double value) Parameters: This method takes in only one parameter: value– the input argument Returns: This method does not return any value. Below is the code to illustrate accept() method: import java.util.function.DoubleConsumer; public class GFG { public static void main(String args[]) { // Create a DoubleConsimer Instance DoubleConsumer display = a -> System.out.println(a * 10); // using accept() method display.accept(3); }} 30.0 It returns a composed DoubleConsumer wherein the parameterized DoubleConsumer will be executed after the first one. If the evaluation of either operation throws an error, it is relayed to the caller of the composed operation. Note: The operation being passed as the argument should be of type DoubleConsumer . Syntax: default DoubleConsumer andThen(DoubleConsumer after) Parameters: This method accepts a parameter after which is the DoubleConsumer to be applied after the current one. Return Value: This method returns a composed DoubleConsumer that first applies the current operation first and then the after operation. Exception: This method throws NullPointerException if the after operation is null. Below is the code to illustrate andThen() method: Program 1: import java.util.function.DoubleConsumer; public class GFG { public static void main(String args[]) { // Create a DoubleConsimer Instance DoubleConsumer display = a -> System.out.println(a * 10); DoubleConsumer mul = a -> a /= 2; // using addThen() method DoubleConsumer composite = mul.andThen(display); composite.accept(3); }} 30.0 Program 2: To demonstrate when NullPointerException is returned. import java.util.function.DoubleConsumer; public class GFG { public static void main(String args[]) { // Create a DoubleConsimer Instance DoubleConsumer mul = a -> a /= 10; try { // using addThen() method DoubleConsumer composite = mul.andThen(null); composite.accept(3); } catch (Exception e) { System.out.println("Exception : " + e); } }} Exception : java.lang.NullPointerException Program 3: To demonstrate how an Exception in the after function is returned and handled. import java.util.function.DoubleConsumer; public class GFG { public static void main(String args[]) { try { DoubleConsumer conv = a -> System.out.println( Integer .parseInt( Double .toString(a))); DoubleConsumer mul = a -> a /= 10; // using addThen() method DoubleConsumer composite = mul.andThen(conv); composite.accept(3); } catch (Exception e) { System.out.println("Exception : " + e); } }} Exception : java.lang.NumberFormatException: For input string: "3.0" Java - util package Java 8 java-basics java-interfaces Java Java Programs Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Functional Interfaces in Java Stream In Java Constructors in Java Different ways of Reading a text file in Java Exceptions in Java Convert a String to Character array in Java Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class How to Iterate HashMap in Java?
[ { "code": null, "e": 23557, "s": 23529, "text": "\n09 Oct, 2018" }, { "code": null, "e": 23813, "s": 23557, "text": "The DoubleConsumer Interface is a part of the java.util.function package which has been introduced since Java 8, to implement functional programming in Java. It represents a function which takes in one double-valued argument but does not return any value." }, { "code": null, "e": 24036, "s": 23813, "text": "The lambda expression assigned to an object of DoubleConsumer type is used to define its accept() which eventually applies the given operation on its only argument. It is similar to using an object of type Consumer<Double>" }, { "code": null, "e": 24106, "s": 24036, "text": "The DoubleConsumer interface consists of the following two functions:" }, { "code": null, "e": 24185, "s": 24106, "text": "This method accepts one value and performs the operation on its only argument." }, { "code": null, "e": 24193, "s": 24185, "text": "Syntax:" }, { "code": null, "e": 24219, "s": 24193, "text": "void accept(double value)" }, { "code": null, "e": 24272, "s": 24219, "text": "Parameters: This method takes in only one parameter:" }, { "code": null, "e": 24298, "s": 24272, "text": "value– the input argument" }, { "code": null, "e": 24346, "s": 24298, "text": "Returns: This method does not return any value." }, { "code": null, "e": 24395, "s": 24346, "text": "Below is the code to illustrate accept() method:" }, { "code": "import java.util.function.DoubleConsumer; public class GFG { public static void main(String args[]) { // Create a DoubleConsimer Instance DoubleConsumer display = a -> System.out.println(a * 10); // using accept() method display.accept(3); }}", "e": 24702, "s": 24395, "text": null }, { "code": null, "e": 24708, "s": 24702, "text": "30.0\n" }, { "code": null, "e": 24934, "s": 24708, "text": "It returns a composed DoubleConsumer wherein the parameterized DoubleConsumer will be executed after the first one. If the evaluation of either operation throws an error, it is relayed to the caller of the composed operation." }, { "code": null, "e": 25018, "s": 24934, "text": "Note: The operation being passed as the argument should be of type DoubleConsumer ." }, { "code": null, "e": 25026, "s": 25018, "text": "Syntax:" }, { "code": null, "e": 25079, "s": 25026, "text": "default DoubleConsumer andThen(DoubleConsumer after)" }, { "code": null, "e": 25194, "s": 25079, "text": "Parameters: This method accepts a parameter after which is the DoubleConsumer to be applied after the current one." }, { "code": null, "e": 25331, "s": 25194, "text": "Return Value: This method returns a composed DoubleConsumer that first applies the current operation first and then the after operation." }, { "code": null, "e": 25414, "s": 25331, "text": "Exception: This method throws NullPointerException if the after operation is null." }, { "code": null, "e": 25464, "s": 25414, "text": "Below is the code to illustrate andThen() method:" }, { "code": null, "e": 25475, "s": 25464, "text": "Program 1:" }, { "code": "import java.util.function.DoubleConsumer; public class GFG { public static void main(String args[]) { // Create a DoubleConsimer Instance DoubleConsumer display = a -> System.out.println(a * 10); DoubleConsumer mul = a -> a /= 2; // using addThen() method DoubleConsumer composite = mul.andThen(display); composite.accept(3); }}", "e": 25860, "s": 25475, "text": null }, { "code": null, "e": 25866, "s": 25860, "text": "30.0\n" }, { "code": null, "e": 25931, "s": 25866, "text": "Program 2: To demonstrate when NullPointerException is returned." }, { "code": "import java.util.function.DoubleConsumer; public class GFG { public static void main(String args[]) { // Create a DoubleConsimer Instance DoubleConsumer mul = a -> a /= 10; try { // using addThen() method DoubleConsumer composite = mul.andThen(null); composite.accept(3); } catch (Exception e) { System.out.println(\"Exception : \" + e); } }}", "e": 26376, "s": 25931, "text": null }, { "code": null, "e": 26420, "s": 26376, "text": "Exception : java.lang.NullPointerException\n" }, { "code": null, "e": 26510, "s": 26420, "text": "Program 3: To demonstrate how an Exception in the after function is returned and handled." }, { "code": "import java.util.function.DoubleConsumer; public class GFG { public static void main(String args[]) { try { DoubleConsumer conv = a -> System.out.println( Integer .parseInt( Double .toString(a))); DoubleConsumer mul = a -> a /= 10; // using addThen() method DoubleConsumer composite = mul.andThen(conv); composite.accept(3); } catch (Exception e) { System.out.println(\"Exception : \" + e); } }}", "e": 27161, "s": 26510, "text": null }, { "code": null, "e": 27231, "s": 27161, "text": "Exception : java.lang.NumberFormatException: For input string: \"3.0\"\n" }, { "code": null, "e": 27251, "s": 27231, "text": "Java - util package" }, { "code": null, "e": 27258, "s": 27251, "text": "Java 8" }, { "code": null, "e": 27270, "s": 27258, "text": "java-basics" }, { "code": null, "e": 27286, "s": 27270, "text": "java-interfaces" }, { "code": null, "e": 27291, "s": 27286, "text": "Java" }, { "code": null, "e": 27305, "s": 27291, "text": "Java Programs" }, { "code": null, "e": 27310, "s": 27305, "text": "Java" }, { "code": null, "e": 27408, "s": 27310, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27417, "s": 27408, "text": "Comments" }, { "code": null, "e": 27430, "s": 27417, "text": "Old Comments" }, { "code": null, "e": 27460, "s": 27430, "text": "Functional Interfaces in Java" }, { "code": null, "e": 27475, "s": 27460, "text": "Stream In Java" }, { "code": null, "e": 27496, "s": 27475, "text": "Constructors in Java" }, { "code": null, "e": 27542, "s": 27496, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 27561, "s": 27542, "text": "Exceptions in Java" }, { "code": null, "e": 27605, "s": 27561, "text": "Convert a String to Character array in Java" }, { "code": null, "e": 27631, "s": 27605, "text": "Java Programming Examples" }, { "code": null, "e": 27665, "s": 27631, "text": "Convert Double to Integer in Java" }, { "code": null, "e": 27712, "s": 27665, "text": "Implementing a Linked List in Java using Class" } ]
SQL UPDATE Statement
The UPDATE statement is used to modify the existing records in a table. Note: Be careful when updating records in a table! Notice the WHERE clause in the UPDATE statement. The WHERE clause specifies which record(s) that should be updated. If you omit the WHERE clause, all records in the table will be updated! Below is a selection from the "Customers" table in the Northwind sample database: The following SQL statement updates the first customer (CustomerID = 1) with a new contact person and a new city. The selection from the "Customers" table will now look like this: It is the WHERE clause that determines how many records will be updated. The following SQL statement will update the ContactName to "Juan" for all records where country is "Mexico": The selection from the "Customers" table will now look like this: Be careful when updating records. If you omit the WHERE clause, ALL records will be updated! The selection from the "Customers" table will now look like this: Update the City column of all records in the Customers table. Customers City = 'Oslo'; Start the Exercise We just launchedW3Schools videos Get certifiedby completinga course today! If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail: help@w3schools.com Your message has been sent to W3Schools.
[ { "code": null, "e": 72, "s": 0, "text": "The UPDATE statement is used to modify the existing records in a table." }, { "code": null, "e": 313, "s": 72, "text": "Note: Be careful when updating records in a table! Notice the \nWHERE clause in the UPDATE statement.\nThe WHERE clause specifies which record(s) that should be updated. If \nyou omit the WHERE clause, all records in the table will be updated!" }, { "code": null, "e": 396, "s": 313, "text": "Below is a selection from the \"Customers\" table in the Northwind sample \ndatabase:" }, { "code": null, "e": 511, "s": 396, "text": "The following SQL statement updates the first customer (CustomerID = 1) with a new contact person and \na new city." }, { "code": null, "e": 577, "s": 511, "text": "The selection from the \"Customers\" table will now look like this:" }, { "code": null, "e": 650, "s": 577, "text": "It is the WHERE clause that determines how many records will be updated." }, { "code": null, "e": 760, "s": 650, "text": "The following SQL statement will \nupdate the ContactName to \"Juan\" for all records where country is \"Mexico\":" }, { "code": null, "e": 826, "s": 760, "text": "The selection from the \"Customers\" table will now look like this:" }, { "code": null, "e": 921, "s": 826, "text": "Be careful when updating records. If you omit the \nWHERE clause, ALL records \nwill be updated!" }, { "code": null, "e": 987, "s": 921, "text": "The selection from the \"Customers\" table will now look like this:" }, { "code": null, "e": 1049, "s": 987, "text": "Update the City column of all records in the Customers table." }, { "code": null, "e": 1077, "s": 1049, "text": " Customers\n City = 'Oslo';\n" }, { "code": null, "e": 1096, "s": 1077, "text": "Start the Exercise" }, { "code": null, "e": 1129, "s": 1096, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 1171, "s": 1129, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 1278, "s": 1171, "text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:" }, { "code": null, "e": 1297, "s": 1278, "text": "help@w3schools.com" } ]
How to build an MP3 Music Player with Python | by Papa Moryba Kouate | Towards Data Science
In this article, I will show you how you can create your own music player using python. Yes, I know I am a data analyst, but sometimes when I work with data I like listening to music. Data Analysis with music can be a very interesting mix of inspiration and concentration for a data analyst or a data scientist. And building your own music player is an amazing way to learn more about python and its potential. Maybe some modules that I will use in this article could be helpful in the deployment of your next machine learning model. If you follow each step in this article, the final output will be like this! So, let’s get started! The first step is to create a directory called environments where to store all your virtual Environments and install the python modules. In this way the program is available only within the set environment and not throughout my computer. So, open your terminal and create a directory as below. mkdir Environments And be sure to be into the directory ‘Environments’. cd C:\Users\moryb\Environments The second step is to use a module virtualenv to create isolated virtual environments. pip install virtualenv Now, we can create a virtual environment named myenv. If you have installed python 3 you can easily digit: virtualenv myenv Inside the directory myenv there is a copy of Python interpreter, the standard library and the various supporting files. We can activate the environment with the following command: myenv\Scripts\activate.bat out: (myenv) C:\Users\moryb\Environments> Then, we need to install Pygame. Pygame is a module that is used for creating videogames. For creating our MP3 Music Player we will use the sound component. pip install pygame In this second phase, I will use Atom as python editor. So I will import the following modules. import pygame #used to create video gamesimport tkinter as tkr #used to develop GUIfrom tkinter.filedialog import askdirectory #it permit to select dirimport os #it permits to interact with the operating system After we have imported the modules, we need to create the interface and establish the interaction with our operating system. So to create the interface, we will write the following code that permits to create the interface, add the title of the interface and set the dimension of the interface. music_player = tkr.Tk() music_player.title(“Life In Music”) music_player.geometry(“450x350”) Now, it is time to create a directory that prompts the user to choose the folder where the music files are listed. To do that the OS module will help us to create interaction between the interface and our operating system. directory = askdirectory()os.chdir(directory) #it permits to chenge the current dirsong_list = os.listdir() #it returns the list of files song Instead, the following code presents a variable called play_list which brings the interface to display the items to the user. In addition, we create a for loop in order to push the program to select each item from the song_list and insert them into the Listbox. play_list = tkr.Listbox(music_player, font=”Helvetica 12 bold”, bg=”yellow”, selectmode=tkr.SINGLE)for item in song_list: pos = 0 play_list.insert(pos, item) pos += 1 For what concerns loading and playing sounds, we use pygame as below. pygame.init()pygame.mixer.init() In this last part, we will see how to create commands such as play, stop, pause and unpause in order to control the music player. To create these commands we will build some functions and we will use tkinter to create the button in the interface. def play(): pygame.mixer.music.load(play_list.get(tkr.ACTIVE)) var.set(play_list.get(tkr.ACTIVE)) pygame.mixer.music.play()def stop(): pygame.mixer.music.stop()def pause(): pygame.mixer.music.pause()def unpause(): pygame.mixer.music.unpause() Then we can create the buttons for the interface of our music player. Button1 = tkr.Button(music_player, width=5, height=3, font=”Helvetica 12 bold”, text=”PLAY”, command=play, bg=”blue”, fg=”white”)Button2 = tkr.Button(music_player, width=5, height=3, font=”Helvetica 12 bold”, text=”STOP”, command=stop, bg=”red”, fg=”white”)Button3 = tkr.Button(music_player, width=5, height=3, font=”Helvetica 12 bold”, text=”PAUSE”, command=pause, bg=”purple”, fg=”white”)Button4 = tkr.Button(music_player, width=5, height=3, font=”Helvetica 12 bold”, text=”UNPAUSE”, command=unpause, bg=”orange”, fg=”white”) Now, we create some variables that permit us to see the song that is running on the top of the application. var = tkr.StringVar() song_title = tkr.Label(music_player, font=”Helvetica 12 bold”, textvariable=var) With the pack method, we can arrange our button in a horizontal way. The last code music_player.mainloop() helps us to run the application. song_title.pack()Button1.pack(fill=”x”)Button2.pack(fill=”x”)Button3.pack(fill=”x”)Button4.pack(fill=”x”)play_list.pack(fill=”both”, expand=”yes”)music_player.mainloop() Finally, to run the music player, go to your terminal, activate the environment and run the program that we have saved as MyPlayer. C:\Users\moryb\Environments>myenv\Scripts\activate.bat(myenv) C:\Users\moryb\Environments>MyPlayer.py Now, you have your own music player and you can listen to songs when you work with data. Sometimes working with data could be very challenging and having your own mp3 music player is very helpful. In addition, I think that building an mp3 music player or other applications can really help you to know new Python modules and at the same time learn more about Python programming. I always say that the better way to improve your programming skills is building something or automating a process. That permits you to have more confidence with programming and it is very useful for your personal portfolio. All these aspects can become your points of strength as a Data Analyst or Data Scientist. Thanks for reading this. There are some other ways you can keep in touch with me and follow my work: Subscribe to my newsletter. You can also get in touch via my Telegram group, Data Science for Beginners.
[ { "code": null, "e": 260, "s": 172, "text": "In this article, I will show you how you can create your own music player using python." }, { "code": null, "e": 706, "s": 260, "text": "Yes, I know I am a data analyst, but sometimes when I work with data I like listening to music. Data Analysis with music can be a very interesting mix of inspiration and concentration for a data analyst or a data scientist. And building your own music player is an amazing way to learn more about python and its potential. Maybe some modules that I will use in this article could be helpful in the deployment of your next machine learning model." }, { "code": null, "e": 783, "s": 706, "text": "If you follow each step in this article, the final output will be like this!" }, { "code": null, "e": 806, "s": 783, "text": "So, let’s get started!" }, { "code": null, "e": 1044, "s": 806, "text": "The first step is to create a directory called environments where to store all your virtual Environments and install the python modules. In this way the program is available only within the set environment and not throughout my computer." }, { "code": null, "e": 1100, "s": 1044, "text": "So, open your terminal and create a directory as below." }, { "code": null, "e": 1119, "s": 1100, "text": "mkdir Environments" }, { "code": null, "e": 1172, "s": 1119, "text": "And be sure to be into the directory ‘Environments’." }, { "code": null, "e": 1203, "s": 1172, "text": "cd C:\\Users\\moryb\\Environments" }, { "code": null, "e": 1290, "s": 1203, "text": "The second step is to use a module virtualenv to create isolated virtual environments." }, { "code": null, "e": 1313, "s": 1290, "text": "pip install virtualenv" }, { "code": null, "e": 1420, "s": 1313, "text": "Now, we can create a virtual environment named myenv. If you have installed python 3 you can easily digit:" }, { "code": null, "e": 1437, "s": 1420, "text": "virtualenv myenv" }, { "code": null, "e": 1558, "s": 1437, "text": "Inside the directory myenv there is a copy of Python interpreter, the standard library and the various supporting files." }, { "code": null, "e": 1618, "s": 1558, "text": "We can activate the environment with the following command:" }, { "code": null, "e": 1645, "s": 1618, "text": "myenv\\Scripts\\activate.bat" }, { "code": null, "e": 1650, "s": 1645, "text": "out:" }, { "code": null, "e": 1687, "s": 1650, "text": "(myenv) C:\\Users\\moryb\\Environments>" }, { "code": null, "e": 1844, "s": 1687, "text": "Then, we need to install Pygame. Pygame is a module that is used for creating videogames. For creating our MP3 Music Player we will use the sound component." }, { "code": null, "e": 1863, "s": 1844, "text": "pip install pygame" }, { "code": null, "e": 1919, "s": 1863, "text": "In this second phase, I will use Atom as python editor." }, { "code": null, "e": 1959, "s": 1919, "text": "So I will import the following modules." }, { "code": null, "e": 2170, "s": 1959, "text": "import pygame #used to create video gamesimport tkinter as tkr #used to develop GUIfrom tkinter.filedialog import askdirectory #it permit to select dirimport os #it permits to interact with the operating system" }, { "code": null, "e": 2295, "s": 2170, "text": "After we have imported the modules, we need to create the interface and establish the interaction with our operating system." }, { "code": null, "e": 2465, "s": 2295, "text": "So to create the interface, we will write the following code that permits to create the interface, add the title of the interface and set the dimension of the interface." }, { "code": null, "e": 2558, "s": 2465, "text": "music_player = tkr.Tk() music_player.title(“Life In Music”) music_player.geometry(“450x350”)" }, { "code": null, "e": 2781, "s": 2558, "text": "Now, it is time to create a directory that prompts the user to choose the folder where the music files are listed. To do that the OS module will help us to create interaction between the interface and our operating system." }, { "code": null, "e": 2924, "s": 2781, "text": "directory = askdirectory()os.chdir(directory) #it permits to chenge the current dirsong_list = os.listdir() #it returns the list of files song" }, { "code": null, "e": 3186, "s": 2924, "text": "Instead, the following code presents a variable called play_list which brings the interface to display the items to the user. In addition, we create a for loop in order to push the program to select each item from the song_list and insert them into the Listbox." }, { "code": null, "e": 3362, "s": 3186, "text": "play_list = tkr.Listbox(music_player, font=”Helvetica 12 bold”, bg=”yellow”, selectmode=tkr.SINGLE)for item in song_list: pos = 0 play_list.insert(pos, item) pos += 1" }, { "code": null, "e": 3432, "s": 3362, "text": "For what concerns loading and playing sounds, we use pygame as below." }, { "code": null, "e": 3465, "s": 3432, "text": "pygame.init()pygame.mixer.init()" }, { "code": null, "e": 3712, "s": 3465, "text": "In this last part, we will see how to create commands such as play, stop, pause and unpause in order to control the music player. To create these commands we will build some functions and we will use tkinter to create the button in the interface." }, { "code": null, "e": 3973, "s": 3712, "text": "def play(): pygame.mixer.music.load(play_list.get(tkr.ACTIVE)) var.set(play_list.get(tkr.ACTIVE)) pygame.mixer.music.play()def stop(): pygame.mixer.music.stop()def pause(): pygame.mixer.music.pause()def unpause(): pygame.mixer.music.unpause()" }, { "code": null, "e": 4043, "s": 3973, "text": "Then we can create the buttons for the interface of our music player." }, { "code": null, "e": 4571, "s": 4043, "text": "Button1 = tkr.Button(music_player, width=5, height=3, font=”Helvetica 12 bold”, text=”PLAY”, command=play, bg=”blue”, fg=”white”)Button2 = tkr.Button(music_player, width=5, height=3, font=”Helvetica 12 bold”, text=”STOP”, command=stop, bg=”red”, fg=”white”)Button3 = tkr.Button(music_player, width=5, height=3, font=”Helvetica 12 bold”, text=”PAUSE”, command=pause, bg=”purple”, fg=”white”)Button4 = tkr.Button(music_player, width=5, height=3, font=”Helvetica 12 bold”, text=”UNPAUSE”, command=unpause, bg=”orange”, fg=”white”)" }, { "code": null, "e": 4679, "s": 4571, "text": "Now, we create some variables that permit us to see the song that is running on the top of the application." }, { "code": null, "e": 4782, "s": 4679, "text": "var = tkr.StringVar() song_title = tkr.Label(music_player, font=”Helvetica 12 bold”, textvariable=var)" }, { "code": null, "e": 4922, "s": 4782, "text": "With the pack method, we can arrange our button in a horizontal way. The last code music_player.mainloop() helps us to run the application." }, { "code": null, "e": 5092, "s": 4922, "text": "song_title.pack()Button1.pack(fill=”x”)Button2.pack(fill=”x”)Button3.pack(fill=”x”)Button4.pack(fill=”x”)play_list.pack(fill=”both”, expand=”yes”)music_player.mainloop()" }, { "code": null, "e": 5224, "s": 5092, "text": "Finally, to run the music player, go to your terminal, activate the environment and run the program that we have saved as MyPlayer." }, { "code": null, "e": 5326, "s": 5224, "text": "C:\\Users\\moryb\\Environments>myenv\\Scripts\\activate.bat(myenv) C:\\Users\\moryb\\Environments>MyPlayer.py" }, { "code": null, "e": 5523, "s": 5326, "text": "Now, you have your own music player and you can listen to songs when you work with data. Sometimes working with data could be very challenging and having your own mp3 music player is very helpful." }, { "code": null, "e": 5705, "s": 5523, "text": "In addition, I think that building an mp3 music player or other applications can really help you to know new Python modules and at the same time learn more about Python programming." }, { "code": null, "e": 6019, "s": 5705, "text": "I always say that the better way to improve your programming skills is building something or automating a process. That permits you to have more confidence with programming and it is very useful for your personal portfolio. All these aspects can become your points of strength as a Data Analyst or Data Scientist." }, { "code": null, "e": 6120, "s": 6019, "text": "Thanks for reading this. There are some other ways you can keep in touch with me and follow my work:" }, { "code": null, "e": 6148, "s": 6120, "text": "Subscribe to my newsletter." } ]
How to create random sample based on group columns of a data.table in R?
Random sampling helps us to reduce the biasedness in the analysis. If we have data in groups then we might want to find a random sample based on groups. For example, if we have a data frame with a group variable and each group contains ten values then we might want to create a random sample where we will have two values randomly selected from each group. This can be done by using sample function inside .SD Consider the below data.table − library(data.table) Group<-rep(c("A","B","C","D","E"),times=4) Percentage<-sample(1:100,20) dt1<-data.table(Group,Percentage) dt1 Group Percentage 1: A 97 2: B 68 3: C 19 4: D 32 5: E 98 6: A 48 7: B 94 8: C 54 9: D 7 10: E 76 11: A 10 12: B 31 13: C 59 14: D 84 15: E 41 16: A 99 17: B 1 18: C 72 19: D 42 20: E 17 Creating a random sample of size 2 from each group − dt1[,.SD[sample(.N, min(2,.N))],by=Group] Group Percentage 1: A 48 2: A 99 3: B 94 4: B 31 5: C 54 6: C 59 7: D 42 8: D 84 9: E 98 10: E 76 Let’s have a look at another example − Class<-rep(c("First","Second","Third","Fourth"),times=10) Experience<-sample(1:5,40,replace=TRUE) dt2<-data.table(Class,Experience) head(dt2,10) Class Experience 1: First 4 2: Second 2 3: Third 4 4: Fourth 2 5: First 4 6: Second 5 7: Third 3 8: Fourth 5 9: First 3 10: Second 5 tail(dt2,10) Class Experience 1: Third 4 2: Fourth 2 3: First 5 4: Second 2 5: Third 1 6: Fourth 4 7: First 5 8: Second 2 9: Third 4 10: Fourth 4 dt2[,.SD[sample(.N, min(5,.N))],by=Class] Class Experience 1: First 3 2: First 3 3: First 4 4: First 5 5: First 5 6: Second 5 7: Second 2 8: Second 5 9: Second 2 10: Second 1 11: Third 3 12: Third 1 13: Third 4 14: Third 3 15: Third 4 16: Fourth 2 17: Fourth 5 18: Fourth 2 19: Fourth 4 20: Fourth 2
[ { "code": null, "e": 1472, "s": 1062, "text": "Random sampling helps us to reduce the biasedness in the analysis. If we have data in groups then we might want to find a random sample based on groups. For example, if we have a data frame with a group variable and each group contains ten values then we might want to create a random sample where we will have two values randomly selected from each group. This can be done by using sample function inside .SD" }, { "code": null, "e": 1504, "s": 1472, "text": "Consider the below data.table −" }, { "code": null, "e": 1634, "s": 1504, "text": "library(data.table) Group<-rep(c(\"A\",\"B\",\"C\",\"D\",\"E\"),times=4) Percentage<-sample(1:100,20) dt1<-data.table(Group,Percentage) dt1" }, { "code": null, "e": 1931, "s": 1634, "text": " Group Percentage\n1: A 97\n2: B 68\n3: C 19\n4: D 32\n5: E 98\n6: A 48\n7: B 94\n8: C 54\n9: D 7\n10: E 76\n11: A 10\n12: B 31\n13: C 59\n14: D 84\n15: E 41\n16: A 99\n17: B 1\n18: C 72\n19: D 42\n20: E 17" }, { "code": null, "e": 1984, "s": 1931, "text": "Creating a random sample of size 2 from each group −" }, { "code": null, "e": 2026, "s": 1984, "text": "dt1[,.SD[sample(.N, min(2,.N))],by=Group]" }, { "code": null, "e": 2186, "s": 2026, "text": " Group Percentage\n1: A 48\n2: A 99\n3: B 94\n4: B 31\n5: C 54\n6: C 59\n7: D 42\n8: D 84\n9: E 98\n10: E 76" }, { "code": null, "e": 2225, "s": 2186, "text": "Let’s have a look at another example −" }, { "code": null, "e": 2370, "s": 2225, "text": "Class<-rep(c(\"First\",\"Second\",\"Third\",\"Fourth\"),times=10)\nExperience<-sample(1:5,40,replace=TRUE)\ndt2<-data.table(Class,Experience)\nhead(dt2,10)" }, { "code": null, "e": 2532, "s": 2370, "text": " Class Experience\n1: First 4\n2: Second 2\n3: Third 4\n4: Fourth 2\n5: First 4 \n6: Second 5\n7: Third 3\n8: Fourth 5\n9: First 3\n10: Second 5" }, { "code": null, "e": 2545, "s": 2532, "text": "tail(dt2,10)" }, { "code": null, "e": 2705, "s": 2545, "text": " Class Experience\n1: Third 4\n2: Fourth 2\n3: First 5\n4: Second 2\n5: Third 1\n6: Fourth 4\n7: First 5\n8: Second 2\n9: Third 4\n10: Fourth 4" }, { "code": null, "e": 2747, "s": 2705, "text": "dt2[,.SD[sample(.N, min(5,.N))],by=Class]" }, { "code": null, "e": 3046, "s": 2747, "text": " Class Experience\n1: First 3\n2: First 3\n3: First 4\n4: First 5\n5: First 5\n6: Second 5\n7: Second 2\n8: Second 5\n9: Second 2\n10: Second 1\n11: Third 3\n12: Third 1\n13: Third 4\n14: Third 3\n15: Third 4\n16: Fourth 2\n17: Fourth 5\n18: Fourth 2\n19: Fourth 4\n20: Fourth 2" } ]
Waterfall Charts with Plotly. Why & How | by Darío Weitz | Towards Data Science
AKA: Flying Bricks Charts, Floating Bricks Charts, Mario Charts Why: is a 2D plot used to represent the cumulative effects of sequentially added positive or negative values over time or over multiple categorical steps. Over time or time-based waterfall charts represent additions and subtractions over a time period. Categorical steps or category-based waterfall charts represent additions and subtractions over revenues and expenses or any other variable with sequentially positive and negative values. How: waterfall charts (WCs) are made up of a series of vertical bars (columns). Initial and final values are represented by full columns (usually starting at a zero baseline), while intermediate values are shown as floating columns representing the additions and subtractions. The last vertical bar indicates the outcome of such additions and subtractions. Additions are usually represented in green while subtractions are usually shown in red color. Also, it is customary to indicate the initial and final columns with another color. It is recommended to display the idea of cumulative effects by linking the columns with connecting horizontal lines. It should be clear now why they are known as Flying Bricks or Floating Bricks charts. Someone named them Mario Charts because of a certain resemblance to the popular video game. Storytelling: WCs are commonly used in finance and business for data that swings between positive and negative values. Time-based WCs show monthly or yearly total changes while showing profits or losses throughout the month or year. Category-based WCs show the cumulative effects of sequentially added positive or negative values for a given variable. Positive values may be revenues, gains, stock added in warehouses, positive changes, or incoming streams. Negative values may be expenses, losses, stock taken from warehouses, negative changes, or outgoing streams. Always keep in mind that the reading is done sequentially from left to right. A WC is a valuable data visualization technique because it allows the analyst to clearly determine which periods or items showed the greatest gains, when the greatest losses were observed, and what the net change was over the time period evaluated. It provides more contextual information than other similar charts. We used Plotly, an open source graphing library, which provides a group of classes called graph objects for constructing figures. Figure is a primary class with a data attribute and a layout attribute. The data attribute refers to a trace, a particular type of chart with its corresponding parameters. The layout attribute specifies the title, axes, legends, and other properties of the figure. For the waterfall chart in this article, the Plotly trace is go.Waterfall() and the corresponding parameters are: x= to set the x coordinates (usually strings or date time objects); y= to set the y coordinates (usually a list con numerical values, including None); base= to set the numerical baseline. The most important parameter is measure=, an array with one of the following values: relative; absolute; total. relative, the default value, indicates additions or subtractions. absolute sets the initial value while total compute the algebraic sums. So this is the code for the waterfall chart in Figure 1: import plotly.graph_objects as gofig1 = go.Figure()hrz = ["Initial", "Addition 1","Addition 2", "Subtraction 1","Subtraction 2","Final"]vrt = [100, 600, 700, -400, -300, None]fig1.add_trace(go.Waterfall( x = hrz, y = vrt, base = 0, measure = [ "absolute","relative", "relative","relative", "relative","total" ] )) fig1.show() We updated the chart to improve the storytelling: text to set annotations for each bar; textposition to locate the text list inside or outside the bars; update.layout to set the title text and the title font. This is the code for the waterfall chart in Figure 2: import plotly.graph_objects as gofig2 = go.Figure()hrz = [ "Initial", "Addition 1", "Addition 2", "Subtraction 1","Subtraction 2","Final"]vrt = [100, 600, 700, -400, -300, None]text = ['100', '+600', '+700', '-400', '-300', '700']fig2.add_trace(go.Waterfall( x = hrz, y = vrt, base = 0, text = text, textposition = 'inside', measure = ["absolute", "relative", "relative", "relative","relative","total"] )) fig2.update_layout( title_text = "Category-Based Waterfall Chart", title_font=dict(size=25,family='Verdana', color='darkred') )fig2.show() In our second example, we are going to represent with a time-based waterfall chart the cumulative effects of sequentially increasing and decreasing number of monthly visitors to a fictional place. First, we are going to create a dataframe with the data we were supposed to collect about the increase and decrease in the number of visitors. We need to import the libraries Numpy & Pandas as np and pd respectively. import numpy as npimport pandas as pdmonths = ['Initial', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec', 'Final']visitors = [15000, +18000, +12000, -4000, +8000, -10000, -5000, +20000, +15000, +18000, -16000, -18000, +10000, 63000]df = pd.DataFrame({'months' : months, 'visitors' : visitors, 'text' : visitors}) We need to create a column in the dataframe that indicates the values associated with measure. Remember that this parameter can take any of the following three values: absolute; relative; total. To fill the column named measure we used the Numpy method np.select() which returns an array drawn from elements in choicelist, depending on a conditions list. conditionlist = [(df['months'] == 'Initial'), (df['months'] == 'Final'), (df['months'] != 'Initial') & (df['months'] != 'Final')]choicelist = ['absolute', 'total', 'relative']df['measure'] = np.select(conditionlist, choicelist, default='absolute') The screenshot below shows the fourteen records of the dataset: Now we are ready to draw the WC. Plotly allows to customize the colors in the floating bars with increasing, decreasing, and totals. fig3 = go.Figure()fig3.add_trace(go.Waterfall( x = df['months'], y = df['visitors'], measure = df['measure'], base = 0, text = df['visitors'], textposition = 'outside', decreasing = {"marker":{"color":"crimson", "line":{"color":"lightsalmon","width":2}}}, increasing = {"marker":{"color":"forestgreen", "line":{"color":"lightgreen", "width":2}}}, totals = {"marker":{"color":"mediumblue"}} )) We decided to locate the annotations outside the bars to avoid cluttering. Finally we set the title and updated the axes: fig3.update_layout( title_text = "Time-Based Waterfall Chart", title_font = dict(size=25,family='Verdana', color='darkred'))fig3.update_yaxes(title = 'Visitors' , range = [0, 100000])fig3.update_xaxes(title = 'Year 2020')fig3.show() To sum up: the key concept in a Waterfall Chart is to communicate changes in positive and negative values across a time period or across a list of related items. They are very simple to implement, particularly with Plotly. They are widely used in financial analysis and business environments. If you find this article of interest, please read my previous (https://medium.com/@dar.wtz): Diverging Bars, Why & How, Storytelling with Divergences towardsdatascience.com Slope Charts, Why & How, Storytelling with Slopes
[ { "code": null, "e": 236, "s": 172, "text": "AKA: Flying Bricks Charts, Floating Bricks Charts, Mario Charts" }, { "code": null, "e": 676, "s": 236, "text": "Why: is a 2D plot used to represent the cumulative effects of sequentially added positive or negative values over time or over multiple categorical steps. Over time or time-based waterfall charts represent additions and subtractions over a time period. Categorical steps or category-based waterfall charts represent additions and subtractions over revenues and expenses or any other variable with sequentially positive and negative values." }, { "code": null, "e": 1328, "s": 676, "text": "How: waterfall charts (WCs) are made up of a series of vertical bars (columns). Initial and final values are represented by full columns (usually starting at a zero baseline), while intermediate values are shown as floating columns representing the additions and subtractions. The last vertical bar indicates the outcome of such additions and subtractions. Additions are usually represented in green while subtractions are usually shown in red color. Also, it is customary to indicate the initial and final columns with another color. It is recommended to display the idea of cumulative effects by linking the columns with connecting horizontal lines." }, { "code": null, "e": 1506, "s": 1328, "text": "It should be clear now why they are known as Flying Bricks or Floating Bricks charts. Someone named them Mario Charts because of a certain resemblance to the popular video game." }, { "code": null, "e": 2151, "s": 1506, "text": "Storytelling: WCs are commonly used in finance and business for data that swings between positive and negative values. Time-based WCs show monthly or yearly total changes while showing profits or losses throughout the month or year. Category-based WCs show the cumulative effects of sequentially added positive or negative values for a given variable. Positive values may be revenues, gains, stock added in warehouses, positive changes, or incoming streams. Negative values may be expenses, losses, stock taken from warehouses, negative changes, or outgoing streams. Always keep in mind that the reading is done sequentially from left to right." }, { "code": null, "e": 2467, "s": 2151, "text": "A WC is a valuable data visualization technique because it allows the analyst to clearly determine which periods or items showed the greatest gains, when the greatest losses were observed, and what the net change was over the time period evaluated. It provides more contextual information than other similar charts." }, { "code": null, "e": 2862, "s": 2467, "text": "We used Plotly, an open source graphing library, which provides a group of classes called graph objects for constructing figures. Figure is a primary class with a data attribute and a layout attribute. The data attribute refers to a trace, a particular type of chart with its corresponding parameters. The layout attribute specifies the title, axes, legends, and other properties of the figure." }, { "code": null, "e": 3164, "s": 2862, "text": "For the waterfall chart in this article, the Plotly trace is go.Waterfall() and the corresponding parameters are: x= to set the x coordinates (usually strings or date time objects); y= to set the y coordinates (usually a list con numerical values, including None); base= to set the numerical baseline." }, { "code": null, "e": 3414, "s": 3164, "text": "The most important parameter is measure=, an array with one of the following values: relative; absolute; total. relative, the default value, indicates additions or subtractions. absolute sets the initial value while total compute the algebraic sums." }, { "code": null, "e": 3471, "s": 3414, "text": "So this is the code for the waterfall chart in Figure 1:" }, { "code": null, "e": 4005, "s": 3471, "text": "import plotly.graph_objects as gofig1 = go.Figure()hrz = [\"Initial\", \"Addition 1\",\"Addition 2\", \"Subtraction 1\",\"Subtraction 2\",\"Final\"]vrt = [100, 600, 700, -400, -300, None]fig1.add_trace(go.Waterfall( x = hrz, y = vrt, base = 0, measure = [ \"absolute\",\"relative\", \"relative\",\"relative\", \"relative\",\"total\" ] )) fig1.show()" }, { "code": null, "e": 4214, "s": 4005, "text": "We updated the chart to improve the storytelling: text to set annotations for each bar; textposition to locate the text list inside or outside the bars; update.layout to set the title text and the title font." }, { "code": null, "e": 4268, "s": 4214, "text": "This is the code for the waterfall chart in Figure 2:" }, { "code": null, "e": 5025, "s": 4268, "text": "import plotly.graph_objects as gofig2 = go.Figure()hrz = [ \"Initial\", \"Addition 1\", \"Addition 2\", \"Subtraction 1\",\"Subtraction 2\",\"Final\"]vrt = [100, 600, 700, -400, -300, None]text = ['100', '+600', '+700', '-400', '-300', '700']fig2.add_trace(go.Waterfall( x = hrz, y = vrt, base = 0, text = text, textposition = 'inside', measure = [\"absolute\", \"relative\", \"relative\", \"relative\",\"relative\",\"total\"] )) fig2.update_layout( title_text = \"Category-Based Waterfall Chart\", title_font=dict(size=25,family='Verdana', color='darkred') )fig2.show()" }, { "code": null, "e": 5222, "s": 5025, "text": "In our second example, we are going to represent with a time-based waterfall chart the cumulative effects of sequentially increasing and decreasing number of monthly visitors to a fictional place." }, { "code": null, "e": 5439, "s": 5222, "text": "First, we are going to create a dataframe with the data we were supposed to collect about the increase and decrease in the number of visitors. We need to import the libraries Numpy & Pandas as np and pd respectively." }, { "code": null, "e": 5843, "s": 5439, "text": "import numpy as npimport pandas as pdmonths = ['Initial', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec', 'Final']visitors = [15000, +18000, +12000, -4000, +8000, -10000, -5000, +20000, +15000, +18000, -16000, -18000, +10000, 63000]df = pd.DataFrame({'months' : months, 'visitors' : visitors, 'text' : visitors})" }, { "code": null, "e": 6198, "s": 5843, "text": "We need to create a column in the dataframe that indicates the values associated with measure. Remember that this parameter can take any of the following three values: absolute; relative; total. To fill the column named measure we used the Numpy method np.select() which returns an array drawn from elements in choicelist, depending on a conditions list." }, { "code": null, "e": 6500, "s": 6198, "text": "conditionlist = [(df['months'] == 'Initial'), (df['months'] == 'Final'), (df['months'] != 'Initial') & (df['months'] != 'Final')]choicelist = ['absolute', 'total', 'relative']df['measure'] = np.select(conditionlist, choicelist, default='absolute')" }, { "code": null, "e": 6564, "s": 6500, "text": "The screenshot below shows the fourteen records of the dataset:" }, { "code": null, "e": 6597, "s": 6564, "text": "Now we are ready to draw the WC." }, { "code": null, "e": 6697, "s": 6597, "text": "Plotly allows to customize the colors in the floating bars with increasing, decreasing, and totals." }, { "code": null, "e": 7272, "s": 6697, "text": "fig3 = go.Figure()fig3.add_trace(go.Waterfall( x = df['months'], y = df['visitors'], measure = df['measure'], base = 0, text = df['visitors'], textposition = 'outside', decreasing = {\"marker\":{\"color\":\"crimson\", \"line\":{\"color\":\"lightsalmon\",\"width\":2}}}, increasing = {\"marker\":{\"color\":\"forestgreen\", \"line\":{\"color\":\"lightgreen\", \"width\":2}}}, totals = {\"marker\":{\"color\":\"mediumblue\"}} ))" }, { "code": null, "e": 7394, "s": 7272, "text": "We decided to locate the annotations outside the bars to avoid cluttering. Finally we set the title and updated the axes:" }, { "code": null, "e": 7699, "s": 7394, "text": "fig3.update_layout( title_text = \"Time-Based Waterfall Chart\", title_font = dict(size=25,family='Verdana', color='darkred'))fig3.update_yaxes(title = 'Visitors' , range = [0, 100000])fig3.update_xaxes(title = 'Year 2020')fig3.show()" }, { "code": null, "e": 7992, "s": 7699, "text": "To sum up: the key concept in a Waterfall Chart is to communicate changes in positive and negative values across a time period or across a list of related items. They are very simple to implement, particularly with Plotly. They are widely used in financial analysis and business environments." }, { "code": null, "e": 8085, "s": 7992, "text": "If you find this article of interest, please read my previous (https://medium.com/@dar.wtz):" }, { "code": null, "e": 8142, "s": 8085, "text": "Diverging Bars, Why & How, Storytelling with Divergences" }, { "code": null, "e": 8165, "s": 8142, "text": "towardsdatascience.com" } ]
JK Flip Flop and SR Flip Flop - GeeksforGeeks
06 Jul, 2020 Flip-Flop is popularly known as the basic digital memory circuit. It has two states as logic 1(High) and logic 0(low) states. A flip flop is a sequential circuit which consists of a single binary state of information or data. The digital circuit is a flip flop which has two outputs and are of opposite states. It is also known as a Bistable Multivibrator. 1. JK Flip Flop :The JK flip flop diagram below represents the basic structure which consists of Clock (CLK), Clear (CLR), and Preset (PR). Operations in JK Flip-Flop – Case-1:PR = CLR = 0 This condition is in its invalid state. PR = CLR = 0 This condition is in its invalid state. Case-2:PR = 0 and CLR = 1 The PR is activated which means the output in the Q is set to 1. Therefore, the flip flop is in the set state. PR = 0 and CLR = 1 The PR is activated which means the output in the Q is set to 1. Therefore, the flip flop is in the set state. Case-3:PR = 1 and CLR = 0 The CLR is activated which means the output in the Q’ is set to 1. Therefore, the flip flop is in the reset state. PR = 1 and CLR = 0 The CLR is activated which means the output in the Q’ is set to 1. Therefore, the flip flop is in the reset state. Case-4:PR = CLR = 1 In this condition, the flip flop works in its normal way whereas the PR and CLR gets deactivated. PR = CLR = 1 In this condition, the flip flop works in its normal way whereas the PR and CLR gets deactivated. JK Flip-Flop with the representation of Preset and Clear – Truth Table for JK Flip-Flop – Race Around Condition in JK Flip-Flop –When the J and K both are set to 1, the input remains high for a longer duration of time, then the output keeps on toggling. Toggle means switching in the output instantly i.e. Q = 0, Q’ = 1 will immediately change to Q = 1 and Q’ = 0 and this continuation keeps on changing. This change in output leads to Race Around Condition. 2. SR Flip-Flop :In SR flip flop, with the help of Preset and Clear, when the power is switched ON, the state of the circuit keeps on changing, i.e. it is uncertain. It may come to Set (Q = 1) or Reset (Q’ = 0) state. In many applications, it is desired to initially Set or Reset the flip flop. This thing is accomplished by the Preset (PR) and the Clear (CLR). Operations in SR Flip-Flop – Case-1:PR = CLR = 1 The asynchronous inputs are inactive and the flip flop responds freely to the S, R and the CLK inputs in the normal way. PR = CLR = 1 The asynchronous inputs are inactive and the flip flop responds freely to the S, R and the CLK inputs in the normal way. Case-2:PR = 0 and CLR = 1 This is used when the Q is set to 1. PR = 0 and CLR = 1 This is used when the Q is set to 1. Case-3:PR = 1 and CLR = 0 This is used when the Q’ is set to 1. PR = 1 and CLR = 0 This is used when the Q’ is set to 1. Case-4:PR = CLR = 0 This is an invalid state. PR = CLR = 0 This is an invalid state. SR Flip-Flop with the representation of Preset and Clear – Truth Table for SR Flip-Flop – Applications of Flip-Flop : Flipflops are used as a bounce elimination switch.They are used as a serial to parallel and parallel to serial conversion.It is used for counters.It is used for frequency divider and also as a latch. Flipflops are used as a bounce elimination switch. They are used as a serial to parallel and parallel to serial conversion. It is used for counters. It is used for frequency divider and also as a latch. Digital Electronics & Logic Design GATE CS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Analog to Digital Conversion Transmission Impairment in Data Communication Latches in Digital Logic Counter Design using verilog HDL Introduction to memory and memory units Layers of OSI Model ACID Properties in DBMS Types of Operating Systems Normal Forms in DBMS
[ { "code": null, "e": 24380, "s": 24352, "text": "\n06 Jul, 2020" }, { "code": null, "e": 24737, "s": 24380, "text": "Flip-Flop is popularly known as the basic digital memory circuit. It has two states as logic 1(High) and logic 0(low) states. A flip flop is a sequential circuit which consists of a single binary state of information or data. The digital circuit is a flip flop which has two outputs and are of opposite states. It is also known as a Bistable Multivibrator." }, { "code": null, "e": 24877, "s": 24737, "text": "1. JK Flip Flop :The JK flip flop diagram below represents the basic structure which consists of Clock (CLK), Clear (CLR), and Preset (PR)." }, { "code": null, "e": 24906, "s": 24877, "text": "Operations in JK Flip-Flop –" }, { "code": null, "e": 24966, "s": 24906, "text": "Case-1:PR = CLR = 0 This condition is in its invalid state." }, { "code": null, "e": 24980, "s": 24966, "text": "PR = CLR = 0 " }, { "code": null, "e": 25020, "s": 24980, "text": "This condition is in its invalid state." }, { "code": null, "e": 25157, "s": 25020, "text": "Case-2:PR = 0 and CLR = 1 The PR is activated which means the output in the Q is set to 1. Therefore, the flip flop is in the set state." }, { "code": null, "e": 25177, "s": 25157, "text": "PR = 0 and CLR = 1 " }, { "code": null, "e": 25288, "s": 25177, "text": "The PR is activated which means the output in the Q is set to 1. Therefore, the flip flop is in the set state." }, { "code": null, "e": 25429, "s": 25288, "text": "Case-3:PR = 1 and CLR = 0 The CLR is activated which means the output in the Q’ is set to 1. Therefore, the flip flop is in the reset state." }, { "code": null, "e": 25449, "s": 25429, "text": "PR = 1 and CLR = 0 " }, { "code": null, "e": 25564, "s": 25449, "text": "The CLR is activated which means the output in the Q’ is set to 1. Therefore, the flip flop is in the reset state." }, { "code": null, "e": 25682, "s": 25564, "text": "Case-4:PR = CLR = 1 In this condition, the flip flop works in its normal way whereas the PR and CLR gets deactivated." }, { "code": null, "e": 25696, "s": 25682, "text": "PR = CLR = 1 " }, { "code": null, "e": 25794, "s": 25696, "text": "In this condition, the flip flop works in its normal way whereas the PR and CLR gets deactivated." }, { "code": null, "e": 25853, "s": 25794, "text": "JK Flip-Flop with the representation of Preset and Clear –" }, { "code": null, "e": 25884, "s": 25853, "text": "Truth Table for JK Flip-Flop –" }, { "code": null, "e": 26253, "s": 25884, "text": "Race Around Condition in JK Flip-Flop –When the J and K both are set to 1, the input remains high for a longer duration of time, then the output keeps on toggling. Toggle means switching in the output instantly i.e. Q = 0, Q’ = 1 will immediately change to Q = 1 and Q’ = 0 and this continuation keeps on changing. This change in output leads to Race Around Condition." }, { "code": null, "e": 26615, "s": 26253, "text": "2. SR Flip-Flop :In SR flip flop, with the help of Preset and Clear, when the power is switched ON, the state of the circuit keeps on changing, i.e. it is uncertain. It may come to Set (Q = 1) or Reset (Q’ = 0) state. In many applications, it is desired to initially Set or Reset the flip flop. This thing is accomplished by the Preset (PR) and the Clear (CLR)." }, { "code": null, "e": 26644, "s": 26615, "text": "Operations in SR Flip-Flop –" }, { "code": null, "e": 26785, "s": 26644, "text": "Case-1:PR = CLR = 1 The asynchronous inputs are inactive and the flip flop responds freely to the S, R and the CLK inputs in the normal way." }, { "code": null, "e": 26799, "s": 26785, "text": "PR = CLR = 1 " }, { "code": null, "e": 26920, "s": 26799, "text": "The asynchronous inputs are inactive and the flip flop responds freely to the S, R and the CLK inputs in the normal way." }, { "code": null, "e": 26983, "s": 26920, "text": "Case-2:PR = 0 and CLR = 1 This is used when the Q is set to 1." }, { "code": null, "e": 27003, "s": 26983, "text": "PR = 0 and CLR = 1 " }, { "code": null, "e": 27040, "s": 27003, "text": "This is used when the Q is set to 1." }, { "code": null, "e": 27104, "s": 27040, "text": "Case-3:PR = 1 and CLR = 0 This is used when the Q’ is set to 1." }, { "code": null, "e": 27124, "s": 27104, "text": "PR = 1 and CLR = 0 " }, { "code": null, "e": 27162, "s": 27124, "text": "This is used when the Q’ is set to 1." }, { "code": null, "e": 27208, "s": 27162, "text": "Case-4:PR = CLR = 0 This is an invalid state." }, { "code": null, "e": 27222, "s": 27208, "text": "PR = CLR = 0 " }, { "code": null, "e": 27248, "s": 27222, "text": "This is an invalid state." }, { "code": null, "e": 27307, "s": 27248, "text": "SR Flip-Flop with the representation of Preset and Clear –" }, { "code": null, "e": 27338, "s": 27307, "text": "Truth Table for SR Flip-Flop –" }, { "code": null, "e": 27366, "s": 27338, "text": "Applications of Flip-Flop :" }, { "code": null, "e": 27566, "s": 27366, "text": "Flipflops are used as a bounce elimination switch.They are used as a serial to parallel and parallel to serial conversion.It is used for counters.It is used for frequency divider and also as a latch." }, { "code": null, "e": 27617, "s": 27566, "text": "Flipflops are used as a bounce elimination switch." }, { "code": null, "e": 27690, "s": 27617, "text": "They are used as a serial to parallel and parallel to serial conversion." }, { "code": null, "e": 27715, "s": 27690, "text": "It is used for counters." }, { "code": null, "e": 27769, "s": 27715, "text": "It is used for frequency divider and also as a latch." }, { "code": null, "e": 27804, "s": 27769, "text": "Digital Electronics & Logic Design" }, { "code": null, "e": 27812, "s": 27804, "text": "GATE CS" }, { "code": null, "e": 27910, "s": 27812, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27919, "s": 27910, "text": "Comments" }, { "code": null, "e": 27932, "s": 27919, "text": "Old Comments" }, { "code": null, "e": 27961, "s": 27932, "text": "Analog to Digital Conversion" }, { "code": null, "e": 28007, "s": 27961, "text": "Transmission Impairment in Data Communication" }, { "code": null, "e": 28032, "s": 28007, "text": "Latches in Digital Logic" }, { "code": null, "e": 28065, "s": 28032, "text": "Counter Design using verilog HDL" }, { "code": null, "e": 28105, "s": 28065, "text": "Introduction to memory and memory units" }, { "code": null, "e": 28125, "s": 28105, "text": "Layers of OSI Model" }, { "code": null, "e": 28149, "s": 28125, "text": "ACID Properties in DBMS" }, { "code": null, "e": 28176, "s": 28149, "text": "Types of Operating Systems" } ]
Tryit Editor v3.6 - Show Python
f = open("demofile2.txt", "a") f.write("Now the file has more content!") f.close() ​ #open and read the file after the appending: f = open("demofile2.txt", "r")
[ { "code": null, "e": 31, "s": 0, "text": "f = open(\"demofile2.txt\", \"a\")" }, { "code": null, "e": 73, "s": 31, "text": "f.write(\"Now the file has more content!\")" }, { "code": null, "e": 83, "s": 73, "text": "f.close()" }, { "code": null, "e": 85, "s": 83, "text": "​" }, { "code": null, "e": 130, "s": 85, "text": "#open and read the file after the appending:" } ]
How to install Python modules in Cygwin?
While installing cygwin, make sure you install the python/python-setuptools from the list. This will install "easy_install" package. Once you have easy_install, you can use it to install pip. Type the following command: $ easy_install-a.b pip You must replace a.b with your python version which can be 2.7 or 3.4 or whatever else. Now you can use pip to install the module you want. For example, To install the latest version of "SomeProject": $ pip install 'SomeProject' To install a specific version: $ pip install 'SomeProject==1.4' To install greater than or equal to one version and less than another: $ pip install 'SomeProject>=1,<2'
[ { "code": null, "e": 1282, "s": 1062, "text": "While installing cygwin, make sure you install the python/python-setuptools from the list. This will install \"easy_install\" package. Once you have easy_install, you can use it to install pip. Type the following command:" }, { "code": null, "e": 1305, "s": 1282, "text": "$ easy_install-a.b pip" }, { "code": null, "e": 1506, "s": 1305, "text": "You must replace a.b with your python version which can be 2.7 or 3.4 or whatever else. Now you can use pip to install the module you want. For example, To install the latest version of \"SomeProject\":" }, { "code": null, "e": 1534, "s": 1506, "text": "$ pip install 'SomeProject'" }, { "code": null, "e": 1565, "s": 1534, "text": "To install a specific version:" }, { "code": null, "e": 1598, "s": 1565, "text": "$ pip install 'SomeProject==1.4'" }, { "code": null, "e": 1669, "s": 1598, "text": "To install greater than or equal to one version and less than another:" }, { "code": null, "e": 1703, "s": 1669, "text": "$ pip install 'SomeProject>=1,<2'" } ]
Behavior Driven Development - Gherkin
Gherkin is a language, which is used to write Features, Scenarios, and Steps. The purpose of Gherkin is to help us write concrete requirements. To understand what we mean by concrete requirements, consider the following example − Customers should be prevented from entering invalid credit card details. If a customer enters a credit card number that is not exactly 16 digits long, when they try to submit the form, it should be redisplayed with an error message advising them of the correct number of digits. The latter has no ambiguity and avoids errors and is much more testable. Gherkin is designed to create requirements that are more concrete. In Gherkin, the above example looks like − Feature Feedback when entering invalid credit card details Feature Definition In user testing, we have seen many people who make mistakes Documentation Background True for all Scenarios Below Given I have chosen an item to buy, And I am about to enter my credit card number Scenario − Credit card number too shortScenario Definition When I enter a card number that is less than 16 digits long And all the other details are correct And I submit the formSteps Then the form should be redisplayed And I should see a message advising me of the correct number of digits Gherkin files are plain text Files and have the extension .feature. Each line that is not blank has to start with a Gherkin keyword, followed by any text you like. The keywords are − Feature Feature Scenario Scenario Given, When, Then, And, But (Steps) Given, When, Then, And, But (Steps) Background Background Scenario Outline Scenario Outline Examples Examples """ (Doc Strings) """ (Doc Strings) | (Data Tables) | (Data Tables) @ (Tags) @ (Tags) # (Comments) # (Comments) * * The Feature keyword is used to describe a software feature, and to group the related scenarios. A Feature has three basic elements − The keyword – Feature. The keyword – Feature. The name of the feature, provided on the same line as the Feature keyword. The name of the feature, provided on the same line as the Feature keyword. An optional (but highly recommended) description that can span multiple lines i.e. all the text between the line containing the keyword Feature, and a line that starts with Scenario, Background, or Scenario Outline. An optional (but highly recommended) description that can span multiple lines i.e. all the text between the line containing the keyword Feature, and a line that starts with Scenario, Background, or Scenario Outline. In addition to a name and a description, Features contain a list of scenarios or scenario outlines, and an optional background. It is conventional to name a .feature file by taking the name of the Feature, converting it to lowercase and replacing the spaces with underlines. For example, feedback_when_entering_invalid_credit_card_details.feature In order to identify Features in your system, you can use what is known as a “feature injection template”. Some parts of Gherkin documents do not have to start with a keyword. In the lines following a Feature, scenario, scenario outline or examples, you can write anything you like, as long as no line starts with a keyword. This is the way to include Descriptions. To express the behavior of your system, you attach one or more scenarios with each Feature. It is typical to see 5 to 20 scenarios per Feature to completely specify all the behaviors around that Feature. Scenarios follows the following pattern − Describe an initial context Describe an initial context Describe an event Describe an event Describe an expected outcome Describe an expected outcome We start with a context, describe an action, and check the outcome. This is done with steps. Gherkin provides three keywords to describe each of the contexts, actions, and outcomes as steps. Given − Establish context Given − Establish context When − Perform action When − Perform action Then − Check outcome Then − Check outcome These keywords provide readability of the scenario. Example Scenario − Withdraw money from account. Given I have $100 in my account. Given I have $100 in my account. When I request $20. When I request $20. Then $20 should be dispensed. Then $20 should be dispensed. If there are multiple Given or When steps underneath each other, you can use And or But. They allow you to specify scenarios in detail. Example Scenario − Attempt withdrawal using stolen card. Given I have $100 in my account. Given I have $100 in my account. But my card is invalid. But my card is invalid. When I request $50. When I request $50. Then my card should not be returned. Then my card should not be returned. And I should be told to contact the bank. And I should be told to contact the bank. While creating scenarios, remember ‘each scenario must make sense and be able to be executed independently of any other scenario’’. This means − You cannot have the success condition of one scenario depend on the fact that some other scenario was executed before it. You cannot have the success condition of one scenario depend on the fact that some other scenario was executed before it. Each scenario creates its particular context, executes one thing, and tests the result. Each scenario creates its particular context, executes one thing, and tests the result. Such scenarios provide the following benefits − Tests will be simpler and easier to understand. Tests will be simpler and easier to understand. You can run just a subset of your scenarios and you do not have to worry about the breaking of your test set. You can run just a subset of your scenarios and you do not have to worry about the breaking of your test set. Depending on your system, you might be able to run the tests in parallel, reducing the amount of time taken to execute all of your tests. Depending on your system, you might be able to run the tests in parallel, reducing the amount of time taken to execute all of your tests. If you have to write scenarios with several inputs or outputs, you might end up creating several scenarios that only differ by their values. The solution is to use scenario outline. To write a scenario outline, Variables in the scenario outline steps are marked up with < and >. Variables in the scenario outline steps are marked up with < and >. The various values for the variables are given as examples in a table. The various values for the variables are given as examples in a table. Example Suppose you are writing a Feature for adding two numbers on a calculator. Feature − Add. Scenario Outline: Add two numbers. Given the input "<input>" When the calculator is run Then the output should be <output>" Examples | input | output | | 2+2 | 4 | | 98+1 | 99 | | 255+390 | 645 | A scenario outline section is always followed by one or more sections of examples, which are a container for a table. The table must have a header row corresponding to the variables in the scenario outline steps. Each of the rows below will create a new scenario, filling in the variable values 17 Lectures 52 mins Shruti Mantri 8 Lectures 23 mins Ken Burke 8 Lectures 1 hours Matej Sucha 5 Lectures 1 hours Matej Sucha 5 Lectures 1 hours Matej Sucha Print Add Notes Bookmark this page
[ { "code": null, "e": 1876, "s": 1732, "text": "Gherkin is a language, which is used to write Features, Scenarios, and Steps. The purpose of Gherkin is to help us write concrete requirements." }, { "code": null, "e": 1962, "s": 1876, "text": "To understand what we mean by concrete requirements, consider the following example −" }, { "code": null, "e": 2035, "s": 1962, "text": "Customers should be prevented from entering invalid credit card details." }, { "code": null, "e": 2241, "s": 2035, "text": "If a customer enters a credit card number that is not exactly 16 digits long, when they try to submit the form, it should be redisplayed with an error message advising them of the correct number of digits." }, { "code": null, "e": 2314, "s": 2241, "text": "The latter has no ambiguity and avoids errors and is much more testable." }, { "code": null, "e": 2424, "s": 2314, "text": "Gherkin is designed to create requirements that are more concrete. In Gherkin, the above example looks like −" }, { "code": null, "e": 2432, "s": 2424, "text": "Feature" }, { "code": null, "e": 2502, "s": 2432, "text": "Feedback when entering invalid credit card details Feature Definition" }, { "code": null, "e": 2576, "s": 2502, "text": "In user testing, we have seen many people who make mistakes Documentation" }, { "code": null, "e": 2616, "s": 2576, "text": "Background True for all Scenarios Below" }, { "code": null, "e": 2652, "s": 2616, "text": "Given I have chosen an item to buy," }, { "code": null, "e": 2698, "s": 2652, "text": "And I am about to enter my credit card number" }, { "code": null, "e": 2757, "s": 2698, "text": "Scenario − Credit card number too shortScenario Definition" }, { "code": null, "e": 2817, "s": 2757, "text": "When I enter a card number that is less than 16 digits long" }, { "code": null, "e": 2855, "s": 2817, "text": "And all the other details are correct" }, { "code": null, "e": 2882, "s": 2855, "text": "And I submit the formSteps" }, { "code": null, "e": 2918, "s": 2882, "text": "Then the form should be redisplayed" }, { "code": null, "e": 2989, "s": 2918, "text": "And I should see a message advising me of the correct number of digits" }, { "code": null, "e": 3172, "s": 2989, "text": "Gherkin files are plain text Files and have the extension .feature. Each line that is not blank has to start with a Gherkin keyword, followed by any text you like. The keywords are −" }, { "code": null, "e": 3180, "s": 3172, "text": "Feature" }, { "code": null, "e": 3188, "s": 3180, "text": "Feature" }, { "code": null, "e": 3197, "s": 3188, "text": "Scenario" }, { "code": null, "e": 3206, "s": 3197, "text": "Scenario" }, { "code": null, "e": 3242, "s": 3206, "text": "Given, When, Then, And, But (Steps)" }, { "code": null, "e": 3278, "s": 3242, "text": "Given, When, Then, And, But (Steps)" }, { "code": null, "e": 3289, "s": 3278, "text": "Background" }, { "code": null, "e": 3300, "s": 3289, "text": "Background" }, { "code": null, "e": 3317, "s": 3300, "text": "Scenario Outline" }, { "code": null, "e": 3334, "s": 3317, "text": "Scenario Outline" }, { "code": null, "e": 3343, "s": 3334, "text": "Examples" }, { "code": null, "e": 3352, "s": 3343, "text": "Examples" }, { "code": null, "e": 3370, "s": 3352, "text": "\"\"\" (Doc Strings)" }, { "code": null, "e": 3388, "s": 3370, "text": "\"\"\" (Doc Strings)" }, { "code": null, "e": 3404, "s": 3388, "text": "| (Data Tables)" }, { "code": null, "e": 3420, "s": 3404, "text": "| (Data Tables)" }, { "code": null, "e": 3429, "s": 3420, "text": "@ (Tags)" }, { "code": null, "e": 3438, "s": 3429, "text": "@ (Tags)" }, { "code": null, "e": 3451, "s": 3438, "text": "# (Comments)" }, { "code": null, "e": 3464, "s": 3451, "text": "# (Comments)" }, { "code": null, "e": 3466, "s": 3464, "text": "*" }, { "code": null, "e": 3468, "s": 3466, "text": "*" }, { "code": null, "e": 3601, "s": 3468, "text": "The Feature keyword is used to describe a software feature, and to group the related scenarios. A Feature has three basic elements −" }, { "code": null, "e": 3624, "s": 3601, "text": "The keyword – Feature." }, { "code": null, "e": 3647, "s": 3624, "text": "The keyword – Feature." }, { "code": null, "e": 3722, "s": 3647, "text": "The name of the feature, provided on the same line as the Feature keyword." }, { "code": null, "e": 3797, "s": 3722, "text": "The name of the feature, provided on the same line as the Feature keyword." }, { "code": null, "e": 4013, "s": 3797, "text": "An optional (but highly recommended) description that can span multiple lines i.e. all the text between the line containing the keyword Feature, and a line that starts with Scenario, Background, or Scenario Outline." }, { "code": null, "e": 4229, "s": 4013, "text": "An optional (but highly recommended) description that can span multiple lines i.e. all the text between the line containing the keyword Feature, and a line that starts with Scenario, Background, or Scenario Outline." }, { "code": null, "e": 4357, "s": 4229, "text": "In addition to a name and a description, Features contain a list of scenarios or scenario outlines, and an optional background." }, { "code": null, "e": 4517, "s": 4357, "text": "It is conventional to name a .feature file by taking the name of the Feature, converting it to lowercase and replacing the spaces with underlines. For example," }, { "code": null, "e": 4577, "s": 4517, "text": "feedback_when_entering_invalid_credit_card_details.feature\n" }, { "code": null, "e": 4684, "s": 4577, "text": "In order to identify Features in your system, you can use what is known as a “feature injection template”." }, { "code": null, "e": 4753, "s": 4684, "text": "Some parts of Gherkin documents do not have to start with a keyword." }, { "code": null, "e": 4943, "s": 4753, "text": "In the lines following a Feature, scenario, scenario outline or examples, you can write anything you like, as long as no line starts with a keyword. This is the way to include Descriptions." }, { "code": null, "e": 5147, "s": 4943, "text": "To express the behavior of your system, you attach one or more scenarios with each Feature. It is typical to see 5 to 20 scenarios per Feature to completely specify all the behaviors around that Feature." }, { "code": null, "e": 5189, "s": 5147, "text": "Scenarios follows the following pattern −" }, { "code": null, "e": 5217, "s": 5189, "text": "Describe an initial context" }, { "code": null, "e": 5245, "s": 5217, "text": "Describe an initial context" }, { "code": null, "e": 5263, "s": 5245, "text": "Describe an event" }, { "code": null, "e": 5281, "s": 5263, "text": "Describe an event" }, { "code": null, "e": 5310, "s": 5281, "text": "Describe an expected outcome" }, { "code": null, "e": 5339, "s": 5310, "text": "Describe an expected outcome" }, { "code": null, "e": 5530, "s": 5339, "text": "We start with a context, describe an action, and check the outcome. This is done with steps. Gherkin provides three keywords to describe each of the contexts, actions, and outcomes as steps." }, { "code": null, "e": 5556, "s": 5530, "text": "Given − Establish context" }, { "code": null, "e": 5582, "s": 5556, "text": "Given − Establish context" }, { "code": null, "e": 5604, "s": 5582, "text": "When − Perform action" }, { "code": null, "e": 5626, "s": 5604, "text": "When − Perform action" }, { "code": null, "e": 5647, "s": 5626, "text": "Then − Check outcome" }, { "code": null, "e": 5668, "s": 5647, "text": "Then − Check outcome" }, { "code": null, "e": 5720, "s": 5668, "text": "These keywords provide readability of the scenario." }, { "code": null, "e": 5728, "s": 5720, "text": "Example" }, { "code": null, "e": 5768, "s": 5728, "text": "Scenario − Withdraw money from account." }, { "code": null, "e": 5801, "s": 5768, "text": "Given I have $100 in my account." }, { "code": null, "e": 5834, "s": 5801, "text": "Given I have $100 in my account." }, { "code": null, "e": 5854, "s": 5834, "text": "When I request $20." }, { "code": null, "e": 5874, "s": 5854, "text": "When I request $20." }, { "code": null, "e": 5904, "s": 5874, "text": "Then $20 should be dispensed." }, { "code": null, "e": 5934, "s": 5904, "text": "Then $20 should be dispensed." }, { "code": null, "e": 6070, "s": 5934, "text": "If there are multiple Given or When steps underneath each other, you can use And or But. They allow you to specify scenarios in detail." }, { "code": null, "e": 6078, "s": 6070, "text": "Example" }, { "code": null, "e": 6127, "s": 6078, "text": "Scenario − Attempt withdrawal using stolen card." }, { "code": null, "e": 6160, "s": 6127, "text": "Given I have $100 in my account." }, { "code": null, "e": 6193, "s": 6160, "text": "Given I have $100 in my account." }, { "code": null, "e": 6217, "s": 6193, "text": "But my card is invalid." }, { "code": null, "e": 6241, "s": 6217, "text": "But my card is invalid." }, { "code": null, "e": 6261, "s": 6241, "text": "When I request $50." }, { "code": null, "e": 6281, "s": 6261, "text": "When I request $50." }, { "code": null, "e": 6318, "s": 6281, "text": "Then my card should not be returned." }, { "code": null, "e": 6355, "s": 6318, "text": "Then my card should not be returned." }, { "code": null, "e": 6397, "s": 6355, "text": "And I should be told to contact the bank." }, { "code": null, "e": 6439, "s": 6397, "text": "And I should be told to contact the bank." }, { "code": null, "e": 6584, "s": 6439, "text": "While creating scenarios, remember ‘each scenario must make sense and be able to be executed independently of any other scenario’’. This means −" }, { "code": null, "e": 6706, "s": 6584, "text": "You cannot have the success condition of one scenario depend on the fact that some other scenario was executed before it." }, { "code": null, "e": 6828, "s": 6706, "text": "You cannot have the success condition of one scenario depend on the fact that some other scenario was executed before it." }, { "code": null, "e": 6916, "s": 6828, "text": "Each scenario creates its particular context, executes one thing, and tests the result." }, { "code": null, "e": 7004, "s": 6916, "text": "Each scenario creates its particular context, executes one thing, and tests the result." }, { "code": null, "e": 7052, "s": 7004, "text": "Such scenarios provide the following benefits −" }, { "code": null, "e": 7100, "s": 7052, "text": "Tests will be simpler and easier to understand." }, { "code": null, "e": 7148, "s": 7100, "text": "Tests will be simpler and easier to understand." }, { "code": null, "e": 7258, "s": 7148, "text": "You can run just a subset of your scenarios and you do not have to worry about the breaking of your test set." }, { "code": null, "e": 7368, "s": 7258, "text": "You can run just a subset of your scenarios and you do not have to worry about the breaking of your test set." }, { "code": null, "e": 7506, "s": 7368, "text": "Depending on your system, you might be able to run the tests in parallel, reducing the amount of time taken to execute all of your tests." }, { "code": null, "e": 7644, "s": 7506, "text": "Depending on your system, you might be able to run the tests in parallel, reducing the amount of time taken to execute all of your tests." }, { "code": null, "e": 7855, "s": 7644, "text": "If you have to write scenarios with several inputs or outputs, you might end up creating several scenarios that only differ by their values. The solution is to use scenario outline. To write a scenario outline," }, { "code": null, "e": 7923, "s": 7855, "text": "Variables in the scenario outline steps are marked up with < and >." }, { "code": null, "e": 7991, "s": 7923, "text": "Variables in the scenario outline steps are marked up with < and >." }, { "code": null, "e": 8062, "s": 7991, "text": "The various values for the variables are given as examples in a table." }, { "code": null, "e": 8133, "s": 8062, "text": "The various values for the variables are given as examples in a table." }, { "code": null, "e": 8141, "s": 8133, "text": "Example" }, { "code": null, "e": 8215, "s": 8141, "text": "Suppose you are writing a Feature for adding two numbers on a calculator." }, { "code": null, "e": 8230, "s": 8215, "text": "Feature − Add." }, { "code": null, "e": 8453, "s": 8230, "text": "Scenario Outline: Add two numbers.\nGiven the input \"<input>\"\nWhen the calculator is run\nThen the output should be <output>\"\nExamples\n| input | output |\n| 2+2 | 4 | \n| 98+1 | 99 |\n| 255+390 | 645 |\n" }, { "code": null, "e": 8748, "s": 8453, "text": "A scenario outline section is always followed by one or more sections of examples, which are a container for a table. The table must have a header row corresponding to the variables in the scenario outline steps. Each of the rows below will create a new scenario, filling in the variable values" }, { "code": null, "e": 8780, "s": 8748, "text": "\n 17 Lectures \n 52 mins\n" }, { "code": null, "e": 8795, "s": 8780, "text": " Shruti Mantri" }, { "code": null, "e": 8826, "s": 8795, "text": "\n 8 Lectures \n 23 mins\n" }, { "code": null, "e": 8837, "s": 8826, "text": " Ken Burke" }, { "code": null, "e": 8869, "s": 8837, "text": "\n 8 Lectures \n 1 hours \n" }, { "code": null, "e": 8882, "s": 8869, "text": " Matej Sucha" }, { "code": null, "e": 8914, "s": 8882, "text": "\n 5 Lectures \n 1 hours \n" }, { "code": null, "e": 8927, "s": 8914, "text": " Matej Sucha" }, { "code": null, "e": 8959, "s": 8927, "text": "\n 5 Lectures \n 1 hours \n" }, { "code": null, "e": 8972, "s": 8959, "text": " Matej Sucha" }, { "code": null, "e": 8979, "s": 8972, "text": " Print" }, { "code": null, "e": 8990, "s": 8979, "text": " Add Notes" } ]
pthread_equal() in C
The pthread_equal() function is used to check whether two threads are equal or not. This returns 0 or non-zero value. For equal threads, it will return non-zero, otherwise it returns 0. The syntax of this function is like below − int pthread_equal (pthread_t th1, pthread_t th2); Now let us see the pthread_equal() in action. In the first case, we will check the self-thread to check the result. #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include <pthread.h> pthread_t sample_thread; void* my_thread_function(void* p) { if (pthread_equal(sample_thread, pthread_self())) { //pthread_self will return current thread id printf("Threads are equal\n"); } else { printf("Threads are not equal\n"); } } main() { pthread_t th1; sample_thread = th1; //assign the thread th1 to another thread object pthread_create(&th1, NULL, my_thread_function, NULL); //create a thread using my thread function pthread_join(th1, NULL); //wait for joining the thread with the main thread } Threads are equal Now we will see the result, if we compare between two different threads. #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include <pthread.h> pthread_t sample_thread; void* my_thread_function1(void* ptr) { sample_thread = pthread_self(); //assign the id of the thread 1 } void* my_thread_function2(void* p) { if (pthread_equal(sample_thread, pthread_self())) { //pthread_self will return current thread id printf("Threads are equal\n"); } else { printf("Threads are not equal\n"); } } main() { pthread_t th1, th2; pthread_create(&th1, NULL, my_thread_function1, NULL); //create a thread using my_thread_function1 pthread_create(&th1, NULL, my_thread_function2, NULL); //create a thread using my_thread_function2 pthread_join(th1, NULL); //wait for joining the thread with the main thread pthread_join(th2, NULL); } Threads are not equal
[ { "code": null, "e": 1292, "s": 1062, "text": "The pthread_equal() function is used to check whether two threads are equal or not. This returns 0 or non-zero value. For equal threads, it will return non-zero, otherwise it returns 0. The syntax of this function is like below −" }, { "code": null, "e": 1342, "s": 1292, "text": "int pthread_equal (pthread_t th1, pthread_t th2);" }, { "code": null, "e": 1458, "s": 1342, "text": "Now let us see the pthread_equal() in action. In the first case, we will check the self-thread to check the result." }, { "code": null, "e": 2100, "s": 1458, "text": "#include <stdio.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include <sys/types.h>\n#include <pthread.h>\npthread_t sample_thread;\nvoid* my_thread_function(void* p) {\n if (pthread_equal(sample_thread, pthread_self())) { //pthread_self will return current thread id\n printf(\"Threads are equal\\n\");\n } else {\n printf(\"Threads are not equal\\n\");\n }\n}\nmain() {\n pthread_t th1;\n sample_thread = th1; //assign the thread th1 to another thread object\n pthread_create(&th1, NULL, my_thread_function, NULL); //create a thread using my thread function\n pthread_join(th1, NULL); //wait for joining the thread with the main thread\n}" }, { "code": null, "e": 2118, "s": 2100, "text": "Threads are equal" }, { "code": null, "e": 2191, "s": 2118, "text": "Now we will see the result, if we compare between two different threads." }, { "code": null, "e": 3007, "s": 2191, "text": "#include <stdio.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include <sys/types.h>\n#include <pthread.h>\npthread_t sample_thread;\nvoid* my_thread_function1(void* ptr) {\n sample_thread = pthread_self(); //assign the id of the thread 1\n}\nvoid* my_thread_function2(void* p) {\n if (pthread_equal(sample_thread, pthread_self())) { //pthread_self will return current thread id\n printf(\"Threads are equal\\n\");\n } else {\n printf(\"Threads are not equal\\n\");\n }\n}\n\nmain() {\n pthread_t th1, th2;\n pthread_create(&th1, NULL, my_thread_function1, NULL); //create a thread using my_thread_function1\n pthread_create(&th1, NULL, my_thread_function2, NULL); //create a thread using my_thread_function2\n pthread_join(th1, NULL); //wait for joining the thread with the main thread\n pthread_join(th2, NULL);\n}" }, { "code": null, "e": 3029, "s": 3007, "text": "Threads are not equal" } ]
Deep Learning with CIFAR-10. Neural Networks are the programmable... | by Aarya Brahmane | Towards Data Science
Neural Networks are the programmable patterns that helps to solve complex problems and bring the best achievable output. Deep Learning as we all know is a step ahead of Machine Learning, and it helps to train the Neural Networks for getting the solution of questions unanswered and or improving the solution! In this article, we will be implementing a Deep Learning Model using CIFAR-10 dataset. The dataset is commonly used in Deep Learning for testing models of Image Classification. It has 60,000 color images comprising of 10 different classes. The image size is 32x32 and the dataset has 50,000 training images and 10,000 test images. One can find the CIFAR-10 dataset here. Importing Data Deep Learning models require machine with high computational power. It is generally recommended to use online GPUs like that of Kaggle or Google Collaboratory for the same. I have implemented the project on Google Collaboratory. For the project we will be using TensorFlow and matplotlib library. Since the dataset is used globally, one can directly import the dataset from keras module of the TensorFlow library. import tensorflow as tfimport matplotlib.pyplot as pltfrom tensorflow.keras.datasets import cifar10 Pre-Processing the Data The first step of any Machine Learning, Deep Learning or Data Science project is to pre-process the data. We will be defining the names of the classes, over which the dataset is distributed. There are 10 different classes of color images of size 32x32. Once we have set the class name. We need to normalize the image so that our model can train faster. The pixel range of a color image is 0–255. We will be dividing each pixel of the image by 255 so the pixel range will be between 0–1. Actually, we will be dividing it by 255.0 as it is a float operation. For the model, we will be using Convolutional Neural Networks (CNN). # setting class namesclass_names=[‘airplane’,’automobile’,’bird’,’cat’,’deer’,’dog’,’frog’,’horse’,’ship’,’truck’]x_train=x_train/255.0x_train.shapex_test=x_test/255.0x_test.shape In the output of shape we see 4 values e.g. (50000,32,32,3). These 4 values are as follows: the first value, i.e.(50,000/10,000) shows the number of images. The second and third value shows the image size, i.e. image height and width. Here the image size is 32x32. The fourth value shows ‘3’, which shows RGB format, since the images we are using are color images. Building CNN model A CNN model works in three stages. In the first stage, a convolutional layer extracts the features of the image/data. In the second stage a pooling layer reduces the dimensionality of the image, so small changes do not create a big change on the model. Simply saying, it prevents over-fitting. In the third stage a flattening layer transforms our model in one-dimension and feeds it to the fully connected dense layer. This dense layer then performs prediction of image. A good model has multiple layers of convolutional layers and pooling layers. While creating a Neural Network model, there are two generally used APIs: Sequential API and Functional API. Sequential API allows us to create a model layer wise and add it to the sequential Class. The drawback of Sequential API is we cannot use it to create a model where we want to use multiple input sources and get outputs at different location. To overcome this drawback, we use Functional API. By using Functional API we can create multiple input and output model. Though, in most of the cases Sequential API is used. We will be using Sequential API for our CNN model. cifar10_model=tf.keras.models.Sequential()# First Layercifar10_model.add(tf.keras.layers.Conv2D(filters=32,kernel_size=3, padding=”same”, activation=”relu”, input_shape=[32,32,3])) We are using Convolutional Neural Network, so we will be using a convolutional layer. The most common used and the layer we are using is Conv2D. Conv2D means convolution takes place on 2 axis. It extends the convolution to three strata, Red, Green and Blue. The other type of convolutional layer is Conv1D. Conv1D is used generally for “texts”, Conv2D is used generally for “images”. I think most of the reader will be knowing what is convolution and how to do it, still, this video will help one to get clarity on how convolution works in CNN. Parameters of the Conv2D layers The first parameter is “filters”. The number. Value of the filters show the number of filters from which the CNN model and the convolutional layer will learn from. From each such filter, the convolutional layer learn something about the image, like hue, boundary, shape/feature. The value of the parameters should be in the power of 2. The second parameter is “kernel-size”. Kernel means a filter which will move through the image and extract features of the part using a dot product. Kernel-size means the dimension (height x width) of that filter. The value of the kernel size if generally an odd number e.g. 3,5,7.. etc. Here we have used kernel-size of 3, which means the filter size is of 3 x 3. The next parameter is “padding”. There are two types of padding, SAME & VALID. In VALID padding, there is no padding of zeros on the boundary of the image. So that when convolution takes place, there is loss of data, as some features can not be convolved. In the SAME padding, there is a layer of zeros padded on all the boundary of image, so there is no loss of data. Moreover, the dimension of the output of the image after convolution is same as the input of the image. Aforementioned is the reason behind the nomenclature of this padding as SAME. Since in the initial layers we can not lose data, we have used SAME padding. The reason behind using Deep Learning models is to solve complex functionalities. For getting a better output, we need to fit the model in ways too complex, so we need to use functions which can solve the non-linear complexity of the model. This is done by using an activation layer. In any deep learning model, one needs a minimum of one layer with activation function. The work of activation function, is to add non-linearity to the model. If we do not add this layer, the model will be a simple linear regression model and would not achieve the desired results, as it is unable to fit the non-linear part. There are 4 famous activation functions: ) Sigmoid function: The value range is between 0 to 1. The graph is a steep graph, so even a small change can bring a big difference. It is mainly used for binary classification, as demarcation can be easily done as value above or below 0.5. ) Sigmoid function: The value range is between 0 to 1. The graph is a steep graph, so even a small change can bring a big difference. It is mainly used for binary classification, as demarcation can be easily done as value above or below 0.5. 2. ) TanH function: It is abbreviation of Tangent Hyperbolic function. It is a derived function of Sigmoid function. The mathematics behind these activation function is out of the scope of this article, so I would not jump there. The range of the value is between -1 to 1. 3. ) ReLu function: It is the abbreviation of Rectified Linear Unit. It is the most famous activation of deep learning. It is famous because it is easier to compute since the mathematical function is easier and simple than other activation functions. 4. ) SoftMax function: SoftMax function is more elucidated form of Sigmoid function. It is used for multi-class classification. The function calculates the probabilities of a particular class in a function. Thus the output value range of the function is between 0 to 1. The primary difference between Sigmoid function and SoftMax function is, Sigmoid function can be used for binary classification while the SoftMax function can be used for Multi-Class Classification also. Pooling layer #MaxPoolingLayercifar10_model.add(tf.keras.layers.MaxPool2D(pool_size=2,strides=2, padding=’valid’)) Pooling layer is used to reduce the size of the image along with keeping the important parameters in role. Thus it helps to reduce the computation in the model. While performing Convolution, the convolutional layer keeps information about the exact position of feature. And thus not-so-important features are also located perfectly. As a result of which we get a problem that even a small change in pixel or feature may lead to a big change in the output of the model. By Max Pooling we narrow down the scope and of all the features, the most important features are only taken into account. Thus the aforementioned problem is solved. Pooling is done in two ways Average Pooling or Max Pooling. Max Pooling is generally used. In Average Pooling, the average value from the pool size is taken. In Max Pooling, the max value from the pool size is taken. The concept will be cleared from the images above and below. Pool Size means the size of filter of which the max value will be taken. The pool size here 2 means, a pool of 2x2 will be used and in that 2x2 pool, the average/max value will become the output. The pool will traverse across the image. It will move according to the value of strides. Strides means how much jump the pool size will make. If the stride is 1, the 2x2 pool will move in right direction gradually from one column to other column. I have used the stride 2, which mean the pool size will shift two columns at a time. The images I have used ahead to explain Max Pooling and Average pooling have a pool size of 2 and strides = 2. In Pooling we use the padding “Valid”, because we are ready to loose some information. As the function of Pooling is to reduce the spatial dimension of the image and reduce computation in the model. Last Layers # Flattening Layercifar10_model.add(tf.keras.layers.Flatten()) Flattening Layer is added after the stack of convolutional layers and pooling layers. Flattening layer converts the 3d image vector into 1d. Because after the stack of layers, mentioned before, a final fully connected Dense layer is added. Now the Dense layer requires the data to be passed in 1dimension, so flattening layer is quintessential. After flattening layer, there is a Dense layer. Dense layer is a fully connected layer and feeds all output from the previous functioning to all the neurons. Dense layer has a weight W, a bias of B and the activation which is passed to each element. Speaking in a lucid way, it connects all the dots. This layer uses all the features extracted before and does the work of training the model. The units mentioned shows the number of neurons the model is going to use. # Droput Layercifar10_model.add(Dropout(0.2))# Adding the first fully connected layercifar10_model.add(tf.keras.layers.Dense(units= 128,activation='relu’)) Now to prevent overfitting, a dropout layer is added. During training of data, some neurons are disabled randomly. The value passed to neurons mean what fraction of neuron one wants to drop during an iteration. Thus after training, the neurons are not affected highly by the weights of other neurons. As a result of which the the model can generalize better. Output Layer In the output, the layer uses the number of units as per the number of classes in the dataset. Here we are using 10, as there are 10 units. In the output we use SOFTMAX activation as it gives the probabilities of each class. While compiling the model, we need to take into account the loss function. There are two loss functions used generally, Sparse Categorical Cross-Entropy(scce) and Categorical Cross-Entropy(cce). Sparse Categorical Cross-Entropy(scce) is used when the classes are mutually exclusive, the classes are totally distinct then this is used. Categorical Cross-Entropy is used when a label or part can have multiple classes. In out scenario the classes are totally distinctive so we are using Sparse Categorical Cross-Entropy. We will be using the generally used Adam Optimizer. Adam is an abbreviation for “Adaptive Learning rate Method”. This optimizer uses the initial of the gradient to adapt to the learning rate. Adam is now used instead of the stochastic gradient descent, which is used in ML, because it can update the weights after each iteration. The final output after playing a bit with epochs was: Using the model I was able to get an accuracy of 78%. So, in this article we go through working of Deep Learning project using Google Collaboratory. We understand about the parameters used in Convolutional Layer and Pooling layer of Convolutional Neural Network. After extracting features in a CNN, we need a dense layer and a dropout to implement this features in recognizing the images. Finally we see a bit about the loss functions and Adam optimizer. You can find the complete code in my git repository: https://github.com/aaryaab/CIFAR-10-Image-Classification. Feel free to connect with me at : https://www.linkedin.com/in/aarya-brahmane-4b6986128/ References: One can find and make some interesting graphs at : https://www.mathsisfun.com/data/function-grapher.php#functions Graphical Images are made by me on Power point. Happy Deep Learning!
[ { "code": null, "e": 481, "s": 172, "text": "Neural Networks are the programmable patterns that helps to solve complex problems and bring the best achievable output. Deep Learning as we all know is a step ahead of Machine Learning, and it helps to train the Neural Networks for getting the solution of questions unanswered and or improving the solution!" }, { "code": null, "e": 852, "s": 481, "text": "In this article, we will be implementing a Deep Learning Model using CIFAR-10 dataset. The dataset is commonly used in Deep Learning for testing models of Image Classification. It has 60,000 color images comprising of 10 different classes. The image size is 32x32 and the dataset has 50,000 training images and 10,000 test images. One can find the CIFAR-10 dataset here." }, { "code": null, "e": 867, "s": 852, "text": "Importing Data" }, { "code": null, "e": 1281, "s": 867, "text": "Deep Learning models require machine with high computational power. It is generally recommended to use online GPUs like that of Kaggle or Google Collaboratory for the same. I have implemented the project on Google Collaboratory. For the project we will be using TensorFlow and matplotlib library. Since the dataset is used globally, one can directly import the dataset from keras module of the TensorFlow library." }, { "code": null, "e": 1382, "s": 1281, "text": "import tensorflow as tfimport matplotlib.pyplot as pltfrom tensorflow.keras.datasets import cifar10 " }, { "code": null, "e": 1406, "s": 1382, "text": "Pre-Processing the Data" }, { "code": null, "e": 2032, "s": 1406, "text": "The first step of any Machine Learning, Deep Learning or Data Science project is to pre-process the data. We will be defining the names of the classes, over which the dataset is distributed. There are 10 different classes of color images of size 32x32. Once we have set the class name. We need to normalize the image so that our model can train faster. The pixel range of a color image is 0–255. We will be dividing each pixel of the image by 255 so the pixel range will be between 0–1. Actually, we will be dividing it by 255.0 as it is a float operation. For the model, we will be using Convolutional Neural Networks (CNN)." }, { "code": null, "e": 2212, "s": 2032, "text": "# setting class namesclass_names=[‘airplane’,’automobile’,’bird’,’cat’,’deer’,’dog’,’frog’,’horse’,’ship’,’truck’]x_train=x_train/255.0x_train.shapex_test=x_test/255.0x_test.shape" }, { "code": null, "e": 2577, "s": 2212, "text": "In the output of shape we see 4 values e.g. (50000,32,32,3). These 4 values are as follows: the first value, i.e.(50,000/10,000) shows the number of images. The second and third value shows the image size, i.e. image height and width. Here the image size is 32x32. The fourth value shows ‘3’, which shows RGB format, since the images we are using are color images." }, { "code": null, "e": 2596, "s": 2577, "text": "Building CNN model" }, { "code": null, "e": 3144, "s": 2596, "text": "A CNN model works in three stages. In the first stage, a convolutional layer extracts the features of the image/data. In the second stage a pooling layer reduces the dimensionality of the image, so small changes do not create a big change on the model. Simply saying, it prevents over-fitting. In the third stage a flattening layer transforms our model in one-dimension and feeds it to the fully connected dense layer. This dense layer then performs prediction of image. A good model has multiple layers of convolutional layers and pooling layers." }, { "code": null, "e": 3720, "s": 3144, "text": "While creating a Neural Network model, there are two generally used APIs: Sequential API and Functional API. Sequential API allows us to create a model layer wise and add it to the sequential Class. The drawback of Sequential API is we cannot use it to create a model where we want to use multiple input sources and get outputs at different location. To overcome this drawback, we use Functional API. By using Functional API we can create multiple input and output model. Though, in most of the cases Sequential API is used. We will be using Sequential API for our CNN model." }, { "code": null, "e": 3901, "s": 3720, "text": "cifar10_model=tf.keras.models.Sequential()# First Layercifar10_model.add(tf.keras.layers.Conv2D(filters=32,kernel_size=3, padding=”same”, activation=”relu”, input_shape=[32,32,3]))" }, { "code": null, "e": 4446, "s": 3901, "text": "We are using Convolutional Neural Network, so we will be using a convolutional layer. The most common used and the layer we are using is Conv2D. Conv2D means convolution takes place on 2 axis. It extends the convolution to three strata, Red, Green and Blue. The other type of convolutional layer is Conv1D. Conv1D is used generally for “texts”, Conv2D is used generally for “images”. I think most of the reader will be knowing what is convolution and how to do it, still, this video will help one to get clarity on how convolution works in CNN." }, { "code": null, "e": 4478, "s": 4446, "text": "Parameters of the Conv2D layers" }, { "code": null, "e": 4814, "s": 4478, "text": "The first parameter is “filters”. The number. Value of the filters show the number of filters from which the CNN model and the convolutional layer will learn from. From each such filter, the convolutional layer learn something about the image, like hue, boundary, shape/feature. The value of the parameters should be in the power of 2." }, { "code": null, "e": 5179, "s": 4814, "text": "The second parameter is “kernel-size”. Kernel means a filter which will move through the image and extract features of the part using a dot product. Kernel-size means the dimension (height x width) of that filter. The value of the kernel size if generally an odd number e.g. 3,5,7.. etc. Here we have used kernel-size of 3, which means the filter size is of 3 x 3." }, { "code": null, "e": 5807, "s": 5179, "text": "The next parameter is “padding”. There are two types of padding, SAME & VALID. In VALID padding, there is no padding of zeros on the boundary of the image. So that when convolution takes place, there is loss of data, as some features can not be convolved. In the SAME padding, there is a layer of zeros padded on all the boundary of image, so there is no loss of data. Moreover, the dimension of the output of the image after convolution is same as the input of the image. Aforementioned is the reason behind the nomenclature of this padding as SAME. Since in the initial layers we can not lose data, we have used SAME padding." }, { "code": null, "e": 6416, "s": 5807, "text": "The reason behind using Deep Learning models is to solve complex functionalities. For getting a better output, we need to fit the model in ways too complex, so we need to use functions which can solve the non-linear complexity of the model. This is done by using an activation layer. In any deep learning model, one needs a minimum of one layer with activation function. The work of activation function, is to add non-linearity to the model. If we do not add this layer, the model will be a simple linear regression model and would not achieve the desired results, as it is unable to fit the non-linear part." }, { "code": null, "e": 6457, "s": 6416, "text": "There are 4 famous activation functions:" }, { "code": null, "e": 6699, "s": 6457, "text": ") Sigmoid function: The value range is between 0 to 1. The graph is a steep graph, so even a small change can bring a big difference. It is mainly used for binary classification, as demarcation can be easily done as value above or below 0.5." }, { "code": null, "e": 6941, "s": 6699, "text": ") Sigmoid function: The value range is between 0 to 1. The graph is a steep graph, so even a small change can bring a big difference. It is mainly used for binary classification, as demarcation can be easily done as value above or below 0.5." }, { "code": null, "e": 7214, "s": 6941, "text": "2. ) TanH function: It is abbreviation of Tangent Hyperbolic function. It is a derived function of Sigmoid function. The mathematics behind these activation function is out of the scope of this article, so I would not jump there. The range of the value is between -1 to 1." }, { "code": null, "e": 7465, "s": 7214, "text": "3. ) ReLu function: It is the abbreviation of Rectified Linear Unit. It is the most famous activation of deep learning. It is famous because it is easier to compute since the mathematical function is easier and simple than other activation functions." }, { "code": null, "e": 7939, "s": 7465, "text": "4. ) SoftMax function: SoftMax function is more elucidated form of Sigmoid function. It is used for multi-class classification. The function calculates the probabilities of a particular class in a function. Thus the output value range of the function is between 0 to 1. The primary difference between Sigmoid function and SoftMax function is, Sigmoid function can be used for binary classification while the SoftMax function can be used for Multi-Class Classification also." }, { "code": null, "e": 7953, "s": 7939, "text": "Pooling layer" }, { "code": null, "e": 8054, "s": 7953, "text": "#MaxPoolingLayercifar10_model.add(tf.keras.layers.MaxPool2D(pool_size=2,strides=2, padding=’valid’))" }, { "code": null, "e": 8779, "s": 8054, "text": "Pooling layer is used to reduce the size of the image along with keeping the important parameters in role. Thus it helps to reduce the computation in the model. While performing Convolution, the convolutional layer keeps information about the exact position of feature. And thus not-so-important features are also located perfectly. As a result of which we get a problem that even a small change in pixel or feature may lead to a big change in the output of the model. By Max Pooling we narrow down the scope and of all the features, the most important features are only taken into account. Thus the aforementioned problem is solved. Pooling is done in two ways Average Pooling or Max Pooling. Max Pooling is generally used." }, { "code": null, "e": 8966, "s": 8779, "text": "In Average Pooling, the average value from the pool size is taken. In Max Pooling, the max value from the pool size is taken. The concept will be cleared from the images above and below." }, { "code": null, "e": 9251, "s": 8966, "text": "Pool Size means the size of filter of which the max value will be taken. The pool size here 2 means, a pool of 2x2 will be used and in that 2x2 pool, the average/max value will become the output. The pool will traverse across the image. It will move according to the value of strides." }, { "code": null, "e": 9605, "s": 9251, "text": "Strides means how much jump the pool size will make. If the stride is 1, the 2x2 pool will move in right direction gradually from one column to other column. I have used the stride 2, which mean the pool size will shift two columns at a time. The images I have used ahead to explain Max Pooling and Average pooling have a pool size of 2 and strides = 2." }, { "code": null, "e": 9804, "s": 9605, "text": "In Pooling we use the padding “Valid”, because we are ready to loose some information. As the function of Pooling is to reduce the spatial dimension of the image and reduce computation in the model." }, { "code": null, "e": 9816, "s": 9804, "text": "Last Layers" }, { "code": null, "e": 9879, "s": 9816, "text": "# Flattening Layercifar10_model.add(tf.keras.layers.Flatten())" }, { "code": null, "e": 10224, "s": 9879, "text": "Flattening Layer is added after the stack of convolutional layers and pooling layers. Flattening layer converts the 3d image vector into 1d. Because after the stack of layers, mentioned before, a final fully connected Dense layer is added. Now the Dense layer requires the data to be passed in 1dimension, so flattening layer is quintessential." }, { "code": null, "e": 10691, "s": 10224, "text": "After flattening layer, there is a Dense layer. Dense layer is a fully connected layer and feeds all output from the previous functioning to all the neurons. Dense layer has a weight W, a bias of B and the activation which is passed to each element. Speaking in a lucid way, it connects all the dots. This layer uses all the features extracted before and does the work of training the model. The units mentioned shows the number of neurons the model is going to use." }, { "code": null, "e": 10847, "s": 10691, "text": "# Droput Layercifar10_model.add(Dropout(0.2))# Adding the first fully connected layercifar10_model.add(tf.keras.layers.Dense(units= 128,activation='relu’))" }, { "code": null, "e": 11206, "s": 10847, "text": "Now to prevent overfitting, a dropout layer is added. During training of data, some neurons are disabled randomly. The value passed to neurons mean what fraction of neuron one wants to drop during an iteration. Thus after training, the neurons are not affected highly by the weights of other neurons. As a result of which the the model can generalize better." }, { "code": null, "e": 11219, "s": 11206, "text": "Output Layer" }, { "code": null, "e": 11444, "s": 11219, "text": "In the output, the layer uses the number of units as per the number of classes in the dataset. Here we are using 10, as there are 10 units. In the output we use SOFTMAX activation as it gives the probabilities of each class." }, { "code": null, "e": 11963, "s": 11444, "text": "While compiling the model, we need to take into account the loss function. There are two loss functions used generally, Sparse Categorical Cross-Entropy(scce) and Categorical Cross-Entropy(cce). Sparse Categorical Cross-Entropy(scce) is used when the classes are mutually exclusive, the classes are totally distinct then this is used. Categorical Cross-Entropy is used when a label or part can have multiple classes. In out scenario the classes are totally distinctive so we are using Sparse Categorical Cross-Entropy." }, { "code": null, "e": 12293, "s": 11963, "text": "We will be using the generally used Adam Optimizer. Adam is an abbreviation for “Adaptive Learning rate Method”. This optimizer uses the initial of the gradient to adapt to the learning rate. Adam is now used instead of the stochastic gradient descent, which is used in ML, because it can update the weights after each iteration." }, { "code": null, "e": 12347, "s": 12293, "text": "The final output after playing a bit with epochs was:" }, { "code": null, "e": 12802, "s": 12347, "text": "Using the model I was able to get an accuracy of 78%. So, in this article we go through working of Deep Learning project using Google Collaboratory. We understand about the parameters used in Convolutional Layer and Pooling layer of Convolutional Neural Network. After extracting features in a CNN, we need a dense layer and a dropout to implement this features in recognizing the images. Finally we see a bit about the loss functions and Adam optimizer." }, { "code": null, "e": 12913, "s": 12802, "text": "You can find the complete code in my git repository: https://github.com/aaryaab/CIFAR-10-Image-Classification." }, { "code": null, "e": 13001, "s": 12913, "text": "Feel free to connect with me at : https://www.linkedin.com/in/aarya-brahmane-4b6986128/" }, { "code": null, "e": 13127, "s": 13001, "text": "References: One can find and make some interesting graphs at : https://www.mathsisfun.com/data/function-grapher.php#functions" }, { "code": null, "e": 13175, "s": 13127, "text": "Graphical Images are made by me on Power point." } ]
Zero-Inflated Regression. Teach your regressor how to output... | by Dr. Robert Kübler | Towards Data Science
When working on regression problems, often you have target values that are continuously and evenly distributed in some range. Let me illustrate what I mean by this. Consider the following dataset 2-dimensional dataset: In this case, the target values are all scattered in the range from about -300 to 400. Applying linear regression, we end up with the following model: Nothing new, nothing fancy. However, there are datasets that have an unusually high amount of zero targets in them. This is what we call a zero-inflated dataset. Examples of such behavior are datasets with the target being the count of rare events. This includes the amount of defects in manufacturing, tornados or other natural disasters in a given date and place, or crimes in some neighborhoods. The common pattern is that usually, nothing bad happens, i.e. the target is zero. But occasionally, for example when a manufacturing machine malfunctions for some hours, the count skyrockets. In this case, the model actually has to predict something different from zero. Many models can get distracted by such behavior, among them linear regression, support vector machines, and also neural networks. The chance that one of these models outputs a zero is quite small. As an example, take a simple linear regression with one feature as depicted above. The output of the algorithm is a line that takes a value of zero exactly one time. The problem persists in higher dimensions, too. Or recall that neural networks can be expressed as a complex, nested formula — if you plug in random numbers, the chance is high that you won’t receive a zero as output. But instead of talking about hypothetical scenarios, let us visualize the problem with a toy dataset. This dataset consists of two columns: the feature Age of a person and the target Salary from working of this person. In this made-up dataset, we can see that children and teens do not earn a salary. Starting at some age, money-making begins. People gain more experience and hence the salary increases with age. In the end, people retire and don’t earn a salary anymore. The story of life. It is immediately clear that a simple linear regression will not work well here. Let’s do it anyway. 😎 Not a great fit. A line cannot capture all the variation in the data, but notice that if we would fit a line to the data between the ages of approximately 20 and 70, the fit in this interval would be great. But this solves only part of the problem. We want a general-purpose model which is also able to make predictions for young and old people. Besides tree-based methods, let us take a look at a simple, yet effective approach to solve this problem. We will now define an estimator that solves the problems related to zero-inflated datasets. Afterward, we use an already implemented version of it on our salary dataset. The idea is quite simple. Consider the following two-step approach: Train a classifier C that tells us whether the regression output is zero, or not.Train a regressor R on the part of the data with a non-zero target. Train a classifier C that tells us whether the regression output is zero, or not. Train a regressor R on the part of the data with a non-zero target. If a data point goes into the model, the classifier first checks if the output should be zero. If yes, output zero. Otherwise, output the result of the regressor for this data point. This is what we call a meta-model, i.e. a model that consists of other models. The great thing is that you can plug in any classifier and regressor you like. Let’s get back to our salary dataset. We see that the classifier has to capture the zero targets on both ends of the age axis. A simple logistic regression cannot do this (think about why!), but an SVM classifier with an RBF kernel might be sufficient. The problem is that we have to implement this meta regressor now. While I believe that you could do this on your own, I want to point you to an awesome, already available implementation of this approach. Note: I am the creator of this implementation and hence biased towards it. It is part of the fabulous scikit-lego project that each of you should be aware of. This library contains a lot of useful scikit-learn compatible extensions, such as estimators, transformers, and more building blocks (hence the name). Let me quote from the project’s Github page: “It was initiated by Matthijs Brouns and Vincent D. Warmerdam as a tool to teach people how to contribute to open source.” Shout out to Vincent and Matthijs! So, take it to heart, check out this project and think about if you can contribute something, too. I already did. Let’s finally code now. import pandas as pdimport numpy as npfrom sklearn.svm import SVCfrom sklearn.linear_model import LinearRegressionfrom sklego.meta import ZeroInflatedRegressor# Create the salary dataset.np.random.seed(0)dataset = pd.DataFrame({'Age': np.random.randint(1, 100, size=200)})dataset['Salary'] = np.where((dataset.Age > 17) & (dataset.Age < 70), 1500*dataset.Age + 5000 + 10000*np.random.randn(200), 0).round()# Instantiate the zero-inflated regressor.zir = ZeroInflatedRegressor( classifier=SVC(), regressor=LinearRegression())# Easy fit!zir.fit(dataset[['Age']], dataset.Salary) We can now plot the result: This is exactly the behavior we want to see! The only thing is that we have to deduct some points because the SVM misses a zero output at age 70. This in turn creates an outlier for the linear regression, which then tilts the line down a bit too much. Luckily, we can also use the ZeroInflatedReressor inside some hyperparameter optimization. from sklearn.model_selection import GridSearchCVgrid = GridSearchCV( estimator=zir, param_grid={ 'classifier__C': range(1, 10) })grid.fit(dataset[['Age']], dataset.Salary) You can get the best SVM parameter C via grid.best_params_ , which is 4 in our case. The result: We have looked at datasets for regression that have a large number of zeroes as targets — zero-inflated data. This can unsettle many regressors such as support vector machines as well as neural networks. As a way to circumvent this problem, we introduced the zero-inflated regressor, a meta-model that consists of a base classifier and a base regressor. The classifier checks whether the base regressor has to work, or if the prediction should be zero anyway. Otherwise, the base regressor takes over and outputs a number. Of course, this number can also be zero, but usually, it is not. In some sense, the classifier makes the life of the regressor easier by keeping the regressor’s head free from clutter. Finally, you might ask: “You mentioned tree-based models. What about them? They should be able to deal with zero-inflated datasets as well.” And yes, they can! Let us train a decision tree with a depth of 4 on the same dataset. This also looks fine, but it has the usual step shape that we see always see with trees. This is not surprising though, as decision trees are basically only piecewise constant functions. So are random forests and gradient boosting algorithms because they are sums of trees. The fit is good, but not as good as ours — a simple linear regression equipped with a support vector machine works better in our case. As usual, try out different models for your dataset at hand. Now you have another tool at your disposal that you can try out. Have fun! I hope that you learned something new, interesting, and useful today. Thanks for reading! As the last point, if you want to support me in writing more about machine learning andplan to get a Medium subscription anyway, want to support me in writing more about machine learning and plan to get a Medium subscription anyway, why not do it via this link? This would help me a lot! 😊 To be transparent, the price for you does not change, but about half of the subscription fees go directly to me. Thanks a lot, if you consider supporting me! If you have any questions, write me on LinkedIn!
[ { "code": null, "e": 391, "s": 172, "text": "When working on regression problems, often you have target values that are continuously and evenly distributed in some range. Let me illustrate what I mean by this. Consider the following dataset 2-dimensional dataset:" }, { "code": null, "e": 542, "s": 391, "text": "In this case, the target values are all scattered in the range from about -300 to 400. Applying linear regression, we end up with the following model:" }, { "code": null, "e": 570, "s": 542, "text": "Nothing new, nothing fancy." }, { "code": null, "e": 704, "s": 570, "text": "However, there are datasets that have an unusually high amount of zero targets in them. This is what we call a zero-inflated dataset." }, { "code": null, "e": 819, "s": 704, "text": "Examples of such behavior are datasets with the target being the count of rare events. This includes the amount of" }, { "code": null, "e": 845, "s": 819, "text": "defects in manufacturing," }, { "code": null, "e": 911, "s": 845, "text": "tornados or other natural disasters in a given date and place, or" }, { "code": null, "e": 941, "s": 911, "text": "crimes in some neighborhoods." }, { "code": null, "e": 1212, "s": 941, "text": "The common pattern is that usually, nothing bad happens, i.e. the target is zero. But occasionally, for example when a manufacturing machine malfunctions for some hours, the count skyrockets. In this case, the model actually has to predict something different from zero." }, { "code": null, "e": 1409, "s": 1212, "text": "Many models can get distracted by such behavior, among them linear regression, support vector machines, and also neural networks. The chance that one of these models outputs a zero is quite small." }, { "code": null, "e": 1793, "s": 1409, "text": "As an example, take a simple linear regression with one feature as depicted above. The output of the algorithm is a line that takes a value of zero exactly one time. The problem persists in higher dimensions, too. Or recall that neural networks can be expressed as a complex, nested formula — if you plug in random numbers, the chance is high that you won’t receive a zero as output." }, { "code": null, "e": 1895, "s": 1793, "text": "But instead of talking about hypothetical scenarios, let us visualize the problem with a toy dataset." }, { "code": null, "e": 1933, "s": 1895, "text": "This dataset consists of two columns:" }, { "code": null, "e": 1965, "s": 1933, "text": "the feature Age of a person and" }, { "code": null, "e": 2012, "s": 1965, "text": "the target Salary from working of this person." }, { "code": null, "e": 2284, "s": 2012, "text": "In this made-up dataset, we can see that children and teens do not earn a salary. Starting at some age, money-making begins. People gain more experience and hence the salary increases with age. In the end, people retire and don’t earn a salary anymore. The story of life." }, { "code": null, "e": 2387, "s": 2284, "text": "It is immediately clear that a simple linear regression will not work well here. Let’s do it anyway. 😎" }, { "code": null, "e": 2594, "s": 2387, "text": "Not a great fit. A line cannot capture all the variation in the data, but notice that if we would fit a line to the data between the ages of approximately 20 and 70, the fit in this interval would be great." }, { "code": null, "e": 2839, "s": 2594, "text": "But this solves only part of the problem. We want a general-purpose model which is also able to make predictions for young and old people. Besides tree-based methods, let us take a look at a simple, yet effective approach to solve this problem." }, { "code": null, "e": 3009, "s": 2839, "text": "We will now define an estimator that solves the problems related to zero-inflated datasets. Afterward, we use an already implemented version of it on our salary dataset." }, { "code": null, "e": 3077, "s": 3009, "text": "The idea is quite simple. Consider the following two-step approach:" }, { "code": null, "e": 3226, "s": 3077, "text": "Train a classifier C that tells us whether the regression output is zero, or not.Train a regressor R on the part of the data with a non-zero target." }, { "code": null, "e": 3308, "s": 3226, "text": "Train a classifier C that tells us whether the regression output is zero, or not." }, { "code": null, "e": 3376, "s": 3308, "text": "Train a regressor R on the part of the data with a non-zero target." }, { "code": null, "e": 3559, "s": 3376, "text": "If a data point goes into the model, the classifier first checks if the output should be zero. If yes, output zero. Otherwise, output the result of the regressor for this data point." }, { "code": null, "e": 3717, "s": 3559, "text": "This is what we call a meta-model, i.e. a model that consists of other models. The great thing is that you can plug in any classifier and regressor you like." }, { "code": null, "e": 3755, "s": 3717, "text": "Let’s get back to our salary dataset." }, { "code": null, "e": 3970, "s": 3755, "text": "We see that the classifier has to capture the zero targets on both ends of the age axis. A simple logistic regression cannot do this (think about why!), but an SVM classifier with an RBF kernel might be sufficient." }, { "code": null, "e": 4174, "s": 3970, "text": "The problem is that we have to implement this meta regressor now. While I believe that you could do this on your own, I want to point you to an awesome, already available implementation of this approach." }, { "code": null, "e": 4249, "s": 4174, "text": "Note: I am the creator of this implementation and hence biased towards it." }, { "code": null, "e": 4529, "s": 4249, "text": "It is part of the fabulous scikit-lego project that each of you should be aware of. This library contains a lot of useful scikit-learn compatible extensions, such as estimators, transformers, and more building blocks (hence the name). Let me quote from the project’s Github page:" }, { "code": null, "e": 4652, "s": 4529, "text": "“It was initiated by Matthijs Brouns and Vincent D. Warmerdam as a tool to teach people how to contribute to open source.”" }, { "code": null, "e": 4801, "s": 4652, "text": "Shout out to Vincent and Matthijs! So, take it to heart, check out this project and think about if you can contribute something, too. I already did." }, { "code": null, "e": 4825, "s": 4801, "text": "Let’s finally code now." }, { "code": null, "e": 5407, "s": 4825, "text": "import pandas as pdimport numpy as npfrom sklearn.svm import SVCfrom sklearn.linear_model import LinearRegressionfrom sklego.meta import ZeroInflatedRegressor# Create the salary dataset.np.random.seed(0)dataset = pd.DataFrame({'Age': np.random.randint(1, 100, size=200)})dataset['Salary'] = np.where((dataset.Age > 17) & (dataset.Age < 70), 1500*dataset.Age + 5000 + 10000*np.random.randn(200), 0).round()# Instantiate the zero-inflated regressor.zir = ZeroInflatedRegressor( classifier=SVC(), regressor=LinearRegression())# Easy fit!zir.fit(dataset[['Age']], dataset.Salary)" }, { "code": null, "e": 5435, "s": 5407, "text": "We can now plot the result:" }, { "code": null, "e": 5480, "s": 5435, "text": "This is exactly the behavior we want to see!" }, { "code": null, "e": 5778, "s": 5480, "text": "The only thing is that we have to deduct some points because the SVM misses a zero output at age 70. This in turn creates an outlier for the linear regression, which then tilts the line down a bit too much. Luckily, we can also use the ZeroInflatedReressor inside some hyperparameter optimization." }, { "code": null, "e": 5966, "s": 5778, "text": "from sklearn.model_selection import GridSearchCVgrid = GridSearchCV( estimator=zir, param_grid={ 'classifier__C': range(1, 10) })grid.fit(dataset[['Age']], dataset.Salary)" }, { "code": null, "e": 6063, "s": 5966, "text": "You can get the best SVM parameter C via grid.best_params_ , which is 4 in our case. The result:" }, { "code": null, "e": 6267, "s": 6063, "text": "We have looked at datasets for regression that have a large number of zeroes as targets — zero-inflated data. This can unsettle many regressors such as support vector machines as well as neural networks." }, { "code": null, "e": 6651, "s": 6267, "text": "As a way to circumvent this problem, we introduced the zero-inflated regressor, a meta-model that consists of a base classifier and a base regressor. The classifier checks whether the base regressor has to work, or if the prediction should be zero anyway. Otherwise, the base regressor takes over and outputs a number. Of course, this number can also be zero, but usually, it is not." }, { "code": null, "e": 6771, "s": 6651, "text": "In some sense, the classifier makes the life of the regressor easier by keeping the regressor’s head free from clutter." }, { "code": null, "e": 6999, "s": 6771, "text": "Finally, you might ask: “You mentioned tree-based models. What about them? They should be able to deal with zero-inflated datasets as well.” And yes, they can! Let us train a decision tree with a depth of 4 on the same dataset." }, { "code": null, "e": 7273, "s": 6999, "text": "This also looks fine, but it has the usual step shape that we see always see with trees. This is not surprising though, as decision trees are basically only piecewise constant functions. So are random forests and gradient boosting algorithms because they are sums of trees." }, { "code": null, "e": 7534, "s": 7273, "text": "The fit is good, but not as good as ours — a simple linear regression equipped with a support vector machine works better in our case. As usual, try out different models for your dataset at hand. Now you have another tool at your disposal that you can try out." }, { "code": null, "e": 7544, "s": 7534, "text": "Have fun!" }, { "code": null, "e": 7634, "s": 7544, "text": "I hope that you learned something new, interesting, and useful today. Thanks for reading!" }, { "code": null, "e": 7660, "s": 7634, "text": "As the last point, if you" }, { "code": null, "e": 7763, "s": 7660, "text": "want to support me in writing more about machine learning andplan to get a Medium subscription anyway," }, { "code": null, "e": 7825, "s": 7763, "text": "want to support me in writing more about machine learning and" }, { "code": null, "e": 7867, "s": 7825, "text": "plan to get a Medium subscription anyway," }, { "code": null, "e": 7924, "s": 7867, "text": "why not do it via this link? This would help me a lot! 😊" }, { "code": null, "e": 8037, "s": 7924, "text": "To be transparent, the price for you does not change, but about half of the subscription fees go directly to me." }, { "code": null, "e": 8082, "s": 8037, "text": "Thanks a lot, if you consider supporting me!" } ]
How to iterate through all selected elements into an array ? - GeeksforGeeks
19 Feb, 2020 The task is to add all the selected HTML elements into an array and iterate through the array. To achieve this, the first step is to select all the desired elements. There are several ways to do this. Finding HTML elements by id:var myElement = document.getElementById("element-id"); var myElement = document.getElementById("element-id"); Finding HTML elements by tag name:var myElements = document.getElementsByTagName("div"); var myElements = document.getElementsByTagName("div"); Finding HTML elements by class name:var myElements = document.getElementsByClassName( "element-class"); var myElements = document.getElementsByClassName( "element-class"); Finding HTML elements by CSS selectors:var myElements = document.querySelectorAll("div.class-name");The second step involves iterating over the array. There are several ways to do this: var myElements = document.querySelectorAll("div.class-name"); The second step involves iterating over the array. There are several ways to do this: Using for loop.array = [ a, b, c, d, e ];for (index = 0; index < array.length; index++) { console.log(array[index]); } array = [ a, b, c, d, e ];for (index = 0; index < array.length; index++) { console.log(array[index]); } Using while loop.index = 0; array = [ a, b, c, d, e ]; while (index < array.length) { console.log(array[index]); index++; } index = 0; array = [ a, b, c, d, e ]; while (index < array.length) { console.log(array[index]); index++; } Using forEach method.index = 0; array = [ a, b, c, d, e ]; array.forEach(myFunction); function myFunction(item, index) { console.log(item); }Approach:First use the querySelectorAll selector to get all the elements. Then, use the forEach() and cloneNode() methods to iterate over the elements.Example 1:In this approach, select all the div elements from the first container, add them to the second container. index = 0; array = [ a, b, c, d, e ]; array.forEach(myFunction); function myFunction(item, index) { console.log(item); } Approach:First use the querySelectorAll selector to get all the elements. Then, use the forEach() and cloneNode() methods to iterate over the elements. Example 1:In this approach, select all the div elements from the first container, add them to the second container. Use querySelectorAll() to get all the div elements in the first container(list-1). Click on the button(Click Me!) to select the elements and append them to the second container. Select the second container(list-2) using querySelector(). Loop through the all the div elements using the forEach() method. Clone each div using the cloneNode() method and add it to the second container using appendChild()<!DOCTYPE html><html> <head> <title>Demo</title> <style> /* Basic styling */ html { text-align: center; display: block; margin: 0 auto; } h1 { color: green; text-align: center; } .list-1, .list-2 { width: 240px; height: 120px; text-align: center; display: block; margin: 0 auto; background: lightgreen; border: 1px solid #000; } div, button { width: 80px; height: 20px; margin: 14px 78px; color: #fff; background: green; border: 1px solid #000; } </style></head> <body> <h1>GeeksforGeeks</h1> <div class="list-1"> <!-- select elements from here --> <div>Element 1</div> <div>Element 2</div> <div>Element 3</div> </div> <button>Click Me!</button> <div class="list-2"> <!-- add the selected elements here --> </div> <script> var divs = document.querySelectorAll('.list-1 > div'); var button = document.querySelector('button'); button.addEventListener("click", () => { var list_2 = document.querySelector('.list-2'); divs.forEach((div) => { list_2.appendChild(div.cloneNode(true)); }) }); </script></body> </html>Output:Before clicking on the button:After clicking on the button:Additional note:querySelectorAll() is not a JavaScript method, it is a browser API that lets you access DOM elements. This method returns a Node List and not an array. The difference between a NodeList and an Array is that a NodeList is a language-agnostic way to access DOM elements, and an Array is a JavaScript object you can use to contain collections of stuff.To convert a NodeList to an array:var divsArr = Array.prototype.slice.call(divs);My Personal Notes arrow_drop_upSave <!DOCTYPE html><html> <head> <title>Demo</title> <style> /* Basic styling */ html { text-align: center; display: block; margin: 0 auto; } h1 { color: green; text-align: center; } .list-1, .list-2 { width: 240px; height: 120px; text-align: center; display: block; margin: 0 auto; background: lightgreen; border: 1px solid #000; } div, button { width: 80px; height: 20px; margin: 14px 78px; color: #fff; background: green; border: 1px solid #000; } </style></head> <body> <h1>GeeksforGeeks</h1> <div class="list-1"> <!-- select elements from here --> <div>Element 1</div> <div>Element 2</div> <div>Element 3</div> </div> <button>Click Me!</button> <div class="list-2"> <!-- add the selected elements here --> </div> <script> var divs = document.querySelectorAll('.list-1 > div'); var button = document.querySelector('button'); button.addEventListener("click", () => { var list_2 = document.querySelector('.list-2'); divs.forEach((div) => { list_2.appendChild(div.cloneNode(true)); }) }); </script></body> </html> Output:Before clicking on the button: After clicking on the button: Additional note:querySelectorAll() is not a JavaScript method, it is a browser API that lets you access DOM elements. This method returns a Node List and not an array. The difference between a NodeList and an Array is that a NodeList is a language-agnostic way to access DOM elements, and an Array is a JavaScript object you can use to contain collections of stuff. To convert a NodeList to an array: var divsArr = Array.prototype.slice.call(divs); JavaScript-Misc Picked Technical Scripter 2019 JavaScript Technical Scripter Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React How to append HTML code to a div using JavaScript ? How to Open URL in New Tab using JavaScript ? Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 24434, "s": 24406, "text": "\n19 Feb, 2020" }, { "code": null, "e": 24635, "s": 24434, "text": "The task is to add all the selected HTML elements into an array and iterate through the array. To achieve this, the first step is to select all the desired elements. There are several ways to do this." }, { "code": null, "e": 24718, "s": 24635, "text": "Finding HTML elements by id:var myElement = document.getElementById(\"element-id\");" }, { "code": null, "e": 24773, "s": 24718, "text": "var myElement = document.getElementById(\"element-id\");" }, { "code": null, "e": 24862, "s": 24773, "text": "Finding HTML elements by tag name:var myElements = document.getElementsByTagName(\"div\");" }, { "code": null, "e": 24917, "s": 24862, "text": "var myElements = document.getElementsByTagName(\"div\");" }, { "code": null, "e": 25021, "s": 24917, "text": "Finding HTML elements by class name:var myElements = document.getElementsByClassName( \"element-class\");" }, { "code": null, "e": 25089, "s": 25021, "text": "var myElements = document.getElementsByClassName( \"element-class\");" }, { "code": null, "e": 25275, "s": 25089, "text": "Finding HTML elements by CSS selectors:var myElements = document.querySelectorAll(\"div.class-name\");The second step involves iterating over the array. There are several ways to do this:" }, { "code": null, "e": 25337, "s": 25275, "text": "var myElements = document.querySelectorAll(\"div.class-name\");" }, { "code": null, "e": 25423, "s": 25337, "text": "The second step involves iterating over the array. There are several ways to do this:" }, { "code": null, "e": 25546, "s": 25423, "text": "Using for loop.array = [ a, b, c, d, e ];for (index = 0; index < array.length; index++) { console.log(array[index]); }" }, { "code": "array = [ a, b, c, d, e ];for (index = 0; index < array.length; index++) { console.log(array[index]); }", "e": 25654, "s": 25546, "text": null }, { "code": null, "e": 25786, "s": 25654, "text": "Using while loop.index = 0; array = [ a, b, c, d, e ]; while (index < array.length) { console.log(array[index]); index++; }" }, { "code": "index = 0; array = [ a, b, c, d, e ]; while (index < array.length) { console.log(array[index]); index++; }", "e": 25901, "s": 25786, "text": null }, { "code": null, "e": 26313, "s": 25901, "text": "Using forEach method.index = 0; array = [ a, b, c, d, e ]; array.forEach(myFunction); function myFunction(item, index) { console.log(item); }Approach:First use the querySelectorAll selector to get all the elements. Then, use the forEach() and cloneNode() methods to iterate over the elements.Example 1:In this approach, select all the div elements from the first container, add them to the second container." }, { "code": "index = 0; array = [ a, b, c, d, e ]; array.forEach(myFunction); function myFunction(item, index) { console.log(item); }", "e": 26438, "s": 26313, "text": null }, { "code": null, "e": 26590, "s": 26438, "text": "Approach:First use the querySelectorAll selector to get all the elements. Then, use the forEach() and cloneNode() methods to iterate over the elements." }, { "code": null, "e": 26706, "s": 26590, "text": "Example 1:In this approach, select all the div elements from the first container, add them to the second container." }, { "code": null, "e": 26789, "s": 26706, "text": "Use querySelectorAll() to get all the div elements in the first container(list-1)." }, { "code": null, "e": 26884, "s": 26789, "text": "Click on the button(Click Me!) to select the elements and append them to the second container." }, { "code": null, "e": 26943, "s": 26884, "text": "Select the second container(list-2) using querySelector()." }, { "code": null, "e": 27009, "s": 26943, "text": "Loop through the all the div elements using the forEach() method." }, { "code": null, "e": 29127, "s": 27009, "text": "Clone each div using the cloneNode() method and add it to the second container using appendChild()<!DOCTYPE html><html> <head> <title>Demo</title> <style> /* Basic styling */ html { text-align: center; display: block; margin: 0 auto; } h1 { color: green; text-align: center; } .list-1, .list-2 { width: 240px; height: 120px; text-align: center; display: block; margin: 0 auto; background: lightgreen; border: 1px solid #000; } div, button { width: 80px; height: 20px; margin: 14px 78px; color: #fff; background: green; border: 1px solid #000; } </style></head> <body> <h1>GeeksforGeeks</h1> <div class=\"list-1\"> <!-- select elements from here --> <div>Element 1</div> <div>Element 2</div> <div>Element 3</div> </div> <button>Click Me!</button> <div class=\"list-2\"> <!-- add the selected elements here --> </div> <script> var divs = document.querySelectorAll('.list-1 > div'); var button = document.querySelector('button'); button.addEventListener(\"click\", () => { var list_2 = document.querySelector('.list-2'); divs.forEach((div) => { list_2.appendChild(div.cloneNode(true)); }) }); </script></body> </html>Output:Before clicking on the button:After clicking on the button:Additional note:querySelectorAll() is not a JavaScript method, it is a browser API that lets you access DOM elements. This method returns a Node List and not an array. The difference between a NodeList and an Array is that a NodeList is a language-agnostic way to access DOM elements, and an Array is a JavaScript object you can use to contain collections of stuff.To convert a NodeList to an array:var divsArr = Array.prototype.slice.call(divs);My Personal Notes\narrow_drop_upSave" }, { "code": "<!DOCTYPE html><html> <head> <title>Demo</title> <style> /* Basic styling */ html { text-align: center; display: block; margin: 0 auto; } h1 { color: green; text-align: center; } .list-1, .list-2 { width: 240px; height: 120px; text-align: center; display: block; margin: 0 auto; background: lightgreen; border: 1px solid #000; } div, button { width: 80px; height: 20px; margin: 14px 78px; color: #fff; background: green; border: 1px solid #000; } </style></head> <body> <h1>GeeksforGeeks</h1> <div class=\"list-1\"> <!-- select elements from here --> <div>Element 1</div> <div>Element 2</div> <div>Element 3</div> </div> <button>Click Me!</button> <div class=\"list-2\"> <!-- add the selected elements here --> </div> <script> var divs = document.querySelectorAll('.list-1 > div'); var button = document.querySelector('button'); button.addEventListener(\"click\", () => { var list_2 = document.querySelector('.list-2'); divs.forEach((div) => { list_2.appendChild(div.cloneNode(true)); }) }); </script></body> </html>", "e": 30600, "s": 29127, "text": null }, { "code": null, "e": 30638, "s": 30600, "text": "Output:Before clicking on the button:" }, { "code": null, "e": 30668, "s": 30638, "text": "After clicking on the button:" }, { "code": null, "e": 31034, "s": 30668, "text": "Additional note:querySelectorAll() is not a JavaScript method, it is a browser API that lets you access DOM elements. This method returns a Node List and not an array. The difference between a NodeList and an Array is that a NodeList is a language-agnostic way to access DOM elements, and an Array is a JavaScript object you can use to contain collections of stuff." }, { "code": null, "e": 31069, "s": 31034, "text": "To convert a NodeList to an array:" }, { "code": null, "e": 31117, "s": 31069, "text": "var divsArr = Array.prototype.slice.call(divs);" }, { "code": null, "e": 31133, "s": 31117, "text": "JavaScript-Misc" }, { "code": null, "e": 31140, "s": 31133, "text": "Picked" }, { "code": null, "e": 31164, "s": 31140, "text": "Technical Scripter 2019" }, { "code": null, "e": 31175, "s": 31164, "text": "JavaScript" }, { "code": null, "e": 31194, "s": 31175, "text": "Technical Scripter" }, { "code": null, "e": 31211, "s": 31194, "text": "Web Technologies" }, { "code": null, "e": 31309, "s": 31211, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31318, "s": 31309, "text": "Comments" }, { "code": null, "e": 31331, "s": 31318, "text": "Old Comments" }, { "code": null, "e": 31376, "s": 31331, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 31437, "s": 31376, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 31509, "s": 31437, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 31561, "s": 31509, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 31607, "s": 31561, "text": "How to Open URL in New Tab using JavaScript ?" }, { "code": null, "e": 31649, "s": 31607, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 31682, "s": 31649, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 31725, "s": 31682, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 31787, "s": 31725, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" } ]
VBScript - Error Handling
There are three types of errors in programming: (a) Syntax Errors, (b) Runtime Errors, and (c) Logical Errors. Syntax errors, also called parsing errors, occur at interpretation time for VBScript. For example, the following line causes a syntax error because it is missing a closing parenthesis − <script type = "text/vbscript"> dim x,y x = "Tutorialspoint" y = Ucase(x </script> Runtime errors, also called exceptions, occur during execution, after interpretation. For example, the following line causes a runtime error because here syntax is correct but at runtime it is trying to call fnmultiply, which is a non-existing function − <script type = "text/vbscript"> Dim x,y x = 10 y = 20 z = fnadd(x,y) a = fnmultiply(x,y) Function fnadd(x,y) fnadd = x+y End Function </script> Logic errors can be the most difficult type of errors to track down. These errors are not the result of a syntax or runtime error. Instead, they occur when you make a mistake in the logic that drives your script and you do not get the result you expected. You cannot catch those errors, because it depends on your business requirement what type of logic you want to put in your program. For example, dividing a number by zero or a script that is written which enters into infinite loop. AAssume if we have a runtime error, then the execution stops by displaying the error message. As a developer, if we want to capture the error, then Error Object is used. In the below example, Err.Number gives the error number and Err.Description gives error description. <script type = "text/vbscript"> Err.Raise 6 ' Raise an overflow error. MsgBox "Error # " & CStr(Err.Number) & " " & Err.Description Err.Clear ' Clear the error. </script> 63 Lectures 4 hours Frahaan Hussain Print Add Notes Bookmark this page
[ { "code": null, "e": 2191, "s": 2080, "text": "There are three types of errors in programming: (a) Syntax Errors, (b) Runtime Errors, and (c) Logical Errors." }, { "code": null, "e": 2377, "s": 2191, "text": "Syntax errors, also called parsing errors, occur at interpretation time for VBScript. For example, the following line causes a syntax error because it is missing a closing parenthesis −" }, { "code": null, "e": 2472, "s": 2377, "text": "<script type = \"text/vbscript\">\n\n dim x,y\n x = \"Tutorialspoint\"\n y = Ucase(x\n\n</script>\n" }, { "code": null, "e": 2727, "s": 2472, "text": "Runtime errors, also called exceptions, occur during execution, after interpretation. For example, the following line causes a runtime error because here syntax is correct but at runtime it is trying to call fnmultiply, which is a non-existing function −" }, { "code": null, "e": 2903, "s": 2727, "text": "<script type = \"text/vbscript\">\n Dim x,y\n x = 10\n y = 20\n z = fnadd(x,y)\n a = fnmultiply(x,y)\n \n Function fnadd(x,y)\n fnadd = x+y\n End Function\n\n</script>" }, { "code": null, "e": 3390, "s": 2903, "text": "Logic errors can be the most difficult type of errors to track down. These errors are not the result of a syntax or runtime error. Instead, they occur when you make a mistake in the logic that drives your script and you do not get the result you expected. You cannot catch those errors, because it depends on your business requirement what type of logic you want to put in your program. For example, dividing a number by zero or a script that is written which enters into infinite loop." }, { "code": null, "e": 3560, "s": 3390, "text": "AAssume if we have a runtime error, then the execution stops by displaying the error message. As a developer, if we want to capture the error, then Error Object is used." }, { "code": null, "e": 3661, "s": 3560, "text": "In the below example, Err.Number gives the error number and Err.Description gives error description." }, { "code": null, "e": 3852, "s": 3661, "text": "<script type = \"text/vbscript\">\n \n Err.Raise 6 ' Raise an overflow error.\n MsgBox \"Error # \" & CStr(Err.Number) & \" \" & Err.Description\n Err.Clear ' Clear the error.\n\n</script>" }, { "code": null, "e": 3885, "s": 3852, "text": "\n 63 Lectures \n 4 hours \n" }, { "code": null, "e": 3902, "s": 3885, "text": " Frahaan Hussain" }, { "code": null, "e": 3909, "s": 3902, "text": " Print" }, { "code": null, "e": 3920, "s": 3909, "text": " Add Notes" } ]
Android - Location Based Services
Android location APIs make it easy for you to build location-aware applications, without needing to focus on the details of the underlying location technology. This becomes possible with the help of Google Play services, which facilitates adding location awareness to your app with automated location tracking, geofencing, and activity recognition. This tutorial shows you how to use Location Services in your APP to get the current location, get periodic location updates, look up addresses etc. The Location object represents a geographic location which can consist of a latitude, longitude, time stamp, and other information such as bearing, altitude and velocity. There are following important methods which you can use with Location object to get location specific information − float distanceTo(Location dest) Returns the approximate distance in meters between this location and the given location. float getAccuracy() Get the estimated accuracy of this location, in meters. double getAltitude() Get the altitude if available, in meters above sea level. float getBearing() Get the bearing, in degrees. double getLatitude() Get the latitude, in degrees. double getLongitude() Get the longitude, in degrees. float getSpeed() Get the speed if it is available, in meters/second over ground. boolean hasAccuracy() True if this location has an accuracy. boolean hasAltitude() True if this location has an altitude. boolean hasBearing() True if this location has a bearing. boolean hasSpeed() True if this location has a speed. void reset() Clears the contents of the location. void setAccuracy(float accuracy) Set the estimated accuracy of this location, meters. void setAltitude(double altitude) Set the altitude, in meters above sea level. void setBearing(float bearing) Set the bearing, in degrees. void setLatitude(double latitude) Set the latitude, in degrees. void setLongitude(double longitude) Set the longitude, in degrees. void setSpeed(float speed) Set the speed, in meters/second over ground. String toString() Returns a string containing a concise, human-readable description of this object. To get the current location, create a location client which is LocationClient object, connect it to Location Services using connect() method, and then call its getLastLocation() method. This method returns the most recent location in the form of Location object that contains latitude and longitude coordinates and other information as explained above. To have location based functionality in your activity, you will have to implement two interfaces − GooglePlayServicesClient.ConnectionCallbacks GooglePlayServicesClient.OnConnectionFailedListener These interfaces provide following important callback methods, which you need to implement in your activity class − abstract void onConnected(Bundle connectionHint) This callback method is called when location service is connected to the location client successfully. You will use connect() method to connect to the location client. abstract void onDisconnected() This callback method is called when the client is disconnected. You will use disconnect() method to disconnect from the location client. abstract void onConnectionFailed(ConnectionResult result) This callback method is called when there was an error connecting the client to the service. If you are willing to have location updates, then apart from above mentioned interfaces, you will need to implement LocationListener interface as well. This interface provide following callback method, which you need to implement in your activity class − abstract void onLocationChanged(Location location) This callback method is used for receiving notifications from the LocationClient when the location has changed. The LocationRequest object is used to request a quality of service (QoS) for location updates from the LocationClient. There are following useful setter methods which you can use to handle QoS. There are equivalent getter methods available which you can check in Android official documentation. setExpirationDuration(long millis) Set the duration of this request, in milliseconds. setExpirationTime(long millis) Set the request expiration time, in millisecond since boot. setFastestInterval(long millis) Explicitly set the fastest interval for location updates, in milliseconds. setInterval(long millis) Set the desired interval for active location updates, in milliseconds. setNumUpdates(int numUpdates) Set the number of location updates. setPriority(int priority) Set the priority of the request. Now for example, if your application wants high accuracy location it should create a location request with setPriority(int) set to PRIORITY_HIGH_ACCURACY and setInterval(long) to 5 seconds. You can also use bigger interval and/or other priorities like PRIORITY_LOW_POWER for to request "city" level accuracy or PRIORITY_BALANCED_POWER_ACCURACY for "block" level accuracy. Once you have Location object, you can use Geocoder.getFromLocation() method to get an address for a given latitude and longitude. This method is synchronous, and may take a long time to do its work, so you should call the method from the doInBackground() method of an AsyncTask class. The AsyncTask must be subclassed to be used and the subclass will override doInBackground(Params...) method to perform a task in the background and onPostExecute(Result) method is invoked on the UI thread after the background computation finishes and at the time to display the result. There is one more important method available in AyncTask which is execute(Params... params), this method executes the task with the specified parameters. Following example shows you in practical how to to use Location Services in your app to get the current location and its equivalent addresses etc. Following is the content of the modified main activity file MainActivity.java. package com.example.tutorialspoint7.myapplication; import android.Manifest; import android.app.Activity; import android.os.Bundle; import android.support.v4.app.ActivityCompat; import android.test.mock.MockPackageManager; import android.view.View; import android.widget.Button; import android.widget.Toast; public class MainActivity extends Activity { Button btnShowLocation; private static final int REQUEST_CODE_PERMISSION = 2; String mPermission = Manifest.permission.ACCESS_FINE_LOCATION; // GPSTracker class GPSTracker gps; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); try { if (ActivityCompat.checkSelfPermission(this, mPermission) != MockPackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[]{mPermission}, REQUEST_CODE_PERMISSION); // If any permission above not allowed by user, this condition will execute every time, else your else part will work } } catch (Exception e) { e.printStackTrace(); } btnShowLocation = (Button) findViewById(R.id.button); // show location button click event btnShowLocation.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { // create class object gps = new GPSTracker(MainActivity.this); // check if GPS enabled if(gps.canGetLocation()){ double latitude = gps.getLatitude(); double longitude = gps.getLongitude(); // \n is for new line Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show(); }else{ // can't get location // GPS or Network is not enabled // Ask user to enable GPS/network in settings gps.showSettingsAlert(); } } }); } } Following is the content of the modified main activity file GPSTracker.java. package com.example.tutorialspoint7.myapplication; import android.app.AlertDialog; import android.app.Service; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Bundle; import android.os.IBinder; import android.provider.Settings; import android.util.Log; public class GPSTracker extends Service implements LocationListener { private final Context mContext; // flag for GPS status boolean isGPSEnabled = false; // flag for network status boolean isNetworkEnabled = false; // flag for GPS status boolean canGetLocation = false; Location location; // location double latitude; // latitude double longitude; // longitude // The minimum distance to change Updates in meters private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters // The minimum time between updates in milliseconds private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute // Declaring a Location Manager protected LocationManager locationManager; public GPSTracker(Context context) { this.mContext = context; getLocation(); } public Location getLocation() { try { locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE); // getting GPS status isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER); // getting network status isNetworkEnabled = locationManager .isProviderEnabled(LocationManager.NETWORK_PROVIDER); if (!isGPSEnabled && !isNetworkEnabled) { // no network provider is enabled } else { this.canGetLocation = true; // First get location from Network Provider if (isNetworkEnabled) { locationManager.requestLocationUpdates( LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this); Log.d("Network", "Network"); if (locationManager != null) { location = locationManager .getLastKnownLocation(LocationManager.NETWORK_PROVIDER); if (location != null) { latitude = location.getLatitude(); longitude = location.getLongitude(); } } } // if GPS Enabled get lat/long using GPS Services if (isGPSEnabled) { if (location == null) { locationManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this); Log.d("GPS Enabled", "GPS Enabled"); if (locationManager != null) { location = locationManager .getLastKnownLocation(LocationManager.GPS_PROVIDER); if (location != null) { latitude = location.getLatitude(); longitude = location.getLongitude(); } } } } } } catch (Exception e) { e.printStackTrace(); } return location; } /** * Stop using GPS listener * Calling this function will stop using GPS in your app * */ public void stopUsingGPS(){ if(locationManager != null){ locationManager.removeUpdates(GPSTracker.this); } } /** * Function to get latitude * */ public double getLatitude(){ if(location != null){ latitude = location.getLatitude(); } // return latitude return latitude; } /** * Function to get longitude * */ public double getLongitude(){ if(location != null){ longitude = location.getLongitude(); } // return longitude return longitude; } /** * Function to check GPS/wifi enabled * @return boolean * */ public boolean canGetLocation() { return this.canGetLocation; } /** * Function to show settings alert dialog * On pressing Settings button will lauch Settings Options * */ public void showSettingsAlert(){ AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext); // Setting Dialog Title alertDialog.setTitle("GPS is settings"); // Setting Dialog Message alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?"); // On pressing Settings button alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog,int which) { Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); mContext.startActivity(intent); } }); // on pressing cancel button alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); // Showing Alert Message alertDialog.show(); } @Override public void onLocationChanged(Location location) { } @Override public void onProviderDisabled(String provider) { } @Override public void onProviderEnabled(String provider) { } @Override public void onStatusChanged(String provider, int status, Bundle extras) { } @Override public IBinder onBind(Intent arg0) { return null; } } Following will be the content of res/layout/activity_main.xml file − <?xml version = "1.0" encoding = "utf-8"?> <LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android" android:layout_width = "fill_parent" android:layout_height = "fill_parent" android:orientation = "vertical" > <Button android:id = "@+id/button" android:layout_width = "fill_parent" android:layout_height = "wrap_content" android:text = "getlocation"/> </LinearLayout> Following will be the content of res/values/strings.xml to define two new constants − <?xml version = "1.0" encoding = "utf-8"?> <resources> <string name = "app_name">Tutorialspoint</string> </resources> Following is the default content of AndroidManifest.xml − <?xml version = "1.0" encoding = "utf-8"?> <manifest xmlns:android = "http://schemas.android.com/apk/res/android" package = "com.example.tutorialspoint7.myapplication"> <uses-permission android:name = "android.permission.ACCESS_FINE_LOCATION" /> <uses-permission android:name = "android.permission.INTERNET" /> <application android:allowBackup = "true" android:icon = "@mipmap/ic_launcher" android:label = "@string/app_name" android:supportsRtl = "true" android:theme = "@style/AppTheme"> <activity android:name = ".MainActivity"> <intent-filter> <action android:name = "android.intent.action.MAIN" /> <category android:name = "android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Let's try to run your Tutorialspoint application. I assume that, 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. Before starting your application, Android studio installer will display following window to select an option where you want to run your Android application. Now to see location select Get Location Button which will display location information as follows − 46 Lectures 7.5 hours Aditya Dua 32 Lectures 3.5 hours Sharad Kumar 9 Lectures 1 hours Abhilash Nelson 14 Lectures 1.5 hours Abhilash Nelson 15 Lectures 1.5 hours Abhilash Nelson 10 Lectures 1 hours Abhilash Nelson Print Add Notes Bookmark this page
[ { "code": null, "e": 3767, "s": 3607, "text": "Android location APIs make it easy for you to build location-aware applications, without needing to focus on the details of the underlying location technology." }, { "code": null, "e": 3956, "s": 3767, "text": "This becomes possible with the help of Google Play services, which facilitates adding location awareness to your app with automated location tracking, geofencing, and activity recognition." }, { "code": null, "e": 4104, "s": 3956, "text": "This tutorial shows you how to use Location Services in your APP to get the current location, get periodic location updates, look up addresses etc." }, { "code": null, "e": 4391, "s": 4104, "text": "The Location object represents a geographic location which can consist of a latitude, longitude, time stamp, and other information such as bearing, altitude and velocity. There are following important methods which you can use with Location object to get location specific information −" }, { "code": null, "e": 4423, "s": 4391, "text": "float distanceTo(Location dest)" }, { "code": null, "e": 4512, "s": 4423, "text": "Returns the approximate distance in meters between this location and the given location." }, { "code": null, "e": 4532, "s": 4512, "text": "float getAccuracy()" }, { "code": null, "e": 4588, "s": 4532, "text": "Get the estimated accuracy of this location, in meters." }, { "code": null, "e": 4609, "s": 4588, "text": "double getAltitude()" }, { "code": null, "e": 4667, "s": 4609, "text": "Get the altitude if available, in meters above sea level." }, { "code": null, "e": 4686, "s": 4667, "text": "float getBearing()" }, { "code": null, "e": 4715, "s": 4686, "text": "Get the bearing, in degrees." }, { "code": null, "e": 4736, "s": 4715, "text": "double getLatitude()" }, { "code": null, "e": 4766, "s": 4736, "text": "Get the latitude, in degrees." }, { "code": null, "e": 4788, "s": 4766, "text": "double getLongitude()" }, { "code": null, "e": 4819, "s": 4788, "text": "Get the longitude, in degrees." }, { "code": null, "e": 4836, "s": 4819, "text": "float getSpeed()" }, { "code": null, "e": 4900, "s": 4836, "text": "Get the speed if it is available, in meters/second over ground." }, { "code": null, "e": 4922, "s": 4900, "text": "boolean hasAccuracy()" }, { "code": null, "e": 4961, "s": 4922, "text": "True if this location has an accuracy." }, { "code": null, "e": 4983, "s": 4961, "text": "boolean hasAltitude()" }, { "code": null, "e": 5022, "s": 4983, "text": "True if this location has an altitude." }, { "code": null, "e": 5043, "s": 5022, "text": "boolean hasBearing()" }, { "code": null, "e": 5080, "s": 5043, "text": "True if this location has a bearing." }, { "code": null, "e": 5099, "s": 5080, "text": "boolean hasSpeed()" }, { "code": null, "e": 5134, "s": 5099, "text": "True if this location has a speed." }, { "code": null, "e": 5147, "s": 5134, "text": "void reset()" }, { "code": null, "e": 5184, "s": 5147, "text": "Clears the contents of the location." }, { "code": null, "e": 5217, "s": 5184, "text": "void setAccuracy(float accuracy)" }, { "code": null, "e": 5270, "s": 5217, "text": "Set the estimated accuracy of this location, meters." }, { "code": null, "e": 5304, "s": 5270, "text": "void setAltitude(double altitude)" }, { "code": null, "e": 5349, "s": 5304, "text": "Set the altitude, in meters above sea level." }, { "code": null, "e": 5380, "s": 5349, "text": "void setBearing(float bearing)" }, { "code": null, "e": 5409, "s": 5380, "text": "Set the bearing, in degrees." }, { "code": null, "e": 5443, "s": 5409, "text": "void setLatitude(double latitude)" }, { "code": null, "e": 5473, "s": 5443, "text": "Set the latitude, in degrees." }, { "code": null, "e": 5509, "s": 5473, "text": "void setLongitude(double longitude)" }, { "code": null, "e": 5540, "s": 5509, "text": "Set the longitude, in degrees." }, { "code": null, "e": 5567, "s": 5540, "text": "void setSpeed(float speed)" }, { "code": null, "e": 5612, "s": 5567, "text": "Set the speed, in meters/second over ground." }, { "code": null, "e": 5630, "s": 5612, "text": "String toString()" }, { "code": null, "e": 5712, "s": 5630, "text": "Returns a string containing a concise, human-readable description of this object." }, { "code": null, "e": 6164, "s": 5712, "text": "To get the current location, create a location client which is LocationClient object, connect it to Location Services using connect() method, and then call its getLastLocation() method. This method returns the most recent location in the form of Location object that contains latitude and longitude coordinates and other information as explained above. To have location based functionality in your activity, you will have to implement two interfaces −" }, { "code": null, "e": 6209, "s": 6164, "text": "GooglePlayServicesClient.ConnectionCallbacks" }, { "code": null, "e": 6261, "s": 6209, "text": "GooglePlayServicesClient.OnConnectionFailedListener" }, { "code": null, "e": 6377, "s": 6261, "text": "These interfaces provide following important callback methods, which you need to implement in your activity class −" }, { "code": null, "e": 6426, "s": 6377, "text": "abstract void onConnected(Bundle connectionHint)" }, { "code": null, "e": 6594, "s": 6426, "text": "This callback method is called when location service is connected to the location client successfully. You will use connect() method to connect to the location client." }, { "code": null, "e": 6625, "s": 6594, "text": "abstract void onDisconnected()" }, { "code": null, "e": 6762, "s": 6625, "text": "This callback method is called when the client is disconnected. You will use disconnect() method to disconnect from the location client." }, { "code": null, "e": 6820, "s": 6762, "text": "abstract void onConnectionFailed(ConnectionResult result)" }, { "code": null, "e": 6913, "s": 6820, "text": "This callback method is called when there was an error connecting the client to the service." }, { "code": null, "e": 7168, "s": 6913, "text": "If you are willing to have location updates, then apart from above mentioned interfaces, you will need to implement LocationListener interface as well. This interface provide following callback method, which you need to implement in your activity class −" }, { "code": null, "e": 7219, "s": 7168, "text": "abstract void onLocationChanged(Location location)" }, { "code": null, "e": 7331, "s": 7219, "text": "This callback method is used for receiving notifications from the LocationClient when the location has changed." }, { "code": null, "e": 7626, "s": 7331, "text": "The LocationRequest object is used to request a quality of service (QoS) for location updates from the LocationClient. There are following useful setter methods which you can use to handle QoS. There are equivalent getter methods available which you can check in Android official documentation." }, { "code": null, "e": 7661, "s": 7626, "text": "setExpirationDuration(long millis)" }, { "code": null, "e": 7712, "s": 7661, "text": "Set the duration of this request, in milliseconds." }, { "code": null, "e": 7743, "s": 7712, "text": "setExpirationTime(long millis)" }, { "code": null, "e": 7803, "s": 7743, "text": "Set the request expiration time, in millisecond since boot." }, { "code": null, "e": 7835, "s": 7803, "text": "setFastestInterval(long millis)" }, { "code": null, "e": 7910, "s": 7835, "text": "Explicitly set the fastest interval for location updates, in milliseconds." }, { "code": null, "e": 7935, "s": 7910, "text": "setInterval(long millis)" }, { "code": null, "e": 8006, "s": 7935, "text": "Set the desired interval for active location updates, in milliseconds." }, { "code": null, "e": 8036, "s": 8006, "text": "setNumUpdates(int numUpdates)" }, { "code": null, "e": 8072, "s": 8036, "text": "Set the number of location updates." }, { "code": null, "e": 8098, "s": 8072, "text": "setPriority(int priority)" }, { "code": null, "e": 8131, "s": 8098, "text": "Set the priority of the request." }, { "code": null, "e": 8503, "s": 8131, "text": "Now for example, if your application wants high accuracy location it should create a location request with setPriority(int) set to PRIORITY_HIGH_ACCURACY and setInterval(long) to 5 seconds. You can also use bigger interval and/or other priorities like PRIORITY_LOW_POWER for to request \"city\" level accuracy or PRIORITY_BALANCED_POWER_ACCURACY for \"block\" level accuracy." }, { "code": null, "e": 8789, "s": 8503, "text": "Once you have Location object, you can use Geocoder.getFromLocation() method to get an address for a given latitude and longitude. This method is synchronous, and may take a long time to do its work, so you should call the method from the doInBackground() method of an AsyncTask class." }, { "code": null, "e": 9229, "s": 8789, "text": "The AsyncTask must be subclassed to be used and the subclass will override doInBackground(Params...) method to perform a task in the background and onPostExecute(Result) method is invoked on the UI thread after the background computation finishes and at the time to display the result. There is one more important method available in AyncTask which is execute(Params... params), this method executes the task with the specified parameters." }, { "code": null, "e": 9376, "s": 9229, "text": "Following example shows you in practical how to to use Location Services in your app to get the current location and its equivalent addresses etc." }, { "code": null, "e": 9455, "s": 9376, "text": "Following is the content of the modified main activity file MainActivity.java." }, { "code": null, "e": 11601, "s": 9455, "text": "package com.example.tutorialspoint7.myapplication;\n\nimport android.Manifest;\nimport android.app.Activity;\nimport android.os.Bundle;\nimport android.support.v4.app.ActivityCompat;\nimport android.test.mock.MockPackageManager;\nimport android.view.View;\nimport android.widget.Button;\nimport android.widget.Toast;\n\npublic class MainActivity extends Activity {\n\n Button btnShowLocation;\n private static final int REQUEST_CODE_PERMISSION = 2;\n String mPermission = Manifest.permission.ACCESS_FINE_LOCATION;\n\n // GPSTracker class\n GPSTracker gps;\n\n @Override\n public void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n\t\t\n try {\n if (ActivityCompat.checkSelfPermission(this, mPermission)\n != MockPackageManager.PERMISSION_GRANTED) {\n\n ActivityCompat.requestPermissions(this, new String[]{mPermission}, \n REQUEST_CODE_PERMISSION);\n\n // If any permission above not allowed by user, this condition will\n execute every time, else your else part will work\n }\n } catch (Exception e) {\n e.printStackTrace();\n }\n\n btnShowLocation = (Button) findViewById(R.id.button);\n\n // show location button click event\n btnShowLocation.setOnClickListener(new View.OnClickListener() {\n\n @Override\n public void onClick(View arg0) {\n // create class object\n gps = new GPSTracker(MainActivity.this);\n\n // check if GPS enabled\n if(gps.canGetLocation()){\n\n double latitude = gps.getLatitude();\n double longitude = gps.getLongitude();\n\n // \\n is for new line\n Toast.makeText(getApplicationContext(), \"Your Location is - \\nLat: \"\n + latitude + \"\\nLong: \" + longitude, Toast.LENGTH_LONG).show();\n }else{\n // can't get location\n // GPS or Network is not enabled\n // Ask user to enable GPS/network in settings\n gps.showSettingsAlert();\n }\n\n }\n });\n }\n}" }, { "code": null, "e": 11678, "s": 11601, "text": "Following is the content of the modified main activity file GPSTracker.java." }, { "code": null, "e": 17526, "s": 11678, "text": "package com.example.tutorialspoint7.myapplication;\n\nimport android.app.AlertDialog;\nimport android.app.Service;\nimport android.content.Context;\nimport android.content.DialogInterface;\nimport android.content.Intent;\nimport android.location.Location;\nimport android.location.LocationListener;\nimport android.location.LocationManager;\nimport android.os.Bundle;\nimport android.os.IBinder;\nimport android.provider.Settings;\nimport android.util.Log;\n\npublic class GPSTracker extends Service implements LocationListener {\n\n private final Context mContext;\n\n // flag for GPS status\n boolean isGPSEnabled = false;\n\n // flag for network status\n boolean isNetworkEnabled = false;\n\n // flag for GPS status\n boolean canGetLocation = false;\n\n Location location; // location\n double latitude; // latitude\n double longitude; // longitude\n\n // The minimum distance to change Updates in meters\n private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters\n\n // The minimum time between updates in milliseconds\n private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute\n\n // Declaring a Location Manager\n protected LocationManager locationManager;\n\n public GPSTracker(Context context) {\n this.mContext = context;\n getLocation();\n }\n\n public Location getLocation() {\n try {\n locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);\n\n // getting GPS status\n isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);\n\n // getting network status\n isNetworkEnabled = locationManager\n .isProviderEnabled(LocationManager.NETWORK_PROVIDER);\n\n if (!isGPSEnabled && !isNetworkEnabled) {\n // no network provider is enabled\n } else {\n this.canGetLocation = true;\n // First get location from Network Provider\n if (isNetworkEnabled) {\n locationManager.requestLocationUpdates(\n LocationManager.NETWORK_PROVIDER,\n MIN_TIME_BW_UPDATES,\n MIN_DISTANCE_CHANGE_FOR_UPDATES, this);\n\t\t\t\t\t\t\n Log.d(\"Network\", \"Network\");\n if (locationManager != null) {\n location = locationManager\n .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);\n\t\t\t\t\t\t\t\n if (location != null) {\n latitude = location.getLatitude();\n longitude = location.getLongitude();\n }\n }\n }\n\t\t\t\t\n // if GPS Enabled get lat/long using GPS Services\n if (isGPSEnabled) {\n if (location == null) {\n locationManager.requestLocationUpdates(\n LocationManager.GPS_PROVIDER,\n MIN_TIME_BW_UPDATES,\n MIN_DISTANCE_CHANGE_FOR_UPDATES, this);\n\t\t\t\t\t\t\t\n Log.d(\"GPS Enabled\", \"GPS Enabled\");\n if (locationManager != null) {\n location = locationManager\n .getLastKnownLocation(LocationManager.GPS_PROVIDER);\n\t\t\t\t\t\t\t\t\n if (location != null) {\n latitude = location.getLatitude();\n longitude = location.getLongitude();\n }\n }\n }\n }\n }\n\n } catch (Exception e) {\n e.printStackTrace();\n }\n\n return location;\n }\n\n /**\n * Stop using GPS listener\n * Calling this function will stop using GPS in your app\n * */\n\t\n public void stopUsingGPS(){\n if(locationManager != null){\n locationManager.removeUpdates(GPSTracker.this);\n }\n }\n\n /**\n * Function to get latitude\n * */\n\t\n public double getLatitude(){\n if(location != null){\n latitude = location.getLatitude();\n }\n\n // return latitude\n return latitude;\n }\n\n /**\n * Function to get longitude\n * */\n\t\n public double getLongitude(){\n if(location != null){\n longitude = location.getLongitude();\n }\n\n // return longitude\n return longitude;\n }\n\n /**\n * Function to check GPS/wifi enabled\n * @return boolean\n * */\n\t\n public boolean canGetLocation() {\n return this.canGetLocation;\n }\n\n /**\n * Function to show settings alert dialog\n * On pressing Settings button will lauch Settings Options\n * */\n\t\n public void showSettingsAlert(){\n AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);\n\n // Setting Dialog Title\n alertDialog.setTitle(\"GPS is settings\");\n\n // Setting Dialog Message\n alertDialog.setMessage(\"GPS is not enabled. Do you want to go to settings menu?\");\n\n // On pressing Settings button\n alertDialog.setPositiveButton(\"Settings\", new DialogInterface.OnClickListener() {\n public void onClick(DialogInterface dialog,int which) {\n Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);\n mContext.startActivity(intent);\n }\n });\n\n // on pressing cancel button\n alertDialog.setNegativeButton(\"Cancel\", new DialogInterface.OnClickListener() {\n public void onClick(DialogInterface dialog, int which) {\n dialog.cancel();\n }\n });\n\n // Showing Alert Message\n alertDialog.show();\n }\n\n @Override\n public void onLocationChanged(Location location) {\n }\n\n @Override\n public void onProviderDisabled(String provider) {\n }\n\n @Override\n public void onProviderEnabled(String provider) {\n }\n\n @Override\n public void onStatusChanged(String provider, int status, Bundle extras) {\n }\n\n @Override\n public IBinder onBind(Intent arg0) {\n return null;\n }\n}" }, { "code": null, "e": 17595, "s": 17526, "text": "Following will be the content of res/layout/activity_main.xml file −" }, { "code": null, "e": 18020, "s": 17595, "text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<LinearLayout xmlns:android = \"http://schemas.android.com/apk/res/android\"\n android:layout_width = \"fill_parent\"\n android:layout_height = \"fill_parent\"\n android:orientation = \"vertical\" >\n\n\n <Button\n android:id = \"@+id/button\"\n android:layout_width = \"fill_parent\"\n android:layout_height = \"wrap_content\"\n android:text = \"getlocation\"/>\n\n</LinearLayout>" }, { "code": null, "e": 18106, "s": 18020, "text": "Following will be the content of res/values/strings.xml to define two new constants −" }, { "code": null, "e": 18227, "s": 18106, "text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<resources>\n <string name = \"app_name\">Tutorialspoint</string>\n</resources>" }, { "code": null, "e": 18285, "s": 18227, "text": "Following is the default content of AndroidManifest.xml −" }, { "code": null, "e": 19110, "s": 18285, "text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<manifest xmlns:android = \"http://schemas.android.com/apk/res/android\"\n package = \"com.example.tutorialspoint7.myapplication\">\n <uses-permission android:name = \"android.permission.ACCESS_FINE_LOCATION\" />\n <uses-permission android:name = \"android.permission.INTERNET\" />\n <application\n android:allowBackup = \"true\"\n android:icon = \"@mipmap/ic_launcher\"\n android:label = \"@string/app_name\"\n android:supportsRtl = \"true\"\n android:theme = \"@style/AppTheme\">\n\t\t\n <activity android:name = \".MainActivity\">\n <intent-filter>\n <action android:name = \"android.intent.action.MAIN\" />\n\n <category android:name = \"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n\n</manifest>" }, { "code": null, "e": 19521, "s": 19110, "text": "Let's try to run your Tutorialspoint application. I assume that, 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. Before starting your application, Android studio installer will display following window to select an option where you want to run your Android application." }, { "code": null, "e": 19621, "s": 19521, "text": "Now to see location select Get Location Button which will display location information as follows −" }, { "code": null, "e": 19656, "s": 19621, "text": "\n 46 Lectures \n 7.5 hours \n" }, { "code": null, "e": 19668, "s": 19656, "text": " Aditya Dua" }, { "code": null, "e": 19703, "s": 19668, "text": "\n 32 Lectures \n 3.5 hours \n" }, { "code": null, "e": 19717, "s": 19703, "text": " Sharad Kumar" }, { "code": null, "e": 19749, "s": 19717, "text": "\n 9 Lectures \n 1 hours \n" }, { "code": null, "e": 19766, "s": 19749, "text": " Abhilash Nelson" }, { "code": null, "e": 19801, "s": 19766, "text": "\n 14 Lectures \n 1.5 hours \n" }, { "code": null, "e": 19818, "s": 19801, "text": " Abhilash Nelson" }, { "code": null, "e": 19853, "s": 19818, "text": "\n 15 Lectures \n 1.5 hours \n" }, { "code": null, "e": 19870, "s": 19853, "text": " Abhilash Nelson" }, { "code": null, "e": 19903, "s": 19870, "text": "\n 10 Lectures \n 1 hours \n" }, { "code": null, "e": 19920, "s": 19903, "text": " Abhilash Nelson" }, { "code": null, "e": 19927, "s": 19920, "text": " Print" }, { "code": null, "e": 19938, "s": 19927, "text": " Add Notes" } ]
How to design a dropdown menu using pure CSS ? - GeeksforGeeks
23 Feb, 2021 The Dropdown Menu is a common UI pattern that we have seen on the web nowadays. It is useful in displaying related information in pieces without overwhelming the user with buttons, texts, and options. Most of the time it is seen inside the navigation bar or headers of websites. With the help of Pure CSS, we can easily create such dropdown menus. Approach: The following points are considered for creating a horizontal menu with dropdown. All the components of the menu should be enclosed within a division with a class named “pure-menu pure-menu-horizontal“. Add class “pure-menu-heading” in the <span> element for the main heading or title. Then add all the items after heading inside <ul> element with class “pure-menu-list”. Each item should be enclosed within <li> element with class “pure-menu-item“. For creating a dropdown menu for a particular list item, add class “pure-menu-has-children“ inside <li> element. Add class name “pure-menu-allow-hover“ to display the submenu on hover. Add all the items of submenu inside <ul> element with class “pure-menu-children”. Each item should be enclosed within <li> element with class “pure-menu-item“. If you want to link an item with a section of your webpage you can further enclose it within <a> element with class “pure-menu-link“. Example: In this example we will create a horizontal menu. HTML <!DOCTYPE html><html> <head> <!--Import Pure Css files--> <link rel="stylesheet" href="https://unpkg.com/purecss@1.0.0/build/pure-min.css" integrity="sha384-nn4HPE8lTHyVtfCBi5yW9d20FjT8BJwUXyWZT9InLYax14RDjBj46LmSztkmNP9w" crossorigin="anonymous"/> <!-- Let browser know website is optimized for mobile --> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> </head> <body> <div class="pure-menu pure-menu-horizontal"> <!--Main heading of menu--> <span class="pure-menu-heading"> GEEKFORGEEKS </span> <ul class="pure-menu-list"> <!--List items of menu--> <li class="pure-menu-item"> <a href="#" class="pure-menu-link"> Home </a> </li> <li class="pure-menu-item"> <a href="#" class="pure-menu-link"> About Us </a> </li> <li class="pure-menu-item pure-menu-has-children pure-menu-allow-hover"> <a href="#" class="pure-menu-link"> Tutorial </a> <!--Submenus of Tutorial--> <ul class="pure-menu-children"> <li class="pure-menu-item"> <a href="#" class="pure-menu-link">C</a> </li> <li class="pure-menu-item"> <a href="#" class="pure-menu-link">C++</a> </li> <li class="pure-menu-item"> <a href="#" class="pure-menu-link">Java</a> </li> </ul> </li> <li class="pure-menu-item"> <a href="#" class="pure-menu-link"> Privacy Policy </a> </li> </ul> </div> </body></html> Output: For creating a vertical menu with dropdown: For creating such menu remove the class name “pure-menu-horizontal“ from the division at beginning. By default, menu items take 100% of the width of the container, so we must limit the width by setting the display to inline-block. Example: In this example we will create a vertical menu. HTML <!DOCTYPE html><html> <head> <!--Import Pure Css files--> <link rel="stylesheet" href="https://unpkg.com/purecss@1.0.0/build/pure-min.css" integrity="sha384-nn4HPE8lTHyVtfCBi5yW9d20FjT8BJwUXyWZT9InLYax14RDjBj46LmSztkmNP9w" crossorigin="anonymous" /> <!-- Let browser know website is optimized for mobile --> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> </head> <body> <style> .custom-restricted-width { /* To limit the menu width to the content of the menu: */ display: inline-block; } </style> <div class="pure-menu custom-restricted-width"> <!--Main heading of menu--> <span class="pure-menu-heading"> GEEKFORGEEKS </span> <ul class="pure-menu-list"> <!--List items of menu--> <li class="pure-menu-item"> <a href="#" class="pure-menu-link"> Home </a> </li> <li class="pure-menu-item"> <a href="#" class="pure-menu-link"> About Us </a> </li> <li class="pure-menu-item pure-menu-has-children pure-menu-allow-hover"> <a href="#" class="pure-menu-link"> Tutorial </a> <!--Submenus of Tutorial--> <ul class="pure-menu-children"> <li class="pure-menu-item"> <a href="#" class="pure-menu-link">C</a> </li> <li class="pure-menu-item"> <a href="#" class="pure-menu-link">C++</a> </li> <li class="pure-menu-item"> <a href="#" class="pure-menu-link">Java</a> </li> </ul> </li> <li class="pure-menu-item"> <a href="#" class="pure-menu-link"> Privacy Policy </a> </li> </ul> </div> </body></html> Output: Pure CSS CSS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to create footer to stay at the bottom of a Web page? Types of CSS (Cascading Style Sheet) How to position a div at the bottom of its container using CSS? Design a web page using HTML and CSS Create a Responsive Navbar using ReactJS Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux How to fetch data from an API in ReactJS ? Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 24708, "s": 24680, "text": "\n23 Feb, 2021" }, { "code": null, "e": 24987, "s": 24708, "text": "The Dropdown Menu is a common UI pattern that we have seen on the web nowadays. It is useful in displaying related information in pieces without overwhelming the user with buttons, texts, and options. Most of the time it is seen inside the navigation bar or headers of websites." }, { "code": null, "e": 25056, "s": 24987, "text": "With the help of Pure CSS, we can easily create such dropdown menus." }, { "code": null, "e": 25148, "s": 25056, "text": "Approach: The following points are considered for creating a horizontal menu with dropdown." }, { "code": null, "e": 25270, "s": 25148, "text": "All the components of the menu should be enclosed within a division with a class named “pure-menu pure-menu-horizontal“." }, { "code": null, "e": 25353, "s": 25270, "text": "Add class “pure-menu-heading” in the <span> element for the main heading or title." }, { "code": null, "e": 25517, "s": 25353, "text": "Then add all the items after heading inside <ul> element with class “pure-menu-list”. Each item should be enclosed within <li> element with class “pure-menu-item“." }, { "code": null, "e": 25862, "s": 25517, "text": "For creating a dropdown menu for a particular list item, add class “pure-menu-has-children“ inside <li> element. Add class name “pure-menu-allow-hover“ to display the submenu on hover. Add all the items of submenu inside <ul> element with class “pure-menu-children”. Each item should be enclosed within <li> element with class “pure-menu-item“." }, { "code": null, "e": 25996, "s": 25862, "text": "If you want to link an item with a section of your webpage you can further enclose it within <a> element with class “pure-menu-link“." }, { "code": null, "e": 26055, "s": 25996, "text": "Example: In this example we will create a horizontal menu." }, { "code": null, "e": 26060, "s": 26055, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <!--Import Pure Css files--> <link rel=\"stylesheet\" href=\"https://unpkg.com/purecss@1.0.0/build/pure-min.css\" integrity=\"sha384-nn4HPE8lTHyVtfCBi5yW9d20FjT8BJwUXyWZT9InLYax14RDjBj46LmSztkmNP9w\" crossorigin=\"anonymous\"/> <!-- Let browser know website is optimized for mobile --> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" /> </head> <body> <div class=\"pure-menu pure-menu-horizontal\"> <!--Main heading of menu--> <span class=\"pure-menu-heading\"> GEEKFORGEEKS </span> <ul class=\"pure-menu-list\"> <!--List items of menu--> <li class=\"pure-menu-item\"> <a href=\"#\" class=\"pure-menu-link\"> Home </a> </li> <li class=\"pure-menu-item\"> <a href=\"#\" class=\"pure-menu-link\"> About Us </a> </li> <li class=\"pure-menu-item pure-menu-has-children pure-menu-allow-hover\"> <a href=\"#\" class=\"pure-menu-link\"> Tutorial </a> <!--Submenus of Tutorial--> <ul class=\"pure-menu-children\"> <li class=\"pure-menu-item\"> <a href=\"#\" class=\"pure-menu-link\">C</a> </li> <li class=\"pure-menu-item\"> <a href=\"#\" class=\"pure-menu-link\">C++</a> </li> <li class=\"pure-menu-item\"> <a href=\"#\" class=\"pure-menu-link\">Java</a> </li> </ul> </li> <li class=\"pure-menu-item\"> <a href=\"#\" class=\"pure-menu-link\"> Privacy Policy </a> </li> </ul> </div> </body></html>", "e": 27783, "s": 26060, "text": null }, { "code": null, "e": 27791, "s": 27783, "text": "Output:" }, { "code": null, "e": 28066, "s": 27791, "text": "For creating a vertical menu with dropdown: For creating such menu remove the class name “pure-menu-horizontal“ from the division at beginning. By default, menu items take 100% of the width of the container, so we must limit the width by setting the display to inline-block." }, { "code": null, "e": 28123, "s": 28066, "text": "Example: In this example we will create a vertical menu." }, { "code": null, "e": 28128, "s": 28123, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <!--Import Pure Css files--> <link rel=\"stylesheet\" href=\"https://unpkg.com/purecss@1.0.0/build/pure-min.css\" integrity=\"sha384-nn4HPE8lTHyVtfCBi5yW9d20FjT8BJwUXyWZT9InLYax14RDjBj46LmSztkmNP9w\" crossorigin=\"anonymous\" /> <!-- Let browser know website is optimized for mobile --> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" /> </head> <body> <style> .custom-restricted-width { /* To limit the menu width to the content of the menu: */ display: inline-block; } </style> <div class=\"pure-menu custom-restricted-width\"> <!--Main heading of menu--> <span class=\"pure-menu-heading\"> GEEKFORGEEKS </span> <ul class=\"pure-menu-list\"> <!--List items of menu--> <li class=\"pure-menu-item\"> <a href=\"#\" class=\"pure-menu-link\"> Home </a> </li> <li class=\"pure-menu-item\"> <a href=\"#\" class=\"pure-menu-link\"> About Us </a> </li> <li class=\"pure-menu-item pure-menu-has-children pure-menu-allow-hover\"> <a href=\"#\" class=\"pure-menu-link\"> Tutorial </a> <!--Submenus of Tutorial--> <ul class=\"pure-menu-children\"> <li class=\"pure-menu-item\"> <a href=\"#\" class=\"pure-menu-link\">C</a> </li> <li class=\"pure-menu-item\"> <a href=\"#\" class=\"pure-menu-link\">C++</a> </li> <li class=\"pure-menu-item\"> <a href=\"#\" class=\"pure-menu-link\">Java</a> </li> </ul> </li> <li class=\"pure-menu-item\"> <a href=\"#\" class=\"pure-menu-link\"> Privacy Policy </a> </li> </ul> </div> </body></html>", "e": 29942, "s": 28128, "text": null }, { "code": null, "e": 29950, "s": 29942, "text": "Output:" }, { "code": null, "e": 29959, "s": 29950, "text": "Pure CSS" }, { "code": null, "e": 29963, "s": 29959, "text": "CSS" }, { "code": null, "e": 29980, "s": 29963, "text": "Web Technologies" }, { "code": null, "e": 30078, "s": 29980, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30136, "s": 30078, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 30173, "s": 30136, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 30237, "s": 30173, "text": "How to position a div at the bottom of its container using CSS?" }, { "code": null, "e": 30274, "s": 30237, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 30315, "s": 30274, "text": "Create a Responsive Navbar using ReactJS" }, { "code": null, "e": 30357, "s": 30315, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 30390, "s": 30357, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 30433, "s": 30390, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 30478, "s": 30433, "text": "Convert a string to an integer in JavaScript" } ]
CSS | ellipse () Function - GeeksforGeeks
17 Jun, 2021 The ellipse() function is an inbuilt function in CSS which is used to create floating text around the ellipse shape picture or anything else. Syntax: circle(100px 10 px at 10px 150px); or ellipse( percentage percentage ); Parameter: This function accepts single parameter length or percentage which is used to hold the value of radius. It is mandatory parameter.Return value: It makes the text ellipse as user want.Example 1: With percentage procedure we will proceed. html <!DOCTYPE html><html> <head> <title> CSS | ellipse() function </title> <style> div { float: left; width: 185px; height: 185px; shape-outside: ellipse(); } img { border-radius: 0px 175px 175px 0px; } h1, h4 { text-align: center; } h1 { color: green; } </style></head> <body> <h1>GeeksforGeeks</h1> <h4>CSS | ellipse() function</h4> <div> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20190808143838/logsm.png" alt="Sample image"> </div> <p>How many times were you frustrated while looking out for a good collection of programming/algorithm/interview questions? What did you expect and what did you get? This portal has been created to provide well written, well thought and well explained solutions for selected questions. An IIT Roorkee alumnus and founder of GeeksforGeeks. He loves to solve programming problems in most efficient ways. Apart from GeeksforGeeks, he has worked with DE Shaw and Co. as a software developer and JIIT Noida as an assistant professor.It is a good platform to learn programming. It is an educational website. Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course. </p> </body> </html> Output: Example 2: html <!DOCTYPE html><html> <head> <title> CSS | ellipse() function </title> <style> h1 { color: green; } img { -webkit-clip-path: ellipse( farthest-side closest-side at 50px 100px); clip-path: ellipse( farthest-side closest-side at 50px 100px); } </style></head> <body> <center> <h1>GeeksforGeeks</h1> <h4>CSS | ellipse() function</h4> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20190808143838/logsm.png" alt="CSS ellipse function"> </center></body> </html> Output: Supported Browsers: The browsers supported by CSS | ellipse () Function are listed below: Google Chrome Microsoft Edge Firefox Safari Opera saurabh1990aror CSS-Functions CSS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to create footer to stay at the bottom of a Web page? Types of CSS (Cascading Style Sheet) How to position a div at the bottom of its container using CSS? Design a web page using HTML and CSS Create a Responsive Navbar using ReactJS Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux How to fetch data from an API in ReactJS ? Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 23986, "s": 23958, "text": "\n17 Jun, 2021" }, { "code": null, "e": 24137, "s": 23986, "text": "The ellipse() function is an inbuilt function in CSS which is used to create floating text around the ellipse shape picture or anything else. Syntax: " }, { "code": null, "e": 24172, "s": 24137, "text": "circle(100px 10 px at 10px 150px);" }, { "code": null, "e": 24176, "s": 24172, "text": "or " }, { "code": null, "e": 24210, "s": 24176, "text": "ellipse( percentage percentage );" }, { "code": null, "e": 24459, "s": 24210, "text": "Parameter: This function accepts single parameter length or percentage which is used to hold the value of radius. It is mandatory parameter.Return value: It makes the text ellipse as user want.Example 1: With percentage procedure we will proceed. " }, { "code": null, "e": 24464, "s": 24459, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title> CSS | ellipse() function </title> <style> div { float: left; width: 185px; height: 185px; shape-outside: ellipse(); } img { border-radius: 0px 175px 175px 0px; } h1, h4 { text-align: center; } h1 { color: green; } </style></head> <body> <h1>GeeksforGeeks</h1> <h4>CSS | ellipse() function</h4> <div> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20190808143838/logsm.png\" alt=\"Sample image\"> </div> <p>How many times were you frustrated while looking out for a good collection of programming/algorithm/interview questions? What did you expect and what did you get? This portal has been created to provide well written, well thought and well explained solutions for selected questions. An IIT Roorkee alumnus and founder of GeeksforGeeks. He loves to solve programming problems in most efficient ways. Apart from GeeksforGeeks, he has worked with DE Shaw and Co. as a software developer and JIIT Noida as an assistant professor.It is a good platform to learn programming. It is an educational website. Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course. </p> </body> </html>", "e": 25961, "s": 24464, "text": null }, { "code": null, "e": 25971, "s": 25961, "text": "Output: " }, { "code": null, "e": 25984, "s": 25971, "text": "Example 2: " }, { "code": null, "e": 25989, "s": 25984, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title> CSS | ellipse() function </title> <style> h1 { color: green; } img { -webkit-clip-path: ellipse( farthest-side closest-side at 50px 100px); clip-path: ellipse( farthest-side closest-side at 50px 100px); } </style></head> <body> <center> <h1>GeeksforGeeks</h1> <h4>CSS | ellipse() function</h4> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20190808143838/logsm.png\" alt=\"CSS ellipse function\"> </center></body> </html>", "e": 26626, "s": 25989, "text": null }, { "code": null, "e": 26636, "s": 26626, "text": "Output: " }, { "code": null, "e": 26728, "s": 26636, "text": "Supported Browsers: The browsers supported by CSS | ellipse () Function are listed below: " }, { "code": null, "e": 26742, "s": 26728, "text": "Google Chrome" }, { "code": null, "e": 26757, "s": 26742, "text": "Microsoft Edge" }, { "code": null, "e": 26765, "s": 26757, "text": "Firefox" }, { "code": null, "e": 26772, "s": 26765, "text": "Safari" }, { "code": null, "e": 26778, "s": 26772, "text": "Opera" }, { "code": null, "e": 26796, "s": 26780, "text": "saurabh1990aror" }, { "code": null, "e": 26810, "s": 26796, "text": "CSS-Functions" }, { "code": null, "e": 26814, "s": 26810, "text": "CSS" }, { "code": null, "e": 26831, "s": 26814, "text": "Web Technologies" }, { "code": null, "e": 26929, "s": 26831, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26987, "s": 26929, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 27024, "s": 26987, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 27088, "s": 27024, "text": "How to position a div at the bottom of its container using CSS?" }, { "code": null, "e": 27125, "s": 27088, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 27166, "s": 27125, "text": "Create a Responsive Navbar using ReactJS" }, { "code": null, "e": 27208, "s": 27166, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 27241, "s": 27208, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 27284, "s": 27241, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 27329, "s": 27284, "text": "Convert a string to an integer in JavaScript" } ]
Python — Print colored text with ease | by Mike Huls | Towards Data Science
Which of the two screenshot in the image above looks better? I’d definitely choose the right one! The colors immediately draw your eye to important things and give you extra information that you can see at a glance. This article touches two subjects: first we’ll get into how printing color in the terminal works on a how printing colors in the terminal works Py-console; a Python package that allows you to print colored outputs easily At the end of this article you’ll be able to print colored outputs so what are we waiting for? Let’s code! First we’ll check out what the terminal needs to print colored text. This’ll show you how printing colored text works on the lowest level. In the next parts we’ll replace this approach by something that’s far easier to work with. When execute the print function in Python the text appears in a terminal. Our goal is to add some data to this value so that our terminal knows to add some color when displaying the text. These pieces of extra data are ANSI escape character sequences that are used to control cursor location, color and font styling e.g. in terminals. The terminal interprets these sequences as commands, rather than text to just display. In the example below we use Python to tell the terminal to print the text ‘This is our message’ with white text and a yellow background: print('\x1b[0;39;43m' + 'This is our message' + '\x1b[0m') The first piece of ANSI code (\x1b[0;39;43m) is a command for the terminal to color all subsequent text in accordance with the specified parameters. We can specify the style, text color and background color with integers in the 0;39;43 part. The second piece of ANSI code at the end(\x1b[0m) tells the terminal to reset the color options so that not all subsequent text is colored white and yellow anymore. The problem with this approach is that this approach is not uniform per platform; ANSI code works on Unix and Macs but are unsupported on Windows. Also we don’t want to type out these specific, hard to understand pieces of code. Let’s find a simpler, cross-platform approach! Py-console is a package that I’ve created that makes printing colors super-easy. It emulates JavaScripts well-known methods likeconsole.log, console.warn, console.error etc. It also adds some more functionalities. Want to create your own Python package? → check out this article for instructions. Also check out this article for creating your own private package) First we’ll install py-console: pip install py-console After installing we can simply call one of 5 functions that will print the text in a specified color: from py_console import consoleconsole.log("log")console.warn("warn")console.error("error")console.success("success")console.info("info") This produces: We can also add a timestamp to out outputs by specifying this for the console or per method: console.setShowTimeDefault(True)orconsole.log('log', showTime=True) These will add the time in front of the string you want to print out: In addition you can also set the timeformat. Check out more information on this here. The example below sets the time format to include years, months and days. console.setTimeFormat('%y-%m-%d %H:%M:%s') In the methods we can specify a ‘severe’ flag so that we have more clear outputs, reversing the text color and background color: from py_console import consoleconsole.log("log", severe=True)console.warn("warn", severe=True)console.error("error, severe=True")console.success("success, severe=True")console.info("info, severe=True") This will produce the output below: Lastly we can also highlight certain parts of a string. Check out this example where we use the console.warn function: In this article we’ve focused briefly on how a terminal prints colored text to display important information more clearly. Then we’ve looked at py-console and how it can make colored output very accessible. I hope that I’ve shed some light on how the terminal can be instructed to print colors and I hope I’ve left you with a nice package for creating beautiful console outputs. If you have suggestions/clarifications please comment so I can improve this article. In the meantime, check out my other articles on all kinds of programming-related topics like these: Create a fast auto-documented, maintainable and easy-to-use Python API in 5 lines of code with FastAPI Python to SQL — UPSERT Safely, Easily and Fast Create and publish your own Python package Create Your Custom, private Python Package That You Can PIP Install From Your Git Repository Virtual environments for absolute beginners — what is it and how to create one (+ examples) Dramatically improve your database insert speed with a simple upgrade Read more about py-console here and more about colorama here. Happy coding! — Mike P.S: like what I’m doing? Follow me!
[ { "code": null, "e": 388, "s": 172, "text": "Which of the two screenshot in the image above looks better? I’d definitely choose the right one! The colors immediately draw your eye to important things and give you extra information that you can see at a glance." }, { "code": null, "e": 490, "s": 388, "text": "This article touches two subjects: first we’ll get into how printing color in the terminal works on a" }, { "code": null, "e": 532, "s": 490, "text": "how printing colors in the terminal works" }, { "code": null, "e": 609, "s": 532, "text": "Py-console; a Python package that allows you to print colored outputs easily" }, { "code": null, "e": 716, "s": 609, "text": "At the end of this article you’ll be able to print colored outputs so what are we waiting for? Let’s code!" }, { "code": null, "e": 946, "s": 716, "text": "First we’ll check out what the terminal needs to print colored text. This’ll show you how printing colored text works on the lowest level. In the next parts we’ll replace this approach by something that’s far easier to work with." }, { "code": null, "e": 1368, "s": 946, "text": "When execute the print function in Python the text appears in a terminal. Our goal is to add some data to this value so that our terminal knows to add some color when displaying the text. These pieces of extra data are ANSI escape character sequences that are used to control cursor location, color and font styling e.g. in terminals. The terminal interprets these sequences as commands, rather than text to just display." }, { "code": null, "e": 1505, "s": 1368, "text": "In the example below we use Python to tell the terminal to print the text ‘This is our message’ with white text and a yellow background:" }, { "code": null, "e": 1564, "s": 1505, "text": "print('\\x1b[0;39;43m' + 'This is our message' + '\\x1b[0m')" }, { "code": null, "e": 1971, "s": 1564, "text": "The first piece of ANSI code (\\x1b[0;39;43m) is a command for the terminal to color all subsequent text in accordance with the specified parameters. We can specify the style, text color and background color with integers in the 0;39;43 part. The second piece of ANSI code at the end(\\x1b[0m) tells the terminal to reset the color options so that not all subsequent text is colored white and yellow anymore." }, { "code": null, "e": 2247, "s": 1971, "text": "The problem with this approach is that this approach is not uniform per platform; ANSI code works on Unix and Macs but are unsupported on Windows. Also we don’t want to type out these specific, hard to understand pieces of code. Let’s find a simpler, cross-platform approach!" }, { "code": null, "e": 2461, "s": 2247, "text": "Py-console is a package that I’ve created that makes printing colors super-easy. It emulates JavaScripts well-known methods likeconsole.log, console.warn, console.error etc. It also adds some more functionalities." }, { "code": null, "e": 2611, "s": 2461, "text": "Want to create your own Python package? → check out this article for instructions. Also check out this article for creating your own private package)" }, { "code": null, "e": 2643, "s": 2611, "text": "First we’ll install py-console:" }, { "code": null, "e": 2666, "s": 2643, "text": "pip install py-console" }, { "code": null, "e": 2768, "s": 2666, "text": "After installing we can simply call one of 5 functions that will print the text in a specified color:" }, { "code": null, "e": 2905, "s": 2768, "text": "from py_console import consoleconsole.log(\"log\")console.warn(\"warn\")console.error(\"error\")console.success(\"success\")console.info(\"info\")" }, { "code": null, "e": 2920, "s": 2905, "text": "This produces:" }, { "code": null, "e": 3013, "s": 2920, "text": "We can also add a timestamp to out outputs by specifying this for the console or per method:" }, { "code": null, "e": 3081, "s": 3013, "text": "console.setShowTimeDefault(True)orconsole.log('log', showTime=True)" }, { "code": null, "e": 3151, "s": 3081, "text": "These will add the time in front of the string you want to print out:" }, { "code": null, "e": 3311, "s": 3151, "text": "In addition you can also set the timeformat. Check out more information on this here. The example below sets the time format to include years, months and days." }, { "code": null, "e": 3354, "s": 3311, "text": "console.setTimeFormat('%y-%m-%d %H:%M:%s')" }, { "code": null, "e": 3483, "s": 3354, "text": "In the methods we can specify a ‘severe’ flag so that we have more clear outputs, reversing the text color and background color:" }, { "code": null, "e": 3685, "s": 3483, "text": "from py_console import consoleconsole.log(\"log\", severe=True)console.warn(\"warn\", severe=True)console.error(\"error, severe=True\")console.success(\"success, severe=True\")console.info(\"info, severe=True\")" }, { "code": null, "e": 3721, "s": 3685, "text": "This will produce the output below:" }, { "code": null, "e": 3840, "s": 3721, "text": "Lastly we can also highlight certain parts of a string. Check out this example where we use the console.warn function:" }, { "code": null, "e": 4047, "s": 3840, "text": "In this article we’ve focused briefly on how a terminal prints colored text to display important information more clearly. Then we’ve looked at py-console and how it can make colored output very accessible." }, { "code": null, "e": 4304, "s": 4047, "text": "I hope that I’ve shed some light on how the terminal can be instructed to print colors and I hope I’ve left you with a nice package for creating beautiful console outputs. If you have suggestions/clarifications please comment so I can improve this article." }, { "code": null, "e": 4404, "s": 4304, "text": "In the meantime, check out my other articles on all kinds of programming-related topics like these:" }, { "code": null, "e": 4507, "s": 4404, "text": "Create a fast auto-documented, maintainable and easy-to-use Python API in 5 lines of code with FastAPI" }, { "code": null, "e": 4554, "s": 4507, "text": "Python to SQL — UPSERT Safely, Easily and Fast" }, { "code": null, "e": 4597, "s": 4554, "text": "Create and publish your own Python package" }, { "code": null, "e": 4690, "s": 4597, "text": "Create Your Custom, private Python Package That You Can PIP Install From Your Git Repository" }, { "code": null, "e": 4782, "s": 4690, "text": "Virtual environments for absolute beginners — what is it and how to create one (+ examples)" }, { "code": null, "e": 4852, "s": 4782, "text": "Dramatically improve your database insert speed with a simple upgrade" }, { "code": null, "e": 4914, "s": 4852, "text": "Read more about py-console here and more about colorama here." }, { "code": null, "e": 4928, "s": 4914, "text": "Happy coding!" }, { "code": null, "e": 4935, "s": 4928, "text": "— Mike" } ]
Integers have sum of squared divisors as perfect square in JavaScript
We are required to write a JavaScript function that takes in a range specified by an array of two numbers m and n. Our function is supposed to find all integers between m and n (m and n integers such as 1 <= m <= n) such that the sum of their squared divisors is itself a square. It should return an array of subarrays. The subarrays will have two elements: first the number the squared divisors of which is a square and then the sum of the squared divisors. Following is the code − Live Demo const range = [1, 500]; const listSquared = ([m, n]) => { const res = []; for (let i = m; i <= n; ++i) { let sum = getDivisors(i).reduce((sum, n) => sum + n * n, 0); let ok = Number.isInteger(Math.sqrt(sum)); if (ok) { res.push([i, sum]); } } return res; } function getDivisors (n) { const divisors = []; for (let i = 1; i <= n / 2; ++i) { if (n % i) { continue; } divisors.push(i); } return divisors.concat([n]); } console.log(listSquared(range)); [ [ 1, 1 ], [ 42, 2500 ], [ 246, 84100 ], [ 287, 84100 ] ]
[ { "code": null, "e": 1177, "s": 1062, "text": "We are required to write a JavaScript function that takes in a range specified by an array of two numbers m and n." }, { "code": null, "e": 1342, "s": 1177, "text": "Our function is supposed to find all integers between m and n (m and n integers such as 1 <= m <= n) such that the sum of their squared divisors is itself a square." }, { "code": null, "e": 1521, "s": 1342, "text": "It should return an array of subarrays. The subarrays will have two elements: first the number the squared divisors of which is a square and then the sum of the squared divisors." }, { "code": null, "e": 1545, "s": 1521, "text": "Following is the code −" }, { "code": null, "e": 1556, "s": 1545, "text": " Live Demo" }, { "code": null, "e": 2089, "s": 1556, "text": "const range = [1, 500];\nconst listSquared = ([m, n]) => {\n const res = [];\n for (let i = m; i <= n; ++i) {\n let sum = getDivisors(i).reduce((sum, n) => sum + n * n, 0);\n let ok = Number.isInteger(Math.sqrt(sum));\n if (ok) {\n res.push([i, sum]);\n }\n }\n return res;\n}\nfunction getDivisors (n) {\n const divisors = [];\n for (let i = 1; i <= n / 2; ++i) {\n if (n % i) {\n continue;\n }\n divisors.push(i);\n }\n return divisors.concat([n]);\n}\nconsole.log(listSquared(range));" }, { "code": null, "e": 2148, "s": 2089, "text": "[ [ 1, 1 ], [ 42, 2500 ], [ 246, 84100 ], [ 287, 84100 ] ]" } ]
Unix / Linux Basic Utilities - Printing, Email
In this chapter, we will discuss in detail about Printing and Email as the basic utilities of Unix. So far, we have tried to understand the Unix OS and the nature of its basic commands. In this chapter, we will learn some important Unix utilities that can be used in our day-to-day life. Before you print a file on a Unix system, you may want to reformat it to adjust the margins, highlight some words, and so on. Most files can also be printed without reformatting, but the raw printout may not be that appealing. Many versions of Unix include two powerful text formatters, nroff and troff. The pr command does minor formatting of files on the terminal screen or for a printer. For example, if you have a long list of names in a file, you can format it onscreen into two or more columns. Following is the syntax for the pr command − pr option(s) filename(s) The pr changes the format of the file only on the screen or on the printed copy; it doesn't modify the original file. Following table lists some pr options − -k Produces k columns of output -d Double-spaces the output (not on all pr versions) -h "header" Takes the next item as a report header -t Eliminates the printing of header and the top/bottom margins -l PAGE_LENGTH Sets the page length to PAGE_LENGTH (66) lines. The default number of lines of text is 56 -o MARGIN Offsets each line with MARGIN (zero) spaces -w PAGE_WIDTH Sets the page width to PAGE_WIDTH (72) characters for multiple text-column output only Before using pr, here are the contents of a sample file named food. $cat food Sweet Tooth Bangkok Wok Mandalay Afghani Cuisine Isle of Java Big Apple Deli Sushi and Sashimi Tio Pepe's Peppers ........ $ Let's use the pr command to make a two-column report with the header Restaurants − $pr -2 -h "Restaurants" food Nov 7 9:58 1997 Restaurants Page 1 Sweet Tooth Isle of Java Bangkok Wok Big Apple Deli Mandalay Sushi and Sashimi Afghani Cuisine Tio Pepe's Peppers ........ $ The command lp or lpr prints a file onto paper as opposed to the screen display. Once you are ready with formatting using the pr command, you can use any of these commands to print your file on the printer connected to your computer. Your system administrator has probably set up a default printer at your site. To print a file named food on the default printer, use the lp or lpr command, as in the following example − $lp food request id is laserp-525 (1 file) $ The lp command shows an ID that you can use to cancel the print job or check its status. If you are using the lp command, you can use the -nNum option to print Num number of copies. Along with the command lpr, you can use -Num for the same. If you are using the lp command, you can use the -nNum option to print Num number of copies. Along with the command lpr, you can use -Num for the same. If there are multiple printers connected with the shared network, then you can choose a printer using -dprinter option along with lp command and for the same purpose you can use -Pprinter option along with lpr command. Here printer is the printer name. If there are multiple printers connected with the shared network, then you can choose a printer using -dprinter option along with lp command and for the same purpose you can use -Pprinter option along with lpr command. Here printer is the printer name. The lpstat command shows what's in the printer queue: request IDs, owners, file sizes, when the jobs were sent for printing, and the status of the requests. Use lpstat -o if you want to see all output requests other than just your own. Requests are shown in the order they'll be printed − $lpstat -o laserp-573 john 128865 Nov 7 11:27 on laserp laserp-574 grace 82744 Nov 7 11:28 laserp-575 john 23347 Nov 7 11:35 $ The lpq gives slightly different information than lpstat -o − $lpq laserp is ready and printing Rank Owner Job Files Total Size active john 573 report.ps 128865 bytes 1st grace 574 ch03.ps ch04.ps 82744 bytes 2nd john 575 standard input 23347 bytes $ Here the first line displays the printer status. If the printer is disabled or running out of paper, you may see different messages on this first line. The cancel command terminates a printing request from the lp command. The lprm command terminates all lpr requests. You can specify either the ID of the request (displayed by lp or lpq) or the name of the printer. $cancel laserp-575 request "laserp-575" cancelled $ To cancel whatever request is currently printing, regardless of its ID, simply enter cancel and the printer name − $cancel laserp request "laserp-573" cancelled $ The lprm command will cancel the active job if it belongs to you. Otherwise, you can give job numbers as arguments, or use a dash (-) to remove all of your jobs − $lprm 575 dfA575diamond dequeued cfA575diamond dequeued $ The lprm command tells you the actual filenames removed from the printer queue. You use the Unix mail command to send and receive mail. Here is the syntax to send an email − $mail [-s subject] [-c cc-addr] [-b bcc-addr] to-addr Here are important options related to mail command −s -s Specifies subject on the command line. -c Sends carbon copies to the list of users. List should be a commaseparated list of names. -b Sends blind carbon copies to list. List should be a commaseparated list of names. Following is an example to send a test message to admin@yahoo.com. $mail -s "Test Message" admin@yahoo.com You are then expected to type in your message, followed by "control-D" at the beginning of a line. To stop, simply type dot (.) as follows − Hi, This is a test . Cc: You can send a complete file using a redirect < operator as follows − $mail -s "Report 05/06/07" admin@yahoo.com < demo.txt To check incoming email at your Unix system, you simply type email as follows − $mail no email 129 Lectures 23 hours Eduonix Learning Solutions 5 Lectures 4.5 hours Frahaan Hussain 35 Lectures 2 hours Pradeep D 41 Lectures 2.5 hours Musab Zayadneh 46 Lectures 4 hours GUHARAJANM 6 Lectures 4 hours Uplatz Print Add Notes Bookmark this page
[ { "code": null, "e": 3035, "s": 2747, "text": "In this chapter, we will discuss in detail about Printing and Email as the basic utilities of Unix. So far, we have tried to understand the Unix OS and the nature of its basic commands. In this chapter, we will learn some important Unix utilities that can be used in our day-to-day life." }, { "code": null, "e": 3262, "s": 3035, "text": "Before you print a file on a Unix system, you may want to reformat it to adjust the margins, highlight some words, and so on. Most files can also be printed without reformatting, but the raw printout may not be that appealing." }, { "code": null, "e": 3339, "s": 3262, "text": "Many versions of Unix include two powerful text formatters, nroff and troff." }, { "code": null, "e": 3536, "s": 3339, "text": "The pr command does minor formatting of files on the terminal screen or for a printer. For example, if you have a long list of names in a file, you can format it onscreen into two or more columns." }, { "code": null, "e": 3581, "s": 3536, "text": "Following is the syntax for the pr command −" }, { "code": null, "e": 3607, "s": 3581, "text": "pr option(s) filename(s)\n" }, { "code": null, "e": 3765, "s": 3607, "text": "The pr changes the format of the file only on the screen or on the printed copy; it doesn't modify the original file. Following table lists some pr options −" }, { "code": null, "e": 3768, "s": 3765, "text": "-k" }, { "code": null, "e": 3797, "s": 3768, "text": "Produces k columns of output" }, { "code": null, "e": 3800, "s": 3797, "text": "-d" }, { "code": null, "e": 3850, "s": 3800, "text": "Double-spaces the output (not on all pr versions)" }, { "code": null, "e": 3862, "s": 3850, "text": "-h \"header\"" }, { "code": null, "e": 3901, "s": 3862, "text": "Takes the next item as a report header" }, { "code": null, "e": 3904, "s": 3901, "text": "-t" }, { "code": null, "e": 3965, "s": 3904, "text": "Eliminates the printing of header and the top/bottom margins" }, { "code": null, "e": 3980, "s": 3965, "text": "-l PAGE_LENGTH" }, { "code": null, "e": 4070, "s": 3980, "text": "Sets the page length to PAGE_LENGTH (66) lines. The default number of lines of text is 56" }, { "code": null, "e": 4080, "s": 4070, "text": "-o MARGIN" }, { "code": null, "e": 4124, "s": 4080, "text": "Offsets each line with MARGIN (zero) spaces" }, { "code": null, "e": 4138, "s": 4124, "text": "-w PAGE_WIDTH" }, { "code": null, "e": 4225, "s": 4138, "text": "Sets the page width to PAGE_WIDTH (72) characters for multiple text-column output only" }, { "code": null, "e": 4293, "s": 4225, "text": "Before using pr, here are the contents of a sample file named food." }, { "code": null, "e": 4429, "s": 4293, "text": "$cat food\nSweet Tooth\nBangkok Wok\nMandalay\nAfghani Cuisine\nIsle of Java\nBig Apple Deli\nSushi and Sashimi\nTio Pepe's Peppers\n........\n$\n" }, { "code": null, "e": 4512, "s": 4429, "text": "Let's use the pr command to make a two-column report with the header Restaurants −" }, { "code": null, "e": 4759, "s": 4512, "text": "$pr -2 -h \"Restaurants\" food\nNov 7 9:58 1997 Restaurants Page 1\n\nSweet Tooth Isle of Java\nBangkok Wok Big Apple Deli\nMandalay Sushi and Sashimi\nAfghani Cuisine Tio Pepe's Peppers\n........\n$\n" }, { "code": null, "e": 4993, "s": 4759, "text": "The command lp or lpr prints a file onto paper as opposed to the screen display. Once you are ready with formatting using the pr command, you can use any of these commands to print your file on the printer connected to your computer." }, { "code": null, "e": 5179, "s": 4993, "text": "Your system administrator has probably set up a default printer at your site. To print a file named food on the default printer, use the lp or lpr command, as in the following example −" }, { "code": null, "e": 5226, "s": 5179, "text": "$lp food\nrequest id is laserp-525 (1 file)\n$\n" }, { "code": null, "e": 5315, "s": 5226, "text": "The lp command shows an ID that you can use to cancel the print job or check its status." }, { "code": null, "e": 5467, "s": 5315, "text": "If you are using the lp command, you can use the -nNum option to print Num number of copies. Along with the command lpr, you can use -Num for the same." }, { "code": null, "e": 5619, "s": 5467, "text": "If you are using the lp command, you can use the -nNum option to print Num number of copies. Along with the command lpr, you can use -Num for the same." }, { "code": null, "e": 5872, "s": 5619, "text": "If there are multiple printers connected with the shared network, then you can choose a printer using -dprinter option along with lp command and for the same purpose you can use -Pprinter option along with lpr command. Here printer is the printer name." }, { "code": null, "e": 6125, "s": 5872, "text": "If there are multiple printers connected with the shared network, then you can choose a printer using -dprinter option along with lp command and for the same purpose you can use -Pprinter option along with lpr command. Here printer is the printer name." }, { "code": null, "e": 6282, "s": 6125, "text": "The lpstat command shows what's in the printer queue: request IDs, owners, file sizes, when the jobs were sent for printing, and the status of the requests." }, { "code": null, "e": 6414, "s": 6282, "text": "Use lpstat -o if you want to see all output requests other than just your own. Requests are shown in the order they'll be printed −" }, { "code": null, "e": 6556, "s": 6414, "text": "$lpstat -o\nlaserp-573 john 128865 Nov 7 11:27 on laserp\nlaserp-574 grace 82744 Nov 7 11:28\nlaserp-575 john 23347 Nov 7 11:35\n$\n" }, { "code": null, "e": 6618, "s": 6556, "text": "The lpq gives slightly different information than lpstat -o −" }, { "code": null, "e": 6887, "s": 6618, "text": "$lpq\nlaserp is ready and printing\nRank Owner Job Files Total Size\nactive john 573 report.ps 128865 bytes\n1st grace 574 ch03.ps ch04.ps 82744 bytes\n2nd john 575 standard input 23347 bytes\n$\n" }, { "code": null, "e": 7039, "s": 6887, "text": "Here the first line displays the printer status. If the printer is disabled or running out of paper, you may see different messages on this first line." }, { "code": null, "e": 7253, "s": 7039, "text": "The cancel command terminates a printing request from the lp command. The lprm command terminates all lpr requests. You can specify either the ID of the request (displayed by lp or lpq) or the name of the printer." }, { "code": null, "e": 7306, "s": 7253, "text": "$cancel laserp-575\nrequest \"laserp-575\" cancelled\n$\n" }, { "code": null, "e": 7421, "s": 7306, "text": "To cancel whatever request is currently printing, regardless of its ID, simply enter cancel and the printer name −" }, { "code": null, "e": 7470, "s": 7421, "text": "$cancel laserp\nrequest \"laserp-573\" cancelled\n$\n" }, { "code": null, "e": 7633, "s": 7470, "text": "The lprm command will cancel the active job if it belongs to you. Otherwise, you can give job numbers as arguments, or use a dash (-) to remove all of your jobs −" }, { "code": null, "e": 7692, "s": 7633, "text": "$lprm 575\ndfA575diamond dequeued\ncfA575diamond dequeued\n$\n" }, { "code": null, "e": 7772, "s": 7692, "text": "The lprm command tells you the actual filenames removed from the printer queue." }, { "code": null, "e": 7866, "s": 7772, "text": "You use the Unix mail command to send and receive mail. Here is the syntax to send an email −" }, { "code": null, "e": 7921, "s": 7866, "text": "$mail [-s subject] [-c cc-addr] [-b bcc-addr] to-addr\n" }, { "code": null, "e": 7975, "s": 7921, "text": "Here are important options related to mail command −s" }, { "code": null, "e": 7978, "s": 7975, "text": "-s" }, { "code": null, "e": 8017, "s": 7978, "text": "Specifies subject on the command line." }, { "code": null, "e": 8020, "s": 8017, "text": "-c" }, { "code": null, "e": 8109, "s": 8020, "text": "Sends carbon copies to the list of users. List should be a commaseparated list of names." }, { "code": null, "e": 8112, "s": 8109, "text": "-b" }, { "code": null, "e": 8194, "s": 8112, "text": "Sends blind carbon copies to list. List should be a commaseparated list of names." }, { "code": null, "e": 8261, "s": 8194, "text": "Following is an example to send a test message to admin@yahoo.com." }, { "code": null, "e": 8303, "s": 8261, "text": "$mail -s \"Test Message\" admin@yahoo.com \n" }, { "code": null, "e": 8444, "s": 8303, "text": "You are then expected to type in your message, followed by \"control-D\" at the beginning of a line. To stop, simply type dot (.) as follows −" }, { "code": null, "e": 8472, "s": 8444, "text": "Hi,\n\nThis is a test\n.\nCc: \n" }, { "code": null, "e": 8542, "s": 8472, "text": "You can send a complete file using a redirect < operator as follows −" }, { "code": null, "e": 8598, "s": 8542, "text": "$mail -s \"Report 05/06/07\" admin@yahoo.com < demo.txt \n" }, { "code": null, "e": 8678, "s": 8598, "text": "To check incoming email at your Unix system, you simply type email as follows −" }, { "code": null, "e": 8694, "s": 8678, "text": "$mail\nno email\n" }, { "code": null, "e": 8729, "s": 8694, "text": "\n 129 Lectures \n 23 hours \n" }, { "code": null, "e": 8757, "s": 8729, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 8791, "s": 8757, "text": "\n 5 Lectures \n 4.5 hours \n" }, { "code": null, "e": 8808, "s": 8791, "text": " Frahaan Hussain" }, { "code": null, "e": 8841, "s": 8808, "text": "\n 35 Lectures \n 2 hours \n" }, { "code": null, "e": 8852, "s": 8841, "text": " Pradeep D" }, { "code": null, "e": 8887, "s": 8852, "text": "\n 41 Lectures \n 2.5 hours \n" }, { "code": null, "e": 8903, "s": 8887, "text": " Musab Zayadneh" }, { "code": null, "e": 8936, "s": 8903, "text": "\n 46 Lectures \n 4 hours \n" }, { "code": null, "e": 8948, "s": 8936, "text": " GUHARAJANM" }, { "code": null, "e": 8980, "s": 8948, "text": "\n 6 Lectures \n 4 hours \n" }, { "code": null, "e": 8988, "s": 8980, "text": " Uplatz" }, { "code": null, "e": 8995, "s": 8988, "text": " Print" }, { "code": null, "e": 9006, "s": 8995, "text": " Add Notes" } ]
Dot notation vs Bracket notation in JavaScript
The dot notation and bracket notation both are used to access the object properties in JavaScript. The dot notation is used mostly as it is easier to read and comprehend and also less verbose. The main difference between dot notation and bracket notation is that the bracket notation allows us to access object properties using variable. Following is the code for bracket notation vs dot notation in JavaScript − 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: 20px; font-weight: 500; color: blueviolet; } </style> </head> <body> <h1>Dot notation vs Bracket notation in JavaScript</h1> <div class="result"></div> <button class="Btn">CLICK HERE</button> <h3>Click on the above button to access the student1 object properties using dot and bracket notation</h3> <script> let resEle = document.querySelector(".result"); let BtnEle = document.querySelector(".Btn"); function Student(name, age, standard) { this.name = name; this.age = age; this.standard = standard; } let student1 = new Student("Rohan", 18, 12); BtnEle.addEventListener("click", () => { let str = "name", str1 = "age", str2 = "standard"; resEle.innerHTML ="Using dot notation <br>student1.name = " + student1.name + "<br>"; resEle.innerHTML += "student1.age = " + student1.age + "<br>"; resEle.innerHTML += "student1.standard = " + student1.standard + "<br><br>"; resEle.innerHTML +=" Using bracket notation <br>student1[str] = " + student1[str] +"<br>"; resEle.innerHTML += "student1[str1] = " + student1[str1] + "<br>"; resEle.innerHTML += "student1[str2] = " + student1[str2] + "<br>"; }); </script> </body> </html> On clicking the ‘CLICK HERE’ button −
[ { "code": null, "e": 1400, "s": 1062, "text": "The dot notation and bracket notation both are used to access the object properties in JavaScript. The dot notation is used mostly as it is easier to read and comprehend and also\nless verbose. The main difference between dot notation and bracket notation is that the bracket notation allows us to access object properties using variable." }, { "code": null, "e": 1475, "s": 1400, "text": "Following is the code for bracket notation vs dot notation in JavaScript −" }, { "code": null, "e": 1486, "s": 1475, "text": " Live Demo" }, { "code": null, "e": 3016, "s": 1486, "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: 20px;\n font-weight: 500;\n color: blueviolet;\n }\n</style>\n</head>\n<body>\n<h1>Dot notation vs Bracket notation in JavaScript</h1>\n<div class=\"result\"></div>\n<button class=\"Btn\">CLICK HERE</button>\n<h3>Click on the above button to access the student1 object properties using dot and bracket notation</h3>\n<script>\n let resEle = document.querySelector(\".result\");\n let BtnEle = document.querySelector(\".Btn\");\n function Student(name, age, standard) {\n this.name = name;\n this.age = age;\n this.standard = standard;\n }\n let student1 = new Student(\"Rohan\", 18, 12);\n BtnEle.addEventListener(\"click\", () => {\n let str = \"name\",\n str1 = \"age\",\n str2 = \"standard\";\n resEle.innerHTML =\"Using dot notation <br>student1.name = \" + student1.name + \"<br>\";\n resEle.innerHTML += \"student1.age = \" + student1.age + \"<br>\";\n resEle.innerHTML +=\n \"student1.standard = \" + student1.standard + \"<br><br>\";\n resEle.innerHTML +=\" Using bracket notation <br>student1[str] = \" +\n student1[str] +\"<br>\";\n resEle.innerHTML += \"student1[str1] = \" + student1[str1] + \"<br>\";\n resEle.innerHTML += \"student1[str2] = \" + student1[str2] + \"<br>\";\n });\n</script>\n</body>\n</html>" }, { "code": null, "e": 3054, "s": 3016, "text": "On clicking the ‘CLICK HERE’ button −" } ]
fmt.print() Function in Golang With Examples - GeeksforGeeks
05 May, 2020 In Go language, fmt package implements formatted I/O with functions analogous to C’s printf() and scanf() function. The fmt.print() function in Go language formats using the default formats for its operands and writes to standard output. Here Spaces are added between operands when any string is not used as a parameter. Moreover, this function is defined under the fmt package. Here, you need to import the “fmt” package in order to use these functions. Syntax: func Print(a ...interface{}) (n int, err error) Here, “a ...interface{}” containing some strings and declared constant variables. Return Value: It returns the number of bytes written and any write error encountered. Example 1: // Golang program to illustrate the usage of// fmt.print() function // Including the main packagepackage main // Importing fmtimport ( "fmt") // Calling mainfunc main() { // Declaring some const variables const name, dept = "GeeksforGeeks", "CS" // Calling print() function fmt.Print(name, " is a ", dept, " portal.\n") // It is conventional not to worry about any // error returned by Print. } Output: GeeksforGeeks is a CS portal. Example 2: // Golang program to illustrate the usage of// fmt.print() function // Including the main packagepackage main // Importing fmtimport ( "fmt") // Calling mainfunc main() { // Declaring some const variables const str1, str2, str3 = "a", "b", "c" // Calling print() function fmt.Print(str1, str2, str3, "\n") // It is conventional not to worry about any // error returned by Print. } Output: abc In the above code, the constant variables used are strings hence spaces are not added in between two strings shown above in the output. Example 3: // Golang program to illustrate the usage of// fmt.print() function // Including the main packagepackage main // Importing fmtimport ( "fmt") // Calling mainfunc main() { // Declaring some const variables const num1, num2, num3 = 5, 15, 15 // Calling print() function fmt.Print(num1, num2, num3, "\n") // It is conventional not to worry about any // error returned by Print. } Output: 5 15 15 In the above code, the constant variables used are numbers hence spaces are added in between two numbers shown above in the output. Golang-fmt Go Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Parse JSON in Golang? Defer Keyword in Golang Loops in Go Language time.Parse() Function in Golang With Examples Anonymous function in Go Language Time Durations in Golang Structures in Golang Strings in Golang How to iterate over an Array using for loop in Golang? Rune in Golang
[ { "code": null, "e": 24460, "s": 24432, "text": "\n05 May, 2020" }, { "code": null, "e": 24915, "s": 24460, "text": "In Go language, fmt package implements formatted I/O with functions analogous to C’s printf() and scanf() function. The fmt.print() function in Go language formats using the default formats for its operands and writes to standard output. Here Spaces are added between operands when any string is not used as a parameter. Moreover, this function is defined under the fmt package. Here, you need to import the “fmt” package in order to use these functions." }, { "code": null, "e": 24923, "s": 24915, "text": "Syntax:" }, { "code": null, "e": 24972, "s": 24923, "text": "func Print(a ...interface{}) (n int, err error)\n" }, { "code": null, "e": 25054, "s": 24972, "text": "Here, “a ...interface{}” containing some strings and declared constant variables." }, { "code": null, "e": 25140, "s": 25054, "text": "Return Value: It returns the number of bytes written and any write error encountered." }, { "code": null, "e": 25151, "s": 25140, "text": "Example 1:" }, { "code": "// Golang program to illustrate the usage of// fmt.print() function // Including the main packagepackage main // Importing fmtimport ( \"fmt\") // Calling mainfunc main() { // Declaring some const variables const name, dept = \"GeeksforGeeks\", \"CS\" // Calling print() function fmt.Print(name, \" is a \", dept, \" portal.\\n\") // It is conventional not to worry about any // error returned by Print. }", "e": 25577, "s": 25151, "text": null }, { "code": null, "e": 25585, "s": 25577, "text": "Output:" }, { "code": null, "e": 25616, "s": 25585, "text": "GeeksforGeeks is a CS portal.\n" }, { "code": null, "e": 25627, "s": 25616, "text": "Example 2:" }, { "code": "// Golang program to illustrate the usage of// fmt.print() function // Including the main packagepackage main // Importing fmtimport ( \"fmt\") // Calling mainfunc main() { // Declaring some const variables const str1, str2, str3 = \"a\", \"b\", \"c\" // Calling print() function fmt.Print(str1, str2, str3, \"\\n\") // It is conventional not to worry about any // error returned by Print. }", "e": 26039, "s": 25627, "text": null }, { "code": null, "e": 26047, "s": 26039, "text": "Output:" }, { "code": null, "e": 26052, "s": 26047, "text": "abc\n" }, { "code": null, "e": 26188, "s": 26052, "text": "In the above code, the constant variables used are strings hence spaces are not added in between two strings shown above in the output." }, { "code": null, "e": 26199, "s": 26188, "text": "Example 3:" }, { "code": "// Golang program to illustrate the usage of// fmt.print() function // Including the main packagepackage main // Importing fmtimport ( \"fmt\") // Calling mainfunc main() { // Declaring some const variables const num1, num2, num3 = 5, 15, 15 // Calling print() function fmt.Print(num1, num2, num3, \"\\n\") // It is conventional not to worry about any // error returned by Print. }", "e": 26607, "s": 26199, "text": null }, { "code": null, "e": 26615, "s": 26607, "text": "Output:" }, { "code": null, "e": 26624, "s": 26615, "text": "5 15 15\n" }, { "code": null, "e": 26756, "s": 26624, "text": "In the above code, the constant variables used are numbers hence spaces are added in between two numbers shown above in the output." }, { "code": null, "e": 26767, "s": 26756, "text": "Golang-fmt" }, { "code": null, "e": 26779, "s": 26767, "text": "Go Language" }, { "code": null, "e": 26877, "s": 26779, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26886, "s": 26877, "text": "Comments" }, { "code": null, "e": 26899, "s": 26886, "text": "Old Comments" }, { "code": null, "e": 26928, "s": 26899, "text": "How to Parse JSON in Golang?" }, { "code": null, "e": 26952, "s": 26928, "text": "Defer Keyword in Golang" }, { "code": null, "e": 26973, "s": 26952, "text": "Loops in Go Language" }, { "code": null, "e": 27019, "s": 26973, "text": "time.Parse() Function in Golang With Examples" }, { "code": null, "e": 27053, "s": 27019, "text": "Anonymous function in Go Language" }, { "code": null, "e": 27078, "s": 27053, "text": "Time Durations in Golang" }, { "code": null, "e": 27099, "s": 27078, "text": "Structures in Golang" }, { "code": null, "e": 27117, "s": 27099, "text": "Strings in Golang" }, { "code": null, "e": 27172, "s": 27117, "text": "How to iterate over an Array using for loop in Golang?" } ]
How to add a JSON string to an existing JSON file in Java?
A Gson is a json library for Java and it can be used to generate a JSON. In the initial step, we can read a JSON file and parsing to a Java object then need to typecast the Java object to a JSonObject and parsing to a JsonArray. Then iterating this JSON array to print the JsonElement. We can create a JsonWriter class to write a JSON encoded value to a stream, one token at a time. Finally, a new JSON string can be written to an existing json file. import java.io.*; import java.util.*; import com.google.gson.*; import com.google.gson.stream.*; import com.google.gson.annotations.*; public class JSONFilewriteTest { public static String nameRead; public static void main(String[] args) { try { JsonParser parser = new JsonParser(); Object obj = parser.parse(new FileReader("employee1.json")); JsonObject jsonObject = (JsonObject) obj; System.out.println("The values of employee1.json file:\n" + jsonObject); JsonArray msg = (JsonArray)jsonObject.get("emps"); Iterator<JsonElement> iterator = msg.iterator(); while(iterator.hasNext()) { nameRead = iterator.next().toString(); System.out.println(nameRead); } Name name = new Name(); name.setName("Vamsi"); Gson gson = new Gson(); String json = gson.toJson(name); FileWriter file = new FileWriter("employee1.json", false); JsonWriter jw = new JsonWriter(file); iterator = msg.iterator(); Employees emps = new Employees(); while(iterator.hasNext()) { emps.addEmployee(gson.fromJson(iterator.next().toString(), Name.class)); } emps.addEmployee(name); gson.toJson(emps, Employees.class, jw); file.close(); System.out.println("data added to an existing employee1.json file successfully"); } catch(Exception e) { e.printStackTrace(); } } } // Name class class Name { @Expose private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } } // Employees class class Employees { @Expose List<Name> emps = new ArrayList<>(); public List<Name> getEmployees() { return emps; } public void addEmployee(Name name) { this.emps.add(name); } } The values of employee1.json file: {"emps":[{"name":"Adithya"},{"name":"Jai"}]} {"name":"Adithya"} {"name":"Jai"} data added to an existing employee1.json file successfully
[ { "code": null, "e": 1514, "s": 1062, "text": "A Gson is a json library for Java and it can be used to generate a JSON. In the initial step, we can read a JSON file and parsing to a Java object then need to typecast the Java object to a JSonObject and parsing to a JsonArray. Then iterating this JSON array to print the JsonElement. We can create a JsonWriter class to write a JSON encoded value to a stream, one token at a time. Finally, a new JSON string can be written to an existing json file. " }, { "code": null, "e": 3427, "s": 1514, "text": "import java.io.*;\nimport java.util.*;\nimport com.google.gson.*;\nimport com.google.gson.stream.*;\nimport com.google.gson.annotations.*;\npublic class JSONFilewriteTest {\n public static String nameRead;\n public static void main(String[] args) {\n try {\n JsonParser parser = new JsonParser();\n Object obj = parser.parse(new FileReader(\"employee1.json\"));\n JsonObject jsonObject = (JsonObject) obj;\n System.out.println(\"The values of employee1.json file:\\n\" + jsonObject);\n JsonArray msg = (JsonArray)jsonObject.get(\"emps\");\n Iterator<JsonElement> iterator = msg.iterator();\n while(iterator.hasNext()) {\n nameRead = iterator.next().toString();\n System.out.println(nameRead);\n }\n Name name = new Name();\n name.setName(\"Vamsi\");\n Gson gson = new Gson();\n String json = gson.toJson(name);\n\n FileWriter file = new FileWriter(\"employee1.json\", false);\n JsonWriter jw = new JsonWriter(file);\n iterator = msg.iterator();\n Employees emps = new Employees();\n while(iterator.hasNext()) {\n emps.addEmployee(gson.fromJson(iterator.next().toString(), Name.class));\n }\n emps.addEmployee(name);\n gson.toJson(emps, Employees.class, jw);\n file.close();\n System.out.println(\"data added to an existing employee1.json file successfully\");\n } catch(Exception e) {\n e.printStackTrace();\n }\n }\n}\n// Name class\nclass Name {\n @Expose\n private String name;\n public String getName() {\n return name;\n }\n public void setName(String name) {\n this.name = name;\n }\n}\n// Employees class\nclass Employees {\n @Expose\n List<Name> emps = new ArrayList<>();\n public List<Name> getEmployees() {\n return emps;\n }\n public void addEmployee(Name name) {\n this.emps.add(name);\n }\n}" }, { "code": null, "e": 3600, "s": 3427, "text": "The values of employee1.json file:\n{\"emps\":[{\"name\":\"Adithya\"},{\"name\":\"Jai\"}]}\n{\"name\":\"Adithya\"}\n{\"name\":\"Jai\"}\ndata added to an existing employee1.json file successfully" } ]
Count Odd Even - Java | Practice | GeeksforGeeks
Congrats on completing Module 1. In the previous module we learnt about the basics of Java. Now, we'll move to more complex stuff. Here, we'll learn about arrays. Given an array A of N elements. The task is to count number of even and odd elements in the array. Example 1: Input: 5 1 2 3 4 5 Output: 3 2 Explanation: In the given array, there are 3 odd elements (1, 3, 5) and 2 even elements (2 and 4). Example 2: Input: 4 1 6 18 7 Output: 2 2 Explanation: In the given array, there are 2 odd elements (1, 7) and 2 even elements (6 and 18). User Task: Your task is to complete the function countOddEven() which should print number of odd and number of even elements in a single line seperated by space. You don't need to provide the new line. Constraints: 1 <= N <= 106 1 <= Ai <= 106 0 sahilkumarkatiriya4 days ago Very simple logic: class Geeks { static void countOddEven(int a[], int n) { // Your code here int odd=0,even=0; for(int i=0;i<n;i++) { if(a[i]%2==0) { even++; } } odd=n-even; System.out.print(odd + " " + even); }} 0 mycountryakash1 month ago class Geeks { static void countOddEven(int a[], int n) { // Your code here int Evencount =0; int oddCount = 0; for(int i=0;i<n;i++){ if((a[i] & 1 )==1){ oddCount =oddCount+1 ; }else{ Evencount =Evencount+1; } } System.out.print(oddCount +" " + Evencount); }} +1 shrutidhongade161 month ago class Geeks { static void countOddEven(int a[], int n) { int even = 0; int odd = 0; for (int i=0; i< a.length; i++){ if (a[i] % 2 == 0){ even += 1; } else{ odd += 1; } } System.out.printf("%d %d",odd, even); } } 0 ravi119033852 months ago // Your code here int count_even=0; int count_odd=0; for(int i=0;i<n;i++) { if(a[i]%2==0) count_even++; else count_odd++; } System.out.print(count_odd+" "+count_even); 0 aakasshuit2 months ago //Java Solutio int odd=0,even=0; for(int i=0;i<n;i++){ if(a[i]%2==0){ even++; }else{ odd++; } } System.out.print(odd+" "+even); 0 patelshivanshu20172 months ago class Geeks { static void countOddEven(int a[], int n) { // Your code here int counte=0; int countodd=0; for(int i=0;i<n;i++){ if(a[i]%2==0){ counte++; }else{ countodd++; } } System.out.print(countodd+" "+counte); }} 0 rajeevdash073 months ago EASY JAVA SOLUTION int count_even=0; int count_odd=0; for(int i = 0;i < n; i++){ if(a[i]==0){ continue; } else if(a[i]%2==0){ count_even++; } else{ count_odd++; } } System.out.print(count_odd+" "+count_even); 0 rajeevdash07 This comment was deleted. 0 harsh84253 months ago class Geeks { static void countOddEven(int a[], int n) { // Your code here long even=0,odd=0; for(int i=0;i<a.length;i++){ if(a[i] == 0){ continue; } else if(a[i]%2==0){ even++; } else{ odd++; } } System.out.print(odd+" "+even); }} +2 ayush90833 months ago → You need only one variable to print the count of both ‘odd’ and ‘even’ numbers in an array. => if there is x number of odd numbers in an array, then it's simply means that there is only n-x even numbers in that same array. Where n is the size of the given array. → Use bitwise AND for fast execution. //solution class Geeks { static void countOddEven(int a[], int n) { int x = 0; for(int i : a) if((i&1) == 1) x++; System.out.print(x + " " + (n-x)); }} 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": 259, "s": 226, "text": "Congrats on completing Module 1." }, { "code": null, "e": 390, "s": 259, "text": "In the previous module we learnt about the basics of Java. Now, we'll move to more complex stuff. Here, we'll learn about arrays." }, { "code": null, "e": 489, "s": 390, "text": "Given an array A of N elements. The task is to count number of even and odd elements in the array." }, { "code": null, "e": 500, "s": 489, "text": "Example 1:" }, { "code": null, "e": 633, "s": 500, "text": "Input:\n5\n1 2 3 4 5\n\nOutput:\n3 2\n\nExplanation:\nIn the given array, there are 3 odd elements \n(1, 3, 5) and 2 even elements (2 and 4)." }, { "code": null, "e": 644, "s": 633, "text": "Example 2:" }, { "code": null, "e": 773, "s": 644, "text": "Input:\n4\n1 6 18 7\n\nOutput:\n2 2\n\nExplanation:\nIn the given array, there are 2 odd\nelements (1, 7) and 2 even elements (6 and 18)." }, { "code": null, "e": 975, "s": 773, "text": "User Task:\nYour task is to complete the function countOddEven() which should print number of odd and number of even elements in a single line seperated by space. You don't need to provide the new line." }, { "code": null, "e": 1017, "s": 975, "text": "Constraints:\n1 <= N <= 106\n1 <= Ai <= 106" }, { "code": null, "e": 1019, "s": 1017, "text": "0" }, { "code": null, "e": 1048, "s": 1019, "text": "sahilkumarkatiriya4 days ago" }, { "code": null, "e": 1067, "s": 1048, "text": "Very simple logic:" }, { "code": null, "e": 1128, "s": 1069, "text": "class Geeks { static void countOddEven(int a[], int n) {" }, { "code": null, "e": 1322, "s": 1128, "text": " // Your code here int odd=0,even=0; for(int i=0;i<n;i++) { if(a[i]%2==0) { even++; } } odd=n-even; System.out.print(odd + \" \" + even); }}" }, { "code": null, "e": 1324, "s": 1322, "text": "0" }, { "code": null, "e": 1350, "s": 1324, "text": "mycountryakash1 month ago" }, { "code": null, "e": 1409, "s": 1350, "text": "class Geeks { static void countOddEven(int a[], int n) {" }, { "code": null, "e": 1675, "s": 1409, "text": " // Your code here int Evencount =0; int oddCount = 0; for(int i=0;i<n;i++){ if((a[i] & 1 )==1){ oddCount =oddCount+1 ; }else{ Evencount =Evencount+1; } } System.out.print(oddCount +\" \" + Evencount); }}" }, { "code": null, "e": 1678, "s": 1675, "text": "+1" }, { "code": null, "e": 1706, "s": 1678, "text": "shrutidhongade161 month ago" }, { "code": null, "e": 2065, "s": 1706, "text": "class Geeks {\n static void countOddEven(int a[], int n) {\n \n int even = 0;\n int odd = 0;\n for (int i=0; i< a.length; i++){\n if (a[i] % 2 == 0){\n even += 1;\n }\n else{\n odd += 1;\n }\n }\n \n System.out.printf(\"%d %d\",odd, even);\n\n }\n}" }, { "code": null, "e": 2067, "s": 2065, "text": "0" }, { "code": null, "e": 2092, "s": 2067, "text": "ravi119033852 months ago" }, { "code": null, "e": 2336, "s": 2092, "text": "// Your code here int count_even=0; int count_odd=0; for(int i=0;i<n;i++) { if(a[i]%2==0) count_even++; else count_odd++; } System.out.print(count_odd+\" \"+count_even);" }, { "code": null, "e": 2338, "s": 2336, "text": "0" }, { "code": null, "e": 2361, "s": 2338, "text": "aakasshuit2 months ago" }, { "code": null, "e": 2590, "s": 2361, "text": "//Java Solutio\n\n int odd=0,even=0;\n for(int i=0;i<n;i++){\n if(a[i]%2==0){\n even++;\n }else{\n odd++;\n }\n }\n System.out.print(odd+\" \"+even);" }, { "code": null, "e": 2592, "s": 2590, "text": "0" }, { "code": null, "e": 2623, "s": 2592, "text": "patelshivanshu20172 months ago" }, { "code": null, "e": 2682, "s": 2623, "text": "class Geeks { static void countOddEven(int a[], int n) {" }, { "code": null, "e": 2965, "s": 2682, "text": " // Your code here int counte=0; int countodd=0; for(int i=0;i<n;i++){ if(a[i]%2==0){ counte++; }else{ countodd++; } } System.out.print(countodd+\" \"+counte); }}" }, { "code": null, "e": 2967, "s": 2965, "text": "0" }, { "code": null, "e": 2992, "s": 2967, "text": "rajeevdash073 months ago" }, { "code": null, "e": 3011, "s": 2992, "text": "EASY JAVA SOLUTION" }, { "code": null, "e": 3403, "s": 3013, "text": "int count_even=0; int count_odd=0; for(int i = 0;i < n; i++){ if(a[i]==0){ continue; } else if(a[i]%2==0){ count_even++; } else{ count_odd++; } } System.out.print(count_odd+\" \"+count_even);" }, { "code": null, "e": 3405, "s": 3403, "text": "0" }, { "code": null, "e": 3418, "s": 3405, "text": "rajeevdash07" }, { "code": null, "e": 3444, "s": 3418, "text": "This comment was deleted." }, { "code": null, "e": 3446, "s": 3444, "text": "0" }, { "code": null, "e": 3468, "s": 3446, "text": "harsh84253 months ago" }, { "code": null, "e": 3527, "s": 3468, "text": "class Geeks { static void countOddEven(int a[], int n) {" }, { "code": null, "e": 3844, "s": 3527, "text": " // Your code here long even=0,odd=0; for(int i=0;i<a.length;i++){ if(a[i] == 0){ continue; } else if(a[i]%2==0){ even++; } else{ odd++; } } System.out.print(odd+\" \"+even); }}" }, { "code": null, "e": 3847, "s": 3844, "text": "+2" }, { "code": null, "e": 3869, "s": 3847, "text": "ayush90833 months ago" }, { "code": null, "e": 3963, "s": 3869, "text": "→ You need only one variable to print the count of both ‘odd’ and ‘even’ numbers in an array." }, { "code": null, "e": 4138, "s": 3963, "text": " => if there is x number of odd numbers in an array, then it's simply means that there is only n-x even numbers in that same array. Where n is the size of the given array." }, { "code": null, "e": 4178, "s": 4140, "text": "→ Use bitwise AND for fast execution." }, { "code": null, "e": 4189, "s": 4178, "text": "//solution" }, { "code": null, "e": 4379, "s": 4189, "text": "class Geeks { static void countOddEven(int a[], int n) { int x = 0; for(int i : a) if((i&1) == 1) x++; System.out.print(x + \" \" + (n-x)); }}" }, { "code": null, "e": 4525, "s": 4379, "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": 4561, "s": 4525, "text": " Login to access your submissions. " }, { "code": null, "e": 4571, "s": 4561, "text": "\nProblem\n" }, { "code": null, "e": 4581, "s": 4571, "text": "\nContest\n" }, { "code": null, "e": 4644, "s": 4581, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 4792, "s": 4644, "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": 5000, "s": 4792, "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": 5106, "s": 5000, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Summarization of COVID research papers using BART model | by Priya Dwivedi | Towards Data Science
In collaboration with Allen AI, White House and several other institutions, Kaggle has open sourced COVID-19 open research data set (CORD-19) . CORD-19 is a resource of over 52,000 scholarly articles, including over 41,000 with full text, about COVID-19, SARS-CoV-2, and related coronaviruses. This freely available dataset is provided to the global research community to apply recent advances in natural language processing and other AI techniques to generate new insights in support of the ongoing fight against this infectious disease. There is a growing urgency for these approaches because of the rapid acceleration in new coronavirus literature, making it difficult for the medical research community to keep up. At Deep Learning Analytics, we have been spending time, trying different NLP techniques on this data set. In this blog, we show how you can use cutting edge Transformer based summarization models to summarize research papers related to COVID-19. This can be quite useful in getting a quick snapshot of the research paper or sections of it to decide whether you want to fully read it. Please note that I am not a health professional and the opinions of this article should not be interpreted as professional advice. We are very passionate about using data science and machine learning to solve problems. Please reach out to us through here if you are a Health Services company and looking for data science help in fighting this crisis. Original full story published on our website here. According to Wikipedia, Summarization is the process of shortening a set of data computationally, to create a subset (a summary) that represents the most important or relevant information within the original content. Summarization can be applied to multiple data types like text, images or video. Summarization has been used many practical applications — summarizing articles, summarizing multiple documents on the same topic, summarizing video content to generate highlights in sports etc. Summarization in text, specifically, can be extremely useful as it saves the users having to read long articles , blogs or other pieces of text. There can be different types of summarization as shown in the figure below which is borrowed from this blog. There are multiple types of summarizations — based on input type, based on desired output or purpose. The input to summarization can be single or multiple documents. Multi-document summarization is a more challenging task but there has been some recent promising research. The summarization task can be either abstractive or extractive. Extractive summarization creates a summary by selecting a subset of the existing text. Extractive summarization is akin to highlighting. Abstractive summarization involves understanding the text and rewriting it. You can also read more about summarization in my blog here. We will be leveraging huggingface’s transformers library to perform summarization on the scientific articles. This library has implementations of different algorithms. In this blog, we will be using the BART algorithm. BART is a denoising autoencoder for pretraining sequence-to-sequence models. As described in their paper, BART is trained by (1) corrupting text with an arbitrary noising function, and (2) learning a model to reconstruct the original text. As a result, BART performs well on multiple tasks like abstractive dialogue, question answering and summarization. Specifically, for summarization, with gains of up to 6 ROUGE score. Let's test out the BART transformer model supported by Huggingface. This model is trained on the CNN/Daily Mail data set which has been the canonical data set for summarization work. The data sets consist of news articles and abstractive summaries written by humans. Before we run this model on research papers, let's run this on a news article. The following code snippets can be used to generate a summary on a news article from transformers import pipelinesummarizer = pipeline(“summarization”) print(summarizer(ARTICLE, max_length=130, min_length=30)) Running the summarization command generates the summary below. Liana Barrientos has been married 10 times, sometimes within two weeks of each other. Prosecutors say the marriages were part of an immigration scam. She pleaded not guilty at State Supreme Court in the Bronx on Friday. In my opinion this is a very good short summary of the news article.The max_length parameter can be adjusted to get longer summaries. Many scientists and researchers across the globe are working on understanding more about the virus to develop effective treatments which can include vaccines or drugs to reduce the severity of attack. Our knowledge on this topic keeps increasing. AI can help humans prioritize their time effectively if it can do a first pass of reading through the research and providing a good summary. However summarization tends to be a difficult and subjective task. To truly summarize AI needs to understand the content which is difficult due to the large variation in writing styles of researchers. In this blog we evaluate how well the BART Transformer model does in summarizing the content of COVID-19 papers. To get a clean data set of CORD-19 research papers, we will be using the dataframe biorxiv_clean.csv from here. Big thanks for xhulu on Kaggle for creating this. Lets get started with summarizing research papers! ## Read the data frameimport pandas as pddata = pd.read_csv('biorxiv_clean.csv') Once we read the dataframe, data looks like this: The key columns we have are paper_id, title, abstract, authors, text, bibliography etc. Then, we will just loop through the dataframe and generate summaries. As we can see, the column ‘text’ has the scientific text in the dataframe. from transformers import pipelinesummarizer = pipeline(“summarization”)for i, text in enumerate(data): print(summarizer(data[‘text’].iloc[i], max_length=1000, min_length=30)) You can experiment with min and max length parameters. We chose the above values since it provides the best results. Some examples of these summaries are: Text: https://www.mdpi.com/2076-0817/9/2/107 Summary generated by BART Transformer: Strongyloidiasis is a prevailing helminth infection ubiquitous in tropical and subtropical areas. However, prevalence data are scarce in migrant populations. This study evaluated the prevalence of this infection in people being attended in six Spanish hospitals. The prevalence was around 9%, being higher in Africa and Latin America compared with other regions. In addition, the prevalence in patients with an impaired immune system was lower compared with people non suffering immunosuppression. Text: https://www.biorxiv.org/content/10.1101/2020.02.22.961268v1 Summary generated by BART Transformer: Transcription polymerase chain reaction (RT-PCR) is a standard and routinely used technique for the analysis and quantification of various pathogenic RNA. After the outbreak of COVID-19, several methods and kits for the detection of SARS-CoV-2 genomic RNA have been reported. Traditional methods consume a large number of operators, but give low diagnosis efficiency and high risk of cross infection. Magnetic nanoparticles (MNPs)-based extraction methods are centrifuge-free and have proven to be easy to operate and compatible to automation. Observations: Overall, I think the BART model that is trained on CNN/Daily Mail data has mixed performance. It does provide a coherent summary which is factually correct but if this summary is compared to the abstract of the paper, then we see some gaps: It may miss out on some key approaches or other related metadata that the researchers might want to see as a part of the summary. Summary tends to be shorter than the abstract on the paper and also weaker in terms of conclusion The embeddings used in BART model are trained on regular English vocabulary and may not be correctly understanding the scientific jargon here In order to address these challenges, the best way would be to finetune the BART model on text and abstracts extracted from the above data frame. We started doing this but couldn’t continue forward much due to the intense compute requirements for training a good summarization model. In this article, we see that pretrained BART model can be used to extract summaries from COVID-19 research papers. Research paper summarization is a difficult task due to scientific terminology and varying writing styles of different researchers. The BART model does quite well in generating summaries of the paper. Its limitation though is that it may not cover all the salient points.
[ { "code": null, "e": 891, "s": 172, "text": "In collaboration with Allen AI, White House and several other institutions, Kaggle has open sourced COVID-19 open research data set (CORD-19) . CORD-19 is a resource of over 52,000 scholarly articles, including over 41,000 with full text, about COVID-19, SARS-CoV-2, and related coronaviruses. This freely available dataset is provided to the global research community to apply recent advances in natural language processing and other AI techniques to generate new insights in support of the ongoing fight against this infectious disease. There is a growing urgency for these approaches because of the rapid acceleration in new coronavirus literature, making it difficult for the medical research community to keep up." }, { "code": null, "e": 1406, "s": 891, "text": "At Deep Learning Analytics, we have been spending time, trying different NLP techniques on this data set. In this blog, we show how you can use cutting edge Transformer based summarization models to summarize research papers related to COVID-19. This can be quite useful in getting a quick snapshot of the research paper or sections of it to decide whether you want to fully read it. Please note that I am not a health professional and the opinions of this article should not be interpreted as professional advice." }, { "code": null, "e": 1677, "s": 1406, "text": "We are very passionate about using data science and machine learning to solve problems. Please reach out to us through here if you are a Health Services company and looking for data science help in fighting this crisis. Original full story published on our website here." }, { "code": null, "e": 2168, "s": 1677, "text": "According to Wikipedia, Summarization is the process of shortening a set of data computationally, to create a subset (a summary) that represents the most important or relevant information within the original content. Summarization can be applied to multiple data types like text, images or video. Summarization has been used many practical applications — summarizing articles, summarizing multiple documents on the same topic, summarizing video content to generate highlights in sports etc." }, { "code": null, "e": 2422, "s": 2168, "text": "Summarization in text, specifically, can be extremely useful as it saves the users having to read long articles , blogs or other pieces of text. There can be different types of summarization as shown in the figure below which is borrowed from this blog." }, { "code": null, "e": 2695, "s": 2422, "text": "There are multiple types of summarizations — based on input type, based on desired output or purpose. The input to summarization can be single or multiple documents. Multi-document summarization is a more challenging task but there has been some recent promising research." }, { "code": null, "e": 3032, "s": 2695, "text": "The summarization task can be either abstractive or extractive. Extractive summarization creates a summary by selecting a subset of the existing text. Extractive summarization is akin to highlighting. Abstractive summarization involves understanding the text and rewriting it. You can also read more about summarization in my blog here." }, { "code": null, "e": 3200, "s": 3032, "text": "We will be leveraging huggingface’s transformers library to perform summarization on the scientific articles. This library has implementations of different algorithms." }, { "code": null, "e": 3674, "s": 3200, "text": "In this blog, we will be using the BART algorithm. BART is a denoising autoencoder for pretraining sequence-to-sequence models. As described in their paper, BART is trained by (1) corrupting text with an arbitrary noising function, and (2) learning a model to reconstruct the original text. As a result, BART performs well on multiple tasks like abstractive dialogue, question answering and summarization. Specifically, for summarization, with gains of up to 6 ROUGE score." }, { "code": null, "e": 4100, "s": 3674, "text": "Let's test out the BART transformer model supported by Huggingface. This model is trained on the CNN/Daily Mail data set which has been the canonical data set for summarization work. The data sets consist of news articles and abstractive summaries written by humans. Before we run this model on research papers, let's run this on a news article. The following code snippets can be used to generate a summary on a news article" }, { "code": null, "e": 4172, "s": 4100, "text": "from transformers import pipelinesummarizer = pipeline(“summarization”)" }, { "code": null, "e": 4230, "s": 4172, "text": "print(summarizer(ARTICLE, max_length=130, min_length=30))" }, { "code": null, "e": 4293, "s": 4230, "text": "Running the summarization command generates the summary below." }, { "code": null, "e": 4513, "s": 4293, "text": "Liana Barrientos has been married 10 times, sometimes within two weeks of each other. Prosecutors say the marriages were part of an immigration scam. She pleaded not guilty at State Supreme Court in the Bronx on Friday." }, { "code": null, "e": 4647, "s": 4513, "text": "In my opinion this is a very good short summary of the news article.The max_length parameter can be adjusted to get longer summaries." }, { "code": null, "e": 5349, "s": 4647, "text": "Many scientists and researchers across the globe are working on understanding more about the virus to develop effective treatments which can include vaccines or drugs to reduce the severity of attack. Our knowledge on this topic keeps increasing. AI can help humans prioritize their time effectively if it can do a first pass of reading through the research and providing a good summary. However summarization tends to be a difficult and subjective task. To truly summarize AI needs to understand the content which is difficult due to the large variation in writing styles of researchers. In this blog we evaluate how well the BART Transformer model does in summarizing the content of COVID-19 papers." }, { "code": null, "e": 5511, "s": 5349, "text": "To get a clean data set of CORD-19 research papers, we will be using the dataframe biorxiv_clean.csv from here. Big thanks for xhulu on Kaggle for creating this." }, { "code": null, "e": 5562, "s": 5511, "text": "Lets get started with summarizing research papers!" }, { "code": null, "e": 5643, "s": 5562, "text": "## Read the data frameimport pandas as pddata = pd.read_csv('biorxiv_clean.csv')" }, { "code": null, "e": 5693, "s": 5643, "text": "Once we read the dataframe, data looks like this:" }, { "code": null, "e": 5781, "s": 5693, "text": "The key columns we have are paper_id, title, abstract, authors, text, bibliography etc." }, { "code": null, "e": 5926, "s": 5781, "text": "Then, we will just loop through the dataframe and generate summaries. As we can see, the column ‘text’ has the scientific text in the dataframe." }, { "code": null, "e": 6105, "s": 5926, "text": "from transformers import pipelinesummarizer = pipeline(“summarization”)for i, text in enumerate(data): print(summarizer(data[‘text’].iloc[i], max_length=1000, min_length=30))" }, { "code": null, "e": 6222, "s": 6105, "text": "You can experiment with min and max length parameters. We chose the above values since it provides the best results." }, { "code": null, "e": 6260, "s": 6222, "text": "Some examples of these summaries are:" }, { "code": null, "e": 6266, "s": 6260, "text": "Text:" }, { "code": null, "e": 6305, "s": 6266, "text": "https://www.mdpi.com/2076-0817/9/2/107" }, { "code": null, "e": 6344, "s": 6305, "text": "Summary generated by BART Transformer:" }, { "code": null, "e": 6842, "s": 6344, "text": "Strongyloidiasis is a prevailing helminth infection ubiquitous in tropical and subtropical areas. However, prevalence data are scarce in migrant populations. This study evaluated the prevalence of this infection in people being attended in six Spanish hospitals. The prevalence was around 9%, being higher in Africa and Latin America compared with other regions. In addition, the prevalence in patients with an impaired immune system was lower compared with people non suffering immunosuppression." }, { "code": null, "e": 6848, "s": 6842, "text": "Text:" }, { "code": null, "e": 6908, "s": 6848, "text": "https://www.biorxiv.org/content/10.1101/2020.02.22.961268v1" }, { "code": null, "e": 6947, "s": 6908, "text": "Summary generated by BART Transformer:" }, { "code": null, "e": 7491, "s": 6947, "text": "Transcription polymerase chain reaction (RT-PCR) is a standard and routinely used technique for the analysis and quantification of various pathogenic RNA. After the outbreak of COVID-19, several methods and kits for the detection of SARS-CoV-2 genomic RNA have been reported. Traditional methods consume a large number of operators, but give low diagnosis efficiency and high risk of cross infection. Magnetic nanoparticles (MNPs)-based extraction methods are centrifuge-free and have proven to be easy to operate and compatible to automation." }, { "code": null, "e": 7505, "s": 7491, "text": "Observations:" }, { "code": null, "e": 7746, "s": 7505, "text": "Overall, I think the BART model that is trained on CNN/Daily Mail data has mixed performance. It does provide a coherent summary which is factually correct but if this summary is compared to the abstract of the paper, then we see some gaps:" }, { "code": null, "e": 7876, "s": 7746, "text": "It may miss out on some key approaches or other related metadata that the researchers might want to see as a part of the summary." }, { "code": null, "e": 7974, "s": 7876, "text": "Summary tends to be shorter than the abstract on the paper and also weaker in terms of conclusion" }, { "code": null, "e": 8116, "s": 7974, "text": "The embeddings used in BART model are trained on regular English vocabulary and may not be correctly understanding the scientific jargon here" }, { "code": null, "e": 8400, "s": 8116, "text": "In order to address these challenges, the best way would be to finetune the BART model on text and abstracts extracted from the above data frame. We started doing this but couldn’t continue forward much due to the intense compute requirements for training a good summarization model." } ]
Count of Double Prime numbers in a given range L to R - GeeksforGeeks
16 Apr, 2021 Given two integers L and R, the task to find the number of Double Prime numbers in the range. A number N is called double prime when the count of prime numbers in the range 1 to N (excluding 1 and including N) is also prime. Examples: Input: L = 3, R = 10 Output: 4 Explanation: For 3, we have the range 1, 2, 3, and count of prime number is 2 (which is also a prime no.) For 4, we have the range 1, 2, 3, 4, and count of a prime number is 2 (which is also a prime no.) For 5, we have the range 1, 2, 3, 4, 5, and count of a prime number is 3 (which is also a prime no.) For 6, we have the range 1, 2, 3, 4, 5, 6, and count of prime numbers is 3 (which is also a prime no.) For 7, we have the range 1, 2, 3, 4, 5, 6, 7, and count of prime numbers is 4 which is nonprime. Similarly for other numbers till R = 10, the count of prime numbers is nonprime. Hence the count of double prime numbers is 4.Input: L = 4, R = 12 Output: 5 Explanation: For the given range there are total 5 double prime numbers. Approach:To solve the problem mentioned above we will use the concept of Sieve to generate prime numbers. Generate all prime numbers for 0 to 106 and store in an array. Initialize a variable count to keep a track of prime numbers from 1 to some ith position. Then for every prime number we will increment the count and also set dp[count] = 1 (where dp is the array which stores a double prime number) indicating the number of numbers from 1 to some ith position that are prime. Lastly, find the cumulative sum of dp array so the answer will be dp[R] – dp[L – 1]. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program to find the count// of Double Prime numbers// in the range L to R #include <bits/stdc++.h>using namespace std; // Array to make Sieve// where arr[i]=0 indicates// non prime and arr[i] = 1// indicates primeint arr[1000001]; // Array to find double primeint dp[1000001]; // Function to find the number// double prime numbers in rangevoid count(){ int maxN = 1000000, i, j; // Assume all numbers as prime for (i = 0; i < maxN; i++) arr[i] = 1; arr[0] = 0; arr[1] = 0; for (i = 2; i * i <= maxN; i++) { // Check if the number is prime if (arr[i] == 1) { // check for multiples of i for (j = 2 * i; j <= maxN; j += i) { // Make all multiples of // ith prime as non-prime arr[j] = 0; } } } int cnt = 0; for (i = 0; i <= maxN; i++) { // Check if number at ith position // is prime then increment count if (arr[i] == 1) cnt++; if (arr[cnt] == 1) // Indicates count of numbers // from 1 to i that are // also prime and // hence double prime dp[i] = 1; else // If number is not a double prime dp[i] = 0; } for (i = 1; i <= maxN; i++) // finding cumulative sum dp[i] += dp[i - 1];} // Driver codeint main(){ int L = 4, R = 12; count(); cout << dp[R] - dp[L - 1]; return 0;} // Java program to find the count// of Double Prime numbers// in the range L to Rimport java.util.*;import java.lang.*;class GFG{ // Array to make Sieve// where arr[i]=0 indicates// non prime and arr[i] = 1// indicates primestatic int[] arr = new int[1000001]; // Array to find double primestatic int[] dp = new int[1000001]; // Function to find the number// double prime numbers in rangestatic void count(){ int maxN = 1000000, i, j; // Assume all numbers as prime for (i = 0; i < maxN; i++) arr[i] = 1; arr[0] = 0; arr[1] = 0; for (i = 2; i * i <= maxN; i++) { // Check if the number is prime if (arr[i] == 1) { // check for multiples of i for (j = 2 * i; j <= maxN; j += i) { // Make all multiples of // ith prime as non-prime arr[j] = 0; } } } int cnt = 0; for (i = 0; i <= maxN; i++) { // Check if number at ith position // is prime then increment count if (arr[i] == 1) cnt++; if (arr[cnt] == 1) // Indicates count of numbers // from 1 to i that are // also prime and // hence double prime dp[i] = 1; else // If number is not a double prime dp[i] = 0; } for (i = 1; i <= maxN; i++) // finding cumulative sum dp[i] += dp[i - 1];} // Driver codepublic static void main(String[] args){ int L = 4, R = 12; count(); System.out.println(dp[R] - dp[L - 1]);}} // This code is contributed by offbeat # Python3 program to find the count# of Double Prime numbers# in the range L to R # Array to make Sieve# where arr[i]=0 indicates# non prime and arr[i] = 1# indicates primearr = [0] * 1000001 # Array to find double primedp = [0] * 1000001 # Function to find the number# double prime numbers in rangedef count(): maxN = 1000000 # Assume all numbers as prime for i in range(0, maxN): arr[i] = 1 arr[0] = 0 arr[1] = 0 i = 2 while(i * i <= maxN): # Check if the number is prime if (arr[i] == 1): # Check for multiples of i for j in range(2 * i, maxN + 1, i): # Make all multiples of # ith prime as non-prime arr[j] = 0 i += 1 cnt = 0 for i in range(0, maxN + 1): # Check if number at ith position # is prime then increment count if (arr[i] == 1): cnt += 1 if (arr[cnt] == 1): # Indicates count of numbers # from 1 to i that are # also prime and # hence double prime dp[i] = 1 else: # If number is not a double prime dp[i] = 0 for i in range(0, maxN + 1): # Finding cumulative sum dp[i] += dp[i - 1] # Driver codeL = 4R = 12 count() print(dp[R] - dp[L - 1]) # This code is contributed by sanjoy_62 // C# program to find the count// of Double Prime numbers// in the range L to Rusing System;class GFG{ // Array to make Sieve// where arr[i]=0 indicates// non prime and arr[i] = 1// indicates primestatic int[] arr = new int[1000001]; // Array to find double primestatic int[] dp = new int[1000001]; // Function to find the number// double prime numbers in rangestatic void count(){ int maxN = 1000000, i, j; // Assume all numbers as prime for (i = 0; i < maxN; i++) arr[i] = 1; arr[0] = 0; arr[1] = 0; for (i = 2; i * i <= maxN; i++) { // Check if the number is prime if (arr[i] == 1) { // check for multiples of i for (j = 2 * i; j <= maxN; j += i) { // Make all multiples of // ith prime as non-prime arr[j] = 0; } } } int cnt = 0; for (i = 0; i <= maxN; i++) { // Check if number at ith position // is prime then increment count if (arr[i] == 1) cnt++; if (arr[cnt] == 1) // Indicates count of numbers // from 1 to i that are // also prime and // hence double prime dp[i] = 1; else // If number is not a double prime dp[i] = 0; } for (i = 1; i <= maxN; i++) // finding cumulative sum dp[i] += dp[i - 1];} // Driver codepublic static void Main(){ int L = 4, R = 12; count(); Console.Write(dp[R] - dp[L - 1]);}} // This code is contributed by Code_Mech <script> // Javascript program to find the count// of Double Prime numbers// in the range L to R // Array to make Sieve// where arr[i]=0 indicates// non prime and arr[i] = 1// indicates primelet arr = []; // Array to find double primelet dp = []; // Function to find the number// double prime numbers in rangefunction count(){ let maxN = 1000000, i, j; // Assume all numbers as prime for (i = 0; i < maxN; i++) arr[i] = 1; arr[0] = 0; arr[1] = 0; for (i = 2; i * i <= maxN; i++) { // Check if the number is prime if (arr[i] == 1) { // check for multiples of i for (j = 2 * i; j <= maxN; j += i) { // Make all multiples of // ith prime as non-prime arr[j] = 0; } } } let cnt = 0; for (i = 0; i <= maxN; i++) { // Check if number at ith position // is prime then increment count if (arr[i] == 1) cnt++; if (arr[cnt] == 1) // Indicates count of numbers // from 1 to i that are // also prime and // hence double prime dp[i] = 1; else // If number is not a double prime dp[i] = 0; } for (i = 1; i <= maxN; i++) // finding cumulative sum dp[i] += dp[i - 1];} // Driver code let L = 4, R = 12; count(); document.write(dp[R] - dp[L - 1]); // This code is contributed by susmitakundugoaldanga.</script> 5 offbeat Code_Mech nidhi_biet sanjoy_62 susmitakundugoaldanga array-range-queries Prime Number sieve Analysis Arrays Competitive Programming Mathematical Arrays Mathematical Prime Number sieve Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete 3-coloring is NP Complete Proof that Independent Set in Graph theory is NP Complete Complexity analysis of various operations of Binary Min Heap Proof that Hamiltonian Cycle is NP-Complete Arrays in Java Maximum and minimum of an array using minimum number of comparisons Arrays in C/C++ Write a program to reverse an array or string Program for array rotation
[ { "code": null, "e": 25020, "s": 24992, "text": "\n16 Apr, 2021" }, { "code": null, "e": 25115, "s": 25020, "text": "Given two integers L and R, the task to find the number of Double Prime numbers in the range. " }, { "code": null, "e": 25246, "s": 25115, "text": "A number N is called double prime when the count of prime numbers in the range 1 to N (excluding 1 and including N) is also prime." }, { "code": null, "e": 25258, "s": 25246, "text": "Examples: " }, { "code": null, "e": 26026, "s": 25258, "text": "Input: L = 3, R = 10 Output: 4 Explanation: For 3, we have the range 1, 2, 3, and count of prime number is 2 (which is also a prime no.) For 4, we have the range 1, 2, 3, 4, and count of a prime number is 2 (which is also a prime no.) For 5, we have the range 1, 2, 3, 4, 5, and count of a prime number is 3 (which is also a prime no.) For 6, we have the range 1, 2, 3, 4, 5, 6, and count of prime numbers is 3 (which is also a prime no.) For 7, we have the range 1, 2, 3, 4, 5, 6, 7, and count of prime numbers is 4 which is nonprime. Similarly for other numbers till R = 10, the count of prime numbers is nonprime. Hence the count of double prime numbers is 4.Input: L = 4, R = 12 Output: 5 Explanation: For the given range there are total 5 double prime numbers. " }, { "code": null, "e": 26136, "s": 26028, "text": "Approach:To solve the problem mentioned above we will use the concept of Sieve to generate prime numbers. " }, { "code": null, "e": 26199, "s": 26136, "text": "Generate all prime numbers for 0 to 106 and store in an array." }, { "code": null, "e": 26289, "s": 26199, "text": "Initialize a variable count to keep a track of prime numbers from 1 to some ith position." }, { "code": null, "e": 26508, "s": 26289, "text": "Then for every prime number we will increment the count and also set dp[count] = 1 (where dp is the array which stores a double prime number) indicating the number of numbers from 1 to some ith position that are prime." }, { "code": null, "e": 26593, "s": 26508, "text": "Lastly, find the cumulative sum of dp array so the answer will be dp[R] – dp[L – 1]." }, { "code": null, "e": 26645, "s": 26593, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 26649, "s": 26645, "text": "C++" }, { "code": null, "e": 26654, "s": 26649, "text": "Java" }, { "code": null, "e": 26662, "s": 26654, "text": "Python3" }, { "code": null, "e": 26665, "s": 26662, "text": "C#" }, { "code": null, "e": 26676, "s": 26665, "text": "Javascript" }, { "code": "// C++ program to find the count// of Double Prime numbers// in the range L to R #include <bits/stdc++.h>using namespace std; // Array to make Sieve// where arr[i]=0 indicates// non prime and arr[i] = 1// indicates primeint arr[1000001]; // Array to find double primeint dp[1000001]; // Function to find the number// double prime numbers in rangevoid count(){ int maxN = 1000000, i, j; // Assume all numbers as prime for (i = 0; i < maxN; i++) arr[i] = 1; arr[0] = 0; arr[1] = 0; for (i = 2; i * i <= maxN; i++) { // Check if the number is prime if (arr[i] == 1) { // check for multiples of i for (j = 2 * i; j <= maxN; j += i) { // Make all multiples of // ith prime as non-prime arr[j] = 0; } } } int cnt = 0; for (i = 0; i <= maxN; i++) { // Check if number at ith position // is prime then increment count if (arr[i] == 1) cnt++; if (arr[cnt] == 1) // Indicates count of numbers // from 1 to i that are // also prime and // hence double prime dp[i] = 1; else // If number is not a double prime dp[i] = 0; } for (i = 1; i <= maxN; i++) // finding cumulative sum dp[i] += dp[i - 1];} // Driver codeint main(){ int L = 4, R = 12; count(); cout << dp[R] - dp[L - 1]; return 0;}", "e": 28154, "s": 26676, "text": null }, { "code": "// Java program to find the count// of Double Prime numbers// in the range L to Rimport java.util.*;import java.lang.*;class GFG{ // Array to make Sieve// where arr[i]=0 indicates// non prime and arr[i] = 1// indicates primestatic int[] arr = new int[1000001]; // Array to find double primestatic int[] dp = new int[1000001]; // Function to find the number// double prime numbers in rangestatic void count(){ int maxN = 1000000, i, j; // Assume all numbers as prime for (i = 0; i < maxN; i++) arr[i] = 1; arr[0] = 0; arr[1] = 0; for (i = 2; i * i <= maxN; i++) { // Check if the number is prime if (arr[i] == 1) { // check for multiples of i for (j = 2 * i; j <= maxN; j += i) { // Make all multiples of // ith prime as non-prime arr[j] = 0; } } } int cnt = 0; for (i = 0; i <= maxN; i++) { // Check if number at ith position // is prime then increment count if (arr[i] == 1) cnt++; if (arr[cnt] == 1) // Indicates count of numbers // from 1 to i that are // also prime and // hence double prime dp[i] = 1; else // If number is not a double prime dp[i] = 0; } for (i = 1; i <= maxN; i++) // finding cumulative sum dp[i] += dp[i - 1];} // Driver codepublic static void main(String[] args){ int L = 4, R = 12; count(); System.out.println(dp[R] - dp[L - 1]);}} // This code is contributed by offbeat", "e": 29785, "s": 28154, "text": null }, { "code": "# Python3 program to find the count# of Double Prime numbers# in the range L to R # Array to make Sieve# where arr[i]=0 indicates# non prime and arr[i] = 1# indicates primearr = [0] * 1000001 # Array to find double primedp = [0] * 1000001 # Function to find the number# double prime numbers in rangedef count(): maxN = 1000000 # Assume all numbers as prime for i in range(0, maxN): arr[i] = 1 arr[0] = 0 arr[1] = 0 i = 2 while(i * i <= maxN): # Check if the number is prime if (arr[i] == 1): # Check for multiples of i for j in range(2 * i, maxN + 1, i): # Make all multiples of # ith prime as non-prime arr[j] = 0 i += 1 cnt = 0 for i in range(0, maxN + 1): # Check if number at ith position # is prime then increment count if (arr[i] == 1): cnt += 1 if (arr[cnt] == 1): # Indicates count of numbers # from 1 to i that are # also prime and # hence double prime dp[i] = 1 else: # If number is not a double prime dp[i] = 0 for i in range(0, maxN + 1): # Finding cumulative sum dp[i] += dp[i - 1] # Driver codeL = 4R = 12 count() print(dp[R] - dp[L - 1]) # This code is contributed by sanjoy_62", "e": 31217, "s": 29785, "text": null }, { "code": "// C# program to find the count// of Double Prime numbers// in the range L to Rusing System;class GFG{ // Array to make Sieve// where arr[i]=0 indicates// non prime and arr[i] = 1// indicates primestatic int[] arr = new int[1000001]; // Array to find double primestatic int[] dp = new int[1000001]; // Function to find the number// double prime numbers in rangestatic void count(){ int maxN = 1000000, i, j; // Assume all numbers as prime for (i = 0; i < maxN; i++) arr[i] = 1; arr[0] = 0; arr[1] = 0; for (i = 2; i * i <= maxN; i++) { // Check if the number is prime if (arr[i] == 1) { // check for multiples of i for (j = 2 * i; j <= maxN; j += i) { // Make all multiples of // ith prime as non-prime arr[j] = 0; } } } int cnt = 0; for (i = 0; i <= maxN; i++) { // Check if number at ith position // is prime then increment count if (arr[i] == 1) cnt++; if (arr[cnt] == 1) // Indicates count of numbers // from 1 to i that are // also prime and // hence double prime dp[i] = 1; else // If number is not a double prime dp[i] = 0; } for (i = 1; i <= maxN; i++) // finding cumulative sum dp[i] += dp[i - 1];} // Driver codepublic static void Main(){ int L = 4, R = 12; count(); Console.Write(dp[R] - dp[L - 1]);}} // This code is contributed by Code_Mech", "e": 32805, "s": 31217, "text": null }, { "code": "<script> // Javascript program to find the count// of Double Prime numbers// in the range L to R // Array to make Sieve// where arr[i]=0 indicates// non prime and arr[i] = 1// indicates primelet arr = []; // Array to find double primelet dp = []; // Function to find the number// double prime numbers in rangefunction count(){ let maxN = 1000000, i, j; // Assume all numbers as prime for (i = 0; i < maxN; i++) arr[i] = 1; arr[0] = 0; arr[1] = 0; for (i = 2; i * i <= maxN; i++) { // Check if the number is prime if (arr[i] == 1) { // check for multiples of i for (j = 2 * i; j <= maxN; j += i) { // Make all multiples of // ith prime as non-prime arr[j] = 0; } } } let cnt = 0; for (i = 0; i <= maxN; i++) { // Check if number at ith position // is prime then increment count if (arr[i] == 1) cnt++; if (arr[cnt] == 1) // Indicates count of numbers // from 1 to i that are // also prime and // hence double prime dp[i] = 1; else // If number is not a double prime dp[i] = 0; } for (i = 1; i <= maxN; i++) // finding cumulative sum dp[i] += dp[i - 1];} // Driver code let L = 4, R = 12; count(); document.write(dp[R] - dp[L - 1]); // This code is contributed by susmitakundugoaldanga.</script>", "e": 34374, "s": 32805, "text": null }, { "code": null, "e": 34376, "s": 34374, "text": "5" }, { "code": null, "e": 34386, "s": 34378, "text": "offbeat" }, { "code": null, "e": 34396, "s": 34386, "text": "Code_Mech" }, { "code": null, "e": 34407, "s": 34396, "text": "nidhi_biet" }, { "code": null, "e": 34417, "s": 34407, "text": "sanjoy_62" }, { "code": null, "e": 34439, "s": 34417, "text": "susmitakundugoaldanga" }, { "code": null, "e": 34459, "s": 34439, "text": "array-range-queries" }, { "code": null, "e": 34472, "s": 34459, "text": "Prime Number" }, { "code": null, "e": 34478, "s": 34472, "text": "sieve" }, { "code": null, "e": 34487, "s": 34478, "text": "Analysis" }, { "code": null, "e": 34494, "s": 34487, "text": "Arrays" }, { "code": null, "e": 34518, "s": 34494, "text": "Competitive Programming" }, { "code": null, "e": 34531, "s": 34518, "text": "Mathematical" }, { "code": null, "e": 34538, "s": 34531, "text": "Arrays" }, { "code": null, "e": 34551, "s": 34538, "text": "Mathematical" }, { "code": null, "e": 34564, "s": 34551, "text": "Prime Number" }, { "code": null, "e": 34570, "s": 34564, "text": "sieve" }, { "code": null, "e": 34668, "s": 34570, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34735, "s": 34668, "text": "Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete" }, { "code": null, "e": 34761, "s": 34735, "text": "3-coloring is NP Complete" }, { "code": null, "e": 34819, "s": 34761, "text": "Proof that Independent Set in Graph theory is NP Complete" }, { "code": null, "e": 34880, "s": 34819, "text": "Complexity analysis of various operations of Binary Min Heap" }, { "code": null, "e": 34924, "s": 34880, "text": "Proof that Hamiltonian Cycle is NP-Complete" }, { "code": null, "e": 34939, "s": 34924, "text": "Arrays in Java" }, { "code": null, "e": 35007, "s": 34939, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 35023, "s": 35007, "text": "Arrays in C/C++" }, { "code": null, "e": 35069, "s": 35023, "text": "Write a program to reverse an array or string" } ]
Graph Theory - Isomorphism
A graph can exist in different forms having the same number of vertices, edges, and also the same edge connectivity. Such graphs are called isomorphic graphs. Note that we label the graphs in this chapter mainly for the purpose of referring to them and recognizing them from one another. Two graphs G1 and G2 are said to be isomorphic if − Their number of components (vertices and edges) are same. Their number of components (vertices and edges) are same. Their edge connectivity is retained. Their edge connectivity is retained. Note − In short, out of the two isomorphic graphs, one is a tweaked version of the other. An unlabelled graph also can be thought of as an isomorphic graph. There exists a function ‘f’ from vertices of G1 to vertices of G2 [f: V(G1) ⇒ V(G2)], such that Case (i): f is a bijection (both one-one and onto) Case (ii): f preserves adjacency of vertices, i.e., if the edge {U, V} ∈ G1, then the edge {f(U), f(V)} ∈ G2, then G1 ≡ G2. Note If G1 ≡ G2 then − |V(G1)| = |V(G2)| |E(G1)| = |E(G2)| Degree sequences of G1 and G2 are same. If the vertices {V1, V2, .. Vk} form a cycle of length K in G1, then the vertices {f(V1), f(V2),... f(Vk)} should form a cycle of length K in G2. All the above conditions are necessary for the graphs G1 and G2 to be isomorphic, but not sufficient to prove that the graphs are isomorphic. (G1 ≡ G2) if and only if (G1− ≡ G2−) where G1 and G2 are simple graphs. (G1 ≡ G2) if and only if (G1− ≡ G2−) where G1 and G2 are simple graphs. (G1 ≡ G2) if the adjacency matrices of G1 and G2 are same. (G1 ≡ G2) if the adjacency matrices of G1 and G2 are same. (G1 ≡ G2) if and only if the corresponding subgraphs of G1 and G2 (obtained by deleting some vertices in G1 and their images in graph G2) are isomorphic. (G1 ≡ G2) if and only if the corresponding subgraphs of G1 and G2 (obtained by deleting some vertices in G1 and their images in graph G2) are isomorphic. Example Which of the following graphs are isomorphic? In the graph G3, vertex ‘w’ has only degree 3, whereas all the other graph vertices has degree 2. Hence G3 not isomorphic to G1 or G2. Taking complements of G1 and G2, you have − Here, (G1− ≡ G2−), hence (G1 ≡ G2). A graph ‘G’ is said to be planar if it can be drawn on a plane or a sphere so that no two edges cross each other at a non-vertex point. Example Every planar graph divides the plane into connected areas called regions. Example Degree of a bounded region r = deg(r) = Number of edges enclosing the regions r. deg(1) = 3 deg(2) = 4 deg(3) = 4 deg(4) = 3 deg(5) = 8 Degree of an unbounded region r = deg(r) = Number of edges enclosing the regions r. deg(R1) = 4 deg(R2) = 6 In planar graphs, the following properties hold good − In a planar graph with ‘n’ vertices, sum of degrees of all the vertices is − According to Sum of Degrees of Regions/ Theorem, in a planar graph with ‘n’ regions, Sum of degrees of regions is − Based on the above theorem, you can draw the following conclusions − In a planar graph, If degree of each region is K, then the sum of degrees of regions is − If the degree of each region is at least K(≥ K), then If the degree of each region is at most K(≤ K), then Note − Assume that all the regions have same degree. According to Euler’s Formulae on planar graphs, If a graph ‘G’ is a connected planar, then If a planar graph with ‘K’ components, then Where, |V| is the number of vertices, |E| is the number of edges, and |R| is the number of regions. Edge Vertex Inequality If ‘G’ is a connected planar graph with degree of each region at least ‘K’ then, |E| ≤ k / (k-2) {|v| - 2} You know, |V| + |R| = |E| + 2 K.|R| ≤ 2|E| K(|E| - |V| + 2) ≤ 2|E| (K - 2)|E| ≤ K(|V| - 2) |E| ≤ k / (k-2) {|v| - 2} If ‘G’ is a simple connected planar graph, then |E| ≤ 3|V| − 6 |R| ≤ 2|V| − 4 There exists at least one vertex V •∈ G, such that deg(V) ≤ 5. If ‘G’ is a simple connected planar graph (with at least 2 edges) and no triangles, then |E| ≤ {2|V| – 4} Kuratowski’s Theorem A graph ‘G’ is non-planar if and only if ‘G’ has a subgraph which is homeomorphic to K5 or K3,3. Two graphs G1 and G2 are said to be homomorphic, if each of these graphs can be obtained from the same graph ‘G’ by dividing some edges of G with more vertices. Take a look at the following example − Divide the edge ‘rs’ into two edges by adding one vertex. The graphs shown below are homomorphic to the first graph. If G1 is isomorphic to G2, then G is homeomorphic to G2 but the converse need not be true. Any graph with 4 or less vertices is planar. Any graph with 4 or less vertices is planar. Any graph with 8 or less edges is planar. Any graph with 8 or less edges is planar. A complete graph Kn is planar if and only if n ≤ 4. A complete graph Kn is planar if and only if n ≤ 4. The complete bipartite graph Km, n is planar if and only if m ≤ 2 or n ≤ 2. The complete bipartite graph Km, n is planar if and only if m ≤ 2 or n ≤ 2. A simple non-planar graph with minimum number of vertices is the complete graph K5. A simple non-planar graph with minimum number of vertices is the complete graph K5. The simple non-planar graph with minimum number of edges is K3, 3. The simple non-planar graph with minimum number of edges is K3, 3. A simple connected planar graph is called a polyhedral graph if the degree of each vertex is ≥ 3, i.e., deg(V) ≥ 3 ∀ V ∈ G. 3|V| ≤ 2|E| 3|V| ≤ 2|E| 3|R| ≤ 2|E| 3|R| ≤ 2|E| 97 Lectures 7 hours Arnab Chakraborty 99 Lectures 6 hours Arnab Chakraborty 7 Lectures 1 hours Zach Miller 31 Lectures 3.5 hours Abhishek And Pukhraj 32 Lectures 6.5 hours William Fiset 54 Lectures 4 hours Sasha Miller Print Add Notes Bookmark this page
[ { "code": null, "e": 2254, "s": 1966, "text": "A graph can exist in different forms having the same number of vertices, edges, and also the same edge connectivity. Such graphs are called isomorphic graphs. Note that we label the graphs in this chapter mainly for the purpose of referring to them and recognizing them from one another." }, { "code": null, "e": 2306, "s": 2254, "text": "Two graphs G1 and G2 are said to be isomorphic if −" }, { "code": null, "e": 2364, "s": 2306, "text": "Their number of components (vertices and edges) are same." }, { "code": null, "e": 2422, "s": 2364, "text": "Their number of components (vertices and edges) are same." }, { "code": null, "e": 2459, "s": 2422, "text": "Their edge connectivity is retained." }, { "code": null, "e": 2496, "s": 2459, "text": "Their edge connectivity is retained." }, { "code": null, "e": 2653, "s": 2496, "text": "Note − In short, out of the two isomorphic graphs, one is a tweaked version of the other. An unlabelled graph also can be thought of as an isomorphic graph." }, { "code": null, "e": 2928, "s": 2653, "text": "There exists a function ‘f’ from vertices of G1 to vertices of G2\n [f: V(G1) ⇒ V(G2)], such that\nCase (i): f is a bijection (both one-one and onto)\nCase (ii): f preserves adjacency of vertices, i.e., if the edge {U, V} ∈ G1, then the\nedge {f(U), f(V)} ∈ G2, then G1 ≡ G2.\n" }, { "code": null, "e": 2933, "s": 2928, "text": "Note" }, { "code": null, "e": 2951, "s": 2933, "text": "If G1 ≡ G2 then −" }, { "code": null, "e": 2969, "s": 2951, "text": "|V(G1)| = |V(G2)|" }, { "code": null, "e": 2987, "s": 2969, "text": "|E(G1)| = |E(G2)|" }, { "code": null, "e": 3027, "s": 2987, "text": "Degree sequences of G1 and G2 are same." }, { "code": null, "e": 3173, "s": 3027, "text": "If the vertices {V1, V2, .. Vk} form a cycle of length K in G1, then the vertices {f(V1), f(V2),... f(Vk)} should form a cycle of length K in G2." }, { "code": null, "e": 3315, "s": 3173, "text": "All the above conditions are necessary for the graphs G1 and G2 to be isomorphic, but not sufficient to prove that the graphs are isomorphic." }, { "code": null, "e": 3387, "s": 3315, "text": "(G1 ≡ G2) if and only if (G1− ≡ G2−) where G1 and G2 are simple graphs." }, { "code": null, "e": 3459, "s": 3387, "text": "(G1 ≡ G2) if and only if (G1− ≡ G2−) where G1 and G2 are simple graphs." }, { "code": null, "e": 3518, "s": 3459, "text": "(G1 ≡ G2) if the adjacency matrices of G1 and G2 are same." }, { "code": null, "e": 3577, "s": 3518, "text": "(G1 ≡ G2) if the adjacency matrices of G1 and G2 are same." }, { "code": null, "e": 3731, "s": 3577, "text": "(G1 ≡ G2) if and only if the corresponding subgraphs of G1 and G2 (obtained by deleting some vertices in G1 and their images in graph G2) are isomorphic." }, { "code": null, "e": 3885, "s": 3731, "text": "(G1 ≡ G2) if and only if the corresponding subgraphs of G1 and G2 (obtained by deleting some vertices in G1 and their images in graph G2) are isomorphic." }, { "code": null, "e": 3893, "s": 3885, "text": "Example" }, { "code": null, "e": 3939, "s": 3893, "text": "Which of the following graphs are isomorphic?" }, { "code": null, "e": 4074, "s": 3939, "text": "In the graph G3, vertex ‘w’ has only degree 3, whereas all the other graph vertices has degree 2. Hence G3 not isomorphic to G1 or G2." }, { "code": null, "e": 4118, "s": 4074, "text": "Taking complements of G1 and G2, you have −" }, { "code": null, "e": 4154, "s": 4118, "text": "Here, (G1− ≡ G2−), hence (G1 ≡ G2)." }, { "code": null, "e": 4290, "s": 4154, "text": "A graph ‘G’ is said to be planar if it can be drawn on a plane or a sphere so that no two edges cross each other at a non-vertex point." }, { "code": null, "e": 4298, "s": 4290, "text": "Example" }, { "code": null, "e": 4372, "s": 4298, "text": "Every planar graph divides the plane into connected areas called regions." }, { "code": null, "e": 4380, "s": 4372, "text": "Example" }, { "code": null, "e": 4461, "s": 4380, "text": "Degree of a bounded region r = deg(r) = Number of edges enclosing the regions r." }, { "code": null, "e": 4518, "s": 4461, "text": "deg(1) = 3\ndeg(2) = 4\ndeg(3) = 4\n\ndeg(4) = 3\ndeg(5) = 8\n" }, { "code": null, "e": 4602, "s": 4518, "text": "Degree of an unbounded region r = deg(r) = Number of edges enclosing the regions r." }, { "code": null, "e": 4627, "s": 4602, "text": "deg(R1) = 4\ndeg(R2) = 6\n" }, { "code": null, "e": 4682, "s": 4627, "text": "In planar graphs, the following properties hold good −" }, { "code": null, "e": 4759, "s": 4682, "text": "In a planar graph with ‘n’ vertices, sum of degrees of all the vertices is −" }, { "code": null, "e": 4875, "s": 4759, "text": "According to Sum of Degrees of Regions/ Theorem, in a planar graph with ‘n’ regions, Sum of degrees of regions is −" }, { "code": null, "e": 4944, "s": 4875, "text": "Based on the above theorem, you can draw the following conclusions −" }, { "code": null, "e": 4963, "s": 4944, "text": "In a planar graph," }, { "code": null, "e": 5034, "s": 4963, "text": "If degree of each region is K, then the sum of degrees of regions is −" }, { "code": null, "e": 5088, "s": 5034, "text": "If the degree of each region is at least K(≥ K), then" }, { "code": null, "e": 5141, "s": 5088, "text": "If the degree of each region is at most K(≤ K), then" }, { "code": null, "e": 5194, "s": 5141, "text": "Note − Assume that all the regions have same degree." }, { "code": null, "e": 5242, "s": 5194, "text": "According to Euler’s Formulae on planar graphs," }, { "code": null, "e": 5285, "s": 5242, "text": "If a graph ‘G’ is a connected planar, then" }, { "code": null, "e": 5329, "s": 5285, "text": "If a planar graph with ‘K’ components, then" }, { "code": null, "e": 5429, "s": 5329, "text": "Where, |V| is the number of vertices, |E| is the number of edges, and |R| is the number of regions." }, { "code": null, "e": 5452, "s": 5429, "text": "Edge Vertex Inequality" }, { "code": null, "e": 5533, "s": 5452, "text": "If ‘G’ is a connected planar graph with degree of each region at least ‘K’ then," }, { "code": null, "e": 5559, "s": 5533, "text": "|E| ≤ k / (k-2) {|v| - 2}" }, { "code": null, "e": 5589, "s": 5559, "text": "You know, |V| + |R| = |E| + 2" }, { "code": null, "e": 5602, "s": 5589, "text": "K.|R| ≤ 2|E|" }, { "code": null, "e": 5626, "s": 5602, "text": "K(|E| - |V| + 2) ≤ 2|E|" }, { "code": null, "e": 5650, "s": 5626, "text": "(K - 2)|E| ≤ K(|V| - 2)" }, { "code": null, "e": 5676, "s": 5650, "text": "|E| ≤ k / (k-2) {|v| - 2}" }, { "code": null, "e": 5724, "s": 5676, "text": "If ‘G’ is a simple connected planar graph, then" }, { "code": null, "e": 5755, "s": 5724, "text": "|E| ≤ 3|V| − 6\n|R| ≤ 2|V| − 4\n" }, { "code": null, "e": 5818, "s": 5755, "text": "There exists at least one vertex V •∈ G, such that deg(V) ≤ 5." }, { "code": null, "e": 5907, "s": 5818, "text": "If ‘G’ is a simple connected planar graph (with at least 2 edges) and no triangles, then" }, { "code": null, "e": 5925, "s": 5907, "text": "|E| ≤ {2|V| – 4}\n" }, { "code": null, "e": 5946, "s": 5925, "text": "Kuratowski’s Theorem" }, { "code": null, "e": 6043, "s": 5946, "text": "A graph ‘G’ is non-planar if and only if ‘G’ has a subgraph which is homeomorphic to K5 or K3,3." }, { "code": null, "e": 6243, "s": 6043, "text": "Two graphs G1 and G2 are said to be homomorphic, if each of these graphs can be obtained from the same graph ‘G’ by dividing some edges of G with more vertices. Take a look at the following example −" }, { "code": null, "e": 6301, "s": 6243, "text": "Divide the edge ‘rs’ into two edges by adding one vertex." }, { "code": null, "e": 6360, "s": 6301, "text": "The graphs shown below are homomorphic to the first graph." }, { "code": null, "e": 6451, "s": 6360, "text": "If G1 is isomorphic to G2, then G is homeomorphic to G2 but the converse need not be true." }, { "code": null, "e": 6496, "s": 6451, "text": "Any graph with 4 or less vertices is planar." }, { "code": null, "e": 6541, "s": 6496, "text": "Any graph with 4 or less vertices is planar." }, { "code": null, "e": 6583, "s": 6541, "text": "Any graph with 8 or less edges is planar." }, { "code": null, "e": 6625, "s": 6583, "text": "Any graph with 8 or less edges is planar." }, { "code": null, "e": 6677, "s": 6625, "text": "A complete graph Kn is planar if and only if n ≤ 4." }, { "code": null, "e": 6729, "s": 6677, "text": "A complete graph Kn is planar if and only if n ≤ 4." }, { "code": null, "e": 6805, "s": 6729, "text": "The complete bipartite graph Km, n is planar if and only if m ≤ 2 or n ≤ 2." }, { "code": null, "e": 6881, "s": 6805, "text": "The complete bipartite graph Km, n is planar if and only if m ≤ 2 or n ≤ 2." }, { "code": null, "e": 6965, "s": 6881, "text": "A simple non-planar graph with minimum number of vertices is the complete graph K5." }, { "code": null, "e": 7049, "s": 6965, "text": "A simple non-planar graph with minimum number of vertices is the complete graph K5." }, { "code": null, "e": 7116, "s": 7049, "text": "The simple non-planar graph with minimum number of edges is K3, 3." }, { "code": null, "e": 7183, "s": 7116, "text": "The simple non-planar graph with minimum number of edges is K3, 3." }, { "code": null, "e": 7307, "s": 7183, "text": "A simple connected planar graph is called a polyhedral graph if the degree of each vertex is ≥ 3, i.e., deg(V) ≥ 3 ∀ V ∈ G." }, { "code": null, "e": 7319, "s": 7307, "text": "3|V| ≤ 2|E|" }, { "code": null, "e": 7331, "s": 7319, "text": "3|V| ≤ 2|E|" }, { "code": null, "e": 7343, "s": 7331, "text": "3|R| ≤ 2|E|" }, { "code": null, "e": 7355, "s": 7343, "text": "3|R| ≤ 2|E|" }, { "code": null, "e": 7388, "s": 7355, "text": "\n 97 Lectures \n 7 hours \n" }, { "code": null, "e": 7407, "s": 7388, "text": " Arnab Chakraborty" }, { "code": null, "e": 7440, "s": 7407, "text": "\n 99 Lectures \n 6 hours \n" }, { "code": null, "e": 7459, "s": 7440, "text": " Arnab Chakraborty" }, { "code": null, "e": 7491, "s": 7459, "text": "\n 7 Lectures \n 1 hours \n" }, { "code": null, "e": 7504, "s": 7491, "text": " Zach Miller" }, { "code": null, "e": 7539, "s": 7504, "text": "\n 31 Lectures \n 3.5 hours \n" }, { "code": null, "e": 7561, "s": 7539, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 7596, "s": 7561, "text": "\n 32 Lectures \n 6.5 hours \n" }, { "code": null, "e": 7611, "s": 7596, "text": " William Fiset" }, { "code": null, "e": 7644, "s": 7611, "text": "\n 54 Lectures \n 4 hours \n" }, { "code": null, "e": 7658, "s": 7644, "text": " Sasha Miller" }, { "code": null, "e": 7665, "s": 7658, "text": " Print" }, { "code": null, "e": 7676, "s": 7665, "text": " Add Notes" } ]
C# Program to Check the Length of Courses is More than 2 Characters Using LINQ - GeeksforGeeks
28 Nov, 2021 Given an array that contains a list of different courses like “DSA”, “OS”, “JavaScript”, etc., now our task is to check the length of all the courses present in the given array is more than 2 characters or not with the help of LINQ. So to do our task we use the All() method of LINQ. This method returns true if all the elements present in the given sequence satisfy the specified condition. Otherwise, it will return false. Syntax: array_name.All(iterator => iterator.Length > 2) Where array_name is the input array and Length is the function used to check the length of each course. Example: Input : { "cse", "it", "ft", "bio-tech", "chemical" } Output : False Input : { "cse", "ece", "bio-tech", "chemical" } Output : True C# // C# program to find the check the length of// courses is more than 2 characters Using LINQusing System;using System.Linq; class GFG{ static void Main(string[] args){ // Create 5 courses string[] course1 = { "cse", "ece", "bio-tech", "chemical", "civil" }; string[] course2 = { "DSA", "JS", "Kotlin", "C", "React" }; // Checking the length of all courses // is greater than 2 or not bool result1 = course1.All(display => display.Length > 2); bool result2 = course2.All(display => display.Length > 2); Console.WriteLine("Is the length of the courses " + "is greater than 2 in course1?: " + result1); Console.WriteLine("Is the length of the courses " + "is greater than 2 in course2?: " + result2);}} Output: Is the length of the courses is greater than 2 in course1?: True Is the length of the courses is greater than 2 in course2?: False Picked C# C# Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Destructors in C# Extension Method in C# HashSet in C# with Examples Top 50 C# Interview Questions & Answers C# | How to insert an element in an Array? Convert String to Character Array in C# Socket Programming in C# Program to Print a New Line in C# Getting a Month Name Using Month Number in C# Program to find absolute value of a given number
[ { "code": null, "e": 24302, "s": 24274, "text": "\n28 Nov, 2021" }, { "code": null, "e": 24727, "s": 24302, "text": "Given an array that contains a list of different courses like “DSA”, “OS”, “JavaScript”, etc., now our task is to check the length of all the courses present in the given array is more than 2 characters or not with the help of LINQ. So to do our task we use the All() method of LINQ. This method returns true if all the elements present in the given sequence satisfy the specified condition. Otherwise, it will return false." }, { "code": null, "e": 24735, "s": 24727, "text": "Syntax:" }, { "code": null, "e": 24783, "s": 24735, "text": "array_name.All(iterator => iterator.Length > 2)" }, { "code": null, "e": 24887, "s": 24783, "text": "Where array_name is the input array and Length is the function used to check the length of each course." }, { "code": null, "e": 24896, "s": 24887, "text": "Example:" }, { "code": null, "e": 25031, "s": 24896, "text": "Input : { \"cse\", \"it\", \"ft\", \"bio-tech\", \"chemical\" }\nOutput : False\n\nInput : { \"cse\", \"ece\", \"bio-tech\", \"chemical\" }\nOutput : True" }, { "code": null, "e": 25034, "s": 25031, "text": "C#" }, { "code": "// C# program to find the check the length of// courses is more than 2 characters Using LINQusing System;using System.Linq; class GFG{ static void Main(string[] args){ // Create 5 courses string[] course1 = { \"cse\", \"ece\", \"bio-tech\", \"chemical\", \"civil\" }; string[] course2 = { \"DSA\", \"JS\", \"Kotlin\", \"C\", \"React\" }; // Checking the length of all courses // is greater than 2 or not bool result1 = course1.All(display => display.Length > 2); bool result2 = course2.All(display => display.Length > 2); Console.WriteLine(\"Is the length of the courses \" + \"is greater than 2 in course1?: \" + result1); Console.WriteLine(\"Is the length of the courses \" + \"is greater than 2 in course2?: \" + result2);}}", "e": 25848, "s": 25034, "text": null }, { "code": null, "e": 25856, "s": 25848, "text": "Output:" }, { "code": null, "e": 25987, "s": 25856, "text": "Is the length of the courses is greater than 2 in course1?: True\nIs the length of the courses is greater than 2 in course2?: False" }, { "code": null, "e": 25994, "s": 25987, "text": "Picked" }, { "code": null, "e": 25997, "s": 25994, "text": "C#" }, { "code": null, "e": 26009, "s": 25997, "text": "C# Programs" }, { "code": null, "e": 26107, "s": 26009, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26125, "s": 26107, "text": "Destructors in C#" }, { "code": null, "e": 26148, "s": 26125, "text": "Extension Method in C#" }, { "code": null, "e": 26176, "s": 26148, "text": "HashSet in C# with Examples" }, { "code": null, "e": 26216, "s": 26176, "text": "Top 50 C# Interview Questions & Answers" }, { "code": null, "e": 26259, "s": 26216, "text": "C# | How to insert an element in an Array?" }, { "code": null, "e": 26299, "s": 26259, "text": "Convert String to Character Array in C#" }, { "code": null, "e": 26324, "s": 26299, "text": "Socket Programming in C#" }, { "code": null, "e": 26358, "s": 26324, "text": "Program to Print a New Line in C#" }, { "code": null, "e": 26404, "s": 26358, "text": "Getting a Month Name Using Month Number in C#" } ]
Big Data Analytics - Introduction to SQL
SQL stands for structured query language. It is one of the most widely used languages for extracting data from databases in traditional data warehouses and big data technologies. In order to demonstrate the basics of SQL we will be working with examples. In order to focus on the language itself, we will be using SQL inside R. In terms of writing SQL code this is exactly as would be done in a database. The core of SQL are three statements: SELECT, FROM and WHERE. The following examples make use of the most common use cases of SQL. Navigate to the folder bda/part2/SQL_introduction and open the SQL_introduction.Rproj file. Then open the 01_select.R script. In order to write SQL code in R we need to install the sqldf package as demonstrated in the following code. # Install the sqldf package install.packages('sqldf') # load the library library('sqldf') library(nycflights13) # We will be working with the fligths dataset in order to introduce SQL # Let’s take a look at the table str(flights) # Classes 'tbl_d', 'tbl' and 'data.frame': 336776 obs. of 16 variables: # $ year : int 2013 2013 2013 2013 2013 2013 2013 2013 2013 2013 ... # $ month : int 1 1 1 1 1 1 1 1 1 1 ... # $ day : int 1 1 1 1 1 1 1 1 1 1 ... # $ dep_time : int 517 533 542 544 554 554 555 557 557 558 ... # $ dep_delay: num 2 4 2 -1 -6 -4 -5 -3 -3 -2 ... # $ arr_time : int 830 850 923 1004 812 740 913 709 838 753 ... # $ arr_delay: num 11 20 33 -18 -25 12 19 -14 -8 8 ... # $ carrier : chr "UA" "UA" "AA" "B6" ... # $ tailnum : chr "N14228" "N24211" "N619AA" "N804JB" ... # $ flight : int 1545 1714 1141 725 461 1696 507 5708 79 301 ... # $ origin : chr "EWR" "LGA" "JFK" "JFK" ... # $ dest : chr "IAH" "IAH" "MIA" "BQN" ... # $ air_time : num 227 227 160 183 116 150 158 53 140 138 ... # $ distance : num 1400 1416 1089 1576 762 ... # $ hour : num 5 5 5 5 5 5 5 5 5 5 ... # $ minute : num 17 33 42 44 54 54 55 57 57 58 ... The select statement is used to retrieve columns from tables and do calculations on them. The simplest SELECT statement is demonstrated in ej1. We can also create new variables as shown in ej2. ### SELECT statement ej1 = sqldf(" SELECT dep_time ,dep_delay ,arr_time ,carrier ,tailnum FROM flights ") head(ej1) # dep_time dep_delay arr_time carrier tailnum # 1 517 2 830 UA N14228 # 2 533 4 850 UA N24211 # 3 542 2 923 AA N619AA # 4 544 -1 1004 B6 N804JB # 5 554 -6 812 DL N668DN # 6 554 -4 740 UA N39463 # In R we can use SQL with the sqldf function. It works exactly the same as in a database # The data.frame (in this case flights) represents the table we are querying and goes in the FROM statement # We can also compute new variables in the select statement using the syntax: # old_variables as new_variable ej2 = sqldf(" SELECT arr_delay - dep_delay as gain, carrier FROM flights ") ej2[1:5, ] # gain carrier # 1 9 UA # 2 16 UA # 3 31 AA # 4 -17 B6 # 5 -19 DL One of the most common used features of SQL is the group by statement. This allows to compute a numeric value for different groups of another variable. Open the script 02_group_by.R. ### GROUP BY # Computing the average ej3 = sqldf(" SELECT avg(arr_delay) as mean_arr_delay, avg(dep_delay) as mean_dep_delay, carrier FROM flights GROUP BY carrier ") # mean_arr_delay mean_dep_delay carrier # 1 7.3796692 16.725769 9E # 2 0.3642909 8.586016 AA # 3 -9.9308886 5.804775 AS # 4 9.4579733 13.022522 B6 # 5 1.6443409 9.264505 DL # 6 15.7964311 19.955390 EV # 7 21.9207048 20.215543 F9 # 8 20.1159055 18.726075 FL # 9 -6.9152047 4.900585 HA # 10 10.7747334 10.552041 MQ # 11 11.9310345 12.586207 OO # 12 3.5580111 12.106073 UA # 13 2.1295951 3.782418 US # 14 1.7644644 12.869421 VX # 15 9.6491199 17.711744 WN # 16 15.5569853 18.996330 YV # Other aggregations ej4 = sqldf(" SELECT avg(arr_delay) as mean_arr_delay, min(dep_delay) as min_dep_delay, max(dep_delay) as max_dep_delay, carrier FROM flights GROUP BY carrier ") # We can compute the minimun, mean, and maximum values of a numeric value ej4 # mean_arr_delay min_dep_delay max_dep_delay carrier # 1 7.3796692 -24 747 9E # 2 0.3642909 -24 1014 AA # 3 -9.9308886 -21 225 AS # 4 9.4579733 -43 502 B6 # 5 1.6443409 -33 960 DL # 6 15.7964311 -32 548 EV # 7 21.9207048 -27 853 F9 # 8 20.1159055 -22 602 FL # 9 -6.9152047 -16 1301 HA # 10 10.7747334 -26 1137 MQ # 11 11.9310345 -14 154 OO # 12 3.5580111 -20 483 UA # 13 2.1295951 -19 500 US # 14 1.7644644 -20 653 VX # 15 9.6491199 -13 471 WN # 16 15.5569853 -16 387 YV ### We could be also interested in knowing how many observations each carrier has ej5 = sqldf(" SELECT carrier, count(*) as count FROM flights GROUP BY carrier ") ej5 # carrier count # 1 9E 18460 # 2 AA 32729 # 3 AS 714 # 4 B6 54635 # 5 DL 48110 # 6 EV 54173 # 7 F9 685 # 8 FL 3260 # 9 HA 342 # 10 MQ 26397 # 11 OO 32 # 12 UA 58665 # 13 US 20536 # 14 VX 5162 # 15 WN 12275 # 16 YV 601 The most useful feature of SQL are joins. A join means that we want to combine table A and table B in one table using one column to match the values of both tables. There are different types of joins, in practical terms, to get started these will be the most useful ones: inner join and left outer join. # Let’s create two tables: A and B to demonstrate joins. A = data.frame(c1 = 1:4, c2 = letters[1:4]) B = data.frame(c1 = c(2,4,5,6), c2 = letters[c(2:5)]) A # c1 c2 # 1 a # 2 b # 3 c # 4 d B # c1 c2 # 2 b # 4 c # 5 d # 6 e ### INNER JOIN # This means to match the observations of the column we would join the tables by. inner = sqldf(" SELECT A.c1, B.c2 FROM A INNER JOIN B ON A.c1 = B.c1 ") # Only the rows that match c1 in both A and B are returned inner # c1 c2 # 2 b # 4 c ### LEFT OUTER JOIN # the left outer join, sometimes just called left join will return the # first all the values of the column used from the A table left = sqldf(" SELECT A.c1, B.c2 FROM A LEFT OUTER JOIN B ON A.c1 = B.c1 ") # Only the rows that match c1 in both A and B are returned left # c1 c2 # 1 <NA> # 2 b # 3 <NA> # 4 c 65 Lectures 6 hours Arnab Chakraborty 18 Lectures 1.5 hours Pranjal Srivastava, Harshit Srivastava 23 Lectures 2 hours John Shea 18 Lectures 1.5 hours Pranjal Srivastava 46 Lectures 3.5 hours Pranjal Srivastava 37 Lectures 3.5 hours Pranjal Srivastava, Harshit Srivastava Print Add Notes Bookmark this page
[ { "code": null, "e": 2959, "s": 2554, "text": "SQL stands for structured query language. It is one of the most widely used languages for extracting data from databases in traditional data warehouses and big data technologies. In order to demonstrate the basics of SQL we will be working with examples. In order to focus on the language itself, we will be using SQL inside R. In terms of writing SQL code this is exactly as would be done in a database." }, { "code": null, "e": 3324, "s": 2959, "text": "The core of SQL are three statements: SELECT, FROM and WHERE. The following examples make use of the most common use cases of SQL. Navigate to the folder bda/part2/SQL_introduction and open the SQL_introduction.Rproj file. Then open the 01_select.R script. In order to write SQL code in R we need to install the sqldf package as demonstrated in the following code." }, { "code": null, "e": 4533, "s": 3324, "text": "# Install the sqldf package\ninstall.packages('sqldf') \n\n# load the library \nlibrary('sqldf') \nlibrary(nycflights13) \n\n# We will be working with the fligths dataset in order to introduce SQL \n\n# Let’s take a look at the table \nstr(flights) \n# Classes 'tbl_d', 'tbl' and 'data.frame': 336776 obs. of 16 variables: \n\n# $ year : int 2013 2013 2013 2013 2013 2013 2013 2013 2013 2013 ... \n# $ month : int 1 1 1 1 1 1 1 1 1 1 ... \n# $ day : int 1 1 1 1 1 1 1 1 1 1 ... \n# $ dep_time : int 517 533 542 544 554 554 555 557 557 558 ... \n# $ dep_delay: num 2 4 2 -1 -6 -4 -5 -3 -3 -2 ... \n# $ arr_time : int 830 850 923 1004 812 740 913 709 838 753 ... \n# $ arr_delay: num 11 20 33 -18 -25 12 19 -14 -8 8 ...\n# $ carrier : chr \"UA\" \"UA\" \"AA\" \"B6\" ... \n\n# $ tailnum : chr \"N14228\" \"N24211\" \"N619AA\" \"N804JB\" ... \n# $ flight : int 1545 1714 1141 725 461 1696 507 5708 79 301 ... \n# $ origin : chr \"EWR\" \"LGA\" \"JFK\" \"JFK\" ... \n# $ dest : chr \"IAH\" \"IAH\" \"MIA\" \"BQN\" ... \n# $ air_time : num 227 227 160 183 116 150 158 53 140 138 ... \n# $ distance : num 1400 1416 1089 1576 762 ... \n# $ hour : num 5 5 5 5 5 5 5 5 5 5 ... \n# $ minute : num 17 33 42 44 54 54 55 57 57 58 ...\n" }, { "code": null, "e": 4727, "s": 4533, "text": "The select statement is used to retrieve columns from tables and do calculations on them. The simplest SELECT statement is demonstrated in ej1. We can also create new variables as shown in ej2." }, { "code": null, "e": 5800, "s": 4727, "text": "### SELECT statement\nej1 = sqldf(\" \n SELECT \n dep_time \n ,dep_delay \n ,arr_time \n ,carrier \n ,tailnum \n FROM \n flights\n\") \n\nhead(ej1) \n# dep_time dep_delay arr_time carrier tailnum \n# 1 517 2 830 UA N14228 \n# 2 533 4 850 UA N24211 \n# 3 542 2 923 AA N619AA \n# 4 544 -1 1004 B6 N804JB \n# 5 554 -6 812 DL N668DN \n# 6 554 -4 740 UA N39463 \n\n# In R we can use SQL with the sqldf function. It works exactly the same as in \na database \n\n# The data.frame (in this case flights) represents the table we are querying \nand goes in the FROM statement \n# We can also compute new variables in the select statement using the syntax: \n\n# old_variables as new_variable \nej2 = sqldf(\" \n SELECT \n arr_delay - dep_delay as gain, \n carrier \n FROM \n flights\n\") \n\nej2[1:5, ] \n# gain carrier \n# 1 9 UA \n# 2 16 UA \n# 3 31 AA \n# 4 -17 B6 \n# 5 -19 DL\n" }, { "code": null, "e": 5983, "s": 5800, "text": "One of the most common used features of SQL is the group by statement. This allows to compute a numeric value for different groups of another variable. Open the script 02_group_by.R." }, { "code": null, "e": 8842, "s": 5983, "text": "### GROUP BY \n\n# Computing the average \nej3 = sqldf(\" \n SELECT \n avg(arr_delay) as mean_arr_delay, \n avg(dep_delay) as mean_dep_delay, \n carrier \n FROM \n flights \n GROUP BY \n carrier \n\") \n\n# mean_arr_delay mean_dep_delay carrier \n# 1 7.3796692 16.725769 9E \n# 2 0.3642909 8.586016 AA \n# 3 -9.9308886 5.804775 AS \n# 4 9.4579733 13.022522 B6 \n# 5 1.6443409 9.264505 DL \n# 6 15.7964311 19.955390 EV \n# 7 21.9207048 20.215543 F9 \n# 8 20.1159055 18.726075 FL \n# 9 -6.9152047 4.900585 HA \n# 10 10.7747334 10.552041 MQ\n# 11 11.9310345 12.586207 OO \n# 12 3.5580111 12.106073 UA \n# 13 2.1295951 3.782418 US \n# 14 1.7644644 12.869421 VX \n# 15 9.6491199 17.711744 WN \n# 16 15.5569853 18.996330 YV \n\n# Other aggregations \nej4 = sqldf(\" \n SELECT \n avg(arr_delay) as mean_arr_delay, \n min(dep_delay) as min_dep_delay, \n max(dep_delay) as max_dep_delay, \n carrier \n FROM \n flights \n GROUP BY \n carrier \n\") \n\n# We can compute the minimun, mean, and maximum values of a numeric value \nej4 \n# mean_arr_delay min_dep_delay max_dep_delay carrier \n# 1 7.3796692 -24 747 9E \n# 2 0.3642909 -24 1014 AA \n# 3 -9.9308886 -21 225 AS \n# 4 9.4579733 -43 502 B6\n# 5 1.6443409 -33 960 DL \n# 6 15.7964311 -32 548 EV \n# 7 21.9207048 -27 853 F9 \n# 8 20.1159055 -22 602 FL \n# 9 -6.9152047 -16 1301 HA \n# 10 10.7747334 -26 1137 MQ \n# 11 11.9310345 -14 154 OO \n# 12 3.5580111 -20 483 UA \n# 13 2.1295951 -19 500 US \n# 14 1.7644644 -20 653 VX \n# 15 9.6491199 -13 471 WN \n# 16 15.5569853 -16 387 YV \n\n### We could be also interested in knowing how many observations each carrier has \nej5 = sqldf(\" \n SELECT \n carrier, count(*) as count \n FROM \n flights \n GROUP BY \n carrier \n\") \n\nej5 \n# carrier count \n# 1 9E 18460\n# 2 AA 32729 \n# 3 AS 714 \n# 4 B6 54635 \n# 5 DL 48110 \n# 6 EV 54173 \n# 7 F9 685 \n# 8 FL 3260 \n# 9 HA 342 \n# 10 MQ 26397 \n# 11 OO 32 \n# 12 UA 58665 \n# 13 US 20536 \n# 14 VX 5162 \n# 15 WN 12275 \n# 16 YV 601 \n" }, { "code": null, "e": 9146, "s": 8842, "text": "The most useful feature of SQL are joins. A join means that we want to combine table A and table B in one table using one column to match the values of both tables. There are different types of joins, in practical terms, to get started these will be the most useful ones: inner join and left outer join." }, { "code": null, "e": 10077, "s": 9146, "text": "# Let’s create two tables: A and B to demonstrate joins.\nA = data.frame(c1 = 1:4, c2 = letters[1:4]) \nB = data.frame(c1 = c(2,4,5,6), c2 = letters[c(2:5)]) \n\nA \n# c1 c2 \n# 1 a \n# 2 b \n# 3 c \n# 4 d \n\nB \n# c1 c2 \n# 2 b \n# 4 c \n# 5 d \n# 6 e \n\n### INNER JOIN \n# This means to match the observations of the column we would join the tables by. \ninner = sqldf(\" \n SELECT \n A.c1, B.c2 \n FROM \n A INNER JOIN B \n ON A.c1 = B.c1 \n\") \n\n# Only the rows that match c1 in both A and B are returned \ninner \n# c1 c2 \n# 2 b \n# 4 c \n\n### LEFT OUTER JOIN\n# the left outer join, sometimes just called left join will return the \n# first all the values of the column used from the A table \nleft = sqldf(\" \n SELECT \n A.c1, B.c2 \n FROM \n A LEFT OUTER JOIN B \n ON A.c1 = B.c1 \n\") \n\n# Only the rows that match c1 in both A and B are returned \nleft \n# c1 c2 \n# 1 <NA> \n# 2 b \n# 3 <NA> \n# 4 c \n" }, { "code": null, "e": 10110, "s": 10077, "text": "\n 65 Lectures \n 6 hours \n" }, { "code": null, "e": 10129, "s": 10110, "text": " Arnab Chakraborty" }, { "code": null, "e": 10164, "s": 10129, "text": "\n 18 Lectures \n 1.5 hours \n" }, { "code": null, "e": 10204, "s": 10164, "text": " Pranjal Srivastava, Harshit Srivastava" }, { "code": null, "e": 10237, "s": 10204, "text": "\n 23 Lectures \n 2 hours \n" }, { "code": null, "e": 10248, "s": 10237, "text": " John Shea" }, { "code": null, "e": 10283, "s": 10248, "text": "\n 18 Lectures \n 1.5 hours \n" }, { "code": null, "e": 10303, "s": 10283, "text": " Pranjal Srivastava" }, { "code": null, "e": 10338, "s": 10303, "text": "\n 46 Lectures \n 3.5 hours \n" }, { "code": null, "e": 10358, "s": 10338, "text": " Pranjal Srivastava" }, { "code": null, "e": 10393, "s": 10358, "text": "\n 37 Lectures \n 3.5 hours \n" }, { "code": null, "e": 10433, "s": 10393, "text": " Pranjal Srivastava, Harshit Srivastava" }, { "code": null, "e": 10440, "s": 10433, "text": " Print" }, { "code": null, "e": 10451, "s": 10440, "text": " Add Notes" } ]
How to generate standard normal random numbers in R?
A standard normal distribution is the type of distribution that has mean equals to zero with standard deviation 1. If we want to generate standard normal random numbers then rnorm function of R can be used but need to pass the mean = 0 and standard deviation = 1 inside this function. Live Demo rnorm(10,0,1) [1] 0.6936607 -0.7967657 -2.7544428 0.2688767 0.5278463 -1.5387568 [7] 1.1716632 -1.5033895 0.8112929 -1.0101065 Live Demo rnorm(50,0,1) [1] 2.58246666 -0.53083341 -0.57343343 1.08172756 1.30341849 -0.07440422 [7] -0.41869305 -0.96227706 -0.46899119 1.55428279 0.09162738 -0.96027221 [13] -0.84735327 -1.74949782 0.58541758 0.23117630 0.47402479 -0.72453853 [19] 0.07171564 1.13088794 0.18735157 0.25091758 -1.34728315 -0.39768159 [25] -0.38109955 -0.34019286 -1.51778561 -0.92222239 -1.22798041 -0.77350032 [31] -1.65852274 0.51227977 0.83822730 0.45359267 0.49714674 -1.47674552 [37] -0.01242228 1.60937112 0.38869615 1.73720338 0.56832087 -0.35619856 [43] -1.74371897 -0.77162373 -1.80142363 -0.92801065 0.92791947 0.14078622 [49] -1.55200961 -0.06995120 Live Demo rnorm(60,0,1) [1] -0.98030635 0.14934486 -1.55025640 0.80780101 -0.54240515 0.14488726 [7] 2.89290245 1.10729520 0.08050478 -0.44497057 1.10941494 1.74939247 [13] 0.84032675 0.47427879 0.11898992 1.85356655 0.19312780 -0.47810793 [19] 2.36569993 -0.45530246 -0.81494824 -1.99941347 -0.50359976 0.55592840 [25] 1.14048452 -1.02259883 -1.17629055 1.48930583 1.76136612 0.70749370 [31] 0.88976803 0.87302066 -0.90594396 -0.92584519 -0.57771767 -2.01680635 [37] 1.25990880 0.87272304 3.86728923 0.48660167 2.12238845 -1.23884756 [43] -0.29534035 -1.66654062 -0.92580904 0.46701435 -0.27171548 -0.79118171 [49] -1.87119180 -1.43572885 3.60672069 0.58631139 -0.38245860 0.62229426 [55] -0.54297322 -2.39866511 -1.91755583 -0.61459590 0.11865738 0.65653693 Live Demo rnorm(80,0,1) [1] -0.21167734 1.00334018 0.58986878 -1.15025242 0.83748340 0.04415646 [7] 0.21006101 -0.35285172 -0.53306794 -0.31683124 -0.15284674 1.72136890 [13] 0.67868984 -0.40103797 0.19409371 -0.31236848 1.08174032 0.82741254 [19] 1.52301592 0.92592501 -1.13193294 -0.52651889 -0.22310016 -0.93938644 [25] 0.27894221 -2.89894569 0.36546350 0.84345631 -0.81706708 0.18261437 [31] -0.69591250 1.09539577 -1.15864497 -0.22639388 -0.32866906 -1.12182835 [37] -0.08435003 1.81382691 0.04255180 -0.32941539 2.64070059 1.56935548 [43] -0.24635038 0.62292947 1.05232124 0.67012389 0.91400357 0.26348570 [49] -0.35494585 1.09602375 -1.39164787 -0.36638726 1.76550599 -0.22423221 [55] -0.33138915 -0.66652623 -0.50509947 -0.93338252 -2.70014038 -0.52016919 [61] 0.80396082 0.75912405 0.52966924 0.76088675 0.87390249 0.19404944 [67] -0.94092779 -1.20741440 -1.28536191 0.03052385 -2.23973254 -0.39531601 [73] -0.84322501 0.78849127 1.70032152 1.11591005 -1.15304534 -1.23219567 [79] 0.91807504 1.21157462 Live Demo rnorm(100,0,1) [1] -0.60163722 0.62726820 -0.78769462 0.72244706 -0.57654069 0.21386083 [7] -0.53096986 0.34563279 -0.97023650 -0.94702500 -0.37624883 0.44073439 [13] 0.51851495 -1.93362586 0.74274197 -0.81861024 -0.49963242 1.45553031 [19] -0.47880775 -0.23169624 0.46348261 -1.19764668 0.77737123 -0.50783209 [25] -1.58899290 0.50528381 1.89222336 -0.57809997 0.05806867 1.16785099 [31] -1.06614535 0.61556520 -0.83564718 -1.02615977 0.89271898 0.53811493 [37] -0.54849449 -0.62497474 0.25675859 0.70320768 0.05848728 0.78376690 [43] 0.44276061 -0.58697558 -0.59758547 1.22975543 1.46945195 -0.79496156 [49] -0.58237963 0.16137738 0.22260587 0.45833685 -0.17046269 0.44890726 [55] -0.15563031 0.73221957 -1.97896622 -1.47629166 -2.02214096 -0.96495535 [61] 0.63474420 1.34149420 -0.91755563 0.35488624 0.01262576 -0.34079663 [67] 0.07963539 0.88896173 1.75045613 -0.08678552 0.19245374 1.32575165 [73] 1.41738151 -1.35060833 0.63737697 0.33369705 1.27021960 1.00779108 [79] -1.19586882 0.72829141 -0.09938002 -0.79827963 -1.20575102 -1.09457152 [85] 0.66310803 -0.41086839 -0.50120916 0.02167787 0.60022806 2.94091060 [91] -0.39845012 0.82483674 -2.72699869 -0.48183377 0.57821380 -0.85565220 [97] 2.55905507 0.24447168 0.53042496 -0.31205488
[ { "code": null, "e": 1347, "s": 1062, "text": "A standard normal distribution is the type of distribution that has mean equals to zero with standard deviation 1. If we want to generate standard normal random numbers then rnorm function of R can be used but need to pass the mean = 0 and standard deviation = 1 inside this function." }, { "code": null, "e": 1358, "s": 1347, "text": " Live Demo" }, { "code": null, "e": 1372, "s": 1358, "text": "rnorm(10,0,1)" }, { "code": null, "e": 1485, "s": 1372, "text": "[1] 0.6936607 -0.7967657 -2.7544428 0.2688767 0.5278463 -1.5387568\n[7] 1.1716632 -1.5033895 0.8112929 -1.0101065" }, { "code": null, "e": 1496, "s": 1485, "text": " Live Demo" }, { "code": null, "e": 1510, "s": 1496, "text": "rnorm(50,0,1)" }, { "code": null, "e": 2131, "s": 1510, "text": "[1] 2.58246666 -0.53083341 -0.57343343 1.08172756 1.30341849 -0.07440422\n[7] -0.41869305 -0.96227706 -0.46899119 1.55428279 0.09162738 -0.96027221\n[13] -0.84735327 -1.74949782 0.58541758 0.23117630 0.47402479 -0.72453853\n[19] 0.07171564 1.13088794 0.18735157 0.25091758 -1.34728315 -0.39768159\n[25] -0.38109955 -0.34019286 -1.51778561 -0.92222239 -1.22798041 -0.77350032\n[31] -1.65852274 0.51227977 0.83822730 0.45359267 0.49714674 -1.47674552\n[37] -0.01242228 1.60937112 0.38869615 1.73720338 0.56832087 -0.35619856\n[43] -1.74371897 -0.77162373 -1.80142363 -0.92801065 0.92791947 0.14078622\n[49] -1.55200961 -0.06995120" }, { "code": null, "e": 2142, "s": 2131, "text": " Live Demo" }, { "code": null, "e": 2156, "s": 2142, "text": "rnorm(60,0,1)" }, { "code": null, "e": 2892, "s": 2156, "text": "[1] -0.98030635 0.14934486 -1.55025640 0.80780101 -0.54240515 0.14488726\n[7] 2.89290245 1.10729520 0.08050478 -0.44497057 1.10941494 1.74939247\n[13] 0.84032675 0.47427879 0.11898992 1.85356655 0.19312780 -0.47810793\n[19] 2.36569993 -0.45530246 -0.81494824 -1.99941347 -0.50359976 0.55592840\n[25] 1.14048452 -1.02259883 -1.17629055 1.48930583 1.76136612 0.70749370\n[31] 0.88976803 0.87302066 -0.90594396 -0.92584519 -0.57771767 -2.01680635\n[37] 1.25990880 0.87272304 3.86728923 0.48660167 2.12238845 -1.23884756\n[43] -0.29534035 -1.66654062 -0.92580904 0.46701435 -0.27171548 -0.79118171\n[49] -1.87119180 -1.43572885 3.60672069 0.58631139 -0.38245860 0.62229426\n[55] -0.54297322 -2.39866511 -1.91755583 -0.61459590 0.11865738 0.65653693" }, { "code": null, "e": 2903, "s": 2892, "text": " Live Demo" }, { "code": null, "e": 2917, "s": 2903, "text": "rnorm(80,0,1)" }, { "code": null, "e": 3905, "s": 2917, "text": "[1] -0.21167734 1.00334018 0.58986878 -1.15025242 0.83748340 0.04415646\n[7] 0.21006101 -0.35285172 -0.53306794 -0.31683124 -0.15284674 1.72136890\n[13] 0.67868984 -0.40103797 0.19409371 -0.31236848 1.08174032 0.82741254\n[19] 1.52301592 0.92592501 -1.13193294 -0.52651889 -0.22310016 -0.93938644\n[25] 0.27894221 -2.89894569 0.36546350 0.84345631 -0.81706708 0.18261437\n[31] -0.69591250 1.09539577 -1.15864497 -0.22639388 -0.32866906 -1.12182835\n[37] -0.08435003 1.81382691 0.04255180 -0.32941539 2.64070059 1.56935548\n[43] -0.24635038 0.62292947 1.05232124 0.67012389 0.91400357 0.26348570\n[49] -0.35494585 1.09602375 -1.39164787 -0.36638726 1.76550599 -0.22423221\n[55] -0.33138915 -0.66652623 -0.50509947 -0.93338252 -2.70014038 -0.52016919\n[61] 0.80396082 0.75912405 0.52966924 0.76088675 0.87390249 0.19404944\n[67] -0.94092779 -1.20741440 -1.28536191 0.03052385 -2.23973254 -0.39531601\n[73] -0.84322501 0.78849127 1.70032152 1.11591005 -1.15304534 -1.23219567\n[79] 0.91807504 1.21157462" }, { "code": null, "e": 3916, "s": 3905, "text": " Live Demo" }, { "code": null, "e": 3931, "s": 3916, "text": "rnorm(100,0,1)" }, { "code": null, "e": 5161, "s": 3931, "text": "[1] -0.60163722 0.62726820 -0.78769462 0.72244706 -0.57654069 0.21386083\n[7] -0.53096986 0.34563279 -0.97023650 -0.94702500 -0.37624883 0.44073439\n[13] 0.51851495 -1.93362586 0.74274197 -0.81861024 -0.49963242 1.45553031\n[19] -0.47880775 -0.23169624 0.46348261 -1.19764668 0.77737123 -0.50783209\n[25] -1.58899290 0.50528381 1.89222336 -0.57809997 0.05806867 1.16785099\n[31] -1.06614535 0.61556520 -0.83564718 -1.02615977 0.89271898 0.53811493\n[37] -0.54849449 -0.62497474 0.25675859 0.70320768 0.05848728 0.78376690\n[43] 0.44276061 -0.58697558 -0.59758547 1.22975543 1.46945195 -0.79496156\n[49] -0.58237963 0.16137738 0.22260587 0.45833685 -0.17046269 0.44890726\n[55] -0.15563031 0.73221957 -1.97896622 -1.47629166 -2.02214096 -0.96495535\n[61] 0.63474420 1.34149420 -0.91755563 0.35488624 0.01262576 -0.34079663\n[67] 0.07963539 0.88896173 1.75045613 -0.08678552 0.19245374 1.32575165\n[73] 1.41738151 -1.35060833 0.63737697 0.33369705 1.27021960 1.00779108\n[79] -1.19586882 0.72829141 -0.09938002 -0.79827963 -1.20575102 -1.09457152\n[85] 0.66310803 -0.41086839 -0.50120916 0.02167787 0.60022806 2.94091060\n[91] -0.39845012 0.82483674 -2.72699869 -0.48183377 0.57821380 -0.85565220\n[97] 2.55905507 0.24447168 0.53042496 -0.31205488" } ]
Node.js – Chalk Module
The chalk module is a third-party library that can be used for styling of texts. It allows the users to create their own themes in a Node.js project. This module helps the users to customize the response messages with different colors as per the preferences. This module helps the users to customize the response messages with different colors as per the preferences. It also improves the readability by providing colors and makes it easier to detect warnings and errors. It also improves the readability by providing colors and makes it easier to detect warnings and errors. npm install chalk Create a file with the name "chalk.js" and copy the following code. After creating the file, use the command "node chalk.js" to run this code as shown in the example below − // Importing the chalk module const chalk=require("chalk"); // Coloring different text messages console.log(chalk.green("Welcome to Tutorials Point")) console.log(chalk.red.underline("Welcome to Tutorials Point")) console.log(chalk.red.underline.bold("Welcome to Tutorials Point")) Let's take another example // Importing the chalk module const chalk=require("chalk"); // Coloring different text messages const welcome=chalk.green; const warning=chalk.red; console.log(welcome("Welcome to Tutorials Point")) console.log(welcome("Success !!!")) console.log(warning("Error - An unknown error occurred !")) console.log(warning("Warning - Exception occurred !"))
[ { "code": null, "e": 1212, "s": 1062, "text": "The chalk module is a third-party library that can be used for styling of texts. It allows the users to create their own themes in a Node.js project." }, { "code": null, "e": 1321, "s": 1212, "text": "This module helps the users to customize the response messages with\ndifferent colors as per the preferences." }, { "code": null, "e": 1430, "s": 1321, "text": "This module helps the users to customize the response messages with\ndifferent colors as per the preferences." }, { "code": null, "e": 1534, "s": 1430, "text": "It also improves the readability by providing colors and makes it easier\nto detect warnings and errors." }, { "code": null, "e": 1638, "s": 1534, "text": "It also improves the readability by providing colors and makes it easier\nto detect warnings and errors." }, { "code": null, "e": 1656, "s": 1638, "text": "npm install chalk" }, { "code": null, "e": 1830, "s": 1656, "text": "Create a file with the name \"chalk.js\" and copy the following code. After creating the file, use the command \"node chalk.js\" to run this code as shown in the example below −" }, { "code": null, "e": 2113, "s": 1830, "text": "// Importing the chalk module\nconst chalk=require(\"chalk\");\n\n// Coloring different text messages\nconsole.log(chalk.green(\"Welcome to Tutorials Point\"))\nconsole.log(chalk.red.underline(\"Welcome to Tutorials Point\"))\nconsole.log(chalk.red.underline.bold(\"Welcome to Tutorials Point\"))" }, { "code": null, "e": 2140, "s": 2113, "text": "Let's take another example" }, { "code": null, "e": 2492, "s": 2140, "text": "// Importing the chalk module\nconst chalk=require(\"chalk\");\n\n// Coloring different text messages\nconst welcome=chalk.green;\nconst warning=chalk.red;\n\nconsole.log(welcome(\"Welcome to Tutorials Point\"))\nconsole.log(welcome(\"Success !!!\"))\nconsole.log(warning(\"Error - An unknown error occurred !\"))\nconsole.log(warning(\"Warning - Exception occurred !\"))" } ]
MongoDB - Database, Collection, and Document - GeeksforGeeks
13 Aug, 2021 Databases, collections, documents are important parts of MongoDB without them you are not able to store data on the MongoDB server. A Database contains a collection, and a collection contains documents and the documents contain data, they are related to each other. In MongoDB, a database contains the collections of documents. One can create multiple databases on the MongoDB server. To see how many databases are present in your MongoDB server, write the following statement in the mongo shell: show dbs For Example: Here, we freshly started MongoDB so we do not have a database except these three default databases, i.e, admin, config, and local. Before creating a database you should first learn about the naming restrictions for databases: In MongoDB, the names of the database are case insensitive, but you must always remember that the database names cannot differ only by the case of the characters. For windows user, MongoDB database names cannot contain any of these following characters: /\. "$*:|? For Unix and Linux users, MongoDB database names cannot contain any of these following characters: /\. "$ MongoDB database names cannot contain null characters(in windows, Unix, and Linux systems). MongoDB database names cannot be empty and must contain less than 64 characters. In the mongo shell, you can create a database with the help of the following command: use database_name This command actually switches you to the new database if the given name does not exist and if the given name exists, then it will switch you to the existing database. Now at this stage, if you use the show command to see the database list where you will find that your new database is not present in that database list because, in MongoDB, the database is actually created when you start entering data in that database. For Example: Here, we create a new database named GeeksforGeeks using the use command. After creating a database when we check the database list we do not find our database on that list because we do not enter any data in the GeeksforGeeks database. Collections are just like tables in relational databases, they also store data, but in the form of documents. A single database is allowed to store multiple collections. As we know that MongoDB databases are schemaless. So, it is not necessary in a collection that the schema of one document is similar to another document. Or in other words, a single collection contains different types of documents like as shown in the below example where mystudentData collection contain two different types of documents: Before creating a collection you should first learn about the naming restrictions for collections: Collection name must starts with an underscore or a character. Collection name does not contain $, empty string, null character and does not begin with system. prefix. The maximum length of the collection name is 120 bytes(including the database name, dot separator, and the collection name). After creating database now we create a collection to store documents. The collection is created using the following syntax: db.collection_name.insertOne({..}) Here, insertOne() function is used to store single data in the specified collection. And in the curly braces {} we store our data or in other words, it is a document. For Example: In this example, we create a collection named as the Author and we insert data in it with the help of insertOne() function. Or in other words, {name: “Ankita”} is a document in the Author collection, and in this document, the name is the key or field and “Ankita” is the value of this key or field. After pressing enter we got a message(as shown in the above image) and this message tells us that the data enters successfully (i.e., “acknowledge”: true) and also assigns us an automatically created id. It is the special feature provided by MongoDB that every document provided a unique id and generally, this id is created automatically, but you are allowed to create your own id (must be unique). In MongoDB, the data records are stored as BSON documents. Here, BSON stands for binary representation of JSON documents, although BSON contains more data types as compared to JSON. The document is created using field-value pairs or key-value pairs and the value of the field can be of any BSON type. Syntax: { field1: value1 field2: value2 .... fieldN: valueN } Before moving further first you should learn about the naming restrictions for fields: The field names are of strings. The _id field name is reserved to use as a primary key. And the value of this field must be unique, immutable, and can be of any type other than an array. The field name cannot contain null characters. The top-level field names should not start with a dollar sign ($). Document Size: The maximum size of the BSON document is 16MB. It ensures that the single document does not use too much amount of RAM or bandwidth(during transmission). If a document contains more data than the specified size, then MongoDB provides a GridFS API to store such type of documents. Important Notes – A single document may contain duplicate fields. MongoDB always saves the order of the fields in the documents except for the _id field (which always comes in the first place) and the renaming of fields may change the order of the fields in the documents. _id Field: In MongoDB, every document store in the collection must contain a unique _id field it is just like a primary key in a relational database. The value of the _id field can be set by the user or by the system (if the user does not create an _id field, then the system will automatically generate an ObjectId for _id field). When you create a collection MongoDB automatically creates a unique index on the _id field.The _id field is the first field of every document.The value of the _id field can be of any BSON type except arrays.The default value of the _id field is ObjectId. When you create a collection MongoDB automatically creates a unique index on the _id field. The _id field is the first field of every document. The value of the _id field can be of any BSON type except arrays. The default value of the _id field is ObjectId. Example #1: Here, name, branch, course, and paid field contain values of string type. amount field contains the value of integer type and _id field is generated by the system. Example #2: Here, the _id field is created by the user. Tip: When you paste data in the functions always use close parenthesis after pasting the data into the function. If you use close parenthesis before pasting data in the function, then you will get an error. singghakshay MongoDB Advanced Computer Subject Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. ML | Linear Regression Decision Tree Introduction with example Copying Files to and from Docker Containers System Design Tutorial Python | Decision tree implementation ML | Underfitting and Overfitting Clustering in Machine Learning Docker - COPY Instruction KDD Process in Data Mining How to Run a Python Script using Docker?
[ { "code": null, "e": 25400, "s": 25372, "text": "\n13 Aug, 2021" }, { "code": null, "e": 25667, "s": 25400, "text": "Databases, collections, documents are important parts of MongoDB without them you are not able to store data on the MongoDB server. A Database contains a collection, and a collection contains documents and the documents contain data, they are related to each other. " }, { "code": null, "e": 25788, "s": 25667, "text": "In MongoDB, a database contains the collections of documents. One can create multiple databases on the MongoDB server. " }, { "code": null, "e": 25902, "s": 25788, "text": "To see how many databases are present in your MongoDB server, write the following statement in the mongo shell: " }, { "code": null, "e": 25911, "s": 25902, "text": "show dbs" }, { "code": null, "e": 25926, "s": 25911, "text": "For Example: " }, { "code": null, "e": 26059, "s": 25926, "text": "Here, we freshly started MongoDB so we do not have a database except these three default databases, i.e, admin, config, and local. " }, { "code": null, "e": 26156, "s": 26059, "text": "Before creating a database you should first learn about the naming restrictions for databases: " }, { "code": null, "e": 26319, "s": 26156, "text": "In MongoDB, the names of the database are case insensitive, but you must always remember that the database names cannot differ only by the case of the characters." }, { "code": null, "e": 26411, "s": 26319, "text": "For windows user, MongoDB database names cannot contain any of these following characters: " }, { "code": null, "e": 26422, "s": 26411, "text": "/\\. \"$*:|?" }, { "code": null, "e": 26522, "s": 26422, "text": "For Unix and Linux users, MongoDB database names cannot contain any of these following characters: " }, { "code": null, "e": 26529, "s": 26522, "text": "/\\. \"$" }, { "code": null, "e": 26621, "s": 26529, "text": "MongoDB database names cannot contain null characters(in windows, Unix, and Linux systems)." }, { "code": null, "e": 26703, "s": 26621, "text": "MongoDB database names cannot be empty and must contain less than 64 characters. " }, { "code": null, "e": 26791, "s": 26703, "text": "In the mongo shell, you can create a database with the help of the following command: " }, { "code": null, "e": 26810, "s": 26791, "text": "use database_name " }, { "code": null, "e": 27232, "s": 26810, "text": "This command actually switches you to the new database if the given name does not exist and if the given name exists, then it will switch you to the existing database. Now at this stage, if you use the show command to see the database list where you will find that your new database is not present in that database list because, in MongoDB, the database is actually created when you start entering data in that database. " }, { "code": null, "e": 27247, "s": 27232, "text": "For Example: " }, { "code": null, "e": 27485, "s": 27247, "text": "Here, we create a new database named GeeksforGeeks using the use command. After creating a database when we check the database list we do not find our database on that list because we do not enter any data in the GeeksforGeeks database. " }, { "code": null, "e": 27657, "s": 27485, "text": "Collections are just like tables in relational databases, they also store data, but in the form of documents. A single database is allowed to store multiple collections. " }, { "code": null, "e": 27997, "s": 27657, "text": "As we know that MongoDB databases are schemaless. So, it is not necessary in a collection that the schema of one document is similar to another document. Or in other words, a single collection contains different types of documents like as shown in the below example where mystudentData collection contain two different types of documents: " }, { "code": null, "e": 28097, "s": 27997, "text": "Before creating a collection you should first learn about the naming restrictions for collections: " }, { "code": null, "e": 28160, "s": 28097, "text": "Collection name must starts with an underscore or a character." }, { "code": null, "e": 28265, "s": 28160, "text": "Collection name does not contain $, empty string, null character and does not begin with system. prefix." }, { "code": null, "e": 28390, "s": 28265, "text": "The maximum length of the collection name is 120 bytes(including the database name, dot separator, and the collection name)." }, { "code": null, "e": 28516, "s": 28390, "text": "After creating database now we create a collection to store documents. The collection is created using the following syntax: " }, { "code": null, "e": 28551, "s": 28516, "text": "db.collection_name.insertOne({..})" }, { "code": null, "e": 28719, "s": 28551, "text": "Here, insertOne() function is used to store single data in the specified collection. And in the curly braces {} we store our data or in other words, it is a document. " }, { "code": null, "e": 28734, "s": 28719, "text": "For Example: " }, { "code": null, "e": 29435, "s": 28734, "text": "In this example, we create a collection named as the Author and we insert data in it with the help of insertOne() function. Or in other words, {name: “Ankita”} is a document in the Author collection, and in this document, the name is the key or field and “Ankita” is the value of this key or field. After pressing enter we got a message(as shown in the above image) and this message tells us that the data enters successfully (i.e., “acknowledge”: true) and also assigns us an automatically created id. It is the special feature provided by MongoDB that every document provided a unique id and generally, this id is created automatically, but you are allowed to create your own id (must be unique). " }, { "code": null, "e": 29737, "s": 29435, "text": "In MongoDB, the data records are stored as BSON documents. Here, BSON stands for binary representation of JSON documents, although BSON contains more data types as compared to JSON. The document is created using field-value pairs or key-value pairs and the value of the field can be of any BSON type. " }, { "code": null, "e": 29747, "s": 29737, "text": "Syntax: " }, { "code": null, "e": 29802, "s": 29747, "text": "{ \nfield1: value1\nfield2: value2\n....\nfieldN: valueN\n}" }, { "code": null, "e": 29890, "s": 29802, "text": "Before moving further first you should learn about the naming restrictions for fields: " }, { "code": null, "e": 29922, "s": 29890, "text": "The field names are of strings." }, { "code": null, "e": 30077, "s": 29922, "text": "The _id field name is reserved to use as a primary key. And the value of this field must be unique, immutable, and can be of any type other than an array." }, { "code": null, "e": 30124, "s": 30077, "text": "The field name cannot contain null characters." }, { "code": null, "e": 30191, "s": 30124, "text": "The top-level field names should not start with a dollar sign ($)." }, { "code": null, "e": 30487, "s": 30191, "text": "Document Size: The maximum size of the BSON document is 16MB. It ensures that the single document does not use too much amount of RAM or bandwidth(during transmission). If a document contains more data than the specified size, then MongoDB provides a GridFS API to store such type of documents. " }, { "code": null, "e": 30507, "s": 30487, "text": "Important Notes – " }, { "code": null, "e": 30555, "s": 30507, "text": "A single document may contain duplicate fields." }, { "code": null, "e": 30762, "s": 30555, "text": "MongoDB always saves the order of the fields in the documents except for the _id field (which always comes in the first place) and the renaming of fields may change the order of the fields in the documents." }, { "code": null, "e": 31349, "s": 30762, "text": "_id Field: In MongoDB, every document store in the collection must contain a unique _id field it is just like a primary key in a relational database. The value of the _id field can be set by the user or by the system (if the user does not create an _id field, then the system will automatically generate an ObjectId for _id field). When you create a collection MongoDB automatically creates a unique index on the _id field.The _id field is the first field of every document.The value of the _id field can be of any BSON type except arrays.The default value of the _id field is ObjectId." }, { "code": null, "e": 31441, "s": 31349, "text": "When you create a collection MongoDB automatically creates a unique index on the _id field." }, { "code": null, "e": 31493, "s": 31441, "text": "The _id field is the first field of every document." }, { "code": null, "e": 31559, "s": 31493, "text": "The value of the _id field can be of any BSON type except arrays." }, { "code": null, "e": 31607, "s": 31559, "text": "The default value of the _id field is ObjectId." }, { "code": null, "e": 31621, "s": 31607, "text": "Example #1: " }, { "code": null, "e": 31786, "s": 31621, "text": "Here, name, branch, course, and paid field contain values of string type. amount field contains the value of integer type and _id field is generated by the system. " }, { "code": null, "e": 31800, "s": 31786, "text": "Example #2: " }, { "code": null, "e": 31845, "s": 31800, "text": "Here, the _id field is created by the user. " }, { "code": null, "e": 32053, "s": 31845, "text": "Tip: When you paste data in the functions always use close parenthesis after pasting the data into the function. If you use close parenthesis before pasting data in the function, then you will get an error. " }, { "code": null, "e": 32066, "s": 32053, "text": "singghakshay" }, { "code": null, "e": 32074, "s": 32066, "text": "MongoDB" }, { "code": null, "e": 32100, "s": 32074, "text": "Advanced Computer Subject" }, { "code": null, "e": 32198, "s": 32100, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32221, "s": 32198, "text": "ML | Linear Regression" }, { "code": null, "e": 32261, "s": 32221, "text": "Decision Tree Introduction with example" }, { "code": null, "e": 32305, "s": 32261, "text": "Copying Files to and from Docker Containers" }, { "code": null, "e": 32328, "s": 32305, "text": "System Design Tutorial" }, { "code": null, "e": 32366, "s": 32328, "text": "Python | Decision tree implementation" }, { "code": null, "e": 32400, "s": 32366, "text": "ML | Underfitting and Overfitting" }, { "code": null, "e": 32431, "s": 32400, "text": "Clustering in Machine Learning" }, { "code": null, "e": 32457, "s": 32431, "text": "Docker - COPY Instruction" }, { "code": null, "e": 32484, "s": 32457, "text": "KDD Process in Data Mining" } ]
Python | Get match indices - GeeksforGeeks
19 Mar, 2019 Sometimes, while working with lists we need to handle two lists and search for the matches, and return just the indices of the match. Querying the whole list for this process is not feasible when the size of master list is very large, hence having just the match indices helps in this cause. Let’s discuss certain ways in which this can be achieved. Method #1 : Using list comprehension + index()This problem can potentially be solved using the index function of python to get the wanted indices and list comprehension can be used to extend this to the whole string. # Python3 code to demonstrate# Get match indices# using list comprehension and index() # initializing liststest_list1 = [5, 4, 1, 3, 2]test_list2 = [1, 2] # printing original listsprint("The original list 1 : " + str(test_list1))print("The original list 2 : " + str(test_list2)) # using list comprehension and index()# Get match indicesres = [test_list1.index(i) for i in test_list2] # print resultprint("The Match indices list is : " + str(res)) The original list 1 : [5, 4, 1, 3, 2] The original list 2 : [1, 2] The Match indices list is : [2, 4] Method #2 : Using enumerate() + list comprehensionThe enumerate function can be used to produce the key value pair for the list being it’s index and value and we can store them using list comprehension. # Python3 code to demonstrate# Get match indices# using list comprehension and enumerate() # initializing liststest_list1 = [5, 4, 1, 3, 2]test_list2 = [1, 2] # printing original listsprint("The original list 1 : " + str(test_list1))print("The original list 2 : " + str(test_list2)) # using list comprehension and enumerate()# Get match indicesres = [key for key, val in enumerate(test_list1) if val in set(test_list2)] # print resultprint("The Match indices list is : " + str(res)) The original list 1 : [5, 4, 1, 3, 2] The original list 2 : [1, 2] The Match indices list is : [2, 4] Python list-programs python-list Python Python Programs python-list Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python program to convert a list to string Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary
[ { "code": null, "e": 26257, "s": 26229, "text": "\n19 Mar, 2019" }, { "code": null, "e": 26607, "s": 26257, "text": "Sometimes, while working with lists we need to handle two lists and search for the matches, and return just the indices of the match. Querying the whole list for this process is not feasible when the size of master list is very large, hence having just the match indices helps in this cause. Let’s discuss certain ways in which this can be achieved." }, { "code": null, "e": 26824, "s": 26607, "text": "Method #1 : Using list comprehension + index()This problem can potentially be solved using the index function of python to get the wanted indices and list comprehension can be used to extend this to the whole string." }, { "code": "# Python3 code to demonstrate# Get match indices# using list comprehension and index() # initializing liststest_list1 = [5, 4, 1, 3, 2]test_list2 = [1, 2] # printing original listsprint(\"The original list 1 : \" + str(test_list1))print(\"The original list 2 : \" + str(test_list2)) # using list comprehension and index()# Get match indicesres = [test_list1.index(i) for i in test_list2] # print resultprint(\"The Match indices list is : \" + str(res))", "e": 27275, "s": 26824, "text": null }, { "code": null, "e": 27378, "s": 27275, "text": "The original list 1 : [5, 4, 1, 3, 2]\nThe original list 2 : [1, 2]\nThe Match indices list is : [2, 4]\n" }, { "code": null, "e": 27583, "s": 27380, "text": "Method #2 : Using enumerate() + list comprehensionThe enumerate function can be used to produce the key value pair for the list being it’s index and value and we can store them using list comprehension." }, { "code": "# Python3 code to demonstrate# Get match indices# using list comprehension and enumerate() # initializing liststest_list1 = [5, 4, 1, 3, 2]test_list2 = [1, 2] # printing original listsprint(\"The original list 1 : \" + str(test_list1))print(\"The original list 2 : \" + str(test_list2)) # using list comprehension and enumerate()# Get match indicesres = [key for key, val in enumerate(test_list1) if val in set(test_list2)] # print resultprint(\"The Match indices list is : \" + str(res))", "e": 28091, "s": 27583, "text": null }, { "code": null, "e": 28194, "s": 28091, "text": "The original list 1 : [5, 4, 1, 3, 2]\nThe original list 2 : [1, 2]\nThe Match indices list is : [2, 4]\n" }, { "code": null, "e": 28215, "s": 28194, "text": "Python list-programs" }, { "code": null, "e": 28227, "s": 28215, "text": "python-list" }, { "code": null, "e": 28234, "s": 28227, "text": "Python" }, { "code": null, "e": 28250, "s": 28234, "text": "Python Programs" }, { "code": null, "e": 28262, "s": 28250, "text": "python-list" }, { "code": null, "e": 28360, "s": 28262, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28378, "s": 28360, "text": "Python Dictionary" }, { "code": null, "e": 28410, "s": 28378, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28432, "s": 28410, "text": "Enumerate() in Python" }, { "code": null, "e": 28474, "s": 28432, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28504, "s": 28474, "text": "Iterate over a list in Python" }, { "code": null, "e": 28547, "s": 28504, "text": "Python program to convert a list to string" }, { "code": null, "e": 28569, "s": 28547, "text": "Defaultdict in Python" }, { "code": null, "e": 28608, "s": 28569, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 28654, "s": 28608, "text": "Python | Split string into list of characters" } ]
How to debug lambda expressions in Java?
The lambda expression composed of two parts, one is an argument and another one is code or expression. These two parts have separated by an arrow operator "->". We can use different IDE's like Netbeans, IntelliJ, and Eclipse to debug the lambda expressions in Java. It is always possible to create multi-line lambda expressions and use print statements to display the values of a variable. The debugger can also provide additional information about the state of a java program. It allows some variables to be modified while the debugger is executing. (parameters) -> expression or (parameters) -> { statements; } import java.util.*; public class LambdaDebugTest { public static void main(String args[]) { List<Strng> list = Arrays.asList("jai", "adithya", "raja"); list.stream() .map(s -> s + " - " + s.toUpperCase()) // Convert to upper case using lambda .forEach(s -> System.out.println(s)); // To print 's' using lambda } } jai - JAI adithya - ADITHYA raja - RAJA
[ { "code": null, "e": 1613, "s": 1062, "text": "The lambda expression composed of two parts, one is an argument and another one is code or expression. These two parts have separated by an arrow operator \"->\". We can use different IDE's like Netbeans, IntelliJ, and Eclipse to debug the lambda expressions in Java. It is always possible to create multi-line lambda expressions and use print statements to display the values of a variable. The debugger can also provide additional information about the state of a java program. It allows some variables to be modified while the debugger is executing." }, { "code": null, "e": 1677, "s": 1613, "text": "(parameters) -> expression\n or\n(parameters) -> { statements; }" }, { "code": null, "e": 2033, "s": 1677, "text": "import java.util.*;\n\npublic class LambdaDebugTest {\n public static void main(String args[]) {\n List<Strng> list = Arrays.asList(\"jai\", \"adithya\", \"raja\");\n list.stream()\n .map(s -> s + \" - \" + s.toUpperCase()) // Convert to upper case using lambda\n .forEach(s -> System.out.println(s)); // To print 's' using lambda\n }\n}" }, { "code": null, "e": 2073, "s": 2033, "text": "jai - JAI\nadithya - ADITHYA\nraja - RAJA" } ]
Apply Glowing Effect to the Image using HTML and CSS - GeeksforGeeks
16 Feb, 2021 While surfing most of the websites you have seen some special effects which can be seen on various images while putting your cursor over them. So, in this article we are going to implement the same. We can use such images as a card for our website. In this article, you’re going to learn how to apply glowing effect to a particular image, when you put cursor over it you will see that effect. We will implement it by using HTML and CSS. A sample video is provided to understand more clearly what you are going to develop in this article. HTML <!-- Give a suitable heading using h1 tag--><h1 style="color: green; text-align: center;"> GeeksForGeeks Glowling Card</h1><div class="container"> <!-- Set a image a background named gfg.jpg present in images folder --> <img class="GFG" src="images/gfg.jpg" alt="GeeksForGeeks" /></div> Now, we will apply some CSS properties to decorate the image and also fix it’s position on webpage. The key is to use the box-shadow property of CSS to glow the image when user put cursor on image. Here is the internal CSS code given to you for help. HTML <style> .GFG{ width:200px ; height:250px; margin-left: 550px; border-radius: 10%;}.GFG:hover{ color: #111; background: greenyellow; box-shadow: 0 0 100px greenyellow; }</style> This example uses box-shadow property to apply glowing effect to the image. You can change the background glowing color according to you. HTML <!DOCTYPE html><html> <head> <style> .GFG { width: 200px; height: 250px; margin-left: 550px; border-radius: 10%; } .GFG:hover { color: #111; background: greenyellow; box-shadow: 0 0 100px greenyellow; } </style></head> <body> <!-- Give a suitable heading using h1 tag--> <h1 style="color: green; text-align: center;"> GeeksForGeeks Glowling Card </h1> <div class="container"> <!-- Set a image a background named gfg.jpg present in images folder --> <img class="GFG" src="images/gfg.jpg" alt="GeeksForGeeks" /> </div> </body> </html> that’s all for this article. Here is the output video of above code. Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. CSS-Questions HTML-Questions Technical Scripter 2020 CSS HTML Technical Scripter Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to set space between the flexbox ? Design a web page using HTML and CSS Form validation using jQuery How to style a checkbox using CSS? Search Bar using HTML, CSS and JavaScript How to set the default value for an HTML <select> element ? Hide or show elements in HTML using display property How to set input type date in dd-mm-yyyy format using HTML ? REST API (Introduction) How to Insert Form Data into Database using PHP ?
[ { "code": null, "e": 26647, "s": 26619, "text": "\n16 Feb, 2021" }, { "code": null, "e": 26897, "s": 26647, "text": "While surfing most of the websites you have seen some special effects which can be seen on various images while putting your cursor over them. So, in this article we are going to implement the same. We can use such images as a card for our website. " }, { "code": null, "e": 27188, "s": 26897, "text": "In this article, you’re going to learn how to apply glowing effect to a particular image, when you put cursor over it you will see that effect. We will implement it by using HTML and CSS. A sample video is provided to understand more clearly what you are going to develop in this article." }, { "code": null, "e": 27193, "s": 27188, "text": "HTML" }, { "code": "<!-- Give a suitable heading using h1 tag--><h1 style=\"color: green; text-align: center;\"> GeeksForGeeks Glowling Card</h1><div class=\"container\"> <!-- Set a image a background named gfg.jpg present in images folder --> <img class=\"GFG\" src=\"images/gfg.jpg\" alt=\"GeeksForGeeks\" /></div>", "e": 27489, "s": 27193, "text": null }, { "code": null, "e": 27741, "s": 27489, "text": "Now, we will apply some CSS properties to decorate the image and also fix it’s position on webpage. The key is to use the box-shadow property of CSS to glow the image when user put cursor on image. Here is the internal CSS code given to you for help. " }, { "code": null, "e": 27746, "s": 27741, "text": "HTML" }, { "code": "<style> .GFG{ width:200px ; height:250px; margin-left: 550px; border-radius: 10%;}.GFG:hover{ color: #111; background: greenyellow; box-shadow: 0 0 100px greenyellow; }</style>", "e": 27949, "s": 27746, "text": null }, { "code": null, "e": 28088, "s": 27949, "text": " This example uses box-shadow property to apply glowing effect to the image. You can change the background glowing color according to you." }, { "code": null, "e": 28093, "s": 28088, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <style> .GFG { width: 200px; height: 250px; margin-left: 550px; border-radius: 10%; } .GFG:hover { color: #111; background: greenyellow; box-shadow: 0 0 100px greenyellow; } </style></head> <body> <!-- Give a suitable heading using h1 tag--> <h1 style=\"color: green; text-align: center;\"> GeeksForGeeks Glowling Card </h1> <div class=\"container\"> <!-- Set a image a background named gfg.jpg present in images folder --> <img class=\"GFG\" src=\"images/gfg.jpg\" alt=\"GeeksForGeeks\" /> </div> </body> </html>", "e": 28811, "s": 28093, "text": null }, { "code": null, "e": 28880, "s": 28811, "text": "that’s all for this article. Here is the output video of above code." }, { "code": null, "e": 29017, "s": 28880, "text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course." }, { "code": null, "e": 29031, "s": 29017, "text": "CSS-Questions" }, { "code": null, "e": 29046, "s": 29031, "text": "HTML-Questions" }, { "code": null, "e": 29070, "s": 29046, "text": "Technical Scripter 2020" }, { "code": null, "e": 29074, "s": 29070, "text": "CSS" }, { "code": null, "e": 29079, "s": 29074, "text": "HTML" }, { "code": null, "e": 29098, "s": 29079, "text": "Technical Scripter" }, { "code": null, "e": 29115, "s": 29098, "text": "Web Technologies" }, { "code": null, "e": 29120, "s": 29115, "text": "HTML" }, { "code": null, "e": 29218, "s": 29120, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29257, "s": 29218, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 29294, "s": 29257, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 29323, "s": 29294, "text": "Form validation using jQuery" }, { "code": null, "e": 29358, "s": 29323, "text": "How to style a checkbox using CSS?" }, { "code": null, "e": 29400, "s": 29358, "text": "Search Bar using HTML, CSS and JavaScript" }, { "code": null, "e": 29460, "s": 29400, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 29513, "s": 29460, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 29574, "s": 29513, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 29598, "s": 29574, "text": "REST API (Introduction)" } ]
Check if a number is Bleak - GeeksforGeeks
17 Nov, 2021 A number ‘n’ is called Bleak if it cannot be represented as sum of a positive number x and set bit count in x, i.e., x + countSetBits(x) is not equal to n for any non-negative number x.Examples : Input : n = 3 Output : false 3 is not Bleak as it can be represented as 2 + countSetBits(2). Input : n = 4 Output : true 4 is t Bleak as it cannot be represented as sum of a number x and countSetBits(x) for any number x. Method 1 (Simple) bool isBleak(n) 1) Consider all numbers smaller than n a) If x + countSetBits(x) == n return false 2) Return true Below is the implementation of the simple approach. C++ Java Python3 C# PHP Javascript // A simple C++ program to check Bleak Number#include <bits/stdc++.h>using namespace std; /* Function to get no of set bits in binary representation of passed binary no. */int countSetBits(int x){ unsigned int count = 0; while (x) { x &= (x - 1); count++; } return count;} // Returns true if n is Bleakbool isBleak(int n){ // Check for all numbers 'x' smaller // than n. If x + countSetBits(x) // becomes n, then n can't be Bleak for (int x = 1; x < n; x++) if (x + countSetBits(x) == n) return false; return true;} // Driver codeint main(){ isBleak(3) ? cout << "Yes\n" : cout << "No\n"; isBleak(4) ? cout << "Yes\n" : cout << "No\n"; return 0;} // A simple Java program to check Bleak Numberimport java.io.*; class GFG { /* Function to get no of set bits in binary representation of passed binary no. */ static int countSetBits(int x) { int count = 0; while (x != 0) { x &= (x - 1); count++; } return count; } // Returns true if n is Bleak static boolean isBleak(int n) { // Check for all numbers 'x' smaller // than n. If x + countSetBits(x) // becomes n, then n can't be Bleak for (int x = 1; x < n; x++) if (x + countSetBits(x) == n) return false; return true; } // Driver code public static void main(String args[]) { if (isBleak(3)) System.out.println("Yes"); else System.out.println("No"); if (isBleak(4)) System.out.println("Yes"); else System.out.println("No"); }} /*This code is contributed by Nikita Tiwari.*/ # A simple Python 3 program# to check Bleak Number # Function to get no of set# bits in binary# representation of passed# binary no.def countSetBits(x) : count = 0 while (x) : x = x & (x-1) count = count + 1 return count # Returns true if n# is Bleakdef isBleak(n) : # Check for all numbers 'x' # smaller than n. If x + # countSetBits(x) becomes # n, then n can't be Bleak. for x in range(1, n) : if (x + countSetBits(x) == n) : return False return True # Driver codeif(isBleak(3)) : print( "Yes")else : print("No") if(isBleak(4)) : print("Yes")else : print( "No") # This code is contributed by Nikita Tiwari. // A simple C# program to check// Bleak Numberusing System; class GFG { /* Function to get no of set bits in binary representation of passed binary no. */ static int countSetBits(int x) { int count = 0; while (x != 0) { x &= (x - 1); count++; } return count; } // Returns true if n is Bleak static bool isBleak(int n) { // Check for all numbers // 'x' smaller than n. If // x + countSetBits(x) // becomes n, then n can't // be Bleak for (int x = 1; x < n; x++) if (x + countSetBits(x) == n) return false; return true; } // Driver code public static void Main() { if (isBleak(3)) Console.Write("Yes"); else Console.WriteLine("No"); if (isBleak(4)) Console.Write("Yes"); else Console.Write("No"); }} // This code is contributed by// Nitin mittal <?php// A simple PHP program// to check Bleak Number // Function to get no of// set bits in binary// representation of// passed binary no.function countSetBits( $x){ $count = 0; while ($x) { $x &= ($x - 1); $count++; } return $count;} // Returns true if n is Bleakfunction isBleak( $n){ // Check for all numbers 'x' smaller // than n. If x + countSetBits(x) // becomes n, then n can't be Bleak for($x = 1; $x < $n; $x++) if ($x + countSetBits($x) == $n) return false; return true;} // Driver code if(isBleak(3)) echo "Yes\n" ; else echo "No\n"; if(isBleak(4)) echo "Yes\n" ; else echo "No\n"; // This code is contributed by anuj_67.?> <script> // JavaScript program to check Bleak Number /* Function to get no of set bits in binary representation of passed binary no. */ function countSetBits(x) { let count = 0; while (x != 0) { x &= (x - 1); count++; } return count; } // Returns true if n is Bleak function isBleak(n) { // Check for all numbers 'x' smaller // than n. If x + countSetBits(x) // becomes n, then n can't be Bleak for (let x = 1; x < n; x++) if (x + countSetBits(x) == n) return false; return true; } // Driver Code if (isBleak(3)) document.write("Yes" + "<br/>"); else document.write("No" + "<br/>"); if (isBleak(4)) document.write("Yes" + "<br/>"); else document.write("No" + "<br/>"); </script> Output : No Yes Time complexity of above solution is O(n Log n). Auxiliary Space: O(1)Method 2 (Efficient) The idea is based on the fact that the largest count of set bits in any number smaller than n cannot exceed ceiling of Log2n. So we need to check only numbers from range n – ceilingLog2(n) to n. bool isBleak(n) 1) Consider all numbers n - ceiling(Log2n) to n-1 a) If x + countSetBits(x) == n return false 2) Return true Below is the implementation of the idea. C++ Java Python3 C# PHP Javascript // An efficient C++ program to check Bleak Number#include <bits/stdc++.h>using namespace std; /* Function to get no of set bits in binary representation of passed binary no. */int countSetBits(int x){ unsigned int count = 0; while (x) { x &= (x - 1); count++; } return count;} // A function to return ceiling of log x// in base 2. For example, it returns 3// for 8 and 4 for 9.int ceilLog2(int x){ int count = 0; x--; while (x > 0) { x = x >> 1; count++; } return count;} // Returns true if n is Bleakbool isBleak(int n){ // Check for all numbers 'x' smaller // than n. If x + countSetBits(x) // becomes n, then n can't be Bleak for (int x = n - ceilLog2(n); x < n; x++) if (x + countSetBits(x) == n) return false; return true;} // Driver codeint main(){ isBleak(3) ? cout << "Yes\n" : cout << "No\n"; isBleak(4) ? cout << "Yes\n" : cout << "No\n"; return 0;} // An efficient Java program to// check Bleak Numberimport java.io.*; class GFG { /* Function to get no of set bits in binary representation of passed binary no. */ static int countSetBits(int x) { int count = 0; while (x != 0) { x &= (x - 1); count++; } return count; } // A function to return ceiling of log x // in base 2. For example, it returns 3 // for 8 and 4 for 9. static int ceilLog2(int x) { int count = 0; x--; while (x > 0) { x = x >> 1; count++; } return count; } // Returns true if n is Bleak static boolean isBleak(int n) { // Check for all numbers 'x' smaller // than n. If x + countSetBits(x) // becomes n, then n can't be Bleak for (int x = n - ceilLog2(n); x < n; x++) if (x + countSetBits(x) == n) return false; return true; } // Driver code public static void main(String[] args) { if (isBleak(3)) System.out.println("Yes"); else System.out.println("No"); if (isBleak(4)) System.out.println("Yes"); else System.out.println("No"); }}// This code is contributed by Prerna Saini # An efficient Python 3 program# to check Bleak Numberimport math # Function to get no of set# bits in binary representation# of passed binary no.def countSetBits(x) : count = 0 while (x) : x = x & (x - 1) count = count + 1 return count # A function to return ceiling# of log x in base 2. For# example, it returns 3 for 8# and 4 for 9.def ceilLog2(x) : count = 0 x = x - 1 while (x > 0) : x = x>>1 count = count + 1 return count # Returns true if n is Bleakdef isBleak(n) : # Check for all numbers 'x' # smaller than n. If x + # countSetBits(x) becomes n, # then n can't be Bleak for x in range ((n - ceilLog2(n)), n) : if (x + countSetBits(x) == n) : return False return True # Driver codeif(isBleak(3)) : print("Yes")else : print( "No") if(isBleak(4)) : print("Yes")else : print("No") # This code is contributed by Nikita Tiwari. // An efficient C# program to check// Bleak Numberusing System; class GFG { /* Function to get no of set bits in binary representation of passed binary no. */ static int countSetBits(int x) { int count = 0; while (x != 0) { x &= (x - 1); count++; } return count; } // A function to return ceiling // of log x in base 2. For // example, it returns 3 for 8 // and 4 for 9. static int ceilLog2(int x) { int count = 0; x--; while (x > 0) { x = x >> 1; count++; } return count; } // Returns true if n is Bleak static bool isBleak(int n) { // Check for all numbers // 'x' smaller than n. If // x + countSetBits(x) // becomes n, then n // can't be Bleak for (int x = n - ceilLog2(n); x < n; x++) if (x + countSetBits(x) == n) return false; return true; } // Driver code public static void Main() { if (isBleak(3)) Console.WriteLine("Yes"); else Console.WriteLine("No"); if (isBleak(4)) Console.WriteLine("Yes"); else Console.WriteLine("No"); }} // This code is contributed by anuj_67. <?php// An efficient PHP program// to check Bleak Number /* Function to get no of set bits in binary representation of passed binary no. */function countSetBits( $x){ $count = 0; while ($x) { $x &= ($x - 1); $count++; } return $count;} // A function to return ceiling of log x// in base 2. For example, it returns 3// for 8 and 4 for 9.function ceilLog2( $x){ $count = 0; $x--; while ($x > 0) { $x = $x >> 1; $count++; } return $count;} // Returns true if n is Bleakfunction isBleak( $n){ // Check for all numbers 'x' smaller // than n. If x + countSetBits(x) // becomes n, then n can't be Bleak for ($x = $n - ceilLog2($n); $x < $n; $x++) if ($x + countSetBits($x) == $n) return false; return true;} // Driver code if(isBleak(3)) echo "Yes\n" ; else echo "No\n"; if(isBleak(4)) echo "Yes\n" ; else echo "No\n"; // This code is contributed by anuj_67?> <script> // An efficient JavaScript // program to check Bleak Number /* Function to get no of set bits in binary representation of passed binary no. */ function countSetBits(x) { let count = 0; while (x != 0) { x &= (x - 1); count++; } return count; } // A function to return ceiling // of log x in base 2. For // example, it returns 3 for 8 // and 4 for 9. function ceilLog2(x) { let count = 0; x--; while (x > 0) { x = x >> 1; count++; } return count; } // Returns true if n is Bleak function isBleak(n) { // Check for all numbers // 'x' smaller than n. If // x + countSetBits(x) // becomes n, then n // can't be Bleak for (let x = n - ceilLog2(n); x < n; x++) if (x + countSetBits(x) == n) return false; return true; } if (isBleak(3)) document.write("Yes" + "</br>"); else document.write("No" + "</br>"); if (isBleak(4)) document.write("Yes" + "</br>"); else document.write("No" + "</br>"); </script> Output: No Yes Time Complexity: O(Log n * Log n) Auxiliary Space: O(1)Note: In GCC, we can directly count set bits using __builtin_popcount(). So we can avoid a separate function for counting set bits. CPP Java Python3 C# Javascript // C++ program to demonstrate __builtin_popcount()#include <iostream>using namespace std; int main(){ cout << __builtin_popcount(4) << endl; cout << __builtin_popcount(15); return 0;} // Java program to demonstrate Integer.bitCount()import java.util.*; class GFG{ public static void main(String[] args){ System.out.print(Integer.bitCount(4) +"\n"); System.out.print(Integer.bitCount(15)); }} // This code is contributed by umadevi9616 # Python program to demonstrate Integer.bitCount() def bitsoncount(i): assert 0 <= i < 0x100000000 i = i - ((i >> 1) & 0x55555555) i = (i & 0x33333333) + ((i >> 2) & 0x33333333) return (((i + (i >> 4) & 0xF0F0F0F) * 0x1010101) & 0xffffffff) >> 24 # Driver codeif __name__ == '__main__': x = 4; y = 15; print(bitsoncount(x)); print(bitsoncount(y)); # This code is contributed by umadevi9616 // C# program to demonstrate int.bitCount()using System; public class GFG{public static int bitCount (int n) { n = n - ((n >> 1) & 0x55555555); n = (n & 0x33333333) + ((n >> 2) & 0x33333333); return ((n + (n >> 4) & 0xF0F0F0F) * 0x1010101) >> 24; }public static void Main(String[] args){ Console.WriteLine(bitCount(4)); Console.WriteLine(bitCount(15));}} // This code is contributed by gauravrajput1 <script> // javascript program to demonstrate int.bitCount()function bitCount ( n) { n = n - ((n >> 1) & 0x55555555); n = (n & 0x33333333) + ((n >> 2) & 0x33333333); return ((n + (n >> 4) & 0xF0F0F0F) * 0x1010101) >> 24; } document.write(bitCount(4)+"<br/>"); document.write(bitCount(15)); // This code is contributed by gauravrajput1</script> Output : 1 4 Time Complexity: O(log n) Auxiliary Space: O(1) This article is contributed by Rahuain. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above nitin mittal vt_m chinmoy1997pal rameshtravel07 umadevi9616 subham348 GauravRajput1 SAP Labs SAP-Labs-Question Bit Magic SAP Labs Bit Magic Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Little and Big Endian Mystery Cyclic Redundancy Check and Modulo-2 Division Add two numbers without using arithmetic operators Set, Clear and Toggle a given bit of a number in C Bit Fields in C Josephus problem | Set 1 (A O(n) Solution) Find the element that appears once Bits manipulation (Important tactics) 1's and 2's complement of a Binary Number C++ bitset and its application
[ { "code": null, "e": 26615, "s": 26587, "text": "\n17 Nov, 2021" }, { "code": null, "e": 26812, "s": 26615, "text": "A number ‘n’ is called Bleak if it cannot be represented as sum of a positive number x and set bit count in x, i.e., x + countSetBits(x) is not equal to n for any non-negative number x.Examples : " }, { "code": null, "e": 27035, "s": 26812, "text": "Input : n = 3\nOutput : false\n3 is not Bleak as it can be represented\nas 2 + countSetBits(2).\n\nInput : n = 4\nOutput : true\n4 is t Bleak as it cannot be represented \nas sum of a number x and countSetBits(x)\nfor any number x." }, { "code": null, "e": 27057, "s": 27037, "text": "Method 1 (Simple) " }, { "code": null, "e": 27187, "s": 27057, "text": "bool isBleak(n)\n1) Consider all numbers smaller than n\n a) If x + countSetBits(x) == n\n return false\n\n2) Return true" }, { "code": null, "e": 27241, "s": 27187, "text": "Below is the implementation of the simple approach. " }, { "code": null, "e": 27245, "s": 27241, "text": "C++" }, { "code": null, "e": 27250, "s": 27245, "text": "Java" }, { "code": null, "e": 27258, "s": 27250, "text": "Python3" }, { "code": null, "e": 27261, "s": 27258, "text": "C#" }, { "code": null, "e": 27265, "s": 27261, "text": "PHP" }, { "code": null, "e": 27276, "s": 27265, "text": "Javascript" }, { "code": "// A simple C++ program to check Bleak Number#include <bits/stdc++.h>using namespace std; /* Function to get no of set bits in binary representation of passed binary no. */int countSetBits(int x){ unsigned int count = 0; while (x) { x &= (x - 1); count++; } return count;} // Returns true if n is Bleakbool isBleak(int n){ // Check for all numbers 'x' smaller // than n. If x + countSetBits(x) // becomes n, then n can't be Bleak for (int x = 1; x < n; x++) if (x + countSetBits(x) == n) return false; return true;} // Driver codeint main(){ isBleak(3) ? cout << \"Yes\\n\" : cout << \"No\\n\"; isBleak(4) ? cout << \"Yes\\n\" : cout << \"No\\n\"; return 0;}", "e": 27995, "s": 27276, "text": null }, { "code": "// A simple Java program to check Bleak Numberimport java.io.*; class GFG { /* Function to get no of set bits in binary representation of passed binary no. */ static int countSetBits(int x) { int count = 0; while (x != 0) { x &= (x - 1); count++; } return count; } // Returns true if n is Bleak static boolean isBleak(int n) { // Check for all numbers 'x' smaller // than n. If x + countSetBits(x) // becomes n, then n can't be Bleak for (int x = 1; x < n; x++) if (x + countSetBits(x) == n) return false; return true; } // Driver code public static void main(String args[]) { if (isBleak(3)) System.out.println(\"Yes\"); else System.out.println(\"No\"); if (isBleak(4)) System.out.println(\"Yes\"); else System.out.println(\"No\"); }} /*This code is contributed by Nikita Tiwari.*/", "e": 29000, "s": 27995, "text": null }, { "code": "# A simple Python 3 program# to check Bleak Number # Function to get no of set# bits in binary# representation of passed# binary no.def countSetBits(x) : count = 0 while (x) : x = x & (x-1) count = count + 1 return count # Returns true if n# is Bleakdef isBleak(n) : # Check for all numbers 'x' # smaller than n. If x + # countSetBits(x) becomes # n, then n can't be Bleak. for x in range(1, n) : if (x + countSetBits(x) == n) : return False return True # Driver codeif(isBleak(3)) : print( \"Yes\")else : print(\"No\") if(isBleak(4)) : print(\"Yes\")else : print( \"No\") # This code is contributed by Nikita Tiwari.", "e": 29731, "s": 29000, "text": null }, { "code": "// A simple C# program to check// Bleak Numberusing System; class GFG { /* Function to get no of set bits in binary representation of passed binary no. */ static int countSetBits(int x) { int count = 0; while (x != 0) { x &= (x - 1); count++; } return count; } // Returns true if n is Bleak static bool isBleak(int n) { // Check for all numbers // 'x' smaller than n. If // x + countSetBits(x) // becomes n, then n can't // be Bleak for (int x = 1; x < n; x++) if (x + countSetBits(x) == n) return false; return true; } // Driver code public static void Main() { if (isBleak(3)) Console.Write(\"Yes\"); else Console.WriteLine(\"No\"); if (isBleak(4)) Console.Write(\"Yes\"); else Console.Write(\"No\"); }} // This code is contributed by// Nitin mittal", "e": 30796, "s": 29731, "text": null }, { "code": "<?php// A simple PHP program// to check Bleak Number // Function to get no of// set bits in binary// representation of// passed binary no.function countSetBits( $x){ $count = 0; while ($x) { $x &= ($x - 1); $count++; } return $count;} // Returns true if n is Bleakfunction isBleak( $n){ // Check for all numbers 'x' smaller // than n. If x + countSetBits(x) // becomes n, then n can't be Bleak for($x = 1; $x < $n; $x++) if ($x + countSetBits($x) == $n) return false; return true;} // Driver code if(isBleak(3)) echo \"Yes\\n\" ; else echo \"No\\n\"; if(isBleak(4)) echo \"Yes\\n\" ; else echo \"No\\n\"; // This code is contributed by anuj_67.?>", "e": 31560, "s": 30796, "text": null }, { "code": "<script> // JavaScript program to check Bleak Number /* Function to get no of set bits in binary representation of passed binary no. */ function countSetBits(x) { let count = 0; while (x != 0) { x &= (x - 1); count++; } return count; } // Returns true if n is Bleak function isBleak(n) { // Check for all numbers 'x' smaller // than n. If x + countSetBits(x) // becomes n, then n can't be Bleak for (let x = 1; x < n; x++) if (x + countSetBits(x) == n) return false; return true; } // Driver Code if (isBleak(3)) document.write(\"Yes\" + \"<br/>\"); else document.write(\"No\" + \"<br/>\"); if (isBleak(4)) document.write(\"Yes\" + \"<br/>\"); else document.write(\"No\" + \"<br/>\"); </script>", "e": 32464, "s": 31560, "text": null }, { "code": null, "e": 32474, "s": 32464, "text": "Output : " }, { "code": null, "e": 32481, "s": 32474, "text": "No\nYes" }, { "code": null, "e": 32531, "s": 32481, "text": "Time complexity of above solution is O(n Log n). " }, { "code": null, "e": 32769, "s": 32531, "text": "Auxiliary Space: O(1)Method 2 (Efficient) The idea is based on the fact that the largest count of set bits in any number smaller than n cannot exceed ceiling of Log2n. So we need to check only numbers from range n – ceilingLog2(n) to n. " }, { "code": null, "e": 32910, "s": 32769, "text": "bool isBleak(n)\n1) Consider all numbers n - ceiling(Log2n) to n-1\n a) If x + countSetBits(x) == n\n return false\n\n2) Return true" }, { "code": null, "e": 32953, "s": 32910, "text": "Below is the implementation of the idea. " }, { "code": null, "e": 32957, "s": 32953, "text": "C++" }, { "code": null, "e": 32962, "s": 32957, "text": "Java" }, { "code": null, "e": 32970, "s": 32962, "text": "Python3" }, { "code": null, "e": 32973, "s": 32970, "text": "C#" }, { "code": null, "e": 32977, "s": 32973, "text": "PHP" }, { "code": null, "e": 32988, "s": 32977, "text": "Javascript" }, { "code": "// An efficient C++ program to check Bleak Number#include <bits/stdc++.h>using namespace std; /* Function to get no of set bits in binary representation of passed binary no. */int countSetBits(int x){ unsigned int count = 0; while (x) { x &= (x - 1); count++; } return count;} // A function to return ceiling of log x// in base 2. For example, it returns 3// for 8 and 4 for 9.int ceilLog2(int x){ int count = 0; x--; while (x > 0) { x = x >> 1; count++; } return count;} // Returns true if n is Bleakbool isBleak(int n){ // Check for all numbers 'x' smaller // than n. If x + countSetBits(x) // becomes n, then n can't be Bleak for (int x = n - ceilLog2(n); x < n; x++) if (x + countSetBits(x) == n) return false; return true;} // Driver codeint main(){ isBleak(3) ? cout << \"Yes\\n\" : cout << \"No\\n\"; isBleak(4) ? cout << \"Yes\\n\" : cout << \"No\\n\"; return 0;}", "e": 33949, "s": 32988, "text": null }, { "code": "// An efficient Java program to// check Bleak Numberimport java.io.*; class GFG { /* Function to get no of set bits in binary representation of passed binary no. */ static int countSetBits(int x) { int count = 0; while (x != 0) { x &= (x - 1); count++; } return count; } // A function to return ceiling of log x // in base 2. For example, it returns 3 // for 8 and 4 for 9. static int ceilLog2(int x) { int count = 0; x--; while (x > 0) { x = x >> 1; count++; } return count; } // Returns true if n is Bleak static boolean isBleak(int n) { // Check for all numbers 'x' smaller // than n. If x + countSetBits(x) // becomes n, then n can't be Bleak for (int x = n - ceilLog2(n); x < n; x++) if (x + countSetBits(x) == n) return false; return true; } // Driver code public static void main(String[] args) { if (isBleak(3)) System.out.println(\"Yes\"); else System.out.println(\"No\"); if (isBleak(4)) System.out.println(\"Yes\"); else System.out.println(\"No\"); }}// This code is contributed by Prerna Saini", "e": 35253, "s": 33949, "text": null }, { "code": "# An efficient Python 3 program# to check Bleak Numberimport math # Function to get no of set# bits in binary representation# of passed binary no.def countSetBits(x) : count = 0 while (x) : x = x & (x - 1) count = count + 1 return count # A function to return ceiling# of log x in base 2. For# example, it returns 3 for 8# and 4 for 9.def ceilLog2(x) : count = 0 x = x - 1 while (x > 0) : x = x>>1 count = count + 1 return count # Returns true if n is Bleakdef isBleak(n) : # Check for all numbers 'x' # smaller than n. If x + # countSetBits(x) becomes n, # then n can't be Bleak for x in range ((n - ceilLog2(n)), n) : if (x + countSetBits(x) == n) : return False return True # Driver codeif(isBleak(3)) : print(\"Yes\")else : print( \"No\") if(isBleak(4)) : print(\"Yes\")else : print(\"No\") # This code is contributed by Nikita Tiwari.", "e": 36243, "s": 35253, "text": null }, { "code": "// An efficient C# program to check// Bleak Numberusing System; class GFG { /* Function to get no of set bits in binary representation of passed binary no. */ static int countSetBits(int x) { int count = 0; while (x != 0) { x &= (x - 1); count++; } return count; } // A function to return ceiling // of log x in base 2. For // example, it returns 3 for 8 // and 4 for 9. static int ceilLog2(int x) { int count = 0; x--; while (x > 0) { x = x >> 1; count++; } return count; } // Returns true if n is Bleak static bool isBleak(int n) { // Check for all numbers // 'x' smaller than n. If // x + countSetBits(x) // becomes n, then n // can't be Bleak for (int x = n - ceilLog2(n); x < n; x++) if (x + countSetBits(x) == n) return false; return true; } // Driver code public static void Main() { if (isBleak(3)) Console.WriteLine(\"Yes\"); else Console.WriteLine(\"No\"); if (isBleak(4)) Console.WriteLine(\"Yes\"); else Console.WriteLine(\"No\"); }} // This code is contributed by anuj_67.", "e": 37608, "s": 36243, "text": null }, { "code": "<?php// An efficient PHP program// to check Bleak Number /* Function to get no of set bits in binary representation of passed binary no. */function countSetBits( $x){ $count = 0; while ($x) { $x &= ($x - 1); $count++; } return $count;} // A function to return ceiling of log x// in base 2. For example, it returns 3// for 8 and 4 for 9.function ceilLog2( $x){ $count = 0; $x--; while ($x > 0) { $x = $x >> 1; $count++; } return $count;} // Returns true if n is Bleakfunction isBleak( $n){ // Check for all numbers 'x' smaller // than n. If x + countSetBits(x) // becomes n, then n can't be Bleak for ($x = $n - ceilLog2($n); $x < $n; $x++) if ($x + countSetBits($x) == $n) return false; return true;} // Driver code if(isBleak(3)) echo \"Yes\\n\" ; else echo \"No\\n\"; if(isBleak(4)) echo \"Yes\\n\" ; else echo \"No\\n\"; // This code is contributed by anuj_67?>", "e": 38637, "s": 37608, "text": null }, { "code": "<script> // An efficient JavaScript // program to check Bleak Number /* Function to get no of set bits in binary representation of passed binary no. */ function countSetBits(x) { let count = 0; while (x != 0) { x &= (x - 1); count++; } return count; } // A function to return ceiling // of log x in base 2. For // example, it returns 3 for 8 // and 4 for 9. function ceilLog2(x) { let count = 0; x--; while (x > 0) { x = x >> 1; count++; } return count; } // Returns true if n is Bleak function isBleak(n) { // Check for all numbers // 'x' smaller than n. If // x + countSetBits(x) // becomes n, then n // can't be Bleak for (let x = n - ceilLog2(n); x < n; x++) if (x + countSetBits(x) == n) return false; return true; } if (isBleak(3)) document.write(\"Yes\" + \"</br>\"); else document.write(\"No\" + \"</br>\"); if (isBleak(4)) document.write(\"Yes\" + \"</br>\"); else document.write(\"No\" + \"</br>\"); </script>", "e": 39843, "s": 38637, "text": null }, { "code": null, "e": 39852, "s": 39843, "text": "Output: " }, { "code": null, "e": 39859, "s": 39852, "text": "No\nYes" }, { "code": null, "e": 39893, "s": 39859, "text": "Time Complexity: O(Log n * Log n)" }, { "code": null, "e": 40047, "s": 39893, "text": "Auxiliary Space: O(1)Note: In GCC, we can directly count set bits using __builtin_popcount(). So we can avoid a separate function for counting set bits. " }, { "code": null, "e": 40051, "s": 40047, "text": "CPP" }, { "code": null, "e": 40056, "s": 40051, "text": "Java" }, { "code": null, "e": 40064, "s": 40056, "text": "Python3" }, { "code": null, "e": 40067, "s": 40064, "text": "C#" }, { "code": null, "e": 40078, "s": 40067, "text": "Javascript" }, { "code": "// C++ program to demonstrate __builtin_popcount()#include <iostream>using namespace std; int main(){ cout << __builtin_popcount(4) << endl; cout << __builtin_popcount(15); return 0;}", "e": 40272, "s": 40078, "text": null }, { "code": "// Java program to demonstrate Integer.bitCount()import java.util.*; class GFG{ public static void main(String[] args){ System.out.print(Integer.bitCount(4) +\"\\n\"); System.out.print(Integer.bitCount(15)); }} // This code is contributed by umadevi9616", "e": 40529, "s": 40272, "text": null }, { "code": "# Python program to demonstrate Integer.bitCount() def bitsoncount(i): assert 0 <= i < 0x100000000 i = i - ((i >> 1) & 0x55555555) i = (i & 0x33333333) + ((i >> 2) & 0x33333333) return (((i + (i >> 4) & 0xF0F0F0F) * 0x1010101) & 0xffffffff) >> 24 # Driver codeif __name__ == '__main__': x = 4; y = 15; print(bitsoncount(x)); print(bitsoncount(y)); # This code is contributed by umadevi9616", "e": 40943, "s": 40529, "text": null }, { "code": "// C# program to demonstrate int.bitCount()using System; public class GFG{public static int bitCount (int n) { n = n - ((n >> 1) & 0x55555555); n = (n & 0x33333333) + ((n >> 2) & 0x33333333); return ((n + (n >> 4) & 0xF0F0F0F) * 0x1010101) >> 24; }public static void Main(String[] args){ Console.WriteLine(bitCount(4)); Console.WriteLine(bitCount(15));}} // This code is contributed by gauravrajput1", "e": 41367, "s": 40943, "text": null }, { "code": "<script> // javascript program to demonstrate int.bitCount()function bitCount ( n) { n = n - ((n >> 1) & 0x55555555); n = (n & 0x33333333) + ((n >> 2) & 0x33333333); return ((n + (n >> 4) & 0xF0F0F0F) * 0x1010101) >> 24; } document.write(bitCount(4)+\"<br/>\"); document.write(bitCount(15)); // This code is contributed by gauravrajput1</script>", "e": 41741, "s": 41367, "text": null }, { "code": null, "e": 41751, "s": 41741, "text": "Output : " }, { "code": null, "e": 41755, "s": 41751, "text": "1\n4" }, { "code": null, "e": 41781, "s": 41755, "text": "Time Complexity: O(log n)" }, { "code": null, "e": 41803, "s": 41781, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 41968, "s": 41803, "text": "This article is contributed by Rahuain. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 41981, "s": 41968, "text": "nitin mittal" }, { "code": null, "e": 41986, "s": 41981, "text": "vt_m" }, { "code": null, "e": 42001, "s": 41986, "text": "chinmoy1997pal" }, { "code": null, "e": 42016, "s": 42001, "text": "rameshtravel07" }, { "code": null, "e": 42028, "s": 42016, "text": "umadevi9616" }, { "code": null, "e": 42038, "s": 42028, "text": "subham348" }, { "code": null, "e": 42052, "s": 42038, "text": "GauravRajput1" }, { "code": null, "e": 42061, "s": 42052, "text": "SAP Labs" }, { "code": null, "e": 42079, "s": 42061, "text": "SAP-Labs-Question" }, { "code": null, "e": 42089, "s": 42079, "text": "Bit Magic" }, { "code": null, "e": 42098, "s": 42089, "text": "SAP Labs" }, { "code": null, "e": 42108, "s": 42098, "text": "Bit Magic" }, { "code": null, "e": 42206, "s": 42108, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 42236, "s": 42206, "text": "Little and Big Endian Mystery" }, { "code": null, "e": 42282, "s": 42236, "text": "Cyclic Redundancy Check and Modulo-2 Division" }, { "code": null, "e": 42333, "s": 42282, "text": "Add two numbers without using arithmetic operators" }, { "code": null, "e": 42384, "s": 42333, "text": "Set, Clear and Toggle a given bit of a number in C" }, { "code": null, "e": 42400, "s": 42384, "text": "Bit Fields in C" }, { "code": null, "e": 42443, "s": 42400, "text": "Josephus problem | Set 1 (A O(n) Solution)" }, { "code": null, "e": 42478, "s": 42443, "text": "Find the element that appears once" }, { "code": null, "e": 42516, "s": 42478, "text": "Bits manipulation (Important tactics)" }, { "code": null, "e": 42558, "s": 42516, "text": "1's and 2's complement of a Binary Number" } ]
How to create a triangle using Python for loop?
There are multiple variations of generating triangle using numbers in Python. Let's look at the 2 simplest forms: for i in range(5): for j in range(i + 1): print(j + 1, end="") print("") This will give the output: 1 12 123 1234 12345 You can also print numbers continuously using: start = 1 for i in range(5): for j in range(i + 1): print(start, end=" ") start += 1 print("") This will give the output: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 You can also print these numbers in reverse using: start = 15 for i in range(5): for j in range(i + 1): print(start, end=" ") start -= 1 print("") This will give the output: 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
[ { "code": null, "e": 1176, "s": 1062, "text": "There are multiple variations of generating triangle using numbers in Python. Let's look at the 2 simplest forms:" }, { "code": null, "e": 1261, "s": 1176, "text": "for i in range(5):\n for j in range(i + 1):\n print(j + 1, end=\"\")\n print(\"\")" }, { "code": null, "e": 1288, "s": 1261, "text": "This will give the output:" }, { "code": null, "e": 1308, "s": 1288, "text": "1\n12\n123\n1234\n12345" }, { "code": null, "e": 1355, "s": 1308, "text": "You can also print numbers continuously using:" }, { "code": null, "e": 1468, "s": 1355, "text": "start = 1\nfor i in range(5):\n for j in range(i + 1):\n print(start, end=\" \")\n start += 1\n print(\"\")" }, { "code": null, "e": 1495, "s": 1468, "text": "This will give the output:" }, { "code": null, "e": 1531, "s": 1495, "text": "1\n2 3\n4 5 6\n7 8 9 10\n11 12 13 14 15" }, { "code": null, "e": 1582, "s": 1531, "text": "You can also print these numbers in reverse using:" }, { "code": null, "e": 1696, "s": 1582, "text": "start = 15\nfor i in range(5):\n for j in range(i + 1):\n print(start, end=\" \")\n start -= 1\n print(\"\")" }, { "code": null, "e": 1723, "s": 1696, "text": "This will give the output:" }, { "code": null, "e": 1759, "s": 1723, "text": "15\n14 13\n12 11 10\n9 8 7 6\n5 4 3 2 1" } ]
Circumradius of the rectangle - GeeksforGeeks
08 Mar, 2022 Here we have a rectangle of length l & breadth b. We have to find the circumradius of the rectangle. Examples: Input : l = 3, b = 4 Output :2.5 Input :l = 10, b = 12 Output :3.95227774224 Approach: From the diagram, we can clearly understand the circumradius r is half of the diagonal of the rectangle. r = √(l^2 + b^2)/2 Below is the implementation of the above approach: C++ C Java Python3 C# PHP Javascript // C++ Program to find the radius// of the circumcircle of the given rectangle #include <bits/stdc++.h>using namespace std; // Function to find the radius// of the circumcirclefloat findRadiusOfcircumcircle(float l, float b){ // the sides cannot be negative if (l < 0 || b < 0) return -1; // Radius of the circumcircle float radius = sqrt(pow(l, 2) + pow(b, 2)) / 2; // Return the radius return radius;} // Driver codeint main(){ // Get the sides of the triangle float l = 4, b = 3; // Find the radius of the circumcircle cout << findRadiusOfcircumcircle(l, b) << endl; return 0;} // C Program to find the radius// of the circumcircle of the given rectangle#include <stdio.h>#include <math.h> // Function to find the radius// of the circumcirclefloat findRadiusOfcircumcircle(float l, float b){ // the sides cannot be negative if (l < 0 || b < 0) return -1; // Radius of the circumcircle float radius = sqrt(pow(l, 2) + pow(b, 2)) / 2; // Return the radius return radius;} // Driver codeint main(){ // Get the sides of the triangle float l = 4, b = 3; // Find the radius of the circumcircle printf("%f\n",findRadiusOfcircumcircle(l, b)); return 0;} // Java Program to find the radius// of the circumcircle of the given// rectangleimport java.util.*;import java.lang.*;import java.io.*; class GFG{ // Function to find the radius// of the circumcirclestatic float findRadiusOfcircumcircle(float l, float b){ // the sides cannot be negative if (l < 0 || b < 0) return -1; // Radius of the circumcircle float radius = (float) Math.sqrt(Math.pow(l, 2) + Math.pow(b, 2)) / 2; // Return the radius return radius;} // Driver codepublic static void main(String args[]){ // Get the sides of the triangle float l = 4, b = 3; // Find the radius of the circumcircle System.out.println(findRadiusOfcircumcircle(l, b));}} // This code is contributed by Subhadeep # Python Program to find the# radius of the circumcircle# of the given rectangleimport math # Function to find the radius# of the circumcircledef findRadiusOfcircumcircle(l, b): # the sides cannot be negative if (l < 0 or b < 0): return -1; # Radius of the circumcircle radius = (math.sqrt(pow(l, 2) + pow(b, 2)) / 2); # Return the radius return radius; # Driver code # Get the sides of the trianglel = 4;b = 3; # Find the radius of the circumcircleprint(findRadiusOfcircumcircle(l, b)); # This code is contributed# by Shivi_Aggarwal // C# Program to find the radius// of the circumcircle of the// given rectangleusing System; class GFG{ // Function to find the radius// of the circumcirclestatic float findRadiusOfcircumcircle(float l, float b){ // the sides cannot be negative if (l < 0 || b < 0) return -1; // Radius of the circumcircle float radius = (float) Math.Sqrt(Math.Pow(l, 2) + Math.Pow(b, 2)) / 2; // Return the radius return radius;} // Driver codepublic static void Main(){ // Get the sides of the triangle float l = 4, b = 3; // Find the radius of the circumcircle Console.WriteLine(findRadiusOfcircumcircle(l, b));}} // This code is contributed by anuj_67 <?php// PHP Program to find the radius// of the circumcircle of the// given rectangle // Function to find the radius// of the circumcirclefunction findRadiusOfcircumcircle($l, $b){ // the sides cannot be negative if ($l < 0 || $b < 0) return -1; // Radius of the circumcircle $radius = sqrt(pow($l, 2) + pow($b, 2)) / 2; // Return the radius return $radius;} // Driver code // Get the sides of the triangle$l = 4; $b = 3; // Find the radius of the circumcircleecho findRadiusOfcircumcircle($l, $b); // This code is contributed by anuj_67?> <script> // javascript Program to find the radius// of the circumcircle of the given// rectangle // Function to find the radius// of the circumcirclefunction findRadiusOfcircumcircle(l,b){ // the sides cannot be negative if (l < 0 || b < 0) return -1; // Radius of the circumcircle var radius = Math.sqrt(Math.pow(l, 2) + Math.pow(b, 2)) / 2; // Return the radius return radius;} // Driver code // Get the sides of the trianglevar l = 4, b = 3;// Find the radius of the circumcircledocument.write(findRadiusOfcircumcircle(l, b).toFixed(6)); // This code contributed by shikhasingrajput </script> Output: 2.5 tufan_gupta2000 vt_m Shivi_Aggarwal Akanksha_Rai shikhasingrajput sooda367 kothavvsaakash circle square-rectangle Geometric School Programming Geometric Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Convex Hull using Divide and Conquer Algorithm Equation of circle when three points on the circle are given Circle and Lattice Points Orientation of 3 ordered points Program to find slope of a line Python Dictionary Arrays in C/C++ Inheritance in C++ Reverse a string in Java Interfaces in Java
[ { "code": null, "e": 25276, "s": 25248, "text": "\n08 Mar, 2022" }, { "code": null, "e": 25377, "s": 25276, "text": "Here we have a rectangle of length l & breadth b. We have to find the circumradius of the rectangle." }, { "code": null, "e": 25388, "s": 25377, "text": "Examples: " }, { "code": null, "e": 25467, "s": 25388, "text": "Input : l = 3, b = 4 \nOutput :2.5\n\nInput :l = 10, b = 12\nOutput :3.95227774224" }, { "code": null, "e": 25583, "s": 25467, "text": "Approach: From the diagram, we can clearly understand the circumradius r is half of the diagonal of the rectangle. " }, { "code": null, "e": 25602, "s": 25583, "text": "r = √(l^2 + b^2)/2" }, { "code": null, "e": 25654, "s": 25602, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 25658, "s": 25654, "text": "C++" }, { "code": null, "e": 25660, "s": 25658, "text": "C" }, { "code": null, "e": 25665, "s": 25660, "text": "Java" }, { "code": null, "e": 25673, "s": 25665, "text": "Python3" }, { "code": null, "e": 25676, "s": 25673, "text": "C#" }, { "code": null, "e": 25680, "s": 25676, "text": "PHP" }, { "code": null, "e": 25691, "s": 25680, "text": "Javascript" }, { "code": "// C++ Program to find the radius// of the circumcircle of the given rectangle #include <bits/stdc++.h>using namespace std; // Function to find the radius// of the circumcirclefloat findRadiusOfcircumcircle(float l, float b){ // the sides cannot be negative if (l < 0 || b < 0) return -1; // Radius of the circumcircle float radius = sqrt(pow(l, 2) + pow(b, 2)) / 2; // Return the radius return radius;} // Driver codeint main(){ // Get the sides of the triangle float l = 4, b = 3; // Find the radius of the circumcircle cout << findRadiusOfcircumcircle(l, b) << endl; return 0;}", "e": 26317, "s": 25691, "text": null }, { "code": "// C Program to find the radius// of the circumcircle of the given rectangle#include <stdio.h>#include <math.h> // Function to find the radius// of the circumcirclefloat findRadiusOfcircumcircle(float l, float b){ // the sides cannot be negative if (l < 0 || b < 0) return -1; // Radius of the circumcircle float radius = sqrt(pow(l, 2) + pow(b, 2)) / 2; // Return the radius return radius;} // Driver codeint main(){ // Get the sides of the triangle float l = 4, b = 3; // Find the radius of the circumcircle printf(\"%f\\n\",findRadiusOfcircumcircle(l, b)); return 0;}", "e": 26940, "s": 26317, "text": null }, { "code": "// Java Program to find the radius// of the circumcircle of the given// rectangleimport java.util.*;import java.lang.*;import java.io.*; class GFG{ // Function to find the radius// of the circumcirclestatic float findRadiusOfcircumcircle(float l, float b){ // the sides cannot be negative if (l < 0 || b < 0) return -1; // Radius of the circumcircle float radius = (float) Math.sqrt(Math.pow(l, 2) + Math.pow(b, 2)) / 2; // Return the radius return radius;} // Driver codepublic static void main(String args[]){ // Get the sides of the triangle float l = 4, b = 3; // Find the radius of the circumcircle System.out.println(findRadiusOfcircumcircle(l, b));}} // This code is contributed by Subhadeep", "e": 27743, "s": 26940, "text": null }, { "code": "# Python Program to find the# radius of the circumcircle# of the given rectangleimport math # Function to find the radius# of the circumcircledef findRadiusOfcircumcircle(l, b): # the sides cannot be negative if (l < 0 or b < 0): return -1; # Radius of the circumcircle radius = (math.sqrt(pow(l, 2) + pow(b, 2)) / 2); # Return the radius return radius; # Driver code # Get the sides of the trianglel = 4;b = 3; # Find the radius of the circumcircleprint(findRadiusOfcircumcircle(l, b)); # This code is contributed# by Shivi_Aggarwal", "e": 28332, "s": 27743, "text": null }, { "code": "// C# Program to find the radius// of the circumcircle of the// given rectangleusing System; class GFG{ // Function to find the radius// of the circumcirclestatic float findRadiusOfcircumcircle(float l, float b){ // the sides cannot be negative if (l < 0 || b < 0) return -1; // Radius of the circumcircle float radius = (float) Math.Sqrt(Math.Pow(l, 2) + Math.Pow(b, 2)) / 2; // Return the radius return radius;} // Driver codepublic static void Main(){ // Get the sides of the triangle float l = 4, b = 3; // Find the radius of the circumcircle Console.WriteLine(findRadiusOfcircumcircle(l, b));}} // This code is contributed by anuj_67", "e": 29081, "s": 28332, "text": null }, { "code": "<?php// PHP Program to find the radius// of the circumcircle of the// given rectangle // Function to find the radius// of the circumcirclefunction findRadiusOfcircumcircle($l, $b){ // the sides cannot be negative if ($l < 0 || $b < 0) return -1; // Radius of the circumcircle $radius = sqrt(pow($l, 2) + pow($b, 2)) / 2; // Return the radius return $radius;} // Driver code // Get the sides of the triangle$l = 4; $b = 3; // Find the radius of the circumcircleecho findRadiusOfcircumcircle($l, $b); // This code is contributed by anuj_67?>", "e": 29667, "s": 29081, "text": null }, { "code": "<script> // javascript Program to find the radius// of the circumcircle of the given// rectangle // Function to find the radius// of the circumcirclefunction findRadiusOfcircumcircle(l,b){ // the sides cannot be negative if (l < 0 || b < 0) return -1; // Radius of the circumcircle var radius = Math.sqrt(Math.pow(l, 2) + Math.pow(b, 2)) / 2; // Return the radius return radius;} // Driver code // Get the sides of the trianglevar l = 4, b = 3;// Find the radius of the circumcircledocument.write(findRadiusOfcircumcircle(l, b).toFixed(6)); // This code contributed by shikhasingrajput </script>", "e": 30318, "s": 29667, "text": null }, { "code": null, "e": 30327, "s": 30318, "text": "Output: " }, { "code": null, "e": 30331, "s": 30327, "text": "2.5" }, { "code": null, "e": 30349, "s": 30333, "text": "tufan_gupta2000" }, { "code": null, "e": 30354, "s": 30349, "text": "vt_m" }, { "code": null, "e": 30369, "s": 30354, "text": "Shivi_Aggarwal" }, { "code": null, "e": 30382, "s": 30369, "text": "Akanksha_Rai" }, { "code": null, "e": 30399, "s": 30382, "text": "shikhasingrajput" }, { "code": null, "e": 30408, "s": 30399, "text": "sooda367" }, { "code": null, "e": 30423, "s": 30408, "text": "kothavvsaakash" }, { "code": null, "e": 30430, "s": 30423, "text": "circle" }, { "code": null, "e": 30447, "s": 30430, "text": "square-rectangle" }, { "code": null, "e": 30457, "s": 30447, "text": "Geometric" }, { "code": null, "e": 30476, "s": 30457, "text": "School Programming" }, { "code": null, "e": 30486, "s": 30476, "text": "Geometric" }, { "code": null, "e": 30584, "s": 30486, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30593, "s": 30584, "text": "Comments" }, { "code": null, "e": 30606, "s": 30593, "text": "Old Comments" }, { "code": null, "e": 30653, "s": 30606, "text": "Convex Hull using Divide and Conquer Algorithm" }, { "code": null, "e": 30714, "s": 30653, "text": "Equation of circle when three points on the circle are given" }, { "code": null, "e": 30740, "s": 30714, "text": "Circle and Lattice Points" }, { "code": null, "e": 30772, "s": 30740, "text": "Orientation of 3 ordered points" }, { "code": null, "e": 30804, "s": 30772, "text": "Program to find slope of a line" }, { "code": null, "e": 30822, "s": 30804, "text": "Python Dictionary" }, { "code": null, "e": 30838, "s": 30822, "text": "Arrays in C/C++" }, { "code": null, "e": 30857, "s": 30838, "text": "Inheritance in C++" }, { "code": null, "e": 30882, "s": 30857, "text": "Reverse a string in Java" } ]
How do you check if a widget has a focus in Tkinter?
Let us assume that we want to check if a particular widget has a focused set or not. The only way to check the widget focus is to use the utility method focus_get(). It returns the object containing the widget’s information which is currently focused on, during the program’s execution. We will use the focus_get() method to find the active widget during our program’s execution. In this example, we have created an Entry widget that will get its focus when we press the <Enter> key. The focus_get() method will return the current widget’s information which is active. #Import the Tkinter library from tkinter import * #Create an instance of Tkinter frame win= Tk() #Define the geometry win.geometry("750x250") #Define Event handlers for different Operations def event_show(event): label.config(text="Hello World") e.focus_set() print("focus is:" ,e.focus_get) #Create a Label label= Label(win, text="Press Enter",font=('Helvetica 15 underline')) label.pack() #Create an entry widget e= Entry(win, width= 25) e.pack(pady=20) #Bind the function win.bind('<Return>',lambda event:event_show(event)) win.mainloop() Running the above code will display a window that contains a button. When we press the <Enter> key, it will print the output containing the widget’s information which is currently focused on the window pane. Now, when we press <Enter>, it will show the output in the shell as, focus is : <bound method Misc.focus_get of <tkinter.Entry object .!entry >>
[ { "code": null, "e": 1442, "s": 1062, "text": "Let us assume that we want to check if a particular widget has a focused set or not. The only way to check the widget focus is to use the utility method focus_get(). It returns the object containing the widget’s information which is currently focused on, during the program’s execution. We will use the focus_get() method to find the active widget during our program’s execution." }, { "code": null, "e": 1631, "s": 1442, "text": "In this example, we have created an Entry widget that will get its focus when we press the <Enter> key. The focus_get() method will return the current widget’s information which is active." }, { "code": null, "e": 2182, "s": 1631, "text": "#Import the Tkinter library\nfrom tkinter import *\n#Create an instance of Tkinter frame\nwin= Tk()\n#Define the geometry\nwin.geometry(\"750x250\")\n#Define Event handlers for different Operations\ndef event_show(event):\n label.config(text=\"Hello World\")\n e.focus_set()\n print(\"focus is:\" ,e.focus_get)\n#Create a Label\nlabel= Label(win, text=\"Press Enter\",font=('Helvetica 15 underline'))\nlabel.pack()\n#Create an entry widget\ne= Entry(win, width= 25)\ne.pack(pady=20)\n#Bind the function\nwin.bind('<Return>',lambda event:event_show(event))\nwin.mainloop()" }, { "code": null, "e": 2390, "s": 2182, "text": "Running the above code will display a window that contains a button. When we press the <Enter> key, it will print the output containing the widget’s information which is currently focused on the window pane." }, { "code": null, "e": 2459, "s": 2390, "text": "Now, when we press <Enter>, it will show the output in the shell as," }, { "code": null, "e": 2535, "s": 2459, "text": "focus is : <bound method Misc.focus_get of <tkinter.Entry object .!entry >>" } ]
Cucumber - Scenarios
Scenario is one of the core Gherkin structures. Every scenario starts with the keyword “Scenario:” (or localized one) and is followed by an optional scenario title. Each feature can have one or more scenarios and every scenario consists of one or more steps. A very simple example of scenario can be − Scenario − Verify Help Functionality. Given user navigates to Facebook. When the user clicks on Help, then the Help page opens. Consider a case, where we need to execute a test scenario more than once. Suppose, we need to make sure that the login functionality is working for all types of subscription holders. That requires execution of login functionality scenario multiple times. Copy paste the same steps in order to just re-execute the code, does not seem to be a smart idea. For this, Gherkin provides one more structure, which is scenario outline. Scenario outline is similar to scenario structure; the only difference is the provision of multiple inputs. As you can see in the following example, the test case remains the same and non-repeatable. At the bottom we have provided multiple input values for the variables “Username” and “Password”. While running the actual test, Cucumber will replace the variable with input values provided and it will execute the test. Once pass-1 has been executed, the test will rerun for second iteration with another input value. Such variable or placeholders can be represented with ”<>” while mentioning with gherkin statements. Scenario Outline − Login functionality for a social networking site. The given user navigates to Facebook. When the user logs in using the Username as "<username>" and the Password as "<password>", then login should be successful. | username | password | | user1 | password1 | | user2 | password2 | There are a few tips and tricks to smartly define the Cucumber scenarios. Each step should be clearly defined, so that it does not create any confusion for the reader. Each step should be clearly defined, so that it does not create any confusion for the reader. Do not repeat the test scenario, if needed use scenario outline to implement repetition. Do not repeat the test scenario, if needed use scenario outline to implement repetition. Develop a test step in a way that, it can be used within multiple scenarios and scenario outlines. Develop a test step in a way that, it can be used within multiple scenarios and scenario outlines. As far as possible, keep each step completely independent. For example: “Given the user is logged in”. This can be divided into two steps Given the user enters the user name. Clicks on login. As far as possible, keep each step completely independent. For example: “Given the user is logged in”. This can be divided into two steps Given the user enters the user name. Clicks on login. Print Add Notes Bookmark this page
[ { "code": null, "e": 2264, "s": 1962, "text": "Scenario is one of the core Gherkin structures. Every scenario starts with the keyword “Scenario:” (or localized one) and is followed by an optional scenario title. Each feature can have one or more scenarios and every scenario consists of one or more steps. A very simple example of scenario can be −" }, { "code": null, "e": 2302, "s": 2264, "text": "Scenario − Verify Help Functionality." }, { "code": null, "e": 2336, "s": 2302, "text": "Given user navigates to Facebook." }, { "code": null, "e": 2392, "s": 2336, "text": "When the user clicks on Help, then the Help page opens." }, { "code": null, "e": 2819, "s": 2392, "text": "Consider a case, where we need to execute a test scenario more than once. Suppose, we need to make sure that the login functionality is working for all types of subscription holders. That requires execution of login functionality scenario multiple times. Copy paste the same steps in order to just re-execute the code, does not seem to be a smart idea. For this, Gherkin provides one more structure, which is scenario outline." }, { "code": null, "e": 3439, "s": 2819, "text": "Scenario outline is similar to scenario structure; the only difference is the provision of multiple inputs. As you can see in the following example, the test case remains the same and non-repeatable. At the bottom we have provided multiple input values for the variables “Username” and “Password”. While running the actual test, Cucumber will replace the variable with input values provided and it will execute the test. Once pass-1 has been executed, the test will rerun for second iteration with another input value. Such variable or placeholders can be represented with ”<>” while mentioning with gherkin statements." }, { "code": null, "e": 3546, "s": 3439, "text": "Scenario Outline − Login functionality for a social networking site. The given user navigates to Facebook." }, { "code": null, "e": 3670, "s": 3546, "text": "When the user logs in using the Username as \"<username>\" and the Password as \"<password>\", then login should be successful." }, { "code": null, "e": 3748, "s": 3670, "text": "| username | password | \n| user1 | password1 | \n| user2 | password2 |\n" }, { "code": null, "e": 3822, "s": 3748, "text": "There are a few tips and tricks to smartly define the Cucumber scenarios." }, { "code": null, "e": 3916, "s": 3822, "text": "Each step should be clearly defined, so that it does not create any confusion for the reader." }, { "code": null, "e": 4010, "s": 3916, "text": "Each step should be clearly defined, so that it does not create any confusion for the reader." }, { "code": null, "e": 4099, "s": 4010, "text": "Do not repeat the test scenario, if needed use scenario outline to implement repetition." }, { "code": null, "e": 4188, "s": 4099, "text": "Do not repeat the test scenario, if needed use scenario outline to implement repetition." }, { "code": null, "e": 4287, "s": 4188, "text": "Develop a test step in a way that, it can be used within multiple scenarios and scenario outlines." }, { "code": null, "e": 4386, "s": 4287, "text": "Develop a test step in a way that, it can be used within multiple scenarios and scenario outlines." }, { "code": null, "e": 4580, "s": 4386, "text": "As far as possible, keep each step completely independent. For example: “Given the user is logged in”. This can be divided into two steps\n\nGiven the user enters the user name.\nClicks on login.\n" }, { "code": null, "e": 4718, "s": 4580, "text": "As far as possible, keep each step completely independent. For example: “Given the user is logged in”. This can be divided into two steps" }, { "code": null, "e": 4755, "s": 4718, "text": "Given the user enters the user name." }, { "code": null, "e": 4772, "s": 4755, "text": "Clicks on login." }, { "code": null, "e": 4779, "s": 4772, "text": " Print" }, { "code": null, "e": 4790, "s": 4779, "text": " Add Notes" } ]
Minimum number of jumps | Practice | GeeksforGeeks
Given an array of N integers arr[] where each element represents the max number of steps that can be made forward from that element. Find the minimum number of jumps to reach the end of the array (starting from the first element). If an element is 0, then you cannot move through that element. Note: Return -1 if you can't reach the end of the array. Example 1: Input: N = 11 arr[] = {1, 3, 5, 8, 9, 2, 6, 7, 6, 8, 9} Output: 3 Explanation: First jump from 1st element to 2nd element with value 3. Now, from here we jump to 5th element with value 9, and from here we will jump to last. Example 2: Input : N = 6 arr = {1, 4, 3, 2, 6, 7} Output: 2 Explanation: First we jump from the 1st to 2nd element and then jump to the last element. Your task: You don't need to read input or print anything. Your task is to complete function minJumps() which takes the array arr and it's size N as input parameters and returns the minimum number of jumps. If not possible returns -1. Expected Time Complexity: O(N) Expected Space Complexity: O(1) Constraints: 1 ≤ N ≤ 107 0 ≤ arri ≤ 107 0 shettyrohan183 This comment was deleted. 0 venkatesh17nayak14 hours ago Test case: 102 3 1 1 2 4 2 0 1 1 expected output = 4 my output = 6 How is result = 4, shouldn't it be 6 ? 2→1→1→2→2→1→1(end) 0 aryangrover2304023 days ago Can anyone help why this solution failing? static int minJumps(int[] arr) { int n = arr.length; int[] dp = new int[n]; dp[n-1] = 0; for(int i=n-2; i>=0; i--) { int min = Integer.MAX_VALUE; for(int jump=1; jump<=arr[i] && jump+i<n; jump++) { min = Math.min(min, dp[i+jump]); } dp[i] = (min==Integer.MAX_VALUE)?min:min+1; } return dp[0]==Integer.MAX_VALUE?-1:dp[0]; } 0 sansan23 days ago Can someone help me with this code?Its failing due to time.... int i=0,temp,j=0; while(i<arr.length) { if(arr[i]>0) { temp=arr[i]; i+=temp; j+=1; } } if(j>0) return j; else return -1; 0 ayush63784 days ago Recursive solution class Solution:def minJumps(self, arr, n): if len(arr) <= 1: return 0 if arr[0] == 0: return -1 if len(arr) - arr[0] - 1 <= 0: return 1 max_i = 1 max_jum = n - 2 - arr[1] for i in range(1, arr[0] + 1): if n - i - 1 - arr[i] < max_value: max_i = i max_jump = n - i - 1 - arr[i] rec = self.minJumps(arr[max_i:], n - max_i) if rec == -1: return -1 ans = 1 + rec return ans 0 nitishpescse5 days ago // { Driver Code Starts#include<bits/stdc++.h>using namespace std; // } Driver Code Ends// Function to return minimum number of jumps to end of array class Solution{ public: int minJumps(int arr[], int n) { if (n == 1) return 0; if (arr[0] == 0) return -1; int maxRange = arr[0], steps = arr[0], jumps = 0; for (int i = 1; i < n - 1; i++) { steps--; maxRange = max(maxRange, arr[i] + i); if (steps == 0) { jumps++; steps = maxRange - i; if (steps <= 0) return -1; } } return jumps + 1; }}; // { Driver Code Starts. int main(){ int t; cin>>t; while(t--) { int n,i,j; cin>>n; int arr[n]; for(int i=0; i<n; i++) cin>>arr[i]; Solution obj; cout<<obj.minJumps(arr, n)<<endl; } return 0;} // } Driver Code Ends 0 jy9041476 days ago java solution by jitu yadav static int minJumps(int[] arr){ int n=arr.length; if(n==1)return 0;if(arr[0]==0)return -1;if(arr[0]>n)return 1;int maxreach=arr[0];int step=arr[0];int jump=1;for(int i=1;i<n;i++){ if(i==n-1)return jump; maxreach=Math.max(maxreach,i+arr[i]); step--; if(step==0){ jump++; if(i>=maxreach)return -1; step=maxreach-i; }}return -1; } +1 buchadebnath1 week ago Can someone explain me the error of this code for TestCase:- 5 0 1 1 1 1 CODE:- class Solution{ static int minJumps(int[] arr){ int len=arr.length; int[] jump=new int[len]; jump[0]=0; for(int i=1;i<len;i++){ jump[i]=Integer.MAX_VALUE; for(int j=0;j<i;j++){ if(arr[j]+j>=i && arr[j]!=Integer.MAX_VALUE){ jump[i]=Math.min(jump[i],jump[j]+1); } } } if(jump[len-1]!=Integer.MAX_VALUE) return jump[len-1]; else return -1; }} +2 milindprajapatmst191 week ago class Solution { public: int minJumps(int arr[], int n) { if (n == 1) return 0; if (arr[0] == 0) return -1; int maxRange = arr[0], steps = arr[0], jumps = 0; for (int i = 1; i < n - 1; i++) { steps--; maxRange = max(maxRange, arr[i] + i); if (steps == 0) { jumps++; steps = maxRange - i; if (steps <= 0) return -1; } } return jumps + 1; } }; +2 0xqt6eumuntdjmlbvx8kwrxi8g36mhs98c0r12mw2 weeks ago A fun Python recursive solution :) class Solution: def recShortList(self, arr, count, n): arrLen = len(arr) if arrLen < 2 :#and arr[0] > 0: return count for i in range(arrLen-1): if arr[i] >= (arrLen - (i+1)) and i < arrLen: return self.recShortList(arr[0:i+1],count + 1,n) return -1 def minJumps(self, arr, n): return self.recShortList(arr,0,n) 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": 589, "s": 238, "text": "Given an array of N integers arr[] where each element represents the max number of steps that can be made forward from that element. Find the minimum number of jumps to reach the end of the array (starting from the first element). If an element is 0, then you cannot move through that element.\nNote: Return -1 if you can't reach the end of the array." }, { "code": null, "e": 602, "s": 589, "text": "\nExample 1: " }, { "code": null, "e": 834, "s": 602, "text": "Input:\nN = 11 \narr[] = {1, 3, 5, 8, 9, 2, 6, 7, 6, 8, 9} \nOutput: 3 \nExplanation: \nFirst jump from 1st element to 2nd \nelement with value 3. Now, from here \nwe jump to 5th element with value 9, \nand from here we will jump to last. " }, { "code": null, "e": 845, "s": 834, "text": "Example 2:" }, { "code": null, "e": 988, "s": 845, "text": "Input :\nN = 6\narr = {1, 4, 3, 2, 6, 7}\nOutput: 2 \nExplanation: \nFirst we jump from the 1st to 2nd element \nand then jump to the last element.\n" }, { "code": null, "e": 1224, "s": 988, "text": "\nYour task:\nYou don't need to read input or print anything. Your task is to complete function minJumps() which takes the array arr and it's size N as input parameters and returns the minimum number of jumps. If not possible returns -1." }, { "code": null, "e": 1288, "s": 1224, "text": "\nExpected Time Complexity: O(N)\nExpected Space Complexity: O(1)" }, { "code": null, "e": 1329, "s": 1288, "text": "\nConstraints:\n1 ≤ N ≤ 107\n0 ≤ arri ≤ 107" }, { "code": null, "e": 1331, "s": 1329, "text": "0" }, { "code": null, "e": 1346, "s": 1331, "text": "shettyrohan183" }, { "code": null, "e": 1372, "s": 1346, "text": "This comment was deleted." }, { "code": null, "e": 1374, "s": 1372, "text": "0" }, { "code": null, "e": 1403, "s": 1374, "text": "venkatesh17nayak14 hours ago" }, { "code": null, "e": 1415, "s": 1403, "text": "Test case: " }, { "code": null, "e": 1437, "s": 1415, "text": "102 3 1 1 2 4 2 0 1 1" }, { "code": null, "e": 1459, "s": 1439, "text": "expected output = 4" }, { "code": null, "e": 1475, "s": 1461, "text": "my output = 6" }, { "code": null, "e": 1516, "s": 1477, "text": "How is result = 4, shouldn't it be 6 ?" }, { "code": null, "e": 1535, "s": 1516, "text": "2→1→1→2→2→1→1(end)" }, { "code": null, "e": 1537, "s": 1535, "text": "0" }, { "code": null, "e": 1565, "s": 1537, "text": "aryangrover2304023 days ago" }, { "code": null, "e": 1608, "s": 1565, "text": "Can anyone help why this solution failing?" }, { "code": null, "e": 2047, "s": 1612, "text": "static int minJumps(int[] arr) {\n int n = arr.length;\n int[] dp = new int[n];\n dp[n-1] = 0;\n \n for(int i=n-2; i>=0; i--) {\n int min = Integer.MAX_VALUE;\n for(int jump=1; jump<=arr[i] && jump+i<n; jump++) {\n min = Math.min(min, dp[i+jump]);\n }\n dp[i] = (min==Integer.MAX_VALUE)?min:min+1;\n }\n return dp[0]==Integer.MAX_VALUE?-1:dp[0];\n }" }, { "code": null, "e": 2053, "s": 2051, "text": "0" }, { "code": null, "e": 2071, "s": 2053, "text": "sansan23 days ago" }, { "code": null, "e": 2134, "s": 2071, "text": "Can someone help me with this code?Its failing due to time...." }, { "code": null, "e": 2391, "s": 2136, "text": " int i=0,temp,j=0; while(i<arr.length) { if(arr[i]>0) { temp=arr[i]; i+=temp; j+=1; } } if(j>0) return j; else return -1;" }, { "code": null, "e": 2397, "s": 2395, "text": "0" }, { "code": null, "e": 2417, "s": 2397, "text": "ayush63784 days ago" }, { "code": null, "e": 2436, "s": 2417, "text": "Recursive solution" }, { "code": null, "e": 2919, "s": 2438, "text": "class Solution:def minJumps(self, arr, n): if len(arr) <= 1: return 0 if arr[0] == 0: return -1 if len(arr) - arr[0] - 1 <= 0: return 1 max_i = 1 max_jum = n - 2 - arr[1] for i in range(1, arr[0] + 1): if n - i - 1 - arr[i] < max_value: max_i = i max_jump = n - i - 1 - arr[i] rec = self.minJumps(arr[max_i:], n - max_i) if rec == -1: return -1 ans = 1 + rec return ans" }, { "code": null, "e": 2921, "s": 2919, "text": "0" }, { "code": null, "e": 2944, "s": 2921, "text": "nitishpescse5 days ago" }, { "code": null, "e": 3011, "s": 2944, "text": "// { Driver Code Starts#include<bits/stdc++.h>using namespace std;" }, { "code": null, "e": 3094, "s": 3011, "text": "// } Driver Code Ends// Function to return minimum number of jumps to end of array" }, { "code": null, "e": 3594, "s": 3094, "text": "class Solution{ public: int minJumps(int arr[], int n) { if (n == 1) return 0; if (arr[0] == 0) return -1; int maxRange = arr[0], steps = arr[0], jumps = 0; for (int i = 1; i < n - 1; i++) { steps--; maxRange = max(maxRange, arr[i] + i); if (steps == 0) { jumps++; steps = maxRange - i; if (steps <= 0) return -1; } } return jumps + 1; }};" }, { "code": null, "e": 3619, "s": 3594, "text": "// { Driver Code Starts." }, { "code": null, "e": 3867, "s": 3619, "text": "int main(){ int t; cin>>t; while(t--) { int n,i,j; cin>>n; int arr[n]; for(int i=0; i<n; i++) cin>>arr[i]; Solution obj; cout<<obj.minJumps(arr, n)<<endl; } return 0;} // } Driver Code Ends" }, { "code": null, "e": 3869, "s": 3867, "text": "0" }, { "code": null, "e": 3888, "s": 3869, "text": "jy9041476 days ago" }, { "code": null, "e": 3916, "s": 3888, "text": "java solution by jitu yadav" }, { "code": null, "e": 3973, "s": 3916, "text": " static int minJumps(int[] arr){ int n=arr.length;" }, { "code": null, "e": 4277, "s": 3973, "text": "if(n==1)return 0;if(arr[0]==0)return -1;if(arr[0]>n)return 1;int maxreach=arr[0];int step=arr[0];int jump=1;for(int i=1;i<n;i++){ if(i==n-1)return jump; maxreach=Math.max(maxreach,i+arr[i]); step--; if(step==0){ jump++; if(i>=maxreach)return -1; step=maxreach-i; }}return -1;" }, { "code": null, "e": 4279, "s": 4277, "text": "}" }, { "code": null, "e": 4282, "s": 4279, "text": "+1" }, { "code": null, "e": 4305, "s": 4282, "text": "buchadebnath1 week ago" }, { "code": null, "e": 4356, "s": 4305, "text": "Can someone explain me the error of this code for " }, { "code": null, "e": 4369, "s": 4358, "text": "TestCase:-" }, { "code": null, "e": 4373, "s": 4371, "text": "5" }, { "code": null, "e": 4383, "s": 4373, "text": "0 1 1 1 1" }, { "code": null, "e": 4392, "s": 4385, "text": "CODE:-" }, { "code": null, "e": 4891, "s": 4394, "text": "class Solution{ static int minJumps(int[] arr){ int len=arr.length; int[] jump=new int[len]; jump[0]=0; for(int i=1;i<len;i++){ jump[i]=Integer.MAX_VALUE; for(int j=0;j<i;j++){ if(arr[j]+j>=i && arr[j]!=Integer.MAX_VALUE){ jump[i]=Math.min(jump[i],jump[j]+1); } } } if(jump[len-1]!=Integer.MAX_VALUE) return jump[len-1]; else return -1; }}" }, { "code": null, "e": 4894, "s": 4891, "text": "+2" }, { "code": null, "e": 4924, "s": 4894, "text": "milindprajapatmst191 week ago" }, { "code": null, "e": 5464, "s": 4924, "text": "class Solution {\n public:\n int minJumps(int arr[], int n) {\n if (n == 1)\n return 0;\n if (arr[0] == 0)\n return -1;\n int maxRange = arr[0], steps = arr[0], jumps = 0;\n for (int i = 1; i < n - 1; i++) {\n steps--;\n maxRange = max(maxRange, arr[i] + i);\n if (steps == 0) {\n jumps++;\n steps = maxRange - i;\n if (steps <= 0)\n return -1;\n }\n }\n return jumps + 1;\n }\n};" }, { "code": null, "e": 5467, "s": 5464, "text": "+2" }, { "code": null, "e": 5519, "s": 5467, "text": "0xqt6eumuntdjmlbvx8kwrxi8g36mhs98c0r12mw2 weeks ago" }, { "code": null, "e": 5554, "s": 5519, "text": "A fun Python recursive solution :)" }, { "code": null, "e": 5911, "s": 5556, "text": "class Solution:\n def recShortList(self, arr, count, n):\n arrLen = len(arr)\n if arrLen < 2 :#and arr[0] > 0:\n return count\n \n for i in range(arrLen-1):\n if arr[i] >= (arrLen - (i+1)) and i < arrLen:\n return self.recShortList(arr[0:i+1],count + 1,n)\n return -1\n\ndef minJumps(self, arr, n):\n return self.recShortList(arr,0,n)" }, { "code": null, "e": 6057, "s": 5911, "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": 6093, "s": 6057, "text": " Login to access your submissions. " }, { "code": null, "e": 6103, "s": 6093, "text": "\nProblem\n" }, { "code": null, "e": 6113, "s": 6103, "text": "\nContest\n" }, { "code": null, "e": 6176, "s": 6113, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 6324, "s": 6176, "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": 6532, "s": 6324, "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": 6638, "s": 6532, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Object Oriented Python - Building Blocks
In this chapter, we will discuss object oriented terms and programming concepts in detail.Class is a just a factory for an instance. This factory contains the blueprint which describes how to make the instances. An instances or object are constructed from the class. In most cases, we can have more than one instances of a class. Every instance has a set of attribute and these attributes are defined in a class, so every instance of a particular class is expected to have the same attributes. A class will let you bundle together the behavior and state of an object. Observe the following diagram for better understanding − The following points are worth notable when discussing class bundles − The word behavior is identical to function – it is a piece of code that does something (or implements a behavior) The word behavior is identical to function – it is a piece of code that does something (or implements a behavior) The word state is identical to variables – it is a place to store values within a class. The word state is identical to variables – it is a place to store values within a class. When we assert a class behavior and state together, it means that a class packages functions and variables. When we assert a class behavior and state together, it means that a class packages functions and variables. In Python, creating a method defines a class behavior. The word method is the OOP name given to a function that is defined within a class. To sum up − Class functions − is synonym for methods Class functions − is synonym for methods Class variables − is synonym for name attributes. Class variables − is synonym for name attributes. Class − a blueprint for an instance with exact behavior. Class − a blueprint for an instance with exact behavior. Object − one of the instances of the class, perform functionality defined in the class. Object − one of the instances of the class, perform functionality defined in the class. Type − indicates the class the instance belongs to Type − indicates the class the instance belongs to Attribute − Any object value: object.attribute Attribute − Any object value: object.attribute Method − a “callable attribute” defined in the class Method − a “callable attribute” defined in the class Observe the following piece of code for example − var = “Hello, John” print( type (var)) # ‘str’> or <class 'str'> print(var.upper()) # upper() method is called, HELLO, JOHN The following code shows how to create our first class and then its instance. class MyClass(object): pass # Create first instance of MyClass this_obj = MyClass() print(this_obj) # Another instance of MyClass that_obj = MyClass() print (that_obj) Here we have created a class called MyClass and which does not do any task. The argument object in MyClass class involves class inheritance and will be discussed in later chapters. pass in the above code indicates that this block is empty, that is it is an empty class definition. Let us create an instance this_obj of MyClass() class and print it as shown − <__main__.MyClass object at 0x03B08E10> <__main__.MyClass object at 0x0369D390> Here, we have created an instance of MyClass. The hex code refers to the address where the object is being stored. Another instance is pointing to another address. Now let us define one variable inside the class MyClass() and get the variable from the instance of that class as shown in the following code − class MyClass(object): var = 9 # Create first instance of MyClass this_obj = MyClass() print(this_obj.var) # Another instance of MyClass that_obj = MyClass() print (that_obj.var) You can observe the following output when you execute the code given above − 9 9 As instance knows from which class it is instantiated, so when requested for an attribute from an instance, the instance looks for the attribute and the class. This is called the attribute lookup. A function defined in a class is called a method. An instance method requires an instance in order to call it and requires no decorator. When creating an instance method, the first parameter is always self. Though we can call it (self) by any other name, it is recommended to use self, as it is a naming convention. class MyClass(object): var = 9 def firstM(self): print("hello, World") obj = MyClass() print(obj.var) obj.firstM() You can observe the following output when you execute the code given above − 9 hello, World Note that in the above program, we defined a method with self as argument. But we cannot call the method as we have not declared any argument to it. class MyClass(object): def firstM(self): print("hello, World") print(self) obj = MyClass() obj.firstM() print(obj) You can observe the following output when you execute the code given above − hello, World <__main__.MyClass object at 0x036A8E10> <__main__.MyClass object at 0x036A8E10> Encapsulation is one of the fundamentals of OOP. OOP enables us to hide the complexity of the internal working of the object which is advantageous to the developer in the following ways − Simplifies and makes it easy to understand to use an object without knowing the internals. Simplifies and makes it easy to understand to use an object without knowing the internals. Any change can be easily manageable. Any change can be easily manageable. Object-oriented programming relies heavily on encapsulation. The terms encapsulation and abstraction (also called data hiding) are often used as synonyms. They are nearly synonymous, as abstraction is achieved through encapsulation. Encapsulation provides us the mechanism of restricting the access to some of the object’s components, this means that the internal representation of an object can’t be seen from outside of the object definition. Access to this data is typically achieved through special methods − Getters and Setters. This data is stored in instance attributes and can be manipulated from anywhere outside the class. To secure it, that data should only be accessed using instance methods. Direct access should not be permitted. class MyClass(object): def setAge(self, num): self.age = num def getAge(self): return self.age zack = MyClass() zack.setAge(45) print(zack.getAge()) zack.setAge("Fourty Five") print(zack.getAge()) You can observe the following output when you execute the code given above − 45 Fourty Five The data should be stored only if it is correct and valid, using Exception handling constructs. As we can see above, there is no restriction on the user input to setAge() method. It could be a string, a number, or a list. So we need to check onto above code to ensure correctness of being stored. class MyClass(object): def setAge(self, num): self.age = num def getAge(self): return self.age zack = MyClass() zack.setAge(45) print(zack.getAge()) zack.setAge("Fourty Five") print(zack.getAge()) The __init__ method is implicitly called as soon as an object of a class is instantiated.This will initialize the object. x = MyClass() The line of code shown above will create a new instance and assigns this object to the local variable x. The instantiation operation, that is calling a class object, creates an empty object. Many classes like to create objects with instances customized to a specific initial state. Therefore, a class may define a special method named ‘ __init__() ‘ as shown − def __init__(self): self.data = [] Python calls __init__ during the instantiation to define an additional attribute that should occur when a class is instantiated that may be setting up some beginning values for that object or running a routine required on instantiation. So in this example, a new, initialized instance can be obtained by − x = MyClass() The __init__() method can have single or multiple arguments for a greater flexibility. The init stands for initialization, as it initializes attributes of the instance. It is called the constructor of a class. class myclass(object): def __init__(self,aaa, bbb): self.a = aaa self.b = bbb x = myclass(4.5, 3) print(x.a, x.b) 4.5 3 The attribute defined in the class is called “class attributes’ and the attributes defined in the function is called ‘instance attributes’. While defining, these attributes are not prefixed by self, as these are the property of the class and not of a particular instance. The class attributes can be accessed by the class itself ( className.attributeName) as well as by the instances of the class (inst.attributeName). So, the instances have access to both the instance attribute as well as class attributes. >>> class myclass(): age = 21 >>> myclass.age 21 >>> x = myclass() >>> x.age 21 >>> A class attribute can be overridden in an instance, even though it is not a good method to break encapsulation. There is a lookup path for attributes in Python. The first being the method defined within the class, and then the class above it. >>> class myclass(object): classy = 'class value' >>> dd = myclass() >>> print (dd.classy) # This should return the string 'class value' class value >>> >>> dd.classy = "Instance Value" >>> print(dd.classy) # Return the string "Instance Value" Instance Value >>> >>> # This will delete the value set for 'dd.classy' in the instance. >>> del dd.classy >>> >>> # Since the overriding attribute was deleted, this will print 'class value'. >>> print(dd.classy) class value >>> We are overriding the ‘classy’ class attribute in the instance dd. When it’s overridden, the Python interpreter reads the overridden value. But once the new value is deleted with ‘del’, the overridden value is no longer present in the instance, and hence the lookup goes a level above and gets it from the class. In this section, let us understand how the class data relates to the instance data. We can store data either in a class or in an instance. When we design a class, we decide which data belongs to the instance and which data should be stored into the overall class. An instance can access the class data. If we create multiple instances, then these instances can access their individual attribute values as well the overall class data. Thus, a class data is the data that is shared among all the instances. Observe the code given below for better undersanding − class InstanceCounter(object): count = 0 # class attribute, will be accessible to all instances def __init__(self, val): self.val = val InstanceCounter.count +=1 # Increment the value of class attribute, accessible through class name # In above line, class ('InstanceCounter') act as an object def set_val(self, newval): self.val = newval def get_val(self): return self.val def get_count(self): return InstanceCounter.count a = InstanceCounter(9) b = InstanceCounter(18) c = InstanceCounter(27) for obj in (a, b, c): print ('val of obj: %s' %(obj.get_val())) # Initialized value ( 9, 18, 27) print ('count: %s' %(obj.get_count())) # always 3 val of obj: 9 count: 3 val of obj: 18 count: 3 val of obj: 27 count: 3 In short, class attributes are same for all instances of class whereas instance attributes is particular for each instance. For two different instances, we will have two different instance attributes. class myClass: class_attribute = 99 def class_method(self): self.instance_attribute = 'I am instance attribute' print (myClass.__dict__) You can observe the following output when you execute the code given above − {'__module__': '__main__', 'class_attribute': 99, 'class_method': , '__dict__': , '__weakref__': , '__doc__': None} The instance attribute myClass.__dict__ as shown − >>> a = myClass() >>> a.class_method() >>> print(a.__dict__) {'instance_attribute': 'I am instance attribute'} 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": 2304, "s": 1810, "text": "In this chapter, we will discuss object oriented terms and programming concepts in detail.Class is a just a factory for an instance. This factory contains the blueprint which describes\nhow to make the instances. An instances or object are constructed from the class. In most cases, we can have more than one instances of a class. Every instance has a set of attribute and these attributes are defined in a class, so every instance of a particular class is expected to have the same attributes." }, { "code": null, "e": 2435, "s": 2304, "text": "A class will let you bundle together the behavior and state of an object. Observe the\nfollowing diagram for better understanding −" }, { "code": null, "e": 2506, "s": 2435, "text": "The following points are worth notable when discussing class bundles −" }, { "code": null, "e": 2620, "s": 2506, "text": "The word behavior is identical to function – it is a piece of code that does something (or implements a behavior)" }, { "code": null, "e": 2734, "s": 2620, "text": "The word behavior is identical to function – it is a piece of code that does something (or implements a behavior)" }, { "code": null, "e": 2823, "s": 2734, "text": "The word state is identical to variables – it is a place to store values within a class." }, { "code": null, "e": 2912, "s": 2823, "text": "The word state is identical to variables – it is a place to store values within a class." }, { "code": null, "e": 3020, "s": 2912, "text": "When we assert a class behavior and state together, it means that a class packages functions and variables." }, { "code": null, "e": 3128, "s": 3020, "text": "When we assert a class behavior and state together, it means that a class packages functions and variables." }, { "code": null, "e": 3279, "s": 3128, "text": "In Python, creating a method defines a class behavior. The word method is the OOP name given to a function that is defined within a class. To sum up −" }, { "code": null, "e": 3320, "s": 3279, "text": "Class functions − is synonym for methods" }, { "code": null, "e": 3361, "s": 3320, "text": "Class functions − is synonym for methods" }, { "code": null, "e": 3411, "s": 3361, "text": "Class variables − is synonym for name attributes." }, { "code": null, "e": 3461, "s": 3411, "text": "Class variables − is synonym for name attributes." }, { "code": null, "e": 3518, "s": 3461, "text": "Class − a blueprint for an instance with exact behavior." }, { "code": null, "e": 3575, "s": 3518, "text": "Class − a blueprint for an instance with exact behavior." }, { "code": null, "e": 3663, "s": 3575, "text": "Object − one of the instances of the class, perform functionality defined in the class." }, { "code": null, "e": 3751, "s": 3663, "text": "Object − one of the instances of the class, perform functionality defined in the class." }, { "code": null, "e": 3802, "s": 3751, "text": "Type − indicates the class the instance belongs to" }, { "code": null, "e": 3853, "s": 3802, "text": "Type − indicates the class the instance belongs to" }, { "code": null, "e": 3900, "s": 3853, "text": "Attribute − Any object value: object.attribute" }, { "code": null, "e": 3947, "s": 3900, "text": "Attribute − Any object value: object.attribute" }, { "code": null, "e": 4000, "s": 3947, "text": "Method − a “callable attribute” defined in the class" }, { "code": null, "e": 4053, "s": 4000, "text": "Method − a “callable attribute” defined in the class" }, { "code": null, "e": 4103, "s": 4053, "text": "Observe the following piece of code for example −" }, { "code": null, "e": 4227, "s": 4103, "text": "var = “Hello, John”\nprint( type (var)) # ‘str’> or <class 'str'>\nprint(var.upper()) # upper() method is called, HELLO, JOHN" }, { "code": null, "e": 4305, "s": 4227, "text": "The following code shows how to create our first class and then its instance." }, { "code": null, "e": 4476, "s": 4305, "text": "class MyClass(object):\n pass\n# Create first instance of MyClass\nthis_obj = MyClass()\nprint(this_obj)\n# Another instance of MyClass\nthat_obj = MyClass()\nprint (that_obj)" }, { "code": null, "e": 4757, "s": 4476, "text": "Here we have created a class called MyClass and which does not do any task. The argument object in MyClass class involves class inheritance and will be discussed in later chapters. pass in the above code indicates that this block is empty, that is it is an empty class definition." }, { "code": null, "e": 4835, "s": 4757, "text": "Let us create an instance this_obj of MyClass() class and print it as shown −" }, { "code": null, "e": 4915, "s": 4835, "text": "<__main__.MyClass object at 0x03B08E10>\n<__main__.MyClass object at 0x0369D390>" }, { "code": null, "e": 5079, "s": 4915, "text": "Here, we have created an instance of MyClass. The hex code refers to the address where the object is being stored. Another instance is pointing to another address." }, { "code": null, "e": 5223, "s": 5079, "text": "Now let us define one variable inside the class MyClass() and get the variable from the instance of that class as shown in the following code −" }, { "code": null, "e": 5408, "s": 5223, "text": "class MyClass(object):\n var = 9\n\n# Create first instance of MyClass\nthis_obj = MyClass()\nprint(this_obj.var)\n\n# Another instance of MyClass\n\nthat_obj = MyClass()\nprint (that_obj.var)" }, { "code": null, "e": 5485, "s": 5408, "text": "You can observe the following output when you execute the code given above −" }, { "code": null, "e": 5490, "s": 5485, "text": "9\n9\n" }, { "code": null, "e": 5687, "s": 5490, "text": "As instance knows from which class it is instantiated, so when requested for an attribute from an instance, the instance looks for the attribute and the class. This is called the attribute lookup." }, { "code": null, "e": 6003, "s": 5687, "text": "A function defined in a class is called a method. An instance method requires an instance in order to call it and requires no decorator. When creating an instance method, the first parameter is always self. Though we can call it (self) by any other name, it is recommended to use self, as it is a naming convention." }, { "code": null, "e": 6130, "s": 6003, "text": "class MyClass(object):\n var = 9\n def firstM(self):\n print(\"hello, World\")\nobj = MyClass()\nprint(obj.var)\nobj.firstM()" }, { "code": null, "e": 6207, "s": 6130, "text": "You can observe the following output when you execute the code given above −" }, { "code": null, "e": 6223, "s": 6207, "text": "9\nhello, World\n" }, { "code": null, "e": 6372, "s": 6223, "text": "Note that in the above program, we defined a method with self as argument. But we cannot call the method as we have not declared any argument to it." }, { "code": null, "e": 6502, "s": 6372, "text": "class MyClass(object):\n def firstM(self):\n print(\"hello, World\")\n print(self)\nobj = MyClass()\nobj.firstM()\nprint(obj)" }, { "code": null, "e": 6579, "s": 6502, "text": "You can observe the following output when you execute the code given above −" }, { "code": null, "e": 6673, "s": 6579, "text": "hello, World\n<__main__.MyClass object at 0x036A8E10>\n<__main__.MyClass object at 0x036A8E10>\n" }, { "code": null, "e": 6861, "s": 6673, "text": "Encapsulation is one of the fundamentals of OOP. OOP enables us to hide the complexity\nof the internal working of the object which is advantageous to the developer in the\nfollowing ways −" }, { "code": null, "e": 6952, "s": 6861, "text": "Simplifies and makes it easy to understand to use an object without knowing the internals." }, { "code": null, "e": 7043, "s": 6952, "text": "Simplifies and makes it easy to understand to use an object without knowing the internals." }, { "code": null, "e": 7080, "s": 7043, "text": "Any change can be easily manageable." }, { "code": null, "e": 7117, "s": 7080, "text": "Any change can be easily manageable." }, { "code": null, "e": 7350, "s": 7117, "text": "Object-oriented programming relies heavily on encapsulation. The terms encapsulation and abstraction (also called data hiding) are often used as synonyms. They are nearly synonymous, as abstraction is achieved through encapsulation." }, { "code": null, "e": 7651, "s": 7350, "text": "Encapsulation provides us the mechanism of restricting the access to some of the object’s\ncomponents, this means that the internal representation of an object can’t be seen from outside of the object definition. Access to this data is typically achieved through special\nmethods − Getters and Setters." }, { "code": null, "e": 7861, "s": 7651, "text": "This data is stored in instance attributes and can be manipulated from anywhere outside the class. To secure it, that data should only be accessed using instance methods. Direct access should not be permitted." }, { "code": null, "e": 8079, "s": 7861, "text": "class MyClass(object):\n def setAge(self, num):\n self.age = num\n\n def getAge(self):\n return self.age\n\nzack = MyClass()\nzack.setAge(45)\nprint(zack.getAge())\n\nzack.setAge(\"Fourty Five\")\nprint(zack.getAge())" }, { "code": null, "e": 8156, "s": 8079, "text": "You can observe the following output when you execute the code given above −" }, { "code": null, "e": 8172, "s": 8156, "text": "45\nFourty Five\n" }, { "code": null, "e": 8469, "s": 8172, "text": "The data should be stored only if it is correct and valid, using Exception handling\nconstructs. As we can see above, there is no restriction on the user input to setAge()\nmethod. It could be a string, a number, or a list. So we need to check onto above code to ensure correctness of being stored." }, { "code": null, "e": 8583, "s": 8469, "text": "class MyClass(object):\n def setAge(self, num):\n self.age = num\n\n def getAge(self):\n return self.age" }, { "code": null, "e": 8685, "s": 8583, "text": "zack = MyClass()\nzack.setAge(45)\nprint(zack.getAge())\nzack.setAge(\"Fourty Five\")\nprint(zack.getAge())" }, { "code": null, "e": 8807, "s": 8685, "text": "The __init__ method is implicitly called as soon as an object of a class is instantiated.This will initialize the object." }, { "code": null, "e": 8821, "s": 8807, "text": "x = MyClass()" }, { "code": null, "e": 8926, "s": 8821, "text": "The line of code shown above will create a new instance and assigns this object to the\nlocal variable x." }, { "code": null, "e": 9182, "s": 8926, "text": "The instantiation operation, that is calling a class object, creates an empty object. Many classes like to create objects with instances customized to a specific initial state. Therefore, a class may define a special method named ‘ __init__() ‘ as shown −" }, { "code": null, "e": 9220, "s": 9182, "text": "def __init__(self):\n self.data = []" }, { "code": null, "e": 9526, "s": 9220, "text": "Python calls __init__ during the instantiation to define an additional attribute that should occur when a class is instantiated that may be setting up some beginning values for that object or running a routine required on instantiation. So in this example, a new, initialized\ninstance can be obtained by −" }, { "code": null, "e": 9540, "s": 9526, "text": "x = MyClass()" }, { "code": null, "e": 9750, "s": 9540, "text": "The __init__() method can have single or multiple arguments for a greater flexibility. The init stands for initialization, as it initializes attributes of the instance. It is called the\nconstructor of a class." }, { "code": null, "e": 9880, "s": 9750, "text": "class myclass(object):\n def __init__(self,aaa, bbb):\n self.a = aaa\n self.b = bbb\n\nx = myclass(4.5, 3)\nprint(x.a, x.b)" }, { "code": null, "e": 9887, "s": 9880, "text": "4.5 3\n" }, { "code": null, "e": 10159, "s": 9887, "text": "The attribute defined in the class is called “class attributes’ and the attributes defined in the function is called ‘instance attributes’. While defining, these attributes are not prefixed\nby self, as these are the property of the class and not of a particular instance." }, { "code": null, "e": 10396, "s": 10159, "text": "The class attributes can be accessed by the class itself ( className.attributeName) as well as by the instances of the class (inst.attributeName). So, the instances have access to both the instance attribute as well as class attributes." }, { "code": null, "e": 10483, "s": 10396, "text": ">>> class myclass():\n age = 21\n>>> myclass.age\n21\n>>> x = myclass()\n>>> x.age\n21\n>>>" }, { "code": null, "e": 10595, "s": 10483, "text": "A class attribute can be overridden in an instance, even though it is not a good method to break encapsulation." }, { "code": null, "e": 10726, "s": 10595, "text": "There is a lookup path for attributes in Python. The first being the method defined within\nthe class, and then the class above it." }, { "code": null, "e": 11203, "s": 10726, "text": ">>> class myclass(object):\n classy = 'class value'\n>>> dd = myclass()\n>>> print (dd.classy) # This should return the string 'class value'\nclass value\n>>>\n>>> dd.classy = \"Instance Value\"\n>>> print(dd.classy) # Return the string \"Instance Value\"\nInstance Value\n>>>\n>>> # This will delete the value set for 'dd.classy' in the instance.\n>>> del dd.classy\n>>> >>> # Since the overriding attribute was deleted, this will print 'class\nvalue'.\n\n>>> print(dd.classy)\nclass value\n>>>" }, { "code": null, "e": 11516, "s": 11203, "text": "We are overriding the ‘classy’ class attribute in the instance dd. When it’s overridden, the Python interpreter reads the overridden value. But once the new value is deleted with ‘del’, the overridden value is no longer present in the instance, and hence the lookup goes a level above and gets it from the class." }, { "code": null, "e": 11780, "s": 11516, "text": "In this section, let us understand how the class data relates to the instance data. We can store data either in a class or in an instance. When we design a class, we decide which data belongs to the instance and which data should be stored into the overall class." }, { "code": null, "e": 11950, "s": 11780, "text": "An instance can access the class data. If we create multiple instances, then these instances can access their individual attribute values as well the overall class data." }, { "code": null, "e": 12076, "s": 11950, "text": "Thus, a class data is the data that is shared among all the instances. Observe the code given below for better undersanding −" }, { "code": null, "e": 12772, "s": 12076, "text": "class InstanceCounter(object):\n count = 0 # class attribute, will be accessible to all instances\n def __init__(self, val):\n self.val = val\n InstanceCounter.count +=1 # Increment the value of class attribute, accessible through class name\n# In above line, class ('InstanceCounter') act as an object\n def set_val(self, newval):\n self.val = newval\n\n def get_val(self):\n return self.val\n\n def get_count(self):\n return InstanceCounter.count\na = InstanceCounter(9)\nb = InstanceCounter(18)\nc = InstanceCounter(27)\n\nfor obj in (a, b, c):\n print ('val of obj: %s' %(obj.get_val())) # Initialized value ( 9, 18, 27)\n print ('count: %s' %(obj.get_count())) # always 3" }, { "code": null, "e": 12844, "s": 12772, "text": "val of obj: 9\ncount: 3\nval of obj: 18\ncount: 3\nval of obj: 27\ncount: 3\n" }, { "code": null, "e": 13045, "s": 12844, "text": "In short, class attributes are same for all instances of class whereas instance attributes is particular for each instance. For two different instances, we will have two different instance attributes." }, { "code": null, "e": 13196, "s": 13045, "text": "class myClass:\n class_attribute = 99\n\n def class_method(self):\n self.instance_attribute = 'I am instance attribute'\n\nprint (myClass.__dict__)" }, { "code": null, "e": 13273, "s": 13196, "text": "You can observe the following output when you execute the code given above −" }, { "code": null, "e": 13390, "s": 13273, "text": "{'__module__': '__main__', 'class_attribute': 99, 'class_method': , '__dict__': , '__weakref__': , '__doc__': None}\n" }, { "code": null, "e": 13441, "s": 13390, "text": "The instance attribute myClass.__dict__ as shown −" }, { "code": null, "e": 13552, "s": 13441, "text": ">>> a = myClass()\n>>> a.class_method()\n>>> print(a.__dict__)\n{'instance_attribute': 'I am instance attribute'}" }, { "code": null, "e": 13587, "s": 13552, "text": "\n 14 Lectures \n 1.5 hours \n" }, { "code": null, "e": 13607, "s": 13587, "text": " Harshit Srivastava" }, { "code": null, "e": 13640, "s": 13607, "text": "\n 60 Lectures \n 8 hours \n" }, { "code": null, "e": 13671, "s": 13640, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 13703, "s": 13671, "text": "\n 11 Lectures \n 35 mins\n" }, { "code": null, "e": 13724, "s": 13703, "text": " Sandip Bhattacharya" }, { "code": null, "e": 13757, "s": 13724, "text": "\n 21 Lectures \n 2 hours \n" }, { "code": null, "e": 13777, "s": 13757, "text": " Pranjal Srivastava" }, { "code": null, "e": 13808, "s": 13777, "text": "\n 6 Lectures \n 43 mins\n" }, { "code": null, "e": 13825, "s": 13808, "text": " Frahaan Hussain" }, { "code": null, "e": 13860, "s": 13825, "text": "\n 49 Lectures \n 4.5 hours \n" }, { "code": null, "e": 13877, "s": 13860, "text": " Abhilash Nelson" }, { "code": null, "e": 13884, "s": 13877, "text": " Print" }, { "code": null, "e": 13895, "s": 13884, "text": " Add Notes" } ]
EJB - Entity Relationships
EJB 3.0 provides option to define database entity relationships/mappings like one-to-one, one-to-many, many-to-one, and many-to-many relationships. Following are the relevant annotations − One-to-One − Objects have one-to-one relationship. For example, a passenger can travel using a single ticket at a time. One-to-One − Objects have one-to-one relationship. For example, a passenger can travel using a single ticket at a time. One-to-Many − Objects have one-to-many relationship. For example, a father can have multiple kids. One-to-Many − Objects have one-to-many relationship. For example, a father can have multiple kids. Many-to-One − Objects have many-to-one relationship. For example, multiple kids having a single mother. Many-to-One − Objects have many-to-one relationship. For example, multiple kids having a single mother. Many-to-Many − Objects have many-to-many relationship. For example, a book can have multiple authors and an author can write multiple books. Many-to-Many − Objects have many-to-many relationship. For example, a book can have multiple authors and an author can write multiple books. We will demonstrate use of ManyToMany mapping here. To represent ManyToMany relationship, three following tables are required − Book − Book table, having records of books. Book − Book table, having records of books. Author − Author table, having records of author. Author − Author table, having records of author. Book_Author − Book Author table, having linkage of above mentioned Book and Author table. Book_Author − Book Author table, having linkage of above mentioned Book and Author table. Create a table book author, book_author in default database postgres. CREATE TABLE book ( book_id integer, name varchar(50) ); CREATE TABLE author ( author_id integer, name varchar(50) ); CREATE TABLE book_author ( book_id integer, author_id integer ); @Entity @Table(name="author") public class Author implements Serializable{ private int id; private String name; ... } @Entity @Table(name="book") public class Book implements Serializable{ private int id; private String title; private Set<Author> authors; ... } Use ManyToMany annotation in Book Entity. @Entity public class Book implements Serializable{ ... @ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE} , fetch = FetchType.EAGER) @JoinTable(table = @Table(name = "book_author"), joinColumns = {@JoinColumn(name = "book_id")}, inverseJoinColumns = {@JoinColumn(name = "author_id")}) public Set<Author> getAuthors() { return authors; } ... } Let us create a test EJB application to test entity relationships objects in EJB 3.0. Create a project with a name EjbComponent under a package com.tutorialspoint.entity as explained in the EJB - Create Application chapter. Please use the project created in EJB - Persistence chapter as such for this chapter to understand embedded objects in EJB concepts. Create Author.java under package com.tutorialspoint.entity as explained in the EJB - Create Application chapter. Keep rest of the files unchanged. Create Book.java under package com.tutorialspoint.entity. Use EJB - Persistence chapter as reference. Keep rest of the files unchanged. Clean and Build the application to make sure business logic is working as per the requirements. Finally, deploy the application in the form of jar file on JBoss Application Server. JBoss Application server will get started automatically if it is not started yet. Now create the EJB client, a console based application in the same way as explained in the EJB - Create Application chapter under topic Create Client to access EJB. package com.tutorialspoint.entity; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name="author") public class Author implements Serializable{ private int id; private String name; public Author() {} public Author(int id, String name) { this.id = id; this.name = name; } @Id @GeneratedValue(strategy= GenerationType.IDENTITY) @Column(name="author_id") public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String toString() { return id + "," + name; } } package com.tutorialspoint.entity; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Table; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; @Entity @Table(name="book") public class Book implements Serializable{ private int id; private String name; private Set<Author> authors; public Book() { } @Id @GeneratedValue(strategy= GenerationType.IDENTITY) @Column(name="book_id") public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public void setAuthors(Set<Author> authors) { this.authors = authors; } @ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE} , fetch = FetchType.EAGER) @JoinTable(table = @Table(name = "book_author"), joinColumns = {@JoinColumn(name = "book_id")}, inverseJoinColumns = {@JoinColumn(name = "author_id")}) public Set<Author> getAuthors() { return authors; } } package com.tutorialspoint.stateless; import com.tutorialspoint.entity.Book; import java.util.List; import javax.ejb.Remote; @Remote public interface LibraryPersistentBeanRemote { void addBook(Book bookName); List<Book> getBooks(); } package com.tutorialspoint.stateless; import com.tutorialspoint.entity.Book; import java.util.List; import javax.ejb.Stateless; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; @Stateless public class LibraryPersistentBean implements LibraryPersistentBeanRemote { public LibraryPersistentBean() { } @PersistenceContext(unitName="EjbComponentPU") private EntityManager entityManager; public void addBook(Book book) { entityManager.persist(book); } public List<Book> getBooks() { return entityManager.createQuery("From Book").getResultList(); } } As soon as you deploy the EjbComponent project on JBOSS, notice the jboss log. As soon as you deploy the EjbComponent project on JBOSS, notice the jboss log. JBoss has automatically created a JNDI entry for our session bean − LibraryPersistentBean/remote. JBoss has automatically created a JNDI entry for our session bean − LibraryPersistentBean/remote. We will using this lookup string to get remote business object of type − com.tutorialspoint.interceptor.LibraryPersistentBeanRemote We will using this lookup string to get remote business object of type − com.tutorialspoint.interceptor.LibraryPersistentBeanRemote ... 16:30:01,401 INFO [JndiSessionRegistrarBase] Binding the following Entries in Global JNDI: LibraryPersistentBean/remote - EJB3.x Default Remote Business Interface LibraryPersistentBean/remote-com.tutorialspoint.interceptor.LibraryPersistentBeanRemote - EJB3.x Remote Business Interface 16:30:02,723 INFO [SessionSpecContainer] Starting jboss.j2ee:jar=EjbComponent.jar,name=LibraryPersistentBean,service=EJB3 16:30:02,723 INFO [EJBContainer] STARTED EJB: com.tutorialspoint.interceptor.LibraryPersistentBeanRemote ejbName: LibraryPersistentBean 16:30:02,731 INFO [JndiSessionRegistrarBase] Binding the following Entries in Global JNDI: LibraryPersistentBean/remote - EJB3.x Default Remote Business Interface LibraryPersistentBean/remote-com.tutorialspoint.interceptor.LibraryPersistentBeanRemote - EJB3.x Remote Business Interface ... java.naming.factory.initial=org.jnp.interfaces.NamingContextFactory java.naming.factory.url.pkgs=org.jboss.naming:org.jnp.interfaces java.naming.provider.url=localhost These properties are used to initialize the InitialContext object of java naming service. These properties are used to initialize the InitialContext object of java naming service. InitialContext object will be used to lookup stateless session bean. InitialContext object will be used to lookup stateless session bean. package com.tutorialspoint.test; import com.tutorialspoint.stateful.LibraryBeanRemote; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; import javax.naming.InitialContext; import javax.naming.NamingException; public class EJBTester { BufferedReader brConsoleReader = null; Properties props; InitialContext ctx; { props = new Properties(); try { props.load(new FileInputStream("jndi.properties")); } catch (IOException ex) { ex.printStackTrace(); } try { ctx = new InitialContext(props); } catch (NamingException ex) { ex.printStackTrace(); } brConsoleReader = new BufferedReader(new InputStreamReader(System.in)); } public static void main(String[] args) { EJBTester ejbTester = new EJBTester(); ejbTester.testEmbeddedObjects(); } private void showGUI() { System.out.println("**********************"); System.out.println("Welcome to Book Store"); System.out.println("**********************"); System.out.print("Options \n1. Add Book\n2. Exit \nEnter Choice: "); } private void testEmbeddedObjects() { try { int choice = 1; LibraryPersistentBeanRemote libraryBean = (LibraryPersistentBeanRemote) ctx.lookup("LibraryPersistentBean/remote"); while (choice != 2) { String bookName; String authorName; showGUI(); String strChoice = brConsoleReader.readLine(); choice = Integer.parseInt(strChoice); if (choice == 1) { System.out.print("Enter book name: "); bookName = brConsoleReader.readLine(); System.out.print("Enter author name: "); authorName = brConsoleReader.readLine(); Book book = new Book(); book.setName(bookName); Author author = new Author(); author.setName(authorName); Set<Author> authors = new HashSet<Author>(); authors.add(author); book.setAuthors(authors); libraryBean.addBook(book); } else if (choice == 2) { break; } } List<Book> booksList = libraryBean.getBooks(); System.out.println("Book(s) entered so far: " + booksList.size()); int i = 0; for (Book book:booksList) { System.out.println((i+1)+". " + book.getName()); System.out.print("Author: "); Author[] authors = (Author[])books.getAuthors().toArray(); for(int j=0;j<authors.length;j++) { System.out.println(authors[j]); } i++; } } catch (Exception e) { System.out.println(e.getMessage()); e.printStackTrace(); }finally { try { if(brConsoleReader !=null) { brConsoleReader.close(); } } catch (IOException ex) { System.out.println(ex.getMessage()); } } } } EJBTester performs the following tasks − Load properties from jndi.properties and initialize the InitialContext object. Load properties from jndi.properties and initialize the InitialContext object. In testInterceptedEjb() method, jndi lookup is done with name - "LibraryPersistenceBean/remote" to obtain the remote business object (stateless EJB). In testInterceptedEjb() method, jndi lookup is done with name - "LibraryPersistenceBean/remote" to obtain the remote business object (stateless EJB). Then the user is shown a library store User Interface and he/she is asked to enter a choice. Then the user is shown a library store User Interface and he/she is asked to enter a choice. If the user enters 1, the system asks for book name and saves the book using stateless session bean addBook() method. Session Bean is storing the book in database. If the user enters 1, the system asks for book name and saves the book using stateless session bean addBook() method. Session Bean is storing the book in database. If the user enters 2, the system retrieves books using stateless session bean getBooks() method and exits. If the user enters 2, the system retrieves books using stateless session bean getBooks() method and exits. Locate EJBTester.java in project explorer. Right click on EJBTester class and select run file. Verify the following output in Netbeans console. run: ********************** Welcome to Book Store ********************** Options 1. Add Book 2. Exit Enter Choice: 1 Enter book name: learn html5 Enter Author name: Robert ********************** Welcome to Book Store ********************** Options 1. Add Book 2. Exit Enter Choice: 2 Book(s) entered so far: 1 1. learn html5 Author: Robert BUILD SUCCESSFUL (total time: 21 seconds) Print Add Notes Bookmark this page
[ { "code": null, "e": 2195, "s": 2047, "text": "EJB 3.0 provides option to define database entity relationships/mappings like one-to-one, one-to-many, many-to-one, and many-to-many relationships." }, { "code": null, "e": 2236, "s": 2195, "text": "Following are the relevant annotations −" }, { "code": null, "e": 2356, "s": 2236, "text": "One-to-One − Objects have one-to-one relationship. For example, a passenger can travel using a single ticket at a time." }, { "code": null, "e": 2476, "s": 2356, "text": "One-to-One − Objects have one-to-one relationship. For example, a passenger can travel using a single ticket at a time." }, { "code": null, "e": 2575, "s": 2476, "text": "One-to-Many − Objects have one-to-many relationship. For example, a father can have multiple kids." }, { "code": null, "e": 2674, "s": 2575, "text": "One-to-Many − Objects have one-to-many relationship. For example, a father can have multiple kids." }, { "code": null, "e": 2778, "s": 2674, "text": "Many-to-One − Objects have many-to-one relationship. For example, multiple kids having a single mother." }, { "code": null, "e": 2882, "s": 2778, "text": "Many-to-One − Objects have many-to-one relationship. For example, multiple kids having a single mother." }, { "code": null, "e": 3023, "s": 2882, "text": "Many-to-Many − Objects have many-to-many relationship. For example, a book can have multiple authors and an author can write multiple books." }, { "code": null, "e": 3164, "s": 3023, "text": "Many-to-Many − Objects have many-to-many relationship. For example, a book can have multiple authors and an author can write multiple books." }, { "code": null, "e": 3292, "s": 3164, "text": "We will demonstrate use of ManyToMany mapping here. To represent ManyToMany relationship, three following tables are required −" }, { "code": null, "e": 3336, "s": 3292, "text": "Book − Book table, having records of books." }, { "code": null, "e": 3380, "s": 3336, "text": "Book − Book table, having records of books." }, { "code": null, "e": 3429, "s": 3380, "text": "Author − Author table, having records of author." }, { "code": null, "e": 3478, "s": 3429, "text": "Author − Author table, having records of author." }, { "code": null, "e": 3568, "s": 3478, "text": "Book_Author − Book Author table, having linkage of above mentioned Book and Author table." }, { "code": null, "e": 3658, "s": 3568, "text": "Book_Author − Book Author table, having linkage of above mentioned Book and Author table." }, { "code": null, "e": 3728, "s": 3658, "text": "Create a table book author, book_author in default database postgres." }, { "code": null, "e": 3963, "s": 3728, "text": "CREATE TABLE book (\n book_id integer, \n name varchar(50) \n);\n\nCREATE TABLE author (\n author_id integer,\n name varchar(50) \n);\n\nCREATE TABLE book_author (\n book_id integer,\n author_id integer \n);" }, { "code": null, "e": 4253, "s": 3963, "text": "@Entity\n@Table(name=\"author\")\npublic class Author implements Serializable{\n private int id;\n private String name;\n ... \n}\n\n@Entity\n@Table(name=\"book\")\npublic class Book implements Serializable{\n private int id;\n private String title;\n private Set<Author> authors;\n ... \n}" }, { "code": null, "e": 4295, "s": 4253, "text": "Use ManyToMany annotation in Book Entity." }, { "code": null, "e": 4692, "s": 4295, "text": "@Entity\npublic class Book implements Serializable{\n ...\n @ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE}\n , fetch = FetchType.EAGER)\n @JoinTable(table = @Table(name = \"book_author\"),\n joinColumns = {@JoinColumn(name = \"book_id\")},\n inverseJoinColumns = {@JoinColumn(name = \"author_id\")})\n public Set<Author> getAuthors() {\n return authors;\n }\n ...\n}" }, { "code": null, "e": 4778, "s": 4692, "text": "Let us create a test EJB application to test entity relationships objects in EJB 3.0." }, { "code": null, "e": 5049, "s": 4778, "text": "Create a project with a name EjbComponent under a package com.tutorialspoint.entity as explained in the EJB - Create Application chapter. Please use the project created in EJB - Persistence chapter as such for this chapter to understand embedded objects in EJB concepts." }, { "code": null, "e": 5197, "s": 5049, "text": "Create Author.java under package com.tutorialspoint.entity as explained in the EJB - Create Application chapter. Keep rest of the files unchanged." }, { "code": null, "e": 5334, "s": 5197, "text": "Create Book.java under package com.tutorialspoint.entity. Use EJB - Persistence chapter as reference. Keep rest of the files unchanged." }, { "code": null, "e": 5430, "s": 5334, "text": "Clean and Build the application to make sure business logic is working as per the requirements." }, { "code": null, "e": 5597, "s": 5430, "text": "Finally, deploy the application in the form of jar file on JBoss Application Server. JBoss Application server will get started automatically if it is not started yet." }, { "code": null, "e": 5762, "s": 5597, "text": "Now create the EJB client, a console based application in the same way as explained in the EJB - Create Application chapter under topic Create Client to access EJB." }, { "code": null, "e": 6667, "s": 5762, "text": "package com.tutorialspoint.entity;\n\nimport java.io.Serializable;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.GenerationType;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n@Entity\n@Table(name=\"author\")\npublic class Author implements Serializable{\n \n private int id;\n private String name;\n\n public Author() {}\n\n public Author(int id, String name) {\n this.id = id;\n this.name = name;\n }\n \n @Id \n @GeneratedValue(strategy= GenerationType.IDENTITY)\n @Column(name=\"author_id\")\n public int getId() {\n return id;\n }\n\n public void setId(int id) {\n this.id = id;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public String toString() {\n return id + \",\" + name;\n } \n}" }, { "code": null, "e": 7835, "s": 6667, "text": "package com.tutorialspoint.entity;\n\nimport java.io.Serializable;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Table;\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.GenerationType;\n\n@Entity\n@Table(name=\"book\")\npublic class Book implements Serializable{\n\n private int id;\n private String name;\n private Set<Author> authors;\n\n public Book() { \n }\n\n @Id \n @GeneratedValue(strategy= GenerationType.IDENTITY)\n @Column(name=\"book_id\")\n public int getId() {\n return id;\n }\n\n public void setId(int id) {\n this.id = id;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public void setAuthors(Set<Author> authors) {\n this.authors = authors;\n } \n \n @ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE}\n , fetch = FetchType.EAGER)\n @JoinTable(table = @Table(name = \"book_author\"),\n joinColumns = {@JoinColumn(name = \"book_id\")},\n inverseJoinColumns = {@JoinColumn(name = \"author_id\")})\n public Set<Author> getAuthors() {\n return authors;\n }\n}" }, { "code": null, "e": 8084, "s": 7835, "text": "package com.tutorialspoint.stateless;\n\nimport com.tutorialspoint.entity.Book;\nimport java.util.List;\nimport javax.ejb.Remote;\n\n@Remote\npublic interface LibraryPersistentBeanRemote {\n\n void addBook(Book bookName);\n\n List<Book> getBooks();\n \n}" }, { "code": null, "e": 8725, "s": 8084, "text": "package com.tutorialspoint.stateless;\n\nimport com.tutorialspoint.entity.Book;\nimport java.util.List;\nimport javax.ejb.Stateless;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.PersistenceContext;\n\n@Stateless\npublic class LibraryPersistentBean implements LibraryPersistentBeanRemote {\n \n public LibraryPersistentBean() {\n }\n\n @PersistenceContext(unitName=\"EjbComponentPU\")\n private EntityManager entityManager; \n\n public void addBook(Book book) {\n entityManager.persist(book);\n } \n\n public List<Book> getBooks() {\n return entityManager.createQuery(\"From Book\").getResultList();\n }\n}" }, { "code": null, "e": 8804, "s": 8725, "text": "As soon as you deploy the EjbComponent project on JBOSS, notice the jboss log." }, { "code": null, "e": 8883, "s": 8804, "text": "As soon as you deploy the EjbComponent project on JBOSS, notice the jboss log." }, { "code": null, "e": 8981, "s": 8883, "text": "JBoss has automatically created a JNDI entry for our session bean − LibraryPersistentBean/remote." }, { "code": null, "e": 9079, "s": 8981, "text": "JBoss has automatically created a JNDI entry for our session bean − LibraryPersistentBean/remote." }, { "code": null, "e": 9211, "s": 9079, "text": "We will using this lookup string to get remote business object of type − com.tutorialspoint.interceptor.LibraryPersistentBeanRemote" }, { "code": null, "e": 9343, "s": 9211, "text": "We will using this lookup string to get remote business object of type − com.tutorialspoint.interceptor.LibraryPersistentBeanRemote" }, { "code": null, "e": 10202, "s": 9343, "text": "...\n16:30:01,401 INFO [JndiSessionRegistrarBase] Binding the following Entries in Global JNDI:\n LibraryPersistentBean/remote - EJB3.x Default Remote Business Interface\n LibraryPersistentBean/remote-com.tutorialspoint.interceptor.LibraryPersistentBeanRemote - EJB3.x Remote Business Interface\n16:30:02,723 INFO [SessionSpecContainer] Starting jboss.j2ee:jar=EjbComponent.jar,name=LibraryPersistentBean,service=EJB3\n16:30:02,723 INFO [EJBContainer] STARTED EJB: com.tutorialspoint.interceptor.LibraryPersistentBeanRemote ejbName: LibraryPersistentBean\n16:30:02,731 INFO [JndiSessionRegistrarBase] Binding the following Entries in Global JNDI:\n\n LibraryPersistentBean/remote - EJB3.x Default Remote Business Interface\n LibraryPersistentBean/remote-com.tutorialspoint.interceptor.LibraryPersistentBeanRemote - EJB3.x Remote Business Interface\n... \n" }, { "code": null, "e": 10370, "s": 10202, "text": "java.naming.factory.initial=org.jnp.interfaces.NamingContextFactory\njava.naming.factory.url.pkgs=org.jboss.naming:org.jnp.interfaces\njava.naming.provider.url=localhost" }, { "code": null, "e": 10460, "s": 10370, "text": "These properties are used to initialize the InitialContext object of java naming service." }, { "code": null, "e": 10550, "s": 10460, "text": "These properties are used to initialize the InitialContext object of java naming service." }, { "code": null, "e": 10619, "s": 10550, "text": "InitialContext object will be used to lookup stateless session bean." }, { "code": null, "e": 10688, "s": 10619, "text": "InitialContext object will be used to lookup stateless session bean." }, { "code": null, "e": 13962, "s": 10688, "text": "package com.tutorialspoint.test;\n \nimport com.tutorialspoint.stateful.LibraryBeanRemote;\n\nimport java.io.BufferedReader;\nimport java.io.FileInputStream;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\n\nimport java.util.*;\n\nimport javax.naming.InitialContext;\nimport javax.naming.NamingException;\n\npublic class EJBTester {\n\n BufferedReader brConsoleReader = null; \n Properties props;\n InitialContext ctx;\n {\n props = new Properties();\n try {\n props.load(new FileInputStream(\"jndi.properties\"));\n } catch (IOException ex) {\n ex.printStackTrace();\n }\n try {\n ctx = new InitialContext(props); \n } catch (NamingException ex) {\n ex.printStackTrace();\n }\n brConsoleReader = \n new BufferedReader(new InputStreamReader(System.in));\n }\n \n public static void main(String[] args) {\n\n EJBTester ejbTester = new EJBTester();\n\n ejbTester.testEmbeddedObjects();\n }\n \n private void showGUI() {\n System.out.println(\"**********************\");\n System.out.println(\"Welcome to Book Store\");\n System.out.println(\"**********************\");\n System.out.print(\"Options \\n1. Add Book\\n2. Exit \\nEnter Choice: \");\n }\n \n private void testEmbeddedObjects() {\n\n try {\n int choice = 1; \n\n LibraryPersistentBeanRemote libraryBean = \n (LibraryPersistentBeanRemote)\n ctx.lookup(\"LibraryPersistentBean/remote\");\n\n while (choice != 2) {\n String bookName;\n String authorName;\n \n showGUI();\n String strChoice = brConsoleReader.readLine();\n choice = Integer.parseInt(strChoice);\n if (choice == 1) {\n System.out.print(\"Enter book name: \");\n bookName = brConsoleReader.readLine();\n System.out.print(\"Enter author name: \");\n authorName = brConsoleReader.readLine(); \n Book book = new Book();\n book.setName(bookName);\n Author author = new Author();\n author.setName(authorName);\n Set<Author> authors = new HashSet<Author>();\n authors.add(author);\n book.setAuthors(authors);\n\n libraryBean.addBook(book); \n } else if (choice == 2) {\n break;\n }\n }\n\n List<Book> booksList = libraryBean.getBooks();\n\n System.out.println(\"Book(s) entered so far: \" + booksList.size());\n int i = 0;\n for (Book book:booksList) {\n System.out.println((i+1)+\". \" + book.getName());\n System.out.print(\"Author: \");\n Author[] authors = (Author[])books.getAuthors().toArray();\n for(int j=0;j<authors.length;j++) {\n System.out.println(authors[j]);\n }\n i++;\n } \n } catch (Exception e) {\n System.out.println(e.getMessage());\n e.printStackTrace();\n }finally {\n try {\n if(brConsoleReader !=null) {\n brConsoleReader.close();\n }\n } catch (IOException ex) {\n System.out.println(ex.getMessage());\n }\n }\n }\n}" }, { "code": null, "e": 14003, "s": 13962, "text": "EJBTester performs the following tasks −" }, { "code": null, "e": 14082, "s": 14003, "text": "Load properties from jndi.properties and initialize the InitialContext object." }, { "code": null, "e": 14161, "s": 14082, "text": "Load properties from jndi.properties and initialize the InitialContext object." }, { "code": null, "e": 14311, "s": 14161, "text": "In testInterceptedEjb() method, jndi lookup is done with name - \"LibraryPersistenceBean/remote\" to obtain the remote business object (stateless EJB)." }, { "code": null, "e": 14461, "s": 14311, "text": "In testInterceptedEjb() method, jndi lookup is done with name - \"LibraryPersistenceBean/remote\" to obtain the remote business object (stateless EJB)." }, { "code": null, "e": 14554, "s": 14461, "text": "Then the user is shown a library store User Interface and he/she is asked to enter a choice." }, { "code": null, "e": 14647, "s": 14554, "text": "Then the user is shown a library store User Interface and he/she is asked to enter a choice." }, { "code": null, "e": 14811, "s": 14647, "text": "If the user enters 1, the system asks for book name and saves the book using stateless session bean addBook() method. Session Bean is storing the book in database." }, { "code": null, "e": 14975, "s": 14811, "text": "If the user enters 1, the system asks for book name and saves the book using stateless session bean addBook() method. Session Bean is storing the book in database." }, { "code": null, "e": 15082, "s": 14975, "text": "If the user enters 2, the system retrieves books using stateless session bean getBooks() method and exits." }, { "code": null, "e": 15189, "s": 15082, "text": "If the user enters 2, the system retrieves books using stateless session bean getBooks() method and exits." }, { "code": null, "e": 15284, "s": 15189, "text": "Locate EJBTester.java in project explorer. Right click on EJBTester class and select run file." }, { "code": null, "e": 15333, "s": 15284, "text": "Verify the following output in Netbeans console." }, { "code": null, "e": 15720, "s": 15333, "text": "run:\n**********************\nWelcome to Book Store\n**********************\nOptions \n1. Add Book\n2. Exit \nEnter Choice: 1\nEnter book name: learn html5\nEnter Author name: Robert\n**********************\nWelcome to Book Store\n**********************\nOptions \n1. Add Book\n2. Exit \nEnter Choice: 2\nBook(s) entered so far: 1\n1. learn html5\nAuthor: Robert\nBUILD SUCCESSFUL (total time: 21 seconds)\n" }, { "code": null, "e": 15727, "s": 15720, "text": " Print" }, { "code": null, "e": 15738, "s": 15727, "text": " Add Notes" } ]
Box Stacking | Practice | GeeksforGeeks
You are given a set of N types of rectangular 3-D boxes, where the ith box has height h, width w and length l. You task is to create a stack of boxes which is as tall as possible, but you can only stack a box on top of another box if the dimensions of the 2-D base of the lower box are each strictly larger than those of the 2-D base of the higher box. Of course, you can rotate a box so that any side functions as its base.It is also allowable to use multiple instances of the same type of box. You task is to complete the function maxHeight which returns the height of the highest possible stack so formed. Note: Base of the lower box should be strictly larger than that of the new box we're going to place. This is in terms of both length and width, not just in terms of area. So, two boxes with same base cannot be placed one over the other. Example 1: Input: n = 4 height[] = {4,1,4,10} width[] = {6,2,5,12} length[] = {7,3,6,32} Output: 60 Explanation: One way of placing the boxes is as follows in the bottom to top manner: (Denoting the boxes in (l, w, h) manner) (12, 32, 10) (10, 12, 32) (6, 7, 4) (5, 6, 4) (4, 5, 6) (2, 3, 1) (1, 2, 3) Hence, the total height of this stack is 10 + 32 + 4 + 4 + 6 + 1 + 3 = 60. No other combination of boxes produces a height greater than this. Example 2: Input: n = 3 height[] = {1,4,3} width[] = {2,5,4} length[] = {3,6,1} Output: 15 Explanation: One way of placing the boxes is as follows in the bottom to top manner: (Denoting the boxes in (l, w, h) manner) (5, 6, 4) (4, 5, 6) (3, 4, 1), (2, 3, 1) (1, 2, 3). Hence, the total height of this stack is 4 + 6 + 1 + 1 + 3 = 15 No other combination of boxes produces a height greater than this. Your Task: You don't need to read input or print anything. Your task is to complete the function maxHeight() which takes three arrays height[], width[], length[], and N as a number of boxes and returns the highest possible stack height which could be formed. Expected Time Complexity : O(N*N) Expected Auxiliary Space: O(N) Constraints: 1<= N <=100 1<= l,w,h <=100 0 nrkarlapati1 week ago Very efficient O(n^2) solution, runs in 0.27 s/15s // { Driver Code Starts//Initial Template for Java import java.util.*;import java.lang.*;import java.io.*;class GFG{ public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int T = Integer.parseInt(br.readLine().trim()); while(T-->0) { int n = Integer.parseInt(br.readLine().trim()); String[] s1 = br.readLine().trim().split(" "); int[] height = new int[n]; for(int i = 0; i < n; i++){ height[i] = Integer.parseInt(s1[i]); } String[] s2 = br.readLine().trim().split(" "); int[] width = new int[n]; for(int i = 0; i < n; i++){ width[i] = Integer.parseInt(s2[i]); } String[] s3 = br.readLine().trim().split(" "); int[] length = new int[n]; for(int i = 0; i < n; i++){ length[i] = Integer.parseInt(s3[i]); } Solution obj = new Solution(); System.out.println(obj.maxHeight(height, width, length, n)); } }}// } Driver Code Ends //User function Template for Java class Solution{ public static int maxHeight(int[] height, int[] width, int[] length, int n) { // Code here //width > length Box[] boxes = new Box[3*n]; for(int i=0;i<n;i++){ int w = Math.max(width[i],length[i]); int l = Math.min(width[i],length[i]); boxes[3*i] = new Box(w,l,height[i]); w = Math.max(width[i],height[i]); l = Math.min(width[i],height[i]); boxes[3*i+1] = new Box(w,l,length[i]); w = Math.max(height[i],length[i]); l = Math.min(height[i],length[i]); boxes[3*i+2] = new Box(w,l,width[i]); } Arrays.sort(boxes); int[] msh = new int[3*n]; msh[0] = boxes[0].height; for(int i=1;i<3*n;i++){ msh[i] = boxes[i].height;//Integer.MIN_VALUE; for(int j=0;j<i;j++){ if(boxes[i].width < boxes[j].width && boxes[i].length < boxes[j].length){ msh[i] = Math.max(msh[i] , msh[j]+boxes[i].height); } } } int output = Integer.MIN_VALUE; for(int i=0;i<3*n;i++){ output = Math.max(output,msh[i] ); } // Stream.of(boxes).reduce(Math::max); return output; } static class Box implements Comparable<Box>{ int width; int length; int height; Box(int width, int length, int height){ this.width = width; this.length = length; this.height = height; } @Override public int compareTo(Box other){ return other.width * other.length - width * length; } }} 0 hamidnourashraf1 month ago class Solution: def maxHeight(self, h, w, l, n): rotations = [] for i in range(n): rot = [0]*3 _w = w[i] _l = l[i] _h = h[i] rot[2] = _w rot[1] = min(_l, _h) rot[0] = max(_l, _h) rotations.append(rot) rot = [0]*3 rot[2] = _h rot[1] = min(_l, _w) rot[0] = max(_l, _w) rotations.append(rot) rot = [0]*3 rot[2] = _l rot[1] = min(_h, _w) rot[0] = max(_h, _w) rotations.append(rot) rotations.sort(reverse=True, key=lambda X: X[0]*X[1]) n = n*3 mh = [0]* n for i in range(n): mh[i] = rotations[i][2] for i in range(1, n): for j in range(0, i): if rotations[i][0] < rotations[j][0] and rotations[i][1] < rotations[j][1]: if mh[i] < mh[j] + rotations[i][2]: mh[i] = mh[j] + rotations[i][2] return max(mh) +1 kuldeepy104591 month ago public: /*The function takes an array of heights, width and length as its 3 arguments where each index i value determines the height, width, length of the ith box. Here n is the total no of boxes.*/ struct box{ int l,r,h; void setBox(int a,int b,int c){ l=a; r=b; h=c; } };// bool cmp(box &a, box& b){// return (a.l*a.r)<(b.l*b.r);// } int maxHeight(int h[],int w[],int l[],int n) { //Your code here box b[3*n];int j=0; for(int i=0;i<n;i++){ b[j++].setBox(min(h[i],w[i]),max(h[i],w[i]),l[i]); b[j++].setBox(min(l[i],w[i]),max(l[i],w[i]),h[i]); b[j++].setBox(min(h[i],l[i]),max(h[i],l[i]),w[i]); } n=n*3; sort(b,b+n,[&](box &a,const box&b){ return (a.l*a.r)>(b.l*b.r);}); int res[n]; for(int i=0;i<n;i++){ res[i]=b[i].h; } for(int i=1;i<n;i++){ for(int j=i-1;j>=0;j--){ if(b[i].l<b[j].l&&b[i].r<b[j].r&&res[i] < res[j] + b[i].h){ res[i]= res[j]+b[i].h; } } } int mx = -1; for(int i=0;i<n;i++){ mx=max(mx,res[i]); } return mx; } 0 geminicode2 months ago Must be in Hard !! here is my python solution. def maxHeight(self,height, width, length, n): #Code here arr = [[0,0,0] for i in range(3*n)] index = 0 #generate all 3*n combinations for i in range(n): arr[index][0] = height[i] arr[index][1] = max(width[i],length[i]) arr[index][2] = min(width[i],length[i]) index+=1 arr[index][0] = width[i] arr[index][1] = max(length[i],height[i]) arr[index][2] = min(length[i],height[i]) index+=1 arr[index][0] = length[i] arr[index][1] = max(width[i],height[i]) arr[index][2] = min(width[i],height[i]) index+=1 arr.sort(key = lambda x:x[1]*x[2],reverse = True) #print(arr) dp = [0 for i in range(3*n)] for i in range(3*n): dp[i] = arr[i][0] #print(dp) #print(arr) for i in range(1,3*n): for j in range(i): if arr[i][1] < arr[j][1] and arr[i][2] < arr[j][2] and \ dp[j]+arr[i][0] > dp[i]: dp[i] = dp[j] + arr[i][0] #print(dp) return max(dp) 0 0166621m2 months ago C++ code using longest increasing approach class box{ public: int l,r,h; void setBox(int a,int b,int c) { l=a; r=b; h=c; } void print() { cout<<l<<" "<<r<<" "<<h<<endl; } }; bool cmp(box a,box b) { return (a.l * a.r) < (b.l * b.r); } class Solution{ public: /*The function takes an array of heights, width and length as its 3 arguments where each index i value determines the height, width, length of the ith box. Here n is the total no of boxes.*/ int maxHeight(int h[],int w[],int l[],int n) { //Your code here box b[3*n];int j=0; for(int i=0;i<n;i++) { b[j++].setBox(min(h[i],w[i]),max(h[i],w[i]),l[i]); b[j++].setBox(min(w[i],l[i]),max(w[i],l[i]),h[i]); b[j++].setBox(min(l[i],h[i]),max(l[i],h[i]),w[i]); } n=n*3; sort(b,b+n,cmp); // for(int i=0;i<n;i++) // { // b[i].print(); // } int res[n]; for(int i=0;i<n;i++) { res[i] = b[i].h; } int m =-1; for(int i=1;i<n;i++) { for(int j=0;j<i;j++) { if(b[i].l > b[j].l && b[i].r > b[j].r && res[j] + b[i].h > res[i]) res[i] = res[j] + b[i].h; } m = max(res[i],m); } return m; } }; +1 bikrambiswas0436 months ago vector<array<int,3>>box(3*n);int k=0;for(int i=0;i<n;i++){ int arr[3]={length[i],width[i],height[i]}; sort(arr,arr+3); box[k++]={arr[0],arr[1],arr[2]}; box[k++]={arr[1],arr[2],arr[0]}; box[k++]={arr[0],arr[2],arr[1]};}sort(box.begin(),box.end(),[&](const array<int,3>&a,const array<int,3>&b){ return a[0]*a[1]<b[0]*b[1];}); vector<int>dp(3*n);int maxi=INT_MIN;for(int i=0;i<3*n;i++){ dp[i]=box[i][2]; for(int j=i-1;j>=0;j--){ if(box[j][0]<box[i][0]&&box[j][1]<box[i][1]){ dp[i]=max(dp[i],dp[j]+box[i][2]); } } maxi=max(maxi,dp[i]);}return maxi; +2 abhinavsingh26 months ago 23 24 56 9 for this input expected output is 15. Can anyone tell me. how? +3 rainx6 months ago C++ CODE //STRUCTURE FOR BOX, EMPTY CONSTRUCTOR USED FOR ARRAY FORMATION struct Box{ int l; int w; int h; Box(){} Box(int l, int w, int h){ this->l=l; this->w=w; this->h=h; } }; //comparator function for sorting bool cmp(Box &A, Box &B){ return A.l*A.w > B.l*B.w; } int maxHeight(int height[],int width[],int length[],int n) { Box rot[3*n]; int index=0; n=3*n; //ALL ROTATIONS for(int i=0;i<n;i++){ rot[index++]=Box(max(length[i],width[i]),min(length[i],width[i]),height[i]); rot[index++]=Box(max(height[i],length[i]),min(height[i],length[i]),width[i]); rot[index++]=Box(max(height[i],width[i]),min(height[i],width[i]),length[i]); } sort(rot,rot+n,cmp); //sorting using comparator function int msh[n]; for (int i=0;i<n;i++){ msh[i] = rot[i].h; //filling the array with curr heights } for (int i=1;i<n;i++){ for (int j=0;j<i;j++){ if(rot[i].w < rot[j].w && rot[i].l < rot[j].l){ msh[i]=max(msh[i], msh[j]+rot[i].h); } } } int mx = -1; for (int i=0;i<n;i++){ mx=max(mx,msh[i]); } return mx; } HAPPY CODING :)) 0 Bayabongo8 months ago Bayabongo [Python 3] https://uploads.disquscdn.c... 0 delectable_boomer8 months ago delectable_boomer We can also sort based on width and length because at the end you want to place box i on box j if box[j].width > box[i].width and same for length. https://ideone.com/tkHhi2 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": 849, "s": 238, "text": "You are given a set of N types of rectangular 3-D boxes, where the ith box has height h, width w and length l. You task is to create a stack of boxes which is as tall as possible, but you can only stack a box on top of another box if the dimensions of the 2-D base of the lower box are each strictly larger than those of the 2-D base of the higher box. Of course, you can rotate a box so that any side functions as its base.It is also allowable to use multiple instances of the same type of box. You task is to complete the function maxHeight which returns the height of the highest possible stack so formed.\n " }, { "code": null, "e": 1087, "s": 849, "text": "Note: \nBase of the lower box should be strictly larger than that of the new box we're going to place. This is in terms of both length and width, not just in terms of area. So, two boxes with same base cannot be placed one over the other." }, { "code": null, "e": 1100, "s": 1089, "text": "Example 1:" }, { "code": null, "e": 1535, "s": 1100, "text": "Input:\nn = 4\nheight[] = {4,1,4,10}\nwidth[] = {6,2,5,12}\nlength[] = {7,3,6,32}\nOutput: 60\nExplanation: One way of placing the boxes is\nas follows in the bottom to top manner:\n(Denoting the boxes in (l, w, h) manner)\n(12, 32, 10) (10, 12, 32) (6, 7, 4) \n(5, 6, 4) (4, 5, 6) (2, 3, 1) (1, 2, 3)\nHence, the total height of this stack is\n10 + 32 + 4 + 4 + 6 + 1 + 3 = 60.\nNo other combination of boxes produces a\nheight greater than this.\n" }, { "code": null, "e": 1546, "s": 1535, "text": "Example 2:" }, { "code": null, "e": 1937, "s": 1546, "text": "Input:\nn = 3\nheight[] = {1,4,3}\nwidth[] = {2,5,4}\nlength[] = {3,6,1}\nOutput: 15\nExplanation: One way of placing the boxes is\nas follows in the bottom to top manner:\n(Denoting the boxes in (l, w, h) manner)\n(5, 6, 4) (4, 5, 6) (3, 4, 1), (2, 3, 1) \n(1, 2, 3).\nHence, the total height of this stack is\n4 + 6 + 1 + 1 + 3 = 15\nNo other combination of boxes produces a\nheight greater than this.\n" }, { "code": null, "e": 2196, "s": 1937, "text": "Your Task:\nYou don't need to read input or print anything. Your task is to complete the function maxHeight() which takes three arrays height[], width[], length[], and N as a number of boxes and returns the highest possible stack height which could be formed." }, { "code": null, "e": 2262, "s": 2196, "text": "\nExpected Time Complexity : O(N*N)\nExpected Auxiliary Space: O(N)" }, { "code": null, "e": 2304, "s": 2262, "text": "\nConstraints:\n1<= N <=100\n1<= l,w,h <=100" }, { "code": null, "e": 2306, "s": 2304, "text": "0" }, { "code": null, "e": 2328, "s": 2306, "text": "nrkarlapati1 week ago" }, { "code": null, "e": 2379, "s": 2328, "text": "Very efficient O(n^2) solution, runs in 0.27 s/15s" }, { "code": null, "e": 2432, "s": 2381, "text": "// { Driver Code Starts//Initial Template for Java" }, { "code": null, "e": 3510, "s": 2432, "text": "import java.util.*;import java.lang.*;import java.io.*;class GFG{ public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int T = Integer.parseInt(br.readLine().trim()); while(T-->0) { int n = Integer.parseInt(br.readLine().trim()); String[] s1 = br.readLine().trim().split(\" \"); int[] height = new int[n]; for(int i = 0; i < n; i++){ height[i] = Integer.parseInt(s1[i]); } String[] s2 = br.readLine().trim().split(\" \"); int[] width = new int[n]; for(int i = 0; i < n; i++){ width[i] = Integer.parseInt(s2[i]); } String[] s3 = br.readLine().trim().split(\" \"); int[] length = new int[n]; for(int i = 0; i < n; i++){ length[i] = Integer.parseInt(s3[i]); } Solution obj = new Solution(); System.out.println(obj.maxHeight(height, width, length, n)); } }}// } Driver Code Ends" }, { "code": null, "e": 3544, "s": 3510, "text": "//User function Template for Java" }, { "code": null, "e": 5234, "s": 3544, "text": "class Solution{ public static int maxHeight(int[] height, int[] width, int[] length, int n) { // Code here //width > length Box[] boxes = new Box[3*n]; for(int i=0;i<n;i++){ int w = Math.max(width[i],length[i]); int l = Math.min(width[i],length[i]); boxes[3*i] = new Box(w,l,height[i]); w = Math.max(width[i],height[i]); l = Math.min(width[i],height[i]); boxes[3*i+1] = new Box(w,l,length[i]); w = Math.max(height[i],length[i]); l = Math.min(height[i],length[i]); boxes[3*i+2] = new Box(w,l,width[i]); } Arrays.sort(boxes); int[] msh = new int[3*n]; msh[0] = boxes[0].height; for(int i=1;i<3*n;i++){ msh[i] = boxes[i].height;//Integer.MIN_VALUE; for(int j=0;j<i;j++){ if(boxes[i].width < boxes[j].width && boxes[i].length < boxes[j].length){ msh[i] = Math.max(msh[i] , msh[j]+boxes[i].height); } } } int output = Integer.MIN_VALUE; for(int i=0;i<3*n;i++){ output = Math.max(output,msh[i] ); } // Stream.of(boxes).reduce(Math::max); return output; } static class Box implements Comparable<Box>{ int width; int length; int height; Box(int width, int length, int height){ this.width = width; this.length = length; this.height = height; } @Override public int compareTo(Box other){ return other.width * other.length - width * length; } }}" }, { "code": null, "e": 5236, "s": 5234, "text": "0" }, { "code": null, "e": 5263, "s": 5236, "text": "hamidnourashraf1 month ago" }, { "code": null, "e": 6364, "s": 5263, "text": "class Solution:\n def maxHeight(self, h, w, l, n):\n rotations = []\n for i in range(n):\n rot = [0]*3\n _w = w[i]\n _l = l[i]\n _h = h[i]\n rot[2] = _w\n rot[1] = min(_l, _h)\n rot[0] = max(_l, _h)\n rotations.append(rot)\n rot = [0]*3\n rot[2] = _h\n rot[1] = min(_l, _w)\n rot[0] = max(_l, _w)\n rotations.append(rot)\n rot = [0]*3\n rot[2] = _l\n rot[1] = min(_h, _w)\n rot[0] = max(_h, _w)\n rotations.append(rot)\n rotations.sort(reverse=True, key=lambda X: X[0]*X[1])\n n = n*3\n mh = [0]* n\n for i in range(n):\n mh[i] = rotations[i][2]\n \n for i in range(1, n):\n for j in range(0, i):\n if rotations[i][0] < rotations[j][0] and rotations[i][1] < rotations[j][1]:\n if mh[i] < mh[j] + rotations[i][2]:\n mh[i] = mh[j] + rotations[i][2]\n \n return max(mh)" }, { "code": null, "e": 6367, "s": 6364, "text": "+1" }, { "code": null, "e": 6392, "s": 6367, "text": "kuldeepy104591 month ago" }, { "code": null, "e": 7623, "s": 6392, "text": "public: /*The function takes an array of heights, width and length as its 3 arguments where each index i value determines the height, width, length of the ith box. Here n is the total no of boxes.*/ struct box{ int l,r,h; void setBox(int a,int b,int c){ l=a; r=b; h=c; } };// bool cmp(box &a, box& b){// return (a.l*a.r)<(b.l*b.r);// } int maxHeight(int h[],int w[],int l[],int n) { //Your code here box b[3*n];int j=0; for(int i=0;i<n;i++){ b[j++].setBox(min(h[i],w[i]),max(h[i],w[i]),l[i]); b[j++].setBox(min(l[i],w[i]),max(l[i],w[i]),h[i]); b[j++].setBox(min(h[i],l[i]),max(h[i],l[i]),w[i]); } n=n*3; sort(b,b+n,[&](box &a,const box&b){ return (a.l*a.r)>(b.l*b.r);}); int res[n]; for(int i=0;i<n;i++){ res[i]=b[i].h; } for(int i=1;i<n;i++){ for(int j=i-1;j>=0;j--){ if(b[i].l<b[j].l&&b[i].r<b[j].r&&res[i] < res[j] + b[i].h){ res[i]= res[j]+b[i].h; } } } int mx = -1; for(int i=0;i<n;i++){ mx=max(mx,res[i]); } return mx;" }, { "code": null, "e": 7628, "s": 7623, "text": " }" }, { "code": null, "e": 7630, "s": 7628, "text": "0" }, { "code": null, "e": 7653, "s": 7630, "text": "geminicode2 months ago" }, { "code": null, "e": 7700, "s": 7653, "text": "Must be in Hard !! here is my python solution." }, { "code": null, "e": 8882, "s": 7700, "text": "def maxHeight(self,height, width, length, n):\n #Code here\n \n arr = [[0,0,0] for i in range(3*n)]\n index = 0\n #generate all 3*n combinations\n for i in range(n):\n arr[index][0] = height[i]\n arr[index][1] = max(width[i],length[i])\n arr[index][2] = min(width[i],length[i])\n index+=1\n \n arr[index][0] = width[i]\n arr[index][1] = max(length[i],height[i])\n arr[index][2] = min(length[i],height[i])\n index+=1\n arr[index][0] = length[i]\n arr[index][1] = max(width[i],height[i])\n arr[index][2] = min(width[i],height[i])\n index+=1\n arr.sort(key = lambda x:x[1]*x[2],reverse = True)\n #print(arr)\n dp = [0 for i in range(3*n)]\n for i in range(3*n):\n dp[i] = arr[i][0]\n #print(dp)\n #print(arr)\n for i in range(1,3*n):\n for j in range(i):\n if arr[i][1] < arr[j][1] and arr[i][2] < arr[j][2] and \\\n dp[j]+arr[i][0] > dp[i]:\n dp[i] = dp[j] + arr[i][0]\n #print(dp)\n return max(dp)" }, { "code": null, "e": 8884, "s": 8882, "text": "0" }, { "code": null, "e": 8905, "s": 8884, "text": "0166621m2 months ago" }, { "code": null, "e": 8948, "s": 8905, "text": "C++ code using longest increasing approach" }, { "code": null, "e": 10365, "s": 8948, "text": "class box{\n public:\n int l,r,h;\n void setBox(int a,int b,int c)\n {\n l=a;\n r=b;\n h=c;\n }\n void print()\n {\n cout<<l<<\" \"<<r<<\" \"<<h<<endl;\n }\n};\nbool cmp(box a,box b)\n{\n return (a.l * a.r) < (b.l * b.r);\n}\n\nclass Solution{\n public:\n /*The function takes an array of heights, width and \n length as its 3 arguments where each index i value \n determines the height, width, length of the ith box. \n Here n is the total no of boxes.*/\n int maxHeight(int h[],int w[],int l[],int n)\n {\n //Your code here\n box b[3*n];int j=0;\n for(int i=0;i<n;i++)\n {\n b[j++].setBox(min(h[i],w[i]),max(h[i],w[i]),l[i]);\n b[j++].setBox(min(w[i],l[i]),max(w[i],l[i]),h[i]);\n b[j++].setBox(min(l[i],h[i]),max(l[i],h[i]),w[i]);\n }\n n=n*3;\n sort(b,b+n,cmp);\n \n // for(int i=0;i<n;i++)\n // {\n // b[i].print();\n // }\n \n int res[n];\n for(int i=0;i<n;i++)\n {\n res[i] = b[i].h;\n }\n \n int m =-1;\n for(int i=1;i<n;i++)\n {\n for(int j=0;j<i;j++)\n {\n if(b[i].l > b[j].l && b[i].r > b[j].r && res[j] + b[i].h > res[i])\n res[i] = res[j] + b[i].h;\n }\n m = max(res[i],m);\n }\n \n return m;\n }\n};" }, { "code": null, "e": 10368, "s": 10365, "text": "+1" }, { "code": null, "e": 10396, "s": 10368, "text": "bikrambiswas0436 months ago" }, { "code": null, "e": 10946, "s": 10396, "text": " vector<array<int,3>>box(3*n);int k=0;for(int i=0;i<n;i++){ int arr[3]={length[i],width[i],height[i]}; sort(arr,arr+3); box[k++]={arr[0],arr[1],arr[2]}; box[k++]={arr[1],arr[2],arr[0]}; box[k++]={arr[0],arr[2],arr[1]};}sort(box.begin(),box.end(),[&](const array<int,3>&a,const array<int,3>&b){ return a[0]*a[1]<b[0]*b[1];}); vector<int>dp(3*n);int maxi=INT_MIN;for(int i=0;i<3*n;i++){ dp[i]=box[i][2]; for(int j=i-1;j>=0;j--){ if(box[j][0]<box[i][0]&&box[j][1]<box[i][1]){ dp[i]=max(dp[i],dp[j]+box[i][2]); } } maxi=max(maxi,dp[i]);}return maxi;" }, { "code": null, "e": 10949, "s": 10946, "text": "+2" }, { "code": null, "e": 10975, "s": 10949, "text": "abhinavsingh26 months ago" }, { "code": null, "e": 10986, "s": 10975, "text": "23 24 56 9" }, { "code": null, "e": 11024, "s": 10986, "text": "for this input expected output is 15." }, { "code": null, "e": 11049, "s": 11024, "text": "Can anyone tell me. how?" }, { "code": null, "e": 11052, "s": 11049, "text": "+3" }, { "code": null, "e": 11070, "s": 11052, "text": "rainx6 months ago" }, { "code": null, "e": 11079, "s": 11070, "text": "C++ CODE" }, { "code": null, "e": 11372, "s": 11083, "text": "//STRUCTURE FOR BOX, EMPTY CONSTRUCTOR USED FOR ARRAY FORMATION\n\nstruct Box{\n int l;\n int w;\n int h;\n Box(){}\n Box(int l, int w, int h){\n this->l=l;\n this->w=w;\n this->h=h; \n }\n};" }, { "code": null, "e": 11465, "s": 11372, "text": "//comparator function for sorting\n\nbool cmp(Box &A, Box &B){\n return A.l*A.w > B.l*B.w;\n}" }, { "code": null, "e": 11584, "s": 11465, "text": "int maxHeight(int height[],int width[],int length[],int n) {\n Box rot[3*n];\n int index=0;\n n=3*n;" }, { "code": null, "e": 11952, "s": 11584, "text": "//ALL ROTATIONS\n\nfor(int i=0;i<n;i++){\n rot[index++]=Box(max(length[i],width[i]),min(length[i],width[i]),height[i]);\n rot[index++]=Box(max(height[i],length[i]),min(height[i],length[i]),width[i]);\n rot[index++]=Box(max(height[i],width[i]),min(height[i],width[i]),length[i]);\n}\n\nsort(rot,rot+n,cmp); //sorting using comparator function" }, { "code": null, "e": 12051, "s": 11952, "text": "int msh[n];\nfor (int i=0;i<n;i++){\n msh[i] = rot[i].h; //filling the array with curr heights\n}" }, { "code": null, "e": 12305, "s": 12051, "text": "for (int i=1;i<n;i++){\n for (int j=0;j<i;j++){\n if(rot[i].w < rot[j].w && rot[i].l < rot[j].l){\n msh[i]=max(msh[i], msh[j]+rot[i].h);\n }\n }\n}\n\n\nint mx = -1;\nfor (int i=0;i<n;i++){\n mx=max(mx,msh[i]);\n}\n return mx;\n}" }, { "code": null, "e": 12322, "s": 12305, "text": "HAPPY CODING :))" }, { "code": null, "e": 12330, "s": 12328, "text": "0" }, { "code": null, "e": 12352, "s": 12330, "text": "Bayabongo8 months ago" }, { "code": null, "e": 12362, "s": 12352, "text": "Bayabongo" }, { "code": null, "e": 12405, "s": 12362, "text": "[Python 3] https://uploads.disquscdn.c..." }, { "code": null, "e": 12407, "s": 12405, "text": "0" }, { "code": null, "e": 12437, "s": 12407, "text": "delectable_boomer8 months ago" }, { "code": null, "e": 12455, "s": 12437, "text": "delectable_boomer" }, { "code": null, "e": 12628, "s": 12455, "text": "We can also sort based on width and length because at the end you want to place box i on box j if box[j].width > box[i].width and same for length. https://ideone.com/tkHhi2" }, { "code": null, "e": 12774, "s": 12628, "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": 12810, "s": 12774, "text": " Login to access your submissions. " }, { "code": null, "e": 12820, "s": 12810, "text": "\nProblem\n" }, { "code": null, "e": 12830, "s": 12820, "text": "\nContest\n" }, { "code": null, "e": 12893, "s": 12830, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 13041, "s": 12893, "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": 13249, "s": 13041, "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": 13355, "s": 13249, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
XSLT <value-of>
<xsl:value-of> tag puts the value of the selected node as per XPath expression, as text. Following is the syntax declaration of <xsl:value-of> element. <xsl:value-of select = Expression disable-output-escaping = "yes" | "no" > </xsl:value-of> Select XPath Expression to be evaluated in current context. disable-outputescaping Default-"no". If "yes", output text will not escape xml characters from text. Parent elements xsl:attribute, xsl:comment, xsl:copy, xsl:element, xsl:fallback, xsl:for-each, xsl:if, xsl:message, xsl:otherwise, xsl:param, xsl:processing instruction, xsl:template, xsl:variable, xsl:when, xsl:with-param, output elements Child elements None This example creates a table of <student> element with its attribute rollno and its child <firstname>, <lastname>, <nickname>, and <marks>. students.xml <?xml version = "1.0"?> <?xml-stylesheet type = "text/xsl" href = "students.xsl"?> <class> <student rollno = "393"> <firstname>Dinkar</firstname> <lastname>Kad</lastname> <nickname>Dinkar</nickname> <marks>85</marks> </student> <student rollno = "493"> <firstname>Vaneet</firstname> <lastname>Gupta</lastname> <nickname>Vinni</nickname> <marks>95</marks> </student> <student rollno = "593"> <firstname>Jasvir</firstname> <lastname>Singh</lastname> <nickname>Jazz</nickname> <marks>90</marks> </student> </class> students.xsl <?xml version = "1.0" encoding = "UTF-8"?> <xsl:stylesheet version = "1.0" xmlns:xsl = "http://www.w3.org/1999/XSL/Transform"> <xsl:template match = "/"> <html> <body> <h2>Students</h2> <table border = "1"> <tr bgcolor = "#9acd32"> <th>Roll No</th> <th>First Name</th> <th>Last Name</th> <th>Nick Name</th> <th>Marks</th> </tr> <xsl:for-each select = "class/student"> <tr> <td><xsl:value-of select = "@rollno"/></td> <td><xsl:value-of select = "firstname"/></td> <td><xsl:value-of select = "lastname"/></td> <td><xsl:value-of select = "nickname"/></td> <td><xsl:value-of select = "marks"/></td> </tr> </xsl:for-each> </table> </body> </html> </xsl:template> </xsl:stylesheet> Print Add Notes Bookmark this page
[ { "code": null, "e": 1848, "s": 1759, "text": "<xsl:value-of> tag puts the value of the selected node as per XPath expression, as text." }, { "code": null, "e": 1911, "s": 1848, "text": "Following is the syntax declaration of <xsl:value-of> element." }, { "code": null, "e": 2009, "s": 1911, "text": "<xsl:value-of\n select = Expression\n disable-output-escaping = \"yes\" | \"no\" >\n</xsl:value-of>\n" }, { "code": null, "e": 2016, "s": 2009, "text": "Select" }, { "code": null, "e": 2069, "s": 2016, "text": "XPath Expression to be evaluated in current context." }, { "code": null, "e": 2092, "s": 2069, "text": "disable-outputescaping" }, { "code": null, "e": 2170, "s": 2092, "text": "Default-\"no\". If \"yes\", output text will not escape xml characters from text." }, { "code": null, "e": 2186, "s": 2170, "text": "Parent elements" }, { "code": null, "e": 2410, "s": 2186, "text": "xsl:attribute, xsl:comment, xsl:copy, xsl:element, xsl:fallback, xsl:for-each, xsl:if, xsl:message, xsl:otherwise, xsl:param, xsl:processing instruction, xsl:template, xsl:variable, xsl:when, xsl:with-param, output elements" }, { "code": null, "e": 2425, "s": 2410, "text": "Child elements" }, { "code": null, "e": 2430, "s": 2425, "text": "None" }, { "code": null, "e": 2570, "s": 2430, "text": "This example creates a table of <student> element with its attribute rollno and its child <firstname>, <lastname>, <nickname>, and <marks>." }, { "code": null, "e": 2583, "s": 2570, "text": "students.xml" }, { "code": null, "e": 3206, "s": 2583, "text": "<?xml version = \"1.0\"?> \n<?xml-stylesheet type = \"text/xsl\" href = \"students.xsl\"?> \n<class> \n <student rollno = \"393\"> \n <firstname>Dinkar</firstname> \n <lastname>Kad</lastname> \n <nickname>Dinkar</nickname> \n <marks>85</marks> \n </student> \n <student rollno = \"493\"> \n <firstname>Vaneet</firstname> \n <lastname>Gupta</lastname> \n <nickname>Vinni</nickname> \n <marks>95</marks> \n </student> \n <student rollno = \"593\"> \n <firstname>Jasvir</firstname> \n <lastname>Singh</lastname> \n <nickname>Jazz</nickname> \n <marks>90</marks> \n </student> \n</class>" }, { "code": null, "e": 3219, "s": 3206, "text": "students.xsl" }, { "code": null, "e": 4310, "s": 3219, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?> \n <xsl:stylesheet version = \"1.0\" \n xmlns:xsl = \"http://www.w3.org/1999/XSL/Transform\">\n\t\t\n <xsl:template match = \"/\"> \n <html> \n <body> \n <h2>Students</h2> \n <table border = \"1\"> \n <tr bgcolor = \"#9acd32\"> \n <th>Roll No</th> \n <th>First Name</th> \n <th>Last Name</th> \n <th>Nick Name</th> \n <th>Marks</th> \n </tr> \n\t\t\t\t\t\n <xsl:for-each select = \"class/student\"> \n <tr> \n <td><xsl:value-of select = \"@rollno\"/></td> \n <td><xsl:value-of select = \"firstname\"/></td> \n <td><xsl:value-of select = \"lastname\"/></td> \n <td><xsl:value-of select = \"nickname\"/></td> \n <td><xsl:value-of select = \"marks\"/></td> \n </tr> \n </xsl:for-each> \n\t\t\t\t\t\n </table> \n </body> \n </html> \n </xsl:template> \n</xsl:stylesheet>" }, { "code": null, "e": 4317, "s": 4310, "text": " Print" }, { "code": null, "e": 4328, "s": 4317, "text": " Add Notes" } ]
How to Zoom an Image on Mouse Hover using CSS ? - GeeksforGeeks
30 Jul, 2021 The image zoom effect is used to apply zoom over an image on mouse hover or click. This type of effect is mostly used in portfolio sites. It is useful in situations where we want to show the user details on the image. There are two possible ways to create a mouse hover effect. Using JavaScript Using CSS In this article, we will see how to zoom an image on hover using CSS. This article contains two sections of code. The first section contains the HTML code and the second section contains CSS code. HTML Code: In this section, we will use HTML to create a basic structure of Image Zoom on hover effect. <!DOCTYPE html><html> <head> <meta charset="UTF-8" /> <meta name="viewport" content= "width=device-width, initial-scale=1.0" /> <title> How to Zoom an Image on Mouse Hover using CSS? </title></head> <body> <div class="geeks"> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20200403151026/adblur_gfg.png" alt="Geeks Image" /> </div></body> </html> CSS Code: In this section, we will use some CSS property to Zoom an Image on mouse hover. To create a zoom effect, we will use transition and transform property. <style> .geeks { width: 300px; height: 300px; overflow: hidden; margin: 0 auto; } .geeks img { width: 100%; transition: 0.5s all ease-in-out; } .geeks:hover img { transform: scale(1.5); }</style> Complete Code: In this section, we will combine the above two sections to create an Image Zoom effect on mouse hover using HTML and CSS. Example: <!DOCTYPE html><html> <head> <meta charset="UTF-8" /> <meta name="viewport" content= "width=device-width, initial-scale=1.0" /> <title> How to Zoom an Image on Mouse Hover using CSS? </title> <style> .geeks { width: 300px; height: 300px; overflow: hidden; margin: 0 auto; } .geeks img { width: 100%; transition: 0.5s all ease-in-out; } .geeks:hover img { transform: scale(1.5); } </style></head> <body> <div class="geeks"> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20200403151026/adblur_gfg.png" alt="Geeks Image" /> </div></body> </html> Output: HTML is the foundation of webpages, is used for webpage development by structuring websites and web apps.You can learn HTML from the ground up by following this HTML Tutorial and HTML Examples. CSS is the foundation of webpages, is used for webpage development by styling websites and web apps.You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples. Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. CSS-Misc HTML-Misc CSS HTML Web Technologies Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to create footer to stay at the bottom of a Web page? Types of CSS (Cascading Style Sheet) Create a Responsive Navbar using ReactJS Design a web page using HTML and CSS How to position a div at the bottom of its container using CSS? How to set the default value for an HTML <select> element ? How to set input type date in dd-mm-yyyy format using HTML ? Types of CSS (Cascading Style Sheet) Hide or show elements in HTML using display property How to Insert Form Data into Database using PHP ?
[ { "code": null, "e": 24943, "s": 24915, "text": "\n30 Jul, 2021" }, { "code": null, "e": 25161, "s": 24943, "text": "The image zoom effect is used to apply zoom over an image on mouse hover or click. This type of effect is mostly used in portfolio sites. It is useful in situations where we want to show the user details on the image." }, { "code": null, "e": 25221, "s": 25161, "text": "There are two possible ways to create a mouse hover effect." }, { "code": null, "e": 25238, "s": 25221, "text": "Using JavaScript" }, { "code": null, "e": 25248, "s": 25238, "text": "Using CSS" }, { "code": null, "e": 25445, "s": 25248, "text": "In this article, we will see how to zoom an image on hover using CSS. This article contains two sections of code. The first section contains the HTML code and the second section contains CSS code." }, { "code": null, "e": 25549, "s": 25445, "text": "HTML Code: In this section, we will use HTML to create a basic structure of Image Zoom on hover effect." }, { "code": "<!DOCTYPE html><html> <head> <meta charset=\"UTF-8\" /> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\" /> <title> How to Zoom an Image on Mouse Hover using CSS? </title></head> <body> <div class=\"geeks\"> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20200403151026/adblur_gfg.png\" alt=\"Geeks Image\" /> </div></body> </html>", "e": 25984, "s": 25549, "text": null }, { "code": null, "e": 26146, "s": 25984, "text": "CSS Code: In this section, we will use some CSS property to Zoom an Image on mouse hover. To create a zoom effect, we will use transition and transform property." }, { "code": "<style> .geeks { width: 300px; height: 300px; overflow: hidden; margin: 0 auto; } .geeks img { width: 100%; transition: 0.5s all ease-in-out; } .geeks:hover img { transform: scale(1.5); }</style>", "e": 26423, "s": 26146, "text": null }, { "code": null, "e": 26560, "s": 26423, "text": "Complete Code: In this section, we will combine the above two sections to create an Image Zoom effect on mouse hover using HTML and CSS." }, { "code": null, "e": 26569, "s": 26560, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <meta charset=\"UTF-8\" /> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\" /> <title> How to Zoom an Image on Mouse Hover using CSS? </title> <style> .geeks { width: 300px; height: 300px; overflow: hidden; margin: 0 auto; } .geeks img { width: 100%; transition: 0.5s all ease-in-out; } .geeks:hover img { transform: scale(1.5); } </style></head> <body> <div class=\"geeks\"> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20200403151026/adblur_gfg.png\" alt=\"Geeks Image\" /> </div></body> </html>", "e": 27344, "s": 26569, "text": null }, { "code": null, "e": 27352, "s": 27344, "text": "Output:" }, { "code": null, "e": 27546, "s": 27352, "text": "HTML is the foundation of webpages, is used for webpage development by structuring websites and web apps.You can learn HTML from the ground up by following this HTML Tutorial and HTML Examples." }, { "code": null, "e": 27732, "s": 27546, "text": "CSS is the foundation of webpages, is used for webpage development by styling websites and web apps.You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples." }, { "code": null, "e": 27869, "s": 27732, "text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course." }, { "code": null, "e": 27878, "s": 27869, "text": "CSS-Misc" }, { "code": null, "e": 27888, "s": 27878, "text": "HTML-Misc" }, { "code": null, "e": 27892, "s": 27888, "text": "CSS" }, { "code": null, "e": 27897, "s": 27892, "text": "HTML" }, { "code": null, "e": 27914, "s": 27897, "text": "Web Technologies" }, { "code": null, "e": 27941, "s": 27914, "text": "Web technologies Questions" }, { "code": null, "e": 27946, "s": 27941, "text": "HTML" }, { "code": null, "e": 28044, "s": 27946, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28053, "s": 28044, "text": "Comments" }, { "code": null, "e": 28066, "s": 28053, "text": "Old Comments" }, { "code": null, "e": 28124, "s": 28066, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 28161, "s": 28124, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 28202, "s": 28161, "text": "Create a Responsive Navbar using ReactJS" }, { "code": null, "e": 28239, "s": 28202, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 28303, "s": 28239, "text": "How to position a div at the bottom of its container using CSS?" }, { "code": null, "e": 28363, "s": 28303, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 28424, "s": 28363, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 28461, "s": 28424, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 28514, "s": 28461, "text": "Hide or show elements in HTML using display property" } ]
XAML - Window
It is the root window of an XAML application which provides minimize/maximize option, Title bar, border, and close button. It also provides the ability to create, configure, show, and manage the lifetime of windows and dialog boxes. The hierarchical inheritance of Window class is as follows − AllowsTransparency Gets or sets a value that indicates whether a window's client area supports transparency. DialogResult Gets or sets the dialog result value, which is the value that is returned from the ShowDialog method. Icon Gets or sets a window's icon. IsActive Gets a value that indicates whether the window is active. Left Gets or sets the position of the window's left edge, in relation to the desktop. OwnedWindows Gets a collection of windows for which this window is the owner. Owner Gets or sets the Window that owns this Window. ResizeMode Gets or sets the resize mode. RestoreBounds Gets the size and location of a window before being either minimized or maximized. ShowActivated Gets or sets a value that indicates whether a window is activated when first shown. ShowInTaskbar Gets or sets a value that indicates whether the window has a task bar button. SizeToContent Gets or sets a value that indicates whether a window will automatically size itself to fit the size of its content. TaskbarItemInfo Gets or sets the Windows 7 taskbar thumbnail for the Window. Title Gets or sets a window's title. Top Gets or sets the position of the window's top edge, in relation to the desktop. Topmost Gets or sets a value that indicates whether a window appears in the topmost z-order. WindowStartupLocation Gets or sets the position of the window when first shown. WindowState Gets or sets a value that indicates whether a window is restored, minimized, or maximized. WindowStyle Gets or sets a window's border style. Activated Occurs when a window becomes the foreground window. Closed Occurs when the window is about to close. Closing Occurs directly after Close is called, and can be handled to cancel window closure. ContentRendered Occurs after a window's content has been rendered. Deactivated Occurs when a window becomes a background window. LocationChanged Occurs when the window's location changes. SourceInitialized This event is raised to support interoperation with Win32. See HwndSource. StateChanged Occurs when the window's WindowState property changes. Activate Attempts to bring the window to the foreground and activates it. Close Manually closes a Window. DragMove Allows a window to be dragged by a mouse with its left button down over an exposed area of the window's client area. GetWindow Returns a reference to the Window object that hosts the content tree within which the dependency object is located. Hide Makes a window invisible. Show Opens a window and returns without waiting for the newly opened window to close. ShowDialog Opens a window and returns only when the newly opened window is closed. When you create a new WPF project, then by default, the Window control is present. Let’s have a look at the following XAML code which starts from Window Tag and ends with </Window> tag. We have also defined some properties as well for the window. <Window x:Class = "XAMLToolTip.MainWindow" xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml" Title = "MainWindow" Height = "350" Width = "604"> <Grid> <StackPanel Orientation = "Vertical"> <Button Content = "Button with a simple ToolTip." ToolTipService.ToolTip = "Simple ToolTip" Width = "200" Margin = "50" /> <!-- A TextBlock with an offset ToolTip. --> <TextBlock Text = "TextBlock with an offset ToolTip." Width = "200" Margin = "50"> <ToolTipService.ToolTip> <ToolTip Content = "Offset ToolTip." HorizontalOffset = "20" VerticalOffset = "30"/> </ToolTipService.ToolTip> </TextBlock> </StackPanel> </Grid> </Window> When you compile and execute the above code with the mouse entering the Window, it will produce the following output − We recommend you to execute the above example code and experiment with some other properties and events. Print Add Notes Bookmark this page
[ { "code": null, "e": 2217, "s": 1923, "text": "It is the root window of an XAML application which provides minimize/maximize option, Title bar, border, and close button. It also provides the ability to create, configure, show, and manage the lifetime of windows and dialog boxes. The hierarchical inheritance of Window class is as follows −" }, { "code": null, "e": 2236, "s": 2217, "text": "AllowsTransparency" }, { "code": null, "e": 2326, "s": 2236, "text": "Gets or sets a value that indicates whether a window's client area supports transparency." }, { "code": null, "e": 2339, "s": 2326, "text": "DialogResult" }, { "code": null, "e": 2441, "s": 2339, "text": "Gets or sets the dialog result value, which is the value that is returned from the ShowDialog method." }, { "code": null, "e": 2446, "s": 2441, "text": "Icon" }, { "code": null, "e": 2476, "s": 2446, "text": "Gets or sets a window's icon." }, { "code": null, "e": 2485, "s": 2476, "text": "IsActive" }, { "code": null, "e": 2543, "s": 2485, "text": "Gets a value that indicates whether the window is active." }, { "code": null, "e": 2548, "s": 2543, "text": "Left" }, { "code": null, "e": 2629, "s": 2548, "text": "Gets or sets the position of the window's left edge, in relation to the desktop." }, { "code": null, "e": 2642, "s": 2629, "text": "OwnedWindows" }, { "code": null, "e": 2707, "s": 2642, "text": "Gets a collection of windows for which this window is the owner." }, { "code": null, "e": 2713, "s": 2707, "text": "Owner" }, { "code": null, "e": 2760, "s": 2713, "text": "Gets or sets the Window that owns this Window." }, { "code": null, "e": 2771, "s": 2760, "text": "ResizeMode" }, { "code": null, "e": 2801, "s": 2771, "text": "Gets or sets the resize mode." }, { "code": null, "e": 2815, "s": 2801, "text": "RestoreBounds" }, { "code": null, "e": 2898, "s": 2815, "text": "Gets the size and location of a window before being either minimized or maximized." }, { "code": null, "e": 2912, "s": 2898, "text": "ShowActivated" }, { "code": null, "e": 2996, "s": 2912, "text": "Gets or sets a value that indicates whether a window is activated when first shown." }, { "code": null, "e": 3010, "s": 2996, "text": "ShowInTaskbar" }, { "code": null, "e": 3088, "s": 3010, "text": "Gets or sets a value that indicates whether the window has a task bar button." }, { "code": null, "e": 3102, "s": 3088, "text": "SizeToContent" }, { "code": null, "e": 3218, "s": 3102, "text": "Gets or sets a value that indicates whether a window will automatically size itself to fit the size of its content." }, { "code": null, "e": 3234, "s": 3218, "text": "TaskbarItemInfo" }, { "code": null, "e": 3295, "s": 3234, "text": "Gets or sets the Windows 7 taskbar thumbnail for the Window." }, { "code": null, "e": 3301, "s": 3295, "text": "Title" }, { "code": null, "e": 3332, "s": 3301, "text": "Gets or sets a window's title." }, { "code": null, "e": 3336, "s": 3332, "text": "Top" }, { "code": null, "e": 3416, "s": 3336, "text": "Gets or sets the position of the window's top edge, in relation to the desktop." }, { "code": null, "e": 3424, "s": 3416, "text": "Topmost" }, { "code": null, "e": 3509, "s": 3424, "text": "Gets or sets a value that indicates whether a window appears in the topmost z-order." }, { "code": null, "e": 3531, "s": 3509, "text": "WindowStartupLocation" }, { "code": null, "e": 3589, "s": 3531, "text": "Gets or sets the position of the window when first shown." }, { "code": null, "e": 3601, "s": 3589, "text": "WindowState" }, { "code": null, "e": 3692, "s": 3601, "text": "Gets or sets a value that indicates whether a window is restored, minimized, or maximized." }, { "code": null, "e": 3704, "s": 3692, "text": "WindowStyle" }, { "code": null, "e": 3742, "s": 3704, "text": "Gets or sets a window's border style." }, { "code": null, "e": 3752, "s": 3742, "text": "Activated" }, { "code": null, "e": 3804, "s": 3752, "text": "Occurs when a window becomes the foreground window." }, { "code": null, "e": 3811, "s": 3804, "text": "Closed" }, { "code": null, "e": 3853, "s": 3811, "text": "Occurs when the window is about to close." }, { "code": null, "e": 3861, "s": 3853, "text": "Closing" }, { "code": null, "e": 3945, "s": 3861, "text": "Occurs directly after Close is called, and can be handled to cancel window closure." }, { "code": null, "e": 3961, "s": 3945, "text": "ContentRendered" }, { "code": null, "e": 4012, "s": 3961, "text": "Occurs after a window's content has been rendered." }, { "code": null, "e": 4024, "s": 4012, "text": "Deactivated" }, { "code": null, "e": 4074, "s": 4024, "text": "Occurs when a window becomes a background window." }, { "code": null, "e": 4090, "s": 4074, "text": "LocationChanged" }, { "code": null, "e": 4133, "s": 4090, "text": "Occurs when the window's location changes." }, { "code": null, "e": 4151, "s": 4133, "text": "SourceInitialized" }, { "code": null, "e": 4226, "s": 4151, "text": "This event is raised to support interoperation with Win32. See HwndSource." }, { "code": null, "e": 4239, "s": 4226, "text": "StateChanged" }, { "code": null, "e": 4294, "s": 4239, "text": "Occurs when the window's WindowState property changes." }, { "code": null, "e": 4303, "s": 4294, "text": "Activate" }, { "code": null, "e": 4368, "s": 4303, "text": "Attempts to bring the window to the foreground and activates it." }, { "code": null, "e": 4374, "s": 4368, "text": "Close" }, { "code": null, "e": 4400, "s": 4374, "text": "Manually closes a Window." }, { "code": null, "e": 4409, "s": 4400, "text": "DragMove" }, { "code": null, "e": 4526, "s": 4409, "text": "Allows a window to be dragged by a mouse with its left button down over an exposed area of the window's client area." }, { "code": null, "e": 4536, "s": 4526, "text": "GetWindow" }, { "code": null, "e": 4652, "s": 4536, "text": "Returns a reference to the Window object that hosts the content tree within which the dependency object is located." }, { "code": null, "e": 4657, "s": 4652, "text": "Hide" }, { "code": null, "e": 4683, "s": 4657, "text": "Makes a window invisible." }, { "code": null, "e": 4688, "s": 4683, "text": "Show" }, { "code": null, "e": 4769, "s": 4688, "text": "Opens a window and returns without waiting for the newly opened window to close." }, { "code": null, "e": 4780, "s": 4769, "text": "ShowDialog" }, { "code": null, "e": 4852, "s": 4780, "text": "Opens a window and returns only when the newly opened window is closed." }, { "code": null, "e": 5099, "s": 4852, "text": "When you create a new WPF project, then by default, the Window control is present. Let’s have a look at the following XAML code which starts from Window Tag and ends with </Window> tag. We have also defined some properties as well for the window." }, { "code": null, "e": 5941, "s": 5099, "text": "<Window x:Class = \"XAMLToolTip.MainWindow\" \n xmlns = \"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x = \"http://schemas.microsoft.com/winfx/2006/xaml\" \n Title = \"MainWindow\" Height = \"350\" Width = \"604\">\n\t\n <Grid> \n <StackPanel Orientation = \"Vertical\"> \n <Button Content = \"Button with a simple ToolTip.\"\n ToolTipService.ToolTip = \"Simple ToolTip\" \n Width = \"200\" Margin = \"50\" />\n\t\t\t\t\n <!-- A TextBlock with an offset ToolTip. -->\n <TextBlock Text = \"TextBlock with an offset ToolTip.\" Width = \"200\" Margin = \"50\"> \n <ToolTipService.ToolTip> \n <ToolTip Content = \"Offset ToolTip.\" HorizontalOffset = \"20\" VerticalOffset = \"30\"/> \n </ToolTipService.ToolTip> \n </TextBlock>\n </StackPanel> \n </Grid> \n\t\n</Window>" }, { "code": null, "e": 6060, "s": 5941, "text": "When you compile and execute the above code with the mouse entering the Window, it will produce the following output −" }, { "code": null, "e": 6165, "s": 6060, "text": "We recommend you to execute the above example code and experiment with some other properties and events." }, { "code": null, "e": 6172, "s": 6165, "text": " Print" }, { "code": null, "e": 6183, "s": 6172, "text": " Add Notes" } ]
C library function - abs()
The C library function int abs(int x) returns the absolute value of int x. Following is the declaration for abs() function. int abs(int x) x − This is the integral value. x − This is the integral value. This function returns the absolute value of x. The following example shows the usage of abs() function. #include <stdio.h> #include <stdlib.h> int main () { int a, b; a = abs(5); printf("value of a = %d\n", a); b = abs(-10); printf("value of b = %d\n", b); return(0); } Let us compile and run the above program, this will produce the following result − value of a = 5 value of b = 10 12 Lectures 2 hours Nishant Malik 12 Lectures 2.5 hours Nishant Malik 48 Lectures 6.5 hours Asif Hussain 12 Lectures 2 hours Richa Maheshwari 20 Lectures 3.5 hours Vandana Annavaram 44 Lectures 1 hours Amit Diwan Print Add Notes Bookmark this page
[ { "code": null, "e": 2082, "s": 2007, "text": "The C library function int abs(int x) returns the absolute value of int x." }, { "code": null, "e": 2131, "s": 2082, "text": "Following is the declaration for abs() function." }, { "code": null, "e": 2146, "s": 2131, "text": "int abs(int x)" }, { "code": null, "e": 2178, "s": 2146, "text": "x − This is the integral value." }, { "code": null, "e": 2210, "s": 2178, "text": "x − This is the integral value." }, { "code": null, "e": 2257, "s": 2210, "text": "This function returns the absolute value of x." }, { "code": null, "e": 2314, "s": 2257, "text": "The following example shows the usage of abs() function." }, { "code": null, "e": 2505, "s": 2314, "text": "#include <stdio.h>\n#include <stdlib.h>\n\nint main () {\n int a, b;\n\n a = abs(5);\n printf(\"value of a = %d\\n\", a);\n\n b = abs(-10);\n printf(\"value of b = %d\\n\", b);\n \n return(0);\n}" }, { "code": null, "e": 2588, "s": 2505, "text": "Let us compile and run the above program, this will produce the following result −" }, { "code": null, "e": 2620, "s": 2588, "text": "value of a = 5\nvalue of b = 10\n" }, { "code": null, "e": 2653, "s": 2620, "text": "\n 12 Lectures \n 2 hours \n" }, { "code": null, "e": 2668, "s": 2653, "text": " Nishant Malik" }, { "code": null, "e": 2703, "s": 2668, "text": "\n 12 Lectures \n 2.5 hours \n" }, { "code": null, "e": 2718, "s": 2703, "text": " Nishant Malik" }, { "code": null, "e": 2753, "s": 2718, "text": "\n 48 Lectures \n 6.5 hours \n" }, { "code": null, "e": 2767, "s": 2753, "text": " Asif Hussain" }, { "code": null, "e": 2800, "s": 2767, "text": "\n 12 Lectures \n 2 hours \n" }, { "code": null, "e": 2818, "s": 2800, "text": " Richa Maheshwari" }, { "code": null, "e": 2853, "s": 2818, "text": "\n 20 Lectures \n 3.5 hours \n" }, { "code": null, "e": 2872, "s": 2853, "text": " Vandana Annavaram" }, { "code": null, "e": 2905, "s": 2872, "text": "\n 44 Lectures \n 1 hours \n" }, { "code": null, "e": 2917, "s": 2905, "text": " Amit Diwan" }, { "code": null, "e": 2924, "s": 2917, "text": " Print" }, { "code": null, "e": 2935, "s": 2924, "text": " Add Notes" } ]
Generating random number list in Python
There is a need to generate random numbers when studying a model or behavior of a program for different range of values. Python can generate such random numbers by using the random module. In the below examples we will first see how to generate a single random number and then extend it to generate a list of random numbers. The random() method in random module generates a float number between 0 and 1. import random n = random.random() print(n) Running the above code gives us the following result − 0.2112200 The randint() method generates a integer between a given range of numbers. import random n = random.randint(0,22) print(n) Running the above code gives us the following result − 2 We can use the above randint() method along with a for loop to generate a list of numbers. We first create an empty list and then append the random numbers generated to the empty list one by one. import random randomlist = [] for i in range(0,5): n = random.randint(1,30) randomlist.append(n) print(randomlist) Running the above code gives us the following result − [10, 5, 21, 1, 17] We can also use the sample() method available in random module to directly generate a list of random numbers.Here we specify a range and give how many random numbers we need to generate. import random #Generate 5 random numbers between 10 and 30 randomlist = random.sample(range(10, 30), 5) print(randomlist) Running the above code gives us the following result − [16, 19, 13, 18, 15]
[ { "code": null, "e": 1387, "s": 1062, "text": "There is a need to generate random numbers when studying a model or behavior of a program for different range of values. Python can generate such random numbers by using the random module. In the below examples we will first see how to generate a single random number and then extend it to generate a list of random numbers." }, { "code": null, "e": 1466, "s": 1387, "text": "The random() method in random module generates a float number between 0 and 1." }, { "code": null, "e": 1509, "s": 1466, "text": "import random\nn = random.random()\nprint(n)" }, { "code": null, "e": 1564, "s": 1509, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 1574, "s": 1564, "text": "0.2112200" }, { "code": null, "e": 1649, "s": 1574, "text": "The randint() method generates a integer between a given range of numbers." }, { "code": null, "e": 1697, "s": 1649, "text": "import random\nn = random.randint(0,22)\nprint(n)" }, { "code": null, "e": 1752, "s": 1697, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 1754, "s": 1752, "text": "2" }, { "code": null, "e": 1950, "s": 1754, "text": "We can use the above randint() method along with a for loop to generate a list of numbers. We first create an empty list and then append the random numbers generated to the empty list one by one." }, { "code": null, "e": 2065, "s": 1950, "text": "import random\nrandomlist = []\nfor i in range(0,5):\nn = random.randint(1,30)\nrandomlist.append(n)\nprint(randomlist)" }, { "code": null, "e": 2120, "s": 2065, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 2139, "s": 2120, "text": "[10, 5, 21, 1, 17]" }, { "code": null, "e": 2326, "s": 2139, "text": "We can also use the sample() method available in random module to directly generate a list of random numbers.Here we specify a range and give how many random numbers we need to generate." }, { "code": null, "e": 2448, "s": 2326, "text": "import random\n#Generate 5 random numbers between 10 and 30\nrandomlist = random.sample(range(10, 30), 5)\nprint(randomlist)" }, { "code": null, "e": 2503, "s": 2448, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 2524, "s": 2503, "text": "[16, 19, 13, 18, 15]" } ]
Spring Boot - Actuator
Spring Boot Actuator provides secured endpoints for monitoring and managing your Spring Boot application. By default, all actuator endpoints are secured. In this chapter, you will learn in detail about how to enable Spring Boot actuator to your application. To enable Spring Boot actuator endpoints to your Spring Boot application, we need to add the Spring Boot Starter actuator dependency in our build configuration file. Maven users can add the below dependency in your pom.xml file. <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency> Gradle users can add the below dependency in your build.gradle file. compile group: 'org.springframework.boot', name: 'spring-boot-starter-actuator' In the application.properties file, we need to disable the security for actuator endpoints. management.security.enabled = false YAML file users can add the following property in your application.yml file. management: security: enabled: false If you want to use the separate port number for accessing the Spring boot actutator endpoints add the management port number in application.properties file. management.port = 9000 YAML file users can add the following property in your application.yml file. management: port: 9000 Now, you can create an executable JAR file, and run the Spring Boot application by using the following Maven or Gradle commands. For Maven, you can use the following command − mvn clean install After “BUILD SUCCESS”, you can find the JAR file under the target directory. For Gradle, you can use the following command − gradle clean build After “BUILD SUCCESSFUL”, you can find the JAR file under the build/libs directory. Now, you can run the JAR file by using the following command − java –jar <JARFILE> Now, the application has started on the Tomcat port 8080. Note that if you specified the management port number, then same application is running on two different port numbers. Some important Spring Boot Actuator endpoints are given below. You can enter them in your web browser and monitor your application behavior. 102 Lectures 8 hours Karthikeya T 39 Lectures 5 hours Chaand Sheikh 73 Lectures 5.5 hours Senol Atac 62 Lectures 4.5 hours Senol Atac 67 Lectures 4.5 hours Senol Atac 69 Lectures 5 hours Senol Atac Print Add Notes Bookmark this page
[ { "code": null, "e": 3283, "s": 3025, "text": "Spring Boot Actuator provides secured endpoints for monitoring and managing your Spring Boot application. By default, all actuator endpoints are secured. In this chapter, you will learn in detail about how to enable Spring Boot actuator to your application." }, { "code": null, "e": 3449, "s": 3283, "text": "To enable Spring Boot actuator endpoints to your Spring Boot application, we need to add the Spring Boot Starter actuator dependency in our build configuration file." }, { "code": null, "e": 3512, "s": 3449, "text": "Maven users can add the below dependency in your pom.xml file." }, { "code": null, "e": 3643, "s": 3512, "text": "<dependency>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-starter-actuator</artifactId>\n</dependency>" }, { "code": null, "e": 3712, "s": 3643, "text": "Gradle users can add the below dependency in your build.gradle file." }, { "code": null, "e": 3793, "s": 3712, "text": "compile group: 'org.springframework.boot', name: 'spring-boot-starter-actuator'\n" }, { "code": null, "e": 3885, "s": 3793, "text": "In the application.properties file, we need to disable the security for actuator endpoints." }, { "code": null, "e": 3922, "s": 3885, "text": "management.security.enabled = false\n" }, { "code": null, "e": 3999, "s": 3922, "text": "YAML file users can add the following property in your application.yml file." }, { "code": null, "e": 4045, "s": 3999, "text": "management:\n security:\n enabled: false" }, { "code": null, "e": 4202, "s": 4045, "text": "If you want to use the separate port number for accessing the Spring boot actutator endpoints add the management port number in application.properties file." }, { "code": null, "e": 4226, "s": 4202, "text": "management.port = 9000\n" }, { "code": null, "e": 4303, "s": 4226, "text": "YAML file users can add the following property in your application.yml file." }, { "code": null, "e": 4330, "s": 4303, "text": "management:\n port: 9000\n" }, { "code": null, "e": 4459, "s": 4330, "text": "Now, you can create an executable JAR file, and run the Spring Boot application by using the following Maven or Gradle commands." }, { "code": null, "e": 4506, "s": 4459, "text": "For Maven, you can use the following command −" }, { "code": null, "e": 4525, "s": 4506, "text": "mvn clean install\n" }, { "code": null, "e": 4602, "s": 4525, "text": "After “BUILD SUCCESS”, you can find the JAR file under the target directory." }, { "code": null, "e": 4650, "s": 4602, "text": "For Gradle, you can use the following command −" }, { "code": null, "e": 4670, "s": 4650, "text": "gradle clean build\n" }, { "code": null, "e": 4754, "s": 4670, "text": "After “BUILD SUCCESSFUL”, you can find the JAR file under the build/libs directory." }, { "code": null, "e": 4817, "s": 4754, "text": "Now, you can run the JAR file by using the following command −" }, { "code": null, "e": 4839, "s": 4817, "text": "java –jar <JARFILE> \n" }, { "code": null, "e": 5016, "s": 4839, "text": "Now, the application has started on the Tomcat port 8080. Note that if you specified the management port number, then same application is running on two different port numbers." }, { "code": null, "e": 5157, "s": 5016, "text": "Some important Spring Boot Actuator endpoints are given below. You can enter them in your web browser and monitor your application behavior." }, { "code": null, "e": 5191, "s": 5157, "text": "\n 102 Lectures \n 8 hours \n" }, { "code": null, "e": 5205, "s": 5191, "text": " Karthikeya T" }, { "code": null, "e": 5238, "s": 5205, "text": "\n 39 Lectures \n 5 hours \n" }, { "code": null, "e": 5253, "s": 5238, "text": " Chaand Sheikh" }, { "code": null, "e": 5288, "s": 5253, "text": "\n 73 Lectures \n 5.5 hours \n" }, { "code": null, "e": 5300, "s": 5288, "text": " Senol Atac" }, { "code": null, "e": 5335, "s": 5300, "text": "\n 62 Lectures \n 4.5 hours \n" }, { "code": null, "e": 5347, "s": 5335, "text": " Senol Atac" }, { "code": null, "e": 5382, "s": 5347, "text": "\n 67 Lectures \n 4.5 hours \n" }, { "code": null, "e": 5394, "s": 5382, "text": " Senol Atac" }, { "code": null, "e": 5427, "s": 5394, "text": "\n 69 Lectures \n 5 hours \n" }, { "code": null, "e": 5439, "s": 5427, "text": " Senol Atac" }, { "code": null, "e": 5446, "s": 5439, "text": " Print" }, { "code": null, "e": 5457, "s": 5446, "text": " Add Notes" } ]
How to validate whether a string is a number in C#?
A string having number can be validated using int.TryParse or int.Parse. Int.Parse throws an exception if it cannot parse the string to an integer, whereas Int.TryParse returns a bool indicating whether it succeeded. Also, Int.TryParse has an out parameter which has the value of the parsed string. Live Demo using System; namespace DemoApplication { class Program { static void Main(string[] args) { string numberString = "123"; int number = 0; if(int.TryParse(numberString, out number)) { Console.WriteLine($"Try Parse Interger Number: {number}"); } Console.WriteLine($"Parse Interger Number: {int.Parse(numberString)}"); Console.ReadLine(); } } } The output of the code is Try Parse Interger Number: 123 Parse Interger Number: 123 In the above example since int.Tryparse returns a boolean value along with the parsed string in the out parameter, the if condition returns true. Also, int.Parse return the integer value as the string contains a proper number. Live Demo using System; namespace DemoApplication { class Program { static void Main(string[] args) { string numberString = "A123"; int number = 0; if(int.TryParse(numberString, out number)) { Console.WriteLine($"Try Parse Interger Number: {number}"); } elsem{ Console.WriteLine($"String doesnot have a proper number"); } Console.ReadLine(); } } } The output of the above code is String doesnot have a proper number As the string does not have a proper number, the int.Tryparse will return false and the else part of the code is executed. In the same case, int.Parse will throw exception like below. using System; namespace DemoApplication { class Program { static void Main(string[] args) { string numberString = "A123"; Console.WriteLine($"Parse Interger Number: {int.Parse(numberString)}"); //Exception: Input string was not in correct format. } } }
[ { "code": null, "e": 1135, "s": 1062, "text": "A string having number can be validated using int.TryParse or int.Parse." }, { "code": null, "e": 1361, "s": 1135, "text": "Int.Parse throws an exception if it cannot parse the string to an integer, whereas Int.TryParse returns a bool indicating whether it succeeded. Also, Int.TryParse has an out parameter which has the value of the parsed string." }, { "code": null, "e": 1372, "s": 1361, "text": " Live Demo" }, { "code": null, "e": 1797, "s": 1372, "text": "using System;\nnamespace DemoApplication {\n class Program {\n static void Main(string[] args) {\n string numberString = \"123\";\n int number = 0;\n if(int.TryParse(numberString, out number)) {\n Console.WriteLine($\"Try Parse Interger Number: {number}\");\n }\n Console.WriteLine($\"Parse Interger Number: {int.Parse(numberString)}\");\n Console.ReadLine();\n }\n }\n}" }, { "code": null, "e": 1823, "s": 1797, "text": "The output of the code is" }, { "code": null, "e": 1881, "s": 1823, "text": "Try Parse Interger Number: 123\nParse Interger Number: 123" }, { "code": null, "e": 2108, "s": 1881, "text": "In the above example since int.Tryparse returns a boolean value along with the parsed string in the out parameter, the if condition returns true. Also, int.Parse return the integer value as the string contains a proper number." }, { "code": null, "e": 2119, "s": 2108, "text": " Live Demo" }, { "code": null, "e": 2562, "s": 2119, "text": "using System;\nnamespace DemoApplication {\n class Program {\n static void Main(string[] args) {\n string numberString = \"A123\";\n int number = 0;\n if(int.TryParse(numberString, out number)) {\n Console.WriteLine($\"Try Parse Interger Number: {number}\");\n }\n elsem{\n Console.WriteLine($\"String doesnot have a proper number\");\n }\n Console.ReadLine();\n }\n }\n}" }, { "code": null, "e": 2594, "s": 2562, "text": "The output of the above code is" }, { "code": null, "e": 2630, "s": 2594, "text": "String doesnot have a proper number" }, { "code": null, "e": 2814, "s": 2630, "text": "As the string does not have a proper number, the int.Tryparse will return false and the else part of the code is executed. In the same case, int.Parse will throw exception like below." }, { "code": null, "e": 3112, "s": 2814, "text": "using System;\nnamespace DemoApplication {\n class Program {\n static void Main(string[] args) {\n string numberString = \"A123\";\n Console.WriteLine($\"Parse Interger Number: {int.Parse(numberString)}\");\n //Exception: Input string was not in correct format.\n }\n }\n}" } ]
Python 3 - Tuple max() Method
The max() method returns the elements from the tuple with maximum value. Following is the syntax for max() method − max(tuple) tuple − This is a tuple from which max valued element to be returned. This method returns the elements from the tuple with maximum value. The following example shows the usage of max() method. #!/usr/bin/python3 tuple1, tuple2 = ('maths', 'che', 'phy', 'bio'), (456, 700, 200) print ("Max value element : ", max(tuple1)) print ("Max value element : ", max(tuple2)) When we run above program, it produces the following result − Max value element : phy Max value element : 700 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": 2413, "s": 2340, "text": "The max() method returns the elements from the tuple with maximum value." }, { "code": null, "e": 2456, "s": 2413, "text": "Following is the syntax for max() method −" }, { "code": null, "e": 2468, "s": 2456, "text": "max(tuple)\n" }, { "code": null, "e": 2538, "s": 2468, "text": "tuple − This is a tuple from which max valued element to be returned." }, { "code": null, "e": 2606, "s": 2538, "text": "This method returns the elements from the tuple with maximum value." }, { "code": null, "e": 2661, "s": 2606, "text": "The following example shows the usage of max() method." }, { "code": null, "e": 2834, "s": 2661, "text": "#!/usr/bin/python3\n\ntuple1, tuple2 = ('maths', 'che', 'phy', 'bio'), (456, 700, 200)\nprint (\"Max value element : \", max(tuple1))\nprint (\"Max value element : \", max(tuple2))" }, { "code": null, "e": 2896, "s": 2834, "text": "When we run above program, it produces the following result −" }, { "code": null, "e": 2947, "s": 2896, "text": "Max value element : phy\nMax value element : 700\n" }, { "code": null, "e": 2984, "s": 2947, "text": "\n 187 Lectures \n 17.5 hours \n" }, { "code": null, "e": 3000, "s": 2984, "text": " Malhar Lathkar" }, { "code": null, "e": 3033, "s": 3000, "text": "\n 55 Lectures \n 8 hours \n" }, { "code": null, "e": 3052, "s": 3033, "text": " Arnab Chakraborty" }, { "code": null, "e": 3087, "s": 3052, "text": "\n 136 Lectures \n 11 hours \n" }, { "code": null, "e": 3109, "s": 3087, "text": " In28Minutes Official" }, { "code": null, "e": 3143, "s": 3109, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 3171, "s": 3143, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 3206, "s": 3171, "text": "\n 70 Lectures \n 8.5 hours \n" }, { "code": null, "e": 3220, "s": 3206, "text": " Lets Kode It" }, { "code": null, "e": 3253, "s": 3220, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 3270, "s": 3253, "text": " Abhilash Nelson" }, { "code": null, "e": 3277, "s": 3270, "text": " Print" }, { "code": null, "e": 3288, "s": 3277, "text": " Add Notes" } ]
NumPy - Array Attributes
In this chapter, we will discuss the various array attributes of NumPy. This array attribute returns a tuple consisting of array dimensions. It can also be used to resize the array. import numpy as np a = np.array([[1,2,3],[4,5,6]]) print a.shape The output is as follows − (2, 3) # this resizes the ndarray import numpy as np a = np.array([[1,2,3],[4,5,6]]) a.shape = (3,2) print a The output is as follows − [[1, 2] [3, 4] [5, 6]] NumPy also provides a reshape function to resize an array. import numpy as np a = np.array([[1,2,3],[4,5,6]]) b = a.reshape(3,2) print b The output is as follows − [[1, 2] [3, 4] [5, 6]] This array attribute returns the number of array dimensions. # an array of evenly spaced numbers import numpy as np a = np.arange(24) print a The output is as follows − [0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23] # this is one dimensional array import numpy as np a = np.arange(24) a.ndim # now reshape it b = a.reshape(2,4,3) print b # b is having three dimensions The output is as follows − [[[ 0, 1, 2] [ 3, 4, 5] [ 6, 7, 8] [ 9, 10, 11]] [[12, 13, 14] [15, 16, 17] [18, 19, 20] [21, 22, 23]]] This array attribute returns the length of each element of array in bytes. # dtype of array is int8 (1 byte) import numpy as np x = np.array([1,2,3,4,5], dtype = np.int8) print x.itemsize The output is as follows − 1 # dtype of array is now float32 (4 bytes) import numpy as np x = np.array([1,2,3,4,5], dtype = np.float32) print x.itemsize The output is as follows − 4 The ndarray object has the following attributes. Its current values are returned by this function. C_CONTIGUOUS (C) The data is in a single, C-style contiguous segment F_CONTIGUOUS (F) The data is in a single, Fortran-style contiguous segment OWNDATA (O) The array owns the memory it uses or borrows it from another object WRITEABLE (W) The data area can be written to. Setting this to False locks the data, making it read-only ALIGNED (A) The data and all elements are aligned appropriately for the hardware UPDATEIFCOPY (U) This array is a copy of some other array. When this array is deallocated, the base array will be updated with the contents of this array The following example shows the current values of flags. import numpy as np x = np.array([1,2,3,4,5]) print x.flags The output is as follows − C_CONTIGUOUS : True F_CONTIGUOUS : True OWNDATA : True WRITEABLE : True ALIGNED : True UPDATEIFCOPY : False 63 Lectures 6 hours Abhilash Nelson 19 Lectures 8 hours DATAhill Solutions Srinivas Reddy 12 Lectures 3 hours DATAhill Solutions Srinivas Reddy 10 Lectures 2.5 hours Akbar Khan 20 Lectures 2 hours Pruthviraja L 63 Lectures 6 hours Anmol Print Add Notes Bookmark this page
[ { "code": null, "e": 2315, "s": 2243, "text": "In this chapter, we will discuss the various array attributes of NumPy." }, { "code": null, "e": 2425, "s": 2315, "text": "This array attribute returns a tuple consisting of array dimensions. It can also be used to resize the array." }, { "code": null, "e": 2492, "s": 2425, "text": "import numpy as np \na = np.array([[1,2,3],[4,5,6]]) \nprint a.shape" }, { "code": null, "e": 2519, "s": 2492, "text": "The output is as follows −" }, { "code": null, "e": 2527, "s": 2519, "text": "(2, 3)\n" }, { "code": null, "e": 2635, "s": 2527, "text": "# this resizes the ndarray \nimport numpy as np \n\na = np.array([[1,2,3],[4,5,6]]) \na.shape = (3,2) \nprint a " }, { "code": null, "e": 2662, "s": 2635, "text": "The output is as follows −" }, { "code": null, "e": 2690, "s": 2662, "text": "[[1, 2] \n [3, 4] \n [5, 6]]\n" }, { "code": null, "e": 2749, "s": 2690, "text": "NumPy also provides a reshape function to resize an array." }, { "code": null, "e": 2830, "s": 2749, "text": "import numpy as np \na = np.array([[1,2,3],[4,5,6]]) \nb = a.reshape(3,2) \nprint b" }, { "code": null, "e": 2857, "s": 2830, "text": "The output is as follows −" }, { "code": null, "e": 2885, "s": 2857, "text": "[[1, 2] \n [3, 4] \n [5, 6]]\n" }, { "code": null, "e": 2946, "s": 2885, "text": "This array attribute returns the number of array dimensions." }, { "code": null, "e": 3030, "s": 2946, "text": "# an array of evenly spaced numbers \nimport numpy as np \na = np.arange(24) \nprint a" }, { "code": null, "e": 3057, "s": 3030, "text": "The output is as follows −" }, { "code": null, "e": 3138, "s": 3057, "text": "[0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23] \n" }, { "code": null, "e": 3300, "s": 3138, "text": "# this is one dimensional array \nimport numpy as np \na = np.arange(24) \na.ndim \n\n# now reshape it \nb = a.reshape(2,4,3) \nprint b \n# b is having three dimensions" }, { "code": null, "e": 3327, "s": 3300, "text": "The output is as follows −" }, { "code": null, "e": 3463, "s": 3327, "text": "[[[ 0, 1, 2] \n [ 3, 4, 5] \n [ 6, 7, 8] \n [ 9, 10, 11]] \n [[12, 13, 14] \n [15, 16, 17]\n [18, 19, 20] \n [21, 22, 23]]] \n" }, { "code": null, "e": 3538, "s": 3463, "text": "This array attribute returns the length of each element of array in bytes." }, { "code": null, "e": 3654, "s": 3538, "text": "# dtype of array is int8 (1 byte) \nimport numpy as np \nx = np.array([1,2,3,4,5], dtype = np.int8) \nprint x.itemsize" }, { "code": null, "e": 3681, "s": 3654, "text": "The output is as follows −" }, { "code": null, "e": 3684, "s": 3681, "text": "1\n" }, { "code": null, "e": 3811, "s": 3684, "text": "# dtype of array is now float32 (4 bytes) \nimport numpy as np \nx = np.array([1,2,3,4,5], dtype = np.float32) \nprint x.itemsize" }, { "code": null, "e": 3838, "s": 3811, "text": "The output is as follows −" }, { "code": null, "e": 3841, "s": 3838, "text": "4\n" }, { "code": null, "e": 3940, "s": 3841, "text": "The ndarray object has the following attributes. Its current values are returned by this function." }, { "code": null, "e": 3957, "s": 3940, "text": "C_CONTIGUOUS (C)" }, { "code": null, "e": 4009, "s": 3957, "text": "The data is in a single, C-style contiguous segment" }, { "code": null, "e": 4026, "s": 4009, "text": "F_CONTIGUOUS (F)" }, { "code": null, "e": 4084, "s": 4026, "text": "The data is in a single, Fortran-style contiguous segment" }, { "code": null, "e": 4096, "s": 4084, "text": "OWNDATA (O)" }, { "code": null, "e": 4164, "s": 4096, "text": "The array owns the memory it uses or borrows it from another object" }, { "code": null, "e": 4178, "s": 4164, "text": "WRITEABLE (W)" }, { "code": null, "e": 4269, "s": 4178, "text": "The data area can be written to. Setting this to False locks the data, making it read-only" }, { "code": null, "e": 4281, "s": 4269, "text": "ALIGNED (A)" }, { "code": null, "e": 4350, "s": 4281, "text": "The data and all elements are aligned appropriately for the hardware" }, { "code": null, "e": 4367, "s": 4350, "text": "UPDATEIFCOPY (U)" }, { "code": null, "e": 4504, "s": 4367, "text": "This array is a copy of some other array. When this array is deallocated, the base array will be updated with the contents of this array" }, { "code": null, "e": 4561, "s": 4504, "text": "The following example shows the current values of flags." }, { "code": null, "e": 4622, "s": 4561, "text": "import numpy as np \nx = np.array([1,2,3,4,5]) \nprint x.flags" }, { "code": null, "e": 4649, "s": 4622, "text": "The output is as follows −" }, { "code": null, "e": 4763, "s": 4649, "text": "C_CONTIGUOUS : True \nF_CONTIGUOUS : True \nOWNDATA : True \nWRITEABLE : True \nALIGNED : True \nUPDATEIFCOPY : False\n" }, { "code": null, "e": 4796, "s": 4763, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 4813, "s": 4796, "text": " Abhilash Nelson" }, { "code": null, "e": 4846, "s": 4813, "text": "\n 19 Lectures \n 8 hours \n" }, { "code": null, "e": 4881, "s": 4846, "text": " DATAhill Solutions Srinivas Reddy" }, { "code": null, "e": 4914, "s": 4881, "text": "\n 12 Lectures \n 3 hours \n" }, { "code": null, "e": 4949, "s": 4914, "text": " DATAhill Solutions Srinivas Reddy" }, { "code": null, "e": 4984, "s": 4949, "text": "\n 10 Lectures \n 2.5 hours \n" }, { "code": null, "e": 4996, "s": 4984, "text": " Akbar Khan" }, { "code": null, "e": 5029, "s": 4996, "text": "\n 20 Lectures \n 2 hours \n" }, { "code": null, "e": 5044, "s": 5029, "text": " Pruthviraja L" }, { "code": null, "e": 5077, "s": 5044, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 5084, "s": 5077, "text": " Anmol" }, { "code": null, "e": 5091, "s": 5084, "text": " Print" }, { "code": null, "e": 5102, "s": 5091, "text": " Add Notes" } ]
Recursively loop through an array and return number of items with JavaScript?
We have to write a function, say searchRecursively() that takes in an array and a search query and returns the count of that search query in the nested array. For example, if the array is given by − const names = ["rakesh", ["kalicharan", "krishna", "rakesh", "james", ["michael", "nathan", "rakesh", "george"]]]; Then − searchRecursively(names, ‘’rakesh’); Should return 3 because it makes a total of 3 appearances in the array. Therefore, let’s write the code for this recursive function − const names = ["rakesh", ["kalicharan", "krishna", "rakesh", "james", ["michael", "nathan", "rakesh", "george"]]]; const searchRecursively = (arr, query, count = 0, len = 0) => { if(len < arr.length){ if(Array.isArray(arr[len])){ return searchRecursively(arr[len], query, count, 0); }; if(arr[len] === query){ return searchRecursively(arr, query, ++count, ++len); }; return searchRecursively(arr, query, count, ++len); }; return count; }; console.log(searchRecursively(names, "rakesh")); The output in the console will be − 3
[ { "code": null, "e": 1221, "s": 1062, "text": "We have to write a function, say searchRecursively() that takes in an array and a search query\nand returns the count of that search query in the nested array." }, { "code": null, "e": 1261, "s": 1221, "text": "For example, if the array is given by −" }, { "code": null, "e": 1376, "s": 1261, "text": "const names = [\"rakesh\", [\"kalicharan\", \"krishna\", \"rakesh\", \"james\", [\"michael\", \"nathan\", \"rakesh\", \"george\"]]];" }, { "code": null, "e": 1383, "s": 1376, "text": "Then −" }, { "code": null, "e": 1420, "s": 1383, "text": "searchRecursively(names, ‘’rakesh’);" }, { "code": null, "e": 1554, "s": 1420, "text": "Should return 3 because it makes a total of 3 appearances in the array. Therefore, let’s write the\ncode for this recursive function −" }, { "code": null, "e": 2099, "s": 1554, "text": "const names = [\"rakesh\", [\"kalicharan\", \"krishna\", \"rakesh\", \"james\",\n[\"michael\", \"nathan\", \"rakesh\", \"george\"]]];\nconst searchRecursively = (arr, query, count = 0, len = 0) => {\n if(len < arr.length){\n if(Array.isArray(arr[len])){\n return searchRecursively(arr[len], query, count, 0);\n };\n if(arr[len] === query){\n return searchRecursively(arr, query, ++count, ++len);\n };\n return searchRecursively(arr, query, count, ++len);\n };\n return count;\n};\nconsole.log(searchRecursively(names, \"rakesh\"));" }, { "code": null, "e": 2135, "s": 2099, "text": "The output in the console will be −" }, { "code": null, "e": 2137, "s": 2135, "text": "3" } ]
Java Examples - create a banner using Applet
How to create a banner using Applet? Following example demonstrates how to play a sound using an applet image using Thread class. It also uses drawRect(), fillRect(), drawString() methods of Graphics class. import java.awt.*; import java.applet.*; public class SampleBanner extends Applet implements Runnable { String str = "This is a simple Banner "; Thread t ; boolean b; public void init() { setBackground(Color.gray); setForeground(Color.yellow); } public void start() { t = new Thread(this); b = false; t.start(); } public void run () { char ch; for( ; ; ) { try { repaint(); Thread.sleep(250); ch = str.charAt(0); str = str.substring(1, str.length()); str = str + ch; } catch(InterruptedException e) {} } } public void paint(Graphics g) { g.drawRect(1,1,300,150); g.setColor(Color.yellow); g.fillRect(1,1,300,150); g.setColor(Color.red); g.drawString(str, 1, 150); } } The above code sample will produce the following result in a java enabled web browser. View in Browser. The following is an another sample example to create a banner using Applet. import java.awt.*; import java.applet.*; public class NewApplet extends Applet implements Runnable { String msg = " It is a moving Banner. "; char cha; boolean stopFlag = true; Thread t = null; public void start() { t = new Thread(this); stopFlag = false; t.start(); } public void run() { for(;;) { try { repaint(); Thread.sleep(250); cha = msg.charAt(0); msg = msg.substring(1,msg.length()); msg = msg + cha; if(stopFlag) break; } catch(InterruptedException e) {} } } public void stop(){ stopFlag = true; t = null; } public void paint(Graphics g) { g.drawString(msg,60,30); } } Print Add Notes Bookmark this page
[ { "code": null, "e": 2105, "s": 2068, "text": "How to create a banner using Applet?" }, { "code": null, "e": 2275, "s": 2105, "text": "Following example demonstrates how to play a sound using an applet image using Thread class. It also uses drawRect(), fillRect(), drawString() methods of Graphics class." }, { "code": null, "e": 3122, "s": 2275, "text": "import java.awt.*;\nimport java.applet.*;\n\npublic class SampleBanner extends Applet implements Runnable {\n String str = \"This is a simple Banner \";\n Thread t ;\n boolean b;\n \n public void init() {\n setBackground(Color.gray);\n setForeground(Color.yellow);\n }\n public void start() {\n t = new Thread(this);\n b = false;\n t.start();\n }\n public void run () {\n char ch;\n for( ; ; ) {\n try {\n repaint();\n Thread.sleep(250);\n ch = str.charAt(0);\n str = str.substring(1, str.length());\n str = str + ch;\n }\n catch(InterruptedException e) {}\n }\n }\n public void paint(Graphics g) {\n g.drawRect(1,1,300,150);\n g.setColor(Color.yellow);\n g.fillRect(1,1,300,150);\n g.setColor(Color.red);\n g.drawString(str, 1, 150);\n }\n}" }, { "code": null, "e": 3209, "s": 3122, "text": "The above code sample will produce the following result in a java enabled web browser." }, { "code": null, "e": 3228, "s": 3209, "text": "View in Browser. \n" }, { "code": null, "e": 3304, "s": 3228, "text": "The following is an another sample example to create a banner using Applet." }, { "code": null, "e": 4081, "s": 3304, "text": "import java.awt.*;\nimport java.applet.*;\n\npublic class NewApplet extends Applet implements Runnable {\n String msg = \" It is a moving Banner. \";\n char cha;\n boolean stopFlag = true;\n Thread t = null;\n \n public void start() {\n t = new Thread(this);\n stopFlag = false; \n t.start();\n } \n public void run() {\n for(;;) { \n try { \n repaint();\n Thread.sleep(250);\n cha = msg.charAt(0);\n msg = msg.substring(1,msg.length());\n msg = msg + cha;\n if(stopFlag) break;\n } \n catch(InterruptedException e) {}\n } \n } \n public void stop(){\n stopFlag = true; \n t = null;\n } \n public void paint(Graphics g) { \n g.drawString(msg,60,30);\n }\n}" }, { "code": null, "e": 4088, "s": 4081, "text": " Print" }, { "code": null, "e": 4099, "s": 4088, "text": " Add Notes" } ]
Explain deleting an element in a queue by using C language
Data structure is collection of data organized in a structured way. It is divided into two types as explained below − Linear data structure − Data is organized in a linear fashion. For example, arrays, structures, stacks, queues, linked lists. Linear data structure − Data is organized in a linear fashion. For example, arrays, structures, stacks, queues, linked lists. Nonlinear data structure − Data is organized in a hierarchical way. For example, Trees, graphs, sets, tables. Nonlinear data structure − Data is organized in a hierarchical way. For example, Trees, graphs, sets, tables. It is a linear data structure, where the insertion is done at rear end and the deletion is done at the front end. The order of queue is FIFO – First In First Out Insert – Inserting an element into a queue. Delete – Deleting an element from the queue. Queue over flow − Trying to insert an element into a full queue. Queue over flow − Trying to insert an element into a full queue. Queue under flow − Trying to delete an element from an empty queue. Queue under flow − Trying to delete an element from an empty queue. Given below is an algorithm for insertion ( ) − Check for queue overflow. if (r==n) printf ("Queue overflow") Otherwise, insert an element in to the queue. q[r] = item r++ Given below is an algorithm for deletion ( ) − Check for queue under flow. if (f==r) printf ("Queue under flow") Otherwise, delete an element from the queue. item = q[f] f++ Given below is an algorithm for display ( ) − Check whether the queue is empty or not. if (f==r) printf("Queue is empty") Otherwise, print all the elements from ‘f’ to ‘r’. for(i=f; i<r; i++) printf ("%d", q[i]); Following is the C program for deleting an element in queue − #include <stdio.h> #define MAX 50 void insert(); int array[MAX]; int rear = - 1; int front = - 1; main(){ int add_item; int choice; while (1){ printf("1.Insert element to queue \n"); printf("2.Delete an element from queue\n"); printf("3.Display elements of queue \n"); printf("4.Quit \n"); printf("Enter your choice : "); scanf("%d", &choice); switch (choice){ case 1: insert(); break; case 2: delete(); case 3: display(); break; case 4: exit(1); default: printf("Wrong choice \n"); } } } void insert(){ int add_item; if (rear == MAX - 1) printf("Queue Overflow \n"); else{ if (front == - 1) /*If queue is initially empty */ front = 0; printf("Inset the element in queue : "); scanf("%d", &add_item); rear = rear + 1; array[rear] = add_item; } } void display(){ int i; if (front == - 1) printf("Queue is empty \n"); else{ printf("Queue is : \n"); for (i = front; i <= rear; i++) printf("%d ", array[i]); printf("\n"); } } void delete(){ if (front == - 1 || front > rear){ printf("Queue Underflow \n"); return ; } else{ printf("Element deleted from queue is : %d\n",array[front]); front = front + 1; } } When the above program is executed, it produces the following result − 1.Insert element to queue 2.Delete an element from queue 3.Display elements of queue 4.Quit Enter your choice: 1 Inset the element in queue: 12 1.Insert element to queue 2.Delete an element from queue 3.Display elements of queue 4.Quit Enter your choice: 1 Inset the element in queue: 23 1.Insert element to queue 2.Delete an element from queue 3.Display elements of queue 4.Quit Enter your choice: 1 Inset the element in queue: 34 1.Insert element to queue 2.Delete an element from queue 3.Display elements of queue 4.Quit Enter your choice: 2 Element deleted from queue is: 12 Queue is: 23 34 1.Insert element to queue 2.Delete an element from queue 3.Display elements of queue 4.Quit Enter your choice: 2 Element deleted from queue is: 23 Queue is: 34 1.Insert element to queue 2.Delete an element from queue 3.Display elements of queue 4.Quit Enter your choice: 4
[ { "code": null, "e": 1180, "s": 1062, "text": "Data structure is collection of data organized in a structured way. It is divided into two types as explained below −" }, { "code": null, "e": 1306, "s": 1180, "text": "Linear data structure − Data is organized in a linear fashion. For example, arrays, structures, stacks, queues, linked lists." }, { "code": null, "e": 1432, "s": 1306, "text": "Linear data structure − Data is organized in a linear fashion. For example, arrays, structures, stacks, queues, linked lists." }, { "code": null, "e": 1542, "s": 1432, "text": "Nonlinear data structure − Data is organized in a hierarchical way. For example, Trees, graphs, sets, tables." }, { "code": null, "e": 1652, "s": 1542, "text": "Nonlinear data structure − Data is organized in a hierarchical way. For example, Trees, graphs, sets, tables." }, { "code": null, "e": 1766, "s": 1652, "text": "It is a linear data structure, where the insertion is done at rear end and the deletion is done at the front end." }, { "code": null, "e": 1814, "s": 1766, "text": "The order of queue is FIFO – First In First Out" }, { "code": null, "e": 1858, "s": 1814, "text": "Insert – Inserting an element into a queue." }, { "code": null, "e": 1903, "s": 1858, "text": "Delete – Deleting an element from the queue." }, { "code": null, "e": 1968, "s": 1903, "text": "Queue over flow − Trying to insert an element into a full queue." }, { "code": null, "e": 2033, "s": 1968, "text": "Queue over flow − Trying to insert an element into a full queue." }, { "code": null, "e": 2101, "s": 2033, "text": "Queue under flow − Trying to delete an element from an empty queue." }, { "code": null, "e": 2169, "s": 2101, "text": "Queue under flow − Trying to delete an element from an empty queue." }, { "code": null, "e": 2217, "s": 2169, "text": "Given below is an algorithm for insertion ( ) −" }, { "code": null, "e": 2243, "s": 2217, "text": "Check for queue overflow." }, { "code": null, "e": 2279, "s": 2243, "text": "if (r==n)\nprintf (\"Queue overflow\")" }, { "code": null, "e": 2325, "s": 2279, "text": "Otherwise, insert an element in to the queue." }, { "code": null, "e": 2341, "s": 2325, "text": "q[r] = item\nr++" }, { "code": null, "e": 2388, "s": 2341, "text": "Given below is an algorithm for deletion ( ) −" }, { "code": null, "e": 2416, "s": 2388, "text": "Check for queue under flow." }, { "code": null, "e": 2454, "s": 2416, "text": "if (f==r)\nprintf (\"Queue under flow\")" }, { "code": null, "e": 2499, "s": 2454, "text": "Otherwise, delete an element from the queue." }, { "code": null, "e": 2515, "s": 2499, "text": "item = q[f]\nf++" }, { "code": null, "e": 2561, "s": 2515, "text": "Given below is an algorithm for display ( ) −" }, { "code": null, "e": 2602, "s": 2561, "text": "Check whether the queue is empty or not." }, { "code": null, "e": 2637, "s": 2602, "text": "if (f==r)\nprintf(\"Queue is empty\")" }, { "code": null, "e": 2688, "s": 2637, "text": "Otherwise, print all the elements from ‘f’ to ‘r’." }, { "code": null, "e": 2728, "s": 2688, "text": "for(i=f; i<r; i++)\nprintf (\"%d\", q[i]);" }, { "code": null, "e": 2790, "s": 2728, "text": "Following is the C program for deleting an element in queue −" }, { "code": null, "e": 4217, "s": 2790, "text": "#include <stdio.h>\n#define MAX 50\nvoid insert();\nint array[MAX];\nint rear = - 1;\nint front = - 1;\nmain(){\n int add_item;\n int choice;\n while (1){\n printf(\"1.Insert element to queue \\n\");\n printf(\"2.Delete an element from queue\\n\");\n printf(\"3.Display elements of queue \\n\");\n printf(\"4.Quit \\n\");\n printf(\"Enter your choice : \");\n scanf(\"%d\", &choice);\n switch (choice){\n case 1:\n insert();\n break;\n case 2:\n delete();\n case 3:\n display();\n break;\n case 4:\n exit(1);\n default:\n printf(\"Wrong choice \\n\");\n }\n }\n}\nvoid insert(){\n int add_item;\n if (rear == MAX - 1)\n printf(\"Queue Overflow \\n\");\n else{\n if (front == - 1)\n /*If queue is initially empty */\n front = 0;\n printf(\"Inset the element in queue : \");\n scanf(\"%d\", &add_item);\n rear = rear + 1;\n array[rear] = add_item;\n }\n}\nvoid display(){\n int i;\n if (front == - 1)\n printf(\"Queue is empty \\n\");\n else{\n printf(\"Queue is : \\n\");\n for (i = front; i <= rear; i++)\n printf(\"%d \", array[i]);\n printf(\"\\n\");\n }\n}\nvoid delete(){\n if (front == - 1 || front > rear){\n printf(\"Queue Underflow \\n\");\n return ;\n }\n else{\n printf(\"Element deleted from queue is : %d\\n\",array[front]);\n front = front + 1;\n }\n}" }, { "code": null, "e": 4288, "s": 4217, "text": "When the above program is executed, it produces the following result −" }, { "code": null, "e": 5156, "s": 4288, "text": "1.Insert element to queue\n2.Delete an element from queue\n3.Display elements of queue\n4.Quit\nEnter your choice: 1\nInset the element in queue: 12\n1.Insert element to queue\n2.Delete an element from queue\n3.Display elements of queue\n4.Quit\nEnter your choice: 1\nInset the element in queue: 23\n1.Insert element to queue\n2.Delete an element from queue\n3.Display elements of queue\n4.Quit\nEnter your choice: 1\nInset the element in queue: 34\n1.Insert element to queue\n2.Delete an element from queue\n3.Display elements of queue\n4.Quit\nEnter your choice: 2\nElement deleted from queue is: 12\nQueue is:\n23 34\n1.Insert element to queue\n2.Delete an element from queue\n3.Display elements of queue\n4.Quit\nEnter your choice: 2\nElement deleted from queue is: 23\nQueue is:\n34\n1.Insert element to queue\n2.Delete an element from queue\n3.Display elements of queue\n4.Quit\nEnter your choice: 4" } ]
Check whether a subsequence exists with sum equal to k if arr[i]> 2*arr[i-1] - GeeksforGeeks
29 Apr, 2021 Given a sorted array of positive integers where arr[i] > 2*arr[i-1], check whether a sub sequence exists whose sum is equal to k.Examples: Input : arr[]={ 1, 3, 7, 15, 31}, K=18 Output :True A[1] + A[3] = 3 + 15 = 18 We found a subsequence whose sum is 18 Input :arr[]={ 1, 3, 7, 15, 31}, K=20 Output :False No subsequence can be found with sum 20 Naive Solution: The basic solution is to check for all the 2^n possible combinations and check if there is any subsequence whose sum is equal to K. This process will not work for higher values of N, N>20. Time Complexity: O(2^N) Efficient Solution: We are given arr[i] >2*arr[i-1] so we can say that arr[i] > ( arr[i-1] + arr[i-2] + ...+ arr[2] + arr[1] + arr[0] ).Let us assume that arr[i] <= K ( arr[i-1] + arr[i-2] + ...+ arr[2] + arr[1] + arr[0] ) ), so we have to include arr[i] in the set . So, we have to traverse the array in descending order and when we find arr[i]<=k, we will include arr[i] in the set and subtract arr[i] from K and continue the loop until value of K is equal to zero.If the value of K is zero then there is a subsequence else not. Below is the Implementation of above approach: C++ Java Python3 C# Javascript // C++ implementation of above approach#include <iostream>using namespace std; // Function to check whether sum of any set// of the array element is equal// to k or notbool CheckForSequence(int arr[], int n, int k){ // Traverse the array from end // to start for (int i = n - 1; i >= 0; i--) { // if k is greater than // arr[i] then subtract // it from k if (k >= arr[i]) k -= arr[i]; } // If there is any subsequence // whose sum is equal to k if (k != 0) return false; else return true;} // Driver codeint main(){ int A[] = { 1, 3, 7, 15, 31 }; int n = sizeof(A) / sizeof(int); cout << (CheckForSequence(A, n, 18) ? "True": "False") << endl; return 0;} // Java implementation of above approachimport java.io.*; class GFG{ // Function to check whether// sum of any set of the array element// is equal to k or notstatic boolean CheckForSequence(int arr[], int n, int k){ // Traverse the array from end // to start for (int i = n - 1; i >= 0; i--) { // if k is greater than // arr[i] then subtract // it from k if (k >= arr[i]) k -= arr[i]; } // If there is any subsequence // whose sum is equal to k if (k != 0) return false; else return true;} // Driver codepublic static void main (String[] args){ int A[] = { 1, 3, 7, 15, 31 }; int n = A.length; System.out.println(CheckForSequence(A, n, 18) ? "True": "False");}} // This code is contributed by jit_t # Python3 implementation of above approach # Function to check whether sum of any set# of the array element is equal# to k or notdef CheckForSequence(arr, n, k) : # Traverse the array from end # to start for i in range(n - 1, -1, -1) : # if k is greater than # arr[i] then subtract # it from k if (k >= arr[i]) : k -= arr[i]; # If there is any subsequence # whose sum is equal to k if (k != 0) : return False; else : return True; # Driver codeif __name__ == "__main__" : A = [ 1, 3, 7, 15, 31 ]; n = len(A); if (CheckForSequence(A, n, 18)) : print(True) else : print(False) # This code is contributed by AnkitRai01 // C# implementation of above approachusing System; class GFG{ // Function to check whether// sum of any set of the array element// is equal to k or notstatic bool CheckForSequence(int []arr, int n, int k){ // Traverse the array from end // to start for (int i = n - 1; i >= 0; i--) { // if k is greater than // arr[i] then subtract // it from k if (k >= arr[i]) k -= arr[i]; } // If there is any subsequence // whose sum is equal to k if (k != 0) return false; else return true;} // Driver codepublic static void Main (){ int []A = { 1, 3, 7, 15, 31 }; int n = A.Length; Console.WriteLine(CheckForSequence(A, n, 18) ? "True": "False");}} // This code is contributed by anuj_67.. <script>// Javascript program to implement the above approach // Function to check whether sum of any set// of the array element is equal// to k or notfunction CheckForSequence( arr,n,k){ // Traverse the array from end // to start for (var i = n - 1; i >= 0; i--) { // if k is greater than // arr[i] then subtract // it from k if (k >= arr[i]) k -= arr[i]; } // If there is any subsequence // whose sum is equal to k if (k != 0) return false; else return true;} var A = [ 1, 3, 7, 15, 31 ];var n = A.length;document.write( (CheckForSequence(A, n, 18) ? "True": "False") +"<br>"); //This code is contributed by SoumikModnal</script> True Time Complexity : O(N) ankthon jit_t vt_m nidhi_biet Akanksha_Rai SoumikMondal subsequence Arrays Competitive Programming Greedy Mathematical Arrays Greedy Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Top 50 Array Coding Problems for Interviews Multidimensional Arrays in Java Introduction to Arrays Linear Search Maximum and minimum of an array using minimum number of comparisons Competitive Programming - A Complete Guide Practice for cracking any coding interview Arrow operator -> in C/C++ with Examples Bits manipulation (Important tactics) Top 10 Algorithms and Data Structures for Competitive Programming
[ { "code": null, "e": 25382, "s": 25354, "text": "\n29 Apr, 2021" }, { "code": null, "e": 25523, "s": 25382, "text": "Given a sorted array of positive integers where arr[i] > 2*arr[i-1], check whether a sub sequence exists whose sum is equal to k.Examples: " }, { "code": null, "e": 25734, "s": 25523, "text": "Input : arr[]={ 1, 3, 7, 15, 31}, K=18 Output :True A[1] + A[3] = 3 + 15 = 18 We found a subsequence whose sum is 18 Input :arr[]={ 1, 3, 7, 15, 31}, K=20 Output :False No subsequence can be found with sum 20 " }, { "code": null, "e": 26545, "s": 25736, "text": "Naive Solution: The basic solution is to check for all the 2^n possible combinations and check if there is any subsequence whose sum is equal to K. This process will not work for higher values of N, N>20. Time Complexity: O(2^N) Efficient Solution: We are given arr[i] >2*arr[i-1] so we can say that arr[i] > ( arr[i-1] + arr[i-2] + ...+ arr[2] + arr[1] + arr[0] ).Let us assume that arr[i] <= K ( arr[i-1] + arr[i-2] + ...+ arr[2] + arr[1] + arr[0] ) ), so we have to include arr[i] in the set . So, we have to traverse the array in descending order and when we find arr[i]<=k, we will include arr[i] in the set and subtract arr[i] from K and continue the loop until value of K is equal to zero.If the value of K is zero then there is a subsequence else not. Below is the Implementation of above approach: " }, { "code": null, "e": 26549, "s": 26545, "text": "C++" }, { "code": null, "e": 26554, "s": 26549, "text": "Java" }, { "code": null, "e": 26562, "s": 26554, "text": "Python3" }, { "code": null, "e": 26565, "s": 26562, "text": "C#" }, { "code": null, "e": 26576, "s": 26565, "text": "Javascript" }, { "code": "// C++ implementation of above approach#include <iostream>using namespace std; // Function to check whether sum of any set// of the array element is equal// to k or notbool CheckForSequence(int arr[], int n, int k){ // Traverse the array from end // to start for (int i = n - 1; i >= 0; i--) { // if k is greater than // arr[i] then subtract // it from k if (k >= arr[i]) k -= arr[i]; } // If there is any subsequence // whose sum is equal to k if (k != 0) return false; else return true;} // Driver codeint main(){ int A[] = { 1, 3, 7, 15, 31 }; int n = sizeof(A) / sizeof(int); cout << (CheckForSequence(A, n, 18) ? \"True\": \"False\") << endl; return 0;}", "e": 27337, "s": 26576, "text": null }, { "code": "// Java implementation of above approachimport java.io.*; class GFG{ // Function to check whether// sum of any set of the array element// is equal to k or notstatic boolean CheckForSequence(int arr[], int n, int k){ // Traverse the array from end // to start for (int i = n - 1; i >= 0; i--) { // if k is greater than // arr[i] then subtract // it from k if (k >= arr[i]) k -= arr[i]; } // If there is any subsequence // whose sum is equal to k if (k != 0) return false; else return true;} // Driver codepublic static void main (String[] args){ int A[] = { 1, 3, 7, 15, 31 }; int n = A.length; System.out.println(CheckForSequence(A, n, 18) ? \"True\": \"False\");}} // This code is contributed by jit_t", "e": 28205, "s": 27337, "text": null }, { "code": "# Python3 implementation of above approach # Function to check whether sum of any set# of the array element is equal# to k or notdef CheckForSequence(arr, n, k) : # Traverse the array from end # to start for i in range(n - 1, -1, -1) : # if k is greater than # arr[i] then subtract # it from k if (k >= arr[i]) : k -= arr[i]; # If there is any subsequence # whose sum is equal to k if (k != 0) : return False; else : return True; # Driver codeif __name__ == \"__main__\" : A = [ 1, 3, 7, 15, 31 ]; n = len(A); if (CheckForSequence(A, n, 18)) : print(True) else : print(False) # This code is contributed by AnkitRai01", "e": 28936, "s": 28205, "text": null }, { "code": "// C# implementation of above approachusing System; class GFG{ // Function to check whether// sum of any set of the array element// is equal to k or notstatic bool CheckForSequence(int []arr, int n, int k){ // Traverse the array from end // to start for (int i = n - 1; i >= 0; i--) { // if k is greater than // arr[i] then subtract // it from k if (k >= arr[i]) k -= arr[i]; } // If there is any subsequence // whose sum is equal to k if (k != 0) return false; else return true;} // Driver codepublic static void Main (){ int []A = { 1, 3, 7, 15, 31 }; int n = A.Length; Console.WriteLine(CheckForSequence(A, n, 18) ? \"True\": \"False\");}} // This code is contributed by anuj_67..", "e": 29785, "s": 28936, "text": null }, { "code": "<script>// Javascript program to implement the above approach // Function to check whether sum of any set// of the array element is equal// to k or notfunction CheckForSequence( arr,n,k){ // Traverse the array from end // to start for (var i = n - 1; i >= 0; i--) { // if k is greater than // arr[i] then subtract // it from k if (k >= arr[i]) k -= arr[i]; } // If there is any subsequence // whose sum is equal to k if (k != 0) return false; else return true;} var A = [ 1, 3, 7, 15, 31 ];var n = A.length;document.write( (CheckForSequence(A, n, 18) ? \"True\": \"False\") +\"<br>\"); //This code is contributed by SoumikModnal</script>", "e": 30494, "s": 29785, "text": null }, { "code": null, "e": 30499, "s": 30494, "text": "True" }, { "code": null, "e": 30526, "s": 30501, "text": "Time Complexity : O(N) " }, { "code": null, "e": 30534, "s": 30526, "text": "ankthon" }, { "code": null, "e": 30540, "s": 30534, "text": "jit_t" }, { "code": null, "e": 30545, "s": 30540, "text": "vt_m" }, { "code": null, "e": 30556, "s": 30545, "text": "nidhi_biet" }, { "code": null, "e": 30569, "s": 30556, "text": "Akanksha_Rai" }, { "code": null, "e": 30582, "s": 30569, "text": "SoumikMondal" }, { "code": null, "e": 30594, "s": 30582, "text": "subsequence" }, { "code": null, "e": 30601, "s": 30594, "text": "Arrays" }, { "code": null, "e": 30625, "s": 30601, "text": "Competitive Programming" }, { "code": null, "e": 30632, "s": 30625, "text": "Greedy" }, { "code": null, "e": 30645, "s": 30632, "text": "Mathematical" }, { "code": null, "e": 30652, "s": 30645, "text": "Arrays" }, { "code": null, "e": 30659, "s": 30652, "text": "Greedy" }, { "code": null, "e": 30672, "s": 30659, "text": "Mathematical" }, { "code": null, "e": 30770, "s": 30672, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30814, "s": 30770, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 30846, "s": 30814, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 30869, "s": 30846, "text": "Introduction to Arrays" }, { "code": null, "e": 30883, "s": 30869, "text": "Linear Search" }, { "code": null, "e": 30951, "s": 30883, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 30994, "s": 30951, "text": "Competitive Programming - A Complete Guide" }, { "code": null, "e": 31037, "s": 30994, "text": "Practice for cracking any coding interview" }, { "code": null, "e": 31078, "s": 31037, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 31116, "s": 31078, "text": "Bits manipulation (Important tactics)" } ]
numpy.insert() in Python
28 Mar, 2022 The numpy.insert() function inserts values along the mentioned axis before the given indices. Syntax : numpy.insert(array, object, values, axis = None) Parameters : array : [array_like]Input array. object : [int, array of ints]Sub-array with the index or indices before which values is inserted values : [array_like]values to be added in the arr. Values should be shaped so that arr[...,obj,...] = values. If the type of values is different from that of arr, values is converted to the type of arr axis : Axis along which we want to insert the values. By default, it object is applied to flattened array Return : An copy of array with values being inserted as per the mentioned object along a given axis. Code 1 : Deletion from 1D array Python # Python Program illustrating# numpy.insert() import numpy as geek #Working on 1Darr = geek.arange(5)print("1D arr : \n", arr)print("Shape : ", arr.shape) # value = 9# index = 1 # Insertion before first indexa = geek.insert(arr, 1, 9)print("\nArray after insertion : ", a)print("Shape : ", a.shape) # Working on 2D arrayarr = geek.arange(12).reshape(3, 4)print("\n\n2D arr : \n", arr)print("Shape : ", arr.shape) a = geek.insert(arr, 1, 9, axis = 1)print("\nArray after insertion : \n", a)print("Shape : ", a.shape) Output : 1D arr : [0 1 2 3 4] Shape : (5,) Array after insertion : [0 9 1 2 3 4] Shape : (6,) 2D arr : [[ 0 1 2 3] [ 4 5 6 7] [ 8 9 10 11]] Shape : (3, 4) Array after insertion : [[ 0 9 1 2 3] [ 4 9 5 6 7] [ 8 9 9 10 11]] Shape : (3, 5) Code 2 : Working with Scalars Python # Python Program illustrating# numpy.insert() import numpy as geek # Working on 2D arrayarr = geek.arange(12).reshape(3, 4)print("2D arr : \n", arr)print("Shape : ", arr.shape) # Working with Scalarsa = geek.insert(arr, [1], [[6],[9],], axis = 0)print("\nArray after insertion : \n", a)print("Shape : ", a.shape) # Working with Scalarsa = geek.insert(arr, [1], [[8],[7],[9]], axis = 1)print("\nArray after insertion : \n", a)print("Shape : ", a.shape) Output : 2D arr : [[ 0 1 2 3] [ 4 5 6 7] [ 8 9 10 11]] Shape : (3, 4) Array after insertion : [[ 0 1 2 3] [ 6 6 6 6] [ 9 9 9 9] [ 4 5 6 7] [ 8 9 10 11]] Shape : (5, 4) Array after insertion : [[ 0 8 1 2 3] [ 4 7 5 6 7] [ 8 9 9 10 11]] Shape : (3, 5) Code 3 : Insertion at different points Python # Python Program illustrating# numpy.insert() import numpy as geek #Working on 1Darr = geek.arange(6).reshape(2, 3)print("1D arr : \n", arr)print("Shape : ", arr.shape) # value = 9# index = 1 # Insertion before first indexa = geek.insert(arr, (2, 4), 9)print("\nInsertion at two points : ", a)print("Shape : ", a.shape) # Working on 2D arrayarr = geek.arange(12).reshape(3, 4)print("\n\n2D arr : \n", arr)print("Shape : ", arr.shape)a = geek.insert(arr, (0, 3), 66, axis = 1)print("\nInsertion at two points : \n", a)print("Shape : ", a.shape) Output : 1D arr : [[0 1 2] [3 4 5]] Shape : (2, 3) Insertion at two points : [0 1 9 2 3 9 4 5] Shape : (8,) 2D arr : [[ 0 1 2 3] [ 4 5 6 7] [ 8 9 10 11]] Shape : (3, 4) Insertion at two points : [[66 0 1 2 66 3] [66 4 5 6 66 7] [66 8 9 10 66 11]] Shape : (3, 6) References : https://docs.scipy.org/doc/numpy/reference/generated/numpy.insert.html#numpy.insert Note : These codes won’t run on online IDE’s. Please run them on your systems to explore the working. This article is contributed by Mohit Gupta_OMG . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. kothavvsaakash Python numpy-arrayManipulation Python-numpy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Mar, 2022" }, { "code": null, "e": 132, "s": 28, "text": "The numpy.insert() function inserts values along the mentioned axis before the given indices. Syntax : " }, { "code": null, "e": 181, "s": 132, "text": "numpy.insert(array, object, values, axis = None)" }, { "code": null, "e": 195, "s": 181, "text": "Parameters : " }, { "code": null, "e": 670, "s": 195, "text": "array : [array_like]Input array. \nobject : [int, array of ints]Sub-array with the index or indices before \n which values is inserted\nvalues : [array_like]values to be added in the arr. Values should be \n shaped so that arr[...,obj,...] = values. If the type of values is different from \n that of arr, values is converted to the type of arr\naxis : Axis along which we want to insert the values. By default, it \n object is applied to flattened array " }, { "code": null, "e": 680, "s": 670, "text": "Return : " }, { "code": null, "e": 773, "s": 680, "text": "An copy of array with values being inserted as per the mentioned object along a given axis. " }, { "code": null, "e": 806, "s": 773, "text": "Code 1 : Deletion from 1D array " }, { "code": null, "e": 813, "s": 806, "text": "Python" }, { "code": "# Python Program illustrating# numpy.insert() import numpy as geek #Working on 1Darr = geek.arange(5)print(\"1D arr : \\n\", arr)print(\"Shape : \", arr.shape) # value = 9# index = 1 # Insertion before first indexa = geek.insert(arr, 1, 9)print(\"\\nArray after insertion : \", a)print(\"Shape : \", a.shape) # Working on 2D arrayarr = geek.arange(12).reshape(3, 4)print(\"\\n\\n2D arr : \\n\", arr)print(\"Shape : \", arr.shape) a = geek.insert(arr, 1, 9, axis = 1)print(\"\\nArray after insertion : \\n\", a)print(\"Shape : \", a.shape)", "e": 1331, "s": 813, "text": null }, { "code": null, "e": 1341, "s": 1331, "text": "Output : " }, { "code": null, "e": 1605, "s": 1341, "text": "1D arr : \n [0 1 2 3 4]\nShape : (5,)\n\nArray after insertion : [0 9 1 2 3 4]\nShape : (6,)\n\n\n2D arr : \n [[ 0 1 2 3]\n [ 4 5 6 7]\n [ 8 9 10 11]]\nShape : (3, 4)\n\nArray after insertion : \n [[ 0 9 1 2 3]\n [ 4 9 5 6 7]\n [ 8 9 9 10 11]]\nShape : (3, 5)" }, { "code": null, "e": 1636, "s": 1605, "text": "Code 2 : Working with Scalars " }, { "code": null, "e": 1643, "s": 1636, "text": "Python" }, { "code": "# Python Program illustrating# numpy.insert() import numpy as geek # Working on 2D arrayarr = geek.arange(12).reshape(3, 4)print(\"2D arr : \\n\", arr)print(\"Shape : \", arr.shape) # Working with Scalarsa = geek.insert(arr, [1], [[6],[9],], axis = 0)print(\"\\nArray after insertion : \\n\", a)print(\"Shape : \", a.shape) # Working with Scalarsa = geek.insert(arr, [1], [[8],[7],[9]], axis = 1)print(\"\\nArray after insertion : \\n\", a)print(\"Shape : \", a.shape)", "e": 2095, "s": 1643, "text": null }, { "code": null, "e": 2105, "s": 2095, "text": "Output : " }, { "code": null, "e": 2395, "s": 2105, "text": "2D arr : \n [[ 0 1 2 3]\n [ 4 5 6 7]\n [ 8 9 10 11]]\nShape : (3, 4)\n\nArray after insertion : \n [[ 0 1 2 3]\n [ 6 6 6 6]\n [ 9 9 9 9]\n [ 4 5 6 7]\n [ 8 9 10 11]]\nShape : (5, 4)\n\nArray after insertion : \n [[ 0 8 1 2 3]\n [ 4 7 5 6 7]\n [ 8 9 9 10 11]]\nShape : (3, 5)" }, { "code": null, "e": 2435, "s": 2395, "text": "Code 3 : Insertion at different points " }, { "code": null, "e": 2442, "s": 2435, "text": "Python" }, { "code": "# Python Program illustrating# numpy.insert() import numpy as geek #Working on 1Darr = geek.arange(6).reshape(2, 3)print(\"1D arr : \\n\", arr)print(\"Shape : \", arr.shape) # value = 9# index = 1 # Insertion before first indexa = geek.insert(arr, (2, 4), 9)print(\"\\nInsertion at two points : \", a)print(\"Shape : \", a.shape) # Working on 2D arrayarr = geek.arange(12).reshape(3, 4)print(\"\\n\\n2D arr : \\n\", arr)print(\"Shape : \", arr.shape)a = geek.insert(arr, (0, 3), 66, axis = 1)print(\"\\nInsertion at two points : \\n\", a)print(\"Shape : \", a.shape)", "e": 2988, "s": 2442, "text": null }, { "code": null, "e": 2998, "s": 2988, "text": "Output : " }, { "code": null, "e": 3288, "s": 2998, "text": "1D arr : \n [[0 1 2]\n [3 4 5]]\nShape : (2, 3)\n\nInsertion at two points : [0 1 9 2 3 9 4 5]\nShape : (8,)\n\n\n2D arr : \n [[ 0 1 2 3]\n [ 4 5 6 7]\n [ 8 9 10 11]]\nShape : (3, 4)\n\nInsertion at two points : \n [[66 0 1 2 66 3]\n [66 4 5 6 66 7]\n [66 8 9 10 66 11]]\nShape : (3, 6)" }, { "code": null, "e": 3912, "s": 3288, "text": "References : https://docs.scipy.org/doc/numpy/reference/generated/numpy.insert.html#numpy.insert Note : These codes won’t run on online IDE’s. Please run them on your systems to explore the working. This article is contributed by Mohit Gupta_OMG . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 3927, "s": 3912, "text": "kothavvsaakash" }, { "code": null, "e": 3958, "s": 3927, "text": "Python numpy-arrayManipulation" }, { "code": null, "e": 3971, "s": 3958, "text": "Python-numpy" }, { "code": null, "e": 3978, "s": 3971, "text": "Python" } ]
Java String toUpperCase() Method With Examples
04 Oct, 2021 The java string toUpperCase() method of String class has converted all characters of the string into an uppercase letter. There is two variant of toUpperCase() method. The key thing that is to be taken into consideration is toUpperCase() method worked same as to UpperCase(Locale.getDefault()) method as internally default locale is used. Syntax: public String toUpperCase(Locale loc) public String toUpperCase() Parameter: Type 1: Locale value to be applied as it converts all the characters into Type 2: NA Return Type: It returns the string in uppercase letters. Note: Lowercase is done using the rules of the given Locale. Example 1: java // Java Program to Demonstrate Working of toUpperCase()// method // Main classclass GFG { // Main driver method public static void main(String args[]) { // Custom input string String str = "Welcome! to Geeksforgeeks"; // Converting above input string to // uppercase letters using UpperCase() method String strup = str.toUpperCase(); // Print the uppercased string System.out.println(strup); }} WELCOME! TO GEEKSFORGEEKS Example 2: java // Java program to demonstrate Working of toUpperCase()// method of Locale class // Importing Locale class from java.util packageimport java.util.Locale; // Main classclass GFG { // Main driver method public static void main(String args[]) { // Custom input string String str = "Geeks for Geeks"; // Locales with the language "tr" for TURKISH //"en" for ENGLISH is created Locale TURKISH = Locale.forLanguageTag("tr"); Locale ENGLISH = Locale.forLanguageTag("en"); // Converting string str to uppercase letter // using TURKISH and ENGLISH language String strup1 = str.toUpperCase(TURKISH); String strup2 = str.toUpperCase(ENGLISH); System.out.println(strup1); System.out.println(strup2); }} GEEKS FOR GEEKS GEEKS FOR GEEKS mihir89 solankimayank Java-Functions Java-Strings Java Java-Strings Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to iterate any Map in Java Interfaces in Java HashMap in Java with Examples Stream In Java ArrayList in Java Collections in Java Singleton Class in Java Multidimensional Arrays in Java Set in Java Stack Class in Java
[ { "code": null, "e": 53, "s": 25, "text": "\n04 Oct, 2021" }, { "code": null, "e": 393, "s": 53, "text": "The java string toUpperCase() method of String class has converted all characters of the string into an uppercase letter. There is two variant of toUpperCase() method. The key thing that is to be taken into consideration is toUpperCase() method worked same as to UpperCase(Locale.getDefault()) method as internally default locale is used. " }, { "code": null, "e": 401, "s": 393, "text": "Syntax:" }, { "code": null, "e": 439, "s": 401, "text": "public String toUpperCase(Locale loc)" }, { "code": null, "e": 467, "s": 439, "text": "public String toUpperCase()" }, { "code": null, "e": 480, "s": 467, "text": "Parameter: " }, { "code": null, "e": 554, "s": 480, "text": "Type 1: Locale value to be applied as it converts all the characters into" }, { "code": null, "e": 565, "s": 554, "text": "Type 2: NA" }, { "code": null, "e": 622, "s": 565, "text": "Return Type: It returns the string in uppercase letters." }, { "code": null, "e": 683, "s": 622, "text": "Note: Lowercase is done using the rules of the given Locale." }, { "code": null, "e": 694, "s": 683, "text": "Example 1:" }, { "code": null, "e": 699, "s": 694, "text": "java" }, { "code": "// Java Program to Demonstrate Working of toUpperCase()// method // Main classclass GFG { // Main driver method public static void main(String args[]) { // Custom input string String str = \"Welcome! to Geeksforgeeks\"; // Converting above input string to // uppercase letters using UpperCase() method String strup = str.toUpperCase(); // Print the uppercased string System.out.println(strup); }}", "e": 1164, "s": 699, "text": null }, { "code": null, "e": 1190, "s": 1164, "text": "WELCOME! TO GEEKSFORGEEKS" }, { "code": null, "e": 1201, "s": 1190, "text": "Example 2:" }, { "code": null, "e": 1206, "s": 1201, "text": "java" }, { "code": "// Java program to demonstrate Working of toUpperCase()// method of Locale class // Importing Locale class from java.util packageimport java.util.Locale; // Main classclass GFG { // Main driver method public static void main(String args[]) { // Custom input string String str = \"Geeks for Geeks\"; // Locales with the language \"tr\" for TURKISH //\"en\" for ENGLISH is created Locale TURKISH = Locale.forLanguageTag(\"tr\"); Locale ENGLISH = Locale.forLanguageTag(\"en\"); // Converting string str to uppercase letter // using TURKISH and ENGLISH language String strup1 = str.toUpperCase(TURKISH); String strup2 = str.toUpperCase(ENGLISH); System.out.println(strup1); System.out.println(strup2); }}", "e": 2003, "s": 1206, "text": null }, { "code": null, "e": 2035, "s": 2003, "text": "GEEKS FOR GEEKS\nGEEKS FOR GEEKS" }, { "code": null, "e": 2043, "s": 2035, "text": "mihir89" }, { "code": null, "e": 2057, "s": 2043, "text": "solankimayank" }, { "code": null, "e": 2072, "s": 2057, "text": "Java-Functions" }, { "code": null, "e": 2085, "s": 2072, "text": "Java-Strings" }, { "code": null, "e": 2090, "s": 2085, "text": "Java" }, { "code": null, "e": 2103, "s": 2090, "text": "Java-Strings" }, { "code": null, "e": 2108, "s": 2103, "text": "Java" }, { "code": null, "e": 2206, "s": 2108, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2237, "s": 2206, "text": "How to iterate any Map in Java" }, { "code": null, "e": 2256, "s": 2237, "text": "Interfaces in Java" }, { "code": null, "e": 2286, "s": 2256, "text": "HashMap in Java with Examples" }, { "code": null, "e": 2301, "s": 2286, "text": "Stream In Java" }, { "code": null, "e": 2319, "s": 2301, "text": "ArrayList in Java" }, { "code": null, "e": 2339, "s": 2319, "text": "Collections in Java" }, { "code": null, "e": 2363, "s": 2339, "text": "Singleton Class in Java" }, { "code": null, "e": 2395, "s": 2363, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 2407, "s": 2395, "text": "Set in Java" } ]
Matplotlib.colors.DivergingNorm class in Python
06 Oct, 2021 Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack. The matplotlib.colors.DivergingNorm class belongs to the matplotlib.colors module. The matplotlib.colors module is used for converting color or numbers arguments to RGBA or RGB.This module is used for mapping numbers to colors or color specification conversion in a 1-D array of colors also known as colormap.The matplotlib.colors.DivergingNorm class is very useful while mapping data with uneven or unequal rate of change around a conceptual center. For instance data range between -2 to, with 0 as the center or mid-point. Syntax: matplotlib.colors.DivergingNorm(vcenter, vmin, vmax)Parameters: vcenter: It accepts a float valuethat defines the 0.5 data value in the normalization. vmin: It is an optional parameter that accepts float values and defines 0.0 data value in normalization which defaults to the minimum value of dataset. vmax: It is an optional parameter that accepts float values and defines 1.0 data value in normalization which defaults to the maximum value of dataset. vcenter: It accepts a float valuethat defines the 0.5 data value in the normalization. vmin: It is an optional parameter that accepts float values and defines 0.0 data value in normalization which defaults to the minimum value of dataset. vmax: It is an optional parameter that accepts float values and defines 1.0 data value in normalization which defaults to the maximum value of dataset. Example 1: Python3 import numpyfrom matplotlib import pyplot as pltfrom matplotlib import colors # dummy data to plotx = numpy.linspace(0, 2*numpy.pi, 30)y = numpy.linspace(0, 2*numpy.pi, 20)[A, B] = numpy.meshgrid(x, y)Q = numpy.sin(A)*numpy.cos(B) fig = plt.figure()plt.ion() # yellow to green to red# colormapplt.set_cmap('brg') ax = fig.add_subplot(1, 2, 1)plt.pcolor(A, B, Q)plt.colorbar() ax = fig.add_subplot(1, 2, 2) # defining the scale, with white# at zerovmin = -0.2vmax = 0.8norms = colors.DivergingNorm(vmin=vmin, vcenter=0, vmax=vmax) plt.pcolor(A, B, Q, vmin=vmin, vmax=vmax, norm=norms) plt.colorbar() Output: Example 2: Python3 import numpy as npimport matplotlib.pyplot as pltimport matplotlib.cbook as cbookimport matplotlib.colors as colors file = cbook.get_sample_data('topobathy.npz', asfileobj = False) with np.load(file) as example: topo = example['topo'] longi = example['longitude'] latit = example['latitude'] figure, axes = plt.subplots(constrained_layout = True) # creating a colormap that# has land and ocean clearly# delineated and of the# same length (256 + 256)undersea = plt.cm.terrain(np.linspace(0, 0.17, 256))land = plt.cm.terrain(np.linspace(0.25, 1, 256))every_colors = np.vstack((undersea, land)) terrain_map = colors.LinearSegmentedColormap.from_list('terrain_map', every_colors) # the center is offset so that# the land has more dynamic range# while making the normdiversity_norm = colors.DivergingNorm(vmin =-500, vcenter = 0, vmax = 4000) pcm = axes.pcolormesh(longi, latit, topo, rasterized = True, norm = diversity_norm, cmap = terrain_map, ) axes.set_xlabel('Longitude $[^o E]$')axes.set_ylabel('Latitude $[^o N]$')axes.set_aspect(1 / np.cos(np.deg2rad(49))) figure.colorbar(pcm, shrink = 0.6, extend ='both', label ='Elevation [m]')plt.show() Output: gabaa406 Python-matplotlib Python Write From Home 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() Convert integer to string in Python Convert string to integer in Python How to set input type date in dd-mm-yyyy format using HTML ? Python infinity Similarities and Difference between Java and C++
[ { "code": null, "e": 28, "s": 0, "text": "\n06 Oct, 2021" }, { "code": null, "e": 242, "s": 28, "text": "Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack. " }, { "code": null, "e": 768, "s": 242, "text": "The matplotlib.colors.DivergingNorm class belongs to the matplotlib.colors module. The matplotlib.colors module is used for converting color or numbers arguments to RGBA or RGB.This module is used for mapping numbers to colors or color specification conversion in a 1-D array of colors also known as colormap.The matplotlib.colors.DivergingNorm class is very useful while mapping data with uneven or unequal rate of change around a conceptual center. For instance data range between -2 to, with 0 as the center or mid-point. " }, { "code": null, "e": 842, "s": 768, "text": "Syntax: matplotlib.colors.DivergingNorm(vcenter, vmin, vmax)Parameters: " }, { "code": null, "e": 1234, "s": 842, "text": "vcenter: It accepts a float valuethat defines the 0.5 data value in the normalization. vmin: It is an optional parameter that accepts float values and defines 0.0 data value in normalization which defaults to the minimum value of dataset. vmax: It is an optional parameter that accepts float values and defines 1.0 data value in normalization which defaults to the maximum value of dataset. " }, { "code": null, "e": 1322, "s": 1234, "text": "vcenter: It accepts a float valuethat defines the 0.5 data value in the normalization. " }, { "code": null, "e": 1475, "s": 1322, "text": "vmin: It is an optional parameter that accepts float values and defines 0.0 data value in normalization which defaults to the minimum value of dataset. " }, { "code": null, "e": 1628, "s": 1475, "text": "vmax: It is an optional parameter that accepts float values and defines 1.0 data value in normalization which defaults to the maximum value of dataset. " }, { "code": null, "e": 1643, "s": 1630, "text": "Example 1: " }, { "code": null, "e": 1651, "s": 1643, "text": "Python3" }, { "code": "import numpyfrom matplotlib import pyplot as pltfrom matplotlib import colors # dummy data to plotx = numpy.linspace(0, 2*numpy.pi, 30)y = numpy.linspace(0, 2*numpy.pi, 20)[A, B] = numpy.meshgrid(x, y)Q = numpy.sin(A)*numpy.cos(B) fig = plt.figure()plt.ion() # yellow to green to red# colormapplt.set_cmap('brg') ax = fig.add_subplot(1, 2, 1)plt.pcolor(A, B, Q)plt.colorbar() ax = fig.add_subplot(1, 2, 2) # defining the scale, with white# at zerovmin = -0.2vmax = 0.8norms = colors.DivergingNorm(vmin=vmin, vcenter=0, vmax=vmax) plt.pcolor(A, B, Q, vmin=vmin, vmax=vmax, norm=norms) plt.colorbar()", "e": 2339, "s": 1651, "text": null }, { "code": null, "e": 2348, "s": 2339, "text": "Output: " }, { "code": null, "e": 2361, "s": 2348, "text": "Example 2: " }, { "code": null, "e": 2369, "s": 2361, "text": "Python3" }, { "code": "import numpy as npimport matplotlib.pyplot as pltimport matplotlib.cbook as cbookimport matplotlib.colors as colors file = cbook.get_sample_data('topobathy.npz', asfileobj = False) with np.load(file) as example: topo = example['topo'] longi = example['longitude'] latit = example['latitude'] figure, axes = plt.subplots(constrained_layout = True) # creating a colormap that# has land and ocean clearly# delineated and of the# same length (256 + 256)undersea = plt.cm.terrain(np.linspace(0, 0.17, 256))land = plt.cm.terrain(np.linspace(0.25, 1, 256))every_colors = np.vstack((undersea, land)) terrain_map = colors.LinearSegmentedColormap.from_list('terrain_map', every_colors) # the center is offset so that# the land has more dynamic range# while making the normdiversity_norm = colors.DivergingNorm(vmin =-500, vcenter = 0, vmax = 4000) pcm = axes.pcolormesh(longi, latit, topo, rasterized = True, norm = diversity_norm, cmap = terrain_map, ) axes.set_xlabel('Longitude $[^o E]$')axes.set_ylabel('Latitude $[^o N]$')axes.set_aspect(1 / np.cos(np.deg2rad(49))) figure.colorbar(pcm, shrink = 0.6, extend ='both', label ='Elevation [m]')plt.show()", "e": 3773, "s": 2369, "text": null }, { "code": null, "e": 3783, "s": 3773, "text": "Output: " }, { "code": null, "e": 3794, "s": 3785, "text": "gabaa406" }, { "code": null, "e": 3812, "s": 3794, "text": "Python-matplotlib" }, { "code": null, "e": 3819, "s": 3812, "text": "Python" }, { "code": null, "e": 3835, "s": 3819, "text": "Write From Home" }, { "code": null, "e": 3933, "s": 3835, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3951, "s": 3933, "text": "Python Dictionary" }, { "code": null, "e": 3993, "s": 3951, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 4015, "s": 3993, "text": "Enumerate() in Python" }, { "code": null, "e": 4050, "s": 4015, "text": "Read a file line by line in Python" }, { "code": null, "e": 4076, "s": 4050, "text": "Python String | replace()" }, { "code": null, "e": 4112, "s": 4076, "text": "Convert integer to string in Python" }, { "code": null, "e": 4148, "s": 4112, "text": "Convert string to integer in Python" }, { "code": null, "e": 4209, "s": 4148, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 4225, "s": 4209, "text": "Python infinity" } ]
Python List list() Method
Python list method list() takes sequence types and converts them to lists. This is used to convert a given tuple into list. Note − Tuple are very similar to lists with only difference that element values of a tuple can not be changed and tuple elements are put between parentheses instead of square bracket. Following is the syntax for list() method − list( seq ) seq − This is a tuple to be converted into list. seq − This is a tuple to be converted into list. This method returns the list. The following example shows the usage of list() method. #!/usr/bin/python aTuple = (123, 'xyz', 'zara', 'abc'); aList = list(aTuple) print "List elements : ", aList When we run above program, it produces following result − List elements : [123, 'xyz', 'zara', 'abc']
[ { "code": null, "e": 2502, "s": 2378, "text": "Python list method list() takes sequence types and converts them to lists. This is used to convert a given tuple into list." }, { "code": null, "e": 2686, "s": 2502, "text": "Note − Tuple are very similar to lists with only difference that element values of a tuple can not be changed and tuple elements are put between parentheses instead of square bracket." }, { "code": null, "e": 2730, "s": 2686, "text": "Following is the syntax for list() method −" }, { "code": null, "e": 2743, "s": 2730, "text": "list( seq )\n" }, { "code": null, "e": 2792, "s": 2743, "text": "seq − This is a tuple to be converted into list." }, { "code": null, "e": 2841, "s": 2792, "text": "seq − This is a tuple to be converted into list." }, { "code": null, "e": 2871, "s": 2841, "text": "This method returns the list." }, { "code": null, "e": 2927, "s": 2871, "text": "The following example shows the usage of list() method." }, { "code": null, "e": 3037, "s": 2927, "text": "#!/usr/bin/python\n\naTuple = (123, 'xyz', 'zara', 'abc');\naList = list(aTuple)\nprint \"List elements : \", aList" }, { "code": null, "e": 3095, "s": 3037, "text": "When we run above program, it produces following result −" } ]
Encrypt and Decrypt Image using Java
04 Aug, 2021 Encryption is the process of converting information or data into a secrete code, especially to prevent unauthorized access. In these cases also we will do the same, For encryption, we will convert the image into a byte array and after converting it we will apply XOR operation on each value of the byte array and after performing XOR operation on each and every value of byte array will be changed. After performing the operation now we will write new data in Image due to which we are unable to open the Encrypted Image. Here are key will act as a password to Encrypt and Decrypt the Image. XOR Operation As we know that how to perform XOR operations now we will see how XOR operation will work here. Let’s consider an example of sample input and output. Input: int key = 8 int byte_val = 5 Operation: // Performing XOR operation between key and byte_val key ^ byte_val Output: // Output of XOR operation 13 Operation: // Performing XOR operation between output and key 13 ^ key Output: // byte_val 5 Example 1: Here, is the screenshot of the above example. Let’s have a look. In the above example, we have clearly observed that our key = 8 and byte_val = 5, and When we perform XOR operation on key and byte_val it gives the output as 13, now if we again perform XOR operation on our output “13” and key, we get our byte_val again. The same operation performed in the case of Encryption and Decryption as well. XOR operation performed between each and every value of byte array and key due to which all data of Image get change and due to which we are unable to open our Image. Now, whenever we apply a Decryption operation with the same key-value byte array value get the change to its original value and able to see our original Image. Note: You can execute the given below code in any IDE offline as you need an input image location from where it can load the image as you have specified in the path for encryption and decryption. Execute on IDE: Open IDE like eclipse IDE. Create a new project. Create a new class like Encryption or Decryption as required. Write the following code given below for encryption and Decryption in IDE. Just press Ctrl+S to save or you can go to file and click on save. Now, to run the code just select the class you want to execute like encryption then right-click. Run as a java application. Now, you will see the console window for output. Let’s have a look at the Screenshot for the above-mentioned steps. Executable code of Encryption: Java import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.util.Scanner; public class Encryption { public static void main(String[] args) throws FileNotFoundException, IOException { Scanner sc = new Scanner(System.in); System.out.println("Note : Encryption Key act as Password to Decrypt the same Image,otherwise it will corrupt the Image."); // Here key is act as password to Encrypt and // Decrypt the Image System.out.print("Enter key for Encryption : "); int key = sc.nextInt(); // Selecting a Image for operation FileInputStream fis = new FileInputStream( "C:\\Users\\lenovo\\Pictures\\logo4.png"); // Converting Image into byte array, create a // array of same size as Image size byte data[] = new byte[fis.available()]; // Read the array fis.read(data); int i = 0; // Performing an XOR operation on each value of // byte array due to which every value of Image // will change. for (byte b : data) { data[i] = (byte)(b ^ key); i++; } // Opening a file for writing purpose FileOutputStream fos = new FileOutputStream( "C:\\Users\\lenovo\\Pictures\\logo4.png"); // Writing new byte array value to image which // will Encrypt it. fos.write(data); // Closing file fos.close(); fis.close(); System.out.println("Encryption Done..."); }} Note: Encryption Key act as Password to Decrypt the same Image,otherwise it will corrupt the Image. Enter key for Encryption : 1234 Encryption Done... Decryption means the conversion of encrypted data into its original form is nothing but Decryption. In the case of Image Decryption as well we convert out encrypted Image into its original form. Here we will use XOR operation to perform decryption as well. As we observe in the above example of XOR that how we get our original value of byte array by performing XOR operation on output and key value. Same logic we will use here. Java import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.util.Scanner; public class Decryption { public static void main(String[] args) throws FileNotFoundException, IOException { Scanner sc = new Scanner(System.in); System.out.println( "Note : Encryption Key act as Password to Decrypt the same Image, otherwise it will corrupt the Image."); System.out.print("Enter a key for Decryption : "); int key = sc.nextInt(); // Selecting a Image for Decryption. FileInputStream fis = new FileInputStream( "C:\\Users\\lenovo\\Pictures\\logo4.png"); // Converting image into byte array,it will // Create a array of same size as image. byte data[] = new byte[fis.available()]; // Read the array fis.read(data); int i = 0; // Performing an XOR operation // on each value of // byte array to Decrypt it. for (byte b : data) { data[i] = (byte)(b ^ key); i++; } // Opening file for writting purpose FileOutputStream fos = new FileOutputStream( "C:\\Users\\lenovo\\Pictures\\logo4.png"); // Writting Decrypted data on Image fos.write(data); fos.close(); fis.close(); System.out.println("Decryption Done..."); }} Note: Encryption Key act as Password to Decrypt the same Image,otherwise it will corrupt the Image. Enter a key for Decryption : 1234 Decryption Done... By using the same logic of Encryption and Decryption of Image we can also create a small GUI project as well. Let’s have a look. simmytarika5 surindertarika1234 Java Java Programs Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n04 Aug, 2021" }, { "code": null, "e": 645, "s": 52, "text": "Encryption is the process of converting information or data into a secrete code, especially to prevent unauthorized access. In these cases also we will do the same, For encryption, we will convert the image into a byte array and after converting it we will apply XOR operation on each value of the byte array and after performing XOR operation on each and every value of byte array will be changed. After performing the operation now we will write new data in Image due to which we are unable to open the Encrypted Image. Here are key will act as a password to Encrypt and Decrypt the Image. " }, { "code": null, "e": 661, "s": 645, "text": "XOR Operation " }, { "code": null, "e": 811, "s": 661, "text": "As we know that how to perform XOR operations now we will see how XOR operation will work here. Let’s consider an example of sample input and output." }, { "code": null, "e": 818, "s": 811, "text": "Input:" }, { "code": null, "e": 848, "s": 818, "text": "int key = 8 \nint byte_val = 5" }, { "code": null, "e": 859, "s": 848, "text": "Operation:" }, { "code": null, "e": 937, "s": 859, "text": "// Performing XOR operation between key and byte_val \nkey ^ byte_val " }, { "code": null, "e": 945, "s": 937, "text": "Output:" }, { "code": null, "e": 990, "s": 945, "text": "// Output of XOR operation \n13 " }, { "code": null, "e": 1001, "s": 990, "text": "Operation:" }, { "code": null, "e": 1077, "s": 1001, "text": "// Performing XOR operation between output and key\n13 ^ key " }, { "code": null, "e": 1085, "s": 1077, "text": "Output:" }, { "code": null, "e": 1116, "s": 1085, "text": "// byte_val\n5 " }, { "code": null, "e": 1127, "s": 1116, "text": "Example 1:" }, { "code": null, "e": 1192, "s": 1127, "text": "Here, is the screenshot of the above example. Let’s have a look." }, { "code": null, "e": 1528, "s": 1192, "text": "In the above example, we have clearly observed that our key = 8 and byte_val = 5, and When we perform XOR operation on key and byte_val it gives the output as 13, now if we again perform XOR operation on our output “13” and key, we get our byte_val again. The same operation performed in the case of Encryption and Decryption as well. " }, { "code": null, "e": 1855, "s": 1528, "text": "XOR operation performed between each and every value of byte array and key due to which all data of Image get change and due to which we are unable to open our Image. Now, whenever we apply a Decryption operation with the same key-value byte array value get the change to its original value and able to see our original Image." }, { "code": null, "e": 2051, "s": 1855, "text": "Note: You can execute the given below code in any IDE offline as you need an input image location from where it can load the image as you have specified in the path for encryption and decryption." }, { "code": null, "e": 2067, "s": 2051, "text": "Execute on IDE:" }, { "code": null, "e": 2094, "s": 2067, "text": "Open IDE like eclipse IDE." }, { "code": null, "e": 2116, "s": 2094, "text": "Create a new project." }, { "code": null, "e": 2178, "s": 2116, "text": "Create a new class like Encryption or Decryption as required." }, { "code": null, "e": 2253, "s": 2178, "text": "Write the following code given below for encryption and Decryption in IDE." }, { "code": null, "e": 2320, "s": 2253, "text": "Just press Ctrl+S to save or you can go to file and click on save." }, { "code": null, "e": 2417, "s": 2320, "text": "Now, to run the code just select the class you want to execute like encryption then right-click." }, { "code": null, "e": 2444, "s": 2417, "text": "Run as a java application." }, { "code": null, "e": 2493, "s": 2444, "text": "Now, you will see the console window for output." }, { "code": null, "e": 2561, "s": 2493, "text": "Let’s have a look at the Screenshot for the above-mentioned steps. " }, { "code": null, "e": 2593, "s": 2561, "text": "Executable code of Encryption: " }, { "code": null, "e": 2598, "s": 2593, "text": "Java" }, { "code": "import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.util.Scanner; public class Encryption { public static void main(String[] args) throws FileNotFoundException, IOException { Scanner sc = new Scanner(System.in); System.out.println(\"Note : Encryption Key act as Password to Decrypt the same Image,otherwise it will corrupt the Image.\"); // Here key is act as password to Encrypt and // Decrypt the Image System.out.print(\"Enter key for Encryption : \"); int key = sc.nextInt(); // Selecting a Image for operation FileInputStream fis = new FileInputStream( \"C:\\\\Users\\\\lenovo\\\\Pictures\\\\logo4.png\"); // Converting Image into byte array, create a // array of same size as Image size byte data[] = new byte[fis.available()]; // Read the array fis.read(data); int i = 0; // Performing an XOR operation on each value of // byte array due to which every value of Image // will change. for (byte b : data) { data[i] = (byte)(b ^ key); i++; } // Opening a file for writing purpose FileOutputStream fos = new FileOutputStream( \"C:\\\\Users\\\\lenovo\\\\Pictures\\\\logo4.png\"); // Writing new byte array value to image which // will Encrypt it. fos.write(data); // Closing file fos.close(); fis.close(); System.out.println(\"Encryption Done...\"); }}", "e": 4438, "s": 2598, "text": null }, { "code": null, "e": 4538, "s": 4438, "text": "Note: Encryption Key act as Password to Decrypt the same Image,otherwise it will corrupt the Image." }, { "code": null, "e": 4571, "s": 4538, "text": "Enter key for Encryption : 1234 " }, { "code": null, "e": 4592, "s": 4571, "text": "Encryption Done... " }, { "code": null, "e": 5022, "s": 4592, "text": "Decryption means the conversion of encrypted data into its original form is nothing but Decryption. In the case of Image Decryption as well we convert out encrypted Image into its original form. Here we will use XOR operation to perform decryption as well. As we observe in the above example of XOR that how we get our original value of byte array by performing XOR operation on output and key value. Same logic we will use here." }, { "code": null, "e": 5027, "s": 5022, "text": "Java" }, { "code": "import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.util.Scanner; public class Decryption { public static void main(String[] args) throws FileNotFoundException, IOException { Scanner sc = new Scanner(System.in); System.out.println( \"Note : Encryption Key act as Password to Decrypt the same Image, otherwise it will corrupt the Image.\"); System.out.print(\"Enter a key for Decryption : \"); int key = sc.nextInt(); // Selecting a Image for Decryption. FileInputStream fis = new FileInputStream( \"C:\\\\Users\\\\lenovo\\\\Pictures\\\\logo4.png\"); // Converting image into byte array,it will // Create a array of same size as image. byte data[] = new byte[fis.available()]; // Read the array fis.read(data); int i = 0; // Performing an XOR operation // on each value of // byte array to Decrypt it. for (byte b : data) { data[i] = (byte)(b ^ key); i++; } // Opening file for writting purpose FileOutputStream fos = new FileOutputStream( \"C:\\\\Users\\\\lenovo\\\\Pictures\\\\logo4.png\"); // Writting Decrypted data on Image fos.write(data); fos.close(); fis.close(); System.out.println(\"Decryption Done...\"); }}", "e": 6551, "s": 5027, "text": null }, { "code": null, "e": 6651, "s": 6551, "text": "Note: Encryption Key act as Password to Decrypt the same Image,otherwise it will corrupt the Image." }, { "code": null, "e": 6686, "s": 6651, "text": "Enter a key for Decryption : 1234 " }, { "code": null, "e": 6707, "s": 6686, "text": "Decryption Done... " }, { "code": null, "e": 6836, "s": 6707, "text": "By using the same logic of Encryption and Decryption of Image we can also create a small GUI project as well. Let’s have a look." }, { "code": null, "e": 6851, "s": 6838, "text": "simmytarika5" }, { "code": null, "e": 6870, "s": 6851, "text": "surindertarika1234" }, { "code": null, "e": 6875, "s": 6870, "text": "Java" }, { "code": null, "e": 6889, "s": 6875, "text": "Java Programs" }, { "code": null, "e": 6894, "s": 6889, "text": "Java" } ]
LOCATE() function in MySQL
17 Dec, 2020 LOCATE() function in MySQL is used for finding the location of a substring in a string. It will return the location of the first occurrence of the substring in the string. If the substring is not present in the string then it will return 0. When searching for the location of a substring in a string it does not perform a case-sensitive search. Syntax : LOCATE(substring, string, start) Parameters : This method accepts three parameter. substring –The string whose position is to be retrieved. string –The string within which the position of the substring is to be retrieved. start –The starting position for the search. It is optional .Position 1 is default. Returns :The location of the first occurrence of the substring in the string. Example-1 : Searching the String ‘f’ in the string ‘geeksforgeeks’ with the help of LOCATE Function. SELECT LOCATE('f', 'geeksforgeeks') AS MatchLocation; Output : Example-2 : Searching the String ‘MYSQL’ in the string ‘Learning SQL is fun’ with the help of LOCATE Function.So, it will return 0. SELECT LOCATE('MYSQL', 'Learning SQL is fun') AS MatchLocation; Output : Example-3 :Searching the String ‘g’ in the string ‘geeksforgeeks’ with the help of LOCATE Function starting from position 3. SELECT LOCATE('g', 'geeksforgeeks', 3) AS MatchLocation; Output : Example-4 :LOCATE Function can also be used on column data. To demonstrate create a table named Student. CREATE TABLE Student ( Student_id INT AUTO_INCREMENT, Student_name VARCHAR(100) NOT NULL, Roll INT NOT NULL, Department VARCHAR(10) NOT NULL, PRIMARY KEY(Student_id ) ); Inserting some data to the Student table : INSERT INTO Student (Student_name, Roll, Department ) VALUES ('Anik Biswas ', 10100, 'CSE'), ('Bina Mallick', 11000, 'ECE' ), ('Aniket Sharma', 12000, 'IT' ), ('Sayani Samanta', 13000, 'ME' ), ('Riyanka Shah ', 14000, 'EE' ), ('Bipin Kohli', 15000, 'CE' ); So, the Student Table is as follows. SELECT * from Student ; Now, we will find the first occurrence of string ‘a’ in the Student_name column with the help of LOCATE function. SELECT *, LOCATE('a', Student_name ) AS FirstOccurrenceOfA FROM STUDENT; DBMS-SQL mysql SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n17 Dec, 2020" }, { "code": null, "e": 373, "s": 28, "text": "LOCATE() function in MySQL is used for finding the location of a substring in a string. It will return the location of the first occurrence of the substring in the string. If the substring is not present in the string then it will return 0. When searching for the location of a substring in a string it does not perform a case-sensitive search." }, { "code": null, "e": 382, "s": 373, "text": "Syntax :" }, { "code": null, "e": 415, "s": 382, "text": "LOCATE(substring, string, start)" }, { "code": null, "e": 428, "s": 415, "text": "Parameters :" }, { "code": null, "e": 465, "s": 428, "text": "This method accepts three parameter." }, { "code": null, "e": 522, "s": 465, "text": "substring –The string whose position is to be retrieved." }, { "code": null, "e": 604, "s": 522, "text": "string –The string within which the position of the substring is to be retrieved." }, { "code": null, "e": 688, "s": 604, "text": "start –The starting position for the search. It is optional .Position 1 is default." }, { "code": null, "e": 766, "s": 688, "text": "Returns :The location of the first occurrence of the substring in the string." }, { "code": null, "e": 867, "s": 766, "text": "Example-1 : Searching the String ‘f’ in the string ‘geeksforgeeks’ with the help of LOCATE Function." }, { "code": null, "e": 921, "s": 867, "text": "SELECT LOCATE('f', 'geeksforgeeks') AS MatchLocation;" }, { "code": null, "e": 930, "s": 921, "text": "Output :" }, { "code": null, "e": 1062, "s": 930, "text": "Example-2 : Searching the String ‘MYSQL’ in the string ‘Learning SQL is fun’ with the help of LOCATE Function.So, it will return 0." }, { "code": null, "e": 1126, "s": 1062, "text": "SELECT LOCATE('MYSQL', 'Learning SQL is fun') AS MatchLocation;" }, { "code": null, "e": 1135, "s": 1126, "text": "Output :" }, { "code": null, "e": 1260, "s": 1135, "text": "Example-3 :Searching the String ‘g’ in the string ‘geeksforgeeks’ with the help of LOCATE Function starting from position 3." }, { "code": null, "e": 1317, "s": 1260, "text": "SELECT LOCATE('g', 'geeksforgeeks', 3) AS MatchLocation;" }, { "code": null, "e": 1326, "s": 1317, "text": "Output :" }, { "code": null, "e": 1431, "s": 1326, "text": "Example-4 :LOCATE Function can also be used on column data. To demonstrate create a table named Student." }, { "code": null, "e": 1603, "s": 1431, "text": "CREATE TABLE Student\n(\nStudent_id INT AUTO_INCREMENT, \nStudent_name VARCHAR(100) NOT NULL,\nRoll INT NOT NULL,\nDepartment VARCHAR(10) NOT NULL,\nPRIMARY KEY(Student_id )\n);" }, { "code": null, "e": 1646, "s": 1603, "text": "Inserting some data to the Student table :" }, { "code": null, "e": 1904, "s": 1646, "text": "INSERT INTO Student\n(Student_name, Roll, Department )\nVALUES\n('Anik Biswas ', 10100, 'CSE'),\n('Bina Mallick', 11000, 'ECE' ),\n('Aniket Sharma', 12000, 'IT' ),\n('Sayani Samanta', 13000, 'ME' ),\n('Riyanka Shah ', 14000, 'EE' ),\n('Bipin Kohli', 15000, 'CE' );" }, { "code": null, "e": 1941, "s": 1904, "text": "So, the Student Table is as follows." }, { "code": null, "e": 1966, "s": 1941, "text": "SELECT * from Student ;" }, { "code": null, "e": 2080, "s": 1966, "text": "Now, we will find the first occurrence of string ‘a’ in the Student_name column with the help of LOCATE function." }, { "code": null, "e": 2155, "s": 2080, "text": "SELECT *, LOCATE('a', Student_name ) AS FirstOccurrenceOfA \nFROM STUDENT;" }, { "code": null, "e": 2164, "s": 2155, "text": "DBMS-SQL" }, { "code": null, "e": 2170, "s": 2164, "text": "mysql" }, { "code": null, "e": 2174, "s": 2170, "text": "SQL" }, { "code": null, "e": 2178, "s": 2174, "text": "SQL" } ]
Pythagorean Quadruple
22 Jun, 2022 Given four points, check whether they form Pythagorean Quadruple. It is defined as a tuple of integers a, b, c, d such that . They are basically the solutions of Diophantine Equations. In the geometric interpretation it represents a cuboid with integer side lengths |a|, |b|, |c| and whose space diagonal is |d| . The cuboids sides shown here are examples of pythagorean quadruples. It is primitive when their greatest common divisor is 1. Every Pythagorean quadruple is an integer multiple of a primitive quadruple. We can generate the set of primitive pythagorean quadruples for which a is odd can be generated by formula : a = m2 + n2 – p2 – q2, b = 2(mq + np), c = 2(nq – mp), d = m2 + n2 + p2 + q2 where m, n, p, q are non-negative integers with greatest common divisor 1 such that m + n + p + q are odd. Thus, all primitive Pythagorean quadruples are characterized by Lebesgue’s identity. (m2 + n2 + p2 + q2)2 = (2mq + 2nq)2 + 2(nq – mp)2 + (m2 + n2 – p2 – q2)m2 + n2 – p2 – q2 C++ Java Python3 C# PHP Javascript // C++ code to detect Pythagorean Quadruples.#include <bits/stdc++.h>using namespace std; // function for checkingbool pythagorean_quadruple(int a, int b, int c, int d){ int sum = a * a + b * b + c * c; if (d * d == sum) return true; else return false;} // Driver Codeint main(){ int a = 1, b = 2, c = 2, d = 3; if (pythagorean_quadruple(a, b, c, d)) cout << "Yes" << endl; else cout << "No" << endl;} // Java code to detect Pythagorean Quadruples.import java.io.*;import java.util.*; class GFG { // function for checkingstatic Boolean pythagorean_quadruple(int a, int b, int c, int d){ int sum = a * a + b * b + c * c; if (d * d == sum) return true; else return false;} // Driver function public static void main (String[] args) { int a = 1, b = 2, c = 2, d = 3; if (pythagorean_quadruple(a, b, c, d)) System.out.println("Yes"); else System.out.println("No" ); }}// This code is contributed by Gitanjali. # Python code to detect# Pythagorean Quadruples.import math # function for checkingdef pythagorean_quadruple(a,b, c, d): sum = a * a + b * b + c * c; if (d * d == sum): return True else: return False #driver codea = 1b = 2c = 2d = 3if (pythagorean_quadruple(a, b, c, d)): print("Yes")else: print("No" ) # This code is contributed# by Gitanjali. // C# code to detect// Pythagorean Quadruples.using System; class GFG { // function for checking static Boolean pythagorean_quadruple(int a, int b, int c, int d) { int sum = a * a + b * b + c * c; if (d * d == sum) return true; else return false; } // Driver function public static void Main () { int a = 1, b = 2, c = 2, d = 3; if (pythagorean_quadruple(a, b, c, d)) Console.WriteLine("Yes"); else Console.WriteLine("No" ); }} // This code is contributed by vt_M. <?php// php code to detect Pythagorean Quadruples. // function for checkingfunction pythagorean_quadruple($a, $b, $c, $d){ $sum = $a * $a + $b * $b + $c * $c; if ($d * $d == $sum) return true; else return false;} // Driver Code $a = 1; $b = 2; $c = 2; $d = 3; if (pythagorean_quadruple($a, $b, $c, $d)) echo "Yes" ; else echo "No" ; // This code is contributed by anuj_67.?> <script> // JavaScript program to detect Pythagorean Quadruples. // function for checkingfunction pythagorean_quadruple(a, b, c, d){ let sum = a * a + b * b + c * c; if (d * d == sum) return true; else return false;} // Driver code let a = 1, b = 2, c = 2, d = 3; if (pythagorean_quadruple(a, b, c, d)) document.write("Yes"); else document.write("No" ); </script> Output: Yes Time Complexity: O(1) Auxiliary Space: O(1) References Wiki mathworld vt_m splevel62 mailaruyashaswi Geometric Geometric Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n22 Jun, 2022" }, { "code": null, "e": 368, "s": 52, "text": "Given four points, check whether they form Pythagorean Quadruple. It is defined as a tuple of integers a, b, c, d such that . They are basically the solutions of Diophantine Equations. In the geometric interpretation it represents a cuboid with integer side lengths |a|, |b|, |c| and whose space diagonal is |d| . " }, { "code": null, "e": 681, "s": 368, "text": "The cuboids sides shown here are examples of pythagorean quadruples. It is primitive when their greatest common divisor is 1. Every Pythagorean quadruple is an integer multiple of a primitive quadruple. We can generate the set of primitive pythagorean quadruples for which a is odd can be generated by formula : " }, { "code": null, "e": 758, "s": 681, "text": "a = m2 + n2 – p2 – q2, b = 2(mq + np), c = 2(nq – mp), d = m2 + n2 + p2 + q2" }, { "code": null, "e": 951, "s": 758, "text": "where m, n, p, q are non-negative integers with greatest common divisor 1 such that m + n + p + q are odd. Thus, all primitive Pythagorean quadruples are characterized by Lebesgue’s identity. " }, { "code": null, "e": 1040, "s": 951, "text": "(m2 + n2 + p2 + q2)2 = (2mq + 2nq)2 + 2(nq – mp)2 + (m2 + n2 – p2 – q2)m2 + n2 – p2 – q2" }, { "code": null, "e": 1046, "s": 1042, "text": "C++" }, { "code": null, "e": 1051, "s": 1046, "text": "Java" }, { "code": null, "e": 1059, "s": 1051, "text": "Python3" }, { "code": null, "e": 1062, "s": 1059, "text": "C#" }, { "code": null, "e": 1066, "s": 1062, "text": "PHP" }, { "code": null, "e": 1077, "s": 1066, "text": "Javascript" }, { "code": "// C++ code to detect Pythagorean Quadruples.#include <bits/stdc++.h>using namespace std; // function for checkingbool pythagorean_quadruple(int a, int b, int c, int d){ int sum = a * a + b * b + c * c; if (d * d == sum) return true; else return false;} // Driver Codeint main(){ int a = 1, b = 2, c = 2, d = 3; if (pythagorean_quadruple(a, b, c, d)) cout << \"Yes\" << endl; else cout << \"No\" << endl;}", "e": 1564, "s": 1077, "text": null }, { "code": "// Java code to detect Pythagorean Quadruples.import java.io.*;import java.util.*; class GFG { // function for checkingstatic Boolean pythagorean_quadruple(int a, int b, int c, int d){ int sum = a * a + b * b + c * c; if (d * d == sum) return true; else return false;} // Driver function public static void main (String[] args) { int a = 1, b = 2, c = 2, d = 3; if (pythagorean_quadruple(a, b, c, d)) System.out.println(\"Yes\"); else System.out.println(\"No\" ); }}// This code is contributed by Gitanjali.", "e": 2163, "s": 1564, "text": null }, { "code": "# Python code to detect# Pythagorean Quadruples.import math # function for checkingdef pythagorean_quadruple(a,b, c, d): sum = a * a + b * b + c * c; if (d * d == sum): return True else: return False #driver codea = 1b = 2c = 2d = 3if (pythagorean_quadruple(a, b, c, d)): print(\"Yes\")else: print(\"No\" ) # This code is contributed# by Gitanjali.", "e": 2540, "s": 2163, "text": null }, { "code": "// C# code to detect// Pythagorean Quadruples.using System; class GFG { // function for checking static Boolean pythagorean_quadruple(int a, int b, int c, int d) { int sum = a * a + b * b + c * c; if (d * d == sum) return true; else return false; } // Driver function public static void Main () { int a = 1, b = 2, c = 2, d = 3; if (pythagorean_quadruple(a, b, c, d)) Console.WriteLine(\"Yes\"); else Console.WriteLine(\"No\" ); }} // This code is contributed by vt_M.", "e": 3184, "s": 2540, "text": null }, { "code": "<?php// php code to detect Pythagorean Quadruples. // function for checkingfunction pythagorean_quadruple($a, $b, $c, $d){ $sum = $a * $a + $b * $b + $c * $c; if ($d * $d == $sum) return true; else return false;} // Driver Code $a = 1; $b = 2; $c = 2; $d = 3; if (pythagorean_quadruple($a, $b, $c, $d)) echo \"Yes\" ; else echo \"No\" ; // This code is contributed by anuj_67.?>", "e": 3623, "s": 3184, "text": null }, { "code": "<script> // JavaScript program to detect Pythagorean Quadruples. // function for checkingfunction pythagorean_quadruple(a, b, c, d){ let sum = a * a + b * b + c * c; if (d * d == sum) return true; else return false;} // Driver code let a = 1, b = 2, c = 2, d = 3; if (pythagorean_quadruple(a, b, c, d)) document.write(\"Yes\"); else document.write(\"No\" ); </script>", "e": 4087, "s": 3623, "text": null }, { "code": null, "e": 4096, "s": 4087, "text": "Output: " }, { "code": null, "e": 4100, "s": 4096, "text": "Yes" }, { "code": null, "e": 4144, "s": 4100, "text": "Time Complexity: O(1) Auxiliary Space: O(1)" }, { "code": null, "e": 4171, "s": 4144, "text": "References Wiki mathworld " }, { "code": null, "e": 4176, "s": 4171, "text": "vt_m" }, { "code": null, "e": 4186, "s": 4176, "text": "splevel62" }, { "code": null, "e": 4202, "s": 4186, "text": "mailaruyashaswi" }, { "code": null, "e": 4212, "s": 4202, "text": "Geometric" }, { "code": null, "e": 4222, "s": 4212, "text": "Geometric" } ]
Lexicographic rank of a string
17 Jun, 2022 Given a string, find its rank among all its permutations sorted lexicographically. For example, rank of “abc” is 1, rank of “acb” is 2, and rank of “cba” is 6. Examples: Input : str[] = "acb" Output : Rank = 2 Input : str[] = "string" Output : Rank = 598 Input : str[] = "cba" Output : Rank = 6 For simplicity, let us assume that the string does not contain any duplicated characters. One simple solution is to initialize rank as 1, generate all permutations in lexicographic order. After generating a permutation, check if the generated permutation is same as given string, if same, then return rank, if not, then increment the rank by 1. The time complexity of this solution will be exponential in worst case. Following is an efficient solution. Let the given string be “STRING”. In the input string, ‘S’ is the first character.There are total 6 characters and 4 of them are smaller than ‘S’.So there can be 4 * 5! smaller strings where first character is smaller than ‘S’, like followingR X X X X X I X X X X X N X X X X X G X X X X XNow let us Fix ‘S’ and find the smaller strings starting with ‘S’.Repeat the same process for T, rank is 4*5! + 4*4! +...Now fix T and repeat the same process for R, rank is 4*5! + 4*4! + 3*3! +...Now fix R and repeat the same process for I, rank is 4*5! + 4*4! + 3*3! + 1*2! +...Now fix I and repeat the same process for N, rank is 4*5! + 4*4! + 3*3! + 1*2! + 1*1! +...Now fix N and repeat the same process for G, rank is 4*5! + 4*4! + 3*3! + 1*2! + 1*1! + 0*0!Rank = 4*5! + 4*4! + 3*3! + 1*2! + 1*1! + 0*0! = 597Note that the above computations find count of smaller strings.Therefore rank of given string is count of smaller strings plus 1.The final rank = 1 + 597 = 598 Below is the implementation of above approach: C++ C Java Python3 C# PHP Javascript // C++ program to find lexicographic rank// of a string#include <bits/stdc++.h>#include <string.h> using namespace std;// A utility function to find factorial of nint fact(int n){ return (n <= 1) ? 1 : n * fact(n - 1);} // A utility function to count smaller characters on right// of arr[low]int findSmallerInRight(char* str, int low, int high){ int countRight = 0, i; for (i = low + 1; i <= high; ++i) if (str[i] < str[low]) ++countRight; return countRight;} // A function to find rank of a string in all permutations// of charactersint findRank(char* str){ int len = strlen(str); int mul = fact(len); int rank = 1; int countRight; int i; for (i = 0; i < len; ++i) { mul /= len - i; // count number of chars smaller than str[i] // from str[i+1] to str[len-1] countRight = findSmallerInRight(str, i, len - 1); rank += countRight * mul; } return rank;} // Driver program to test above functionint main(){ char str[] = "string"; cout << findRank(str); return 0;} // This code is contributed// by Akanksha Rai // C program to find lexicographic rank// of a string#include <stdio.h>#include <string.h> // A utility function to find factorial of nint fact(int n){ return (n <= 1) ? 1 : n * fact(n - 1);} // A utility function to count smaller characters on right// of arr[low]int findSmallerInRight(char* str, int low, int high){ int countRight = 0, i; for (i = low + 1; i <= high; ++i) if (str[i] < str[low]) ++countRight; return countRight;} // A function to find rank of a string in all permutations// of charactersint findRank(char* str){ int len = strlen(str); int mul = fact(len); int rank = 1; int countRight; int i; for (i = 0; i < len; ++i) { mul /= len - i; // count number of chars smaller than str[i] // from str[i+1] to str[len-1] countRight = findSmallerInRight(str, i, len - 1); rank += countRight * mul; } return rank;} // Driver program to test above functionint main(){ char str[] = "string"; printf("%d", findRank(str)); return 0;} // Java program to find lexicographic rank// of a stringimport java.io.*;import java.util.*; class GFG { // A utility function to find factorial of n static int fact(int n) { return (n <= 1) ? 1 : n * fact(n - 1); } // A utility function to count smaller // characters on right of arr[low] static int findSmallerInRight(String str, int low, int high) { int countRight = 0, i; for (i = low + 1; i <= high; ++i) if (str.charAt(i) < str.charAt(low)) ++countRight; return countRight; } // A function to find rank of a string in // all permutations of characters static int findRank(String str) { int len = str.length(); int mul = fact(len); int rank = 1; int countRight; for (int i = 0; i < len; ++i) { mul /= len - i; // count number of chars smaller // than str[i] from str[i+1] to // str[len-1] countRight = findSmallerInRight(str, i, len - 1); rank += countRight * mul; } return rank; } // Driver program to test above function public static void main(String[] args) { String str = "string"; System.out.println(findRank(str)); }} // This code is contributed by Nikita Tiwari. # Python program to find lexicographic # rank of a string # A utility function to find factorial# of ndef fact(n) : f = 1 while n >= 1 : f = f * n n = n - 1 return f # A utility function to count smaller # characters on right of arr[low]def findSmallerInRight(st, low, high) : countRight = 0 i = low + 1 while i <= high : if st[i] < st[low] : countRight = countRight + 1 i = i + 1 return countRight # A function to find rank of a string# in all permutations of charactersdef findRank (st) : ln = len(st) mul = fact(ln) rank = 1 i = 0 while i < ln : mul = mul // (ln - i) # count number of chars smaller # than str[i] from str[i + 1] to # str[len-1] countRight = findSmallerInRight(st, i, ln-1) rank = rank + countRight * mul i = i + 1 return rank # Driver program to test above functionst = "string"print (findRank(st)) # This code is contributed by Nikita Tiwari. // C# program to find lexicographic rank// of a stringusing System; class GFG { // A utility function to find factorial of n static int fact(int n) { return (n <= 1) ? 1 : n * fact(n - 1); } // A utility function to count smaller // characters on right of arr[low] static int findSmallerInRight(string str, int low, int high) { int countRight = 0, i; for (i = low + 1; i <= high; ++i) if (str[i] < str[low]) ++countRight; return countRight; } // A function to find rank of a string in // all permutations of characters static int findRank(string str) { int len = str.Length; int mul = fact(len); int rank = 1; int countRight; for (int i = 0; i < len; ++i) { mul /= len - i; // count number of chars smaller // than str[i] from str[i+1] to // str[len-1] countRight = findSmallerInRight(str, i, len - 1); rank += countRight * mul; } return rank; } // Driver program to test above function public static void Main() { string str = "string"; Console.Write(findRank(str)); }} // This code is contributed nitin mittal. <?php // A utility function to find factorial of nfunction fact($n){ return ($n <= 1) ? 1 :$n * fact($n - 1);} // A utility function to count smaller // characters on right of arr[low]function findSmallerInRight($str, $low, $high){ $countRight = 0; for ($i = $low + 1; $i <= $high; ++$i) if ($str[$i] < $str[$low]) ++$countRight; return $countRight;} // A function to find rank of a string // in all permutations of charactersfunction findRank ($str){ $len = strlen($str); $mul = fact($len); $rank = 1; for ($i = 0; $i < $len; ++$i) { $mul /= $len - $i; // count number of chars smaller than // str[i] from str[i+1] to str[len-1] $countRight = findSmallerInRight($str, $i, $len - 1); $rank += $countRight * $mul ; } return $rank;} // Driver Code$str = "string";echo findRank($str); // This code is contributed by ChitraNayal?> <script> // JavaScript program to find lexicographic rank // A utility function to find factorial of nfunction fact(n){ return (n <= 1) ? 1 : n * fact(n - 1);} // A utility function to count smaller // characters on right of arr[low]function findSmallerInRight(str, low, high){ let countRight = 0; let i; for(i = low + 1; i <= high; ++i) if (str[i] < str[low]) ++countRight; return countRight;} // A function to find rank of a string// in all permutations of charactersfunction findRank(str){ let len = (str).length; let mul = fact(len); let rank = 1; let countRight; let i; for(i = 0; i < len; ++i) { mul /= len - i; // count number of chars smaller than str[i] // from str[i+1] to str[len-1] countRight = findSmallerInRight(str, i, len - 1); rank += countRight * mul; } return rank;} // Driver codelet str = "string";document.write(findRank(str)); // This code is contributed by rohan07 </script> 598 The time complexity of the above solution is O(n^2). We can reduce the time complexity to O(n) by creating an auxiliary array of size 256. See following code. C++ C Java Python3 C# PHP Javascript // A O(n) solution for finding rank of string#include <bits/stdc++.h>using namespace std;#define MAX_CHAR 256 // A utility function to find factorial of nint fact(int n){ return (n <= 1) ? 1 : n * fact(n - 1);} // Construct a count array where value at every index// contains count of smaller characters in whole stringvoid populateAndIncreaseCount(int* count, char* str){ int i; for (i = 0; str[i]; ++i) ++count[str[i]]; for (i = 1; i < MAX_CHAR; ++i) count[i] += count[i - 1];} // Removes a character ch from count[] array// constructed by populateAndIncreaseCount()void updatecount(int* count, char ch){ int i; for (i = ch; i < MAX_CHAR; ++i) --count[i];} // A function to find rank of a string in all permutations// of charactersint findRank(char* str){ int len = strlen(str); int mul = fact(len); int rank = 1, i; // all elements of count[] are initialized with 0 int count[MAX_CHAR] = { 0 }; // Populate the count array such that count[i] // contains count of characters which are present // in str and are smaller than i populateAndIncreaseCount(count, str); for (i = 0; i < len; ++i) { mul /= len - i; // count number of chars smaller than str[i] // from str[i+1] to str[len-1] rank += count[str[i] - 1] * mul; // Reduce count of characters greater than str[i] updatecount(count, str[i]); } return rank;} // Driver program to test above functionint main(){ char str[] = "string"; cout << findRank(str); return 0;} // This is code is contributed by rathbhupendra // A O(n) solution for finding rank of string#include <stdio.h>#include <string.h>#define MAX_CHAR 256 // A utility function to find factorial of nint fact(int n){ return (n <= 1) ? 1 : n * fact(n - 1);} // Construct a count array where value at every index// contains count of smaller characters in whole stringvoid populateAndIncreaseCount(int* count, char* str){ int i; for (i = 0; str[i]; ++i) ++count[str[i]]; for (i = 1; i < MAX_CHAR; ++i) count[i] += count[i - 1];} // Removes a character ch from count[] array// constructed by populateAndIncreaseCount()void updatecount(int* count, char ch){ int i; for (i = ch; i < MAX_CHAR; ++i) --count[i];} // A function to find rank of a string in all permutations// of charactersint findRank(char* str){ int len = strlen(str); int mul = fact(len); int rank = 1, i; // all elements of count[] are initialized with 0 int count[MAX_CHAR] = { 0 }; // Populate the count array such that count[i] // contains count of characters which are present // in str and are smaller than i populateAndIncreaseCount(count, str); for (i = 0; i < len; ++i) { mul /= len - i; // count number of chars smaller than str[i] // from str[i+1] to str[len-1] rank += count[str[i] - 1] * mul; // Reduce count of characters greater than str[i] updatecount(count, str[i]); } return rank;} // Driver program to test above functionint main(){ char str[] = "string"; printf("%d", findRank(str)); return 0;} // A O(n) solution for finding rank of string class GFG { static int MAX_CHAR = 256; // A utility function to find factorial of n static int fact(int n) { return (n <= 1) ? 1 : n * fact(n - 1); } // Construct a count array where value at every index // contains count of smaller characters in whole string static void populateAndIncreaseCount(int[] count, char[] str) { int i; for (i = 0; i < str.length; ++i) ++count[str[i]]; for (i = 1; i < MAX_CHAR; ++i) count[i] += count[i - 1]; } // Removes a character ch from count[] array // constructed by populateAndIncreaseCount() static void updatecount(int[] count, char ch) { int i; for (i = ch; i < MAX_CHAR; ++i) --count[i]; } // A function to find rank of a string in all permutations // of characters static int findRank(char[] str) { int len = str.length; int mul = fact(len); int rank = 1, i; // all elements of count[] are initialized with 0 int count[] = new int[MAX_CHAR]; // Populate the count array such that count[i] // contains count of characters which are present // in str and are smaller than i populateAndIncreaseCount(count, str); for (i = 0; i < len; ++i) { mul /= len - i; // count number of chars smaller than str[i] // from str[i+1] to str[len-1] rank += count[str[i] - 1] * mul; // Reduce count of characters greater than str[i] updatecount(count, str[i]); } return rank; } // Driver code public static void main(String args[]) { char str[] = "string".toCharArray(); System.out.println(findRank(str)); }} // This code has been contributed by 29AjayKumar # A O(n) solution for finding rank of stringMAX_CHAR=256; # all elements of count[] are initialized with 0count=[0]*(MAX_CHAR + 1); # A utility function to find factorial of ndef fact(n): return 1 if(n <= 1) else (n * fact(n - 1)); # Construct a count array where value at every index# contains count of smaller characters in whole stringdef populateAndIncreaseCount(str): for i in range(len(str)): count[ord(str[i])]+=1; for i in range(1,MAX_CHAR): count[i] += count[i - 1]; # Removes a character ch from count[] array# constructed by populateAndIncreaseCount()def updatecount(ch): for i in range(ord(ch),MAX_CHAR): count[i]-=1; # A function to find rank of a string in all permutations# of charactersdef findRank(str): len1 = len(str); mul = fact(len1); rank = 1; # Populate the count array such that count[i] # contains count of characters which are present # in str and are smaller than i populateAndIncreaseCount(str); for i in range(len1): mul = mul//(len1 - i); # count number of chars smaller than str[i] # from str[i+1] to str[len-1] rank += count[ord(str[i]) - 1] * mul; # Reduce count of characters greater than str[i] updatecount(str[i]); return rank; # Driver codestr = "string";print(findRank(str)); # This is code is contributed by chandan_jnu // A O(n) solution for finding rank of stringusing System; class GFG { static int MAX_CHAR = 256; // A utility function to find factorial of n static int fact(int n) { return (n <= 1) ? 1 : n * fact(n - 1); } // Construct a count array where value at every index // contains count of smaller characters in whole string static void populateAndIncreaseCount(int[] count, char[] str) { int i; for (i = 0; i < str.Length; ++i) ++count[str[i]]; for (i = 1; i < MAX_CHAR; ++i) count[i] += count[i - 1]; } // Removes a character ch from count[] array // constructed by populateAndIncreaseCount() static void updatecount(int[] count, char ch) { int i; for (i = ch; i < MAX_CHAR; ++i) --count[i]; } // A function to find rank of a string in all permutations // of characters static int findRank(char[] str) { int len = str.Length; int mul = fact(len); int rank = 1, i; // all elements of count[] are initialized with 0 int[] count = new int[MAX_CHAR]; // Populate the count array such that count[i] // contains count of characters which are present // in str and are smaller than i populateAndIncreaseCount(count, str); for (i = 0; i < len; ++i) { mul /= len - i; // count number of chars smaller than str[i] // from str[i+1] to str[len-1] rank += count[str[i] - 1] * mul; // Reduce count of characters greater than str[i] updatecount(count, str[i]); } return rank; } // Driver code public static void Main(String[] args) { char[] str = "string".ToCharArray(); Console.WriteLine(findRank(str)); }} /* This code contributed by PrinciRaj1992 */ <?php// A O(n) solution for finding rank of string$MAX_CHAR=256; // A utility function to find factorial of nfunction fact($n){ return ($n <= 1) ? 1 : $n * fact($n - 1);} // Construct a count array where value at every index// contains count of smaller characters in whole stringfunction populateAndIncreaseCount(&$count, $str){global $MAX_CHAR; for ($i = 0; $i < strlen($str); ++$i) ++$count[ord($str[$i])]; for ($i = 1; $i < $MAX_CHAR; ++$i) $count[$i] += $count[$i - 1];} // Removes a character ch from count[] array// constructed by populateAndIncreaseCount()function updatecount(&$count, $ch){ global $MAX_CHAR; for ($i = ord($ch); $i < $MAX_CHAR; ++$i) --$count[$i];} // A function to find rank of a string in all permutations// of charactersfunction findRank($str){ global $MAX_CHAR; $len = strlen($str); $mul = fact($len); $rank = 1; // all elements of count[] are initialized with 0 $count=array_fill(0, $MAX_CHAR + 1, 0); // Populate the count array such that count[i] // contains count of characters which are present // in str and are smaller than i populateAndIncreaseCount($count, $str); for ($i = 0; $i < $len; ++$i) { $mul = (int)($mul/($len - $i)); // count number of chars smaller than str[i] // from str[i+1] to str[len-1] $rank += $count[ord($str[$i]) - 1] * $mul; // Reduce count of characters greater than str[i] updatecount($count, $str[$i]); } return $rank;} // Driver code $str = "string"; echo findRank($str); // This is code is contributed by chandan_jnu?> <script>// A O(n) solution for finding rank of stringlet MAX_CHAR = 256; // A utility function to find factorial of nfunction fact(n){ return (n <= 1) ? 1 : n * fact(n - 1);} // Construct a count array where value at every index // contains count of smaller characters in whole stringfunction populateAndIncreaseCount(count,str){ let i; for (i = 0; i < str.length; ++i) ++count[str[i].charCodeAt(0)]; for (i = 1; i < MAX_CHAR; ++i) count[i] += count[i - 1];} // Removes a character ch from count[] array // constructed by populateAndIncreaseCount()function updatecount(count,ch){ let i; for (i = ch.charCodeAt(0); i < MAX_CHAR; ++i) --count[i];} // A function to find rank of a string in all permutations // of charactersfunction findRank(str){ let len = str.length; let mul = fact(len); let rank = 1, i; // all elements of count[] are initialized with 0 let count = new Array(MAX_CHAR); for(let i = 0; i < count.length; i++) { count[i] = 0; } // Populate the count array such that count[i] // contains count of characters which are present // in str and are smaller than i populateAndIncreaseCount(count, str); for (i = 0; i < len; ++i) { mul = Math.floor(mul/(len - i)); // count number of chars smaller than str[i] // from str[i+1] to str[len-1] rank += count[str[i].charCodeAt(0) - 1] * mul; // Reduce count of characters greater than str[i] updatecount(count, str[i]); } return rank;} // Driver codelet str= "string".split("");document.write(findRank(str)); // This code is contributed by rag2127</script> 598 The above programs don’t work for duplicate characters. To make them work for duplicate characters, find all the characters that are smaller (include equal this time also), do the same as above but, this time divide the rank so formed by p! where p is the count of occurrences of the repeating character. nitin mittal ukasp Akanksha_Rai rathbhupendra 29AjayKumar princiraj1992 Chandan_Kumar decoder_ dhiman_saab rohan07 rag2127 swarnpallav simmytarika5 surinderdawra388 amartyaghoshgfg hardikkoriintern FactSet number-theory Combinatorial Strings FactSet number-theory Strings Combinatorial Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Write a program to print all permutations of a given string Permutation and Combination in Python Factorial of a large number Count of subsets with sum equal to X itertools.combinations() module in Python to print all possible combinations Write a program to reverse an array or string Reverse a string in Java Write a program to print all permutations of a given string C++ Data Types Check for Balanced Brackets in an expression (well-formedness) using Stack
[ { "code": null, "e": 52, "s": 24, "text": "\n17 Jun, 2022" }, { "code": null, "e": 213, "s": 52, "text": "Given a string, find its rank among all its permutations sorted lexicographically. For example, rank of “abc” is 1, rank of “acb” is 2, and rank of “cba” is 6. " }, { "code": null, "e": 225, "s": 213, "text": "Examples: " }, { "code": null, "e": 352, "s": 225, "text": "Input : str[] = \"acb\"\nOutput : Rank = 2\n\nInput : str[] = \"string\"\nOutput : Rank = 598\n\nInput : str[] = \"cba\"\nOutput : Rank = 6" }, { "code": null, "e": 442, "s": 352, "text": "For simplicity, let us assume that the string does not contain any duplicated characters." }, { "code": null, "e": 805, "s": 442, "text": "One simple solution is to initialize rank as 1, generate all permutations in lexicographic order. After generating a permutation, check if the generated permutation is same as given string, if same, then return rank, if not, then increment the rank by 1. The time complexity of this solution will be exponential in worst case. Following is an efficient solution." }, { "code": null, "e": 1768, "s": 805, "text": "Let the given string be “STRING”. In the input string, ‘S’ is the first character.There are total 6 characters and 4 of them are smaller than ‘S’.So there can be 4 * 5! smaller strings where first character is smaller than ‘S’, like followingR X X X X X I X X X X X N X X X X X G X X X X XNow let us Fix ‘S’ and find the smaller strings starting with ‘S’.Repeat the same process for T, rank is 4*5! + 4*4! +...Now fix T and repeat the same process for R, rank is 4*5! + 4*4! + 3*3! +...Now fix R and repeat the same process for I, rank is 4*5! + 4*4! + 3*3! + 1*2! +...Now fix I and repeat the same process for N, rank is 4*5! + 4*4! + 3*3! + 1*2! + 1*1! +...Now fix N and repeat the same process for G, rank is 4*5! + 4*4! + 3*3! + 1*2! + 1*1! + 0*0!Rank = 4*5! + 4*4! + 3*3! + 1*2! + 1*1! + 0*0! = 597Note that the above computations find count of smaller strings.Therefore rank of given string is count of smaller strings plus 1.The final rank = 1 + 597 = 598" }, { "code": null, "e": 1817, "s": 1768, "text": "Below is the implementation of above approach: " }, { "code": null, "e": 1821, "s": 1817, "text": "C++" }, { "code": null, "e": 1823, "s": 1821, "text": "C" }, { "code": null, "e": 1828, "s": 1823, "text": "Java" }, { "code": null, "e": 1836, "s": 1828, "text": "Python3" }, { "code": null, "e": 1839, "s": 1836, "text": "C#" }, { "code": null, "e": 1843, "s": 1839, "text": "PHP" }, { "code": null, "e": 1854, "s": 1843, "text": "Javascript" }, { "code": "// C++ program to find lexicographic rank// of a string#include <bits/stdc++.h>#include <string.h> using namespace std;// A utility function to find factorial of nint fact(int n){ return (n <= 1) ? 1 : n * fact(n - 1);} // A utility function to count smaller characters on right// of arr[low]int findSmallerInRight(char* str, int low, int high){ int countRight = 0, i; for (i = low + 1; i <= high; ++i) if (str[i] < str[low]) ++countRight; return countRight;} // A function to find rank of a string in all permutations// of charactersint findRank(char* str){ int len = strlen(str); int mul = fact(len); int rank = 1; int countRight; int i; for (i = 0; i < len; ++i) { mul /= len - i; // count number of chars smaller than str[i] // from str[i+1] to str[len-1] countRight = findSmallerInRight(str, i, len - 1); rank += countRight * mul; } return rank;} // Driver program to test above functionint main(){ char str[] = \"string\"; cout << findRank(str); return 0;} // This code is contributed// by Akanksha Rai", "e": 2976, "s": 1854, "text": null }, { "code": "// C program to find lexicographic rank// of a string#include <stdio.h>#include <string.h> // A utility function to find factorial of nint fact(int n){ return (n <= 1) ? 1 : n * fact(n - 1);} // A utility function to count smaller characters on right// of arr[low]int findSmallerInRight(char* str, int low, int high){ int countRight = 0, i; for (i = low + 1; i <= high; ++i) if (str[i] < str[low]) ++countRight; return countRight;} // A function to find rank of a string in all permutations// of charactersint findRank(char* str){ int len = strlen(str); int mul = fact(len); int rank = 1; int countRight; int i; for (i = 0; i < len; ++i) { mul /= len - i; // count number of chars smaller than str[i] // from str[i+1] to str[len-1] countRight = findSmallerInRight(str, i, len - 1); rank += countRight * mul; } return rank;} // Driver program to test above functionint main(){ char str[] = \"string\"; printf(\"%d\", findRank(str)); return 0;}", "e": 4029, "s": 2976, "text": null }, { "code": "// Java program to find lexicographic rank// of a stringimport java.io.*;import java.util.*; class GFG { // A utility function to find factorial of n static int fact(int n) { return (n <= 1) ? 1 : n * fact(n - 1); } // A utility function to count smaller // characters on right of arr[low] static int findSmallerInRight(String str, int low, int high) { int countRight = 0, i; for (i = low + 1; i <= high; ++i) if (str.charAt(i) < str.charAt(low)) ++countRight; return countRight; } // A function to find rank of a string in // all permutations of characters static int findRank(String str) { int len = str.length(); int mul = fact(len); int rank = 1; int countRight; for (int i = 0; i < len; ++i) { mul /= len - i; // count number of chars smaller // than str[i] from str[i+1] to // str[len-1] countRight = findSmallerInRight(str, i, len - 1); rank += countRight * mul; } return rank; } // Driver program to test above function public static void main(String[] args) { String str = \"string\"; System.out.println(findRank(str)); }} // This code is contributed by Nikita Tiwari.", "e": 5397, "s": 4029, "text": null }, { "code": "# Python program to find lexicographic # rank of a string # A utility function to find factorial# of ndef fact(n) : f = 1 while n >= 1 : f = f * n n = n - 1 return f # A utility function to count smaller # characters on right of arr[low]def findSmallerInRight(st, low, high) : countRight = 0 i = low + 1 while i <= high : if st[i] < st[low] : countRight = countRight + 1 i = i + 1 return countRight # A function to find rank of a string# in all permutations of charactersdef findRank (st) : ln = len(st) mul = fact(ln) rank = 1 i = 0 while i < ln : mul = mul // (ln - i) # count number of chars smaller # than str[i] from str[i + 1] to # str[len-1] countRight = findSmallerInRight(st, i, ln-1) rank = rank + countRight * mul i = i + 1 return rank # Driver program to test above functionst = \"string\"print (findRank(st)) # This code is contributed by Nikita Tiwari.", "e": 6459, "s": 5397, "text": null }, { "code": "// C# program to find lexicographic rank// of a stringusing System; class GFG { // A utility function to find factorial of n static int fact(int n) { return (n <= 1) ? 1 : n * fact(n - 1); } // A utility function to count smaller // characters on right of arr[low] static int findSmallerInRight(string str, int low, int high) { int countRight = 0, i; for (i = low + 1; i <= high; ++i) if (str[i] < str[low]) ++countRight; return countRight; } // A function to find rank of a string in // all permutations of characters static int findRank(string str) { int len = str.Length; int mul = fact(len); int rank = 1; int countRight; for (int i = 0; i < len; ++i) { mul /= len - i; // count number of chars smaller // than str[i] from str[i+1] to // str[len-1] countRight = findSmallerInRight(str, i, len - 1); rank += countRight * mul; } return rank; } // Driver program to test above function public static void Main() { string str = \"string\"; Console.Write(findRank(str)); }} // This code is contributed nitin mittal.", "e": 7807, "s": 6459, "text": null }, { "code": "<?php // A utility function to find factorial of nfunction fact($n){ return ($n <= 1) ? 1 :$n * fact($n - 1);} // A utility function to count smaller // characters on right of arr[low]function findSmallerInRight($str, $low, $high){ $countRight = 0; for ($i = $low + 1; $i <= $high; ++$i) if ($str[$i] < $str[$low]) ++$countRight; return $countRight;} // A function to find rank of a string // in all permutations of charactersfunction findRank ($str){ $len = strlen($str); $mul = fact($len); $rank = 1; for ($i = 0; $i < $len; ++$i) { $mul /= $len - $i; // count number of chars smaller than // str[i] from str[i+1] to str[len-1] $countRight = findSmallerInRight($str, $i, $len - 1); $rank += $countRight * $mul ; } return $rank;} // Driver Code$str = \"string\";echo findRank($str); // This code is contributed by ChitraNayal?>", "e": 8778, "s": 7807, "text": null }, { "code": "<script> // JavaScript program to find lexicographic rank // A utility function to find factorial of nfunction fact(n){ return (n <= 1) ? 1 : n * fact(n - 1);} // A utility function to count smaller // characters on right of arr[low]function findSmallerInRight(str, low, high){ let countRight = 0; let i; for(i = low + 1; i <= high; ++i) if (str[i] < str[low]) ++countRight; return countRight;} // A function to find rank of a string// in all permutations of charactersfunction findRank(str){ let len = (str).length; let mul = fact(len); let rank = 1; let countRight; let i; for(i = 0; i < len; ++i) { mul /= len - i; // count number of chars smaller than str[i] // from str[i+1] to str[len-1] countRight = findSmallerInRight(str, i, len - 1); rank += countRight * mul; } return rank;} // Driver codelet str = \"string\";document.write(findRank(str)); // This code is contributed by rohan07 </script>", "e": 9798, "s": 8778, "text": null }, { "code": null, "e": 9802, "s": 9798, "text": "598" }, { "code": null, "e": 9962, "s": 9802, "text": "The time complexity of the above solution is O(n^2). We can reduce the time complexity to O(n) by creating an auxiliary array of size 256. See following code. " }, { "code": null, "e": 9966, "s": 9962, "text": "C++" }, { "code": null, "e": 9968, "s": 9966, "text": "C" }, { "code": null, "e": 9973, "s": 9968, "text": "Java" }, { "code": null, "e": 9981, "s": 9973, "text": "Python3" }, { "code": null, "e": 9984, "s": 9981, "text": "C#" }, { "code": null, "e": 9988, "s": 9984, "text": "PHP" }, { "code": null, "e": 9999, "s": 9988, "text": "Javascript" }, { "code": "// A O(n) solution for finding rank of string#include <bits/stdc++.h>using namespace std;#define MAX_CHAR 256 // A utility function to find factorial of nint fact(int n){ return (n <= 1) ? 1 : n * fact(n - 1);} // Construct a count array where value at every index// contains count of smaller characters in whole stringvoid populateAndIncreaseCount(int* count, char* str){ int i; for (i = 0; str[i]; ++i) ++count[str[i]]; for (i = 1; i < MAX_CHAR; ++i) count[i] += count[i - 1];} // Removes a character ch from count[] array// constructed by populateAndIncreaseCount()void updatecount(int* count, char ch){ int i; for (i = ch; i < MAX_CHAR; ++i) --count[i];} // A function to find rank of a string in all permutations// of charactersint findRank(char* str){ int len = strlen(str); int mul = fact(len); int rank = 1, i; // all elements of count[] are initialized with 0 int count[MAX_CHAR] = { 0 }; // Populate the count array such that count[i] // contains count of characters which are present // in str and are smaller than i populateAndIncreaseCount(count, str); for (i = 0; i < len; ++i) { mul /= len - i; // count number of chars smaller than str[i] // from str[i+1] to str[len-1] rank += count[str[i] - 1] * mul; // Reduce count of characters greater than str[i] updatecount(count, str[i]); } return rank;} // Driver program to test above functionint main(){ char str[] = \"string\"; cout << findRank(str); return 0;} // This is code is contributed by rathbhupendra", "e": 11617, "s": 9999, "text": null }, { "code": "// A O(n) solution for finding rank of string#include <stdio.h>#include <string.h>#define MAX_CHAR 256 // A utility function to find factorial of nint fact(int n){ return (n <= 1) ? 1 : n * fact(n - 1);} // Construct a count array where value at every index// contains count of smaller characters in whole stringvoid populateAndIncreaseCount(int* count, char* str){ int i; for (i = 0; str[i]; ++i) ++count[str[i]]; for (i = 1; i < MAX_CHAR; ++i) count[i] += count[i - 1];} // Removes a character ch from count[] array// constructed by populateAndIncreaseCount()void updatecount(int* count, char ch){ int i; for (i = ch; i < MAX_CHAR; ++i) --count[i];} // A function to find rank of a string in all permutations// of charactersint findRank(char* str){ int len = strlen(str); int mul = fact(len); int rank = 1, i; // all elements of count[] are initialized with 0 int count[MAX_CHAR] = { 0 }; // Populate the count array such that count[i] // contains count of characters which are present // in str and are smaller than i populateAndIncreaseCount(count, str); for (i = 0; i < len; ++i) { mul /= len - i; // count number of chars smaller than str[i] // from str[i+1] to str[len-1] rank += count[str[i] - 1] * mul; // Reduce count of characters greater than str[i] updatecount(count, str[i]); } return rank;} // Driver program to test above functionint main(){ char str[] = \"string\"; printf(\"%d\", findRank(str)); return 0;}", "e": 13185, "s": 11617, "text": null }, { "code": "// A O(n) solution for finding rank of string class GFG { static int MAX_CHAR = 256; // A utility function to find factorial of n static int fact(int n) { return (n <= 1) ? 1 : n * fact(n - 1); } // Construct a count array where value at every index // contains count of smaller characters in whole string static void populateAndIncreaseCount(int[] count, char[] str) { int i; for (i = 0; i < str.length; ++i) ++count[str[i]]; for (i = 1; i < MAX_CHAR; ++i) count[i] += count[i - 1]; } // Removes a character ch from count[] array // constructed by populateAndIncreaseCount() static void updatecount(int[] count, char ch) { int i; for (i = ch; i < MAX_CHAR; ++i) --count[i]; } // A function to find rank of a string in all permutations // of characters static int findRank(char[] str) { int len = str.length; int mul = fact(len); int rank = 1, i; // all elements of count[] are initialized with 0 int count[] = new int[MAX_CHAR]; // Populate the count array such that count[i] // contains count of characters which are present // in str and are smaller than i populateAndIncreaseCount(count, str); for (i = 0; i < len; ++i) { mul /= len - i; // count number of chars smaller than str[i] // from str[i+1] to str[len-1] rank += count[str[i] - 1] * mul; // Reduce count of characters greater than str[i] updatecount(count, str[i]); } return rank; } // Driver code public static void main(String args[]) { char str[] = \"string\".toCharArray(); System.out.println(findRank(str)); }} // This code has been contributed by 29AjayKumar", "e": 15052, "s": 13185, "text": null }, { "code": "# A O(n) solution for finding rank of stringMAX_CHAR=256; # all elements of count[] are initialized with 0count=[0]*(MAX_CHAR + 1); # A utility function to find factorial of ndef fact(n): return 1 if(n <= 1) else (n * fact(n - 1)); # Construct a count array where value at every index# contains count of smaller characters in whole stringdef populateAndIncreaseCount(str): for i in range(len(str)): count[ord(str[i])]+=1; for i in range(1,MAX_CHAR): count[i] += count[i - 1]; # Removes a character ch from count[] array# constructed by populateAndIncreaseCount()def updatecount(ch): for i in range(ord(ch),MAX_CHAR): count[i]-=1; # A function to find rank of a string in all permutations# of charactersdef findRank(str): len1 = len(str); mul = fact(len1); rank = 1; # Populate the count array such that count[i] # contains count of characters which are present # in str and are smaller than i populateAndIncreaseCount(str); for i in range(len1): mul = mul//(len1 - i); # count number of chars smaller than str[i] # from str[i+1] to str[len-1] rank += count[ord(str[i]) - 1] * mul; # Reduce count of characters greater than str[i] updatecount(str[i]); return rank; # Driver codestr = \"string\";print(findRank(str)); # This is code is contributed by chandan_jnu", "e": 16436, "s": 15052, "text": null }, { "code": "// A O(n) solution for finding rank of stringusing System; class GFG { static int MAX_CHAR = 256; // A utility function to find factorial of n static int fact(int n) { return (n <= 1) ? 1 : n * fact(n - 1); } // Construct a count array where value at every index // contains count of smaller characters in whole string static void populateAndIncreaseCount(int[] count, char[] str) { int i; for (i = 0; i < str.Length; ++i) ++count[str[i]]; for (i = 1; i < MAX_CHAR; ++i) count[i] += count[i - 1]; } // Removes a character ch from count[] array // constructed by populateAndIncreaseCount() static void updatecount(int[] count, char ch) { int i; for (i = ch; i < MAX_CHAR; ++i) --count[i]; } // A function to find rank of a string in all permutations // of characters static int findRank(char[] str) { int len = str.Length; int mul = fact(len); int rank = 1, i; // all elements of count[] are initialized with 0 int[] count = new int[MAX_CHAR]; // Populate the count array such that count[i] // contains count of characters which are present // in str and are smaller than i populateAndIncreaseCount(count, str); for (i = 0; i < len; ++i) { mul /= len - i; // count number of chars smaller than str[i] // from str[i+1] to str[len-1] rank += count[str[i] - 1] * mul; // Reduce count of characters greater than str[i] updatecount(count, str[i]); } return rank; } // Driver code public static void Main(String[] args) { char[] str = \"string\".ToCharArray(); Console.WriteLine(findRank(str)); }} /* This code contributed by PrinciRaj1992 */", "e": 18311, "s": 16436, "text": null }, { "code": "<?php// A O(n) solution for finding rank of string$MAX_CHAR=256; // A utility function to find factorial of nfunction fact($n){ return ($n <= 1) ? 1 : $n * fact($n - 1);} // Construct a count array where value at every index// contains count of smaller characters in whole stringfunction populateAndIncreaseCount(&$count, $str){global $MAX_CHAR; for ($i = 0; $i < strlen($str); ++$i) ++$count[ord($str[$i])]; for ($i = 1; $i < $MAX_CHAR; ++$i) $count[$i] += $count[$i - 1];} // Removes a character ch from count[] array// constructed by populateAndIncreaseCount()function updatecount(&$count, $ch){ global $MAX_CHAR; for ($i = ord($ch); $i < $MAX_CHAR; ++$i) --$count[$i];} // A function to find rank of a string in all permutations// of charactersfunction findRank($str){ global $MAX_CHAR; $len = strlen($str); $mul = fact($len); $rank = 1; // all elements of count[] are initialized with 0 $count=array_fill(0, $MAX_CHAR + 1, 0); // Populate the count array such that count[i] // contains count of characters which are present // in str and are smaller than i populateAndIncreaseCount($count, $str); for ($i = 0; $i < $len; ++$i) { $mul = (int)($mul/($len - $i)); // count number of chars smaller than str[i] // from str[i+1] to str[len-1] $rank += $count[ord($str[$i]) - 1] * $mul; // Reduce count of characters greater than str[i] updatecount($count, $str[$i]); } return $rank;} // Driver code $str = \"string\"; echo findRank($str); // This is code is contributed by chandan_jnu?>", "e": 19946, "s": 18311, "text": null }, { "code": "<script>// A O(n) solution for finding rank of stringlet MAX_CHAR = 256; // A utility function to find factorial of nfunction fact(n){ return (n <= 1) ? 1 : n * fact(n - 1);} // Construct a count array where value at every index // contains count of smaller characters in whole stringfunction populateAndIncreaseCount(count,str){ let i; for (i = 0; i < str.length; ++i) ++count[str[i].charCodeAt(0)]; for (i = 1; i < MAX_CHAR; ++i) count[i] += count[i - 1];} // Removes a character ch from count[] array // constructed by populateAndIncreaseCount()function updatecount(count,ch){ let i; for (i = ch.charCodeAt(0); i < MAX_CHAR; ++i) --count[i];} // A function to find rank of a string in all permutations // of charactersfunction findRank(str){ let len = str.length; let mul = fact(len); let rank = 1, i; // all elements of count[] are initialized with 0 let count = new Array(MAX_CHAR); for(let i = 0; i < count.length; i++) { count[i] = 0; } // Populate the count array such that count[i] // contains count of characters which are present // in str and are smaller than i populateAndIncreaseCount(count, str); for (i = 0; i < len; ++i) { mul = Math.floor(mul/(len - i)); // count number of chars smaller than str[i] // from str[i+1] to str[len-1] rank += count[str[i].charCodeAt(0) - 1] * mul; // Reduce count of characters greater than str[i] updatecount(count, str[i]); } return rank;} // Driver codelet str= \"string\".split(\"\");document.write(findRank(str)); // This code is contributed by rag2127</script>", "e": 21746, "s": 19946, "text": null }, { "code": null, "e": 21750, "s": 21746, "text": "598" }, { "code": null, "e": 22056, "s": 21750, "text": "The above programs don’t work for duplicate characters. To make them work for duplicate characters, find all the characters that are smaller (include equal this time also), do the same as above but, this time divide the rank so formed by p! where p is the count of occurrences of the repeating character. " }, { "code": null, "e": 22069, "s": 22056, "text": "nitin mittal" }, { "code": null, "e": 22075, "s": 22069, "text": "ukasp" }, { "code": null, "e": 22088, "s": 22075, "text": "Akanksha_Rai" }, { "code": null, "e": 22102, "s": 22088, "text": "rathbhupendra" }, { "code": null, "e": 22114, "s": 22102, "text": "29AjayKumar" }, { "code": null, "e": 22128, "s": 22114, "text": "princiraj1992" }, { "code": null, "e": 22142, "s": 22128, "text": "Chandan_Kumar" }, { "code": null, "e": 22151, "s": 22142, "text": "decoder_" }, { "code": null, "e": 22163, "s": 22151, "text": "dhiman_saab" }, { "code": null, "e": 22171, "s": 22163, "text": "rohan07" }, { "code": null, "e": 22179, "s": 22171, "text": "rag2127" }, { "code": null, "e": 22191, "s": 22179, "text": "swarnpallav" }, { "code": null, "e": 22204, "s": 22191, "text": "simmytarika5" }, { "code": null, "e": 22221, "s": 22204, "text": "surinderdawra388" }, { "code": null, "e": 22237, "s": 22221, "text": "amartyaghoshgfg" }, { "code": null, "e": 22254, "s": 22237, "text": "hardikkoriintern" }, { "code": null, "e": 22262, "s": 22254, "text": "FactSet" }, { "code": null, "e": 22276, "s": 22262, "text": "number-theory" }, { "code": null, "e": 22290, "s": 22276, "text": "Combinatorial" }, { "code": null, "e": 22298, "s": 22290, "text": "Strings" }, { "code": null, "e": 22306, "s": 22298, "text": "FactSet" }, { "code": null, "e": 22320, "s": 22306, "text": "number-theory" }, { "code": null, "e": 22328, "s": 22320, "text": "Strings" }, { "code": null, "e": 22342, "s": 22328, "text": "Combinatorial" }, { "code": null, "e": 22440, "s": 22342, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 22500, "s": 22440, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 22538, "s": 22500, "text": "Permutation and Combination in Python" }, { "code": null, "e": 22566, "s": 22538, "text": "Factorial of a large number" }, { "code": null, "e": 22603, "s": 22566, "text": "Count of subsets with sum equal to X" }, { "code": null, "e": 22680, "s": 22603, "text": "itertools.combinations() module in Python to print all possible combinations" }, { "code": null, "e": 22726, "s": 22680, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 22751, "s": 22726, "text": "Reverse a string in Java" }, { "code": null, "e": 22811, "s": 22751, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 22826, "s": 22811, "text": "C++ Data Types" } ]
Redis - Strings
Redis strings commands are used for managing string values in Redis. Following is the syntax for using Redis string commands. redis 127.0.0.1:6379> COMMAND KEY_NAME redis 127.0.0.1:6379> SET tutorialspoint redis OK redis 127.0.0.1:6379> GET tutorialspoint "redis" In the above example, SET and GET are the commands, while tutorialspoint is the key. Following table lists some basic commands to manage strings in Redis. This command sets the value at the specified key. Gets the value of a key. Gets a substring of the string stored at a key. Sets the string value of a key and return its old value. Returns the bit value at the offset in the string value stored at the key. Gets the values of all the given keys Sets or clears the bit at the offset in the string value stored at the key Sets the value with the expiry of a key Sets the value of a key, only if the key does not exist Overwrites the part of a string at the key starting at the specified offset Gets the length of the value stored in a key Sets multiple keys to multiple values Sets multiple keys to multiple values, only if none of the keys exist Sets the value and expiration in milliseconds of a key Increments the integer value of a key by one Increments the integer value of a key by the given amount Increments the float value of a key by the given amount Decrements the integer value of a key by one Decrements the integer value of a key by the given number Appends a value to a key
[ { "code": null, "e": 2305, "s": 2179, "text": "Redis strings commands are used for managing string values in Redis. Following is the syntax for using Redis string commands." }, { "code": null, "e": 2346, "s": 2305, "text": "redis 127.0.0.1:6379> COMMAND KEY_NAME \n" }, { "code": null, "e": 2450, "s": 2346, "text": "redis 127.0.0.1:6379> SET tutorialspoint redis \nOK \nredis 127.0.0.1:6379> GET tutorialspoint \n\"redis\" \n" }, { "code": null, "e": 2535, "s": 2450, "text": "In the above example, SET and GET are the commands, while tutorialspoint is the key." }, { "code": null, "e": 2605, "s": 2535, "text": "Following table lists some basic commands to manage strings in Redis." }, { "code": null, "e": 2655, "s": 2605, "text": "This command sets the value at the specified key." }, { "code": null, "e": 2680, "s": 2655, "text": "Gets the value of a key." }, { "code": null, "e": 2728, "s": 2680, "text": "Gets a substring of the string stored at a key." }, { "code": null, "e": 2785, "s": 2728, "text": "Sets the string value of a key and return its old value." }, { "code": null, "e": 2860, "s": 2785, "text": "Returns the bit value at the offset in the string value stored at the key." }, { "code": null, "e": 2898, "s": 2860, "text": "Gets the values of all the given keys" }, { "code": null, "e": 2973, "s": 2898, "text": "Sets or clears the bit at the offset in the string value stored at the key" }, { "code": null, "e": 3013, "s": 2973, "text": "Sets the value with the expiry of a key" }, { "code": null, "e": 3069, "s": 3013, "text": "Sets the value of a key, only if the key does not exist" }, { "code": null, "e": 3145, "s": 3069, "text": "Overwrites the part of a string at the key starting at the specified offset" }, { "code": null, "e": 3190, "s": 3145, "text": "Gets the length of the value stored in a key" }, { "code": null, "e": 3228, "s": 3190, "text": "Sets multiple keys to multiple values" }, { "code": null, "e": 3298, "s": 3228, "text": "Sets multiple keys to multiple values, only if none of the keys exist" }, { "code": null, "e": 3353, "s": 3298, "text": "Sets the value and expiration in milliseconds of a key" }, { "code": null, "e": 3398, "s": 3353, "text": "Increments the integer value of a key by one" }, { "code": null, "e": 3456, "s": 3398, "text": "Increments the integer value of a key by the given amount" }, { "code": null, "e": 3512, "s": 3456, "text": "Increments the float value of a key by the given amount" }, { "code": null, "e": 3557, "s": 3512, "text": "Decrements the integer value of a key by one" }, { "code": null, "e": 3615, "s": 3557, "text": "Decrements the integer value of a key by the given number" } ]
Python & MySQL - Connect Database Example
Python MySQLdb provides MySQLdb.connect() function to open a database connection. This function takes multiple parameters and returns a connection object to do database operations. db = MySQLdb.connect(host, username, passwd, dbName, port, socket); host Optional − The host name running the database server. If not specified, then the default value will be localhost:3306. username Optional − The username accessing the database. If not specified, then the default will be the name of the user that owns the server process. passwd Optional − The password of the user accessing the database. If not specified, then the default will be an empty password. dbName Optional − database name on which query is to be performed. port Optional − the port number to attempt to connect to the MySQL server.. socket Optional − socket or named pipe that should be used. There are several other properties as well. Refer MySQLdb for complete reference. You can disconnect from the MySQL database anytime using another connection object function close(). db.close() Try the following example to connect to a MySQL server − Copy and paste the following example as mysql_example.py − #!/usr/bin/python import MySQLdb # Open database connection db = MySQLdb.connect("localhost","root","root@123") # prepare a cursor object using cursor() method cursor = db.cursor() # execute SQL query using execute() method. cursor.execute("SELECT VERSION()") # Fetch a single row using fetchone() method. data = cursor.fetchone() if data: print('Version available: ', data) else: print('Version not retrieved.') # disconnect from server db.close() Execute the mysql_example.py script using python and verify the output. py mysql_example.py Version available: ('8.0.23',)
[ { "code": null, "e": 2534, "s": 2353, "text": "Python MySQLdb provides MySQLdb.connect() function to open a database connection. This function takes multiple parameters and returns a connection object to do database operations." }, { "code": null, "e": 2603, "s": 2534, "text": "db = MySQLdb.connect(host, username, passwd, dbName, port, socket);\n" }, { "code": null, "e": 2608, "s": 2603, "text": "host" }, { "code": null, "e": 2727, "s": 2608, "text": "Optional − The host name running the database server. If not specified, then the default value will be localhost:3306." }, { "code": null, "e": 2736, "s": 2727, "text": "username" }, { "code": null, "e": 2878, "s": 2736, "text": "Optional − The username accessing the database. If not specified, then the default will be the name of the user that owns the server process." }, { "code": null, "e": 2885, "s": 2878, "text": "passwd" }, { "code": null, "e": 3007, "s": 2885, "text": "Optional − The password of the user accessing the database. If not specified, then the default will be an empty password." }, { "code": null, "e": 3014, "s": 3007, "text": "dbName" }, { "code": null, "e": 3074, "s": 3014, "text": "Optional − database name on which query is to be performed." }, { "code": null, "e": 3079, "s": 3074, "text": "port" }, { "code": null, "e": 3150, "s": 3079, "text": "Optional − the port number to attempt to connect to the MySQL server.." }, { "code": null, "e": 3157, "s": 3150, "text": "socket" }, { "code": null, "e": 3210, "s": 3157, "text": "Optional − socket or named pipe that should be used." }, { "code": null, "e": 3292, "s": 3210, "text": "There are several other properties as well. Refer MySQLdb for complete reference." }, { "code": null, "e": 3393, "s": 3292, "text": "You can disconnect from the MySQL database anytime using another connection object function close()." }, { "code": null, "e": 3405, "s": 3393, "text": "db.close()\n" }, { "code": null, "e": 3462, "s": 3405, "text": "Try the following example to connect to a MySQL server −" }, { "code": null, "e": 3521, "s": 3462, "text": "Copy and paste the following example as mysql_example.py −" }, { "code": null, "e": 3982, "s": 3521, "text": "#!/usr/bin/python\n\nimport MySQLdb\n\n# Open database connection\ndb = MySQLdb.connect(\"localhost\",\"root\",\"root@123\")\n\n# prepare a cursor object using cursor() method\ncursor = db.cursor()\n\n# execute SQL query using execute() method.\ncursor.execute(\"SELECT VERSION()\")\n\n# Fetch a single row using fetchone() method.\ndata = cursor.fetchone()\nif data:\n print('Version available: ', data)\nelse:\n print('Version not retrieved.')\n\n# disconnect from server\ndb.close()" }, { "code": null, "e": 4054, "s": 3982, "text": "Execute the mysql_example.py script using python and verify the output." } ]
MongoDB – getIndexes() Method
05 Feb, 2021 In MongoDB, the getIndexes() method returns an array that contains a list of documents that identify and describe the existing indexes on the specified collection. It also includes hidden indexes as well. This method does not take any parameters. The index information return by this method contains the keys and the options used to create an index. In this method, the hidden index available starting from MongoDB 4.4. Only if the value is true. Syntax: db.Collection_name.getIndexes() Return: This method returns an array that contains a list of documents that identify and describe the existing indexes on the specified collection. It also includes hidden indexes as well. Examples: In the following examples, we are working with: Database: gfg Collection: student Documents: Three documents contains name and the language in which the students are interested. Return an array of documents that hold index information for the student collection: db.student.getIndexes() Create an index using createIndex() method: db.student.createIndex({name:1, language:-1}) Here, we first create an index using createIndex() method. After creating a new index we use greateIndex() method to find the index information for the student collection. db.student.getIndexes() Picked MongoDB Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to connect MongoDB with ReactJS ? MongoDB - limit() Method MongoDB - sort() Method MongoDB - FindOne() Method MongoDB updateOne() Method - db.Collection.updateOne() MongoDB - Regex MongoDB - Compound Indexes MongoDB updateMany() Method - db.Collection.updateMany() MongoDB Cursor Mongoose | update() Function
[ { "code": null, "e": 28, "s": 0, "text": "\n05 Feb, 2021" }, { "code": null, "e": 234, "s": 28, "text": "In MongoDB, the getIndexes() method returns an array that contains a list of documents that identify and describe the existing indexes on the specified collection. It also includes hidden indexes as well. " }, { "code": null, "e": 276, "s": 234, "text": "This method does not take any parameters." }, { "code": null, "e": 379, "s": 276, "text": "The index information return by this method contains the keys and the options used to create an index." }, { "code": null, "e": 476, "s": 379, "text": "In this method, the hidden index available starting from MongoDB 4.4. Only if the value is true." }, { "code": null, "e": 484, "s": 476, "text": "Syntax:" }, { "code": null, "e": 516, "s": 484, "text": "db.Collection_name.getIndexes()" }, { "code": null, "e": 524, "s": 516, "text": "Return:" }, { "code": null, "e": 705, "s": 524, "text": "This method returns an array that contains a list of documents that identify and describe the existing indexes on the specified collection. It also includes hidden indexes as well." }, { "code": null, "e": 715, "s": 705, "text": "Examples:" }, { "code": null, "e": 763, "s": 715, "text": "In the following examples, we are working with:" }, { "code": null, "e": 777, "s": 763, "text": "Database: gfg" }, { "code": null, "e": 797, "s": 777, "text": "Collection: student" }, { "code": null, "e": 893, "s": 797, "text": "Documents: Three documents contains name and the language in which the students are interested." }, { "code": null, "e": 978, "s": 893, "text": "Return an array of documents that hold index information for the student collection:" }, { "code": null, "e": 1002, "s": 978, "text": "db.student.getIndexes()" }, { "code": null, "e": 1046, "s": 1002, "text": "Create an index using createIndex() method:" }, { "code": null, "e": 1092, "s": 1046, "text": "db.student.createIndex({name:1, language:-1})" }, { "code": null, "e": 1151, "s": 1092, "text": "Here, we first create an index using createIndex() method." }, { "code": null, "e": 1264, "s": 1151, "text": "After creating a new index we use greateIndex() method to find the index information for the student collection." }, { "code": null, "e": 1288, "s": 1264, "text": "db.student.getIndexes()" }, { "code": null, "e": 1295, "s": 1288, "text": "Picked" }, { "code": null, "e": 1303, "s": 1295, "text": "MongoDB" }, { "code": null, "e": 1401, "s": 1303, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1439, "s": 1401, "text": "How to connect MongoDB with ReactJS ?" }, { "code": null, "e": 1464, "s": 1439, "text": "MongoDB - limit() Method" }, { "code": null, "e": 1488, "s": 1464, "text": "MongoDB - sort() Method" }, { "code": null, "e": 1515, "s": 1488, "text": "MongoDB - FindOne() Method" }, { "code": null, "e": 1570, "s": 1515, "text": "MongoDB updateOne() Method - db.Collection.updateOne()" }, { "code": null, "e": 1586, "s": 1570, "text": "MongoDB - Regex" }, { "code": null, "e": 1613, "s": 1586, "text": "MongoDB - Compound Indexes" }, { "code": null, "e": 1670, "s": 1613, "text": "MongoDB updateMany() Method - db.Collection.updateMany()" }, { "code": null, "e": 1685, "s": 1670, "text": "MongoDB Cursor" } ]
How to remove all white spaces from a String in Java?
07 Nov, 2018 Given a String with white spaces, the task is to remove all white spaces from a string using Java built-in methods. Examples: Input: str = " Geeks for Geeks " Output: GeeksforGeeks Input: str = " A Computer Science Portal" Output: AComputerSciencePortal To remove all white spaces from String, use replaceAll() method of String class with two arguments, i.e. replaceAll("\\s", ""); where \\s is a single space in unicode Program: class BlankSpace { public static void main(String[] args) { String str = " Geeks for Geeks "; // Call the replaceAll() method str = str.replaceAll("\\s", ""); System.out.println(str); }} GeeksforGeeks Java-Strings Java Programs Strings Java-Strings Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Factory method design pattern in Java Java Program to Remove Duplicate Elements From the Array Iterate through List in Java How to Iterate HashMap in Java? Iterate Over the Characters of a String in Java Write a program to reverse an array or string Reverse a string in Java Write a program to print all permutations of a given string C++ Data Types Different Methods to Reverse a String in C++
[ { "code": null, "e": 53, "s": 25, "text": "\n07 Nov, 2018" }, { "code": null, "e": 169, "s": 53, "text": "Given a String with white spaces, the task is to remove all white spaces from a string using Java built-in methods." }, { "code": null, "e": 179, "s": 169, "text": "Examples:" }, { "code": null, "e": 344, "s": 179, "text": "Input: str = \" Geeks for Geeks \" \nOutput: GeeksforGeeks\n\nInput: str = \" A Computer Science Portal\"\nOutput: AComputerSciencePortal\n" }, { "code": null, "e": 449, "s": 344, "text": "To remove all white spaces from String, use replaceAll() method of String class with two arguments, i.e." }, { "code": null, "e": 511, "s": 449, "text": "replaceAll(\"\\\\s\", \"\");\nwhere \\\\s is a single space in unicode" }, { "code": null, "e": 520, "s": 511, "text": "Program:" }, { "code": "class BlankSpace { public static void main(String[] args) { String str = \" Geeks for Geeks \"; // Call the replaceAll() method str = str.replaceAll(\"\\\\s\", \"\"); System.out.println(str); }}", "e": 777, "s": 520, "text": null }, { "code": null, "e": 792, "s": 777, "text": "GeeksforGeeks\n" }, { "code": null, "e": 805, "s": 792, "text": "Java-Strings" }, { "code": null, "e": 819, "s": 805, "text": "Java Programs" }, { "code": null, "e": 827, "s": 819, "text": "Strings" }, { "code": null, "e": 840, "s": 827, "text": "Java-Strings" }, { "code": null, "e": 848, "s": 840, "text": "Strings" }, { "code": null, "e": 946, "s": 848, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 984, "s": 946, "text": "Factory method design pattern in Java" }, { "code": null, "e": 1041, "s": 984, "text": "Java Program to Remove Duplicate Elements From the Array" }, { "code": null, "e": 1070, "s": 1041, "text": "Iterate through List in Java" }, { "code": null, "e": 1102, "s": 1070, "text": "How to Iterate HashMap in Java?" }, { "code": null, "e": 1150, "s": 1102, "text": "Iterate Over the Characters of a String in Java" }, { "code": null, "e": 1196, "s": 1150, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 1221, "s": 1196, "text": "Reverse a string in Java" }, { "code": null, "e": 1281, "s": 1221, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 1296, "s": 1281, "text": "C++ Data Types" } ]