title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Confusion Matrix — Clearly Explained | by Indhumathy Chelliah | Towards Data Science
In machine learning, the confusion matrix helps to summarize the performance of classification models. From the confusion matrix, we can calculate many metrics like recall, precision,f1 score which is used to evaluate the performance of classification models. In this blog, we will learn about the confusion matrix and the metrics calculated from the confusion matrix. Classification Accuracy What we need Confusion Matrix? What is the Confusion Matrix? Terminologies used in Confusion Matrix Metrics Calculated from Confusion Matrix1.Precision2. Recall Which metric to choose precision or recall? F1 Score F1 Score vs Accuracy Calculating metrics from the confusion matrix Confusion matrix using scikit learn In Machine learning for classification models, Accuracy is one metric used to evaluate the performance of the model. Example: If we have a data set[cancer prediction] of 100 records, and if the accuracy is 95% means, the model predicts 95 records correctly. 5 records are predicted wrongly. Error is said to be 5%. We can’t predict what type of error is this? Two types of errors are possible. 1 [malignant-cancer] is predicted as 0[benign- no cancer] 0[benign-no cancer] is predicted as 1[malignant-cancer] Out of these two errors, for this model, first, one is considered to be risky. Because if a cancer patient is mispredicted, their condition will become worse without treatment. If a non-cancer patient is predicted as cancer means, he/she may go for another screening and will get the correct result in the next screening. So, this error is not risky. If those 5 misclassified records belong to the first category (Cancer patients predicted as no cancer) means, it will be very risky. From the accuracy metrics, we can’t evaluate the performance of the model. So, we go for a confusion matrix which breaks down the type of error also. A confusion matrix is a n*n matrix that is used for evaluating the performance of the classification model.For Binary classification — The confusion Matrix is a 2*2 matrix.If the target class is 3 means Confusion Matrix is 3*3 matrix and so on. True Positive → Positive class which is predicted as positive. True Negative → Negative class which is predicted as negative. False Positive → Negative class which is predicted as positive.[Type I Error] False Negative →Positive class which is predicted as negative.[Type II Error] False Positive(FP) is also known as Type I Error.False Negative(FN) is also known as Type II Error Recall is a measure of how many positives your model is able to recall from the data. Out of all positive records, how many records are predicted correctly. Recall is also known as Sensitivity or TPR (True Positive Rate) Precision is the ratio of correct positive predictions to the total positive predictions. Out of all positives been predicted, how many are actually positive. Both precision and recall are used for evaluating the performance of the model. Which one to chose depends on the problem we aim to solve. Cancer Prediction-For this dataset, if the model predicts cancer records as non-cancer means it’s risky. All our cancer records should be predicted correctly. In this example, recall metrics is more important than precision. The recall rate should be 100%. All positive records( cancer records) should be predicted correctly. False Negative should be 0. For this cancer dataset, recall metrics is given more importance while evaluating the performance of the model. If non-cancer records are predicted as cancer means it’s not that risky. Example. The cancer data set has 100 records, out of which 94 are cancer records and 6 are non-cancer records. But the model is predicting 90 out of 94 cancer records correctly. Four cancer records are not predicted correctly [ 4 — FN] Email Spam Filtering- For this dataset, if the model predicts good email as spam means it's risky. We don’t want any of our good emails to be predicted as Spam. So, the precision metric is given more importance while evaluating this model. False Positive should be 0. If the spam filtering dataset has 100 records, out of which 94 are predicted as spam emails. Only 90 out of 94 records is predicted correctly. 4 good emails are classified as spam. It’s risky. The precision rate is 95%. It should be 100%. No good emails should be classified as “Spam”. False-positive should be 0 for this model. F1 score is a harmonic mean of precision and recall. F1 score metric is used when you seek a balance between precision and recall. Accuracy deals with True positive and True Negative. It doesn't mention about False-positive and False-negative. So we are not aware of the distribution of False-positive and False-negative. If accuracy is 95% means, we don't know how the remaining 5% is distributed between False-positive and False-negative. F1 Score deals with False-positive and False-negative. For some models, we want to know about the distribution of False-negative and False positive. For those models, the F1 Score metric is used for evaluating the performance. Let’s take the “Email Spam Filtering” example. Our task is to detect spam emails. So spam emails are marked as 1 and not spam emails are marked as 0. I have taken 10 records. Let’s say our model prediction looks like this. Let’s calculate metrics from the confusion matrix. Calculating Precision, Recall, F1 Score from the confusion matrix. Calculating Precision, Recall, F1 Score from the confusion matrix. 2. Calculating Accuracy from the confusion matrix. Now let’s calculate the same metrics using scikit learn I have taken the same example mentioned above. I have assigned spam class as 1 and non-spam as 0. Let’s say our model prediction looks like this. Confusion Matrix Confusion Matrix from sklearn.metrics import confusion_matrixactual = [1, 1, 1, 1, 0, 0, 0, 0, 0, 0]predicted = [1, 1, 1, 0, 0, 0, 1, 1, 0, 0]cm = confusion_matrix(actual, predicted)print(cm)#Output:[[4 2] [1 3]] To show the class in the confusion matrix. pd.crosstab([actual],[predicted]) 2. Accuracy Score from sklearn.metrics import accuracy_scoreprint (accuracy_score(actual,predicted))#Output: 0.7 3. Classification report from sklearn.metrics import classification_reportprint (classification_report(actual,predicted))#Output precision recall f1-score support0 0.80 0.67 0.73 61 0.60 0.75 0.67 4accuracy 0.70 10 macro avg 0.70 0.71 0.70 10weighted avg 0.72 0.70 0.70 10Process finished with exit code 0 support → tells the number of records. import seaborn as snssns.heatmap(cm, annot=True) Classification output can be either class output or probability output. For classification problems with class output, the confusion matrix is used. In this article, we have learned about calculating metrics for classification problems with class outputs. For classification problems with probability output, ROC Curve is used. towardsdatascience.com towardsdatascience.com Watch this space for more articles on Python and DataScience. If you like to read more of my tutorials, follow me on Medium, LinkedIn, Twitter. Become a Medium Member by Clicking here: https://indhumathychelliah.medium.com/membership
[ { "code": null, "e": 432, "s": 172, "text": "In machine learning, the confusion matrix helps to summarize the performance of classification models. From the confusion matrix, we can calculate many metrics like recall, precision,f1 score which is used to evaluate the performance of classification models." }, { "code": null, "e": 541, "s": 432, "text": "In this blog, we will learn about the confusion matrix and the metrics calculated from the confusion matrix." }, { "code": null, "e": 565, "s": 541, "text": "Classification Accuracy" }, { "code": null, "e": 596, "s": 565, "text": "What we need Confusion Matrix?" }, { "code": null, "e": 626, "s": 596, "text": "What is the Confusion Matrix?" }, { "code": null, "e": 665, "s": 626, "text": "Terminologies used in Confusion Matrix" }, { "code": null, "e": 726, "s": 665, "text": "Metrics Calculated from Confusion Matrix1.Precision2. Recall" }, { "code": null, "e": 770, "s": 726, "text": "Which metric to choose precision or recall?" }, { "code": null, "e": 779, "s": 770, "text": "F1 Score" }, { "code": null, "e": 800, "s": 779, "text": "F1 Score vs Accuracy" }, { "code": null, "e": 846, "s": 800, "text": "Calculating metrics from the confusion matrix" }, { "code": null, "e": 882, "s": 846, "text": "Confusion matrix using scikit learn" }, { "code": null, "e": 999, "s": 882, "text": "In Machine learning for classification models, Accuracy is one metric used to evaluate the performance of the model." }, { "code": null, "e": 1173, "s": 999, "text": "Example: If we have a data set[cancer prediction] of 100 records, and if the accuracy is 95% means, the model predicts 95 records correctly. 5 records are predicted wrongly." }, { "code": null, "e": 1276, "s": 1173, "text": "Error is said to be 5%. We can’t predict what type of error is this? Two types of errors are possible." }, { "code": null, "e": 1334, "s": 1276, "text": "1 [malignant-cancer] is predicted as 0[benign- no cancer]" }, { "code": null, "e": 1390, "s": 1334, "text": "0[benign-no cancer] is predicted as 1[malignant-cancer]" }, { "code": null, "e": 1567, "s": 1390, "text": "Out of these two errors, for this model, first, one is considered to be risky. Because if a cancer patient is mispredicted, their condition will become worse without treatment." }, { "code": null, "e": 1741, "s": 1567, "text": "If a non-cancer patient is predicted as cancer means, he/she may go for another screening and will get the correct result in the next screening. So, this error is not risky." }, { "code": null, "e": 1949, "s": 1741, "text": "If those 5 misclassified records belong to the first category (Cancer patients predicted as no cancer) means, it will be very risky. From the accuracy metrics, we can’t evaluate the performance of the model." }, { "code": null, "e": 2024, "s": 1949, "text": "So, we go for a confusion matrix which breaks down the type of error also." }, { "code": null, "e": 2269, "s": 2024, "text": "A confusion matrix is a n*n matrix that is used for evaluating the performance of the classification model.For Binary classification — The confusion Matrix is a 2*2 matrix.If the target class is 3 means Confusion Matrix is 3*3 matrix and so on." }, { "code": null, "e": 2332, "s": 2269, "text": "True Positive → Positive class which is predicted as positive." }, { "code": null, "e": 2395, "s": 2332, "text": "True Negative → Negative class which is predicted as negative." }, { "code": null, "e": 2473, "s": 2395, "text": "False Positive → Negative class which is predicted as positive.[Type I Error]" }, { "code": null, "e": 2551, "s": 2473, "text": "False Negative →Positive class which is predicted as negative.[Type II Error]" }, { "code": null, "e": 2650, "s": 2551, "text": "False Positive(FP) is also known as Type I Error.False Negative(FN) is also known as Type II Error" }, { "code": null, "e": 2736, "s": 2650, "text": "Recall is a measure of how many positives your model is able to recall from the data." }, { "code": null, "e": 2807, "s": 2736, "text": "Out of all positive records, how many records are predicted correctly." }, { "code": null, "e": 2871, "s": 2807, "text": "Recall is also known as Sensitivity or TPR (True Positive Rate)" }, { "code": null, "e": 2961, "s": 2871, "text": "Precision is the ratio of correct positive predictions to the total positive predictions." }, { "code": null, "e": 3030, "s": 2961, "text": "Out of all positives been predicted, how many are actually positive." }, { "code": null, "e": 3169, "s": 3030, "text": "Both precision and recall are used for evaluating the performance of the model. Which one to chose depends on the problem we aim to solve." }, { "code": null, "e": 3328, "s": 3169, "text": "Cancer Prediction-For this dataset, if the model predicts cancer records as non-cancer means it’s risky. All our cancer records should be predicted correctly." }, { "code": null, "e": 3523, "s": 3328, "text": "In this example, recall metrics is more important than precision. The recall rate should be 100%. All positive records( cancer records) should be predicted correctly. False Negative should be 0." }, { "code": null, "e": 3635, "s": 3523, "text": "For this cancer dataset, recall metrics is given more importance while evaluating the performance of the model." }, { "code": null, "e": 3708, "s": 3635, "text": "If non-cancer records are predicted as cancer means it’s not that risky." }, { "code": null, "e": 3944, "s": 3708, "text": "Example. The cancer data set has 100 records, out of which 94 are cancer records and 6 are non-cancer records. But the model is predicting 90 out of 94 cancer records correctly. Four cancer records are not predicted correctly [ 4 — FN]" }, { "code": null, "e": 4212, "s": 3944, "text": "Email Spam Filtering- For this dataset, if the model predicts good email as spam means it's risky. We don’t want any of our good emails to be predicted as Spam. So, the precision metric is given more importance while evaluating this model. False Positive should be 0." }, { "code": null, "e": 4541, "s": 4212, "text": "If the spam filtering dataset has 100 records, out of which 94 are predicted as spam emails. Only 90 out of 94 records is predicted correctly. 4 good emails are classified as spam. It’s risky. The precision rate is 95%. It should be 100%. No good emails should be classified as “Spam”. False-positive should be 0 for this model." }, { "code": null, "e": 4594, "s": 4541, "text": "F1 score is a harmonic mean of precision and recall." }, { "code": null, "e": 4672, "s": 4594, "text": "F1 score metric is used when you seek a balance between precision and recall." }, { "code": null, "e": 4982, "s": 4672, "text": "Accuracy deals with True positive and True Negative. It doesn't mention about False-positive and False-negative. So we are not aware of the distribution of False-positive and False-negative. If accuracy is 95% means, we don't know how the remaining 5% is distributed between False-positive and False-negative." }, { "code": null, "e": 5209, "s": 4982, "text": "F1 Score deals with False-positive and False-negative. For some models, we want to know about the distribution of False-negative and False positive. For those models, the F1 Score metric is used for evaluating the performance." }, { "code": null, "e": 5359, "s": 5209, "text": "Let’s take the “Email Spam Filtering” example. Our task is to detect spam emails. So spam emails are marked as 1 and not spam emails are marked as 0." }, { "code": null, "e": 5432, "s": 5359, "text": "I have taken 10 records. Let’s say our model prediction looks like this." }, { "code": null, "e": 5483, "s": 5432, "text": "Let’s calculate metrics from the confusion matrix." }, { "code": null, "e": 5550, "s": 5483, "text": "Calculating Precision, Recall, F1 Score from the confusion matrix." }, { "code": null, "e": 5617, "s": 5550, "text": "Calculating Precision, Recall, F1 Score from the confusion matrix." }, { "code": null, "e": 5668, "s": 5617, "text": "2. Calculating Accuracy from the confusion matrix." }, { "code": null, "e": 5724, "s": 5668, "text": "Now let’s calculate the same metrics using scikit learn" }, { "code": null, "e": 5870, "s": 5724, "text": "I have taken the same example mentioned above. I have assigned spam class as 1 and non-spam as 0. Let’s say our model prediction looks like this." }, { "code": null, "e": 5887, "s": 5870, "text": "Confusion Matrix" }, { "code": null, "e": 5904, "s": 5887, "text": "Confusion Matrix" }, { "code": null, "e": 6100, "s": 5904, "text": "from sklearn.metrics import confusion_matrixactual = [1, 1, 1, 1, 0, 0, 0, 0, 0, 0]predicted = [1, 1, 1, 0, 0, 0, 1, 1, 0, 0]cm = confusion_matrix(actual, predicted)print(cm)#Output:[[4 2] [1 3]]" }, { "code": null, "e": 6143, "s": 6100, "text": "To show the class in the confusion matrix." }, { "code": null, "e": 6177, "s": 6143, "text": "pd.crosstab([actual],[predicted])" }, { "code": null, "e": 6195, "s": 6177, "text": "2. Accuracy Score" }, { "code": null, "e": 6290, "s": 6195, "text": "from sklearn.metrics import accuracy_scoreprint (accuracy_score(actual,predicted))#Output: 0.7" }, { "code": null, "e": 6315, "s": 6290, "text": "3. Classification report" }, { "code": null, "e": 6758, "s": 6315, "text": "from sklearn.metrics import classification_reportprint (classification_report(actual,predicted))#Output precision recall f1-score support0 0.80 0.67 0.73 61 0.60 0.75 0.67 4accuracy 0.70 10 macro avg 0.70 0.71 0.70 10weighted avg 0.72 0.70 0.70 10Process finished with exit code 0" }, { "code": null, "e": 6797, "s": 6758, "text": "support → tells the number of records." }, { "code": null, "e": 6846, "s": 6797, "text": "import seaborn as snssns.heatmap(cm, annot=True)" }, { "code": null, "e": 7174, "s": 6846, "text": "Classification output can be either class output or probability output. For classification problems with class output, the confusion matrix is used. In this article, we have learned about calculating metrics for classification problems with class outputs. For classification problems with probability output, ROC Curve is used." }, { "code": null, "e": 7197, "s": 7174, "text": "towardsdatascience.com" }, { "code": null, "e": 7220, "s": 7197, "text": "towardsdatascience.com" }, { "code": null, "e": 7364, "s": 7220, "text": "Watch this space for more articles on Python and DataScience. If you like to read more of my tutorials, follow me on Medium, LinkedIn, Twitter." } ]
Start Coding - Java | Practice | GeeksforGeeks
When learning a new language, we first learn to output some message. Here, we'll start with the famous Hello World message. Now, here you are given a function to complete. Don't worry about the ins and outs of functions, just add the command (System.out.print("Hello World")) to print Hello World. Example: Input: No input Output: Hello World Explanation: Hello World is printed. User Task: Your task is to complete the function below to print hello world. 0 habdulhannan204 days ago System.out.print("Hello World"); 0 kopparapupranav5 days ago class Geeks { static void printHello () { System.out.println("Hello World"); } } 0 nivruttidahake301 week ago // { Driver Code Starts//Initial Template for Java // } Driver Code Ends//User function Template for Java class Geeks{ // Function to print hello static void printHello(){ // Your code here System.out.println("Hello World"); } } // { Driver Code Starts. class GfG{ public static void main(String args[]){ //Creating an Object of Class Geeks Geeks g = new Geeks(); //Calling printHello() function of the Class Geeks g.printHello(); } } // } Driver Code Ends 0 maquickstop2 weeks ago class hello{ public void m1(){ System.out.println("Hello World"); } } 0 vadaliyaravi22 weeks ago class Geeks{ // Function to print hello static void printHello(){ System.out.println("Hello World") } } 0 roxsonu93 weeks ago class Geeks{ // Function to print hello static void printHello(){ System.out.print("Hello World"); } } 0 priyanshukumar235653 weeks ago class Geeks{ // Function to print hello static void printHello(){ System.out.println("Hello World"); // Your code here } } 0 shubhamkumar0285s3 weeks ago class Geeks{ // Function to print hello static void printHello(){ // Your code here System.out.println("Hello World"); } } 0 arpandutta5034 weeks ago System.out.println(hello world) 0 arpandutta5034 weeks ago System.out.println(Hello world); 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": 524, "s": 226, "text": "When learning a new language, we first learn to output some message. Here, we'll start with the famous Hello World message. Now, here you are given a function to complete. Don't worry about the ins and outs of functions, just add the command (System.out.print(\"Hello World\")) to print Hello World." }, { "code": null, "e": 533, "s": 524, "text": "Example:" }, { "code": null, "e": 608, "s": 533, "text": "Input:\nNo input\n\nOutput:\nHello World\n\nExplanation:\nHello World is printed." }, { "code": null, "e": 685, "s": 608, "text": "User Task:\nYour task is to complete the function below to print hello world." }, { "code": null, "e": 687, "s": 685, "text": "0" }, { "code": null, "e": 712, "s": 687, "text": "habdulhannan204 days ago" }, { "code": null, "e": 745, "s": 712, "text": "System.out.print(\"Hello World\");" }, { "code": null, "e": 747, "s": 745, "text": "0" }, { "code": null, "e": 773, "s": 747, "text": "kopparapupranav5 days ago" }, { "code": null, "e": 787, "s": 773, "text": "class Geeks {" }, { "code": null, "e": 816, "s": 787, "text": " static void printHello () {" }, { "code": null, "e": 854, "s": 816, "text": " System.out.println(\"Hello World\");" }, { "code": null, "e": 856, "s": 854, "text": "}" }, { "code": null, "e": 858, "s": 856, "text": "}" }, { "code": null, "e": 860, "s": 858, "text": "0" }, { "code": null, "e": 887, "s": 860, "text": "nivruttidahake301 week ago" }, { "code": null, "e": 938, "s": 887, "text": "// { Driver Code Starts//Initial Template for Java" }, { "code": null, "e": 993, "s": 938, "text": "// } Driver Code Ends//User function Template for Java" }, { "code": null, "e": 1146, "s": 993, "text": "class Geeks{ // Function to print hello static void printHello(){ // Your code here System.out.println(\"Hello World\"); } }" }, { "code": null, "e": 1171, "s": 1146, "text": "// { Driver Code Starts." }, { "code": null, "e": 1420, "s": 1171, "text": "class GfG{ public static void main(String args[]){ //Creating an Object of Class Geeks Geeks g = new Geeks(); //Calling printHello() function of the Class Geeks g.printHello(); } } // } Driver Code Ends" }, { "code": null, "e": 1422, "s": 1420, "text": "0" }, { "code": null, "e": 1445, "s": 1422, "text": "maquickstop2 weeks ago" }, { "code": null, "e": 1458, "s": 1445, "text": "class hello{" }, { "code": null, "e": 1476, "s": 1458, "text": "public void m1(){" }, { "code": null, "e": 1511, "s": 1476, "text": "System.out.println(\"Hello World\");" }, { "code": null, "e": 1513, "s": 1511, "text": "}" }, { "code": null, "e": 1515, "s": 1513, "text": "}" }, { "code": null, "e": 1517, "s": 1515, "text": "0" }, { "code": null, "e": 1542, "s": 1517, "text": "vadaliyaravi22 weeks ago" }, { "code": null, "e": 1676, "s": 1542, "text": "class Geeks{ // Function to print hello static void printHello(){ System.out.println(\"Hello World\") } }" }, { "code": null, "e": 1678, "s": 1676, "text": "0" }, { "code": null, "e": 1698, "s": 1678, "text": "roxsonu93 weeks ago" }, { "code": null, "e": 1832, "s": 1698, "text": "class Geeks{ // Function to print hello static void printHello(){ System.out.print(\"Hello World\"); } }" }, { "code": null, "e": 1834, "s": 1832, "text": "0" }, { "code": null, "e": 1865, "s": 1834, "text": "priyanshukumar235653 weeks ago" }, { "code": null, "e": 2025, "s": 1865, "text": "class Geeks{ // Function to print hello static void printHello(){ System.out.println(\"Hello World\"); // Your code here } }" }, { "code": null, "e": 2027, "s": 2025, "text": "0" }, { "code": null, "e": 2056, "s": 2027, "text": "shubhamkumar0285s3 weeks ago" }, { "code": null, "e": 2209, "s": 2056, "text": "class Geeks{ // Function to print hello static void printHello(){ // Your code here System.out.println(\"Hello World\"); } }" }, { "code": null, "e": 2211, "s": 2209, "text": "0" }, { "code": null, "e": 2236, "s": 2211, "text": "arpandutta5034 weeks ago" }, { "code": null, "e": 2268, "s": 2236, "text": "System.out.println(hello world)" }, { "code": null, "e": 2270, "s": 2268, "text": "0" }, { "code": null, "e": 2295, "s": 2270, "text": "arpandutta5034 weeks ago" }, { "code": null, "e": 2328, "s": 2295, "text": "System.out.println(Hello world);" }, { "code": null, "e": 2474, "s": 2328, "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": 2510, "s": 2474, "text": " Login to access your submissions. " }, { "code": null, "e": 2520, "s": 2510, "text": "\nProblem\n" }, { "code": null, "e": 2530, "s": 2520, "text": "\nContest\n" }, { "code": null, "e": 2593, "s": 2530, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 2741, "s": 2593, "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": 2949, "s": 2741, "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": 3055, "s": 2949, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
PyTorch – FiveCrop Transformation
To crop a given image into four corners and the central crop, we apply FiveCrop() transformation. It's one of the transformations provided by the torchvision.transforms module. This module contains many important transformations that can be used to perform different types of manipulations on the image data. FiveCrop() transformation accepts both PIL and tensor images. A tensor image is a torch Tensor with shape [C, H, W], where C is the number of channels, H is the image height, and W is the image width. If the image is neither a PIL image nor a tensor image, then we first convert it to a tensor image and then apply the FiveCrop transformation. torchvision.transforms.FiveCrop(size) where size is the desired crop size. size is a sequence like (h, w), where h and w are the height and width of each cropped image. If size is an int, the cropped images are square. It returns a tuple of five cropped images, four corner and one central image. We could use the following steps to crop an image into four images and the central crop with given size − Import the required libraries. In all the following examples, the required Python libraries are torch, Pillow, and torchvision. Make sure you have already installed them. Import the required libraries. In all the following examples, the required Python libraries are torch, Pillow, and torchvision. Make sure you have already installed them. import torch import torchvision import torchvision.transforms as transforms from PIL import Image Read the input image. The input image is a PIL image or a torch tensor. Read the input image. The input image is a PIL image or a torch tensor. img = Image.open('recording.jpg') Define a transform to crop the image into four corners and the central crop. The crop size is set to (150, 300) for rectangular crop and 250 for square crop. Change the crop size according your need. Define a transform to crop the image into four corners and the central crop. The crop size is set to (150, 300) for rectangular crop and 250 for square crop. Change the crop size according your need. # transform for rectangular crop transform = transforms.FiveCrop((200,250)) # transform for square crop transform = transforms.FiveCrop(250) Apply the above-defined transform on the input image to crop the image into four corners and the central crop. Apply the above-defined transform on the input image to crop the image into four corners and the central crop. img = transform(img) Show all the five cropped images. Show all the five cropped images. We will use this image in both the following examples. In below Python3 program we crop four corner and a central crop. The five cropped images are rectangular in shape. # import required libraries import torch import torchvision.transforms as transforms from PIL import Image import matplotlib.pyplot as plt # Read the image img = Image.open('recording.jpg') # define a transform to crop the image into four # corners and the central crop transform = transforms.FiveCrop((150, 300)) # apply the above transform on the image imgs = transform(img) # This transform returns a tuple of 5 images print(type(imgs)) print("Total cropped images:",len(imgs)) <class 'tuple'> Total cropped images: 5 In the following Python3 program, we crop fours corner and a central crop. The five cropped images are square in shape. # import required libraries import torch import torchvision.transforms as transforms from PIL import Image import matplotlib.pyplot as plt # Read the image img = Image.open('recording.jpg') # define a transform to crop the image into four # corners and the central crop transform = transforms.FiveCrop(200) # apply the above transform on the image imgs = transform(img) # Define a figure of size (8, 8) fig=plt.figure(figsize=(8, 8)) # Define row and cols in the figure rows, cols = 1, 5 # Display all 5 cropped images for j in range(0, cols*rows): fig.add_subplot(rows, cols, j+1) plt.imshow(imgs[j]) plt.xticks([]) plt.yticks([]) plt.show() It will produce the following output −
[ { "code": null, "e": 1371, "s": 1062, "text": "To crop a given image into four corners and the central crop, we apply FiveCrop() transformation. It's one of the transformations provided by the torchvision.transforms module. This module contains many important transformations that can be used to perform different types of manipulations on the image data." }, { "code": null, "e": 1715, "s": 1371, "text": "FiveCrop() transformation accepts both PIL and tensor images. A tensor image is a torch Tensor with shape [C, H, W], where C is the number of channels, H is the image height, and W is the image width. If the image is neither a PIL image nor a tensor image, then we first convert it to a tensor image and then apply the FiveCrop transformation." }, { "code": null, "e": 1753, "s": 1715, "text": "torchvision.transforms.FiveCrop(size)" }, { "code": null, "e": 1934, "s": 1753, "text": "where size is the desired crop size. size is a sequence like (h, w), where h and w are the height and width of each cropped image. If size is an int, the cropped images are square." }, { "code": null, "e": 2012, "s": 1934, "text": "It returns a tuple of five cropped images, four corner and one central image." }, { "code": null, "e": 2118, "s": 2012, "text": "We could use the following steps to crop an image into four images and the central\ncrop with given size −" }, { "code": null, "e": 2289, "s": 2118, "text": "Import the required libraries. In all the following examples, the required Python libraries are torch, Pillow, and torchvision. Make sure you have already installed them." }, { "code": null, "e": 2460, "s": 2289, "text": "Import the required libraries. In all the following examples, the required Python libraries are torch, Pillow, and torchvision. Make sure you have already installed them." }, { "code": null, "e": 2558, "s": 2460, "text": "import torch\nimport torchvision\nimport torchvision.transforms as transforms\nfrom PIL import Image" }, { "code": null, "e": 2630, "s": 2558, "text": "Read the input image. The input image is a PIL image or a torch tensor." }, { "code": null, "e": 2702, "s": 2630, "text": "Read the input image. The input image is a PIL image or a torch tensor." }, { "code": null, "e": 2736, "s": 2702, "text": "img = Image.open('recording.jpg')" }, { "code": null, "e": 2936, "s": 2736, "text": "Define a transform to crop the image into four corners and the central crop. The crop size is set to (150, 300) for rectangular crop and 250 for square crop. Change the crop size according your need." }, { "code": null, "e": 3136, "s": 2936, "text": "Define a transform to crop the image into four corners and the central crop. The crop size is set to (150, 300) for rectangular crop and 250 for square crop. Change the crop size according your need." }, { "code": null, "e": 3278, "s": 3136, "text": "# transform for rectangular crop\ntransform = transforms.FiveCrop((200,250))\n\n# transform for square crop\ntransform = transforms.FiveCrop(250)" }, { "code": null, "e": 3389, "s": 3278, "text": "Apply the above-defined transform on the input image to crop the image\ninto four corners and the central crop." }, { "code": null, "e": 3500, "s": 3389, "text": "Apply the above-defined transform on the input image to crop the image\ninto four corners and the central crop." }, { "code": null, "e": 3521, "s": 3500, "text": "img = transform(img)" }, { "code": null, "e": 3555, "s": 3521, "text": "Show all the five cropped images." }, { "code": null, "e": 3589, "s": 3555, "text": "Show all the five cropped images." }, { "code": null, "e": 3644, "s": 3589, "text": "We will use this image in both the following examples." }, { "code": null, "e": 3759, "s": 3644, "text": "In below Python3 program we crop four corner and a central crop. The five cropped images are rectangular in shape." }, { "code": null, "e": 4244, "s": 3759, "text": "# import required libraries\nimport torch\nimport torchvision.transforms as transforms\nfrom PIL import Image\nimport matplotlib.pyplot as plt\n\n# Read the image\nimg = Image.open('recording.jpg')\n\n# define a transform to crop the image into four\n# corners and the central crop\ntransform = transforms.FiveCrop((150, 300))\n\n# apply the above transform on the image\nimgs = transform(img)\n\n# This transform returns a tuple of 5 images\nprint(type(imgs))\nprint(\"Total cropped images:\",len(imgs))" }, { "code": null, "e": 4284, "s": 4244, "text": "<class 'tuple'>\nTotal cropped images: 5" }, { "code": null, "e": 4404, "s": 4284, "text": "In the following Python3 program, we crop fours corner and a central crop. The five cropped images are square in shape." }, { "code": null, "e": 5065, "s": 4404, "text": "# import required libraries\nimport torch\nimport torchvision.transforms as transforms\nfrom PIL import Image\nimport matplotlib.pyplot as plt\n\n# Read the image\nimg = Image.open('recording.jpg')\n\n# define a transform to crop the image into four\n# corners and the central crop\ntransform = transforms.FiveCrop(200)\n\n# apply the above transform on the image\nimgs = transform(img)\n\n# Define a figure of size (8, 8)\nfig=plt.figure(figsize=(8, 8))\n\n# Define row and cols in the figure\nrows, cols = 1, 5\n\n# Display all 5 cropped images\nfor j in range(0, cols*rows):\n fig.add_subplot(rows, cols, j+1)\n plt.imshow(imgs[j])\n plt.xticks([])\n plt.yticks([])\nplt.show()" }, { "code": null, "e": 5104, "s": 5065, "text": "It will produce the following output −" } ]
Path methods in C#
To handle File Paths in C#, use the Path methods. These methods come under System.IO Namespace. Some of them are − Retrieve the extension of the file using the GetExtension() method. For example, .txt, .dat, etc. Retrieve the name of the file using the GetFileName() method. For example, new.txt, details.dat, etc. Retrieve the name of the file without extension using the GetFileNameWithoutExtension() method. For example, new, details, etc. Let us see an example − Live Demo using System.IO; using System; class Program { static void Main() { string myPath = "D:\\one.txt"; string fileExtension = Path.GetExtension(myPath); string fileName = Path.GetFileName(myPath); string noExtension = Path.GetFileNameWithoutExtension(myPath); Console.WriteLine("File Extension: "+fileExtension); Console.WriteLine("Fine Name: "+fileName); Console.WriteLine("File Name without extension: "+noExtension); } } File Extension: .txt Fine Name: D:\one.txt File Name without extension: D:\one
[ { "code": null, "e": 1158, "s": 1062, "text": "To handle File Paths in C#, use the Path methods. These methods come under System.IO Namespace." }, { "code": null, "e": 1177, "s": 1158, "text": "Some of them are −" }, { "code": null, "e": 1245, "s": 1177, "text": "Retrieve the extension of the file using the GetExtension() method." }, { "code": null, "e": 1275, "s": 1245, "text": "For example, .txt, .dat, etc." }, { "code": null, "e": 1337, "s": 1275, "text": "Retrieve the name of the file using the GetFileName() method." }, { "code": null, "e": 1377, "s": 1337, "text": "For example, new.txt, details.dat, etc." }, { "code": null, "e": 1473, "s": 1377, "text": "Retrieve the name of the file without extension using the GetFileNameWithoutExtension() method." }, { "code": null, "e": 1505, "s": 1473, "text": "For example, new, details, etc." }, { "code": null, "e": 1529, "s": 1505, "text": "Let us see an example −" }, { "code": null, "e": 1540, "s": 1529, "text": " Live Demo" }, { "code": null, "e": 2009, "s": 1540, "text": "using System.IO;\nusing System;\nclass Program {\n static void Main() {\n string myPath = \"D:\\\\one.txt\";\n string fileExtension = Path.GetExtension(myPath);\n string fileName = Path.GetFileName(myPath);\n string noExtension = Path.GetFileNameWithoutExtension(myPath);\n\n Console.WriteLine(\"File Extension: \"+fileExtension);\n Console.WriteLine(\"Fine Name: \"+fileName);\n Console.WriteLine(\"File Name without extension: \"+noExtension);\n }\n}" }, { "code": null, "e": 2088, "s": 2009, "text": "File Extension: .txt\nFine Name: D:\\one.txt\nFile Name without extension: D:\\one" } ]
Add two numbers represented by linked lists | Set 1 - GeeksforGeeks
12 Apr, 2022 Given two numbers represented by two lists, write a function that returns the sum list. The sum list is a list representation of the addition of two input numbers. Example: Input: List1: 5->6->3 // represents number 563 List2: 8->4->2 // represents number 842 Output: Resultant list: 1->4->0->5 // represents number 1405 Explanation: 563 + 842 = 1405 Input: List1: 7->5->9->4->6 // represents number 75946List2: 8->4 // represents number 84Output: Resultant list: 7->6->0->3->0// represents number 76030Explanation: 75946+84=76030 Approach: Traverse both lists to the end and add preceding zeros in the list with lesser digits. Then call a recursive function on the start nodes of both lists which calls itself for the next nodes of both lists till it gets to the end. This function creates a node for the sum of the current digits and returns the carry. The steps are: Traverse the two linked lists in order to add preceding zeros in case a list is having lesser digits than the other one.Start from the head node of both lists and call a recursive function for the next nodes.Continue it till the end of the lists.Creates a node for current digits sum and returns the carry. Traverse the two linked lists in order to add preceding zeros in case a list is having lesser digits than the other one. Start from the head node of both lists and call a recursive function for the next nodes. Continue it till the end of the lists. Creates a node for current digits sum and returns the carry. Below is the implementation of this approach. C++ C Java C# // C++ program to add two numbers// represented by linked list#include <bits/stdc++.h>using namespace std; /* Linked list node */class Node {public: int data; Node* next;}; /* Function to create anew node with given data */Node* newNode(int data){ Node* new_node = new Node(); new_node->data = data; new_node->next = NULL; return new_node;} /* Function to insert a node at thebeginning of the Singly Linked List */void push(Node** head_ref, int new_data){ /* allocate node */ Node* new_node = newNode(new_data); /* link the old list off the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node;} /* Adds contents of two linked lists andreturn the head node of resultant list */Node* addTwoLists(Node* first, Node* second){ // res is head node of the resultant list Node* res = NULL; Node *temp, *prev = NULL; int carry = 0, sum; // while both lists exist while (first != NULL || second != NULL) { // Calculate value of next digit in resultant list. // The next digit is sum of following things // (i) Carry // (ii) Next digit of first list (if there is a next digit) // (ii) Next digit of second list (if there is a next digit) sum = carry + (first ? first->data : 0) + (second ? second->data : 0); // update carry for next calculation carry = (sum >= 10) ? 1 : 0; // update sum if it is greater than 10 sum = sum % 10; // Create a new node with sum as data temp = newNode(sum); // if this is the first node then set it as head of the resultant list if (res == NULL) res = temp; // If this is not the first node then connect it to the rest. else prev->next = temp; // Set prev for next insertion prev = temp; // Move first and second pointers to next nodes if (first) first = first->next; if (second) second = second->next; } if (carry > 0) temp->next = newNode(carry); // return head of the resultant list return res;} Node* reverse(Node* head){ if (head == NULL || head->next == NULL) return head; // reverse the rest list and put the first element at the end Node* rest = reverse(head->next); head->next->next = head; head->next = NULL; // fix the head pointer return rest;} // A utility function to print a linked listvoid printList(Node* node){ while (node != NULL) { cout << node->data << " "; node = node->next; } cout << endl;} /* Driver code */int main(void){ Node* res = NULL; Node* first = NULL; Node* second = NULL; // create first list 7->5->9->4->6 push(&first, 6); push(&first, 4); push(&first, 9); push(&first, 5); push(&first, 7); printf("First List is "); printList(first); // create second list 8->4 push(&second, 4); push(&second, 8); cout << "Second List is "; printList(second); // reverse both the lists first = reverse(first); second = reverse(second); // Add the two lists res = addTwoLists(first, second); // reverse the res to get the sum res = reverse(res); cout << "Resultant list is "; printList(res); return 0;} // This code is contributed by Aditya Kumar (adityakumar129) // C program to add two numbers// represented by linked list#include <stdio.h>#include <stdlib.h> /* Linked list node */typedef struct Node { int data; struct Node* next;}Node; /* Function to create anew node with given data */Node* newNode(int data){ Node* new_node = (Node *)malloc(sizeof(Node)); new_node->data = data; new_node->next = NULL; return new_node;} /* Function to insert a node at thebeginning of the Singly Linked List */void push(Node** head_ref, int new_data){ /* allocate node */ Node* new_node = newNode(new_data); /* link the old list off the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node;} /* Adds contents of two linked lists andreturn the head node of resultant list */Node* addTwoLists(Node* first, Node* second){ // res is head node of the resultant list Node* res = NULL; Node *temp, *prev = NULL; int carry = 0, sum; // while both lists exist while (first != NULL || second != NULL) { // Calculate value of next digit in resultant list. // The next digit is sum of following things // (i) Carry // (ii) Next digit of first list (if there is a next digit) // (ii) Next digit of second list (if there is a next digit) sum = carry + (first ? first->data : 0) + (second ? second->data : 0); // update carry for next calculation carry = (sum >= 10) ? 1 : 0; // update sum if it is greater than 10 sum = sum % 10; // Create a new node with sum as data temp = newNode(sum); // if this is the first node then set it as head of the resultant list if (res == NULL) res = temp; // If this is not the first node then connect it to the rest. else prev->next = temp; // Set prev for next insertion prev = temp; // Move first and second pointers to next nodes if (first) first = first->next; if (second) second = second->next; } if (carry > 0) temp->next = newNode(carry); // return head of the resultant list return res;} Node* reverse(Node* head){ if (head == NULL || head->next == NULL) return head; // reverse the rest list and put the first element at the end Node* rest = reverse(head->next); head->next->next = head; head->next = NULL; // fix the head pointer return rest;} // A utility function to print a linked listvoid printList(Node* node){ while (node != NULL) { printf("%d ",node->data); node = node->next; } printf("\n");} /* Driver code */int main(void){ Node* res = NULL; Node* first = NULL; Node* second = NULL; // create first list 7->5->9->4->6 push(&first, 6); push(&first, 4); push(&first, 9); push(&first, 5); push(&first, 7); printf("First List is "); printList(first); // create second list 8->4 push(&second, 4); push(&second, 8); printf("Second List is"); printList(second); // reverse both the lists first = reverse(first); second = reverse(second); // Add the two lists res = addTwoLists(first, second); // reverse the res to get the sum res = reverse(res); printf("Resultant list is "); printList(res); return 0;} // This code is contributed by Aditya Kumar (adityakumar129) // Java program to add two numbers// represented by linked list class LinkedList { static Node head1, head2; static class Node { int data; Node next; Node(int d) { data = d; next = null; } } /* Adds contents of two linked lists and prints it */ void addTwoLists(Node first, Node second) { Node start1 = new Node(0); start1.next = first; Node start2 = new Node(0); start2.next = second; addPrecedingZeros(start1, start2); Node result = new Node(0); if (sumTwoNodes(start1.next, start2.next, result) == 1) { Node node = new Node(1); node.next = result.next; result.next = node; } printList(result.next); } /* Adds lists and returns the carry */ private int sumTwoNodes(Node first, Node second, Node result) { if (first == null) { return 0; } int number = first.data + second.data + sumTwoNodes(first.next, second.next, result); Node node = new Node(number % 10); node.next = result.next; result.next = node; return number / 10; } /* Appends preceding zeros in case a list is having lesser nodes than the other one*/ private void addPrecedingZeros(Node start1, Node start2) { Node next1 = start1.next; Node next2 = start2.next; while (next1 != null && next2 != null) { next1 = next1.next; next2 = next2.next; } if (next1 == null && next2 != null) { while (next2 != null) { Node node = new Node(0); node.next = start1.next; start1.next = node; next2 = next2.next; } } else if (next2 == null && next1 != null) { while (next1 != null) { Node node = new Node(0); node.next = start2.next; start2.next = node; next1 = next1.next; } } } /* Utility function to print a linked list */ void printList(Node head) { while (head != null) { System.out.print(head.data + " "); head = head.next; } System.out.println(""); } // Driver Code public static void main(String[] args) { LinkedList list = new LinkedList(); // creating first list list.head1 = new Node(7); list.head1.next = new Node(5); list.head1.next.next = new Node(9); list.head1.next.next.next = new Node(4); list.head1.next.next.next.next = new Node(6); System.out.print("First List is "); list.printList(head1); // creating second list list.head2 = new Node(8); list.head2.next = new Node(4); System.out.print("Second List is "); list.printList(head2); System.out.print("Resultant List is "); // add the two lists and see the result list.addTwoLists(head1, head2); } // this code is contributed by *Saurabh321Gupta*} // C# program to add two numbers// represented by linked listusing System;public class List { public class Node { public int data; public Node next; public Node(int d) { data = d; next = null; } } public static Node head1, head2; /* Adds contents of two linked lists and prints it */ public void addTwoLists(Node first, Node second) { Node start1 = new Node(0); start1.next = first; Node start2 = new Node(0); start2.next = second; addPrecedingZeros(start1, start2); Node result = new Node(0); if (sumTwoNodes(start1.next, start2.next, result) == 1) { Node node = new Node(1); node.next = result.next; result.next = node; } printList(result.next); } /* Adds lists and returns the carry */ public int sumTwoNodes(Node first, Node second, Node result) { if (first == null) { return 0; } int number = first.data + second.data + sumTwoNodes(first.next, second.next, result); Node node = new Node(number % 10); node.next = result.next; result.next = node; return number / 10; } /* * Appends preceding zeros in case a list is having lesser nodes than the other * one */ public void addPrecedingZeros(Node start1, Node start2) { Node next1 = start1.next; Node next2 = start2.next; while (next1 != null && next2 != null) { next1 = next1.next; next2 = next2.next; } if (next1 == null && next2 != null) { while (next2 != null) { Node node = new Node(0); node.next = start1.next; start1.next = node; next2 = next2.next; } } else if (next2 == null && next1 != null) { while (next1 != null) { Node node = new Node(0); node.next = start2.next; start2.next = node; next1 = next1.next; } } } /* Utility function to print a linked list */ public void printList(Node head) { while (head != null) { Console.Write(head.data + " "); head = head.next; } Console.WriteLine(""); } // Driver Code public static void Main(String[] args) { List list = new List(); // creating first list Node head1 = new Node(7); head1.next = new Node(5); head1.next.next = new Node(9); head1.next.next.next = new Node(4); head1.next.next.next.next = new Node(6); Console.Write("First List is "); list.printList(head1); // creating second list Node head2 = new Node(8); head2.next = new Node(4); Console.Write("Second List is "); list.printList(head2); Console.Write("Resultant List is "); // add the two lists and see the result list.addTwoLists(head1, head2); }} // This code is contributed by umadevi9616 First List is 7 5 9 4 6 Second List is 8 4 Resultant list is 7 6 0 3 0 Complexity Analysis: Time Complexity: O(m + n), where m and n are numbers of nodes in first and second lists respectively. The lists need to be traversed only once. Space Complexity: O(m + n). A temporary linked list is needed to store the output number Method 2(Using STL): Using the stack data structure Create 3 stacks namely s1,s2,s3. Fill s1 with Nodes of list1 and fill s2 with nodes of list2. Fill s3 by creating new nodes and setting the data of new nodes to the sum of s1.top(), s2.top() and carry until list1 and list2 are empty . If the sum >9set carry 1 set carry 1 elseset carry 0 set carry 0 Create a Node(say prev) that will contain the head of the sum List. Link all the elements of s3 from top to bottom return prev Code: C++ // C++ program to add two numbers represented by Linked// Lists using Stack#include <bits/stdc++.h>using namespace std;class Node {public: int data; Node* next;};Node* newnode(int data){ Node* x = new Node(); x->data = data; return x;}// function that returns the sum of two numbers represented// by linked listsNode* addTwoNumbers(Node* l1, Node* l2){ Node* prev = NULL; // Create 3 stacks stack<Node*> s1, s2, s3; // Fill first stack with first List Elements while (l1 != NULL) { s1.push(l1); l1 = l1->next; } // Fill second stack with second List Elements while (l2 != NULL) { s2.push(l2); l2 = l2->next; } int carry = 0; // Fill the third stack with the sum of first and second // stack while (!s1.empty() && !s2.empty()) { int sum = s1.top()->data + s2.top()->data + carry; Node* temp = newnode(sum % 10); s3.push(temp); if (sum > 9) { carry = 1; } else { carry = 0; } s1.pop(); s2.pop(); } while (!s1.empty()) { int sum = carry + s1.top()->data; Node* temp = newnode(sum % 10); s3.push(temp); if (sum > 9) { carry = 1; } else { carry = 0; } s1.pop(); } while (!s2.empty()) { int sum = carry + s2.top()->data; Node* temp = newnode(sum % 10); s3.push(temp); if (sum > 9) { carry = 1; } else { carry = 0; } s2.pop(); } // If carry is still present create a new node with // value 1 and push it to the third stack if (carry == 1) { Node* temp = newnode(1); s3.push(temp); } // Link all the elements inside third stack with each // other if (!s3.empty()) prev = s3.top(); while (!s3.empty()) { Node* temp = s3.top(); s3.pop(); if (s3.size() == 0) { temp->next = NULL; } else { temp->next = s3.top(); } } return prev;}// utility functions// Function that displays the Listvoid Display(Node* head){ if (head == NULL) { return; } while (head->next != NULL) { cout << head->data << " -> "; head = head->next; } cout << head->data << endl;}// Function that adds element at the end of the Linked Listvoid push(Node** head_ref, int d){ Node* new_node = newnode(d); new_node->next = NULL; if (*head_ref == NULL) { new_node->next = *head_ref; *head_ref = new_node; return; } Node* last = *head_ref; while (last->next != NULL && last != NULL) { last = last->next; } last->next = new_node; return;}// Driver Program for above Functionsint main(){ // Creating two lists // first list = 9 -> 5 -> 0 // second List = 6 -> 7 Node* first = NULL; Node* second = NULL; Node* sum = NULL; push(&first, 7); push(&first, 5); push(&first, 9); push(&first, 4); push(&first, 6); push(&second, 8); push(&second, 4); cout << "First List : "; Display(first); cout << "Second List : "; Display(second); sum = addTwoNumbers(first, second); cout << "Sum List : "; Display(sum); return 0;} First List : 7 -> 5 -> 9 -> 4 -> 6 Second List : 8 -> 4 Sum List : 7 -> 6 -> 0 -> 3 -> 0 Another Approach with time complexity O(N): The given approach works as following steps: First, we calculate the sizes of both the linked lists, size1 and size2, respectively.Then we traverse the bigger linked list, if any, and decrement till the size of both become the same.Now we traverse both linked lists till the end.Now the backtracking occurs while performing addition.Finally, the head node is returned to the linked list containing the answer. First, we calculate the sizes of both the linked lists, size1 and size2, respectively. Then we traverse the bigger linked list, if any, and decrement till the size of both become the same. Now we traverse both linked lists till the end. Now the backtracking occurs while performing addition. Finally, the head node is returned to the linked list containing the answer. C++ #include <iostream>using namespace std; struct Node { int data; struct Node* next;}; // recursive functionNode* addition(Node* temp1, Node* temp2, int size1, int size2){ // creating a new Node Node* newNode = (struct Node*)malloc(sizeof(struct Node)); // base case if (temp1->next == NULL && temp2->next == NULL) { // addition of current nodes which is the last nodes // of both linked lists newNode->data = (temp1->data + temp2->data); // set this current node's link null newNode->next = NULL; // return the current node return newNode; } // creating a node that contains sum of previously added // number Node* returnedNode = (struct Node*)malloc(sizeof(struct Node)); // if sizes are same then we move in both linked list if (size2 == size1) { // recursively call the function // move ahead in both linked list returnedNode = addition(temp1->next, temp2->next, size1 - 1, size2 - 1); // add the current nodes and append the carry newNode->data = (temp1->data + temp2->data) + ((returnedNode->data) / 10); } // or else we just move in big linked list else { // recursively call the function // move ahead in big linked list returnedNode = addition(temp1, temp2->next, size1, size2 - 1); // add the current node and carry newNode->data = (temp2->data) + ((returnedNode->data) / 10); } // this node contains previously added numbers // so we need to set only rightmost digit of it returnedNode->data = (returnedNode->data) % 10; // set the returned node to the current node newNode->next = returnedNode; // return the current node return newNode;} // Function to add two numbers represented by nexted list.struct Node* addTwoLists(struct Node* head1, struct Node* head2){ struct Node *temp1, *temp2, *ans = NULL; temp1 = head1; temp2 = head2; int size1 = 0, size2 = 0; // calculating the size of first linked list while (temp1 != NULL) { temp1 = temp1->next; size1++; } // calculating the size of second linked list while (temp2 != NULL) { temp2 = temp2->next; size2++; } Node* returnedNode = (struct Node*)malloc(sizeof(struct Node)); // traverse the bigger linked list if (size2 > size1) { returnedNode = addition(head1, head2, size1, size2); } else { returnedNode = addition(head2, head1, size2, size1); } // creating new node if head node is >10 if (returnedNode->data >= 10) { ans = (struct Node*)malloc(sizeof(struct Node)); ans->data = (returnedNode->data) / 10; returnedNode->data = returnedNode->data % 10; ans->next = returnedNode; } else ans = returnedNode; // return the head node of linked list that contains // answer return ans;} void Display(Node* head){ if (head == NULL) { return; } while (head->next != NULL) { cout << head->data << " -> "; head = head->next; } cout << head->data << endl;}// Function that adds element at the end of the Linked Listvoid push(Node** head_ref, int d){ Node* new_node = (struct Node*)malloc(sizeof(struct Node)); new_node->data = d; new_node->next = NULL; if (*head_ref == NULL) { new_node->next = *head_ref; *head_ref = new_node; return; } Node* last = *head_ref; while (last->next != NULL && last != NULL) { last = last->next; } last->next = new_node; return;}// Driver Program for above Functionsint main(){ // Creating two lists Node* first = NULL; Node* second = NULL; Node* sum = NULL; push(&first, 7); push(&first, 5); push(&first, 9); push(&first, 4); push(&first, 6); push(&second, 8); push(&second, 4); cout << "First List : "; Display(first); cout << "Second List : "; Display(second); sum = addTwoLists(first, second); cout << "Sum List : "; Display(sum); return 0;} // This code is contributed by Dharmik Parmar First List : 7 -> 5 -> 9 -> 4 -> 6 Second List : 8 -> 4 Sum List : 7 -> 6 -> 0 -> 3 -> 0 Related Article: Add two numbers represented by linked lists | Set 2 Please write comments if you find the above codes/algorithms incorrect, or find other ways to solve the same problem. amogha_ha Rajput-Ji rathbhupendra andrew1234 praddyumn aashish1995 prathamjha5683 freshcode7 manishchandwani1212 gulshankumarar231 dharmikparmar7 simmytarika5 anikakapoor saurabh321gupta niharikatanwar61 amartyaghoshgfg RishabhPrabhu umadevi9616 adityakumar129 Accolite Amazon Flipkart MakeMyTrip Microsoft Qualcomm Snapdeal Linked List Flipkart Accolite Amazon Microsoft Snapdeal MakeMyTrip Qualcomm Linked List Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Delete a Linked List node at a given position Queue - Linked List Implementation Implement a stack using singly linked list Implementing a Linked List in Java using Class Circular Linked List | Set 1 (Introduction and Applications) Remove duplicates from a sorted linked list Find Length of a Linked List (Iterative and Recursive) Function to check if a singly linked list is palindrome Search an element in a Linked List (Iterative and Recursive) Write a function to delete a Linked List
[ { "code": null, "e": 24231, "s": 24203, "text": "\n12 Apr, 2022" }, { "code": null, "e": 24395, "s": 24231, "text": "Given two numbers represented by two lists, write a function that returns the sum list. The sum list is a list representation of the addition of two input numbers." }, { "code": null, "e": 24404, "s": 24395, "text": "Example:" }, { "code": null, "e": 24582, "s": 24404, "text": "Input: List1: 5->6->3 // represents number 563 List2: 8->4->2 // represents number 842 Output: Resultant list: 1->4->0->5 // represents number 1405 Explanation: 563 + 842 = 1405" }, { "code": null, "e": 24762, "s": 24582, "text": "Input: List1: 7->5->9->4->6 // represents number 75946List2: 8->4 // represents number 84Output: Resultant list: 7->6->0->3->0// represents number 76030Explanation: 75946+84=76030" }, { "code": null, "e": 25087, "s": 24762, "text": "Approach: Traverse both lists to the end and add preceding zeros in the list with lesser digits. Then call a recursive function on the start nodes of both lists which calls itself for the next nodes of both lists till it gets to the end. This function creates a node for the sum of the current digits and returns the carry. " }, { "code": null, "e": 25103, "s": 25087, "text": "The steps are: " }, { "code": null, "e": 25410, "s": 25103, "text": "Traverse the two linked lists in order to add preceding zeros in case a list is having lesser digits than the other one.Start from the head node of both lists and call a recursive function for the next nodes.Continue it till the end of the lists.Creates a node for current digits sum and returns the carry." }, { "code": null, "e": 25531, "s": 25410, "text": "Traverse the two linked lists in order to add preceding zeros in case a list is having lesser digits than the other one." }, { "code": null, "e": 25620, "s": 25531, "text": "Start from the head node of both lists and call a recursive function for the next nodes." }, { "code": null, "e": 25659, "s": 25620, "text": "Continue it till the end of the lists." }, { "code": null, "e": 25720, "s": 25659, "text": "Creates a node for current digits sum and returns the carry." }, { "code": null, "e": 25767, "s": 25720, "text": "Below is the implementation of this approach. " }, { "code": null, "e": 25771, "s": 25767, "text": "C++" }, { "code": null, "e": 25773, "s": 25771, "text": "C" }, { "code": null, "e": 25778, "s": 25773, "text": "Java" }, { "code": null, "e": 25781, "s": 25778, "text": "C#" }, { "code": "// C++ program to add two numbers// represented by linked list#include <bits/stdc++.h>using namespace std; /* Linked list node */class Node {public: int data; Node* next;}; /* Function to create anew node with given data */Node* newNode(int data){ Node* new_node = new Node(); new_node->data = data; new_node->next = NULL; return new_node;} /* Function to insert a node at thebeginning of the Singly Linked List */void push(Node** head_ref, int new_data){ /* allocate node */ Node* new_node = newNode(new_data); /* link the old list off the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node;} /* Adds contents of two linked lists andreturn the head node of resultant list */Node* addTwoLists(Node* first, Node* second){ // res is head node of the resultant list Node* res = NULL; Node *temp, *prev = NULL; int carry = 0, sum; // while both lists exist while (first != NULL || second != NULL) { // Calculate value of next digit in resultant list. // The next digit is sum of following things // (i) Carry // (ii) Next digit of first list (if there is a next digit) // (ii) Next digit of second list (if there is a next digit) sum = carry + (first ? first->data : 0) + (second ? second->data : 0); // update carry for next calculation carry = (sum >= 10) ? 1 : 0; // update sum if it is greater than 10 sum = sum % 10; // Create a new node with sum as data temp = newNode(sum); // if this is the first node then set it as head of the resultant list if (res == NULL) res = temp; // If this is not the first node then connect it to the rest. else prev->next = temp; // Set prev for next insertion prev = temp; // Move first and second pointers to next nodes if (first) first = first->next; if (second) second = second->next; } if (carry > 0) temp->next = newNode(carry); // return head of the resultant list return res;} Node* reverse(Node* head){ if (head == NULL || head->next == NULL) return head; // reverse the rest list and put the first element at the end Node* rest = reverse(head->next); head->next->next = head; head->next = NULL; // fix the head pointer return rest;} // A utility function to print a linked listvoid printList(Node* node){ while (node != NULL) { cout << node->data << \" \"; node = node->next; } cout << endl;} /* Driver code */int main(void){ Node* res = NULL; Node* first = NULL; Node* second = NULL; // create first list 7->5->9->4->6 push(&first, 6); push(&first, 4); push(&first, 9); push(&first, 5); push(&first, 7); printf(\"First List is \"); printList(first); // create second list 8->4 push(&second, 4); push(&second, 8); cout << \"Second List is \"; printList(second); // reverse both the lists first = reverse(first); second = reverse(second); // Add the two lists res = addTwoLists(first, second); // reverse the res to get the sum res = reverse(res); cout << \"Resultant list is \"; printList(res); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)", "e": 29150, "s": 25781, "text": null }, { "code": "// C program to add two numbers// represented by linked list#include <stdio.h>#include <stdlib.h> /* Linked list node */typedef struct Node { int data; struct Node* next;}Node; /* Function to create anew node with given data */Node* newNode(int data){ Node* new_node = (Node *)malloc(sizeof(Node)); new_node->data = data; new_node->next = NULL; return new_node;} /* Function to insert a node at thebeginning of the Singly Linked List */void push(Node** head_ref, int new_data){ /* allocate node */ Node* new_node = newNode(new_data); /* link the old list off the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node;} /* Adds contents of two linked lists andreturn the head node of resultant list */Node* addTwoLists(Node* first, Node* second){ // res is head node of the resultant list Node* res = NULL; Node *temp, *prev = NULL; int carry = 0, sum; // while both lists exist while (first != NULL || second != NULL) { // Calculate value of next digit in resultant list. // The next digit is sum of following things // (i) Carry // (ii) Next digit of first list (if there is a next digit) // (ii) Next digit of second list (if there is a next digit) sum = carry + (first ? first->data : 0) + (second ? second->data : 0); // update carry for next calculation carry = (sum >= 10) ? 1 : 0; // update sum if it is greater than 10 sum = sum % 10; // Create a new node with sum as data temp = newNode(sum); // if this is the first node then set it as head of the resultant list if (res == NULL) res = temp; // If this is not the first node then connect it to the rest. else prev->next = temp; // Set prev for next insertion prev = temp; // Move first and second pointers to next nodes if (first) first = first->next; if (second) second = second->next; } if (carry > 0) temp->next = newNode(carry); // return head of the resultant list return res;} Node* reverse(Node* head){ if (head == NULL || head->next == NULL) return head; // reverse the rest list and put the first element at the end Node* rest = reverse(head->next); head->next->next = head; head->next = NULL; // fix the head pointer return rest;} // A utility function to print a linked listvoid printList(Node* node){ while (node != NULL) { printf(\"%d \",node->data); node = node->next; } printf(\"\\n\");} /* Driver code */int main(void){ Node* res = NULL; Node* first = NULL; Node* second = NULL; // create first list 7->5->9->4->6 push(&first, 6); push(&first, 4); push(&first, 9); push(&first, 5); push(&first, 7); printf(\"First List is \"); printList(first); // create second list 8->4 push(&second, 4); push(&second, 8); printf(\"Second List is\"); printList(second); // reverse both the lists first = reverse(first); second = reverse(second); // Add the two lists res = addTwoLists(first, second); // reverse the res to get the sum res = reverse(res); printf(\"Resultant list is \"); printList(res); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)", "e": 32543, "s": 29150, "text": null }, { "code": "// Java program to add two numbers// represented by linked list class LinkedList { static Node head1, head2; static class Node { int data; Node next; Node(int d) { data = d; next = null; } } /* Adds contents of two linked lists and prints it */ void addTwoLists(Node first, Node second) { Node start1 = new Node(0); start1.next = first; Node start2 = new Node(0); start2.next = second; addPrecedingZeros(start1, start2); Node result = new Node(0); if (sumTwoNodes(start1.next, start2.next, result) == 1) { Node node = new Node(1); node.next = result.next; result.next = node; } printList(result.next); } /* Adds lists and returns the carry */ private int sumTwoNodes(Node first, Node second, Node result) { if (first == null) { return 0; } int number = first.data + second.data + sumTwoNodes(first.next, second.next, result); Node node = new Node(number % 10); node.next = result.next; result.next = node; return number / 10; } /* Appends preceding zeros in case a list is having lesser nodes than the other one*/ private void addPrecedingZeros(Node start1, Node start2) { Node next1 = start1.next; Node next2 = start2.next; while (next1 != null && next2 != null) { next1 = next1.next; next2 = next2.next; } if (next1 == null && next2 != null) { while (next2 != null) { Node node = new Node(0); node.next = start1.next; start1.next = node; next2 = next2.next; } } else if (next2 == null && next1 != null) { while (next1 != null) { Node node = new Node(0); node.next = start2.next; start2.next = node; next1 = next1.next; } } } /* Utility function to print a linked list */ void printList(Node head) { while (head != null) { System.out.print(head.data + \" \"); head = head.next; } System.out.println(\"\"); } // Driver Code public static void main(String[] args) { LinkedList list = new LinkedList(); // creating first list list.head1 = new Node(7); list.head1.next = new Node(5); list.head1.next.next = new Node(9); list.head1.next.next.next = new Node(4); list.head1.next.next.next.next = new Node(6); System.out.print(\"First List is \"); list.printList(head1); // creating second list list.head2 = new Node(8); list.head2.next = new Node(4); System.out.print(\"Second List is \"); list.printList(head2); System.out.print(\"Resultant List is \"); // add the two lists and see the result list.addTwoLists(head1, head2); } // this code is contributed by *Saurabh321Gupta*}", "e": 35581, "s": 32543, "text": null }, { "code": "// C# program to add two numbers// represented by linked listusing System;public class List { public class Node { public int data; public Node next; public Node(int d) { data = d; next = null; } } public static Node head1, head2; /* Adds contents of two linked lists and prints it */ public void addTwoLists(Node first, Node second) { Node start1 = new Node(0); start1.next = first; Node start2 = new Node(0); start2.next = second; addPrecedingZeros(start1, start2); Node result = new Node(0); if (sumTwoNodes(start1.next, start2.next, result) == 1) { Node node = new Node(1); node.next = result.next; result.next = node; } printList(result.next); } /* Adds lists and returns the carry */ public int sumTwoNodes(Node first, Node second, Node result) { if (first == null) { return 0; } int number = first.data + second.data + sumTwoNodes(first.next, second.next, result); Node node = new Node(number % 10); node.next = result.next; result.next = node; return number / 10; } /* * Appends preceding zeros in case a list is having lesser nodes than the other * one */ public void addPrecedingZeros(Node start1, Node start2) { Node next1 = start1.next; Node next2 = start2.next; while (next1 != null && next2 != null) { next1 = next1.next; next2 = next2.next; } if (next1 == null && next2 != null) { while (next2 != null) { Node node = new Node(0); node.next = start1.next; start1.next = node; next2 = next2.next; } } else if (next2 == null && next1 != null) { while (next1 != null) { Node node = new Node(0); node.next = start2.next; start2.next = node; next1 = next1.next; } } } /* Utility function to print a linked list */ public void printList(Node head) { while (head != null) { Console.Write(head.data + \" \"); head = head.next; } Console.WriteLine(\"\"); } // Driver Code public static void Main(String[] args) { List list = new List(); // creating first list Node head1 = new Node(7); head1.next = new Node(5); head1.next.next = new Node(9); head1.next.next.next = new Node(4); head1.next.next.next.next = new Node(6); Console.Write(\"First List is \"); list.printList(head1); // creating second list Node head2 = new Node(8); head2.next = new Node(4); Console.Write(\"Second List is \"); list.printList(head2); Console.Write(\"Resultant List is \"); // add the two lists and see the result list.addTwoLists(head1, head2); }} // This code is contributed by umadevi9616", "e": 38635, "s": 35581, "text": null }, { "code": null, "e": 38709, "s": 38635, "text": "First List is 7 5 9 4 6 \nSecond List is 8 4 \nResultant list is 7 6 0 3 0 " }, { "code": null, "e": 38731, "s": 38709, "text": "Complexity Analysis: " }, { "code": null, "e": 38875, "s": 38731, "text": "Time Complexity: O(m + n), where m and n are numbers of nodes in first and second lists respectively. The lists need to be traversed only once." }, { "code": null, "e": 38964, "s": 38875, "text": "Space Complexity: O(m + n). A temporary linked list is needed to store the output number" }, { "code": null, "e": 39016, "s": 38964, "text": "Method 2(Using STL): Using the stack data structure" }, { "code": null, "e": 39049, "s": 39016, "text": "Create 3 stacks namely s1,s2,s3." }, { "code": null, "e": 39110, "s": 39049, "text": "Fill s1 with Nodes of list1 and fill s2 with nodes of list2." }, { "code": null, "e": 39251, "s": 39110, "text": "Fill s3 by creating new nodes and setting the data of new nodes to the sum of s1.top(), s2.top() and carry until list1 and list2 are empty ." }, { "code": null, "e": 39276, "s": 39251, "text": "If the sum >9set carry 1" }, { "code": null, "e": 39288, "s": 39276, "text": "set carry 1" }, { "code": null, "e": 39304, "s": 39288, "text": "elseset carry 0" }, { "code": null, "e": 39316, "s": 39304, "text": "set carry 0" }, { "code": null, "e": 39384, "s": 39316, "text": "Create a Node(say prev) that will contain the head of the sum List." }, { "code": null, "e": 39431, "s": 39384, "text": "Link all the elements of s3 from top to bottom" }, { "code": null, "e": 39444, "s": 39431, "text": "return prev " }, { "code": null, "e": 39450, "s": 39444, "text": "Code:" }, { "code": null, "e": 39454, "s": 39450, "text": "C++" }, { "code": "// C++ program to add two numbers represented by Linked// Lists using Stack#include <bits/stdc++.h>using namespace std;class Node {public: int data; Node* next;};Node* newnode(int data){ Node* x = new Node(); x->data = data; return x;}// function that returns the sum of two numbers represented// by linked listsNode* addTwoNumbers(Node* l1, Node* l2){ Node* prev = NULL; // Create 3 stacks stack<Node*> s1, s2, s3; // Fill first stack with first List Elements while (l1 != NULL) { s1.push(l1); l1 = l1->next; } // Fill second stack with second List Elements while (l2 != NULL) { s2.push(l2); l2 = l2->next; } int carry = 0; // Fill the third stack with the sum of first and second // stack while (!s1.empty() && !s2.empty()) { int sum = s1.top()->data + s2.top()->data + carry; Node* temp = newnode(sum % 10); s3.push(temp); if (sum > 9) { carry = 1; } else { carry = 0; } s1.pop(); s2.pop(); } while (!s1.empty()) { int sum = carry + s1.top()->data; Node* temp = newnode(sum % 10); s3.push(temp); if (sum > 9) { carry = 1; } else { carry = 0; } s1.pop(); } while (!s2.empty()) { int sum = carry + s2.top()->data; Node* temp = newnode(sum % 10); s3.push(temp); if (sum > 9) { carry = 1; } else { carry = 0; } s2.pop(); } // If carry is still present create a new node with // value 1 and push it to the third stack if (carry == 1) { Node* temp = newnode(1); s3.push(temp); } // Link all the elements inside third stack with each // other if (!s3.empty()) prev = s3.top(); while (!s3.empty()) { Node* temp = s3.top(); s3.pop(); if (s3.size() == 0) { temp->next = NULL; } else { temp->next = s3.top(); } } return prev;}// utility functions// Function that displays the Listvoid Display(Node* head){ if (head == NULL) { return; } while (head->next != NULL) { cout << head->data << \" -> \"; head = head->next; } cout << head->data << endl;}// Function that adds element at the end of the Linked Listvoid push(Node** head_ref, int d){ Node* new_node = newnode(d); new_node->next = NULL; if (*head_ref == NULL) { new_node->next = *head_ref; *head_ref = new_node; return; } Node* last = *head_ref; while (last->next != NULL && last != NULL) { last = last->next; } last->next = new_node; return;}// Driver Program for above Functionsint main(){ // Creating two lists // first list = 9 -> 5 -> 0 // second List = 6 -> 7 Node* first = NULL; Node* second = NULL; Node* sum = NULL; push(&first, 7); push(&first, 5); push(&first, 9); push(&first, 4); push(&first, 6); push(&second, 8); push(&second, 4); cout << \"First List : \"; Display(first); cout << \"Second List : \"; Display(second); sum = addTwoNumbers(first, second); cout << \"Sum List : \"; Display(sum); return 0;}", "e": 42720, "s": 39454, "text": null }, { "code": null, "e": 42809, "s": 42720, "text": "First List : 7 -> 5 -> 9 -> 4 -> 6\nSecond List : 8 -> 4\nSum List : 7 -> 6 -> 0 -> 3 -> 0" }, { "code": null, "e": 42853, "s": 42809, "text": "Another Approach with time complexity O(N):" }, { "code": null, "e": 42899, "s": 42853, "text": "The given approach works as following steps: " }, { "code": null, "e": 43264, "s": 42899, "text": "First, we calculate the sizes of both the linked lists, size1 and size2, respectively.Then we traverse the bigger linked list, if any, and decrement till the size of both become the same.Now we traverse both linked lists till the end.Now the backtracking occurs while performing addition.Finally, the head node is returned to the linked list containing the answer." }, { "code": null, "e": 43351, "s": 43264, "text": "First, we calculate the sizes of both the linked lists, size1 and size2, respectively." }, { "code": null, "e": 43453, "s": 43351, "text": "Then we traverse the bigger linked list, if any, and decrement till the size of both become the same." }, { "code": null, "e": 43501, "s": 43453, "text": "Now we traverse both linked lists till the end." }, { "code": null, "e": 43556, "s": 43501, "text": "Now the backtracking occurs while performing addition." }, { "code": null, "e": 43633, "s": 43556, "text": "Finally, the head node is returned to the linked list containing the answer." }, { "code": null, "e": 43637, "s": 43633, "text": "C++" }, { "code": "#include <iostream>using namespace std; struct Node { int data; struct Node* next;}; // recursive functionNode* addition(Node* temp1, Node* temp2, int size1, int size2){ // creating a new Node Node* newNode = (struct Node*)malloc(sizeof(struct Node)); // base case if (temp1->next == NULL && temp2->next == NULL) { // addition of current nodes which is the last nodes // of both linked lists newNode->data = (temp1->data + temp2->data); // set this current node's link null newNode->next = NULL; // return the current node return newNode; } // creating a node that contains sum of previously added // number Node* returnedNode = (struct Node*)malloc(sizeof(struct Node)); // if sizes are same then we move in both linked list if (size2 == size1) { // recursively call the function // move ahead in both linked list returnedNode = addition(temp1->next, temp2->next, size1 - 1, size2 - 1); // add the current nodes and append the carry newNode->data = (temp1->data + temp2->data) + ((returnedNode->data) / 10); } // or else we just move in big linked list else { // recursively call the function // move ahead in big linked list returnedNode = addition(temp1, temp2->next, size1, size2 - 1); // add the current node and carry newNode->data = (temp2->data) + ((returnedNode->data) / 10); } // this node contains previously added numbers // so we need to set only rightmost digit of it returnedNode->data = (returnedNode->data) % 10; // set the returned node to the current node newNode->next = returnedNode; // return the current node return newNode;} // Function to add two numbers represented by nexted list.struct Node* addTwoLists(struct Node* head1, struct Node* head2){ struct Node *temp1, *temp2, *ans = NULL; temp1 = head1; temp2 = head2; int size1 = 0, size2 = 0; // calculating the size of first linked list while (temp1 != NULL) { temp1 = temp1->next; size1++; } // calculating the size of second linked list while (temp2 != NULL) { temp2 = temp2->next; size2++; } Node* returnedNode = (struct Node*)malloc(sizeof(struct Node)); // traverse the bigger linked list if (size2 > size1) { returnedNode = addition(head1, head2, size1, size2); } else { returnedNode = addition(head2, head1, size2, size1); } // creating new node if head node is >10 if (returnedNode->data >= 10) { ans = (struct Node*)malloc(sizeof(struct Node)); ans->data = (returnedNode->data) / 10; returnedNode->data = returnedNode->data % 10; ans->next = returnedNode; } else ans = returnedNode; // return the head node of linked list that contains // answer return ans;} void Display(Node* head){ if (head == NULL) { return; } while (head->next != NULL) { cout << head->data << \" -> \"; head = head->next; } cout << head->data << endl;}// Function that adds element at the end of the Linked Listvoid push(Node** head_ref, int d){ Node* new_node = (struct Node*)malloc(sizeof(struct Node)); new_node->data = d; new_node->next = NULL; if (*head_ref == NULL) { new_node->next = *head_ref; *head_ref = new_node; return; } Node* last = *head_ref; while (last->next != NULL && last != NULL) { last = last->next; } last->next = new_node; return;}// Driver Program for above Functionsint main(){ // Creating two lists Node* first = NULL; Node* second = NULL; Node* sum = NULL; push(&first, 7); push(&first, 5); push(&first, 9); push(&first, 4); push(&first, 6); push(&second, 8); push(&second, 4); cout << \"First List : \"; Display(first); cout << \"Second List : \"; Display(second); sum = addTwoLists(first, second); cout << \"Sum List : \"; Display(sum); return 0;} // This code is contributed by Dharmik Parmar", "e": 47877, "s": 43637, "text": null }, { "code": null, "e": 47966, "s": 47877, "text": "First List : 7 -> 5 -> 9 -> 4 -> 6\nSecond List : 8 -> 4\nSum List : 7 -> 6 -> 0 -> 3 -> 0" }, { "code": null, "e": 48035, "s": 47966, "text": "Related Article: Add two numbers represented by linked lists | Set 2" }, { "code": null, "e": 48154, "s": 48035, "text": "Please write comments if you find the above codes/algorithms incorrect, or find other ways to solve the same problem. " }, { "code": null, "e": 48166, "s": 48156, "text": "amogha_ha" }, { "code": null, "e": 48176, "s": 48166, "text": "Rajput-Ji" }, { "code": null, "e": 48190, "s": 48176, "text": "rathbhupendra" }, { "code": null, "e": 48201, "s": 48190, "text": "andrew1234" }, { "code": null, "e": 48211, "s": 48201, "text": "praddyumn" }, { "code": null, "e": 48223, "s": 48211, "text": "aashish1995" }, { "code": null, "e": 48238, "s": 48223, "text": "prathamjha5683" }, { "code": null, "e": 48249, "s": 48238, "text": "freshcode7" }, { "code": null, "e": 48269, "s": 48249, "text": "manishchandwani1212" }, { "code": null, "e": 48287, "s": 48269, "text": "gulshankumarar231" }, { "code": null, "e": 48302, "s": 48287, "text": "dharmikparmar7" }, { "code": null, "e": 48315, "s": 48302, "text": "simmytarika5" }, { "code": null, "e": 48327, "s": 48315, "text": "anikakapoor" }, { "code": null, "e": 48343, "s": 48327, "text": "saurabh321gupta" }, { "code": null, "e": 48360, "s": 48343, "text": "niharikatanwar61" }, { "code": null, "e": 48376, "s": 48360, "text": "amartyaghoshgfg" }, { "code": null, "e": 48390, "s": 48376, "text": "RishabhPrabhu" }, { "code": null, "e": 48402, "s": 48390, "text": "umadevi9616" }, { "code": null, "e": 48417, "s": 48402, "text": "adityakumar129" }, { "code": null, "e": 48426, "s": 48417, "text": "Accolite" }, { "code": null, "e": 48433, "s": 48426, "text": "Amazon" }, { "code": null, "e": 48442, "s": 48433, "text": "Flipkart" }, { "code": null, "e": 48453, "s": 48442, "text": "MakeMyTrip" }, { "code": null, "e": 48463, "s": 48453, "text": "Microsoft" }, { "code": null, "e": 48472, "s": 48463, "text": "Qualcomm" }, { "code": null, "e": 48481, "s": 48472, "text": "Snapdeal" }, { "code": null, "e": 48493, "s": 48481, "text": "Linked List" }, { "code": null, "e": 48502, "s": 48493, "text": "Flipkart" }, { "code": null, "e": 48511, "s": 48502, "text": "Accolite" }, { "code": null, "e": 48518, "s": 48511, "text": "Amazon" }, { "code": null, "e": 48528, "s": 48518, "text": "Microsoft" }, { "code": null, "e": 48537, "s": 48528, "text": "Snapdeal" }, { "code": null, "e": 48548, "s": 48537, "text": "MakeMyTrip" }, { "code": null, "e": 48557, "s": 48548, "text": "Qualcomm" }, { "code": null, "e": 48569, "s": 48557, "text": "Linked List" }, { "code": null, "e": 48667, "s": 48569, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 48676, "s": 48667, "text": "Comments" }, { "code": null, "e": 48689, "s": 48676, "text": "Old Comments" }, { "code": null, "e": 48735, "s": 48689, "text": "Delete a Linked List node at a given position" }, { "code": null, "e": 48770, "s": 48735, "text": "Queue - Linked List Implementation" }, { "code": null, "e": 48813, "s": 48770, "text": "Implement a stack using singly linked list" }, { "code": null, "e": 48860, "s": 48813, "text": "Implementing a Linked List in Java using Class" }, { "code": null, "e": 48921, "s": 48860, "text": "Circular Linked List | Set 1 (Introduction and Applications)" }, { "code": null, "e": 48965, "s": 48921, "text": "Remove duplicates from a sorted linked list" }, { "code": null, "e": 49020, "s": 48965, "text": "Find Length of a Linked List (Iterative and Recursive)" }, { "code": null, "e": 49076, "s": 49020, "text": "Function to check if a singly linked list is palindrome" }, { "code": null, "e": 49137, "s": 49076, "text": "Search an element in a Linked List (Iterative and Recursive)" } ]
C Program To Check For Balanced Brackets In An Expression (Well-Formedness) Using Stack - GeeksforGeeks
14 Dec, 2021 Given an expression string exp, write a program to examine whether the pairs and the orders of “{“, “}”, “(“, “)”, “[“, “]” are correct in exp. Example: Input: exp = “[()]{}{[()()]()}” Output: Balanced Input: exp = “[(])” Output: Not Balanced Algorithm: Declare a character stack S. Now traverse the expression string exp. If the current character is a starting bracket (‘(‘ or ‘{‘ or ‘[‘) then push it to stack.If the current character is a closing bracket (‘)’ or ‘}’ or ‘]’) then pop from stack and if the popped character is the matching starting bracket then fine else brackets are not balanced. If the current character is a starting bracket (‘(‘ or ‘{‘ or ‘[‘) then push it to stack.If the current character is a closing bracket (‘)’ or ‘}’ or ‘]’) then pop from stack and if the popped character is the matching starting bracket then fine else brackets are not balanced. If the current character is a starting bracket (‘(‘ or ‘{‘ or ‘[‘) then push it to stack. If the current character is a closing bracket (‘)’ or ‘}’ or ‘]’) then pop from stack and if the popped character is the matching starting bracket then fine else brackets are not balanced. After complete traversal, if there is some starting bracket left in stack then “not balanced” Below image is a dry run of the above approach: Below is the implementation of the above approach: C #include <stdio.h>#include <stdlib.h>#define bool int // structure of a stack nodestruct sNode { char data; struct sNode* next;}; // Function to push an item to stackvoid push(struct sNode** top_ref, int new_data); // Function to pop an item from stackint pop(struct sNode** top_ref); // Returns 1 if character1 and character2 are matching left// and right Bracketsbool isMatchingPair(char character1, char character2){ if (character1 == '(' && character2 == ')') return 1; else if (character1 == '{' && character2 == '}') return 1; else if (character1 == '[' && character2 == ']') return 1; else return 0;} // Return 1 if expression has balanced Bracketsbool areBracketsBalanced(char exp[]){ int i = 0; // Declare an empty character stack struct sNode* stack = NULL; // Traverse the given expression to check matching // brackets while (exp[i]) { // If the exp[i] is a starting bracket then push // it if (exp[i] == '{' || exp[i] == '(' || exp[i] == '[') push(&stack, exp[i]); // If exp[i] is an ending bracket then pop from // stack and check if the popped bracket is a // matching pair*/ if (exp[i] == '}' || exp[i] == ')' || exp[i] == ']') { // If we see an ending bracket without a pair // then return false if (stack == NULL) return 0; // Pop the top element from stack, if it is not // a pair bracket of character then there is a // mismatch. // his happens for expressions like {(}) else if (!isMatchingPair(pop(&stack), exp[i])) return 0; } i++; } // If there is something left in expression then there // is a starting bracket without a closing // bracket if (stack == NULL) return 1; // balanced else return 0; // not balanced} // Driver codeint main(){ char exp[100] = "{()}[]"; // Function call if (areBracketsBalanced(exp)) printf("Balanced "); else printf("Not Balanced "); return 0;} // Function to push an item to stackvoid push(struct sNode** top_ref, int new_data){ // allocate node struct sNode* new_node = (struct sNode*)malloc(sizeof(struct sNode)); if (new_node == NULL) { printf("Stack overflow n"); getchar(); exit(0); } // put in the data new_node->data = new_data; // link the old list off the new node new_node->next = (*top_ref); // move the head to point to the new node (*top_ref) = new_node;} // Function to pop an item from stackint pop(struct sNode** top_ref){ char res; struct sNode* top; // If stack is empty then error if (*top_ref == NULL) { printf("Stack overflow n"); getchar(); exit(0); } else { top = *top_ref; res = top->data; *top_ref = top->next; free(top); return res; }} Balanced Time Complexity: O(n) Auxiliary Space: O(n) for stack. Please refer complete article on Check for Balanced Brackets in an expression (well-formedness) using Stack for more details! Amazon Hike Oracle Parentheses-Problems Snapdeal Walmart Wipro Yatra.com Zoho C Programs Stack Strings Zoho Amazon Snapdeal Hike Oracle Walmart Wipro Yatra.com Strings Stack Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C Program to read contents of Whole File Producer Consumer Problem in C C program to find the length of a string Exit codes in C/C++ with Examples Regular expressions in C Stack Data Structure (Introduction and Program) Stack Class in Java Stack in Python Check for Balanced Brackets in an expression (well-formedness) using Stack Program for Tower of Hanoi
[ { "code": null, "e": 25008, "s": 24980, "text": "\n14 Dec, 2021" }, { "code": null, "e": 25152, "s": 25008, "text": "Given an expression string exp, write a program to examine whether the pairs and the orders of “{“, “}”, “(“, “)”, “[“, “]” are correct in exp." }, { "code": null, "e": 25162, "s": 25152, "text": "Example: " }, { "code": null, "e": 25211, "s": 25162, "text": "Input: exp = “[()]{}{[()()]()}” Output: Balanced" }, { "code": null, "e": 25253, "s": 25211, "text": "Input: exp = “[(])” Output: Not Balanced " }, { "code": null, "e": 25265, "s": 25253, "text": "Algorithm: " }, { "code": null, "e": 25294, "s": 25265, "text": "Declare a character stack S." }, { "code": null, "e": 25612, "s": 25294, "text": "Now traverse the expression string exp. If the current character is a starting bracket (‘(‘ or ‘{‘ or ‘[‘) then push it to stack.If the current character is a closing bracket (‘)’ or ‘}’ or ‘]’) then pop from stack and if the popped character is the matching starting bracket then fine else brackets are not balanced." }, { "code": null, "e": 25890, "s": 25612, "text": "If the current character is a starting bracket (‘(‘ or ‘{‘ or ‘[‘) then push it to stack.If the current character is a closing bracket (‘)’ or ‘}’ or ‘]’) then pop from stack and if the popped character is the matching starting bracket then fine else brackets are not balanced." }, { "code": null, "e": 25980, "s": 25890, "text": "If the current character is a starting bracket (‘(‘ or ‘{‘ or ‘[‘) then push it to stack." }, { "code": null, "e": 26169, "s": 25980, "text": "If the current character is a closing bracket (‘)’ or ‘}’ or ‘]’) then pop from stack and if the popped character is the matching starting bracket then fine else brackets are not balanced." }, { "code": null, "e": 26263, "s": 26169, "text": "After complete traversal, if there is some starting bracket left in stack then “not balanced”" }, { "code": null, "e": 26311, "s": 26263, "text": "Below image is a dry run of the above approach:" }, { "code": null, "e": 26362, "s": 26311, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 26364, "s": 26362, "text": "C" }, { "code": "#include <stdio.h>#include <stdlib.h>#define bool int // structure of a stack nodestruct sNode { char data; struct sNode* next;}; // Function to push an item to stackvoid push(struct sNode** top_ref, int new_data); // Function to pop an item from stackint pop(struct sNode** top_ref); // Returns 1 if character1 and character2 are matching left// and right Bracketsbool isMatchingPair(char character1, char character2){ if (character1 == '(' && character2 == ')') return 1; else if (character1 == '{' && character2 == '}') return 1; else if (character1 == '[' && character2 == ']') return 1; else return 0;} // Return 1 if expression has balanced Bracketsbool areBracketsBalanced(char exp[]){ int i = 0; // Declare an empty character stack struct sNode* stack = NULL; // Traverse the given expression to check matching // brackets while (exp[i]) { // If the exp[i] is a starting bracket then push // it if (exp[i] == '{' || exp[i] == '(' || exp[i] == '[') push(&stack, exp[i]); // If exp[i] is an ending bracket then pop from // stack and check if the popped bracket is a // matching pair*/ if (exp[i] == '}' || exp[i] == ')' || exp[i] == ']') { // If we see an ending bracket without a pair // then return false if (stack == NULL) return 0; // Pop the top element from stack, if it is not // a pair bracket of character then there is a // mismatch. // his happens for expressions like {(}) else if (!isMatchingPair(pop(&stack), exp[i])) return 0; } i++; } // If there is something left in expression then there // is a starting bracket without a closing // bracket if (stack == NULL) return 1; // balanced else return 0; // not balanced} // Driver codeint main(){ char exp[100] = \"{()}[]\"; // Function call if (areBracketsBalanced(exp)) printf(\"Balanced \"); else printf(\"Not Balanced \"); return 0;} // Function to push an item to stackvoid push(struct sNode** top_ref, int new_data){ // allocate node struct sNode* new_node = (struct sNode*)malloc(sizeof(struct sNode)); if (new_node == NULL) { printf(\"Stack overflow n\"); getchar(); exit(0); } // put in the data new_node->data = new_data; // link the old list off the new node new_node->next = (*top_ref); // move the head to point to the new node (*top_ref) = new_node;} // Function to pop an item from stackint pop(struct sNode** top_ref){ char res; struct sNode* top; // If stack is empty then error if (*top_ref == NULL) { printf(\"Stack overflow n\"); getchar(); exit(0); } else { top = *top_ref; res = top->data; *top_ref = top->next; free(top); return res; }}", "e": 29381, "s": 26364, "text": null }, { "code": null, "e": 29390, "s": 29381, "text": "Balanced" }, { "code": null, "e": 29446, "s": 29390, "text": "Time Complexity: O(n) Auxiliary Space: O(n) for stack. " }, { "code": null, "e": 29572, "s": 29446, "text": "Please refer complete article on Check for Balanced Brackets in an expression (well-formedness) using Stack for more details!" }, { "code": null, "e": 29579, "s": 29572, "text": "Amazon" }, { "code": null, "e": 29584, "s": 29579, "text": "Hike" }, { "code": null, "e": 29591, "s": 29584, "text": "Oracle" }, { "code": null, "e": 29612, "s": 29591, "text": "Parentheses-Problems" }, { "code": null, "e": 29621, "s": 29612, "text": "Snapdeal" }, { "code": null, "e": 29629, "s": 29621, "text": "Walmart" }, { "code": null, "e": 29635, "s": 29629, "text": "Wipro" }, { "code": null, "e": 29645, "s": 29635, "text": "Yatra.com" }, { "code": null, "e": 29650, "s": 29645, "text": "Zoho" }, { "code": null, "e": 29661, "s": 29650, "text": "C Programs" }, { "code": null, "e": 29667, "s": 29661, "text": "Stack" }, { "code": null, "e": 29675, "s": 29667, "text": "Strings" }, { "code": null, "e": 29680, "s": 29675, "text": "Zoho" }, { "code": null, "e": 29687, "s": 29680, "text": "Amazon" }, { "code": null, "e": 29696, "s": 29687, "text": "Snapdeal" }, { "code": null, "e": 29701, "s": 29696, "text": "Hike" }, { "code": null, "e": 29708, "s": 29701, "text": "Oracle" }, { "code": null, "e": 29716, "s": 29708, "text": "Walmart" }, { "code": null, "e": 29722, "s": 29716, "text": "Wipro" }, { "code": null, "e": 29732, "s": 29722, "text": "Yatra.com" }, { "code": null, "e": 29740, "s": 29732, "text": "Strings" }, { "code": null, "e": 29746, "s": 29740, "text": "Stack" }, { "code": null, "e": 29844, "s": 29746, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29885, "s": 29844, "text": "C Program to read contents of Whole File" }, { "code": null, "e": 29916, "s": 29885, "text": "Producer Consumer Problem in C" }, { "code": null, "e": 29957, "s": 29916, "text": "C program to find the length of a string" }, { "code": null, "e": 29991, "s": 29957, "text": "Exit codes in C/C++ with Examples" }, { "code": null, "e": 30016, "s": 29991, "text": "Regular expressions in C" }, { "code": null, "e": 30064, "s": 30016, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 30084, "s": 30064, "text": "Stack Class in Java" }, { "code": null, "e": 30100, "s": 30084, "text": "Stack in Python" }, { "code": null, "e": 30175, "s": 30100, "text": "Check for Balanced Brackets in an expression (well-formedness) using Stack" } ]
Find numbers a and b that satisfy the given conditions - GeeksforGeeks
07 Mar, 2022 Given an integer n, the task is to find two integers a and b which satisfy the below conditions: a % b = 0a * b > na / b < n a % b = 0 a * b > n a / b < n If no pair satisfies the above conditions then print -1. Note: There can be multiple (a, b) pairs satisfying the above conditions for n.Examples: Input: n = 10 Output: a = 90, b = 10 90 % 10 = 0 90 * 10 = 900 > 10 90 / 10 = 9 < 10 All three conditions are satisfied. Input: n = 1 Output: -1 Approach: Let’s suppose b = n, by taking this assumption a can be found based on the given conditions: (a % b = 0) => a should be multiple of b. (a / b < n) => a / b = n – 1 which is < n. (a * b > n) => a = n. Below is the implementation of the above approach: C++ Java Python3 C# PHP Javascript // C++ implementation of the above approach#include <bits/stdc++.h>using namespace std; // Function to print the required numbersvoid find(int n){ // Suppose b = n and we want a % b = 0 and also // (a / b) < n so a = b * (n - 1) int b = n; int a = b * (n - 1); // Special case if n = 1 // we get a = 0 so (a * b) < n if (a * b > n && a / b < n) { cout << "a = " << a << ", b = " << b; } // If no pair satisfies the conditions else cout << -1 << endl;} // Driver codeint main(){ int n = 10; find(n); return 0;} // Java implementation of the above approach public class GFG{ // Function to print the required numbers static void find(int n) { // Suppose b = n and we want a % b = 0 and also // (a / b) < n so a = b * (n - 1) int b = n; int a = b * (n - 1); // Special case if n = 1 // we get a = 0 so (a * b) < n if (a * b > n && a / b < n) { System.out.print("a = " + a + ", b = " + b); } // If no pair satisfies the conditions else System.out.println(-1); } // Driver code public static void main(String []args) { int n = 10; find(n); } // This code is contributed by Ryuga} # Python3 implementation of the above approach # Function to print the required numbersdef find(n): # Suppose b = n and we want a % b = 0 # and also (a / b) < n so a = b * (n - 1) b = n a = b * (n - 1) # Special case if n = 1 # we get a = 0 so (a * b) < n if a * b > n and a // b < n: print("a = {}, b = {}" . format(a, b)) # If no pair satisfies the conditions else: print(-1) # Driver Codeif __name__ == "__main__": n = 10 find(n) # This code is contributed by Rituraj Jain // C# implementation of the above approachusing System; class GFG{ // Function to print the required numbersstatic void find(int n){ // Suppose b = n and we want a % b = 0 // and also (a / b) < n so a = b * (n - 1) int b = n; int a = b * (n - 1); // Special case if n = 1 // we get a = 0 so (a * b) < n if (a * b > n && a / b < n) { Console.Write("a = " + a + ", b = " + b); } // If no pair satisfies the conditions else Console.WriteLine(-1);} // Driver codepublic static void Main(){ int n = 10; find(n);}} // This code is contributed// by Akanksha Rai <?php// PHP implementation of the above approach // Function to print the required numbersfunction find($n){ // Suppose b = n and we want a % b = 0 and also // (a / b) < n so a = b * (n - 1) $b = $n; $a = $b * ($n - 1); // Special case if n = 1 // we get a = 0 so (a * b) < n if ($a * $b > $n && $a / $b <$n) { echo "a = " , $a , ", b = " , $b; } // If no pair satisfies the conditions else echo -1 ;} // Driver code $n = 10; find($n);// This code is contributed// by inder_verma..?> <script> // Javascript implementation of the above approach // Function to print the required numbers function find(n) { // Suppose b = n and we want a % b = 0 // and also (a / b) < n so a = b * (n - 1) let b = n; let a = b * (n - 1); // Special case if n = 1 // we get a = 0 so (a * b) < n if (a * b > n && a / b < n) { document.write("a = " + a + ", b = " + b); } // If no pair satisfies the conditions else document.write(-1); } let n = 10; find(n); // This code is contributed by surehs07.</script> a = 90, b = 10 Time Complexity: O(1)Auxiliary Space: O(1) rituraj_jain ankthon Akanksha_Rai inderDuMCA suresh07 singhh3010 number-theory Mathematical number-theory Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Algorithm to solve Rubik's Cube Program to print prime numbers from 1 to N. Fizz Buzz Implementation Program to multiply two matrices Modular multiplicative inverse Check if a number is Palindrome Find first and last digits of a number Count ways to reach the n'th stair Program to convert a given number to words Find Union and Intersection of two unsorted arrays
[ { "code": null, "e": 24716, "s": 24688, "text": "\n07 Mar, 2022" }, { "code": null, "e": 24815, "s": 24716, "text": "Given an integer n, the task is to find two integers a and b which satisfy the below conditions: " }, { "code": null, "e": 24843, "s": 24815, "text": "a % b = 0a * b > na / b < n" }, { "code": null, "e": 24853, "s": 24843, "text": "a % b = 0" }, { "code": null, "e": 24863, "s": 24853, "text": "a * b > n" }, { "code": null, "e": 24873, "s": 24863, "text": "a / b < n" }, { "code": null, "e": 25021, "s": 24873, "text": "If no pair satisfies the above conditions then print -1. Note: There can be multiple (a, b) pairs satisfying the above conditions for n.Examples: " }, { "code": null, "e": 25167, "s": 25021, "text": "Input: n = 10\nOutput: a = 90, b = 10\n90 % 10 = 0\n90 * 10 = 900 > 10\n90 / 10 = 9 < 10\nAll three conditions are satisfied.\n\nInput: n = 1\nOutput: -1" }, { "code": null, "e": 25274, "s": 25169, "text": "Approach: Let’s suppose b = n, by taking this assumption a can be found based on the given conditions: " }, { "code": null, "e": 25316, "s": 25274, "text": "(a % b = 0) => a should be multiple of b." }, { "code": null, "e": 25359, "s": 25316, "text": "(a / b < n) => a / b = n – 1 which is < n." }, { "code": null, "e": 25381, "s": 25359, "text": "(a * b > n) => a = n." }, { "code": null, "e": 25433, "s": 25381, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 25437, "s": 25433, "text": "C++" }, { "code": null, "e": 25442, "s": 25437, "text": "Java" }, { "code": null, "e": 25450, "s": 25442, "text": "Python3" }, { "code": null, "e": 25453, "s": 25450, "text": "C#" }, { "code": null, "e": 25457, "s": 25453, "text": "PHP" }, { "code": null, "e": 25468, "s": 25457, "text": "Javascript" }, { "code": "// C++ implementation of the above approach#include <bits/stdc++.h>using namespace std; // Function to print the required numbersvoid find(int n){ // Suppose b = n and we want a % b = 0 and also // (a / b) < n so a = b * (n - 1) int b = n; int a = b * (n - 1); // Special case if n = 1 // we get a = 0 so (a * b) < n if (a * b > n && a / b < n) { cout << \"a = \" << a << \", b = \" << b; } // If no pair satisfies the conditions else cout << -1 << endl;} // Driver codeint main(){ int n = 10; find(n); return 0;}", "e": 26033, "s": 25468, "text": null }, { "code": "// Java implementation of the above approach public class GFG{ // Function to print the required numbers static void find(int n) { // Suppose b = n and we want a % b = 0 and also // (a / b) < n so a = b * (n - 1) int b = n; int a = b * (n - 1); // Special case if n = 1 // we get a = 0 so (a * b) < n if (a * b > n && a / b < n) { System.out.print(\"a = \" + a + \", b = \" + b); } // If no pair satisfies the conditions else System.out.println(-1); } // Driver code public static void main(String []args) { int n = 10; find(n); } // This code is contributed by Ryuga}", "e": 26747, "s": 26033, "text": null }, { "code": "# Python3 implementation of the above approach # Function to print the required numbersdef find(n): # Suppose b = n and we want a % b = 0 # and also (a / b) < n so a = b * (n - 1) b = n a = b * (n - 1) # Special case if n = 1 # we get a = 0 so (a * b) < n if a * b > n and a // b < n: print(\"a = {}, b = {}\" . format(a, b)) # If no pair satisfies the conditions else: print(-1) # Driver Codeif __name__ == \"__main__\": n = 10 find(n) # This code is contributed by Rituraj Jain", "e": 27278, "s": 26747, "text": null }, { "code": "// C# implementation of the above approachusing System; class GFG{ // Function to print the required numbersstatic void find(int n){ // Suppose b = n and we want a % b = 0 // and also (a / b) < n so a = b * (n - 1) int b = n; int a = b * (n - 1); // Special case if n = 1 // we get a = 0 so (a * b) < n if (a * b > n && a / b < n) { Console.Write(\"a = \" + a + \", b = \" + b); } // If no pair satisfies the conditions else Console.WriteLine(-1);} // Driver codepublic static void Main(){ int n = 10; find(n);}} // This code is contributed// by Akanksha Rai", "e": 27888, "s": 27278, "text": null }, { "code": "<?php// PHP implementation of the above approach // Function to print the required numbersfunction find($n){ // Suppose b = n and we want a % b = 0 and also // (a / b) < n so a = b * (n - 1) $b = $n; $a = $b * ($n - 1); // Special case if n = 1 // we get a = 0 so (a * b) < n if ($a * $b > $n && $a / $b <$n) { echo \"a = \" , $a , \", b = \" , $b; } // If no pair satisfies the conditions else echo -1 ;} // Driver code $n = 10; find($n);// This code is contributed// by inder_verma..?>", "e": 28425, "s": 27888, "text": null }, { "code": "<script> // Javascript implementation of the above approach // Function to print the required numbers function find(n) { // Suppose b = n and we want a % b = 0 // and also (a / b) < n so a = b * (n - 1) let b = n; let a = b * (n - 1); // Special case if n = 1 // we get a = 0 so (a * b) < n if (a * b > n && a / b < n) { document.write(\"a = \" + a + \", b = \" + b); } // If no pair satisfies the conditions else document.write(-1); } let n = 10; find(n); // This code is contributed by surehs07.</script>", "e": 29073, "s": 28425, "text": null }, { "code": null, "e": 29088, "s": 29073, "text": "a = 90, b = 10" }, { "code": null, "e": 29133, "s": 29090, "text": "Time Complexity: O(1)Auxiliary Space: O(1)" }, { "code": null, "e": 29146, "s": 29133, "text": "rituraj_jain" }, { "code": null, "e": 29154, "s": 29146, "text": "ankthon" }, { "code": null, "e": 29167, "s": 29154, "text": "Akanksha_Rai" }, { "code": null, "e": 29178, "s": 29167, "text": "inderDuMCA" }, { "code": null, "e": 29187, "s": 29178, "text": "suresh07" }, { "code": null, "e": 29198, "s": 29187, "text": "singhh3010" }, { "code": null, "e": 29212, "s": 29198, "text": "number-theory" }, { "code": null, "e": 29225, "s": 29212, "text": "Mathematical" }, { "code": null, "e": 29239, "s": 29225, "text": "number-theory" }, { "code": null, "e": 29252, "s": 29239, "text": "Mathematical" }, { "code": null, "e": 29350, "s": 29252, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29382, "s": 29350, "text": "Algorithm to solve Rubik's Cube" }, { "code": null, "e": 29426, "s": 29382, "text": "Program to print prime numbers from 1 to N." }, { "code": null, "e": 29451, "s": 29426, "text": "Fizz Buzz Implementation" }, { "code": null, "e": 29484, "s": 29451, "text": "Program to multiply two matrices" }, { "code": null, "e": 29515, "s": 29484, "text": "Modular multiplicative inverse" }, { "code": null, "e": 29547, "s": 29515, "text": "Check if a number is Palindrome" }, { "code": null, "e": 29586, "s": 29547, "text": "Find first and last digits of a number" }, { "code": null, "e": 29621, "s": 29586, "text": "Count ways to reach the n'th stair" }, { "code": null, "e": 29664, "s": 29621, "text": "Program to convert a given number to words" } ]
PHP | file_put_contents() Function - GeeksforGeeks
03 May, 2018 The file_put_contents() function in PHP is an inbuilt function which is used to write a string to a file. The file_put_contents() function checks for the file in which the user wants to write and if the file doesn’t exist, it creates a new file. The path of the file on which the user wants to write and the data that has to be written are sent as parameters to the function and it returns the number of bytes that were written on the file on success and FALSE on failure. Syntax: file_put_contents($file, $data, $mode, $context) Parameters: The file_put_contents() function in PHP accepts two mandatory parameters and two optional parameters. $file: It specifies the file on which you want to write.$data: It specifies the data that has to be written on the file. It can be a string, an array or a data stream.$context: It is an optional parameter which is used to specify a custom context or the behavior of the stream.$mode: It is an optional parameter which is used to specify how the data has to be written on the file such as FILE_USE_INCLUDE_PATH, FILE_APPEND, LOCK_EX. $file: It specifies the file on which you want to write. $data: It specifies the data that has to be written on the file. It can be a string, an array or a data stream. $context: It is an optional parameter which is used to specify a custom context or the behavior of the stream. $mode: It is an optional parameter which is used to specify how the data has to be written on the file such as FILE_USE_INCLUDE_PATH, FILE_APPEND, LOCK_EX. Return Value: It returns the number of bytes that were written on the file on success and FALSE on failure. Errors And Exception: The file_put_contents() function returns Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE.This function fails to write contents if the directory provided is invalid. The file_put_contents() function returns Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE. This function fails to write contents if the directory provided is invalid. Examples: Input : file_put_contents("gfg.txt", "A computer science portal for geeks!"); Output : 36 Input : $file_pointer = 'gfg.txt'; $open = file_get_contents($file_pointer); $open .= "A computer science portal for geeks!"; file_put_contents($file_pointer, $open); Output : 36 Below programs illustrate the file_put_contents() function. Program 1: <?php // writing content on gfg.txtecho file_put_contents("gfg.txt", "A computer science portal for geeks!");?> Output: 36 Program 2: <?php $file_pointer = 'gfg.txt'; // Open the file to get existing content$open = file_get_contents($file_pointer); // Append a new person to the file$open .= "A computer science portal for geeks!"; // Write the contents back to the filefile_put_contents($file_pointer, $open); ?> Output: 36 Reference:http://php.net/manual/en/function.file-put-contents.php PHP-file-handling PHP Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Insert Form Data into Database using PHP ? How to convert array to string in PHP ? How to Upload Image into Database and Display it using PHP ? How to check whether an array is empty using PHP? How to receive JSON POST with PHP ? Top 10 Front End Developer Skills That You Need in 2022 Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 24255, "s": 24227, "text": "\n03 May, 2018" }, { "code": null, "e": 24501, "s": 24255, "text": "The file_put_contents() function in PHP is an inbuilt function which is used to write a string to a file. The file_put_contents() function checks for the file in which the user wants to write and if the file doesn’t exist, it creates a new file." }, { "code": null, "e": 24728, "s": 24501, "text": "The path of the file on which the user wants to write and the data that has to be written are sent as parameters to the function and it returns the number of bytes that were written on the file on success and FALSE on failure." }, { "code": null, "e": 24736, "s": 24728, "text": "Syntax:" }, { "code": null, "e": 24785, "s": 24736, "text": "file_put_contents($file, $data, $mode, $context)" }, { "code": null, "e": 24899, "s": 24785, "text": "Parameters: The file_put_contents() function in PHP accepts two mandatory parameters and two optional parameters." }, { "code": null, "e": 25332, "s": 24899, "text": "$file: It specifies the file on which you want to write.$data: It specifies the data that has to be written on the file. It can be a string, an array or a data stream.$context: It is an optional parameter which is used to specify a custom context or the behavior of the stream.$mode: It is an optional parameter which is used to specify how the data has to be written on the file such as FILE_USE_INCLUDE_PATH, FILE_APPEND, LOCK_EX." }, { "code": null, "e": 25389, "s": 25332, "text": "$file: It specifies the file on which you want to write." }, { "code": null, "e": 25501, "s": 25389, "text": "$data: It specifies the data that has to be written on the file. It can be a string, an array or a data stream." }, { "code": null, "e": 25612, "s": 25501, "text": "$context: It is an optional parameter which is used to specify a custom context or the behavior of the stream." }, { "code": null, "e": 25768, "s": 25612, "text": "$mode: It is an optional parameter which is used to specify how the data has to be written on the file such as FILE_USE_INCLUDE_PATH, FILE_APPEND, LOCK_EX." }, { "code": null, "e": 25876, "s": 25768, "text": "Return Value: It returns the number of bytes that were written on the file on success and FALSE on failure." }, { "code": null, "e": 25898, "s": 25876, "text": "Errors And Exception:" }, { "code": null, "e": 26095, "s": 25898, "text": "The file_put_contents() function returns Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE.This function fails to write contents if the directory provided is invalid." }, { "code": null, "e": 26217, "s": 26095, "text": "The file_put_contents() function returns Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE." }, { "code": null, "e": 26293, "s": 26217, "text": "This function fails to write contents if the directory provided is invalid." }, { "code": null, "e": 26303, "s": 26293, "text": "Examples:" }, { "code": null, "e": 26620, "s": 26303, "text": "Input : file_put_contents(\"gfg.txt\", \"A computer \n science portal for geeks!\");\nOutput : 36\n\nInput : $file_pointer = 'gfg.txt';\n $open = file_get_contents($file_pointer);\n $open .= \"A computer science portal for geeks!\";\n file_put_contents($file_pointer, $open);\nOutput : 36\n" }, { "code": null, "e": 26680, "s": 26620, "text": "Below programs illustrate the file_put_contents() function." }, { "code": null, "e": 26691, "s": 26680, "text": "Program 1:" }, { "code": "<?php // writing content on gfg.txtecho file_put_contents(\"gfg.txt\", \"A computer science portal for geeks!\");?>", "e": 26822, "s": 26691, "text": null }, { "code": null, "e": 26830, "s": 26822, "text": "Output:" }, { "code": null, "e": 26833, "s": 26830, "text": "36" }, { "code": null, "e": 26844, "s": 26833, "text": "Program 2:" }, { "code": "<?php $file_pointer = 'gfg.txt'; // Open the file to get existing content$open = file_get_contents($file_pointer); // Append a new person to the file$open .= \"A computer science portal for geeks!\"; // Write the contents back to the filefile_put_contents($file_pointer, $open); ?>", "e": 27129, "s": 26844, "text": null }, { "code": null, "e": 27137, "s": 27129, "text": "Output:" }, { "code": null, "e": 27140, "s": 27137, "text": "36" }, { "code": null, "e": 27206, "s": 27140, "text": "Reference:http://php.net/manual/en/function.file-put-contents.php" }, { "code": null, "e": 27224, "s": 27206, "text": "PHP-file-handling" }, { "code": null, "e": 27228, "s": 27224, "text": "PHP" }, { "code": null, "e": 27245, "s": 27228, "text": "Web Technologies" }, { "code": null, "e": 27249, "s": 27245, "text": "PHP" }, { "code": null, "e": 27347, "s": 27249, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27356, "s": 27347, "text": "Comments" }, { "code": null, "e": 27369, "s": 27356, "text": "Old Comments" }, { "code": null, "e": 27419, "s": 27369, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 27459, "s": 27419, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 27520, "s": 27459, "text": "How to Upload Image into Database and Display it using PHP ?" }, { "code": null, "e": 27570, "s": 27520, "text": "How to check whether an array is empty using PHP?" }, { "code": null, "e": 27606, "s": 27570, "text": "How to receive JSON POST with PHP ?" }, { "code": null, "e": 27662, "s": 27606, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 27695, "s": 27662, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 27757, "s": 27695, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 27800, "s": 27757, "text": "How to fetch data from an API in ReactJS ?" } ]
How to use MongoDB Aggregate to sort?
Use aggregate() and within that to sort, use $sort in MongoDB. Let us create a collection with documents − > db.demo164.insertOne({"StudentAge":24}); { "acknowledged" : true, "insertedId" : ObjectId("5e36883d9e4f06af551997c8") } > db.demo164.insertOne({"StudentAge":25}); { "acknowledged" : true, "insertedId" : ObjectId("5e3688409e4f06af551997c9") } > db.demo164.insertOne({"StudentAge":22}); { "acknowledged" : true, "insertedId" : ObjectId("5e3688429e4f06af551997ca") } > db.demo164.insertOne({"StudentAge":21}); { "acknowledged" : true, "insertedId" : ObjectId("5e3688439e4f06af551997cb") } Display all documents from a collection with the help of find() method − > db.demo164.find(); This will produce the following output − { "_id" : ObjectId("5e36883d9e4f06af551997c8"), "StudentAge" : 24 } { "_id" : ObjectId("5e3688409e4f06af551997c9"), "StudentAge" : 25 } { "_id" : ObjectId("5e3688429e4f06af551997ca"), "StudentAge" : 22 } { "_id" : ObjectId("5e3688439e4f06af551997cb"), "StudentAge" : 21 } Here is the query to use MongoDB aggregate() − > db.demo164.aggregate([{ $sort : { StudentAge : -1 } }]); This will produce the following output − { "_id" : ObjectId("5e3688409e4f06af551997c9"), "StudentAge" : 25 } { "_id" : ObjectId("5e36883d9e4f06af551997c8"), "StudentAge" : 24 } { "_id" : ObjectId("5e3688429e4f06af551997ca"), "StudentAge" : 22 } { "_id" : ObjectId("5e3688439e4f06af551997cb"), "StudentAge" : 21 }
[ { "code": null, "e": 1169, "s": 1062, "text": "Use aggregate() and within that to sort, use $sort in MongoDB. Let us create a collection with documents −" }, { "code": null, "e": 1681, "s": 1169, "text": "> db.demo164.insertOne({\"StudentAge\":24});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e36883d9e4f06af551997c8\")\n}\n> db.demo164.insertOne({\"StudentAge\":25});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e3688409e4f06af551997c9\")\n}\n> db.demo164.insertOne({\"StudentAge\":22});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e3688429e4f06af551997ca\")\n}\n> db.demo164.insertOne({\"StudentAge\":21});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e3688439e4f06af551997cb\")\n}" }, { "code": null, "e": 1754, "s": 1681, "text": "Display all documents from a collection with the help of find() method −" }, { "code": null, "e": 1775, "s": 1754, "text": "> db.demo164.find();" }, { "code": null, "e": 1816, "s": 1775, "text": "This will produce the following output −" }, { "code": null, "e": 2088, "s": 1816, "text": "{ \"_id\" : ObjectId(\"5e36883d9e4f06af551997c8\"), \"StudentAge\" : 24 }\n{ \"_id\" : ObjectId(\"5e3688409e4f06af551997c9\"), \"StudentAge\" : 25 }\n{ \"_id\" : ObjectId(\"5e3688429e4f06af551997ca\"), \"StudentAge\" : 22 }\n{ \"_id\" : ObjectId(\"5e3688439e4f06af551997cb\"), \"StudentAge\" : 21 }" }, { "code": null, "e": 2135, "s": 2088, "text": "Here is the query to use MongoDB aggregate() −" }, { "code": null, "e": 2194, "s": 2135, "text": "> db.demo164.aggregate([{ $sort : { StudentAge : -1 } }]);" }, { "code": null, "e": 2235, "s": 2194, "text": "This will produce the following output −" }, { "code": null, "e": 2507, "s": 2235, "text": "{ \"_id\" : ObjectId(\"5e3688409e4f06af551997c9\"), \"StudentAge\" : 25 }\n{ \"_id\" : ObjectId(\"5e36883d9e4f06af551997c8\"), \"StudentAge\" : 24 }\n{ \"_id\" : ObjectId(\"5e3688429e4f06af551997ca\"), \"StudentAge\" : 22 }\n{ \"_id\" : ObjectId(\"5e3688439e4f06af551997cb\"), \"StudentAge\" : 21 }" } ]
Wavelet Transforms in Python with Google JAX | by Shailesh Kumar | Towards Data Science
Wavelet transforms are one of the key tools for signal analysis. They are extensively used in science and engineering. Some of the specific applications include data compression, gait analysis, signal/image de-noising, digital communications, etc. This article focuses on a simple lossy data compression application by using the DWT (Discrete Wavelet Transform) support provided in the CR-Sparse library. For a good introduction to wavelet transforms, please see: Wikipedia, Wavelet transform THE WAVELET TUTORIAL, PART I C. Valens, A really friendly guide to wavelets Vidakovic and Mueller, Wavelets for kids, A tutorial introduction There are several packages in Python which have support for wavelet transforms. Let me list a few: PyWavelets is one of the most comprehensive implementations for wavelet support in python for both discrete and continuous wavelets. pytorch-wavelets provide support for 2D discrete wavelet and 2d dual-tree complex wavelet transforms. scipy provides some basic support for the continuous wavelet transform. PyWavelet is probably the most mature library available. Its coverage and performance are great. However, major parts of the library are written in C. Hence, retargeting the implementation for GPU hardware is not possible. That is one of the reasons for people coming up with newer implementations e.g. on top of PyTorch which provides the necessary GPU support. The CR-Sparse library now includes support for computing discrete and continuous wavelet transforms using the Google JAX library. JAX provides high-performance numerical computing by taking advantage of XLA. XLA is a domain-specific compiler for linear algebra. JAX provides a NumPy-like API and a JIT compiler so that code written using JAX can be easily just in time compiled (using XLA) to machine code for specific hardware architecture. Thus, you can write pure Python code on top of JAX API and build sophisticated numerical algorithms which can get cross-compiled to different GPU architectures efficiently. JAX has tools like pmap which makes parallel evaluation of code straightforward. For large datasets, JAX easily outperforms NumPy even on CPU. However, getting advantage of JAX does require some work. We have to write our numerical algorithms in a manner so that they can be JIT-compiled. One specific need is that all the code is written using functional programming principles. E.g. the JAX arrays are immutable (while NumPy arrays are not) so any change to an array actually creates a new array at the Python level of code. XLA compiler is smart enough to reuse memory. In a way, rewriting numerical algorithms in a functional manner is quite a rewarding experience. It lets you focus on the essential mathematics, avoids unnecessary global state manipulation, keeps the implementation quite clean and simple. CR-Sparse focuses on functional models and algorithms for sparse signal processing, i.e. exploiting the sparsity of signal representations in signal processing problems. Wavelet transforms are a key tool for constructing sparse representations of common signals. Thus, they form an important part of the CR-Sparse library. The implementation is pure Python, written using functional programming principles followed by JAX, and it gets just in time compiled to CPU/GPU/TPU architectures seamlessly giving excellent performance. The wavelet module API is inspired by and is similar to PyWavelets. In addition, the wavelet functionality has been wrapped as 1D and 2D linear operators similar to PyLops. Please refer to my previous article Implementing Linear Operators in Python with Google JAX for more information about linear operator design. Wavelet transforms are invertible. We can decompose a signal using a wavelet to obtain the wavelet coefficients using an algorithm called discrete wavelet transform (DWT). The signal is decomposed into two sets of coefficients: the approximation coefficients (low pass component of a signal) and detail coefficients (high frequency. We can reconstruct the signal back from the wavelet coefficients using an algorithm called inverse discrete wavelet transform (IDWT). Multi-level decomposition Usually, the wavelet decomposition is done multiple times. We start with the signal, compute approximation and detail coefficients, then apply the DWT again on the approximation coefficients. We repeat this process multiple times to achieve a multi-level decomposition of the signal. The following example shows a 4 level decomposition X => [A1 D1] => [A2 D2 D1] => [A3 D3 D2 D1] => [A4 D4 D3 D2 D1]A1, D1 = DWT(X)A2, D2 = DWT(A1)A3, D3 = DWT(A2)A4, D4 = DWT(A3) Signal X is split into approximation and detail coefficients A1 and D1 by applying DWT. If the signal has N coefficients, then the decomposition will have N/2 approximation coefficients and N/2 detail coefficients (technically, if we use periodization extension while computing the DWT, other extensions lead to more coefficients). The approximation coefficients A1 have split again into approximation and detail coefficients A2 and D2 by applying DWT. We repeat this process 2 more times. The 4 level decomposition of X is obtained by concatenating the coefficients in A4, D4, D3, D2, D1. If the signal X has N samples, then the wavelet decomposition will also consist of N coefficients. The reconstruction of the signal proceeds as follows: A3 = IDWT(A4, D4)A2 = IDWT(A3, D3)A1 = IDWT (A2, D2)X = IDWT(A1, D1) It turns out that the signal can still be faithfully reconstructed with pretty high SNR if we drop some of the detail coefficients. If we drop D1 coefficients, we achieve 50% compression. If we drop both D1 and D2 coefficients, we can achieve 75% compression. An important consideration is to measure the signal-to-noise ratio after reconstructing the signal from the remaining coefficients. If the compression technique is good, the SNR will be high. This is a very simplistic treatment of the compression problem but it will suffice for the purposes of this article. We now show the sample code for using 1D and 2D wavelet transform for signal and image compression and reconstruction. The detailed example code is available in the examples gallery (in the CR-Sparse documentation) here. This example runs against the latest version in the repository which can be installed with: python -m pip install git+https://github.com/carnotresearch/cr-sparse.git First, the necessary imports. We will also need JAX, matplotlib, and scikit-image libraries. import jax.numpy as jnpimport matplotlib.pyplot as pltimport cr.sparse as crsfrom cr.sparse import lopfrom cr.sparse import metricsimport skimage.datafrom cr.sparse.dsp import time_values We will construct a signal consisting of multiple sinusoids at different frequencies and amplitudes for this example. fs = 1000.T = 2t = time_values(fs, T)n = t.sizex = jnp.zeros(n)freqs = [25, 7, 9]amps = [1, -3, .8]for (f, amp) in zip(freqs, amps): sinusoid = amp * jnp.sin(2 * jnp.pi * f * t) x = x + sinusoid The CR-Sparse linear operator module (lop) includes a 1D wavelet transform operator. We will construct the operator. We will provide the size of the signal, the wavelet type, and the number of levels of decomposition as parameters for this operator. DWT_op = lop.dwt(n, wavelet='dmey', level=5) Wavelet coefficients are computed by applying the linear operator to the data. Read here for learning how linear operators work in CR-Sparse. alpha = DWT_op.times(x) It is interesting to note that most of the detail coefficients are negligible. The magnitude of a wavelet coefficient indicates the portion of signal energy carried by that coefficient. Dropping these coefficients shouldn’t lead to a high reconstruction error. Let’s drop all but 10% of the coefficients (compression): cutoff = n // 10alpha2 = alpha.at[cutoff:].set(0) For our purposes, we just set those coefficients to 0. In a digital communication setup, those coefficients won’t be transmitted and will be assumed to be zero by the receiver. We also see a little difficult syntax for array updates. Since arrays are immutable in JAX, hence JAX provides functional variants for constructing a new array from an old array by updating parts of it. See here for details. We now reconstruct the original signal from the remaining coefficients by applying the adjoint of the DWT linear operator (which happens to be its inverse). x_rec = DWT_op.trans(alpha2)snr = metrics.signal_noise_ratio(x, x_rec)print(snr) SNR is 36.56 dB. We can see from this plot that the reconstruction error is negligible. Let’s try our luck on a 2D image now. We will take a sample grass image from scikit-image library for this demo. image = skimage.data.grass() 2D DWT is a straightforward extension of 1D DWT. Given an image X of size say NxN, compute DWT of each column. We get two new images CA and CD of size N/2 x N each (i.e. half the number of rows). Apply DWT on each row of CA to obtain CAA and CAD images (of size N/2 x N/2 each). Apply DWT on each row of CD to obtain CDA and CDD images. This way we split X into [CAA, CAD, CDA, CDD] 4 sub-images. We can combine these sub-images to form a single coefficients image. We repeat the 2D DWT decomposition on the CAA part recursively to compute the multilevel decomposition. The 2D IDWT takes [CAA, CAD, CDA, CDD] as input and returns X as output (by first applying IDWT on rows and then IDWT on columns). We will use a 2D Haar wavelet transform operator with 5 levels of decomposition. DWT2_op = lop.dwt2D(image.shape, wavelet='haar', level=5)DWT2_op = lop.jit(DWT2_op) Computing the wavelet coefficients is about applying the linear operator on the image: coefs = DWT2_op.times(image) Let’s keep only 1/16 of the coefficients (i.e. just 6.25% of coefficients). We are dropping the first and the second levels of detail coefficients. h, w = coefs.shapecoefs2 = jnp.zeros_like(coefs)coefs2 = coefs2.at[:h//4, :w//4].set(coefs[:h//4, :w//4]) Reconstruction involves applying the adjoint of the operator which happens to be its inverse. After reconstruction, we will compute the peak signal to noise ratio to measure the quality of reconstruction. image_rec = DWT2_op.trans(coefs2)# PSNRpsnr = metrics.peak_signal_noise_ratio(image, image_rec)print(psnr) PSNR is 19.38 dB. A 19 dB PSNR with just 6% of the wavelet coefficients is not bad. Also, the details of the image are well preserved and there are no blocking artifacts. I hope that this article gives a good introduction to the wavelet transform capabilities available in CR-Sparse. For more advanced usage, check out the image deblurring using LSQR and FISTA algorithms example.
[ { "code": null, "e": 577, "s": 172, "text": "Wavelet transforms are one of the key tools for signal analysis. They are extensively used in science and engineering. Some of the specific applications include data compression, gait analysis, signal/image de-noising, digital communications, etc. This article focuses on a simple lossy data compression application by using the DWT (Discrete Wavelet Transform) support provided in the CR-Sparse library." }, { "code": null, "e": 636, "s": 577, "text": "For a good introduction to wavelet transforms, please see:" }, { "code": null, "e": 665, "s": 636, "text": "Wikipedia, Wavelet transform" }, { "code": null, "e": 694, "s": 665, "text": "THE WAVELET TUTORIAL, PART I" }, { "code": null, "e": 741, "s": 694, "text": "C. Valens, A really friendly guide to wavelets" }, { "code": null, "e": 807, "s": 741, "text": "Vidakovic and Mueller, Wavelets for kids, A tutorial introduction" }, { "code": null, "e": 906, "s": 807, "text": "There are several packages in Python which have support for wavelet transforms. Let me list a few:" }, { "code": null, "e": 1039, "s": 906, "text": "PyWavelets is one of the most comprehensive implementations for wavelet support in python for both discrete and continuous wavelets." }, { "code": null, "e": 1141, "s": 1039, "text": "pytorch-wavelets provide support for 2D discrete wavelet and 2d dual-tree complex wavelet transforms." }, { "code": null, "e": 1213, "s": 1141, "text": "scipy provides some basic support for the continuous wavelet transform." }, { "code": null, "e": 1576, "s": 1213, "text": "PyWavelet is probably the most mature library available. Its coverage and performance are great. However, major parts of the library are written in C. Hence, retargeting the implementation for GPU hardware is not possible. That is one of the reasons for people coming up with newer implementations e.g. on top of PyTorch which provides the necessary GPU support." }, { "code": null, "e": 1706, "s": 1576, "text": "The CR-Sparse library now includes support for computing discrete and continuous wavelet transforms using the Google JAX library." }, { "code": null, "e": 2018, "s": 1706, "text": "JAX provides high-performance numerical computing by taking advantage of XLA. XLA is a domain-specific compiler for linear algebra. JAX provides a NumPy-like API and a JIT compiler so that code written using JAX can be easily just in time compiled (using XLA) to machine code for specific hardware architecture." }, { "code": null, "e": 2191, "s": 2018, "text": "Thus, you can write pure Python code on top of JAX API and build sophisticated numerical algorithms which can get cross-compiled to different GPU architectures efficiently." }, { "code": null, "e": 2334, "s": 2191, "text": "JAX has tools like pmap which makes parallel evaluation of code straightforward. For large datasets, JAX easily outperforms NumPy even on CPU." }, { "code": null, "e": 3004, "s": 2334, "text": "However, getting advantage of JAX does require some work. We have to write our numerical algorithms in a manner so that they can be JIT-compiled. One specific need is that all the code is written using functional programming principles. E.g. the JAX arrays are immutable (while NumPy arrays are not) so any change to an array actually creates a new array at the Python level of code. XLA compiler is smart enough to reuse memory. In a way, rewriting numerical algorithms in a functional manner is quite a rewarding experience. It lets you focus on the essential mathematics, avoids unnecessary global state manipulation, keeps the implementation quite clean and simple." }, { "code": null, "e": 3704, "s": 3004, "text": "CR-Sparse focuses on functional models and algorithms for sparse signal processing, i.e. exploiting the sparsity of signal representations in signal processing problems. Wavelet transforms are a key tool for constructing sparse representations of common signals. Thus, they form an important part of the CR-Sparse library. The implementation is pure Python, written using functional programming principles followed by JAX, and it gets just in time compiled to CPU/GPU/TPU architectures seamlessly giving excellent performance. The wavelet module API is inspired by and is similar to PyWavelets. In addition, the wavelet functionality has been wrapped as 1D and 2D linear operators similar to PyLops." }, { "code": null, "e": 3847, "s": 3704, "text": "Please refer to my previous article Implementing Linear Operators in Python with Google JAX for more information about linear operator design." }, { "code": null, "e": 3882, "s": 3847, "text": "Wavelet transforms are invertible." }, { "code": null, "e": 4180, "s": 3882, "text": "We can decompose a signal using a wavelet to obtain the wavelet coefficients using an algorithm called discrete wavelet transform (DWT). The signal is decomposed into two sets of coefficients: the approximation coefficients (low pass component of a signal) and detail coefficients (high frequency." }, { "code": null, "e": 4314, "s": 4180, "text": "We can reconstruct the signal back from the wavelet coefficients using an algorithm called inverse discrete wavelet transform (IDWT)." }, { "code": null, "e": 4340, "s": 4314, "text": "Multi-level decomposition" }, { "code": null, "e": 4399, "s": 4340, "text": "Usually, the wavelet decomposition is done multiple times." }, { "code": null, "e": 4532, "s": 4399, "text": "We start with the signal, compute approximation and detail coefficients, then apply the DWT again on the approximation coefficients." }, { "code": null, "e": 4624, "s": 4532, "text": "We repeat this process multiple times to achieve a multi-level decomposition of the signal." }, { "code": null, "e": 4676, "s": 4624, "text": "The following example shows a 4 level decomposition" }, { "code": null, "e": 4803, "s": 4676, "text": "X => [A1 D1] => [A2 D2 D1] => [A3 D3 D2 D1] => [A4 D4 D3 D2 D1]A1, D1 = DWT(X)A2, D2 = DWT(A1)A3, D3 = DWT(A2)A4, D4 = DWT(A3)" }, { "code": null, "e": 5135, "s": 4803, "text": "Signal X is split into approximation and detail coefficients A1 and D1 by applying DWT. If the signal has N coefficients, then the decomposition will have N/2 approximation coefficients and N/2 detail coefficients (technically, if we use periodization extension while computing the DWT, other extensions lead to more coefficients)." }, { "code": null, "e": 5256, "s": 5135, "text": "The approximation coefficients A1 have split again into approximation and detail coefficients A2 and D2 by applying DWT." }, { "code": null, "e": 5293, "s": 5256, "text": "We repeat this process 2 more times." }, { "code": null, "e": 5393, "s": 5293, "text": "The 4 level decomposition of X is obtained by concatenating the coefficients in A4, D4, D3, D2, D1." }, { "code": null, "e": 5492, "s": 5393, "text": "If the signal X has N samples, then the wavelet decomposition will also consist of N coefficients." }, { "code": null, "e": 5546, "s": 5492, "text": "The reconstruction of the signal proceeds as follows:" }, { "code": null, "e": 5615, "s": 5546, "text": "A3 = IDWT(A4, D4)A2 = IDWT(A3, D3)A1 = IDWT (A2, D2)X = IDWT(A1, D1)" }, { "code": null, "e": 5747, "s": 5615, "text": "It turns out that the signal can still be faithfully reconstructed with pretty high SNR if we drop some of the detail coefficients." }, { "code": null, "e": 5875, "s": 5747, "text": "If we drop D1 coefficients, we achieve 50% compression. If we drop both D1 and D2 coefficients, we can achieve 75% compression." }, { "code": null, "e": 6067, "s": 5875, "text": "An important consideration is to measure the signal-to-noise ratio after reconstructing the signal from the remaining coefficients. If the compression technique is good, the SNR will be high." }, { "code": null, "e": 6184, "s": 6067, "text": "This is a very simplistic treatment of the compression problem but it will suffice for the purposes of this article." }, { "code": null, "e": 6405, "s": 6184, "text": "We now show the sample code for using 1D and 2D wavelet transform for signal and image compression and reconstruction. The detailed example code is available in the examples gallery (in the CR-Sparse documentation) here." }, { "code": null, "e": 6497, "s": 6405, "text": "This example runs against the latest version in the repository which can be installed with:" }, { "code": null, "e": 6571, "s": 6497, "text": "python -m pip install git+https://github.com/carnotresearch/cr-sparse.git" }, { "code": null, "e": 6664, "s": 6571, "text": "First, the necessary imports. We will also need JAX, matplotlib, and scikit-image libraries." }, { "code": null, "e": 6852, "s": 6664, "text": "import jax.numpy as jnpimport matplotlib.pyplot as pltimport cr.sparse as crsfrom cr.sparse import lopfrom cr.sparse import metricsimport skimage.datafrom cr.sparse.dsp import time_values" }, { "code": null, "e": 6970, "s": 6852, "text": "We will construct a signal consisting of multiple sinusoids at different frequencies and amplitudes for this example." }, { "code": null, "e": 7172, "s": 6970, "text": "fs = 1000.T = 2t = time_values(fs, T)n = t.sizex = jnp.zeros(n)freqs = [25, 7, 9]amps = [1, -3, .8]for (f, amp) in zip(freqs, amps): sinusoid = amp * jnp.sin(2 * jnp.pi * f * t) x = x + sinusoid" }, { "code": null, "e": 7422, "s": 7172, "text": "The CR-Sparse linear operator module (lop) includes a 1D wavelet transform operator. We will construct the operator. We will provide the size of the signal, the wavelet type, and the number of levels of decomposition as parameters for this operator." }, { "code": null, "e": 7467, "s": 7422, "text": "DWT_op = lop.dwt(n, wavelet='dmey', level=5)" }, { "code": null, "e": 7609, "s": 7467, "text": "Wavelet coefficients are computed by applying the linear operator to the data. Read here for learning how linear operators work in CR-Sparse." }, { "code": null, "e": 7633, "s": 7609, "text": "alpha = DWT_op.times(x)" }, { "code": null, "e": 7894, "s": 7633, "text": "It is interesting to note that most of the detail coefficients are negligible. The magnitude of a wavelet coefficient indicates the portion of signal energy carried by that coefficient. Dropping these coefficients shouldn’t lead to a high reconstruction error." }, { "code": null, "e": 7952, "s": 7894, "text": "Let’s drop all but 10% of the coefficients (compression):" }, { "code": null, "e": 8002, "s": 7952, "text": "cutoff = n // 10alpha2 = alpha.at[cutoff:].set(0)" }, { "code": null, "e": 8404, "s": 8002, "text": "For our purposes, we just set those coefficients to 0. In a digital communication setup, those coefficients won’t be transmitted and will be assumed to be zero by the receiver. We also see a little difficult syntax for array updates. Since arrays are immutable in JAX, hence JAX provides functional variants for constructing a new array from an old array by updating parts of it. See here for details." }, { "code": null, "e": 8561, "s": 8404, "text": "We now reconstruct the original signal from the remaining coefficients by applying the adjoint of the DWT linear operator (which happens to be its inverse)." }, { "code": null, "e": 8642, "s": 8561, "text": "x_rec = DWT_op.trans(alpha2)snr = metrics.signal_noise_ratio(x, x_rec)print(snr)" }, { "code": null, "e": 8659, "s": 8642, "text": "SNR is 36.56 dB." }, { "code": null, "e": 8730, "s": 8659, "text": "We can see from this plot that the reconstruction error is negligible." }, { "code": null, "e": 8843, "s": 8730, "text": "Let’s try our luck on a 2D image now. We will take a sample grass image from scikit-image library for this demo." }, { "code": null, "e": 8872, "s": 8843, "text": "image = skimage.data.grass()" }, { "code": null, "e": 8921, "s": 8872, "text": "2D DWT is a straightforward extension of 1D DWT." }, { "code": null, "e": 9068, "s": 8921, "text": "Given an image X of size say NxN, compute DWT of each column. We get two new images CA and CD of size N/2 x N each (i.e. half the number of rows)." }, { "code": null, "e": 9151, "s": 9068, "text": "Apply DWT on each row of CA to obtain CAA and CAD images (of size N/2 x N/2 each)." }, { "code": null, "e": 9209, "s": 9151, "text": "Apply DWT on each row of CD to obtain CDA and CDD images." }, { "code": null, "e": 9269, "s": 9209, "text": "This way we split X into [CAA, CAD, CDA, CDD] 4 sub-images." }, { "code": null, "e": 9338, "s": 9269, "text": "We can combine these sub-images to form a single coefficients image." }, { "code": null, "e": 9442, "s": 9338, "text": "We repeat the 2D DWT decomposition on the CAA part recursively to compute the multilevel decomposition." }, { "code": null, "e": 9573, "s": 9442, "text": "The 2D IDWT takes [CAA, CAD, CDA, CDD] as input and returns X as output (by first applying IDWT on rows and then IDWT on columns)." }, { "code": null, "e": 9654, "s": 9573, "text": "We will use a 2D Haar wavelet transform operator with 5 levels of decomposition." }, { "code": null, "e": 9738, "s": 9654, "text": "DWT2_op = lop.dwt2D(image.shape, wavelet='haar', level=5)DWT2_op = lop.jit(DWT2_op)" }, { "code": null, "e": 9825, "s": 9738, "text": "Computing the wavelet coefficients is about applying the linear operator on the image:" }, { "code": null, "e": 9854, "s": 9825, "text": "coefs = DWT2_op.times(image)" }, { "code": null, "e": 10002, "s": 9854, "text": "Let’s keep only 1/16 of the coefficients (i.e. just 6.25% of coefficients). We are dropping the first and the second levels of detail coefficients." }, { "code": null, "e": 10108, "s": 10002, "text": "h, w = coefs.shapecoefs2 = jnp.zeros_like(coefs)coefs2 = coefs2.at[:h//4, :w//4].set(coefs[:h//4, :w//4])" }, { "code": null, "e": 10313, "s": 10108, "text": "Reconstruction involves applying the adjoint of the operator which happens to be its inverse. After reconstruction, we will compute the peak signal to noise ratio to measure the quality of reconstruction." }, { "code": null, "e": 10420, "s": 10313, "text": "image_rec = DWT2_op.trans(coefs2)# PSNRpsnr = metrics.peak_signal_noise_ratio(image, image_rec)print(psnr)" }, { "code": null, "e": 10438, "s": 10420, "text": "PSNR is 19.38 dB." }, { "code": null, "e": 10591, "s": 10438, "text": "A 19 dB PSNR with just 6% of the wavelet coefficients is not bad. Also, the details of the image are well preserved and there are no blocking artifacts." }, { "code": null, "e": 10704, "s": 10591, "text": "I hope that this article gives a good introduction to the wavelet transform capabilities available in CR-Sparse." } ]
Java if-then-else statement
In Java, if-then-else is represented by the if-else statement. An if statement can be followed by an optional else statement, which executes when the Boolean expression is false. Following is the syntax of an if...else statement − if(Boolean_expression) { // Executes when the Boolean expression is true }else { // Executes when the Boolean expression is false } If the boolean expression evaluates to true, then the if a block of code will be executed, otherwise else block of code will be executed. Live Demo public class Test { public static void main(String args[]) { int x = 30; if( x < 20 ) { System.out.print("This is if statement"); }else { System.out.print("This is else statement"); } } } This will produce the following result − This is else statement
[ { "code": null, "e": 1125, "s": 1062, "text": "In Java, if-then-else is represented by the if-else statement." }, { "code": null, "e": 1241, "s": 1125, "text": "An if statement can be followed by an optional else statement, which executes when the Boolean expression is false." }, { "code": null, "e": 1293, "s": 1241, "text": "Following is the syntax of an if...else statement −" }, { "code": null, "e": 1431, "s": 1293, "text": "if(Boolean_expression) {\n // Executes when the Boolean expression is true\n}else {\n // Executes when the Boolean expression is false\n}" }, { "code": null, "e": 1569, "s": 1431, "text": "If the boolean expression evaluates to true, then the if a block of code will be executed, otherwise else block of code will be executed." }, { "code": null, "e": 1579, "s": 1569, "text": "Live Demo" }, { "code": null, "e": 1817, "s": 1579, "text": "public class Test {\n\n public static void main(String args[]) {\n int x = 30;\n\n if( x < 20 ) {\n System.out.print(\"This is if statement\");\n }else {\n System.out.print(\"This is else statement\");\n }\n }\n}" }, { "code": null, "e": 1858, "s": 1817, "text": "This will produce the following result −" }, { "code": null, "e": 1881, "s": 1858, "text": "This is else statement" } ]
Maximize GCD of all possible pairs from 1 to N - GeeksforGeeks
05 Apr, 2021 Given an integer N (? 2), the task is to find the maximum GCD among all pairs possible by the integers in the range [1, N]. Example: Input: N = 5 Output: 2 Explanation : GCD(1, 2) : 1 GCD(1, 3) : 1 GCD(1, 4) : 1 GCD(1, 5) : 1 GCD(2, 3) : 1 GCD(2, 4) : 2 GCD(2, 5) : 1 GCD(3, 4) : 1 GCD(3, 5) : 1 GCD(4, 5) : 1 Input: N = 6 Output: 3 Explanation: GCD of pair (3, 6) is the maximum. Naive Approach: The simplest approach to solve the problem is to generate all possible pairs from [1, N] and calculate GCD of each pair. Finally, print the maximum GCD obtained. Time Complexity: O(N2logN) Auxiliary Space: O(1) Efficient Approach: Follow the steps below to solve the problem: Since all the pairs are distinct, then, for any pair {a, b} with GCD g, either of a or b is greater than g. Considering b to be the greater number, b ? 2g, since 2g is the smallest multiple of g greater than it. Since b cannot exceed N, and 2g ? N. Therefore, g ? floor(n/2). Therefore, the maximum GCD that can be obtained is floor(n/2), when pair chosen is (floor(n/2), 2*floor(n/2)). Illustration: N = 6 Maximum GCD = 6/2 = 3, occurs for the pair (3, 6) Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ Program to implement// the approach#include <bits/stdc++.h>using namespace std; // Function to obtain the maximum// gcd of all pairs from 1 to nvoid find(int n){ // Print the answer cout << n / 2 << endl;} // Driver codeint main(){ int n = 5; // Function call find(n); return 0;} // Java Program to implement// the approachclass GFG{ // Function to obtain the maximum// gcd of all pairs from 1 to nstatic void find(int n){ // Print the answer System.out.println(n / 2);} // Driver codepublic static void main(String[] args){ int n = 5; // Function call find(n);}} // This code is contributed by Ritik Bansal # Python3 program to implement# the approach # Function to obtain the maximum# gcd of all pairs from 1 to ndef find(n): # Print the answer print(n // 2) # Driver Codeif __name__ == '__main__': # Given n n = 5 # Function call find(n) # This code is contributed by Shivam Singh // C# Program to implement// the approachusing System;class GFG{ // Function to obtain the maximum// gcd of all pairs from 1 to nstatic void find(int n){ // Print the answer Console.Write(n / 2);} // Driver codepublic static void Main(string[] args){ int n = 5; // Function call find(n);}} // This code is contributed by rock_cool <script> // Javascript program to implement// the approach // Function to obtain the maximum// gcd of all pairs from 1 to nfunction find(n){ // Print the answer document.write(parseInt(n / 2, 10) + "</br>");} // Driver codelet n = 5; // Function callfind(n); // This code is contributed by divyeshrabadiya07 </script> 2 Time Complexity: O(1) Auxiliary Space: O(1) bansal_rtk_ rock_cool divyeshrabadiya07 GCD-LCM Greedy Mathematical Greedy Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Activity Selection Problem | Greedy Algo-1 Fractional Knapsack Problem Program for Shortest Job First (or SJF) CPU Scheduling | Set 1 (Non- preemptive) Job Sequencing Problem Dijkstra’s Algorithm for Adjacency List Representation | Greedy Algo-8 Program for Fibonacci numbers C++ Data Types Set in C++ Standard Template Library (STL) Merge two sorted arrays
[ { "code": null, "e": 24511, "s": 24483, "text": "\n05 Apr, 2021" }, { "code": null, "e": 24635, "s": 24511, "text": "Given an integer N (? 2), the task is to find the maximum GCD among all pairs possible by the integers in the range [1, N]." }, { "code": null, "e": 24645, "s": 24635, "text": "Example: " }, { "code": null, "e": 24822, "s": 24645, "text": "Input: N = 5 Output: 2 Explanation : GCD(1, 2) : 1 GCD(1, 3) : 1 GCD(1, 4) : 1 GCD(1, 5) : 1 GCD(2, 3) : 1 GCD(2, 4) : 2 GCD(2, 5) : 1 GCD(3, 4) : 1 GCD(3, 5) : 1 GCD(4, 5) : 1" }, { "code": null, "e": 24895, "s": 24822, "text": "Input: N = 6 Output: 3 Explanation: GCD of pair (3, 6) is the maximum. " }, { "code": null, "e": 25123, "s": 24895, "text": "Naive Approach: The simplest approach to solve the problem is to generate all possible pairs from [1, N] and calculate GCD of each pair. Finally, print the maximum GCD obtained. Time Complexity: O(N2logN) Auxiliary Space: O(1) " }, { "code": null, "e": 25190, "s": 25123, "text": "Efficient Approach: Follow the steps below to solve the problem: " }, { "code": null, "e": 25298, "s": 25190, "text": "Since all the pairs are distinct, then, for any pair {a, b} with GCD g, either of a or b is greater than g." }, { "code": null, "e": 25402, "s": 25298, "text": "Considering b to be the greater number, b ? 2g, since 2g is the smallest multiple of g greater than it." }, { "code": null, "e": 25439, "s": 25402, "text": "Since b cannot exceed N, and 2g ? N." }, { "code": null, "e": 25466, "s": 25439, "text": "Therefore, g ? floor(n/2)." }, { "code": null, "e": 25578, "s": 25466, "text": "Therefore, the maximum GCD that can be obtained is floor(n/2), when pair chosen is (floor(n/2), 2*floor(n/2)). " }, { "code": null, "e": 25650, "s": 25578, "text": "Illustration: N = 6 Maximum GCD = 6/2 = 3, occurs for the pair (3, 6) " }, { "code": null, "e": 25702, "s": 25650, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 25706, "s": 25702, "text": "C++" }, { "code": null, "e": 25711, "s": 25706, "text": "Java" }, { "code": null, "e": 25719, "s": 25711, "text": "Python3" }, { "code": null, "e": 25722, "s": 25719, "text": "C#" }, { "code": null, "e": 25733, "s": 25722, "text": "Javascript" }, { "code": "// C++ Program to implement// the approach#include <bits/stdc++.h>using namespace std; // Function to obtain the maximum// gcd of all pairs from 1 to nvoid find(int n){ // Print the answer cout << n / 2 << endl;} // Driver codeint main(){ int n = 5; // Function call find(n); return 0;}", "e": 26038, "s": 25733, "text": null }, { "code": "// Java Program to implement// the approachclass GFG{ // Function to obtain the maximum// gcd of all pairs from 1 to nstatic void find(int n){ // Print the answer System.out.println(n / 2);} // Driver codepublic static void main(String[] args){ int n = 5; // Function call find(n);}} // This code is contributed by Ritik Bansal", "e": 26384, "s": 26038, "text": null }, { "code": "# Python3 program to implement# the approach # Function to obtain the maximum# gcd of all pairs from 1 to ndef find(n): # Print the answer print(n // 2) # Driver Codeif __name__ == '__main__': # Given n n = 5 # Function call find(n) # This code is contributed by Shivam Singh", "e": 26681, "s": 26384, "text": null }, { "code": "// C# Program to implement// the approachusing System;class GFG{ // Function to obtain the maximum// gcd of all pairs from 1 to nstatic void find(int n){ // Print the answer Console.Write(n / 2);} // Driver codepublic static void Main(string[] args){ int n = 5; // Function call find(n);}} // This code is contributed by rock_cool", "e": 27033, "s": 26681, "text": null }, { "code": "<script> // Javascript program to implement// the approach // Function to obtain the maximum// gcd of all pairs from 1 to nfunction find(n){ // Print the answer document.write(parseInt(n / 2, 10) + \"</br>\");} // Driver codelet n = 5; // Function callfind(n); // This code is contributed by divyeshrabadiya07 </script>", "e": 27362, "s": 27033, "text": null }, { "code": null, "e": 27364, "s": 27362, "text": "2" }, { "code": null, "e": 27411, "s": 27366, "text": "Time Complexity: O(1) Auxiliary Space: O(1) " }, { "code": null, "e": 27423, "s": 27411, "text": "bansal_rtk_" }, { "code": null, "e": 27433, "s": 27423, "text": "rock_cool" }, { "code": null, "e": 27451, "s": 27433, "text": "divyeshrabadiya07" }, { "code": null, "e": 27459, "s": 27451, "text": "GCD-LCM" }, { "code": null, "e": 27466, "s": 27459, "text": "Greedy" }, { "code": null, "e": 27479, "s": 27466, "text": "Mathematical" }, { "code": null, "e": 27486, "s": 27479, "text": "Greedy" }, { "code": null, "e": 27499, "s": 27486, "text": "Mathematical" }, { "code": null, "e": 27597, "s": 27499, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27606, "s": 27597, "text": "Comments" }, { "code": null, "e": 27619, "s": 27606, "text": "Old Comments" }, { "code": null, "e": 27662, "s": 27619, "text": "Activity Selection Problem | Greedy Algo-1" }, { "code": null, "e": 27690, "s": 27662, "text": "Fractional Knapsack Problem" }, { "code": null, "e": 27771, "s": 27690, "text": "Program for Shortest Job First (or SJF) CPU Scheduling | Set 1 (Non- preemptive)" }, { "code": null, "e": 27794, "s": 27771, "text": "Job Sequencing Problem" }, { "code": null, "e": 27865, "s": 27794, "text": "Dijkstra’s Algorithm for Adjacency List Representation | Greedy Algo-8" }, { "code": null, "e": 27895, "s": 27865, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 27910, "s": 27895, "text": "C++ Data Types" }, { "code": null, "e": 27953, "s": 27910, "text": "Set in C++ Standard Template Library (STL)" } ]
A Simple Way of Automating and Scheduling SQL Server Database Replication between Different Servers | by Christopher Tao | Towards Data Science
Microsoft SQL Server provides SQL Server Replication features that we can utilise to set a database as Publisher and another one is Subscriber, so we can replicate the database with customisations in the scripts. However, sometimes the requirements may not be that complex so that SQL Server Replication could be a little overkill. For example, recently one of my clients want to start a POC project to build a data warehouse. They have concerns regarding the production databases that they are relying on to keep the business running. So, before we can extract the data from the databases to build the data warehouse, we need to replicate the databases so that all the development works will be conducted on these replicas. In this case, it is not necessary to include any customisations in the replicating processes, which is just simply mirroring the database. In this article, I’ll introduce a very easy way of automatically replicating SQL Server Databases between different servers. Let’s firstly create two SQL Servers for this experiment. It is highly recommended to use Azure, or otherwise, you’ll need to prepare two different machines, get proper SQL Server licenses and install the SQL Server software which could take an entire day. If you are new to Azure, you’ll get $200 credits (in one month) when you register Azure as a new user. Go to your Azure subscription, create a resource group first, which will be the container of the SQL Servers. Then, go to the marketplace and search “sql server”, choose the SQL Server 2017 on Windows Server 2016 as shown in the screenshot. In the dropdown manual, choose the Standard Edition to have all the standard features. Then, click “Start with a pre-set configuration” to save time. Here we can choose Dev/Test environment and D-Series VM (both smallest) to save costs, especially if you have already spent all the free credits. Then, click “Create VM” Make sure you selected the resource group that you created for this. Then, click next. Fill in administrator credentials. The disk is not important for this experiment, so we can skip. However, the virtual network is very important. Make sure you create a new virtual network and subnet, and more importantly, the other SQL Server that will be created later on must be in the same virtual network and subnet, if you don’t want to create some accessibility issues for this experiment. Also, open the RDP port 3389 for later on convenience. Do not change the default port number and create an SQL Authentication. After that, we have done the configurations. Click create button to create the resources in Azure. While waiting for the resource being deployed, we can create the other SQL Server. I’ll call it SQL-Server-Test. After the first SQL Server has been deployed, go to the resource group and find the Windows VM for SQL-Server-Prod. Because we have opened the RDP port for the machine, so we can remote control this VM using its public IP address. Please also record the private IP address, which will be used later for the testing machine to connect to this product machine Let’s install a sample database from Microsoft. On the production machine, download the database backup: https://github.com/Microsoft/sql-server-samples/releases/download/adventureworks/AdventureWorks2017.bak In SSMS, login to the DB instance using the default Windows admin account. Right-click “Databases” and select “Restore Database”. In the popup window, click the browse button on the right of “Device” radio button -> Add -> Browse the bak file that you’ve just downloaded -> OK -> OK -> OK. It may take about 1 minute to restore the whole database. Next, we need to create a folder that the backup files will be put into. Also, we need to share this folder in the network so that the Test machine can access the backup file and restore it. I created the directory C:\backup\. Then, share the fold to the same admin account at the other machine. Note that it is important to add MSSQLSERVER user to the sharing. Otherwise, SQL Server might not be able to write backup files into this folder after the sharing. Just simply type the MSSQLSERVER username and click Add button, then make sure to grant Read/Write permission to it. On the Test machine, we will be able to access the backup directory now. Since the SQL Server Agent is disabled by default, we need to remote control the Prod machine again to enable it. Right-click on SQL-Server-Agent -> Start. Then, in the pop-up confirmation window click Yes. Wait until SQL Server Agent is started, go back to the testing machine. You will need to reconnect the production SQL Server to see the SQL Agent enabled. Right-click Jobs -> New Job.... In the New Job window, input a name and go to Steps tab. In Steps tab, click New button. In the New Job Step window, input step name and the script as follows: USE AdventureWorks2017GODECLARE @filename varchar(255)DECLARE @date datetimeSELECT @date=getdate()SELECT @filename='C:\backup\AdventureWorks2017-' + CAST(DATEPART(yyyy, @date) as varchar) + '-' + CAST(DATEPART(mm, @date) as varchar) + '-' + CAST(DATEPART(dd, @date) as varchar) + '.bak'BACKUP DATABASE AdventureWorks2017 TO DISK=@filename WITH INITGO After that, go to theAdvanced tab, configure the success and failure behaviours. Here, you need to consider your situations, such as how large your database is and etc. Click OK to confirm apply the Job Step, then go to Schedule tab and click New button. You may configure the schedule based on your requirements. In this example, I’ll let the backup happens every day at 1:00 AM. Then, click the OK button to confirm the schedule. You may also want to create alerts or notifications such as sending emails when the job fails. In this experiment, we’ll skip this step because it is not always needed. Now, rather than wait until tomorrow at 1 AM, I would like to test the job. We can right-click the job we created and select “Start Job at Step...” to test the job. Since we only have 1 step in this job, it will directly start and run the backup step. After a while, the job is success and you can also find the backup file at the backup directory. First of all, let’s check the accessibility of the backup file from the test machine by access \\SQL-Server-Prod\backup\<backup-file>. Another crucial step is to mount the remote backup folder to a local drive. This is because usually the SQL Server Windows Service is run as a service account which does not have permission to use network/remote resources, so the remote resource is not visible to it. Simply right-click on the backup folder and select “Map network drive...”. Let’s mount it to Z: drive on the test machine. Then, we need to let SQL Server identify the network drive using the xp_cmdshell command. By default, this command is not enabled, so we need to enable it. Open a new query sheet and run the following script to enable it. EXEC sp_configure 'show advanced options', 1;GORECONFIGURE;GOEXEC sp_configure 'xp_cmdshell',1GORECONFIGUREGO Then, define the network drive using xp_cmdshell. You can use any Windows user that can access this network drive. Note that you only need to run this command once, so the password will not be retained anywhere in plain format. EXEC XP_CMDSHELL 'net use Z: \\SQL-Server-Prod\backup <password> /USER:<username>' From the result panel, you should see the output saying it was successful. We can also test whether it works or not, by the following script. EXEC XP_CMDSHELL 'dir Z:' If it works, you should see the file list including the backup file. After that, we just need to create another SQL Server Agent Job with a step for restoring the database from the identified network drive. The script of the step is as follows: DECLARE @filename varchar(255)DECLARE @date datetimeSELECT @date=getdate()SELECT @filename='Z:\AdventureWorks2017-' + CAST(DATEPART(yyyy, @date) as varchar) + '-' + CAST(DATEPART(mm, @date) as varchar) + '-' + CAST(DATEPART(dd, @date) as varchar) + '.bak'RESTORE DATABASE AdventureWorks2017FROM DISK=@filenameWITH REPLACEGO Then, repeat what we have done before in the production machine, right-click the agent job and select “Start Job at Step” to test the job. Wait for a while until the restoring finished, right-click “Databases” to refresh the database list, you will see the restored database! medium.com If you feel my articles are helpful, please consider joining Medium Membership to support me and thousands of other writers! (Click the link above) Make Network Path Visible For SQL Server Backup and Restore in SSMS:https://www.mssqltips.com/sqlservertip/3499/make-network-path-visible-for-sql-server-backup-and-restore-in-ssms/ BACKUP Statements (Transact-SQL, Microsoft official Docs):https://docs.microsoft.com/en-us/sql/t-sql/statements/backup-transact-sql?view=sql-server-ver15 RESTORE Statements (Transact-SQL, Microsoft official Docs):https://docs.microsoft.com/en-us/sql/t-sql/statements/restore-statements-transact-sql?view=sql-server-ver15
[ { "code": null, "e": 378, "s": 46, "text": "Microsoft SQL Server provides SQL Server Replication features that we can utilise to set a database as Publisher and another one is Subscriber, so we can replicate the database with customisations in the scripts. However, sometimes the requirements may not be that complex so that SQL Server Replication could be a little overkill." }, { "code": null, "e": 771, "s": 378, "text": "For example, recently one of my clients want to start a POC project to build a data warehouse. They have concerns regarding the production databases that they are relying on to keep the business running. So, before we can extract the data from the databases to build the data warehouse, we need to replicate the databases so that all the development works will be conducted on these replicas." }, { "code": null, "e": 1035, "s": 771, "text": "In this case, it is not necessary to include any customisations in the replicating processes, which is just simply mirroring the database. In this article, I’ll introduce a very easy way of automatically replicating SQL Server Databases between different servers." }, { "code": null, "e": 1292, "s": 1035, "text": "Let’s firstly create two SQL Servers for this experiment. It is highly recommended to use Azure, or otherwise, you’ll need to prepare two different machines, get proper SQL Server licenses and install the SQL Server software which could take an entire day." }, { "code": null, "e": 1395, "s": 1292, "text": "If you are new to Azure, you’ll get $200 credits (in one month) when you register Azure as a new user." }, { "code": null, "e": 1636, "s": 1395, "text": "Go to your Azure subscription, create a resource group first, which will be the container of the SQL Servers. Then, go to the marketplace and search “sql server”, choose the SQL Server 2017 on Windows Server 2016 as shown in the screenshot." }, { "code": null, "e": 1786, "s": 1636, "text": "In the dropdown manual, choose the Standard Edition to have all the standard features. Then, click “Start with a pre-set configuration” to save time." }, { "code": null, "e": 1956, "s": 1786, "text": "Here we can choose Dev/Test environment and D-Series VM (both smallest) to save costs, especially if you have already spent all the free credits. Then, click “Create VM”" }, { "code": null, "e": 2043, "s": 1956, "text": "Make sure you selected the resource group that you created for this. Then, click next." }, { "code": null, "e": 2078, "s": 2043, "text": "Fill in administrator credentials." }, { "code": null, "e": 2495, "s": 2078, "text": "The disk is not important for this experiment, so we can skip. However, the virtual network is very important. Make sure you create a new virtual network and subnet, and more importantly, the other SQL Server that will be created later on must be in the same virtual network and subnet, if you don’t want to create some accessibility issues for this experiment. Also, open the RDP port 3389 for later on convenience." }, { "code": null, "e": 2666, "s": 2495, "text": "Do not change the default port number and create an SQL Authentication. After that, we have done the configurations. Click create button to create the resources in Azure." }, { "code": null, "e": 2779, "s": 2666, "text": "While waiting for the resource being deployed, we can create the other SQL Server. I’ll call it SQL-Server-Test." }, { "code": null, "e": 3010, "s": 2779, "text": "After the first SQL Server has been deployed, go to the resource group and find the Windows VM for SQL-Server-Prod. Because we have opened the RDP port for the machine, so we can remote control this VM using its public IP address." }, { "code": null, "e": 3137, "s": 3010, "text": "Please also record the private IP address, which will be used later for the testing machine to connect to this product machine" }, { "code": null, "e": 3346, "s": 3137, "text": "Let’s install a sample database from Microsoft. On the production machine, download the database backup: https://github.com/Microsoft/sql-server-samples/releases/download/adventureworks/AdventureWorks2017.bak" }, { "code": null, "e": 3421, "s": 3346, "text": "In SSMS, login to the DB instance using the default Windows admin account." }, { "code": null, "e": 3476, "s": 3421, "text": "Right-click “Databases” and select “Restore Database”." }, { "code": null, "e": 3694, "s": 3476, "text": "In the popup window, click the browse button on the right of “Device” radio button -> Add -> Browse the bak file that you’ve just downloaded -> OK -> OK -> OK. It may take about 1 minute to restore the whole database." }, { "code": null, "e": 3885, "s": 3694, "text": "Next, we need to create a folder that the backup files will be put into. Also, we need to share this folder in the network so that the Test machine can access the backup file and restore it." }, { "code": null, "e": 3990, "s": 3885, "text": "I created the directory C:\\backup\\. Then, share the fold to the same admin account at the other machine." }, { "code": null, "e": 4271, "s": 3990, "text": "Note that it is important to add MSSQLSERVER user to the sharing. Otherwise, SQL Server might not be able to write backup files into this folder after the sharing. Just simply type the MSSQLSERVER username and click Add button, then make sure to grant Read/Write permission to it." }, { "code": null, "e": 4344, "s": 4271, "text": "On the Test machine, we will be able to access the backup directory now." }, { "code": null, "e": 4551, "s": 4344, "text": "Since the SQL Server Agent is disabled by default, we need to remote control the Prod machine again to enable it. Right-click on SQL-Server-Agent -> Start. Then, in the pop-up confirmation window click Yes." }, { "code": null, "e": 4706, "s": 4551, "text": "Wait until SQL Server Agent is started, go back to the testing machine. You will need to reconnect the production SQL Server to see the SQL Agent enabled." }, { "code": null, "e": 4738, "s": 4706, "text": "Right-click Jobs -> New Job...." }, { "code": null, "e": 4795, "s": 4738, "text": "In the New Job window, input a name and go to Steps tab." }, { "code": null, "e": 4827, "s": 4795, "text": "In Steps tab, click New button." }, { "code": null, "e": 4898, "s": 4827, "text": "In the New Job Step window, input step name and the script as follows:" }, { "code": null, "e": 5250, "s": 4898, "text": "USE AdventureWorks2017GODECLARE @filename varchar(255)DECLARE @date datetimeSELECT @date=getdate()SELECT @filename='C:\\backup\\AdventureWorks2017-' + CAST(DATEPART(yyyy, @date) as varchar) + '-' + CAST(DATEPART(mm, @date) as varchar) + '-' + CAST(DATEPART(dd, @date) as varchar) + '.bak'BACKUP DATABASE AdventureWorks2017 TO DISK=@filename WITH INITGO" }, { "code": null, "e": 5419, "s": 5250, "text": "After that, go to theAdvanced tab, configure the success and failure behaviours. Here, you need to consider your situations, such as how large your database is and etc." }, { "code": null, "e": 5682, "s": 5419, "text": "Click OK to confirm apply the Job Step, then go to Schedule tab and click New button. You may configure the schedule based on your requirements. In this example, I’ll let the backup happens every day at 1:00 AM. Then, click the OK button to confirm the schedule." }, { "code": null, "e": 5851, "s": 5682, "text": "You may also want to create alerts or notifications such as sending emails when the job fails. In this experiment, we’ll skip this step because it is not always needed." }, { "code": null, "e": 6103, "s": 5851, "text": "Now, rather than wait until tomorrow at 1 AM, I would like to test the job. We can right-click the job we created and select “Start Job at Step...” to test the job. Since we only have 1 step in this job, it will directly start and run the backup step." }, { "code": null, "e": 6200, "s": 6103, "text": "After a while, the job is success and you can also find the backup file at the backup directory." }, { "code": null, "e": 6335, "s": 6200, "text": "First of all, let’s check the accessibility of the backup file from the test machine by access \\\\SQL-Server-Prod\\backup\\<backup-file>." }, { "code": null, "e": 6603, "s": 6335, "text": "Another crucial step is to mount the remote backup folder to a local drive. This is because usually the SQL Server Windows Service is run as a service account which does not have permission to use network/remote resources, so the remote resource is not visible to it." }, { "code": null, "e": 6678, "s": 6603, "text": "Simply right-click on the backup folder and select “Map network drive...”." }, { "code": null, "e": 6726, "s": 6678, "text": "Let’s mount it to Z: drive on the test machine." }, { "code": null, "e": 6948, "s": 6726, "text": "Then, we need to let SQL Server identify the network drive using the xp_cmdshell command. By default, this command is not enabled, so we need to enable it. Open a new query sheet and run the following script to enable it." }, { "code": null, "e": 7058, "s": 6948, "text": "EXEC sp_configure 'show advanced options', 1;GORECONFIGURE;GOEXEC sp_configure 'xp_cmdshell',1GORECONFIGUREGO" }, { "code": null, "e": 7286, "s": 7058, "text": "Then, define the network drive using xp_cmdshell. You can use any Windows user that can access this network drive. Note that you only need to run this command once, so the password will not be retained anywhere in plain format." }, { "code": null, "e": 7369, "s": 7286, "text": "EXEC XP_CMDSHELL 'net use Z: \\\\SQL-Server-Prod\\backup <password> /USER:<username>'" }, { "code": null, "e": 7444, "s": 7369, "text": "From the result panel, you should see the output saying it was successful." }, { "code": null, "e": 7511, "s": 7444, "text": "We can also test whether it works or not, by the following script." }, { "code": null, "e": 7537, "s": 7511, "text": "EXEC XP_CMDSHELL 'dir Z:'" }, { "code": null, "e": 7606, "s": 7537, "text": "If it works, you should see the file list including the backup file." }, { "code": null, "e": 7782, "s": 7606, "text": "After that, we just need to create another SQL Server Agent Job with a step for restoring the database from the identified network drive. The script of the step is as follows:" }, { "code": null, "e": 8107, "s": 7782, "text": "DECLARE @filename varchar(255)DECLARE @date datetimeSELECT @date=getdate()SELECT @filename='Z:\\AdventureWorks2017-' + CAST(DATEPART(yyyy, @date) as varchar) + '-' + CAST(DATEPART(mm, @date) as varchar) + '-' + CAST(DATEPART(dd, @date) as varchar) + '.bak'RESTORE DATABASE AdventureWorks2017FROM DISK=@filenameWITH REPLACEGO" }, { "code": null, "e": 8383, "s": 8107, "text": "Then, repeat what we have done before in the production machine, right-click the agent job and select “Start Job at Step” to test the job. Wait for a while until the restoring finished, right-click “Databases” to refresh the database list, you will see the restored database!" }, { "code": null, "e": 8394, "s": 8383, "text": "medium.com" }, { "code": null, "e": 8542, "s": 8394, "text": "If you feel my articles are helpful, please consider joining Medium Membership to support me and thousands of other writers! (Click the link above)" }, { "code": null, "e": 8723, "s": 8542, "text": "Make Network Path Visible For SQL Server Backup and Restore in SSMS:https://www.mssqltips.com/sqlservertip/3499/make-network-path-visible-for-sql-server-backup-and-restore-in-ssms/" }, { "code": null, "e": 8877, "s": 8723, "text": "BACKUP Statements (Transact-SQL, Microsoft official Docs):https://docs.microsoft.com/en-us/sql/t-sql/statements/backup-transact-sql?view=sql-server-ver15" } ]
Count of substrings of a binary string containing K ones - GeeksforGeeks
13 Sep, 2021 Given a binary string of length N and an integer K, we need to find out how many substrings of this string are exist which contains exactly K ones. Examples: Input : s = “10010” K = 1 Output : 9 The 9 substrings containing one 1 are, “1”, “10”, “100”, “001”, “01”, “1”, “10”, “0010” and “010” In this problem we need to find count of substrings which contains exactly K ones or in other words sum of digits in those substring is K. We first create a prefix sum array and loop over that and stop when sum value is greater than or equal to K. Now if sum at current index is (K + a) then we know that substring sum, from all those indices where sum is (a), till current index will be K, so count of indices having sum (a), will be added to result. This procedure is explained with an example below, string s = “100101” K = 2 prefix sum array = [1, 1, 1, 2, 2, 3] So, at index 3, we have prefix sum 2, Now total indices from where sum is 2, is 1 so result = 1 Substring considered = [“1001”] At index 4, we have prefix sum 2, Now total indices from where sum is 2, is 1 so result = 2 Substring considered = [“1001”, “10010”] At index 5, we have prefix sum 3, Now total indices from where sum is 2, is 3 so result = 5 Substring considered = [“1001”, “10010”, “00101”, “0101”, “101”] So we need to track two things, prefix sum and frequency of particular sum. In below code, instead of storing complete prefix sum, only prefix sum at current index is stored using one variable and frequency of sums in stored in an array. Total time complexity of solution is O(N). C++ Java Python3 C# PHP Javascript // C++ program to find count of substring containing// exactly K ones#include <bits/stdc++.h>using namespace std; // method returns total number of substring having K onesint countOfSubstringWithKOnes(string s, int K){ int N = s.length(); int res = 0; int countOfOne = 0; int freq[N + 1] = {0}; // initialize index having zero sum as 1 freq[0] = 1; // loop over binary characters of string for (int i = 0; i < N; i++) { // update countOfOne variable with value // of ith character countOfOne += (s[i] - '0'); // if value reaches more than K, then // update result if (countOfOne >= K) { // add frequency of indices, having // sum (current sum - K), to the result res += freq[countOfOne - K]; } // update frequency of one's count freq[countOfOne]++; } return res;} // Driver code to test above methodsint main(){ string s = "10010"; int K = 1; cout << countOfSubstringWithKOnes(s, K) << endl; return 0;} // Java program to find count of substring// containing exactly K onesimport java.io.*; public class GFG { // method returns total number of // substring having K ones static int countOfSubstringWithKOnes( String s, int K) { int N = s.length(); int res = 0; int countOfOne = 0; int []freq = new int[N+1]; // initialize index having zero // sum as 1 freq[0] = 1; // loop over binary characters // of string for (int i = 0; i < N; i++) { // update countOfOne variable // with value of ith character countOfOne += (s.charAt(i) - '0'); // if value reaches more than // K, then update result if (countOfOne >= K) { // add frequency of indices, // having sum (current sum - K), // to the result res += freq[countOfOne - K]; } // update frequency of one's count freq[countOfOne]++; } return res; } // Driver code to test above methods static public void main (String[] args) { String s = "10010"; int K = 1; System.out.println( countOfSubstringWithKOnes(s, K)); }} // This code is contributed by vt_m. # Python 3 program to find count of# substring containing exactly K ones # method returns total number of# substring having K onesdef countOfSubstringWithKOnes(s, K): N = len(s) res = 0 countOfOne = 0 freq = [0 for i in range(N + 1)] # initialize index having # zero sum as 1 freq[0] = 1 # loop over binary characters of string for i in range(0, N, 1): # update countOfOne variable with # value of ith character countOfOne += ord(s[i]) - ord('0') # if value reaches more than K, # then update result if (countOfOne >= K): # add frequency of indices, having # sum (current sum - K), to the result res += freq[countOfOne - K] # update frequency of one's count freq[countOfOne] += 1 return res # Driver codeif __name__ == '__main__': s = "10010" K = 1 print(countOfSubstringWithKOnes(s, K)) # This code is contributed by# Surendra_Gangwar // C# program to find count of substring// containing exactly K onesusing System; public class GFG { // method returns total number of // substring having K ones static int countOfSubstringWithKOnes( string s, int K) { int N = s.Length; int res = 0; int countOfOne = 0; int []freq = new int[N+1]; // initialize index having zero // sum as 1 freq[0] = 1; // loop over binary characters // of string for (int i = 0; i < N; i++) { // update countOfOne variable // with value of ith character countOfOne += (s[i] - '0'); // if value reaches more than // K, then update result if (countOfOne >= K) { // add frequency of indices, // having sum (current sum - K), // to the result res += freq[countOfOne - K]; } // update frequency of one's count freq[countOfOne]++; } return res; } // Driver code to test above methods static public void Main () { string s = "10010"; int K = 1; Console.WriteLine( countOfSubstringWithKOnes(s, K)); }} // This code is contributed by vt_m. <?php// PHP program to find count// of substring containing// exactly K ones // method returns total number// of substring having K onesfunction countOfSubstringWithKOnes($s, $K){ $N = strlen($s); $res = 0; $countOfOne = 0; $freq = array(); for ($i = 0; $i <= $N; $i++) $freq[$i] = 0; // initialize index // having zero sum as 1 $freq[0] = 1; // loop over binary // characters of string for ($i = 0; $i < $N; $i++) { // update countOfOne // variable with value // of ith character $countOfOne += ($s[$i] - '0'); // if value reaches more // than K, then update result if ($countOfOne >= $K) { // add frequency of indices, // having sum (current sum - K), // to the result $res = $res + $freq[$countOfOne - $K]; } // update frequency // of one's count $freq[$countOfOne]++; } return $res;} // Driver code$s = "10010";$K = 1;echo countOfSubstringWithKOnes($s, $K) ,"\n"; // This code is contributed by m_kit?> <script> // Javascript program to find count of// substring containing exactly K ones // Method returns total number of// substring having K onesfunction countOfSubstringWithKOnes(s, K){ let N = s.length; let res = 0; let countOfOne = 0; let freq = new Array(N + 1); freq.fill(0); // Initialize index having zero // sum as 1 freq[0] = 1; // Loop over binary characters // of string for(let i = 0; i < N; i++) { // Update countOfOne variable // with value of ith character countOfOne += (s[i] - '0'); // If value reaches more than // K, then update result if (countOfOne >= K) { // Add frequency of indices, // having sum (current sum - K), // to the result res += freq[countOfOne - K]; } // Update frequency of one's count freq[countOfOne]++; } return res;} // Driver codelet s = "10010";let K = 1; document.write(countOfSubstringWithKOnes(s, K)); // This code is contributed by suresh07 </script> Output: 9 This article is contributed by Utkarsh Trivedi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. vt_m jit_t SURENDRA_GANGWAR suresh07 nnr223442 binary-string prefix-sum Hash Strings prefix-sum Hash Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Most frequent element in an array Counting frequencies of array elements Sorting a Map by value in C++ STL Double Hashing C++ program for hashing with chaining 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": 25306, "s": 25278, "text": "\n13 Sep, 2021" }, { "code": null, "e": 25454, "s": 25306, "text": "Given a binary string of length N and an integer K, we need to find out how many substrings of this string are exist which contains exactly K ones." }, { "code": null, "e": 25465, "s": 25454, "text": "Examples: " }, { "code": null, "e": 25609, "s": 25465, "text": "Input : s = “10010”\n K = 1\nOutput : 9\nThe 9 substrings containing one 1 are,\n“1”, “10”, “100”, “001”, “01”, “1”, \n“10”, “0010” and “010”" }, { "code": null, "e": 26113, "s": 25609, "text": "In this problem we need to find count of substrings which contains exactly K ones or in other words sum of digits in those substring is K. We first create a prefix sum array and loop over that and stop when sum value is greater than or equal to K. Now if sum at current index is (K + a) then we know that substring sum, from all those indices where sum is (a), till current index will be K, so count of indices having sum (a), will be added to result. This procedure is explained with an example below, " }, { "code": null, "e": 26616, "s": 26113, "text": "string s = “100101”\nK = 2\nprefix sum array = [1, 1, 1, 2, 2, 3]\n\nSo, at index 3, we have prefix sum 2, \nNow total indices from where sum is 2, is 1\nso result = 1\n\nSubstring considered = [“1001”]\nAt index 4, we have prefix sum 2,\nNow total indices from where sum is 2, is \n1 so result = 2\n\nSubstring considered = [“1001”, “10010”]\nAt index 5, we have prefix sum 3,\nNow total indices from where sum is 2, \nis 3 so result = 5\nSubstring considered = [“1001”, “10010”, \n“00101”, “0101”, “101”]" }, { "code": null, "e": 26899, "s": 26616, "text": "So we need to track two things, prefix sum and frequency of particular sum. In below code, instead of storing complete prefix sum, only prefix sum at current index is stored using one variable and frequency of sums in stored in an array. Total time complexity of solution is O(N). " }, { "code": null, "e": 26903, "s": 26899, "text": "C++" }, { "code": null, "e": 26908, "s": 26903, "text": "Java" }, { "code": null, "e": 26916, "s": 26908, "text": "Python3" }, { "code": null, "e": 26919, "s": 26916, "text": "C#" }, { "code": null, "e": 26923, "s": 26919, "text": "PHP" }, { "code": null, "e": 26934, "s": 26923, "text": "Javascript" }, { "code": "// C++ program to find count of substring containing// exactly K ones#include <bits/stdc++.h>using namespace std; // method returns total number of substring having K onesint countOfSubstringWithKOnes(string s, int K){ int N = s.length(); int res = 0; int countOfOne = 0; int freq[N + 1] = {0}; // initialize index having zero sum as 1 freq[0] = 1; // loop over binary characters of string for (int i = 0; i < N; i++) { // update countOfOne variable with value // of ith character countOfOne += (s[i] - '0'); // if value reaches more than K, then // update result if (countOfOne >= K) { // add frequency of indices, having // sum (current sum - K), to the result res += freq[countOfOne - K]; } // update frequency of one's count freq[countOfOne]++; } return res;} // Driver code to test above methodsint main(){ string s = \"10010\"; int K = 1; cout << countOfSubstringWithKOnes(s, K) << endl; return 0;}", "e": 27981, "s": 26934, "text": null }, { "code": "// Java program to find count of substring// containing exactly K onesimport java.io.*; public class GFG { // method returns total number of // substring having K ones static int countOfSubstringWithKOnes( String s, int K) { int N = s.length(); int res = 0; int countOfOne = 0; int []freq = new int[N+1]; // initialize index having zero // sum as 1 freq[0] = 1; // loop over binary characters // of string for (int i = 0; i < N; i++) { // update countOfOne variable // with value of ith character countOfOne += (s.charAt(i) - '0'); // if value reaches more than // K, then update result if (countOfOne >= K) { // add frequency of indices, // having sum (current sum - K), // to the result res += freq[countOfOne - K]; } // update frequency of one's count freq[countOfOne]++; } return res; } // Driver code to test above methods static public void main (String[] args) { String s = \"10010\"; int K = 1; System.out.println( countOfSubstringWithKOnes(s, K)); }} // This code is contributed by vt_m.", "e": 29359, "s": 27981, "text": null }, { "code": "# Python 3 program to find count of# substring containing exactly K ones # method returns total number of# substring having K onesdef countOfSubstringWithKOnes(s, K): N = len(s) res = 0 countOfOne = 0 freq = [0 for i in range(N + 1)] # initialize index having # zero sum as 1 freq[0] = 1 # loop over binary characters of string for i in range(0, N, 1): # update countOfOne variable with # value of ith character countOfOne += ord(s[i]) - ord('0') # if value reaches more than K, # then update result if (countOfOne >= K): # add frequency of indices, having # sum (current sum - K), to the result res += freq[countOfOne - K] # update frequency of one's count freq[countOfOne] += 1 return res # Driver codeif __name__ == '__main__': s = \"10010\" K = 1 print(countOfSubstringWithKOnes(s, K)) # This code is contributed by# Surendra_Gangwar", "e": 30362, "s": 29359, "text": null }, { "code": "// C# program to find count of substring// containing exactly K onesusing System; public class GFG { // method returns total number of // substring having K ones static int countOfSubstringWithKOnes( string s, int K) { int N = s.Length; int res = 0; int countOfOne = 0; int []freq = new int[N+1]; // initialize index having zero // sum as 1 freq[0] = 1; // loop over binary characters // of string for (int i = 0; i < N; i++) { // update countOfOne variable // with value of ith character countOfOne += (s[i] - '0'); // if value reaches more than // K, then update result if (countOfOne >= K) { // add frequency of indices, // having sum (current sum - K), // to the result res += freq[countOfOne - K]; } // update frequency of one's count freq[countOfOne]++; } return res; } // Driver code to test above methods static public void Main () { string s = \"10010\"; int K = 1; Console.WriteLine( countOfSubstringWithKOnes(s, K)); }} // This code is contributed by vt_m.", "e": 31710, "s": 30362, "text": null }, { "code": "<?php// PHP program to find count// of substring containing// exactly K ones // method returns total number// of substring having K onesfunction countOfSubstringWithKOnes($s, $K){ $N = strlen($s); $res = 0; $countOfOne = 0; $freq = array(); for ($i = 0; $i <= $N; $i++) $freq[$i] = 0; // initialize index // having zero sum as 1 $freq[0] = 1; // loop over binary // characters of string for ($i = 0; $i < $N; $i++) { // update countOfOne // variable with value // of ith character $countOfOne += ($s[$i] - '0'); // if value reaches more // than K, then update result if ($countOfOne >= $K) { // add frequency of indices, // having sum (current sum - K), // to the result $res = $res + $freq[$countOfOne - $K]; } // update frequency // of one's count $freq[$countOfOne]++; } return $res;} // Driver code$s = \"10010\";$K = 1;echo countOfSubstringWithKOnes($s, $K) ,\"\\n\"; // This code is contributed by m_kit?>", "e": 32805, "s": 31710, "text": null }, { "code": "<script> // Javascript program to find count of// substring containing exactly K ones // Method returns total number of// substring having K onesfunction countOfSubstringWithKOnes(s, K){ let N = s.length; let res = 0; let countOfOne = 0; let freq = new Array(N + 1); freq.fill(0); // Initialize index having zero // sum as 1 freq[0] = 1; // Loop over binary characters // of string for(let i = 0; i < N; i++) { // Update countOfOne variable // with value of ith character countOfOne += (s[i] - '0'); // If value reaches more than // K, then update result if (countOfOne >= K) { // Add frequency of indices, // having sum (current sum - K), // to the result res += freq[countOfOne - K]; } // Update frequency of one's count freq[countOfOne]++; } return res;} // Driver codelet s = \"10010\";let K = 1; document.write(countOfSubstringWithKOnes(s, K)); // This code is contributed by suresh07 </script>", "e": 33896, "s": 32805, "text": null }, { "code": null, "e": 33905, "s": 33896, "text": "Output: " }, { "code": null, "e": 33907, "s": 33905, "text": "9" }, { "code": null, "e": 34331, "s": 33907, "text": "This article is contributed by Utkarsh Trivedi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 34336, "s": 34331, "text": "vt_m" }, { "code": null, "e": 34342, "s": 34336, "text": "jit_t" }, { "code": null, "e": 34359, "s": 34342, "text": "SURENDRA_GANGWAR" }, { "code": null, "e": 34368, "s": 34359, "text": "suresh07" }, { "code": null, "e": 34378, "s": 34368, "text": "nnr223442" }, { "code": null, "e": 34392, "s": 34378, "text": "binary-string" }, { "code": null, "e": 34403, "s": 34392, "text": "prefix-sum" }, { "code": null, "e": 34408, "s": 34403, "text": "Hash" }, { "code": null, "e": 34416, "s": 34408, "text": "Strings" }, { "code": null, "e": 34427, "s": 34416, "text": "prefix-sum" }, { "code": null, "e": 34432, "s": 34427, "text": "Hash" }, { "code": null, "e": 34440, "s": 34432, "text": "Strings" }, { "code": null, "e": 34538, "s": 34440, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34572, "s": 34538, "text": "Most frequent element in an array" }, { "code": null, "e": 34611, "s": 34572, "text": "Counting frequencies of array elements" }, { "code": null, "e": 34645, "s": 34611, "text": "Sorting a Map by value in C++ STL" }, { "code": null, "e": 34660, "s": 34645, "text": "Double Hashing" }, { "code": null, "e": 34698, "s": 34660, "text": "C++ program for hashing with chaining" }, { "code": null, "e": 34744, "s": 34698, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 34769, "s": 34744, "text": "Reverse a string in Java" }, { "code": null, "e": 34829, "s": 34769, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 34844, "s": 34829, "text": "C++ Data Types" } ]
Recursive program to insert a star between pair of identical characters - GeeksforGeeks
27 May, 2021 Given a string with repeated characters, we have to insert a star i.e.” * “ between pair of adjacent identical characters using recursion. Examples: Input : aabb Output : a*ab*b Input : xxxy Output : x*x*xy Approach: If there is an empty string then simply return. This forms our base condition. Check if the first two characters are identical. If yes, then insert ” * ” between them. As we have now checked for identical characters at the first two positions of the string so we now make a recursive call without the first character of the string. The above approach has been implemented below: C++ Java Python3 C# PHP Javascript // Recursive CPP program to insert * between// two consecutive same characters.#include <iostream>using namespace std; // Function to insert * at desired positionvoid pairStar(string& input, string& output, int i = 0){ // Append current character output = output + input[i]; // If we reached last character if (i == input.length() - 1) return; // If next character is same, // append '*' if (input[i] == input[i + 1]) output = output + '*'; pairStar(input, output, i+1);} // Driver codeint main(){ string input = "geeks", output = ""; pairStar(input, output); cout << output << endl; return 0;} // Recursive Java program to insert * between// two consecutive same characters.class GFG{ static String output=""; // Function to insert * at desired positionstatic void pairStar(String input, int i){ // Append current character output = output + input.charAt(i); // If we reached last character if (i == input.length() - 1) return; // If next character is same, // append '*' if (input.charAt(i) == input.charAt(i+1)) output = output + '*'; pairStar(input, i+1);} // Driver codepublic static void main(String[] args){ String input = "geeks"; pairStar(input,0); System.out.println(output);}} // This code is contributed by Princi Singh # Recursive CPP program to insert * between# two consecutive same characters. # Function to insert * at desired positiondef pairStar(Input, Output, i = 0) : # Append current character Output = Output + Input[i] # If we reached last character if (i == len(Input) - 1) : print(Output) return; # If next character is same, # append '*' if (Input[i] == Input[i + 1]) : Output = Output + '*'; pairStar(Input, Output, i + 1); # Driver codeif __name__ == "__main__" : Input = "geeks" Output = "" pairStar(Input, Output); # This code is contributed by Ryuga // Recursive C# program to insert * between// two consecutive same characters.using System; class GFG{ static String output=""; // Function to insert * at desired positionstatic void pairStar(String input, int i){ // Append current character output = output + input[i]; // If we reached last character if (i == input.Length - 1) return; // If next character is same, // append '*' if (input[i] == input[i+1]) output = output + '*'; pairStar(input, i+1);} // Driver codepublic static void Main(String[] args){ String input = "geeks"; pairStar(input,0); Console.WriteLine(output);}} /* This code is contributed by PrinciRaj1992 */ <?php // Recursive PHP program to insert * between// two consecutive same characters. // Function to insert * at desired positionfunction pairStar(&$input, &$output, $i = 0){ // Append current character $output = $output . $input[$i]; // If we reached last character if ($i == strlen($input) - 1) return; // If next character is same, // append '*' if ($input[$i] == $input[$i + 1]) $output = $output . '*'; pairStar($input, $output, $i+1);} // Driver code $input = "geeks"; $output = ""; pairStar($input, $output); echo $output; return 0; // This code is contributed by ChitraNayal?> <script>// Recursive Javascript program to insert * between// two consecutive same characters. let output=""; // Function to insert * at desired positionfunction pairStar(input,i){ // Append current character output = output + input[i]; // If we reached last character if (i == input.length - 1) return; // If next character is same, // append '*' if (input[i] == input[i+1]) output = output + '*'; pairStar(input, i+1);} // Driver codelet input = "geeks";pairStar(input,0);document.write(output); // This code is contributed by avanitrachhadiya2155</script> ge*eks Note: The recursive function in the above code is tail recursive as the recursive call is the last thing executed by the function. ankthon ukasp princi singh princiraj1992 avanitrachhadiya2155 tail-recursion C++ Programs Recursion Strings Strings Recursion Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Passing a function as a parameter in C++ Program to implement Singly Linked List in C++ using class cout in C++ Pi(π) in C++ with Examples Const keyword in C++ Write a program to print all permutations of a given string Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) Recursion Program for Tower of Hanoi Program for Sum of the digits of a given number
[ { "code": null, "e": 24241, "s": 24213, "text": "\n27 May, 2021" }, { "code": null, "e": 24381, "s": 24241, "text": "Given a string with repeated characters, we have to insert a star i.e.” * “ between pair of adjacent identical characters using recursion. " }, { "code": null, "e": 24392, "s": 24381, "text": "Examples: " }, { "code": null, "e": 24453, "s": 24392, "text": "Input : aabb \nOutput : a*ab*b\n\nInput : xxxy\nOutput : x*x*xy " }, { "code": null, "e": 24464, "s": 24453, "text": "Approach: " }, { "code": null, "e": 24543, "s": 24464, "text": "If there is an empty string then simply return. This forms our base condition." }, { "code": null, "e": 24632, "s": 24543, "text": "Check if the first two characters are identical. If yes, then insert ” * ” between them." }, { "code": null, "e": 24796, "s": 24632, "text": "As we have now checked for identical characters at the first two positions of the string so we now make a recursive call without the first character of the string." }, { "code": null, "e": 24844, "s": 24796, "text": "The above approach has been implemented below: " }, { "code": null, "e": 24848, "s": 24844, "text": "C++" }, { "code": null, "e": 24853, "s": 24848, "text": "Java" }, { "code": null, "e": 24861, "s": 24853, "text": "Python3" }, { "code": null, "e": 24864, "s": 24861, "text": "C#" }, { "code": null, "e": 24868, "s": 24864, "text": "PHP" }, { "code": null, "e": 24879, "s": 24868, "text": "Javascript" }, { "code": "// Recursive CPP program to insert * between// two consecutive same characters.#include <iostream>using namespace std; // Function to insert * at desired positionvoid pairStar(string& input, string& output, int i = 0){ // Append current character output = output + input[i]; // If we reached last character if (i == input.length() - 1) return; // If next character is same, // append '*' if (input[i] == input[i + 1]) output = output + '*'; pairStar(input, output, i+1);} // Driver codeint main(){ string input = \"geeks\", output = \"\"; pairStar(input, output); cout << output << endl; return 0;}", "e": 25546, "s": 24879, "text": null }, { "code": "// Recursive Java program to insert * between// two consecutive same characters.class GFG{ static String output=\"\"; // Function to insert * at desired positionstatic void pairStar(String input, int i){ // Append current character output = output + input.charAt(i); // If we reached last character if (i == input.length() - 1) return; // If next character is same, // append '*' if (input.charAt(i) == input.charAt(i+1)) output = output + '*'; pairStar(input, i+1);} // Driver codepublic static void main(String[] args){ String input = \"geeks\"; pairStar(input,0); System.out.println(output);}} // This code is contributed by Princi Singh", "e": 26248, "s": 25546, "text": null }, { "code": "# Recursive CPP program to insert * between# two consecutive same characters. # Function to insert * at desired positiondef pairStar(Input, Output, i = 0) : # Append current character Output = Output + Input[i] # If we reached last character if (i == len(Input) - 1) : print(Output) return; # If next character is same, # append '*' if (Input[i] == Input[i + 1]) : Output = Output + '*'; pairStar(Input, Output, i + 1); # Driver codeif __name__ == \"__main__\" : Input = \"geeks\" Output = \"\" pairStar(Input, Output); # This code is contributed by Ryuga", "e": 26865, "s": 26248, "text": null }, { "code": "// Recursive C# program to insert * between// two consecutive same characters.using System; class GFG{ static String output=\"\"; // Function to insert * at desired positionstatic void pairStar(String input, int i){ // Append current character output = output + input[i]; // If we reached last character if (i == input.Length - 1) return; // If next character is same, // append '*' if (input[i] == input[i+1]) output = output + '*'; pairStar(input, i+1);} // Driver codepublic static void Main(String[] args){ String input = \"geeks\"; pairStar(input,0); Console.WriteLine(output);}} /* This code is contributed by PrinciRaj1992 */", "e": 27563, "s": 26865, "text": null }, { "code": "<?php // Recursive PHP program to insert * between// two consecutive same characters. // Function to insert * at desired positionfunction pairStar(&$input, &$output, $i = 0){ // Append current character $output = $output . $input[$i]; // If we reached last character if ($i == strlen($input) - 1) return; // If next character is same, // append '*' if ($input[$i] == $input[$i + 1]) $output = $output . '*'; pairStar($input, $output, $i+1);} // Driver code $input = \"geeks\"; $output = \"\"; pairStar($input, $output); echo $output; return 0; // This code is contributed by ChitraNayal?>", "e": 28216, "s": 27563, "text": null }, { "code": "<script>// Recursive Javascript program to insert * between// two consecutive same characters. let output=\"\"; // Function to insert * at desired positionfunction pairStar(input,i){ // Append current character output = output + input[i]; // If we reached last character if (i == input.length - 1) return; // If next character is same, // append '*' if (input[i] == input[i+1]) output = output + '*'; pairStar(input, i+1);} // Driver codelet input = \"geeks\";pairStar(input,0);document.write(output); // This code is contributed by avanitrachhadiya2155</script>", "e": 28831, "s": 28216, "text": null }, { "code": null, "e": 28838, "s": 28831, "text": "ge*eks" }, { "code": null, "e": 28972, "s": 28840, "text": "Note: The recursive function in the above code is tail recursive as the recursive call is the last thing executed by the function. " }, { "code": null, "e": 28980, "s": 28972, "text": "ankthon" }, { "code": null, "e": 28986, "s": 28980, "text": "ukasp" }, { "code": null, "e": 28999, "s": 28986, "text": "princi singh" }, { "code": null, "e": 29013, "s": 28999, "text": "princiraj1992" }, { "code": null, "e": 29034, "s": 29013, "text": "avanitrachhadiya2155" }, { "code": null, "e": 29049, "s": 29034, "text": "tail-recursion" }, { "code": null, "e": 29062, "s": 29049, "text": "C++ Programs" }, { "code": null, "e": 29072, "s": 29062, "text": "Recursion" }, { "code": null, "e": 29080, "s": 29072, "text": "Strings" }, { "code": null, "e": 29088, "s": 29080, "text": "Strings" }, { "code": null, "e": 29098, "s": 29088, "text": "Recursion" }, { "code": null, "e": 29196, "s": 29098, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29205, "s": 29196, "text": "Comments" }, { "code": null, "e": 29218, "s": 29205, "text": "Old Comments" }, { "code": null, "e": 29259, "s": 29218, "text": "Passing a function as a parameter in C++" }, { "code": null, "e": 29318, "s": 29259, "text": "Program to implement Singly Linked List in C++ using class" }, { "code": null, "e": 29330, "s": 29318, "text": "cout in C++" }, { "code": null, "e": 29357, "s": 29330, "text": "Pi(π) in C++ with Examples" }, { "code": null, "e": 29378, "s": 29357, "text": "Const keyword in C++" }, { "code": null, "e": 29438, "s": 29378, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 29523, "s": 29438, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 29533, "s": 29523, "text": "Recursion" }, { "code": null, "e": 29560, "s": 29533, "text": "Program for Tower of Hanoi" } ]
Groovy - Maps get()
Look up the key in this Map and return the corresponding value. If there is no entry in this Map for the key, then return null. Object get(Object key) Key − Key to search for retrieval. The key-value pair or NULL if it does not exist. Following is an example of the usage of this method − class Example { static void main(String[] args) { def mp = ["TopicName" : "Maps", "TopicDescription" : "Methods in Maps"] println(mp.get("TopicName")); println(mp.get("Topic")); } } When we run the above program, we will get the following result − Maps Null 52 Lectures 8 hours Krishna Sakinala 49 Lectures 2.5 hours Packt Publishing Print Add Notes Bookmark this page
[ { "code": null, "e": 2366, "s": 2238, "text": "Look up the key in this Map and return the corresponding value. If there is no entry in this Map for the key, then return null." }, { "code": null, "e": 2390, "s": 2366, "text": "Object get(Object key)\n" }, { "code": null, "e": 2425, "s": 2390, "text": "Key − Key to search for retrieval." }, { "code": null, "e": 2474, "s": 2425, "text": "The key-value pair or NULL if it does not exist." }, { "code": null, "e": 2528, "s": 2474, "text": "Following is an example of the usage of this method −" }, { "code": null, "e": 2740, "s": 2528, "text": "class Example { \n static void main(String[] args) { \n def mp = [\"TopicName\" : \"Maps\", \"TopicDescription\" : \"Methods in Maps\"] \n println(mp.get(\"TopicName\")); \n println(mp.get(\"Topic\")); \n } \n}" }, { "code": null, "e": 2806, "s": 2740, "text": "When we run the above program, we will get the following result −" }, { "code": null, "e": 2818, "s": 2806, "text": "Maps \nNull\n" }, { "code": null, "e": 2851, "s": 2818, "text": "\n 52 Lectures \n 8 hours \n" }, { "code": null, "e": 2869, "s": 2851, "text": " Krishna Sakinala" }, { "code": null, "e": 2904, "s": 2869, "text": "\n 49 Lectures \n 2.5 hours \n" }, { "code": null, "e": 2922, "s": 2904, "text": " Packt Publishing" }, { "code": null, "e": 2929, "s": 2922, "text": " Print" }, { "code": null, "e": 2940, "s": 2929, "text": " Add Notes" } ]
How to align objects vertically when working with grids in CSS ? - GeeksforGeeks
07 Jan, 2020 CSS grid layout is one of the strongest layout of CSS. The grid layout is 2-D which means it can handle both rows and columns, unlike flexbox which is 1-D. To align objects apply CSS to the parent element which becomes the grid container and the element’s child which becomes the items in the grid. Approach:Use the align-content property of CSS grids to vertically align objects. Syntax: align-content: center; Example 1: <!DOCTYPE html><html> <head> <style> .gfg { display: grid; /* display is set to grid layout */ height: 400px; align-content: center; /* vertically aligns objects to the center */ grid-template-columns: auto auto auto; grid-gap: 10px; background-color: #4dd599; /* background colour is set */ padding: 10px; } .gfg > div { background-color: rgba(255, 255, 255, 0.8); text-align: center; /* text inside the container is set to center */ padding: 20px 0; font-size: 30px; } </style></head> <body> <div class="gfg"> <div>Welcome</div> <div>to</div> <div>Geeks</div> <div>for</div> <div>Geeks</div> <div>Start</div> </div> </body> </html> Output: Example 2: <!DOCTYPE html><html> <head> <style> .gfg { display: grid; /* display is set to grid layout */ height: 400px; align-content: center; /* vertically aligns objects to the center */ grid-template-columns: auto auto auto; grid-gap: 10px; background-color: #f67280; /* background colour is set */ padding: 10px; } .gfg > div { background-color: rgba(255, 255, 255, 0.8); text-align: center; /* text inside the container is set to center */ padding: 20px 0; font-size: 30px; } </style></head> <body> <div class="gfg"> <div>Explore</div> <div>the</div> <div>world</div> <div>travel</div> <div>and</div> <div>eat</div> </div> </body> </html> Output: CSS-Properties Picked CSS Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Design a web page using HTML and CSS Form validation using jQuery How to set space between the flexbox ? Search Bar using HTML, CSS and JavaScript How to Create Time-Table schedule using HTML ? 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": 25376, "s": 25348, "text": "\n07 Jan, 2020" }, { "code": null, "e": 25675, "s": 25376, "text": "CSS grid layout is one of the strongest layout of CSS. The grid layout is 2-D which means it can handle both rows and columns, unlike flexbox which is 1-D. To align objects apply CSS to the parent element which becomes the grid container and the element’s child which becomes the items in the grid." }, { "code": null, "e": 25757, "s": 25675, "text": "Approach:Use the align-content property of CSS grids to vertically align objects." }, { "code": null, "e": 25765, "s": 25757, "text": "Syntax:" }, { "code": null, "e": 25789, "s": 25765, "text": "align-content: center;\n" }, { "code": null, "e": 25800, "s": 25789, "text": "Example 1:" }, { "code": "<!DOCTYPE html><html> <head> <style> .gfg { display: grid; /* display is set to grid layout */ height: 400px; align-content: center; /* vertically aligns objects to the center */ grid-template-columns: auto auto auto; grid-gap: 10px; background-color: #4dd599; /* background colour is set */ padding: 10px; } .gfg > div { background-color: rgba(255, 255, 255, 0.8); text-align: center; /* text inside the container is set to center */ padding: 20px 0; font-size: 30px; } </style></head> <body> <div class=\"gfg\"> <div>Welcome</div> <div>to</div> <div>Geeks</div> <div>for</div> <div>Geeks</div> <div>Start</div> </div> </body> </html>", "e": 26697, "s": 25800, "text": null }, { "code": null, "e": 26705, "s": 26697, "text": "Output:" }, { "code": null, "e": 26716, "s": 26705, "text": "Example 2:" }, { "code": "<!DOCTYPE html><html> <head> <style> .gfg { display: grid; /* display is set to grid layout */ height: 400px; align-content: center; /* vertically aligns objects to the center */ grid-template-columns: auto auto auto; grid-gap: 10px; background-color: #f67280; /* background colour is set */ padding: 10px; } .gfg > div { background-color: rgba(255, 255, 255, 0.8); text-align: center; /* text inside the container is set to center */ padding: 20px 0; font-size: 30px; } </style></head> <body> <div class=\"gfg\"> <div>Explore</div> <div>the</div> <div>world</div> <div>travel</div> <div>and</div> <div>eat</div> </div> </body> </html>", "e": 27613, "s": 26716, "text": null }, { "code": null, "e": 27621, "s": 27613, "text": "Output:" }, { "code": null, "e": 27636, "s": 27621, "text": "CSS-Properties" }, { "code": null, "e": 27643, "s": 27636, "text": "Picked" }, { "code": null, "e": 27647, "s": 27643, "text": "CSS" }, { "code": null, "e": 27664, "s": 27647, "text": "Web Technologies" }, { "code": null, "e": 27691, "s": 27664, "text": "Web technologies Questions" }, { "code": null, "e": 27789, "s": 27691, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27826, "s": 27789, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 27855, "s": 27826, "text": "Form validation using jQuery" }, { "code": null, "e": 27894, "s": 27855, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 27936, "s": 27894, "text": "Search Bar using HTML, CSS and JavaScript" }, { "code": null, "e": 27983, "s": 27936, "text": "How to Create Time-Table schedule using HTML ?" }, { "code": null, "e": 28025, "s": 27983, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 28058, "s": 28025, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 28101, "s": 28058, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 28146, "s": 28101, "text": "Convert a string to an integer in JavaScript" } ]
How to do a batch insert in MySQL?
To do a batch insert, we need to use all column names with parenthesis, separated by ‘,’. Let us see an example. First, we will create a table. The following is the CREATE command to create a table. mysql> CREATE table MultipleRecordWithValues - > ( - > id int, - > name varchar(100) - > ); Query OK, 0 rows affected (0.88 sec) The following is the syntax of batch insert. INSERT into yourTableName values(column1,column2,....N),(column1,column2,....N),(column1,column2,....N),...........N; Applying the above syntax to insert batch records. mysql> insert into MultipleRecordWithValues values(1,'John'),(2,'Carol'),(3,'Bob'),(4,'Smith'); Query OK, 4 rows affected (0.16 sec) Records: 4 Duplicates: 0 Warnings: 0 Since 4 rows are affected, it implies that we have inserted records successfully. To check if all records are present in the table, use the SELECT command. mysql> select *from MultipleRecordWithValues; The following is the output. +------+-------+ | id | name | +------+-------+ | 1 | John | | 2 | Carol | | 3 | Bob | | 4 | Smith | +------+-------+ 4 rows in set (0.00 sec)
[ { "code": null, "e": 1152, "s": 1062, "text": "To do a batch insert, we need to use all column names with parenthesis, separated by ‘,’." }, { "code": null, "e": 1261, "s": 1152, "text": "Let us see an example. First, we will create a table. The following is the CREATE command to create a table." }, { "code": null, "e": 1402, "s": 1261, "text": "mysql> CREATE table MultipleRecordWithValues\n - > (\n - > id int,\n - > name varchar(100)\n - > );\nQuery OK, 0 rows affected (0.88 sec)" }, { "code": null, "e": 1447, "s": 1402, "text": "The following is the syntax of batch insert." }, { "code": null, "e": 1566, "s": 1447, "text": "INSERT into yourTableName values(column1,column2,....N),(column1,column2,....N),(column1,column2,....N),...........N;\n" }, { "code": null, "e": 1617, "s": 1566, "text": "Applying the above syntax to insert batch records." }, { "code": null, "e": 1789, "s": 1617, "text": "mysql> insert into MultipleRecordWithValues values(1,'John'),(2,'Carol'),(3,'Bob'),(4,'Smith');\nQuery OK, 4 rows affected (0.16 sec)\nRecords: 4 Duplicates: 0 Warnings: 0" }, { "code": null, "e": 1945, "s": 1789, "text": "Since 4 rows are affected, it implies that we have inserted records successfully. To check if all records are present in the table, use the SELECT command." }, { "code": null, "e": 1991, "s": 1945, "text": "mysql> select *from MultipleRecordWithValues;" }, { "code": null, "e": 2020, "s": 1991, "text": "The following is the output." }, { "code": null, "e": 2182, "s": 2020, "text": "+------+-------+\n| id | name |\n+------+-------+\n| 1 | John |\n| 2 | Carol |\n| 3 | Bob |\n| 4 | Smith |\n+------+-------+\n4 rows in set (0.00 sec)\n" } ]
How can I make a horizontal ListView in Android?
This example demonstrates about How can I make a horizontal ListView in Android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/rlMain" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_margin="16dp" android:orientation="vertical"> <androidx.recyclerview.widget.RecyclerView android:id="@+id/recyclerView" android:layout_width="match_parent" android:layout_height="match_parent" /> </LinearLayout> Step 3 − Add the following code to src/MainActivity.java package app.com.sample; import android.os.Bundle; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.DefaultItemAnimator; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import java.util.ArrayList; import java.util.List; public class MainActivity extends AppCompatActivity { private List<MovieModel> movieList = new ArrayList<>(); private MoviesAdapter mAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); RecyclerView recyclerView = findViewById(R.id.recyclerView); mAdapter = new MoviesAdapter(movieList); LinearLayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext()); mLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL); recyclerView.setLayoutManager(mLayoutManager); recyclerView.setItemAnimator(new DefaultItemAnimator()); recyclerView.setAdapter(mAdapter); prepareMovieData(); } private void prepareMovieData() { MovieModel movie = new MovieModel("Mad Max: Fury Road", "Action & Adventure", "2015"); movieList.add(movie); movie = new MovieModel("Inside Out", "Animation, Kids & Family", "2015"); movieList.add(movie); movie = new MovieModel("Star Wars: Episode VII - The Force Awakens", "Action", "2015"); movieList.add(movie); movie = new MovieModel("Shaun the Sheep", "Animation", "2015"); movieList.add(movie); movie = new MovieModel("The Martian", "Science Fiction & Fantasy", "2015"); movieList.add(movie); movie = new MovieModel("Mission: Impossible Rogue Nation", "Action", "2015"); movieList.add(movie); movie = new MovieModel("Up", "Animation", "2009"); movieList.add(movie); movie = new MovieModel("Star Trek", "Science Fiction", "2009"); movieList.add(movie); movie = new MovieModel("The LEGO MovieModel", "Animation", "2014"); movieList.add(movie); movie = new MovieModel("Iron Man", "Action & Adventure", "2008"); movieList.add(movie); movie = new MovieModel("Aliens", "Science Fiction", "1986"); movieList.add(movie); movie = new MovieModel("Chicken Run", "Animation", "2000"); movieList.add(movie); movie = new MovieModel("Back to the Future", "Science Fiction", "1985"); movieList.add(movie); movie = new MovieModel("Raiders of the Lost Ark", "Action & Adventure", "1981"); movieList.add(movie); movie = new MovieModel("Goldfinger", "Action & Adventure", "1965"); movieList.add(movie); movie = new MovieModel("Guardians of the Galaxy", "Science Fiction & Fantasy", "2014"); movieList.add(movie); mAdapter.notifyDataSetChanged(); } } Step 7 − Add the following code to src/MovieModel.java package app.com.sample; public class MovieModel { private String title, genre, year; public MovieModel() { } public MovieModel(String title, String genre, String year) { this.title = title; this.genre = genre; this.year = year; } public String getTitle() { return title; } public void setTitle(String name) { this.title = name; } public String getYear() { return year; } public void setYear(String year) { this.year = year; } public String getGenre() { return genre; } public void setGenre(String genre) { this.genre = genre; } } Step 5 − Add the following code to res/layout/movies_list.xml. <?xml version="1.0" encoding="utf-8"?> <androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="250dp" android:layout_height="100dp" android:layout_margin="8dp"> <RelativeLayout android:layout_width="match_parent" android:layout_height="match_parent" android:padding="8dp"> <TextView android:id="@+id/title" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentStart="true" android:layout_toStartOf="@+id/year" android:textColor="#222222" android:textSize="16sp" android:textStyle="bold" /> <TextView android:id="@+id/year" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentEnd="true" android:textColor="#999999" /> <TextView android:id="@+id/genre" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentBottom="true" /> </RelativeLayout> </androidx.cardview.widget.CardView> Step 6 − Add the following code to src/MoviesAdapter.java package app.com.sample; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import java.util.List; public class MoviesAdapter extends RecyclerView.Adapter<MoviesAdapter.MyViewHolder> { private List<MovieModel> moviesList; class MyViewHolder extends RecyclerView.ViewHolder { TextView title, year, genre; MyViewHolder(View view) { super(view); title = view.findViewById(R.id.title); genre = view.findViewById(R.id.genre); year = view.findViewById(R.id.year); } } public MoviesAdapter(List<MovieModel> moviesList) { this.moviesList = moviesList; } @NonNull @Override public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View itemView = LayoutInflater.from(parent.getContext()) .inflate(R.layout.movie_list, parent, false); return new MyViewHolder(itemView); } @Override public void onBindViewHolder(MyViewHolder holder, int position) { MovieModel movie = moviesList.get(position); holder.title.setText(movie.getTitle()); holder.genre.setText(movie.getGenre()); holder.year.setText(movie.getYear()); } @Override public int getItemCount() { return moviesList.size(); } } Step 7 − 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": 1143, "s": 1062, "text": "This example demonstrates about How can I make a horizontal ListView in Android." }, { "code": null, "e": 1273, "s": 1143, "text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project." }, { "code": null, "e": 1339, "s": 1273, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 1812, "s": 1339, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n android:id=\"@+id/rlMain\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:layout_margin=\"16dp\"\n android:orientation=\"vertical\">\n <androidx.recyclerview.widget.RecyclerView\n android:id=\"@+id/recyclerView\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\" />\n</LinearLayout>" }, { "code": null, "e": 1870, "s": 1812, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 4727, "s": 1870, "text": "package app.com.sample;\nimport android.os.Bundle;\nimport androidx.appcompat.app.AppCompatActivity;\nimport androidx.recyclerview.widget.DefaultItemAnimator;\nimport androidx.recyclerview.widget.LinearLayoutManager;\nimport androidx.recyclerview.widget.RecyclerView;\nimport java.util.ArrayList;\nimport java.util.List;\npublic class MainActivity extends AppCompatActivity {\n private List<MovieModel> movieList = new ArrayList<>();\n private MoviesAdapter mAdapter;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n RecyclerView recyclerView = findViewById(R.id.recyclerView);\n mAdapter = new MoviesAdapter(movieList);\n LinearLayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());\n mLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);\n recyclerView.setLayoutManager(mLayoutManager);\n recyclerView.setItemAnimator(new DefaultItemAnimator());\n recyclerView.setAdapter(mAdapter);\n prepareMovieData();\n }\n private void prepareMovieData() {\n MovieModel movie = new MovieModel(\"Mad Max: Fury Road\", \"Action & Adventure\", \"2015\");\n movieList.add(movie);\n movie = new MovieModel(\"Inside Out\", \"Animation, Kids & Family\", \"2015\");\n movieList.add(movie);\n movie = new MovieModel(\"Star Wars: Episode VII - The Force Awakens\", \"Action\", \"2015\");\n movieList.add(movie);\n movie = new MovieModel(\"Shaun the Sheep\", \"Animation\", \"2015\");\n movieList.add(movie);\n movie = new MovieModel(\"The Martian\", \"Science Fiction & Fantasy\", \"2015\");\n movieList.add(movie);\n movie = new MovieModel(\"Mission: Impossible Rogue Nation\", \"Action\", \"2015\");\n movieList.add(movie);\n movie = new MovieModel(\"Up\", \"Animation\", \"2009\");\n movieList.add(movie);\n movie = new MovieModel(\"Star Trek\", \"Science Fiction\", \"2009\");\n movieList.add(movie);\n movie = new MovieModel(\"The LEGO MovieModel\", \"Animation\", \"2014\");\n movieList.add(movie);\n movie = new MovieModel(\"Iron Man\", \"Action & Adventure\", \"2008\");\n movieList.add(movie);\n movie = new MovieModel(\"Aliens\", \"Science Fiction\", \"1986\");\n movieList.add(movie);\n movie = new MovieModel(\"Chicken Run\", \"Animation\", \"2000\");\n movieList.add(movie);\n movie = new MovieModel(\"Back to the Future\", \"Science Fiction\", \"1985\");\n movieList.add(movie);\n movie = new MovieModel(\"Raiders of the Lost Ark\", \"Action & Adventure\", \"1981\");\n movieList.add(movie);\n movie = new MovieModel(\"Goldfinger\", \"Action & Adventure\", \"1965\");\n movieList.add(movie);\n movie = new MovieModel(\"Guardians of the Galaxy\", \"Science Fiction & Fantasy\", \"2014\");\n movieList.add(movie);\n mAdapter.notifyDataSetChanged();\n }\n}" }, { "code": null, "e": 4783, "s": 4727, "text": "Step 7 − Add the following code to src/MovieModel.java" }, { "code": null, "e": 5418, "s": 4783, "text": "package app.com.sample;\npublic class MovieModel {\n private String title, genre, year;\n public MovieModel() {\n }\n public MovieModel(String title, String genre, String year) {\n this.title = title;\n this.genre = genre;\n this.year = year;\n }\n public String getTitle() {\n return title;\n }\n public void setTitle(String name) {\n this.title = name;\n }\n public String getYear() {\n return year;\n }\n public void setYear(String year) {\n this.year = year;\n }\n public String getGenre() {\n return genre;\n }\n public void setGenre(String genre) {\n this.genre = genre;\n }\n}" }, { "code": null, "e": 5482, "s": 5418, "text": "Step 5 − Add the following code to res/layout/movies_list.xml." }, { "code": null, "e": 6661, "s": 5482, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<androidx.cardview.widget.CardView xmlns:android=\"http://schemas.android.com/apk/res/android\"\n android:layout_width=\"250dp\"\n android:layout_height=\"100dp\"\n android:layout_margin=\"8dp\">\n <RelativeLayout\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:padding=\"8dp\">\n <TextView\n android:id=\"@+id/title\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:layout_alignParentStart=\"true\"\n android:layout_toStartOf=\"@+id/year\"\n android:textColor=\"#222222\"\n android:textSize=\"16sp\"\n android:textStyle=\"bold\" />\n <TextView\n android:id=\"@+id/year\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_alignParentEnd=\"true\"\n android:textColor=\"#999999\" />\n <TextView\n android:id=\"@+id/genre\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:layout_alignParentBottom=\"true\" />\n </RelativeLayout>\n</androidx.cardview.widget.CardView>" }, { "code": null, "e": 6720, "s": 6661, "text": "Step 6 − Add the following code to src/MoviesAdapter.java" }, { "code": null, "e": 8119, "s": 6720, "text": "package app.com.sample;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.TextView;\nimport androidx.annotation.NonNull;\nimport androidx.recyclerview.widget.RecyclerView;\nimport java.util.List;\npublic class MoviesAdapter extends RecyclerView.Adapter<MoviesAdapter.MyViewHolder> {\n private List<MovieModel> moviesList;\n class MyViewHolder extends RecyclerView.ViewHolder {\n TextView title, year, genre;\n MyViewHolder(View view) {\n super(view);\n title = view.findViewById(R.id.title);\n genre = view.findViewById(R.id.genre);\n year = view.findViewById(R.id.year);\n }\n }\n public MoviesAdapter(List<MovieModel> moviesList) {\n this.moviesList = moviesList;\n }\n @NonNull\n @Override\n public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {\n View itemView = LayoutInflater.from(parent.getContext())\n .inflate(R.layout.movie_list, parent, false);\n return new MyViewHolder(itemView);\n }\n @Override\n public void onBindViewHolder(MyViewHolder holder, int position) {\n MovieModel movie = moviesList.get(position);\n holder.title.setText(movie.getTitle());\n holder.genre.setText(movie.getGenre());\n holder.year.setText(movie.getYear());\n }\n @Override\n public int getItemCount() {\n return moviesList.size();\n }\n}" }, { "code": null, "e": 8175, "s": 8119, "text": "Step 7 − Add the following code to androidManifest.xml" }, { "code": null, "e": 8848, "s": 8175, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n 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": 9195, "s": 8848, "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": 9236, "s": 9195, "text": "Click here to download the project code." } ]
Huffman Coding Algorithm
Huffman coding is a lossless data compression algorithm. In this algorithm, a variable-length code is assigned to input different characters. The code length is related to how frequently characters are used. Most frequent characters have the smallest codes and longer codes for least frequent characters. There are mainly two parts. First one to create a Huffman tree, and another one to traverse the tree to find codes. For an example, consider some strings “YYYZXXYYX”, the frequency of character Y is larger than X and the character Z has the least frequency. So the length of the code for Y is smaller than X, and code for X will be smaller than Z. Complexity for assigning the code for each character according to their frequency is O(n log n) Input: A string with different characters, say “ACCEBFFFFAAXXBLKE” Output: Code for different characters: Data: K, Frequency: 1, Code: 0000 Data: L, Frequency: 1, Code: 0001 Data: E, Frequency: 2, Code: 001 Data: F, Frequency: 4, Code: 01 Data: B, Frequency: 2, Code: 100 Data: C, Frequency: 2, Code: 101 Data: X, Frequency: 2, Code: 110 Data: A, Frequency: 3, Code: 111 huffmanCoding(string) Input: A string with different characters. Output: The codes for each individual characters. Begin define a node with character, frequency, left and right child of the node for Huffman tree. create a list ‘freq’ to store frequency of each character, initially, all are 0 for each character c in the string do increase the frequency for character ch in freq list. done for all type of character ch do if the frequency of ch is non zero then add ch and its frequency as a node of priority queue Q. done while Q is not empty do remove item from Q and assign it to left child of node remove item from Q and assign to the right child of node traverse the node to find the assigned code done End traverseNode(n: node, code) Input: The node n of the Huffman tree, and the code assigned from the previous call Output: Code assigned with each character if a left child of node n ≠φ then traverseNode(leftChild(n), code+’0’) //traverse through the left child traverseNode(rightChild(n), code+’1’) //traverse through the right child else display the character and data of current node. #include #include #include using namespace std; struct node { int freq; char data; const node *child0, *child1; node(char d, int f = -1) { //assign values in the node data = d; freq = f; child0 = NULL; child1 = NULL; } node(const node *c0, const node *c1) { data = 0; freq = c0->freq + c1->freq; child0=c0; child1=c1; } bool operator<( const node &a ) const { //< operator performs to find priority in queue return freq >a.freq; } void traverse(string code = "")const { if(child0!=NULL) { child0->traverse(code+'0'); //add 0 with the code as left child child1->traverse(code+'1'); //add 1 with the code as right child }else { cout << "Data: " << data<< ", Frequency: "< qu; int frequency[256]; for(int i = 0; i<256; i++) frequency[i] = 0; //clear all frequency for(int i = 0; i1) { node *c0 = new node(qu.top()); //get left child and remove from queue qu.pop(); node *c1 = new node(qu.top()); //get right child and remove from queue qu.pop(); qu.push(node(c0, c1)); //add freq of two child and add again in the queue } cout << "The Huffman Code: "< The Huffman Code: Data: K, Frequency: 1, Code: 0000 Data: L, Frequency: 1, Code: 0001 Data: E, Frequency: 2, Code: 001 Data: F, Frequency: 4, Code: 01 Data: B, Frequency: 2, Code: 100 Data: C, Frequency: 2, Code: 101 Data: X, Frequency: 2, Code: 110 Data: A, Frequency: 3, Code: 111
[ { "code": null, "e": 1367, "s": 1062, "text": "Huffman coding is a lossless data compression algorithm. In this algorithm, a variable-length code is assigned to input different characters. The code length is related to how frequently characters are used. Most frequent characters have the smallest codes and longer codes for least frequent characters." }, { "code": null, "e": 1483, "s": 1367, "text": "There are mainly two parts. First one to create a Huffman tree, and another one to traverse the tree to find codes." }, { "code": null, "e": 1715, "s": 1483, "text": "For an example, consider some strings “YYYZXXYYX”, the frequency of character Y is larger than X and the character Z has the least frequency. So the length of the code for Y is smaller than X, and code for X will be smaller than Z." }, { "code": null, "e": 1811, "s": 1715, "text": "Complexity for assigning the code for each character according to their frequency is O(n log n)" }, { "code": null, "e": 2182, "s": 1811, "text": "Input:\nA string with different characters, say “ACCEBFFFFAAXXBLKE”\nOutput:\nCode for different characters:\nData: K, Frequency: 1, Code: 0000\nData: L, Frequency: 1, Code: 0001\nData: E, Frequency: 2, Code: 001\nData: F, Frequency: 4, Code: 01\nData: B, Frequency: 2, Code: 100\nData: C, Frequency: 2, Code: 101\nData: X, Frequency: 2, Code: 110\nData: A, Frequency: 3, Code: 111" }, { "code": null, "e": 2204, "s": 2182, "text": "huffmanCoding(string)" }, { "code": null, "e": 2247, "s": 2204, "text": "Input: A string with different characters." }, { "code": null, "e": 2297, "s": 2247, "text": "Output: The codes for each individual characters." }, { "code": null, "e": 2959, "s": 2297, "text": "Begin\n define a node with character, frequency, left and right child of the node for Huffman tree.\n create a list ‘freq’ to store frequency of each character, initially, all are 0\n for each character c in the string do\n increase the frequency for character ch in freq list.\n done\n\n for all type of character ch do\n if the frequency of ch is non zero then\n add ch and its frequency as a node of priority queue Q.\n done\n\n while Q is not empty do\n remove item from Q and assign it to left child of node\n remove item from Q and assign to the right child of node\n traverse the node to find the assigned code\n done\nEnd" }, { "code": null, "e": 2987, "s": 2959, "text": "traverseNode(n: node, code)" }, { "code": null, "e": 3071, "s": 2987, "text": "Input: The node n of the Huffman tree, and the code assigned from the previous call" }, { "code": null, "e": 3113, "s": 3071, "text": "Output: Code assigned with each character" }, { "code": null, "e": 3361, "s": 3113, "text": "if a left child of node n ≠φ then\n traverseNode(leftChild(n), code+’0’) //traverse through the left child\n traverseNode(rightChild(n), code+’1’) //traverse through the right child\nelse\n display the character and data of current node." }, { "code": null, "e": 4560, "s": 3361, "text": "#include\n#include\n#include\nusing namespace std;\n\nstruct node {\n int freq;\n char data;\n const node *child0, *child1;\n\n node(char d, int f = -1) { //assign values in the node\n data = d;\n freq = f;\n child0 = NULL;\n child1 = NULL;\n }\n\n node(const node *c0, const node *c1) {\n data = 0;\n freq = c0->freq + c1->freq;\n child0=c0;\n child1=c1;\n }\n\n bool operator<( const node &a ) const { //< operator performs to find priority in queue\n return freq >a.freq;\n }\n\n void traverse(string code = \"\")const {\n if(child0!=NULL) {\n child0->traverse(code+'0'); //add 0 with the code as left child\n child1->traverse(code+'1'); //add 1 with the code as right child\n }else {\n cout << \"Data: \" << data<< \", Frequency: \"< qu;\n int frequency[256];\n\n for(int i = 0; i<256; i++)\n frequency[i] = 0; //clear all frequency\n\n for(int i = 0; i1) {\n node *c0 = new node(qu.top()); //get left child and remove from queue\n qu.pop();\n node *c1 = new node(qu.top()); //get right child and remove from queue\n qu.pop();\n qu.push(node(c0, c1)); //add freq of two child and add again in the queue\n }\n\n" }, { "code": null, "e": 4593, "s": 4560, "text": " cout << \"The Huffman Code: \"<" }, { "code": null, "e": 4876, "s": 4593, "text": "The Huffman Code:\nData: K, Frequency: 1, Code: 0000\nData: L, Frequency: 1, Code: 0001\nData: E, Frequency: 2, Code: 001\nData: F, Frequency: 4, Code: 01\nData: B, Frequency: 2, Code: 100\nData: C, Frequency: 2, Code: 101\nData: X, Frequency: 2, Code: 110\nData: A, Frequency: 3, Code: 111" } ]
How to convert JSON to Ordereddict?
24 Jan, 2021 The full-form of JSON is JavaScript Object Notation. It means that a script (executable) file which is made of text in a programming language, is used to store and transfer the data. Python supports JSON through a built-in package called json. To use this feature, we import the json package in Python script. The text in JSON is done through quoted-string which contains a value in key-value mapping within { }. It is similar to the dictionary in Python. An OrderedDict is a dictionary subclass that remembers the order that keys were first inserted. The only difference between dict() and OrderedDict() is that: OrderedDict preserves the order in which the keys are inserted. A regular dict doesn’t track the insertion order and iterating it gives the values in an arbitrary order. In this article we are going to discuss various methods to convert JSON to Ordereddict. Method #1 By specifying the object_pairs_hook argument to JSONDecoder. Python # import required modulesimport jsonfrom collections import OrderedDict # assign json filejsonFile = '{"Geeks":1, "for": 2, "geeks":3}'print(jsonFile) # convert to Ordereddictdata = json.JSONDecoder(object_pairs_hook=OrderedDict).decode(jsonFile)print(data) Output: {"Geeks":1, "for": 2, "geeks":3} OrderedDict([(u'Geeks', 1), (u'for', 2), (u'geeks', 3)]) Method #2 By passing the JSON data as a parameter to json.loads(). Python # import required modulesimport jsonfrom collections import OrderedDict # assign json filejsonFile = '{"Geeks":1, "for": 2, "geeks":3}'print(jsonFile) # convert to Ordereddictdata = json.loads(jsonFile, object_pairs_hook=OrderedDict)print(data) Output: {"Geeks":1, "for": 2, "geeks":3} OrderedDict([(u'Geeks', 1), (u'for', 2), (u'geeks', 3)]) Picked Python collections-module Python-json Technical Scripter 2020 Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python OOPs Concepts Python Classes and Objects Introduction To PYTHON Python | os.path.join() method How to drop one or multiple columns in Pandas Dataframe Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python - Pandas dataframe.append() Create a directory in Python
[ { "code": null, "e": 53, "s": 25, "text": "\n24 Jan, 2021" }, { "code": null, "e": 509, "s": 53, "text": "The full-form of JSON is JavaScript Object Notation. It means that a script (executable) file which is made of text in a programming language, is used to store and transfer the data. Python supports JSON through a built-in package called json. To use this feature, we import the json package in Python script. The text in JSON is done through quoted-string which contains a value in key-value mapping within { }. It is similar to the dictionary in Python." }, { "code": null, "e": 837, "s": 509, "text": "An OrderedDict is a dictionary subclass that remembers the order that keys were first inserted. The only difference between dict() and OrderedDict() is that: OrderedDict preserves the order in which the keys are inserted. A regular dict doesn’t track the insertion order and iterating it gives the values in an arbitrary order." }, { "code": null, "e": 925, "s": 837, "text": "In this article we are going to discuss various methods to convert JSON to Ordereddict." }, { "code": null, "e": 935, "s": 925, "text": "Method #1" }, { "code": null, "e": 996, "s": 935, "text": "By specifying the object_pairs_hook argument to JSONDecoder." }, { "code": null, "e": 1003, "s": 996, "text": "Python" }, { "code": "# import required modulesimport jsonfrom collections import OrderedDict # assign json filejsonFile = '{\"Geeks\":1, \"for\": 2, \"geeks\":3}'print(jsonFile) # convert to Ordereddictdata = json.JSONDecoder(object_pairs_hook=OrderedDict).decode(jsonFile)print(data)", "e": 1263, "s": 1003, "text": null }, { "code": null, "e": 1271, "s": 1263, "text": "Output:" }, { "code": null, "e": 1361, "s": 1271, "text": "{\"Geeks\":1, \"for\": 2, \"geeks\":3}\nOrderedDict([(u'Geeks', 1), (u'for', 2), (u'geeks', 3)])" }, { "code": null, "e": 1371, "s": 1361, "text": "Method #2" }, { "code": null, "e": 1428, "s": 1371, "text": "By passing the JSON data as a parameter to json.loads()." }, { "code": null, "e": 1435, "s": 1428, "text": "Python" }, { "code": "# import required modulesimport jsonfrom collections import OrderedDict # assign json filejsonFile = '{\"Geeks\":1, \"for\": 2, \"geeks\":3}'print(jsonFile) # convert to Ordereddictdata = json.loads(jsonFile, object_pairs_hook=OrderedDict)print(data)", "e": 1700, "s": 1435, "text": null }, { "code": null, "e": 1708, "s": 1700, "text": "Output:" }, { "code": null, "e": 1798, "s": 1708, "text": "{\"Geeks\":1, \"for\": 2, \"geeks\":3}\nOrderedDict([(u'Geeks', 1), (u'for', 2), (u'geeks', 3)])" }, { "code": null, "e": 1805, "s": 1798, "text": "Picked" }, { "code": null, "e": 1831, "s": 1805, "text": "Python collections-module" }, { "code": null, "e": 1843, "s": 1831, "text": "Python-json" }, { "code": null, "e": 1867, "s": 1843, "text": "Technical Scripter 2020" }, { "code": null, "e": 1874, "s": 1867, "text": "Python" }, { "code": null, "e": 1893, "s": 1874, "text": "Technical Scripter" }, { "code": null, "e": 1991, "s": 1893, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2023, "s": 1991, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2044, "s": 2023, "text": "Python OOPs Concepts" }, { "code": null, "e": 2071, "s": 2044, "text": "Python Classes and Objects" }, { "code": null, "e": 2094, "s": 2071, "text": "Introduction To PYTHON" }, { "code": null, "e": 2125, "s": 2094, "text": "Python | os.path.join() method" }, { "code": null, "e": 2181, "s": 2125, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 2223, "s": 2181, "text": "Check if element exists in list in Python" }, { "code": null, "e": 2265, "s": 2223, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 2300, "s": 2265, "text": "Python - Pandas dataframe.append()" } ]
Justify the given Text based on the given width of each line
27 Feb, 2020 Given a string str and width of each line as L, the task is to justify the string such that each line of justified text is of length L with help of space (‘ ‘) and the last line should be left-justified. Examples: Input: str = “GeeksforGeek is the best computer science portal for geeks.”, L = 16Output:GeeksforGeek__isthe_________bestcomputer_scienceportal_______forgeeks.__________ Input: str = “The quick brown fox jumps over the lazy dog.”, L = 11Output:The___quickbrown___foxjumped_overthe____lazydogs.______The symbol _ denotes a space. Approach:The number of spaces between words in each line cannot be computed until a complete set of words in that line is known. We will solve this problem on a line-by-line basis. Split the given text into wordsFirstly select the words which can be inserted in each line including a space between each word. For that, the sum of length of included words with one space between them must be smaller than or equal to L.Now count the number of spaces needed to make the length of each line L and distribute the spaces evenly.Repeat above steps for next set of words.For the last line spaces must be assigned at the end as the last line must be left-justified. Split the given text into words Firstly select the words which can be inserted in each line including a space between each word. For that, the sum of length of included words with one space between them must be smaller than or equal to L. Now count the number of spaces needed to make the length of each line L and distribute the spaces evenly. Repeat above steps for next set of words. For the last line spaces must be assigned at the end as the last line must be left-justified. Below is the implementation of the above approach: // C++ program to Justify the given Text// according to the given width of each line #include "bits/stdc++.h"using namespace std; // Function to join the words// with spaces spread evenlystring JoinALineWithSpace( vector<string>& words, int start, int end, int num_spaces){ // Number of words in current line int num_words_curr_line = end - start + 1; // String to store the justified text string line; for (int i = start; i < end; i++) { line += words[i]; --num_words_curr_line; // Count number of current space needed int num_curr_space = ceil((double)(num_spaces) / num_words_curr_line); // Insert spaces in string line line.append(num_curr_space, ' '); // Delete the spaces inserted in line num_spaces -= num_curr_space; } // Insert word to string line line += words[end]; line.append(num_spaces, ' '); // Return justified text return line;} // Function that justify the words of// sentence of length of line Lvector<string> JustifyText( vector<string>& words, int L){ int curr_line_start = 0; int num_words_curr_line = 0; int curr_line_length = 0; // To store the justified text vector<string> result; // Traversing the words array for (int i = 0; i < words.size(); i++) { // curr_line_start is the first word // in the current line, and i is // used to identify the last word ++num_words_curr_line; int lookahead_line_length = curr_line_length + words[i].size() + (num_words_curr_line - 1); // If by including the words length becomes L, // then that set of words is justified // and add the justified text to result if (lookahead_line_length == L) { // Justify the set of words string ans = JoinALineWithSpace( words, curr_line_start, i, i - curr_line_start); // Store the justified text in result result.emplace_back(ans); // Start the current line // with next index curr_line_start = i + 1; // num of words in the current line // and current line length set to 0 num_words_curr_line = 0; curr_line_length = 0; } // If by including the words such that // length of words becomes greater than L, // then hat set is justified with // one less word and add the // justified text to result else if (lookahead_line_length > L) { // Justify the set of words string ans = JoinALineWithSpace( words, curr_line_start, i - 1, L - curr_line_length); // Store the justified text in result result.emplace_back(ans); // Current line set to current word curr_line_start = i; // Number of words set to 1 num_words_curr_line = 1; // Current line length set // to current word length curr_line_length = words[i].size(); } // If length is less than L then, // add the word to current line length else { curr_line_length += words[i].size(); } } // Last line is to be left-aligned if (num_words_curr_line > 0) { string line = JoinALineWithSpace( words, curr_line_start, words.size() - 1, num_words_curr_line - 1); line.append( L - curr_line_length - (num_words_curr_line - 1), ' '); // Insert the last line // left-aligned to result result.emplace_back(line); } // Return result return result;} // Function to insert words// of sentencevector<string> splitWords(string str){ vector<string> words; string a = ""; for (int i = 0; str[i]; i++) { // Add char to string a // to get the word if (str[i] != ' ') { a += str[i]; } // If a space occurs // split the words and // add it to vector else { words.push_back(a); a = ""; } } // Push_back the last word // of sentence words.push_back(a); // Return the vector of // words extracted from // string return words;} // Function to print justified textvoid printJustifiedText(vector<string>& result){ for (auto& it : result) { cout << it << endl; }} // Function to call the justificationvoid justifyTheText(string str, int L){ vector<string> words; // Inserting words from // given string words = splitWords(str); // Function call to // justify the text vector<string> result = JustifyText(words, L); // Print the justified // text printJustifiedText(result);} // Driver Codeint main(){ string str = "GeeksforGeek is the best" " computer science portal" " for geeks."; int L = 16; justifyTheText(str, L); return 0;} GeeksforGeek is the best computer science portal for geeks. Time Complexity: O(N), where N = length of string Technical Scripter 2019 Strings Technical Scripter Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n27 Feb, 2020" }, { "code": null, "e": 256, "s": 52, "text": "Given a string str and width of each line as L, the task is to justify the string such that each line of justified text is of length L with help of space (‘ ‘) and the last line should be left-justified." }, { "code": null, "e": 266, "s": 256, "text": "Examples:" }, { "code": null, "e": 436, "s": 266, "text": "Input: str = “GeeksforGeek is the best computer science portal for geeks.”, L = 16Output:GeeksforGeek__isthe_________bestcomputer_scienceportal_______forgeeks.__________" }, { "code": null, "e": 595, "s": 436, "text": "Input: str = “The quick brown fox jumps over the lazy dog.”, L = 11Output:The___quickbrown___foxjumped_overthe____lazydogs.______The symbol _ denotes a space." }, { "code": null, "e": 776, "s": 595, "text": "Approach:The number of spaces between words in each line cannot be computed until a complete set of words in that line is known. We will solve this problem on a line-by-line basis." }, { "code": null, "e": 1253, "s": 776, "text": "Split the given text into wordsFirstly select the words which can be inserted in each line including a space between each word. For that, the sum of length of included words with one space between them must be smaller than or equal to L.Now count the number of spaces needed to make the length of each line L and distribute the spaces evenly.Repeat above steps for next set of words.For the last line spaces must be assigned at the end as the last line must be left-justified." }, { "code": null, "e": 1285, "s": 1253, "text": "Split the given text into words" }, { "code": null, "e": 1492, "s": 1285, "text": "Firstly select the words which can be inserted in each line including a space between each word. For that, the sum of length of included words with one space between them must be smaller than or equal to L." }, { "code": null, "e": 1598, "s": 1492, "text": "Now count the number of spaces needed to make the length of each line L and distribute the spaces evenly." }, { "code": null, "e": 1640, "s": 1598, "text": "Repeat above steps for next set of words." }, { "code": null, "e": 1734, "s": 1640, "text": "For the last line spaces must be assigned at the end as the last line must be left-justified." }, { "code": null, "e": 1785, "s": 1734, "text": "Below is the implementation of the above approach:" }, { "code": "// C++ program to Justify the given Text// according to the given width of each line #include \"bits/stdc++.h\"using namespace std; // Function to join the words// with spaces spread evenlystring JoinALineWithSpace( vector<string>& words, int start, int end, int num_spaces){ // Number of words in current line int num_words_curr_line = end - start + 1; // String to store the justified text string line; for (int i = start; i < end; i++) { line += words[i]; --num_words_curr_line; // Count number of current space needed int num_curr_space = ceil((double)(num_spaces) / num_words_curr_line); // Insert spaces in string line line.append(num_curr_space, ' '); // Delete the spaces inserted in line num_spaces -= num_curr_space; } // Insert word to string line line += words[end]; line.append(num_spaces, ' '); // Return justified text return line;} // Function that justify the words of// sentence of length of line Lvector<string> JustifyText( vector<string>& words, int L){ int curr_line_start = 0; int num_words_curr_line = 0; int curr_line_length = 0; // To store the justified text vector<string> result; // Traversing the words array for (int i = 0; i < words.size(); i++) { // curr_line_start is the first word // in the current line, and i is // used to identify the last word ++num_words_curr_line; int lookahead_line_length = curr_line_length + words[i].size() + (num_words_curr_line - 1); // If by including the words length becomes L, // then that set of words is justified // and add the justified text to result if (lookahead_line_length == L) { // Justify the set of words string ans = JoinALineWithSpace( words, curr_line_start, i, i - curr_line_start); // Store the justified text in result result.emplace_back(ans); // Start the current line // with next index curr_line_start = i + 1; // num of words in the current line // and current line length set to 0 num_words_curr_line = 0; curr_line_length = 0; } // If by including the words such that // length of words becomes greater than L, // then hat set is justified with // one less word and add the // justified text to result else if (lookahead_line_length > L) { // Justify the set of words string ans = JoinALineWithSpace( words, curr_line_start, i - 1, L - curr_line_length); // Store the justified text in result result.emplace_back(ans); // Current line set to current word curr_line_start = i; // Number of words set to 1 num_words_curr_line = 1; // Current line length set // to current word length curr_line_length = words[i].size(); } // If length is less than L then, // add the word to current line length else { curr_line_length += words[i].size(); } } // Last line is to be left-aligned if (num_words_curr_line > 0) { string line = JoinALineWithSpace( words, curr_line_start, words.size() - 1, num_words_curr_line - 1); line.append( L - curr_line_length - (num_words_curr_line - 1), ' '); // Insert the last line // left-aligned to result result.emplace_back(line); } // Return result return result;} // Function to insert words// of sentencevector<string> splitWords(string str){ vector<string> words; string a = \"\"; for (int i = 0; str[i]; i++) { // Add char to string a // to get the word if (str[i] != ' ') { a += str[i]; } // If a space occurs // split the words and // add it to vector else { words.push_back(a); a = \"\"; } } // Push_back the last word // of sentence words.push_back(a); // Return the vector of // words extracted from // string return words;} // Function to print justified textvoid printJustifiedText(vector<string>& result){ for (auto& it : result) { cout << it << endl; }} // Function to call the justificationvoid justifyTheText(string str, int L){ vector<string> words; // Inserting words from // given string words = splitWords(str); // Function call to // justify the text vector<string> result = JustifyText(words, L); // Print the justified // text printJustifiedText(result);} // Driver Codeint main(){ string str = \"GeeksforGeek is the best\" \" computer science portal\" \" for geeks.\"; int L = 16; justifyTheText(str, L); return 0;}", "e": 7093, "s": 1785, "text": null }, { "code": null, "e": 7169, "s": 7093, "text": "GeeksforGeek is\nthe best\ncomputer science\nportal for\ngeeks.\n" }, { "code": null, "e": 7219, "s": 7169, "text": "Time Complexity: O(N), where N = length of string" }, { "code": null, "e": 7243, "s": 7219, "text": "Technical Scripter 2019" }, { "code": null, "e": 7251, "s": 7243, "text": "Strings" }, { "code": null, "e": 7270, "s": 7251, "text": "Technical Scripter" }, { "code": null, "e": 7278, "s": 7270, "text": "Strings" } ]
RadioButton in Tkinter | Python
16 Feb, 2021 The Radiobutton is a standard Tkinter widget used to implement one-of-many selections. Radiobuttons can contain text or images, and you can associate a Python function or method with each button. When the button is pressed, Tkinter automatically calls that function or method.Syntax: button = Radiobutton(master, text=”Name on Button”, variable = “shared variable”, value = “values of each button”, options = values, ...)shared variable = A Tkinter variable shared among all Radio buttons value = each radiobutton should have different value otherwise more than 1 radiobutton will get selected. Code #1: Radio buttons, but not in the form of buttons, in form of button box. In order to display button box, indicatoron/indicator option should be set to 0. Python3 # Importing Tkinter modulefrom tkinter import *# from tkinter.ttk import * # Creating master Tkinter windowmaster = Tk()master.geometry("175x175") # Tkinter string variable# able to store any string valuev = StringVar(master, "1") # Dictionary to create multiple buttonsvalues = {"RadioButton 1" : "1", "RadioButton 2" : "2", "RadioButton 3" : "3", "RadioButton 4" : "4", "RadioButton 5" : "5"} # Loop is used to create multiple Radiobuttons# rather than creating each button separatelyfor (text, value) in values.items(): Radiobutton(master, text = text, variable = v, value = value, indicator = 0, background = "light blue").pack(fill = X, ipady = 5) # Infinite loop can be terminated by# keyboard or mouse interrupt# or by any predefined function (destroy())mainloop() Output: The background of these button boxes is light blue. Button boxes having a white backgrounds as well as sunken are selected ones. Code #2: Changing button boxes into standard radio buttons. For this remove indicatoron option. Python3 # Importing Tkinter modulefrom tkinter import *from tkinter.ttk import * # Creating master Tkinter windowmaster = Tk()master.geometry("175x175") # Tkinter string variable# able to store any string valuev = StringVar(master, "1") # Dictionary to create multiple buttonsvalues = {"RadioButton 1" : "1", "RadioButton 2" : "2", "RadioButton 3" : "3", "RadioButton 4" : "4", "RadioButton 5" : "5"} # Loop is used to create multiple Radiobuttons# rather than creating each button separatelyfor (text, value) in values.items(): Radiobutton(master, text = text, variable = v, value = value).pack(side = TOP, ipady = 5) # Infinite loop can be terminated by# keyboard or mouse interrupt# or by any predefined function (destroy())mainloop() Output: These Radiobuttons are created using tkinter.ttk that is why background option is not available but we can use style class to do styling. Code #3: Adding Style to Radio Button using style class. Python3 # Importing Tkinter modulefrom tkinter import *from tkinter.ttk import * # Creating master Tkinter windowmaster = Tk()master.geometry('175x175') # Tkinter string variable# able to store any string valuev = StringVar(master, "1") # Style class to add style to Radiobutton# it can be used to style any ttk widgetstyle = Style(master)style.configure("TRadiobutton", background = "light green", foreground = "red", font = ("arial", 10, "bold")) # Dictionary to create multiple buttonsvalues = {"RadioButton 1" : "1", "RadioButton 2" : "2", "RadioButton 3" : "3", "RadioButton 4" : "4", "RadioButton 5" : "5"} # Loop is used to create multiple Radiobuttons# rather than creating each button separatelyfor (text, value) in values.items(): Radiobutton(master, text = text, variable = v, value = value).pack(side = TOP, ipady = 5) # Infinite loop can be terminated by# keyboard or mouse interrupt# or by any predefined function (destroy())mainloop() Output: You may observe that font style is changed as well as background and foreground colors are also changed. Here, TRadiobutton is used in style class, it automatically applies styling to all the available Radiobuttons. shubham_singh abhigoya Python-gui Python-tkinter Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Read JSON file using Python Python map() function Adding new column to existing DataFrame in Pandas How to get column names in Pandas dataframe Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python How to Install PIP on Windows ? Python String | replace() Python OOPs Concepts
[ { "code": null, "e": 54, "s": 26, "text": "\n16 Feb, 2021" }, { "code": null, "e": 340, "s": 54, "text": "The Radiobutton is a standard Tkinter widget used to implement one-of-many selections. Radiobuttons can contain text or images, and you can associate a Python function or method with each button. When the button is pressed, Tkinter automatically calls that function or method.Syntax: " }, { "code": null, "e": 653, "s": 340, "text": "button = Radiobutton(master, text=”Name on Button”, variable = “shared variable”, value = “values of each button”, options = values, ...)shared variable = A Tkinter variable shared among all Radio buttons value = each radiobutton should have different value otherwise more than 1 radiobutton will get selected. " }, { "code": null, "e": 815, "s": 653, "text": "Code #1: Radio buttons, but not in the form of buttons, in form of button box. In order to display button box, indicatoron/indicator option should be set to 0. " }, { "code": null, "e": 823, "s": 815, "text": "Python3" }, { "code": "# Importing Tkinter modulefrom tkinter import *# from tkinter.ttk import * # Creating master Tkinter windowmaster = Tk()master.geometry(\"175x175\") # Tkinter string variable# able to store any string valuev = StringVar(master, \"1\") # Dictionary to create multiple buttonsvalues = {\"RadioButton 1\" : \"1\", \"RadioButton 2\" : \"2\", \"RadioButton 3\" : \"3\", \"RadioButton 4\" : \"4\", \"RadioButton 5\" : \"5\"} # Loop is used to create multiple Radiobuttons# rather than creating each button separatelyfor (text, value) in values.items(): Radiobutton(master, text = text, variable = v, value = value, indicator = 0, background = \"light blue\").pack(fill = X, ipady = 5) # Infinite loop can be terminated by# keyboard or mouse interrupt# or by any predefined function (destroy())mainloop()", "e": 1664, "s": 823, "text": null }, { "code": null, "e": 1674, "s": 1664, "text": "Output: " }, { "code": null, "e": 1804, "s": 1674, "text": "The background of these button boxes is light blue. Button boxes having a white backgrounds as well as sunken are selected ones. " }, { "code": null, "e": 1904, "s": 1804, "text": " Code #2: Changing button boxes into standard radio buttons. For this remove indicatoron option. " }, { "code": null, "e": 1912, "s": 1904, "text": "Python3" }, { "code": "# Importing Tkinter modulefrom tkinter import *from tkinter.ttk import * # Creating master Tkinter windowmaster = Tk()master.geometry(\"175x175\") # Tkinter string variable# able to store any string valuev = StringVar(master, \"1\") # Dictionary to create multiple buttonsvalues = {\"RadioButton 1\" : \"1\", \"RadioButton 2\" : \"2\", \"RadioButton 3\" : \"3\", \"RadioButton 4\" : \"4\", \"RadioButton 5\" : \"5\"} # Loop is used to create multiple Radiobuttons# rather than creating each button separatelyfor (text, value) in values.items(): Radiobutton(master, text = text, variable = v, value = value).pack(side = TOP, ipady = 5) # Infinite loop can be terminated by# keyboard or mouse interrupt# or by any predefined function (destroy())mainloop()", "e": 2680, "s": 1912, "text": null }, { "code": null, "e": 2689, "s": 2680, "text": "Output: " }, { "code": null, "e": 2889, "s": 2691, "text": "These Radiobuttons are created using tkinter.ttk that is why background option is not available but we can use style class to do styling. Code #3: Adding Style to Radio Button using style class. " }, { "code": null, "e": 2897, "s": 2889, "text": "Python3" }, { "code": "# Importing Tkinter modulefrom tkinter import *from tkinter.ttk import * # Creating master Tkinter windowmaster = Tk()master.geometry('175x175') # Tkinter string variable# able to store any string valuev = StringVar(master, \"1\") # Style class to add style to Radiobutton# it can be used to style any ttk widgetstyle = Style(master)style.configure(\"TRadiobutton\", background = \"light green\", foreground = \"red\", font = (\"arial\", 10, \"bold\")) # Dictionary to create multiple buttonsvalues = {\"RadioButton 1\" : \"1\", \"RadioButton 2\" : \"2\", \"RadioButton 3\" : \"3\", \"RadioButton 4\" : \"4\", \"RadioButton 5\" : \"5\"} # Loop is used to create multiple Radiobuttons# rather than creating each button separatelyfor (text, value) in values.items(): Radiobutton(master, text = text, variable = v, value = value).pack(side = TOP, ipady = 5) # Infinite loop can be terminated by# keyboard or mouse interrupt# or by any predefined function (destroy())mainloop()", "e": 3908, "s": 2897, "text": null }, { "code": null, "e": 3917, "s": 3908, "text": "Output: " }, { "code": null, "e": 4136, "s": 3919, "text": "You may observe that font style is changed as well as background and foreground colors are also changed. Here, TRadiobutton is used in style class, it automatically applies styling to all the available Radiobuttons. " }, { "code": null, "e": 4150, "s": 4136, "text": "shubham_singh" }, { "code": null, "e": 4159, "s": 4150, "text": "abhigoya" }, { "code": null, "e": 4170, "s": 4159, "text": "Python-gui" }, { "code": null, "e": 4185, "s": 4170, "text": "Python-tkinter" }, { "code": null, "e": 4192, "s": 4185, "text": "Python" }, { "code": null, "e": 4290, "s": 4192, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4318, "s": 4290, "text": "Read JSON file using Python" }, { "code": null, "e": 4340, "s": 4318, "text": "Python map() function" }, { "code": null, "e": 4390, "s": 4340, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 4434, "s": 4390, "text": "How to get column names in Pandas dataframe" }, { "code": null, "e": 4476, "s": 4434, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 4498, "s": 4476, "text": "Enumerate() in Python" }, { "code": null, "e": 4533, "s": 4498, "text": "Read a file line by line in Python" }, { "code": null, "e": 4565, "s": 4533, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 4591, "s": 4565, "text": "Python String | replace()" } ]
JavaScript | Const
07 Dec, 2021 ES2015 (ES6) introduced const keyword to define a new variable. The difference in const variable declaration than others is that it cannot be reassigned. Properties: Cannot be reassigned. Block Scope It can be assign on the variable on declaration line. Primitive value. The property of a const object can be change but it cannot be change to reference to the new object The values inside the const array can be change, it can add new items to const arrays but it cannot reference to a new array. Re-declaring of a const variable inside different block scope is allowed. Cannot be Hoisted. Create only read only reference to value. Example 1: It describes that the const variable cannot be reassigned. <script type="text/javascript"> const x = 12; x = 13; x += 1;</script> Output: Uncaught TypeError: Assignment to constant variable. Example 2: It describes the const variable which contains the Block Scope. <script type="text/javascript"> const x = 22; { const x = 90; console.log(x); { const x = 77; console.log(x); } { const x = 45; console.log(x); } } console.log(x);</script> Output: 90 77 45 22 Example 3: It describes the const variable and assigned it after declaration. <script type="text/javascript"> const x; x = 12;</script> Output: Uncaught SyntaxError: Missing initializer in const declaration Example 4: It describes the const variable cannot be Hoisted. <script type="text/javascript"> x = 3; console.log(x); const x;</script> Output: Uncaught SyntaxError: Missing initializer in const declaration Example 5: It describes that the array values can be modified only reference to array cannot be change. <script type="text/javascript"> // Changing the content of array is // possible in cost array const arr1 = ["pankaj", "sumit", "chandan", "ajay"]; console.log(arr1.toString()); arr1[2] = "Narayan"; // possible console.log(arr1.toString());</script> Output: pankaj, sumit, chandan, ajay pankaj, sumit, Narayan, ajay Example 6: It describes that the object properties can be modified only reference to object cannot be changed. <script type="text/javascript"> const person = { first_name: "Pankaj", last_name: "Singh", Age: 20, About: "Web Developer and Competitive Programmer" }; console.log(person); // It is possible person.first_name = "Aryan"; person.last_name = "Yadav"; person.Age = 22; person.About = "Commerce undergraduate"; console.log(person); // it is not possible // const person={ // "first_name":"Aryan", // "last_name":"Yadav", // "Age":22, // "About":"Commerce undergraduate" // }</script> Output: Supported Browsers: chrome 21 and above Edge 12 and above Firefox 36 and above Internet Explorer 11 and above Opera 9 and above Safari 5.1 and above ysachin2314 javascript-basics Picked JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Roadmap to Learn JavaScript For Beginners Difference between var, let and const keywords in JavaScript Remove elements from a JavaScript Array Differences between Functional Components and Class Components in React Hide or show elements in HTML using display property Top 10 Projects For Beginners To Practice HTML and CSS Skills Installation of Node.js on Linux Roadmap to Learn JavaScript For Beginners Difference between var, let and const keywords in JavaScript How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 54, "s": 26, "text": "\n07 Dec, 2021" }, { "code": null, "e": 208, "s": 54, "text": "ES2015 (ES6) introduced const keyword to define a new variable. The difference in const variable declaration than others is that it cannot be reassigned." }, { "code": null, "e": 220, "s": 208, "text": "Properties:" }, { "code": null, "e": 242, "s": 220, "text": "Cannot be reassigned." }, { "code": null, "e": 254, "s": 242, "text": "Block Scope" }, { "code": null, "e": 308, "s": 254, "text": "It can be assign on the variable on declaration line." }, { "code": null, "e": 325, "s": 308, "text": "Primitive value." }, { "code": null, "e": 425, "s": 325, "text": "The property of a const object can be change but it cannot be change to reference to the new object" }, { "code": null, "e": 551, "s": 425, "text": "The values inside the const array can be change, it can add new items to const arrays but it cannot reference to a new array." }, { "code": null, "e": 625, "s": 551, "text": "Re-declaring of a const variable inside different block scope is allowed." }, { "code": null, "e": 644, "s": 625, "text": "Cannot be Hoisted." }, { "code": null, "e": 686, "s": 644, "text": "Create only read only reference to value." }, { "code": null, "e": 756, "s": 686, "text": "Example 1: It describes that the const variable cannot be reassigned." }, { "code": "<script type=\"text/javascript\"> const x = 12; x = 13; x += 1;</script> ", "e": 856, "s": 756, "text": null }, { "code": null, "e": 864, "s": 856, "text": "Output:" }, { "code": null, "e": 918, "s": 864, "text": "Uncaught TypeError: Assignment to constant variable.\n" }, { "code": null, "e": 993, "s": 918, "text": "Example 2: It describes the const variable which contains the Block Scope." }, { "code": "<script type=\"text/javascript\"> const x = 22; { const x = 90; console.log(x); { const x = 77; console.log(x); } { const x = 45; console.log(x); } } console.log(x);</script>", "e": 1267, "s": 993, "text": null }, { "code": null, "e": 1275, "s": 1267, "text": "Output:" }, { "code": null, "e": 1288, "s": 1275, "text": "90\n77\n45\n22\n" }, { "code": null, "e": 1366, "s": 1288, "text": "Example 3: It describes the const variable and assigned it after declaration." }, { "code": "<script type=\"text/javascript\"> const x; x = 12;</script>", "e": 1430, "s": 1366, "text": null }, { "code": null, "e": 1438, "s": 1430, "text": "Output:" }, { "code": null, "e": 1502, "s": 1438, "text": "Uncaught SyntaxError: Missing initializer in const declaration\n" }, { "code": null, "e": 1564, "s": 1502, "text": "Example 4: It describes the const variable cannot be Hoisted." }, { "code": "<script type=\"text/javascript\"> x = 3; console.log(x); const x;</script>", "e": 1646, "s": 1564, "text": null }, { "code": null, "e": 1654, "s": 1646, "text": "Output:" }, { "code": null, "e": 1718, "s": 1654, "text": "Uncaught SyntaxError: Missing initializer in const declaration\n" }, { "code": null, "e": 1822, "s": 1718, "text": "Example 5: It describes that the array values can be modified only reference to array cannot be change." }, { "code": "<script type=\"text/javascript\"> // Changing the content of array is // possible in cost array const arr1 = [\"pankaj\", \"sumit\", \"chandan\", \"ajay\"]; console.log(arr1.toString()); arr1[2] = \"Narayan\"; // possible console.log(arr1.toString());</script>", "e": 2109, "s": 1822, "text": null }, { "code": null, "e": 2117, "s": 2109, "text": "Output:" }, { "code": null, "e": 2176, "s": 2117, "text": "pankaj, sumit, chandan, ajay\npankaj, sumit, Narayan, ajay\n" }, { "code": null, "e": 2287, "s": 2176, "text": "Example 6: It describes that the object properties can be modified only reference to object cannot be changed." }, { "code": "<script type=\"text/javascript\"> const person = { first_name: \"Pankaj\", last_name: \"Singh\", Age: 20, About: \"Web Developer and Competitive Programmer\" }; console.log(person); // It is possible person.first_name = \"Aryan\"; person.last_name = \"Yadav\"; person.Age = 22; person.About = \"Commerce undergraduate\"; console.log(person); // it is not possible // const person={ // \"first_name\":\"Aryan\", // \"last_name\":\"Yadav\", // \"Age\":22, // \"About\":\"Commerce undergraduate\" // }</script>", "e": 2883, "s": 2287, "text": null }, { "code": null, "e": 2891, "s": 2883, "text": "Output:" }, { "code": null, "e": 2911, "s": 2891, "text": "Supported Browsers:" }, { "code": null, "e": 2931, "s": 2911, "text": "chrome 21 and above" }, { "code": null, "e": 2949, "s": 2931, "text": "Edge 12 and above" }, { "code": null, "e": 2970, "s": 2949, "text": "Firefox 36 and above" }, { "code": null, "e": 3001, "s": 2970, "text": "Internet Explorer 11 and above" }, { "code": null, "e": 3019, "s": 3001, "text": "Opera 9 and above" }, { "code": null, "e": 3040, "s": 3019, "text": "Safari 5.1 and above" }, { "code": null, "e": 3052, "s": 3040, "text": "ysachin2314" }, { "code": null, "e": 3070, "s": 3052, "text": "javascript-basics" }, { "code": null, "e": 3077, "s": 3070, "text": "Picked" }, { "code": null, "e": 3088, "s": 3077, "text": "JavaScript" }, { "code": null, "e": 3105, "s": 3088, "text": "Web Technologies" }, { "code": null, "e": 3203, "s": 3105, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3245, "s": 3203, "text": "Roadmap to Learn JavaScript For Beginners" }, { "code": null, "e": 3306, "s": 3245, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 3346, "s": 3306, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 3418, "s": 3346, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 3471, "s": 3418, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 3533, "s": 3471, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 3566, "s": 3533, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 3608, "s": 3566, "text": "Roadmap to Learn JavaScript For Beginners" }, { "code": null, "e": 3669, "s": 3608, "text": "Difference between var, let and const keywords in JavaScript" } ]
C++ Utility Library - make_pair Function
It constructs a pair object with its first element set to x and its second element set to y. Following is the declaration for std::make_pair function. template <class T1, class T2> pair<T1,T2> make_pair (T1 x, T2 y); template <class T1, class T2> pair<V1,V2> make_pair (T1&& x, T2&& y); x, y − These are two values. It returns a pair object whose elements first and second are set to x and y respectivelly. Basic guarantee − if the construction or assignment of type T throws. If either (or both) T1 or T2 is an rvalue reference type of a type supporting move semantics, its corresponding argument is modified. In below example explains about std::make_pair function. #include <utility> #include <iostream> int main () { std::pair <int,char> foo; std::pair <int,int> bar; foo = std::make_pair (1,'A'); bar = std::make_pair (100,3); std::cout << "foo: " << foo.first << ", " << foo.second << '\n'; std::cout << "bar: " << bar.first << ", " << bar.second << '\n'; return 0; } Let us compile and run the above program, this will produce the following result − foo: 1, A bar: 100, 3 Print Add Notes Bookmark this page
[ { "code": null, "e": 2696, "s": 2603, "text": "It constructs a pair object with its first element set to x and its second element set to y." }, { "code": null, "e": 2754, "s": 2696, "text": "Following is the declaration for std::make_pair function." }, { "code": null, "e": 2823, "s": 2754, "text": "template <class T1, class T2>\n pair<T1,T2> make_pair (T1 x, T2 y);" }, { "code": null, "e": 2897, "s": 2823, "text": "template <class T1, class T2>\n pair<V1,V2> make_pair (T1&& x, T2&& y); " }, { "code": null, "e": 2926, "s": 2897, "text": "x, y − These are two values." }, { "code": null, "e": 3017, "s": 2926, "text": "It returns a pair object whose elements first and second are set to x and y respectivelly." }, { "code": null, "e": 3087, "s": 3017, "text": "Basic guarantee − if the construction or assignment of type T throws." }, { "code": null, "e": 3221, "s": 3087, "text": "If either (or both) T1 or T2 is an rvalue reference type of a type supporting move semantics, its corresponding argument is modified." }, { "code": null, "e": 3278, "s": 3221, "text": "In below example explains about std::make_pair function." }, { "code": null, "e": 3609, "s": 3278, "text": "#include <utility>\n#include <iostream>\n\nint main () {\n std::pair <int,char> foo;\n std::pair <int,int> bar;\n\n foo = std::make_pair (1,'A');\n bar = std::make_pair (100,3);\n\n std::cout << \"foo: \" << foo.first << \", \" << foo.second << '\\n';\n std::cout << \"bar: \" << bar.first << \", \" << bar.second << '\\n';\n\n return 0;\n}" }, { "code": null, "e": 3692, "s": 3609, "text": "Let us compile and run the above program, this will produce the following result −" }, { "code": null, "e": 3715, "s": 3692, "text": "foo: 1, A\nbar: 100, 3\n" }, { "code": null, "e": 3722, "s": 3715, "text": " Print" }, { "code": null, "e": 3733, "s": 3722, "text": " Add Notes" } ]
Why is indentation important in Python?
Many a times it is required to treat more than one statements in a program as a block. Different programming languages use different techniques to define scope and extent of block of statements in constructs like class, function, conditional and loop. In C and C++ for example, statements inside curly brackets are treated as a block. Python uses uniform indentation to mark block of statements. Before beginning of block symbol : is used. First and subsequent statements in block are written by leaving additional (but uniform) whitespace (called indent) . In order to signal end of block, the whitespace is dedented. Following example illustrates the use of indents in Python: num = int(input("enter number")) if num%2 == 0: if num%3 == 0: print ("Divisible by 3 and 2") else: print ("divisible by 2 not divisible by 3") else: if num%3 == 0: print ("divisible by 3 not divisible by 2") else: print ("not Divisible by 2 not divisible by 3") Note: It is important to ensure that all statements in a block at particular level should have same indentation.
[ { "code": null, "e": 1458, "s": 1062, "text": "Many a times it is required to treat more than one statements in a program as a block. Different programming languages use different techniques to define scope and extent of block of statements in constructs like class, function, conditional and loop. In C and C++ for example, statements inside curly brackets are treated as a block. Python uses uniform indentation to mark block of statements." }, { "code": null, "e": 1741, "s": 1458, "text": "Before beginning of block symbol : is used. First and subsequent statements in block are written by leaving additional (but uniform) whitespace (called indent) . In order to signal end of block, the whitespace is dedented. Following example illustrates the use of indents in Python:" }, { "code": null, "e": 2041, "s": 1741, "text": "num = int(input(\"enter number\"))\nif num%2 == 0:\n if num%3 == 0:\n print (\"Divisible by 3 and 2\")\n else:\n print (\"divisible by 2 not divisible by 3\")\nelse:\n if num%3 == 0:\n print (\"divisible by 3 not divisible by 2\")\n else:\n print (\"not Divisible by 2 not divisible by 3\")" }, { "code": null, "e": 2154, "s": 2041, "text": "Note: It is important to ensure that all statements in a block at particular level should have same indentation." } ]
ES6 - Variables
A variable, by definition, is “a named space in the memory” that stores values. In other words, it acts as a container for values in a program. Variable names are called identifiers. Following are the naming rules for an identifier − Identifiers cannot be keywords. Identifiers cannot be keywords. Identifiers can contain alphabets and numbers. Identifiers can contain alphabets and numbers. Identifiers cannot contain spaces and special characters, except the underscore (_) and the dollar ($) sign. Identifiers cannot contain spaces and special characters, except the underscore (_) and the dollar ($) sign. Variable names cannot begin with a number. Variable names cannot begin with a number. A variable must be declared before it is used. ES5 syntax used the var keyword to achieve the same. The ES5 syntax for declaring a variable is as follows. //Declaration using var keyword var variable_name ES6 introduces the following variable declaration syntax − Using the let. Using the const. Variable initialization refers to the process of storing a value in the variable. A variable may be initialized either at the time of its declaration or at a later point in time. The traditional ES5 type syntax for declaring and initializing a variable is as follows − //Declaration using var keyword var variable_name = value var name = "Tom" console.log("The value in the variable is: "+name) The above example declares a variable and prints its value. The following output is displayed on successful execution. The value in the variable is Tom JavaScript is an un-typed language. This means that a JavaScript variable can hold a value of any data type. Unlike many other languages, you don't have to tell JavaScript during variable declaration what type of value the variable will hold. The value type of a variable can change during the execution of a program and JavaScript takes care of it automatically. This feature is termed as dynamic typing. The scope of a variable is the region of your program in which it is defined. Traditionally, JavaScript defines only two scopes-global and local. Global Scope − A variable with global scope can be accessed from within any part of the JavaScript code. Global Scope − A variable with global scope can be accessed from within any part of the JavaScript code. Local Scope − A variable with a local scope can be accessed from within a function where it is declared. Local Scope − A variable with a local scope can be accessed from within a function where it is declared. The following example declares two variables by the name num - one outside the function (global scope) and the other within the function (local scope). var num = 10 function test() { var num = 100 console.log("value of num in test() "+num) } console.log("value of num outside test() "+num) test() The variable when referred to within the function displays the value of the locally scoped variable. However, the variable num when accessed outside the function returns the globally scoped instance. The following output is displayed on successful execution. value of num outside test() 10 value of num in test() 100 ES6 defines a new variable scope - The Block scope. The block scope restricts a variable’s access to the block in which it is declared. The var keyword assigns a function scope to the variable. Unlike the var keyword, the let keyword allows the script to restrict access to the variable to the nearest enclosing block. "use strict" function test() { var num = 100 console.log("value of num in test() "+num) { console.log("Inner Block begins") let num = 200 console.log("value of num : "+num) } } test() The script declares a variable num within the local scope of a function and re-declares it within a block using the let keyword. The value of the locally scoped variable is printed when the variable is accessed outside the inner block, while the block scoped variable is referred to within the inner block. Note − The strict mode is a way to opt in to a restricted variant of JavaScript. The following output is displayed on successful execution. value of num in test() 100 Inner Block begins value of num : 200 var no = 10; var no = 20; console.log(no); The following output is displayed on successful execution of the above code. 20 Let us re-write the same code using the let keyword. let no = 10; let no = 20; console.log(no); The above code will throw an error: Identifier 'no' has already been declared. Any variable declared using the let keyword is assigned the block scope. If we try to declare a let variable twice within the same block, it will throw an error. Consider the following example − <script> let balance = 5000 // number type console.log(typeof balance) let balance = {message:"hello"} // changing number to object type console.log(typeof balance) </script> The above code will result in the following error − Uncaught SyntaxError: Identifier 'balance' has already been declared However, the same let variable can be used in different block level scopes without any syntax errors. <script> let count = 100 for (let count = 1;count <= 10;count++){ //inside for loop brackets ,count value starts from 1 console.log("count value inside loop is ",count); } //outside for loop brackets ,count value is 100 console.log("count value after loop is",count); if(count == 100){ //inside if brackets ,count value is 50 let count = 50; console.log("count inside if block",count); } console.log(count); </script> The output of the above code will be as follows − count value inside loop is 1 count value inside loop is 2 count value inside loop is 3 count value inside loop is 4 count value inside loop is 5 count value inside loop is 6 count value inside loop is 7 count value inside loop is 8 count value inside loop is 9 count value inside loop is 10 count value after loop is 100 count inside if block 50 100 The const declaration creates a read-only reference to a value. It does not mean the value it holds is immutable, just that the variable identifier cannot be reassigned. Constants are block-scoped, much like variables defined using the let statement. The value of a constant cannot change through re-assignment, and it can't be re-declared. The following rules hold true for a variable declared using the const keyword − Constants cannot be reassigned a value. A constant cannot be re-declared. A constant requires an initializer. This means constants must be initialized during its declaration. The value assigned to a const variable is mutable. const x = 10 x = 12 // will result in an error!! The above code will return an error since constants cannot be reassigned a value. Constants variable are immutable. Unlike variables declared using let keyword, constants are immutable. This means its value cannot be changed. For example, if we try to change value of the constant variable, an error will be displayed. <script> let income = 100000 const INTEREST_RATE = 0.08 income += 50000 // mutable console.log("changed income value is ",income) INTEREST_RATE += 0.01 console.log("changed rate is ",INTEREST_RATE) //Error: not mutable </script> The output of the above code will be as follows − changed income value is 150000 Uncaught TypeError: Assignment to constant variable The following example shows how to create an immutable array. New elements can be added to the array. However, reinitializing the array will result in an error as shown below − <script> const DEPT_NOS = [10,20,30,50] DEPT_NOS.push(40) console.log('dept numbers is ',DEPT_NOS) const EMP_IDS = [1001,1002,1003] console.log('employee ids',EMP_IDS) //re assigning variable employee ids EMP_IDS = [2001,2002,2003] console.log('employee ids after changing',EMP_IDS) </script> The output of the above code will be as shown below − dept numbers is (5) [10, 20, 30, 50, 40] employee ids (3) [1001, 1002, 1003] Uncaught TypeError: Assignment to constant variable. Prior to ES6, the var keyword was used to declare a variable in JavaScript. Variables declared using var do not support block level scope. This means if a variable is declared in a loop or if block it can be accessed outside the loop or the if block. This is because the variables declared using the var keyword support hoisting. Variable hoisting allows the use of a variable in a JavaScript program, even before it is declared. Such variables will be initialized to undefined by default. JavaScript runtime will scan for variable declarations and put them to the top of the function or script. Variables declared with var keyword get hoisted to the top. Consider the following example − <script> variable company is hoisted to top , var company = undefined console.log(company); // using variable before declaring var company = "TutorialsPoint"; // declare and initialized here console.log(company); </script> The output of the above code will be as shown below − undefined TutorialsPoint The block scope restricts a variable’s access to the block in which it is declared. The var keyword assigns a function scope to the variable. Variables declared using the var keyword do not have a block scope. Consider the following example − <script> //hoisted to top ; var i = undefined for (var i = 1;i <= 5;i++){ console.log(i); } console.log("after the loop i value is "+i); </script> The output of the above code will be as follows − 1 2 3 4 5 after the loop i value is 6 The variable i is declared inside the for loop using the var keyword. The variable i is accessible outside the loop. However, at times, there might be a need to restrict a variable's access within a block. We cannot use the var keyword in this scenario. ES6 introduces the let keyword to overcome this limitation. If we declare the same variable twice using the var keyword within a block, the compiler will not throw an error. However, this may lead to unexpected logical errors at runtime. <script> var balance = 5000 console.log(typeof balance) var balance = {message:"hello"} console.log(typeof balance) </script> The output of the above code is as shown below − number object 32 Lectures 3.5 hours Sharad Kumar 40 Lectures 5 hours Richa Maheshwari 16 Lectures 1 hours Anadi Sharma 50 Lectures 6.5 hours Gowthami Swarna 14 Lectures 1 hours Deepti Trivedi 31 Lectures 1.5 hours Shweta Print Add Notes Bookmark this page
[ { "code": null, "e": 2511, "s": 2277, "text": "A variable, by definition, is “a named space in the memory” that stores values. In other words, it acts as a container for values in a program. Variable names are called identifiers. Following are the naming rules for an identifier −" }, { "code": null, "e": 2543, "s": 2511, "text": "Identifiers cannot be keywords." }, { "code": null, "e": 2575, "s": 2543, "text": "Identifiers cannot be keywords." }, { "code": null, "e": 2622, "s": 2575, "text": "Identifiers can contain alphabets and numbers." }, { "code": null, "e": 2669, "s": 2622, "text": "Identifiers can contain alphabets and numbers." }, { "code": null, "e": 2778, "s": 2669, "text": "Identifiers cannot contain spaces and special characters, except the underscore (_) and the dollar ($) sign." }, { "code": null, "e": 2887, "s": 2778, "text": "Identifiers cannot contain spaces and special characters, except the underscore (_) and the dollar ($) sign." }, { "code": null, "e": 2930, "s": 2887, "text": "Variable names cannot begin with a number." }, { "code": null, "e": 2973, "s": 2930, "text": "Variable names cannot begin with a number." }, { "code": null, "e": 3128, "s": 2973, "text": "A variable must be declared before it is used. ES5 syntax used the var keyword to achieve the same. The ES5 syntax for declaring a variable is as follows." }, { "code": null, "e": 3181, "s": 3128, "text": "//Declaration using var keyword \nvar variable_name\n" }, { "code": null, "e": 3240, "s": 3181, "text": "ES6 introduces the following variable declaration syntax −" }, { "code": null, "e": 3255, "s": 3240, "text": "Using the let." }, { "code": null, "e": 3272, "s": 3255, "text": "Using the const." }, { "code": null, "e": 3451, "s": 3272, "text": "Variable initialization refers to the process of storing a value in the variable. A variable may be initialized either at the time of its declaration or at a later point in time." }, { "code": null, "e": 3541, "s": 3451, "text": "The traditional ES5 type syntax for declaring and initializing a variable is as follows −" }, { "code": null, "e": 3601, "s": 3541, "text": "//Declaration using var keyword \nvar variable_name = value\n" }, { "code": null, "e": 3670, "s": 3601, "text": "var name = \"Tom\" \nconsole.log(\"The value in the variable is: \"+name)" }, { "code": null, "e": 3730, "s": 3670, "text": "The above example declares a variable and prints its value." }, { "code": null, "e": 3789, "s": 3730, "text": "The following output is displayed on successful execution." }, { "code": null, "e": 3823, "s": 3789, "text": "The value in the variable is Tom\n" }, { "code": null, "e": 4229, "s": 3823, "text": "JavaScript is an un-typed language. This means that a JavaScript variable can hold a value of any data type. Unlike many other languages, you don't have to tell JavaScript during variable declaration what type of value the variable will hold. The value type of a variable can change during the execution of a program and JavaScript takes care of it automatically. This feature is termed as dynamic typing." }, { "code": null, "e": 4375, "s": 4229, "text": "The scope of a variable is the region of your program in which it is defined. Traditionally, JavaScript defines only two scopes-global and local." }, { "code": null, "e": 4480, "s": 4375, "text": "Global Scope − A variable with global scope can be accessed from within any part of the JavaScript code." }, { "code": null, "e": 4585, "s": 4480, "text": "Global Scope − A variable with global scope can be accessed from within any part of the JavaScript code." }, { "code": null, "e": 4690, "s": 4585, "text": "Local Scope − A variable with a local scope can be accessed from within a function where it is declared." }, { "code": null, "e": 4795, "s": 4690, "text": "Local Scope − A variable with a local scope can be accessed from within a function where it is declared." }, { "code": null, "e": 4947, "s": 4795, "text": "The following example declares two variables by the name num - one outside the function (global scope) and the other within the function (local scope)." }, { "code": null, "e": 5104, "s": 4947, "text": "var num = 10 \nfunction test() { \n var num = 100 \n console.log(\"value of num in test() \"+num) \n} \nconsole.log(\"value of num outside test() \"+num) \ntest()" }, { "code": null, "e": 5304, "s": 5104, "text": "The variable when referred to within the function displays the value of the locally scoped variable. However, the variable num when accessed outside the function returns the globally scoped instance." }, { "code": null, "e": 5363, "s": 5304, "text": "The following output is displayed on successful execution." }, { "code": null, "e": 5422, "s": 5363, "text": "value of num outside test() 10\nvalue of num in test() 100\n" }, { "code": null, "e": 5474, "s": 5422, "text": "ES6 defines a new variable scope - The Block scope." }, { "code": null, "e": 5741, "s": 5474, "text": "The block scope restricts a variable’s access to the block in which it is declared. The var keyword assigns a function scope to the variable. Unlike the var keyword, the let keyword allows the script to restrict access to the variable to the nearest enclosing block." }, { "code": null, "e": 5962, "s": 5741, "text": "\"use strict\" \nfunction test() { \n var num = 100 \n console.log(\"value of num in test() \"+num) { \n console.log(\"Inner Block begins\") \n let num = 200 \n console.log(\"value of num : \"+num) \n } \n} \ntest()" }, { "code": null, "e": 6269, "s": 5962, "text": "The script declares a variable num within the local scope of a function and re-declares it within a block using the let keyword. The value of the locally scoped variable is printed when the variable is accessed outside the inner block, while the block scoped variable is referred to within the inner block." }, { "code": null, "e": 6350, "s": 6269, "text": "Note − The strict mode is a way to opt in to a restricted variant of JavaScript." }, { "code": null, "e": 6409, "s": 6350, "text": "The following output is displayed on successful execution." }, { "code": null, "e": 6477, "s": 6409, "text": "value of num in test() 100 \nInner Block begins \nvalue of num : 200\n" }, { "code": null, "e": 6522, "s": 6477, "text": "var no = 10; \nvar no = 20; \nconsole.log(no);" }, { "code": null, "e": 6599, "s": 6522, "text": "The following output is displayed on successful execution of the above code." }, { "code": null, "e": 6603, "s": 6599, "text": "20\n" }, { "code": null, "e": 6656, "s": 6603, "text": "Let us re-write the same code using the let keyword." }, { "code": null, "e": 6702, "s": 6656, "text": "let no = 10; \nlet no = 20; \nconsole.log(no);\n" }, { "code": null, "e": 6854, "s": 6702, "text": "The above code will throw an error: Identifier 'no' has already been declared. Any variable declared using the let keyword is assigned the block scope." }, { "code": null, "e": 6976, "s": 6854, "text": "If we try to declare a let variable twice within the same block, it will throw an error. Consider the following example −" }, { "code": null, "e": 7163, "s": 6976, "text": "<script>\n let balance = 5000 // number type\n console.log(typeof balance)\n let balance = {message:\"hello\"} // changing number to object type\n console.log(typeof balance)\n</script>" }, { "code": null, "e": 7215, "s": 7163, "text": "The above code will result in the following error −" }, { "code": null, "e": 7285, "s": 7215, "text": "Uncaught SyntaxError: Identifier 'balance' has already been declared\n" }, { "code": null, "e": 7387, "s": 7285, "text": "However, the same let variable can be used in different block level scopes without any syntax errors." }, { "code": null, "e": 7860, "s": 7387, "text": "<script>\n let count = 100\n for (let count = 1;count <= 10;count++){\n //inside for loop brackets ,count value starts from 1\n console.log(\"count value inside loop is \",count);\n }\n //outside for loop brackets ,count value is 100\n console.log(\"count value after loop is\",count);\n\n if(count == 100){\n //inside if brackets ,count value is 50\n let count = 50;\n console.log(\"count inside if block\",count);\n }\n console.log(count);\n</script>" }, { "code": null, "e": 7910, "s": 7860, "text": "The output of the above code will be as follows −" }, { "code": null, "e": 8261, "s": 7910, "text": "count value inside loop is 1\ncount value inside loop is 2\ncount value inside loop is 3\ncount value inside loop is 4\ncount value inside loop is 5\ncount value inside loop is 6\ncount value inside loop is 7\ncount value inside loop is 8\ncount value inside loop is 9\ncount value inside loop is 10\ncount value after loop is 100\ncount inside if block 50\n100\n" }, { "code": null, "e": 8602, "s": 8261, "text": "The const declaration creates a read-only reference to a value. It does not mean the value it holds is immutable, just that the variable identifier cannot be reassigned. Constants are block-scoped, much like variables defined using the let statement. The value of a constant cannot change through re-assignment, and it can't be re-declared." }, { "code": null, "e": 8682, "s": 8602, "text": "The following rules hold true for a variable declared using the const keyword −" }, { "code": null, "e": 8722, "s": 8682, "text": "Constants cannot be reassigned a value." }, { "code": null, "e": 8756, "s": 8722, "text": "A constant cannot be re-declared." }, { "code": null, "e": 8857, "s": 8756, "text": "A constant requires an initializer. This means constants must be initialized during its declaration." }, { "code": null, "e": 8908, "s": 8857, "text": "The value assigned to a const variable is mutable." }, { "code": null, "e": 8958, "s": 8908, "text": "const x = 10\nx = 12 // will result in an error!!\n" }, { "code": null, "e": 9074, "s": 8958, "text": "The above code will return an error since constants cannot be reassigned a value. Constants variable are immutable." }, { "code": null, "e": 9277, "s": 9074, "text": "Unlike variables declared using let keyword, constants are immutable. This means its value cannot be changed. For example, if we try to change value of the constant variable, an error will be displayed." }, { "code": null, "e": 9524, "s": 9277, "text": "<script>\n let income = 100000\n const INTEREST_RATE = 0.08\n income += 50000 // mutable\n console.log(\"changed income value is \",income)\n INTEREST_RATE += 0.01\n console.log(\"changed rate is \",INTEREST_RATE) //Error: not mutable\n</script>" }, { "code": null, "e": 9574, "s": 9524, "text": "The output of the above code will be as follows −" }, { "code": null, "e": 9657, "s": 9574, "text": "changed income value is 150000\nUncaught TypeError: Assignment to constant variable" }, { "code": null, "e": 9834, "s": 9657, "text": "The following example shows how to create an immutable array. New elements can be added to the array. However, reinitializing the array will result in an error as shown below −" }, { "code": null, "e": 10152, "s": 9834, "text": "<script>\n const DEPT_NOS = [10,20,30,50]\n DEPT_NOS.push(40)\n console.log('dept numbers is ',DEPT_NOS)\n\n const EMP_IDS = [1001,1002,1003]\n console.log('employee ids',EMP_IDS)\n //re assigning variable employee ids\n EMP_IDS = [2001,2002,2003]\n console.log('employee ids after changing',EMP_IDS)\n</script>" }, { "code": null, "e": 10206, "s": 10152, "text": "The output of the above code will be as shown below −" }, { "code": null, "e": 10337, "s": 10206, "text": "dept numbers is (5) [10, 20, 30, 50, 40]\nemployee ids (3) [1001, 1002, 1003]\nUncaught TypeError: Assignment to constant variable.\n" }, { "code": null, "e": 10667, "s": 10337, "text": "Prior to ES6, the var keyword was used to declare a variable in JavaScript. Variables declared using var do not support block level scope. This means if a variable is declared in a loop or if block it can be accessed outside the loop or the if block. This is because the variables declared using the var keyword support hoisting." }, { "code": null, "e": 11026, "s": 10667, "text": "Variable hoisting allows the use of a variable in a JavaScript program, even before it is declared. Such variables will be initialized to undefined by default. JavaScript runtime will scan for variable declarations and put them to the top of the function or script. Variables declared with var keyword get hoisted to the top. Consider the following example −" }, { "code": null, "e": 11261, "s": 11026, "text": "<script>\n variable company is hoisted to top , var company = undefined\n console.log(company); // using variable before declaring\n var company = \"TutorialsPoint\"; // declare and initialized here\n console.log(company);\n</script>" }, { "code": null, "e": 11315, "s": 11261, "text": "The output of the above code will be as shown below −" }, { "code": null, "e": 11341, "s": 11315, "text": "undefined\nTutorialsPoint\n" }, { "code": null, "e": 11584, "s": 11341, "text": "The block scope restricts a variable’s access to the block in which it is declared. The var keyword assigns a function scope to the variable. Variables declared using the var keyword do not have a block scope. Consider the following example −" }, { "code": null, "e": 11749, "s": 11584, "text": "<script>\n //hoisted to top ; var i = undefined\n for (var i = 1;i <= 5;i++){\n console.log(i);\n }\n console.log(\"after the loop i value is \"+i);\n</script>" }, { "code": null, "e": 11799, "s": 11749, "text": "The output of the above code will be as follows −" }, { "code": null, "e": 11838, "s": 11799, "text": "1\n2\n3\n4\n5\nafter the loop i value is 6\n" }, { "code": null, "e": 12152, "s": 11838, "text": "The variable i is declared inside the for loop using the var keyword. The variable i is accessible outside the loop. However, at times, there might be a need to restrict a variable's access within a block. We cannot use the var keyword in this scenario. ES6 introduces the let keyword to overcome this limitation." }, { "code": null, "e": 12330, "s": 12152, "text": "If we declare the same variable twice using the var keyword within a block, the compiler will not throw an error. However, this may lead to unexpected logical errors at runtime." }, { "code": null, "e": 12468, "s": 12330, "text": "<script>\n var balance = 5000\n console.log(typeof balance)\n var balance = {message:\"hello\"}\n console.log(typeof balance)\n</script>" }, { "code": null, "e": 12517, "s": 12468, "text": "The output of the above code is as shown below −" }, { "code": null, "e": 12532, "s": 12517, "text": "number\nobject\n" }, { "code": null, "e": 12567, "s": 12532, "text": "\n 32 Lectures \n 3.5 hours \n" }, { "code": null, "e": 12581, "s": 12567, "text": " Sharad Kumar" }, { "code": null, "e": 12614, "s": 12581, "text": "\n 40 Lectures \n 5 hours \n" }, { "code": null, "e": 12632, "s": 12614, "text": " Richa Maheshwari" }, { "code": null, "e": 12665, "s": 12632, "text": "\n 16 Lectures \n 1 hours \n" }, { "code": null, "e": 12679, "s": 12665, "text": " Anadi Sharma" }, { "code": null, "e": 12714, "s": 12679, "text": "\n 50 Lectures \n 6.5 hours \n" }, { "code": null, "e": 12731, "s": 12714, "text": " Gowthami Swarna" }, { "code": null, "e": 12764, "s": 12731, "text": "\n 14 Lectures \n 1 hours \n" }, { "code": null, "e": 12780, "s": 12764, "text": " Deepti Trivedi" }, { "code": null, "e": 12815, "s": 12780, "text": "\n 31 Lectures \n 1.5 hours \n" }, { "code": null, "e": 12823, "s": 12815, "text": " Shweta" }, { "code": null, "e": 12830, "s": 12823, "text": " Print" }, { "code": null, "e": 12841, "s": 12830, "text": " Add Notes" } ]
HBase - Scan
The scan command is used to view the data in HTable. Using the scan command, you can get the table data. Its syntax is as follows: scan ‘<table name>’ The following example shows how to read data from a table using the scan command. Here we are reading the emp table. hbase(main):010:0> scan 'emp' ROW COLUMN + CELL 1 column = personal data:city, timestamp = 1417521848375, value = hyderabad 1 column = personal data:name, timestamp = 1417521785385, value = ramu 1 column = professional data:designation, timestamp = 1417585277,value = manager 1 column = professional data:salary, timestamp = 1417521903862, value = 50000 1 row(s) in 0.0370 seconds The complete program to scan the entire table data using java API is as follows. import java.io.IOException; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.HBaseConfiguration; import org.apache.hadoop.hbase.util.Bytes; import org.apache.hadoop.hbase.client.HTable; import org.apache.hadoop.hbase.client.Result; import org.apache.hadoop.hbase.client.ResultScanner; import org.apache.hadoop.hbase.client.Scan; public class ScanTable{ public static void main(String args[]) throws IOException{ // Instantiating Configuration class Configuration config = HBaseConfiguration.create(); // Instantiating HTable class HTable table = new HTable(config, "emp"); // Instantiating the Scan class Scan scan = new Scan(); // Scanning the required columns scan.addColumn(Bytes.toBytes("personal"), Bytes.toBytes("name")); scan.addColumn(Bytes.toBytes("personal"), Bytes.toBytes("city")); // Getting the scan result ResultScanner scanner = table.getScanner(scan); // Reading values from scan result for (Result result = scanner.next(); result != null; result = scanner.next()) System.out.println("Found row : " + result); //closing the scanner scanner.close(); } } Compile and execute the above program as shown below. $javac ScanTable.java $java ScanTable The following should be the output: Found row : keyvalues={row1/personal:city/1418275612888/Put/vlen=5/mvcc=0, row1/personal:name/1418035791555/Put/vlen=4/mvcc=0} Print Add Notes Bookmark this page
[ { "code": null, "e": 2168, "s": 2037, "text": "The scan command is used to view the data in HTable. Using the scan command, you can get the table data. Its syntax is as follows:" }, { "code": null, "e": 2190, "s": 2168, "text": "scan ‘<table name>’ \n" }, { "code": null, "e": 2307, "s": 2190, "text": "The following example shows how to read data from a table using the scan command. Here we are reading the emp table." }, { "code": null, "e": 2721, "s": 2307, "text": "hbase(main):010:0> scan 'emp'\n\nROW COLUMN + CELL\n\n1 column = personal data:city, timestamp = 1417521848375, value = hyderabad\n \n1 column = personal data:name, timestamp = 1417521785385, value = ramu\n\n1 column = professional data:designation, timestamp = 1417585277,value = manager\n\n1 column = professional data:salary, timestamp = 1417521903862, value = 50000\n\n1 row(s) in 0.0370 seconds" }, { "code": null, "e": 2802, "s": 2721, "text": "The complete program to scan the entire table data using java API is as follows." }, { "code": null, "e": 4014, "s": 2802, "text": "import java.io.IOException;\n\nimport org.apache.hadoop.conf.Configuration;\n\nimport org.apache.hadoop.hbase.HBaseConfiguration;\nimport org.apache.hadoop.hbase.util.Bytes;\n\nimport org.apache.hadoop.hbase.client.HTable;\nimport org.apache.hadoop.hbase.client.Result;\nimport org.apache.hadoop.hbase.client.ResultScanner;\nimport org.apache.hadoop.hbase.client.Scan;\n\n\npublic class ScanTable{\n\n public static void main(String args[]) throws IOException{\n\n // Instantiating Configuration class\n Configuration config = HBaseConfiguration.create();\n\n // Instantiating HTable class\n HTable table = new HTable(config, \"emp\");\n\n // Instantiating the Scan class\n Scan scan = new Scan();\n\n // Scanning the required columns\n scan.addColumn(Bytes.toBytes(\"personal\"), Bytes.toBytes(\"name\"));\n scan.addColumn(Bytes.toBytes(\"personal\"), Bytes.toBytes(\"city\"));\n\n // Getting the scan result\n ResultScanner scanner = table.getScanner(scan);\n\n // Reading values from scan result\n for (Result result = scanner.next(); result != null; result = scanner.next())\n\n System.out.println(\"Found row : \" + result);\n //closing the scanner\n scanner.close();\n }\n}" }, { "code": null, "e": 4068, "s": 4014, "text": "Compile and execute the above program as shown below." }, { "code": null, "e": 4108, "s": 4068, "text": "$javac ScanTable.java\n$java ScanTable \n" }, { "code": null, "e": 4144, "s": 4108, "text": "The following should be the output:" }, { "code": null, "e": 4272, "s": 4144, "text": "Found row :\nkeyvalues={row1/personal:city/1418275612888/Put/vlen=5/mvcc=0,\nrow1/personal:name/1418035791555/Put/vlen=4/mvcc=0}\n" }, { "code": null, "e": 4279, "s": 4272, "text": " Print" }, { "code": null, "e": 4290, "s": 4279, "text": " Add Notes" } ]
Single level inheritance in Java
Single Level inheritance - A class inherits properties from a single class. For example, Class B inherits Class A. Live Demo class Shape { public void display() { System.out.println("Inside display"); } } class Rectangle extends Shape { public void area() { System.out.println("Inside area"); } } public class Tester { public static void main(String[] arguments) { Rectangle rect = new Rectangle(); rect.display(); rect.area(); } } Inside display Inside area Here Rectangle class inherits Shape class and can execute two methods, display() and area() as shown.
[ { "code": null, "e": 1177, "s": 1062, "text": "Single Level inheritance - A class inherits properties from a single class. For example, Class B inherits Class A." }, { "code": null, "e": 1188, "s": 1177, "text": " Live Demo" }, { "code": null, "e": 1543, "s": 1188, "text": "class Shape {\n public void display() {\n System.out.println(\"Inside display\");\n }\n}\nclass Rectangle extends Shape {\n public void area() {\n System.out.println(\"Inside area\");\n }\n}\npublic class Tester {\n public static void main(String[] arguments) {\n Rectangle rect = new Rectangle();\n rect.display();\n rect.area();\n }\n}" }, { "code": null, "e": 1570, "s": 1543, "text": "Inside display\nInside area" }, { "code": null, "e": 1672, "s": 1570, "text": "Here Rectangle class inherits Shape class and can execute two methods, display() and area() as shown." } ]
PHP $_FILES
The global predefined variable $_FILES is an associative array containing items uploaded via HTTP POST method. Uploading a file requires HTTP POST method form with enctype attribute set to multipart/form-data. $HTTP_POST_FILES also contains the same information, but is not a superglobal, and now been deprecated The _FILES array contains following properties − $_FILES['file']['name'] - The original name of the file to be uploaded. $_FILES['file']['type'] - The mime type of the file. $_FILES['file']['size'] - The size, in bytes, of the uploaded file. $_FILES['file']['tmp_name'] - The temporary filename of the file in which the uploaded file was stored on the server. $_FILES['file']['error'] - The error code associated with this file upload. Following test.html contains a HTML form whose enctype is set to multiform/form-data. It also has an input file element which presents a button on the form for the user to select file to be uploaded. <form action="testscript.php" method="POST" enctype="multipart/form-data"> <input type="file" name="file"> <input type ="submit" value="submit"> </form> The PHP script is as follows: <?php echo "Filename: " . $_FILES['file']['name']."<br>"; echo "Type : " . $_FILES['file']['type'] ."<br>"; echo "Size : " . $_FILES['file']['size'] ."<br>"; echo "Temp name: " . $_FILES['file']['tmp_name'] ."<br>"; echo "Error : " . $_FILES['file']['error'] . "<br>"; ?> This will produce following result − Filename: hello.html Type : text/html Size : 56 Temp name: C:\xampp\tmp\php32CE.tmp Error : 0
[ { "code": null, "e": 1272, "s": 1062, "text": "The global predefined variable $_FILES is an associative array containing items uploaded via HTTP POST method. Uploading a file requires HTTP POST method form with enctype attribute set to multipart/form-data." }, { "code": null, "e": 1375, "s": 1272, "text": "$HTTP_POST_FILES also contains the same information, but is not a superglobal, and now been deprecated" }, { "code": null, "e": 1424, "s": 1375, "text": "The _FILES array contains following properties −" }, { "code": null, "e": 1496, "s": 1424, "text": "$_FILES['file']['name'] - The original name of the file to be uploaded." }, { "code": null, "e": 1549, "s": 1496, "text": "$_FILES['file']['type'] - The mime type of the file." }, { "code": null, "e": 1617, "s": 1549, "text": "$_FILES['file']['size'] - The size, in bytes, of the uploaded file." }, { "code": null, "e": 1735, "s": 1617, "text": "$_FILES['file']['tmp_name'] - The temporary filename of the file in which the uploaded file was stored on the server." }, { "code": null, "e": 1811, "s": 1735, "text": "$_FILES['file']['error'] - The error code associated with this file upload." }, { "code": null, "e": 2011, "s": 1811, "text": "Following test.html contains a HTML form whose enctype is set to multiform/form-data. It also has an input file element which presents a button on the form for the user to select file to be uploaded." }, { "code": null, "e": 2170, "s": 2011, "text": "<form action=\"testscript.php\" method=\"POST\" enctype=\"multipart/form-data\">\n <input type=\"file\" name=\"file\">\n <input type =\"submit\" value=\"submit\">\n</form>" }, { "code": null, "e": 2200, "s": 2170, "text": "The PHP script is as follows:" }, { "code": null, "e": 2472, "s": 2200, "text": "<?php\necho \"Filename: \" . $_FILES['file']['name'].\"<br>\";\necho \"Type : \" . $_FILES['file']['type'] .\"<br>\";\necho \"Size : \" . $_FILES['file']['size'] .\"<br>\";\necho \"Temp name: \" . $_FILES['file']['tmp_name'] .\"<br>\";\necho \"Error : \" . $_FILES['file']['error'] . \"<br>\";\n?>" }, { "code": null, "e": 2509, "s": 2472, "text": "This will produce following result −" }, { "code": null, "e": 2603, "s": 2509, "text": "Filename: hello.html\nType : text/html\nSize : 56\nTemp name: C:\\xampp\\tmp\\php32CE.tmp\nError : 0" } ]
How to detect integer overflow in C/C++?
The only safe way is to check for overflow before it occurs. There are some hacky ways of checking for integer overflow though. So if you're aiming for detecting overflow in unsigned int addition, you can check if the result is actually lesser than either values added. So for example, unsigned int x, y; unsigned int value = x + y; bool overflow = value < x; // Alternatively "value < y" should also work This is because if x and y are both unsigned ints, if added and they overflow, their values can't be greater than either of them as it would need to be greater than max possible unsigned int to be able to wrap around and get ahead of these values. Another way is to try and access the Overflow flag in your CPU. Some compilers provide access to it which you could then test but this isn't standard.
[ { "code": null, "e": 1348, "s": 1062, "text": "The only safe way is to check for overflow before it occurs. There are some hacky ways of checking for integer overflow though. So if you're aiming for detecting overflow in unsigned int addition, you can check if the result is actually lesser than either values added. So for example," }, { "code": null, "e": 1468, "s": 1348, "text": "unsigned int x, y;\nunsigned int value = x + y;\nbool overflow = value < x; // Alternatively \"value < y\" should also work" }, { "code": null, "e": 1716, "s": 1468, "text": "This is because if x and y are both unsigned ints, if added and they overflow, their values can't be greater than either of them as it would need to be greater than max possible unsigned int to be able to wrap around and get ahead of these values." }, { "code": null, "e": 1867, "s": 1716, "text": "Another way is to try and access the Overflow flag in your CPU. Some compilers provide access to it which you could then test but this isn't standard." } ]
AsEnumerable() in C#
To cast a specific type to its IEnumerable equivalent, use the AsEnumerable() method. It is an extension method. The following is our array − int[] arr = new int[5]; arr[0] = 10; arr[1] = 20; arr[2] = 30; arr[3] = 40; arr[4] = 50; Now, get the IEnumerable equivalent. arr.AsEnumerable(); Live Demo using System; using System.Linq; class Demo { static void Main() { int[] arr = new int[5]; arr[0] = 10; arr[1] = 20; arr[2] = 30; arr[3] = 40; arr[4] = 50; var res = arr.AsEnumerable(); foreach (var ele in res) { Console.WriteLine(ele); } } } 10 20 30 40 50
[ { "code": null, "e": 1175, "s": 1062, "text": "To cast a specific type to its IEnumerable equivalent, use the AsEnumerable() method. It is an extension method." }, { "code": null, "e": 1204, "s": 1175, "text": "The following is our array −" }, { "code": null, "e": 1293, "s": 1204, "text": "int[] arr = new int[5];\narr[0] = 10;\narr[1] = 20;\narr[2] = 30;\narr[3] = 40;\narr[4] = 50;" }, { "code": null, "e": 1330, "s": 1293, "text": "Now, get the IEnumerable equivalent." }, { "code": null, "e": 1350, "s": 1330, "text": "arr.AsEnumerable();" }, { "code": null, "e": 1361, "s": 1350, "text": " Live Demo" }, { "code": null, "e": 1673, "s": 1361, "text": "using System;\nusing System.Linq;\nclass Demo {\n static void Main() {\n int[] arr = new int[5];\n arr[0] = 10;\n arr[1] = 20;\n arr[2] = 30;\n arr[3] = 40;\n arr[4] = 50;\n var res = arr.AsEnumerable();\n foreach (var ele in res) {\n Console.WriteLine(ele);\n }\n }\n}" }, { "code": null, "e": 1688, "s": 1673, "text": "10\n20\n30\n40\n50" } ]
Tutorial: Create a Python CLI Package via Traitlets | by Joél Collins | Towards Data Science
If you’re like me... You love writing scripts to speed up your workflow You’re fluent in Python and basically nothing else. Annoyingly, python can feel a little clunky in the terminal. If you want to run python scripts from command line, you either need to... Assign a different command (usually a bash alias) to every script impossible to remember Use the sys python package to parse the command line arguments from scratch gross Use argparse to parse the command line, and activate every function with if/else checks. also gross Fortunately, there is a solution to this issue! It’s called traitlets. Traitlets was created by IPython to validate datatypes, monitor changes to variables, parse and implement application settings from configuration files, and activate python code from the command line. It functions as a sort of behind the scenes engine for much of the software produced by IPython and the Jupyter Project. For now, we will focus on two elements of traitlets. Activating python code from the command lineConfigurable variables Activating python code from the command line Configurable variables In this article, I will walk through building a simple traitlets application. With this knowledge you will be able to write a command line program that Is written entirely in python. Assigns multiple tools to a single CLI command. Can be easily configured via command line or in system configuration files. (You do not have to write code to parse configuration data 🤩) Has a straight forward Object Oriented Programming structure. The project code: If you want to write the project code yourself, this github repository contains all of the project files. The code in each file has been replaced with guiding comments. The completed project code can be found here. (The code is stored on the the solution branch of the github repository. If you’ve cloned the repository, you can run git checkout solution to access the code on your computer.) First let’s take a look at what the finished product looks like... This application has two commands. greet When this command is run “Hello, World!” is printed to the terminal. This command has the arguments --greeting, --name, and --punctuation that allow you to alter the printed message. abs When this command is run the absolute path for a provided filename is printed to the terminal. This command has the flag --size. When this flag is used, the file size (in bytes) is printed in addition to the absolute path. The directory structure for this project looks like this: subapps/ <------------- All "command" code-files are placed here AbsApp.py <------ Code for the `abs` command GreetingApp.py <-- Code for the `greet` command __init__.py <----- Set up for easy importingCLIapp.py <------------ Code for CLI activation okok let’s write some code. Navigate into the subapps/directory of the project folder and open the GreetApp.py file. We will need two imports for this file. from traitlets.config import Applicationfrom traitlets import Unicode from traitlets.config import Application from traitlets import Unicode Before moving on, let’s quickly break down these two imports. Import #1 — Application Application is the “parent” for every class we will write in this project. Applicationobjects offer a slew of helpful tools such as parsing the command line, loading configuration files, generating config files, auto-generating code documentation, and more. In this tutorial we will focus on the methods used by Application objects to parse the command line and activate the application code. Import #2 — Unicode Unicode is a traitlets type. Code examples of types. List of all available types. Traitlets types are class attributes that, when defined, prevent attributes from being assigned to the incorrect datatype. When the argument config=True is added to the type, the variable becomes configurable, which means the default value for the attribute can be changed via command line arguments or by setting the desired default inside a configuration file. In the code cell below we... Import theApplication and Unicode objectsDefine the GreetApp classInherit from the Application parent classDefine type variables with a default setting.Mark the variable as configurable Import theApplication and Unicode objects Define the GreetApp class Inherit from the Application parent class Define type variables with a default setting. Mark the variable as configurable Now let’s create the start method The start method is where the app’s functionality is activated. In the code block below we... Define a start methodActivate the app functionality Define a start method Activate the app functionality Technically, we could leave the app like this and it would work, but changing the configurable variable would be a little annoying for the user. Right now, instead of users running --greeting='Hi' to change the greeting config variable to 'Hi' , the user would have to run: --GreetApp.greeting='Hi' To make this easier, we have to create an aliases class attribute. This attribute is used by the Application parent class while parsing the command line. In the code block below we... Define a dictionary containing our aliasesSet the dictionary keys to the command line arguments we want to useSet the value to the name of the Application child we want to configureClarify the configurable variable we want to alterSet the aliases class trait to the dictionary of aliases Define a dictionary containing our aliases Set the dictionary keys to the command line arguments we want to use Set the value to the name of the Application child we want to configure Clarify the configurable variable we want to alter Set the aliases class trait to the dictionary of aliases The GreetApp is done! There are a few other things we can add to this app that will be covered in a follow up article “How to Autogenerate Documentation.” If you’re working through the code-it-yourself files, skip the unfilled out portions for now. They are not required for this article. Now that we’ve completed an application, we need to set up the main function that activates the code. This process will be handled by the CLIapp.py file. Navigate to the CLIapp.py file. For this file, we will need the following imports. from traitlets.config import Applicationfrom subapps import GreetApp (The application object we just wrote!) from traitlets.config import Application from subapps import GreetApp (The application object we just wrote!) Application objects have an attribute called subcommands that allow you to attach commands for activating specific applications. In this file we will define an application called CLIapp that contains a dictionary of subcommands, and a start method for activating the subcommand’s start method. TL;DR The CLIapp is an application with the sole purpose of activating the code for other applications. Let’s write this out In the code block below we... Import the Application and GreetApp objectsDefine the CLIPapp applicationDefine a dictionary with the following format: Import the Application and GreetApp objects Define the CLIPapp application Define a dictionary with the following format: {command : (application object, application description)} 4. Define a startmethod 5. Check to make sure the user has provided a subcommand. If they haven’t print the available subcommands 6. Activate the Application.start method which in turn, activates the subapplication’s start method. Ok! That is the CLIapp Now the last thing we need to do is define a main function that activate all the code. In the code block below we... Define a main function outside of the CLIappActivate the code via the launch_instance method. This is where the command line is parsedAdd if __name__ == "__main__" check which allows us to call the main function from command line. Define a main function outside of the CLIapp Activate the code via the launch_instance method. This is where the command line is parsed Add if __name__ == "__main__" check which allows us to call the main function from command line. We now have a working application! 🥳 In your terminal, navigate to the top level of the project directory and run python CLIapp.py greet “Hello, World!” will be printed python CLIapp.py greet --greeting="Hi" “Hi, World!” will be printed python CLIapp.py greet --name="Joel" “Hello, Joel!” will be printed Now let’s look at the process for adding new tools to an existing application by creating the abs command. Inside the AbsApp.py file, we will run the following imports from traitlets.config import Applicationfrom traitlets import Boolimport os The two new imports are Bool and os . Bool is another traitlets type. In this case, it ensures that the variable is set to either True or False os is a base Python package that stands for “Operating System”. It is a standard package used to generate file paths, to list files inside a folder, and to interact with a computer’s operating system. In our case, we will use os to generate the absolute path for a file and to calculate how many bytes a file uses. Ok, next we will construct our AbApp class. In the cell below we... Define the AbsApp applicationDefine a configurablesize variable with a traitlets type of BoolDefine a start methodAccess the filename that has been provided by the user via the extra_args attributeEnsure the file provided by the user is a valid file via the os isfile function.Print the absolute path for the provided filenameIf the user has set the size configurable variable to True the file-size is also printed. Define the AbsApp application Define a configurablesize variable with a traitlets type of Bool Define a start method Access the filename that has been provided by the user via the extra_args attribute Ensure the file provided by the user is a valid file via the os isfile function. Print the absolute path for the provided filename If the user has set the size configurable variable to True the file-size is also printed. Now, we will create a flag for the AbsApp that allows users to simply run... --size ...without having to explicitly set size to True or False. To do this we will define a flags class variable that is used by the Application parent class while parsing the command line. In the cell below we... Define a dictvariable called flagsSet the top level key to flag that will be used in command lineSet the value of the key to a tupleAdd a dictionary to the tuple where the key is the name of the application that should be configured by the flagSet the value of the key to another dictionary where the key is the name of the configurable variable, and the value is the data would like to assign to the variable.Add a description for the flag as the second item inside the tuple. This will be printed if a user uses the --help argument!Add the flag to the application via the Application.flags attribute. Define a dictvariable called flags Set the top level key to flag that will be used in command line Set the value of the key to a tuple Add a dictionary to the tuple where the key is the name of the application that should be configured by the flag Set the value of the key to another dictionary where the key is the name of the configurable variable, and the value is the data would like to assign to the variable. Add a description for the flag as the second item inside the tuple. This will be printed if a user uses the --help argument! Add the flag to the application via the Application.flags attribute. Worth noting: flags are pretty powerful when it comes to updating configurations. The second level dictionary can contain multiple applications and the third level dictionary can contain multiple configurable variables! The AbsApp is complete! ✅ Now the final step is to add the app to the CLIapp.py file! In the code block below we... Import the AbsApp object into the CLIapp.py fileAdd an abs subcommand to the CLIapp object Import the AbsApp object into the CLIapp.py file Add an abs subcommand to the CLIapp object And just like that, a new command is added to your application! In your terminal, navigate to the top level of the project directory and run python CLIapp.py abs CLIapp.py The absolute path for the CLIapp.py file will be printed python CLIapp.py abs CLIapp.py --size The absolute path and the filesize for the CLIapp.py file will be printed In my own experience writing applications with traitlets, the ease of writing new applications and adding new commands to an existing tool is one of the best perks. Because the process is so rooted in Object Oriented Programming, sometimes writing an entirely new application is as simple as inheriting from an existing application and then editing a single line of code! Alright, that is it for now. Be sure to click the follow button for my next article: A walkthrough of traitlets configuration files and how to autogenerate code documentation!
[ { "code": null, "e": 192, "s": 171, "text": "If you’re like me..." }, { "code": null, "e": 243, "s": 192, "text": "You love writing scripts to speed up your workflow" }, { "code": null, "e": 295, "s": 243, "text": "You’re fluent in Python and basically nothing else." }, { "code": null, "e": 356, "s": 295, "text": "Annoyingly, python can feel a little clunky in the terminal." }, { "code": null, "e": 431, "s": 356, "text": "If you want to run python scripts from command line, you either need to..." }, { "code": null, "e": 520, "s": 431, "text": "Assign a different command (usually a bash alias) to every script impossible to remember" }, { "code": null, "e": 602, "s": 520, "text": "Use the sys python package to parse the command line arguments from scratch gross" }, { "code": null, "e": 702, "s": 602, "text": "Use argparse to parse the command line, and activate every function with if/else checks. also gross" }, { "code": null, "e": 773, "s": 702, "text": "Fortunately, there is a solution to this issue! It’s called traitlets." }, { "code": null, "e": 1148, "s": 773, "text": "Traitlets was created by IPython to validate datatypes, monitor changes to variables, parse and implement application settings from configuration files, and activate python code from the command line. It functions as a sort of behind the scenes engine for much of the software produced by IPython and the Jupyter Project. For now, we will focus on two elements of traitlets." }, { "code": null, "e": 1215, "s": 1148, "text": "Activating python code from the command lineConfigurable variables" }, { "code": null, "e": 1260, "s": 1215, "text": "Activating python code from the command line" }, { "code": null, "e": 1283, "s": 1260, "text": "Configurable variables" }, { "code": null, "e": 1435, "s": 1283, "text": "In this article, I will walk through building a simple traitlets application. With this knowledge you will be able to write a command line program that" }, { "code": null, "e": 1466, "s": 1435, "text": "Is written entirely in python." }, { "code": null, "e": 1514, "s": 1466, "text": "Assigns multiple tools to a single CLI command." }, { "code": null, "e": 1652, "s": 1514, "text": "Can be easily configured via command line or in system configuration files. (You do not have to write code to parse configuration data 🤩)" }, { "code": null, "e": 1714, "s": 1652, "text": "Has a straight forward Object Oriented Programming structure." }, { "code": null, "e": 1732, "s": 1714, "text": "The project code:" }, { "code": null, "e": 1901, "s": 1732, "text": "If you want to write the project code yourself, this github repository contains all of the project files. The code in each file has been replaced with guiding comments." }, { "code": null, "e": 2125, "s": 1901, "text": "The completed project code can be found here. (The code is stored on the the solution branch of the github repository. If you’ve cloned the repository, you can run git checkout solution to access the code on your computer.)" }, { "code": null, "e": 2192, "s": 2125, "text": "First let’s take a look at what the finished product looks like..." }, { "code": null, "e": 2227, "s": 2192, "text": "This application has two commands." }, { "code": null, "e": 2233, "s": 2227, "text": "greet" }, { "code": null, "e": 2302, "s": 2233, "text": "When this command is run “Hello, World!” is printed to the terminal." }, { "code": null, "e": 2416, "s": 2302, "text": "This command has the arguments --greeting, --name, and --punctuation that allow you to alter the printed message." }, { "code": null, "e": 2420, "s": 2416, "text": "abs" }, { "code": null, "e": 2515, "s": 2420, "text": "When this command is run the absolute path for a provided filename is printed to the terminal." }, { "code": null, "e": 2643, "s": 2515, "text": "This command has the flag --size. When this flag is used, the file size (in bytes) is printed in addition to the absolute path." }, { "code": null, "e": 2701, "s": 2643, "text": "The directory structure for this project looks like this:" }, { "code": null, "e": 2964, "s": 2701, "text": "subapps/ <------------- All \"command\" code-files are placed here AbsApp.py <------ Code for the `abs` command GreetingApp.py <-- Code for the `greet` command __init__.py <----- Set up for easy importingCLIapp.py <------------ Code for CLI activation" }, { "code": null, "e": 2992, "s": 2964, "text": "okok let’s write some code." }, { "code": null, "e": 3081, "s": 2992, "text": "Navigate into the subapps/directory of the project folder and open the GreetApp.py file." }, { "code": null, "e": 3121, "s": 3081, "text": "We will need two imports for this file." }, { "code": null, "e": 3191, "s": 3121, "text": "from traitlets.config import Applicationfrom traitlets import Unicode" }, { "code": null, "e": 3232, "s": 3191, "text": "from traitlets.config import Application" }, { "code": null, "e": 3262, "s": 3232, "text": "from traitlets import Unicode" }, { "code": null, "e": 3324, "s": 3262, "text": "Before moving on, let’s quickly break down these two imports." }, { "code": null, "e": 3348, "s": 3324, "text": "Import #1 — Application" }, { "code": null, "e": 3741, "s": 3348, "text": "Application is the “parent” for every class we will write in this project. Applicationobjects offer a slew of helpful tools such as parsing the command line, loading configuration files, generating config files, auto-generating code documentation, and more. In this tutorial we will focus on the methods used by Application objects to parse the command line and activate the application code." }, { "code": null, "e": 3761, "s": 3741, "text": "Import #2 — Unicode" }, { "code": null, "e": 3790, "s": 3761, "text": "Unicode is a traitlets type." }, { "code": null, "e": 3814, "s": 3790, "text": "Code examples of types." }, { "code": null, "e": 3843, "s": 3814, "text": "List of all available types." }, { "code": null, "e": 4206, "s": 3843, "text": "Traitlets types are class attributes that, when defined, prevent attributes from being assigned to the incorrect datatype. When the argument config=True is added to the type, the variable becomes configurable, which means the default value for the attribute can be changed via command line arguments or by setting the desired default inside a configuration file." }, { "code": null, "e": 4235, "s": 4206, "text": "In the code cell below we..." }, { "code": null, "e": 4421, "s": 4235, "text": "Import theApplication and Unicode objectsDefine the GreetApp classInherit from the Application parent classDefine type variables with a default setting.Mark the variable as configurable" }, { "code": null, "e": 4463, "s": 4421, "text": "Import theApplication and Unicode objects" }, { "code": null, "e": 4489, "s": 4463, "text": "Define the GreetApp class" }, { "code": null, "e": 4531, "s": 4489, "text": "Inherit from the Application parent class" }, { "code": null, "e": 4577, "s": 4531, "text": "Define type variables with a default setting." }, { "code": null, "e": 4611, "s": 4577, "text": "Mark the variable as configurable" }, { "code": null, "e": 4645, "s": 4611, "text": "Now let’s create the start method" }, { "code": null, "e": 4709, "s": 4645, "text": "The start method is where the app’s functionality is activated." }, { "code": null, "e": 4739, "s": 4709, "text": "In the code block below we..." }, { "code": null, "e": 4791, "s": 4739, "text": "Define a start methodActivate the app functionality" }, { "code": null, "e": 4813, "s": 4791, "text": "Define a start method" }, { "code": null, "e": 4844, "s": 4813, "text": "Activate the app functionality" }, { "code": null, "e": 4989, "s": 4844, "text": "Technically, we could leave the app like this and it would work, but changing the configurable variable would be a little annoying for the user." }, { "code": null, "e": 5118, "s": 4989, "text": "Right now, instead of users running --greeting='Hi' to change the greeting config variable to 'Hi' , the user would have to run:" }, { "code": null, "e": 5143, "s": 5118, "text": "--GreetApp.greeting='Hi'" }, { "code": null, "e": 5297, "s": 5143, "text": "To make this easier, we have to create an aliases class attribute. This attribute is used by the Application parent class while parsing the command line." }, { "code": null, "e": 5327, "s": 5297, "text": "In the code block below we..." }, { "code": null, "e": 5615, "s": 5327, "text": "Define a dictionary containing our aliasesSet the dictionary keys to the command line arguments we want to useSet the value to the name of the Application child we want to configureClarify the configurable variable we want to alterSet the aliases class trait to the dictionary of aliases" }, { "code": null, "e": 5658, "s": 5615, "text": "Define a dictionary containing our aliases" }, { "code": null, "e": 5727, "s": 5658, "text": "Set the dictionary keys to the command line arguments we want to use" }, { "code": null, "e": 5799, "s": 5727, "text": "Set the value to the name of the Application child we want to configure" }, { "code": null, "e": 5850, "s": 5799, "text": "Clarify the configurable variable we want to alter" }, { "code": null, "e": 5907, "s": 5850, "text": "Set the aliases class trait to the dictionary of aliases" }, { "code": null, "e": 5929, "s": 5907, "text": "The GreetApp is done!" }, { "code": null, "e": 6196, "s": 5929, "text": "There are a few other things we can add to this app that will be covered in a follow up article “How to Autogenerate Documentation.” If you’re working through the code-it-yourself files, skip the unfilled out portions for now. They are not required for this article." }, { "code": null, "e": 6350, "s": 6196, "text": "Now that we’ve completed an application, we need to set up the main function that activates the code. This process will be handled by the CLIapp.py file." }, { "code": null, "e": 6382, "s": 6350, "text": "Navigate to the CLIapp.py file." }, { "code": null, "e": 6433, "s": 6382, "text": "For this file, we will need the following imports." }, { "code": null, "e": 6542, "s": 6433, "text": "from traitlets.config import Applicationfrom subapps import GreetApp (The application object we just wrote!)" }, { "code": null, "e": 6583, "s": 6542, "text": "from traitlets.config import Application" }, { "code": null, "e": 6652, "s": 6583, "text": "from subapps import GreetApp (The application object we just wrote!)" }, { "code": null, "e": 7050, "s": 6652, "text": "Application objects have an attribute called subcommands that allow you to attach commands for activating specific applications. In this file we will define an application called CLIapp that contains a dictionary of subcommands, and a start method for activating the subcommand’s start method. TL;DR The CLIapp is an application with the sole purpose of activating the code for other applications." }, { "code": null, "e": 7071, "s": 7050, "text": "Let’s write this out" }, { "code": null, "e": 7101, "s": 7071, "text": "In the code block below we..." }, { "code": null, "e": 7221, "s": 7101, "text": "Import the Application and GreetApp objectsDefine the CLIPapp applicationDefine a dictionary with the following format:" }, { "code": null, "e": 7265, "s": 7221, "text": "Import the Application and GreetApp objects" }, { "code": null, "e": 7296, "s": 7265, "text": "Define the CLIPapp application" }, { "code": null, "e": 7343, "s": 7296, "text": "Define a dictionary with the following format:" }, { "code": null, "e": 7401, "s": 7343, "text": "{command : (application object, application description)}" }, { "code": null, "e": 7425, "s": 7401, "text": "4. Define a startmethod" }, { "code": null, "e": 7531, "s": 7425, "text": "5. Check to make sure the user has provided a subcommand. If they haven’t print the available subcommands" }, { "code": null, "e": 7632, "s": 7531, "text": "6. Activate the Application.start method which in turn, activates the subapplication’s start method." }, { "code": null, "e": 7655, "s": 7632, "text": "Ok! That is the CLIapp" }, { "code": null, "e": 7742, "s": 7655, "text": "Now the last thing we need to do is define a main function that activate all the code." }, { "code": null, "e": 7772, "s": 7742, "text": "In the code block below we..." }, { "code": null, "e": 8003, "s": 7772, "text": "Define a main function outside of the CLIappActivate the code via the launch_instance method. This is where the command line is parsedAdd if __name__ == \"__main__\" check which allows us to call the main function from command line." }, { "code": null, "e": 8048, "s": 8003, "text": "Define a main function outside of the CLIapp" }, { "code": null, "e": 8139, "s": 8048, "text": "Activate the code via the launch_instance method. This is where the command line is parsed" }, { "code": null, "e": 8236, "s": 8139, "text": "Add if __name__ == \"__main__\" check which allows us to call the main function from command line." }, { "code": null, "e": 8273, "s": 8236, "text": "We now have a working application! 🥳" }, { "code": null, "e": 8350, "s": 8273, "text": "In your terminal, navigate to the top level of the project directory and run" }, { "code": null, "e": 8405, "s": 8350, "text": "python CLIapp.py greet “Hello, World!” will be printed" }, { "code": null, "e": 8473, "s": 8405, "text": "python CLIapp.py greet --greeting=\"Hi\" “Hi, World!” will be printed" }, { "code": null, "e": 8541, "s": 8473, "text": "python CLIapp.py greet --name=\"Joel\" “Hello, Joel!” will be printed" }, { "code": null, "e": 8648, "s": 8541, "text": "Now let’s look at the process for adding new tools to an existing application by creating the abs command." }, { "code": null, "e": 8709, "s": 8648, "text": "Inside the AbsApp.py file, we will run the following imports" }, { "code": null, "e": 8785, "s": 8709, "text": "from traitlets.config import Applicationfrom traitlets import Boolimport os" }, { "code": null, "e": 8823, "s": 8785, "text": "The two new imports are Bool and os ." }, { "code": null, "e": 8929, "s": 8823, "text": "Bool is another traitlets type. In this case, it ensures that the variable is set to either True or False" }, { "code": null, "e": 9244, "s": 8929, "text": "os is a base Python package that stands for “Operating System”. It is a standard package used to generate file paths, to list files inside a folder, and to interact with a computer’s operating system. In our case, we will use os to generate the absolute path for a file and to calculate how many bytes a file uses." }, { "code": null, "e": 9288, "s": 9244, "text": "Ok, next we will construct our AbApp class." }, { "code": null, "e": 9312, "s": 9288, "text": "In the cell below we..." }, { "code": null, "e": 9728, "s": 9312, "text": "Define the AbsApp applicationDefine a configurablesize variable with a traitlets type of BoolDefine a start methodAccess the filename that has been provided by the user via the extra_args attributeEnsure the file provided by the user is a valid file via the os isfile function.Print the absolute path for the provided filenameIf the user has set the size configurable variable to True the file-size is also printed." }, { "code": null, "e": 9758, "s": 9728, "text": "Define the AbsApp application" }, { "code": null, "e": 9823, "s": 9758, "text": "Define a configurablesize variable with a traitlets type of Bool" }, { "code": null, "e": 9845, "s": 9823, "text": "Define a start method" }, { "code": null, "e": 9929, "s": 9845, "text": "Access the filename that has been provided by the user via the extra_args attribute" }, { "code": null, "e": 10010, "s": 9929, "text": "Ensure the file provided by the user is a valid file via the os isfile function." }, { "code": null, "e": 10060, "s": 10010, "text": "Print the absolute path for the provided filename" }, { "code": null, "e": 10150, "s": 10060, "text": "If the user has set the size configurable variable to True the file-size is also printed." }, { "code": null, "e": 10227, "s": 10150, "text": "Now, we will create a flag for the AbsApp that allows users to simply run..." }, { "code": null, "e": 10234, "s": 10227, "text": "--size" }, { "code": null, "e": 10419, "s": 10234, "text": "...without having to explicitly set size to True or False. To do this we will define a flags class variable that is used by the Application parent class while parsing the command line." }, { "code": null, "e": 10443, "s": 10419, "text": "In the cell below we..." }, { "code": null, "e": 11046, "s": 10443, "text": "Define a dictvariable called flagsSet the top level key to flag that will be used in command lineSet the value of the key to a tupleAdd a dictionary to the tuple where the key is the name of the application that should be configured by the flagSet the value of the key to another dictionary where the key is the name of the configurable variable, and the value is the data would like to assign to the variable.Add a description for the flag as the second item inside the tuple. This will be printed if a user uses the --help argument!Add the flag to the application via the Application.flags attribute." }, { "code": null, "e": 11081, "s": 11046, "text": "Define a dictvariable called flags" }, { "code": null, "e": 11145, "s": 11081, "text": "Set the top level key to flag that will be used in command line" }, { "code": null, "e": 11181, "s": 11145, "text": "Set the value of the key to a tuple" }, { "code": null, "e": 11294, "s": 11181, "text": "Add a dictionary to the tuple where the key is the name of the application that should be configured by the flag" }, { "code": null, "e": 11461, "s": 11294, "text": "Set the value of the key to another dictionary where the key is the name of the configurable variable, and the value is the data would like to assign to the variable." }, { "code": null, "e": 11586, "s": 11461, "text": "Add a description for the flag as the second item inside the tuple. This will be printed if a user uses the --help argument!" }, { "code": null, "e": 11655, "s": 11586, "text": "Add the flag to the application via the Application.flags attribute." }, { "code": null, "e": 11875, "s": 11655, "text": "Worth noting: flags are pretty powerful when it comes to updating configurations. The second level dictionary can contain multiple applications and the third level dictionary can contain multiple configurable variables!" }, { "code": null, "e": 11901, "s": 11875, "text": "The AbsApp is complete! ✅" }, { "code": null, "e": 11961, "s": 11901, "text": "Now the final step is to add the app to the CLIapp.py file!" }, { "code": null, "e": 11991, "s": 11961, "text": "In the code block below we..." }, { "code": null, "e": 12082, "s": 11991, "text": "Import the AbsApp object into the CLIapp.py fileAdd an abs subcommand to the CLIapp object" }, { "code": null, "e": 12131, "s": 12082, "text": "Import the AbsApp object into the CLIapp.py file" }, { "code": null, "e": 12174, "s": 12131, "text": "Add an abs subcommand to the CLIapp object" }, { "code": null, "e": 12238, "s": 12174, "text": "And just like that, a new command is added to your application!" }, { "code": null, "e": 12315, "s": 12238, "text": "In your terminal, navigate to the top level of the project directory and run" }, { "code": null, "e": 12403, "s": 12315, "text": "python CLIapp.py abs CLIapp.py The absolute path for the CLIapp.py file will be printed" }, { "code": null, "e": 12515, "s": 12403, "text": "python CLIapp.py abs CLIapp.py --size The absolute path and the filesize for the CLIapp.py file will be printed" }, { "code": null, "e": 12887, "s": 12515, "text": "In my own experience writing applications with traitlets, the ease of writing new applications and adding new commands to an existing tool is one of the best perks. Because the process is so rooted in Object Oriented Programming, sometimes writing an entirely new application is as simple as inheriting from an existing application and then editing a single line of code!" } ]
What is use of fluent Validation in C# and how to use in C#?
FluentValidation is a .NET library for building strongly-typed validation rules. It Uses a fluent interface and lambda expressions for building validation rules. It helps clean up your domain code and make it more cohesive, as well as giving you a single place to look for validation logic To make use of fluent validation we have to install the below package <PackageReference Include="FluentValidation" Version="9.2.2" /> static class Program { static void Main (string[] args) { List errors = new List(); PersonModel person = new PersonModel(); person.FirstName = ""; person.LastName = "S"; person.AccountBalance = 100; person.DateOfBirth = DateTime.Now.Date; PersonValidator validator = new PersonValidator(); ValidationResult results = validator.Validate(person); if (results.IsValid == false) { foreach (ValidationFailure failure in results.Errors) { errors.Add(failure.ErrorMessage); } } foreach (var item in errors) { Console.WriteLine(item); } Console.ReadLine (); } } public class PersonModel { public string FirstName { get; set; } public string LastName { get; set; } public decimal AccountBalance { get; set; } public DateTime DateOfBirth { get; set; } } public class PersonValidator : AbstractValidator { public PersonValidator(){ RuleFor(p => p.FirstName) .Cascade(CascadeMode.StopOnFirstFailure) .NotEmpty().WithMessage("{PropertyName} is Empty") .Length(2, 50).WithMessage("Length ({TotalLength}) of {PropertyName} Invalid") .Must(BeAValidName).WithMessage("{PropertyName} Contains Invalid Characters"); RuleFor(p => p.LastName) .Cascade(CascadeMode.StopOnFirstFailure) .NotEmpty().WithMessage("{PropertyName} is Empty") .Length(2, 50).WithMessage("Length ({TotalLength}) of {PropertyName} Invalid") .Must(BeAValidName).WithMessage("{PropertyName} Contains Invalid Characters"); } protected bool BeAValidName(string name) { name = name.Replace(" ", ""); name = name.Replace("-", ""); return name.All(Char.IsLetter); } } First Name is Empty Length (1) of Last Name Invalid
[ { "code": null, "e": 1352, "s": 1062, "text": "FluentValidation is a .NET library for building strongly-typed validation rules. It Uses a fluent interface and lambda expressions for building validation rules. It helps clean up your domain code and make it more cohesive, as well as giving you a single place to look for validation logic" }, { "code": null, "e": 1422, "s": 1352, "text": "To make use of fluent validation we have to install the below package" }, { "code": null, "e": 1486, "s": 1422, "text": "<PackageReference Include=\"FluentValidation\" Version=\"9.2.2\" />" }, { "code": null, "e": 3233, "s": 1486, "text": "static class Program {\n static void Main (string[] args) {\n List errors = new List();\n\n PersonModel person = new PersonModel();\n person.FirstName = \"\";\n person.LastName = \"S\";\n person.AccountBalance = 100;\n person.DateOfBirth = DateTime.Now.Date;\n\n PersonValidator validator = new PersonValidator();\n ValidationResult results = validator.Validate(person);\n\n if (results.IsValid == false) {\n foreach (ValidationFailure failure in results.Errors) {\n errors.Add(failure.ErrorMessage);\n }\n }\n foreach (var item in errors) {\n Console.WriteLine(item);\n }\n Console.ReadLine ();\n }\n}\n\npublic class PersonModel {\n public string FirstName { get; set; }\n public string LastName { get; set; }\n public decimal AccountBalance { get; set; }\n public DateTime DateOfBirth { get; set; }\n}\n\npublic class PersonValidator : AbstractValidator {\n public PersonValidator(){\n RuleFor(p => p.FirstName)\n .Cascade(CascadeMode.StopOnFirstFailure)\n .NotEmpty().WithMessage(\"{PropertyName} is Empty\")\n .Length(2, 50).WithMessage(\"Length ({TotalLength}) of {PropertyName} Invalid\")\n .Must(BeAValidName).WithMessage(\"{PropertyName} Contains Invalid Characters\");\n\n RuleFor(p => p.LastName)\n .Cascade(CascadeMode.StopOnFirstFailure)\n .NotEmpty().WithMessage(\"{PropertyName} is Empty\")\n .Length(2, 50).WithMessage(\"Length ({TotalLength}) of {PropertyName} Invalid\")\n .Must(BeAValidName).WithMessage(\"{PropertyName} Contains Invalid Characters\");\n\n }\n\n protected bool BeAValidName(string name) {\n name = name.Replace(\" \", \"\");\n name = name.Replace(\"-\", \"\");\n return name.All(Char.IsLetter);\n }\n}\n" }, { "code": null, "e": 3285, "s": 3233, "text": "First Name is Empty\nLength (1) of Last Name Invalid" } ]
Julia Programming - Plotting
Julia has various packages for plotting and before starting making plots, we need to first download and install some of them as follows − (@v1.5) pkg> add Plots PyPlot GR UnicodePlots The package Plots is a high-level plotting package, also referred to as ‘back-ends’ interfaces with other plotting packages. To start using the Plots package, type the following command − julia> using Plots [ Info: Precompiling Plots [91a5bcdd-55d7-5caf-9e0b-520d859cae80] For plotting a function, we need to switch back to PyPlot back-end as follows − julia> pyplot() Plots.PyPlotBackend() Here we will be plotting the equation of Time graph which can be modeled by the following function − julia> eq(d) = -7.65 * sind(d) + 9.87 * sind(2d + 206); julia> plot(eq, 1:365) sys:1: MatplotlibDeprecationWarning: Passing the fontdict parameter of _set_ticklabels() positionally is deprecated since Matplotlib 3.3; the parameter will become keyword-only two minor releases later. sys:1: UserWarning: FixedFormatter should only be used together with FixedLocator Everyone wants a package that helps them to draw quick plots by text rather than graphics. Julia provides one such package called UnicodePlots which can produce the following − scatter plots scatter plots line plots line plots bar plots bar plots staircase plots staircase plots histograms histograms sparsity patterns sparsity patterns density plots density plots We can add it to our Julia installation by the following command − (@v1.5) pkg> add UnicodePlots Once added, we can use this to plot a graph as follows: julia> using UnicodePlots Following Julia example generates a line chart using UnicodePlots. julia> FirstLinePlot = lineplot([1, 2, 3, 7], [1, 2, -5, 7], title="First Line Plot", border=:dotted) First Line Plot Following Julia example generates a density chart using UnicodePlots. Julia> using UnicodePlots Julia> FirstDensityPlot = densityplot(collect(1:100), randn(100), border=:dotted) This Julia package is a visualization grammar which allows us to create visualization in a web browser window. With this package, we can − describe data visualization in a JSON format describe data visualization in a JSON format generate interactive views using HTML5 Canvas or SVG generate interactive views using HTML5 Canvas or SVG It can produce the following − Area plots Area plots Bar plots/Histograms Bar plots/Histograms Line plots Line plots Scatter plots Scatter plots Pie/Donut charts Pie/Donut charts Waterfall charts Waterfall charts Worldclouds Worldclouds We can add it to our Julia installation by following command − (@v1.5) pkg> add VegaLite Once added we can use this to plot a graph as follows − julia> using VegaLite Following Julia example generates a Pie chart using VegaLite. julia> X = ["Monday", "Tuesday", "Wednesday", "Thrusday", "Friday","Saturday","Sunday"]; julia> Y = [11, 11, 15, 13, 12, 13, 10] 7-element Array{Int64,1}: 11 11 15 13 12 13 10 julia> P = pie(X,Y) 73 Lectures 4 hours Lemuel Ogbunude 24 Lectures 3 hours Mohammad Nauman 29 Lectures 2.5 hours Stone River ELearning Print Add Notes Bookmark this page
[ { "code": null, "e": 2216, "s": 2078, "text": "Julia has various packages for plotting and before starting making plots, we need to first download and install some of them as follows −" }, { "code": null, "e": 2262, "s": 2216, "text": "(@v1.5) pkg> add Plots PyPlot GR UnicodePlots" }, { "code": null, "e": 2450, "s": 2262, "text": "The package Plots is a high-level plotting package, also referred to as ‘back-ends’ interfaces with other plotting packages. To start using the Plots package, type the following command −" }, { "code": null, "e": 2535, "s": 2450, "text": "julia> using Plots\n[ Info: Precompiling Plots [91a5bcdd-55d7-5caf-9e0b-520d859cae80]" }, { "code": null, "e": 2615, "s": 2535, "text": "For plotting a function, we need to switch back to PyPlot back-end as follows −" }, { "code": null, "e": 2655, "s": 2615, "text": " julia> pyplot()\nPlots.PyPlotBackend()" }, { "code": null, "e": 2756, "s": 2655, "text": "Here we will be plotting the equation of Time graph which can be modeled by the following function −" }, { "code": null, "e": 3120, "s": 2756, "text": "julia> eq(d) = -7.65 * sind(d) + 9.87 * sind(2d + 206);\njulia> plot(eq, 1:365)\nsys:1: MatplotlibDeprecationWarning: Passing the fontdict parameter of _set_ticklabels() positionally is deprecated since Matplotlib 3.3; the parameter will become keyword-only two minor releases later.\nsys:1: UserWarning: FixedFormatter should only be used together with FixedLocator" }, { "code": null, "e": 3211, "s": 3120, "text": "Everyone wants a package that helps them to draw quick plots by text rather than graphics." }, { "code": null, "e": 3297, "s": 3211, "text": "Julia provides one such package called UnicodePlots which can produce the following −" }, { "code": null, "e": 3311, "s": 3297, "text": "scatter plots" }, { "code": null, "e": 3325, "s": 3311, "text": "scatter plots" }, { "code": null, "e": 3336, "s": 3325, "text": "line plots" }, { "code": null, "e": 3347, "s": 3336, "text": "line plots" }, { "code": null, "e": 3357, "s": 3347, "text": "bar plots" }, { "code": null, "e": 3367, "s": 3357, "text": "bar plots" }, { "code": null, "e": 3383, "s": 3367, "text": "staircase plots" }, { "code": null, "e": 3399, "s": 3383, "text": "staircase plots" }, { "code": null, "e": 3410, "s": 3399, "text": "histograms" }, { "code": null, "e": 3421, "s": 3410, "text": "histograms" }, { "code": null, "e": 3439, "s": 3421, "text": "sparsity patterns" }, { "code": null, "e": 3457, "s": 3439, "text": "sparsity patterns" }, { "code": null, "e": 3471, "s": 3457, "text": "density plots" }, { "code": null, "e": 3485, "s": 3471, "text": "density plots" }, { "code": null, "e": 3552, "s": 3485, "text": "We can add it to our Julia installation by the following command −" }, { "code": null, "e": 3583, "s": 3552, "text": "(@v1.5) pkg> add UnicodePlots\n" }, { "code": null, "e": 3639, "s": 3583, "text": "Once added, we can use this to plot a graph as follows:" }, { "code": null, "e": 3666, "s": 3639, "text": "julia> using UnicodePlots\n" }, { "code": null, "e": 3733, "s": 3666, "text": "Following Julia example generates a line chart using UnicodePlots." }, { "code": null, "e": 3852, "s": 3733, "text": "julia> FirstLinePlot = lineplot([1, 2, 3, 7], [1, 2, -5, 7], title=\"First Line Plot\", border=:dotted) First Line Plot\n" }, { "code": null, "e": 3922, "s": 3852, "text": "Following Julia example generates a density chart using UnicodePlots." }, { "code": null, "e": 4030, "s": 3922, "text": "Julia> using UnicodePlots\nJulia> FirstDensityPlot = densityplot(collect(1:100), randn(100), border=:dotted)" }, { "code": null, "e": 4169, "s": 4030, "text": "This Julia package is a visualization grammar which allows us to create visualization in a web browser window. With this package, we can −" }, { "code": null, "e": 4214, "s": 4169, "text": "describe data visualization in a JSON format" }, { "code": null, "e": 4259, "s": 4214, "text": "describe data visualization in a JSON format" }, { "code": null, "e": 4312, "s": 4259, "text": "generate interactive views using HTML5 Canvas or SVG" }, { "code": null, "e": 4365, "s": 4312, "text": "generate interactive views using HTML5 Canvas or SVG" }, { "code": null, "e": 4396, "s": 4365, "text": "It can produce the following −" }, { "code": null, "e": 4407, "s": 4396, "text": "Area plots" }, { "code": null, "e": 4418, "s": 4407, "text": "Area plots" }, { "code": null, "e": 4439, "s": 4418, "text": "Bar plots/Histograms" }, { "code": null, "e": 4460, "s": 4439, "text": "Bar plots/Histograms" }, { "code": null, "e": 4471, "s": 4460, "text": "Line plots" }, { "code": null, "e": 4482, "s": 4471, "text": "Line plots" }, { "code": null, "e": 4496, "s": 4482, "text": "Scatter plots" }, { "code": null, "e": 4510, "s": 4496, "text": "Scatter plots" }, { "code": null, "e": 4527, "s": 4510, "text": "Pie/Donut charts" }, { "code": null, "e": 4544, "s": 4527, "text": "Pie/Donut charts" }, { "code": null, "e": 4561, "s": 4544, "text": "Waterfall charts" }, { "code": null, "e": 4578, "s": 4561, "text": "Waterfall charts" }, { "code": null, "e": 4590, "s": 4578, "text": "Worldclouds" }, { "code": null, "e": 4602, "s": 4590, "text": "Worldclouds" }, { "code": null, "e": 4665, "s": 4602, "text": "We can add it to our Julia installation by following command −" }, { "code": null, "e": 4692, "s": 4665, "text": "(@v1.5) pkg> add VegaLite\n" }, { "code": null, "e": 4748, "s": 4692, "text": "Once added we can use this to plot a graph as follows −" }, { "code": null, "e": 4771, "s": 4748, "text": "julia> using VegaLite\n" }, { "code": null, "e": 4833, "s": 4771, "text": "Following Julia example generates a Pie chart using VegaLite." }, { "code": null, "e": 5041, "s": 4833, "text": "julia> X = [\"Monday\", \"Tuesday\", \"Wednesday\", \"Thrusday\", \"Friday\",\"Saturday\",\"Sunday\"];\n\njulia> Y = [11, 11, 15, 13, 12, 13, 10]\n7-element Array{Int64,1}:\n 11\n 11\n 15\n 13\n 12\n 13\n 10\n \n \njulia> P = pie(X,Y)" }, { "code": null, "e": 5074, "s": 5041, "text": "\n 73 Lectures \n 4 hours \n" }, { "code": null, "e": 5091, "s": 5074, "text": " Lemuel Ogbunude" }, { "code": null, "e": 5124, "s": 5091, "text": "\n 24 Lectures \n 3 hours \n" }, { "code": null, "e": 5141, "s": 5124, "text": " Mohammad Nauman" }, { "code": null, "e": 5176, "s": 5141, "text": "\n 29 Lectures \n 2.5 hours \n" }, { "code": null, "e": 5199, "s": 5176, "text": " Stone River ELearning" }, { "code": null, "e": 5206, "s": 5199, "text": " Print" }, { "code": null, "e": 5217, "s": 5206, "text": " Add Notes" } ]
Plotly - Polar Chart and Radar Chart
In this chapter, we will learn how Polar Chart and Radar Chart can be made with the help Plotly. First of all, let us study about polar chart. Polar Chart is a common variation of circular graphs. It is useful when relationships between data points can be visualized most easily in terms of radiuses and angles. In Polar Charts, a series is represented by a closed curve that connect points in the polar coordinate system. Each data point is determined by the distance from the pole (the radial coordinate) and the angle from the fixed direction (the angular coordinate). A polar chart represents data along radial and angular axes. The radial and angular coordinates are given with the r and theta arguments for go.Scatterpolar() function. The theta data can be categorical, but, numerical data are possible too and is the most commonly used. Following code produces a basic polar chart. In addition to r and theta arguments, we set mode to lines (it can be set to markers well in which case only the data points will be displayed). import numpy as np r1 = [0,6,12,18,24,30,36,42,48,54,60] t1 = [1,0.995,0.978,0.951,0.914,0.866,0.809,0.743,0.669,0.588,0.5] trace = go.Scatterpolar( r = [0.5,1,2,2.5,3,4], theta = [35,70,120,155,205,240], mode = 'lines', ) data = [trace] fig = go.Figure(data = data) iplot(fig) The output is given below − In the following example data from a comma-separated values (CSV) file is used to generate polar chart. First few rows of polar.csv are as follows − y,x1,x2,x3,x4,x5, 0,1,1,1,1,1, 6,0.995,0.997,0.996,0.998,0.997, 12,0.978,0.989,0.984,0.993,0.986, 18,0.951,0.976,0.963,0.985,0.969, 24,0.914,0.957,0.935,0.974,0.946, 30,0.866,0.933,0.9,0.96,0.916, 36,0.809,0.905,0.857,0.943,0.88, 42,0.743,0.872,0.807,0.923,0.838, 48,0.669,0.835,0.752,0.901,0.792, 54,0.588,0.794,0.691,0.876,0.74, 60,0.5,0.75,0.625,0.85,0.685, Enter the following script in notebook’s input cell to generate polar chart as below − import pandas as pd df = pd.read_csv("polar.csv") t1 = go.Scatterpolar( r = df['x1'], theta = df['y'], mode = 'lines', name = 't1' ) t2 = go.Scatterpolar( r = df['x2'], theta = df['y'], mode = 'lines', name = 't2' ) t3 = go.Scatterpolar( r = df['x3'], theta = df['y'], mode = 'lines', name = 't3' ) data = [t1,t2,t3] fig = go.Figure(data = data) iplot(fig) Given below is the output of the above mentioned code − A Radar Chart (also known as a spider plot or star plot) displays multivariate data in the form of a two-dimensional chart of quantitative variables represented on axes originating from the center. The relative position and angle of the axes is typically uninformative. For a Radar Chart, use a polar chart with categorical angular variables in go.Scatterpolar() function in the general case. Following code renders a basic radar chart with Scatterpolar() function − radar = go.Scatterpolar( r = [1, 5, 2, 2, 3], theta = [ 'processing cost', 'mechanical properties', 'chemical stability', 'thermal stability', 'device integration' ], fill = 'toself' ) data = [radar] fig = go.Figure(data = data) iplot(fig) The below mentioned output is a result of the above given code − 12 Lectures 53 mins Pranjal Srivastava Print Add Notes Bookmark this page
[ { "code": null, "e": 2457, "s": 2360, "text": "In this chapter, we will learn how Polar Chart and Radar Chart can be made with the help Plotly." }, { "code": null, "e": 2503, "s": 2457, "text": "First of all, let us study about polar chart." }, { "code": null, "e": 2672, "s": 2503, "text": "Polar Chart is a common variation of circular graphs. It is useful when relationships between data points can be visualized most easily in terms of radiuses and angles." }, { "code": null, "e": 2932, "s": 2672, "text": "In Polar Charts, a series is represented by a closed curve that connect points in the polar coordinate system. Each data point is determined by the distance from the pole (the radial coordinate) and the angle from the fixed direction (the angular coordinate)." }, { "code": null, "e": 3204, "s": 2932, "text": "A polar chart represents data along radial and angular axes. The radial and angular coordinates are given with the r and theta arguments for go.Scatterpolar() function. The theta data can be categorical, but, numerical data are possible too and is the most commonly used." }, { "code": null, "e": 3394, "s": 3204, "text": "Following code produces a basic polar chart. In addition to r and theta arguments, we set mode to lines (it can be set to markers well in which case only the data points will be displayed)." }, { "code": null, "e": 3681, "s": 3394, "text": "import numpy as np\nr1 = [0,6,12,18,24,30,36,42,48,54,60]\nt1 = [1,0.995,0.978,0.951,0.914,0.866,0.809,0.743,0.669,0.588,0.5]\ntrace = go.Scatterpolar(\n r = [0.5,1,2,2.5,3,4],\n theta = [35,70,120,155,205,240],\n mode = 'lines',\n)\ndata = [trace]\nfig = go.Figure(data = data)\niplot(fig)" }, { "code": null, "e": 3709, "s": 3681, "text": "The output is given below −" }, { "code": null, "e": 3858, "s": 3709, "text": "In the following example data from a comma-separated values (CSV) file is used to generate polar chart. First few rows of polar.csv are as follows −" }, { "code": null, "e": 4220, "s": 3858, "text": "y,x1,x2,x3,x4,x5,\n0,1,1,1,1,1,\n6,0.995,0.997,0.996,0.998,0.997,\n12,0.978,0.989,0.984,0.993,0.986,\n18,0.951,0.976,0.963,0.985,0.969,\n24,0.914,0.957,0.935,0.974,0.946,\n30,0.866,0.933,0.9,0.96,0.916,\n36,0.809,0.905,0.857,0.943,0.88,\n42,0.743,0.872,0.807,0.923,0.838,\n48,0.669,0.835,0.752,0.901,0.792,\n54,0.588,0.794,0.691,0.876,0.74,\n60,0.5,0.75,0.625,0.85,0.685,\n" }, { "code": null, "e": 4307, "s": 4220, "text": "Enter the following script in notebook’s input cell to generate polar chart as below −" }, { "code": null, "e": 4673, "s": 4307, "text": "import pandas as pd\ndf = pd.read_csv(\"polar.csv\")\nt1 = go.Scatterpolar(\n r = df['x1'], theta = df['y'], mode = 'lines', name = 't1'\n)\nt2 = go.Scatterpolar(\n r = df['x2'], theta = df['y'], mode = 'lines', name = 't2'\n)\nt3 = go.Scatterpolar(\n r = df['x3'], theta = df['y'], mode = 'lines', name = 't3'\n)\ndata = [t1,t2,t3]\nfig = go.Figure(data = data)\niplot(fig)" }, { "code": null, "e": 4729, "s": 4673, "text": "Given below is the output of the above mentioned code −" }, { "code": null, "e": 4999, "s": 4729, "text": "A Radar Chart (also known as a spider plot or star plot) displays multivariate data in the form of a two-dimensional chart of quantitative variables represented on axes originating from the center. The relative position and angle of the axes is typically uninformative." }, { "code": null, "e": 5122, "s": 4999, "text": "For a Radar Chart, use a polar chart with categorical angular variables in go.Scatterpolar() function in the general case." }, { "code": null, "e": 5196, "s": 5122, "text": "Following code renders a basic radar chart with Scatterpolar() function −" }, { "code": null, "e": 5479, "s": 5196, "text": "radar = go.Scatterpolar(\n r = [1, 5, 2, 2, 3],\n theta = [\n 'processing cost',\n 'mechanical properties',\n 'chemical stability', \n 'thermal stability',\n 'device integration'\n ],\n fill = 'toself'\n)\ndata = [radar]\nfig = go.Figure(data = data)\niplot(fig)" }, { "code": null, "e": 5544, "s": 5479, "text": "The below mentioned output is a result of the above given code −" }, { "code": null, "e": 5576, "s": 5544, "text": "\n 12 Lectures \n 53 mins\n" }, { "code": null, "e": 5596, "s": 5576, "text": " Pranjal Srivastava" }, { "code": null, "e": 5603, "s": 5596, "text": " Print" }, { "code": null, "e": 5614, "s": 5603, "text": " Add Notes" } ]
isupper() function in C Language
The function isupper() is used to check that the character is uppercase or not. It returns non-zero value if successful otherwise, return zero. It is declared in “ctype.h” header file. Here is the syntax of isupper() in C language, int isupper(int character); Here, character − The character which is to be checked. Here is an example of isupper() in C language, Live Demo #include<stdio.h> #include<ctype.h> int main() { char val1 = 's'; char val2 = 'S'; if(isupper(val1)) printf("The character is uppercase\n"); else printf("The character is not uppercase\n"); if(isupper(val2)) printf("The character is uppercase\n"); else printf("The character is not uppercase"); return 0; } The character is not uppercase The character is uppercase In the above program, two variables val1 and val2 are initialized with random alphabets and by using isupper() function, these variables are checked that they are uppercase letter or not. char val1 = 's'; char val2 = 'S'; if(isupper(val1)) printf("The character is uppercase\n"); else printf("The character is not uppercase\n");
[ { "code": null, "e": 1247, "s": 1062, "text": "The function isupper() is used to check that the character is uppercase or not. It returns non-zero value if successful otherwise, return zero. It is declared in “ctype.h” header file." }, { "code": null, "e": 1294, "s": 1247, "text": "Here is the syntax of isupper() in C language," }, { "code": null, "e": 1322, "s": 1294, "text": "int isupper(int character);" }, { "code": null, "e": 1328, "s": 1322, "text": "Here," }, { "code": null, "e": 1378, "s": 1328, "text": "character − The character which is to be checked." }, { "code": null, "e": 1425, "s": 1378, "text": "Here is an example of isupper() in C language," }, { "code": null, "e": 1436, "s": 1425, "text": " Live Demo" }, { "code": null, "e": 1776, "s": 1436, "text": "#include<stdio.h>\n#include<ctype.h>\nint main() {\n char val1 = 's';\n char val2 = 'S';\n if(isupper(val1))\n printf(\"The character is uppercase\\n\");\n else\n printf(\"The character is not uppercase\\n\");\n if(isupper(val2))\n printf(\"The character is uppercase\\n\");\n else\n printf(\"The character is not uppercase\");\n return 0;\n}" }, { "code": null, "e": 1834, "s": 1776, "text": "The character is not uppercase\nThe character is uppercase" }, { "code": null, "e": 2022, "s": 1834, "text": "In the above program, two variables val1 and val2 are initialized with random alphabets and by using isupper() function, these variables are checked that they are uppercase letter or not." }, { "code": null, "e": 2163, "s": 2022, "text": "char val1 = 's';\nchar val2 = 'S';\nif(isupper(val1))\nprintf(\"The character is uppercase\\n\");\nelse\nprintf(\"The character is not uppercase\\n\");" } ]
Python - Convert Index Dictionary to List - GeeksforGeeks
03 Jul, 2020 Sometimes, while working with Python dictionaries, we can have a problem in which we have keys mapped with values, where keys represent list index where value has to be placed. This kind of problem can have application in all data domains such as web development. Let’s discuss certain ways in which this task can be performed. Input : test_dict = { 1 : ‘Gfg’, 3 : ‘is’, 5 : ‘Best’ }Output : [0, ‘Gfg’, 0, ‘is’, 0, ‘Best’, 0, 0, 0, 0, 0] Input : test_dict = { 2 : ‘Gfg’, 6 : ‘Best’ }Output : [0, 0, ‘Gfg’, 0, 0, 0, ‘Best’, 0, 0, 0, 0] Method #1 : Using list comprehension + keys()The combination of above functions can be used to solve this problem. In this, we perform the task of assigning values to list checking for index, by extracting keys of dictionary for lookup. # Python3 code to demonstrate working of # Convert Index Dictionary to List# Using list comprehension + keys() # initializing dictionarytest_dict = { 2 : 'Gfg', 4 : 'is', 6 : 'Best' } # printing original dictionaryprint("The original dictionary is : " + str(test_dict)) # Convert Index Dictionary to List# Using list comprehension + keys()res = [test_dict[key] if key in test_dict.keys() else 0 for key in range(10)] # printing result print("The converted list : " + str(res)) The original dictionary is : {2: 'Gfg', 4: 'is', 6: 'Best'} The converted list : [0, 0, 'Gfg', 0, 'is', 0, 'Best', 0, 0, 0] Method #2 : Using list comprehension + get()The combination of above functions can be used to solve this problem. In this, we extract element using get(), so as to assign the default values harnessing default value initializing property of get(). # Python3 code to demonstrate working of # Convert Index Dictionary to List# Using list comprehension + get() # initializing dictionarytest_dict = { 2 : 'Gfg', 4 : 'is', 6 : 'Best' } # printing original dictionaryprint("The original dictionary is : " + str(test_dict)) # Convert Index Dictionary to List# Using list comprehension + get()res = [test_dict.get(ele, 0) for ele in range(10)] # printing result print("The converted list : " + str(res)) The original dictionary is : {2: 'Gfg', 4: 'is', 6: 'Best'} The converted list : [0, 0, 'Gfg', 0, 'is', 0, 'Best', 0, 0, 0] Python dictionary-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python Different ways to create Pandas Dataframe Python 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 program to check whether a number is Prime or not
[ { "code": null, "e": 23933, "s": 23905, "text": "\n03 Jul, 2020" }, { "code": null, "e": 24261, "s": 23933, "text": "Sometimes, while working with Python dictionaries, we can have a problem in which we have keys mapped with values, where keys represent list index where value has to be placed. This kind of problem can have application in all data domains such as web development. Let’s discuss certain ways in which this task can be performed." }, { "code": null, "e": 24371, "s": 24261, "text": "Input : test_dict = { 1 : ‘Gfg’, 3 : ‘is’, 5 : ‘Best’ }Output : [0, ‘Gfg’, 0, ‘is’, 0, ‘Best’, 0, 0, 0, 0, 0]" }, { "code": null, "e": 24468, "s": 24371, "text": "Input : test_dict = { 2 : ‘Gfg’, 6 : ‘Best’ }Output : [0, 0, ‘Gfg’, 0, 0, 0, ‘Best’, 0, 0, 0, 0]" }, { "code": null, "e": 24705, "s": 24468, "text": "Method #1 : Using list comprehension + keys()The combination of above functions can be used to solve this problem. In this, we perform the task of assigning values to list checking for index, by extracting keys of dictionary for lookup." }, { "code": "# Python3 code to demonstrate working of # Convert Index Dictionary to List# Using list comprehension + keys() # initializing dictionarytest_dict = { 2 : 'Gfg', 4 : 'is', 6 : 'Best' } # printing original dictionaryprint(\"The original dictionary is : \" + str(test_dict)) # Convert Index Dictionary to List# Using list comprehension + keys()res = [test_dict[key] if key in test_dict.keys() else 0 for key in range(10)] # printing result print(\"The converted list : \" + str(res)) ", "e": 25188, "s": 24705, "text": null }, { "code": null, "e": 25313, "s": 25188, "text": "The original dictionary is : {2: 'Gfg', 4: 'is', 6: 'Best'}\nThe converted list : [0, 0, 'Gfg', 0, 'is', 0, 'Best', 0, 0, 0]\n" }, { "code": null, "e": 25562, "s": 25315, "text": "Method #2 : Using list comprehension + get()The combination of above functions can be used to solve this problem. In this, we extract element using get(), so as to assign the default values harnessing default value initializing property of get()." }, { "code": "# Python3 code to demonstrate working of # Convert Index Dictionary to List# Using list comprehension + get() # initializing dictionarytest_dict = { 2 : 'Gfg', 4 : 'is', 6 : 'Best' } # printing original dictionaryprint(\"The original dictionary is : \" + str(test_dict)) # Convert Index Dictionary to List# Using list comprehension + get()res = [test_dict.get(ele, 0) for ele in range(10)] # printing result print(\"The converted list : \" + str(res)) ", "e": 26016, "s": 25562, "text": null }, { "code": null, "e": 26141, "s": 26016, "text": "The original dictionary is : {2: 'Gfg', 4: 'is', 6: 'Best'}\nThe converted list : [0, 0, 'Gfg', 0, 'is', 0, 'Best', 0, 0, 0]\n" }, { "code": null, "e": 26168, "s": 26141, "text": "Python dictionary-programs" }, { "code": null, "e": 26175, "s": 26168, "text": "Python" }, { "code": null, "e": 26191, "s": 26175, "text": "Python Programs" }, { "code": null, "e": 26289, "s": 26191, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26298, "s": 26289, "text": "Comments" }, { "code": null, "e": 26311, "s": 26298, "text": "Old Comments" }, { "code": null, "e": 26346, "s": 26311, "text": "Read a file line by line in Python" }, { "code": null, "e": 26368, "s": 26346, "text": "Enumerate() in Python" }, { "code": null, "e": 26400, "s": 26368, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26430, "s": 26400, "text": "Iterate over a list in Python" }, { "code": null, "e": 26472, "s": 26430, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 26515, "s": 26472, "text": "Python program to convert a list to string" }, { "code": null, "e": 26537, "s": 26515, "text": "Defaultdict in Python" }, { "code": null, "e": 26576, "s": 26537, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 26622, "s": 26576, "text": "Python | Split string into list of characters" } ]
Risk
Risk can be defined as the probability of an event, hazard, accident, threat or situation occurring and its undesirable consequences. It is a factor that could result in negative consequences and usually expressed as the product of impact and likelihood. Risk = Probability of the event occurring x Impact if it did happen In software terminology, the risk is broadly divided into two main categories: Supplier issues Supplier issues Organizational factors Organizational factors Technical issues Technical issues Below are some of the product risks occurring in a LIVE environment: Defect Prone Software delivered Defect Prone Software delivered The Critical defects in the product that could cause harm to an individual (injury or death) or company The Critical defects in the product that could cause harm to an individual (injury or death) or company Poor software Features Poor software Features Inconsistent Software Features Inconsistent Software Features 80 Lectures 7.5 hours Arnab Chakraborty 10 Lectures 1 hours Zach Miller 17 Lectures 1.5 hours Zach Miller 60 Lectures 5 hours John Shea 99 Lectures 10 hours Daniel IT 62 Lectures 5 hours GlobalETraining Print Add Notes Bookmark this page
[ { "code": null, "e": 6000, "s": 5745, "text": "Risk can be defined as the probability of an event, hazard, accident, threat or situation occurring and its undesirable consequences. It is a factor that could result in negative consequences and usually expressed as the product of impact and likelihood." }, { "code": null, "e": 6069, "s": 6000, "text": "Risk = Probability of the event occurring x Impact if it did happen " }, { "code": null, "e": 6148, "s": 6069, "text": "In software terminology, the risk is broadly divided into two main categories:" }, { "code": null, "e": 6164, "s": 6148, "text": "Supplier issues" }, { "code": null, "e": 6180, "s": 6164, "text": "Supplier issues" }, { "code": null, "e": 6203, "s": 6180, "text": "Organizational factors" }, { "code": null, "e": 6226, "s": 6203, "text": "Organizational factors" }, { "code": null, "e": 6243, "s": 6226, "text": "Technical issues" }, { "code": null, "e": 6260, "s": 6243, "text": "Technical issues" }, { "code": null, "e": 6329, "s": 6260, "text": "Below are some of the product risks occurring in a LIVE environment:" }, { "code": null, "e": 6361, "s": 6329, "text": "Defect Prone Software delivered" }, { "code": null, "e": 6393, "s": 6361, "text": "Defect Prone Software delivered" }, { "code": null, "e": 6497, "s": 6393, "text": "The Critical defects in the product that could cause harm to an individual (injury or death) or company" }, { "code": null, "e": 6601, "s": 6497, "text": "The Critical defects in the product that could cause harm to an individual (injury or death) or company" }, { "code": null, "e": 6624, "s": 6601, "text": "Poor software Features" }, { "code": null, "e": 6647, "s": 6624, "text": "Poor software Features" }, { "code": null, "e": 6678, "s": 6647, "text": "Inconsistent Software Features" }, { "code": null, "e": 6709, "s": 6678, "text": "Inconsistent Software Features" }, { "code": null, "e": 6744, "s": 6709, "text": "\n 80 Lectures \n 7.5 hours \n" }, { "code": null, "e": 6763, "s": 6744, "text": " Arnab Chakraborty" }, { "code": null, "e": 6796, "s": 6763, "text": "\n 10 Lectures \n 1 hours \n" }, { "code": null, "e": 6809, "s": 6796, "text": " Zach Miller" }, { "code": null, "e": 6844, "s": 6809, "text": "\n 17 Lectures \n 1.5 hours \n" }, { "code": null, "e": 6857, "s": 6844, "text": " Zach Miller" }, { "code": null, "e": 6890, "s": 6857, "text": "\n 60 Lectures \n 5 hours \n" }, { "code": null, "e": 6901, "s": 6890, "text": " John Shea" }, { "code": null, "e": 6935, "s": 6901, "text": "\n 99 Lectures \n 10 hours \n" }, { "code": null, "e": 6946, "s": 6935, "text": " Daniel IT" }, { "code": null, "e": 6979, "s": 6946, "text": "\n 62 Lectures \n 5 hours \n" }, { "code": null, "e": 6996, "s": 6979, "text": " GlobalETraining" }, { "code": null, "e": 7003, "s": 6996, "text": " Print" }, { "code": null, "e": 7014, "s": 7003, "text": " Add Notes" } ]
Java - The LinkedHashMap Class
This class extends HashMap and maintains a linked list of the entries in the map, in the order in which they were inserted. This allows insertion-order iteration over the map. That is, when iterating a LinkedHashMap, the elements will be returned in the order in which they were inserted. You can also create a LinkedHashMap that returns its elements in the order in which they were last accessed. Following is the list of constructors supported by the LinkedHashMap class. LinkedHashMap( ) This constructor constructs a default LinkedHashMap. LinkedHashMap(Map m) This constructor initializes the LinkedHashMap with the elements from the given Map class m. LinkedHashMap(int capacity) This constructor initializes a LinkedHashMap with the given capacity. LinkedHashMap(int capacity, float fillRatio) This constructor initializes both the capacity and the fill ratio. The meaning of capacity and fill ratio are the same as for HashMap. LinkedHashMap(int capacity, float fillRatio, boolean Order) This constructor allows you to specify whether the elements will be stored in the linked list by insertion order, or by order of last access. If Order is true, then access order is used. If Order is false, then insertion order is used. Apart from the methods inherited from its parent classes, LinkedHashMap defines the following methods − void clear() Removes all mappings from this map. boolean containsKey(Object key) Returns true if this map maps one or more keys to the specified value. Object get(Object key) Returns the value to which this map maps the specified key. protected boolean removeEldestEntry(Map.Entry eldest) Returns true if this map should remove its eldest entry. The following program illustrates several of the methods supported by this collection − import java.util.*; public class LinkedHashMapDemo { public static void main(String args[]) { // Create a hash map LinkedHashMap lhm = new LinkedHashMap(); // Put elements to the map lhm.put("Zara", new Double(3434.34)); lhm.put("Mahnaz", new Double(123.22)); lhm.put("Ayan", new Double(1378.00)); lhm.put("Daisy", new Double(99.22)); lhm.put("Qadir", new Double(-19.08)); // Get a set of the entries Set set = lhm.entrySet(); // Get an iterator Iterator i = set.iterator(); // Display elements while(i.hasNext()) { Map.Entry me = (Map.Entry)i.next(); System.out.print(me.getKey() + ": "); System.out.println(me.getValue()); } System.out.println(); // Deposit 1000 into Zara's account double balance = ((Double)lhm.get("Zara")).doubleValue(); lhm.put("Zara", new Double(balance + 1000)); System.out.println("Zara's new balance: " + lhm.get("Zara")); } } This will produce the following result − Zara: 3434.34 Mahnaz: 123.22 Ayan: 1378.0 Daisy: 99.22 Qadir: -19.08 Zara's new balance: 4434.34 16 Lectures 2 hours Malhar Lathkar 19 Lectures 5 hours Malhar Lathkar 25 Lectures 2.5 hours Anadi Sharma 126 Lectures 7 hours Tushar Kale 119 Lectures 17.5 hours Monica Mittal 76 Lectures 7 hours Arnab Chakraborty Print Add Notes Bookmark this page
[ { "code": null, "e": 2666, "s": 2377, "text": "This class extends HashMap and maintains a linked list of the entries in the map, in the order in which they were inserted. This allows insertion-order iteration over the map. That is, when iterating a LinkedHashMap, the elements will be returned in the order in which they were inserted." }, { "code": null, "e": 2775, "s": 2666, "text": "You can also create a LinkedHashMap that returns its elements in the order in which they were last accessed." }, { "code": null, "e": 2851, "s": 2775, "text": "Following is the list of constructors supported by the LinkedHashMap class." }, { "code": null, "e": 2868, "s": 2851, "text": "LinkedHashMap( )" }, { "code": null, "e": 2921, "s": 2868, "text": "This constructor constructs a default LinkedHashMap." }, { "code": null, "e": 2942, "s": 2921, "text": "LinkedHashMap(Map m)" }, { "code": null, "e": 3035, "s": 2942, "text": "This constructor initializes the LinkedHashMap with the elements from the given Map class m." }, { "code": null, "e": 3063, "s": 3035, "text": "LinkedHashMap(int capacity)" }, { "code": null, "e": 3133, "s": 3063, "text": "This constructor initializes a LinkedHashMap with the given capacity." }, { "code": null, "e": 3178, "s": 3133, "text": "LinkedHashMap(int capacity, float fillRatio)" }, { "code": null, "e": 3313, "s": 3178, "text": "This constructor initializes both the capacity and the fill ratio. The meaning of capacity and fill ratio are the same as for HashMap." }, { "code": null, "e": 3373, "s": 3313, "text": "LinkedHashMap(int capacity, float fillRatio, boolean Order)" }, { "code": null, "e": 3609, "s": 3373, "text": "This constructor allows you to specify whether the elements will be stored in the linked list by insertion order, or by order of last access. If Order is true, then access order is used. If Order is false, then insertion order is used." }, { "code": null, "e": 3713, "s": 3609, "text": "Apart from the methods inherited from its parent classes, LinkedHashMap defines the following methods −" }, { "code": null, "e": 3726, "s": 3713, "text": "void clear()" }, { "code": null, "e": 3762, "s": 3726, "text": "Removes all mappings from this map." }, { "code": null, "e": 3794, "s": 3762, "text": "boolean containsKey(Object key)" }, { "code": null, "e": 3865, "s": 3794, "text": "Returns true if this map maps one or more keys to the specified value." }, { "code": null, "e": 3888, "s": 3865, "text": "Object get(Object key)" }, { "code": null, "e": 3948, "s": 3888, "text": "Returns the value to which this map maps the specified key." }, { "code": null, "e": 4002, "s": 3948, "text": "protected boolean removeEldestEntry(Map.Entry eldest)" }, { "code": null, "e": 4059, "s": 4002, "text": "Returns true if this map should remove its eldest entry." }, { "code": null, "e": 4147, "s": 4059, "text": "The following program illustrates several of the methods supported by this collection −" }, { "code": null, "e": 5190, "s": 4147, "text": "import java.util.*;\npublic class LinkedHashMapDemo {\n\n public static void main(String args[]) {\n // Create a hash map\n LinkedHashMap lhm = new LinkedHashMap();\n \n // Put elements to the map\n lhm.put(\"Zara\", new Double(3434.34));\n lhm.put(\"Mahnaz\", new Double(123.22));\n lhm.put(\"Ayan\", new Double(1378.00));\n lhm.put(\"Daisy\", new Double(99.22));\n lhm.put(\"Qadir\", new Double(-19.08));\n \n // Get a set of the entries\n Set set = lhm.entrySet();\n \n // Get an iterator\n Iterator i = set.iterator();\n \n // Display elements\n while(i.hasNext()) {\n Map.Entry me = (Map.Entry)i.next();\n System.out.print(me.getKey() + \": \");\n System.out.println(me.getValue());\n }\n System.out.println();\n \n // Deposit 1000 into Zara's account\n double balance = ((Double)lhm.get(\"Zara\")).doubleValue();\n lhm.put(\"Zara\", new Double(balance + 1000));\n System.out.println(\"Zara's new balance: \" + lhm.get(\"Zara\"));\n }\n}" }, { "code": null, "e": 5231, "s": 5190, "text": "This will produce the following result −" }, { "code": null, "e": 5330, "s": 5231, "text": "Zara: 3434.34\nMahnaz: 123.22\nAyan: 1378.0\nDaisy: 99.22\nQadir: -19.08\n\nZara's new balance: 4434.34\n" }, { "code": null, "e": 5363, "s": 5330, "text": "\n 16 Lectures \n 2 hours \n" }, { "code": null, "e": 5379, "s": 5363, "text": " Malhar Lathkar" }, { "code": null, "e": 5412, "s": 5379, "text": "\n 19 Lectures \n 5 hours \n" }, { "code": null, "e": 5428, "s": 5412, "text": " Malhar Lathkar" }, { "code": null, "e": 5463, "s": 5428, "text": "\n 25 Lectures \n 2.5 hours \n" }, { "code": null, "e": 5477, "s": 5463, "text": " Anadi Sharma" }, { "code": null, "e": 5511, "s": 5477, "text": "\n 126 Lectures \n 7 hours \n" }, { "code": null, "e": 5525, "s": 5511, "text": " Tushar Kale" }, { "code": null, "e": 5562, "s": 5525, "text": "\n 119 Lectures \n 17.5 hours \n" }, { "code": null, "e": 5577, "s": 5562, "text": " Monica Mittal" }, { "code": null, "e": 5610, "s": 5577, "text": "\n 76 Lectures \n 7 hours \n" }, { "code": null, "e": 5629, "s": 5610, "text": " Arnab Chakraborty" }, { "code": null, "e": 5636, "s": 5629, "text": " Print" }, { "code": null, "e": 5647, "s": 5636, "text": " Add Notes" } ]
Program to convert given number of days in terms of Years, Weeks and Days in C
You are given with number of days, and the task is to convert the given number of days in terms of years, weeks and days. Let us assume the number of days in a year =365 Number of year = (number of days) / 365 Explanation-: number of years will be the quotient obtained by dividing the given number of days with 365 Number of weeks = (number of days % 365) / 7 Explanation-: number of weeks will be obtained by collecting the remainder from dividing the number of days with 365 and further dividing the result with number of days in a week which is 7. Number of days = (number of days % 365) % 7 Explanation-: number of days will be obtained by collecting the remainder from dividing the number of days with 365 and further acquiring the remainder by dividing the partial remainder with number of days in a week which is 7. Input-:days = 209 Output-: years = 0 weeks = 29 days = 6 Input-: days = 1000 Output-: years = 2 weeks = 38 days = 4 Start Step 1-> declare macro for number of days as const int n=7 Step 2-> Declare function to convert number of days in terms of Years, Weeks and Days void find(int total_days) declare variables as int year, weeks, days Set year = total_days / 365 Set weeks = (total_days % 365) / n Set days = (total_days % 365) % n Print year, weeks and days Step 3-> in main() Declare int Total_days = 209 Call find(Total_days) Stop Live Demo #include <stdio.h> const int n=7 ; //find year, week, days void find(int total_days) { int year, weeks, days; // assuming its not a leap year year = total_days / 365; weeks = (total_days % 365) / n; days = (total_days % 365) % n; printf("years = %d",year); printf("\nweeks = %d", weeks); printf("\ndays = %d ",days); } int main() { int Total_days = 209; find(Total_days); return 0; } IF WE RUN THE ABOVE CODE IT WILL GENERATE FOLLOWING OUTPUT years = 0 weeks = 29 days = 6
[ { "code": null, "e": 1184, "s": 1062, "text": "You are given with number of days, and the task is to convert the given number of days in terms of years, weeks and days." }, { "code": null, "e": 1232, "s": 1184, "text": "Let us assume the number of days in a year =365" }, { "code": null, "e": 1272, "s": 1232, "text": "Number of year = (number of days) / 365" }, { "code": null, "e": 1378, "s": 1272, "text": "Explanation-: number of years will be the quotient obtained by dividing the given number of days with 365" }, { "code": null, "e": 1423, "s": 1378, "text": "Number of weeks = (number of days % 365) / 7" }, { "code": null, "e": 1614, "s": 1423, "text": "Explanation-: number of weeks will be obtained by collecting the remainder from dividing the number of days with 365 and further dividing the result with number of days in a week which is 7." }, { "code": null, "e": 1658, "s": 1614, "text": "Number of days = (number of days % 365) % 7" }, { "code": null, "e": 1886, "s": 1658, "text": "Explanation-: number of days will be obtained by collecting the remainder from dividing the number of days with 365 and further acquiring the remainder by dividing the partial remainder with number of days in a week which is 7." }, { "code": null, "e": 2014, "s": 1886, "text": "Input-:days = 209\nOutput-: years = 0\n weeks = 29\n days = 6\nInput-: days = 1000\nOutput-: years = 2\n weeks = 38\n days = 4" }, { "code": null, "e": 2472, "s": 2014, "text": "Start\nStep 1-> declare macro for number of days as const int n=7\nStep 2-> Declare function to convert number of days in terms of Years, Weeks and Days\n void find(int total_days)\n declare variables as int year, weeks, days\n Set year = total_days / 365\n Set weeks = (total_days % 365) / n\n Set days = (total_days % 365) % n\n Print year, weeks and days\nStep 3-> in main()\n Declare int Total_days = 209\n Call find(Total_days)\nStop" }, { "code": null, "e": 2483, "s": 2472, "text": " Live Demo" }, { "code": null, "e": 2900, "s": 2483, "text": "#include <stdio.h>\nconst int n=7 ;\n//find year, week, days\nvoid find(int total_days) {\n int year, weeks, days;\n // assuming its not a leap year\n year = total_days / 365;\n weeks = (total_days % 365) / n;\n days = (total_days % 365) % n;\n printf(\"years = %d\",year);\n printf(\"\\nweeks = %d\", weeks);\n printf(\"\\ndays = %d \",days);\n}\nint main() {\n int Total_days = 209;\n find(Total_days);\n return 0;\n}" }, { "code": null, "e": 2959, "s": 2900, "text": "IF WE RUN THE ABOVE CODE IT WILL GENERATE FOLLOWING OUTPUT" }, { "code": null, "e": 2989, "s": 2959, "text": "years = 0\nweeks = 29\ndays = 6" } ]
Basic Calculator II in Python
Suppose we have to implement a basic calculator to evaluate a simple expression string. The expression string will hold only non-negative integers, some operators like, +, -, *, / and empty spaces. The integer division should take the quotient part only. So if the input is like “3+2*2”, then the output will be 7. To solve this, we will follow these steps − define a stack s, i := 0, x := an empty string for each character j in sif j is not a blank characterappend j into x if j is not a blank characterappend j into x append j into x s := x, n := length of x while i < nif s[i] is ‘/’, thenincrease i by 1num := number starting from ith index, then update i as the last character of the numberif stack top element < 0, then update stack top element as -(stack top / num), otherwise update stack top element as (stack top / num)otherwise when s[i] = “*”increase i by 1num := number starting from ith index, then update i as the last character of the numberstack top := num * stack topotherwise when s[i] = ‘-’increase i by 1num := number starting from ith index, then update i as the last character of the numberinsert –num into stackotherwisenum := number starting from ith index, then update i as the last character of the numberinsert num into stackincrease i by 1 if s[i] is ‘/’, thenincrease i by 1num := number starting from ith index, then update i as the last character of the numberif stack top element < 0, then update stack top element as -(stack top / num), otherwise update stack top element as (stack top / num) increase i by 1 num := number starting from ith index, then update i as the last character of the number if stack top element < 0, then update stack top element as -(stack top / num), otherwise update stack top element as (stack top / num) otherwise when s[i] = “*”increase i by 1num := number starting from ith index, then update i as the last character of the numberstack top := num * stack top increase i by 1 num := number starting from ith index, then update i as the last character of the number stack top := num * stack top otherwise when s[i] = ‘-’increase i by 1num := number starting from ith index, then update i as the last character of the numberinsert –num into stack increase i by 1 num := number starting from ith index, then update i as the last character of the number insert –num into stack otherwisenum := number starting from ith index, then update i as the last character of the numberinsert num into stackincrease i by 1 num := number starting from ith index, then update i as the last character of the number insert num into stack increase i by 1 return sum of the elements of the stack Let us see the following implementation to get better understanding − class Solution(object): def calculate(self, s): """ :type s: str :rtype: int """ stack = [] i = 0 x="" for j in s: if j !=" ": x+=j s = x n = len(s) while i<n: if s[i] == '/': i+=1 num,i = self.make_num(s,i) if stack[-1]<0: stack[-1] = -1*(abs(stack[-1])/num) else: stack[-1] = stack[-1]/num elif s[i] == '*': i+=1 num,i = self.make_num(s,i) stack[-1] = stack[-1]*num elif s[i] == '-': i+=1 num,i = self.make_num(s,i) stack.append(-num) elif s[i] =='+': i+=1 num,i = self.make_num(s,i) stack.append(num) else: num,i = self.make_num(s,i) stack.append(num) i+=1 return sum(stack) def make_num(self,s,i): start = i while i<len(s) and s[i]!= '/' and s[i]!= '*' and s[i]!= '-' and s[i]!='+': i+=1 return int(s[start:i]),i-1 "3+2*2" 7
[ { "code": null, "e": 1317, "s": 1062, "text": "Suppose we have to implement a basic calculator to evaluate a simple expression string. The expression string will hold only non-negative integers, some operators like, +, -, *, / and empty spaces. The integer division should take the quotient part only." }, { "code": null, "e": 1377, "s": 1317, "text": "So if the input is like “3+2*2”, then the output will be 7." }, { "code": null, "e": 1421, "s": 1377, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1468, "s": 1421, "text": "define a stack s, i := 0, x := an empty string" }, { "code": null, "e": 1538, "s": 1468, "text": "for each character j in sif j is not a blank characterappend j into x" }, { "code": null, "e": 1583, "s": 1538, "text": "if j is not a blank characterappend j into x" }, { "code": null, "e": 1599, "s": 1583, "text": "append j into x" }, { "code": null, "e": 1624, "s": 1599, "text": "s := x, n := length of x" }, { "code": null, "e": 2332, "s": 1624, "text": "while i < nif s[i] is ‘/’, thenincrease i by 1num := number starting from ith index, then update i as the last character of the numberif stack top element < 0, then update stack top element as -(stack top / num), otherwise update stack top element as (stack top / num)otherwise when s[i] = “*”increase i by 1num := number starting from ith index, then update i as the last character of the numberstack top := num * stack topotherwise when s[i] = ‘-’increase i by 1num := number starting from ith index, then update i as the last character of the numberinsert –num into stackotherwisenum := number starting from ith index, then update i as the last character of the numberinsert num into stackincrease i by 1" }, { "code": null, "e": 2590, "s": 2332, "text": "if s[i] is ‘/’, thenincrease i by 1num := number starting from ith index, then update i as the last character of the numberif stack top element < 0, then update stack top element as -(stack top / num), otherwise update stack top element as (stack top / num)" }, { "code": null, "e": 2606, "s": 2590, "text": "increase i by 1" }, { "code": null, "e": 2695, "s": 2606, "text": "num := number starting from ith index, then update i as the last character of the number" }, { "code": null, "e": 2830, "s": 2695, "text": "if stack top element < 0, then update stack top element as -(stack top / num), otherwise update stack top element as (stack top / num)" }, { "code": null, "e": 2987, "s": 2830, "text": "otherwise when s[i] = “*”increase i by 1num := number starting from ith index, then update i as the last character of the numberstack top := num * stack top" }, { "code": null, "e": 3003, "s": 2987, "text": "increase i by 1" }, { "code": null, "e": 3092, "s": 3003, "text": "num := number starting from ith index, then update i as the last character of the number" }, { "code": null, "e": 3121, "s": 3092, "text": "stack top := num * stack top" }, { "code": null, "e": 3272, "s": 3121, "text": "otherwise when s[i] = ‘-’increase i by 1num := number starting from ith index, then update i as the last character of the numberinsert –num into stack" }, { "code": null, "e": 3288, "s": 3272, "text": "increase i by 1" }, { "code": null, "e": 3377, "s": 3288, "text": "num := number starting from ith index, then update i as the last character of the number" }, { "code": null, "e": 3400, "s": 3377, "text": "insert –num into stack" }, { "code": null, "e": 3534, "s": 3400, "text": "otherwisenum := number starting from ith index, then update i as the last character of the numberinsert num into stackincrease i by 1" }, { "code": null, "e": 3623, "s": 3534, "text": "num := number starting from ith index, then update i as the last character of the number" }, { "code": null, "e": 3645, "s": 3623, "text": "insert num into stack" }, { "code": null, "e": 3661, "s": 3645, "text": "increase i by 1" }, { "code": null, "e": 3701, "s": 3661, "text": "return sum of the elements of the stack" }, { "code": null, "e": 3771, "s": 3701, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 4808, "s": 3771, "text": "class Solution(object):\n def calculate(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n stack = []\n i = 0\n x=\"\"\n for j in s:\n if j !=\" \":\n x+=j\n s = x\n n = len(s)\n while i<n:\n if s[i] == '/':\n i+=1\n num,i = self.make_num(s,i)\n if stack[-1]<0:\n stack[-1] = -1*(abs(stack[-1])/num)\n else:\n stack[-1] = stack[-1]/num\n elif s[i] == '*':\n i+=1\n num,i = self.make_num(s,i)\n stack[-1] = stack[-1]*num\n elif s[i] == '-':\n i+=1\n num,i = self.make_num(s,i)\n stack.append(-num)\n elif s[i] =='+':\n i+=1\n num,i = self.make_num(s,i)\n stack.append(num)\n else:\n num,i = self.make_num(s,i)\n stack.append(num)\n i+=1\n return sum(stack)\n def make_num(self,s,i):\n start = i\n while i<len(s) and s[i]!= '/' and s[i]!= '*' and s[i]!= '-' and s[i]!='+':\n i+=1\n return int(s[start:i]),i-1" }, { "code": null, "e": 4816, "s": 4808, "text": "\"3+2*2\"" }, { "code": null, "e": 4818, "s": 4816, "text": "7" } ]
AIML - <star> Tag
<star> Tag is used to match wild card * character(s) in <pattern> Tag. <star index = "n"/> n signifies the position of * within the user input in <pattern> Tag. Consider the following example − <category> <pattern> A * is a *. </pattern> <template> When a <star index = "1"/> is not a <star index = "2"/>? </template> </category> If the user enters "A mango is a fruit." then bot will respond as "When a mango is not a fruit?" Create star.aiml inside C > ab > bots > test > aiml and star.aiml.csv inside C > ab > bots > test > aimlif directories. <?xml version = "1.0" encoding = "UTF-8"?> <aiml version = "1.0.1" encoding = "UTF-8"?> <category> <pattern>I LIKE *</pattern> <template> I too like <star/>. </template> </category> <category> <pattern>A * IS A *</pattern> <template> How <star index = "1"/> can not be a <star index = "2"/>? </template> </category> </aiml> 0,I LIKE *,*,*,I too like <star/>.,star.aiml 0,A * IS A *,*,*,How <star index = "1"/> can not be a <star index = "2"/>?,star.aiml Open the command prompt. Go to C > ab > and type the following command − java -cp lib/Ab.jar Main bot = test action = chat trace = false You will see the following output − Human: I like mango Robot: I too like mango. Human: A mango is a fruit Robot: How mango can not be a fruit? <star index = "1"/> is often used as <star /> Print Add Notes Bookmark this page
[ { "code": null, "e": 1882, "s": 1811, "text": "<star> Tag is used to match wild card * character(s) in <pattern> Tag." }, { "code": null, "e": 1903, "s": 1882, "text": "<star index = \"n\"/>\n" }, { "code": null, "e": 1974, "s": 1903, "text": "n signifies the position of * within the user input in <pattern> Tag." }, { "code": null, "e": 2007, "s": 1974, "text": "Consider the following example −" }, { "code": null, "e": 2166, "s": 2007, "text": "<category>\n <pattern> A * is a *. </pattern>\n \n <template>\n When a <star index = \"1\"/> is not a <star index = \"2\"/>?\n </template>\n \n</category>" }, { "code": null, "e": 2263, "s": 2166, "text": "If the user enters \"A mango is a fruit.\" then bot will respond as \"When a mango is not a fruit?\"" }, { "code": null, "e": 2383, "s": 2263, "text": "Create star.aiml inside C > ab > bots > test > aiml and star.aiml.csv inside C > ab > bots > test > aimlif directories." }, { "code": null, "e": 2785, "s": 2383, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<aiml version = \"1.0.1\" encoding = \"UTF-8\"?>\n \n <category>\n <pattern>I LIKE *</pattern>\n <template>\n I too like <star/>.\n </template>\n </category>\n \n <category>\n <pattern>A * IS A *</pattern>\n <template>\n How <star index = \"1\"/> can not be a <star index = \"2\"/>?\n </template>\n </category>\n \n</aiml>" }, { "code": null, "e": 2915, "s": 2785, "text": "0,I LIKE *,*,*,I too like <star/>.,star.aiml\n0,A * IS A *,*,*,How <star index = \"1\"/> can not be a <star index = \"2\"/>?,star.aiml" }, { "code": null, "e": 2988, "s": 2915, "text": "Open the command prompt. Go to C > ab > and type the following command −" }, { "code": null, "e": 3053, "s": 2988, "text": "java -cp lib/Ab.jar Main bot = test action = chat trace = false\n" }, { "code": null, "e": 3089, "s": 3053, "text": "You will see the following output −" }, { "code": null, "e": 3199, "s": 3089, "text": "Human: I like mango\nRobot: I too like mango.\nHuman: A mango is a fruit\nRobot: How mango can not be a fruit? \n" }, { "code": null, "e": 3245, "s": 3199, "text": "<star index = \"1\"/> is often used as <star />" }, { "code": null, "e": 3252, "s": 3245, "text": " Print" }, { "code": null, "e": 3263, "s": 3252, "text": " Add Notes" } ]
Difference between Instance Variable and Class Variable - GeeksforGeeks
28 Apr, 2021 Instance Variable: It is basically a class variable without a static modifier and is usually shared by all class instances. Across different objects, these variables can have different values. They are tied to a particular object instance of the class, therefore, the contents of an instance variable are totally independent of one object instance to others. Example: class Taxes { int count; /*...*/ } Class Variable: It is basically a static variable that can be declared anywhere at class level with static. Across different objects, these variables can have only one value. These variables are not tied to any particular object of the class, therefore, can share across all objects of the class. Example: class Taxes { static int count; /*...*/ } Tabular difference between Instance and Class variable: Instance Variable Class Variable C-Variable Declaration and Scope Analysis Difference Between Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments 3-coloring is NP Complete Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete Proof that Dominant Set of a Graph is NP-Complete Proof that SAT is NP Complete Proof that Independent Set in Graph theory is NP Complete Difference between BFS and DFS Class method vs Static method in Python Differences between TCP and UDP Difference between var, let and const keywords in JavaScript Difference Between Method Overloading and Method Overriding in Java
[ { "code": null, "e": 24965, "s": 24937, "text": "\n28 Apr, 2021" }, { "code": null, "e": 25324, "s": 24965, "text": "Instance Variable: It is basically a class variable without a static modifier and is usually shared by all class instances. Across different objects, these variables can have different values. They are tied to a particular object instance of the class, therefore, the contents of an instance variable are totally independent of one object instance to others." }, { "code": null, "e": 25333, "s": 25324, "text": "Example:" }, { "code": null, "e": 25384, "s": 25333, "text": "class Taxes \n{ \n int count; \n /*...*/ \n} " }, { "code": null, "e": 25683, "s": 25384, "text": "Class Variable: It is basically a static variable that can be declared anywhere at class level with static. Across different objects, these variables can have only one value. These variables are not tied to any particular object of the class, therefore, can share across all objects of the class. " }, { "code": null, "e": 25692, "s": 25683, "text": "Example:" }, { "code": null, "e": 25750, "s": 25692, "text": "class Taxes \n{ \n static int count; \n /*...*/ \n} " }, { "code": null, "e": 25806, "s": 25750, "text": "Tabular difference between Instance and Class variable:" }, { "code": null, "e": 25824, "s": 25806, "text": "Instance Variable" }, { "code": null, "e": 25839, "s": 25824, "text": "Class Variable" }, { "code": null, "e": 25872, "s": 25839, "text": "C-Variable Declaration and Scope" }, { "code": null, "e": 25881, "s": 25872, "text": "Analysis" }, { "code": null, "e": 25900, "s": 25881, "text": "Difference Between" }, { "code": null, "e": 25998, "s": 25900, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26007, "s": 25998, "text": "Comments" }, { "code": null, "e": 26020, "s": 26007, "text": "Old Comments" }, { "code": null, "e": 26046, "s": 26020, "text": "3-coloring is NP Complete" }, { "code": null, "e": 26113, "s": 26046, "text": "Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete" }, { "code": null, "e": 26163, "s": 26113, "text": "Proof that Dominant Set of a Graph is NP-Complete" }, { "code": null, "e": 26193, "s": 26163, "text": "Proof that SAT is NP Complete" }, { "code": null, "e": 26251, "s": 26193, "text": "Proof that Independent Set in Graph theory is NP Complete" }, { "code": null, "e": 26282, "s": 26251, "text": "Difference between BFS and DFS" }, { "code": null, "e": 26322, "s": 26282, "text": "Class method vs Static method in Python" }, { "code": null, "e": 26354, "s": 26322, "text": "Differences between TCP and UDP" }, { "code": null, "e": 26415, "s": 26354, "text": "Difference between var, let and const keywords in JavaScript" } ]
Non-Negative Matrix Factorization - GeeksforGeeks
18 Jul, 2021 Prerequisite : Low Rank Approximation</p> Non-Negative Matrix Factorization: For a matrix A of dimensions m x n, where each element is ≥ 0, NMF can factorize it into two matrices W and H having dimensions m x k and k x n respectively and these two matrices only contain non-negative elements. Here, matrix A is defined as: where, A -> Original Input Matrix (Linear combination of W & H) W -> Feature Matrix H -> Coefficient Matrix (Weights associated with W) k -> Low rank approximation of A (k ≤ min(m,n)) This method is widely used in performing tasks such as feature reduction in Facial Recognition and for various NLP tasks. Intuition: Fig 1 : NMF Intuition The objective of NMF is dimensionality reduction and feature extraction. So, when we set lower dimension as k, the goal of NMF is to find two matrices W ∈ Rm×k and H ∈ Rn×k having only nonnegative elements. (As shown in Fig 1) Therefore, by using NMF we are able to obtain factorized matrices having significantly lower dimensions than those of the product matrix. Intuitively, NMF assumes that the original input is made of a set of hidden features, represented by each column of W matrix and each column in H matrix represents the ‘coordinates of a data point’ in the matrix W. In simple terms, it contains the weights associated with matrix W. In this, each data point that is represented as a column in A, can be approximated by an additive combination of the non-negative vectors, which are represented as columns in W. Real-life example: Let us consider some real-life examples to understand the working of the NMF algorithm. Let’s take a case of image processing. Suppose, we have an input image, having pixels that form matrix A. Using NMF, we factorize it into two matrices, one containing the facial feature set [Matrix W] and the other containing the importance of each facial feature in the input image, i.e. the weights [Matrix H]. (As shown in Fig 2.) Fig 2 : NMF in Image Processing NMF is used in major applications such as image processing, text mining, spectral data analysis and many more. Currently, there is an ongoing research on NMF to increase its efficiency and robustness. Other research is being done on collective factorization, efficient update of matrices etc as well. For any doubt/query, comment below. Attention reader! Don’t stop learning now. Get hold of all the important Machine Learning Concepts with the Machine Learning Foundation Course at a student-friendly price and become industry ready. Machine Learning Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments ML | Stochastic Gradient Descent (SGD) Support Vector Machine Algorithm CNN | Introduction to Pooling Layer Difference between Informed and Uninformed Search in AI ML | Logistic Regression using Python Singular Value Decomposition (SVD) Principal Component Analysis with Python Normalization vs Standardization ML | Linear Discriminant Analysis Difference between ANN, CNN and RNN
[ { "code": null, "e": 24264, "s": 24236, "text": "\n18 Jul, 2021" }, { "code": null, "e": 24306, "s": 24264, "text": "Prerequisite : Low Rank Approximation</p>" }, { "code": null, "e": 24587, "s": 24306, "text": "Non-Negative Matrix Factorization: For a matrix A of dimensions m x n, where each element is ≥ 0, NMF can factorize it into two matrices W and H having dimensions m x k and k x n respectively and these two matrices only contain non-negative elements. Here, matrix A is defined as:" }, { "code": null, "e": 24771, "s": 24587, "text": "where,\nA -> Original Input Matrix (Linear combination of W & H)\nW -> Feature Matrix\nH -> Coefficient Matrix (Weights associated with W)\nk -> Low rank approximation of A (k ≤ min(m,n))" }, { "code": null, "e": 24894, "s": 24771, "text": "This method is widely used in performing tasks such as feature reduction in Facial Recognition and for various NLP tasks. " }, { "code": null, "e": 24905, "s": 24894, "text": "Intuition:" }, { "code": null, "e": 24928, "s": 24905, "text": "Fig 1 : NMF Intuition " }, { "code": null, "e": 25155, "s": 24928, "text": "The objective of NMF is dimensionality reduction and feature extraction. So, when we set lower dimension as k, the goal of NMF is to find two matrices W ∈ Rm×k and H ∈ Rn×k having only nonnegative elements. (As shown in Fig 1)" }, { "code": null, "e": 25575, "s": 25155, "text": "Therefore, by using NMF we are able to obtain factorized matrices having significantly lower dimensions than those of the product matrix. Intuitively, NMF assumes that the original input is made of a set of hidden features, represented by each column of W matrix and each column in H matrix represents the ‘coordinates of a data point’ in the matrix W. In simple terms, it contains the weights associated with matrix W." }, { "code": null, "e": 25753, "s": 25575, "text": "In this, each data point that is represented as a column in A, can be approximated by an additive combination of the non-negative vectors, which are represented as columns in W." }, { "code": null, "e": 25773, "s": 25753, "text": "Real-life example: " }, { "code": null, "e": 25901, "s": 25773, "text": "Let us consider some real-life examples to understand the working of the NMF algorithm. Let’s take a case of image processing. " }, { "code": null, "e": 26196, "s": 25901, "text": "Suppose, we have an input image, having pixels that form matrix A. Using NMF, we factorize it into two matrices, one containing the facial feature set [Matrix W] and the other containing the importance of each facial feature in the input image, i.e. the weights [Matrix H]. (As shown in Fig 2.)" }, { "code": null, "e": 26228, "s": 26196, "text": "Fig 2 : NMF in Image Processing" }, { "code": null, "e": 26565, "s": 26228, "text": "NMF is used in major applications such as image processing, text mining, spectral data analysis and many more. Currently, there is an ongoing research on NMF to increase its efficiency and robustness. Other research is being done on collective factorization, efficient update of matrices etc as well. For any doubt/query, comment below." }, { "code": null, "e": 26763, "s": 26565, "text": "Attention reader! Don’t stop learning now. Get hold of all the important Machine Learning Concepts with the Machine Learning Foundation Course at a student-friendly price and become industry ready." }, { "code": null, "e": 26780, "s": 26763, "text": "Machine Learning" }, { "code": null, "e": 26797, "s": 26780, "text": "Machine Learning" }, { "code": null, "e": 26895, "s": 26797, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26904, "s": 26895, "text": "Comments" }, { "code": null, "e": 26917, "s": 26904, "text": "Old Comments" }, { "code": null, "e": 26956, "s": 26917, "text": "ML | Stochastic Gradient Descent (SGD)" }, { "code": null, "e": 26989, "s": 26956, "text": "Support Vector Machine Algorithm" }, { "code": null, "e": 27025, "s": 26989, "text": "CNN | Introduction to Pooling Layer" }, { "code": null, "e": 27081, "s": 27025, "text": "Difference between Informed and Uninformed Search in AI" }, { "code": null, "e": 27119, "s": 27081, "text": "ML | Logistic Regression using Python" }, { "code": null, "e": 27154, "s": 27119, "text": "Singular Value Decomposition (SVD)" }, { "code": null, "e": 27195, "s": 27154, "text": "Principal Component Analysis with Python" }, { "code": null, "e": 27228, "s": 27195, "text": "Normalization vs Standardization" }, { "code": null, "e": 27262, "s": 27228, "text": "ML | Linear Discriminant Analysis" } ]
Angular 8 - Data Binding
Data binding deals with how to bind your data from component to HTML DOM elements (Templates). We can easily interact with application without worrying about how to insert your data. We can make connections in two different ways one way and two-way binding. Before moving to this topic, let’s create a component in Angular 8. Open command prompt and create new Angular application using below command − cd /go/to/workspace ng new databind-app cd databind-app Create a test component using Angular CLI as mentioned below − ng generate component test The above create a new component and the output is as follows − CREATE src/app/test/test.component.scss (0 bytes) CREATE src/app/test/test.component.html (19 bytes) CREATE src/app/test/test.component.spec.ts (614 bytes) CREATE src/app/test/test.component.ts (262 bytes) UPDATE src/app/app.module.ts (545 bytes) Run the application using below command − ng serve One-way data binding is a one-way interaction between component and its template. If you perform any changes in your component, then it will reflect the HTML elements. It supports the following types − In general, String interpolation is the process of formatting or manipulating strings. In Angular, Interpolation is used to display data from component to view (DOM). It is denoted by the expression of {{ }} and also known as mustache syntax. Let’s create a simple string property in component and bind the data to view. Add the below code in test.component.ts file as follows − export class TestComponent implements OnInit { appName = "My first app in Angular 8"; } Move to test.component.html file and add the below code − <h1>{{appName}}</h1> Add the test component in your app.component.html file by replacing the existing content as follows − <app-test></app-test> Finally, start your application (if not done already) using the below command − ng serve You could see the following output on your screen − Events are actions like mouse click, double click, hover or any keyboard and mouse actions. If a user interacts with an application and performs some actions, then event will be raised. It is denoted by either parenthesis () or on-. We have different ways to bind an event to DOM element. Let’s understand one by one in brief. Let’s understand how simple button click even handling works. Add the following code in test.component.tsfile as follows − export class TestComponent { showData($event: any){ console.log("button is clicked!"); if($event) { console.log($event.target); console.log($event.target.value); } } } event∗refersthefiredevent⋅Inthisscenario,∗click∗istheevent⋅∗event has all the information about event and the target element. Here, the target is button. $event.target property will have the target information. We have two approaches to call the component method to view (test.component.html). First one is defined below − <h2>Event Binding</h2> <button (click)="showData($event)">Click here</button> Alternatively, you can use prefix - on using canonical form as shown below − <button on-click = "showData()">Click here</button> Here, we have not used $event as it is optional. Finally, start your application (if not done already) using the below command − ng serve Now, run your application and you could see the below response − Here, when the user clicks on the button, event binding understands to button click action and call component showData() method so we can conclude it is one-way binding. Property binding is used to bind the data from property of a component to DOM elements. It is denoted by []. Let’s understand with a simple example. Add the below code in test.component.ts file. export class TestComponent { userName:string = "Peter"; } Add the below changes in view test.component.html, <input type="text" [value]="userName"> Here, userName property is bind to an attribute of a DOM element <input> tag. Finally, start your application (if not done already) using the below command − ng serve Attribute binding is used to bind the data from component to HTML attributes. The syntax is as follows − <HTMLTag [attr.ATTR]="Component data"> For example, <td [attr.colspan]="columnSpan"> ... </td> Let’s understand with a simple example. Add the below code in test.component.ts file. export class TestComponent { userName:string = "Peter"; } Add the below changes in view test.component.html, <input type="text" [value]="userName"> Here, userName property is bind to an attribute of a DOM element <input> tag. Finally, start your application (if not done already) using the below command − ng serve Class binding is used to bind the data from component to HTML class property. The syntax is as follows − <HTMLTag [class]="component variable holding class name"> Class Binding provides additional functionality. If the component data is boolean, then the class will bind only when it is true. Multiple class can be provided by string (“foo bar”) as well as Array of string. Many more options are available. For example, <p [class]="myClasses"> Let’s understand with a simple example. Add the below code in test.component.ts file, export class TestComponent { myCSSClass = "red"; applyCSSClass = false; } Add the below changes in view test.component.html. <p [class]="myCSSClass">This paragraph class comes from *myClass* property </p> <p [class.blue]="applyCSSClass">This paragraph class does not apply</p> Add the below content in test.component.css. .red { color: red; } .blue { color: blue; } Finally, start your application (if not done already) using the below command − ng serve The final output will be as shown below − Style binding is used to bind the data from component into HTML style property. The syntax is as follows − <HTMLTag [style.STYLE]="component data"> For example, <p [style.color]="myParaColor"> ... </p> Let’s understand with a simple example. Add the below code in test.component.ts file. myColor = 'brown'; Add the below changes in view test.component.html. <p [style.color]="myColor">Text color is styled using style binding</p> Finally, start your application (if not done already) using the below command − ng serve The final output will be as shown below − Two-way data binding is a two-way interaction, data flows in both ways (from component to views and views to component). Simple example is ngModel. If you do any changes in your property (or model) then, it reflects in your view and vice versa. It is the combination of property and event binding. NgModel is a standalone directive. ngModel directive binds form control to property and property to form control. The syntax of ngModel is as follows − <HTML [(ngModel)]="model.name" /> For example, <input type="text" [(ngModel)]="model.name" /> Let’s try to use ngModel in our test application. Configure FormsModule in AppModule (src/app/app.module.ts) import { FormsModule } from '@angular/forms'; @NgModule({ imports: [ BrowserModule, FormsModule ] }) export class AppModule { } FormModule do the necessary setup to enable two-way data binding. Update TestComponent view (test.component.html) as mentioned below − <input type="text" [(ngModel)]="userName" /> <p>Two way binding! Hello {{ userName }}!</p> Here, Property is bind to form control ngModeldirective and if you enter any text in the textbox, it will bind to the property. After running your application, you could see the below changes − Finally, start your application (if not done already) using the below command − ng serve Now, run your application and you could see the below response − Now, try to change the input value to Jack. As you type, the text below the input gets changed and the final output will be as shown below − We will learn more about form controls in the upcoming chapters. Let us implement all the concept learned in this chapter in our ExpenseManager application. Open command prompt and go to project root folder. cd /go/to/expense-manager Create ExpenseEntry interface (src/app/expense-entry.ts) and add id, amount, category, Location, spendOn and createdOn. export interface ExpenseEntry { id: number; item: string; amount: number; category: string; location: string; spendOn: Date; createdOn: Date; } Import ExpenseEntry into ExpenseEntryComponent. import { ExpenseEntry } from '../expense-entry'; Create a ExpenseEntry object, expenseEntry as shown below − export class ExpenseEntryComponent implements OnInit { title: string; expenseEntry: ExpenseEntry; constructor() { } ngOnInit() { this.title = "Expense Entry"; this.expenseEntry = { id: 1, item: "Pizza", amount: 21, category: "Food", location: "Zomato", spendOn: new Date(2020, 6, 1, 10, 10, 10), createdOn: new Date(2020, 6, 1, 10, 10, 10), }; } } Update the component template using expenseEntry object, src/app/expense-entry/expense-entry.component.html as specified below − <!-- Page Content --> <div class="container"> <div class="row"> <div class="col-lg-12 text-center" style="padding-top: 20px;"> <div class="container" style="padding-left: 0px; padding-right: 0px;"> <div class="row"> <div class="col-sm" style="text-align: left;"> {{ title }} </div> <div class="col-sm" style="text-align: right;"> <button type="button" class="btn btn-primary">Edit</button> </div> </div> </div> <div class="container box" style="margin-top: 10px;"> <div class="row"> <div class="col-2" style="text-align: right;"> <strong><em>Item:</em></strong> </div> <div class="col" style="text-align: left;"> {{ expenseEntry.item }} </div> </div> <div class="row"> <div class="col-2" style="text-align: right;"> <strong><em>Amount:</em></strong> </div> <div class="col" style="text-align: left;"> {{ expenseEntry.amount }} </div> </div> <div class="row"> <div class="col-2" style="text-align: right;"> <strong><em>Category:</em></strong> </div> <div class="col" style="text-align: left;"> {{ expenseEntry.category }} </div> </div> <div class="row"> <div class="col-2" style="text-align: right;"> <strong><em>Location:</em></strong> </div> <div class="col" style="text-align: left;"> {{ expenseEntry.location }} </div> </div> <div class="row"> <div class="col-2" style="text-align: right;"> <strong><em>Spend On:</em></strong> </div> <div class="col" style="text-align: left;"> {{ expenseEntry.spendOn }} </div> </div> </div> </div> </div> </div> 16 Lectures 1.5 hours Anadi Sharma 28 Lectures 2.5 hours Anadi Sharma 11 Lectures 7.5 hours SHIVPRASAD KOIRALA 16 Lectures 2.5 hours Frahaan Hussain 69 Lectures 5 hours Senol Atac 53 Lectures 3.5 hours Senol Atac Print Add Notes Bookmark this page
[ { "code": null, "e": 2646, "s": 2388, "text": "Data binding deals with how to bind your data from component to HTML DOM elements (Templates). We can easily interact with application without worrying about how to insert your data. We can make connections in two different ways one way and two-way binding." }, { "code": null, "e": 2714, "s": 2646, "text": "Before moving to this topic, let’s create a component in Angular 8." }, { "code": null, "e": 2791, "s": 2714, "text": "Open command prompt and create new Angular application using below command −" }, { "code": null, "e": 2850, "s": 2791, "text": "cd /go/to/workspace \nng new databind-app \ncd databind-app\n" }, { "code": null, "e": 2913, "s": 2850, "text": "Create a test component using Angular CLI as mentioned below −" }, { "code": null, "e": 2941, "s": 2913, "text": "ng generate component test\n" }, { "code": null, "e": 3005, "s": 2941, "text": "The above create a new component and the output is as follows −" }, { "code": null, "e": 3254, "s": 3005, "text": "CREATE src/app/test/test.component.scss (0 bytes) CREATE src/app/test/test.component.html (19 bytes) CREATE src/app/test/test.component.spec.ts (614 bytes) \nCREATE src/app/test/test.component.ts (262 bytes) UPDATE src/app/app.module.ts (545 bytes)\n" }, { "code": null, "e": 3296, "s": 3254, "text": "Run the application using below command −" }, { "code": null, "e": 3306, "s": 3296, "text": "ng serve\n" }, { "code": null, "e": 3508, "s": 3306, "text": "One-way data binding is a one-way interaction between component and its template. If you perform any changes in your component, then it will reflect the HTML elements. It supports the following types −" }, { "code": null, "e": 3751, "s": 3508, "text": "In general, String interpolation is the process of formatting or manipulating strings. In Angular, Interpolation is used to display data from component to view (DOM). It is denoted by the expression of {{ }} and also known as mustache syntax." }, { "code": null, "e": 3829, "s": 3751, "text": "Let’s create a simple string property in component and bind the data to view." }, { "code": null, "e": 3887, "s": 3829, "text": "Add the below code in test.component.ts file as follows −" }, { "code": null, "e": 3981, "s": 3887, "text": "export class TestComponent implements OnInit { \n appName = \"My first app in Angular 8\"; \n}\n" }, { "code": null, "e": 4039, "s": 3981, "text": "Move to test.component.html file and add the below code −" }, { "code": null, "e": 4061, "s": 4039, "text": "<h1>{{appName}}</h1>\n" }, { "code": null, "e": 4163, "s": 4061, "text": "Add the test component in your app.component.html file by replacing the existing content as follows −" }, { "code": null, "e": 4186, "s": 4163, "text": "<app-test></app-test>\n" }, { "code": null, "e": 4266, "s": 4186, "text": "Finally, start your application (if not done already) using the below command −" }, { "code": null, "e": 4276, "s": 4266, "text": "ng serve\n" }, { "code": null, "e": 4328, "s": 4276, "text": "You could see the following output on your screen −" }, { "code": null, "e": 4655, "s": 4328, "text": "Events are actions like mouse click, double click, hover or any keyboard and mouse actions. If a user interacts with an application and performs some actions, then event will be raised. It is denoted by either parenthesis () or on-. We have different ways to bind an event to DOM element. Let’s understand one by one in brief." }, { "code": null, "e": 4717, "s": 4655, "text": "Let’s understand how simple button click even handling works." }, { "code": null, "e": 4778, "s": 4717, "text": "Add the following code in test.component.tsfile as follows −" }, { "code": null, "e": 4989, "s": 4778, "text": "export class TestComponent { \n showData($event: any){ \n console.log(\"button is clicked!\"); if($event) { \n console.log($event.target); \n console.log($event.target.value); \n } \n } \n}" }, { "code": null, "e": 5200, "s": 4989, "text": "event∗refersthefiredevent⋅Inthisscenario,∗click∗istheevent⋅∗event has all the information about event and the target element. Here, the target is button. $event.target property will have the target information." }, { "code": null, "e": 5312, "s": 5200, "text": "We have two approaches to call the component method to view (test.component.html). First one is defined below −" }, { "code": null, "e": 5392, "s": 5312, "text": "<h2>Event Binding</h2> \n<button (click)=\"showData($event)\">Click here</button>\n" }, { "code": null, "e": 5469, "s": 5392, "text": "Alternatively, you can use prefix - on using canonical form as shown below −" }, { "code": null, "e": 5522, "s": 5469, "text": "<button on-click = \"showData()\">Click here</button>\n" }, { "code": null, "e": 5571, "s": 5522, "text": "Here, we have not used $event as it is optional." }, { "code": null, "e": 5651, "s": 5571, "text": "Finally, start your application (if not done already) using the below command −" }, { "code": null, "e": 5661, "s": 5651, "text": "ng serve\n" }, { "code": null, "e": 5726, "s": 5661, "text": "Now, run your application and you could see the below response −" }, { "code": null, "e": 5896, "s": 5726, "text": "Here, when the user clicks on the button, event binding understands to button click action and call component showData() method so we can conclude it is one-way binding." }, { "code": null, "e": 6005, "s": 5896, "text": "Property binding is used to bind the data from property of a component to DOM elements. It is denoted by []." }, { "code": null, "e": 6045, "s": 6005, "text": "Let’s understand with a simple example." }, { "code": null, "e": 6091, "s": 6045, "text": "Add the below code in test.component.ts file." }, { "code": null, "e": 6155, "s": 6091, "text": "export class TestComponent { \n userName:string = \"Peter\"; \n}\n" }, { "code": null, "e": 6206, "s": 6155, "text": "Add the below changes in view test.component.html," }, { "code": null, "e": 6246, "s": 6206, "text": "<input type=\"text\" [value]=\"userName\">\n" }, { "code": null, "e": 6252, "s": 6246, "text": "Here," }, { "code": null, "e": 6324, "s": 6252, "text": "userName property is bind to an attribute of a DOM element <input> tag." }, { "code": null, "e": 6404, "s": 6324, "text": "Finally, start your application (if not done already) using the below command −" }, { "code": null, "e": 6414, "s": 6404, "text": "ng serve\n" }, { "code": null, "e": 6519, "s": 6414, "text": "Attribute binding is used to bind the data from component to HTML attributes. The syntax is as follows −" }, { "code": null, "e": 6559, "s": 6519, "text": "<HTMLTag [attr.ATTR]=\"Component data\">\n" }, { "code": null, "e": 6572, "s": 6559, "text": "For example," }, { "code": null, "e": 6616, "s": 6572, "text": "<td [attr.colspan]=\"columnSpan\"> ... </td>\n" }, { "code": null, "e": 6656, "s": 6616, "text": "Let’s understand with a simple example." }, { "code": null, "e": 6702, "s": 6656, "text": "Add the below code in test.component.ts file." }, { "code": null, "e": 6766, "s": 6702, "text": "export class TestComponent { \n userName:string = \"Peter\"; \n}\n" }, { "code": null, "e": 6817, "s": 6766, "text": "Add the below changes in view test.component.html," }, { "code": null, "e": 6857, "s": 6817, "text": "<input type=\"text\" [value]=\"userName\">\n" }, { "code": null, "e": 6863, "s": 6857, "text": "Here," }, { "code": null, "e": 6935, "s": 6863, "text": "userName property is bind to an attribute of a DOM element <input> tag." }, { "code": null, "e": 7015, "s": 6935, "text": "Finally, start your application (if not done already) using the below command −" }, { "code": null, "e": 7025, "s": 7015, "text": "ng serve\n" }, { "code": null, "e": 7130, "s": 7025, "text": "Class binding is used to bind the data from component to HTML class property. The syntax is as follows −" }, { "code": null, "e": 7189, "s": 7130, "text": "<HTMLTag [class]=\"component variable holding class name\">\n" }, { "code": null, "e": 7433, "s": 7189, "text": "Class Binding provides additional functionality. If the component data is boolean, then the class will bind only when it is true. Multiple class can be provided by string (“foo bar”) as well as Array of string. Many more options are available." }, { "code": null, "e": 7446, "s": 7433, "text": "For example," }, { "code": null, "e": 7471, "s": 7446, "text": "<p [class]=\"myClasses\">\n" }, { "code": null, "e": 7511, "s": 7471, "text": "Let’s understand with a simple example." }, { "code": null, "e": 7557, "s": 7511, "text": "Add the below code in test.component.ts file," }, { "code": null, "e": 7641, "s": 7557, "text": "export class TestComponent { \n myCSSClass = \"red\"; \n applyCSSClass = false; \n}\n" }, { "code": null, "e": 7692, "s": 7641, "text": "Add the below changes in view test.component.html." }, { "code": null, "e": 7846, "s": 7692, "text": "<p [class]=\"myCSSClass\">This paragraph class comes from *myClass* property </p> \n<p [class.blue]=\"applyCSSClass\">This paragraph class does not apply</p>\n" }, { "code": null, "e": 7891, "s": 7846, "text": "Add the below content in test.component.css." }, { "code": null, "e": 7947, "s": 7891, "text": ".red { \n color: red; \n} \n.blue { \n color: blue; \n}\n" }, { "code": null, "e": 8027, "s": 7947, "text": "Finally, start your application (if not done already) using the below command −" }, { "code": null, "e": 8037, "s": 8027, "text": "ng serve\n" }, { "code": null, "e": 8079, "s": 8037, "text": "The final output will be as shown below −" }, { "code": null, "e": 8186, "s": 8079, "text": "Style binding is used to bind the data from component into HTML style property. The syntax is as follows −" }, { "code": null, "e": 8228, "s": 8186, "text": "<HTMLTag [style.STYLE]=\"component data\">\n" }, { "code": null, "e": 8241, "s": 8228, "text": "For example," }, { "code": null, "e": 8283, "s": 8241, "text": "<p [style.color]=\"myParaColor\"> ... </p>\n" }, { "code": null, "e": 8323, "s": 8283, "text": "Let’s understand with a simple example." }, { "code": null, "e": 8369, "s": 8323, "text": "Add the below code in test.component.ts file." }, { "code": null, "e": 8389, "s": 8369, "text": "myColor = 'brown';\n" }, { "code": null, "e": 8440, "s": 8389, "text": "Add the below changes in view test.component.html." }, { "code": null, "e": 8513, "s": 8440, "text": "<p [style.color]=\"myColor\">Text color is styled using style binding</p>\n" }, { "code": null, "e": 8593, "s": 8513, "text": "Finally, start your application (if not done already) using the below command −" }, { "code": null, "e": 8603, "s": 8593, "text": "ng serve\n" }, { "code": null, "e": 8645, "s": 8603, "text": "The final output will be as shown below −" }, { "code": null, "e": 8943, "s": 8645, "text": "Two-way data binding is a two-way interaction, data flows in both ways (from component to views and views to component). Simple example is ngModel. If you do any changes in your property (or model) then, it reflects in your view and vice versa. It is the combination of property and event binding." }, { "code": null, "e": 9095, "s": 8943, "text": "NgModel is a standalone directive. ngModel directive binds form control to property and property to form control. The syntax of ngModel is as follows −" }, { "code": null, "e": 9130, "s": 9095, "text": "<HTML [(ngModel)]=\"model.name\" />\n" }, { "code": null, "e": 9143, "s": 9130, "text": "For example," }, { "code": null, "e": 9191, "s": 9143, "text": "<input type=\"text\" [(ngModel)]=\"model.name\" />\n" }, { "code": null, "e": 9241, "s": 9191, "text": "Let’s try to use ngModel in our test application." }, { "code": null, "e": 9300, "s": 9241, "text": "Configure FormsModule in AppModule (src/app/app.module.ts)" }, { "code": null, "e": 9451, "s": 9300, "text": "import { FormsModule } from '@angular/forms'; @NgModule({ \n imports: [ \n BrowserModule, \n FormsModule\n ] \n}) \nexport class AppModule { }" }, { "code": null, "e": 9517, "s": 9451, "text": "FormModule do the necessary setup to enable two-way data binding." }, { "code": null, "e": 9586, "s": 9517, "text": "Update TestComponent view (test.component.html) as mentioned below −" }, { "code": null, "e": 9678, "s": 9586, "text": "<input type=\"text\" [(ngModel)]=\"userName\" />\n<p>Two way binding! Hello {{ userName }}!</p>\n" }, { "code": null, "e": 9684, "s": 9678, "text": "Here," }, { "code": null, "e": 9872, "s": 9684, "text": "Property is bind to form control ngModeldirective and if you enter any text in the textbox, it will bind to the property. After running your application, you could see the below changes −" }, { "code": null, "e": 9952, "s": 9872, "text": "Finally, start your application (if not done already) using the below command −" }, { "code": null, "e": 9962, "s": 9952, "text": "ng serve\n" }, { "code": null, "e": 10027, "s": 9962, "text": "Now, run your application and you could see the below response −" }, { "code": null, "e": 10168, "s": 10027, "text": "Now, try to change the input value to Jack. As you type, the text below the input gets changed and the final output will be as shown below −" }, { "code": null, "e": 10233, "s": 10168, "text": "We will learn more about form controls in the upcoming chapters." }, { "code": null, "e": 10325, "s": 10233, "text": "Let us implement all the concept learned in this chapter in our ExpenseManager application." }, { "code": null, "e": 10376, "s": 10325, "text": "Open command prompt and go to project root folder." }, { "code": null, "e": 10403, "s": 10376, "text": "cd /go/to/expense-manager\n" }, { "code": null, "e": 10523, "s": 10403, "text": "Create ExpenseEntry interface (src/app/expense-entry.ts) and add id, amount, category, Location, spendOn and createdOn." }, { "code": null, "e": 10696, "s": 10523, "text": "export interface ExpenseEntry { \n id: number; \n item: string; \n amount: number; \n category: string; \n location: string; \n spendOn: Date; \n createdOn: Date; \n}" }, { "code": null, "e": 10744, "s": 10696, "text": "Import ExpenseEntry into ExpenseEntryComponent." }, { "code": null, "e": 10794, "s": 10744, "text": "import { ExpenseEntry } from '../expense-entry';\n" }, { "code": null, "e": 10854, "s": 10794, "text": "Create a ExpenseEntry object, expenseEntry as shown below −" }, { "code": null, "e": 11304, "s": 10854, "text": "export class ExpenseEntryComponent implements OnInit { \n title: string; \n expenseEntry: ExpenseEntry; \n constructor() { } \n ngOnInit() { \n this.title = \"Expense Entry\"; \n this.expenseEntry = { \n id: 1, \n item: \"Pizza\", \n amount: 21, \n category: \"Food\", \n location: \"Zomato\", \n spendOn: new Date(2020, 6, 1, 10, 10, 10), createdOn: new Date(2020, 6, 1, 10, 10, 10), \n }; \n } \n}" }, { "code": null, "e": 11433, "s": 11304, "text": "Update the component template using expenseEntry object, src/app/expense-entry/expense-entry.component.html as specified below −" }, { "code": null, "e": 13712, "s": 11433, "text": "<!-- Page Content --> \n<div class=\"container\">\n <div class=\"row\"> \n <div class=\"col-lg-12 text-center\" style=\"padding-top: 20px;\"> \n <div class=\"container\" style=\"padding-left: 0px; padding-right: 0px;\"> \n <div class=\"row\"> \n <div class=\"col-sm\" style=\"text-align: left;\"> \n {{ title }} \n </div> \n <div class=\"col-sm\" style=\"text-align: right;\"> \n <button type=\"button\" class=\"btn btn-primary\">Edit</button> \n </div> \n </div> \n </div> \n <div class=\"container box\" style=\"margin-top: 10px;\"> \n <div class=\"row\"> \n <div class=\"col-2\" style=\"text-align: right;\"> \n <strong><em>Item:</em></strong> \n </div> \n <div class=\"col\" style=\"text-align: left;\"> \n {{ expenseEntry.item }} \n </div> \n </div> \n <div class=\"row\"> \n <div class=\"col-2\" style=\"text-align: right;\"> \n <strong><em>Amount:</em></strong> \n </div> \n <div class=\"col\" style=\"text-align: left;\">\n {{ expenseEntry.amount }} \n </div> \n </div> \n <div class=\"row\"> \n <div class=\"col-2\" style=\"text-align: right;\"> \n <strong><em>Category:</em></strong> \n </div> \n <div class=\"col\" style=\"text-align: left;\"> \n {{ expenseEntry.category }} \n </div> \n </div> \n <div class=\"row\"> \n <div class=\"col-2\" style=\"text-align: right;\"> \n <strong><em>Location:</em></strong> \n </div> \n <div class=\"col\" style=\"text-align: left;\"> \n {{ expenseEntry.location }} \n </div> \n </div> \n <div class=\"row\"> \n <div class=\"col-2\" style=\"text-align: right;\">\n <strong><em>Spend On:</em></strong>\n </div> \n <div class=\"col\" style=\"text-align: left;\"> \n {{ expenseEntry.spendOn }} \n </div> \n </div> \n </div> \n </div> \n </div> \n</div>" }, { "code": null, "e": 13747, "s": 13712, "text": "\n 16 Lectures \n 1.5 hours \n" }, { "code": null, "e": 13761, "s": 13747, "text": " Anadi Sharma" }, { "code": null, "e": 13796, "s": 13761, "text": "\n 28 Lectures \n 2.5 hours \n" }, { "code": null, "e": 13810, "s": 13796, "text": " Anadi Sharma" }, { "code": null, "e": 13845, "s": 13810, "text": "\n 11 Lectures \n 7.5 hours \n" }, { "code": null, "e": 13865, "s": 13845, "text": " SHIVPRASAD KOIRALA" }, { "code": null, "e": 13900, "s": 13865, "text": "\n 16 Lectures \n 2.5 hours \n" }, { "code": null, "e": 13917, "s": 13900, "text": " Frahaan Hussain" }, { "code": null, "e": 13950, "s": 13917, "text": "\n 69 Lectures \n 5 hours \n" }, { "code": null, "e": 13962, "s": 13950, "text": " Senol Atac" }, { "code": null, "e": 13997, "s": 13962, "text": "\n 53 Lectures \n 3.5 hours \n" }, { "code": null, "e": 14009, "s": 13997, "text": " Senol Atac" }, { "code": null, "e": 14016, "s": 14009, "text": " Print" }, { "code": null, "e": 14027, "s": 14016, "text": " Add Notes" } ]
Java Internalization - Formatting Patterns
Followings is the use of characters in formatting patterns. 0 To display 0 if less digits are present. # To display digit ommitting leading zeroes. . Decimal separator. , Grouping separator. E Mantissa and Exponent separator for exponential formats. ; Format separator. - Negative number prefix. % Shows number as percentage after multiplying with 100. ? Shows number as mille after multiplying with 1000. X To mark character as number prefix/suffix. ' To mark quote around special characters. In this example, we're formatting numbers based on different patterns. IOTester.java import java.text.DecimalFormat; public class I18NTester { public static void main(String[] args) { String pattern = "###.###"; double number = 123456789.123; DecimalFormat numberFormat = new DecimalFormat(pattern); System.out.println(number); //pattern ###.### System.out.println(numberFormat.format(number)); //pattern ###.# numberFormat.applyPattern("###.#"); System.out.println(numberFormat.format(number)); //pattern ###,###.## numberFormat.applyPattern("###,###.##"); System.out.println(numberFormat.format(number)); number = 9.34; //pattern 000.### numberFormat.applyPattern("000.##"); System.out.println(numberFormat.format(number)); } } It will print the following result. 1.23456789123E8 1,2345,6789.12 16 Lectures 2 hours Malhar Lathkar 19 Lectures 5 hours Malhar Lathkar 25 Lectures 2.5 hours Anadi Sharma 126 Lectures 7 hours Tushar Kale 119 Lectures 17.5 hours Monica Mittal 76 Lectures 7 hours Arnab Chakraborty Print Add Notes Bookmark this page
[ { "code": null, "e": 2765, "s": 2705, "text": "Followings is the use of characters in formatting patterns." }, { "code": null, "e": 2767, "s": 2765, "text": "0" }, { "code": null, "e": 2808, "s": 2767, "text": "To display 0 if less digits are present." }, { "code": null, "e": 2810, "s": 2808, "text": "#" }, { "code": null, "e": 2853, "s": 2810, "text": "To display digit ommitting leading zeroes." }, { "code": null, "e": 2855, "s": 2853, "text": "." }, { "code": null, "e": 2874, "s": 2855, "text": "Decimal separator." }, { "code": null, "e": 2876, "s": 2874, "text": "," }, { "code": null, "e": 2896, "s": 2876, "text": "Grouping separator." }, { "code": null, "e": 2898, "s": 2896, "text": "E" }, { "code": null, "e": 2955, "s": 2898, "text": "Mantissa and Exponent separator for exponential formats." }, { "code": null, "e": 2957, "s": 2955, "text": ";" }, { "code": null, "e": 2975, "s": 2957, "text": "Format separator." }, { "code": null, "e": 2977, "s": 2975, "text": "-" }, { "code": null, "e": 3001, "s": 2977, "text": "Negative number prefix." }, { "code": null, "e": 3003, "s": 3001, "text": "%" }, { "code": null, "e": 3058, "s": 3003, "text": "Shows number as percentage after multiplying with 100." }, { "code": null, "e": 3060, "s": 3058, "text": "?" }, { "code": null, "e": 3111, "s": 3060, "text": "Shows number as mille after multiplying with 1000." }, { "code": null, "e": 3113, "s": 3111, "text": "X" }, { "code": null, "e": 3156, "s": 3113, "text": "To mark character as number prefix/suffix." }, { "code": null, "e": 3158, "s": 3156, "text": "'" }, { "code": null, "e": 3199, "s": 3158, "text": "To mark quote around special characters." }, { "code": null, "e": 3270, "s": 3199, "text": "In this example, we're formatting numbers based on different patterns." }, { "code": null, "e": 3284, "s": 3270, "text": "IOTester.java" }, { "code": null, "e": 4050, "s": 3284, "text": "import java.text.DecimalFormat;\n\npublic class I18NTester {\n public static void main(String[] args) {\n String pattern = \"###.###\";\n double number = 123456789.123;\n\n DecimalFormat numberFormat = new DecimalFormat(pattern);\n\n System.out.println(number);\n\n //pattern ###.###\n System.out.println(numberFormat.format(number));\n\n //pattern ###.#\n numberFormat.applyPattern(\"###.#\");\n System.out.println(numberFormat.format(number));\n\n //pattern ###,###.##\n numberFormat.applyPattern(\"###,###.##\");\n System.out.println(numberFormat.format(number));\n\n number = 9.34;\n\n //pattern 000.###\n numberFormat.applyPattern(\"000.##\");\n System.out.println(numberFormat.format(number)); \n }\n}" }, { "code": null, "e": 4086, "s": 4050, "text": "It will print the following result." }, { "code": null, "e": 4118, "s": 4086, "text": "1.23456789123E8\n1,2345,6789.12\n" }, { "code": null, "e": 4151, "s": 4118, "text": "\n 16 Lectures \n 2 hours \n" }, { "code": null, "e": 4167, "s": 4151, "text": " Malhar Lathkar" }, { "code": null, "e": 4200, "s": 4167, "text": "\n 19 Lectures \n 5 hours \n" }, { "code": null, "e": 4216, "s": 4200, "text": " Malhar Lathkar" }, { "code": null, "e": 4251, "s": 4216, "text": "\n 25 Lectures \n 2.5 hours \n" }, { "code": null, "e": 4265, "s": 4251, "text": " Anadi Sharma" }, { "code": null, "e": 4299, "s": 4265, "text": "\n 126 Lectures \n 7 hours \n" }, { "code": null, "e": 4313, "s": 4299, "text": " Tushar Kale" }, { "code": null, "e": 4350, "s": 4313, "text": "\n 119 Lectures \n 17.5 hours \n" }, { "code": null, "e": 4365, "s": 4350, "text": " Monica Mittal" }, { "code": null, "e": 4398, "s": 4365, "text": "\n 76 Lectures \n 7 hours \n" }, { "code": null, "e": 4417, "s": 4398, "text": " Arnab Chakraborty" }, { "code": null, "e": 4424, "s": 4417, "text": " Print" }, { "code": null, "e": 4435, "s": 4424, "text": " Add Notes" } ]
How to Build a Content-Based Movie Recommender System | by Egemen Zeytinci | Towards Data Science
In this article, I will try to explain how we can create a recommender system without user data. I’ll also share an example that I’ve done with Python and tell you how it works step by step. I am not going to explain the types of recommender systems separately, since it is quite easy to find on the internet. So, let’s start talking about the content-based recommender system! Content-based recommender systems do not include datas retrieved from the users other than you. It simply helps you by identifying products that are similar to the product you like. For example, you have a website that sells stuff online and you don’t have a registered user yet, but you still want to recommend products to the visitors of the website. In this case, the content-based recommender system would be an ideal option for you. However, content-based recommendation systems are limited because they do not contain other user data. And it doesn’t help a user discover their potential tastes. For example, let’s say that user A and user B like drama movies. User A also likes comedy movies, but since you don’t have that knowledge, you keep offering drama movies. Eventually, you’re eliminating other options that user B potentially might like. Anyway! Let’s talk about a few terms we’re going to use before we create this system. Let’s start with Kernel Density Estimation! Kernel density estimation is a really useful statistical tool with an intimidating name. Often shortened to KDE, it’s a technique that let’s you create a smooth curve given a set of data. KDE is a method to help determine the density of data distribution. It provides information about where many points are located and where they are not. So in one-dimensional arrays, it helps you clustering by separating the lowest density points (local minima) with the highest density points (local maxima). Just follow these steps, Compute densitiesFind local minima and local maxima valuesCreate clusters Compute densities Find local minima and local maxima values Create clusters Cosine similarity is a method for measuring similarity between vectors. Mathematically, it calculates the cosine of the angle between the two vectors. If the angle between the two vectors is zero, the similarity is calculated as 1 because the cosine of zero is 1. So the two vectors are identical. The cosine of any angle varies from 0 to 1. Therefore, similarity rates will vary from 0 to 1. The formula is expressed as follows: That’s enough for now! Let’s code it! I want to set a score for each movie or series, and I need a coefficient for each feature, so I’m going to look at feature importances. The dataset is as follows, You can easily obtain this data set by merging files shared at https://datasets.imdbws.com. I obtained this data by merging title.basics.tsv.gz with title.ratings.tsv.gz and after, I deleted some features. For example, the end_year field contained too much null value, so I removed it. For more detailed information, please see my repository. It is shared at the end of this article. I have to say one more detail, I’ve converted the kind field into an integer field by using label encoder. As you can see above, I’ve tried three different methods. The first is the importance of the feature provided directly by the Random Forests model. Another is Permutation Importances. This approach directly measures the effect of the field on the model using the random re-shuffling technique for each predictor. It maintains the distribution of the variable because it uses a random re-shuffling technique. The last is Drop Column Feature Importances. This method is completely intuitive and each time it wipes one feature and compares it to the model in which all columns are used. It is usually much safer, but it can have a long processing time. Processing time is not so important for our data set. The results are like this: We choose the Drop Column Feature Importances method among these methods. As we indicated before, it is much more reliable and, when we take a glance at the results, they make much more sense to calculate scores. dataset['score'] = ( 0.4576 * dataset['num_votes'] + 0.3271 * dataset['runtime'] + 0.3517 * dataset['start_year'] + 0.0493 * dataset['kind']) I’m going to use the scores to create the clusters. So I can recommend movies with the same score on average. I have a 1-dimensional array of scores, and I can use KDE to cluster. I used this code to see the distribution of scores: import matplotlib.pyplot as pltimport seaborn as snsplt.figure(figsize=(9, 6))sns.distplot(dataset['score'])plt.axvline(18000, color='r'); And I got a graph like this, I added a vertical line for 18,000, because the density is between 650 and 18,000. If I give you points greater than 18,000 when applying KDE, it collects all points less than 18,000 in one cluster, and that’s not what we want, because it’s going to reduce diversity. I applied 3 stages to do clustering with KDE as I mentioned at the beginning of my article. Compute densities Compute densities from sklearn.neighbors.kde import KernelDensityvals = dataset['score'].values.reshape(-1, 1)kde = KernelDensity(kernel='gaussian', bandwidth=3).fit(vals)s = np.linspace(650, 18000)e = kde.score_samples(s.reshape(-1, 1)) 2. Find local minima and local maxima values from scipy.signal import argrelextremami = argrelextrema(e, np.less)[0]ma = argrelextrema(e, np.greater)[0]points = np.concatenate((s[mi], s[ma]), axis=0)buckets = []for point in points: buckets.append(point)buckets = np.array(buckets)buckets.sort() 3. Create clusters dataset['cluster'] = buckets.searchsorted(dataset.score) Finally, I calculated the similarities between the genres in order to be able to recommend the same type of film as accurate as possible. I used TF-IDF and Linear Kernel for this. Consequently, cosine similarity was used in the background to find similarities. from sklearn.feature_extraction.text import TfidfVectorizerfrom sklearn.metrics.pairwise import linear_kerneltfidf_vectorizer = TfidfVectorizer()matrix = tfidf_vectorizer.fit_transform(dataset['genres'])kernel = linear_kernel(matrix, matrix) Let’s see the recommendations now! def get_recommendations2(movie_index): print(dataset.iloc[movie_index]) print('**' * 40) sim_ = list(enumerate(kernel[movie_index])) sim = sorted(sim_, key=lambda x: x[1], reverse=True) index = [i[0] for i in sim if i[0] != movie_index and i[1] > .5] cond1 = dataset.index.isin(index) cond2 = dataset.cluster == dataset.iloc[movie_index]['cluster'] selected = dataset.loc[cond1 & cond2] \ .sort_values(by='score', ascending=False).head(20) print(selected[['title', 'cluster', 'genres']]) That seemed pretty useful to me! If you want to see the codes in more detail, serve with flask, index movies with elasticsearch and use docker, you can look at my repository: github.com Thank you for reading! Eryk Lewinson, Explaining Feature Importance by example of a Random Forest (2019) Matthew Conlen, Kernel Density Estimation Matthew Overby, 1D Clustering with KDE (2017) CountVectorizer, TfidfVectorizer, Predict Comments (2018)
[ { "code": null, "e": 363, "s": 172, "text": "In this article, I will try to explain how we can create a recommender system without user data. I’ll also share an example that I’ve done with Python and tell you how it works step by step." }, { "code": null, "e": 550, "s": 363, "text": "I am not going to explain the types of recommender systems separately, since it is quite easy to find on the internet. So, let’s start talking about the content-based recommender system!" }, { "code": null, "e": 732, "s": 550, "text": "Content-based recommender systems do not include datas retrieved from the users other than you. It simply helps you by identifying products that are similar to the product you like." }, { "code": null, "e": 988, "s": 732, "text": "For example, you have a website that sells stuff online and you don’t have a registered user yet, but you still want to recommend products to the visitors of the website. In this case, the content-based recommender system would be an ideal option for you." }, { "code": null, "e": 1151, "s": 988, "text": "However, content-based recommendation systems are limited because they do not contain other user data. And it doesn’t help a user discover their potential tastes." }, { "code": null, "e": 1403, "s": 1151, "text": "For example, let’s say that user A and user B like drama movies. User A also likes comedy movies, but since you don’t have that knowledge, you keep offering drama movies. Eventually, you’re eliminating other options that user B potentially might like." }, { "code": null, "e": 1533, "s": 1403, "text": "Anyway! Let’s talk about a few terms we’re going to use before we create this system. Let’s start with Kernel Density Estimation!" }, { "code": null, "e": 1721, "s": 1533, "text": "Kernel density estimation is a really useful statistical tool with an intimidating name. Often shortened to KDE, it’s a technique that let’s you create a smooth curve given a set of data." }, { "code": null, "e": 2055, "s": 1721, "text": "KDE is a method to help determine the density of data distribution. It provides information about where many points are located and where they are not. So in one-dimensional arrays, it helps you clustering by separating the lowest density points (local minima) with the highest density points (local maxima). Just follow these steps," }, { "code": null, "e": 2129, "s": 2055, "text": "Compute densitiesFind local minima and local maxima valuesCreate clusters" }, { "code": null, "e": 2147, "s": 2129, "text": "Compute densities" }, { "code": null, "e": 2189, "s": 2147, "text": "Find local minima and local maxima values" }, { "code": null, "e": 2205, "s": 2189, "text": "Create clusters" }, { "code": null, "e": 2635, "s": 2205, "text": "Cosine similarity is a method for measuring similarity between vectors. Mathematically, it calculates the cosine of the angle between the two vectors. If the angle between the two vectors is zero, the similarity is calculated as 1 because the cosine of zero is 1. So the two vectors are identical. The cosine of any angle varies from 0 to 1. Therefore, similarity rates will vary from 0 to 1. The formula is expressed as follows:" }, { "code": null, "e": 2673, "s": 2635, "text": "That’s enough for now! Let’s code it!" }, { "code": null, "e": 2809, "s": 2673, "text": "I want to set a score for each movie or series, and I need a coefficient for each feature, so I’m going to look at feature importances." }, { "code": null, "e": 2836, "s": 2809, "text": "The dataset is as follows," }, { "code": null, "e": 3220, "s": 2836, "text": "You can easily obtain this data set by merging files shared at https://datasets.imdbws.com. I obtained this data by merging title.basics.tsv.gz with title.ratings.tsv.gz and after, I deleted some features. For example, the end_year field contained too much null value, so I removed it. For more detailed information, please see my repository. It is shared at the end of this article." }, { "code": null, "e": 3327, "s": 3220, "text": "I have to say one more detail, I’ve converted the kind field into an integer field by using label encoder." }, { "code": null, "e": 3475, "s": 3327, "text": "As you can see above, I’ve tried three different methods. The first is the importance of the feature provided directly by the Random Forests model." }, { "code": null, "e": 3735, "s": 3475, "text": "Another is Permutation Importances. This approach directly measures the effect of the field on the model using the random re-shuffling technique for each predictor. It maintains the distribution of the variable because it uses a random re-shuffling technique." }, { "code": null, "e": 4031, "s": 3735, "text": "The last is Drop Column Feature Importances. This method is completely intuitive and each time it wipes one feature and compares it to the model in which all columns are used. It is usually much safer, but it can have a long processing time. Processing time is not so important for our data set." }, { "code": null, "e": 4058, "s": 4031, "text": "The results are like this:" }, { "code": null, "e": 4271, "s": 4058, "text": "We choose the Drop Column Feature Importances method among these methods. As we indicated before, it is much more reliable and, when we take a glance at the results, they make much more sense to calculate scores." }, { "code": null, "e": 4428, "s": 4271, "text": "dataset['score'] = ( 0.4576 * dataset['num_votes'] + 0.3271 * dataset['runtime'] + 0.3517 * dataset['start_year'] + 0.0493 * dataset['kind'])" }, { "code": null, "e": 4538, "s": 4428, "text": "I’m going to use the scores to create the clusters. So I can recommend movies with the same score on average." }, { "code": null, "e": 4660, "s": 4538, "text": "I have a 1-dimensional array of scores, and I can use KDE to cluster. I used this code to see the distribution of scores:" }, { "code": null, "e": 4799, "s": 4660, "text": "import matplotlib.pyplot as pltimport seaborn as snsplt.figure(figsize=(9, 6))sns.distplot(dataset['score'])plt.axvline(18000, color='r');" }, { "code": null, "e": 4828, "s": 4799, "text": "And I got a graph like this," }, { "code": null, "e": 5096, "s": 4828, "text": "I added a vertical line for 18,000, because the density is between 650 and 18,000. If I give you points greater than 18,000 when applying KDE, it collects all points less than 18,000 in one cluster, and that’s not what we want, because it’s going to reduce diversity." }, { "code": null, "e": 5188, "s": 5096, "text": "I applied 3 stages to do clustering with KDE as I mentioned at the beginning of my article." }, { "code": null, "e": 5206, "s": 5188, "text": "Compute densities" }, { "code": null, "e": 5224, "s": 5206, "text": "Compute densities" }, { "code": null, "e": 5444, "s": 5224, "text": "from sklearn.neighbors.kde import KernelDensityvals = dataset['score'].values.reshape(-1, 1)kde = KernelDensity(kernel='gaussian', bandwidth=3).fit(vals)s = np.linspace(650, 18000)e = kde.score_samples(s.reshape(-1, 1))" }, { "code": null, "e": 5489, "s": 5444, "text": "2. Find local minima and local maxima values" }, { "code": null, "e": 5742, "s": 5489, "text": "from scipy.signal import argrelextremami = argrelextrema(e, np.less)[0]ma = argrelextrema(e, np.greater)[0]points = np.concatenate((s[mi], s[ma]), axis=0)buckets = []for point in points: buckets.append(point)buckets = np.array(buckets)buckets.sort()" }, { "code": null, "e": 5761, "s": 5742, "text": "3. Create clusters" }, { "code": null, "e": 5818, "s": 5761, "text": "dataset['cluster'] = buckets.searchsorted(dataset.score)" }, { "code": null, "e": 6079, "s": 5818, "text": "Finally, I calculated the similarities between the genres in order to be able to recommend the same type of film as accurate as possible. I used TF-IDF and Linear Kernel for this. Consequently, cosine similarity was used in the background to find similarities." }, { "code": null, "e": 6321, "s": 6079, "text": "from sklearn.feature_extraction.text import TfidfVectorizerfrom sklearn.metrics.pairwise import linear_kerneltfidf_vectorizer = TfidfVectorizer()matrix = tfidf_vectorizer.fit_transform(dataset['genres'])kernel = linear_kernel(matrix, matrix)" }, { "code": null, "e": 6356, "s": 6321, "text": "Let’s see the recommendations now!" }, { "code": null, "e": 6886, "s": 6356, "text": "def get_recommendations2(movie_index): print(dataset.iloc[movie_index]) print('**' * 40) sim_ = list(enumerate(kernel[movie_index])) sim = sorted(sim_, key=lambda x: x[1], reverse=True) index = [i[0] for i in sim if i[0] != movie_index and i[1] > .5] cond1 = dataset.index.isin(index) cond2 = dataset.cluster == dataset.iloc[movie_index]['cluster'] selected = dataset.loc[cond1 & cond2] \\ .sort_values(by='score', ascending=False).head(20) print(selected[['title', 'cluster', 'genres']])" }, { "code": null, "e": 7061, "s": 6886, "text": "That seemed pretty useful to me! If you want to see the codes in more detail, serve with flask, index movies with elasticsearch and use docker, you can look at my repository:" }, { "code": null, "e": 7072, "s": 7061, "text": "github.com" }, { "code": null, "e": 7095, "s": 7072, "text": "Thank you for reading!" }, { "code": null, "e": 7177, "s": 7095, "text": "Eryk Lewinson, Explaining Feature Importance by example of a Random Forest (2019)" }, { "code": null, "e": 7219, "s": 7177, "text": "Matthew Conlen, Kernel Density Estimation" }, { "code": null, "e": 7265, "s": 7219, "text": "Matthew Overby, 1D Clustering with KDE (2017)" } ]
C# - Program Structure
Before we study basic building blocks of the C# programming language, let us look at a bare minimum C# program structure so that we can take it as a reference in upcoming chapters. A C# program consists of the following parts − Namespace declaration A class Class methods Class attributes A Main method Statements and Expressions Comments Let us look at a simple code that prints the words "Hello World" − using System; namespace HelloWorldApplication { class HelloWorld { static void Main(string[] args) { /* my first program in C# */ Console.WriteLine("Hello World"); Console.ReadKey(); } } } When this code is compiled and executed, it produces the following result − Hello World Let us look at the various parts of the given program − The first line of the program using System; - the using keyword is used to include the System namespace in the program. A program generally has multiple using statements. The first line of the program using System; - the using keyword is used to include the System namespace in the program. A program generally has multiple using statements. The next line has the namespace declaration. A namespace is a collection of classes. The HelloWorldApplication namespace contains the class HelloWorld. The next line has the namespace declaration. A namespace is a collection of classes. The HelloWorldApplication namespace contains the class HelloWorld. The next line has a class declaration, the class HelloWorld contains the data and method definitions that your program uses. Classes generally contain multiple methods. Methods define the behavior of the class. However, the HelloWorld class has only one method Main. The next line has a class declaration, the class HelloWorld contains the data and method definitions that your program uses. Classes generally contain multiple methods. Methods define the behavior of the class. However, the HelloWorld class has only one method Main. The next line defines the Main method, which is the entry point for all C# programs. The Main method states what the class does when executed. The next line defines the Main method, which is the entry point for all C# programs. The Main method states what the class does when executed. The next line /*...*/ is ignored by the compiler and it is put to add comments in the program. The next line /*...*/ is ignored by the compiler and it is put to add comments in the program. The Main method specifies its behavior with the statement Console.WriteLine("Hello World"); WriteLine is a method of the Console class defined in the System namespace. This statement causes the message "Hello, World!" to be displayed on the screen. The Main method specifies its behavior with the statement Console.WriteLine("Hello World"); WriteLine is a method of the Console class defined in the System namespace. This statement causes the message "Hello, World!" to be displayed on the screen. The last line Console.ReadKey(); is for the VS.NET Users. This makes the program wait for a key press and it prevents the screen from running and closing quickly when the program is launched from Visual Studio .NET. The last line Console.ReadKey(); is for the VS.NET Users. This makes the program wait for a key press and it prevents the screen from running and closing quickly when the program is launched from Visual Studio .NET. It is worth to note the following points − C# is case sensitive. C# is case sensitive. All statements and expression must end with a semicolon (;). All statements and expression must end with a semicolon (;). The program execution starts at the Main method. The program execution starts at the Main method. Unlike Java, program file name could be different from the class name. Unlike Java, program file name could be different from the class name. If you are using Visual Studio.Net for compiling and executing C# programs, take the following steps − Start Visual Studio. Start Visual Studio. On the menu bar, choose File -> New -> Project. On the menu bar, choose File -> New -> Project. Choose Visual C# from templates, and then choose Windows. Choose Visual C# from templates, and then choose Windows. Choose Console Application. Choose Console Application. Specify a name for your project and click OK button. Specify a name for your project and click OK button. This creates a new project in Solution Explorer. This creates a new project in Solution Explorer. Write code in the Code Editor. Write code in the Code Editor. Click the Run button or press F5 key to execute the project. A Command Prompt window appears that contains the line Hello World. Click the Run button or press F5 key to execute the project. A Command Prompt window appears that contains the line Hello World. You can compile a C# program by using the command-line instead of the Visual Studio IDE − Open a text editor and add the above-mentioned code. Open a text editor and add the above-mentioned code. Save the file as helloworld.cs Save the file as helloworld.cs Open the command prompt tool and go to the directory where you saved the file. Open the command prompt tool and go to the directory where you saved the file. Type csc helloworld.cs and press enter to compile your code. Type csc helloworld.cs and press enter to compile your code. If there are no errors in your code, the command prompt takes you to the next line and generates helloworld.exe executable file. If there are no errors in your code, the command prompt takes you to the next line and generates helloworld.exe executable file. Type helloworld to execute your program. Type helloworld to execute your program. You can see the output Hello World printed on the screen. You can see the output Hello World printed on the screen. 119 Lectures 23.5 hours Raja Biswas 37 Lectures 13 hours Trevoir Williams 16 Lectures 1 hours Peter Jepson 159 Lectures 21.5 hours Ebenezer Ogbu 193 Lectures 17 hours Arnold Higuit 24 Lectures 2.5 hours Eric Frick Print Add Notes Bookmark this page
[ { "code": null, "e": 2451, "s": 2270, "text": "Before we study basic building blocks of the C# programming language, let us look at a bare minimum C# program structure so that we can take it as a reference in upcoming chapters." }, { "code": null, "e": 2498, "s": 2451, "text": "A C# program consists of the following parts −" }, { "code": null, "e": 2520, "s": 2498, "text": "Namespace declaration" }, { "code": null, "e": 2528, "s": 2520, "text": "A class" }, { "code": null, "e": 2542, "s": 2528, "text": "Class methods" }, { "code": null, "e": 2559, "s": 2542, "text": "Class attributes" }, { "code": null, "e": 2573, "s": 2559, "text": "A Main method" }, { "code": null, "e": 2600, "s": 2573, "text": "Statements and Expressions" }, { "code": null, "e": 2609, "s": 2600, "text": "Comments" }, { "code": null, "e": 2676, "s": 2609, "text": "Let us look at a simple code that prints the words \"Hello World\" −" }, { "code": null, "e": 2911, "s": 2676, "text": "using System;\n\nnamespace HelloWorldApplication {\n class HelloWorld {\n static void Main(string[] args) {\n /* my first program in C# */\n Console.WriteLine(\"Hello World\");\n Console.ReadKey();\n }\n }\n}" }, { "code": null, "e": 2987, "s": 2911, "text": "When this code is compiled and executed, it produces the following result −" }, { "code": null, "e": 3000, "s": 2987, "text": "Hello World\n" }, { "code": null, "e": 3056, "s": 3000, "text": "Let us look at the various parts of the given program −" }, { "code": null, "e": 3229, "s": 3056, "text": "The first line of the program using System; - the using keyword is used to include the System namespace in the program. A program generally has multiple using statements." }, { "code": null, "e": 3402, "s": 3229, "text": "The first line of the program using System; - the using keyword is used to include the System namespace in the program. A program generally has multiple using statements." }, { "code": null, "e": 3554, "s": 3402, "text": "The next line has the namespace declaration. A namespace is a collection of classes. The HelloWorldApplication namespace contains the class HelloWorld." }, { "code": null, "e": 3706, "s": 3554, "text": "The next line has the namespace declaration. A namespace is a collection of classes. The HelloWorldApplication namespace contains the class HelloWorld." }, { "code": null, "e": 3974, "s": 3706, "text": "The next line has a class declaration, the class HelloWorld contains the data and method definitions that your program uses. Classes generally contain multiple methods. Methods define the behavior of the class. However, the HelloWorld class has only one method Main." }, { "code": null, "e": 4242, "s": 3974, "text": "The next line has a class declaration, the class HelloWorld contains the data and method definitions that your program uses. Classes generally contain multiple methods. Methods define the behavior of the class. However, the HelloWorld class has only one method Main." }, { "code": null, "e": 4386, "s": 4242, "text": "The next line defines the Main method, which is the entry point for all C# programs. The Main method states what the class does when executed." }, { "code": null, "e": 4530, "s": 4386, "text": "The next line defines the Main method, which is the entry point for all C# programs. The Main method states what the class does when executed." }, { "code": null, "e": 4626, "s": 4530, "text": "The next line /*...*/ is ignored by the compiler and it is put to add comments in the program." }, { "code": null, "e": 4722, "s": 4626, "text": "The next line /*...*/ is ignored by the compiler and it is put to add comments in the program." }, { "code": null, "e": 4972, "s": 4722, "text": "The Main method specifies its behavior with the statement Console.WriteLine(\"Hello World\");\nWriteLine is a method of the Console class defined in the System namespace. This statement causes the message \"Hello, World!\" to be displayed on the screen.\n" }, { "code": null, "e": 5065, "s": 4972, "text": "The Main method specifies its behavior with the statement Console.WriteLine(\"Hello World\");\n" }, { "code": null, "e": 5222, "s": 5065, "text": "WriteLine is a method of the Console class defined in the System namespace. This statement causes the message \"Hello, World!\" to be displayed on the screen." }, { "code": null, "e": 5438, "s": 5222, "text": "The last line Console.ReadKey(); is for the VS.NET Users. This makes the program wait for a key press and it prevents the screen from running and closing quickly when the program is launched from Visual Studio .NET." }, { "code": null, "e": 5654, "s": 5438, "text": "The last line Console.ReadKey(); is for the VS.NET Users. This makes the program wait for a key press and it prevents the screen from running and closing quickly when the program is launched from Visual Studio .NET." }, { "code": null, "e": 5697, "s": 5654, "text": "It is worth to note the following points −" }, { "code": null, "e": 5719, "s": 5697, "text": "C# is case sensitive." }, { "code": null, "e": 5741, "s": 5719, "text": "C# is case sensitive." }, { "code": null, "e": 5802, "s": 5741, "text": "All statements and expression must end with a semicolon (;)." }, { "code": null, "e": 5863, "s": 5802, "text": "All statements and expression must end with a semicolon (;)." }, { "code": null, "e": 5912, "s": 5863, "text": "The program execution starts at the Main method." }, { "code": null, "e": 5961, "s": 5912, "text": "The program execution starts at the Main method." }, { "code": null, "e": 6032, "s": 5961, "text": "Unlike Java, program file name could be different from the class name." }, { "code": null, "e": 6103, "s": 6032, "text": "Unlike Java, program file name could be different from the class name." }, { "code": null, "e": 6206, "s": 6103, "text": "If you are using Visual Studio.Net for compiling and executing C# programs, take the following steps −" }, { "code": null, "e": 6227, "s": 6206, "text": "Start Visual Studio." }, { "code": null, "e": 6248, "s": 6227, "text": "Start Visual Studio." }, { "code": null, "e": 6296, "s": 6248, "text": "On the menu bar, choose File -> New -> Project." }, { "code": null, "e": 6344, "s": 6296, "text": "On the menu bar, choose File -> New -> Project." }, { "code": null, "e": 6402, "s": 6344, "text": "Choose Visual C# from templates, and then choose Windows." }, { "code": null, "e": 6460, "s": 6402, "text": "Choose Visual C# from templates, and then choose Windows." }, { "code": null, "e": 6488, "s": 6460, "text": "Choose Console Application." }, { "code": null, "e": 6516, "s": 6488, "text": "Choose Console Application." }, { "code": null, "e": 6569, "s": 6516, "text": "Specify a name for your project and click OK button." }, { "code": null, "e": 6622, "s": 6569, "text": "Specify a name for your project and click OK button." }, { "code": null, "e": 6671, "s": 6622, "text": "This creates a new project in Solution Explorer." }, { "code": null, "e": 6720, "s": 6671, "text": "This creates a new project in Solution Explorer." }, { "code": null, "e": 6751, "s": 6720, "text": "Write code in the Code Editor." }, { "code": null, "e": 6782, "s": 6751, "text": "Write code in the Code Editor." }, { "code": null, "e": 6911, "s": 6782, "text": "Click the Run button or press F5 key to execute the project. A Command Prompt window appears that contains the line Hello World." }, { "code": null, "e": 7040, "s": 6911, "text": "Click the Run button or press F5 key to execute the project. A Command Prompt window appears that contains the line Hello World." }, { "code": null, "e": 7130, "s": 7040, "text": "You can compile a C# program by using the command-line instead of the Visual Studio IDE −" }, { "code": null, "e": 7183, "s": 7130, "text": "Open a text editor and add the above-mentioned code." }, { "code": null, "e": 7236, "s": 7183, "text": "Open a text editor and add the above-mentioned code." }, { "code": null, "e": 7267, "s": 7236, "text": "Save the file as helloworld.cs" }, { "code": null, "e": 7298, "s": 7267, "text": "Save the file as helloworld.cs" }, { "code": null, "e": 7377, "s": 7298, "text": "Open the command prompt tool and go to the directory where you saved the file." }, { "code": null, "e": 7456, "s": 7377, "text": "Open the command prompt tool and go to the directory where you saved the file." }, { "code": null, "e": 7517, "s": 7456, "text": "Type csc helloworld.cs and press enter to compile your code." }, { "code": null, "e": 7578, "s": 7517, "text": "Type csc helloworld.cs and press enter to compile your code." }, { "code": null, "e": 7707, "s": 7578, "text": "If there are no errors in your code, the command prompt takes you to the next line and generates helloworld.exe executable file." }, { "code": null, "e": 7836, "s": 7707, "text": "If there are no errors in your code, the command prompt takes you to the next line and generates helloworld.exe executable file." }, { "code": null, "e": 7877, "s": 7836, "text": "Type helloworld to execute your program." }, { "code": null, "e": 7918, "s": 7877, "text": "Type helloworld to execute your program." }, { "code": null, "e": 7976, "s": 7918, "text": "You can see the output Hello World printed on the screen." }, { "code": null, "e": 8034, "s": 7976, "text": "You can see the output Hello World printed on the screen." }, { "code": null, "e": 8071, "s": 8034, "text": "\n 119 Lectures \n 23.5 hours \n" }, { "code": null, "e": 8084, "s": 8071, "text": " Raja Biswas" }, { "code": null, "e": 8118, "s": 8084, "text": "\n 37 Lectures \n 13 hours \n" }, { "code": null, "e": 8136, "s": 8118, "text": " Trevoir Williams" }, { "code": null, "e": 8169, "s": 8136, "text": "\n 16 Lectures \n 1 hours \n" }, { "code": null, "e": 8183, "s": 8169, "text": " Peter Jepson" }, { "code": null, "e": 8220, "s": 8183, "text": "\n 159 Lectures \n 21.5 hours \n" }, { "code": null, "e": 8235, "s": 8220, "text": " Ebenezer Ogbu" }, { "code": null, "e": 8270, "s": 8235, "text": "\n 193 Lectures \n 17 hours \n" }, { "code": null, "e": 8285, "s": 8270, "text": " Arnold Higuit" }, { "code": null, "e": 8320, "s": 8285, "text": "\n 24 Lectures \n 2.5 hours \n" }, { "code": null, "e": 8332, "s": 8320, "text": " Eric Frick" }, { "code": null, "e": 8339, "s": 8332, "text": " Print" }, { "code": null, "e": 8350, "s": 8339, "text": " Add Notes" } ]
PostgreSQL - COMMIT - GeeksforGeeks
01 Feb, 2021 PostgreSQL COMMIT command is used to save changes and reflect it database whenever we display the required data. For suppose we updated data in the database but we didn’t give COMMIT then the changes are not reflected in the database. To save the changes done in a transaction, we should COMMIT that transaction for sure. Syntax : COMMIT TRANSACTION; (or) COMMIT; (or) END TRANSACTION; Unlike other database languages in PostgreSQL, we commit the transaction in 3 different forms which are mentioned above. Now for getting good command in the use of COMMIT command we will first create a table for examples. CREATE TABLE BankStatements ( customer_id serial PRIMARY KEY, full_name VARCHAR NOT NULL, balance INT ); Now we will insert data of some customers INSERT INTO BankStatements ( customer_id , full_name, balance ) VALUES (1, 'Sekhar rao', 1000), (2, 'Abishek Yadav', 500), (3, 'Srinivas Goud', 1000); Now as the table is ready we will understand about commit Example 1: We will add the data to the table in the transaction using the commit BEGIN; INSERT INTO BankStatements ( customer_id, full_name, balance ) VALUES( 4, 'Priya chetri', 500 ) ; COMMIT; Output: Example 2: We will update the balance and display the data without committing the transaction thereafter committing it. BEGIN; UPDATE BankStatements SET balance = balance - 500 WHERE customer_id = 1; // displaying data before // commmiting the transaction SELECT customer_id, full_name, balance FROM BankStatements; UPDATE BankStatements SET balance = balance + 500 WHERE customer_id = 2; COMMIT; // displaying data after // commmiting the transaction SELECT customer_id, full_name, balance FROM BankStatements; Output: NOTE: When we try to display data from another session before committing the changes then we will get the same output that we got in the first example. Picked postgreSQL-managing-database Technical Scripter 2020 PostgreSQL Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments PostgreSQL - Change Column Type PostgreSQL - Psql commands PostgreSQL - For Loops PostgreSQL - Function Returning A Table PostgreSQL - Create Auto-increment Column using SERIAL PostgreSQL - ARRAY_AGG() Function PostgreSQL - DROP INDEX PostgreSQL - ROW_NUMBER Function How to use PostgreSQL Database in Django? PostgreSQL - Copy Table
[ { "code": null, "e": 27609, "s": 27581, "text": "\n01 Feb, 2021" }, { "code": null, "e": 27931, "s": 27609, "text": "PostgreSQL COMMIT command is used to save changes and reflect it database whenever we display the required data. For suppose we updated data in the database but we didn’t give COMMIT then the changes are not reflected in the database. To save the changes done in a transaction, we should COMMIT that transaction for sure." }, { "code": null, "e": 27940, "s": 27931, "text": "Syntax :" }, { "code": null, "e": 27999, "s": 27940, "text": "COMMIT TRANSACTION;\n\n(or)\n\nCOMMIT;\n\n(or)\n\nEND TRANSACTION;" }, { "code": null, "e": 28221, "s": 27999, "text": "Unlike other database languages in PostgreSQL, we commit the transaction in 3 different forms which are mentioned above. Now for getting good command in the use of COMMIT command we will first create a table for examples." }, { "code": null, "e": 28338, "s": 28221, "text": "CREATE TABLE BankStatements (\n customer_id serial PRIMARY KEY,\n full_name VARCHAR NOT NULL,\n balance INT\n);" }, { "code": null, "e": 28380, "s": 28338, "text": "Now we will insert data of some customers" }, { "code": null, "e": 28555, "s": 28380, "text": "INSERT INTO BankStatements (\n customer_id ,\n full_name,\n balance\n)\nVALUES\n (1, 'Sekhar rao', 1000),\n (2, 'Abishek Yadav', 500),\n (3, 'Srinivas Goud', 1000);" }, { "code": null, "e": 28614, "s": 28555, "text": "Now as the table is ready we will understand about commit" }, { "code": null, "e": 28626, "s": 28614, "text": "Example 1: " }, { "code": null, "e": 28696, "s": 28626, "text": "We will add the data to the table in the transaction using the commit" }, { "code": null, "e": 28857, "s": 28696, "text": "BEGIN;\n\n INSERT INTO BankStatements (\n customer_id,\n full_name,\n balance\n\n)\n VALUES(\n 4, 'Priya chetri', 500\n )\n;\n \nCOMMIT;" }, { "code": null, "e": 28865, "s": 28857, "text": "Output:" }, { "code": null, "e": 28876, "s": 28865, "text": "Example 2:" }, { "code": null, "e": 28985, "s": 28876, "text": "We will update the balance and display the data without committing the transaction thereafter committing it." }, { "code": null, "e": 29479, "s": 28985, "text": "BEGIN;\n\n\n UPDATE BankStatements\n SET balance = balance - 500\n WHERE \n customer_id = 1;\n \n // displaying data before\n // commmiting the transaction\n SELECT customer_id, full_name, balance\n FROM BankStatements;\n \n UPDATE BankStatements\n SET balance = balance + 500\n WHERE \n customer_id = 2;\n \n\n\n\n \nCOMMIT;\n\n// displaying data after\n// commmiting the transaction\nSELECT customer_id, full_name, balance\nFROM BankStatements;" }, { "code": null, "e": 29487, "s": 29479, "text": "Output:" }, { "code": null, "e": 29640, "s": 29487, "text": "NOTE: When we try to display data from another session before committing the changes then we will get the same output that we got in the first example. " }, { "code": null, "e": 29647, "s": 29640, "text": "Picked" }, { "code": null, "e": 29676, "s": 29647, "text": "postgreSQL-managing-database" }, { "code": null, "e": 29700, "s": 29676, "text": "Technical Scripter 2020" }, { "code": null, "e": 29711, "s": 29700, "text": "PostgreSQL" }, { "code": null, "e": 29730, "s": 29711, "text": "Technical Scripter" }, { "code": null, "e": 29828, "s": 29730, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29837, "s": 29828, "text": "Comments" }, { "code": null, "e": 29850, "s": 29837, "text": "Old Comments" }, { "code": null, "e": 29882, "s": 29850, "text": "PostgreSQL - Change Column Type" }, { "code": null, "e": 29909, "s": 29882, "text": "PostgreSQL - Psql commands" }, { "code": null, "e": 29932, "s": 29909, "text": "PostgreSQL - For Loops" }, { "code": null, "e": 29972, "s": 29932, "text": "PostgreSQL - Function Returning A Table" }, { "code": null, "e": 30027, "s": 29972, "text": "PostgreSQL - Create Auto-increment Column using SERIAL" }, { "code": null, "e": 30061, "s": 30027, "text": "PostgreSQL - ARRAY_AGG() Function" }, { "code": null, "e": 30085, "s": 30061, "text": "PostgreSQL - DROP INDEX" }, { "code": null, "e": 30118, "s": 30085, "text": "PostgreSQL - ROW_NUMBER Function" }, { "code": null, "e": 30160, "s": 30118, "text": "How to use PostgreSQL Database in Django?" } ]
How to change Pagefile settings using PowerShell?
To change the pagefile settings, we will divide this into multiple sections. First, when Pagefile is automatically managed, we can’t modify the settings so we need to remove that box. In GUI that box can be unchecked in Virtual memory settings. Code to uncheck the above box. $pagefile = Get-WmiObject Win32_ComputerSystem -EnableAllPrivileges $pagefile.AutomaticManagedPagefile = $false $pagefile.put() | Out-Null So once the above code is executed, other fields will be enabled. We now need to Customize the size of the pagefile in the below image by providing Initial and Maximum size using PowerShell. Here we have already the pagefile on the C: while on the E: there is no pagefile set. First, we will set the pagefile on C Drive. $pagefileset = Get-WmiObject Win32_pagefilesetting $pagefileset.InitialSize = 1024 $pagefileset.MaximumSize = 2048 $pagefileset.Put() | Out-Null Once you run the above command and check the pagefile settings, it will be customized on C Drive. You may need to reboot the system after setting the pagefile. PS C:\> Gwmi win32_Pagefilesetting | Select Name, InitialSize, MaximumSize Name InitialSize MaximumSize ---- ----------- ----------- C:\pagefile.sys 1024 2048 If you have another scenario, like setting up pagefile on the different drive for example in the above image we have E: as well. If there is no pagefile set on the drive then we need to set WMI instance for it. Set-WmiInstance -Class Win32_PageFileSetting -Arguments @{name="E:\pagefile.sys"; InitialSize = 0; MaximumSize = 0} -EnableAllPrivileges | Out-Null We have now set the pagefile on E: and it is system managed. PS C:\> Gwmi win32_pagefilesetting | where{$_.caption -like 'E:*'} MaximumSize Name Caption ----------- ---- ------- 0 E:\pagefile.sys E:\ 'pagefile.sys' If there are multiple pagefiles on the system and if we need to customize the size to the specific drive, we need to filter out the drive. In this case, we need to customize on E: so, we can filter this pagefile and modify settings. $pagefileset = Gwmi win32_pagefilesetting | where{$_.caption -like 'E:*'} $pagefileset.InitialSize = 1024 $pagefileset.MaximumSize = 2048 $pagefileset.Put() | Out-Null The size of the pagefile is now customized on E:
[ { "code": null, "e": 1432, "s": 1187, "text": "To change the pagefile settings, we will divide this into multiple sections. First, when Pagefile is\nautomatically managed, we can’t modify the settings so we need to remove that box. In GUI that box\ncan be unchecked in Virtual memory settings." }, { "code": null, "e": 1463, "s": 1432, "text": "Code to uncheck the above box." }, { "code": null, "e": 1602, "s": 1463, "text": "$pagefile = Get-WmiObject Win32_ComputerSystem -EnableAllPrivileges\n$pagefile.AutomaticManagedPagefile = $false\n$pagefile.put() | Out-Null" }, { "code": null, "e": 1793, "s": 1602, "text": "So once the above code is executed, other fields will be enabled. We now need to Customize the size of\nthe pagefile in the below image by providing Initial and Maximum size using PowerShell." }, { "code": null, "e": 1923, "s": 1793, "text": "Here we have already the pagefile on the C: while on the E: there is no pagefile set. First, we will set the pagefile on C Drive." }, { "code": null, "e": 2068, "s": 1923, "text": "$pagefileset = Get-WmiObject Win32_pagefilesetting\n$pagefileset.InitialSize = 1024\n$pagefileset.MaximumSize = 2048\n$pagefileset.Put() | Out-Null" }, { "code": null, "e": 2228, "s": 2068, "text": "Once you run the above command and check the pagefile settings, it will be customized on C Drive. You\nmay need to reboot the system after setting the pagefile." }, { "code": null, "e": 2425, "s": 2228, "text": "PS C:\\> Gwmi win32_Pagefilesetting | Select Name, InitialSize, MaximumSize\nName InitialSize MaximumSize\n---- ----------- -----------\nC:\\pagefile.sys 1024 2048" }, { "code": null, "e": 2636, "s": 2425, "text": "If you have another scenario, like setting up pagefile on the different drive for example in the above image we have E: as well. If there is no pagefile set on the drive then we need to set WMI instance for it." }, { "code": null, "e": 2784, "s": 2636, "text": "Set-WmiInstance -Class Win32_PageFileSetting -Arguments @{name=\"E:\\pagefile.sys\";\nInitialSize = 0; MaximumSize = 0} -EnableAllPrivileges | Out-Null" }, { "code": null, "e": 2845, "s": 2784, "text": "We have now set the pagefile on E: and it is system managed." }, { "code": null, "e": 3022, "s": 2845, "text": "PS C:\\> Gwmi win32_pagefilesetting | where{$_.caption -like 'E:*'}\nMaximumSize Name Caption\n----------- ---- -------\n0 E:\\pagefile.sys E:\\ 'pagefile.sys'" }, { "code": null, "e": 3255, "s": 3022, "text": "If there are multiple pagefiles on the system and if we need to customize the size to the specific drive, we need to filter out the drive. In this case, we need to customize on E: so, we can filter this pagefile and modify settings." }, { "code": null, "e": 3423, "s": 3255, "text": "$pagefileset = Gwmi win32_pagefilesetting | where{$_.caption -like 'E:*'}\n$pagefileset.InitialSize = 1024\n$pagefileset.MaximumSize = 2048\n$pagefileset.Put() | Out-Null" }, { "code": null, "e": 3472, "s": 3423, "text": "The size of the pagefile is now customized on E:" } ]
Time To Live (TTL) for a column in Cassandra
27 Nov, 2019 In this article we will discuss how to insert and update using Time To Live (TTL) command and how to determine the expire time limit of an existing column.In Cassandra Time to Live (TTL) is play an important role while if we want to set the time limit of a column and we want to automatically delete after a point of time then at the time using TTL keyword is very useful to define the time limit for a particular column. In Cassandra Both the INSERT and UPDATE commands support setting a time for data in a column to expire.It is used to set the time limit for a specific period of time. By USING TTL clause we can set the TTL value at the time of insertion.We can use TTL function to get the time remaining for a specific selected query.At the point of insertion, we can set expire limit of inserted data by using TTL clause. Let us consider if we want to set the expire limit to two days then we need to define its TTL value.By using TTL we can set the expiration period to two days and the value of TTL will be 172800 seconds. Let’s understand with an example. In Cassandra Both the INSERT and UPDATE commands support setting a time for data in a column to expire. It is used to set the time limit for a specific period of time. By USING TTL clause we can set the TTL value at the time of insertion. We can use TTL function to get the time remaining for a specific selected query. At the point of insertion, we can set expire limit of inserted data by using TTL clause. Let us consider if we want to set the expire limit to two days then we need to define its TTL value. By using TTL we can set the expiration period to two days and the value of TTL will be 172800 seconds. Let’s understand with an example. Table : student_RegistrationTo create the table used the following CQL query. CREATE TABLE student_Registration( Id int PRIMARY KEY, Name text, Event text ); Insertion using TTL :To insert data by using TTL then used the following CQL query. INSERT INTO student_Registration (Id, Name, Event) VALUES (101, 'Ashish', 'Ninza') USING TTL 172800; INSERT INTO student_Registration (Id, Name, Event) VALUES (102, 'Ashish', 'Code') USING TTL 172800; INSERT INTO student_Registration (Id, Name, Event) VALUES (103, 'Aksh', 'Ninza') USING TTL 172800; Output: Now, to determine the remaining time to expire for a specific column used the following CQL query. SELECT TTL (Name) from student_Registration WHERE Id = 101; Output: It will decrease as you will check again for its TTL value just because of TTL time limit. Now, used the following CQL query to check again. SELECT TTL (Name) from student_Registration WHERE Id = 101; Output: Updating using TTL:Now, if we want to extend the time limit then we can extend with the help of UPDATE command and USING TTL keyword. Let’s have a look. To extend time limit with 3 days and also to update the name to ‘rana’ then used the following CQL query. UPDATE student_Registration USING TTL 259200 SET Name = 'Rana' WHERE Id= 102 Output: SELECT TTL (Name) from student_Registration WHERE Id = 102; Output: Deleting a column using TTL:To delete the specific existing column used the following CQL query. UPDATE student_Registration USING TTL 0 SET Name = 'Ashish' WHERE Id = 102; Note: We can set the default TTL for entire table using Default value of TTL. Reference – https://docs.datastax.com/ Apache DBMS DBMS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. CTE in SQL Difference between Clustered and Non-clustered index Introduction of DBMS (Database Management System) | Set 1 SQL Trigger | Student Database Introduction of B-Tree SQL Interview Questions SQL | Views Introduction of ER Model Data Preprocessing in Data Mining Difference between DELETE, DROP and TRUNCATE
[ { "code": null, "e": 28, "s": 0, "text": "\n27 Nov, 2019" }, { "code": null, "e": 450, "s": 28, "text": "In this article we will discuss how to insert and update using Time To Live (TTL) command and how to determine the expire time limit of an existing column.In Cassandra Time to Live (TTL) is play an important role while if we want to set the time limit of a column and we want to automatically delete after a point of time then at the time using TTL keyword is very useful to define the time limit for a particular column." }, { "code": null, "e": 1093, "s": 450, "text": "In Cassandra Both the INSERT and UPDATE commands support setting a time for data in a column to expire.It is used to set the time limit for a specific period of time. By USING TTL clause we can set the TTL value at the time of insertion.We can use TTL function to get the time remaining for a specific selected query.At the point of insertion, we can set expire limit of inserted data by using TTL clause. Let us consider if we want to set the expire limit to two days then we need to define its TTL value.By using TTL we can set the expiration period to two days and the value of TTL will be 172800 seconds. Let’s understand with an example." }, { "code": null, "e": 1197, "s": 1093, "text": "In Cassandra Both the INSERT and UPDATE commands support setting a time for data in a column to expire." }, { "code": null, "e": 1332, "s": 1197, "text": "It is used to set the time limit for a specific period of time. By USING TTL clause we can set the TTL value at the time of insertion." }, { "code": null, "e": 1413, "s": 1332, "text": "We can use TTL function to get the time remaining for a specific selected query." }, { "code": null, "e": 1603, "s": 1413, "text": "At the point of insertion, we can set expire limit of inserted data by using TTL clause. Let us consider if we want to set the expire limit to two days then we need to define its TTL value." }, { "code": null, "e": 1740, "s": 1603, "text": "By using TTL we can set the expiration period to two days and the value of TTL will be 172800 seconds. Let’s understand with an example." }, { "code": null, "e": 1818, "s": 1740, "text": "Table : student_RegistrationTo create the table used the following CQL query." }, { "code": null, "e": 1899, "s": 1818, "text": "CREATE TABLE student_Registration(\nId int PRIMARY KEY,\nName text,\nEvent text\n);\n" }, { "code": null, "e": 1983, "s": 1899, "text": "Insertion using TTL :To insert data by using TTL then used the following CQL query." }, { "code": null, "e": 2308, "s": 1983, "text": "INSERT INTO student_Registration (Id, Name, Event) \n VALUES (101, 'Ashish', 'Ninza') USING TTL 172800;\nINSERT INTO student_Registration (Id, Name, Event) \n VALUES (102, 'Ashish', 'Code') USING TTL 172800;\nINSERT INTO student_Registration (Id, Name, Event) \n VALUES (103, 'Aksh', 'Ninza') USING TTL 172800; " }, { "code": null, "e": 2316, "s": 2308, "text": "Output:" }, { "code": null, "e": 2415, "s": 2316, "text": "Now, to determine the remaining time to expire for a specific column used the following CQL query." }, { "code": null, "e": 2478, "s": 2415, "text": "SELECT TTL (Name) \nfrom student_Registration \nWHERE Id = 101; " }, { "code": null, "e": 2486, "s": 2478, "text": "Output:" }, { "code": null, "e": 2627, "s": 2486, "text": "It will decrease as you will check again for its TTL value just because of TTL time limit. Now, used the following CQL query to check again." }, { "code": null, "e": 2690, "s": 2627, "text": "SELECT TTL (Name) \nfrom student_Registration \nWHERE Id = 101; " }, { "code": null, "e": 2698, "s": 2690, "text": "Output:" }, { "code": null, "e": 2957, "s": 2698, "text": "Updating using TTL:Now, if we want to extend the time limit then we can extend with the help of UPDATE command and USING TTL keyword. Let’s have a look. To extend time limit with 3 days and also to update the name to ‘rana’ then used the following CQL query." }, { "code": null, "e": 3037, "s": 2957, "text": "UPDATE student_Registration\nUSING TTL 259200 \nSET Name = 'Rana' \nWHERE Id= 102 " }, { "code": null, "e": 3045, "s": 3037, "text": "Output:" }, { "code": null, "e": 3108, "s": 3045, "text": "SELECT TTL (Name) \nfrom student_Registration \nWHERE Id = 102; " }, { "code": null, "e": 3116, "s": 3108, "text": "Output:" }, { "code": null, "e": 3213, "s": 3116, "text": "Deleting a column using TTL:To delete the specific existing column used the following CQL query." }, { "code": null, "e": 3292, "s": 3213, "text": "UPDATE student_Registration\nUSING TTL 0 \nSET Name = 'Ashish' \nWHERE Id = 102; " }, { "code": null, "e": 3370, "s": 3292, "text": "Note: We can set the default TTL for entire table using Default value of TTL." }, { "code": null, "e": 3409, "s": 3370, "text": "Reference – https://docs.datastax.com/" }, { "code": null, "e": 3416, "s": 3409, "text": "Apache" }, { "code": null, "e": 3421, "s": 3416, "text": "DBMS" }, { "code": null, "e": 3426, "s": 3421, "text": "DBMS" }, { "code": null, "e": 3524, "s": 3426, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3535, "s": 3524, "text": "CTE in SQL" }, { "code": null, "e": 3588, "s": 3535, "text": "Difference between Clustered and Non-clustered index" }, { "code": null, "e": 3646, "s": 3588, "text": "Introduction of DBMS (Database Management System) | Set 1" }, { "code": null, "e": 3677, "s": 3646, "text": "SQL Trigger | Student Database" }, { "code": null, "e": 3700, "s": 3677, "text": "Introduction of B-Tree" }, { "code": null, "e": 3724, "s": 3700, "text": "SQL Interview Questions" }, { "code": null, "e": 3736, "s": 3724, "text": "SQL | Views" }, { "code": null, "e": 3761, "s": 3736, "text": "Introduction of ER Model" }, { "code": null, "e": 3795, "s": 3761, "text": "Data Preprocessing in Data Mining" } ]
Python Program to Convert Celsius To Fahrenheit
24 Oct, 2021 Given the temperature in degree Celsius. the task is to convert the value in the Fahrenheit scale and display it. Examples : Input : 37 Output : 37.00 Celsius is: 98.60 Fahrenheit Input : 40 Output : 40.00 Celsius is equivalent to: 104.00 Fahrenheit Approach: Take Celsius temperature as input from the user, apply the conversion formula of Fahrenheit from Celsius, and display it. The relationship between the Celsius scale and the Fahrenheit scale is given by : Below is the implementation. Python3 # Temperature in celsius degreecelsius = 40 # Converting the temperature to# fehrenheit using the above# mentioned formulafahrenheit = (celsius * 1.8) + 32 # printing the resultprint('%.2f Celsius is equivalent to: %.2f Fahrenheit' %(celsius, fahrenheit)) Output: 40.00 Celsius is equivalent to: 104.00 Fahrenheit surinderdawra388 school-programming Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() Python program to convert a list to string Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python | Convert string dictionary to dictionary
[ { "code": null, "e": 53, "s": 25, "text": "\n24 Oct, 2021" }, { "code": null, "e": 180, "s": 53, "text": "Given the temperature in degree Celsius. the task is to convert the value in the Fahrenheit scale and display it. Examples : " }, { "code": null, "e": 307, "s": 180, "text": "Input :\n37 \nOutput :\n37.00 Celsius is: 98.60 Fahrenheit\n\nInput :\n40\nOutput :\n40.00 Celsius is equivalent to: 104.00 Fahrenheit" }, { "code": null, "e": 555, "s": 307, "text": "Approach: Take Celsius temperature as input from the user, apply the conversion formula of Fahrenheit from Celsius, and display it. The relationship between the Celsius scale and the Fahrenheit scale is given by : Below is the implementation. " }, { "code": null, "e": 563, "s": 555, "text": "Python3" }, { "code": "# Temperature in celsius degreecelsius = 40 # Converting the temperature to# fehrenheit using the above# mentioned formulafahrenheit = (celsius * 1.8) + 32 # printing the resultprint('%.2f Celsius is equivalent to: %.2f Fahrenheit' %(celsius, fahrenheit))", "e": 824, "s": 563, "text": null }, { "code": null, "e": 833, "s": 824, "text": "Output: " }, { "code": null, "e": 883, "s": 833, "text": "40.00 Celsius is equivalent to: 104.00 Fahrenheit" }, { "code": null, "e": 902, "s": 885, "text": "surinderdawra388" }, { "code": null, "e": 921, "s": 902, "text": "school-programming" }, { "code": null, "e": 928, "s": 921, "text": "Python" }, { "code": null, "e": 944, "s": 928, "text": "Python Programs" }, { "code": null, "e": 1042, "s": 944, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1060, "s": 1042, "text": "Python Dictionary" }, { "code": null, "e": 1102, "s": 1060, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 1124, "s": 1102, "text": "Enumerate() in Python" }, { "code": null, "e": 1159, "s": 1124, "text": "Read a file line by line in Python" }, { "code": null, "e": 1185, "s": 1159, "text": "Python String | replace()" }, { "code": null, "e": 1228, "s": 1185, "text": "Python program to convert a list to string" }, { "code": null, "e": 1250, "s": 1228, "text": "Defaultdict in Python" }, { "code": null, "e": 1289, "s": 1250, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 1327, "s": 1289, "text": "Python | Convert a list to dictionary" } ]
How to create a hyperlink for values from an array in Angular 8?
11 Sep, 2020 Introduction:In angular 8, we can create hyperlinks for all the values that are present in the array using *ngFor. Approach:1) First declare and initialize array in .ts file.2) Then use *ngFor directive for iterating through the array.3) Using this *ngFor directive in .html file, we can use it as per the requirement.4) Once the implementation is done then the serve the project. Syntax:Syntax for starting the project. ng serve --open Implementation by code: app.component.html: <div *ngFor = "let item of data"> <a [attr.href]="item.url"> {{item.name}} </a></div> app.component.ts: import { Component } from '@angular/core';@Component({ selector: 'my-app', templateUrl: './app.component.html', styleUrls: [ `a{ text-decoration: none; color:black; cursor: pointer } ` ]})export class AppComponent { data=[ { name:"GeeksForGeeks", url:"www.geeksforgeeks.org" }, { name:"Google", url:"www.google.com" }, { name:"HackerRank", url:"www.hackerrank.com" } ] } Output: AngularJS-Misc Picked AngularJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n11 Sep, 2020" }, { "code": null, "e": 143, "s": 28, "text": "Introduction:In angular 8, we can create hyperlinks for all the values that are present in the array using *ngFor." }, { "code": null, "e": 409, "s": 143, "text": "Approach:1) First declare and initialize array in .ts file.2) Then use *ngFor directive for iterating through the array.3) Using this *ngFor directive in .html file, we can use it as per the requirement.4) Once the implementation is done then the serve the project." }, { "code": null, "e": 449, "s": 409, "text": "Syntax:Syntax for starting the project." }, { "code": null, "e": 465, "s": 449, "text": "ng serve --open" }, { "code": null, "e": 489, "s": 465, "text": "Implementation by code:" }, { "code": null, "e": 510, "s": 489, "text": "app.component.html: " }, { "code": "<div *ngFor = \"let item of data\"> <a [attr.href]=\"item.url\"> {{item.name}} </a></div>", "e": 601, "s": 510, "text": null }, { "code": null, "e": 620, "s": 601, "text": "app.component.ts: " }, { "code": "import { Component } from '@angular/core';@Component({ selector: 'my-app', templateUrl: './app.component.html', styleUrls: [ `a{ text-decoration: none; color:black; cursor: pointer } ` ]})export class AppComponent { data=[ { name:\"GeeksForGeeks\", url:\"www.geeksforgeeks.org\" }, { name:\"Google\", url:\"www.google.com\" }, { name:\"HackerRank\", url:\"www.hackerrank.com\" } ] }", "e": 1070, "s": 620, "text": null }, { "code": null, "e": 1079, "s": 1070, "text": "Output: " }, { "code": null, "e": 1094, "s": 1079, "text": "AngularJS-Misc" }, { "code": null, "e": 1101, "s": 1094, "text": "Picked" }, { "code": null, "e": 1111, "s": 1101, "text": "AngularJS" }, { "code": null, "e": 1128, "s": 1111, "text": "Web Technologies" } ]
Advanced C++ with boost library
C++ boost libraries are widely useful library. This is used for different sections. It has large domain of applications. For example, using boost, we can use large number like 264 in C++. Here we will see some examples of boost library. We can use big integer datatype. We can use different datatypes like int128_t, int256_t, int1024_t etc. By using this we can get precision up to 1024 easily. At first we are multiplying two huge number using boost library. #include<iostream> #include <boost/multiprecision/cpp_int.hpp> using namespace boost::multiprecision; using namespace std; int128_t large_product(long long n1, long long n2) { int128_t ans = (int128_t) n1 * n2; return ans; } int main() { long long num1 = 98745636214564698; long long num2 = 7459874565236544789; cout >> "Product of ">> num1 >> " * ">> num2 >> " = " >> large_product(num1,num2); } Product of 98745636214564698 * 7459874565236544789 = 736630060025131838840151335215258722 Another kind of datatype is that Arbitrary Precision Datatype. So we can use any precision using cpp_int datatype. It automatically assigns precision at runtime. #include<iostream> #include <boost/multiprecision/cpp_int.hpp> using namespace boost::multiprecision; using namespace std; cpp_int large_fact(int num) { cpp_int fact = 1; for (int i=num; i>1; --i) fact *= i; return fact; } int main() { cout >> "Factorial of 50: " >> large_fact(50) >> endl; } Factorial of 50: 30414093201713378043612608166064768844377641568960512000000000000 Using multi-precision float, we can get precision up to 50 and 100 decimal places. For this we can use cpp_float_50 or cpp_dec_float_100 respectively. Let us see the example to get the better idea. #include<iostream> #include <boost/multiprecision/cpp_dec_float.hpp> #include <boost/math/constants/constants.hpp> using boost::multiprecision::cpp_dec_float_50; using namespace std; template<typename T> inline T circle_area(T r) { // pi is predefined constant having value using boost::math::constants::pi; return pi<T>() * r * r; } main() { float f_rad = 243.0/ 100; float f_area = circle_area(f_rad); double d_rad = 243.0 / 100; double d_area = circle_area(d_rad); cpp_dec_float_50 rad_mp = 243.0 / 100; cpp_dec_float_50 area_mp = circle_area(rad_mp); cout >> "Float: " >> setprecision(numeric_limits<float>::digits10) >> f_area >> endl; // Double area cout >> "Double: " >>setprecision(numeric_limits<double>::digits10) >> d_area >> endl; // Area by using Boost Multiprecision cout >> "Boost Multiprecision Res: " >> setprecision(numeric_limits<cpp_dec_float_50>::digits10) >> area_mp >> endl; } Float: 18.5508 Double: 18.5507904601824 Boost Multiprecision Res: 18.550790460182372534747952560288165408707655564121
[ { "code": null, "e": 1375, "s": 1187, "text": "C++ boost libraries are widely useful library. This is used for different sections. It has large domain of applications. For example, using boost, we can use large number like 264 in C++." }, { "code": null, "e": 1582, "s": 1375, "text": "Here we will see some examples of boost library. We can use big integer datatype. We can use different datatypes like int128_t, int256_t, int1024_t etc. By using this we can get precision up to 1024 easily." }, { "code": null, "e": 1647, "s": 1582, "text": "At first we are multiplying two huge number using boost library." }, { "code": null, "e": 2062, "s": 1647, "text": "#include<iostream>\n#include <boost/multiprecision/cpp_int.hpp>\nusing namespace boost::multiprecision;\nusing namespace std;\nint128_t large_product(long long n1, long long n2) {\n int128_t ans = (int128_t) n1 * n2;\n return ans;\n}\nint main() {\n long long num1 = 98745636214564698;\n long long num2 = 7459874565236544789;\n cout >> \"Product of \">> num1 >> \" * \">> num2 >> \" = \" >>\n large_product(num1,num2);\n}" }, { "code": null, "e": 2152, "s": 2062, "text": "Product of 98745636214564698 * 7459874565236544789 =\n736630060025131838840151335215258722" }, { "code": null, "e": 2314, "s": 2152, "text": "Another kind of datatype is that Arbitrary Precision Datatype. So we can use any precision using cpp_int datatype. It automatically assigns precision at runtime." }, { "code": null, "e": 2625, "s": 2314, "text": "#include<iostream>\n#include <boost/multiprecision/cpp_int.hpp>\nusing namespace boost::multiprecision;\nusing namespace std;\ncpp_int large_fact(int num) {\n cpp_int fact = 1;\n for (int i=num; i>1; --i)\n fact *= i;\n return fact;\n}\nint main() {\n cout >> \"Factorial of 50: \" >> large_fact(50) >> endl;\n}" }, { "code": null, "e": 2708, "s": 2625, "text": "Factorial of 50:\n30414093201713378043612608166064768844377641568960512000000000000" }, { "code": null, "e": 2906, "s": 2708, "text": "Using multi-precision float, we can get precision up to 50 and 100 decimal places. For this we can use cpp_float_50 or cpp_dec_float_100 respectively. Let us see the example to get the better idea." }, { "code": null, "e": 3857, "s": 2906, "text": "#include<iostream>\n#include <boost/multiprecision/cpp_dec_float.hpp>\n#include <boost/math/constants/constants.hpp>\nusing boost::multiprecision::cpp_dec_float_50;\nusing namespace std;\ntemplate<typename T>\ninline T circle_area(T r) {\n // pi is predefined constant having value\n using boost::math::constants::pi;\n return pi<T>() * r * r;\n}\nmain() {\n float f_rad = 243.0/ 100;\n float f_area = circle_area(f_rad);\n double d_rad = 243.0 / 100;\n double d_area = circle_area(d_rad);\n cpp_dec_float_50 rad_mp = 243.0 / 100;\n cpp_dec_float_50 area_mp = circle_area(rad_mp);\n cout >> \"Float: \" >> setprecision(numeric_limits<float>::digits10) >> f_area >>\n endl;\n // Double area\n cout >> \"Double: \" >>setprecision(numeric_limits<double>::digits10) >> d_area\n >> endl;\n // Area by using Boost Multiprecision\n cout >> \"Boost Multiprecision Res: \" >>\n setprecision(numeric_limits<cpp_dec_float_50>::digits10) >> area_mp >> endl;\n}" }, { "code": null, "e": 3975, "s": 3857, "text": "Float: 18.5508\nDouble: 18.5507904601824\nBoost Multiprecision Res:\n18.550790460182372534747952560288165408707655564121" } ]
Adding JSON field in Django models
In this article, we will see how to add JSON fields to our Django models. JSON is a simple format to store data in key and value format. It is written in curly braces. Many a time, on developer website, we need to add developer data and JSON fields are useful in such cases. First create a Django project and an app. Please do all the basic things, like adding app in INSTALLED_APPS and setting up urls, making a basic model and render its form in an HTML file. Install the django-jsonfield package − pip install django-jsonfield Now, let's create a model in models.py, for example − import jsonfield from django.db import models # Create your models here. class StudentData(models.Model): name=models.CharField(max_length=100) standard=models.CharField(max_length=100) section=models.CharField(max_length=100) the_json = jsonfield.JSONField() In admin.py, add the following lines − from django.contrib import admin from .models import StudentData admin.site.register(StudentData) We created a model here which has four fields, one of it is our thirdparty JSON field. Now, run these commands − python manage.py makemigrations python manage.py migrate python manage.py createsuperuser These commands will create the table and the last command will create an admin user for you. Now, you are all done. Go to http://127.0.0.1/admin/ and go to your model admin, then add an instance, you will see a field like this −
[ { "code": null, "e": 1462, "s": 1187, "text": "In this article, we will see how to add JSON fields to our Django models. JSON is a simple format to store data in key and value format. It is written in curly braces. Many a time, on developer website, we need to add developer data and JSON fields are useful in such cases." }, { "code": null, "e": 1649, "s": 1462, "text": "First create a Django project and an app. Please do all the basic things, like adding app in INSTALLED_APPS and setting up urls, making a basic model and render its form in an HTML file." }, { "code": null, "e": 1688, "s": 1649, "text": "Install the django-jsonfield package −" }, { "code": null, "e": 1717, "s": 1688, "text": "pip install django-jsonfield" }, { "code": null, "e": 1771, "s": 1717, "text": "Now, let's create a model in models.py, for example −" }, { "code": null, "e": 2045, "s": 1771, "text": "import jsonfield\nfrom django.db import models\n\n# Create your models here.\n\nclass StudentData(models.Model):\n name=models.CharField(max_length=100)\n standard=models.CharField(max_length=100)\n section=models.CharField(max_length=100)\n the_json = jsonfield.JSONField()" }, { "code": null, "e": 2084, "s": 2045, "text": "In admin.py, add the following lines −" }, { "code": null, "e": 2184, "s": 2084, "text": "from django.contrib import admin\n\nfrom .models import StudentData\n\nadmin.site.register(StudentData)" }, { "code": null, "e": 2271, "s": 2184, "text": "We created a model here which has four fields, one of it is our thirdparty JSON field." }, { "code": null, "e": 2297, "s": 2271, "text": "Now, run these commands −" }, { "code": null, "e": 2387, "s": 2297, "text": "python manage.py makemigrations\npython manage.py migrate\npython manage.py createsuperuser" }, { "code": null, "e": 2480, "s": 2387, "text": "These commands will create the table and the last command will create an admin user for you." }, { "code": null, "e": 2503, "s": 2480, "text": "Now, you are all done." }, { "code": null, "e": 2616, "s": 2503, "text": "Go to http://127.0.0.1/admin/ and go to your model admin, then add an instance, you will see a field like this −" } ]
Print the pattern by using one loop | Set 2 (Using Continue Statement)
23 Apr, 2021 Given a number n, print triangular pattern. We are allowed to use only one loop.Example: Input: 7 Output: * * * * * * * * * * * * * * * * * * * * * * * * * * * * We use single for-loop and in the loop we maintain two variables for line count and current star count. If current star count is less than current line count, we print a star and continue. Else we print a new line and increment line count. C Java Python 3 C# PHP Javascript // C++ program to print a pattern using single// loop and continue statement#include<bits/stdc++.h>using namespace std; // printPattern function to print patternvoid printPattern(int n){ // Variable initialization int line_no = 1; // Line count // Loop to print desired pattern int curr_star = 0; for (int line_no = 1; line_no <= n; ) { // If current star count is less than // current line number if (curr_star < line_no) { cout << "* "; curr_star++; continue; } // Else time to print a new line if (curr_star == line_no) { cout << "\n"; line_no++; curr_star = 0; } }} // Driver codeint main(){ printPattern(7); return 0;} // Java program to print a pattern using single// loop and continue statementimport java.io.*; class GFG { // printPattern function to print pattern static void printPattern(int n) { // Variable initialization // Line count int line_no = 1; // Loop to print desired pattern int curr_star = 0; for ( line_no = 1; line_no <= n;) { // If current star count is less than // current line number if (curr_star < line_no) { System.out.print ( "* "); curr_star++; continue; } // Else time to print a new line if (curr_star == line_no) { System.out.println (""); line_no++; curr_star = 0; } } } // Driver code public static void main (String[] args) { printPattern(7); }} // This code is contributed by vt_m # Python 3 program to print# a pattern using single# loop and continue statement # printPattern function# to print patterndef printPattern(n): # Variable initialization line_no = 1 # Line count # Loop to print # desired pattern curr_star = 0 line_no = 1 while(line_no <= n ): # If current star count # is less than current # line number if (curr_star < line_no): print("* ", end = "") curr_star += 1 continue # Else time to print # a new line if (curr_star == line_no): print("") line_no += 1 curr_star = 0 # Driver codeprintPattern(7) # This code is contributed# by Smitha // C# program to print a pattern using single// loop and continue statementusing System; class GFG { // printPattern function to print pattern static void printPattern(int n) { // Variable initialization // Line count int line_no = 1; // Loop to print desired pattern int curr_star = 0; for ( line_no = 1; line_no <= n;) { // If current star count is less than // current line number if (curr_star < line_no) { Console.Write ( "* "); curr_star++; continue; } // Else time to print a new line if (curr_star == line_no) { Console.WriteLine (); line_no++; curr_star = 0; } } } // Driver code public static void Main () { printPattern(7); }} // This code is contributed by vt_m <?php// php program to print a// pattern using single loop// and continue statement // printPattern function// to print patternfunction printPattern($n){ // Variable initialization $line_no = 1; // Line count // Loop to print desired pattern $curr_star = 0; for ($line_no = 1; $line_no <= $n { // If current star count is less // than current line number if ($curr_star < $line_no) { echo "* "; $curr_star++; continue; } // Else time to print // a new line if ($curr_star == $line_no) { echo "\n"; $line_no++; $curr_star = 0; } }} // Driver code $n=7; printPattern($n); // This code is contributed by mits?> <script> // JavaScript program to print a pattern using single // loop and continue statement // printPattern function to print pattern function printPattern(n) { // Variable initialization var line_no = 1; // Line count // Loop to print desired pattern var curr_star = 0; for (var line_no = 1; line_no <= n; ) { // If current star count is less than // current line number if (curr_star < line_no) { document.write("* "); curr_star++; continue; } // Else time to print a new line if (curr_star == line_no) { document.write("<br>"); line_no++; curr_star = 0; } } } // Driver code printPattern(7); // This code is contributed by rdtank. </script> Output: * * * * * * * * * * * * * * * * * * * * * * * * * * * * Time Complexity: O(n) Auxiliary Space: O(1)Please refer below post for one more approach. Print pattern using only one loopThis article is contributed by Ashish Varshney. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Mithun Kumar Smitha Dinesh Semwal subhammahato348 rdtank pattern-printing School Programming pattern-printing Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n23 Apr, 2021" }, { "code": null, "e": 142, "s": 52, "text": "Given a number n, print triangular pattern. We are allowed to use only one loop.Example: " }, { "code": null, "e": 216, "s": 142, "text": "Input: 7\nOutput:\n*\n* * \n* * *\n* * * *\n* * * * *\n* * * * * *\n* * * * * * *" }, { "code": null, "e": 458, "s": 216, "text": "We use single for-loop and in the loop we maintain two variables for line count and current star count. If current star count is less than current line count, we print a star and continue. Else we print a new line and increment line count. " }, { "code": null, "e": 460, "s": 458, "text": "C" }, { "code": null, "e": 465, "s": 460, "text": "Java" }, { "code": null, "e": 474, "s": 465, "text": "Python 3" }, { "code": null, "e": 477, "s": 474, "text": "C#" }, { "code": null, "e": 481, "s": 477, "text": "PHP" }, { "code": null, "e": 492, "s": 481, "text": "Javascript" }, { "code": "// C++ program to print a pattern using single// loop and continue statement#include<bits/stdc++.h>using namespace std; // printPattern function to print patternvoid printPattern(int n){ // Variable initialization int line_no = 1; // Line count // Loop to print desired pattern int curr_star = 0; for (int line_no = 1; line_no <= n; ) { // If current star count is less than // current line number if (curr_star < line_no) { cout << \"* \"; curr_star++; continue; } // Else time to print a new line if (curr_star == line_no) { cout << \"\\n\"; line_no++; curr_star = 0; } }} // Driver codeint main(){ printPattern(7); return 0;}", "e": 1268, "s": 492, "text": null }, { "code": "// Java program to print a pattern using single// loop and continue statementimport java.io.*; class GFG { // printPattern function to print pattern static void printPattern(int n) { // Variable initialization // Line count int line_no = 1; // Loop to print desired pattern int curr_star = 0; for ( line_no = 1; line_no <= n;) { // If current star count is less than // current line number if (curr_star < line_no) { System.out.print ( \"* \"); curr_star++; continue; } // Else time to print a new line if (curr_star == line_no) { System.out.println (\"\"); line_no++; curr_star = 0; } } } // Driver code public static void main (String[] args) { printPattern(7); }} // This code is contributed by vt_m", "e": 2263, "s": 1268, "text": null }, { "code": "# Python 3 program to print# a pattern using single# loop and continue statement # printPattern function# to print patterndef printPattern(n): # Variable initialization line_no = 1 # Line count # Loop to print # desired pattern curr_star = 0 line_no = 1 while(line_no <= n ): # If current star count # is less than current # line number if (curr_star < line_no): print(\"* \", end = \"\") curr_star += 1 continue # Else time to print # a new line if (curr_star == line_no): print(\"\") line_no += 1 curr_star = 0 # Driver codeprintPattern(7) # This code is contributed# by Smitha", "e": 2997, "s": 2263, "text": null }, { "code": "// C# program to print a pattern using single// loop and continue statementusing System; class GFG { // printPattern function to print pattern static void printPattern(int n) { // Variable initialization // Line count int line_no = 1; // Loop to print desired pattern int curr_star = 0; for ( line_no = 1; line_no <= n;) { // If current star count is less than // current line number if (curr_star < line_no) { Console.Write ( \"* \"); curr_star++; continue; } // Else time to print a new line if (curr_star == line_no) { Console.WriteLine (); line_no++; curr_star = 0; } } } // Driver code public static void Main () { printPattern(7); }} // This code is contributed by vt_m", "e": 3967, "s": 2997, "text": null }, { "code": "<?php// php program to print a// pattern using single loop// and continue statement // printPattern function// to print patternfunction printPattern($n){ // Variable initialization $line_no = 1; // Line count // Loop to print desired pattern $curr_star = 0; for ($line_no = 1; $line_no <= $n { // If current star count is less // than current line number if ($curr_star < $line_no) { echo \"* \"; $curr_star++; continue; } // Else time to print // a new line if ($curr_star == $line_no) { echo \"\\n\"; $line_no++; $curr_star = 0; } }} // Driver code $n=7; printPattern($n); // This code is contributed by mits?>", "e": 4758, "s": 3967, "text": null }, { "code": "<script> // JavaScript program to print a pattern using single // loop and continue statement // printPattern function to print pattern function printPattern(n) { // Variable initialization var line_no = 1; // Line count // Loop to print desired pattern var curr_star = 0; for (var line_no = 1; line_no <= n; ) { // If current star count is less than // current line number if (curr_star < line_no) { document.write(\"* \"); curr_star++; continue; } // Else time to print a new line if (curr_star == line_no) { document.write(\"<br>\"); line_no++; curr_star = 0; } } } // Driver code printPattern(7); // This code is contributed by rdtank. </script>", "e": 5675, "s": 4758, "text": null }, { "code": null, "e": 5684, "s": 5675, "text": "Output: " }, { "code": null, "e": 5740, "s": 5684, "text": "*\n* *\n* * *\n* * * *\n* * * * *\n* * * * * *\n* * * * * * *" }, { "code": null, "e": 5762, "s": 5740, "text": "Time Complexity: O(n)" }, { "code": null, "e": 6290, "s": 5762, "text": "Auxiliary Space: O(1)Please refer below post for one more approach. Print pattern using only one loopThis article is contributed by Ashish Varshney. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 6303, "s": 6290, "text": "Mithun Kumar" }, { "code": null, "e": 6324, "s": 6303, "text": "Smitha Dinesh Semwal" }, { "code": null, "e": 6340, "s": 6324, "text": "subhammahato348" }, { "code": null, "e": 6347, "s": 6340, "text": "rdtank" }, { "code": null, "e": 6364, "s": 6347, "text": "pattern-printing" }, { "code": null, "e": 6383, "s": 6364, "text": "School Programming" }, { "code": null, "e": 6400, "s": 6383, "text": "pattern-printing" } ]
Implement Like a Blog Post Functionality in Social Media Android App
17 Jun, 2021 This is the Part 10 of “Build a Social Media App on Android Studio” tutorial, and we are going to cover the following functionalities in this article: We are going to Like a Blog. We are implementing this feature using two images one like button with white background and another like button with blue background. When the user clicks on the button for the first time we will change the image to the button with the background color blue and will increase the count. When the user clicks again then we will decrease the count and change the like button with background white. Step 1: Working with the row_posts.xml file Add a like button and total like TextView. XML <Button android:id="@+id/like" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:autoLink="all" android:background="@color/colorWhite" android:drawableStart="@drawable/ic_like" android:drawableLeft="@drawable/ic_like" android:padding="5dp" android:text="Like" /> Below is the updated code for the row_posts.xml file. XML <?xml version="1.0" encoding="utf-8"?><androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" app:cardBackgroundColor="@color/colorWhite" app:cardCornerRadius="3dp" app:cardElevation="3dp" app:cardUseCompatPadding="true" app:contentPadding="5dp"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <LinearLayout android:id="@+id/profilelayout" android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center_vertical" android:orientation="horizontal"> <de.hdodenhof.circleimageview.CircleImageView android:id="@+id/picturetv" android:layout_width="50dp" android:layout_height="50dp" android:scaleType="centerCrop" android:src="@drawable/profile_image" /> <LinearLayout android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:orientation="vertical"> <TextView android:id="@+id/unametv" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Name" android:textColor="@color/colorBlack" android:textSize="20sp" /> <TextView android:id="@+id/utimetv" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="33 min" /> </LinearLayout> <ImageButton android:id="@+id/morebtn" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@null" android:src="@drawable/ic_more" /> </LinearLayout> <TextView android:id="@+id/ptitletv" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Title" android:textSize="16sp" android:textStyle="bold" /> <TextView android:id="@+id/descript" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Description" android:textColor="@color/colorBlack" /> <ImageView android:id="@+id/pimagetv" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@color/colorWhite" /> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <TextView android:id="@+id/plikeb" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="1" android:text="1.2K Likes" android:textColor="@color/colorPrimary" /> <TextView android:id="@+id/pcommentco" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="1" android:text="1.2K Comment" android:textAlignment="textEnd" android:textColor="@color/colorPrimary" /> </LinearLayout> <View android:layout_width="match_parent" android:layout_height="1dp" android:background="#F5F0F0" /> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center" android:orientation="horizontal"> <Button android:id="@+id/like" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:autoLink="all" android:background="@color/colorWhite" android:drawableStart="@drawable/ic_like" android:drawableLeft="@drawable/ic_like" android:padding="5dp" android:text="Like" /> <Button android:id="@+id/comment" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:autoLink="all" android:background="@color/colorWhite" android:drawableStart="@drawable/ic_comment" android:drawableLeft="@drawable/ic_comment" android:padding="5dp" android:text="COMMENT" /> </LinearLayout> </LinearLayout> </androidx.cardview.widget.CardView> Step 2: Working with the AdapterPosts.java file Go to the AdapterPosts.java file and refer to the following code. Below is the updated code for the AdapterPosts.java file. Java package com.example.socialmediaapp; import android.app.ProgressDialog;import android.content.Context;import android.content.Intent;import android.text.format.DateFormat;import android.view.Gravity;import android.view.LayoutInflater;import android.view.Menu;import android.view.MenuItem;import android.view.View;import android.view.ViewGroup;import android.widget.Button;import android.widget.ImageButton;import android.widget.ImageView;import android.widget.LinearLayout;import android.widget.PopupMenu;import android.widget.TextView;import android.widget.Toast; import androidx.annotation.NonNull;import androidx.recyclerview.widget.RecyclerView; import com.bumptech.glide.Glide;import com.google.android.gms.tasks.OnFailureListener;import com.google.android.gms.tasks.OnSuccessListener;import com.google.firebase.auth.FirebaseAuth;import com.google.firebase.database.DataSnapshot;import com.google.firebase.database.DatabaseError;import com.google.firebase.database.DatabaseReference;import com.google.firebase.database.FirebaseDatabase;import com.google.firebase.database.Query;import com.google.firebase.database.ValueEventListener;import com.google.firebase.storage.FirebaseStorage;import com.google.firebase.storage.StorageReference; import java.util.Calendar;import java.util.List;import java.util.Locale; public class AdapterPosts extends RecyclerView.Adapter<com.example.socialmediaapp.AdapterPosts.MyHolder> { Context context; String myuid; private DatabaseReference liekeref, postref; boolean mprocesslike = false; public AdapterPosts(Context context, List<ModelPost> modelPosts) { this.context = context; this.modelPosts = modelPosts; myuid = FirebaseAuth.getInstance().getCurrentUser().getUid(); liekeref = FirebaseDatabase.getInstance().getReference().child("Likes"); postref = FirebaseDatabase.getInstance().getReference().child("Posts"); } List<ModelPost> modelPosts; @NonNull @Override public MyHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(context).inflate(R.layout.row_posts, parent, false); return new MyHolder(view); } @Override public void onBindViewHolder(@NonNull final MyHolder holder, final int position) { final String uid = modelPosts.get(position).getUid(); String nameh = modelPosts.get(position).getUname(); final String titlee = modelPosts.get(position).getTitle(); final String descri = modelPosts.get(position).getDescription(); final String ptime = modelPosts.get(position).getPtime(); String dp = modelPosts.get(position).getUdp(); String plike = modelPosts.get(position).getPlike(); final String image = modelPosts.get(position).getUimage(); String email = modelPosts.get(position).getUemail(); String comm = modelPosts.get(position).getPcomments(); final String pid = modelPosts.get(position).getPtime(); Calendar calendar = Calendar.getInstance(Locale.ENGLISH); calendar.setTimeInMillis(Long.parseLong(ptime)); String timedate = DateFormat.format("dd/MM/yyyy hh:mm aa", calendar).toString(); holder.name.setText(nameh); holder.title.setText(titlee); holder.description.setText(descri); holder.time.setText(timedate); holder.like.setText(plike + " Likes"); holder.comments.setText(comm + " Comments"); setLikes(holder, ptime); try { Glide.with(context).load(dp).into(holder.picture); } catch (Exception e) { } holder.image.setVisibility(View.VISIBLE); try { Glide.with(context).load(image).into(holder.image); } catch (Exception e) { } holder.like.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(holder.itemView.getContext(), PostLikedByActivity.class); intent.putExtra("pid", pid); holder.itemView.getContext().startActivity(intent); } }); holder.likebtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { final int plike = Integer.parseInt(modelPosts.get(position).getPlike()); mprocesslike = true; final String postid = modelPosts.get(position).getPtime(); liekeref.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { if (mprocesslike) { if (dataSnapshot.child(postid).hasChild(myuid)) { postref.child(postid).child("plike").setValue("" + (plike - 1)); liekeref.child(postid).child(myuid).removeValue(); mprocesslike = false; } else { postref.child(postid).child("plike").setValue("" + (plike + 1)); liekeref.child(postid).child(myuid).setValue("Liked"); mprocesslike = false; } } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); } }); holder.more.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showMoreOptions(holder.more, uid, myuid, ptime, image); } }); holder.comment.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(context, PostDetailsActivity.class); intent.putExtra("pid", ptime); context.startActivity(intent); } }); } private void showMoreOptions(ImageButton more, String uid, String myuid, final String pid, final String image) { PopupMenu popupMenu = new PopupMenu(context, more, Gravity.END); if (uid.equals(myuid)) { popupMenu.getMenu().add(Menu.NONE, 0, 0, "DELETE"); } popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { if (item.getItemId() == 0) { deltewithImage(pid, image); } return false; } }); popupMenu.show(); } private void deltewithImage(final String pid, String image) { final ProgressDialog pd = new ProgressDialog(context); pd.setMessage("Deleting"); StorageReference picref = FirebaseStorage.getInstance().getReferenceFromUrl(image); picref.delete().addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { Query query = FirebaseDatabase.getInstance().getReference("Posts").orderByChild("ptime").equalTo(pid); query.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) { dataSnapshot1.getRef().removeValue(); } pd.dismiss(); Toast.makeText(context, "Deleted Successfully", Toast.LENGTH_LONG).show(); } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { } }); } private void setLikes(final MyHolder holder, final String pid) { liekeref.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { if (dataSnapshot.child(pid).hasChild(myuid)) { holder.likebtn.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_liked, 0, 0, 0); holder.likebtn.setText("Liked"); } else { holder.likebtn.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_like, 0, 0, 0); holder.likebtn.setText("Like"); } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); } @Override public int getItemCount() { return modelPosts.size(); } class MyHolder extends RecyclerView.ViewHolder { ImageView picture, image; TextView name, time, title, description, like, comments; ImageButton more; Button likebtn, comment; LinearLayout profile; public MyHolder(@NonNull View itemView) { super(itemView); picture = itemView.findViewById(R.id.picturetv); image = itemView.findViewById(R.id.pimagetv); name = itemView.findViewById(R.id.unametv); time = itemView.findViewById(R.id.utimetv); more = itemView.findViewById(R.id.morebtn); title = itemView.findViewById(R.id.ptitletv); description = itemView.findViewById(R.id.descript); like = itemView.findViewById(R.id.plikeb); comments = itemView.findViewById(R.id.pcommentco); likebtn = itemView.findViewById(R.id.like); comment = itemView.findViewById(R.id.comment); profile = itemView.findViewById(R.id.profilelayout); } }} Output: For all the drawable file used in this article please refer to this link: https://drive.google.com/drive/folders/1M_knOH_ugCuwSP5nkYzeD4dRp-Honzbe?usp=sharing Below is the file structure after performing these operations: ruhelaa48 Firebase Android Java Java Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n17 Jun, 2021" }, { "code": null, "e": 179, "s": 28, "text": "This is the Part 10 of “Build a Social Media App on Android Studio” tutorial, and we are going to cover the following functionalities in this article:" }, { "code": null, "e": 342, "s": 179, "text": "We are going to Like a Blog. We are implementing this feature using two images one like button with white background and another like button with blue background." }, { "code": null, "e": 604, "s": 342, "text": "When the user clicks on the button for the first time we will change the image to the button with the background color blue and will increase the count. When the user clicks again then we will decrease the count and change the like button with background white." }, { "code": null, "e": 648, "s": 604, "text": "Step 1: Working with the row_posts.xml file" }, { "code": null, "e": 691, "s": 648, "text": "Add a like button and total like TextView." }, { "code": null, "e": 695, "s": 691, "text": "XML" }, { "code": "<Button android:id=\"@+id/like\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_weight=\"1\" android:autoLink=\"all\" android:background=\"@color/colorWhite\" android:drawableStart=\"@drawable/ic_like\" android:drawableLeft=\"@drawable/ic_like\" android:padding=\"5dp\" android:text=\"Like\" />", "e": 1025, "s": 695, "text": null }, { "code": null, "e": 1083, "s": 1029, "text": "Below is the updated code for the row_posts.xml file." }, { "code": null, "e": 1089, "s": 1085, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.cardview.widget.CardView xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:orientation=\"vertical\" app:cardBackgroundColor=\"@color/colorWhite\" app:cardCornerRadius=\"3dp\" app:cardElevation=\"3dp\" app:cardUseCompatPadding=\"true\" app:contentPadding=\"5dp\"> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:orientation=\"vertical\"> <LinearLayout android:id=\"@+id/profilelayout\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:gravity=\"center_vertical\" android:orientation=\"horizontal\"> <de.hdodenhof.circleimageview.CircleImageView android:id=\"@+id/picturetv\" android:layout_width=\"50dp\" android:layout_height=\"50dp\" android:scaleType=\"centerCrop\" android:src=\"@drawable/profile_image\" /> <LinearLayout android:layout_width=\"0dp\" android:layout_height=\"wrap_content\" android:layout_weight=\"1\" android:orientation=\"vertical\"> <TextView android:id=\"@+id/unametv\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"Name\" android:textColor=\"@color/colorBlack\" android:textSize=\"20sp\" /> <TextView android:id=\"@+id/utimetv\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"33 min\" /> </LinearLayout> <ImageButton android:id=\"@+id/morebtn\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:background=\"@null\" android:src=\"@drawable/ic_more\" /> </LinearLayout> <TextView android:id=\"@+id/ptitletv\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:text=\"Title\" android:textSize=\"16sp\" android:textStyle=\"bold\" /> <TextView android:id=\"@+id/descript\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:text=\"Description\" android:textColor=\"@color/colorBlack\" /> <ImageView android:id=\"@+id/pimagetv\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:background=\"@color/colorWhite\" /> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:orientation=\"horizontal\"> <TextView android:id=\"@+id/plikeb\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_weight=\"1\" android:text=\"1.2K Likes\" android:textColor=\"@color/colorPrimary\" /> <TextView android:id=\"@+id/pcommentco\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_weight=\"1\" android:text=\"1.2K Comment\" android:textAlignment=\"textEnd\" android:textColor=\"@color/colorPrimary\" /> </LinearLayout> <View android:layout_width=\"match_parent\" android:layout_height=\"1dp\" android:background=\"#F5F0F0\" /> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:gravity=\"center\" android:orientation=\"horizontal\"> <Button android:id=\"@+id/like\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_weight=\"1\" android:autoLink=\"all\" android:background=\"@color/colorWhite\" android:drawableStart=\"@drawable/ic_like\" android:drawableLeft=\"@drawable/ic_like\" android:padding=\"5dp\" android:text=\"Like\" /> <Button android:id=\"@+id/comment\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_weight=\"1\" android:autoLink=\"all\" android:background=\"@color/colorWhite\" android:drawableStart=\"@drawable/ic_comment\" android:drawableLeft=\"@drawable/ic_comment\" android:padding=\"5dp\" android:text=\"COMMENT\" /> </LinearLayout> </LinearLayout> </androidx.cardview.widget.CardView>", "e": 6276, "s": 1089, "text": null }, { "code": null, "e": 6328, "s": 6280, "text": "Step 2: Working with the AdapterPosts.java file" }, { "code": null, "e": 6454, "s": 6330, "text": "Go to the AdapterPosts.java file and refer to the following code. Below is the updated code for the AdapterPosts.java file." }, { "code": null, "e": 6461, "s": 6456, "text": "Java" }, { "code": "package com.example.socialmediaapp; import android.app.ProgressDialog;import android.content.Context;import android.content.Intent;import android.text.format.DateFormat;import android.view.Gravity;import android.view.LayoutInflater;import android.view.Menu;import android.view.MenuItem;import android.view.View;import android.view.ViewGroup;import android.widget.Button;import android.widget.ImageButton;import android.widget.ImageView;import android.widget.LinearLayout;import android.widget.PopupMenu;import android.widget.TextView;import android.widget.Toast; import androidx.annotation.NonNull;import androidx.recyclerview.widget.RecyclerView; import com.bumptech.glide.Glide;import com.google.android.gms.tasks.OnFailureListener;import com.google.android.gms.tasks.OnSuccessListener;import com.google.firebase.auth.FirebaseAuth;import com.google.firebase.database.DataSnapshot;import com.google.firebase.database.DatabaseError;import com.google.firebase.database.DatabaseReference;import com.google.firebase.database.FirebaseDatabase;import com.google.firebase.database.Query;import com.google.firebase.database.ValueEventListener;import com.google.firebase.storage.FirebaseStorage;import com.google.firebase.storage.StorageReference; import java.util.Calendar;import java.util.List;import java.util.Locale; public class AdapterPosts extends RecyclerView.Adapter<com.example.socialmediaapp.AdapterPosts.MyHolder> { Context context; String myuid; private DatabaseReference liekeref, postref; boolean mprocesslike = false; public AdapterPosts(Context context, List<ModelPost> modelPosts) { this.context = context; this.modelPosts = modelPosts; myuid = FirebaseAuth.getInstance().getCurrentUser().getUid(); liekeref = FirebaseDatabase.getInstance().getReference().child(\"Likes\"); postref = FirebaseDatabase.getInstance().getReference().child(\"Posts\"); } List<ModelPost> modelPosts; @NonNull @Override public MyHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(context).inflate(R.layout.row_posts, parent, false); return new MyHolder(view); } @Override public void onBindViewHolder(@NonNull final MyHolder holder, final int position) { final String uid = modelPosts.get(position).getUid(); String nameh = modelPosts.get(position).getUname(); final String titlee = modelPosts.get(position).getTitle(); final String descri = modelPosts.get(position).getDescription(); final String ptime = modelPosts.get(position).getPtime(); String dp = modelPosts.get(position).getUdp(); String plike = modelPosts.get(position).getPlike(); final String image = modelPosts.get(position).getUimage(); String email = modelPosts.get(position).getUemail(); String comm = modelPosts.get(position).getPcomments(); final String pid = modelPosts.get(position).getPtime(); Calendar calendar = Calendar.getInstance(Locale.ENGLISH); calendar.setTimeInMillis(Long.parseLong(ptime)); String timedate = DateFormat.format(\"dd/MM/yyyy hh:mm aa\", calendar).toString(); holder.name.setText(nameh); holder.title.setText(titlee); holder.description.setText(descri); holder.time.setText(timedate); holder.like.setText(plike + \" Likes\"); holder.comments.setText(comm + \" Comments\"); setLikes(holder, ptime); try { Glide.with(context).load(dp).into(holder.picture); } catch (Exception e) { } holder.image.setVisibility(View.VISIBLE); try { Glide.with(context).load(image).into(holder.image); } catch (Exception e) { } holder.like.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(holder.itemView.getContext(), PostLikedByActivity.class); intent.putExtra(\"pid\", pid); holder.itemView.getContext().startActivity(intent); } }); holder.likebtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { final int plike = Integer.parseInt(modelPosts.get(position).getPlike()); mprocesslike = true; final String postid = modelPosts.get(position).getPtime(); liekeref.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { if (mprocesslike) { if (dataSnapshot.child(postid).hasChild(myuid)) { postref.child(postid).child(\"plike\").setValue(\"\" + (plike - 1)); liekeref.child(postid).child(myuid).removeValue(); mprocesslike = false; } else { postref.child(postid).child(\"plike\").setValue(\"\" + (plike + 1)); liekeref.child(postid).child(myuid).setValue(\"Liked\"); mprocesslike = false; } } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); } }); holder.more.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showMoreOptions(holder.more, uid, myuid, ptime, image); } }); holder.comment.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(context, PostDetailsActivity.class); intent.putExtra(\"pid\", ptime); context.startActivity(intent); } }); } private void showMoreOptions(ImageButton more, String uid, String myuid, final String pid, final String image) { PopupMenu popupMenu = new PopupMenu(context, more, Gravity.END); if (uid.equals(myuid)) { popupMenu.getMenu().add(Menu.NONE, 0, 0, \"DELETE\"); } popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { if (item.getItemId() == 0) { deltewithImage(pid, image); } return false; } }); popupMenu.show(); } private void deltewithImage(final String pid, String image) { final ProgressDialog pd = new ProgressDialog(context); pd.setMessage(\"Deleting\"); StorageReference picref = FirebaseStorage.getInstance().getReferenceFromUrl(image); picref.delete().addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { Query query = FirebaseDatabase.getInstance().getReference(\"Posts\").orderByChild(\"ptime\").equalTo(pid); query.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) { dataSnapshot1.getRef().removeValue(); } pd.dismiss(); Toast.makeText(context, \"Deleted Successfully\", Toast.LENGTH_LONG).show(); } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { } }); } private void setLikes(final MyHolder holder, final String pid) { liekeref.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { if (dataSnapshot.child(pid).hasChild(myuid)) { holder.likebtn.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_liked, 0, 0, 0); holder.likebtn.setText(\"Liked\"); } else { holder.likebtn.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_like, 0, 0, 0); holder.likebtn.setText(\"Like\"); } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); } @Override public int getItemCount() { return modelPosts.size(); } class MyHolder extends RecyclerView.ViewHolder { ImageView picture, image; TextView name, time, title, description, like, comments; ImageButton more; Button likebtn, comment; LinearLayout profile; public MyHolder(@NonNull View itemView) { super(itemView); picture = itemView.findViewById(R.id.picturetv); image = itemView.findViewById(R.id.pimagetv); name = itemView.findViewById(R.id.unametv); time = itemView.findViewById(R.id.utimetv); more = itemView.findViewById(R.id.morebtn); title = itemView.findViewById(R.id.ptitletv); description = itemView.findViewById(R.id.descript); like = itemView.findViewById(R.id.plikeb); comments = itemView.findViewById(R.id.pcommentco); likebtn = itemView.findViewById(R.id.like); comment = itemView.findViewById(R.id.comment); profile = itemView.findViewById(R.id.profilelayout); } }}", "e": 16428, "s": 6461, "text": null }, { "code": null, "e": 16440, "s": 16432, "text": "Output:" }, { "code": null, "e": 16603, "s": 16444, "text": "For all the drawable file used in this article please refer to this link: https://drive.google.com/drive/folders/1M_knOH_ugCuwSP5nkYzeD4dRp-Honzbe?usp=sharing" }, { "code": null, "e": 16668, "s": 16605, "text": "Below is the file structure after performing these operations:" }, { "code": null, "e": 16682, "s": 16672, "text": "ruhelaa48" }, { "code": null, "e": 16691, "s": 16682, "text": "Firebase" }, { "code": null, "e": 16699, "s": 16691, "text": "Android" }, { "code": null, "e": 16704, "s": 16699, "text": "Java" }, { "code": null, "e": 16709, "s": 16704, "text": "Java" }, { "code": null, "e": 16717, "s": 16709, "text": "Android" } ]
Implementing Multidimensional Map in C++
30 Apr, 2020 Multidimensional maps are used when we want to map a value to a combination of keys. The key can be of any data type, including those that are user-defined. Multidimensional maps are nested maps; that is, they map a key to another map, which itself stores combinations of key values with corresponding mapped values. Syntax: // Creating a two-dimensional map: map< key_1_type, map< key_2_type, value_type> > object; // Creating an N-dimensional map: map< key_1_type, map< key_2_type, ... map< key_N_type, value_type> > > object; Example 1: // C++14 code to implement two-dimensional map #include <bits/stdc++.h>using namespace std; int main(){ // Two-dimensional key map<int, map<int, int> > m; // For accessing outer map map<int, map<int, int> >::iterator itr; // For accessing inner map map<int, int>::iterator ptr; for (int i = 0; i < 2; i++) { for (int j = 0; j < 2; j++) { m[i][j] = i + j; } } for (int i = 0; i < 2; i++) { for (int j = 0; j < 2; j++) { // Accessing through array subscript cout << "First key is " << i << " And second key is " << j << " And value is " << m[i][j] << endl; } } cout << "\nNow accessing map though iterator \n\n"; for (itr = m.begin(); itr != m.end(); itr++) { for (ptr = itr->second.begin(); ptr != itr->second.end(); ptr++) { cout << "First key is " << itr->first << " And second key is " << ptr->first << " And value is " << ptr->second << endl; } }} First key is 0 And second key is 0 And value is 0 First key is 0 And second key is 1 And value is 1 First key is 1 And second key is 0 And value is 1 First key is 1 And second key is 1 And value is 2 Now accessing map though iterator First key is 0 And second key is 0 And value is 0 First key is 0 And second key is 1 And value is 1 First key is 1 And second key is 0 And value is 1 First key is 1 And second key is 1 And value is 2 Example 2: // C++14 code to implement two-dimensional map// and inserting value through insert() #include <bits/stdc++.h>using namespace std; int main(){ // First key type is a string map<string, map<int, int> > m; map<string, map<int, int> >::iterator itr; map<int, int>::iterator ptr; m.insert(make_pair("Noob", map<int, int>())); m["Noob"].insert(make_pair(0, 5)); m.insert(make_pair("Geek", map<int, int>())); m["Geek"].insert(make_pair(1, 10)); m.insert(make_pair("Geek", map<int, int>())); m["Geek"].insert(make_pair(2, 20)); for (itr = m.begin(); itr != m.end(); itr++) { for (ptr = itr->second.begin(); ptr != itr->second.end(); ptr++) { cout << "First key is " << itr->first << " And second key is " << ptr->first << " And value is " << ptr->second << endl; } }} First key is Geek And second key is 1 And value is 10 First key is Geek And second key is 2 And value is 20 First key is Noob And second key is 0 And value is 5 jacksonthall22 cpp-map-functions C++ Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. return 0 vs return 1 in C++ cout in C++ Passing a function as a parameter in C++ Const keyword in C++ C++ Keywords Program to count Number of connected components in an undirected graph Program to implement Singly Linked List in C++ using class How to sort an Array in descending order using STL in C++? Setting up Sublime Text for C++ Competitive Programming Environment Why it is important to write "using namespace std" in C++ program?
[ { "code": null, "e": 54, "s": 26, "text": "\n30 Apr, 2020" }, { "code": null, "e": 371, "s": 54, "text": "Multidimensional maps are used when we want to map a value to a combination of keys. The key can be of any data type, including those that are user-defined. Multidimensional maps are nested maps; that is, they map a key to another map, which itself stores combinations of key values with corresponding mapped values." }, { "code": null, "e": 379, "s": 371, "text": "Syntax:" }, { "code": null, "e": 585, "s": 379, "text": "// Creating a two-dimensional map:\nmap< key_1_type, map< key_2_type, value_type> > object;\n\n// Creating an N-dimensional map:\nmap< key_1_type, map< key_2_type, ... map< key_N_type, value_type> > > object;\n" }, { "code": null, "e": 596, "s": 585, "text": "Example 1:" }, { "code": "// C++14 code to implement two-dimensional map #include <bits/stdc++.h>using namespace std; int main(){ // Two-dimensional key map<int, map<int, int> > m; // For accessing outer map map<int, map<int, int> >::iterator itr; // For accessing inner map map<int, int>::iterator ptr; for (int i = 0; i < 2; i++) { for (int j = 0; j < 2; j++) { m[i][j] = i + j; } } for (int i = 0; i < 2; i++) { for (int j = 0; j < 2; j++) { // Accessing through array subscript cout << \"First key is \" << i << \" And second key is \" << j << \" And value is \" << m[i][j] << endl; } } cout << \"\\nNow accessing map though iterator \\n\\n\"; for (itr = m.begin(); itr != m.end(); itr++) { for (ptr = itr->second.begin(); ptr != itr->second.end(); ptr++) { cout << \"First key is \" << itr->first << \" And second key is \" << ptr->first << \" And value is \" << ptr->second << endl; } }}", "e": 1656, "s": 596, "text": null }, { "code": null, "e": 2094, "s": 1656, "text": "First key is 0 And second key is 0 And value is 0\nFirst key is 0 And second key is 1 And value is 1\nFirst key is 1 And second key is 0 And value is 1\nFirst key is 1 And second key is 1 And value is 2\n\nNow accessing map though iterator \n\nFirst key is 0 And second key is 0 And value is 0\nFirst key is 0 And second key is 1 And value is 1\nFirst key is 1 And second key is 0 And value is 1\nFirst key is 1 And second key is 1 And value is 2\n" }, { "code": null, "e": 2105, "s": 2094, "text": "Example 2:" }, { "code": "// C++14 code to implement two-dimensional map// and inserting value through insert() #include <bits/stdc++.h>using namespace std; int main(){ // First key type is a string map<string, map<int, int> > m; map<string, map<int, int> >::iterator itr; map<int, int>::iterator ptr; m.insert(make_pair(\"Noob\", map<int, int>())); m[\"Noob\"].insert(make_pair(0, 5)); m.insert(make_pair(\"Geek\", map<int, int>())); m[\"Geek\"].insert(make_pair(1, 10)); m.insert(make_pair(\"Geek\", map<int, int>())); m[\"Geek\"].insert(make_pair(2, 20)); for (itr = m.begin(); itr != m.end(); itr++) { for (ptr = itr->second.begin(); ptr != itr->second.end(); ptr++) { cout << \"First key is \" << itr->first << \" And second key is \" << ptr->first << \" And value is \" << ptr->second << endl; } }}", "e": 2975, "s": 2105, "text": null }, { "code": null, "e": 3137, "s": 2975, "text": "First key is Geek And second key is 1 And value is 10\nFirst key is Geek And second key is 2 And value is 20\nFirst key is Noob And second key is 0 And value is 5\n" }, { "code": null, "e": 3152, "s": 3137, "text": "jacksonthall22" }, { "code": null, "e": 3170, "s": 3152, "text": "cpp-map-functions" }, { "code": null, "e": 3183, "s": 3170, "text": "C++ Programs" }, { "code": null, "e": 3281, "s": 3183, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3309, "s": 3281, "text": "return 0 vs return 1 in C++" }, { "code": null, "e": 3321, "s": 3309, "text": "cout in C++" }, { "code": null, "e": 3362, "s": 3321, "text": "Passing a function as a parameter in C++" }, { "code": null, "e": 3383, "s": 3362, "text": "Const keyword in C++" }, { "code": null, "e": 3396, "s": 3383, "text": "C++ Keywords" }, { "code": null, "e": 3467, "s": 3396, "text": "Program to count Number of connected components in an undirected graph" }, { "code": null, "e": 3526, "s": 3467, "text": "Program to implement Singly Linked List in C++ using class" }, { "code": null, "e": 3585, "s": 3526, "text": "How to sort an Array in descending order using STL in C++?" }, { "code": null, "e": 3653, "s": 3585, "text": "Setting up Sublime Text for C++ Competitive Programming Environment" } ]
Jobs, Waiting, Cancellation in Kotlin Coroutines
19 May, 2022 Prerequisite: Kotlin Coroutines On Android Dispatchers in Kotlin Coroutines Suspend Function In Kotlin Coroutines In this article, the following topics will be discussed like what are the jobs in a coroutine, how to wait for the coroutine, and how to cancel the coroutine. Whenever a new coroutine is launched, it will return a job. The job which is returned can be used in many places like it can be used to wait for the coroutine to do some work or it can be used to cancel the coroutine. The job can be used to call many functionalities like the join() method which is used to wait for the coroutine and the cancel() method which is used to cancel the execution of the coroutine. According to the official documentation, the definition of a job is given as follows: A Job is a cancellable thing with a life-cycle that culminates in its completion.Coroutine job is created with launch coroutine builder. It runs a specified block of code and completes on completion of this block. As it is discussed that a job will be returned when a new coroutine will be launched, so now let’s see programmatically how the job is returned and how the job can be used. Kotlin // sample kotlin program in kotlinimport androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport kotlinx.coroutines.Dispatchersimport kotlinx.coroutines.GlobalScopeimport kotlinx.coroutines.launch class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // A job is returned val job = GlobalScope.launch(Dispatchers.Default) { } }} Coroutines can be controlled through the functions that are available on the Job interface. Some functions out of many that job interface offers are as follows: start() join() cancel() join() function is a suspending function, i.e it can be called from a coroutine or from within another suspending function. Job blocks all the threads until the coroutine in which it is written or have context finished its work. Only when the coroutine gets finishes, lines after the join() function will be executed. Let’s take an example that demonstrates the working of the join() function. Kotlin // sample kotlin program for demonstrating job.join methodimport androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.util.Logimport kotlinx.coroutines.* class MainActivity : AppCompatActivity() { val TAG:String = "Main Activity" override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // creating/launching a coroutine will return the job val job = GlobalScope.launch(Dispatchers.Default) { repeat(5) { Log.d(TAG, "Coroutines is still working") // delay the coroutine by 1sec delay(1000) } } runBlocking { // waiting for the coroutine to finish it's work job.join() Log.d(TAG, "Main Thread is Running") } }} The Log Output is as follows: Time Stamps are shown by Oval Circle It can be seen that the Log Statement is not allowed to execute until that coroutine which is running finishes its work and it happens possibly only due to the join() method. cancel() method is used to cancel the coroutine, without waiting for it to finish its work. It can be said that it is just opposite to that of the join method, in the sense that join() method waits for the coroutine to finish its whole work and block all other threads, whereas the cancel() method when encountered, kills the coroutine ie stops the coroutine. Let’s take an example that demonstrates the working of the cancel() function. Kotlin // sample kotlin programimport androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.util.Logimport kotlinx.coroutines.* class MainActivity : AppCompatActivity() { val TAG:String = "Main Activity" override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val job = GlobalScope.launch(Dispatchers.Default) { repeat(5) { Log.d(TAG, "Coroutines is still working") delay(1000) } } runBlocking { // delaying the coroutine by 2sec delay(2000) // canceling/stopping the coroutine job.cancel() Log.d(TAG, "Main Thread is Running") } }} The Log Output is as follows: Time Stamps are shown by Oval Circle Canceling a coroutine is not always easier as it is in the above example. One should remember that when someone is using the cancel() method, coroutine should be aware that the cancel method would be encountered, ie it might happen that the cancel method would have encountered and coroutine is still running. In short, there needs to be enough time to tell the coroutine that it has been canceled. The delay() function within the repeat function insure that the coroutine has enough time to prepare Let’s take an example and try to understand these paragraph: Kotlin // sample kotlin programimport androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.util.Logimport kotlinx.coroutines.* class MainActivity : AppCompatActivity() { val TAG:String = "Main Activity" override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val job = GlobalScope.launch(Dispatchers.Default) { Log.d(TAG,"Starting the long calculation...") // running the loop from 30 to 40 for(i in 30..40) { Log.d(TAG, "Result for i =$i : ${fib(i)}") } Log.d(TAG, "Ending the long calculation...") } runBlocking { delay(2000) job.cancel() Log.d(TAG, "Main Thread is Running") } } // fibonacci function fun fib(n:Int):Long { return if(n==0) 0 else if(n==1) 1 else fib(n-1) + fib(n-2) }} The Log Output is as follows: Time Stamps are shown by Oval Circle It can be seen that even after the cancel() method has been encountered, our coroutine will continue to calculate the result of the Fibonacci of the numbers. It is so because our coroutine was so busy in doing the calculation that it does not get time to cancel itself. Suspending there has no suspended function(like delay()), we don’t have enough time to tell the coroutine that it has been canceled. So we have to check manually that if the coroutine has been canceled or not. This can be done using isActive to check whether the coroutine is active or not. Kotlin // sample kotlin programimport androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.util.Logimport kotlinx.coroutines.* class MainActivity : AppCompatActivity() { val TAG:String = "Main Activity" override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val job = GlobalScope.launch(Dispatchers.Default) { Log.d(TAG, "Starting the long calculation...") for(i in 30..40) { // using isActive functionality to check whether the // coroutine is active or not if(isActive) Log.d(TAG, "Result for i =$i : ${fib(i)}") } Log.d(TAG, "Ending the long calculation...") } runBlocking { delay(2000) job.cancel() Log.d(TAG, "Main Thread is Running") } } fun fib(n:Int):Long { return if(n==0) 0 else if(n==1) 1 else fib(n-1) + fib(n-2) }} The Log Output is as follows: Time Stamps are shown by Oval Circle It can be seen that using isActive has increased the awareness of coroutine towards its cancellation and it performs very less calculation after being canceled, as compared to that when isActive has not been used. Kotlin coroutine has come up with a good solution to the above problems i.e, the coroutine will automatically be canceled and don’t do any further calculations when a certain time has elapsed and withTimeOut() helps in doing so. There is no need to cancel the coroutine manually by using runBlocking() function. Let’s see how withTimeOut() function works: Kotlin // sample kotlin programimport androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.util.Logimport kotlinx.coroutines.* class MainActivity : AppCompatActivity() { val TAG:String = "Main Activity" override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val job = GlobalScope.launch(Dispatchers.Default) { Log.d(TAG, "Starting the long calculation...") // using withTimeOut function // which runs the coroutine for 3sec withTimeout(3000L) { for(i in 30..40) { if(isActive) Log.d(TAG, "Result for i =$i : ${fib(i)}") } } Log.d(TAG, "Ending the long calculation...") } } fun fib(n:Int):Long { return if(n==0) 0 else if(n==1) 1 else fib(n-1) + fib(n-2) }} The Log Output is as follows: Time Stamps are shown by Oval Circle sweetyty abhishek0719kadiyan simmytarika5 android Android Kotlin Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Add Views Dynamically and Store Data in Arraylist in Android? Android SDK and it's Components Flutter - Custom Bottom Navigation Bar How to Communicate Between Fragments in Android? Retrofit with Kotlin Coroutine in Android How to Add Views Dynamically and Store Data in Arraylist in Android? Android UI Layouts Kotlin Array How to Communicate Between Fragments in Android? Retrofit with Kotlin Coroutine in Android
[ { "code": null, "e": 28, "s": 0, "text": "\n19 May, 2022" }, { "code": null, "e": 42, "s": 28, "text": "Prerequisite:" }, { "code": null, "e": 71, "s": 42, "text": "Kotlin Coroutines On Android" }, { "code": null, "e": 104, "s": 71, "text": "Dispatchers in Kotlin Coroutines" }, { "code": null, "e": 142, "s": 104, "text": "Suspend Function In Kotlin Coroutines" }, { "code": null, "e": 712, "s": 142, "text": "In this article, the following topics will be discussed like what are the jobs in a coroutine, how to wait for the coroutine, and how to cancel the coroutine. Whenever a new coroutine is launched, it will return a job. The job which is returned can be used in many places like it can be used to wait for the coroutine to do some work or it can be used to cancel the coroutine. The job can be used to call many functionalities like the join() method which is used to wait for the coroutine and the cancel() method which is used to cancel the execution of the coroutine. " }, { "code": null, "e": 798, "s": 712, "text": "According to the official documentation, the definition of a job is given as follows:" }, { "code": null, "e": 1012, "s": 798, "text": "A Job is a cancellable thing with a life-cycle that culminates in its completion.Coroutine job is created with launch coroutine builder. It runs a specified block of code and completes on completion of this block." }, { "code": null, "e": 1185, "s": 1012, "text": "As it is discussed that a job will be returned when a new coroutine will be launched, so now let’s see programmatically how the job is returned and how the job can be used." }, { "code": null, "e": 1192, "s": 1185, "text": "Kotlin" }, { "code": "// sample kotlin program in kotlinimport androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport kotlinx.coroutines.Dispatchersimport kotlinx.coroutines.GlobalScopeimport kotlinx.coroutines.launch class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // A job is returned val job = GlobalScope.launch(Dispatchers.Default) { } }}", "e": 1703, "s": 1192, "text": null }, { "code": null, "e": 1869, "s": 1708, "text": "Coroutines can be controlled through the functions that are available on the Job interface. Some functions out of many that job interface offers are as follows:" }, { "code": null, "e": 1879, "s": 1871, "text": "start()" }, { "code": null, "e": 1886, "s": 1879, "text": "join()" }, { "code": null, "e": 1895, "s": 1886, "text": "cancel()" }, { "code": null, "e": 2291, "s": 1897, "text": "join() function is a suspending function, i.e it can be called from a coroutine or from within another suspending function. Job blocks all the threads until the coroutine in which it is written or have context finished its work. Only when the coroutine gets finishes, lines after the join() function will be executed. Let’s take an example that demonstrates the working of the join() function." }, { "code": null, "e": 2300, "s": 2293, "text": "Kotlin" }, { "code": "// sample kotlin program for demonstrating job.join methodimport androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.util.Logimport kotlinx.coroutines.* class MainActivity : AppCompatActivity() { val TAG:String = \"Main Activity\" override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // creating/launching a coroutine will return the job val job = GlobalScope.launch(Dispatchers.Default) { repeat(5) { Log.d(TAG, \"Coroutines is still working\") // delay the coroutine by 1sec delay(1000) } } runBlocking { // waiting for the coroutine to finish it's work job.join() Log.d(TAG, \"Main Thread is Running\") } }}", "e": 3193, "s": 2300, "text": null }, { "code": null, "e": 3226, "s": 3196, "text": "The Log Output is as follows:" }, { "code": null, "e": 3265, "s": 3228, "text": "Time Stamps are shown by Oval Circle" }, { "code": null, "e": 3444, "s": 3269, "text": "It can be seen that the Log Statement is not allowed to execute until that coroutine which is running finishes its work and it happens possibly only due to the join() method." }, { "code": null, "e": 3886, "s": 3448, "text": "cancel() method is used to cancel the coroutine, without waiting for it to finish its work. It can be said that it is just opposite to that of the join method, in the sense that join() method waits for the coroutine to finish its whole work and block all other threads, whereas the cancel() method when encountered, kills the coroutine ie stops the coroutine. Let’s take an example that demonstrates the working of the cancel() function." }, { "code": null, "e": 3895, "s": 3888, "text": "Kotlin" }, { "code": "// sample kotlin programimport androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.util.Logimport kotlinx.coroutines.* class MainActivity : AppCompatActivity() { val TAG:String = \"Main Activity\" override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val job = GlobalScope.launch(Dispatchers.Default) { repeat(5) { Log.d(TAG, \"Coroutines is still working\") delay(1000) } } runBlocking { // delaying the coroutine by 2sec delay(2000) // canceling/stopping the coroutine job.cancel() Log.d(TAG, \"Main Thread is Running\") } }}", "e": 4710, "s": 3895, "text": null }, { "code": null, "e": 4743, "s": 4713, "text": "The Log Output is as follows:" }, { "code": null, "e": 4782, "s": 4745, "text": "Time Stamps are shown by Oval Circle" }, { "code": null, "e": 5347, "s": 4786, "text": "Canceling a coroutine is not always easier as it is in the above example. One should remember that when someone is using the cancel() method, coroutine should be aware that the cancel method would be encountered, ie it might happen that the cancel method would have encountered and coroutine is still running. In short, there needs to be enough time to tell the coroutine that it has been canceled. The delay() function within the repeat function insure that the coroutine has enough time to prepare Let’s take an example and try to understand these paragraph:" }, { "code": null, "e": 5356, "s": 5349, "text": "Kotlin" }, { "code": "// sample kotlin programimport androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.util.Logimport kotlinx.coroutines.* class MainActivity : AppCompatActivity() { val TAG:String = \"Main Activity\" override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val job = GlobalScope.launch(Dispatchers.Default) { Log.d(TAG,\"Starting the long calculation...\") // running the loop from 30 to 40 for(i in 30..40) { Log.d(TAG, \"Result for i =$i : ${fib(i)}\") } Log.d(TAG, \"Ending the long calculation...\") } runBlocking { delay(2000) job.cancel() Log.d(TAG, \"Main Thread is Running\") } } // fibonacci function fun fib(n:Int):Long { return if(n==0) 0 else if(n==1) 1 else fib(n-1) + fib(n-2) }}", "e": 6358, "s": 5356, "text": null }, { "code": null, "e": 6391, "s": 6361, "text": "The Log Output is as follows:" }, { "code": null, "e": 6430, "s": 6393, "text": "Time Stamps are shown by Oval Circle" }, { "code": null, "e": 6996, "s": 6434, "text": "It can be seen that even after the cancel() method has been encountered, our coroutine will continue to calculate the result of the Fibonacci of the numbers. It is so because our coroutine was so busy in doing the calculation that it does not get time to cancel itself. Suspending there has no suspended function(like delay()), we don’t have enough time to tell the coroutine that it has been canceled. So we have to check manually that if the coroutine has been canceled or not. This can be done using isActive to check whether the coroutine is active or not. " }, { "code": null, "e": 7005, "s": 6998, "text": "Kotlin" }, { "code": "// sample kotlin programimport androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.util.Logimport kotlinx.coroutines.* class MainActivity : AppCompatActivity() { val TAG:String = \"Main Activity\" override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val job = GlobalScope.launch(Dispatchers.Default) { Log.d(TAG, \"Starting the long calculation...\") for(i in 30..40) { // using isActive functionality to check whether the // coroutine is active or not if(isActive) Log.d(TAG, \"Result for i =$i : ${fib(i)}\") } Log.d(TAG, \"Ending the long calculation...\") } runBlocking { delay(2000) job.cancel() Log.d(TAG, \"Main Thread is Running\") } } fun fib(n:Int):Long { return if(n==0) 0 else if(n==1) 1 else fib(n-1) + fib(n-2) }}", "e": 8066, "s": 7005, "text": null }, { "code": null, "e": 8099, "s": 8069, "text": "The Log Output is as follows:" }, { "code": null, "e": 8138, "s": 8101, "text": "Time Stamps are shown by Oval Circle" }, { "code": null, "e": 8356, "s": 8142, "text": "It can be seen that using isActive has increased the awareness of coroutine towards its cancellation and it performs very less calculation after being canceled, as compared to that when isActive has not been used." }, { "code": null, "e": 8716, "s": 8360, "text": "Kotlin coroutine has come up with a good solution to the above problems i.e, the coroutine will automatically be canceled and don’t do any further calculations when a certain time has elapsed and withTimeOut() helps in doing so. There is no need to cancel the coroutine manually by using runBlocking() function. Let’s see how withTimeOut() function works:" }, { "code": null, "e": 8725, "s": 8718, "text": "Kotlin" }, { "code": "// sample kotlin programimport androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.util.Logimport kotlinx.coroutines.* class MainActivity : AppCompatActivity() { val TAG:String = \"Main Activity\" override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val job = GlobalScope.launch(Dispatchers.Default) { Log.d(TAG, \"Starting the long calculation...\") // using withTimeOut function // which runs the coroutine for 3sec withTimeout(3000L) { for(i in 30..40) { if(isActive) Log.d(TAG, \"Result for i =$i : ${fib(i)}\") } } Log.d(TAG, \"Ending the long calculation...\") } } fun fib(n:Int):Long { return if(n==0) 0 else if(n==1) 1 else fib(n-1) + fib(n-2) }}", "e": 9726, "s": 8725, "text": null }, { "code": null, "e": 9759, "s": 9729, "text": "The Log Output is as follows:" }, { "code": null, "e": 9798, "s": 9761, "text": "Time Stamps are shown by Oval Circle" }, { "code": null, "e": 9811, "s": 9802, "text": "sweetyty" }, { "code": null, "e": 9831, "s": 9811, "text": "abhishek0719kadiyan" }, { "code": null, "e": 9844, "s": 9831, "text": "simmytarika5" }, { "code": null, "e": 9852, "s": 9844, "text": "android" }, { "code": null, "e": 9860, "s": 9852, "text": "Android" }, { "code": null, "e": 9867, "s": 9860, "text": "Kotlin" }, { "code": null, "e": 9875, "s": 9867, "text": "Android" }, { "code": null, "e": 9973, "s": 9875, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 10042, "s": 9973, "text": "How to Add Views Dynamically and Store Data in Arraylist in Android?" }, { "code": null, "e": 10074, "s": 10042, "text": "Android SDK and it's Components" }, { "code": null, "e": 10113, "s": 10074, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 10162, "s": 10113, "text": "How to Communicate Between Fragments in Android?" }, { "code": null, "e": 10204, "s": 10162, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 10273, "s": 10204, "text": "How to Add Views Dynamically and Store Data in Arraylist in Android?" }, { "code": null, "e": 10292, "s": 10273, "text": "Android UI Layouts" }, { "code": null, "e": 10305, "s": 10292, "text": "Kotlin Array" }, { "code": null, "e": 10354, "s": 10305, "text": "How to Communicate Between Fragments in Android?" } ]
How to detect the user browser ( Safari, Chrome, IE, Firefox and Opera ) using JavaScript ?
29 Jun, 2022 The browser on which the current page is opening can be checked using JavaScript. The userAgent property of the navigator object is used to return the user-agent header string sent by the browser. This user-agent string contains information about the browser by including certain keywords that may be tested for their presence. The presence of a specific user-string can be detected using the indexOf() method. The indexOf() method is used to return the first occurrence of the specified string value in a string. If the value does not come up in the string, “-1” is returned. The user-agent string of the browser is accessed using the navigator.userAgent property and then stored in a variable. The presence of the strings of a browser in this user-agent string is detected one by one. Detecting the Chrome browser: The user-agent of the Chrome browser is “Chrome”. This value is passed to indexOf() method to detect this value in the user-agent string.As the indexOf() method would return a value that is greater than “-1” to denote a successful search, the “greater-than” operator is used to return a boolean value on whether the search was successful or not. This is done for all the following tests.// Detect Chromelet chromeAgent = userAgentString.indexOf("Chrome") > -1; As the indexOf() method would return a value that is greater than “-1” to denote a successful search, the “greater-than” operator is used to return a boolean value on whether the search was successful or not. This is done for all the following tests. // Detect Chromelet chromeAgent = userAgentString.indexOf("Chrome") > -1; Detecting the Internet Explorer browser: The user-agent of the Internet Explorer browser is “MSIE” or “rv:”. Both these values are passed to the indexOf() method to detect this value in the user-agent string and the result of both them are used with the OR operator.// Detect Internet Explorerlet IExplorerAgent = userAgentString.indexOf("MSIE") > -1 || userAgentString.indexOf("rv:") > -1; // Detect Internet Explorerlet IExplorerAgent = userAgentString.indexOf("MSIE") > -1 || userAgentString.indexOf("rv:") > -1; Detecting the Firefox browser: The user-agent of the Firefox browser is “Firefox”. This value is passed to indexOf() method to detect this value in the user-agent string.// Detect Firefoxlet firefoxAgent = userAgentString.indexOf("Firefox") > -1; // Detect Firefoxlet firefoxAgent = userAgentString.indexOf("Firefox") > -1; Detecting the Safari browser: The user-agent of the Safari browser is “Safari”. This value is passed to indexOf() method to detect this value in the user-agent string.One additional check is required in the case of the Safari browser as the user-agent of the Chrome browser also includes the Safari browser’s user-agent. If both the user-agents of Chrome and Safari are in the user-agent, it means that the browser is Chrome, and hence the Safari browser value is discarded.// Detect Safarilet safariAgent = userAgentString.indexOf("Safari") > -1; // Discard Safari since it also matches Chromeif ((chromeAgent) && (safariAgent)) safariAgent = false; One additional check is required in the case of the Safari browser as the user-agent of the Chrome browser also includes the Safari browser’s user-agent. If both the user-agents of Chrome and Safari are in the user-agent, it means that the browser is Chrome, and hence the Safari browser value is discarded. // Detect Safarilet safariAgent = userAgentString.indexOf("Safari") > -1; // Discard Safari since it also matches Chromeif ((chromeAgent) && (safariAgent)) safariAgent = false; Detecting the Opera browser: The user-agent of the Opera browser is “OP”. This value is passed to indexOf() method to detect this value in the user-agent string.One additional check is also required in the case of this browser as the user-agent of the Opera browser also includes the Chrome browser’s user-agent. If both the user-agents of Chrome and Opera are in the user-agent, it means that the browser is Opera, and hence the Chrome browser value is discarded.// Detect Operalet operaAgent = userAgentString.indexOf("OP") > -1; // Discard Chrome since it also matches Opera if ((chromeAgent) && (operaAgent)) chromeAgent = false; One additional check is also required in the case of this browser as the user-agent of the Opera browser also includes the Chrome browser’s user-agent. If both the user-agents of Chrome and Opera are in the user-agent, it means that the browser is Opera, and hence the Chrome browser value is discarded. // Detect Operalet operaAgent = userAgentString.indexOf("OP") > -1; // Discard Chrome since it also matches Opera if ((chromeAgent) && (operaAgent)) chromeAgent = false; Example: <!DOCTYPE html><html> <head> <title> How to detect Safari, Chrome, IE, Firefox and Opera browser using JavaScript? </title></head> <body> <h1 style="color: green">GeeksforGeeks</h1> <b> How to detect Safari, Chrome, IE, Firefox and Opera browser using JavaScript? </b> <p> Click on the button to detect the current browser </p> <p> Is Safari? <span class="output-safari"></span> </p> <p> Is Chrome? <span class="output-chrome"></span> </p> <p> Is Internet Explorer? <span class="output-ie"></span> </p> <p> Is Firefox? <span class="output-firefox"></span> </p> <p> Is Opera browser? <span class="output-opera"></span> </p> <button onclick="checkBrowser()"> Detect browser </button> <script> function checkBrowser() { // Get the user-agent string let userAgentString = navigator.userAgent; // Detect Chrome let chromeAgent = userAgentString.indexOf("Chrome") > -1; // Detect Internet Explorer let IExplorerAgent = userAgentString.indexOf("MSIE") > -1 || userAgentString.indexOf("rv:") > -1; // Detect Firefox let firefoxAgent = userAgentString.indexOf("Firefox") > -1; // Detect Safari let safariAgent = userAgentString.indexOf("Safari") > -1; // Discard Safari since it also matches Chrome if ((chromeAgent) && (safariAgent)) safariAgent = false; // Detect Opera let operaAgent = userAgentString.indexOf("OP") > -1; // Discard Chrome since it also matches Opera if ((chromeAgent) && (operaAgent)) chromeAgent = false; document.querySelector(".output-safari").textContent = safariAgent; document.querySelector(".output-chrome").textContent = chromeAgent; document.querySelector(".output-ie").textContent = IExplorerAgent; document.querySelector(".output-opera").textContent = operaAgent; document.querySelector(".output-firefox").textContent = firefoxAgent; } </script></body> </html> Output: Output on the Chrome browser: Output on the Firefox browser: Output on the Opera browser: JavaScript-Misc Picked JavaScript Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n29 Jun, 2022" }, { "code": null, "e": 110, "s": 28, "text": "The browser on which the current page is opening can be checked using JavaScript." }, { "code": null, "e": 356, "s": 110, "text": "The userAgent property of the navigator object is used to return the user-agent header string sent by the browser. This user-agent string contains information about the browser by including certain keywords that may be tested for their presence." }, { "code": null, "e": 605, "s": 356, "text": "The presence of a specific user-string can be detected using the indexOf() method. The indexOf() method is used to return the first occurrence of the specified string value in a string. If the value does not come up in the string, “-1” is returned." }, { "code": null, "e": 815, "s": 605, "text": "The user-agent string of the browser is accessed using the navigator.userAgent property and then stored in a variable. The presence of the strings of a browser in this user-agent string is detected one by one." }, { "code": null, "e": 1306, "s": 815, "text": "Detecting the Chrome browser: The user-agent of the Chrome browser is “Chrome”. This value is passed to indexOf() method to detect this value in the user-agent string.As the indexOf() method would return a value that is greater than “-1” to denote a successful search, the “greater-than” operator is used to return a boolean value on whether the search was successful or not. This is done for all the following tests.// Detect Chromelet chromeAgent = userAgentString.indexOf(\"Chrome\") > -1;" }, { "code": null, "e": 1557, "s": 1306, "text": "As the indexOf() method would return a value that is greater than “-1” to denote a successful search, the “greater-than” operator is used to return a boolean value on whether the search was successful or not. This is done for all the following tests." }, { "code": "// Detect Chromelet chromeAgent = userAgentString.indexOf(\"Chrome\") > -1;", "e": 1631, "s": 1557, "text": null }, { "code": null, "e": 2043, "s": 1631, "text": "Detecting the Internet Explorer browser: The user-agent of the Internet Explorer browser is “MSIE” or “rv:”. Both these values are passed to the indexOf() method to detect this value in the user-agent string and the result of both them are used with the OR operator.// Detect Internet Explorerlet IExplorerAgent = userAgentString.indexOf(\"MSIE\") > -1 || userAgentString.indexOf(\"rv:\") > -1;" }, { "code": "// Detect Internet Explorerlet IExplorerAgent = userAgentString.indexOf(\"MSIE\") > -1 || userAgentString.indexOf(\"rv:\") > -1;", "e": 2189, "s": 2043, "text": null }, { "code": null, "e": 2436, "s": 2189, "text": "Detecting the Firefox browser: The user-agent of the Firefox browser is “Firefox”. This value is passed to indexOf() method to detect this value in the user-agent string.// Detect Firefoxlet firefoxAgent = userAgentString.indexOf(\"Firefox\") > -1;" }, { "code": "// Detect Firefoxlet firefoxAgent = userAgentString.indexOf(\"Firefox\") > -1;", "e": 2513, "s": 2436, "text": null }, { "code": null, "e": 3165, "s": 2513, "text": "Detecting the Safari browser: The user-agent of the Safari browser is “Safari”. This value is passed to indexOf() method to detect this value in the user-agent string.One additional check is required in the case of the Safari browser as the user-agent of the Chrome browser also includes the Safari browser’s user-agent. If both the user-agents of Chrome and Safari are in the user-agent, it means that the browser is Chrome, and hence the Safari browser value is discarded.// Detect Safarilet safariAgent = userAgentString.indexOf(\"Safari\") > -1; // Discard Safari since it also matches Chromeif ((chromeAgent) && (safariAgent)) safariAgent = false;" }, { "code": null, "e": 3473, "s": 3165, "text": "One additional check is required in the case of the Safari browser as the user-agent of the Chrome browser also includes the Safari browser’s user-agent. If both the user-agents of Chrome and Safari are in the user-agent, it means that the browser is Chrome, and hence the Safari browser value is discarded." }, { "code": "// Detect Safarilet safariAgent = userAgentString.indexOf(\"Safari\") > -1; // Discard Safari since it also matches Chromeif ((chromeAgent) && (safariAgent)) safariAgent = false;", "e": 3651, "s": 3473, "text": null }, { "code": null, "e": 4293, "s": 3651, "text": "Detecting the Opera browser: The user-agent of the Opera browser is “OP”. This value is passed to indexOf() method to detect this value in the user-agent string.One additional check is also required in the case of this browser as the user-agent of the Opera browser also includes the Chrome browser’s user-agent. If both the user-agents of Chrome and Opera are in the user-agent, it means that the browser is Opera, and hence the Chrome browser value is discarded.// Detect Operalet operaAgent = userAgentString.indexOf(\"OP\") > -1; // Discard Chrome since it also matches Opera if ((chromeAgent) && (operaAgent)) chromeAgent = false;" }, { "code": null, "e": 4597, "s": 4293, "text": "One additional check is also required in the case of this browser as the user-agent of the Opera browser also includes the Chrome browser’s user-agent. If both the user-agents of Chrome and Opera are in the user-agent, it means that the browser is Opera, and hence the Chrome browser value is discarded." }, { "code": "// Detect Operalet operaAgent = userAgentString.indexOf(\"OP\") > -1; // Discard Chrome since it also matches Opera if ((chromeAgent) && (operaAgent)) chromeAgent = false;", "e": 4775, "s": 4597, "text": null }, { "code": null, "e": 4784, "s": 4775, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <title> How to detect Safari, Chrome, IE, Firefox and Opera browser using JavaScript? </title></head> <body> <h1 style=\"color: green\">GeeksforGeeks</h1> <b> How to detect Safari, Chrome, IE, Firefox and Opera browser using JavaScript? </b> <p> Click on the button to detect the current browser </p> <p> Is Safari? <span class=\"output-safari\"></span> </p> <p> Is Chrome? <span class=\"output-chrome\"></span> </p> <p> Is Internet Explorer? <span class=\"output-ie\"></span> </p> <p> Is Firefox? <span class=\"output-firefox\"></span> </p> <p> Is Opera browser? <span class=\"output-opera\"></span> </p> <button onclick=\"checkBrowser()\"> Detect browser </button> <script> function checkBrowser() { // Get the user-agent string let userAgentString = navigator.userAgent; // Detect Chrome let chromeAgent = userAgentString.indexOf(\"Chrome\") > -1; // Detect Internet Explorer let IExplorerAgent = userAgentString.indexOf(\"MSIE\") > -1 || userAgentString.indexOf(\"rv:\") > -1; // Detect Firefox let firefoxAgent = userAgentString.indexOf(\"Firefox\") > -1; // Detect Safari let safariAgent = userAgentString.indexOf(\"Safari\") > -1; // Discard Safari since it also matches Chrome if ((chromeAgent) && (safariAgent)) safariAgent = false; // Detect Opera let operaAgent = userAgentString.indexOf(\"OP\") > -1; // Discard Chrome since it also matches Opera if ((chromeAgent) && (operaAgent)) chromeAgent = false; document.querySelector(\".output-safari\").textContent = safariAgent; document.querySelector(\".output-chrome\").textContent = chromeAgent; document.querySelector(\".output-ie\").textContent = IExplorerAgent; document.querySelector(\".output-opera\").textContent = operaAgent; document.querySelector(\".output-firefox\").textContent = firefoxAgent; } </script></body> </html>", "e": 7431, "s": 4784, "text": null }, { "code": null, "e": 7439, "s": 7431, "text": "Output:" }, { "code": null, "e": 7469, "s": 7439, "text": "Output on the Chrome browser:" }, { "code": null, "e": 7500, "s": 7469, "text": "Output on the Firefox browser:" }, { "code": null, "e": 7529, "s": 7500, "text": "Output on the Opera browser:" }, { "code": null, "e": 7545, "s": 7529, "text": "JavaScript-Misc" }, { "code": null, "e": 7552, "s": 7545, "text": "Picked" }, { "code": null, "e": 7563, "s": 7552, "text": "JavaScript" }, { "code": null, "e": 7580, "s": 7563, "text": "Web Technologies" }, { "code": null, "e": 7607, "s": 7580, "text": "Web technologies Questions" } ]
JavaScript Page Refresh
You can refresh a web page using JavaScript location.reload method. This code can be called automatically upon an event or simply when the user clicks on a link. If you want to refresh a web page using a mouse click, then you can use the following code − <a href="javascript:location.reload(true)">Refresh Page</a> To understand it in better way you can Refresh Page. You can also use JavaScript to refresh the page automatically after a given time period. Here setTimeout() is a built-in JavaScript function which can be used to execute another function after a given time interval. Try the following example. It shows how to refresh a page after every 5 seconds. You can change this time as per your requirement. <html> <head> <script type = "text/JavaScript"> <!-- function AutoRefresh( t ) { setTimeout("location.reload(true);", t); } //--> </script> </head> <body onload = "JavaScript:AutoRefresh(5000);"> <p>This page will refresh every 5 seconds.</p> </body> </html> This page will refresh every 5 seconds. 25 Lectures 2.5 hours Anadi Sharma 74 Lectures 10 hours Lets Kode It 72 Lectures 4.5 hours Frahaan Hussain 70 Lectures 4.5 hours Frahaan Hussain 46 Lectures 6 hours Eduonix Learning Solutions 88 Lectures 14 hours Eduonix Learning Solutions Print Add Notes Bookmark this page
[ { "code": null, "e": 2721, "s": 2466, "text": "You can refresh a web page using JavaScript location.reload method. This code can be called automatically upon an event or simply when the user clicks on a link. If you want to refresh a web page using a mouse click, then you can use the following code −" }, { "code": null, "e": 2782, "s": 2721, "text": "<a href=\"javascript:location.reload(true)\">Refresh Page</a>\n" }, { "code": null, "e": 2835, "s": 2782, "text": "To understand it in better way you can Refresh Page." }, { "code": null, "e": 3051, "s": 2835, "text": "You can also use JavaScript to refresh the page automatically after a given time period. Here setTimeout() is a built-in JavaScript function which can be used to execute another function after a given time interval." }, { "code": null, "e": 3182, "s": 3051, "text": "Try the following example. It shows how to refresh a page after every 5 seconds. You can change this time as per your requirement." }, { "code": null, "e": 3550, "s": 3182, "text": "<html>\n <head>\n \n <script type = \"text/JavaScript\">\n <!--\n function AutoRefresh( t ) {\n setTimeout(\"location.reload(true);\", t);\n }\n //-->\n </script>\n \n </head>\n \n <body onload = \"JavaScript:AutoRefresh(5000);\">\n <p>This page will refresh every 5 seconds.</p>\n </body>\n \n</html>" }, { "code": null, "e": 3591, "s": 3550, "text": "This page will refresh every 5 seconds.\n" }, { "code": null, "e": 3626, "s": 3591, "text": "\n 25 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3640, "s": 3626, "text": " Anadi Sharma" }, { "code": null, "e": 3674, "s": 3640, "text": "\n 74 Lectures \n 10 hours \n" }, { "code": null, "e": 3688, "s": 3674, "text": " Lets Kode It" }, { "code": null, "e": 3723, "s": 3688, "text": "\n 72 Lectures \n 4.5 hours \n" }, { "code": null, "e": 3740, "s": 3723, "text": " Frahaan Hussain" }, { "code": null, "e": 3775, "s": 3740, "text": "\n 70 Lectures \n 4.5 hours \n" }, { "code": null, "e": 3792, "s": 3775, "text": " Frahaan Hussain" }, { "code": null, "e": 3825, "s": 3792, "text": "\n 46 Lectures \n 6 hours \n" }, { "code": null, "e": 3853, "s": 3825, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 3887, "s": 3853, "text": "\n 88 Lectures \n 14 hours \n" }, { "code": null, "e": 3915, "s": 3887, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 3922, "s": 3915, "text": " Print" }, { "code": null, "e": 3933, "s": 3922, "text": " Add Notes" } ]
Counting How Many Numbers Are Smaller Than the Current Number in JavaScript
We are required to write a JavaScript function that takes in an array of Numbers. The function should construct a new array based on the input array. Each corresponding element of the new array should be the number of elements that are smaller in the original array than that corresponding element. For example − If the input array is − const arr = [2, 7, 3, 1, 56, 4, 7, 8]; Then the output array should be − const output = [1, 4, 2, 0, 7, 3, 4, 6 ]; Following is the code − const arr = [2, 7, 3, 1, 56, 4, 7, 8]; const smallerThanCurrent = (arr = []) => { let { length } = arr; let res = Array(length).fill(0); for (let i = 0; i < length; i++){ for (let j = 0; j < length; ++j){ if (i != j && arr[i] > arr[j]){ ++res[i]; }; }; }; return res; }; console.log(smallerThanCurrent(arr)); Following is the console output [ 1, 4, 2, 0, 7, 3, 4, 6 ]
[ { "code": null, "e": 1144, "s": 1062, "text": "We are required to write a JavaScript function that takes in an array of Numbers." }, { "code": null, "e": 1212, "s": 1144, "text": "The function should construct a new array based on the input array." }, { "code": null, "e": 1361, "s": 1212, "text": "Each corresponding element of the new array should be the number of elements that are smaller in the original array than that corresponding element." }, { "code": null, "e": 1375, "s": 1361, "text": "For example −" }, { "code": null, "e": 1399, "s": 1375, "text": "If the input array is −" }, { "code": null, "e": 1438, "s": 1399, "text": "const arr = [2, 7, 3, 1, 56, 4, 7, 8];" }, { "code": null, "e": 1472, "s": 1438, "text": "Then the output array should be −" }, { "code": null, "e": 1514, "s": 1472, "text": "const output = [1, 4, 2, 0, 7, 3, 4, 6 ];" }, { "code": null, "e": 1538, "s": 1514, "text": "Following is the code −" }, { "code": null, "e": 1904, "s": 1538, "text": "const arr = [2, 7, 3, 1, 56, 4, 7, 8];\nconst smallerThanCurrent = (arr = []) => {\n let { length } = arr;\n let res = Array(length).fill(0);\n for (let i = 0; i < length; i++){\n for (let j = 0; j < length; ++j){\n if (i != j && arr[i] > arr[j]){\n ++res[i];\n };\n };\n };\n return res;\n};\nconsole.log(smallerThanCurrent(arr));" }, { "code": null, "e": 1936, "s": 1904, "text": "Following is the console output" }, { "code": null, "e": 1970, "s": 1936, "text": "[\n 1, 4, 2, 0,\n\n 7, 3, 4, 6\n]" } ]
How to persist Redux state in local Storage without any external library? - GeeksforGeeks
29 Jan, 2021 Redux as per the official documentation is a predictable state container for JavaScript apps. In simple words, it is a state management library, with the help of Redux managing the state of components becomes very easy. We can manage the state of the app by creating a global state known as a store. The idea to use Redux may be fine for a complex react app but this state is not persistable throughout. It means that once you reload the browser the state of the app changes and reaches its default state. Persisting the data of such react apps is very easy. We will be using local storage to store the current state of the React app and persist the data even on reloads. Creating React Application And Installing Module: Step 1: Create a React application using the following command: npx create-react-app myapp Step 2: After creating your project folder i.e. myapp, move to it using the following command: cd myapp Step 3: After creating the ReactJS application, Install the required modules using the following command: npm install redux npm install react-redux Project Structure: It will look like the following. Project Structure Example: We will create a simple shopping cart application through which we will persist data to our local storage. Filename- App.js This is the App component of our React app. All the dependencies that are required for a typical react application are imported. The provider function is imported from react-redux. This will act as a wrapping component for our App, to this wrapping component we will pass the store. The store is basically a global state of our application. Javascript import React from "react";import { Provider } from 'react-redux';import CartContainer from "./components/CartContainer"; // Storeimport { store } from './store';import { saveState } from './localStorage'; store.subscribe(() => { saveState({ cart: store.getState().cart, total: store.getState().total, amount: store.getState().amount });}); // Itemsconst cartItems = [ { id: 1, title: "Samsung", price: 799.99, img: "shorturl.at/ajkq9", amount: 1 }, { id: 2, title: "Google pixel Max", price: 399.99, img: "shorturl.at/ajkq9", amount: 1 }, { id: 3, title: "Xiaomi", price: 999.99, img: "shorturl.at/ajkq9", amount: 1 }]; function App() { return ( <Provider store={store}> <CartContainer cart={cartItems} /> </Provider> );} export default App; Filename- store.js In this file, the basic store set up is done using redux. The store is initialized and the state is being persisted to local storage. The redux store contains total, amount, and cart items. This store’s state will be later saved in the local storage. Javascript import reducer from './reducer';import { createStore } from 'redux';import { loadState } from './localStorage'; const cartItems = [ { id: 1, title: "Samsung", price: 799.99, img: "shorturl.at/ajkq9", amount: 1 }, { id: 2, title: "Google pixel Max", price: 399.99, img: "shorturl.at/ajkq9", amount: 1 }, { id: 3, title: "Xiaomi", price: 999.99, img: "shorturl.at/ajkq9", amount: 1 }]; const persistedState = loadState(); const initialStore = { cart: cartItems, amount: 0, total: 0, persistedState} export const store = createStore(reducer, persistedState); Filename: reducer.js This file contains the reducer function. As per the action dispatched through the UI, the corresponding functionality takes place. Mainly our reducer will be dealing with 5 basic operations of our app namely: The DECREASE action decreases the quantity of the items in our cart. The INCREASE action increases the quantity of the items in our cart. The REMOVE action removes an item from the cart. The CLEAR_CART action basically clears the entire cart. The GET_TOTALS action gets the sum of all the items in our cart. Note: One important thing to remember is that do not mutate the state of the app while using Redux. Javascript import { INCREASE, DECREASE, REMOVE, CLEAR_CART, GET_TOTALS,} from './actions'; function reducer(state, action) { if (action.type === DECREASE) { return { ...state, cart: state.cart.map((item) => { if (item.id === action.payload.id) { if (item.amount === 0) { return item; } else { item.amount--; } } return item; }) } } if (action.type === INCREASE) { return { ...state, cart: state.cart.map((item) => { if (item.id === action.payload.id) { item.amount++; } return item; }) } } if (action.type === CLEAR_CART) { return { ...state, cart: [] }; } if (action.type === REMOVE) { return {...state, cart: state.cart.filter(item => item.id !== action.payload.id)} } if (action.type === GET_TOTALS) { let { total, amount } = state.cart.reduce((cartTotal, cartItem) => { const { price, amount } = cartItem; cartTotal.amount += amount; cartTotal.total += Math.floor(amount * price); return cartTotal; }, { amount: 0, total: 0 }); return { ...state, total, amount }; } return state;} export default reducer; Filename: CartItem.js This file contains the code for the cartItem component. It is in this file that different methods are dispatched. The function mapDispatchToProps include three actions DECREASE, INCREASE, REMOVE. Javascript import React from "react";import { connect } from 'react-redux';import { DECREASE, INCREASE, REMOVE } from '../actions'; const CartItem = ({ title, price, img, amount, increase, decrease, remove }) => { return ( <div className="cart-item"> <img src={img} alt={img} /> <div> <h4>{title}</h4> <h4 className="item-price">${price}</h4> </div> <div> {/* increase amount */} <button className="amount-btn" onClick={() => increase()}> <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20"> <path d="M10.707 7.05L10 6.343 4.343 12l1.414 1.414L10 9.172l4.243 4.242L15.657 12z" /> </svg> </button> {/* amount */} <p className="amount">{amount}</p> {/* decrease amount */} <button className="amount-btn" onClick={() => decrease()} > <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20"> <path d="M9.293 12.95l.707.707L15.657 8l-1.414-1.414L10 10.828 5.757 6.586 4.343 8z" /> </svg> </button> </div> </div> );}; const mapDispatchToProps = (dispatch, ownProps) => { const { id, amount } = ownProps; return { increase: () => dispatch({ type: INCREASE, payload: { id } }), decrease: () => dispatch({ type: DECREASE, payload: { id } }), remove: () => dispatch({ type: REMOVE, payload: { id, amount } }) }} export default connect(null, mapDispatchToProps)(CartItem); Filename- CartContainer.js This file imports the carttem component and passes them the props that are needed. Here we connect mapStateToProps and mapDispatchToProps and then pass CartContainer to it. Javascript import React from "react";import CartItem from './CartItem';import { connect } from 'react-redux';import { CLEAR_CART, GET_TOTALS } from '../actions'; const CartContainer = ({ cart = [], total, remove, getTotal }) => { React.useEffect(() => { getTotal(); }) if (cart.length === 0) { return ( <section className="cart"> <header> <h2>your bag</h2> <h4 className="empty-cart"> is currently empty </h4> </header> </section> ); } return ( <section className="cart"> {/* cart header */} <header> <h2>your bag</h2> </header> {/* cart items */} <article> {cart.map((item) => { return <CartItem key={item.id} {...item} /> })} </article> {/* cart footer */} <footer> <hr /> <div className="cart-total"> <h4> total <span>${total}</span> </h4> </div> <button className="btn clear-btn" onClick={() => remove()} >clear cart</button> </footer> </section> );}; function mapStateToProps(store) { const { cart, total } = store; return { cart: cart, total: total };} function mapDispatchToProps(dispatch) { return { remove: () => dispatch({ type: CLEAR_CART }), getTotal: () => dispatch({ type: GET_TOTALS }) }} export default connect(mapStateToProps, mapDispatchToProps)(CartContainer); Filename- localStorage.js Now we will be adding the localStorage.js file. The method of persisting of data requires only four simple steps: Step 1: Create a file named localStorage.js in the root folder typically in the src folder of your react app. In this file, we will be adding two methods one to load state from the local storage and the other method to save state to the local storage. The code for loadState method is as follows: Javascript export const loadState = () => { try { const serialState = localStorage.getItem('appState'); if (serialState === null) { return undefined; } return JSON.parse(serialState); } catch (err) { return undefined; }}; In the local storage, data is stored in the form of key-value pairs. Here the key is ‘appState’ and the value will be the actual state of the app. Step 2: Code for saveState method is as follows: Javascript export const saveState = (state) => { try { const serialState = JSON.stringify(state); localStorage.setItem('appState', serialState); } catch(err) { console.log(err); }}; Step 3: Now in the store.js file import the loadState method from the localStorage.js file and get its value in the persistedState constant. Now as an object put this persistedState constant with the actual state of your app and export it by passing it to the store. Filename- store.js Javascript import reducer from './reducer';import {createStore} from 'redux';import {loadState} from './localStorage'; const persistedState = loadState(); const initialStore={ /* state of your app */ cart:cartItems, amount:0, total:0, persistedState} export const store=createStore(reducer,persistedState); Step 4: This is the most important step as this involves saving the state to the local storage of the browser. Now in the App.js component import the store from the store.js file and saveState() method from the localStorage.js file. Now save the state of the app by calling the subscribe function from the store. Filename- App.js Javascript import {store} from './store';import {saveState} from './localStorage'; store.subscribe(() => { saveState({ /* example state */ cart:store.getState().cart, total:store.getState().total, amount: store.getState().amount });}); Now just pass this store to the Provider component in the App component and the data will become persistent in the local storage. Output: You can check the state by opening developer tools on chrome and then navigating to Application then to Storage than to local storage. In the local storage, you’ll see the key named appState. This is the place where the entire data is stored. Redux JavaScript ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Difference between var, let and const keywords in JavaScript Convert a string to an integer 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 ? How to fetch data from an API in ReactJS ? How to redirect to another page in ReactJS ? How to pass data from child component to its parent in ReactJS ? Create a Responsive Navbar using ReactJS How to pass data from one component to other component in ReactJS ?
[ { "code": null, "e": 24859, "s": 24831, "text": "\n29 Jan, 2021" }, { "code": null, "e": 25159, "s": 24859, "text": "Redux as per the official documentation is a predictable state container for JavaScript apps. In simple words, it is a state management library, with the help of Redux managing the state of components becomes very easy. We can manage the state of the app by creating a global state known as a store." }, { "code": null, "e": 25532, "s": 25159, "text": "The idea to use Redux may be fine for a complex react app but this state is not persistable throughout. It means that once you reload the browser the state of the app changes and reaches its default state. Persisting the data of such react apps is very easy. We will be using local storage to store the current state of the React app and persist the data even on reloads. " }, { "code": null, "e": 25582, "s": 25532, "text": "Creating React Application And Installing Module:" }, { "code": null, "e": 25646, "s": 25582, "text": "Step 1: Create a React application using the following command:" }, { "code": null, "e": 25673, "s": 25646, "text": "npx create-react-app myapp" }, { "code": null, "e": 25768, "s": 25673, "text": "Step 2: After creating your project folder i.e. myapp, move to it using the following command:" }, { "code": null, "e": 25777, "s": 25768, "text": "cd myapp" }, { "code": null, "e": 25883, "s": 25777, "text": "Step 3: After creating the ReactJS application, Install the required modules using the following command:" }, { "code": null, "e": 25925, "s": 25883, "text": "npm install redux\nnpm install react-redux" }, { "code": null, "e": 25977, "s": 25925, "text": "Project Structure: It will look like the following." }, { "code": null, "e": 25995, "s": 25977, "text": "Project Structure" }, { "code": null, "e": 26111, "s": 25995, "text": "Example: We will create a simple shopping cart application through which we will persist data to our local storage." }, { "code": null, "e": 26469, "s": 26111, "text": "Filename- App.js This is the App component of our React app. All the dependencies that are required for a typical react application are imported. The provider function is imported from react-redux. This will act as a wrapping component for our App, to this wrapping component we will pass the store. The store is basically a global state of our application." }, { "code": null, "e": 26480, "s": 26469, "text": "Javascript" }, { "code": "import React from \"react\";import { Provider } from 'react-redux';import CartContainer from \"./components/CartContainer\"; // Storeimport { store } from './store';import { saveState } from './localStorage'; store.subscribe(() => { saveState({ cart: store.getState().cart, total: store.getState().total, amount: store.getState().amount });}); // Itemsconst cartItems = [ { id: 1, title: \"Samsung\", price: 799.99, img: \"shorturl.at/ajkq9\", amount: 1 }, { id: 2, title: \"Google pixel Max\", price: 399.99, img: \"shorturl.at/ajkq9\", amount: 1 }, { id: 3, title: \"Xiaomi\", price: 999.99, img: \"shorturl.at/ajkq9\", amount: 1 }]; function App() { return ( <Provider store={store}> <CartContainer cart={cartItems} /> </Provider> );} export default App;", "e": 27317, "s": 26480, "text": null }, { "code": null, "e": 27587, "s": 27317, "text": "Filename- store.js In this file, the basic store set up is done using redux. The store is initialized and the state is being persisted to local storage. The redux store contains total, amount, and cart items. This store’s state will be later saved in the local storage." }, { "code": null, "e": 27598, "s": 27587, "text": "Javascript" }, { "code": "import reducer from './reducer';import { createStore } from 'redux';import { loadState } from './localStorage'; const cartItems = [ { id: 1, title: \"Samsung\", price: 799.99, img: \"shorturl.at/ajkq9\", amount: 1 }, { id: 2, title: \"Google pixel Max\", price: 399.99, img: \"shorturl.at/ajkq9\", amount: 1 }, { id: 3, title: \"Xiaomi\", price: 999.99, img: \"shorturl.at/ajkq9\", amount: 1 }]; const persistedState = loadState(); const initialStore = { cart: cartItems, amount: 0, total: 0, persistedState} export const store = createStore(reducer, persistedState);", "e": 28228, "s": 27598, "text": null }, { "code": null, "e": 28458, "s": 28228, "text": "Filename: reducer.js This file contains the reducer function. As per the action dispatched through the UI, the corresponding functionality takes place. Mainly our reducer will be dealing with 5 basic operations of our app namely:" }, { "code": null, "e": 28527, "s": 28458, "text": "The DECREASE action decreases the quantity of the items in our cart." }, { "code": null, "e": 28596, "s": 28527, "text": "The INCREASE action increases the quantity of the items in our cart." }, { "code": null, "e": 28645, "s": 28596, "text": "The REMOVE action removes an item from the cart." }, { "code": null, "e": 28701, "s": 28645, "text": "The CLEAR_CART action basically clears the entire cart." }, { "code": null, "e": 28766, "s": 28701, "text": "The GET_TOTALS action gets the sum of all the items in our cart." }, { "code": null, "e": 28867, "s": 28766, "text": "Note: One important thing to remember is that do not mutate the state of the app while using Redux. " }, { "code": null, "e": 28878, "s": 28867, "text": "Javascript" }, { "code": "import { INCREASE, DECREASE, REMOVE, CLEAR_CART, GET_TOTALS,} from './actions'; function reducer(state, action) { if (action.type === DECREASE) { return { ...state, cart: state.cart.map((item) => { if (item.id === action.payload.id) { if (item.amount === 0) { return item; } else { item.amount--; } } return item; }) } } if (action.type === INCREASE) { return { ...state, cart: state.cart.map((item) => { if (item.id === action.payload.id) { item.amount++; } return item; }) } } if (action.type === CLEAR_CART) { return { ...state, cart: [] }; } if (action.type === REMOVE) { return {...state, cart: state.cart.filter(item => item.id !== action.payload.id)} } if (action.type === GET_TOTALS) { let { total, amount } = state.cart.reduce((cartTotal, cartItem) => { const { price, amount } = cartItem; cartTotal.amount += amount; cartTotal.total += Math.floor(amount * price); return cartTotal; }, { amount: 0, total: 0 }); return { ...state, total, amount }; } return state;} export default reducer;", "e": 30061, "s": 28878, "text": null }, { "code": null, "e": 30279, "s": 30061, "text": "Filename: CartItem.js This file contains the code for the cartItem component. It is in this file that different methods are dispatched. The function mapDispatchToProps include three actions DECREASE, INCREASE, REMOVE." }, { "code": null, "e": 30290, "s": 30279, "text": "Javascript" }, { "code": "import React from \"react\";import { connect } from 'react-redux';import { DECREASE, INCREASE, REMOVE } from '../actions'; const CartItem = ({ title, price, img, amount, increase, decrease, remove }) => { return ( <div className=\"cart-item\"> <img src={img} alt={img} /> <div> <h4>{title}</h4> <h4 className=\"item-price\">${price}</h4> </div> <div> {/* increase amount */} <button className=\"amount-btn\" onClick={() => increase()}> <svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 20 20\"> <path d=\"M10.707 7.05L10 6.343 4.343 12l1.414 1.414L10 9.172l4.243 4.242L15.657 12z\" /> </svg> </button> {/* amount */} <p className=\"amount\">{amount}</p> {/* decrease amount */} <button className=\"amount-btn\" onClick={() => decrease()} > <svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 20 20\"> <path d=\"M9.293 12.95l.707.707L15.657 8l-1.414-1.414L10 10.828 5.757 6.586 4.343 8z\" /> </svg> </button> </div> </div> );}; const mapDispatchToProps = (dispatch, ownProps) => { const { id, amount } = ownProps; return { increase: () => dispatch({ type: INCREASE, payload: { id } }), decrease: () => dispatch({ type: DECREASE, payload: { id } }), remove: () => dispatch({ type: REMOVE, payload: { id, amount } }) }} export default connect(null, mapDispatchToProps)(CartItem);", "e": 31783, "s": 30290, "text": null }, { "code": null, "e": 31983, "s": 31783, "text": "Filename- CartContainer.js This file imports the carttem component and passes them the props that are needed. Here we connect mapStateToProps and mapDispatchToProps and then pass CartContainer to it." }, { "code": null, "e": 31994, "s": 31983, "text": "Javascript" }, { "code": "import React from \"react\";import CartItem from './CartItem';import { connect } from 'react-redux';import { CLEAR_CART, GET_TOTALS } from '../actions'; const CartContainer = ({ cart = [], total, remove, getTotal }) => { React.useEffect(() => { getTotal(); }) if (cart.length === 0) { return ( <section className=\"cart\"> <header> <h2>your bag</h2> <h4 className=\"empty-cart\"> is currently empty </h4> </header> </section> ); } return ( <section className=\"cart\"> {/* cart header */} <header> <h2>your bag</h2> </header> {/* cart items */} <article> {cart.map((item) => { return <CartItem key={item.id} {...item} /> })} </article> {/* cart footer */} <footer> <hr /> <div className=\"cart-total\"> <h4> total <span>${total}</span> </h4> </div> <button className=\"btn clear-btn\" onClick={() => remove()} >clear cart</button> </footer> </section> );}; function mapStateToProps(store) { const { cart, total } = store; return { cart: cart, total: total };} function mapDispatchToProps(dispatch) { return { remove: () => dispatch({ type: CLEAR_CART }), getTotal: () => dispatch({ type: GET_TOTALS }) }} export default connect(mapStateToProps, mapDispatchToProps)(CartContainer);", "e": 33405, "s": 31994, "text": null }, { "code": null, "e": 33545, "s": 33405, "text": "Filename- localStorage.js Now we will be adding the localStorage.js file. The method of persisting of data requires only four simple steps:" }, { "code": null, "e": 33842, "s": 33545, "text": "Step 1: Create a file named localStorage.js in the root folder typically in the src folder of your react app. In this file, we will be adding two methods one to load state from the local storage and the other method to save state to the local storage. The code for loadState method is as follows:" }, { "code": null, "e": 33853, "s": 33842, "text": "Javascript" }, { "code": "export const loadState = () => { try { const serialState = localStorage.getItem('appState'); if (serialState === null) { return undefined; } return JSON.parse(serialState); } catch (err) { return undefined; }};", "e": 34105, "s": 33853, "text": null }, { "code": null, "e": 34252, "s": 34105, "text": "In the local storage, data is stored in the form of key-value pairs. Here the key is ‘appState’ and the value will be the actual state of the app." }, { "code": null, "e": 34301, "s": 34252, "text": "Step 2: Code for saveState method is as follows:" }, { "code": null, "e": 34312, "s": 34301, "text": "Javascript" }, { "code": "export const saveState = (state) => { try { const serialState = JSON.stringify(state); localStorage.setItem('appState', serialState); } catch(err) { console.log(err); }};", "e": 34509, "s": 34312, "text": null }, { "code": null, "e": 34776, "s": 34509, "text": "Step 3: Now in the store.js file import the loadState method from the localStorage.js file and get its value in the persistedState constant. Now as an object put this persistedState constant with the actual state of your app and export it by passing it to the store." }, { "code": null, "e": 34795, "s": 34776, "text": "Filename- store.js" }, { "code": null, "e": 34806, "s": 34795, "text": "Javascript" }, { "code": "import reducer from './reducer';import {createStore} from 'redux';import {loadState} from './localStorage'; const persistedState = loadState(); const initialStore={ /* state of your app */ cart:cartItems, amount:0, total:0, persistedState} export const store=createStore(reducer,persistedState);", "e": 35123, "s": 34806, "text": null }, { "code": null, "e": 35436, "s": 35123, "text": "Step 4: This is the most important step as this involves saving the state to the local storage of the browser. Now in the App.js component import the store from the store.js file and saveState() method from the localStorage.js file. Now save the state of the app by calling the subscribe function from the store." }, { "code": null, "e": 35453, "s": 35436, "text": "Filename- App.js" }, { "code": null, "e": 35464, "s": 35453, "text": "Javascript" }, { "code": "import {store} from './store';import {saveState} from './localStorage'; store.subscribe(() => { saveState({ /* example state */ cart:store.getState().cart, total:store.getState().total, amount: store.getState().amount });});", "e": 35703, "s": 35464, "text": null }, { "code": null, "e": 35834, "s": 35703, "text": "Now just pass this store to the Provider component in the App component and the data will become persistent in the local storage. " }, { "code": null, "e": 36085, "s": 35834, "text": "Output: You can check the state by opening developer tools on chrome and then navigating to Application then to Storage than to local storage. In the local storage, you’ll see the key named appState. This is the place where the entire data is stored." }, { "code": null, "e": 36091, "s": 36085, "text": "Redux" }, { "code": null, "e": 36102, "s": 36091, "text": "JavaScript" }, { "code": null, "e": 36110, "s": 36102, "text": "ReactJS" }, { "code": null, "e": 36127, "s": 36110, "text": "Web Technologies" }, { "code": null, "e": 36225, "s": 36127, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36234, "s": 36225, "text": "Comments" }, { "code": null, "e": 36247, "s": 36234, "text": "Old Comments" }, { "code": null, "e": 36308, "s": 36247, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 36353, "s": 36308, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 36425, "s": 36353, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 36477, "s": 36425, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 36523, "s": 36477, "text": "How to Open URL in New Tab using JavaScript ?" }, { "code": null, "e": 36566, "s": 36523, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 36611, "s": 36566, "text": "How to redirect to another page in ReactJS ?" }, { "code": null, "e": 36676, "s": 36611, "text": "How to pass data from child component to its parent in ReactJS ?" }, { "code": null, "e": 36717, "s": 36676, "text": "Create a Responsive Navbar using ReactJS" } ]
How to find and replace the word in a text file using PowerShell?
To search for the word in PowerShell and replace it in the file we will use the string operation. In fact, the Get-Content command in PowerShell is used to read almost any type of file content. In this article, we are considering one text file as shown below. Get-Content C:\Temp\TestFile.txt PS C:\> Get-Content C:\Temp\TestFile.txt # In case of linux, networkInterface names are of the form eth* # In Windows, please use the network full name from Device Manager networkInterfaces: ["Microsoft Hyper-V Network Adapter" ] overrideMetricsUsingScriptFile: false scriptTimeoutInSec: 60 scriptFiles: - osType: windows filePath: monitors/NetworkMonitor/scripts/windows-metrics.bat - osType: unixBase filePath: monitors/NetworkMonitor/scripts/unix-base-metrics.sh The above output is the content of the file and we are going to work with it. We need to find the NetWorkMonitor word and replace it with “Active”. Please note the above file is the text file so we don’t need to convert it to the string but if there are any other extensions you may need to convert the output to a string using .ToString() command or Out-String method before performing any operation. Now, we will find the requested string first, and let’s check how many lines we need to replace using Select-String cmdlet. (Get-Content C:\Temp\TestFile.txt) | Select-String -Pattern "NetworkMonitor" PS C:\> (Get-Content C:\Temp\TestFile.txt) | Select-String -Pattern "NetworkMonitor" filePath: monitors/NetworkMonitor/scripts/windows-metrics.bat filePath: monitors/NetworkMonitor/scripts/unix-base-metrics.sh We found out there are two lines that have the “NetworkMonitor” word. We need to replace that word with the following command. You can also store Get-Content output in a variable and perform operation on it. (Get-Content C:\Temp\TestFile.txt) -replace "NetworkMonitor","Active" PS C:\> (Get-Content C:\Temp\TestFile.txt) -replace "NetworkMonitor","Active" # In case of linux, networkInterface names are of the form eth* # In Windows, please use the network full name from Device Manager networkInterfaces: ["Microsoft Hyper-V Network Adapter" ] overrideMetricsUsingScriptFile: false scriptTimeoutInSec: 60 scriptFiles: - osType: windows filePath: monitors/Active/scripts/windows-metrics.bat - osType: unixBase filePath: monitors/Active/scripts/unix-base-metrics.sh The above command replaced the file content but it is not stored yet so to save the updated file, we will use the Set-Content and the final code would be, (Get-Content C:\Temp\TestFile.txt) -replace "NetworkMonitor","Active" | Set-Content C:\Temp\Testfile.txt -Verbos You can also choose a different path to save the file. If the file is read-only then use -Force parameter with Set-Content cmdlet.
[ { "code": null, "e": 1322, "s": 1062, "text": "To search for the word in PowerShell and replace it in the file we will use the string operation. In fact, the Get-Content command in PowerShell is used to read almost any type of file content. In this article, we are considering one text file as shown below." }, { "code": null, "e": 1355, "s": 1322, "text": "Get-Content C:\\Temp\\TestFile.txt" }, { "code": null, "e": 1824, "s": 1355, "text": "PS C:\\> Get-Content C:\\Temp\\TestFile.txt\n# In case of linux, networkInterface names are of the form eth*\n# In Windows, please use the network full name from Device Manager\nnetworkInterfaces: [\"Microsoft Hyper-V Network Adapter\"\n]\n\noverrideMetricsUsingScriptFile: false\n\nscriptTimeoutInSec: 60\n\nscriptFiles:\n- osType: windows\nfilePath: monitors/NetworkMonitor/scripts/windows-metrics.bat\n- osType: unixBase\nfilePath: monitors/NetworkMonitor/scripts/unix-base-metrics.sh" }, { "code": null, "e": 2226, "s": 1824, "text": "The above output is the content of the file and we are going to work with it. We need to find the NetWorkMonitor word and replace it with “Active”. Please note the above file is the text file so we don’t need to convert it to the string but if there are any other extensions you may need to convert the output to a string using .ToString() command or Out-String method before performing any operation." }, { "code": null, "e": 2350, "s": 2226, "text": "Now, we will find the requested string first, and let’s check how many lines we need to replace using Select-String cmdlet." }, { "code": null, "e": 2427, "s": 2350, "text": "(Get-Content C:\\Temp\\TestFile.txt) | Select-String -Pattern \"NetworkMonitor\"" }, { "code": null, "e": 2643, "s": 2427, "text": "PS C:\\> (Get-Content C:\\Temp\\TestFile.txt) | Select-String -Pattern \"NetworkMonitor\"\n filePath: monitors/NetworkMonitor/scripts/windows-metrics.bat\n filePath: monitors/NetworkMonitor/scripts/unix-base-metrics.sh" }, { "code": null, "e": 2851, "s": 2643, "text": "We found out there are two lines that have the “NetworkMonitor” word. We need to replace that word with the following command. You can also store Get-Content output in a variable and perform operation on it." }, { "code": null, "e": 2921, "s": 2851, "text": "(Get-Content C:\\Temp\\TestFile.txt) -replace \"NetworkMonitor\",\"Active\"" }, { "code": null, "e": 3411, "s": 2921, "text": "PS C:\\> (Get-Content C:\\Temp\\TestFile.txt) -replace \"NetworkMonitor\",\"Active\"\n# In case of linux, networkInterface names are of the form eth*\n# In Windows, please use the network full name from Device Manager\nnetworkInterfaces: [\"Microsoft Hyper-V Network Adapter\"\n]\n\noverrideMetricsUsingScriptFile: false\n\nscriptTimeoutInSec: 60\n\nscriptFiles:\n- osType: windows\nfilePath: monitors/Active/scripts/windows-metrics.bat\n- osType: unixBase\nfilePath: monitors/Active/scripts/unix-base-metrics.sh" }, { "code": null, "e": 3566, "s": 3411, "text": "The above command replaced the file content but it is not stored yet so to save the updated file, we will use the Set-Content and the final code would be," }, { "code": null, "e": 3679, "s": 3566, "text": "(Get-Content C:\\Temp\\TestFile.txt) -replace \"NetworkMonitor\",\"Active\" | Set-Content\nC:\\Temp\\Testfile.txt -Verbos" }, { "code": null, "e": 3810, "s": 3679, "text": "You can also choose a different path to save the file. If the file is read-only then use -Force parameter with Set-Content cmdlet." } ]
Remainder with 7 | Practice | GeeksforGeeks
Given a number as string(n) , find the remainder of the number whe it is divided by 7 Example 1: Input: 5 Output: 5 Example 2: Input: 8 Output: 1 Your Task: You only need to complete the function remainderwith7() that takes string n as parameter and returns an integer which denotes the remainder of the number when its divided by 7 Constraints: 1<=length of n <=105 0 thaloravinash101 week ago def remainderWith7(self, str): a=int(str) return a%7 0 adityapratyush1 month ago Python Solution: def remainderWith7(self, str): return int(str) % 7 -1 aahankatiyar2 months ago // why this code is wrong ?? int remainderWith7(string n) { //Your code here int size=n.length(); int i=size-1; int num=0; int j=0; while(i >=0) { int a=n[i]-'0'; num +=a*pow(10,j); j++; i--; } return (num % 7); } +1 akashindranagar3 months ago **************************JAVA Solution ************************ class Solution{ // Complete the function int remainderWith7(String num) { // Your code here java.math.BigInteger rem; java.math.BigInteger a=new java.math.BigInteger(num); java.math.BigInteger no1=new java.math.BigInteger("7"); rem=a.remainder(no1); int result=rem.intValue(); return result; }} 0 mp333943 months ago #python code (0.02 s) class Solution: #your task is to complete this function #Function should return the required answer #You are not allowed to convert string to integer def remainderWith7(self, str): #Code here s = int(str) return s%7 +6 sourabhsingh191220014 months ago int remainderWith7(string n) { int rem = 0; for(int i = 0; i < n.length(); i++) { rem = rem*10 + (n[i] - '0'); rem = rem%7; } return rem; } 0 sourabhsingh19122001 This comment was deleted. +3 amoldongarwar4 months ago where is wrong???? int remainderWith7(string n) { int rem; int no=stoi(n); rem=no%7; return rem; } 0 ankita12apr5 months ago int remainderWith7(String num) { // Your code here java.math.BigInteger b1 = new java.math.BigInteger(num); java.math.BigInteger b2 = new java.math.BigInteger("7"); java.math.BigInteger number = b1.mod(b2); int n = number.intValue(); return n; } 0 komalk80096 months ago https://www.geeksforgeeks.org/remainder-7-large-numbers/ 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": 336, "s": 238, "text": "Given a number as string(n) , find the remainder of the number whe it is divided by 7\n\nExample 1:" }, { "code": null, "e": 355, "s": 336, "text": "Input:\n5\nOutput:\n5" }, { "code": null, "e": 368, "s": 357, "text": "Example 2:" }, { "code": null, "e": 388, "s": 368, "text": "Input:\n8\nOutput:\n1\n" }, { "code": null, "e": 402, "s": 390, "text": "Your Task: " }, { "code": null, "e": 578, "s": 402, "text": "You only need to complete the function remainderwith7() that takes string n as parameter and returns an integer which denotes the remainder of the number when its divided by 7" }, { "code": null, "e": 616, "s": 580, "text": "Constraints:\n1<=length of n <=105\n " }, { "code": null, "e": 618, "s": 616, "text": "0" }, { "code": null, "e": 644, "s": 618, "text": "thaloravinash101 week ago" }, { "code": null, "e": 709, "s": 644, "text": "def remainderWith7(self, str): a=int(str) return a%7" }, { "code": null, "e": 711, "s": 709, "text": "0" }, { "code": null, "e": 737, "s": 711, "text": "adityapratyush1 month ago" }, { "code": null, "e": 754, "s": 737, "text": "Python Solution:" }, { "code": null, "e": 811, "s": 754, "text": "def remainderWith7(self, str): return int(str) % 7" }, { "code": null, "e": 814, "s": 811, "text": "-1" }, { "code": null, "e": 839, "s": 814, "text": "aahankatiyar2 months ago" }, { "code": null, "e": 868, "s": 839, "text": "// why this code is wrong ??" }, { "code": null, "e": 1175, "s": 870, "text": " int remainderWith7(string n) { //Your code here int size=n.length(); int i=size-1; int num=0; int j=0; while(i >=0) { int a=n[i]-'0'; num +=a*pow(10,j); j++; i--; } return (num % 7); }" }, { "code": null, "e": 1178, "s": 1175, "text": "+1" }, { "code": null, "e": 1206, "s": 1178, "text": "akashindranagar3 months ago" }, { "code": null, "e": 1271, "s": 1206, "text": "**************************JAVA Solution ************************" }, { "code": null, "e": 1624, "s": 1271, "text": "class Solution{ // Complete the function int remainderWith7(String num) { // Your code here java.math.BigInteger rem; java.math.BigInteger a=new java.math.BigInteger(num); java.math.BigInteger no1=new java.math.BigInteger(\"7\"); rem=a.remainder(no1); int result=rem.intValue(); return result; }} " }, { "code": null, "e": 1626, "s": 1624, "text": "0" }, { "code": null, "e": 1646, "s": 1626, "text": "mp333943 months ago" }, { "code": null, "e": 1668, "s": 1646, "text": "#python code (0.02 s)" }, { "code": null, "e": 1910, "s": 1668, "text": "class Solution: #your task is to complete this function #Function should return the required answer #You are not allowed to convert string to integer def remainderWith7(self, str): #Code here s = int(str) return s%7" }, { "code": null, "e": 1915, "s": 1912, "text": "+6" }, { "code": null, "e": 1948, "s": 1915, "text": "sourabhsingh191220014 months ago" }, { "code": null, "e": 2127, "s": 1948, "text": " int remainderWith7(string n)\n{\n int rem = 0; \n for(int i = 0; i < n.length(); i++)\n {\n rem = rem*10 + (n[i] - '0');\n rem = rem%7;\n }\n return rem;\n}" }, { "code": null, "e": 2129, "s": 2127, "text": "0" }, { "code": null, "e": 2150, "s": 2129, "text": "sourabhsingh19122001" }, { "code": null, "e": 2176, "s": 2150, "text": "This comment was deleted." }, { "code": null, "e": 2179, "s": 2176, "text": "+3" }, { "code": null, "e": 2205, "s": 2179, "text": "amoldongarwar4 months ago" }, { "code": null, "e": 2224, "s": 2205, "text": "where is wrong????" }, { "code": null, "e": 2332, "s": 2224, "text": "int remainderWith7(string n) { int rem; int no=stoi(n); rem=no%7; return rem; }" }, { "code": null, "e": 2334, "s": 2332, "text": "0" }, { "code": null, "e": 2358, "s": 2334, "text": "ankita12apr5 months ago" }, { "code": null, "e": 2644, "s": 2358, "text": "int remainderWith7(String num) { // Your code here java.math.BigInteger b1 = new java.math.BigInteger(num); java.math.BigInteger b2 = new java.math.BigInteger(\"7\"); java.math.BigInteger number = b1.mod(b2); int n = number.intValue(); return n; }" }, { "code": null, "e": 2646, "s": 2644, "text": "0" }, { "code": null, "e": 2669, "s": 2646, "text": "komalk80096 months ago" }, { "code": null, "e": 2726, "s": 2669, "text": "https://www.geeksforgeeks.org/remainder-7-large-numbers/" }, { "code": null, "e": 2872, "s": 2726, "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": 2908, "s": 2872, "text": " Login to access your submissions. " }, { "code": null, "e": 2918, "s": 2908, "text": "\nProblem\n" }, { "code": null, "e": 2928, "s": 2918, "text": "\nContest\n" }, { "code": null, "e": 2991, "s": 2928, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 3139, "s": 2991, "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": 3347, "s": 3139, "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": 3453, "s": 3347, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
How can I delete all cookies with JavaScript?
To delete all cookies with JavaScript, you can try to run the following code. Here, we’re using an array and the split() method to get all the cookies and finally delete them Live Demo <!DOCTYPE html> <html> <head> <script> var num = 1; function addCookie(){ document.cookie = num+" = "+num; num++; } function listCookies(){ var result = document.cookie; document.getElementById("list").innerHTML = result; } function removeCookies() { var res = document.cookie; var multiple = res.split(";"); for(var i = 0; i < multiple.length; i++) { var key = multiple[i].split("="); document.cookie = key[0]+" =; expires = Thu, 01 Jan 1970 00:00:00 UTC"; } } </script> </head> <body> <button onclick = 'addCookie()'>ADD</button><br> <button onclick = 'listCookies()'>LIST COOKIES</button><br> <button onclick = 'removeCookies()'>REMOVE</button> <h1>Cookies List</h1> <p id = "list"></p> </body> </html>
[ { "code": null, "e": 1237, "s": 1062, "text": "To delete all cookies with JavaScript, you can try to run the following code. Here, we’re using an array and the split() method to get all the cookies and finally delete them" }, { "code": null, "e": 1247, "s": 1237, "text": "Live Demo" }, { "code": null, "e": 2196, "s": 1247, "text": "<!DOCTYPE html>\n<html>\n <head>\n <script>\n var num = 1;\n function addCookie(){\n document.cookie = num+\" = \"+num;\n num++;\n }\n function listCookies(){\n var result = document.cookie;\n document.getElementById(\"list\").innerHTML = result;\n }\n function removeCookies() {\n var res = document.cookie;\n var multiple = res.split(\";\");\n for(var i = 0; i < multiple.length; i++) {\n var key = multiple[i].split(\"=\");\n document.cookie = key[0]+\" =; expires = Thu, 01 Jan 1970 00:00:00 UTC\";\n }\n }\n </script>\n </head>\n <body>\n <button onclick = 'addCookie()'>ADD</button><br>\n <button onclick = 'listCookies()'>LIST COOKIES</button><br>\n <button onclick = 'removeCookies()'>REMOVE</button>\n <h1>Cookies List</h1>\n <p id = \"list\"></p>\n </body>\n</html>" } ]
Queries to update a given index and find gcd in range - GeeksforGeeks
11 Nov, 2021 Given an array arr[] of N integers and queries Q. Queries are of two types: Update a given index ind by X.Find the gcd of the elements in the index range [L, R]. Update a given index ind by X. Find the gcd of the elements in the index range [L, R]. Examples: Input: arr[] = {1, 3, 6, 9, 9, 11} Type 2 query: L = 1, R = 3 Type 1 query: ind = 1, X = 10 Type 2 query: L = 1, R = 3 Output: 3 1 Input: arr[] = {1, 2, 4, 9, 3} Type 2 query: L = 1, R = 2 Type 1 query: ind = 2, X = 7 Type 2 query: L = 1, R = 2 Type 2 query: L = 3, R = 4 Output: 2 1 3 Approach: The following problem can be solved using Segment Tree. Segment tree can be used to do preprocessing and query in moderate time. With segment tree, preprocessing time is O(n) and time to for GCD query is O(Logn). The extra space required is O(n) to store the segment tree.Representation of Segment trees Leaf Nodes are the elements of the input array. Each internal node represents GCD of all leaves under it. Array representation of tree is used to represent Segment Trees i.e., for each node at index i Left child is at index 2*i+1 Right child at 2*i+2 and the parent is at floor((i-1)/2). Construction of Segment Tree from given array Begin with a segment arr[0 . . . n-1] and keep dividing into two halves. Every time we divide the current segment into two halves (if it has not yet become a segment of length 1), then call the same procedure on both halves, and for each such segment, we store the GCD value in a segment tree node. All levels of the constructed segment tree will be completely filled except the last level. Also, the tree will be a Full Binary Tree (every node has 0 or two children) because we always divide segments in two halves at every level. Since the constructed tree is always full binary tree with n leaves, there will be n-1 internal nodes. So total number of nodes will be 2*n – 1. Like tree construction and query operations, the update can also be done recursively. We are given an index which needs to be updated. Let diff be the value to be added. We start from root of the segment tree and add diff to all nodes which have given index in their range. If a node doesn’t have given index in its range, we don’t make any changes to that node.Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // A utility function to get the// middle index from corner indexesint getMid(int s, int e){ return (s + (e - s) / 2);} // A recursive function to get the gcd of values in given range// of the array. The following are parameters for this function // st --> Pointer to segment tree// si --> Index of current node in the segment tree. Initially// 0 is passed as root is always at index 0// ss & se --> Starting and ending indexes of the segment represented// by current node, i.e., st[si]// qs & qe --> Starting and ending indexes of query rangeint getGcdUtil(int* st, int ss, int se, int qs, int qe, int si){ // If segment of this node is a part of given range // then return the gcd of the segment if (qs <= ss && qe >= se) return st[si]; // If segment of this node is outside the given range if (se < qs || ss > qe) return 0; // If a part of this segment overlaps with the given range int mid = getMid(ss, se); return __gcd(getGcdUtil(st, ss, mid, qs, qe, 2 * si + 1), getGcdUtil(st, mid + 1, se, qs, qe, 2 * si + 2));} // A recursive function to update the nodes which have the given// index in their range. The following are parameters// st, si, ss and se are same as getSumUtil()// i --> index of the element to be updated. This index is// in the input array.// diff --> Value to be added to all nodes which have i in rangevoid updateValueUtil(int* st, int ss, int se, int i, int diff, int si){ // Base Case: If the input index lies outside the range of // this segment if (i < ss || i > se) return; // If the input index is in range of this node, then update // the value of the node and its children st[si] = st[si] + diff; if (se != ss) { int mid = getMid(ss, se); updateValueUtil(st, ss, mid, i, diff, 2 * si + 1); updateValueUtil(st, mid + 1, se, i, diff, 2 * si + 2); }} // The function to update a value in input array and segment tree.// It uses updateValueUtil() to update the value in segment treevoid updateValue(int arr[], int* st, int n, int i, int new_val){ // Check for erroneous input index if (i < 0 || i > n - 1) { cout << "Invalid Input"; return; } // Get the difference between new value and old value int diff = new_val - arr[i]; // Update the value in array arr[i] = new_val; // Update the values of nodes in segment tree updateValueUtil(st, 0, n - 1, i, diff, 0);} // Function to return the sum of elements in range// from index qs (query start) to qe (query end)// It mainly uses getSumUtil()int getGcd(int* st, int n, int qs, int qe){ // Check for erroneous input values if (qs < 0 || qe > n - 1 || qs > qe) { cout << "Invalid Input"; return -1; } return getGcdUtil(st, 0, n - 1, qs, qe, 0);} // A recursive function that constructs Segment Tree for array[ss..se].// si is index of current node in segment tree stint constructGcdUtil(int arr[], int ss, int se, int* st, int si){ // If there is one element in array, store it in current node of // segment tree and return if (ss == se) { st[si] = arr[ss]; return arr[ss]; } // If there are more than one element then recur for left and // right subtrees and store the sum of values in this node int mid = getMid(ss, se); st[si] = __gcd(constructGcdUtil(arr, ss, mid, st, si * 2 + 1), constructGcdUtil(arr, mid + 1, se, st, si * 2 + 2)); return st[si];} // Function to construct segment tree from given array. This function// allocates memory for segment tree and calls constructSTUtil() to// fill the allocated memoryint* constructGcd(int arr[], int n){ // Allocate memory for the segment tree // Height of segment tree int x = (int)(ceil(log2(n))); // Maximum size of segment tree int max_size = 2 * (int)pow(2, x) - 1; // Allocate memory int* st = new int[max_size]; // Fill the allocated memory st constructGcdUtil(arr, 0, n - 1, st, 0); // Return the constructed segment tree return st;} // Driver codeint main(){ int arr[] = { 1, 3, 6, 9, 9, 11 }; int n = sizeof(arr) / sizeof(arr[0]); // Build segment tree from given array int* st = constructGcd(arr, n); // Print GCD of values in array from index 1 to 3 cout << getGcd(st, n, 1, 3) << endl; // Update: set arr[1] = 10 and update corresponding // segment tree nodes updateValue(arr, st, n, 1, 10); // Find GCD after the value is updated cout << getGcd(st, n, 1, 3) << endl; return 0;} // Java implementation of the approachclass GFG{ // segment treestatic int st[]; // Recursive function to return gcd of a and bstatic int __gcd(int a, int b){ if (b == 0) return a; return __gcd(b, a % b); } // A utility function to get the// middle index from corner indexesstatic int getMid(int s, int e){ return (s + (e - s) / 2);} // A recursive function to get the gcd of values in given range// of the array. The following are parameters for this function // st --> Pointer to segment tree// si --> Index of current node in the segment tree. Initially// 0 is passed as root is always at index 0// ss & se --> Starting and ending indexes of the segment represented// by current node, i.e., st[si]// qs & qe --> Starting and ending indexes of query rangestatic int getGcdUtil( int ss, int se, int qs, int qe, int si){ // If segment of this node is a part of given range // then return the gcd of the segment if (qs <= ss && qe >= se) return st[si]; // If segment of this node is outside the given range if (se < qs || ss > qe) return 0; // If a part of this segment overlaps with the given range int mid = getMid(ss, se); return __gcd(getGcdUtil( ss, mid, qs, qe, 2 * si + 1), getGcdUtil( mid + 1, se, qs, qe, 2 * si + 2));} // A recursive function to update the nodes which have the given// index in their range. The following are parameters// si, ss and se are same as getSumUtil()// i --> index of the element to be updated. This index is// in the input array.// diff --> Value to be added to all nodes which have i in rangestatic void updateValueUtil( int ss, int se, int i, int diff, int si){ // Base Case: If the input index lies outside the range of // this segment if (i < ss || i > se) return; // If the input index is in range of this node, then update // the value of the node and its children st[si] = st[si] + diff; if (se != ss) { int mid = getMid(ss, se); updateValueUtil( ss, mid, i, diff, 2 * si + 1); updateValueUtil( mid + 1, se, i, diff, 2 * si + 2); }} // The function to update a value in input array and segment tree.// It uses updateValueUtil() to update the value in segment treestatic void updateValue(int arr[], int n, int i, int new_val){ // Check for erroneous input index if (i < 0 || i > n - 1) { System.out.println("Invalid Input"); return; } // Get the difference between new value and old value int diff = new_val - arr[i]; // Update the value in array arr[i] = new_val; // Update the values of nodes in segment tree updateValueUtil( 0, n - 1, i, diff, 0);} // Function to return the sum of elements in range// from index qs (query start) to qe (query end)// It mainly uses getSumUtil()static int getGcd( int n, int qs, int qe){ // Check for erroneous input values if (qs < 0 || qe > n - 1 || qs > qe) { System.out.println( "Invalid Input"); return -1; } return getGcdUtil( 0, n - 1, qs, qe, 0);} // A recursive function that constructs Segment Tree for array[ss..se].// si is index of current node in segment tree ststatic int constructGcdUtil(int arr[], int ss, int se, int si){ // If there is one element in array, store it in current node of // segment tree and return if (ss == se) { st[si] = arr[ss]; return arr[ss]; } // If there are more than one element then recur for left and // right subtrees and store the sum of values in this node int mid = getMid(ss, se); st[si] = __gcd(constructGcdUtil(arr, ss, mid, si * 2 + 1), constructGcdUtil(arr, mid + 1, se, si * 2 + 2)); return st[si];} // Function to construct segment tree from given array. This function// allocates memory for segment tree and calls constructSTUtil() to// fill the allocated memorystatic void constructGcd(int arr[], int n){ // Allocate memory for the segment tree // Height of segment tree int x = (int)(Math.ceil(Math.log(n)/Math.log(2))); // Maximum size of segment tree int max_size = 2 * (int)Math.pow(2, x) - 1; // Allocate memory st = new int[max_size]; // Fill the allocated memory st constructGcdUtil(arr, 0, n - 1, 0); } // Driver codepublic static void main(String args[]){ int arr[] = { 1, 3, 6, 9, 9, 11 }; int n = arr.length; // Build segment tree from given array constructGcd(arr, n); // Print GCD of values in array from index 1 to 3 System.out.println( getGcd( n, 1, 3) ); // Update: set arr[1] = 10 and update corresponding // segment tree nodes updateValue(arr, n, 1, 10); // Find GCD after the value is updated System.out.println( getGcd( n, 1, 3) );}} // This code is constructed by Arnab Kundu # Python 3 implementation of the approach from math import gcd,ceil,log2,pow # A utility function to get the# middle index from corner indexesdef getMid(s, e): return (s + int((e - s) / 2)) # A recursive function to get the gcd of values in given range# of the array. The following are parameters for this function # st --> Pointer to segment tree# si --> Index of current node in the segment tree. Initially# 0 is passed as root is always at index 0# ss & se --> Starting and ending indexes of the segment represented# by current node, i.e., st[si]# qs & qe --> Starting and ending indexes of query rangedef getGcdUtil(st,ss,se,qs,qe,si): # If segment of this node is a part of given range # then return the gcd of the segment if (qs <= ss and qe >= se): return st[si] # If segment of this node is outside the given range if (se < qs or ss > qe): return 0 # If a part of this segment overlaps with the given range mid = getMid(ss, se) return gcd(getGcdUtil(st, ss, mid, qs, qe, 2 * si + 1), getGcdUtil(st, mid + 1, se, qs, qe, 2 * si + 2)) # A recursive function to update the nodes which have the given# index in their range. The following are parameters# st, si, ss and se are same as getSumUtil()# i --> index of the element to be updated. This index is# in the input array.# diff --> Value to be added to all nodes which have i in rangedef updateValueUtil(st,ss,se,i,diff,si): # Base Case: If the input index lies outside the range of # this segment if (i < ss or i > se): return # If the input index is in range of this node, then update # the value of the node and its children st[si] = st[si] + diff if (se != ss): mid = getMid(ss, se) updateValueUtil(st, ss, mid, i, diff, 2 * si + 1) updateValueUtil(st, mid + 1, se, i, diff, 2 * si + 2) # The function to update a value in input array and segment tree.# It uses updateValueUtil() to update the value in segment treedef updateValue(arr, st, n, i, new_val): # Check for erroneous input index if (i < 0 or i > n - 1): print("Invalid Input") return # Get the difference between new value and old value diff = new_val - arr[i] # Update the value in array arr[i] = new_val # Update the values of nodes in segment tree updateValueUtil(st, 0, n - 1, i, diff, 0) # Function to return the sum of elements in range# from index qs (query start) to qe (query end)# It mainly uses getSumUtil()def getGcd(st,n,qs,qe): # Check for erroneous input values if (qs < 0 or qe > n - 1 or qs > qe): cout << "Invalid Input" return -1 return getGcdUtil(st, 0, n - 1, qs, qe, 0) # A recursive function that constructs Segment Tree for array[ss..se].# si is index of current node in segment tree stdef constructGcdUtil(arr, ss,se, st, si): # If there is one element in array, store it in current node of # segment tree and return if (ss == se): st[si] = arr[ss] return arr[ss] # If there are more than one element then recur for left and # right subtrees and store the sum of values in this node mid = getMid(ss, se) st[si] = gcd(constructGcdUtil(arr, ss, mid, st, si * 2 + 1), constructGcdUtil(arr, mid + 1, se, st, si * 2 + 2)) return st[si] # Function to construct segment tree from given array. This function# allocates memory for segment tree and calls constructSTUtil() to# fill the allocated memorydef constructGcd(arr, n): # Allocate memory for the segment tree # Height of segment tree x = int(ceil(log2(n))) # Maximum size of segment tree max_size = 2 * int(pow(2, x) - 1) # Allocate memory st = [0 for i in range(max_size)] # Fill the allocated memory st constructGcdUtil(arr, 0, n - 1, st, 0) # Return the constructed segment tree return st # Driver codeif __name__ == '__main__': arr = [1, 3, 6, 9, 9, 11] n = len(arr) # Build segment tree from given array st = constructGcd(arr, n) # Print GCD of values in array from index 1 to 3 print(getGcd(st, n, 1, 3)) # Update: set arr[1] = 10 and update corresponding # segment tree nodes updateValue(arr, st, n, 1, 10) # Find GCD after the value is updated print(getGcd(st, n, 1, 3)) # This code is contributed by# SURENDRA_GANGWAR // C# implementation of the approach.using System; class GFG{ // segment treestatic int []st; // Recursive function to return gcd of a and bstatic int __gcd(int a, int b){ if (b == 0) return a; return __gcd(b, a % b); } // A utility function to get the// middle index from corner indexesstatic int getMid(int s, int e){ return (s + (e - s) / 2);} // A recursive function to get the gcd of values in given range// of the array. The following are parameters for this function // st --> Pointer to segment tree// si --> Index of current node in the segment tree. Initially// 0 is passed as root is always at index 0// ss & se --> Starting and ending indexes of the segment represented// by current node, i.e., st[si]// qs & qe --> Starting and ending indexes of query rangestatic int getGcdUtil( int ss, int se, int qs, int qe, int si){ // If segment of this node is a part of given range // then return the gcd of the segment if (qs <= ss && qe >= se) return st[si]; // If segment of this node is outside the given range if (se < qs || ss > qe) return 0; // If a part of this segment overlaps with the given range int mid = getMid(ss, se); return __gcd(getGcdUtil( ss, mid, qs, qe, 2 * si + 1), getGcdUtil( mid + 1, se, qs, qe, 2 * si + 2));} // A recursive function to update the nodes which have the given// index in their range. The following are parameters// si, ss and se are same as getSumUtil()// i --> index of the element to be updated. This index is// in the input array.// diff --> Value to be added to all nodes which have i in rangestatic void updateValueUtil( int ss, int se, int i, int diff, int si){ // Base Case: If the input index lies outside the range of // this segment if (i < ss || i > se) return; // If the input index is in range of this node, then update // the value of the node and its children st[si] = st[si] + diff; if (se != ss) { int mid = getMid(ss, se); updateValueUtil( ss, mid, i, diff, 2 * si + 1); updateValueUtil( mid + 1, se, i, diff, 2 * si + 2); }} // The function to update a value in input array and segment tree.// It uses updateValueUtil() to update the value in segment treestatic void updateValue(int []arr, int n, int i, int new_val){ // Check for erroneous input index if (i < 0 || i > n - 1) { Console.WriteLine("Invalid Input"); return; } // Get the difference between new value and old value int diff = new_val - arr[i]; // Update the value in array arr[i] = new_val; // Update the values of nodes in segment tree updateValueUtil( 0, n - 1, i, diff, 0);} // Function to return the sum of elements in range// from index qs (query start) to qe (query end)// It mainly uses getSumUtil()static int getGcd( int n, int qs, int qe){ // Check for erroneous input values if (qs < 0 || qe > n - 1 || qs > qe) { Console.WriteLine( "Invalid Input"); return -1; } return getGcdUtil( 0, n - 1, qs, qe, 0);} // A recursive function that constructs Segment Tree for array[ss..se].// si is index of current node in segment tree ststatic int constructGcdUtil(int []arr, int ss, int se, int si){ // If there is one element in array, store it in current node of // segment tree and return if (ss == se) { st[si] = arr[ss]; return arr[ss]; } // If there are more than one element then recur for left and // right subtrees and store the sum of values in this node int mid = getMid(ss, se); st[si] = __gcd(constructGcdUtil(arr, ss, mid, si * 2 + 1), constructGcdUtil(arr, mid + 1, se, si * 2 + 2)); return st[si];} // Function to construct segment tree from given array. This function// allocates memory for segment tree and calls constructSTUtil() to// fill the allocated memorystatic void constructGcd(int []arr, int n){ // Allocate memory for the segment tree // Height of segment tree int x = (int)(Math.Ceiling(Math.Log(n)/Math.Log(2))); // Maximum size of segment tree int max_size = 2 * (int)Math.Pow(2, x) - 1; // Allocate memory st = new int[max_size]; // Fill the allocated memory st constructGcdUtil(arr, 0, n - 1, 0); } // Driver codepublic static void Main(String []args){ int []arr = { 1, 3, 6, 9, 9, 11 }; int n = arr.Length; // Build segment tree from given array constructGcd(arr, n); // Print GCD of values in array from index 1 to 3 Console.WriteLine( getGcd( n, 1, 3) ); // Update: set arr[1] = 10 and update corresponding // segment tree nodes updateValue(arr, n, 1, 10); // Find GCD after the value is updated Console.WriteLine( getGcd( n, 1, 3) );}} // This code contributed by Rajput-Ji <script>// javascript implementation of the approach // segment tree var st; // Recursive function to return gcd of a and b function __gcd(a , b) { if (b == 0) return a; return __gcd(b, a % b); } // A utility function to get the // middle index from corner indexes function getMid(s , e) { return (s + parseInt((e - s) / 2)); } // A recursive function to get the gcd of values in given range // of the array. The following are parameters for this function // st --> Pointer to segment tree // si --> Index of current node in the segment tree. Initially // 0 is passed as root is always at index 0 // ss & se --> Starting and ending indexes of the segment represented // by current node, i.e., st[si] // qs & qe --> Starting and ending indexes of query range function getGcdUtil(ss , se , qs , qe , si) { // If segment of this node is a part of given range // then return the gcd of the segment if (qs <= ss && qe >= se) return st[si]; // If segment of this node is outside the given range if (se < qs || ss > qe) return 0; // If a part of this segment overlaps with the given range var mid = getMid(ss, se); return __gcd(getGcdUtil(ss, mid, qs, qe, 2 * si + 1), getGcdUtil(mid + 1, se, qs, qe, 2 * si + 2)); } // A recursive function to update the nodes which have the given // index in their range. The following are parameters // si, ss and se are same as getSumUtil() // i --> index of the element to be updated. This index is // in the input array. // diff --> Value to be added to all nodes which have i in range function updateValueUtil(ss , se , i , diff , si) { // Base Case: If the input index lies outside the range of // this segment if (i < ss || i > se) return; // If the input index is in range of this node, then update // the value of the node and its children st[si] = st[si] + diff; if (se != ss) { var mid = getMid(ss, se); updateValueUtil(ss, mid, i, diff, 2 * si + 1); updateValueUtil(mid + 1, se, i, diff, 2 * si + 2); } } // The function to update a value in input array and segment tree. // It uses updateValueUtil() to update the value in segment tree function updateValue(arr , n , i , new_val) { // Check for erroneous input index if (i < 0 || i > n - 1) { document.write("Invalid Input"); return; } // Get the difference between new value and old value var diff = new_val - arr[i]; // Update the value in array arr[i] = new_val; // Update the values of nodes in segment tree updateValueUtil(0, n - 1, i, diff, 0); } // Function to return the sum of elements in range // from index qs (query start) to qe (query end) // It mainly uses getSumUtil() function getGcd(n , qs , qe) { // Check for erroneous input values if (qs < 0 || qe > n - 1 || qs > qe) { document.write("Invalid Input"); return -1; } return getGcdUtil(0, n - 1, qs, qe, 0); } // A recursive function that constructs Segment Tree for array[ss..se]. // si is index of current node in segment tree st function constructGcdUtil(arr , ss , se , si) { // If there is one element in array, store it in current node of // segment tree and return if (ss == se) { st[si] = arr[ss]; return arr[ss]; } // If there are more than one element then recur for left and // right subtrees and store the sum of values in this node var mid = getMid(ss, se); st[si] = __gcd(constructGcdUtil(arr, ss, mid, si * 2 + 1), constructGcdUtil(arr, mid + 1, se, si * 2 + 2)); return st[si]; } // Function to construct segment tree from given array. This function // allocates memory for segment tree and calls constructSTUtil() to // fill the allocated memory function constructGcd(arr , n) { // Allocate memory for the segment tree // Height of segment tree var x = parseInt( (Math.ceil(Math.log(n) / Math.log(2)))); // Maximum size of segment tree var max_size = 2 * parseInt( Math.pow(2, x) - 1); // Allocate memory st = Array(max_size).fill(0); // Fill the allocated memory st constructGcdUtil(arr, 0, n - 1, 0); } // Driver code var arr = [ 1, 3, 6, 9, 9, 11 ]; var n = arr.length; // Build segment tree from given array constructGcd(arr, n); // Print GCD of values in array from index 1 to 3 document.write(getGcd(n, 1, 3)+"<br/>"); // Update: set arr[1] = 10 and update corresponding // segment tree nodes updateValue(arr, n, 1, 10); // Find GCD after the value is updated document.write(getGcd(n, 1, 3)); // This code contributed by umadevi9616</script> 3 1 andrew1234 SURENDRA_GANGWAR Rajput-Ji umadevi9616 Kirti_Mangal array-range-queries GCD-LCM Segment-Tree Advanced Data Structure Arrays Tree Arrays Tree Segment-Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Agents in Artificial Intelligence Decision Tree Introduction with example Segment Tree | Set 1 (Sum of given range) AVL Tree | Set 2 (Deletion) Ordered Set and GNU C++ PBDS Arrays in Java Arrays in C/C++ Maximum and minimum of an array using minimum number of comparisons Write a program to reverse an array or string Program for array rotation
[ { "code": null, "e": 26549, "s": 26521, "text": "\n11 Nov, 2021" }, { "code": null, "e": 26627, "s": 26549, "text": "Given an array arr[] of N integers and queries Q. Queries are of two types: " }, { "code": null, "e": 26713, "s": 26627, "text": "Update a given index ind by X.Find the gcd of the elements in the index range [L, R]." }, { "code": null, "e": 26744, "s": 26713, "text": "Update a given index ind by X." }, { "code": null, "e": 26800, "s": 26744, "text": "Find the gcd of the elements in the index range [L, R]." }, { "code": null, "e": 26812, "s": 26800, "text": "Examples: " }, { "code": null, "e": 27100, "s": 26812, "text": "Input: arr[] = {1, 3, 6, 9, 9, 11} Type 2 query: L = 1, R = 3 Type 1 query: ind = 1, X = 10 Type 2 query: L = 1, R = 3 Output: 3 1 Input: arr[] = {1, 2, 4, 9, 3} Type 2 query: L = 1, R = 2 Type 1 query: ind = 2, X = 7 Type 2 query: L = 1, R = 2 Type 2 query: L = 3, R = 4 Output: 2 1 3 " }, { "code": null, "e": 27418, "s": 27102, "text": "Approach: The following problem can be solved using Segment Tree. Segment tree can be used to do preprocessing and query in moderate time. With segment tree, preprocessing time is O(n) and time to for GCD query is O(Logn). The extra space required is O(n) to store the segment tree.Representation of Segment trees " }, { "code": null, "e": 27466, "s": 27418, "text": "Leaf Nodes are the elements of the input array." }, { "code": null, "e": 27524, "s": 27466, "text": "Each internal node represents GCD of all leaves under it." }, { "code": null, "e": 27621, "s": 27524, "text": "Array representation of tree is used to represent Segment Trees i.e., for each node at index i " }, { "code": null, "e": 27650, "s": 27621, "text": "Left child is at index 2*i+1" }, { "code": null, "e": 27708, "s": 27650, "text": "Right child at 2*i+2 and the parent is at floor((i-1)/2)." }, { "code": null, "e": 27756, "s": 27708, "text": "Construction of Segment Tree from given array " }, { "code": null, "e": 28055, "s": 27756, "text": "Begin with a segment arr[0 . . . n-1] and keep dividing into two halves. Every time we divide the current segment into two halves (if it has not yet become a segment of length 1), then call the same procedure on both halves, and for each such segment, we store the GCD value in a segment tree node." }, { "code": null, "e": 28288, "s": 28055, "text": "All levels of the constructed segment tree will be completely filled except the last level. Also, the tree will be a Full Binary Tree (every node has 0 or two children) because we always divide segments in two halves at every level." }, { "code": null, "e": 28433, "s": 28288, "text": "Since the constructed tree is always full binary tree with n leaves, there will be n-1 internal nodes. So total number of nodes will be 2*n – 1." }, { "code": null, "e": 28848, "s": 28433, "text": "Like tree construction and query operations, the update can also be done recursively. We are given an index which needs to be updated. Let diff be the value to be added. We start from root of the segment tree and add diff to all nodes which have given index in their range. If a node doesn’t have given index in its range, we don’t make any changes to that node.Below is the implementation of the above approach: " }, { "code": null, "e": 28852, "s": 28848, "text": "C++" }, { "code": null, "e": 28857, "s": 28852, "text": "Java" }, { "code": null, "e": 28865, "s": 28857, "text": "Python3" }, { "code": null, "e": 28868, "s": 28865, "text": "C#" }, { "code": null, "e": 28879, "s": 28868, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // A utility function to get the// middle index from corner indexesint getMid(int s, int e){ return (s + (e - s) / 2);} // A recursive function to get the gcd of values in given range// of the array. The following are parameters for this function // st --> Pointer to segment tree// si --> Index of current node in the segment tree. Initially// 0 is passed as root is always at index 0// ss & se --> Starting and ending indexes of the segment represented// by current node, i.e., st[si]// qs & qe --> Starting and ending indexes of query rangeint getGcdUtil(int* st, int ss, int se, int qs, int qe, int si){ // If segment of this node is a part of given range // then return the gcd of the segment if (qs <= ss && qe >= se) return st[si]; // If segment of this node is outside the given range if (se < qs || ss > qe) return 0; // If a part of this segment overlaps with the given range int mid = getMid(ss, se); return __gcd(getGcdUtil(st, ss, mid, qs, qe, 2 * si + 1), getGcdUtil(st, mid + 1, se, qs, qe, 2 * si + 2));} // A recursive function to update the nodes which have the given// index in their range. The following are parameters// st, si, ss and se are same as getSumUtil()// i --> index of the element to be updated. This index is// in the input array.// diff --> Value to be added to all nodes which have i in rangevoid updateValueUtil(int* st, int ss, int se, int i, int diff, int si){ // Base Case: If the input index lies outside the range of // this segment if (i < ss || i > se) return; // If the input index is in range of this node, then update // the value of the node and its children st[si] = st[si] + diff; if (se != ss) { int mid = getMid(ss, se); updateValueUtil(st, ss, mid, i, diff, 2 * si + 1); updateValueUtil(st, mid + 1, se, i, diff, 2 * si + 2); }} // The function to update a value in input array and segment tree.// It uses updateValueUtil() to update the value in segment treevoid updateValue(int arr[], int* st, int n, int i, int new_val){ // Check for erroneous input index if (i < 0 || i > n - 1) { cout << \"Invalid Input\"; return; } // Get the difference between new value and old value int diff = new_val - arr[i]; // Update the value in array arr[i] = new_val; // Update the values of nodes in segment tree updateValueUtil(st, 0, n - 1, i, diff, 0);} // Function to return the sum of elements in range// from index qs (query start) to qe (query end)// It mainly uses getSumUtil()int getGcd(int* st, int n, int qs, int qe){ // Check for erroneous input values if (qs < 0 || qe > n - 1 || qs > qe) { cout << \"Invalid Input\"; return -1; } return getGcdUtil(st, 0, n - 1, qs, qe, 0);} // A recursive function that constructs Segment Tree for array[ss..se].// si is index of current node in segment tree stint constructGcdUtil(int arr[], int ss, int se, int* st, int si){ // If there is one element in array, store it in current node of // segment tree and return if (ss == se) { st[si] = arr[ss]; return arr[ss]; } // If there are more than one element then recur for left and // right subtrees and store the sum of values in this node int mid = getMid(ss, se); st[si] = __gcd(constructGcdUtil(arr, ss, mid, st, si * 2 + 1), constructGcdUtil(arr, mid + 1, se, st, si * 2 + 2)); return st[si];} // Function to construct segment tree from given array. This function// allocates memory for segment tree and calls constructSTUtil() to// fill the allocated memoryint* constructGcd(int arr[], int n){ // Allocate memory for the segment tree // Height of segment tree int x = (int)(ceil(log2(n))); // Maximum size of segment tree int max_size = 2 * (int)pow(2, x) - 1; // Allocate memory int* st = new int[max_size]; // Fill the allocated memory st constructGcdUtil(arr, 0, n - 1, st, 0); // Return the constructed segment tree return st;} // Driver codeint main(){ int arr[] = { 1, 3, 6, 9, 9, 11 }; int n = sizeof(arr) / sizeof(arr[0]); // Build segment tree from given array int* st = constructGcd(arr, n); // Print GCD of values in array from index 1 to 3 cout << getGcd(st, n, 1, 3) << endl; // Update: set arr[1] = 10 and update corresponding // segment tree nodes updateValue(arr, st, n, 1, 10); // Find GCD after the value is updated cout << getGcd(st, n, 1, 3) << endl; return 0;}", "e": 33504, "s": 28879, "text": null }, { "code": "// Java implementation of the approachclass GFG{ // segment treestatic int st[]; // Recursive function to return gcd of a and bstatic int __gcd(int a, int b){ if (b == 0) return a; return __gcd(b, a % b); } // A utility function to get the// middle index from corner indexesstatic int getMid(int s, int e){ return (s + (e - s) / 2);} // A recursive function to get the gcd of values in given range// of the array. The following are parameters for this function // st --> Pointer to segment tree// si --> Index of current node in the segment tree. Initially// 0 is passed as root is always at index 0// ss & se --> Starting and ending indexes of the segment represented// by current node, i.e., st[si]// qs & qe --> Starting and ending indexes of query rangestatic int getGcdUtil( int ss, int se, int qs, int qe, int si){ // If segment of this node is a part of given range // then return the gcd of the segment if (qs <= ss && qe >= se) return st[si]; // If segment of this node is outside the given range if (se < qs || ss > qe) return 0; // If a part of this segment overlaps with the given range int mid = getMid(ss, se); return __gcd(getGcdUtil( ss, mid, qs, qe, 2 * si + 1), getGcdUtil( mid + 1, se, qs, qe, 2 * si + 2));} // A recursive function to update the nodes which have the given// index in their range. The following are parameters// si, ss and se are same as getSumUtil()// i --> index of the element to be updated. This index is// in the input array.// diff --> Value to be added to all nodes which have i in rangestatic void updateValueUtil( int ss, int se, int i, int diff, int si){ // Base Case: If the input index lies outside the range of // this segment if (i < ss || i > se) return; // If the input index is in range of this node, then update // the value of the node and its children st[si] = st[si] + diff; if (se != ss) { int mid = getMid(ss, se); updateValueUtil( ss, mid, i, diff, 2 * si + 1); updateValueUtil( mid + 1, se, i, diff, 2 * si + 2); }} // The function to update a value in input array and segment tree.// It uses updateValueUtil() to update the value in segment treestatic void updateValue(int arr[], int n, int i, int new_val){ // Check for erroneous input index if (i < 0 || i > n - 1) { System.out.println(\"Invalid Input\"); return; } // Get the difference between new value and old value int diff = new_val - arr[i]; // Update the value in array arr[i] = new_val; // Update the values of nodes in segment tree updateValueUtil( 0, n - 1, i, diff, 0);} // Function to return the sum of elements in range// from index qs (query start) to qe (query end)// It mainly uses getSumUtil()static int getGcd( int n, int qs, int qe){ // Check for erroneous input values if (qs < 0 || qe > n - 1 || qs > qe) { System.out.println( \"Invalid Input\"); return -1; } return getGcdUtil( 0, n - 1, qs, qe, 0);} // A recursive function that constructs Segment Tree for array[ss..se].// si is index of current node in segment tree ststatic int constructGcdUtil(int arr[], int ss, int se, int si){ // If there is one element in array, store it in current node of // segment tree and return if (ss == se) { st[si] = arr[ss]; return arr[ss]; } // If there are more than one element then recur for left and // right subtrees and store the sum of values in this node int mid = getMid(ss, se); st[si] = __gcd(constructGcdUtil(arr, ss, mid, si * 2 + 1), constructGcdUtil(arr, mid + 1, se, si * 2 + 2)); return st[si];} // Function to construct segment tree from given array. This function// allocates memory for segment tree and calls constructSTUtil() to// fill the allocated memorystatic void constructGcd(int arr[], int n){ // Allocate memory for the segment tree // Height of segment tree int x = (int)(Math.ceil(Math.log(n)/Math.log(2))); // Maximum size of segment tree int max_size = 2 * (int)Math.pow(2, x) - 1; // Allocate memory st = new int[max_size]; // Fill the allocated memory st constructGcdUtil(arr, 0, n - 1, 0); } // Driver codepublic static void main(String args[]){ int arr[] = { 1, 3, 6, 9, 9, 11 }; int n = arr.length; // Build segment tree from given array constructGcd(arr, n); // Print GCD of values in array from index 1 to 3 System.out.println( getGcd( n, 1, 3) ); // Update: set arr[1] = 10 and update corresponding // segment tree nodes updateValue(arr, n, 1, 10); // Find GCD after the value is updated System.out.println( getGcd( n, 1, 3) );}} // This code is constructed by Arnab Kundu", "e": 38275, "s": 33504, "text": null }, { "code": "# Python 3 implementation of the approach from math import gcd,ceil,log2,pow # A utility function to get the# middle index from corner indexesdef getMid(s, e): return (s + int((e - s) / 2)) # A recursive function to get the gcd of values in given range# of the array. The following are parameters for this function # st --> Pointer to segment tree# si --> Index of current node in the segment tree. Initially# 0 is passed as root is always at index 0# ss & se --> Starting and ending indexes of the segment represented# by current node, i.e., st[si]# qs & qe --> Starting and ending indexes of query rangedef getGcdUtil(st,ss,se,qs,qe,si): # If segment of this node is a part of given range # then return the gcd of the segment if (qs <= ss and qe >= se): return st[si] # If segment of this node is outside the given range if (se < qs or ss > qe): return 0 # If a part of this segment overlaps with the given range mid = getMid(ss, se) return gcd(getGcdUtil(st, ss, mid, qs, qe, 2 * si + 1), getGcdUtil(st, mid + 1, se, qs, qe, 2 * si + 2)) # A recursive function to update the nodes which have the given# index in their range. The following are parameters# st, si, ss and se are same as getSumUtil()# i --> index of the element to be updated. This index is# in the input array.# diff --> Value to be added to all nodes which have i in rangedef updateValueUtil(st,ss,se,i,diff,si): # Base Case: If the input index lies outside the range of # this segment if (i < ss or i > se): return # If the input index is in range of this node, then update # the value of the node and its children st[si] = st[si] + diff if (se != ss): mid = getMid(ss, se) updateValueUtil(st, ss, mid, i, diff, 2 * si + 1) updateValueUtil(st, mid + 1, se, i, diff, 2 * si + 2) # The function to update a value in input array and segment tree.# It uses updateValueUtil() to update the value in segment treedef updateValue(arr, st, n, i, new_val): # Check for erroneous input index if (i < 0 or i > n - 1): print(\"Invalid Input\") return # Get the difference between new value and old value diff = new_val - arr[i] # Update the value in array arr[i] = new_val # Update the values of nodes in segment tree updateValueUtil(st, 0, n - 1, i, diff, 0) # Function to return the sum of elements in range# from index qs (query start) to qe (query end)# It mainly uses getSumUtil()def getGcd(st,n,qs,qe): # Check for erroneous input values if (qs < 0 or qe > n - 1 or qs > qe): cout << \"Invalid Input\" return -1 return getGcdUtil(st, 0, n - 1, qs, qe, 0) # A recursive function that constructs Segment Tree for array[ss..se].# si is index of current node in segment tree stdef constructGcdUtil(arr, ss,se, st, si): # If there is one element in array, store it in current node of # segment tree and return if (ss == se): st[si] = arr[ss] return arr[ss] # If there are more than one element then recur for left and # right subtrees and store the sum of values in this node mid = getMid(ss, se) st[si] = gcd(constructGcdUtil(arr, ss, mid, st, si * 2 + 1), constructGcdUtil(arr, mid + 1, se, st, si * 2 + 2)) return st[si] # Function to construct segment tree from given array. This function# allocates memory for segment tree and calls constructSTUtil() to# fill the allocated memorydef constructGcd(arr, n): # Allocate memory for the segment tree # Height of segment tree x = int(ceil(log2(n))) # Maximum size of segment tree max_size = 2 * int(pow(2, x) - 1) # Allocate memory st = [0 for i in range(max_size)] # Fill the allocated memory st constructGcdUtil(arr, 0, n - 1, st, 0) # Return the constructed segment tree return st # Driver codeif __name__ == '__main__': arr = [1, 3, 6, 9, 9, 11] n = len(arr) # Build segment tree from given array st = constructGcd(arr, n) # Print GCD of values in array from index 1 to 3 print(getGcd(st, n, 1, 3)) # Update: set arr[1] = 10 and update corresponding # segment tree nodes updateValue(arr, st, n, 1, 10) # Find GCD after the value is updated print(getGcd(st, n, 1, 3)) # This code is contributed by# SURENDRA_GANGWAR", "e": 42625, "s": 38275, "text": null }, { "code": "// C# implementation of the approach.using System; class GFG{ // segment treestatic int []st; // Recursive function to return gcd of a and bstatic int __gcd(int a, int b){ if (b == 0) return a; return __gcd(b, a % b); } // A utility function to get the// middle index from corner indexesstatic int getMid(int s, int e){ return (s + (e - s) / 2);} // A recursive function to get the gcd of values in given range// of the array. The following are parameters for this function // st --> Pointer to segment tree// si --> Index of current node in the segment tree. Initially// 0 is passed as root is always at index 0// ss & se --> Starting and ending indexes of the segment represented// by current node, i.e., st[si]// qs & qe --> Starting and ending indexes of query rangestatic int getGcdUtil( int ss, int se, int qs, int qe, int si){ // If segment of this node is a part of given range // then return the gcd of the segment if (qs <= ss && qe >= se) return st[si]; // If segment of this node is outside the given range if (se < qs || ss > qe) return 0; // If a part of this segment overlaps with the given range int mid = getMid(ss, se); return __gcd(getGcdUtil( ss, mid, qs, qe, 2 * si + 1), getGcdUtil( mid + 1, se, qs, qe, 2 * si + 2));} // A recursive function to update the nodes which have the given// index in their range. The following are parameters// si, ss and se are same as getSumUtil()// i --> index of the element to be updated. This index is// in the input array.// diff --> Value to be added to all nodes which have i in rangestatic void updateValueUtil( int ss, int se, int i, int diff, int si){ // Base Case: If the input index lies outside the range of // this segment if (i < ss || i > se) return; // If the input index is in range of this node, then update // the value of the node and its children st[si] = st[si] + diff; if (se != ss) { int mid = getMid(ss, se); updateValueUtil( ss, mid, i, diff, 2 * si + 1); updateValueUtil( mid + 1, se, i, diff, 2 * si + 2); }} // The function to update a value in input array and segment tree.// It uses updateValueUtil() to update the value in segment treestatic void updateValue(int []arr, int n, int i, int new_val){ // Check for erroneous input index if (i < 0 || i > n - 1) { Console.WriteLine(\"Invalid Input\"); return; } // Get the difference between new value and old value int diff = new_val - arr[i]; // Update the value in array arr[i] = new_val; // Update the values of nodes in segment tree updateValueUtil( 0, n - 1, i, diff, 0);} // Function to return the sum of elements in range// from index qs (query start) to qe (query end)// It mainly uses getSumUtil()static int getGcd( int n, int qs, int qe){ // Check for erroneous input values if (qs < 0 || qe > n - 1 || qs > qe) { Console.WriteLine( \"Invalid Input\"); return -1; } return getGcdUtil( 0, n - 1, qs, qe, 0);} // A recursive function that constructs Segment Tree for array[ss..se].// si is index of current node in segment tree ststatic int constructGcdUtil(int []arr, int ss, int se, int si){ // If there is one element in array, store it in current node of // segment tree and return if (ss == se) { st[si] = arr[ss]; return arr[ss]; } // If there are more than one element then recur for left and // right subtrees and store the sum of values in this node int mid = getMid(ss, se); st[si] = __gcd(constructGcdUtil(arr, ss, mid, si * 2 + 1), constructGcdUtil(arr, mid + 1, se, si * 2 + 2)); return st[si];} // Function to construct segment tree from given array. This function// allocates memory for segment tree and calls constructSTUtil() to// fill the allocated memorystatic void constructGcd(int []arr, int n){ // Allocate memory for the segment tree // Height of segment tree int x = (int)(Math.Ceiling(Math.Log(n)/Math.Log(2))); // Maximum size of segment tree int max_size = 2 * (int)Math.Pow(2, x) - 1; // Allocate memory st = new int[max_size]; // Fill the allocated memory st constructGcdUtil(arr, 0, n - 1, 0); } // Driver codepublic static void Main(String []args){ int []arr = { 1, 3, 6, 9, 9, 11 }; int n = arr.Length; // Build segment tree from given array constructGcd(arr, n); // Print GCD of values in array from index 1 to 3 Console.WriteLine( getGcd( n, 1, 3) ); // Update: set arr[1] = 10 and update corresponding // segment tree nodes updateValue(arr, n, 1, 10); // Find GCD after the value is updated Console.WriteLine( getGcd( n, 1, 3) );}} // This code contributed by Rajput-Ji", "e": 47407, "s": 42625, "text": null }, { "code": "<script>// javascript implementation of the approach // segment tree var st; // Recursive function to return gcd of a and b function __gcd(a , b) { if (b == 0) return a; return __gcd(b, a % b); } // A utility function to get the // middle index from corner indexes function getMid(s , e) { return (s + parseInt((e - s) / 2)); } // A recursive function to get the gcd of values in given range // of the array. The following are parameters for this function // st --> Pointer to segment tree // si --> Index of current node in the segment tree. Initially // 0 is passed as root is always at index 0 // ss & se --> Starting and ending indexes of the segment represented // by current node, i.e., st[si] // qs & qe --> Starting and ending indexes of query range function getGcdUtil(ss , se , qs , qe , si) { // If segment of this node is a part of given range // then return the gcd of the segment if (qs <= ss && qe >= se) return st[si]; // If segment of this node is outside the given range if (se < qs || ss > qe) return 0; // If a part of this segment overlaps with the given range var mid = getMid(ss, se); return __gcd(getGcdUtil(ss, mid, qs, qe, 2 * si + 1), getGcdUtil(mid + 1, se, qs, qe, 2 * si + 2)); } // A recursive function to update the nodes which have the given // index in their range. The following are parameters // si, ss and se are same as getSumUtil() // i --> index of the element to be updated. This index is // in the input array. // diff --> Value to be added to all nodes which have i in range function updateValueUtil(ss , se , i , diff , si) { // Base Case: If the input index lies outside the range of // this segment if (i < ss || i > se) return; // If the input index is in range of this node, then update // the value of the node and its children st[si] = st[si] + diff; if (se != ss) { var mid = getMid(ss, se); updateValueUtil(ss, mid, i, diff, 2 * si + 1); updateValueUtil(mid + 1, se, i, diff, 2 * si + 2); } } // The function to update a value in input array and segment tree. // It uses updateValueUtil() to update the value in segment tree function updateValue(arr , n , i , new_val) { // Check for erroneous input index if (i < 0 || i > n - 1) { document.write(\"Invalid Input\"); return; } // Get the difference between new value and old value var diff = new_val - arr[i]; // Update the value in array arr[i] = new_val; // Update the values of nodes in segment tree updateValueUtil(0, n - 1, i, diff, 0); } // Function to return the sum of elements in range // from index qs (query start) to qe (query end) // It mainly uses getSumUtil() function getGcd(n , qs , qe) { // Check for erroneous input values if (qs < 0 || qe > n - 1 || qs > qe) { document.write(\"Invalid Input\"); return -1; } return getGcdUtil(0, n - 1, qs, qe, 0); } // A recursive function that constructs Segment Tree for array[ss..se]. // si is index of current node in segment tree st function constructGcdUtil(arr , ss , se , si) { // If there is one element in array, store it in current node of // segment tree and return if (ss == se) { st[si] = arr[ss]; return arr[ss]; } // If there are more than one element then recur for left and // right subtrees and store the sum of values in this node var mid = getMid(ss, se); st[si] = __gcd(constructGcdUtil(arr, ss, mid, si * 2 + 1), constructGcdUtil(arr, mid + 1, se, si * 2 + 2)); return st[si]; } // Function to construct segment tree from given array. This function // allocates memory for segment tree and calls constructSTUtil() to // fill the allocated memory function constructGcd(arr , n) { // Allocate memory for the segment tree // Height of segment tree var x = parseInt( (Math.ceil(Math.log(n) / Math.log(2)))); // Maximum size of segment tree var max_size = 2 * parseInt( Math.pow(2, x) - 1); // Allocate memory st = Array(max_size).fill(0); // Fill the allocated memory st constructGcdUtil(arr, 0, n - 1, 0); } // Driver code var arr = [ 1, 3, 6, 9, 9, 11 ]; var n = arr.length; // Build segment tree from given array constructGcd(arr, n); // Print GCD of values in array from index 1 to 3 document.write(getGcd(n, 1, 3)+\"<br/>\"); // Update: set arr[1] = 10 and update corresponding // segment tree nodes updateValue(arr, n, 1, 10); // Find GCD after the value is updated document.write(getGcd(n, 1, 3)); // This code contributed by umadevi9616</script>", "e": 52474, "s": 47407, "text": null }, { "code": null, "e": 52478, "s": 52474, "text": "3\n1" }, { "code": null, "e": 52491, "s": 52480, "text": "andrew1234" }, { "code": null, "e": 52508, "s": 52491, "text": "SURENDRA_GANGWAR" }, { "code": null, "e": 52518, "s": 52508, "text": "Rajput-Ji" }, { "code": null, "e": 52530, "s": 52518, "text": "umadevi9616" }, { "code": null, "e": 52543, "s": 52530, "text": "Kirti_Mangal" }, { "code": null, "e": 52563, "s": 52543, "text": "array-range-queries" }, { "code": null, "e": 52571, "s": 52563, "text": "GCD-LCM" }, { "code": null, "e": 52584, "s": 52571, "text": "Segment-Tree" }, { "code": null, "e": 52608, "s": 52584, "text": "Advanced Data Structure" }, { "code": null, "e": 52615, "s": 52608, "text": "Arrays" }, { "code": null, "e": 52620, "s": 52615, "text": "Tree" }, { "code": null, "e": 52627, "s": 52620, "text": "Arrays" }, { "code": null, "e": 52632, "s": 52627, "text": "Tree" }, { "code": null, "e": 52645, "s": 52632, "text": "Segment-Tree" }, { "code": null, "e": 52743, "s": 52645, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 52777, "s": 52743, "text": "Agents in Artificial Intelligence" }, { "code": null, "e": 52817, "s": 52777, "text": "Decision Tree Introduction with example" }, { "code": null, "e": 52859, "s": 52817, "text": "Segment Tree | Set 1 (Sum of given range)" }, { "code": null, "e": 52887, "s": 52859, "text": "AVL Tree | Set 2 (Deletion)" }, { "code": null, "e": 52916, "s": 52887, "text": "Ordered Set and GNU C++ PBDS" }, { "code": null, "e": 52931, "s": 52916, "text": "Arrays in Java" }, { "code": null, "e": 52947, "s": 52931, "text": "Arrays in C/C++" }, { "code": null, "e": 53015, "s": 52947, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 53061, "s": 53015, "text": "Write a program to reverse an array or string" } ]
Python - tensorflow.boolean_mask() method - GeeksforGeeks
25 Aug, 2021 TensorFlow is open-source Python library designed by Google to develop Machine Learning models and deep learning neural networks. boolean_mask() is method used to apply boolean mask to a Tensor. Syntax: tensorflow.boolean_mask(tensor, mask, axis, name) Parameters: tensor: It’s a N-dimensional input tensor. mask: It’s a boolean tensor with k-dimensions where k<=N and k is know statically. axis: It’s a 0-dimensional tensor which represents the axis from which mask should be applied. Default value for axis is zero and k+axis<=N. name: It’s an optional parameter that defines the name for the operation. Return: It returns (N-K+1)-dimensional tensor which have the values that are populated against the True values in mask. Example 1: In this example input is 1-D. Python3 # importing the libraryimport tensorflow as tf # initializing the inputstensor = [1,2,3]mask = [False, True, True] # printing the inputprint('Tensor: ',tensor)print('Mask: ',mask) # applying the maskresult = tf.boolean_mask(tensor, mask) # printing the resultprint('Result: ',result) Output: Tensor: [1, 2, 3] Mask: [False, True, True] Result: tf.Tensor([2 3], shape=(2,), dtype=int32) Example 2: In this example 2-D input is taken. Python3 # importing the libraryimport tensorflow as tf # initializing the inputstensor = [[1, 2], [10, 14], [9, 7]]mask = [False, True, True] # printing the inputprint('Tensor: ',tensor)print('Mask: ',mask) # applying the maskresult = tf.boolean_mask(tensor, mask) # printing the resultprint('Result: ',result) Output: Tensor: [[1, 2], [10, 14], [9, 7]] Mask: [False, True, True] Result: tf.Tensor( [[10 14] [ 9 7]], shape=(2, 2), dtype=int32) clintra Python-Tensorflow 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? Python Classes and Objects How to drop one or multiple columns in Pandas Dataframe Defaultdict in Python Python | Get unique values from a list Python | os.path.join() method Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n25 Aug, 2021" }, { "code": null, "e": 25733, "s": 25537, "text": "TensorFlow is open-source Python library designed by Google to develop Machine Learning models and deep learning neural networks. boolean_mask() is method used to apply boolean mask to a Tensor." }, { "code": null, "e": 25791, "s": 25733, "text": "Syntax: tensorflow.boolean_mask(tensor, mask, axis, name)" }, { "code": null, "e": 25803, "s": 25791, "text": "Parameters:" }, { "code": null, "e": 25846, "s": 25803, "text": "tensor: It’s a N-dimensional input tensor." }, { "code": null, "e": 25930, "s": 25846, "text": "mask: It’s a boolean tensor with k-dimensions where k<=N and k is know statically." }, { "code": null, "e": 26071, "s": 25930, "text": "axis: It’s a 0-dimensional tensor which represents the axis from which mask should be applied. Default value for axis is zero and k+axis<=N." }, { "code": null, "e": 26145, "s": 26071, "text": "name: It’s an optional parameter that defines the name for the operation." }, { "code": null, "e": 26267, "s": 26145, "text": "Return: It returns (N-K+1)-dimensional tensor which have the values that are populated against the True values in mask. " }, { "code": null, "e": 26308, "s": 26267, "text": "Example 1: In this example input is 1-D." }, { "code": null, "e": 26316, "s": 26308, "text": "Python3" }, { "code": "# importing the libraryimport tensorflow as tf # initializing the inputstensor = [1,2,3]mask = [False, True, True] # printing the inputprint('Tensor: ',tensor)print('Mask: ',mask) # applying the maskresult = tf.boolean_mask(tensor, mask) # printing the resultprint('Result: ',result)", "e": 26600, "s": 26316, "text": null }, { "code": null, "e": 26608, "s": 26600, "text": "Output:" }, { "code": null, "e": 26705, "s": 26608, "text": "Tensor: [1, 2, 3]\nMask: [False, True, True]\nResult: tf.Tensor([2 3], shape=(2,), dtype=int32)" }, { "code": null, "e": 26752, "s": 26705, "text": "Example 2: In this example 2-D input is taken." }, { "code": null, "e": 26760, "s": 26752, "text": "Python3" }, { "code": "# importing the libraryimport tensorflow as tf # initializing the inputstensor = [[1, 2], [10, 14], [9, 7]]mask = [False, True, True] # printing the inputprint('Tensor: ',tensor)print('Mask: ',mask) # applying the maskresult = tf.boolean_mask(tensor, mask) # printing the resultprint('Result: ',result)", "e": 27063, "s": 26760, "text": null }, { "code": null, "e": 27071, "s": 27063, "text": "Output:" }, { "code": null, "e": 27201, "s": 27071, "text": "Tensor: [[1, 2], [10, 14], [9, 7]]\nMask: [False, True, True]\nResult: tf.Tensor(\n[[10 14]\n [ 9 7]], shape=(2, 2), dtype=int32)" }, { "code": null, "e": 27209, "s": 27201, "text": "clintra" }, { "code": null, "e": 27227, "s": 27209, "text": "Python-Tensorflow" }, { "code": null, "e": 27234, "s": 27227, "text": "Python" }, { "code": null, "e": 27332, "s": 27234, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27364, "s": 27332, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27406, "s": 27364, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27448, "s": 27406, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27475, "s": 27448, "text": "Python Classes and Objects" }, { "code": null, "e": 27531, "s": 27475, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27553, "s": 27531, "text": "Defaultdict in Python" }, { "code": null, "e": 27592, "s": 27553, "text": "Python | Get unique values from a list" }, { "code": null, "e": 27623, "s": 27592, "text": "Python | os.path.join() method" }, { "code": null, "e": 27652, "s": 27623, "text": "Create a directory in Python" } ]
Implement Interface in Kotlin - GeeksforGeeks
13 Jan, 2022 Interfaces in Kotlin can contain declarations of abstract methods, as well as method implementations. What makes them different from abstract classes is that interfaces cannot store a state. They can have properties, but these need to be abstract or provide accessor implementations. A Kotlin interface contains declarations of abstract methods, and default method implementations although they cannot store state. interface MyInterface { fun bar() } This interface can now be implemented by a class as follows: class Child : MyInterface { override fun bar() { print("bar() was called") } } An interface in Kotlin can have default implementations for functions: interface MyInterface { fun withImplementation() { print("withImplementation() was called") } } Classes implementing such interfaces will be able to use those functions without reimplementing class MyClass: MyInterface { // No need to reimplement here } val instance = MyClass() instance.withImplementation() Default implementations also work for property getters and setters: interface MyInterface2 { val helloWorld get() = "Hello World!" } Interface accessors implementations can’t use backing fields interface MyInterface3 { // this property won't compile! var helloWorld: Int get() = field set(value) { field = value } } When multiple interfaces implement the same function, or all of them define with one or more implementing, the derived class needs to manually resolve proper call Kotlin interface A { fun notImplemented() fun implementedOnlyInA() { print("only A") } fun implementedInBoth() { print("both, A") } fun implementedInOne() { print("implemented in A") }} interface B { fun implementedInBoth() { print("both, B") } // only defined fun implementedInOne() } class MyClass: A, B { override fun notImplemented() { print("Normal implementation") } // implementedOnlyInA() can by normally used in instances // class needs to define how to use interface functions override fun implementedInBoth() { super<B>.implementedInBoth() super<A>.implementedInBoth() } // even if there's only one implementation,// there multiple definitionsoverride fun implementedInOne() { super<A>.implementedInOne() print("implementedInOne class implementation") }} You can declare properties in interfaces. Since an interface cannot have stated you can only declare a property as abstract or by providing default implementation for the accessors. Kotlin interface MyInterface { // abstract val property: Int val propertyWithImplementation: String get() = "foo" fun foo() { print(property) }} class Child : MyInterface { override val property: Int = 29} When implementing more than one interface that has methods of the same name that include default implementations, it is ambiguous to the compiler which implementation should be used. In the case of a conflict, the developer must override the conflicting method and provide a custom implementation. That implementation may choose to delegate to the default implementations or not. Kotlin interface FirstTrait { fun foo() { print("first") } fun bar()} interface SecondTrait { fun foo() { print("second") } fun bar() { print("bar") }} class ClassWithConflict : FirstTrait, SecondTrait { override fun foo() { // delegate to the default // implementation of FirstTrait super<FirstTrait>.foo() // delegate to the default // implementation of SecondTrait super<SecondTrait>.foo() } // function bar() only has a default implementation // in one interface and therefore is ok.} interface MyInterface { fun funcOne() { // optional body print("Function with default implementation") } } Note: If the method in the interface has its own default implementation, we can use the super keyword to access it. super.funcOne() Kotlin OOPs Kotlin Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Retrofit with Kotlin Coroutine in Android How to Get Current Location in Android? ImageView in Android with Example How to Build a Weather App in Android? Android SQLite Database in Kotlin ScrollView in Android Suspend Function In Kotlin Coroutines Kotlin Coroutines on Android How to Use View Binding in RecyclerView Adapter Class in Android? Notifications in Android with Example
[ { "code": null, "e": 25763, "s": 25735, "text": "\n13 Jan, 2022" }, { "code": null, "e": 26047, "s": 25763, "text": "Interfaces in Kotlin can contain declarations of abstract methods, as well as method implementations. What makes them different from abstract classes is that interfaces cannot store a state. They can have properties, but these need to be abstract or provide accessor implementations." }, { "code": null, "e": 26178, "s": 26047, "text": "A Kotlin interface contains declarations of abstract methods, and default method implementations although they cannot store state." }, { "code": null, "e": 26218, "s": 26178, "text": "interface MyInterface {\n fun bar()\n}" }, { "code": null, "e": 26279, "s": 26218, "text": "This interface can now be implemented by a class as follows:" }, { "code": null, "e": 26374, "s": 26279, "text": "class Child : MyInterface {\n override fun bar() {\n print(\"bar() was called\")\n }\n}" }, { "code": null, "e": 26445, "s": 26374, "text": "An interface in Kotlin can have default implementations for functions:" }, { "code": null, "e": 26557, "s": 26445, "text": "interface MyInterface {\n fun withImplementation() {\n print(\"withImplementation() was called\")\n }\n}" }, { "code": null, "e": 26653, "s": 26557, "text": "Classes implementing such interfaces will be able to use those functions without reimplementing" }, { "code": null, "e": 26782, "s": 26653, "text": "class MyClass: MyInterface {\n // No need to reimplement here\n}\n val instance = MyClass()\n instance.withImplementation()" }, { "code": null, "e": 26850, "s": 26782, "text": "Default implementations also work for property getters and setters:" }, { "code": null, "e": 26917, "s": 26850, "text": "interface MyInterface2 {\n val helloWorld\n get() = \"Hello World!\"\n}" }, { "code": null, "e": 26978, "s": 26917, "text": "Interface accessors implementations can’t use backing fields" }, { "code": null, "e": 27116, "s": 26978, "text": "interface MyInterface3 {\n // this property won't compile!\n var helloWorld: Int\n get() = field\n set(value) { field = value }\n}" }, { "code": null, "e": 27279, "s": 27116, "text": "When multiple interfaces implement the same function, or all of them define with one or more implementing, the derived class needs to manually resolve proper call" }, { "code": null, "e": 27286, "s": 27279, "text": "Kotlin" }, { "code": "interface A { fun notImplemented() fun implementedOnlyInA() { print(\"only A\") } fun implementedInBoth() { print(\"both, A\") } fun implementedInOne() { print(\"implemented in A\") }} interface B { fun implementedInBoth() { print(\"both, B\") } // only defined fun implementedInOne() } class MyClass: A, B { override fun notImplemented() { print(\"Normal implementation\") } // implementedOnlyInA() can by normally used in instances // class needs to define how to use interface functions override fun implementedInBoth() { super<B>.implementedInBoth() super<A>.implementedInBoth() } // even if there's only one implementation,// there multiple definitionsoverride fun implementedInOne() { super<A>.implementedInOne() print(\"implementedInOne class implementation\") }}", "e": 28081, "s": 27286, "text": null }, { "code": null, "e": 28263, "s": 28081, "text": "You can declare properties in interfaces. Since an interface cannot have stated you can only declare a property as abstract or by providing default implementation for the accessors." }, { "code": null, "e": 28270, "s": 28263, "text": "Kotlin" }, { "code": "interface MyInterface { // abstract val property: Int val propertyWithImplementation: String get() = \"foo\" fun foo() { print(property) }} class Child : MyInterface { override val property: Int = 29}", "e": 28485, "s": 28270, "text": null }, { "code": null, "e": 28865, "s": 28485, "text": "When implementing more than one interface that has methods of the same name that include default implementations, it is ambiguous to the compiler which implementation should be used. In the case of a conflict, the developer must override the conflicting method and provide a custom implementation. That implementation may choose to delegate to the default implementations or not." }, { "code": null, "e": 28872, "s": 28865, "text": "Kotlin" }, { "code": "interface FirstTrait { fun foo() { print(\"first\") } fun bar()} interface SecondTrait { fun foo() { print(\"second\") } fun bar() { print(\"bar\") }} class ClassWithConflict : FirstTrait, SecondTrait { override fun foo() { // delegate to the default // implementation of FirstTrait super<FirstTrait>.foo() // delegate to the default // implementation of SecondTrait super<SecondTrait>.foo() } // function bar() only has a default implementation // in one interface and therefore is ok.}", "e": 29383, "s": 28872, "text": null }, { "code": null, "e": 29502, "s": 29383, "text": "interface MyInterface {\n fun funcOne() {\n // optional body\n print(\"Function with default implementation\")\n }\n}" }, { "code": null, "e": 29508, "s": 29502, "text": "Note:" }, { "code": null, "e": 29618, "s": 29508, "text": "If the method in the interface has its own default implementation, we can use the super keyword to access it." }, { "code": null, "e": 29634, "s": 29618, "text": "super.funcOne()" }, { "code": null, "e": 29646, "s": 29634, "text": "Kotlin OOPs" }, { "code": null, "e": 29653, "s": 29646, "text": "Kotlin" }, { "code": null, "e": 29751, "s": 29653, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29793, "s": 29751, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 29833, "s": 29793, "text": "How to Get Current Location in Android?" }, { "code": null, "e": 29867, "s": 29833, "text": "ImageView in Android with Example" }, { "code": null, "e": 29906, "s": 29867, "text": "How to Build a Weather App in Android?" }, { "code": null, "e": 29940, "s": 29906, "text": "Android SQLite Database in Kotlin" }, { "code": null, "e": 29962, "s": 29940, "text": "ScrollView in Android" }, { "code": null, "e": 30000, "s": 29962, "text": "Suspend Function In Kotlin Coroutines" }, { "code": null, "e": 30029, "s": 30000, "text": "Kotlin Coroutines on Android" }, { "code": null, "e": 30095, "s": 30029, "text": "How to Use View Binding in RecyclerView Adapter Class in Android?" } ]
Minimum cost to convert a string to another by replacing blanks - GeeksforGeeks
15 Feb, 2022 Given two strings s1 and s2 with lower-case alphabets having length N. The strings s1 and s2 initially may contain some blanks, the task is to find minimum operations to convert a string s1 to s2. Initially, if there are any blanks they should be replaced by any same character which cost 0 and Any vowel in the string can be replaced by any consonant and any consonant can be replaced by any vowel which costs 1. Examples: Input: s1 = “g_e_s”, s2 = “ge_ks”Output: 1Explanation: Replacing blanks with ‘e’, the strings become s1= “geees”, s2 = “geeks”In the 3rd index of s1 convert e -> k which costs only 1 operation. Input: s1 = “abcd”, s2 = “aeca”Output: 2 Approach: Since there are only 26 lower case characters if there are blanks in the strings the blanks can be replaced by each of these characters and minimum cost can be counted to convert string s1 to s2. If both the characters of the string one is a vowel and the other is consonant or vice versa it costs only one unit to transform one character. If both the characters are vowels or consonants and are not equal then it bears cost of 2; consonant -> vowel -> consonant (cost = 2) or vowel -> consonant -> vowel (cost = 2). Follow these steps to solve the above problem: If both the lengths of the strings are not equal return -1. Initialize n with the length and res as INT_MAX. Now iterate through each of the 26 characters. Initialize the variable ops = 0 to store the costs required. Traverse from the range [0, n) and check if there is a blank in any of the strings. If there is a blank initialize the chars c1 and c2 to store the modified characters. If both the chars c1 == c2 (the character after replacing the blank) no operations are required. Else if both are vowels or consonants it requires 2 operations else it requires only 1 operation add it to the ops variable. After the traversal store the minimum operations in the res (min(ops, res)). Print the result res. 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 check whether// a character is vowel or notbool isVowel(char c){ return (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u');} // Function to calculate minimum costvoid minCost(string s1, string s2){ // If both the lengths are not equal if (s1.length() != s2.length()) { cout << -1 << endl; return; } int n = s1.length(); // Initialize res with max value int res = INT_MAX; // Iterate through every character // and check the minimum cost by // replacing the blank by all letters for (char c = 'a'; c <= 'z'; c++) { // Initialize ops to check // the cost required by replacing // each char c int ops = 0; for (int i = 0; i < n; i++) { // If it is blank replace with c char c1 = s1[i] == '_' ? c : s1[i]; char c2 = s2[i] == '_' ? c : s2[i]; // If both are equal no ops required if (c1 == c2) continue; else { // If both are vowels or consonants // it requires cost as two // vowel->consonant ->vowel // and vice versa // Else 1 operation ops = ops + (isVowel(s1[i]) != isVowel(s2[i]) ? 2 : 1); } } // Take the minimum if (ops < res) { res = ops; } } // Print the result cout << res << endl;} // Driver codeint main(){ // Initialize the strings string s1 = "g_e_s", s2 = "ge_ks"; // Function call minCost(s1, s2); return 0;} // Java program for the above approachimport java.util.*;public class GFG{ // Function to check whether // a character is vowel or not static boolean isVowel(char c) { return (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u'); } // Function to calculate minimum cost static void minCost(String s1, String s2) { // If both the lengths are not equal if (s1.length() != s2.length()) { System.out.println(-1); return; } int n = s1.length(); // Initialize res with max value int res = Integer.MAX_VALUE; // Iterate through every character // and check the minimum cost by // replacing the blank by all letters for (char c = 'a'; c <= 'z'; c++) { // Initialize ops to check // the cost required by replacing // each char c int ops = 0; for (int i = 0; i < n; i++) { // If it is blank replace with c char c1 = s1.charAt(i) == '_' ? c : s1.charAt(i); char c2 = s2.charAt(i) == '_' ? c : s2.charAt(i); // If both are equal no ops required if (c1 == c2) continue; else { // If both are vowels or consonants // it requires cost as two // vowel->consonant ->vowel // and vice versa // Else 1 operation ops = ops + (isVowel(s1.charAt(i)) != isVowel(s2.charAt(i)) ? 2 : 1); } } // Take the minimum if (ops < res) { res = ops; } } // Print the result System.out.println(res); } // Driver code public static void main(String args[]) { // Initialize the strings String s1 = "g_e_s", s2 = "ge_ks"; // Function call minCost(s1, s2); }} // This code is contributed by Samim Hossain Mondal. # Python 3 program for the above approachimport sys # Function to check whether# a character is vowel or notdef isVowel(c): return (c == 'a' or c == 'e' or c == 'i' or c == 'o' or c == 'u') # Function to calculate minimum costdef minCost(s1, s2): # If both the lengths are not equal if (len(s1) != len(s2)): print(-1) return n = len(s1) # Initialize res with max value res = sys.maxsize # Iterate through every character # and check the minimum cost by # replacing the blank by all letters for c in range(ord('a'), ord('z')+1): # Initialize ops to check # the cost required by replacing # each char c ops = 0 for i in range(n): # If it is blank replace with c if s1[i] == '_': c1 = chr(c) else: c1 = s1[i] if s2[i] == '_': c2 = chr(c) else: c2 = s2[i] # If both are equal no ops required if (c1 == c2): continue else: # If both are vowels or consonants # it requires cost as two # vowel->consonant ->vowel # and vice versa # Else 1 operation if isVowel(s1[i]) != isVowel(s2[i]): ops += 2 else: ops += 1 # Take the minimum if (ops < res): res = ops # Print the result print(res) # Driver codeif __name__ == "__main__": # Initialize the strings s1 = "g_e_s" s2 = "ge_ks" # Function call minCost(s1, s2) # This code is contributed by ukasp. // C# program for the above approachusing System;class GFG{ // Function to check whether // a character is vowel or not static bool isVowel(char c) { return (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u'); } // Function to calculate minimum cost static void minCost(string s1, string s2) { // If both the lengths are not equal if (s1.Length != s2.Length) { Console.WriteLine(-1); return; } int n = s1.Length; // Initialize res with max value int res = Int32.MaxValue; // Iterate through every character // and check the minimum cost by // replacing the blank by all letters for (char c = 'a'; c <= 'z'; c++) { // Initialize ops to check // the cost required by replacing // each char c int ops = 0; for (int i = 0; i < n; i++) { // If it is blank replace with c char c1 = s1[i] == '_' ? c : s1[i]; char c2 = s2[i] == '_' ? c : s2[i]; // If both are equal no ops required if (c1 == c2) continue; else { // If both are vowels or consonants // it requires cost as two // vowel->consonant ->vowel // and vice versa // Else 1 operation ops = ops + (isVowel(s1[i]) != isVowel(s2[i]) ? 2 : 1); } } // Take the minimum if (ops < res) { res = ops; } } // Print the result Console.WriteLine(res); } // Driver code public static void Main() { // Initialize the strings string s1 = "g_e_s", s2 = "ge_ks"; // Function call minCost(s1, s2); }} // This code is contributed by Samim Hossain Mondal. <script>// Javascript program for the above approach // Function to check whether// a character is vowel or notfunction isVowel(c){ return (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u');} // Function to calculate minimum costfunction minCost(s1, s2){ // If both the lengths are not equal if (s1.length != s2.length) { document.write(-1); return; } let n = s1.length; // Initialize res with max value let res = Number. MAX_SAFE_INTEGER; // Iterate through every character // and check the minimum cost by // replacing the blank by all letters let c = 'a'; for (let j = 0; j < 26; j++) { // Initialize ops to check // the cost required by replacing // each char c let ops = 0; for (let i = 0; i < n; i++) { // If it is blank replace with c let c1 = s1[i] == '_' ? c : s1[i]; let c2 = s2[i] == '_' ? c : s2[i]; // If both are equal no ops required if (c1 == c2) continue; else { // If both are vowels or consonants // it requires cost as two // vowel->consonant ->vowel // and vice versa // Else 1 operation ops = ops + (isVowel(s1[i]) != isVowel(s2[i]) ? 2 : 1); } } c = String.fromCharCode(c.charCodeAt(0) + 1); // Take the minimum if (ops < res) { res = ops; } } // Print the result document.write(res);} // Driver code // Initialize the stringslet s1 = "g_e_s";let s2 = "ge_ks"; // Function callminCost(s1, s2); // This code is contributed by Samim Hossain Mondal.</script> 1 Time Complexity: O(26* N)Space Complexity: O(1) samim2000 ukasp simmytarika5 Algo-Geek 2021 Algo Geek Strings Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Check if the given string is valid English word or not Sort strings on the basis of their numeric part Divide given number into two even parts Bit Manipulation technique to replace boolean arrays of fixed size less than 64 Count of Palindrome Strings in given Array of strings 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 Longest Common Subsequence | DP-4
[ { "code": null, "e": 27431, "s": 27403, "text": "\n15 Feb, 2022" }, { "code": null, "e": 27629, "s": 27431, "text": "Given two strings s1 and s2 with lower-case alphabets having length N. The strings s1 and s2 initially may contain some blanks, the task is to find minimum operations to convert a string s1 to s2. " }, { "code": null, "e": 27727, "s": 27629, "text": "Initially, if there are any blanks they should be replaced by any same character which cost 0 and" }, { "code": null, "e": 27846, "s": 27727, "text": "Any vowel in the string can be replaced by any consonant and any consonant can be replaced by any vowel which costs 1." }, { "code": null, "e": 27857, "s": 27846, "text": "Examples: " }, { "code": null, "e": 28053, "s": 27857, "text": "Input: s1 = “g_e_s”, s2 = “ge_ks”Output: 1Explanation: Replacing blanks with ‘e’, the strings become s1= “geees”, s2 = “geeks”In the 3rd index of s1 convert e -> k which costs only 1 operation. " }, { "code": null, "e": 28094, "s": 28053, "text": "Input: s1 = “abcd”, s2 = “aeca”Output: 2" }, { "code": null, "e": 28668, "s": 28094, "text": "Approach: Since there are only 26 lower case characters if there are blanks in the strings the blanks can be replaced by each of these characters and minimum cost can be counted to convert string s1 to s2. If both the characters of the string one is a vowel and the other is consonant or vice versa it costs only one unit to transform one character. If both the characters are vowels or consonants and are not equal then it bears cost of 2; consonant -> vowel -> consonant (cost = 2) or vowel -> consonant -> vowel (cost = 2). Follow these steps to solve the above problem:" }, { "code": null, "e": 28728, "s": 28668, "text": "If both the lengths of the strings are not equal return -1." }, { "code": null, "e": 28777, "s": 28728, "text": "Initialize n with the length and res as INT_MAX." }, { "code": null, "e": 28824, "s": 28777, "text": "Now iterate through each of the 26 characters." }, { "code": null, "e": 28885, "s": 28824, "text": "Initialize the variable ops = 0 to store the costs required." }, { "code": null, "e": 28969, "s": 28885, "text": "Traverse from the range [0, n) and check if there is a blank in any of the strings." }, { "code": null, "e": 29054, "s": 28969, "text": "If there is a blank initialize the chars c1 and c2 to store the modified characters." }, { "code": null, "e": 29151, "s": 29054, "text": "If both the chars c1 == c2 (the character after replacing the blank) no operations are required." }, { "code": null, "e": 29276, "s": 29151, "text": "Else if both are vowels or consonants it requires 2 operations else it requires only 1 operation add it to the ops variable." }, { "code": null, "e": 29353, "s": 29276, "text": "After the traversal store the minimum operations in the res (min(ops, res))." }, { "code": null, "e": 29375, "s": 29353, "text": "Print the result res." }, { "code": null, "e": 29426, "s": 29375, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 29430, "s": 29426, "text": "C++" }, { "code": null, "e": 29435, "s": 29430, "text": "Java" }, { "code": null, "e": 29443, "s": 29435, "text": "Python3" }, { "code": null, "e": 29446, "s": 29443, "text": "C#" }, { "code": null, "e": 29457, "s": 29446, "text": "Javascript" }, { "code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to check whether// a character is vowel or notbool isVowel(char c){ return (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u');} // Function to calculate minimum costvoid minCost(string s1, string s2){ // If both the lengths are not equal if (s1.length() != s2.length()) { cout << -1 << endl; return; } int n = s1.length(); // Initialize res with max value int res = INT_MAX; // Iterate through every character // and check the minimum cost by // replacing the blank by all letters for (char c = 'a'; c <= 'z'; c++) { // Initialize ops to check // the cost required by replacing // each char c int ops = 0; for (int i = 0; i < n; i++) { // If it is blank replace with c char c1 = s1[i] == '_' ? c : s1[i]; char c2 = s2[i] == '_' ? c : s2[i]; // If both are equal no ops required if (c1 == c2) continue; else { // If both are vowels or consonants // it requires cost as two // vowel->consonant ->vowel // and vice versa // Else 1 operation ops = ops + (isVowel(s1[i]) != isVowel(s2[i]) ? 2 : 1); } } // Take the minimum if (ops < res) { res = ops; } } // Print the result cout << res << endl;} // Driver codeint main(){ // Initialize the strings string s1 = \"g_e_s\", s2 = \"ge_ks\"; // Function call minCost(s1, s2); return 0;}", "e": 31229, "s": 29457, "text": null }, { "code": "// Java program for the above approachimport java.util.*;public class GFG{ // Function to check whether // a character is vowel or not static boolean isVowel(char c) { return (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u'); } // Function to calculate minimum cost static void minCost(String s1, String s2) { // If both the lengths are not equal if (s1.length() != s2.length()) { System.out.println(-1); return; } int n = s1.length(); // Initialize res with max value int res = Integer.MAX_VALUE; // Iterate through every character // and check the minimum cost by // replacing the blank by all letters for (char c = 'a'; c <= 'z'; c++) { // Initialize ops to check // the cost required by replacing // each char c int ops = 0; for (int i = 0; i < n; i++) { // If it is blank replace with c char c1 = s1.charAt(i) == '_' ? c : s1.charAt(i); char c2 = s2.charAt(i) == '_' ? c : s2.charAt(i); // If both are equal no ops required if (c1 == c2) continue; else { // If both are vowels or consonants // it requires cost as two // vowel->consonant ->vowel // and vice versa // Else 1 operation ops = ops + (isVowel(s1.charAt(i)) != isVowel(s2.charAt(i)) ? 2 : 1); } } // Take the minimum if (ops < res) { res = ops; } } // Print the result System.out.println(res); } // Driver code public static void main(String args[]) { // Initialize the strings String s1 = \"g_e_s\", s2 = \"ge_ks\"; // Function call minCost(s1, s2); }} // This code is contributed by Samim Hossain Mondal.", "e": 33034, "s": 31229, "text": null }, { "code": "# Python 3 program for the above approachimport sys # Function to check whether# a character is vowel or notdef isVowel(c): return (c == 'a' or c == 'e' or c == 'i' or c == 'o' or c == 'u') # Function to calculate minimum costdef minCost(s1, s2): # If both the lengths are not equal if (len(s1) != len(s2)): print(-1) return n = len(s1) # Initialize res with max value res = sys.maxsize # Iterate through every character # and check the minimum cost by # replacing the blank by all letters for c in range(ord('a'), ord('z')+1): # Initialize ops to check # the cost required by replacing # each char c ops = 0 for i in range(n): # If it is blank replace with c if s1[i] == '_': c1 = chr(c) else: c1 = s1[i] if s2[i] == '_': c2 = chr(c) else: c2 = s2[i] # If both are equal no ops required if (c1 == c2): continue else: # If both are vowels or consonants # it requires cost as two # vowel->consonant ->vowel # and vice versa # Else 1 operation if isVowel(s1[i]) != isVowel(s2[i]): ops += 2 else: ops += 1 # Take the minimum if (ops < res): res = ops # Print the result print(res) # Driver codeif __name__ == \"__main__\": # Initialize the strings s1 = \"g_e_s\" s2 = \"ge_ks\" # Function call minCost(s1, s2) # This code is contributed by ukasp.", "e": 34735, "s": 33034, "text": null }, { "code": "// C# program for the above approachusing System;class GFG{ // Function to check whether // a character is vowel or not static bool isVowel(char c) { return (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u'); } // Function to calculate minimum cost static void minCost(string s1, string s2) { // If both the lengths are not equal if (s1.Length != s2.Length) { Console.WriteLine(-1); return; } int n = s1.Length; // Initialize res with max value int res = Int32.MaxValue; // Iterate through every character // and check the minimum cost by // replacing the blank by all letters for (char c = 'a'; c <= 'z'; c++) { // Initialize ops to check // the cost required by replacing // each char c int ops = 0; for (int i = 0; i < n; i++) { // If it is blank replace with c char c1 = s1[i] == '_' ? c : s1[i]; char c2 = s2[i] == '_' ? c : s2[i]; // If both are equal no ops required if (c1 == c2) continue; else { // If both are vowels or consonants // it requires cost as two // vowel->consonant ->vowel // and vice versa // Else 1 operation ops = ops + (isVowel(s1[i]) != isVowel(s2[i]) ? 2 : 1); } } // Take the minimum if (ops < res) { res = ops; } } // Print the result Console.WriteLine(res); } // Driver code public static void Main() { // Initialize the strings string s1 = \"g_e_s\", s2 = \"ge_ks\"; // Function call minCost(s1, s2); }} // This code is contributed by Samim Hossain Mondal.", "e": 36457, "s": 34735, "text": null }, { "code": "<script>// Javascript program for the above approach // Function to check whether// a character is vowel or notfunction isVowel(c){ return (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u');} // Function to calculate minimum costfunction minCost(s1, s2){ // If both the lengths are not equal if (s1.length != s2.length) { document.write(-1); return; } let n = s1.length; // Initialize res with max value let res = Number. MAX_SAFE_INTEGER; // Iterate through every character // and check the minimum cost by // replacing the blank by all letters let c = 'a'; for (let j = 0; j < 26; j++) { // Initialize ops to check // the cost required by replacing // each char c let ops = 0; for (let i = 0; i < n; i++) { // If it is blank replace with c let c1 = s1[i] == '_' ? c : s1[i]; let c2 = s2[i] == '_' ? c : s2[i]; // If both are equal no ops required if (c1 == c2) continue; else { // If both are vowels or consonants // it requires cost as two // vowel->consonant ->vowel // and vice versa // Else 1 operation ops = ops + (isVowel(s1[i]) != isVowel(s2[i]) ? 2 : 1); } } c = String.fromCharCode(c.charCodeAt(0) + 1); // Take the minimum if (ops < res) { res = ops; } } // Print the result document.write(res);} // Driver code // Initialize the stringslet s1 = \"g_e_s\";let s2 = \"ge_ks\"; // Function callminCost(s1, s2); // This code is contributed by Samim Hossain Mondal.</script>", "e": 38311, "s": 36457, "text": null }, { "code": null, "e": 38316, "s": 38314, "text": "1" }, { "code": null, "e": 38365, "s": 38316, "text": "Time Complexity: O(26* N)Space Complexity: O(1) " }, { "code": null, "e": 38375, "s": 38365, "text": "samim2000" }, { "code": null, "e": 38381, "s": 38375, "text": "ukasp" }, { "code": null, "e": 38394, "s": 38381, "text": "simmytarika5" }, { "code": null, "e": 38409, "s": 38394, "text": "Algo-Geek 2021" }, { "code": null, "e": 38419, "s": 38409, "text": "Algo Geek" }, { "code": null, "e": 38427, "s": 38419, "text": "Strings" }, { "code": null, "e": 38435, "s": 38427, "text": "Strings" }, { "code": null, "e": 38533, "s": 38435, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 38588, "s": 38533, "text": "Check if the given string is valid English word or not" }, { "code": null, "e": 38636, "s": 38588, "text": "Sort strings on the basis of their numeric part" }, { "code": null, "e": 38676, "s": 38636, "text": "Divide given number into two even parts" }, { "code": null, "e": 38756, "s": 38676, "text": "Bit Manipulation technique to replace boolean arrays of fixed size less than 64" }, { "code": null, "e": 38810, "s": 38756, "text": "Count of Palindrome Strings in given Array of strings" }, { "code": null, "e": 38856, "s": 38810, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 38881, "s": 38856, "text": "Reverse a string in Java" }, { "code": null, "e": 38941, "s": 38881, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 38956, "s": 38941, "text": "C++ Data Types" } ]
Analysis of Algorithm | Set 4 (Solving Recurrences) - GeeksforGeeks
14 Jun, 2021 In the previous post, we discussed analysis of loops. Many algorithms are recursive in nature. When we analyze them, we get a recurrence relation for time complexity. We get running time on an input of size n as a function of n and the running time on inputs of smaller sizes. For example in Merge Sort, to sort a given array, we divide it in two halves and recursively repeat the process for the two halves. Finally we merge the results. Time complexity of Merge Sort can be written as T(n) = 2T(n/2) + cn. There are many other algorithms like Binary Search, Tower of Hanoi, etc. There are mainly three ways for solving recurrences. 1) Substitution Method: We make a guess for the solution and then we use mathematical induction to prove the guess is correct or incorrect. For example consider the recurrence T(n) = 2T(n/2) + n We guess the solution as T(n) = O(nLogn). Now we use induction to prove our guess. We need to prove that T(n) <= cnLogn. We can assume that it is true for values smaller than n. T(n) = 2T(n/2) + n <= 2cn/2Log(n/2) + n = cnLogn - cnLog2 + n = cnLogn - cn + n <= cnLogn 2) Recurrence Tree Method: In this method, we draw a recurrence tree and calculate the time taken by every level of tree. Finally, we sum the work done at all levels. To draw the recurrence tree, we start from the given recurrence and keep drawing till we find a pattern among levels. The pattern is typically a arithmetic or geometric series. For example consider the recurrence relation T(n) = T(n/4) + T(n/2) + cn2 cn2 / \ T(n/4) T(n/2) If we further break down the expression T(n/4) and T(n/2), we get following recursion tree. cn2 / \ c(n2)/16 c(n2)/4 / \ / \ T(n/16) T(n/8) T(n/8) T(n/4) Breaking down further gives us following cn2 / \ c(n2)/16 c(n2)/4 / \ / \ c(n2)/256 c(n2)/64 c(n2)/64 c(n2)/16 / \ / \ / \ / \ To know the value of T(n), we need to calculate sum of tree nodes level by level. If we sum the above tree level by level, we get the following series T(n) = c(n^2 + 5(n^2)/16 + 25(n^2)/256) + .... The above series is geometrical progression with ratio 5/16. To get an upper bound, we can sum the infinite series. We get the sum as (n2)/(1 - 5/16) which is O(n2) 3) Master Method: Master Method is a direct way to get the solution. The master method works only for following type of recurrences or for recurrences that can be transformed to following type. T(n) = aT(n/b) + f(n) where a >= 1 and b > 1 There are following three cases: 1. If f(n) = O(nc) where c < Logba then T(n) = Θ(nLogba) 2. If f(n) = Θ(nc) where c = Logba then T(n) = Θ(ncLog n) 3.If f(n) = u0004u0004u0004u0004u0004Ω(u0004nc) where c > Logba then T(n) = Θ(f(n)) u0004 How does this work? Master method is mainly derived from recurrence tree method. If we draw recurrence tree of T(n) = aT(n/b) + f(n), we can see that the work done at root is f(n) and work done at all leaves is Θ(nc) where c is Logba. And the height of recurrence tree is Logbn In recurrence tree method, we calculate total work done. If the work done at leaves is polynomially more, then leaves are the dominant part, and our result becomes the work done at leaves (Case 1). If work done at leaves and root is asymptotically same, then our result becomes height multiplied by work done at any level (Case 2). If work done at root is asymptotically more, then our result becomes work done at root (Case 3). Examples of some standard algorithms whose time complexity can be evaluated using Master Method Merge Sort: T(n) = 2T(n/2) + Θ(n). It falls in case 2 as c is 1 and Logba] is also 1. So the solution is Θ(n Logn) Binary Search: T(n) = T(n/2) + Θ(1). It also falls in case 2 as c is 0 and Logba is also 0. So the solution is Θ(Logn) Notes: 1) It is not necessary that a recurrence of the form T(n) = aT(n/b) + f(n) can be solved using Master Theorem. The given three cases have some gaps between them. For example, the recurrence T(n) = 2T(n/2) + n/Logn cannot be solved using master method. 2) Case 2 can be extended for f(n) = Θ(ncLogkn) If f(n) = Θ(ncLogkn) for some constant k >= 0 and c = Logba, then T(n) = Θ(ncLogk+1n) Practice Problems and Solutions on Master Theorem. Next – Analysis of Algorithm | Set 5 (Amortized Analysis Introduction) References: http://en.wikipedia.org/wiki/Master_theorem MIT Video Lecture on Asymptotic Notation | Recurrences | Substitution, Master Method Introduction to Algorithms 3rd Edition by Clifford Stein, Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above Manish Dhanuka animagussirius7 pragatpandya Analysis Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Understanding Time Complexity with Simple Examples Time Complexity and Space Complexity Practice Questions on Time Complexity Analysis Complexity of different operations in Binary tree, Binary Search Tree and AVL tree Time Complexity of building a heap Analysis of Algorithms | Big-O analysis Difference between NP hard and NP complete problem Analysis of different sorting techniques NP-Completeness | Set 1 (Introduction) Difference between Big Oh, Big Omega and Big Theta
[ { "code": null, "e": 35841, "s": 35813, "text": "\n14 Jun, 2021" }, { "code": null, "e": 36423, "s": 35841, "text": "In the previous post, we discussed analysis of loops. Many algorithms are recursive in nature. When we analyze them, we get a recurrence relation for time complexity. We get running time on an input of size n as a function of n and the running time on inputs of smaller sizes. For example in Merge Sort, to sort a given array, we divide it in two halves and recursively repeat the process for the two halves. Finally we merge the results. Time complexity of Merge Sort can be written as T(n) = 2T(n/2) + cn. There are many other algorithms like Binary Search, Tower of Hanoi, etc. " }, { "code": null, "e": 36477, "s": 36423, "text": "There are mainly three ways for solving recurrences. " }, { "code": null, "e": 36618, "s": 36477, "text": "1) Substitution Method: We make a guess for the solution and then we use mathematical induction to prove the guess is correct or incorrect. " }, { "code": null, "e": 36962, "s": 36618, "text": "For example consider the recurrence T(n) = 2T(n/2) + n\n\nWe guess the solution as T(n) = O(nLogn). Now we use induction\nto prove our guess.\n\nWe need to prove that T(n) <= cnLogn. We can assume that it is true\nfor values smaller than n.\n\nT(n) = 2T(n/2) + n\n <= 2cn/2Log(n/2) + n\n = cnLogn - cnLog2 + n\n = cnLogn - cn + n\n <= cnLogn" }, { "code": null, "e": 37308, "s": 36962, "text": "2) Recurrence Tree Method: In this method, we draw a recurrence tree and calculate the time taken by every level of tree. Finally, we sum the work done at all levels. To draw the recurrence tree, we start from the given recurrence and keep drawing till we find a pattern among levels. The pattern is typically a arithmetic or geometric series. " }, { "code": null, "e": 38308, "s": 37308, "text": "For example consider the recurrence relation \nT(n) = T(n/4) + T(n/2) + cn2\n\n cn2\n / \\\n T(n/4) T(n/2)\n\nIf we further break down the expression T(n/4) and T(n/2), \nwe get following recursion tree.\n\n cn2\n / \\ \n c(n2)/16 c(n2)/4\n / \\ / \\\n T(n/16) T(n/8) T(n/8) T(n/4) \nBreaking down further gives us following\n cn2\n / \\ \n c(n2)/16 c(n2)/4\n / \\ / \\\nc(n2)/256 c(n2)/64 c(n2)/64 c(n2)/16\n / \\ / \\ / \\ / \\ \n\nTo know the value of T(n), we need to calculate sum of tree \nnodes level by level. If we sum the above tree level by level, \nwe get the following series\nT(n) = c(n^2 + 5(n^2)/16 + 25(n^2)/256) + ....\nThe above series is geometrical progression with ratio 5/16.\n\nTo get an upper bound, we can sum the infinite series. \nWe get the sum as (n2)/(1 - 5/16) which is O(n2)" }, { "code": null, "e": 38504, "s": 38308, "text": "3) Master Method: Master Method is a direct way to get the solution. The master method works only for following type of recurrences or for recurrences that can be transformed to following type. " }, { "code": null, "e": 38549, "s": 38504, "text": "T(n) = aT(n/b) + f(n) where a >= 1 and b > 1" }, { "code": null, "e": 38640, "s": 38549, "text": "There are following three cases: 1. If f(n) = O(nc) where c < Logba then T(n) = Θ(nLogba) " }, { "code": null, "e": 38699, "s": 38640, "text": "2. If f(n) = Θ(nc) where c = Logba then T(n) = Θ(ncLog n) " }, { "code": null, "e": 38789, "s": 38699, "text": "3.If f(n) = u0004u0004u0004u0004u0004Ω(u0004nc) where c > Logba then T(n) = Θ(f(n)) u0004" }, { "code": null, "e": 39069, "s": 38789, "text": "How does this work? Master method is mainly derived from recurrence tree method. If we draw recurrence tree of T(n) = aT(n/b) + f(n), we can see that the work done at root is f(n) and work done at all leaves is Θ(nc) where c is Logba. And the height of recurrence tree is Logbn " }, { "code": null, "e": 39499, "s": 39069, "text": "In recurrence tree method, we calculate total work done. If the work done at leaves is polynomially more, then leaves are the dominant part, and our result becomes the work done at leaves (Case 1). If work done at leaves and root is asymptotically same, then our result becomes height multiplied by work done at any level (Case 2). If work done at root is asymptotically more, then our result becomes work done at root (Case 3). " }, { "code": null, "e": 39711, "s": 39499, "text": "Examples of some standard algorithms whose time complexity can be evaluated using Master Method Merge Sort: T(n) = 2T(n/2) + Θ(n). It falls in case 2 as c is 1 and Logba] is also 1. So the solution is Θ(n Logn) " }, { "code": null, "e": 39831, "s": 39711, "text": "Binary Search: T(n) = T(n/2) + Θ(1). It also falls in case 2 as c is 0 and Logba is also 0. So the solution is Θ(Logn) " }, { "code": null, "e": 40091, "s": 39831, "text": "Notes: 1) It is not necessary that a recurrence of the form T(n) = aT(n/b) + f(n) can be solved using Master Theorem. The given three cases have some gaps between them. For example, the recurrence T(n) = 2T(n/2) + n/Logn cannot be solved using master method. " }, { "code": null, "e": 40226, "s": 40091, "text": "2) Case 2 can be extended for f(n) = Θ(ncLogkn) If f(n) = Θ(ncLogkn) for some constant k >= 0 and c = Logba, then T(n) = Θ(ncLogk+1n) " }, { "code": null, "e": 40278, "s": 40226, "text": "Practice Problems and Solutions on Master Theorem. " }, { "code": null, "e": 40350, "s": 40278, "text": "Next – Analysis of Algorithm | Set 5 (Amortized Analysis Introduction) " }, { "code": null, "e": 40607, "s": 40350, "text": "References: http://en.wikipedia.org/wiki/Master_theorem MIT Video Lecture on Asymptotic Notation | Recurrences | Substitution, Master Method Introduction to Algorithms 3rd Edition by Clifford Stein, Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest " }, { "code": null, "e": 40732, "s": 40607, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 40747, "s": 40732, "text": "Manish Dhanuka" }, { "code": null, "e": 40763, "s": 40747, "text": "animagussirius7" }, { "code": null, "e": 40776, "s": 40763, "text": "pragatpandya" }, { "code": null, "e": 40785, "s": 40776, "text": "Analysis" }, { "code": null, "e": 40883, "s": 40785, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 40934, "s": 40883, "text": "Understanding Time Complexity with Simple Examples" }, { "code": null, "e": 40971, "s": 40934, "text": "Time Complexity and Space Complexity" }, { "code": null, "e": 41018, "s": 40971, "text": "Practice Questions on Time Complexity Analysis" }, { "code": null, "e": 41101, "s": 41018, "text": "Complexity of different operations in Binary tree, Binary Search Tree and AVL tree" }, { "code": null, "e": 41136, "s": 41101, "text": "Time Complexity of building a heap" }, { "code": null, "e": 41176, "s": 41136, "text": "Analysis of Algorithms | Big-O analysis" }, { "code": null, "e": 41227, "s": 41176, "text": "Difference between NP hard and NP complete problem" }, { "code": null, "e": 41268, "s": 41227, "text": "Analysis of different sorting techniques" }, { "code": null, "e": 41307, "s": 41268, "text": "NP-Completeness | Set 1 (Introduction)" } ]
Store duplicate keys-values pair and sort the key-value pair by key - GeeksforGeeks
03 Jun, 2021 Given N key-value pairs that contain duplicate keys and values, the task is to store these pairs and sort the pairs by key. Examples: Input : N : 10 Keys : 5 1 4 6 8 0 6 6 5 5 values: 0 1 2 3 4 5 6 7 8 9 Output : Keys : 0 1 4 5 5 5 6 6 6 8 values: 5 1 2 0 8 9 3 6 7 4 Explanation: We have given 10 key, value pairs which contain duplicate keys and values. The key value pair is {(5, 0), (1, 1), (4, 2), (6, 3), (8, 4), (0, 5), (6, 6), (6, 7), (5, 8), (5, 9)} and we want to store these key value pair and sort these key value pair by keys. So, the expected output is {(0, 5), (1, 1), (4, 2), (5, 0), (5, 8), (5, 9), (6, 3), (6, 6), (6, 7), (8, 4)}. Because the sorted increasing order of keys is {0, 1, 4, 5, 5, 5, 6, 6, 6, 8}. Approach:To solve the problem mentioned above we can use separate arrays to store keys and values and then we can simply sort keys by Merge sort algorithm. We can use any sorting Algorithm but Mergesort is the fastest standard sort algorithm and parallelly we can perform the same operations on values array which is performed on the keys so that the key-value pair will stay at the same index on both the array. Below is the implementation of the above approach: Java Python3 C# Javascript // Java program to Store duplicate// keys-values pair and sort the// key-value pair by keyimport java.util.*;import java.lang.*;import java.io.*; class Solution { // Merges two subarrays of arr[]. // First subarray is arr[l..m] // Second subarray is arr[m+1..r] void merge(int arrk[], int l, int m, int r, int arrv[]) { // Sizes of two subarrays // that are to be merged int n1 = m - l + 1; int n2 = r - m; /* Create temporary arrays */ int L[] = new int[n1]; int R[] = new int[n2]; int Lk[] = new int[n1]; int Rk[] = new int[n2]; /* Copy data to temporary arrays */ for (int i = 0; i < n1; ++i) { L[i] = arrk[l + i]; Lk[i] = arrv[l + i]; } for (int j = 0; j < n2; ++j) { R[j] = arrk[m + 1 + j]; Rk[j] = arrv[m + 1 + j]; } // Initial indexes of // first and second subarrays int i = 0, j = 0; int k = l; while (i < n1 && j < n2) { if (L[i] <= R[j]) { arrk[k] = L[i]; arrv[k] = Lk[i]; i++; } else { arrk[k] = R[j]; arrv[k] = Rk[j]; j++; } k++; } /* Copy remaining elements of L[] if any */ while (i < n1) { arrk[k] = L[i]; arrv[k] = Lk[i]; i++; k++; } /* Copy remaining elements of R[] if any */ while (j < n2) { arrk[k] = R[j]; arrv[k] = Rk[j]; j++; k++; } } // Function that sorts arr[l..r] using merge() void sort(int arrk[], int l, int r, int arrv[]) { if (l < r) { // Find the middle point int m = (l + r) / 2; // Sort first and second halves sort(arrk, l, m, arrv); sort(arrk, m + 1, r, arrv); // Merge the sorted halves merge(arrk, l, m, r, arrv); } } /* Function to print array of size n */ static void printArray(int arr[]) { int n = arr.length; for (int i = 0; i < n; ++i) System.out.print(arr[i] + " "); System.out.println(); } // Driver code public static void main(String[] args) throws java.lang.Exception { // Size of Array int n = 10; // array of keys int[] arrk = { 5, 1, 4, 6, 8, 0, 6, 6, 5, 5 }; // array of values int[] arrv = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; Solution ob = new Solution(); ob.sort(arrk, 0, n - 1, arrv); System.out.print("Keys: "); printArray(arrk); System.out.println(); System.out.print("Values: "); printArray(arrv); }} # Python program to Store duplicate# keys-values pair and sort the# key-value pair by key # Merges two subarrays of arr[].# First subarray is arr[l..m]# Second subarray is arr[m+1..r]def merge(arrk, l, m, r, arrv): # Sizes of two subarrays # that are to be merged n1 = m - l + 1; n2 = r - m; #Create temporary arrays L = [0]*n1 R = [0]*n2 Lk = [0]*n1 Rk = [0]*n2 #Copy data to temporary arrays for i in range(n1): L[i] = arrk[l + i]; Lk[i] = arrv[l + i]; for j in range(n2): R[j] = arrk[m + 1 + j]; Rk[j] = arrv[m + 1 + j]; # Initial indexes of # first and second subarrays a = 0 b = 0 k = l while(a < n1 and b < n2): if (L[a] <= R[b]): arrk[k] = L[a]; arrv[k] = Lk[a]; a += 1; else: arrk[k] = R[b]; arrv[k] = Rk[b]; b += 1; k += 1; # Copy remaining elements of L[] if any while (a < n1): arrk[k] = L[a]; arrv[k] = Lk[a]; a += 1; k += 1; # Copy remaining elements of R[] if any while (b < n2): arrk[k] = R[b]; arrv[k] = Rk[b]; b += 1; k += 1; # Function that sorts arr[l..r] using merge()def sort(arrk, l, r, arrv): if (l < r): # Find the middle point m = (l + r) // 2; # Sort first and second halves sort(arrk, l, m, arrv); sort(arrk, m + 1, r, arrv); # Merge the sorted halves merge(arrk, l, m, r, arrv); # Function to print array of size n def printArray(arr): n = len(arr) for i in range(n): print(arr[i], end = " ") print() # Driver code # Size of Arrayn = 10; # array of keysarrk = [5, 1, 4, 6, 8, 0, 6, 6, 5, 5 ] # array of values arrv = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] sort(arrk, 0, n - 1, arrv)print("Keys: ", end = '')printArray(arrk);print()print("Values: ", end = "")printArray(arrv); # This code is contributed by avanitrachhadiya2155 // C# program to Store duplicate// keys-values pair and sort the// key-value pair by keyusing System; class Solution{ // Merges two subarrays of arr[].// First subarray is arr[l..m]// Second subarray is arr[m+1..r]void merge(int []arrk, int l, int m, int r, int []arrv){ // Sizes of two subarrays // that are to be merged int n1 = m - l + 1; int n2 = r - m; // Create temporary arrays int []L = new int[n1]; int []R = new int[n2]; int []Lk = new int[n1]; int []Rk = new int[n2]; // Copy data to temporary arrays for(int i = 0; i < n1; ++i) { L[i] = arrk[l + i]; Lk[i] = arrv[l + i]; } for(int j = 0; j < n2; ++j) { R[j] = arrk[m + 1 + j]; Rk[j] = arrv[m + 1 + j]; } // Initial indexes of // first and second subarrays int a = 0 , b = 0; int k = l; while (a < n1 && b < n2) { if (L[a] <= R[b]) { arrk[k] = L[a]; arrv[k] = Lk[a]; a++; } else { arrk[k] = R[b]; arrv[k] = Rk[b]; b++; } k++; } // Copy remaining elements of L[] if any while (a < n1) { arrk[k] = L[a]; arrv[k] = Lk[a]; a++; k++; } // Copy remaining elements of R[] if any while (b < n2) { arrk[k] = R[b]; arrv[k] = Rk[b]; b++; k++; }} // Function that sorts arr[l..r] using merge()void sort(int []arrk, int l, int r, int []arrv){ if (l < r) { // Find the middle point int m = (l + r) / 2; // Sort first and second halves sort(arrk, l, m, arrv); sort(arrk, m + 1, r, arrv); // Merge the sorted halves merge(arrk, l, m, r, arrv); }} // Function to print array of size nstatic void printArray(int []arr){ int n = arr.Length; for(int i = 0; i < n; ++i) Console.Write(arr[i] + " "); Console.WriteLine();} // Driver codepublic static void Main(string[] args){ // Size of Array int n = 10; // array of keys int[] arrk = { 5, 1, 4, 6, 8, 0, 6, 6, 5, 5 }; // array of values int[] arrv = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; Solution ob = new Solution(); ob.sort(arrk, 0, n - 1, arrv); Console.Write("Keys: "); printArray(arrk); Console.WriteLine(); Console.Write("Values: "); printArray(arrv);}} // This code is contributed by ukasp <script> // Javascript program to Store duplicate// keys-values pair and sort the// key-value pair by key // Merges two subarrays of arr[].// First subarray is arr[l..m]// Second subarray is arr[m+1..r]function merge(arrk, l, m, r, arrv){ // Sizes of two subarrays // that are to be merged var n1 = m - l + 1; var n2 = r - m; /* Create temporary arrays */ var L = Array(n1).fill(0); var R = Array(n2).fill(0); var Lk = Array(n1).fill(0); var Rk = Array(n2).fill(0); /* Copy data to temporary arrays */ for (var i = 0; i < n1; ++i) { L[i] = arrk[l + i]; Lk[i] = arrv[l + i]; } for (var j = 0; j < n2; ++j) { R[j] = arrk[m + 1 + j]; Rk[j] = arrv[m + 1 + j]; } // Initial indexes of // first and second subarrays var i = 0, j = 0; var k = l; while (i < n1 && j < n2) { if (L[i] <= R[j]) { arrk[k] = L[i]; arrv[k] = Lk[i]; i++; } else { arrk[k] = R[j]; arrv[k] = Rk[j]; j++; } k++; } /* Copy remaining elements of L[] if any */ while (i < n1) { arrk[k] = L[i]; arrv[k] = Lk[i]; i++; k++; } /* Copy remaining elements of R[] if any */ while (j < n2) { arrk[k] = R[j]; arrv[k] = Rk[j]; j++; k++; }}// Function that sorts arr[l..r] using merge()function sort(arrk, l, r, arrv){ if (l < r) { // Find the middle point var m = parseInt((l + r) / 2); // Sort first and second halves sort(arrk, l, m, arrv); sort(arrk, m + 1, r, arrv); // Merge the sorted halves merge(arrk, l, m, r, arrv); }}/* Function to print array of size n */function printArray(arr){ var n = arr.length; for (var i = 0; i < n; ++i) document.write(arr[i] + " "); document.write("<br>");}// Driver code // Size of Arrayvar n = 10;// array of keysvar arrk = [ 5, 1, 4, 6, 8, 0, 6, 6, 5, 5 ]// array of valuesvar arrv = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ]sort(arrk, 0, n - 1, arrv);document.write("Keys: ");printArray(arrk);document.write("<br>");document.write("Values: ");printArray(arrv); </script> Keys: 0 1 4 5 5 5 6 6 6 8 Values: 5 1 2 0 8 9 3 6 7 4 Time Complexity: O(N*logN) rrrtnx ukasp avanitrachhadiya2155 Algorithms Arrays Java Programs Arrays Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. DSA Sheet by Love Babbar How to Start Learning DSA? Difference between Algorithm, Pseudocode and Program K means Clustering - Introduction Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete Arrays in Java Arrays in C/C++ Maximum and minimum of an array using minimum number of comparisons Write a program to reverse an array or string Program for array rotation
[ { "code": null, "e": 25942, "s": 25914, "text": "\n03 Jun, 2021" }, { "code": null, "e": 26066, "s": 25942, "text": "Given N key-value pairs that contain duplicate keys and values, the task is to store these pairs and sort the pairs by key." }, { "code": null, "e": 26077, "s": 26066, "text": "Examples: " }, { "code": null, "e": 26673, "s": 26077, "text": "Input : N : 10 Keys : 5 1 4 6 8 0 6 6 5 5 values: 0 1 2 3 4 5 6 7 8 9 Output : Keys : 0 1 4 5 5 5 6 6 6 8 values: 5 1 2 0 8 9 3 6 7 4 Explanation: We have given 10 key, value pairs which contain duplicate keys and values. The key value pair is {(5, 0), (1, 1), (4, 2), (6, 3), (8, 4), (0, 5), (6, 6), (6, 7), (5, 8), (5, 9)} and we want to store these key value pair and sort these key value pair by keys. So, the expected output is {(0, 5), (1, 1), (4, 2), (5, 0), (5, 8), (5, 9), (6, 3), (6, 6), (6, 7), (8, 4)}. Because the sorted increasing order of keys is {0, 1, 4, 5, 5, 5, 6, 6, 6, 8}. " }, { "code": null, "e": 27086, "s": 26673, "text": "Approach:To solve the problem mentioned above we can use separate arrays to store keys and values and then we can simply sort keys by Merge sort algorithm. We can use any sorting Algorithm but Mergesort is the fastest standard sort algorithm and parallelly we can perform the same operations on values array which is performed on the keys so that the key-value pair will stay at the same index on both the array." }, { "code": null, "e": 27138, "s": 27086, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 27143, "s": 27138, "text": "Java" }, { "code": null, "e": 27151, "s": 27143, "text": "Python3" }, { "code": null, "e": 27154, "s": 27151, "text": "C#" }, { "code": null, "e": 27165, "s": 27154, "text": "Javascript" }, { "code": "// Java program to Store duplicate// keys-values pair and sort the// key-value pair by keyimport java.util.*;import java.lang.*;import java.io.*; class Solution { // Merges two subarrays of arr[]. // First subarray is arr[l..m] // Second subarray is arr[m+1..r] void merge(int arrk[], int l, int m, int r, int arrv[]) { // Sizes of two subarrays // that are to be merged int n1 = m - l + 1; int n2 = r - m; /* Create temporary arrays */ int L[] = new int[n1]; int R[] = new int[n2]; int Lk[] = new int[n1]; int Rk[] = new int[n2]; /* Copy data to temporary arrays */ for (int i = 0; i < n1; ++i) { L[i] = arrk[l + i]; Lk[i] = arrv[l + i]; } for (int j = 0; j < n2; ++j) { R[j] = arrk[m + 1 + j]; Rk[j] = arrv[m + 1 + j]; } // Initial indexes of // first and second subarrays int i = 0, j = 0; int k = l; while (i < n1 && j < n2) { if (L[i] <= R[j]) { arrk[k] = L[i]; arrv[k] = Lk[i]; i++; } else { arrk[k] = R[j]; arrv[k] = Rk[j]; j++; } k++; } /* Copy remaining elements of L[] if any */ while (i < n1) { arrk[k] = L[i]; arrv[k] = Lk[i]; i++; k++; } /* Copy remaining elements of R[] if any */ while (j < n2) { arrk[k] = R[j]; arrv[k] = Rk[j]; j++; k++; } } // Function that sorts arr[l..r] using merge() void sort(int arrk[], int l, int r, int arrv[]) { if (l < r) { // Find the middle point int m = (l + r) / 2; // Sort first and second halves sort(arrk, l, m, arrv); sort(arrk, m + 1, r, arrv); // Merge the sorted halves merge(arrk, l, m, r, arrv); } } /* Function to print array of size n */ static void printArray(int arr[]) { int n = arr.length; for (int i = 0; i < n; ++i) System.out.print(arr[i] + \" \"); System.out.println(); } // Driver code public static void main(String[] args) throws java.lang.Exception { // Size of Array int n = 10; // array of keys int[] arrk = { 5, 1, 4, 6, 8, 0, 6, 6, 5, 5 }; // array of values int[] arrv = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; Solution ob = new Solution(); ob.sort(arrk, 0, n - 1, arrv); System.out.print(\"Keys: \"); printArray(arrk); System.out.println(); System.out.print(\"Values: \"); printArray(arrv); }}", "e": 30081, "s": 27165, "text": null }, { "code": "# Python program to Store duplicate# keys-values pair and sort the# key-value pair by key # Merges two subarrays of arr[].# First subarray is arr[l..m]# Second subarray is arr[m+1..r]def merge(arrk, l, m, r, arrv): # Sizes of two subarrays # that are to be merged n1 = m - l + 1; n2 = r - m; #Create temporary arrays L = [0]*n1 R = [0]*n2 Lk = [0]*n1 Rk = [0]*n2 #Copy data to temporary arrays for i in range(n1): L[i] = arrk[l + i]; Lk[i] = arrv[l + i]; for j in range(n2): R[j] = arrk[m + 1 + j]; Rk[j] = arrv[m + 1 + j]; # Initial indexes of # first and second subarrays a = 0 b = 0 k = l while(a < n1 and b < n2): if (L[a] <= R[b]): arrk[k] = L[a]; arrv[k] = Lk[a]; a += 1; else: arrk[k] = R[b]; arrv[k] = Rk[b]; b += 1; k += 1; # Copy remaining elements of L[] if any while (a < n1): arrk[k] = L[a]; arrv[k] = Lk[a]; a += 1; k += 1; # Copy remaining elements of R[] if any while (b < n2): arrk[k] = R[b]; arrv[k] = Rk[b]; b += 1; k += 1; # Function that sorts arr[l..r] using merge()def sort(arrk, l, r, arrv): if (l < r): # Find the middle point m = (l + r) // 2; # Sort first and second halves sort(arrk, l, m, arrv); sort(arrk, m + 1, r, arrv); # Merge the sorted halves merge(arrk, l, m, r, arrv); # Function to print array of size n def printArray(arr): n = len(arr) for i in range(n): print(arr[i], end = \" \") print() # Driver code # Size of Arrayn = 10; # array of keysarrk = [5, 1, 4, 6, 8, 0, 6, 6, 5, 5 ] # array of values arrv = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] sort(arrk, 0, n - 1, arrv)print(\"Keys: \", end = '')printArray(arrk);print()print(\"Values: \", end = \"\")printArray(arrv); # This code is contributed by avanitrachhadiya2155", "e": 32226, "s": 30081, "text": null }, { "code": "// C# program to Store duplicate// keys-values pair and sort the// key-value pair by keyusing System; class Solution{ // Merges two subarrays of arr[].// First subarray is arr[l..m]// Second subarray is arr[m+1..r]void merge(int []arrk, int l, int m, int r, int []arrv){ // Sizes of two subarrays // that are to be merged int n1 = m - l + 1; int n2 = r - m; // Create temporary arrays int []L = new int[n1]; int []R = new int[n2]; int []Lk = new int[n1]; int []Rk = new int[n2]; // Copy data to temporary arrays for(int i = 0; i < n1; ++i) { L[i] = arrk[l + i]; Lk[i] = arrv[l + i]; } for(int j = 0; j < n2; ++j) { R[j] = arrk[m + 1 + j]; Rk[j] = arrv[m + 1 + j]; } // Initial indexes of // first and second subarrays int a = 0 , b = 0; int k = l; while (a < n1 && b < n2) { if (L[a] <= R[b]) { arrk[k] = L[a]; arrv[k] = Lk[a]; a++; } else { arrk[k] = R[b]; arrv[k] = Rk[b]; b++; } k++; } // Copy remaining elements of L[] if any while (a < n1) { arrk[k] = L[a]; arrv[k] = Lk[a]; a++; k++; } // Copy remaining elements of R[] if any while (b < n2) { arrk[k] = R[b]; arrv[k] = Rk[b]; b++; k++; }} // Function that sorts arr[l..r] using merge()void sort(int []arrk, int l, int r, int []arrv){ if (l < r) { // Find the middle point int m = (l + r) / 2; // Sort first and second halves sort(arrk, l, m, arrv); sort(arrk, m + 1, r, arrv); // Merge the sorted halves merge(arrk, l, m, r, arrv); }} // Function to print array of size nstatic void printArray(int []arr){ int n = arr.Length; for(int i = 0; i < n; ++i) Console.Write(arr[i] + \" \"); Console.WriteLine();} // Driver codepublic static void Main(string[] args){ // Size of Array int n = 10; // array of keys int[] arrk = { 5, 1, 4, 6, 8, 0, 6, 6, 5, 5 }; // array of values int[] arrv = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; Solution ob = new Solution(); ob.sort(arrk, 0, n - 1, arrv); Console.Write(\"Keys: \"); printArray(arrk); Console.WriteLine(); Console.Write(\"Values: \"); printArray(arrv);}} // This code is contributed by ukasp", "e": 34701, "s": 32226, "text": null }, { "code": "<script> // Javascript program to Store duplicate// keys-values pair and sort the// key-value pair by key // Merges two subarrays of arr[].// First subarray is arr[l..m]// Second subarray is arr[m+1..r]function merge(arrk, l, m, r, arrv){ // Sizes of two subarrays // that are to be merged var n1 = m - l + 1; var n2 = r - m; /* Create temporary arrays */ var L = Array(n1).fill(0); var R = Array(n2).fill(0); var Lk = Array(n1).fill(0); var Rk = Array(n2).fill(0); /* Copy data to temporary arrays */ for (var i = 0; i < n1; ++i) { L[i] = arrk[l + i]; Lk[i] = arrv[l + i]; } for (var j = 0; j < n2; ++j) { R[j] = arrk[m + 1 + j]; Rk[j] = arrv[m + 1 + j]; } // Initial indexes of // first and second subarrays var i = 0, j = 0; var k = l; while (i < n1 && j < n2) { if (L[i] <= R[j]) { arrk[k] = L[i]; arrv[k] = Lk[i]; i++; } else { arrk[k] = R[j]; arrv[k] = Rk[j]; j++; } k++; } /* Copy remaining elements of L[] if any */ while (i < n1) { arrk[k] = L[i]; arrv[k] = Lk[i]; i++; k++; } /* Copy remaining elements of R[] if any */ while (j < n2) { arrk[k] = R[j]; arrv[k] = Rk[j]; j++; k++; }}// Function that sorts arr[l..r] using merge()function sort(arrk, l, r, arrv){ if (l < r) { // Find the middle point var m = parseInt((l + r) / 2); // Sort first and second halves sort(arrk, l, m, arrv); sort(arrk, m + 1, r, arrv); // Merge the sorted halves merge(arrk, l, m, r, arrv); }}/* Function to print array of size n */function printArray(arr){ var n = arr.length; for (var i = 0; i < n; ++i) document.write(arr[i] + \" \"); document.write(\"<br>\");}// Driver code // Size of Arrayvar n = 10;// array of keysvar arrk = [ 5, 1, 4, 6, 8, 0, 6, 6, 5, 5 ]// array of valuesvar arrv = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ]sort(arrk, 0, n - 1, arrv);document.write(\"Keys: \");printArray(arrk);document.write(\"<br>\");document.write(\"Values: \");printArray(arrv); </script>", "e": 36902, "s": 34701, "text": null }, { "code": null, "e": 36958, "s": 36902, "text": "Keys: 0 1 4 5 5 5 6 6 6 8 \n\nValues: 5 1 2 0 8 9 3 6 7 4" }, { "code": null, "e": 36988, "s": 36960, "text": "Time Complexity: O(N*logN) " }, { "code": null, "e": 36995, "s": 36988, "text": "rrrtnx" }, { "code": null, "e": 37001, "s": 36995, "text": "ukasp" }, { "code": null, "e": 37022, "s": 37001, "text": "avanitrachhadiya2155" }, { "code": null, "e": 37033, "s": 37022, "text": "Algorithms" }, { "code": null, "e": 37040, "s": 37033, "text": "Arrays" }, { "code": null, "e": 37054, "s": 37040, "text": "Java Programs" }, { "code": null, "e": 37061, "s": 37054, "text": "Arrays" }, { "code": null, "e": 37072, "s": 37061, "text": "Algorithms" }, { "code": null, "e": 37170, "s": 37072, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 37195, "s": 37170, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 37222, "s": 37195, "text": "How to Start Learning DSA?" }, { "code": null, "e": 37275, "s": 37222, "text": "Difference between Algorithm, Pseudocode and Program" }, { "code": null, "e": 37309, "s": 37275, "text": "K means Clustering - Introduction" }, { "code": null, "e": 37376, "s": 37309, "text": "Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete" }, { "code": null, "e": 37391, "s": 37376, "text": "Arrays in Java" }, { "code": null, "e": 37407, "s": 37391, "text": "Arrays in C/C++" }, { "code": null, "e": 37475, "s": 37407, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 37521, "s": 37475, "text": "Write a program to reverse an array or string" } ]
Installation of Wpscan Tool in Kali Linux - GeeksforGeeks
24 Dec, 2020 Wpscan (WordPress vulnerability Scanner) is a black box WordPress vulnerability scanner. Wpscan is used to scan remote WordPress installations or websites to find security issues. WordPress can also be used to enumerate WordPress plugins and themes and brute-force logins. Approximately 35% of the internet runs on WordPress, WordPress is a free content management system. Which is used to build and maintain websites). Making a website using WordPress is very easy and absolutely free of cost, that’s why it is widely used. With the increase in the WordPress market, its security becoming a big concern for creators and users. Over 8% of internet breakability is found on WordPress websites. There are many WordPress vulnerability scanners available in the market like SUCURI(It is a Security website that protects your website from hackers, malware, DDoS, and blacklists), and WPScan(It is the scanner to scan your WordPress websites for vulnerable plugins, themes, and security misconfigurations). Installation of Wpscan tool: Usually Wpscan tool comes pre-installed with Kali Linux but, if we need to install it we can run the following command : 1. We can install Git in Kali Linux by the below command sudo apt-get install git 2. Once Git is installed, we need to fix Kali Linux dependencies for the latest Ruby development environment. Type below command in terminal sudo apt-get install git ruby ruby-dev libcurl4-openssl-dev m 3. Now we can install WPScan tool on Kali Linux, by running the below command in the terminal. git clone http://github.com/wpscanteam/wpscan.git 4. Once the download is completed, let change our directory to WPscan directory, by following the below command. cd wpscan 5. Bundler is required to use the WPscan tool. WPScan is a ruby based application that uses ‘Gems’ as part of the programming language. Bundler will help keep WPScan and all of its dependencies updated effectively. We can install bundler in Kali Linux by running the below command in the WPScan directory : sudo gem install bundler && bundle install --without test Kali-Linux Technical Scripter 2020 Linux-Unix Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. scp command in Linux with Examples mv command in Linux with examples Docker - COPY Instruction SED command in Linux | Set 2 chown command in Linux with Examples nohup Command in Linux with Examples Named Pipe or FIFO with example C program Thread functions in C/C++ uniq Command in LINUX with examples Start/Stop/Restart Services Using Systemctl in Linux
[ { "code": null, "e": 25651, "s": 25623, "text": "\n24 Dec, 2020" }, { "code": null, "e": 26652, "s": 25651, "text": "Wpscan (WordPress vulnerability Scanner) is a black box WordPress vulnerability scanner. Wpscan is used to scan remote WordPress installations or websites to find security issues. WordPress can also be used to enumerate WordPress plugins and themes and brute-force logins. Approximately 35% of the internet runs on WordPress, WordPress is a free content management system. Which is used to build and maintain websites). Making a website using WordPress is very easy and absolutely free of cost, that’s why it is widely used. With the increase in the WordPress market, its security becoming a big concern for creators and users. Over 8% of internet breakability is found on WordPress websites. There are many WordPress vulnerability scanners available in the market like SUCURI(It is a Security website that protects your website from hackers, malware, DDoS, and blacklists), and WPScan(It is the scanner to scan your WordPress websites for vulnerable plugins, themes, and security misconfigurations)." }, { "code": null, "e": 26802, "s": 26652, "text": "Installation of Wpscan tool: Usually Wpscan tool comes pre-installed with Kali Linux but, if we need to install it we can run the following command :" }, { "code": null, "e": 26859, "s": 26802, "text": "1. We can install Git in Kali Linux by the below command" }, { "code": null, "e": 26884, "s": 26859, "text": "sudo apt-get install git" }, { "code": null, "e": 27025, "s": 26884, "text": "2. Once Git is installed, we need to fix Kali Linux dependencies for the latest Ruby development environment. Type below command in terminal" }, { "code": null, "e": 27087, "s": 27025, "text": "sudo apt-get install git ruby ruby-dev libcurl4-openssl-dev m" }, { "code": null, "e": 27182, "s": 27087, "text": "3. Now we can install WPScan tool on Kali Linux, by running the below command in the terminal." }, { "code": null, "e": 27232, "s": 27182, "text": "git clone http://github.com/wpscanteam/wpscan.git" }, { "code": null, "e": 27345, "s": 27232, "text": "4. Once the download is completed, let change our directory to WPscan directory, by following the below command." }, { "code": null, "e": 27355, "s": 27345, "text": "cd wpscan" }, { "code": null, "e": 27662, "s": 27355, "text": "5. Bundler is required to use the WPscan tool. WPScan is a ruby based application that uses ‘Gems’ as part of the programming language. Bundler will help keep WPScan and all of its dependencies updated effectively. We can install bundler in Kali Linux by running the below command in the WPScan directory :" }, { "code": null, "e": 27720, "s": 27662, "text": "sudo gem install bundler && bundle install --without test" }, { "code": null, "e": 27731, "s": 27720, "text": "Kali-Linux" }, { "code": null, "e": 27755, "s": 27731, "text": "Technical Scripter 2020" }, { "code": null, "e": 27766, "s": 27755, "text": "Linux-Unix" }, { "code": null, "e": 27785, "s": 27766, "text": "Technical Scripter" }, { "code": null, "e": 27883, "s": 27785, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27918, "s": 27883, "text": "scp command in Linux with Examples" }, { "code": null, "e": 27952, "s": 27918, "text": "mv command in Linux with examples" }, { "code": null, "e": 27978, "s": 27952, "text": "Docker - COPY Instruction" }, { "code": null, "e": 28007, "s": 27978, "text": "SED command in Linux | Set 2" }, { "code": null, "e": 28044, "s": 28007, "text": "chown command in Linux with Examples" }, { "code": null, "e": 28081, "s": 28044, "text": "nohup Command in Linux with Examples" }, { "code": null, "e": 28123, "s": 28081, "text": "Named Pipe or FIFO with example C program" }, { "code": null, "e": 28149, "s": 28123, "text": "Thread functions in C/C++" }, { "code": null, "e": 28185, "s": 28149, "text": "uniq Command in LINUX with examples" } ]
Python | Pandas dataframe.reindex_axis() - GeeksforGeeks
22 Nov, 2018 Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas dataframe.reindex_axis() function Conform input object to new index. The function populates NaN values in locations having no value in the previous index. It also provides a way to fill the missing values in the dataframe. A new object is produced unless the new index is equivalent to the current one and copy=False Syntax:Syntax: DataFrame.reindex_axis(labels, axis=0, method=None, level=None, copy=True, limit=None, fill_value=nan) Parameters :labels : New labels / index to conform to. Preferably an Index object to avoid duplicating dataaxis : {0 or ‘index’, 1 or ‘columns’}method : {None, ‘backfill’/’bfill’, ‘pad’/’ffill’, ‘nearest’}, optionalcopy : Return a new object, even if the passed indexes are the samelevel : Broadcast across a level, matching Index values on the passed MultiIndex levellimit : Maximum number of consecutive elements to forward or backward filltolerance : Maximum distance between original and new labels for inexact matches. The values of the index at the matching locations most satisfy the equation abs(index[indexer] – target) <= tolerance. Returns : reindexed : DataFrame Example #1: Use reindex_axis() function to reindex the dataframe over the index axis. By default values in the new index that do not have corresponding records in the dataframe are assigned NaN.Note : We can fill in the missing values using ‘ffill’ method # importing pandas as pdimport pandas as pd # Creating the dataframe df = pd.DataFrame({"A":[1, 5, 3, 4, 2], "B":[3, 2, 4, 3, 4], "C":[2, 2, 7, 3, 4], "D":[4, 3, 6, 12, 7]}, index =["A1", "A2", "A3", "A4", "A5"]) # Print the dataframedf Let’s use the dataframe.reindex_axis() function to reindex the dataframe over the index axis # reindexing with new index valuesdf.reindex_axis(["A1", "A2", "A4", "A7", "A8"], axis = 0) Output :Notice the output, new indexes are populated with NaN values, we can fill in the missing values using ‘ffill’ method. # filling the missing values using ffill methoddf.reindex_axis(["A1", "A2", "A4", "A7", "A8"], axis = 0, method ='ffill') Output :Notice in the output, the new indexes has been populated using the “A5” row. Example #2: Use reindex_axis() function to reindex the column axis # importing pandas as pdimport pandas as pd # Creating the dataframe df = pd.DataFrame({"A":[1, 5, 3, 4, 2], "B":[3, 2, 4, 3, 4], "C":[2, 2, 7, 3, 4], "D":[4, 3, 6, 12, 7]}, index =["A1", "A2", "A3", "A4", "A5"]) # reindexing the column axis with# old and new index valuesdf.reindex_axis(["A", "B", "D", "E"], axis = 1) Output : Notice, we have NaN values in the new columns after reindexing, we can take care of the missing values at the time of reindexing. By using ffill method we can forward fill the missing values. # reindex the columns# we fill the missing values using ffill methoddf.reindex_axis(["A", "B", "D", "E"], axis = 1, method ='ffill') Output : Python pandas-dataFrame Python pandas-dataFrame-methods Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | Get unique values from a list Python | os.path.join() method Defaultdict in Python Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n22 Nov, 2018" }, { "code": null, "e": 25751, "s": 25537, "text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier." }, { "code": null, "e": 26075, "s": 25751, "text": "Pandas dataframe.reindex_axis() function Conform input object to new index. The function populates NaN values in locations having no value in the previous index. It also provides a way to fill the missing values in the dataframe. A new object is produced unless the new index is equivalent to the current one and copy=False" }, { "code": null, "e": 26193, "s": 26075, "text": "Syntax:Syntax: DataFrame.reindex_axis(labels, axis=0, method=None, level=None, copy=True, limit=None, fill_value=nan)" }, { "code": null, "e": 26836, "s": 26193, "text": "Parameters :labels : New labels / index to conform to. Preferably an Index object to avoid duplicating dataaxis : {0 or ‘index’, 1 or ‘columns’}method : {None, ‘backfill’/’bfill’, ‘pad’/’ffill’, ‘nearest’}, optionalcopy : Return a new object, even if the passed indexes are the samelevel : Broadcast across a level, matching Index values on the passed MultiIndex levellimit : Maximum number of consecutive elements to forward or backward filltolerance : Maximum distance between original and new labels for inexact matches. The values of the index at the matching locations most satisfy the equation abs(index[indexer] – target) <= tolerance." }, { "code": null, "e": 26868, "s": 26836, "text": "Returns : reindexed : DataFrame" }, { "code": null, "e": 27124, "s": 26868, "text": "Example #1: Use reindex_axis() function to reindex the dataframe over the index axis. By default values in the new index that do not have corresponding records in the dataframe are assigned NaN.Note : We can fill in the missing values using ‘ffill’ method" }, { "code": "# importing pandas as pdimport pandas as pd # Creating the dataframe df = pd.DataFrame({\"A\":[1, 5, 3, 4, 2], \"B\":[3, 2, 4, 3, 4], \"C\":[2, 2, 7, 3, 4], \"D\":[4, 3, 6, 12, 7]}, index =[\"A1\", \"A2\", \"A3\", \"A4\", \"A5\"]) # Print the dataframedf", "e": 27436, "s": 27124, "text": null }, { "code": null, "e": 27529, "s": 27436, "text": "Let’s use the dataframe.reindex_axis() function to reindex the dataframe over the index axis" }, { "code": "# reindexing with new index valuesdf.reindex_axis([\"A1\", \"A2\", \"A4\", \"A7\", \"A8\"], axis = 0)", "e": 27621, "s": 27529, "text": null }, { "code": null, "e": 27747, "s": 27621, "text": "Output :Notice the output, new indexes are populated with NaN values, we can fill in the missing values using ‘ffill’ method." }, { "code": "# filling the missing values using ffill methoddf.reindex_axis([\"A1\", \"A2\", \"A4\", \"A7\", \"A8\"], axis = 0, method ='ffill')", "e": 27890, "s": 27747, "text": null }, { "code": null, "e": 28042, "s": 27890, "text": "Output :Notice in the output, the new indexes has been populated using the “A5” row. Example #2: Use reindex_axis() function to reindex the column axis" }, { "code": "# importing pandas as pdimport pandas as pd # Creating the dataframe df = pd.DataFrame({\"A\":[1, 5, 3, 4, 2], \"B\":[3, 2, 4, 3, 4], \"C\":[2, 2, 7, 3, 4], \"D\":[4, 3, 6, 12, 7]}, index =[\"A1\", \"A2\", \"A3\", \"A4\", \"A5\"]) # reindexing the column axis with# old and new index valuesdf.reindex_axis([\"A\", \"B\", \"D\", \"E\"], axis = 1)", "e": 28437, "s": 28042, "text": null }, { "code": null, "e": 28446, "s": 28437, "text": "Output :" }, { "code": null, "e": 28638, "s": 28446, "text": "Notice, we have NaN values in the new columns after reindexing, we can take care of the missing values at the time of reindexing. By using ffill method we can forward fill the missing values." }, { "code": "# reindex the columns# we fill the missing values using ffill methoddf.reindex_axis([\"A\", \"B\", \"D\", \"E\"], axis = 1, method ='ffill')", "e": 28771, "s": 28638, "text": null }, { "code": null, "e": 28780, "s": 28771, "text": "Output :" }, { "code": null, "e": 28804, "s": 28780, "text": "Python pandas-dataFrame" }, { "code": null, "e": 28836, "s": 28804, "text": "Python pandas-dataFrame-methods" }, { "code": null, "e": 28850, "s": 28836, "text": "Python-pandas" }, { "code": null, "e": 28857, "s": 28850, "text": "Python" }, { "code": null, "e": 28955, "s": 28857, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28987, "s": 28955, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29029, "s": 28987, "text": "Check if element exists in list in Python" }, { "code": null, "e": 29071, "s": 29029, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 29127, "s": 29071, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 29154, "s": 29127, "text": "Python Classes and Objects" }, { "code": null, "e": 29193, "s": 29154, "text": "Python | Get unique values from a list" }, { "code": null, "e": 29224, "s": 29193, "text": "Python | os.path.join() method" }, { "code": null, "e": 29246, "s": 29224, "text": "Defaultdict in Python" }, { "code": null, "e": 29275, "s": 29246, "text": "Create a directory in Python" } ]
How to Customize AppCompat EditText in Android? - GeeksforGeeks
18 Feb, 2021 The EditText is one of the important UI element which takes the data as input from the user. The usual EditText in Android which looks decent enough has only the hint text and line which makes the user click on that line and insert the data. Refer to the article EditText widget in Android using Java with Examples, which explains basics about the normal AppCompat EditText. In this article, it’s been discussed how to customize the AppCompat EditText. Have a look at the following image to differentiate between the usual non-customized AppCompat EditText and the customized AppCompat EditText. Step 1: Create an empty Activity Project Create an empty activity Android Studio Project. Refer to Android | How to Create/Start a New Project in Android Studio? Step 2: Working with the activity_main.xml file Only two EditText widgets are implemented in the main layout file. One is Username and another is Password field. Invoke the following code to implement the same UI. XML <?xml version="1.0" encoding="utf-8"?><ScrollView 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" tools:ignore="HardcodedText"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <!--E-mail field--> <EditText android:id="@+id/emailField1" android:layout_width="match_parent" android:layout_height="60dp" android:layout_marginStart="16dp" android:layout_marginTop="32dp" android:layout_marginEnd="16dp" android:hint="Email" /> <!--Password field--> <EditText android:id="@+id/passwordField1" android:layout_width="match_parent" android:layout_height="60dp" android:layout_marginStart="16dp" android:layout_marginTop="16dp" android:layout_marginEnd="16dp" android:hint="Password" /> </LinearLayout> </ScrollView> Output UI: Step 3: Import vector icons Import vector icons into the drawable folder. To import the vector icons right-click on the drawable folder > New > Vector Asset. Make sure to make copies of the single icon in the drawable folder. One icon when the edit text is out of focus and when the edit text is in focus. Set the color of the icon to grey when the edit text is out of focus and set the color of the icon to colorPrimary when the EditText is in focus. Refer to the following image to get the steps discussed above. And combining both the icons make a selector XML layout custom_mail_icon as following. XML <?xml version="1.0" encoding="utf-8"?><selector xmlns:android="http://schemas.android.com/apk/res/android"> <!--the icon turns to green when the edit text is in focus--> <item android:drawable="@drawable/ic_mail_focused" android:state_focused="true" /> <!--the icon turns to grey when the edit text is out of focus--> <item android:drawable="@drawable/ic_mail" android:state_focused="false" /></selector> The same goes for the password field icon. Step 1: Create a Selector layout background for the EditText This is the layout that gives the cut-cornered box for the EditText field. To implement the same create a custom_edit_text_cut.xml file under the drawable folder and invoke the following code. XML <?xml version="1.0" encoding="utf-8"?><selector xmlns:android="http://schemas.android.com/apk/res/android"> <!--the outline box turns to green when the edit text is in focus--> <item android:state_enabled="true" android:state_focused="true"> <shape android:shape="rectangle"> <solid android:color="@android:color/white" /> <stroke android:width="2dp" android:color="@color/colorPrimary" /> </shape> </item> <!--the outline box turns to grey when the edit text is out of focus--> <item android:state_enabled="true"> <shape android:shape="rectangle"> <solid android:color="@android:color/white" /> <stroke android:width="2dp" android:color="@android:color/darker_gray" /> </shape> </item> </selector> Step 2: Working with the activity_main.xml file In the activity_main.xml file invoke the background for the EditText as custom_edit_text_cut.xml. XML <?xml version="1.0" encoding="utf-8"?><ScrollView 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" tools:ignore="HardcodedText"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <!--invoke the background as the custom_edit_text_cut--> <EditText android:id="@+id/emailField1" android:layout_width="match_parent" android:layout_height="60dp" android:layout_marginStart="16dp" android:layout_marginTop="32dp" android:layout_marginEnd="16dp" android:background="@drawable/custom_edit_text_cut" android:drawableStart="@drawable/custom_mail_icon" android:drawablePadding="12dp" android:hint="Email" android:paddingStart="12dp" android:paddingEnd="12dp" /> <!--same background for the password field as the custom_edit_text_cut--> <EditText android:id="@+id/passwordField1" android:layout_width="match_parent" android:layout_height="60dp" android:layout_marginStart="16dp" android:layout_marginTop="16dp" android:layout_marginEnd="16dp" android:background="@drawable/custom_edit_text_cut" android:drawableStart="@drawable/custom_vpn_icon" android:drawablePadding="12dp" android:hint="Password" android:paddingStart="12dp" android:paddingEnd="12dp" /> </LinearLayout> </ScrollView> Step 1: Create a Selector layout background for the EditText This is the layout that gives the cut-cornered box for the EditText field. To implement the same create a custom_edit_text_rounded.xml file under the drawable folder and invoke the following code. XML <?xml version="1.0" encoding="utf-8"?><selector xmlns:android="http://schemas.android.com/apk/res/android"> <!--The outline turns to colorPrimary when the EditText is in focus--> <item android:state_enabled="true" android:state_focused="true"> <shape android:shape="rectangle"> <solid android:color="@android:color/white" /> <corners android:radius="12dp" /> <stroke android:width="2dp" android:color="@color/colorPrimary" /> </shape> </item> <!--The outline turns to grey when the EditText is out of focus--> <item android:state_enabled="true"> <shape android:shape="rectangle"> <solid android:color="@android:color/white" /> <corners android:radius="12dp" /> <stroke android:width="2dp" android:color="@android:color/darker_gray" /> </shape> </item> </selector> Step 2: Working with the activity_main.xml file In the activity_main.xml file invoke the background for the EditText as custom_edit_text_rounded.xml. XML <?xml version="1.0" encoding="utf-8"?><ScrollView 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" tools:ignore="HardcodedText"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <!--invoke the background as the custom_edit_text_rounded--> <EditText android:id="@+id/emailField1" android:layout_width="match_parent" android:layout_height="60dp" android:layout_marginStart="16dp" android:layout_marginTop="32dp" android:layout_marginEnd="16dp" android:background="@drawable/custom_edit_text_rounded" android:drawableStart="@drawable/custom_mail_icon" android:drawablePadding="12dp" android:hint="Email" android:paddingStart="12dp" android:paddingEnd="12dp" /> <!--same background for the password field as the custom_edit_text_rounded--> <EditText android:id="@+id/passwordField1" android:layout_width="match_parent" android:layout_height="60dp" android:layout_marginStart="16dp" android:layout_marginTop="32dp" android:layout_marginEnd="16dp" android:background="@drawable/custom_edit_text_rounded" android:drawableStart="@drawable/custom_vpn_icon" android:drawablePadding="12dp" android:hint="Password" android:paddingStart="12dp" android:paddingEnd="12dp" /> </LinearLayout> </ScrollView> android Android-View Technical Scripter 2020 Android Technical Scripter Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Resource Raw Folder in Android Studio Flutter - Custom Bottom Navigation Bar How to Read Data from SQLite Database in Android? How to Post Data to API using Retrofit in Android? Retrofit with Kotlin Coroutine in Android How to Get Current Location in Android? Android Listview in Java with Example How to Save Data to the Firebase Realtime Database in Android? Flexbox-Layout in Android How to Change the Background Color After Clicking the Button in Android?
[ { "code": null, "e": 26381, "s": 26353, "text": "\n18 Feb, 2021" }, { "code": null, "e": 26977, "s": 26381, "text": "The EditText is one of the important UI element which takes the data as input from the user. The usual EditText in Android which looks decent enough has only the hint text and line which makes the user click on that line and insert the data. Refer to the article EditText widget in Android using Java with Examples, which explains basics about the normal AppCompat EditText. In this article, it’s been discussed how to customize the AppCompat EditText. Have a look at the following image to differentiate between the usual non-customized AppCompat EditText and the customized AppCompat EditText." }, { "code": null, "e": 27018, "s": 26977, "text": "Step 1: Create an empty Activity Project" }, { "code": null, "e": 27067, "s": 27018, "text": "Create an empty activity Android Studio Project." }, { "code": null, "e": 27139, "s": 27067, "text": "Refer to Android | How to Create/Start a New Project in Android Studio?" }, { "code": null, "e": 27187, "s": 27139, "text": "Step 2: Working with the activity_main.xml file" }, { "code": null, "e": 27301, "s": 27187, "text": "Only two EditText widgets are implemented in the main layout file. One is Username and another is Password field." }, { "code": null, "e": 27353, "s": 27301, "text": "Invoke the following code to implement the same UI." }, { "code": null, "e": 27357, "s": 27353, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><ScrollView 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\" tools:ignore=\"HardcodedText\"> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:orientation=\"vertical\"> <!--E-mail field--> <EditText android:id=\"@+id/emailField1\" android:layout_width=\"match_parent\" android:layout_height=\"60dp\" android:layout_marginStart=\"16dp\" android:layout_marginTop=\"32dp\" android:layout_marginEnd=\"16dp\" android:hint=\"Email\" /> <!--Password field--> <EditText android:id=\"@+id/passwordField1\" android:layout_width=\"match_parent\" android:layout_height=\"60dp\" android:layout_marginStart=\"16dp\" android:layout_marginTop=\"16dp\" android:layout_marginEnd=\"16dp\" android:hint=\"Password\" /> </LinearLayout> </ScrollView>", "e": 28534, "s": 27357, "text": null }, { "code": null, "e": 28545, "s": 28534, "text": "Output UI:" }, { "code": null, "e": 28573, "s": 28545, "text": "Step 3: Import vector icons" }, { "code": null, "e": 28619, "s": 28573, "text": "Import vector icons into the drawable folder." }, { "code": null, "e": 28703, "s": 28619, "text": "To import the vector icons right-click on the drawable folder > New > Vector Asset." }, { "code": null, "e": 28851, "s": 28703, "text": "Make sure to make copies of the single icon in the drawable folder. One icon when the edit text is out of focus and when the edit text is in focus." }, { "code": null, "e": 28997, "s": 28851, "text": "Set the color of the icon to grey when the edit text is out of focus and set the color of the icon to colorPrimary when the EditText is in focus." }, { "code": null, "e": 29060, "s": 28997, "text": "Refer to the following image to get the steps discussed above." }, { "code": null, "e": 29147, "s": 29060, "text": "And combining both the icons make a selector XML layout custom_mail_icon as following." }, { "code": null, "e": 29151, "s": 29147, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><selector xmlns:android=\"http://schemas.android.com/apk/res/android\"> <!--the icon turns to green when the edit text is in focus--> <item android:drawable=\"@drawable/ic_mail_focused\" android:state_focused=\"true\" /> <!--the icon turns to grey when the edit text is out of focus--> <item android:drawable=\"@drawable/ic_mail\" android:state_focused=\"false\" /></selector>", "e": 29570, "s": 29151, "text": null }, { "code": null, "e": 29613, "s": 29570, "text": "The same goes for the password field icon." }, { "code": null, "e": 29674, "s": 29613, "text": "Step 1: Create a Selector layout background for the EditText" }, { "code": null, "e": 29749, "s": 29674, "text": "This is the layout that gives the cut-cornered box for the EditText field." }, { "code": null, "e": 29867, "s": 29749, "text": "To implement the same create a custom_edit_text_cut.xml file under the drawable folder and invoke the following code." }, { "code": null, "e": 29871, "s": 29867, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><selector xmlns:android=\"http://schemas.android.com/apk/res/android\"> <!--the outline box turns to green when the edit text is in focus--> <item android:state_enabled=\"true\" android:state_focused=\"true\"> <shape android:shape=\"rectangle\"> <solid android:color=\"@android:color/white\" /> <stroke android:width=\"2dp\" android:color=\"@color/colorPrimary\" /> </shape> </item> <!--the outline box turns to grey when the edit text is out of focus--> <item android:state_enabled=\"true\"> <shape android:shape=\"rectangle\"> <solid android:color=\"@android:color/white\" /> <stroke android:width=\"2dp\" android:color=\"@android:color/darker_gray\" /> </shape> </item> </selector>", "e": 30665, "s": 29871, "text": null }, { "code": null, "e": 30713, "s": 30665, "text": "Step 2: Working with the activity_main.xml file" }, { "code": null, "e": 30811, "s": 30713, "text": "In the activity_main.xml file invoke the background for the EditText as custom_edit_text_cut.xml." }, { "code": null, "e": 30815, "s": 30811, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><ScrollView 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\" tools:ignore=\"HardcodedText\"> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:orientation=\"vertical\"> <!--invoke the background as the custom_edit_text_cut--> <EditText android:id=\"@+id/emailField1\" android:layout_width=\"match_parent\" android:layout_height=\"60dp\" android:layout_marginStart=\"16dp\" android:layout_marginTop=\"32dp\" android:layout_marginEnd=\"16dp\" android:background=\"@drawable/custom_edit_text_cut\" android:drawableStart=\"@drawable/custom_mail_icon\" android:drawablePadding=\"12dp\" android:hint=\"Email\" android:paddingStart=\"12dp\" android:paddingEnd=\"12dp\" /> <!--same background for the password field as the custom_edit_text_cut--> <EditText android:id=\"@+id/passwordField1\" android:layout_width=\"match_parent\" android:layout_height=\"60dp\" android:layout_marginStart=\"16dp\" android:layout_marginTop=\"16dp\" android:layout_marginEnd=\"16dp\" android:background=\"@drawable/custom_edit_text_cut\" android:drawableStart=\"@drawable/custom_vpn_icon\" android:drawablePadding=\"12dp\" android:hint=\"Password\" android:paddingStart=\"12dp\" android:paddingEnd=\"12dp\" /> </LinearLayout> </ScrollView>", "e": 32590, "s": 30815, "text": null }, { "code": null, "e": 32651, "s": 32590, "text": "Step 1: Create a Selector layout background for the EditText" }, { "code": null, "e": 32726, "s": 32651, "text": "This is the layout that gives the cut-cornered box for the EditText field." }, { "code": null, "e": 32848, "s": 32726, "text": "To implement the same create a custom_edit_text_rounded.xml file under the drawable folder and invoke the following code." }, { "code": null, "e": 32852, "s": 32848, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><selector xmlns:android=\"http://schemas.android.com/apk/res/android\"> <!--The outline turns to colorPrimary when the EditText is in focus--> <item android:state_enabled=\"true\" android:state_focused=\"true\"> <shape android:shape=\"rectangle\"> <solid android:color=\"@android:color/white\" /> <corners android:radius=\"12dp\" /> <stroke android:width=\"2dp\" android:color=\"@color/colorPrimary\" /> </shape> </item> <!--The outline turns to grey when the EditText is out of focus--> <item android:state_enabled=\"true\"> <shape android:shape=\"rectangle\"> <solid android:color=\"@android:color/white\" /> <corners android:radius=\"12dp\" /> <stroke android:width=\"2dp\" android:color=\"@android:color/darker_gray\" /> </shape> </item> </selector>", "e": 33733, "s": 32852, "text": null }, { "code": null, "e": 33781, "s": 33733, "text": "Step 2: Working with the activity_main.xml file" }, { "code": null, "e": 33883, "s": 33781, "text": "In the activity_main.xml file invoke the background for the EditText as custom_edit_text_rounded.xml." }, { "code": null, "e": 33887, "s": 33883, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><ScrollView 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\" tools:ignore=\"HardcodedText\"> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:orientation=\"vertical\"> <!--invoke the background as the custom_edit_text_rounded--> <EditText android:id=\"@+id/emailField1\" android:layout_width=\"match_parent\" android:layout_height=\"60dp\" android:layout_marginStart=\"16dp\" android:layout_marginTop=\"32dp\" android:layout_marginEnd=\"16dp\" android:background=\"@drawable/custom_edit_text_rounded\" android:drawableStart=\"@drawable/custom_mail_icon\" android:drawablePadding=\"12dp\" android:hint=\"Email\" android:paddingStart=\"12dp\" android:paddingEnd=\"12dp\" /> <!--same background for the password field as the custom_edit_text_rounded--> <EditText android:id=\"@+id/passwordField1\" android:layout_width=\"match_parent\" android:layout_height=\"60dp\" android:layout_marginStart=\"16dp\" android:layout_marginTop=\"32dp\" android:layout_marginEnd=\"16dp\" android:background=\"@drawable/custom_edit_text_rounded\" android:drawableStart=\"@drawable/custom_vpn_icon\" android:drawablePadding=\"12dp\" android:hint=\"Password\" android:paddingStart=\"12dp\" android:paddingEnd=\"12dp\" /> </LinearLayout> </ScrollView>", "e": 35678, "s": 33887, "text": null }, { "code": null, "e": 35686, "s": 35678, "text": "android" }, { "code": null, "e": 35699, "s": 35686, "text": "Android-View" }, { "code": null, "e": 35723, "s": 35699, "text": "Technical Scripter 2020" }, { "code": null, "e": 35731, "s": 35723, "text": "Android" }, { "code": null, "e": 35750, "s": 35731, "text": "Technical Scripter" }, { "code": null, "e": 35758, "s": 35750, "text": "Android" }, { "code": null, "e": 35856, "s": 35758, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35894, "s": 35856, "text": "Resource Raw Folder in Android Studio" }, { "code": null, "e": 35933, "s": 35894, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 35983, "s": 35933, "text": "How to Read Data from SQLite Database in Android?" }, { "code": null, "e": 36034, "s": 35983, "text": "How to Post Data to API using Retrofit in Android?" }, { "code": null, "e": 36076, "s": 36034, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 36116, "s": 36076, "text": "How to Get Current Location in Android?" }, { "code": null, "e": 36154, "s": 36116, "text": "Android Listview in Java with Example" }, { "code": null, "e": 36217, "s": 36154, "text": "How to Save Data to the Firebase Realtime Database in Android?" }, { "code": null, "e": 36243, "s": 36217, "text": "Flexbox-Layout in Android" } ]
Python DateTime weekday() Method with Example - GeeksforGeeks
23 Aug, 2021 In this article, we will discuss the weekday() function in the DateTime module. weekday() function is used to get the week number based on given DateTime. It will return the number in the range of 0-6 It will take input as DateTime in the format of “(YYYY, MM, DD, HH, MM, SS)”, where, YYYY stands for year MM stands for Month DD stands for Date HH stands for Hour MM stands for minute SS stands for second We first need to import the DateTime module and create a DateTime, now using weekday() function we will get the weekday for a particular DateTime. Syntax: datetime(YYYY,MM,DD, HH,MM,SS).weekday() we can also extract date from DateTime by using the following syntax: Syntax: datetime(YYYY,MM,DD, HH,MM,SS).date() Example: Python program to create DateTime and display DateTime and date Python3 # importing datetime classfrom datetime import datetime # create datetimex = datetime(2021, 8, 8, 12, 5, 6) # displayprint("Datetime is :", x) # get the dateprint("Date is :", x.date()) Output: Datetime is : 2021-08-08 12:05:06 Date is : 2021-08-08 Example: Python program to get the weekdays for the given datetime(s) Python3 # importing datetime classfrom datetime import datetime # create datetimex = datetime(2021, 8, 8, 12, 5, 6) # displayprint("Datetime is :", x) # get the weekdayprint("weekday is :", x.weekday()) # create datetimex = datetime(2021, 9, 10, 12, 5, 6) # displayprint("Datetime is :", x) # get the weekdayprint("weekday is :", x.weekday()) # create datetimex = datetime(2020, 1, 8, 12, 5, 6) # displayprint("Datetime is :", x) # get the weekdayprint("weekday is :", x.weekday()) Output: Datetime is : 2021-08-08 12:05:06 weekday is : 6 Datetime is : 2021-09-10 12:05:06 weekday is : 4 Datetime is : 2020-01-08 12:05:06 weekday is : 2 Example 3: Python program to get the name of weekday Python3 # create a list of weekdaysfrom datetime import datetime days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"] # importing datetime class # create datetimex = datetime(2021, 8, 8, 12, 5, 6) # displayprint("Datetime is :", x) # get the weekday name using indexprint("weekday is :", days[x.weekday()]) # create datetimex = datetime(2021, 9, 10, 12, 5, 6) # displayprint("Datetime is :", x) # get the weekday name using indexprint("weekday is :", days[x.weekday()]) # create datetime using indexx = datetime(2020, 1, 8, 12, 5, 6) # displayprint("Datetime is :", x) # get the weekday name using indexprint("weekday is :", days[x.weekday()]) Output: Datetime is : 2021-08-08 12:05:06 weekday is : Sunday Datetime is : 2021-09-10 12:05:06 weekday is : Friday Datetime is : 2020-01-08 12:05:06 weekday is : Wednesday Picked Python-datetime 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? Python Classes and Objects How to drop one or multiple columns in Pandas Dataframe Defaultdict in Python Python | Get unique values from a list Python | os.path.join() method Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n23 Aug, 2021" }, { "code": null, "e": 25738, "s": 25537, "text": "In this article, we will discuss the weekday() function in the DateTime module. weekday() function is used to get the week number based on given DateTime. It will return the number in the range of 0-6" }, { "code": null, "e": 25823, "s": 25738, "text": "It will take input as DateTime in the format of “(YYYY, MM, DD, HH, MM, SS)”, where," }, { "code": null, "e": 25844, "s": 25823, "text": "YYYY stands for year" }, { "code": null, "e": 25864, "s": 25844, "text": "MM stands for Month" }, { "code": null, "e": 25883, "s": 25864, "text": "DD stands for Date" }, { "code": null, "e": 25902, "s": 25883, "text": "HH stands for Hour" }, { "code": null, "e": 25923, "s": 25902, "text": "MM stands for minute" }, { "code": null, "e": 25944, "s": 25923, "text": "SS stands for second" }, { "code": null, "e": 26091, "s": 25944, "text": "We first need to import the DateTime module and create a DateTime, now using weekday() function we will get the weekday for a particular DateTime." }, { "code": null, "e": 26099, "s": 26091, "text": "Syntax:" }, { "code": null, "e": 26140, "s": 26099, "text": "datetime(YYYY,MM,DD, HH,MM,SS).weekday()" }, { "code": null, "e": 26210, "s": 26140, "text": "we can also extract date from DateTime by using the following syntax:" }, { "code": null, "e": 26218, "s": 26210, "text": "Syntax:" }, { "code": null, "e": 26256, "s": 26218, "text": "datetime(YYYY,MM,DD, HH,MM,SS).date()" }, { "code": null, "e": 26329, "s": 26256, "text": "Example: Python program to create DateTime and display DateTime and date" }, { "code": null, "e": 26337, "s": 26329, "text": "Python3" }, { "code": "# importing datetime classfrom datetime import datetime # create datetimex = datetime(2021, 8, 8, 12, 5, 6) # displayprint(\"Datetime is :\", x) # get the dateprint(\"Date is :\", x.date())", "e": 26528, "s": 26337, "text": null }, { "code": null, "e": 26536, "s": 26528, "text": "Output:" }, { "code": null, "e": 26570, "s": 26536, "text": "Datetime is : 2021-08-08 12:05:06" }, { "code": null, "e": 26591, "s": 26570, "text": "Date is : 2021-08-08" }, { "code": null, "e": 26661, "s": 26591, "text": "Example: Python program to get the weekdays for the given datetime(s)" }, { "code": null, "e": 26669, "s": 26661, "text": "Python3" }, { "code": "# importing datetime classfrom datetime import datetime # create datetimex = datetime(2021, 8, 8, 12, 5, 6) # displayprint(\"Datetime is :\", x) # get the weekdayprint(\"weekday is :\", x.weekday()) # create datetimex = datetime(2021, 9, 10, 12, 5, 6) # displayprint(\"Datetime is :\", x) # get the weekdayprint(\"weekday is :\", x.weekday()) # create datetimex = datetime(2020, 1, 8, 12, 5, 6) # displayprint(\"Datetime is :\", x) # get the weekdayprint(\"weekday is :\", x.weekday())", "e": 27160, "s": 26669, "text": null }, { "code": null, "e": 27168, "s": 27160, "text": "Output:" }, { "code": null, "e": 27202, "s": 27168, "text": "Datetime is : 2021-08-08 12:05:06" }, { "code": null, "e": 27217, "s": 27202, "text": "weekday is : 6" }, { "code": null, "e": 27251, "s": 27217, "text": "Datetime is : 2021-09-10 12:05:06" }, { "code": null, "e": 27266, "s": 27251, "text": "weekday is : 4" }, { "code": null, "e": 27300, "s": 27266, "text": "Datetime is : 2020-01-08 12:05:06" }, { "code": null, "e": 27315, "s": 27300, "text": "weekday is : 2" }, { "code": null, "e": 27368, "s": 27315, "text": "Example 3: Python program to get the name of weekday" }, { "code": null, "e": 27376, "s": 27368, "text": "Python3" }, { "code": "# create a list of weekdaysfrom datetime import datetime days = [\"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\", \"Sunday\"] # importing datetime class # create datetimex = datetime(2021, 8, 8, 12, 5, 6) # displayprint(\"Datetime is :\", x) # get the weekday name using indexprint(\"weekday is :\", days[x.weekday()]) # create datetimex = datetime(2021, 9, 10, 12, 5, 6) # displayprint(\"Datetime is :\", x) # get the weekday name using indexprint(\"weekday is :\", days[x.weekday()]) # create datetime using indexx = datetime(2020, 1, 8, 12, 5, 6) # displayprint(\"Datetime is :\", x) # get the weekday name using indexprint(\"weekday is :\", days[x.weekday()])", "e": 28072, "s": 27376, "text": null }, { "code": null, "e": 28080, "s": 28072, "text": "Output:" }, { "code": null, "e": 28114, "s": 28080, "text": "Datetime is : 2021-08-08 12:05:06" }, { "code": null, "e": 28134, "s": 28114, "text": "weekday is : Sunday" }, { "code": null, "e": 28168, "s": 28134, "text": "Datetime is : 2021-09-10 12:05:06" }, { "code": null, "e": 28188, "s": 28168, "text": "weekday is : Friday" }, { "code": null, "e": 28222, "s": 28188, "text": "Datetime is : 2020-01-08 12:05:06" }, { "code": null, "e": 28245, "s": 28222, "text": "weekday is : Wednesday" }, { "code": null, "e": 28252, "s": 28245, "text": "Picked" }, { "code": null, "e": 28268, "s": 28252, "text": "Python-datetime" }, { "code": null, "e": 28275, "s": 28268, "text": "Python" }, { "code": null, "e": 28373, "s": 28275, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28405, "s": 28373, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28447, "s": 28405, "text": "Check if element exists in list in Python" }, { "code": null, "e": 28489, "s": 28447, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 28516, "s": 28489, "text": "Python Classes and Objects" }, { "code": null, "e": 28572, "s": 28516, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28594, "s": 28572, "text": "Defaultdict in Python" }, { "code": null, "e": 28633, "s": 28594, "text": "Python | Get unique values from a list" }, { "code": null, "e": 28664, "s": 28633, "text": "Python | os.path.join() method" }, { "code": null, "e": 28693, "s": 28664, "text": "Create a directory in Python" } ]
Extracting Tweets containing a particular Hashtag using Python - GeeksforGeeks
29 Dec, 2021 Twitter is one of the most popular social media platforms. The Twitter API provides the tools you need to contribute to, engage with, and analyze the conversation happening on Twitter, which finds a lot of application in fields like Data Analytics and Artificial Intelligence. This article focuses on how to extract tweets having a particular Hashtag starting from a given date. Tweepy is a Python package meant for easy accessing of the Twitter API. Almost all the functionality provided by Twitter API can be used through Tweepy. To install this type the below command in the terminal. pip install Tweepy Pandas is a very powerful framework for data analysis in python. It is built on Numpy Package and its key data structure is a DataFrame where one can manipulate tabular data. To install this type the below command in the terminal. pip install pandas Create a Twitter Developer account and obtain your consumer secret key and access token Install Tweepy and Pandas module on your system by running this command in Command Prompt Import required modules.Create an explicit function to display tweet data.Create another function to scrape data regarding a given Hashtag using tweepy module.In the Driver Code assign Twitter Developer account credentials along with the Hashtag, initial date and number of tweets.Finally, call the function to scrape the data with Hashtag, initial date and number of tweets as argument. Import required modules. Create an explicit function to display tweet data. Create another function to scrape data regarding a given Hashtag using tweepy module. In the Driver Code assign Twitter Developer account credentials along with the Hashtag, initial date and number of tweets. Finally, call the function to scrape the data with Hashtag, initial date and number of tweets as argument. Below is the complete program based on the above approach: Python # Python Script to Extract tweets of a# particular Hashtag using Tweepy and Pandas # import modulesimport pandas as pdimport tweepy # function to display data of each tweetdef printtweetdata(n, ith_tweet): print() print(f"Tweet {n}:") print(f"Username:{ith_tweet[0]}") print(f"Description:{ith_tweet[1]}") print(f"Location:{ith_tweet[2]}") print(f"Following Count:{ith_tweet[3]}") print(f"Follower Count:{ith_tweet[4]}") print(f"Total Tweets:{ith_tweet[5]}") print(f"Retweet Count:{ith_tweet[6]}") print(f"Tweet Text:{ith_tweet[7]}") print(f"Hashtags Used:{ith_tweet[8]}") # function to perform data extractiondef scrape(words, date_since, numtweet): # Creating DataFrame using pandas db = pd.DataFrame(columns=['username', 'description', 'location', 'following', 'followers', 'totaltweets', 'retweetcount', 'text', 'hashtags']) # We are using .Cursor() to search # through twitter for the required tweets. # The number of tweets can be # restricted using .items(number of tweets) tweets = tweepy.Cursor(api.search_tweets, words, lang="en", since_id=date_since, tweet_mode='extended').items(numtweet) # .Cursor() returns an iterable object. Each item in # the iterator has various attributes # that you can access to # get information about each tweet list_tweets = [tweet for tweet in tweets] # Counter to maintain Tweet Count i = 1 # we will iterate over each tweet in the # list for extracting information about each tweet for tweet in list_tweets: username = tweet.user.screen_name description = tweet.user.description location = tweet.user.location following = tweet.user.friends_count followers = tweet.user.followers_count totaltweets = tweet.user.statuses_count retweetcount = tweet.retweet_count hashtags = tweet.entities['hashtags'] # Retweets can be distinguished by # a retweeted_status attribute, # in case it is an invalid reference, # except block will be executed try: text = tweet.retweeted_status.full_text except AttributeError: text = tweet.full_text hashtext = list() for j in range(0, len(hashtags)): hashtext.append(hashtags[j]['text']) # Here we are appending all the # extracted information in the DataFrame ith_tweet = [username, description, location, following, followers, totaltweets, retweetcount, text, hashtext] db.loc[len(db)] = ith_tweet # Function call to print tweet data on screen printtweetdata(i, ith_tweet) i = i+1 filename = 'scraped_tweets.csv' # we will save our database as a CSV file. db.to_csv(filename) if __name__ == '__main__': # Enter your own credentials obtained # from your developer account consumer_key = "XXXXXXXXXXXXXXXXXXXXX" consumer_secret = "XXXXXXXXXXXXXXXXXXXXX" access_key = "XXXXXXXXXXXXXXXXXXXXX" access_secret = "XXXXXXXXXXXXXXXXXXXXX" auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_key, access_secret) api = tweepy.API(auth) # Enter Hashtag and initial date print("Enter Twitter HashTag to search for") words = input() print("Enter Date since The Tweets are required in yyyy-mm--dd") date_since = input() # number of tweets you want to extract in one run numtweet = 100 scrape(words, date_since, numtweet) print('Scraping has completed!') Output: Demo: ParagPallavSingh1 Python-Tweepy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | Get unique values from a list Python | os.path.join() method Create a directory in Python Defaultdict in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n29 Dec, 2021" }, { "code": null, "e": 25916, "s": 25537, "text": "Twitter is one of the most popular social media platforms. The Twitter API provides the tools you need to contribute to, engage with, and analyze the conversation happening on Twitter, which finds a lot of application in fields like Data Analytics and Artificial Intelligence. This article focuses on how to extract tweets having a particular Hashtag starting from a given date." }, { "code": null, "e": 26125, "s": 25916, "text": "Tweepy is a Python package meant for easy accessing of the Twitter API. Almost all the functionality provided by Twitter API can be used through Tweepy. To install this type the below command in the terminal." }, { "code": null, "e": 26144, "s": 26125, "text": "pip install Tweepy" }, { "code": null, "e": 26375, "s": 26144, "text": "Pandas is a very powerful framework for data analysis in python. It is built on Numpy Package and its key data structure is a DataFrame where one can manipulate tabular data. To install this type the below command in the terminal." }, { "code": null, "e": 26394, "s": 26375, "text": "pip install pandas" }, { "code": null, "e": 26482, "s": 26394, "text": "Create a Twitter Developer account and obtain your consumer secret key and access token" }, { "code": null, "e": 26572, "s": 26482, "text": "Install Tweepy and Pandas module on your system by running this command in Command Prompt" }, { "code": null, "e": 26960, "s": 26572, "text": "Import required modules.Create an explicit function to display tweet data.Create another function to scrape data regarding a given Hashtag using tweepy module.In the Driver Code assign Twitter Developer account credentials along with the Hashtag, initial date and number of tweets.Finally, call the function to scrape the data with Hashtag, initial date and number of tweets as argument." }, { "code": null, "e": 26985, "s": 26960, "text": "Import required modules." }, { "code": null, "e": 27036, "s": 26985, "text": "Create an explicit function to display tweet data." }, { "code": null, "e": 27122, "s": 27036, "text": "Create another function to scrape data regarding a given Hashtag using tweepy module." }, { "code": null, "e": 27245, "s": 27122, "text": "In the Driver Code assign Twitter Developer account credentials along with the Hashtag, initial date and number of tweets." }, { "code": null, "e": 27352, "s": 27245, "text": "Finally, call the function to scrape the data with Hashtag, initial date and number of tweets as argument." }, { "code": null, "e": 27411, "s": 27352, "text": "Below is the complete program based on the above approach:" }, { "code": null, "e": 27418, "s": 27411, "text": "Python" }, { "code": "# Python Script to Extract tweets of a# particular Hashtag using Tweepy and Pandas # import modulesimport pandas as pdimport tweepy # function to display data of each tweetdef printtweetdata(n, ith_tweet): print() print(f\"Tweet {n}:\") print(f\"Username:{ith_tweet[0]}\") print(f\"Description:{ith_tweet[1]}\") print(f\"Location:{ith_tweet[2]}\") print(f\"Following Count:{ith_tweet[3]}\") print(f\"Follower Count:{ith_tweet[4]}\") print(f\"Total Tweets:{ith_tweet[5]}\") print(f\"Retweet Count:{ith_tweet[6]}\") print(f\"Tweet Text:{ith_tweet[7]}\") print(f\"Hashtags Used:{ith_tweet[8]}\") # function to perform data extractiondef scrape(words, date_since, numtweet): # Creating DataFrame using pandas db = pd.DataFrame(columns=['username', 'description', 'location', 'following', 'followers', 'totaltweets', 'retweetcount', 'text', 'hashtags']) # We are using .Cursor() to search # through twitter for the required tweets. # The number of tweets can be # restricted using .items(number of tweets) tweets = tweepy.Cursor(api.search_tweets, words, lang=\"en\", since_id=date_since, tweet_mode='extended').items(numtweet) # .Cursor() returns an iterable object. Each item in # the iterator has various attributes # that you can access to # get information about each tweet list_tweets = [tweet for tweet in tweets] # Counter to maintain Tweet Count i = 1 # we will iterate over each tweet in the # list for extracting information about each tweet for tweet in list_tweets: username = tweet.user.screen_name description = tweet.user.description location = tweet.user.location following = tweet.user.friends_count followers = tweet.user.followers_count totaltweets = tweet.user.statuses_count retweetcount = tweet.retweet_count hashtags = tweet.entities['hashtags'] # Retweets can be distinguished by # a retweeted_status attribute, # in case it is an invalid reference, # except block will be executed try: text = tweet.retweeted_status.full_text except AttributeError: text = tweet.full_text hashtext = list() for j in range(0, len(hashtags)): hashtext.append(hashtags[j]['text']) # Here we are appending all the # extracted information in the DataFrame ith_tweet = [username, description, location, following, followers, totaltweets, retweetcount, text, hashtext] db.loc[len(db)] = ith_tweet # Function call to print tweet data on screen printtweetdata(i, ith_tweet) i = i+1 filename = 'scraped_tweets.csv' # we will save our database as a CSV file. db.to_csv(filename) if __name__ == '__main__': # Enter your own credentials obtained # from your developer account consumer_key = \"XXXXXXXXXXXXXXXXXXXXX\" consumer_secret = \"XXXXXXXXXXXXXXXXXXXXX\" access_key = \"XXXXXXXXXXXXXXXXXXXXX\" access_secret = \"XXXXXXXXXXXXXXXXXXXXX\" auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_key, access_secret) api = tweepy.API(auth) # Enter Hashtag and initial date print(\"Enter Twitter HashTag to search for\") words = input() print(\"Enter Date since The Tweets are required in yyyy-mm--dd\") date_since = input() # number of tweets you want to extract in one run numtweet = 100 scrape(words, date_since, numtweet) print('Scraping has completed!')", "e": 31784, "s": 27418, "text": null }, { "code": null, "e": 31792, "s": 31784, "text": "Output:" }, { "code": null, "e": 31798, "s": 31792, "text": "Demo:" }, { "code": null, "e": 31816, "s": 31798, "text": "ParagPallavSingh1" }, { "code": null, "e": 31830, "s": 31816, "text": "Python-Tweepy" }, { "code": null, "e": 31837, "s": 31830, "text": "Python" }, { "code": null, "e": 31935, "s": 31837, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31967, "s": 31935, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 32009, "s": 31967, "text": "Check if element exists in list in Python" }, { "code": null, "e": 32051, "s": 32009, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 32107, "s": 32051, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 32134, "s": 32107, "text": "Python Classes and Objects" }, { "code": null, "e": 32173, "s": 32134, "text": "Python | Get unique values from a list" }, { "code": null, "e": 32204, "s": 32173, "text": "Python | os.path.join() method" }, { "code": null, "e": 32233, "s": 32204, "text": "Create a directory in Python" }, { "code": null, "e": 32255, "s": 32233, "text": "Defaultdict in Python" } ]
Scala | Auxiliary Constructor - GeeksforGeeks
17 Jun, 2021 Constructors are used to initializing the object’s state. Like methods, a constructor also contains a collection of statements (i.e. instructions). Statements are executed at the time of object creation. In Scala Program, the constructors other than the primary constructor are known as Auxiliary Constructors. We are allowed to create any number of auxiliary constructors in our Scala class, but a scala class contains only one primary constructor.Auxiliary constructors are defined as methods in the class with the keyword this. We can describe multiple auxiliary constructors, but they must have different parameter lists.Syntax : def this(......) Let’s try to understand Auxiliary constructors with help of some examples. Example #1: Using one Auxiliary Constructor Scala // Scala program to illustrate the// concept of Auxiliary Constructor // Primary constructorclass GFG( Lname: String, Tname: String){ var no: Int = 0;; def show() { println("Language name: " + Lname); println("Topic name: " + Tname); println("Total number of articles: " + no); } // Auxiliary Constructor def this(Lname: String, Tname: String, no:Int) { // Invoking primary constructor this(Lname, Tname) this.no = no }} // Creating objectobject Main{ // Main method def main(args: Array[String]) { // Creating object of GFG class var obj = new GFG("Scala", "Constructor", 4); obj.show(); }} Output: Language name: Scala Topic name: Constructor Total number of articles: 4 In above example, as we can see only one auxiliary constructor is used and primary constructor invoked in that auxiliary constructor. After creating object of GFG class(obj), show() function will be called and print the result. Example #2: Using more than one Auxiliary Constructor. scala // Scala program to illustrate the// concept of more than concept// Auxiliary Constructor // Primary constructorclass Company{ private var Cname = "" private var Employee = 0 // Creating function def show() { println("Language name: " + Cname); println("Total number of employee: " + Employee); } // An auxiliary constructor def this(Cname: String) { // Calls primary constructor this() this.Cname = Cname } // Another auxiliary constructor def this(Cname: String, Employee: Int) { // Calls previous auxiliary constructor this(Cname) this.Employee = Employee }} // Creating objectobject Main{ // Main method def main(args: Array[String]) { // Primary constructor val c1 = new Company c1.show() // First auxiliary constructor val c2 = new Company("GeeksForGeeks") c2.show() // Second auxiliary constructor val c3 = new Company("GeeksForGeeks", 42) c3.show() }} Output: Language name: Total number of employee: 0 Language name: GeeksForGeeks Total number of employee: 0 Language name: GeeksForGeeks Total number of employee: 42 In above example, as we can see two auxiliary constructors are created with different parameters. Auxiliary constructor invoked primary constructor and another auxiliary constructor invoked previously defined auxiliary constructor. In a single class, we are allowed to create one or more than one auxiliary constructors, but they have different signatures or parameter-lists. Each auxiliary constructor must call one of the previously defined constructors, this would be primary constructor or previous auxiliary constructor. The invoke constructor may be a primary or previous auxiliary constructor that comes textually before the calling constructor. The first statement of the auxiliary constructor must contain this keyword. varshagumber28 Scala-Constructor Scala Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Scala Map Scala Lists Scala Tutorial – Learn Scala with Step By Step Guide Scala List contains() method with example Scala | Arrays Scala String substring() method with example How to get the first element of List in Scala Lambda Expression in Scala Scala String replace() method with example Scala Map get() method with example
[ { "code": null, "e": 25113, "s": 25085, "text": "\n17 Jun, 2021" }, { "code": null, "e": 25749, "s": 25113, "text": "Constructors are used to initializing the object’s state. Like methods, a constructor also contains a collection of statements (i.e. instructions). Statements are executed at the time of object creation. In Scala Program, the constructors other than the primary constructor are known as Auxiliary Constructors. We are allowed to create any number of auxiliary constructors in our Scala class, but a scala class contains only one primary constructor.Auxiliary constructors are defined as methods in the class with the keyword this. We can describe multiple auxiliary constructors, but they must have different parameter lists.Syntax : " }, { "code": null, "e": 25766, "s": 25749, "text": "def this(......)" }, { "code": null, "e": 25887, "s": 25766, "text": "Let’s try to understand Auxiliary constructors with help of some examples. Example #1: Using one Auxiliary Constructor " }, { "code": null, "e": 25893, "s": 25887, "text": "Scala" }, { "code": "// Scala program to illustrate the// concept of Auxiliary Constructor // Primary constructorclass GFG( Lname: String, Tname: String){ var no: Int = 0;; def show() { println(\"Language name: \" + Lname); println(\"Topic name: \" + Tname); println(\"Total number of articles: \" + no); } // Auxiliary Constructor def this(Lname: String, Tname: String, no:Int) { // Invoking primary constructor this(Lname, Tname) this.no = no }} // Creating objectobject Main{ // Main method def main(args: Array[String]) { // Creating object of GFG class var obj = new GFG(\"Scala\", \"Constructor\", 4); obj.show(); }}", "e": 26616, "s": 25893, "text": null }, { "code": null, "e": 26626, "s": 26616, "text": "Output: " }, { "code": null, "e": 26699, "s": 26626, "text": "Language name: Scala\nTopic name: Constructor\nTotal number of articles: 4" }, { "code": null, "e": 26986, "s": 26699, "text": "In above example, as we can see only one auxiliary constructor is used and primary constructor invoked in that auxiliary constructor. After creating object of GFG class(obj), show() function will be called and print the result. Example #2: Using more than one Auxiliary Constructor. " }, { "code": null, "e": 26992, "s": 26986, "text": "scala" }, { "code": "// Scala program to illustrate the// concept of more than concept// Auxiliary Constructor // Primary constructorclass Company{ private var Cname = \"\" private var Employee = 0 // Creating function def show() { println(\"Language name: \" + Cname); println(\"Total number of employee: \" + Employee); } // An auxiliary constructor def this(Cname: String) { // Calls primary constructor this() this.Cname = Cname } // Another auxiliary constructor def this(Cname: String, Employee: Int) { // Calls previous auxiliary constructor this(Cname) this.Employee = Employee }} // Creating objectobject Main{ // Main method def main(args: Array[String]) { // Primary constructor val c1 = new Company c1.show() // First auxiliary constructor val c2 = new Company(\"GeeksForGeeks\") c2.show() // Second auxiliary constructor val c3 = new Company(\"GeeksForGeeks\", 42) c3.show() }}", "e": 28059, "s": 26992, "text": null }, { "code": null, "e": 28069, "s": 28059, "text": "Output: " }, { "code": null, "e": 28228, "s": 28069, "text": "Language name: \nTotal number of employee: 0\nLanguage name: GeeksForGeeks\nTotal number of employee: 0\nLanguage name: GeeksForGeeks\nTotal number of employee: 42" }, { "code": null, "e": 28461, "s": 28228, "text": "In above example, as we can see two auxiliary constructors are created with different parameters. Auxiliary constructor invoked primary constructor and another auxiliary constructor invoked previously defined auxiliary constructor. " }, { "code": null, "e": 28607, "s": 28463, "text": "In a single class, we are allowed to create one or more than one auxiliary constructors, but they have different signatures or parameter-lists." }, { "code": null, "e": 28757, "s": 28607, "text": "Each auxiliary constructor must call one of the previously defined constructors, this would be primary constructor or previous auxiliary constructor." }, { "code": null, "e": 28884, "s": 28757, "text": "The invoke constructor may be a primary or previous auxiliary constructor that comes textually before the calling constructor." }, { "code": null, "e": 28960, "s": 28884, "text": "The first statement of the auxiliary constructor must contain this keyword." }, { "code": null, "e": 28977, "s": 28962, "text": "varshagumber28" }, { "code": null, "e": 28995, "s": 28977, "text": "Scala-Constructor" }, { "code": null, "e": 29001, "s": 28995, "text": "Scala" }, { "code": null, "e": 29099, "s": 29001, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29109, "s": 29099, "text": "Scala Map" }, { "code": null, "e": 29121, "s": 29109, "text": "Scala Lists" }, { "code": null, "e": 29174, "s": 29121, "text": "Scala Tutorial – Learn Scala with Step By Step Guide" }, { "code": null, "e": 29216, "s": 29174, "text": "Scala List contains() method with example" }, { "code": null, "e": 29231, "s": 29216, "text": "Scala | Arrays" }, { "code": null, "e": 29276, "s": 29231, "text": "Scala String substring() method with example" }, { "code": null, "e": 29322, "s": 29276, "text": "How to get the first element of List in Scala" }, { "code": null, "e": 29349, "s": 29322, "text": "Lambda Expression in Scala" }, { "code": null, "e": 29392, "s": 29349, "text": "Scala String replace() method with example" } ]
Logger setLevel() method in Java with Examples - GeeksforGeeks
26 Mar, 2019 setLevel() method of a Logger class used to set the log level to describe which message levels will be logged by this logger. The level we want to set is passed as a parameter. Message levels lower than passed log level value will be discarded by the logger. The level value Level.OFF can be used to turn off logging. Log Levels: The log levels control the logging details. They determine the extent to which depth the log files are generated. Each level is associated with a numeric value and there are 7 basic log levels and 2 special ones. We need to specify the desired level of logging every time, we seek to interact with the log system. To know more about Log Levels, refer this Log Levels in Logging. Syntax: public void setLevel(Level newLevel) throws SecurityException Parameters: This method accepts one parameter newLevel which represents the new value for the log level. Return value: This method returns nothing. Exception: This method throws SecurityException if a security manager exists, this logger is not anonymous, and the caller does not have LoggingPermission(“control”). Below programs illustrate the setLevel() method:Program 1: // Java program to demonstrate// Logger.setLevel() method import java.util.logging.*; public class GFG { public static void main(String[] args) throws SecurityException { // Create a logger Logger logger = Logger.getLogger( GFG.class.getName()); // Set log levels logger.setLevel(Level.FINEST); // Print log level System.out.println("Log Level = " + logger.getLevel()); }} Output:The output printed on console of Eclipse is shown below- Program 2: // Java program to demonstrate// Logger.setLevel() method import java.util.logging.*; public class GFG { public static void main(String[] args) throws SecurityException { // Create a logger Logger logger = Logger.getLogger( GFG.class.getName()); // Set log levels logger.setLevel(Level.WARNING); // Print log level System.out.println("Log Level = " + logger.getLevel()); }} Output:The output printed on console output is shown below- Reference: https://docs.oracle.com/javase/10/docs/api/java/util/logging/Logger.html#setLevel(java.util.logging.Level) Java - util package Java-Functions Java-Logger Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Constructors in Java Exceptions in Java Functional Interfaces in Java Different ways of Reading a text file in Java Generics in Java Introduction to Java Comparator Interface in Java with Examples Internal Working of HashMap in Java Strings in Java
[ { "code": null, "e": 25225, "s": 25197, "text": "\n26 Mar, 2019" }, { "code": null, "e": 25543, "s": 25225, "text": "setLevel() method of a Logger class used to set the log level to describe which message levels will be logged by this logger. The level we want to set is passed as a parameter. Message levels lower than passed log level value will be discarded by the logger. The level value Level.OFF can be used to turn off logging." }, { "code": null, "e": 25934, "s": 25543, "text": "Log Levels: The log levels control the logging details. They determine the extent to which depth the log files are generated. Each level is associated with a numeric value and there are 7 basic log levels and 2 special ones. We need to specify the desired level of logging every time, we seek to interact with the log system. To know more about Log Levels, refer this Log Levels in Logging." }, { "code": null, "e": 25942, "s": 25934, "text": "Syntax:" }, { "code": null, "e": 26019, "s": 25942, "text": "public void setLevel(Level newLevel)\n throws SecurityException\n" }, { "code": null, "e": 26124, "s": 26019, "text": "Parameters: This method accepts one parameter newLevel which represents the new value for the log level." }, { "code": null, "e": 26167, "s": 26124, "text": "Return value: This method returns nothing." }, { "code": null, "e": 26334, "s": 26167, "text": "Exception: This method throws SecurityException if a security manager exists, this logger is not anonymous, and the caller does not have LoggingPermission(“control”)." }, { "code": null, "e": 26393, "s": 26334, "text": "Below programs illustrate the setLevel() method:Program 1:" }, { "code": "// Java program to demonstrate// Logger.setLevel() method import java.util.logging.*; public class GFG { public static void main(String[] args) throws SecurityException { // Create a logger Logger logger = Logger.getLogger( GFG.class.getName()); // Set log levels logger.setLevel(Level.FINEST); // Print log level System.out.println(\"Log Level = \" + logger.getLevel()); }}", "e": 26886, "s": 26393, "text": null }, { "code": null, "e": 26950, "s": 26886, "text": "Output:The output printed on console of Eclipse is shown below-" }, { "code": null, "e": 26961, "s": 26950, "text": "Program 2:" }, { "code": "// Java program to demonstrate// Logger.setLevel() method import java.util.logging.*; public class GFG { public static void main(String[] args) throws SecurityException { // Create a logger Logger logger = Logger.getLogger( GFG.class.getName()); // Set log levels logger.setLevel(Level.WARNING); // Print log level System.out.println(\"Log Level = \" + logger.getLevel()); }}", "e": 27455, "s": 26961, "text": null }, { "code": null, "e": 27515, "s": 27455, "text": "Output:The output printed on console output is shown below-" }, { "code": null, "e": 27633, "s": 27515, "text": "Reference: https://docs.oracle.com/javase/10/docs/api/java/util/logging/Logger.html#setLevel(java.util.logging.Level)" }, { "code": null, "e": 27653, "s": 27633, "text": "Java - util package" }, { "code": null, "e": 27668, "s": 27653, "text": "Java-Functions" }, { "code": null, "e": 27680, "s": 27668, "text": "Java-Logger" }, { "code": null, "e": 27685, "s": 27680, "text": "Java" }, { "code": null, "e": 27690, "s": 27685, "text": "Java" }, { "code": null, "e": 27788, "s": 27690, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27803, "s": 27788, "text": "Stream In Java" }, { "code": null, "e": 27824, "s": 27803, "text": "Constructors in Java" }, { "code": null, "e": 27843, "s": 27824, "text": "Exceptions in Java" }, { "code": null, "e": 27873, "s": 27843, "text": "Functional Interfaces in Java" }, { "code": null, "e": 27919, "s": 27873, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 27936, "s": 27919, "text": "Generics in Java" }, { "code": null, "e": 27957, "s": 27936, "text": "Introduction to Java" }, { "code": null, "e": 28000, "s": 27957, "text": "Comparator Interface in Java with Examples" }, { "code": null, "e": 28036, "s": 28000, "text": "Internal Working of HashMap in Java" } ]
C program to store Student records as Structures and Sort them by Age or ID
29 May, 2019 Given student’s records with each record containing id, name and age of a student. Write a C program to read these records and display them in sorted order by age or id. Examples: Input: Student Records = { {Id = 1, Name = bd, Age = 12 }, {Id = 2, Name = ba, Age = 10 }, {Id = 3, Name = bc, Age = 8 }, {Id = 4, Name = aaz, Age = 9 }, {Id = 5, Name = az, Age = 10 } } Output: {{Id = 3, Name = bc, Age = 8 }, {Id = 4, Name = aaz, Age = 9 }, {Id = 2, Name = ba, Age = 10 }, {Id = 5, Name = az, Age = 10 }, {Id = 1, Name = bd, Age = 12 } } Approach: This problem is solved in the following steps: Create a structure with fields id, name and age. Read the students records in the structure Define a comparator by setting up rules for comparison. Here age can be sorted with the help of difference of the age of 2 students. (Student1 -> age – Student2 -> age) Now sort the structure based on the defined comparator with the help of qsort() method. Print the sorted students’ records. Program: // C program to read Student records// like id, name and age,// and display them in sorted order by Age #include <stdio.h>#include <stdlib.h>#include <string.h> // struct person with 3 fieldsstruct Student { char* name; int id; char age;}; // setting up rules for comparison// to sort the students based on ageint comparator(const void* p, const void* q){ return (((struct Student*)p)->age - ((struct Student*)q)->age);} // Driver programint main(){ int i = 0, n = 5; struct Student arr[n]; // Get the students data arr[0].id = 1; arr[0].name = "bd"; arr[0].age = 12; arr[1].id = 2; arr[1].name = "ba"; arr[1].age = 10; arr[2].id = 3; arr[2].name = "bc"; arr[2].age = 8; arr[3].id = 4; arr[3].name = "aaz"; arr[3].age = 9; arr[4].id = 5; arr[4].name = "az"; arr[4].age = 10; // Print the Unsorted Structure printf("Unsorted Student Records:\n"); for (i = 0; i < n; i++) { printf("Id = %d, Name = %s, Age = %d \n", arr[i].id, arr[i].name, arr[i].age); } // Sort the structure // based on the specified comparator qsort(arr, n, sizeof(struct Student), comparator); // Print the Sorted Structure printf("\n\nStudent Records sorted by Age:\n"); for (i = 0; i < n; i++) { printf("Id = %d, Name = %s, Age = %d \n", arr[i].id, arr[i].name, arr[i].age); } return 0;} Unsorted Student Records: Id = 1, Name = bd, Age = 12 Id = 2, Name = ba, Age = 10 Id = 3, Name = bc, Age = 8 Id = 4, Name = aaz, Age = 9 Id = 5, Name = az, Age = 10 Student Records sorted by Age: Id = 3, Name = bc, Age = 8 Id = 4, Name = aaz, Age = 9 Id = 2, Name = ba, Age = 10 Id = 5, Name = az, Age = 10 Id = 1, Name = bd, Age = 12 Examples: Input: Student Records = { {Id = 1, Name = bd, Age = 12 }, {Id = 2, Name = ba, Age = 10 }, {Id = 3, Name = bc, Age = 8 }, {Id = 4, Name = aaz, Age = 9 }, {Id = 5, Name = az, Age = 10 } } Output: {{Id = 1, Name = bd, Age = 12 }, {Id = 2, Name = ba, Age = 10 }, {Id = 3, Name = bc, Age = 8 }, {Id = 4, Name = aaz, Age = 9 }, {Id = 5, Name = az, Age = 10 } } Approach: This problem is solved in the following steps: Create a structure with fields id, name and age. Read the students records in the structure Define a comparator by setting up rules for comparison. Here id can be sorted with the help of difference of the id of 2 students. (Student1 -> id – Student2 -> id) Now sort the structure based on the defined comparator with the help of qsort() method. Print the sorted students’ records. Program: // C program to read Student records// like id, name and age,// and display them in sorted order by ID #include <stdio.h>#include <stdlib.h>#include <string.h> // struct person with 3 fieldsstruct Student { char* name; int id; char age;}; // setting up rules for comparison// to sort the students based on IDint comparator(const void* p, const void* q){ return (((struct Student*)p)->id - ((struct Student*)q)->id);} // Driver programint main(){ int i = 0, n = 5; struct Student arr[n]; // Get the students data arr[0].id = 1; arr[0].name = "bd"; arr[0].age = 12; arr[1].id = 2; arr[1].name = "ba"; arr[1].age = 10; arr[2].id = 3; arr[2].name = "bc"; arr[2].age = 8; arr[3].id = 4; arr[3].name = "aaz"; arr[3].age = 9; arr[4].id = 5; arr[4].name = "az"; arr[4].age = 10; // Print the Unsorted Structure printf("Unsorted Student Records:\n"); for (i = 0; i < n; i++) { printf("Id = %d, Name = %s, Age = %d \n", arr[i].id, arr[i].name, arr[i].age); } // Sort the structure // based on the specified comparator qsort(arr, n, sizeof(struct Student), comparator); // Print the Sorted Structure printf("\n\nStudent Records sorted by ID:\n"); for (i = 0; i < n; i++) { printf("Id = %d, Name = %s, Age = %d \n", arr[i].id, arr[i].name, arr[i].age); } return 0;} Unsorted Student Records: Id = 1, Name = bd, Age = 12 Id = 2, Name = ba, Age = 10 Id = 3, Name = bc, Age = 8 Id = 4, Name = aaz, Age = 9 Id = 5, Name = az, Age = 10 Student Records sorted by ID: Id = 1, Name = bd, Age = 12 Id = 2, Name = ba, Age = 10 Id = 3, Name = bc, Age = 8 Id = 4, Name = aaz, Age = 9 Id = 5, Name = az, Age = 10 C-Structure & Union C Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n29 May, 2019" }, { "code": null, "e": 198, "s": 28, "text": "Given student’s records with each record containing id, name and age of a student. Write a C program to read these records and display them in sorted order by age or id." }, { "code": null, "e": 208, "s": 198, "text": "Examples:" }, { "code": null, "e": 566, "s": 208, "text": "Input: Student Records = {\n{Id = 1, Name = bd, Age = 12 },\n{Id = 2, Name = ba, Age = 10 },\n{Id = 3, Name = bc, Age = 8 },\n{Id = 4, Name = aaz, Age = 9 },\n{Id = 5, Name = az, Age = 10 } }\n\nOutput:\n{{Id = 3, Name = bc, Age = 8 },\n{Id = 4, Name = aaz, Age = 9 },\n{Id = 2, Name = ba, Age = 10 },\n{Id = 5, Name = az, Age = 10 },\n{Id = 1, Name = bd, Age = 12 } }\n" }, { "code": null, "e": 623, "s": 566, "text": "Approach: This problem is solved in the following steps:" }, { "code": null, "e": 672, "s": 623, "text": "Create a structure with fields id, name and age." }, { "code": null, "e": 715, "s": 672, "text": "Read the students records in the structure" }, { "code": null, "e": 884, "s": 715, "text": "Define a comparator by setting up rules for comparison. Here age can be sorted with the help of difference of the age of 2 students. (Student1 -> age – Student2 -> age)" }, { "code": null, "e": 972, "s": 884, "text": "Now sort the structure based on the defined comparator with the help of qsort() method." }, { "code": null, "e": 1008, "s": 972, "text": "Print the sorted students’ records." }, { "code": null, "e": 1017, "s": 1008, "text": "Program:" }, { "code": "// C program to read Student records// like id, name and age,// and display them in sorted order by Age #include <stdio.h>#include <stdlib.h>#include <string.h> // struct person with 3 fieldsstruct Student { char* name; int id; char age;}; // setting up rules for comparison// to sort the students based on ageint comparator(const void* p, const void* q){ return (((struct Student*)p)->age - ((struct Student*)q)->age);} // Driver programint main(){ int i = 0, n = 5; struct Student arr[n]; // Get the students data arr[0].id = 1; arr[0].name = \"bd\"; arr[0].age = 12; arr[1].id = 2; arr[1].name = \"ba\"; arr[1].age = 10; arr[2].id = 3; arr[2].name = \"bc\"; arr[2].age = 8; arr[3].id = 4; arr[3].name = \"aaz\"; arr[3].age = 9; arr[4].id = 5; arr[4].name = \"az\"; arr[4].age = 10; // Print the Unsorted Structure printf(\"Unsorted Student Records:\\n\"); for (i = 0; i < n; i++) { printf(\"Id = %d, Name = %s, Age = %d \\n\", arr[i].id, arr[i].name, arr[i].age); } // Sort the structure // based on the specified comparator qsort(arr, n, sizeof(struct Student), comparator); // Print the Sorted Structure printf(\"\\n\\nStudent Records sorted by Age:\\n\"); for (i = 0; i < n; i++) { printf(\"Id = %d, Name = %s, Age = %d \\n\", arr[i].id, arr[i].name, arr[i].age); } return 0;}", "e": 2442, "s": 1017, "text": null }, { "code": null, "e": 2789, "s": 2442, "text": "Unsorted Student Records:\nId = 1, Name = bd, Age = 12 \nId = 2, Name = ba, Age = 10 \nId = 3, Name = bc, Age = 8 \nId = 4, Name = aaz, Age = 9 \nId = 5, Name = az, Age = 10 \n\n\nStudent Records sorted by Age:\nId = 3, Name = bc, Age = 8 \nId = 4, Name = aaz, Age = 9 \nId = 2, Name = ba, Age = 10 \nId = 5, Name = az, Age = 10 \nId = 1, Name = bd, Age = 12\n" }, { "code": null, "e": 2799, "s": 2789, "text": "Examples:" }, { "code": null, "e": 3157, "s": 2799, "text": "Input: Student Records = {\n{Id = 1, Name = bd, Age = 12 },\n{Id = 2, Name = ba, Age = 10 },\n{Id = 3, Name = bc, Age = 8 },\n{Id = 4, Name = aaz, Age = 9 },\n{Id = 5, Name = az, Age = 10 } }\n\nOutput:\n{{Id = 1, Name = bd, Age = 12 },\n{Id = 2, Name = ba, Age = 10 },\n{Id = 3, Name = bc, Age = 8 },\n{Id = 4, Name = aaz, Age = 9 },\n{Id = 5, Name = az, Age = 10 } }\n" }, { "code": null, "e": 3214, "s": 3157, "text": "Approach: This problem is solved in the following steps:" }, { "code": null, "e": 3263, "s": 3214, "text": "Create a structure with fields id, name and age." }, { "code": null, "e": 3306, "s": 3263, "text": "Read the students records in the structure" }, { "code": null, "e": 3471, "s": 3306, "text": "Define a comparator by setting up rules for comparison. Here id can be sorted with the help of difference of the id of 2 students. (Student1 -> id – Student2 -> id)" }, { "code": null, "e": 3559, "s": 3471, "text": "Now sort the structure based on the defined comparator with the help of qsort() method." }, { "code": null, "e": 3595, "s": 3559, "text": "Print the sorted students’ records." }, { "code": null, "e": 3604, "s": 3595, "text": "Program:" }, { "code": "// C program to read Student records// like id, name and age,// and display them in sorted order by ID #include <stdio.h>#include <stdlib.h>#include <string.h> // struct person with 3 fieldsstruct Student { char* name; int id; char age;}; // setting up rules for comparison// to sort the students based on IDint comparator(const void* p, const void* q){ return (((struct Student*)p)->id - ((struct Student*)q)->id);} // Driver programint main(){ int i = 0, n = 5; struct Student arr[n]; // Get the students data arr[0].id = 1; arr[0].name = \"bd\"; arr[0].age = 12; arr[1].id = 2; arr[1].name = \"ba\"; arr[1].age = 10; arr[2].id = 3; arr[2].name = \"bc\"; arr[2].age = 8; arr[3].id = 4; arr[3].name = \"aaz\"; arr[3].age = 9; arr[4].id = 5; arr[4].name = \"az\"; arr[4].age = 10; // Print the Unsorted Structure printf(\"Unsorted Student Records:\\n\"); for (i = 0; i < n; i++) { printf(\"Id = %d, Name = %s, Age = %d \\n\", arr[i].id, arr[i].name, arr[i].age); } // Sort the structure // based on the specified comparator qsort(arr, n, sizeof(struct Student), comparator); // Print the Sorted Structure printf(\"\\n\\nStudent Records sorted by ID:\\n\"); for (i = 0; i < n; i++) { printf(\"Id = %d, Name = %s, Age = %d \\n\", arr[i].id, arr[i].name, arr[i].age); } return 0;}", "e": 5024, "s": 3604, "text": null }, { "code": null, "e": 5370, "s": 5024, "text": "Unsorted Student Records:\nId = 1, Name = bd, Age = 12 \nId = 2, Name = ba, Age = 10 \nId = 3, Name = bc, Age = 8 \nId = 4, Name = aaz, Age = 9 \nId = 5, Name = az, Age = 10 \n\n\nStudent Records sorted by ID:\nId = 1, Name = bd, Age = 12 \nId = 2, Name = ba, Age = 10 \nId = 3, Name = bc, Age = 8 \nId = 4, Name = aaz, Age = 9 \nId = 5, Name = az, Age = 10\n" }, { "code": null, "e": 5390, "s": 5370, "text": "C-Structure & Union" }, { "code": null, "e": 5401, "s": 5390, "text": "C Programs" } ]
Python Program for nth Catalan Number
13 Jun, 2022 Catalan numbers are a sequence of natural numbers that occurs in many interesting counting problems like the following. 1) Count the number of expressions containing n pairs of parentheses which are correctly matched. For n = 3, possible expressions are ((())), ()(()), ()()(), (())(), (()()). 2) Count the number of possible Binary Search Trees with n keys (See this) See this for more applications. The first few Catalan numbers for n = 0, 1, 2, 3, ... are 1, 1, 2, 5, 14, 42, 132, 429, 1430, 4862, ... Recursive Solution Catalan numbers satisfy the following recursive formula. Following is the implementation of above recursive formula. Python3 # A recursive function to find nth catalan numberdef catalan(n): # Base Case if n <= 1: return 1 # Catalan(n) is the sum of catalan(i)*catalan(n-i-1) res = 0 for i in range(n): res += catalan(i) * catalan(n-i-1) return res # Driver Program to test above functionfor i in range(10): print(catalan(i), end=' ') 1 1 2 5 14 42 132 429 1430 4862 Time Complexity: O(2n) Auxiliary Space: O(n) We can observe that the above recursive implementation does a lot of repeated work (we can the same by drawing a recursion tree). Since there are overlapping sub-problems, we can use dynamic programming for this. Following is a Dynamic programming-based implementation in Python. Python3 # A dynamic programming based function to find nth# Catalan number def catalan(n): if (n == 0 or n == 1): return 1 # Table to store results of subproblems catalan = [0 for i in range(n + 1)] # Initialize first two values in table catalan[0] = 1 catalan[1] = 1 # Fill entries in catalan[] using recursive formula for i in range(2, n + 1): catalan[i] = 0 for j in range(i): catalan[i] += catalan[j] * catalan[i-j-1] # Return last entry return catalan[n] # Driver codefor i in range(10): print(catalan(i)) 1 1 2 5 14 42 132 429 1430 4862 Time Complexity: O(n^2)Auxiliary Space: O(n) Please refer complete article on Program for nth Catalan Number for more details! cyberkid05 amartyaghoshgfg chandramauliguptach Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n13 Jun, 2022" }, { "code": null, "e": 148, "s": 28, "text": "Catalan numbers are a sequence of natural numbers that occurs in many interesting counting problems like the following." }, { "code": null, "e": 322, "s": 148, "text": "1) Count the number of expressions containing n pairs of parentheses which are correctly matched. For n = 3, possible expressions are ((())), ()(()), ()()(), (())(), (()())." }, { "code": null, "e": 398, "s": 322, "text": "2) Count the number of possible Binary Search Trees with n keys (See this) " }, { "code": null, "e": 431, "s": 398, "text": "See this for more applications. " }, { "code": null, "e": 535, "s": 431, "text": "The first few Catalan numbers for n = 0, 1, 2, 3, ... are 1, 1, 2, 5, 14, 42, 132, 429, 1430, 4862, ..." }, { "code": null, "e": 555, "s": 535, "text": "Recursive Solution " }, { "code": null, "e": 613, "s": 555, "text": "Catalan numbers satisfy the following recursive formula. " }, { "code": null, "e": 675, "s": 613, "text": "Following is the implementation of above recursive formula. " }, { "code": null, "e": 683, "s": 675, "text": "Python3" }, { "code": "# A recursive function to find nth catalan numberdef catalan(n): # Base Case if n <= 1: return 1 # Catalan(n) is the sum of catalan(i)*catalan(n-i-1) res = 0 for i in range(n): res += catalan(i) * catalan(n-i-1) return res # Driver Program to test above functionfor i in range(10): print(catalan(i), end=' ')", "e": 1030, "s": 683, "text": null }, { "code": null, "e": 1062, "s": 1030, "text": "1 1 2 5 14 42 132 429 1430 4862" }, { "code": null, "e": 1087, "s": 1064, "text": "Time Complexity: O(2n)" }, { "code": null, "e": 1110, "s": 1087, "text": "Auxiliary Space: O(n)" }, { "code": null, "e": 1392, "s": 1110, "text": "We can observe that the above recursive implementation does a lot of repeated work (we can the same by drawing a recursion tree). Since there are overlapping sub-problems, we can use dynamic programming for this. Following is a Dynamic programming-based implementation in Python. " }, { "code": null, "e": 1400, "s": 1392, "text": "Python3" }, { "code": "# A dynamic programming based function to find nth# Catalan number def catalan(n): if (n == 0 or n == 1): return 1 # Table to store results of subproblems catalan = [0 for i in range(n + 1)] # Initialize first two values in table catalan[0] = 1 catalan[1] = 1 # Fill entries in catalan[] using recursive formula for i in range(2, n + 1): catalan[i] = 0 for j in range(i): catalan[i] += catalan[j] * catalan[i-j-1] # Return last entry return catalan[n] # Driver codefor i in range(10): print(catalan(i))", "e": 1973, "s": 1400, "text": null }, { "code": null, "e": 2005, "s": 1973, "text": "1\n1\n2\n5\n14\n42\n132\n429\n1430\n4862" }, { "code": null, "e": 2053, "s": 2007, "text": "Time Complexity: O(n^2)Auxiliary Space: O(n) " }, { "code": null, "e": 2135, "s": 2053, "text": "Please refer complete article on Program for nth Catalan Number for more details!" }, { "code": null, "e": 2146, "s": 2135, "text": "cyberkid05" }, { "code": null, "e": 2162, "s": 2146, "text": "amartyaghoshgfg" }, { "code": null, "e": 2182, "s": 2162, "text": "chandramauliguptach" }, { "code": null, "e": 2198, "s": 2182, "text": "Python Programs" } ]
Convert a sentence into its equivalent mobile numeric keypad sequence
23 Jun, 2022 Given a sentence in the form of a string, convert it into its equivalent mobile numeric keypad sequence. Examples : Input : GEEKSFORGEEKS Output : 4333355777733366677743333557777 For obtaining a number, we need to press a number corresponding to that character for number of times equal to position of the character. For example, for character C, we press number 2 three times and accordingly. Input : HELLO WORLD Output : 4433555555666096667775553 Recommended: Please try your approach on {IDE} first, before moving on to the solution. Chapters descriptions off, selected captions settings, opens captions settings dialog captions off, selected English This is a modal window. Beginning of dialog window. Escape will cancel and close the window. End of dialog window. Follow the steps given below to convert a sentence into its equivalent mobile numeric keypad sequence. For each character, store the sequence which should be obtained at its respective position in an array, i.e. for Z, store 9999. For Y, store 999. For K, store 55 and so on. For each character, subtract ASCII value of ‘A’ and obtain the position in the array pointed by that character and add the sequence stored in that array to a string. If the character is a space, store 0 Print the overall sequence. Below is the implementation of above method : C++ Java Python3 C# PHP Javascript // C++ implementation to convert a// sentence into its equivalent// mobile numeric keypad sequence#include <bits/stdc++.h>using namespace std; // Function which computes the sequencestring printSequence(string arr[], string input){ string output = ""; // length of input string int n = input.length(); for (int i=0; i<n; i++) { // Checking for space if (input[i] == ' ') output = output + "0"; else { // Calculating index for each // character int position = input[i]-'A'; output = output + arr[position]; } } // Output sequence return output;} // Driver functionint main(){ // storing the sequence in array string str[] = {"2","22","222", "3","33","333", "4","44","444", "5","55","555", "6","66","666", "7","77","777","7777", "8","88","888", "9","99","999","9999" }; string input = "GEEKSFORGEEKS"; cout << printSequence(str, input); return 0;} // Java implementation to convert a// sentence into its equivalent// mobile numeric keypad sequenceimport java.util.*; class GFG{ // Function which computes the sequence static String printSequence(String arr[], String input) { String output = ""; // length of input string int n = input.length(); for (int i = 0; i < n; i++) { // Checking for space if (input.charAt(i) == ' ') output = output + "0"; else { // Calculating index for each // character int position = input.charAt(i) - 'A'; output = output + arr[position]; } } // Output sequence return output; } // Driver Function public static void main(String[] args) { // storing the sequence in array String str[] = {"2","22","222", "3","33","333", "4","44","444", "5","55","555", "6","66","666", "7","77","777","7777", "8","88","888", "9","99","999","9999" }; String input = "GEEKSFORGEEKS"; System.out.println(printSequence(str, input)); }} // This code is contributed by Gitanjali. # Python3 implementation to convert# a sentence into its equivalent# mobile numeric keypad sequence # Function which computes the# sequencedef printSequence(arr, input): # length of input string n = len(input) output = "" for i in range(n): # checking for space if(input[i] == ' '): output = output + "0" else: # calculating index for each # character position = ord(input[i]) - ord('A') output = output + arr[position] # output sequence return output # Driver codestr = ["2", "22", "222", "3", "33", "333", "4", "44", "444", "5", "55", "555", "6", "66", "666", "7", "77", "777", "7777", "8", "88", "888", "9", "99", "999", "9999" ] input = "GEEKSFORGEEKS";print( printSequence(str, input)) # This code is contributed by upendra bartwal // C# implementation to convert a// sentence into its equivalent// mobile numeric keypad sequenceusing System; class GFG{ // Function which computes the sequence static String printSequence(string []arr, string input) { string output = ""; // length of input string int n = input.Length; for (int i = 0; i < n; i++) { // Checking for space if (input[i] == ' ') output = output + "0"; else { // Calculating index for each // character int position = input[i] - 'A'; output = output + arr[position]; } } // Output sequence return output; } // Driver Function public static void Main() { // storing the sequence in array string []str = {"2","22","222", "3","33","333", "4","44","444", "5","55","555", "6","66","666", "7","77","777","7777", "8","88","888", "9","99","999","9999" }; string input = "GEEKSFORGEEKS"; Console.WriteLine(printSequence(str, input)); }} // This code is contributed by vt_m. <?php// PHP implementation to convert a// sentence into its equivalent// mobile numeric keypad sequence // Function which computes the sequencefunction printSequence(&$arr, $input){ $output = ""; // length of input string $n = strlen($input); for ($i = 0; $i < $n; $i++) { // Checking for space if ($input[$i] == ' ') $output = $output + "0"; else { // Calculating index for each // character $position = ord($input[$i]) - ord('A'); $output = $output . $arr[$position]; } } // Output sequence return $output;} // Driver Code // storing the sequence in array$str = array("2","22","222", "3","33","333", "4","44","444", "5","55","555", "6","66","666", "7","77","777","7777", "8","88","888", "9","99","999","9999"); $input = "GEEKSFORGEEKS";echo printSequence($str, $input); // This code is contributed by ita_c?> <script> // Javascript implementation to convert a// sentence into its equivalent// mobile numeric keypad sequence // Function which computes the sequence function printSequence(arr,input) { let output = ""; // length of input string let n = input.length; for (let i = 0; i < n; i++) { // Checking for space if (input[i] == ' ') output = output + "0".charCodeAt(0); else { // Calculating index for each // character let position = input[i].charCodeAt(0) - 'A'.charCodeAt(0); output = output + arr[position]; } } // Output sequence return output; } // Driver Function let str = ["2", "22", "222", "3", "33", "333", "4", "44", "444", "5", "55", "555", "6", "66", "666", "7", "77", "777", "7777", "8", "88", "888", "9", "99", "999", "9999" ] let input = "GEEKSFORGEEKS"; document.write(printSequence(str, input)); // This code is contributed by avanitrachhadiya2155</script> Output : 4333355777733366677743333557777 Time complexity: O(n) Auxiliary Space: O(n), Linear complexity for the above code. Convert a sentence into its equivalent mobile numeric keypad sequence | GeeksforGeeks - YouTubeGeeksforGeeks530K subscribersConvert a sentence into its equivalent mobile numeric keypad sequence | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:20•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=hE4Nn7o4GFw" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> ukasp avanitrachhadiya2155 rupasriachanta421 mailaruyashaswi Hash Strings Hash Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) What is Hashing | A Complete Tutorial Hashing | Set 1 (Introduction) Internal Working of HashMap in Java Count pairs with given sum Write a program to reverse an array or string Reverse a string in Java C++ Data Types Write a program to print all permutations of a given string Check for Balanced Brackets in an expression (well-formedness) using Stack
[ { "code": null, "e": 52, "s": 24, "text": "\n23 Jun, 2022" }, { "code": null, "e": 159, "s": 52, "text": "Given a sentence in the form of a string, convert it into its equivalent mobile numeric keypad sequence. " }, { "code": null, "e": 172, "s": 159, "text": "Examples : " }, { "code": null, "e": 509, "s": 172, "text": "Input : GEEKSFORGEEKS\nOutput : 4333355777733366677743333557777\nFor obtaining a number, we need to press a\nnumber corresponding to that character for \nnumber of times equal to position of the \ncharacter. For example, for character C, \nwe press number 2 three times and accordingly.\n\nInput : HELLO WORLD\nOutput : 4433555555666096667775553" }, { "code": null, "e": 599, "s": 511, "text": "Recommended: Please try your approach on {IDE} first, before moving on to the solution." }, { "code": null, "e": 608, "s": 599, "text": "Chapters" }, { "code": null, "e": 635, "s": 608, "text": "descriptions off, selected" }, { "code": null, "e": 685, "s": 635, "text": "captions settings, opens captions settings dialog" }, { "code": null, "e": 708, "s": 685, "text": "captions off, selected" }, { "code": null, "e": 716, "s": 708, "text": "English" }, { "code": null, "e": 740, "s": 716, "text": "This is a modal window." }, { "code": null, "e": 809, "s": 740, "text": "Beginning of dialog window. Escape will cancel and close the window." }, { "code": null, "e": 831, "s": 809, "text": "End of dialog window." }, { "code": null, "e": 936, "s": 831, "text": "Follow the steps given below to convert a sentence into its equivalent mobile numeric keypad sequence. " }, { "code": null, "e": 1109, "s": 936, "text": "For each character, store the sequence which should be obtained at its respective position in an array, i.e. for Z, store 9999. For Y, store 999. For K, store 55 and so on." }, { "code": null, "e": 1275, "s": 1109, "text": "For each character, subtract ASCII value of ‘A’ and obtain the position in the array pointed by that character and add the sequence stored in that array to a string." }, { "code": null, "e": 1312, "s": 1275, "text": "If the character is a space, store 0" }, { "code": null, "e": 1340, "s": 1312, "text": "Print the overall sequence." }, { "code": null, "e": 1388, "s": 1340, "text": "Below is the implementation of above method : " }, { "code": null, "e": 1392, "s": 1388, "text": "C++" }, { "code": null, "e": 1397, "s": 1392, "text": "Java" }, { "code": null, "e": 1405, "s": 1397, "text": "Python3" }, { "code": null, "e": 1408, "s": 1405, "text": "C#" }, { "code": null, "e": 1412, "s": 1408, "text": "PHP" }, { "code": null, "e": 1423, "s": 1412, "text": "Javascript" }, { "code": "// C++ implementation to convert a// sentence into its equivalent// mobile numeric keypad sequence#include <bits/stdc++.h>using namespace std; // Function which computes the sequencestring printSequence(string arr[], string input){ string output = \"\"; // length of input string int n = input.length(); for (int i=0; i<n; i++) { // Checking for space if (input[i] == ' ') output = output + \"0\"; else { // Calculating index for each // character int position = input[i]-'A'; output = output + arr[position]; } } // Output sequence return output;} // Driver functionint main(){ // storing the sequence in array string str[] = {\"2\",\"22\",\"222\", \"3\",\"33\",\"333\", \"4\",\"44\",\"444\", \"5\",\"55\",\"555\", \"6\",\"66\",\"666\", \"7\",\"77\",\"777\",\"7777\", \"8\",\"88\",\"888\", \"9\",\"99\",\"999\",\"9999\" }; string input = \"GEEKSFORGEEKS\"; cout << printSequence(str, input); return 0;}", "e": 2575, "s": 1423, "text": null }, { "code": "// Java implementation to convert a// sentence into its equivalent// mobile numeric keypad sequenceimport java.util.*; class GFG{ // Function which computes the sequence static String printSequence(String arr[], String input) { String output = \"\"; // length of input string int n = input.length(); for (int i = 0; i < n; i++) { // Checking for space if (input.charAt(i) == ' ') output = output + \"0\"; else { // Calculating index for each // character int position = input.charAt(i) - 'A'; output = output + arr[position]; } } // Output sequence return output; } // Driver Function public static void main(String[] args) { // storing the sequence in array String str[] = {\"2\",\"22\",\"222\", \"3\",\"33\",\"333\", \"4\",\"44\",\"444\", \"5\",\"55\",\"555\", \"6\",\"66\",\"666\", \"7\",\"77\",\"777\",\"7777\", \"8\",\"88\",\"888\", \"9\",\"99\",\"999\",\"9999\" }; String input = \"GEEKSFORGEEKS\"; System.out.println(printSequence(str, input)); }} // This code is contributed by Gitanjali.", "e": 3984, "s": 2575, "text": null }, { "code": "# Python3 implementation to convert# a sentence into its equivalent# mobile numeric keypad sequence # Function which computes the# sequencedef printSequence(arr, input): # length of input string n = len(input) output = \"\" for i in range(n): # checking for space if(input[i] == ' '): output = output + \"0\" else: # calculating index for each # character position = ord(input[i]) - ord('A') output = output + arr[position] # output sequence return output # Driver codestr = [\"2\", \"22\", \"222\", \"3\", \"33\", \"333\", \"4\", \"44\", \"444\", \"5\", \"55\", \"555\", \"6\", \"66\", \"666\", \"7\", \"77\", \"777\", \"7777\", \"8\", \"88\", \"888\", \"9\", \"99\", \"999\", \"9999\" ] input = \"GEEKSFORGEEKS\";print( printSequence(str, input)) # This code is contributed by upendra bartwal", "e": 4880, "s": 3984, "text": null }, { "code": "// C# implementation to convert a// sentence into its equivalent// mobile numeric keypad sequenceusing System; class GFG{ // Function which computes the sequence static String printSequence(string []arr, string input) { string output = \"\"; // length of input string int n = input.Length; for (int i = 0; i < n; i++) { // Checking for space if (input[i] == ' ') output = output + \"0\"; else { // Calculating index for each // character int position = input[i] - 'A'; output = output + arr[position]; } } // Output sequence return output; } // Driver Function public static void Main() { // storing the sequence in array string []str = {\"2\",\"22\",\"222\", \"3\",\"33\",\"333\", \"4\",\"44\",\"444\", \"5\",\"55\",\"555\", \"6\",\"66\",\"666\", \"7\",\"77\",\"777\",\"7777\", \"8\",\"88\",\"888\", \"9\",\"99\",\"999\",\"9999\" }; string input = \"GEEKSFORGEEKS\"; Console.WriteLine(printSequence(str, input)); }} // This code is contributed by vt_m.", "e": 6243, "s": 4880, "text": null }, { "code": "<?php// PHP implementation to convert a// sentence into its equivalent// mobile numeric keypad sequence // Function which computes the sequencefunction printSequence(&$arr, $input){ $output = \"\"; // length of input string $n = strlen($input); for ($i = 0; $i < $n; $i++) { // Checking for space if ($input[$i] == ' ') $output = $output + \"0\"; else { // Calculating index for each // character $position = ord($input[$i]) - ord('A'); $output = $output . $arr[$position]; } } // Output sequence return $output;} // Driver Code // storing the sequence in array$str = array(\"2\",\"22\",\"222\", \"3\",\"33\",\"333\", \"4\",\"44\",\"444\", \"5\",\"55\",\"555\", \"6\",\"66\",\"666\", \"7\",\"77\",\"777\",\"7777\", \"8\",\"88\",\"888\", \"9\",\"99\",\"999\",\"9999\"); $input = \"GEEKSFORGEEKS\";echo printSequence($str, $input); // This code is contributed by ita_c?>", "e": 7207, "s": 6243, "text": null }, { "code": "<script> // Javascript implementation to convert a// sentence into its equivalent// mobile numeric keypad sequence // Function which computes the sequence function printSequence(arr,input) { let output = \"\"; // length of input string let n = input.length; for (let i = 0; i < n; i++) { // Checking for space if (input[i] == ' ') output = output + \"0\".charCodeAt(0); else { // Calculating index for each // character let position = input[i].charCodeAt(0) - 'A'.charCodeAt(0); output = output + arr[position]; } } // Output sequence return output; } // Driver Function let str = [\"2\", \"22\", \"222\", \"3\", \"33\", \"333\", \"4\", \"44\", \"444\", \"5\", \"55\", \"555\", \"6\", \"66\", \"666\", \"7\", \"77\", \"777\", \"7777\", \"8\", \"88\", \"888\", \"9\", \"99\", \"999\", \"9999\" ] let input = \"GEEKSFORGEEKS\"; document.write(printSequence(str, input)); // This code is contributed by avanitrachhadiya2155</script>", "e": 8375, "s": 7207, "text": null }, { "code": null, "e": 8386, "s": 8375, "text": "Output : " }, { "code": null, "e": 8418, "s": 8386, "text": "4333355777733366677743333557777" }, { "code": null, "e": 8441, "s": 8418, "text": "Time complexity: O(n) " }, { "code": null, "e": 8503, "s": 8441, "text": "Auxiliary Space: O(n), Linear complexity for the above code. " }, { "code": null, "e": 9459, "s": 8503, "text": "Convert a sentence into its equivalent mobile numeric keypad sequence | GeeksforGeeks - YouTubeGeeksforGeeks530K subscribersConvert a sentence into its equivalent mobile numeric keypad sequence | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:20•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=hE4Nn7o4GFw\" 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": 9467, "s": 9461, "text": "ukasp" }, { "code": null, "e": 9488, "s": 9467, "text": "avanitrachhadiya2155" }, { "code": null, "e": 9506, "s": 9488, "text": "rupasriachanta421" }, { "code": null, "e": 9522, "s": 9506, "text": "mailaruyashaswi" }, { "code": null, "e": 9527, "s": 9522, "text": "Hash" }, { "code": null, "e": 9535, "s": 9527, "text": "Strings" }, { "code": null, "e": 9540, "s": 9535, "text": "Hash" }, { "code": null, "e": 9548, "s": 9540, "text": "Strings" }, { "code": null, "e": 9646, "s": 9548, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 9731, "s": 9646, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 9769, "s": 9731, "text": "What is Hashing | A Complete Tutorial" }, { "code": null, "e": 9800, "s": 9769, "text": "Hashing | Set 1 (Introduction)" }, { "code": null, "e": 9836, "s": 9800, "text": "Internal Working of HashMap in Java" }, { "code": null, "e": 9863, "s": 9836, "text": "Count pairs with given sum" }, { "code": null, "e": 9909, "s": 9863, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 9934, "s": 9909, "text": "Reverse a string in Java" }, { "code": null, "e": 9949, "s": 9934, "text": "C++ Data Types" }, { "code": null, "e": 10009, "s": 9949, "text": "Write a program to print all permutations of a given string" } ]
Stack empty() Method in Java
02 Aug, 2018 The java.util.Stack.empty() method in Java is used to check whether a stack is empty or not. The method is of boolean type and returns true if the stack is empty else false. Syntax: STACK.empty() Parameters: The method does not take any parameters. Return Value: The method returns boolean true if the stack is empty else it returns false. Below programs illustrate the working of java.util.Stack.empty() method:Program 1: // Java code to demonstrate empty() methodimport java.util.*; public class Stack_Demo { public static void main(String[] args) { // Creating an empty Stack Stack<String> STACK = new Stack<String>(); // Stacking strings STACK.push("Geeks"); STACK.push("4"); STACK.push("Geeks"); STACK.push("Welcomes"); STACK.push("You"); // Displaying the Stack System.out.println("The stack is: " + STACK); // Checking for the emptiness of stack System.out.println("Is the stack empty? " + STACK.empty()); // Popping out all the elements STACK.pop(); STACK.pop(); STACK.pop(); STACK.pop(); STACK.pop(); // Checking for the emptiness of stack System.out.println("Is the stack empty? " + STACK.empty()); }} The stack is: [Geeks, 4, Geeks, Welcomes, You] Is the stack empty? false Is the stack empty? true Program 2: // Java code to demonstrate empty() methodimport java.util.*; public class Stack_Demo { public static void main(String[] args) { // Creating an empty Stack Stack<Integer> STACK = new Stack<Integer>(); // Stacking int values STACK.push(8); STACK.push(5); STACK.push(9); STACK.push(2); STACK.push(4); // Displaying the Stack System.out.println("The stack is: " + STACK); // Checking for the emptiness of stack System.out.println("Is the stack empty? " + STACK.empty()); }} The stack is: [8, 5, 9, 2, 4] Is the stack empty? false Java - util package Java-Collections Java-Functions Java-Stack Java Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n02 Aug, 2018" }, { "code": null, "e": 227, "s": 53, "text": "The java.util.Stack.empty() method in Java is used to check whether a stack is empty or not. The method is of boolean type and returns true if the stack is empty else false." }, { "code": null, "e": 235, "s": 227, "text": "Syntax:" }, { "code": null, "e": 249, "s": 235, "text": "STACK.empty()" }, { "code": null, "e": 302, "s": 249, "text": "Parameters: The method does not take any parameters." }, { "code": null, "e": 393, "s": 302, "text": "Return Value: The method returns boolean true if the stack is empty else it returns false." }, { "code": null, "e": 476, "s": 393, "text": "Below programs illustrate the working of java.util.Stack.empty() method:Program 1:" }, { "code": "// Java code to demonstrate empty() methodimport java.util.*; public class Stack_Demo { public static void main(String[] args) { // Creating an empty Stack Stack<String> STACK = new Stack<String>(); // Stacking strings STACK.push(\"Geeks\"); STACK.push(\"4\"); STACK.push(\"Geeks\"); STACK.push(\"Welcomes\"); STACK.push(\"You\"); // Displaying the Stack System.out.println(\"The stack is: \" + STACK); // Checking for the emptiness of stack System.out.println(\"Is the stack empty? \" + STACK.empty()); // Popping out all the elements STACK.pop(); STACK.pop(); STACK.pop(); STACK.pop(); STACK.pop(); // Checking for the emptiness of stack System.out.println(\"Is the stack empty? \" + STACK.empty()); }}", "e": 1402, "s": 476, "text": null }, { "code": null, "e": 1501, "s": 1402, "text": "The stack is: [Geeks, 4, Geeks, Welcomes, You]\nIs the stack empty? false\nIs the stack empty? true\n" }, { "code": null, "e": 1512, "s": 1501, "text": "Program 2:" }, { "code": "// Java code to demonstrate empty() methodimport java.util.*; public class Stack_Demo { public static void main(String[] args) { // Creating an empty Stack Stack<Integer> STACK = new Stack<Integer>(); // Stacking int values STACK.push(8); STACK.push(5); STACK.push(9); STACK.push(2); STACK.push(4); // Displaying the Stack System.out.println(\"The stack is: \" + STACK); // Checking for the emptiness of stack System.out.println(\"Is the stack empty? \" + STACK.empty()); }}", "e": 2123, "s": 1512, "text": null }, { "code": null, "e": 2180, "s": 2123, "text": "The stack is: [8, 5, 9, 2, 4]\nIs the stack empty? false\n" }, { "code": null, "e": 2200, "s": 2180, "text": "Java - util package" }, { "code": null, "e": 2217, "s": 2200, "text": "Java-Collections" }, { "code": null, "e": 2232, "s": 2217, "text": "Java-Functions" }, { "code": null, "e": 2243, "s": 2232, "text": "Java-Stack" }, { "code": null, "e": 2248, "s": 2243, "text": "Java" }, { "code": null, "e": 2253, "s": 2248, "text": "Java" }, { "code": null, "e": 2270, "s": 2253, "text": "Java-Collections" } ]
Encapsulation in Python
17 Mar, 2022 Encapsulation is one of the fundamental concepts in object-oriented programming (OOP). It describes the idea of wrapping data and the methods that work on data within one unit. This puts restrictions on accessing variables and methods directly and can prevent the accidental modification of data. To prevent accidental change, an object’s variable can only be changed by an object’s method. Those types of variables are known as private variables. A class is an example of encapsulation as it encapsulates all the data that is member functions, variables, etc. Consider a real-life example of encapsulation, in a company, there are different sections like the accounts section, finance section, sales section etc. The finance section handles all the financial transactions and keeps records of all the data related to finance. Similarly, the sales section handles all the sales-related activities and keeps records of all the sales. Now there may arise a situation when for some reason an official from the finance section needs all the data about sales in a particular month. In this case, he is not allowed to directly access the data of the sales section. He will first have to contact some other officer in the sales section and then request him to give the particular data. This is what encapsulation is. Here the data of the sales section and the employees that can manipulate them are wrapped under a single name “sales section”. Using encapsulation also hides the data. In this example, the data of the sections like sales, finance, or accounts are hidden from any other section. Protected members (in C++ and JAVA) are those members of the class that cannot be accessed outside the class but can be accessed from within the class and its subclasses. To accomplish this in Python, just follow the convention by prefixing the name of the member by a single underscore “_”. Although the protected variable can be accessed out of the class as well as in the derived class(modified too in derived class), it is customary(convention not a rule) to not access the protected out the class body. Note: The __init__ method is a constructor and runs as soon as an object of a class is instantiated. Python3 # Python program to# demonstrate protected members # Creating a base classclass Base: def __init__(self): # Protected member self._a = 2 # Creating a derived classclass Derived(Base): def __init__(self): # Calling constructor of # Base class Base.__init__(self) print("Calling protected member of base class: ", self._a) # Modify the protected variable: self._a = 3 print("Calling modified protected member outside class: ", self._a) obj1 = Derived() obj2 = Base() # Calling protected member# Can be accessed but should not be done due to conventionprint("Accessing protected member of obj1: ", obj1._a) # Accessing the protected variable outsideprint("Accessing protected member of obj2: ", obj2._a) Output: Calling protected member of base class: 2 Calling modified protected member outside class: 3 Accessing protected member of obj1: 3 Accessing protected member of obj2: 2 Private members are similar to protected members, the difference is that the class members declared private should neither be accessed outside the class nor by any base class. In Python, there is no existence of Private instance variables that cannot be accessed except inside a class. However, to define a private member prefix the member name with double underscore “__”. Note: Python’s private and protected members can be accessed outside the class through python name mangling. Python3 # Python program to# demonstrate private members # Creating a Base class class Base: def __init__(self): self.a = "GeeksforGeeks" self.__c = "GeeksforGeeks" # Creating a derived classclass Derived(Base): def __init__(self): # Calling constructor of # Base class Base.__init__(self) print("Calling private member of base class: ") print(self.__c) # Driver codeobj1 = Base()print(obj1.a) # Uncommenting print(obj1.c) will# raise an AttributeError # Uncommenting obj2 = Derived() will# also raise an AtrributeError as# private member of base class# is called inside derived class Output: GeeksforGeeks Traceback (most recent call last): File "/home/f4905b43bfcf29567e360c709d3c52bd.py", line 25, in <module> print(obj1.c) AttributeError: 'Base' object has no attribute 'c' Traceback (most recent call last): File "/home/4d97a4efe3ea68e55f48f1e7c7ed39cf.py", line 27, in <module> obj2 = Derived() File "/home/4d97a4efe3ea68e55f48f1e7c7ed39cf.py", line 20, in __init__ print(self.__c) AttributeError: 'Derived' object has no attribute '_Derived__c' garwanaveen1 bunnyram19 claudio84 Spider_man nishantsharmansbs kocharajay1996 Python-OOP 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 Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? Iterate over a list in Python
[ { "code": null, "e": 52, "s": 24, "text": "\n17 Mar, 2022" }, { "code": null, "e": 500, "s": 52, "text": "Encapsulation is one of the fundamental concepts in object-oriented programming (OOP). It describes the idea of wrapping data and the methods that work on data within one unit. This puts restrictions on accessing variables and methods directly and can prevent the accidental modification of data. To prevent accidental change, an object’s variable can only be changed by an object’s method. Those types of variables are known as private variables." }, { "code": null, "e": 613, "s": 500, "text": "A class is an example of encapsulation as it encapsulates all the data that is member functions, variables, etc." }, { "code": null, "e": 1640, "s": 613, "text": "Consider a real-life example of encapsulation, in a company, there are different sections like the accounts section, finance section, sales section etc. The finance section handles all the financial transactions and keeps records of all the data related to finance. Similarly, the sales section handles all the sales-related activities and keeps records of all the sales. Now there may arise a situation when for some reason an official from the finance section needs all the data about sales in a particular month. In this case, he is not allowed to directly access the data of the sales section. He will first have to contact some other officer in the sales section and then request him to give the particular data. This is what encapsulation is. Here the data of the sales section and the employees that can manipulate them are wrapped under a single name “sales section”. Using encapsulation also hides the data. In this example, the data of the sections like sales, finance, or accounts are hidden from any other section." }, { "code": null, "e": 1932, "s": 1640, "text": "Protected members (in C++ and JAVA) are those members of the class that cannot be accessed outside the class but can be accessed from within the class and its subclasses. To accomplish this in Python, just follow the convention by prefixing the name of the member by a single underscore “_”." }, { "code": null, "e": 2148, "s": 1932, "text": "Although the protected variable can be accessed out of the class as well as in the derived class(modified too in derived class), it is customary(convention not a rule) to not access the protected out the class body." }, { "code": null, "e": 2251, "s": 2148, "text": "Note: The __init__ method is a constructor and runs as soon as an object of a class is instantiated. " }, { "code": null, "e": 2259, "s": 2251, "text": "Python3" }, { "code": "# Python program to# demonstrate protected members # Creating a base classclass Base: def __init__(self): # Protected member self._a = 2 # Creating a derived classclass Derived(Base): def __init__(self): # Calling constructor of # Base class Base.__init__(self) print(\"Calling protected member of base class: \", self._a) # Modify the protected variable: self._a = 3 print(\"Calling modified protected member outside class: \", self._a) obj1 = Derived() obj2 = Base() # Calling protected member# Can be accessed but should not be done due to conventionprint(\"Accessing protected member of obj1: \", obj1._a) # Accessing the protected variable outsideprint(\"Accessing protected member of obj2: \", obj2._a)", "e": 3059, "s": 2259, "text": null }, { "code": null, "e": 3068, "s": 3059, "text": "Output: " }, { "code": null, "e": 3241, "s": 3068, "text": "Calling protected member of base class: 2\nCalling modified protected member outside class: 3\nAccessing protected member of obj1: 3\nAccessing protected member of obj2: 2" }, { "code": null, "e": 3527, "s": 3241, "text": "Private members are similar to protected members, the difference is that the class members declared private should neither be accessed outside the class nor by any base class. In Python, there is no existence of Private instance variables that cannot be accessed except inside a class." }, { "code": null, "e": 3615, "s": 3527, "text": "However, to define a private member prefix the member name with double underscore “__”." }, { "code": null, "e": 3725, "s": 3615, "text": "Note: Python’s private and protected members can be accessed outside the class through python name mangling. " }, { "code": null, "e": 3733, "s": 3725, "text": "Python3" }, { "code": "# Python program to# demonstrate private members # Creating a Base class class Base: def __init__(self): self.a = \"GeeksforGeeks\" self.__c = \"GeeksforGeeks\" # Creating a derived classclass Derived(Base): def __init__(self): # Calling constructor of # Base class Base.__init__(self) print(\"Calling private member of base class: \") print(self.__c) # Driver codeobj1 = Base()print(obj1.a) # Uncommenting print(obj1.c) will# raise an AttributeError # Uncommenting obj2 = Derived() will# also raise an AtrributeError as# private member of base class# is called inside derived class", "e": 4368, "s": 3733, "text": null }, { "code": null, "e": 4377, "s": 4368, "text": "Output: " }, { "code": null, "e": 4391, "s": 4377, "text": "GeeksforGeeks" }, { "code": null, "e": 4856, "s": 4391, "text": "Traceback (most recent call last):\n File \"/home/f4905b43bfcf29567e360c709d3c52bd.py\", line 25, in <module>\n print(obj1.c)\nAttributeError: 'Base' object has no attribute 'c'\n\nTraceback (most recent call last):\n File \"/home/4d97a4efe3ea68e55f48f1e7c7ed39cf.py\", line 27, in <module>\n obj2 = Derived()\n File \"/home/4d97a4efe3ea68e55f48f1e7c7ed39cf.py\", line 20, in __init__\n print(self.__c)\nAttributeError: 'Derived' object has no attribute '_Derived__c' " }, { "code": null, "e": 4869, "s": 4856, "text": "garwanaveen1" }, { "code": null, "e": 4880, "s": 4869, "text": "bunnyram19" }, { "code": null, "e": 4890, "s": 4880, "text": "claudio84" }, { "code": null, "e": 4901, "s": 4890, "text": "Spider_man" }, { "code": null, "e": 4919, "s": 4901, "text": "nishantsharmansbs" }, { "code": null, "e": 4934, "s": 4919, "text": "kocharajay1996" }, { "code": null, "e": 4945, "s": 4934, "text": "Python-OOP" }, { "code": null, "e": 4952, "s": 4945, "text": "Python" }, { "code": null, "e": 5050, "s": 4952, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5078, "s": 5050, "text": "Read JSON file using Python" }, { "code": null, "e": 5128, "s": 5078, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 5150, "s": 5128, "text": "Python map() function" }, { "code": null, "e": 5194, "s": 5150, "text": "How to get column names in Pandas dataframe" }, { "code": null, "e": 5236, "s": 5194, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 5258, "s": 5236, "text": "Enumerate() in Python" }, { "code": null, "e": 5293, "s": 5258, "text": "Read a file line by line in Python" }, { "code": null, "e": 5319, "s": 5293, "text": "Python String | replace()" }, { "code": null, "e": 5351, "s": 5319, "text": "How to Install PIP on Windows ?" } ]
Variable-length arguments in Python
You may need to process a function for more arguments than you specified while defining the function. These arguments are called variable-length arguments and are not named in the function definition, unlike required and default arguments. Syntax for a function with non-keyword variable arguments is this − def functionname([formal_args,] *var_args_tuple ): "function_docstring" function_suite return [expression] An asterisk (*) is placed before the variable name that holds the values of all nonkeyword variable arguments. This tuple remains empty if no additional arguments are specified during the function call. Live Demo #!/usr/bin/python # Function definition is here def printinfo( arg1, *vartuple ): "This prints a variable passed arguments" print "Output is: " print arg1 for var in vartuple: print var return; # Now you can call printinfo function printinfo( 10 ) printinfo( 70, 60, 50 ) When the above code is executed, it produces the following result − Output is: 10 Output is: 70 60 50
[ { "code": null, "e": 1427, "s": 1187, "text": "You may need to process a function for more arguments than you specified while defining the function. These arguments are called variable-length arguments and are not named in the function definition, unlike required and default arguments." }, { "code": null, "e": 1495, "s": 1427, "text": "Syntax for a function with non-keyword variable arguments is this −" }, { "code": null, "e": 1602, "s": 1495, "text": "def functionname([formal_args,] *var_args_tuple ):\n\"function_docstring\"\nfunction_suite\nreturn [expression]" }, { "code": null, "e": 1805, "s": 1602, "text": "An asterisk (*) is placed before the variable name that holds the values of all nonkeyword variable arguments. This tuple remains empty if no additional arguments are specified during the function call." }, { "code": null, "e": 1816, "s": 1805, "text": " Live Demo" }, { "code": null, "e": 2088, "s": 1816, "text": "#!/usr/bin/python\n# Function definition is here\ndef printinfo( arg1, *vartuple ):\n\"This prints a variable passed arguments\"\nprint \"Output is: \"\nprint arg1\nfor var in vartuple:\nprint var\nreturn;\n# Now you can call printinfo function\nprintinfo( 10 )\nprintinfo( 70, 60, 50 )" }, { "code": null, "e": 2156, "s": 2088, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 2190, "s": 2156, "text": "Output is:\n10\nOutput is:\n70\n60\n50" } ]
Construct all possible BSTs for keys 1 to N
27 Jun, 2022 In this article, first count of possible BST (Binary Search Trees)s is discussed, then the construction of all possible BSTs. How many structurally unique BSTs for keys from 1..N? For example, for N = 2, there are 2 unique BSTs 1 2 \ / 2 1 For N = 3, there are 5 possible BSTs 1 3 3 2 1 \ / / / \ \ 3 2 1 1 3 2 / / \ \ 2 1 2 3 We strongly recommend you to minimize your browser and try this yourself first.We know that all node in left subtree are smaller than root and in right subtree are larger than root so if we have ith number as root, all numbers from 1 to i-1 will be in left subtree and i+1 to N will be in right subtree. If 1 to i-1 can form x different trees and i+1 to N can from y different trees then we will have x*y total trees when ith number is root and we also have N choices for root also so we can simply iterate from 1 to N for root and another loop for left and right subtree. If we take a closer look, we can notice that the count is basically n’th Catalan number. We have discussed different approaches to find n’th Catalan number here. How to construct all BST for keys 1..N? The idea is to maintain a list of roots of all BSTs. Recursively construct all possible left and right subtrees. Create a tree for every pair of left and right subtree and add the tree to list. Below is detailed algorithm. Initialize list of BSTs as empty. For every number i where i varies from 1 to N, do followingCreate a new node with key as ‘i’, let this node be ‘node’Recursively construct list of all left subtrees.Recursively construct list of all right subtrees.Iterate for all left subtreesFor current leftsubtree, iterate for all right subtreesAdd current left and right subtrees to ‘node’ and addnode’ to list. Initialize list of BSTs as empty. For every number i where i varies from 1 to N, do followingCreate a new node with key as ‘i’, let this node be ‘node’Recursively construct list of all left subtrees.Recursively construct list of all right subtrees. Create a new node with key as ‘i’, let this node be ‘node’ Recursively construct list of all left subtrees. Recursively construct list of all right subtrees. Iterate for all left subtreesFor current leftsubtree, iterate for all right subtreesAdd current left and right subtrees to ‘node’ and addnode’ to list. For current leftsubtree, iterate for all right subtrees Add current left and right subtrees to ‘node’ and add node’ to list. Below is the implementation of the above idea. C++ Java Python3 C# Javascript // A C++ program to construct all unique BSTs for keys from 1 to n#include <bits/stdc++.h>using namespace std; // node structurestruct node{ int key; struct node *left, *right;}; // A utility function to create a new BST nodestruct node *newNode(int item){ struct node *temp = new node; temp->key = item; temp->left = temp->right = NULL; return temp;} // A utility function to do preorder traversal of BSTvoid preorder(struct node *root){ if (root != NULL) { cout << root->key << " "; preorder(root->left); preorder(root->right); }} // function for constructing treesvector<struct node *> constructTrees(int start, int end){ vector<struct node *> list; /* if start > end then subtree will be empty so returning NULL in the list */ if (start > end) { list.push_back(NULL); return list; } /* iterating through all values from start to end for constructing\ left and right subtree recursively */ for (int i = start; i <= end; i++) { /* constructing left subtree */ vector<struct node *> leftSubtree = constructTrees(start, i - 1); /* constructing right subtree */ vector<struct node *> rightSubtree = constructTrees(i + 1, end); /* now looping through all left and right subtrees and connecting them to ith root below */ for (int j = 0; j < leftSubtree.size(); j++) { struct node* left = leftSubtree[j]; for (int k = 0; k < rightSubtree.size(); k++) { struct node * right = rightSubtree[k]; struct node * node = newNode(i);// making value i as root node->left = left; // connect left subtree node->right = right; // connect right subtree list.push_back(node); // add this tree to list } } } return list;} // Driver Program to test above functionsint main(){ // Construct all possible BSTs vector<struct node *> totalTreesFrom1toN = constructTrees(1, 3); /* Printing preorder traversal of all constructed BSTs */ cout << "Preorder traversals of all constructed BSTs are \n"; for (int i = 0; i < totalTreesFrom1toN.size(); i++) { preorder(totalTreesFrom1toN[i]); cout << endl; } return 0;} // A Java program to construct all unique BSTs for keys from 1 to nimport java.util.ArrayList;public class Main { // function for constructing trees static ArrayList<Node> constructTrees(int start, int end) { ArrayList<Node> list=new ArrayList<>(); /* if start > end then subtree will be empty so returning NULL in the list */ if (start > end) { list.add(null); return list; } /* iterating through all values from start to end for constructing\ left and right subtree recursively */ for (int i = start; i <= end; i++) { /* constructing left subtree */ ArrayList<Node> leftSubtree = constructTrees(start, i - 1); /* constructing right subtree */ ArrayList<Node> rightSubtree = constructTrees(i + 1, end); /* now looping through all left and right subtrees and connecting them to ith root below */ for (int j = 0; j < leftSubtree.size(); j++) { Node left = leftSubtree.get(j); for (int k = 0; k < rightSubtree.size(); k++) { Node right = rightSubtree.get(k); Node node = new Node(i); // making value i as root node.left = left; // connect left subtree node.right = right; // connect right subtree list.add(node); // add this tree to list } } } return list; } // A utility function to do preorder traversal of BST static void preorder(Node root) { if (root != null) { System.out.print(root.key+" ") ; preorder(root.left); preorder(root.right); } } public static void main(String args[]) { ArrayList<Node> totalTreesFrom1toN = constructTrees(1, 3); /* Printing preorder traversal of all constructed BSTs */ System.out.println("Preorder traversals of all constructed BSTs are "); for (int i = 0; i < totalTreesFrom1toN.size(); i++) { preorder(totalTreesFrom1toN.get(i)); System.out.println(); } }} // node structureclass Node{ int key; Node left, right; Node(int data) { this.key=data; left=right=null; }};//This code is contributed by Gaurav Tiwari # Python3 program to construct all unique# BSTs for keys from 1 to n # Binary Tree Node""" A utility function to create anew BST node """class newNode: # Construct to create a newNode def __init__(self, item): self.key=item self.left = None self.right = None # A utility function to do preorder# traversal of BSTdef preorder(root) : if (root != None) : print(root.key, end = " " ) preorder(root.left) preorder(root.right) # function for constructing treesdef constructTrees(start, end): list = [] """ if start > end then subtree will be empty so returning None in the list """ if (start > end) : list.append(None) return list """ iterating through all values from start to end for constructing left and right subtree recursively """ for i in range(start, end + 1): """ constructing left subtree """ leftSubtree = constructTrees(start, i - 1) """ constructing right subtree """ rightSubtree = constructTrees(i + 1, end) """ now looping through all left and right subtrees and connecting them to ith root below """ for j in range(len(leftSubtree)) : left = leftSubtree[j] for k in range(len(rightSubtree)): right = rightSubtree[k] node = newNode(i) # making value i as root node.left = left # connect left subtree node.right = right # connect right subtree list.append(node) # add this tree to list return list # Driver Codeif __name__ == '__main__': # Construct all possible BSTs totalTreesFrom1toN = constructTrees(1, 3) """ Printing preorder traversal of all constructed BSTs """ print("Preorder traversals of all", "constructed BSTs are") for i in range(len(totalTreesFrom1toN)): preorder(totalTreesFrom1toN[i]) print() # This code is contributed by# Shubham Singh(SHUBHAMSINGH10) // C# program to construct all// unique BSTs for keys from 1 to nusing System.Collections;using System; class GFG{ // function for constructing trees static ArrayList constructTrees(int start, int end) { ArrayList list = new ArrayList(); /* if start > end then subtree will be empty so returning NULL in the list */ if (start > end) { list.Add(null); return list; } /* iterating through all values from start to end for constructing\ left and right subtree recursively */ for (int i = start; i <= end; i++) { /* constructing left subtree */ ArrayList leftSubtree = constructTrees(start, i - 1); /* constructing right subtree */ ArrayList rightSubtree = constructTrees(i + 1, end); /* now looping through all left and right subtrees and connecting them to ith root below */ for (int j = 0; j < leftSubtree.Count; j++) { Node left = (Node)leftSubtree[j]; for (int k = 0; k < rightSubtree.Count; k++) { Node right = (Node)rightSubtree[k]; // making value i as root Node node = new Node(i); // connect left subtree node.left = left; // connect right subtree node.right = right; // Add this tree to list list.Add(node); } } } return list; } // A utility function to do // preorder traversal of BST static void preorder(Node root) { if (root != null) { Console.Write(root.key+" ") ; preorder(root.left); preorder(root.right); } } // Driver code public static void Main(String []args) { ArrayList totalTreesFrom1toN = constructTrees(1, 3); /* Printing preorder traversal of all constructed BSTs */ Console.WriteLine("Preorder traversals of all" + "constructed BSTs are "); for (int i = 0; i < totalTreesFrom1toN.Count; i++) { preorder((Node)totalTreesFrom1toN[i]); Console.WriteLine(); } } // node structurepublic class Node{ public int key; public Node left, right; public Node(int data) { this.key=data; left=right=null; }};} // This code is contributed by Arnab Kundu <script> // node structureclass Node{ constructor(data) { this.key = data; this.left = null; this.right = null; }}; // Javascript program to construct all// unique BSTs for keys from 1 to n// function for constructing treesfunction constructTrees(start, end){ var list = []; /* if start > end then subtree will be empty so returning NULL in the list */ if (start > end) { list.push(null); return list; } /* iterating through all values from start to end for constructing\ left and right subtree recursively */ for (var i = start; i <= end; i++) { /* constructing left subtree */ var leftSubtree = constructTrees(start, i - 1); /* constructing right subtree */ var rightSubtree = constructTrees(i + 1, end); /* now looping through all left and right subtrees and connecting them to ith root below */ for (var j = 0; j < leftSubtree.length; j++) { var left = leftSubtree[j]; for (var k = 0; k < rightSubtree.length; k++) { var right = rightSubtree[k]; // making value i as root var node = new Node(i); // connect left subtree node.left = left; // connect right subtree node.right = right; // push this tree to list list.push(node); } } } return list;} // A utility function to do// preorder traversal of BSTfunction preorder(root){ if (root != null) { document.write(root.key+" ") ; preorder(root.left); preorder(root.right); }}// Driver codevar totalTreesFrom1toN = constructTrees(1, 3); /* Printing preorder traversalof all constructed BSTs */document.write("Preorder traversals of all" + "constructed BSTs are<br>");for (var i = 0; i < totalTreesFrom1toN.length; i++){ preorder(totalTreesFrom1toN[i]); document.write("<br>");} </script> Preorder traversals of all constructed BSTs are 1 2 3 1 3 2 2 1 3 3 1 2 3 2 1 This article is contributed by Utkarsh Trivedi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. _Gaurav_Tiwari SHUBHAMSINGH10 andrew1234 rutvik_56 surinderdawra388 simmytarika5 hardikkoriintern Amazon catalan Binary Search Tree Amazon Binary Search Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. A program to check if a binary tree is BST or not Find postorder traversal of BST from preorder traversal Overview of Data Structures | Set 2 (Binary Tree, BST, Heap and Hash) Optimal Binary Search Tree | DP-24 Sorted Array to Balanced BST Inorder Successor in Binary Search Tree Convert a normal BST to Balanced BST set vs unordered_set in C++ STL Find k-th smallest element in BST (Order Statistics in BST) Check if a given array can represent Preorder Traversal of Binary Search Tree
[ { "code": null, "e": 52, "s": 24, "text": "\n27 Jun, 2022" }, { "code": null, "e": 178, "s": 52, "text": "In this article, first count of possible BST (Binary Search Trees)s is discussed, then the construction of all possible BSTs." }, { "code": null, "e": 233, "s": 178, "text": "How many structurally unique BSTs for keys from 1..N? " }, { "code": null, "e": 620, "s": 233, "text": "For example, for N = 2, there are 2 unique BSTs\n 1 2 \n \\ /\n 2 1 \n\nFor N = 3, there are 5 possible BSTs\n 1 3 3 2 1\n \\ / / / \\ \\\n 3 2 1 1 3 2\n / / \\ \\\n 2 1 2 3" }, { "code": null, "e": 1356, "s": 620, "text": "We strongly recommend you to minimize your browser and try this yourself first.We know that all node in left subtree are smaller than root and in right subtree are larger than root so if we have ith number as root, all numbers from 1 to i-1 will be in left subtree and i+1 to N will be in right subtree. If 1 to i-1 can form x different trees and i+1 to N can from y different trees then we will have x*y total trees when ith number is root and we also have N choices for root also so we can simply iterate from 1 to N for root and another loop for left and right subtree. If we take a closer look, we can notice that the count is basically n’th Catalan number. We have discussed different approaches to find n’th Catalan number here. " }, { "code": null, "e": 1620, "s": 1356, "text": "How to construct all BST for keys 1..N? The idea is to maintain a list of roots of all BSTs. Recursively construct all possible left and right subtrees. Create a tree for every pair of left and right subtree and add the tree to list. Below is detailed algorithm. " }, { "code": null, "e": 2021, "s": 1620, "text": "Initialize list of BSTs as empty. For every number i where i varies from 1 to N, do followingCreate a new node with key as ‘i’, let this node be ‘node’Recursively construct list of all left subtrees.Recursively construct list of all right subtrees.Iterate for all left subtreesFor current leftsubtree, iterate for all right subtreesAdd current left and right subtrees to ‘node’ and addnode’ to list." }, { "code": null, "e": 2057, "s": 2021, "text": "Initialize list of BSTs as empty. " }, { "code": null, "e": 2272, "s": 2057, "text": "For every number i where i varies from 1 to N, do followingCreate a new node with key as ‘i’, let this node be ‘node’Recursively construct list of all left subtrees.Recursively construct list of all right subtrees." }, { "code": null, "e": 2331, "s": 2272, "text": "Create a new node with key as ‘i’, let this node be ‘node’" }, { "code": null, "e": 2380, "s": 2331, "text": "Recursively construct list of all left subtrees." }, { "code": null, "e": 2430, "s": 2380, "text": "Recursively construct list of all right subtrees." }, { "code": null, "e": 2582, "s": 2430, "text": "Iterate for all left subtreesFor current leftsubtree, iterate for all right subtreesAdd current left and right subtrees to ‘node’ and addnode’ to list." }, { "code": null, "e": 2638, "s": 2582, "text": "For current leftsubtree, iterate for all right subtrees" }, { "code": null, "e": 2692, "s": 2638, "text": "Add current left and right subtrees to ‘node’ and add" }, { "code": null, "e": 2707, "s": 2692, "text": "node’ to list." }, { "code": null, "e": 2755, "s": 2707, "text": "Below is the implementation of the above idea. " }, { "code": null, "e": 2759, "s": 2755, "text": "C++" }, { "code": null, "e": 2764, "s": 2759, "text": "Java" }, { "code": null, "e": 2772, "s": 2764, "text": "Python3" }, { "code": null, "e": 2775, "s": 2772, "text": "C#" }, { "code": null, "e": 2786, "s": 2775, "text": "Javascript" }, { "code": "// A C++ program to construct all unique BSTs for keys from 1 to n#include <bits/stdc++.h>using namespace std; // node structurestruct node{ int key; struct node *left, *right;}; // A utility function to create a new BST nodestruct node *newNode(int item){ struct node *temp = new node; temp->key = item; temp->left = temp->right = NULL; return temp;} // A utility function to do preorder traversal of BSTvoid preorder(struct node *root){ if (root != NULL) { cout << root->key << \" \"; preorder(root->left); preorder(root->right); }} // function for constructing treesvector<struct node *> constructTrees(int start, int end){ vector<struct node *> list; /* if start > end then subtree will be empty so returning NULL in the list */ if (start > end) { list.push_back(NULL); return list; } /* iterating through all values from start to end for constructing\\ left and right subtree recursively */ for (int i = start; i <= end; i++) { /* constructing left subtree */ vector<struct node *> leftSubtree = constructTrees(start, i - 1); /* constructing right subtree */ vector<struct node *> rightSubtree = constructTrees(i + 1, end); /* now looping through all left and right subtrees and connecting them to ith root below */ for (int j = 0; j < leftSubtree.size(); j++) { struct node* left = leftSubtree[j]; for (int k = 0; k < rightSubtree.size(); k++) { struct node * right = rightSubtree[k]; struct node * node = newNode(i);// making value i as root node->left = left; // connect left subtree node->right = right; // connect right subtree list.push_back(node); // add this tree to list } } } return list;} // Driver Program to test above functionsint main(){ // Construct all possible BSTs vector<struct node *> totalTreesFrom1toN = constructTrees(1, 3); /* Printing preorder traversal of all constructed BSTs */ cout << \"Preorder traversals of all constructed BSTs are \\n\"; for (int i = 0; i < totalTreesFrom1toN.size(); i++) { preorder(totalTreesFrom1toN[i]); cout << endl; } return 0;}", "e": 5162, "s": 2786, "text": null }, { "code": "// A Java program to construct all unique BSTs for keys from 1 to nimport java.util.ArrayList;public class Main { // function for constructing trees static ArrayList<Node> constructTrees(int start, int end) { ArrayList<Node> list=new ArrayList<>(); /* if start > end then subtree will be empty so returning NULL in the list */ if (start > end) { list.add(null); return list; } /* iterating through all values from start to end for constructing\\ left and right subtree recursively */ for (int i = start; i <= end; i++) { /* constructing left subtree */ ArrayList<Node> leftSubtree = constructTrees(start, i - 1); /* constructing right subtree */ ArrayList<Node> rightSubtree = constructTrees(i + 1, end); /* now looping through all left and right subtrees and connecting them to ith root below */ for (int j = 0; j < leftSubtree.size(); j++) { Node left = leftSubtree.get(j); for (int k = 0; k < rightSubtree.size(); k++) { Node right = rightSubtree.get(k); Node node = new Node(i); // making value i as root node.left = left; // connect left subtree node.right = right; // connect right subtree list.add(node); // add this tree to list } } } return list; } // A utility function to do preorder traversal of BST static void preorder(Node root) { if (root != null) { System.out.print(root.key+\" \") ; preorder(root.left); preorder(root.right); } } public static void main(String args[]) { ArrayList<Node> totalTreesFrom1toN = constructTrees(1, 3); /* Printing preorder traversal of all constructed BSTs */ System.out.println(\"Preorder traversals of all constructed BSTs are \"); for (int i = 0; i < totalTreesFrom1toN.size(); i++) { preorder(totalTreesFrom1toN.get(i)); System.out.println(); } }} // node structureclass Node{ int key; Node left, right; Node(int data) { this.key=data; left=right=null; }};//This code is contributed by Gaurav Tiwari", "e": 7637, "s": 5162, "text": null }, { "code": "# Python3 program to construct all unique# BSTs for keys from 1 to n # Binary Tree Node\"\"\" A utility function to create anew BST node \"\"\"class newNode: # Construct to create a newNode def __init__(self, item): self.key=item self.left = None self.right = None # A utility function to do preorder# traversal of BSTdef preorder(root) : if (root != None) : print(root.key, end = \" \" ) preorder(root.left) preorder(root.right) # function for constructing treesdef constructTrees(start, end): list = [] \"\"\" if start > end then subtree will be empty so returning None in the list \"\"\" if (start > end) : list.append(None) return list \"\"\" iterating through all values from start to end for constructing left and right subtree recursively \"\"\" for i in range(start, end + 1): \"\"\" constructing left subtree \"\"\" leftSubtree = constructTrees(start, i - 1) \"\"\" constructing right subtree \"\"\" rightSubtree = constructTrees(i + 1, end) \"\"\" now looping through all left and right subtrees and connecting them to ith root below \"\"\" for j in range(len(leftSubtree)) : left = leftSubtree[j] for k in range(len(rightSubtree)): right = rightSubtree[k] node = newNode(i) # making value i as root node.left = left # connect left subtree node.right = right # connect right subtree list.append(node) # add this tree to list return list # Driver Codeif __name__ == '__main__': # Construct all possible BSTs totalTreesFrom1toN = constructTrees(1, 3) \"\"\" Printing preorder traversal of all constructed BSTs \"\"\" print(\"Preorder traversals of all\", \"constructed BSTs are\") for i in range(len(totalTreesFrom1toN)): preorder(totalTreesFrom1toN[i]) print() # This code is contributed by# Shubham Singh(SHUBHAMSINGH10)", "e": 9679, "s": 7637, "text": null }, { "code": "// C# program to construct all// unique BSTs for keys from 1 to nusing System.Collections;using System; class GFG{ // function for constructing trees static ArrayList constructTrees(int start, int end) { ArrayList list = new ArrayList(); /* if start > end then subtree will be empty so returning NULL in the list */ if (start > end) { list.Add(null); return list; } /* iterating through all values from start to end for constructing\\ left and right subtree recursively */ for (int i = start; i <= end; i++) { /* constructing left subtree */ ArrayList leftSubtree = constructTrees(start, i - 1); /* constructing right subtree */ ArrayList rightSubtree = constructTrees(i + 1, end); /* now looping through all left and right subtrees and connecting them to ith root below */ for (int j = 0; j < leftSubtree.Count; j++) { Node left = (Node)leftSubtree[j]; for (int k = 0; k < rightSubtree.Count; k++) { Node right = (Node)rightSubtree[k]; // making value i as root Node node = new Node(i); // connect left subtree node.left = left; // connect right subtree node.right = right; // Add this tree to list list.Add(node); } } } return list; } // A utility function to do // preorder traversal of BST static void preorder(Node root) { if (root != null) { Console.Write(root.key+\" \") ; preorder(root.left); preorder(root.right); } } // Driver code public static void Main(String []args) { ArrayList totalTreesFrom1toN = constructTrees(1, 3); /* Printing preorder traversal of all constructed BSTs */ Console.WriteLine(\"Preorder traversals of all\" + \"constructed BSTs are \"); for (int i = 0; i < totalTreesFrom1toN.Count; i++) { preorder((Node)totalTreesFrom1toN[i]); Console.WriteLine(); } } // node structurepublic class Node{ public int key; public Node left, right; public Node(int data) { this.key=data; left=right=null; }};} // This code is contributed by Arnab Kundu", "e": 12364, "s": 9679, "text": null }, { "code": "<script> // node structureclass Node{ constructor(data) { this.key = data; this.left = null; this.right = null; }}; // Javascript program to construct all// unique BSTs for keys from 1 to n// function for constructing treesfunction constructTrees(start, end){ var list = []; /* if start > end then subtree will be empty so returning NULL in the list */ if (start > end) { list.push(null); return list; } /* iterating through all values from start to end for constructing\\ left and right subtree recursively */ for (var i = start; i <= end; i++) { /* constructing left subtree */ var leftSubtree = constructTrees(start, i - 1); /* constructing right subtree */ var rightSubtree = constructTrees(i + 1, end); /* now looping through all left and right subtrees and connecting them to ith root below */ for (var j = 0; j < leftSubtree.length; j++) { var left = leftSubtree[j]; for (var k = 0; k < rightSubtree.length; k++) { var right = rightSubtree[k]; // making value i as root var node = new Node(i); // connect left subtree node.left = left; // connect right subtree node.right = right; // push this tree to list list.push(node); } } } return list;} // A utility function to do// preorder traversal of BSTfunction preorder(root){ if (root != null) { document.write(root.key+\" \") ; preorder(root.left); preorder(root.right); }}// Driver codevar totalTreesFrom1toN = constructTrees(1, 3); /* Printing preorder traversalof all constructed BSTs */document.write(\"Preorder traversals of all\" + \"constructed BSTs are<br>\");for (var i = 0; i < totalTreesFrom1toN.length; i++){ preorder(totalTreesFrom1toN[i]); document.write(\"<br>\");} </script>", "e": 14487, "s": 12364, "text": null }, { "code": null, "e": 14572, "s": 14487, "text": "Preorder traversals of all constructed BSTs are \n1 2 3 \n1 3 2 \n2 1 3 \n3 1 2 \n3 2 1 \n" }, { "code": null, "e": 14745, "s": 14572, "text": "This article is contributed by Utkarsh Trivedi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 14760, "s": 14745, "text": "_Gaurav_Tiwari" }, { "code": null, "e": 14775, "s": 14760, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 14786, "s": 14775, "text": "andrew1234" }, { "code": null, "e": 14796, "s": 14786, "text": "rutvik_56" }, { "code": null, "e": 14813, "s": 14796, "text": "surinderdawra388" }, { "code": null, "e": 14826, "s": 14813, "text": "simmytarika5" }, { "code": null, "e": 14843, "s": 14826, "text": "hardikkoriintern" }, { "code": null, "e": 14850, "s": 14843, "text": "Amazon" }, { "code": null, "e": 14858, "s": 14850, "text": "catalan" }, { "code": null, "e": 14877, "s": 14858, "text": "Binary Search Tree" }, { "code": null, "e": 14884, "s": 14877, "text": "Amazon" }, { "code": null, "e": 14903, "s": 14884, "text": "Binary Search Tree" }, { "code": null, "e": 15001, "s": 14903, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 15051, "s": 15001, "text": "A program to check if a binary tree is BST or not" }, { "code": null, "e": 15107, "s": 15051, "text": "Find postorder traversal of BST from preorder traversal" }, { "code": null, "e": 15177, "s": 15107, "text": "Overview of Data Structures | Set 2 (Binary Tree, BST, Heap and Hash)" }, { "code": null, "e": 15212, "s": 15177, "text": "Optimal Binary Search Tree | DP-24" }, { "code": null, "e": 15241, "s": 15212, "text": "Sorted Array to Balanced BST" }, { "code": null, "e": 15281, "s": 15241, "text": "Inorder Successor in Binary Search Tree" }, { "code": null, "e": 15318, "s": 15281, "text": "Convert a normal BST to Balanced BST" }, { "code": null, "e": 15350, "s": 15318, "text": "set vs unordered_set in C++ STL" }, { "code": null, "e": 15410, "s": 15350, "text": "Find k-th smallest element in BST (Order Statistics in BST)" } ]
Tailwind CSS Background Attachment
14 Jul, 2021 In this article, we will learn how to attach background images using Tailwind CSS. Approach: You can easily attach background images using the background-attachment property in Tailwind CSS. All the properties are covered in class form. It is the alternative to the CSS background-attachment property. It can be set to scroll or remain fixed. Background attachment classes: bg-fixed: This class is used to fix the background image relative to the viewport. bg-local: This class is used to scroll the background image with the container and the viewport. bg-scroll: This class is used to scroll the background image with the viewport, but not with the container. Syntax: <div class="bg-fixed ..."> ... </div> Example 1: The following example demonstrates fixing the background image relative to the viewport using the bg-fixed class. HTML <!DOCTYPE html><html> <head> <link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet"></head> <body class="text-center"> <h1 class="text-green-600 text-5xl font-bold"> GeeksforGeeks </h1> <b>Tailwind CSS Background Attachment Class</b> <div class="mx-4 h-screen w-full"> <div class="bg-fixed bg-contain overflow-auto m-20 h-80 w-38" style="background-image:url(https://media.geeksforgeeks.org/wp-content/uploads/20210603152813/tree276014340-300x191.jpg )"> </div> </div></body> </html> Output: bg-fixed Example 2: The following example demonstrates fixing the background image with the container and the viewport using the bg-local property. HTML <!DOCTYPE html><html> <head> <link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet"></head> <body> <div class="mx-4 flex items-center justify-center h-screen w-full"> <div class="bg-local bg-contain overflow-auto m-20 h-80 w-38" style="background-image:url(https://media.geeksforgeeks.org/wp-content/uploads/20210603154238/download-200x125.jpeg)"> <div class="h-64 w-64"></div> </div> </div></body> </html> Output: bg-local Example 3: The following example demonstrates fixing the background image with the viewport, but not with the container using the bg-scroll property. HTML <!DOCTYPE html><html> <head> <link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet"></head> <body> <div class="mx-4 flex items-center justify-center h-screen w-full"> <div class="bg-scroll bg-contain overflow-auto m-20 h-60 w-38" style="background-image:url( https://media.geeksforgeeks.org/wp-content/uploads/20210628092647/bgimage.jpg )"> <div class="h-64 w-64"></div> </div> </div></body> </html> Output: bg-scroll Picked Tailwind CSS CSS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Design a Tribute Page using HTML & CSS How to set space between the flexbox ? Build a Survey Form using HTML and CSS Form validation using jQuery Design a web page using HTML and CSS Installation of Node.js on Linux Difference between var, let and const keywords in JavaScript How to fetch data from an API in ReactJS ? Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array
[ { "code": null, "e": 28, "s": 0, "text": "\n14 Jul, 2021" }, { "code": null, "e": 111, "s": 28, "text": "In this article, we will learn how to attach background images using Tailwind CSS." }, { "code": null, "e": 121, "s": 111, "text": "Approach:" }, { "code": null, "e": 373, "s": 121, "text": "You can easily attach background images using the background-attachment property in Tailwind CSS. All the properties are covered in class form. It is the alternative to the CSS background-attachment property. It can be set to scroll or remain fixed. " }, { "code": null, "e": 404, "s": 373, "text": "Background attachment classes:" }, { "code": null, "e": 487, "s": 404, "text": "bg-fixed: This class is used to fix the background image relative to the viewport." }, { "code": null, "e": 584, "s": 487, "text": "bg-local: This class is used to scroll the background image with the container and the viewport." }, { "code": null, "e": 692, "s": 584, "text": "bg-scroll: This class is used to scroll the background image with the viewport, but not with the container." }, { "code": null, "e": 702, "s": 694, "text": "Syntax:" }, { "code": null, "e": 744, "s": 702, "text": "<div class=\"bg-fixed ...\">\n ...\n</div>" }, { "code": null, "e": 870, "s": 744, "text": "Example 1: The following example demonstrates fixing the background image relative to the viewport using the bg-fixed class. " }, { "code": null, "e": 875, "s": 870, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <link href=\"https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css\" rel=\"stylesheet\"></head> <body class=\"text-center\"> <h1 class=\"text-green-600 text-5xl font-bold\"> GeeksforGeeks </h1> <b>Tailwind CSS Background Attachment Class</b> <div class=\"mx-4 h-screen w-full\"> <div class=\"bg-fixed bg-contain overflow-auto m-20 h-80 w-38\" style=\"background-image:url(https://media.geeksforgeeks.org/wp-content/uploads/20210603152813/tree276014340-300x191.jpg )\"> </div> </div></body> </html>", "e": 1472, "s": 875, "text": null }, { "code": null, "e": 1480, "s": 1472, "text": "Output:" }, { "code": null, "e": 1489, "s": 1480, "text": "bg-fixed" }, { "code": null, "e": 1628, "s": 1489, "text": "Example 2: The following example demonstrates fixing the background image with the container and the viewport using the bg-local property." }, { "code": null, "e": 1633, "s": 1628, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <link href=\"https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css\" rel=\"stylesheet\"></head> <body> <div class=\"mx-4 flex items-center justify-center h-screen w-full\"> <div class=\"bg-local bg-contain overflow-auto m-20 h-80 w-38\" style=\"background-image:url(https://media.geeksforgeeks.org/wp-content/uploads/20210603154238/download-200x125.jpeg)\"> <div class=\"h-64 w-64\"></div> </div> </div></body> </html>", "e": 2155, "s": 1633, "text": null }, { "code": null, "e": 2163, "s": 2155, "text": "Output:" }, { "code": null, "e": 2172, "s": 2163, "text": "bg-local" }, { "code": null, "e": 2322, "s": 2172, "text": "Example 3: The following example demonstrates fixing the background image with the viewport, but not with the container using the bg-scroll property." }, { "code": null, "e": 2327, "s": 2322, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <link href=\"https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css\" rel=\"stylesheet\"></head> <body> <div class=\"mx-4 flex items-center justify-center h-screen w-full\"> <div class=\"bg-scroll bg-contain overflow-auto m-20 h-60 w-38\" style=\"background-image:url( https://media.geeksforgeeks.org/wp-content/uploads/20210628092647/bgimage.jpg )\"> <div class=\"h-64 w-64\"></div> </div> </div></body> </html>", "e": 2865, "s": 2327, "text": null }, { "code": null, "e": 2873, "s": 2865, "text": "Output:" }, { "code": null, "e": 2883, "s": 2873, "text": "bg-scroll" }, { "code": null, "e": 2890, "s": 2883, "text": "Picked" }, { "code": null, "e": 2903, "s": 2890, "text": "Tailwind CSS" }, { "code": null, "e": 2907, "s": 2903, "text": "CSS" }, { "code": null, "e": 2924, "s": 2907, "text": "Web Technologies" }, { "code": null, "e": 3022, "s": 2924, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3061, "s": 3022, "text": "Design a Tribute Page using HTML & CSS" }, { "code": null, "e": 3100, "s": 3061, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 3139, "s": 3100, "text": "Build a Survey Form using HTML and CSS" }, { "code": null, "e": 3168, "s": 3139, "text": "Form validation using jQuery" }, { "code": null, "e": 3205, "s": 3168, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 3238, "s": 3205, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 3299, "s": 3238, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 3342, "s": 3299, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 3414, "s": 3342, "text": "Differences between Functional Components and Class Components in React" } ]
Send mail from your Gmail account using Python
17 May, 2020 Here, we are going to learn how to send a simple basic mail using Python code. Python, being a powerful language don’t need any external library to import and offers a native library to send emails- “SMTP lib”. “smtplib” creates a Simple Mail Transfer Protocol client session object which is used to send emails to any valid email id on the internet. Different websites use different port numbers.In this article, we are using a Gmail account to send a mail. Port number used here is ‘587’. And if you want to send mail using a website other than Gmail, you need to get the corresponding information. Steps to send mail from Gmail account: First of all, “smtplib” library needs to be imported.After that, to create a session, we will be using its instance SMTP to encapsulate an SMTP connection.s = smtplib.SMTP('smtp.gmail.com', 587)In this, you need to pass the first parameter of the server location and the second parameter of the port to use. For Gmail, we use port number 587.For security reasons, now put the SMTP connection in the TLS mode. TLS (Transport Layer Security) encrypts all the SMTP commands. After that, for security and authentication, you need to pass your Gmail account credentials in the login instance.The compiler will show an authentication error if you enter invalid email id or password.Store the message you need to send in a variable say, message. Using the sendmail() instance, send your message. sendmail() uses three parameters: sender_email_id, receiver_email_id and message_to_be_sent. The parameters need to be in the same sequence. First of all, “smtplib” library needs to be imported. After that, to create a session, we will be using its instance SMTP to encapsulate an SMTP connection.s = smtplib.SMTP('smtp.gmail.com', 587)In this, you need to pass the first parameter of the server location and the second parameter of the port to use. For Gmail, we use port number 587. s = smtplib.SMTP('smtp.gmail.com', 587) In this, you need to pass the first parameter of the server location and the second parameter of the port to use. For Gmail, we use port number 587. For security reasons, now put the SMTP connection in the TLS mode. TLS (Transport Layer Security) encrypts all the SMTP commands. After that, for security and authentication, you need to pass your Gmail account credentials in the login instance.The compiler will show an authentication error if you enter invalid email id or password. Store the message you need to send in a variable say, message. Using the sendmail() instance, send your message. sendmail() uses three parameters: sender_email_id, receiver_email_id and message_to_be_sent. The parameters need to be in the same sequence. This will send the email from your account. After you have completed your task, terminate the SMTP session by using quit(). # Python code to illustrate Sending mail from # your Gmail account import smtplib # creates SMTP sessions = smtplib.SMTP('smtp.gmail.com', 587) # start TLS for securitys.starttls() # Authentications.login("sender_email_id", "sender_email_id_password") # message to be sentmessage = "Message_you_need_to_send" # sending the mails.sendmail("sender_email_id", "receiver_email_id", message) # terminating the sessions.quit() Sending same message to multiple people If you need to send the same message to different people. You can use for loop for that.For example, you have a list of email ids to which you need to send the same mail. To do so, insert a “for” loop between the initialization and termination of the SMTP session. Loop will initialize turn by turn and after sending the email, SMTP session will be terminated. # Python code to illustrate Sending mail # to multiple users # from your Gmail account import smtplib # list of email_id to send the mailli = ["[email protected]", "[email protected]"] for dest in li: s = smtplib.SMTP('smtp.gmail.com', 587) s.starttls() s.login("sender_email_id", "sender_email_id_password") message = "Message_you_need_to_send" s.sendmail("sender_email_id", dest, message) s.quit() Important Points: This code can send simple mail which doesn’t have any attachment or any subject. One of the most amazing things about this code is that we can send any number of emails using this and Gmail mostly put your mail in the primary section. Sent mails would not be detected as Spam generally. File handling can also be used to fetch email id from a file and further used for sending the emails. Next: Send mail with attachments from your Gmail account using Python This article is contributed by Rishabh Bansal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. SelsoLiberado Aman884036 Python TechTips Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Find the Wi-Fi Password Using CMD in Windows? Docker - COPY Instruction Setting up the environment in Java How to Run a Python Script using Docker? Running Python script on GPU.
[ { "code": null, "e": 54, "s": 26, "text": "\n17 May, 2020" }, { "code": null, "e": 655, "s": 54, "text": "Here, we are going to learn how to send a simple basic mail using Python code. Python, being a powerful language don’t need any external library to import and offers a native library to send emails- “SMTP lib”. “smtplib” creates a Simple Mail Transfer Protocol client session object which is used to send emails to any valid email id on the internet. Different websites use different port numbers.In this article, we are using a Gmail account to send a mail. Port number used here is ‘587’. And if you want to send mail using a website other than Gmail, you need to get the corresponding information." }, { "code": null, "e": 694, "s": 655, "text": "Steps to send mail from Gmail account:" }, { "code": null, "e": 1624, "s": 694, "text": "First of all, “smtplib” library needs to be imported.After that, to create a session, we will be using its instance SMTP to encapsulate an SMTP connection.s = smtplib.SMTP('smtp.gmail.com', 587)In this, you need to pass the first parameter of the server location and the second parameter of the port to use. For Gmail, we use port number 587.For security reasons, now put the SMTP connection in the TLS mode. TLS (Transport Layer Security) encrypts all the SMTP commands. After that, for security and authentication, you need to pass your Gmail account credentials in the login instance.The compiler will show an authentication error if you enter invalid email id or password.Store the message you need to send in a variable say, message. Using the sendmail() instance, send your message. sendmail() uses three parameters: sender_email_id, receiver_email_id and message_to_be_sent. The parameters need to be in the same sequence." }, { "code": null, "e": 1678, "s": 1624, "text": "First of all, “smtplib” library needs to be imported." }, { "code": null, "e": 1968, "s": 1678, "text": "After that, to create a session, we will be using its instance SMTP to encapsulate an SMTP connection.s = smtplib.SMTP('smtp.gmail.com', 587)In this, you need to pass the first parameter of the server location and the second parameter of the port to use. For Gmail, we use port number 587." }, { "code": null, "e": 2008, "s": 1968, "text": "s = smtplib.SMTP('smtp.gmail.com', 587)" }, { "code": null, "e": 2157, "s": 2008, "text": "In this, you need to pass the first parameter of the server location and the second parameter of the port to use. For Gmail, we use port number 587." }, { "code": null, "e": 2492, "s": 2157, "text": "For security reasons, now put the SMTP connection in the TLS mode. TLS (Transport Layer Security) encrypts all the SMTP commands. After that, for security and authentication, you need to pass your Gmail account credentials in the login instance.The compiler will show an authentication error if you enter invalid email id or password." }, { "code": null, "e": 2746, "s": 2492, "text": "Store the message you need to send in a variable say, message. Using the sendmail() instance, send your message. sendmail() uses three parameters: sender_email_id, receiver_email_id and message_to_be_sent. The parameters need to be in the same sequence." }, { "code": null, "e": 2870, "s": 2746, "text": "This will send the email from your account. After you have completed your task, terminate the SMTP session by using quit()." }, { "code": "# Python code to illustrate Sending mail from # your Gmail account import smtplib # creates SMTP sessions = smtplib.SMTP('smtp.gmail.com', 587) # start TLS for securitys.starttls() # Authentications.login(\"sender_email_id\", \"sender_email_id_password\") # message to be sentmessage = \"Message_you_need_to_send\" # sending the mails.sendmail(\"sender_email_id\", \"receiver_email_id\", message) # terminating the sessions.quit()", "e": 3297, "s": 2870, "text": null }, { "code": null, "e": 3337, "s": 3297, "text": "Sending same message to multiple people" }, { "code": null, "e": 3698, "s": 3337, "text": "If you need to send the same message to different people. You can use for loop for that.For example, you have a list of email ids to which you need to send the same mail. To do so, insert a “for” loop between the initialization and termination of the SMTP session. Loop will initialize turn by turn and after sending the email, SMTP session will be terminated." }, { "code": "# Python code to illustrate Sending mail # to multiple users # from your Gmail account import smtplib # list of email_id to send the mailli = [\"[email protected]\", \"[email protected]\"] for dest in li: s = smtplib.SMTP('smtp.gmail.com', 587) s.starttls() s.login(\"sender_email_id\", \"sender_email_id_password\") message = \"Message_you_need_to_send\" s.sendmail(\"sender_email_id\", dest, message) s.quit()", "e": 4114, "s": 3698, "text": null }, { "code": null, "e": 4132, "s": 4114, "text": "Important Points:" }, { "code": null, "e": 4213, "s": 4132, "text": "This code can send simple mail which doesn’t have any attachment or any subject." }, { "code": null, "e": 4419, "s": 4213, "text": "One of the most amazing things about this code is that we can send any number of emails using this and Gmail mostly put your mail in the primary section. Sent mails would not be detected as Spam generally." }, { "code": null, "e": 4521, "s": 4419, "text": "File handling can also be used to fetch email id from a file and further used for sending the emails." }, { "code": null, "e": 4591, "s": 4521, "text": "Next: Send mail with attachments from your Gmail account using Python" }, { "code": null, "e": 4893, "s": 4591, "text": "This article is contributed by Rishabh Bansal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 5018, "s": 4893, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 5032, "s": 5018, "text": "SelsoLiberado" }, { "code": null, "e": 5043, "s": 5032, "text": "Aman884036" }, { "code": null, "e": 5050, "s": 5043, "text": "Python" }, { "code": null, "e": 5059, "s": 5050, "text": "TechTips" }, { "code": null, "e": 5157, "s": 5059, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5175, "s": 5157, "text": "Python Dictionary" }, { "code": null, "e": 5217, "s": 5175, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 5239, "s": 5217, "text": "Enumerate() in Python" }, { "code": null, "e": 5274, "s": 5239, "text": "Read a file line by line in Python" }, { "code": null, "e": 5300, "s": 5274, "text": "Python String | replace()" }, { "code": null, "e": 5353, "s": 5300, "text": "How to Find the Wi-Fi Password Using CMD in Windows?" }, { "code": null, "e": 5379, "s": 5353, "text": "Docker - COPY Instruction" }, { "code": null, "e": 5414, "s": 5379, "text": "Setting up the environment in Java" }, { "code": null, "e": 5455, "s": 5414, "text": "How to Run a Python Script using Docker?" } ]
groups command in Linux with examples
20 May, 2019 In linux, there can be multiple users(those who use/operate the system), and groups are nothing but the collection of users. Groups make it easy to manage users with the same security and access privileges. A user can be part of different groups. Important Points: Groups command prints the names of the primary and any supplementary groups for each given username, or the current process if no names are given. If more than one name is given, the name of each user is printed before the list of that user’s groups and the username is separated from the group list by a colon. Syntax: groups [username]... Example 1: Provided with a user name $groups demon In this example, username demon is passed with groups command and the output shows the groups in which the user demon is present, separated by a colon. Example 2: No username is passed then this will display group membership for the current user $groups Here the current user is demon . So when we give “groups” command only we get groups in which demon is a user. Example 3: Passing root with groups command Note: Primary and supplementary groups for a process are normally inherited from its parent and are usually unchanged since login. This means that if you change the group database after logging in, groups will not reflect your changes within your existing login session. The only options are –help and –version. linux-command Linux-misc-commands Picked Technical Scripter 2018 Linux-Unix Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. ZIP command in Linux with examples tar command in Linux with examples curl command in Linux with Examples SORT command in Linux/Unix with examples 'crontab' in Linux with Examples Tail command in Linux with examples Conditional Statements | Shell Script TCP Server-Client implementation in C Docker - COPY Instruction scp command in Linux with Examples
[ { "code": null, "e": 28, "s": 0, "text": "\n20 May, 2019" }, { "code": null, "e": 275, "s": 28, "text": "In linux, there can be multiple users(those who use/operate the system), and groups are nothing but the collection of users. Groups make it easy to manage users with the same security and access privileges. A user can be part of different groups." }, { "code": null, "e": 293, "s": 275, "text": "Important Points:" }, { "code": null, "e": 440, "s": 293, "text": "Groups command prints the names of the primary and any supplementary groups for each given username, or the current process if no names are given." }, { "code": null, "e": 605, "s": 440, "text": "If more than one name is given, the name of each user is printed before the list of that user’s groups and the username is separated from the group list by a colon." }, { "code": null, "e": 613, "s": 605, "text": "Syntax:" }, { "code": null, "e": 635, "s": 613, "text": "groups [username]...\n" }, { "code": null, "e": 672, "s": 635, "text": "Example 1: Provided with a user name" }, { "code": null, "e": 687, "s": 672, "text": "$groups demon\n" }, { "code": null, "e": 839, "s": 687, "text": "In this example, username demon is passed with groups command and the output shows the groups in which the user demon is present, separated by a colon." }, { "code": null, "e": 933, "s": 839, "text": "Example 2: No username is passed then this will display group membership for the current user" }, { "code": null, "e": 942, "s": 933, "text": "$groups\n" }, { "code": null, "e": 1053, "s": 942, "text": "Here the current user is demon . So when we give “groups” command only we get groups in which demon is a user." }, { "code": null, "e": 1097, "s": 1053, "text": "Example 3: Passing root with groups command" }, { "code": null, "e": 1409, "s": 1097, "text": "Note: Primary and supplementary groups for a process are normally inherited from its parent and are usually unchanged since login. This means that if you change the group database after logging in, groups will not reflect your changes within your existing login session. The only options are –help and –version." }, { "code": null, "e": 1423, "s": 1409, "text": "linux-command" }, { "code": null, "e": 1443, "s": 1423, "text": "Linux-misc-commands" }, { "code": null, "e": 1450, "s": 1443, "text": "Picked" }, { "code": null, "e": 1474, "s": 1450, "text": "Technical Scripter 2018" }, { "code": null, "e": 1485, "s": 1474, "text": "Linux-Unix" }, { "code": null, "e": 1504, "s": 1485, "text": "Technical Scripter" }, { "code": null, "e": 1602, "s": 1504, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1637, "s": 1602, "text": "ZIP command in Linux with examples" }, { "code": null, "e": 1672, "s": 1637, "text": "tar command in Linux with examples" }, { "code": null, "e": 1708, "s": 1672, "text": "curl command in Linux with Examples" }, { "code": null, "e": 1749, "s": 1708, "text": "SORT command in Linux/Unix with examples" }, { "code": null, "e": 1782, "s": 1749, "text": "'crontab' in Linux with Examples" }, { "code": null, "e": 1818, "s": 1782, "text": "Tail command in Linux with examples" }, { "code": null, "e": 1856, "s": 1818, "text": "Conditional Statements | Shell Script" }, { "code": null, "e": 1894, "s": 1856, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 1920, "s": 1894, "text": "Docker - COPY Instruction" } ]
Java Program to Check Array Bounds while Inputing Elements into the Array
23 Jun, 2021 Concept: Arrays are static data structures and do not grow automatically with an increasing number of elements. With arrays, it is important to specify the array size at the time of the declaration. In Java, when we try to access an array index beyond the range of the array it throws an ArrayIndexOutOfBounds Exception. An exception is an obstruction to the normal program execution. Java has try-catch-finally blocks for efficient Exception Handling. ArrayIndexOutOfBoundsException is a runtime exception and must be handled carefully to prevent abrupt termination of the program. Approaches: Using try-catch block where input is taken beyond the array index rangeUsing try-catch block where input is taken within the array index rangeUsing constraints over user input Using try-catch block where input is taken beyond the array index range Using try-catch block where input is taken within the array index range Using constraints over user input First Approach In the first approach, an array of size = 5 is declared. The input is taken within a try block and the loop is executed 6 times. Since the array size is 5, after the 6th input an ArrayIndexOutOfBoundsException is thrown. The exception is handled by the catch block. The code to handle the exception is placed within the catch block. In this example, we notify the user that an exception has occurred and the input exceeds the array range. Implementation: In all approaches variable named ‘i’ is used of integer data-type been taken for consideration. Java // Importing generic Classes/Filesimport java.util.*; public class GFG { // Main driver method public static void main(String args[]) throws ArrayIndexOutOfBoundsException { // Taking input from user Scanner s = new Scanner(System.in); // Storing user input elements in an array int arr[] = new int[5]; // Try block to check exception try { // Forcefully iteration loop no of times // these no of times > array size for (int i = 0; i < 6; i++) { // Storing elements through nextInt() arr[i] = s.nextInt(); } } catch (ArrayIndexOutOfBoundsException e) { // Print message when any exception occurs System.out.println( "Array Bounds Exceeded...\nTry Again"); } }} Output: Second Approach In the second approach, we declare an array of size = 5. The input is taken within a while loop inside a try block. The value of i is checked against the size of the array at every iteration. The value of ‘i’ is initiated with 0 and can take input up to index 4. As soon as the value of ‘i’ reaches 5 an exception is thrown. This exception is handled by the catch block. This method is similar to the first one, however, in this approach, no input is taken beyond the array index range which was not the case in the first approach. Implementation: Java // Importing generic Classes/Filesimport java.util.*; public class GFG { // Main driver method public static void main(String args[]) throws ArrayIndexOutOfBoundsException { // Taking input from user Scanner s = new Scanner(System.in); // Storing elements as array int arr[] = new int[5]; / variable created and initialized with 0 int i = 0; // try block to check exception try { // Condition check while (true) { if (i == 5) // Statement responsible for exception throw new ArrayIndexOutOfBoundsException(); arr[i++] = s.nextInt(); } } // Catch block to handle exception catch (ArrayIndexOutOfBoundsException e) { // Message printed when exception occurs System.out.println( "Array Bounds Exceeded...\nTry Again"); } }} Output: Third Approach In this approach we do not use the concept of exception handling rather we limit the input using loops. It is an easier and convenient method of checking array bounds while taking inputs from the user. Implementation: Java // Importing Classes/Filesimport java.util.*; public class GFG { // Main driver code public static void main(String args[]) { // Taking user input through scanner Scanner s = new Scanner(System.in); // Creating array to store elements int arr[] = new int[5]; // creating and initializing variable with 0 int i = 0; // Condition check while (i < 5) { // Storing user defined elements in array arr[i++] = s.nextInt(); } System.out.println( "Array elements are as follows: "); // Iteration over elements for (int j = 0; j < 5; j++) System.out.print(arr[j] + " "); }} Output: sooda367 Java-Array-Programs Technical Scripter 2020 Java Java Programs Technical Scripter Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java How to iterate any Map in Java Interfaces in Java HashMap in Java with Examples Stream In Java Initializing a List in Java Java Programming Examples Convert a String to Character Array in Java Implementing a Linked List in Java using Class Factory method design pattern in Java
[ { "code": null, "e": 28, "s": 0, "text": "\n23 Jun, 2021" }, { "code": null, "e": 612, "s": 28, "text": "Concept: Arrays are static data structures and do not grow automatically with an increasing number of elements. With arrays, it is important to specify the array size at the time of the declaration. In Java, when we try to access an array index beyond the range of the array it throws an ArrayIndexOutOfBounds Exception. An exception is an obstruction to the normal program execution. Java has try-catch-finally blocks for efficient Exception Handling. ArrayIndexOutOfBoundsException is a runtime exception and must be handled carefully to prevent abrupt termination of the program. " }, { "code": null, "e": 624, "s": 612, "text": "Approaches:" }, { "code": null, "e": 801, "s": 624, "text": "Using try-catch block where input is taken beyond the array index rangeUsing try-catch block where input is taken within the array index rangeUsing constraints over user input " }, { "code": null, "e": 873, "s": 801, "text": "Using try-catch block where input is taken beyond the array index range" }, { "code": null, "e": 945, "s": 873, "text": "Using try-catch block where input is taken within the array index range" }, { "code": null, "e": 980, "s": 945, "text": "Using constraints over user input " }, { "code": null, "e": 995, "s": 980, "text": "First Approach" }, { "code": null, "e": 1434, "s": 995, "text": "In the first approach, an array of size = 5 is declared. The input is taken within a try block and the loop is executed 6 times. Since the array size is 5, after the 6th input an ArrayIndexOutOfBoundsException is thrown. The exception is handled by the catch block. The code to handle the exception is placed within the catch block. In this example, we notify the user that an exception has occurred and the input exceeds the array range." }, { "code": null, "e": 1546, "s": 1434, "text": "Implementation: In all approaches variable named ‘i’ is used of integer data-type been taken for consideration." }, { "code": null, "e": 1551, "s": 1546, "text": "Java" }, { "code": "// Importing generic Classes/Filesimport java.util.*; public class GFG { // Main driver method public static void main(String args[]) throws ArrayIndexOutOfBoundsException { // Taking input from user Scanner s = new Scanner(System.in); // Storing user input elements in an array int arr[] = new int[5]; // Try block to check exception try { // Forcefully iteration loop no of times // these no of times > array size for (int i = 0; i < 6; i++) { // Storing elements through nextInt() arr[i] = s.nextInt(); } } catch (ArrayIndexOutOfBoundsException e) { // Print message when any exception occurs System.out.println( \"Array Bounds Exceeded...\\nTry Again\"); } }}", "e": 2410, "s": 1551, "text": null }, { "code": null, "e": 2418, "s": 2410, "text": "Output:" }, { "code": null, "e": 2434, "s": 2418, "text": "Second Approach" }, { "code": null, "e": 2966, "s": 2434, "text": "In the second approach, we declare an array of size = 5. The input is taken within a while loop inside a try block. The value of i is checked against the size of the array at every iteration. The value of ‘i’ is initiated with 0 and can take input up to index 4. As soon as the value of ‘i’ reaches 5 an exception is thrown. This exception is handled by the catch block. This method is similar to the first one, however, in this approach, no input is taken beyond the array index range which was not the case in the first approach." }, { "code": null, "e": 2982, "s": 2966, "text": "Implementation:" }, { "code": null, "e": 2987, "s": 2982, "text": "Java" }, { "code": "// Importing generic Classes/Filesimport java.util.*; public class GFG { // Main driver method public static void main(String args[]) throws ArrayIndexOutOfBoundsException { // Taking input from user Scanner s = new Scanner(System.in); // Storing elements as array int arr[] = new int[5]; / variable created and initialized with 0 int i = 0; // try block to check exception try { // Condition check while (true) { if (i == 5) // Statement responsible for exception throw new ArrayIndexOutOfBoundsException(); arr[i++] = s.nextInt(); } } // Catch block to handle exception catch (ArrayIndexOutOfBoundsException e) { // Message printed when exception occurs System.out.println( \"Array Bounds Exceeded...\\nTry Again\"); } }}", "e": 3950, "s": 2987, "text": null }, { "code": null, "e": 3958, "s": 3950, "text": "Output:" }, { "code": null, "e": 3973, "s": 3958, "text": "Third Approach" }, { "code": null, "e": 4175, "s": 3973, "text": "In this approach we do not use the concept of exception handling rather we limit the input using loops. It is an easier and convenient method of checking array bounds while taking inputs from the user." }, { "code": null, "e": 4191, "s": 4175, "text": "Implementation:" }, { "code": null, "e": 4196, "s": 4191, "text": "Java" }, { "code": "// Importing Classes/Filesimport java.util.*; public class GFG { // Main driver code public static void main(String args[]) { // Taking user input through scanner Scanner s = new Scanner(System.in); // Creating array to store elements int arr[] = new int[5]; // creating and initializing variable with 0 int i = 0; // Condition check while (i < 5) { // Storing user defined elements in array arr[i++] = s.nextInt(); } System.out.println( \"Array elements are as follows: \"); // Iteration over elements for (int j = 0; j < 5; j++) System.out.print(arr[j] + \" \"); }}", "e": 4908, "s": 4196, "text": null }, { "code": null, "e": 4916, "s": 4908, "text": "Output:" }, { "code": null, "e": 4925, "s": 4916, "text": "sooda367" }, { "code": null, "e": 4945, "s": 4925, "text": "Java-Array-Programs" }, { "code": null, "e": 4969, "s": 4945, "text": "Technical Scripter 2020" }, { "code": null, "e": 4974, "s": 4969, "text": "Java" }, { "code": null, "e": 4988, "s": 4974, "text": "Java Programs" }, { "code": null, "e": 5007, "s": 4988, "text": "Technical Scripter" }, { "code": null, "e": 5012, "s": 5007, "text": "Java" }, { "code": null, "e": 5110, "s": 5012, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5161, "s": 5110, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 5192, "s": 5161, "text": "How to iterate any Map in Java" }, { "code": null, "e": 5211, "s": 5192, "text": "Interfaces in Java" }, { "code": null, "e": 5241, "s": 5211, "text": "HashMap in Java with Examples" }, { "code": null, "e": 5256, "s": 5241, "text": "Stream In Java" }, { "code": null, "e": 5284, "s": 5256, "text": "Initializing a List in Java" }, { "code": null, "e": 5310, "s": 5284, "text": "Java Programming Examples" }, { "code": null, "e": 5354, "s": 5310, "text": "Convert a String to Character Array in Java" }, { "code": null, "e": 5401, "s": 5354, "text": "Implementing a Linked List in Java using Class" } ]
Node.js http.server.listen() Method
12 Jan, 2021 The http.server.listen() is an inbuilt application programming interface of class Server within the http module which is used to start the server from accepting new connections. Syntax: const server.listen(options[, callback]) Parameters: This method accepts the following two parameters: option: It can be the port, host, path, backlog, exclusive, readableAll, writableAll, ipv6Only, etc depending upon user need. callback: It is an optional parameter, it is the callback function that is passed as a parameter. Return Value: This method returns nothing but a callback function. Example 1: Filename-index.js Javascript // Node.js program to demonstrate the // server.listen() method // Importing http module var http = require('http'); // Setting up PORT const PORT = process.env.PORT || 3000; // Creating http Server var httpServer = http.createServer( function (request, response) { // Getting the reference of the // underlying socket object // by using socket method const value = response.socket; // Display result // by using end() method response.end("socket buffersize : " + value.bufferSize, 'utf8', () => { console.log("displaying the result..."); // Closing server // by using close() method httpServer.close(() => { console.log("server is closed") }) });}); // Listening to http Server // by using listen() methodhttpServer.listen(PORT, () => { console.log("Server is running at port 3000...");}); Run the index.js file using the following command: node index.js Output: Server is running at port 3000... displaying the result... server is closed Now run http://localhost:3000/ in the browser and you will see the following output on screen: socket buffersize : 0 Example 2: Filename-index.js Javascript // Node.js program to demonstrate the // server.listen() method // Importing http module var http = require('http'); // Request and response handler const httpHandlers = (request, response) => { // Getting the reference of the // underlying socket object // by using socket method const value = response.socket; // Display result by using end() method response.end("socket local address : " + value.localAddress, 'utf8', () => { console.log("displaying the result..."); // Closing server by using close() method httpServer.close(() => { console.log("server is closed") }) });}; // Listening to http Server // by using listen() methodvar httpServer = http.createServer( httpHandlers).listen(3000, () => { console.log("Server is running at port 3000...");}); Run the index.js file using the following command: node index.js Output: Server is running at port 3000... displaying the result... server is closed Now run http://localhost:3000/ in the browser and you will see the following output on screen: socket local address : ::1 Reference: https://nodejs.org/dist/latest-v12.x/docs/api/http.html#http_server_listen Node.js-Methods Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Node.js fs.writeFile() Method How to install the previous version of node.js and npm ? Difference between promise and async await in Node.js Mongoose | findByIdAndUpdate() Function Installation of Node.js on Windows Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ? Differences between Functional Components and Class Components in React
[ { "code": null, "e": 28, "s": 0, "text": "\n12 Jan, 2021" }, { "code": null, "e": 206, "s": 28, "text": "The http.server.listen() is an inbuilt application programming interface of class Server within the http module which is used to start the server from accepting new connections." }, { "code": null, "e": 214, "s": 206, "text": "Syntax:" }, { "code": null, "e": 255, "s": 214, "text": "const server.listen(options[, callback])" }, { "code": null, "e": 317, "s": 255, "text": "Parameters: This method accepts the following two parameters:" }, { "code": null, "e": 443, "s": 317, "text": "option: It can be the port, host, path, backlog, exclusive, readableAll, writableAll, ipv6Only, etc depending upon user need." }, { "code": null, "e": 541, "s": 443, "text": "callback: It is an optional parameter, it is the callback function that is passed as a parameter." }, { "code": null, "e": 608, "s": 541, "text": "Return Value: This method returns nothing but a callback function." }, { "code": null, "e": 637, "s": 608, "text": "Example 1: Filename-index.js" }, { "code": null, "e": 648, "s": 637, "text": "Javascript" }, { "code": "// Node.js program to demonstrate the // server.listen() method // Importing http module var http = require('http'); // Setting up PORT const PORT = process.env.PORT || 3000; // Creating http Server var httpServer = http.createServer( function (request, response) { // Getting the reference of the // underlying socket object // by using socket method const value = response.socket; // Display result // by using end() method response.end(\"socket buffersize : \" + value.bufferSize, 'utf8', () => { console.log(\"displaying the result...\"); // Closing server // by using close() method httpServer.close(() => { console.log(\"server is closed\") }) });}); // Listening to http Server // by using listen() methodhttpServer.listen(PORT, () => { console.log(\"Server is running at port 3000...\");});", "e": 1563, "s": 648, "text": null }, { "code": null, "e": 1614, "s": 1563, "text": "Run the index.js file using the following command:" }, { "code": null, "e": 1628, "s": 1614, "text": "node index.js" }, { "code": null, "e": 1636, "s": 1628, "text": "Output:" }, { "code": null, "e": 1712, "s": 1636, "text": "Server is running at port 3000...\ndisplaying the result...\nserver is closed" }, { "code": null, "e": 1807, "s": 1712, "text": "Now run http://localhost:3000/ in the browser and you will see the following output on screen:" }, { "code": null, "e": 1829, "s": 1807, "text": "socket buffersize : 0" }, { "code": null, "e": 1858, "s": 1829, "text": "Example 2: Filename-index.js" }, { "code": null, "e": 1869, "s": 1858, "text": "Javascript" }, { "code": "// Node.js program to demonstrate the // server.listen() method // Importing http module var http = require('http'); // Request and response handler const httpHandlers = (request, response) => { // Getting the reference of the // underlying socket object // by using socket method const value = response.socket; // Display result by using end() method response.end(\"socket local address : \" + value.localAddress, 'utf8', () => { console.log(\"displaying the result...\"); // Closing server by using close() method httpServer.close(() => { console.log(\"server is closed\") }) });}; // Listening to http Server // by using listen() methodvar httpServer = http.createServer( httpHandlers).listen(3000, () => { console.log(\"Server is running at port 3000...\");});", "e": 2734, "s": 1869, "text": null }, { "code": null, "e": 2785, "s": 2734, "text": "Run the index.js file using the following command:" }, { "code": null, "e": 2799, "s": 2785, "text": "node index.js" }, { "code": null, "e": 2807, "s": 2799, "text": "Output:" }, { "code": null, "e": 2883, "s": 2807, "text": "Server is running at port 3000...\ndisplaying the result...\nserver is closed" }, { "code": null, "e": 2978, "s": 2883, "text": "Now run http://localhost:3000/ in the browser and you will see the following output on screen:" }, { "code": null, "e": 3005, "s": 2978, "text": "socket local address : ::1" }, { "code": null, "e": 3091, "s": 3005, "text": "Reference: https://nodejs.org/dist/latest-v12.x/docs/api/http.html#http_server_listen" }, { "code": null, "e": 3107, "s": 3091, "text": "Node.js-Methods" }, { "code": null, "e": 3115, "s": 3107, "text": "Node.js" }, { "code": null, "e": 3132, "s": 3115, "text": "Web Technologies" }, { "code": null, "e": 3230, "s": 3132, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3260, "s": 3230, "text": "Node.js fs.writeFile() Method" }, { "code": null, "e": 3317, "s": 3260, "text": "How to install the previous version of node.js and npm ?" }, { "code": null, "e": 3371, "s": 3317, "text": "Difference between promise and async await in Node.js" }, { "code": null, "e": 3411, "s": 3371, "text": "Mongoose | findByIdAndUpdate() Function" }, { "code": null, "e": 3446, "s": 3411, "text": "Installation of Node.js on Windows" }, { "code": null, "e": 3508, "s": 3446, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 3569, "s": 3508, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 3619, "s": 3569, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 3662, "s": 3619, "text": "How to fetch data from an API in ReactJS ?" } ]
MongoDB – Less than Operator $lt
27 Mar, 2020 MongoDB provides different types of comparison operators and less than operator ( $lt ) is one of them. This operator is used to select those documents where the value of the field is less than (<) the given value. You can use this operator in methods like, find(), update(), etc. as per your requirements. Syntax: {field: {$lt: value}} In the following examples, we are working with: Database: GeeksforGeeksCollection: employeeDocument: four documents that contain the details of the employees in the form of field-value pairs. Example #1:In this example, we are selecting those documents where the value of the salary field is less than 35000. Example #2: In this example, we are selecting only those documents where the age of the employee is less than 24. Or in other words, in this example, we are specifying conditions on the field in the embedded document using dot notation. Example #3:In this example, we are selecting only those documents where the points array is less than the specified array. Example #4:In this example, we are updating the salary of those employees whose experience year is less than 2 years. Or in other words, set the value of the salary field to 23000 of those documents whose experienceYear field value is less than 2. MongoDB Advanced Computer Subject Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n27 Mar, 2020" }, { "code": null, "e": 335, "s": 28, "text": "MongoDB provides different types of comparison operators and less than operator ( $lt ) is one of them. This operator is used to select those documents where the value of the field is less than (<) the given value. You can use this operator in methods like, find(), update(), etc. as per your requirements." }, { "code": null, "e": 343, "s": 335, "text": "Syntax:" }, { "code": null, "e": 365, "s": 343, "text": "{field: {$lt: value}}" }, { "code": null, "e": 413, "s": 365, "text": "In the following examples, we are working with:" }, { "code": null, "e": 557, "s": 413, "text": "Database: GeeksforGeeksCollection: employeeDocument: four documents that contain the details of the employees in the form of field-value pairs." }, { "code": null, "e": 675, "s": 557, "text": " Example #1:In this example, we are selecting those documents where the value of the salary field is less than 35000." }, { "code": null, "e": 688, "s": 675, "text": " Example #2:" }, { "code": null, "e": 1036, "s": 688, "text": "In this example, we are selecting only those documents where the age of the employee is less than 24. Or in other words, in this example, we are specifying conditions on the field in the embedded document using dot notation. Example #3:In this example, we are selecting only those documents where the points array is less than the specified array." }, { "code": null, "e": 1285, "s": 1036, "text": " Example #4:In this example, we are updating the salary of those employees whose experience year is less than 2 years. Or in other words, set the value of the salary field to 23000 of those documents whose experienceYear field value is less than 2." }, { "code": null, "e": 1293, "s": 1285, "text": "MongoDB" }, { "code": null, "e": 1319, "s": 1293, "text": "Advanced Computer Subject" } ]
HTML - Backgrounds
By default, your webpage background is white in color. You may not like it, but no worries. HTML provides you following two good ways to decorate your webpage background. HTML Background with Colors HTML Background with Images Now let's see both the approaches one by one using appropriate examples. The bgcolor attribute is used to control the background of an HTML element, specifically page body and table backgrounds. Note − The bgcolor attribute deprecated in HTML5. Do not use this attribute. Following is the syntax to use bgcolor attribute with any HTML tag. <tagname bgcolor = "color_value"...> This color_value can be given in any of the following formats − <!-- Format 1 - Use color name --> <table bgcolor = "lime" > <!-- Format 2 - Use hex value --> <table bgcolor = "#f1f1f1" > <!-- Format 3 - Use color value in RGB terms --> <table bgcolor = "rgb(0,0,120)" > Here are the examples to set background of an HTML tag − <!DOCTYPE html> <html> <head> <title>HTML Background Colors</title> </head> <body> <!-- Format 1 - Use color name --> <table bgcolor = "yellow" width = "100%"> <tr> <td> This background is yellow </td> </tr> </table> <!-- Format 2 - Use hex value --> <table bgcolor = "#6666FF" width = "100%"> <tr> <td> This background is sky blue </td> </tr> </table> <!-- Format 3 - Use color value in RGB terms --> <table bgcolor = "rgb(255,0,255)" width = "100%"> <tr> <td> This background is green </td> </tr> </table> </body> </html> This will produce the following result − The background attribute can also be used to control the background of an HTML element, specifically page body and table backgrounds. You can specify an image to set background of your HTML page or table. Note − The background attribute deprecated in HTML5. Do not use this attribute. Following is the syntax to use background attribute with any HTML tag. Note − The background attribute is deprecated and it is recommended to use Style Sheet for background setting. <tagname background = "Image URL"...> The most frequently used image formats are JPEG, GIF and PNG images. Here are the examples to set background images of a table. <!DOCTYPE html> <html> <head> <title>HTML Background Images</title> </head> <body> <!-- Set table background --> <table background = "/images/html.gif" width = "100%" height = "100"> <tr><td> This background is filled up with HTML image. </td></tr> </table> </body> </html> This will produce the following result − You might have seen many pattern or transparent backgrounds on various websites. This simply can be achieved by using patterned image or transparent image in the background. It is suggested that while creating patterns or transparent GIF or PNG images, use the smallest dimensions possible even as small as 1x1 to avoid slow loading. Here are the examples to set background pattern of a table − <!DOCTYPE html> <html> <head> <title>HTML Background Images</title> </head> <body> <!-- Set a table background using pattern --> <table background = "/images/pattern1.gif" width = "100%" height = "100"> <tr> <td> This background is filled up with a pattern image. </td> </tr> </table> <!-- Another example on table background using pattern --> <table background = "/images/pattern2.gif" width = "100%" height = "100"> <tr> <td> This background is filled up with a pattern image. </td> </tr> </table> </body> </html> This will produce the following result −
[ { "code": null, "e": 2679, "s": 2508, "text": "By default, your webpage background is white in color. You may not like it, but no worries. HTML provides you following two good ways to decorate your webpage background." }, { "code": null, "e": 2707, "s": 2679, "text": "HTML Background with Colors" }, { "code": null, "e": 2735, "s": 2707, "text": "HTML Background with Images" }, { "code": null, "e": 2808, "s": 2735, "text": "Now let's see both the approaches one by one using appropriate examples." }, { "code": null, "e": 2930, "s": 2808, "text": "The bgcolor attribute is used to control the background of an HTML element, specifically page body and table backgrounds." }, { "code": null, "e": 3007, "s": 2930, "text": "Note − The bgcolor attribute deprecated in HTML5. Do not use this attribute." }, { "code": null, "e": 3075, "s": 3007, "text": "Following is the syntax to use bgcolor attribute with any HTML tag." }, { "code": null, "e": 3113, "s": 3075, "text": "<tagname bgcolor = \"color_value\"...>\n" }, { "code": null, "e": 3177, "s": 3113, "text": "This color_value can be given in any of the following formats −" }, { "code": null, "e": 3389, "s": 3177, "text": "<!-- Format 1 - Use color name -->\n<table bgcolor = \"lime\" >\n \n<!-- Format 2 - Use hex value -->\n<table bgcolor = \"#f1f1f1\" >\n \n<!-- Format 3 - Use color value in RGB terms -->\n<table bgcolor = \"rgb(0,0,120)\" >\n" }, { "code": null, "e": 3446, "s": 3389, "text": "Here are the examples to set background of an HTML tag −" }, { "code": null, "e": 4224, "s": 3446, "text": "<!DOCTYPE html>\n<html>\n\n <head>\n <title>HTML Background Colors</title>\n </head>\n\t\n <body>\n <!-- Format 1 - Use color name -->\n <table bgcolor = \"yellow\" width = \"100%\">\n <tr>\n <td>\n This background is yellow\n </td>\n </tr>\n </table>\n \n <!-- Format 2 - Use hex value -->\n <table bgcolor = \"#6666FF\" width = \"100%\">\n <tr>\n <td>\n This background is sky blue\n </td>\n </tr>\n </table>\n \n <!-- Format 3 - Use color value in RGB terms -->\n <table bgcolor = \"rgb(255,0,255)\" width = \"100%\">\n <tr>\n <td>\n This background is green\n </td>\n </tr>\n </table>\n </body>\n \n</html>" }, { "code": null, "e": 4265, "s": 4224, "text": "This will produce the following result −" }, { "code": null, "e": 4470, "s": 4265, "text": "The background attribute can also be used to control the background of an HTML element, specifically page body and table backgrounds. You can specify an image to set background of your HTML page or table." }, { "code": null, "e": 4550, "s": 4470, "text": "Note − The background attribute deprecated in HTML5. Do not use this attribute." }, { "code": null, "e": 4621, "s": 4550, "text": "Following is the syntax to use background attribute with any HTML tag." }, { "code": null, "e": 4732, "s": 4621, "text": "Note − The background attribute is deprecated and it is recommended to use Style Sheet for background setting." }, { "code": null, "e": 4771, "s": 4732, "text": "<tagname background = \"Image URL\"...>\n" }, { "code": null, "e": 4840, "s": 4771, "text": "The most frequently used image formats are JPEG, GIF and PNG images." }, { "code": null, "e": 4899, "s": 4840, "text": "Here are the examples to set background images of a table." }, { "code": null, "e": 5246, "s": 4899, "text": "<!DOCTYPE html>\n<html>\n\n <head>\n <title>HTML Background Images</title>\n </head>\n\t\n <body>\n <!-- Set table background -->\n <table background = \"/images/html.gif\" width = \"100%\" height = \"100\">\n <tr><td>\n This background is filled up with HTML image.\n </td></tr>\n </table>\n </body>\n \n</html>" }, { "code": null, "e": 5287, "s": 5246, "text": "This will produce the following result −" }, { "code": null, "e": 5461, "s": 5287, "text": "You might have seen many pattern or transparent backgrounds on various websites. This simply can be achieved by using patterned image or transparent image in the background." }, { "code": null, "e": 5621, "s": 5461, "text": "It is suggested that while creating patterns or transparent GIF or PNG images, use the smallest dimensions possible even as small as 1x1 to avoid slow loading." }, { "code": null, "e": 5682, "s": 5621, "text": "Here are the examples to set background pattern of a table −" }, { "code": null, "e": 6374, "s": 5682, "text": "<!DOCTYPE html>\n<html>\n\n <head>\n <title>HTML Background Images</title>\n </head>\n\t\n <body>\n <!-- Set a table background using pattern -->\n <table background = \"/images/pattern1.gif\" width = \"100%\" height = \"100\">\n <tr>\n <td>\n This background is filled up with a pattern image.\n </td>\n </tr>\n </table>\n\n <!-- Another example on table background using pattern -->\n <table background = \"/images/pattern2.gif\" width = \"100%\" height = \"100\">\n <tr>\n <td>\n This background is filled up with a pattern image.\n </td>\n </tr>\n </table>\n </body>\n \n</html>" } ]
Palindromic Primes
01 Nov, 2021 A palindromic prime (sometimes called a palprime) is a prime number that is also a palindromic number. Given a number n, print all palindromic primes smaller than or equal to n. For example, If n is 10, the output should be “2, 3, 5, 7′. And if n is 20, the output should be “2, 3, 5, 7, 11′.Idea is to generate all prime numbers smaller than or equal to given number n and checking every prime number whether it is palindromic or not.Methods used To find if a given number is prime or not- sieve-of-eratosthenes method To check whether the given number is palindromic number or not: Recursive function for checking palindrome Below is the implementation of above algorithm: C++ Java Python3 C# PHP Javascript // C++ Program to print all palindromic primes// smaller than or equal to n.#include<bits/stdc++.h>using namespace std; // A function that returns true only if num// contains one digitint oneDigit(int num){ // comparison operation is faster than // division operation. So using following // instead of "return num / 10 == 0;" return (num >= 0 && num < 10);} // A recursive function to find out whether// num is palindrome or not. Initially, dupNum// contains address of a copy of num.bool isPalUtil(int num, int* dupNum){ // Base case (needed for recursion termination): // This statement/ mainly compares the first // digit with the last digit if (oneDigit(num)) return (num == (*dupNum) % 10); // This is the key line in this method. Note // that all recursive/ calls have a separate // copy of num, but they all share same copy // of *dupNum. We divide num while moving up // the recursion tree if (!isPalUtil(num/10, dupNum)) return false; // The following statements are executed when // we move up the recursion call tree *dupNum /= 10; // At this point, if num%10 contains i'th // digit from beginning, then (*dupNum)%10 // contains i'th digit from end return (num % 10 == (*dupNum) % 10);} // The main function that uses recursive function// isPalUtil() to find out whether num is palindrome// or notint isPal(int num){ // If num is negative, make it positive if (num < 0) num = -num; // Create a separate copy of num, so that // modifications made to address dupNum don't // change the input number. int *dupNum = new int(num); // *dupNum = num return isPalUtil(num, dupNum);} // Function to generate all primes and checking// whether number is palindromic or notvoid printPalPrimesLessThanN(int n){ // Create a boolean array "prime[0..n]" and // initialize all entries it as true. A value // in prime[i] will finally be false if i is // Not a prime, else true. bool prime[n+1]; memset(prime, true, sizeof(prime)); for (int p=2; p*p<=n; p++) { // If prime[p] is not changed, then it is // a prime if (prime[p] == true) { // Update all multiples of p for (int i=p*2; i<=n; i += p) prime[i] = false; } } // Print all palindromic prime numbers for (int p=2; p<=n; p++) // checking whether the given number is // prime palindromic or not if (prime[p] && isPal(p)) cout << p << " ";} // Driver Programint main(){ int n = 100; printf("Palindromic primes smaller than or " "equal to %d are :\n", n); printPalPrimesLessThanN(n);} // Java Program to print all palindromic primes// smaller than or equal to n.import java.util.*; class GFG { // A function that returns true only if num // contains one digit static boolean oneDigit(int num) { // comparison operation is faster than // division operation. So using following // instead of "return num / 10 == 0;" return (num >= 0 && num < 10); } // A recursive function to find out whether // num is palindrome or not. Initially, dupNum // contains address of a copy of num. static boolean isPalUtil(int num, int dupNum) { // Base case (needed for recursion termination): // This statement/ mainly compares the first // digit with the last digit if (oneDigit(num)) return (num == (dupNum) % 10); // This is the key line in this method. Note // that all recursive/ calls have a separate // copy of num, but they all share same copy // of dupNum. We divide num while moving up // the recursion tree if (!isPalUtil(num/10, dupNum)) return false; // The following statements are executed when // we move up the recursion call tree dupNum /= 10; // At this point, if num%10 contains ith // digit from beginning, then (dupNum)%10 // contains ith digit from end return (num % 10 == (dupNum) % 10); } // The main function that uses recursive function // isPalUtil() to find out whether num is palindrome // or not static boolean isPal(int num) { // If num is negative, make it positive if (num < 0) num = -num; // Create a separate copy of num, so that // modifications made to address dupNum don't // change the input number. int dupNum = num; // dupNum = num return isPalUtil(num, dupNum); } // Function to generate all primes and checking // whether number is palindromic or not static void printPalPrimesLessThanN(int n) { // Create a boolean array "prime[0..n]" and // initialize all entries it as true. A value // in prime[i] will finally be false if i is // Not a prime, else true. boolean prime[] = new boolean[n+1]; Arrays.fill(prime, true); for (int p = 2; p*p <= n; p++) { // If prime[p] is not changed, then it is // a prime if (prime[p]) { // Update all multiples of p for (int i = p*2; i <= n; i += p){ prime[i] = false;} } } // Print all palindromic prime numbers for (int p = 2; p <= n; p++){ // checking whether the given number is // prime palindromic or not if (prime[p] && isPal(p)){ System.out.print(p + " "); } } } // Driver function public static void main(String[] args) { int n = 100; System.out.printf("Palindromic primes smaller than or " +"equal to %d are :\n", n); printPalPrimesLessThanN(n); } } // This code is contributed by Arnav Kr. Mandal. # Python3 Program to print all palindromic# primes smaller than or equal to n. # A function that returns true only if# num contains one digitdef oneDigit(num): # comparison operation is faster than # division operation. So using following # instead of "return num / 10 == 0;" return (num >= 0 and num < 10); # A recursive function to find out whether# num is palindrome or not. Initially, dupNum# contains address of a copy of num.def isPalUtil(num, dupNum): # Base case (needed for recursion termination): # This statement/ mainly compares the first # digit with the last digit if (oneDigit(num)): return (num == (dupNum) % 10); # This is the key line in this method. Note # that all recursive/ calls have a separate # copy of num, but they all share same copy # of dupNum. We divide num while moving up # the recursion tree if (not isPalUtil(int(num / 10), dupNum)): return False; # The following statements are executed # when we move up the recursion call tree dupNum =int(dupNum/10); # At this point, if num%10 contains ith # digit from beginning, then (dupNum)%10 # contains ith digit from end return (num % 10 == (dupNum) % 10); # The main function that uses recursive# function isPalUtil() to find out whether# num is palindrome or notdef isPal(num): # If num is negative, make it positive if (num < 0): num = -num; # Create a separate copy of num, so that # modifications made to address dupNum # don't change the input number. dupNum = num; # dupNum = num return isPalUtil(num, dupNum); # Function to generate all primes and checking# whether number is palindromic or notdef printPalPrimesLessThanN(n): # Create a boolean array "prime[0..n]" and # initialize all entries it as true. A value # in prime[i] will finally be false if i is # Not a prime, else true. prime = [True] * (n + 1); p = 2; while (p * p <= n): # If prime[p] is not changed, # then it is a prime if (prime[p]): # Update all multiples of p for i in range(p * 2, n + 1, p): prime[i] = False; p += 1; # Print all palindromic prime numbers for p in range(2, n + 1): # checking whether the given number # is prime palindromic or not if (prime[p] and isPal(p)): print(p, end = " "); # Driver Coden = 100;print("Palindromic primes smaller", "than or equal to", n, "are :");printPalPrimesLessThanN(n); # This code is contributed by chandan_jnu // C# Program to print all palindromic// primes smaller than or equal to n.using System; class GFG { // A function that returns true only // if num contains one digit static bool oneDigit(int num) { // comparison operation is faster than // division operation. So using following // instead of "return num / 10 == 0;" return (num >= 0 && num < 10); } // A recursive function to find out whether // num is palindrome or not. Initially, dupNum // contains address of a copy of num. static bool isPalUtil(int num, int dupNum) { // Base case (needed for recursion termination): // This statement/ mainly compares the first // digit with the last digit if (oneDigit(num)) return (num == (dupNum) % 10); // This is the key line in this method. Note // that all recursive/ calls have a separate // copy of num, but they all share same copy // of dupNum. We divide num while moving up // the recursion tree if (!isPalUtil(num/10, dupNum)) return false; // The following statements are executed when // we move up the recursion call tree dupNum /= 10; // At this point, if num%10 contains ith // digit from beginning, then (dupNum)%10 // contains ith digit from end return (num % 10 == (dupNum) % 10); } // The main function that uses recursive // function isPalUtil() to find out // whether num is palindrome or not static bool isPal(int num) { // If num is negative, make it positive if (num < 0) num = -num; // Create a separate copy of num, so that // modifications made to address dupNum don't // change the input number. int dupNum = num; // dupNum = num return isPalUtil(num, dupNum); } // Function to generate all primes and checking // whether number is palindromic or not static void printPalPrimesLessThanN(int n) { // Create a boolean array "prime[0..n]" and // initialize all entries it as true. A value // in prime[i] will finally be false if i is // Not a prime, else true. bool []prime = new bool[n+1]; for (int i=0;i<n+1;i++) prime[i]=true; for (int p = 2; p*p <= n; p++) { // If prime[p] is not changed, // then it is a prime if (prime[p]) { // Update all multiples of p for (int i = p*2; i <= n; i += p){ prime[i] = false;} } } // Print all palindromic prime numbers for (int p = 2; p <= n; p++){ // checking whether the given number is // prime palindromic or not if (prime[p] && isPal(p)){ Console.Write(p + " "); } } } // Driver function public static void Main() { int n = 100; Console.Write("Palindromic primes smaller than or " + "equal to are :\n", n); printPalPrimesLessThanN(n); }} // This code is contributed by nitin mittal. <?php// PHP Program to print all palindromic// primes smaller than or equal to n. // A function that returns true only// if num contains one digitfunction oneDigit($num){ // comparison operation is faster than // division operation. So using following // instead of "return num / 10 == 0;" return ($num >= 0 && $num < 10);} // A recursive function to find out whether// num is palindrome or not. Initially,// dupNum contains address of a copy of num.function isPalUtil($num, $dupNum){ // Base case (needed for recursion termination): // This statement/ mainly compares the first // digit with the last digit if (oneDigit($num)) return ($num == ($dupNum) % 10); // This is the key line in this method. Note // that all recursive/ calls have a separate // copy of num, but they all share same copy // of dupNum. We divide num while moving up // the recursion tree if (!isPalUtil((int)($num/10), $dupNum)) return false; // The following statements are executed // when we move up the recursion call tree $dupNum = (int)($dupNum / 10); // At this point, if num%10 contains ith // digit from beginning, then (dupNum)%10 // contains ith digit from end return ($num % 10 == ($dupNum) % 10);} // The main function that uses recursive// function isPalUtil() to find out whether// num is palindrome or notfunction isPal($num){ // If num is negative, make it positive if ($num < 0) $num = -$num; // Create a separate copy of num, so that // modifications made to address dupNum // don't change the input number. $dupNum = $num; // dupNum = num return isPalUtil($num, $dupNum);} // Function to generate all primes and checking// whether number is palindromic or notfunction printPalPrimesLessThanN($n){ // Create a boolean array "prime[0..n]" and // initialize all entries it as true. A value // in prime[i] will finally be false if i is // Not a prime, else true. $prime = array_fill(0, $n + 1, true); for ($p = 2; $p * $p <= $n; $p++) { // If prime[p] is not changed, then // it is a prime if ($prime[$p]) { // Update all multiples of p for ($i = $p * 2; $i <= $n; $i += $p) { $prime[$i] = false; } } } // Print all palindromic prime numbers for ($p = 2; $p <= $n; $p++) { // checking whether the given number // is prime palindromic or not if ($prime[$p] && isPal($p)) { print($p . " "); } }} // Driver Code$n = 100;print("Palindromic primes smaller " . "than or equal to ".$n." are :\n");printPalPrimesLessThanN($n); // This code is contributed by mits?> <script> // javascript Program to print all palindromic primes// smaller than or equal to n. // A function that returns true only if num // contains one digit function oneDigit(num) { // comparison operation is faster than // division operation. So using following // instead of "return num / 10 == 0;" return (num >= 0 && num < 10); } // A recursive function to find out whether // num is palindrome or not. Initially, dupNum // contains address of a copy of num. function isPalUtil(num , dupNum) { // Base case (needed for recursion termination): // This statement/ mainly compares the first // digit with the last digit if (oneDigit(num)) return (num == (dupNum) % 10); // This is the key line in this method. Note // that all recursive/ calls have a separate // copy of num, but they all share same copy // of dupNum. We divide num while moving up // the recursion tree if (!isPalUtil(parseInt(num/10), dupNum)) return false; // The following statements are executed when // we move up the recursion call tree dupNum = parseInt(dupNum/10); // At this point, if num%10 contains ith // digit from beginning, then (dupNum)%10 // contains ith digit from end return (num % 10 == (dupNum) % 10); } // The main function that uses recursive function // isPalUtil() to find out whether num is palindrome // or not function isPal(num) { // If num is negative, make it positive if (num < 0) num = -num; // Create a separate copy of num, so that // modifications made to address dupNum don't // change the input number. var dupNum = num; // dupNum = num return isPalUtil(num, dupNum); } // Function to generate all primes and checking // whether number is palindromic or not function printPalPrimesLessThanN(n) { // Create a boolean array "prime[0..n]" and // initialize all entries it as true. A value // in prime[i] will finally be false if i is // Not a prime, else true. var prime = Array.from({length: n+1}, (_, i) => true); for (p = 2; p*p <= n; p++) { // If prime[p] is not changed, then it is // a prime if (prime[p]) { // Update all multiples of p for (i = p*2; i <= n; i += p){ prime[i] = false;} } } // Print all palindromic prime numbers for (p = 2; p <= n; p++){ // checking whether the given number is // prime palindromic or not if (prime[p] && isPal(p)){ document.write(p + " "); } } } // Driver function var n = 100; document.write('Palindromic primes smaller than or equal to '+n+' are :<br>'); printPalPrimesLessThanN(n); // This code is contributed by Princi Singh</script> Output: Palindromic primes smaller than or equal to 100 are : 2 3 5 7 11 This article is contributed by Rahul Agrawal .If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. nitin mittal Chandan_Kumar Mithun Kumar princi singh saurabh1990aror anikakapoor Kirti_Mangal palindrome Prime Number sieve Mathematical Mathematical Prime Number sieve palindrome Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Operators in C / C++ Merge two sorted arrays The Knight's tour problem | Backtracking-1 Program for Binary To Decimal Conversion Modulo Operator (%) in C/C++ with Examples Algorithm to solve Rubik's Cube Program to calculate value of nCr Hash Functions and list/types of Hash functions Ugly Numbers Print all possible combinations of r elements in a given array of size n
[ { "code": null, "e": 52, "s": 24, "text": "\n01 Nov, 2021" }, { "code": null, "e": 500, "s": 52, "text": "A palindromic prime (sometimes called a palprime) is a prime number that is also a palindromic number. Given a number n, print all palindromic primes smaller than or equal to n. For example, If n is 10, the output should be “2, 3, 5, 7′. And if n is 20, the output should be “2, 3, 5, 7, 11′.Idea is to generate all prime numbers smaller than or equal to given number n and checking every prime number whether it is palindromic or not.Methods used" }, { "code": null, "e": 572, "s": 500, "text": "To find if a given number is prime or not- sieve-of-eratosthenes method" }, { "code": null, "e": 679, "s": 572, "text": "To check whether the given number is palindromic number or not: Recursive function for checking palindrome" }, { "code": null, "e": 729, "s": 679, "text": "Below is the implementation of above algorithm: " }, { "code": null, "e": 733, "s": 729, "text": "C++" }, { "code": null, "e": 738, "s": 733, "text": "Java" }, { "code": null, "e": 746, "s": 738, "text": "Python3" }, { "code": null, "e": 749, "s": 746, "text": "C#" }, { "code": null, "e": 753, "s": 749, "text": "PHP" }, { "code": null, "e": 764, "s": 753, "text": "Javascript" }, { "code": "// C++ Program to print all palindromic primes// smaller than or equal to n.#include<bits/stdc++.h>using namespace std; // A function that returns true only if num// contains one digitint oneDigit(int num){ // comparison operation is faster than // division operation. So using following // instead of \"return num / 10 == 0;\" return (num >= 0 && num < 10);} // A recursive function to find out whether// num is palindrome or not. Initially, dupNum// contains address of a copy of num.bool isPalUtil(int num, int* dupNum){ // Base case (needed for recursion termination): // This statement/ mainly compares the first // digit with the last digit if (oneDigit(num)) return (num == (*dupNum) % 10); // This is the key line in this method. Note // that all recursive/ calls have a separate // copy of num, but they all share same copy // of *dupNum. We divide num while moving up // the recursion tree if (!isPalUtil(num/10, dupNum)) return false; // The following statements are executed when // we move up the recursion call tree *dupNum /= 10; // At this point, if num%10 contains i'th // digit from beginning, then (*dupNum)%10 // contains i'th digit from end return (num % 10 == (*dupNum) % 10);} // The main function that uses recursive function// isPalUtil() to find out whether num is palindrome// or notint isPal(int num){ // If num is negative, make it positive if (num < 0) num = -num; // Create a separate copy of num, so that // modifications made to address dupNum don't // change the input number. int *dupNum = new int(num); // *dupNum = num return isPalUtil(num, dupNum);} // Function to generate all primes and checking// whether number is palindromic or notvoid printPalPrimesLessThanN(int n){ // Create a boolean array \"prime[0..n]\" and // initialize all entries it as true. A value // in prime[i] will finally be false if i is // Not a prime, else true. bool prime[n+1]; memset(prime, true, sizeof(prime)); for (int p=2; p*p<=n; p++) { // If prime[p] is not changed, then it is // a prime if (prime[p] == true) { // Update all multiples of p for (int i=p*2; i<=n; i += p) prime[i] = false; } } // Print all palindromic prime numbers for (int p=2; p<=n; p++) // checking whether the given number is // prime palindromic or not if (prime[p] && isPal(p)) cout << p << \" \";} // Driver Programint main(){ int n = 100; printf(\"Palindromic primes smaller than or \" \"equal to %d are :\\n\", n); printPalPrimesLessThanN(n);}", "e": 3458, "s": 764, "text": null }, { "code": "// Java Program to print all palindromic primes// smaller than or equal to n.import java.util.*; class GFG { // A function that returns true only if num // contains one digit static boolean oneDigit(int num) { // comparison operation is faster than // division operation. So using following // instead of \"return num / 10 == 0;\" return (num >= 0 && num < 10); } // A recursive function to find out whether // num is palindrome or not. Initially, dupNum // contains address of a copy of num. static boolean isPalUtil(int num, int dupNum) { // Base case (needed for recursion termination): // This statement/ mainly compares the first // digit with the last digit if (oneDigit(num)) return (num == (dupNum) % 10); // This is the key line in this method. Note // that all recursive/ calls have a separate // copy of num, but they all share same copy // of dupNum. We divide num while moving up // the recursion tree if (!isPalUtil(num/10, dupNum)) return false; // The following statements are executed when // we move up the recursion call tree dupNum /= 10; // At this point, if num%10 contains ith // digit from beginning, then (dupNum)%10 // contains ith digit from end return (num % 10 == (dupNum) % 10); } // The main function that uses recursive function // isPalUtil() to find out whether num is palindrome // or not static boolean isPal(int num) { // If num is negative, make it positive if (num < 0) num = -num; // Create a separate copy of num, so that // modifications made to address dupNum don't // change the input number. int dupNum = num; // dupNum = num return isPalUtil(num, dupNum); } // Function to generate all primes and checking // whether number is palindromic or not static void printPalPrimesLessThanN(int n) { // Create a boolean array \"prime[0..n]\" and // initialize all entries it as true. A value // in prime[i] will finally be false if i is // Not a prime, else true. boolean prime[] = new boolean[n+1]; Arrays.fill(prime, true); for (int p = 2; p*p <= n; p++) { // If prime[p] is not changed, then it is // a prime if (prime[p]) { // Update all multiples of p for (int i = p*2; i <= n; i += p){ prime[i] = false;} } } // Print all palindromic prime numbers for (int p = 2; p <= n; p++){ // checking whether the given number is // prime palindromic or not if (prime[p] && isPal(p)){ System.out.print(p + \" \"); } } } // Driver function public static void main(String[] args) { int n = 100; System.out.printf(\"Palindromic primes smaller than or \" +\"equal to %d are :\\n\", n); printPalPrimesLessThanN(n); } } // This code is contributed by Arnav Kr. Mandal.", "e": 6742, "s": 3458, "text": null }, { "code": "# Python3 Program to print all palindromic# primes smaller than or equal to n. # A function that returns true only if# num contains one digitdef oneDigit(num): # comparison operation is faster than # division operation. So using following # instead of \"return num / 10 == 0;\" return (num >= 0 and num < 10); # A recursive function to find out whether# num is palindrome or not. Initially, dupNum# contains address of a copy of num.def isPalUtil(num, dupNum): # Base case (needed for recursion termination): # This statement/ mainly compares the first # digit with the last digit if (oneDigit(num)): return (num == (dupNum) % 10); # This is the key line in this method. Note # that all recursive/ calls have a separate # copy of num, but they all share same copy # of dupNum. We divide num while moving up # the recursion tree if (not isPalUtil(int(num / 10), dupNum)): return False; # The following statements are executed # when we move up the recursion call tree dupNum =int(dupNum/10); # At this point, if num%10 contains ith # digit from beginning, then (dupNum)%10 # contains ith digit from end return (num % 10 == (dupNum) % 10); # The main function that uses recursive# function isPalUtil() to find out whether# num is palindrome or notdef isPal(num): # If num is negative, make it positive if (num < 0): num = -num; # Create a separate copy of num, so that # modifications made to address dupNum # don't change the input number. dupNum = num; # dupNum = num return isPalUtil(num, dupNum); # Function to generate all primes and checking# whether number is palindromic or notdef printPalPrimesLessThanN(n): # Create a boolean array \"prime[0..n]\" and # initialize all entries it as true. A value # in prime[i] will finally be false if i is # Not a prime, else true. prime = [True] * (n + 1); p = 2; while (p * p <= n): # If prime[p] is not changed, # then it is a prime if (prime[p]): # Update all multiples of p for i in range(p * 2, n + 1, p): prime[i] = False; p += 1; # Print all palindromic prime numbers for p in range(2, n + 1): # checking whether the given number # is prime palindromic or not if (prime[p] and isPal(p)): print(p, end = \" \"); # Driver Coden = 100;print(\"Palindromic primes smaller\", \"than or equal to\", n, \"are :\");printPalPrimesLessThanN(n); # This code is contributed by chandan_jnu", "e": 9396, "s": 6742, "text": null }, { "code": "// C# Program to print all palindromic// primes smaller than or equal to n.using System; class GFG { // A function that returns true only // if num contains one digit static bool oneDigit(int num) { // comparison operation is faster than // division operation. So using following // instead of \"return num / 10 == 0;\" return (num >= 0 && num < 10); } // A recursive function to find out whether // num is palindrome or not. Initially, dupNum // contains address of a copy of num. static bool isPalUtil(int num, int dupNum) { // Base case (needed for recursion termination): // This statement/ mainly compares the first // digit with the last digit if (oneDigit(num)) return (num == (dupNum) % 10); // This is the key line in this method. Note // that all recursive/ calls have a separate // copy of num, but they all share same copy // of dupNum. We divide num while moving up // the recursion tree if (!isPalUtil(num/10, dupNum)) return false; // The following statements are executed when // we move up the recursion call tree dupNum /= 10; // At this point, if num%10 contains ith // digit from beginning, then (dupNum)%10 // contains ith digit from end return (num % 10 == (dupNum) % 10); } // The main function that uses recursive // function isPalUtil() to find out // whether num is palindrome or not static bool isPal(int num) { // If num is negative, make it positive if (num < 0) num = -num; // Create a separate copy of num, so that // modifications made to address dupNum don't // change the input number. int dupNum = num; // dupNum = num return isPalUtil(num, dupNum); } // Function to generate all primes and checking // whether number is palindromic or not static void printPalPrimesLessThanN(int n) { // Create a boolean array \"prime[0..n]\" and // initialize all entries it as true. A value // in prime[i] will finally be false if i is // Not a prime, else true. bool []prime = new bool[n+1]; for (int i=0;i<n+1;i++) prime[i]=true; for (int p = 2; p*p <= n; p++) { // If prime[p] is not changed, // then it is a prime if (prime[p]) { // Update all multiples of p for (int i = p*2; i <= n; i += p){ prime[i] = false;} } } // Print all palindromic prime numbers for (int p = 2; p <= n; p++){ // checking whether the given number is // prime palindromic or not if (prime[p] && isPal(p)){ Console.Write(p + \" \"); } } } // Driver function public static void Main() { int n = 100; Console.Write(\"Palindromic primes smaller than or \" + \"equal to are :\\n\", n); printPalPrimesLessThanN(n); }} // This code is contributed by nitin mittal.", "e": 12603, "s": 9396, "text": null }, { "code": "<?php// PHP Program to print all palindromic// primes smaller than or equal to n. // A function that returns true only// if num contains one digitfunction oneDigit($num){ // comparison operation is faster than // division operation. So using following // instead of \"return num / 10 == 0;\" return ($num >= 0 && $num < 10);} // A recursive function to find out whether// num is palindrome or not. Initially,// dupNum contains address of a copy of num.function isPalUtil($num, $dupNum){ // Base case (needed for recursion termination): // This statement/ mainly compares the first // digit with the last digit if (oneDigit($num)) return ($num == ($dupNum) % 10); // This is the key line in this method. Note // that all recursive/ calls have a separate // copy of num, but they all share same copy // of dupNum. We divide num while moving up // the recursion tree if (!isPalUtil((int)($num/10), $dupNum)) return false; // The following statements are executed // when we move up the recursion call tree $dupNum = (int)($dupNum / 10); // At this point, if num%10 contains ith // digit from beginning, then (dupNum)%10 // contains ith digit from end return ($num % 10 == ($dupNum) % 10);} // The main function that uses recursive// function isPalUtil() to find out whether// num is palindrome or notfunction isPal($num){ // If num is negative, make it positive if ($num < 0) $num = -$num; // Create a separate copy of num, so that // modifications made to address dupNum // don't change the input number. $dupNum = $num; // dupNum = num return isPalUtil($num, $dupNum);} // Function to generate all primes and checking// whether number is palindromic or notfunction printPalPrimesLessThanN($n){ // Create a boolean array \"prime[0..n]\" and // initialize all entries it as true. A value // in prime[i] will finally be false if i is // Not a prime, else true. $prime = array_fill(0, $n + 1, true); for ($p = 2; $p * $p <= $n; $p++) { // If prime[p] is not changed, then // it is a prime if ($prime[$p]) { // Update all multiples of p for ($i = $p * 2; $i <= $n; $i += $p) { $prime[$i] = false; } } } // Print all palindromic prime numbers for ($p = 2; $p <= $n; $p++) { // checking whether the given number // is prime palindromic or not if ($prime[$p] && isPal($p)) { print($p . \" \"); } }} // Driver Code$n = 100;print(\"Palindromic primes smaller \" . \"than or equal to \".$n.\" are :\\n\");printPalPrimesLessThanN($n); // This code is contributed by mits?>", "e": 15326, "s": 12603, "text": null }, { "code": "<script> // javascript Program to print all palindromic primes// smaller than or equal to n. // A function that returns true only if num // contains one digit function oneDigit(num) { // comparison operation is faster than // division operation. So using following // instead of \"return num / 10 == 0;\" return (num >= 0 && num < 10); } // A recursive function to find out whether // num is palindrome or not. Initially, dupNum // contains address of a copy of num. function isPalUtil(num , dupNum) { // Base case (needed for recursion termination): // This statement/ mainly compares the first // digit with the last digit if (oneDigit(num)) return (num == (dupNum) % 10); // This is the key line in this method. Note // that all recursive/ calls have a separate // copy of num, but they all share same copy // of dupNum. We divide num while moving up // the recursion tree if (!isPalUtil(parseInt(num/10), dupNum)) return false; // The following statements are executed when // we move up the recursion call tree dupNum = parseInt(dupNum/10); // At this point, if num%10 contains ith // digit from beginning, then (dupNum)%10 // contains ith digit from end return (num % 10 == (dupNum) % 10); } // The main function that uses recursive function // isPalUtil() to find out whether num is palindrome // or not function isPal(num) { // If num is negative, make it positive if (num < 0) num = -num; // Create a separate copy of num, so that // modifications made to address dupNum don't // change the input number. var dupNum = num; // dupNum = num return isPalUtil(num, dupNum); } // Function to generate all primes and checking // whether number is palindromic or not function printPalPrimesLessThanN(n) { // Create a boolean array \"prime[0..n]\" and // initialize all entries it as true. A value // in prime[i] will finally be false if i is // Not a prime, else true. var prime = Array.from({length: n+1}, (_, i) => true); for (p = 2; p*p <= n; p++) { // If prime[p] is not changed, then it is // a prime if (prime[p]) { // Update all multiples of p for (i = p*2; i <= n; i += p){ prime[i] = false;} } } // Print all palindromic prime numbers for (p = 2; p <= n; p++){ // checking whether the given number is // prime palindromic or not if (prime[p] && isPal(p)){ document.write(p + \" \"); } } } // Driver function var n = 100; document.write('Palindromic primes smaller than or equal to '+n+' are :<br>'); printPalPrimesLessThanN(n); // This code is contributed by Princi Singh</script>", "e": 18436, "s": 15326, "text": null }, { "code": null, "e": 18446, "s": 18436, "text": "Output: " }, { "code": null, "e": 18512, "s": 18446, "text": "Palindromic primes smaller than or equal to 100 are :\n2 3 5 7 11 " }, { "code": null, "e": 18934, "s": 18512, "text": "This article is contributed by Rahul Agrawal .If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 18947, "s": 18934, "text": "nitin mittal" }, { "code": null, "e": 18961, "s": 18947, "text": "Chandan_Kumar" }, { "code": null, "e": 18974, "s": 18961, "text": "Mithun Kumar" }, { "code": null, "e": 18987, "s": 18974, "text": "princi singh" }, { "code": null, "e": 19003, "s": 18987, "text": "saurabh1990aror" }, { "code": null, "e": 19015, "s": 19003, "text": "anikakapoor" }, { "code": null, "e": 19028, "s": 19015, "text": "Kirti_Mangal" }, { "code": null, "e": 19039, "s": 19028, "text": "palindrome" }, { "code": null, "e": 19052, "s": 19039, "text": "Prime Number" }, { "code": null, "e": 19058, "s": 19052, "text": "sieve" }, { "code": null, "e": 19071, "s": 19058, "text": "Mathematical" }, { "code": null, "e": 19084, "s": 19071, "text": "Mathematical" }, { "code": null, "e": 19097, "s": 19084, "text": "Prime Number" }, { "code": null, "e": 19103, "s": 19097, "text": "sieve" }, { "code": null, "e": 19114, "s": 19103, "text": "palindrome" }, { "code": null, "e": 19212, "s": 19114, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 19233, "s": 19212, "text": "Operators in C / C++" }, { "code": null, "e": 19257, "s": 19233, "text": "Merge two sorted arrays" }, { "code": null, "e": 19300, "s": 19257, "text": "The Knight's tour problem | Backtracking-1" }, { "code": null, "e": 19341, "s": 19300, "text": "Program for Binary To Decimal Conversion" }, { "code": null, "e": 19384, "s": 19341, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 19416, "s": 19384, "text": "Algorithm to solve Rubik's Cube" }, { "code": null, "e": 19450, "s": 19416, "text": "Program to calculate value of nCr" }, { "code": null, "e": 19498, "s": 19450, "text": "Hash Functions and list/types of Hash functions" }, { "code": null, "e": 19511, "s": 19498, "text": "Ugly Numbers" } ]
Redis - Sorted Set Zadd Command
Redis ZADD command adds all the specified members with the specified scores to the sorted set stored at the key. It is possible to specify multiple score/member pairs. If a specified member is already a member of the sorted set, the score is updated and the element is reinserted at the right position to ensure correct ordering. If the key does not exist, a new sorted set with the specified members as sole members is created, like if the sorted set was empty. If the key exists but does not hold a sorted set, an error is returned. Integer reply. The number of elements added to the sorted sets, not including elements already existing for which the score was updated. Following is the basic syntax of Redis ZADD command. redis 127.0.0.1:6379> ZADD KEY_NAME SCORE1 VALUE1.. SCOREN VALUEN redis 127.0.0.1:6379> ZADD myset 1 "hello" (integer) 1 redis 127.0.0.1:6379> ZADD myset 1 "foo" (integer) 1 redis 127.0.0.1:6379> ZADD myset 2 "world" 3 "bar" (integer) 2 redis 127.0.0.1:6379> ZRANGE myzset 0 -1 WITHSCORES
[ { "code": null, "e": 2714, "s": 2179, "text": "Redis ZADD command adds all the specified members with the specified scores to the sorted set stored at the key. It is possible to specify multiple score/member pairs. If a specified member is already a member of the sorted set, the score is updated and the element is reinserted at the right position to ensure correct ordering. If the key does not exist, a new sorted set with the specified members as sole members is created, like if the sorted set was empty. If the key exists but does not hold a sorted set, an error is returned." }, { "code": null, "e": 2851, "s": 2714, "text": "Integer reply. The number of elements added to the sorted sets, not including elements already existing for which the score was updated." }, { "code": null, "e": 2904, "s": 2851, "text": "Following is the basic syntax of Redis ZADD command." }, { "code": null, "e": 2971, "s": 2904, "text": "redis 127.0.0.1:6379> ZADD KEY_NAME SCORE1 VALUE1.. SCOREN VALUEN\n" } ]
Integer floatValue() Method in Java
03 May, 2022 floatValue() method of Integer class present inside java.lang package is used to convert the value of the given Integer to a float type after a widening primitive conversion which in general is mostly applicable when we want to truncate or rounding-off the integer value. The package view is as follows: --> java.lang Package --> Integer Class --> floatValue() Method Syntax: public float floatValue() Return Type: A numeric value represented by this object after converting it to type float. Note: This method is workable when it is supported by java version 1.2 or onwards, so make sure to update java version if running on older(introductory) java versions. Example 1: java // Java Program to Demonstrate floatValue() Method// of Integer Class // Importing required classesimport java.lang.Integer; // Classclass GFG { // Main driver method public static void main(String args[]) { // Creating a custom integer by // creating object of Integer class Integer a = new Integer(28); // Converting Integer number to float value // using floatValue() method float b = a.floatValue(); // Printing the float value System.out.println(b); }} Output: Example 2: Java // Java Program to Demonstrate Working of floatValue()// Method of Integer Class // Importing required classimport java.lang.Integer; // Classclass GFG { // Main driver method public static void main(String args[]) { // Creating a custom integer value by // declaring object of Integer Class Integer a = new Integer(20); // Convert Integer number to float value // using floatValue() method float b = a.floatValue(); // Printing the float value on console System.out.println(b); }} Output: solankimayank Java-Functions Java-Integer Java-lang package Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n03 May, 2022" }, { "code": null, "e": 332, "s": 28, "text": "floatValue() method of Integer class present inside java.lang package is used to convert the value of the given Integer to a float type after a widening primitive conversion which in general is mostly applicable when we want to truncate or rounding-off the integer value. The package view is as follows:" }, { "code": null, "e": 413, "s": 332, "text": "--> java.lang Package\n --> Integer Class\n --> floatValue() Method " }, { "code": null, "e": 421, "s": 413, "text": "Syntax:" }, { "code": null, "e": 447, "s": 421, "text": "public float floatValue()" }, { "code": null, "e": 538, "s": 447, "text": "Return Type: A numeric value represented by this object after converting it to type float." }, { "code": null, "e": 706, "s": 538, "text": "Note: This method is workable when it is supported by java version 1.2 or onwards, so make sure to update java version if running on older(introductory) java versions." }, { "code": null, "e": 717, "s": 706, "text": "Example 1:" }, { "code": null, "e": 722, "s": 717, "text": "java" }, { "code": "// Java Program to Demonstrate floatValue() Method// of Integer Class // Importing required classesimport java.lang.Integer; // Classclass GFG { // Main driver method public static void main(String args[]) { // Creating a custom integer by // creating object of Integer class Integer a = new Integer(28); // Converting Integer number to float value // using floatValue() method float b = a.floatValue(); // Printing the float value System.out.println(b); }}", "e": 1252, "s": 722, "text": null }, { "code": null, "e": 1260, "s": 1252, "text": "Output:" }, { "code": null, "e": 1273, "s": 1262, "text": "Example 2:" }, { "code": null, "e": 1278, "s": 1273, "text": "Java" }, { "code": "// Java Program to Demonstrate Working of floatValue()// Method of Integer Class // Importing required classimport java.lang.Integer; // Classclass GFG { // Main driver method public static void main(String args[]) { // Creating a custom integer value by // declaring object of Integer Class Integer a = new Integer(20); // Convert Integer number to float value // using floatValue() method float b = a.floatValue(); // Printing the float value on console System.out.println(b); }}", "e": 1831, "s": 1278, "text": null }, { "code": null, "e": 1839, "s": 1831, "text": "Output:" }, { "code": null, "e": 1855, "s": 1841, "text": "solankimayank" }, { "code": null, "e": 1870, "s": 1855, "text": "Java-Functions" }, { "code": null, "e": 1883, "s": 1870, "text": "Java-Integer" }, { "code": null, "e": 1901, "s": 1883, "text": "Java-lang package" }, { "code": null, "e": 1906, "s": 1901, "text": "Java" }, { "code": null, "e": 1911, "s": 1906, "text": "Java" } ]
Neo4j - Set Clause
Using Set clause, you can add new properties to an existing Node or Relationship, and also add or update existing Properties values. In this chapter, we are going to discuss how to − Set a property Remove a property Set multiple properties Set a label on a node Set multiple labels on a node Using the SET clause, you can create a new property in a node. Following is the syntax for setting a property. MATCH (node:label{properties . . . . . . . . . . . . . . }) SET node.property = value RETURN node Before proceeding with the example, first create a node named Dhawan as shown below. CREATE (Dhawan:player{name: "shikar Dhawan", YOB: 1985, POB: "Delhi"}) Following is a sample Cypher Query to create a property named “highestscore” with value “187”. MATCH (Dhawan:player{name: "shikar Dhawan", YOB: 1985, POB: "Delhi"}) SET Dhawan.highestscore = 187 RETURN Dhawan To execute the above query, carry out the following steps − Step 1 − Open the Neo4j desktop App and start the Neo4j Server. Open the built-in browser app of Neo4j using the URL http://localhost:7474/ as shown in the following screnshot. Step 2 − Copy and paste the desired query in the dollar prompt and press the play button (to execute the query) highlighted in the following screenshot. On executing, you will get the following result. Here you can observe that a property with a key-value pair highestscore/187 is created in the node named “Dhawan”. You can remove an existing property by passing NULL as value to it. Following is the syntax of removing a property from a node using the SET clause. MATCH (node:label {properties}) SET node.property = NULL RETURN node Before proceeding with the example, first create a node “jadeja” as shown below. Create (Jadeja:player {name: "Ravindra Jadeja", YOB: 1988, POB: "NavagamGhed"}) Following is a sample Cypher Query which removes the property named POB from this node using the SET clause as shown below. MATCH (Jadeja:player {name: "Ravindra Jadeja", YOB: 1988, POB: "NavagamGhed"}) SET Jadeja.POB = NULL RETURN Jadeja To execute the above query, carry out the following steps − Step 1 − Open the Neo4j desktop App and start the Neo4j Server. Open the built-in browser app of Neo4j using the URL http://localhost:7474/ as shown in the following screenshot. Step 2 − Copy and paste the desired query in the dollar prompt and press the play button (to execute the query) highlighted in the following screenshot. On executing, you will get the following result. Here you can observe that the variable named POB was deleted. In the same way, you can create multiple properties in a node using the Set clause. To do so, you need to specify these key value pairs with commas. Following is the syntax to create multiple properties in a node using the SET clause. MATCH (node:label {properties}) SET node.property1 = value, node.property2 = value RETURN node Following is a sample Cypher Query which creates multiple properties in a node using the SET clause in Neo4j. MATCH (Jadeja:player {name: "Ravindra Jadeja", YOB: 1988}) SET Jadeja.POB: "NavagamGhed", Jadeja.HS = "90" RETURN Jadeja To execute the above query, carry out the following steps − Step 1 − Open the Neo4j desktop App and start the Neo4j Server. Open the built-in browser app of Neo4j using the URL http://localhost:7474/ as shown in the following screenshot. Step 2 − Copy and paste the desired query in the dollar prompt and press the play button (to execute the query) highlighted in the following screenshot. On executing, you will get the following result. Here you can observe that properties named POB and HS were created. You can set a label to an existing node using the SET clause. Following is the syntax to set a label to an existing node. MATCH (n {properties . . . . . . . }) SET n :label RETURN n Before proceeding with the example, first create a node “Anderson” as shown below. CREATE (Anderson {name: "James Anderson", YOB: 1982, POB: "Burnely"}) Following is a sample Cypher Query to set a label on a node using the SET clause. This query adds the label “player” to the node Anderson and returns it. MATCH (Anderson {name: "James Anderson", YOB: 1982, POB: "Burnely"}) SET Anderson: player RETURN Anderson To execute the above query, carry out the following steps − Step 1 − Open the Neo4j desktop App and start the Neo4j Server. Open the built-in browser app of Neo4j using the URL http://localhost:7474/ as shown in the following screenshot. Step 2 − Copy and paste the desired query in the dollar prompt and press the play button (to execute the query) highlighted in the following screenshot. On executing, you will get the following result. Here you can observe that the label named “player” is added to the node. You can set multiple labels to an existing node using the SET clause. Here you need to specify the labels by separating them with colons “:”. Following is the syntax to set multiple labels to an existing node using the SET clause. MATCH (n {properties . . . . . . . }) SET n :label1:label2 RETURN n Before proceeding with the example, first create a node named “Ishant” as shown below. CREATE (Ishant {name: "Ishant Sharma", YOB: 1988, POB: "Delhi"}) Following is a sample Cypher Query used to create multiple labels on a node using the SET clause. MATCH (Ishant {name: "Ishant Sharma", YOB: 1988, POB: "Delhi"}) SET Ishant: player:person RETURN Ishant To execute the above query, carry out the following steps − Step 1 − Open the Neo4j desktop App and start the Neo4j Server. Open the built-in browser app of Neo4j using the URL http://localhost:7474/ as shown in the following screenshot. Step 2 − Copy and paste the desired query in the dollar prompt and press the play button (to execute the query) highlighted in the following screenshot. On executing, you will get the following result. Here you can observe that two labels - person and player – are added to the node named Ishant. Print Add Notes Bookmark this page
[ { "code": null, "e": 2472, "s": 2339, "text": "Using Set clause, you can add new properties to an existing Node or Relationship, and also add or update existing Properties values." }, { "code": null, "e": 2522, "s": 2472, "text": "In this chapter, we are going to discuss how to −" }, { "code": null, "e": 2537, "s": 2522, "text": "Set a property" }, { "code": null, "e": 2555, "s": 2537, "text": "Remove a property" }, { "code": null, "e": 2579, "s": 2555, "text": "Set multiple properties" }, { "code": null, "e": 2601, "s": 2579, "text": "Set a label on a node" }, { "code": null, "e": 2631, "s": 2601, "text": "Set multiple labels on a node" }, { "code": null, "e": 2694, "s": 2631, "text": "Using the SET clause, you can create a new property in a node." }, { "code": null, "e": 2742, "s": 2694, "text": "Following is the syntax for setting a property." }, { "code": null, "e": 2843, "s": 2742, "text": "MATCH (node:label{properties . . . . . . . . . . . . . . }) \nSET node.property = value \nRETURN node\n" }, { "code": null, "e": 2928, "s": 2843, "text": "Before proceeding with the example, first create a node named Dhawan as shown below." }, { "code": null, "e": 3000, "s": 2928, "text": "CREATE (Dhawan:player{name: \"shikar Dhawan\", YOB: 1985, POB: \"Delhi\"}) " }, { "code": null, "e": 3095, "s": 3000, "text": "Following is a sample Cypher Query to create a property named “highestscore” with value “187”." }, { "code": null, "e": 3211, "s": 3095, "text": "MATCH (Dhawan:player{name: \"shikar Dhawan\", YOB: 1985, POB: \"Delhi\"}) \nSET Dhawan.highestscore = 187 \nRETURN Dhawan" }, { "code": null, "e": 3271, "s": 3211, "text": "To execute the above query, carry out the following steps −" }, { "code": null, "e": 3448, "s": 3271, "text": "Step 1 − Open the Neo4j desktop App and start the Neo4j Server. Open the built-in browser app of Neo4j using the URL http://localhost:7474/ as shown in the following screnshot." }, { "code": null, "e": 3601, "s": 3448, "text": "Step 2 − Copy and paste the desired query in the dollar prompt and press the play button (to execute the query) highlighted in the following screenshot." }, { "code": null, "e": 3765, "s": 3601, "text": "On executing, you will get the following result. Here you can observe that a property with a key-value pair highestscore/187 is created in the node named “Dhawan”." }, { "code": null, "e": 3833, "s": 3765, "text": "You can remove an existing property by passing NULL as value to it." }, { "code": null, "e": 3914, "s": 3833, "text": "Following is the syntax of removing a property from a node using the SET clause." }, { "code": null, "e": 3987, "s": 3914, "text": "MATCH (node:label {properties}) \nSET node.property = NULL \nRETURN node \n" }, { "code": null, "e": 4068, "s": 3987, "text": "Before proceeding with the example, first create a node “jadeja” as shown below." }, { "code": null, "e": 4148, "s": 4068, "text": "Create (Jadeja:player {name: \"Ravindra Jadeja\", YOB: 1988, POB: \"NavagamGhed\"})" }, { "code": null, "e": 4272, "s": 4148, "text": "Following is a sample Cypher Query which removes the property named POB from this node using the SET clause as shown below." }, { "code": null, "e": 4390, "s": 4272, "text": "MATCH (Jadeja:player {name: \"Ravindra Jadeja\", YOB: 1988, POB: \"NavagamGhed\"}) \nSET Jadeja.POB = NULL \nRETURN Jadeja " }, { "code": null, "e": 4450, "s": 4390, "text": "To execute the above query, carry out the following steps −" }, { "code": null, "e": 4628, "s": 4450, "text": "Step 1 − Open the Neo4j desktop App and start the Neo4j Server. Open the built-in browser app of Neo4j using the URL http://localhost:7474/ as shown in the following screenshot." }, { "code": null, "e": 4781, "s": 4628, "text": "Step 2 − Copy and paste the desired query in the dollar prompt and press the play button (to execute the query) highlighted in the following screenshot." }, { "code": null, "e": 4892, "s": 4781, "text": "On executing, you will get the following result. Here you can observe that the variable named POB was deleted." }, { "code": null, "e": 5041, "s": 4892, "text": "In the same way, you can create multiple properties in a node using the Set clause. To do so, you need to specify these key value pairs with commas." }, { "code": null, "e": 5127, "s": 5041, "text": "Following is the syntax to create multiple properties in a node using the SET clause." }, { "code": null, "e": 5226, "s": 5127, "text": "MATCH (node:label {properties}) \nSET node.property1 = value, node.property2 = value \nRETURN node \n" }, { "code": null, "e": 5336, "s": 5226, "text": "Following is a sample Cypher Query which creates multiple properties in a node using the SET clause in Neo4j." }, { "code": null, "e": 5460, "s": 5336, "text": "MATCH (Jadeja:player {name: \"Ravindra Jadeja\", YOB: 1988}) \nSET Jadeja.POB: \"NavagamGhed\", Jadeja.HS = \"90\" \nRETURN Jadeja" }, { "code": null, "e": 5520, "s": 5460, "text": "To execute the above query, carry out the following steps −" }, { "code": null, "e": 5698, "s": 5520, "text": "Step 1 − Open the Neo4j desktop App and start the Neo4j Server. Open the built-in browser app of Neo4j using the URL http://localhost:7474/ as shown in the following screenshot." }, { "code": null, "e": 5851, "s": 5698, "text": "Step 2 − Copy and paste the desired query in the dollar prompt and press the play button (to execute the query) highlighted in the following screenshot." }, { "code": null, "e": 5968, "s": 5851, "text": "On executing, you will get the following result. Here you can observe that properties named POB and HS were created." }, { "code": null, "e": 6030, "s": 5968, "text": "You can set a label to an existing node using the SET clause." }, { "code": null, "e": 6090, "s": 6030, "text": "Following is the syntax to set a label to an existing node." }, { "code": null, "e": 6154, "s": 6090, "text": "MATCH (n {properties . . . . . . . }) \nSET n :label \nRETURN n \n" }, { "code": null, "e": 6237, "s": 6154, "text": "Before proceeding with the example, first create a node “Anderson” as shown below." }, { "code": null, "e": 6307, "s": 6237, "text": "CREATE (Anderson {name: \"James Anderson\", YOB: 1982, POB: \"Burnely\"})" }, { "code": null, "e": 6461, "s": 6307, "text": "Following is a sample Cypher Query to set a label on a node using the SET clause. This query adds the label “player” to the node Anderson and returns it." }, { "code": null, "e": 6570, "s": 6461, "text": "MATCH (Anderson {name: \"James Anderson\", YOB: 1982, POB: \"Burnely\"}) \nSET Anderson: player \nRETURN Anderson " }, { "code": null, "e": 6630, "s": 6570, "text": "To execute the above query, carry out the following steps −" }, { "code": null, "e": 6808, "s": 6630, "text": "Step 1 − Open the Neo4j desktop App and start the Neo4j Server. Open the built-in browser app of Neo4j using the URL http://localhost:7474/ as shown in the following screenshot." }, { "code": null, "e": 6961, "s": 6808, "text": "Step 2 − Copy and paste the desired query in the dollar prompt and press the play button (to execute the query) highlighted in the following screenshot." }, { "code": null, "e": 7083, "s": 6961, "text": "On executing, you will get the following result. Here you can observe that the label named “player” is added to the node." }, { "code": null, "e": 7225, "s": 7083, "text": "You can set multiple labels to an existing node using the SET clause. Here you need to specify the labels by separating them with colons “:”." }, { "code": null, "e": 7314, "s": 7225, "text": "Following is the syntax to set multiple labels to an existing node using the SET clause." }, { "code": null, "e": 7386, "s": 7314, "text": "MATCH (n {properties . . . . . . . }) \nSET n :label1:label2 \nRETURN n \n" }, { "code": null, "e": 7473, "s": 7386, "text": "Before proceeding with the example, first create a node named “Ishant” as shown below." }, { "code": null, "e": 7539, "s": 7473, "text": "CREATE (Ishant {name: \"Ishant Sharma\", YOB: 1988, POB: \"Delhi\"}) " }, { "code": null, "e": 7637, "s": 7539, "text": "Following is a sample Cypher Query used to create multiple labels on a node using the SET clause." }, { "code": null, "e": 7744, "s": 7637, "text": "MATCH (Ishant {name: \"Ishant Sharma\", YOB: 1988, POB: \"Delhi\"}) \nSET Ishant: player:person \nRETURN Ishant " }, { "code": null, "e": 7804, "s": 7744, "text": "To execute the above query, carry out the following steps −" }, { "code": null, "e": 7982, "s": 7804, "text": "Step 1 − Open the Neo4j desktop App and start the Neo4j Server. Open the built-in browser app of Neo4j using the URL http://localhost:7474/ as shown in the following screenshot." }, { "code": null, "e": 8135, "s": 7982, "text": "Step 2 − Copy and paste the desired query in the dollar prompt and press the play button (to execute the query) highlighted in the following screenshot." }, { "code": null, "e": 8279, "s": 8135, "text": "On executing, you will get the following result. Here you can observe that two labels - person and player – are added to the node named Ishant." }, { "code": null, "e": 8286, "s": 8279, "text": " Print" }, { "code": null, "e": 8297, "s": 8286, "text": " Add Notes" } ]
Decrypt the encoded string with help of Matrix as per given encryption decryption technique - GeeksforGeeks
14 Mar, 2022 Given an encoded (or encrypted) string S of length N, an integer M. The task is to decrypt the encrypted string and print it. The encryption and decryption techniques are given as: Encryption: The original string is placed in a Matrix of M rows and N/M columns, such that the first character of the Original text or string is placed on the top-left cell to the bottom-right manner. If last row is reached, then again go to the top row, and start from the next column. For example: If string is “geeks”, M = 2, then the string will be encrypted in below manner Then traverse the matrix row wise and print the characters as they appear. Therefore the above string will be encrypted as = “ges ek” Decryption: Traverse the matrix diagonally in the same manner as it was encrypted and find the actual string. Examples: Input: “GSRE_ _ _E_ _K_ _ _EFGS_ _ _KOE” (Here ‘_’ means a space), 4Output: “GEEKS FOR GEEKS”Explanation: See the image below for understanding the approach. Here column number is 6. So, the traversing starts from (0, 0) position, then goes upto the end of the row, means from (0, 0) –> (1, 1)–>(2, 2)–>(3, 3)–>(4, 4). Then get to the first row, and start from the next, means from (0, 1)–>(1, 2)–>(2, 3)->(3, 4) and continues upto it reaches to the end of the given string. Input: “GEEKSFORGEEKS”, 1Output: “GEEKSFORGEEKS”Explanation: There is only one row. so the decoded string will be as same as the given encoded string. Input: “abc de”, 2Output: “adbec” Approach: First, find the number of columns. Then, start traversing. Follow the below steps to solve the problem: For each of the columns, go up to the length of the string starting from the i’th row, and after each traversal increase the iterating value to column+1. Because, here traversal is done diagonally, and here the next diagonal character will be after column number plus one. For example, in the below picture, the X is a character, whose next diagonal character is XX, and the column number where X is present is 2, the next character row number is just one greater than the previous. At the time of traversing add the characters into an empty string. Then check, if there is any space at the end of the string or not, if it is, then just delete it. At last, print that string, and this will be the decoded string/desired string. 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 find the desire stringstring decodeString(string encodedText, int rows){ // Stores the length of the string int len = encodedText.size(); // Stores the number of columns int cols = len / rows; // Declaring an empty string string res; for (int i = 0; i < cols; ++i) for (int j = i; j < len; j += cols + 1) // Adding the characters // into the empty string res += encodedText[j]; // If their any space at the end, // delete it while (res.back() == ' ') { res.pop_back(); } return res;} // Driver Codeint main(){ string S = "GSRE E K EFGS KOE"; int row = 4; cout << decodeString(S, row) << endl; return 0;} // Java program for the above approachclass GFG { // Function to find the desire string static String decodeString(String encodedText, int rows) { // Stores the length of the string int len = encodedText.length(); // Stores the number of columns int cols = len / rows; // Declaring an empty string String res = ""; for (int i = 0; i < cols; ++i) { for (int j = i; j < len; j += cols + 1) { // Adding the characters // into the empty string res += encodedText.charAt(j); } } // If their any space at the end, // delete it while (res.charAt(res.length() - 1) == ' ') { res = res.substring(0, res.length() - 2); } return res; } // Driver Code public static void main(String args[]) { String S = "GSRE E K EFGS KOE"; int row = 4; System.out.println(decodeString(S, row)); }} // This code is contributed by gfgking # Python code for the above approach # Function to find the desire stringdef decodeString(encodedText, rows): # Stores the length of the string _len = len(encodedText) # Stores the number of columns cols = _len // rows # Declaring an empty string res = ""; for i in range(cols): for j in range(i, _len, cols + 1): # Adding the characters # into the empty string res += encodedText[j]; # If their any space at the end, # delete it while (res[len(res) - 1] == ' '): res = res[0: len(res) - 1]; return res; # Driver CodeS = "GSRE E K EFGS KOE";row = 4;print(decodeString(S, row)) # This code is contributed by Saurabh Jaiswal // C# program for the above approachusing System;class GFG{ // Function to find the desire stringstatic string decodeString(string encodedText, int rows){ // Stores the length of the string int len = encodedText.Length; // Stores the number of columns int cols = len / rows; // Declaring an empty string string res = ""; for (int i = 0; i < cols; ++i) { for (int j = i; j < len; j += cols + 1) { // Adding the characters // into the empty string res += encodedText[j]; } } // If their any space at the end, // delete it while (res[res.Length - 1] == ' ') { res = res.Remove(res.Length - 1); } return res;} // Driver Codepublic static void Main(){ string S = "GSRE E K EFGS KOE"; int row = 4; Console.Write(decodeString(S, row)); }} // This code is contributed by Samim Hossain Mondal. <script> // JavaScript code for the above approach // Function to find the desire string function decodeString(encodedText, rows) { // Stores the length of the string let len = encodedText.length; // Stores the number of columns let cols = Math.floor(len / rows); // Declaring an empty string let res = ""; for (let i = 0; i < cols; ++i) for (let j = i; j < len; j += cols + 1) // Adding the characters // into the empty string res += encodedText[j]; // If their any space at the end, // delete it while (res[res.length - 1] == ' ') { res = res.slice(0, res.length - 1); } return res; } // Driver Code let S = "GSRE E K EFGS KOE"; let row = 4; document.write(decodeString(S, row)) // This code is contributed by Potta Lokesh </script> GEEKS FOR GEEKS Time Complexity: O(M*(M/col)) which is near about O(length of the string)Auxiliary Space: O(N) lokeshpotta20 samim2000 _saurabh_jaiswal gfgking sumitgumber28 encoding-decoding Matrix Strings Strings Matrix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Breadth First Traversal ( BFS ) on a 2D array Flood fill Algorithm - how to implement fill() in paint? Program to find the Sum of each Row and each Column of a Matrix Python program to add two Matrices Mathematics | L U Decomposition of a System of Linear Equations Reverse a string in Java Write a program to reverse an array or string Longest Common Subsequence | DP-4 Write a program to print all permutations of a given string C++ Data Types
[ { "code": null, "e": 24896, "s": 24868, "text": "\n14 Mar, 2022" }, { "code": null, "e": 25077, "s": 24896, "text": "Given an encoded (or encrypted) string S of length N, an integer M. The task is to decrypt the encrypted string and print it. The encryption and decryption techniques are given as:" }, { "code": null, "e": 25364, "s": 25077, "text": "Encryption: The original string is placed in a Matrix of M rows and N/M columns, such that the first character of the Original text or string is placed on the top-left cell to the bottom-right manner. If last row is reached, then again go to the top row, and start from the next column." }, { "code": null, "e": 25456, "s": 25364, "text": "For example: If string is “geeks”, M = 2, then the string will be encrypted in below manner" }, { "code": null, "e": 25532, "s": 25456, "text": "Then traverse the matrix row wise and print the characters as they appear. " }, { "code": null, "e": 25591, "s": 25532, "text": "Therefore the above string will be encrypted as = “ges ek”" }, { "code": null, "e": 25701, "s": 25591, "text": "Decryption: Traverse the matrix diagonally in the same manner as it was encrypted and find the actual string." }, { "code": null, "e": 25711, "s": 25701, "text": "Examples:" }, { "code": null, "e": 25870, "s": 25711, "text": "Input: “GSRE_ _ _E_ _K_ _ _EFGS_ _ _KOE” (Here ‘_’ means a space), 4Output: “GEEKS FOR GEEKS”Explanation: See the image below for understanding the approach." }, { "code": null, "e": 26187, "s": 25870, "text": "Here column number is 6. So, the traversing starts from (0, 0) position, then goes upto the end of the row, means from (0, 0) –> (1, 1)–>(2, 2)–>(3, 3)–>(4, 4). Then get to the first row, and start from the next, means from (0, 1)–>(1, 2)–>(2, 3)->(3, 4) and continues upto it reaches to the end of the given string." }, { "code": null, "e": 26339, "s": 26187, "text": "Input: “GEEKSFORGEEKS”, 1Output: “GEEKSFORGEEKS”Explanation: There is only one row. so the decoded string will be as same as the given encoded string. " }, { "code": null, "e": 26373, "s": 26339, "text": "Input: “abc de”, 2Output: “adbec”" }, { "code": null, "e": 26487, "s": 26373, "text": "Approach: First, find the number of columns. Then, start traversing. Follow the below steps to solve the problem:" }, { "code": null, "e": 26641, "s": 26487, "text": "For each of the columns, go up to the length of the string starting from the i’th row, and after each traversal increase the iterating value to column+1." }, { "code": null, "e": 26760, "s": 26641, "text": "Because, here traversal is done diagonally, and here the next diagonal character will be after column number plus one." }, { "code": null, "e": 26970, "s": 26760, "text": "For example, in the below picture, the X is a character, whose next diagonal character is XX, and the column number where X is present is 2, the next character row number is just one greater than the previous." }, { "code": null, "e": 27136, "s": 26970, "text": "At the time of traversing add the characters into an empty string. Then check, if there is any space at the end of the string or not, if it is, then just delete it." }, { "code": null, "e": 27216, "s": 27136, "text": "At last, print that string, and this will be the decoded string/desired string." }, { "code": null, "e": 27267, "s": 27216, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 27271, "s": 27267, "text": "C++" }, { "code": null, "e": 27276, "s": 27271, "text": "Java" }, { "code": null, "e": 27284, "s": 27276, "text": "Python3" }, { "code": null, "e": 27287, "s": 27284, "text": "C#" }, { "code": null, "e": 27298, "s": 27287, "text": "Javascript" }, { "code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find the desire stringstring decodeString(string encodedText, int rows){ // Stores the length of the string int len = encodedText.size(); // Stores the number of columns int cols = len / rows; // Declaring an empty string string res; for (int i = 0; i < cols; ++i) for (int j = i; j < len; j += cols + 1) // Adding the characters // into the empty string res += encodedText[j]; // If their any space at the end, // delete it while (res.back() == ' ') { res.pop_back(); } return res;} // Driver Codeint main(){ string S = \"GSRE E K EFGS KOE\"; int row = 4; cout << decodeString(S, row) << endl; return 0;}", "e": 28106, "s": 27298, "text": null }, { "code": "// Java program for the above approachclass GFG { // Function to find the desire string static String decodeString(String encodedText, int rows) { // Stores the length of the string int len = encodedText.length(); // Stores the number of columns int cols = len / rows; // Declaring an empty string String res = \"\"; for (int i = 0; i < cols; ++i) { for (int j = i; j < len; j += cols + 1) { // Adding the characters // into the empty string res += encodedText.charAt(j); } } // If their any space at the end, // delete it while (res.charAt(res.length() - 1) == ' ') { res = res.substring(0, res.length() - 2); } return res; } // Driver Code public static void main(String args[]) { String S = \"GSRE E K EFGS KOE\"; int row = 4; System.out.println(decodeString(S, row)); }} // This code is contributed by gfgking", "e": 29029, "s": 28106, "text": null }, { "code": "# Python code for the above approach # Function to find the desire stringdef decodeString(encodedText, rows): # Stores the length of the string _len = len(encodedText) # Stores the number of columns cols = _len // rows # Declaring an empty string res = \"\"; for i in range(cols): for j in range(i, _len, cols + 1): # Adding the characters # into the empty string res += encodedText[j]; # If their any space at the end, # delete it while (res[len(res) - 1] == ' '): res = res[0: len(res) - 1]; return res; # Driver CodeS = \"GSRE E K EFGS KOE\";row = 4;print(decodeString(S, row)) # This code is contributed by Saurabh Jaiswal", "e": 29753, "s": 29029, "text": null }, { "code": "// C# program for the above approachusing System;class GFG{ // Function to find the desire stringstatic string decodeString(string encodedText, int rows){ // Stores the length of the string int len = encodedText.Length; // Stores the number of columns int cols = len / rows; // Declaring an empty string string res = \"\"; for (int i = 0; i < cols; ++i) { for (int j = i; j < len; j += cols + 1) { // Adding the characters // into the empty string res += encodedText[j]; } } // If their any space at the end, // delete it while (res[res.Length - 1] == ' ') { res = res.Remove(res.Length - 1); } return res;} // Driver Codepublic static void Main(){ string S = \"GSRE E K EFGS KOE\"; int row = 4; Console.Write(decodeString(S, row)); }} // This code is contributed by Samim Hossain Mondal.", "e": 30653, "s": 29753, "text": null }, { "code": "<script> // JavaScript code for the above approach // Function to find the desire string function decodeString(encodedText, rows) { // Stores the length of the string let len = encodedText.length; // Stores the number of columns let cols = Math.floor(len / rows); // Declaring an empty string let res = \"\"; for (let i = 0; i < cols; ++i) for (let j = i; j < len; j += cols + 1) // Adding the characters // into the empty string res += encodedText[j]; // If their any space at the end, // delete it while (res[res.length - 1] == ' ') { res = res.slice(0, res.length - 1); } return res; } // Driver Code let S = \"GSRE E K EFGS KOE\"; let row = 4; document.write(decodeString(S, row)) // This code is contributed by Potta Lokesh </script>", "e": 31642, "s": 30653, "text": null }, { "code": null, "e": 31658, "s": 31642, "text": "GEEKS FOR GEEKS" }, { "code": null, "e": 31753, "s": 31658, "text": "Time Complexity: O(M*(M/col)) which is near about O(length of the string)Auxiliary Space: O(N)" }, { "code": null, "e": 31767, "s": 31753, "text": "lokeshpotta20" }, { "code": null, "e": 31777, "s": 31767, "text": "samim2000" }, { "code": null, "e": 31794, "s": 31777, "text": "_saurabh_jaiswal" }, { "code": null, "e": 31802, "s": 31794, "text": "gfgking" }, { "code": null, "e": 31816, "s": 31802, "text": "sumitgumber28" }, { "code": null, "e": 31834, "s": 31816, "text": "encoding-decoding" }, { "code": null, "e": 31841, "s": 31834, "text": "Matrix" }, { "code": null, "e": 31849, "s": 31841, "text": "Strings" }, { "code": null, "e": 31857, "s": 31849, "text": "Strings" }, { "code": null, "e": 31864, "s": 31857, "text": "Matrix" }, { "code": null, "e": 31962, "s": 31864, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32008, "s": 31962, "text": "Breadth First Traversal ( BFS ) on a 2D array" }, { "code": null, "e": 32065, "s": 32008, "text": "Flood fill Algorithm - how to implement fill() in paint?" }, { "code": null, "e": 32129, "s": 32065, "text": "Program to find the Sum of each Row and each Column of a Matrix" }, { "code": null, "e": 32164, "s": 32129, "text": "Python program to add two Matrices" }, { "code": null, "e": 32228, "s": 32164, "text": "Mathematics | L U Decomposition of a System of Linear Equations" }, { "code": null, "e": 32253, "s": 32228, "text": "Reverse a string in Java" }, { "code": null, "e": 32299, "s": 32253, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 32333, "s": 32299, "text": "Longest Common Subsequence | DP-4" }, { "code": null, "e": 32393, "s": 32333, "text": "Write a program to print all permutations of a given string" } ]
Hashmap vs WeakHashMap in Java
Details about HashMap and WeakHashMap that help to differentiate them are given as follows − A HashMap has key-value pairs i.e. keys that are associated with the values and the keys are in arbitrary order. A HashMap object that is specified as a key is not eligible for garbage collection. This means that the HashMap has dominance over the garbage collector. A program that demonstrates this is given as follows − Live Demo import java.util.*; class A { public String toString() { return "A "; } public void finalize() { System.out.println("Finalize method"); } } public class Demo { public static void main(String args[])throws Exception { HashMap hMap = new HashMap(); A obj = new A(); hMap.put(obj, " Apple "); System.out.println(hMap); obj = null; System.gc(); Thread.sleep(5000); System.out.println(hMap); } } The output of the above program is as follows − {A = Apple } {A = Apple } A WeakHashMap has key-value pairs i.e. it is quite similar to a HashMap in Java. A difference is that the WeakHashMap object that is specified as a key is still eligible for garbage collection. This means that the garbage collector has dominance over the WeakHashMap. A program that demonstrates this is given as follows − Live Demo import java.util.*; class A { public String toString() { return "A "; } public void finalize() { System.out.println("Finalize method"); } } public class Demo { public static void main(String args[])throws Exception { WeakHashMap whMap = new WeakHashMap(); A obj = new A(); whMap.put(obj, " Apple "); System.out.println(whMap); obj = null; System.gc(); Thread.sleep(5000); System.out.println(whMap); } } The output of the above program is as follows − {A = Apple } Finalize method {}
[ { "code": null, "e": 1155, "s": 1062, "text": "Details about HashMap and WeakHashMap that help to differentiate them are given as follows −" }, { "code": null, "e": 1422, "s": 1155, "text": "A HashMap has key-value pairs i.e. keys that are associated with the values and the keys are in arbitrary order. A HashMap object that is specified as a key is not eligible for garbage collection. This means that the HashMap has dominance over the garbage collector." }, { "code": null, "e": 1477, "s": 1422, "text": "A program that demonstrates this is given as follows −" }, { "code": null, "e": 1488, "s": 1477, "text": " Live Demo" }, { "code": null, "e": 1957, "s": 1488, "text": "import java.util.*;\nclass A {\n public String toString() {\n return \"A \";\n }\n public void finalize() {\n System.out.println(\"Finalize method\");\n }\n}\npublic class Demo {\n public static void main(String args[])throws Exception {\n HashMap hMap = new HashMap();\n A obj = new A();\n hMap.put(obj, \" Apple \");\n System.out.println(hMap);\n obj = null;\n System.gc();\n Thread.sleep(5000);\n System.out.println(hMap);\n }\n}" }, { "code": null, "e": 2005, "s": 1957, "text": "The output of the above program is as follows −" }, { "code": null, "e": 2031, "s": 2005, "text": "{A = Apple }\n{A = Apple }" }, { "code": null, "e": 2299, "s": 2031, "text": "A WeakHashMap has key-value pairs i.e. it is quite similar to a HashMap in Java. A difference is that the WeakHashMap object that is specified as a key is still eligible for garbage collection. This means that the garbage collector has dominance over the WeakHashMap." }, { "code": null, "e": 2354, "s": 2299, "text": "A program that demonstrates this is given as follows −" }, { "code": null, "e": 2365, "s": 2354, "text": " Live Demo" }, { "code": null, "e": 2846, "s": 2365, "text": "import java.util.*;\nclass A {\n public String toString() {\n return \"A \";\n }\n public void finalize() {\n System.out.println(\"Finalize method\");\n }\n}\npublic class Demo {\n public static void main(String args[])throws Exception {\n WeakHashMap whMap = new WeakHashMap();\n A obj = new A();\n whMap.put(obj, \" Apple \");\n System.out.println(whMap);\n obj = null;\n System.gc();\n Thread.sleep(5000);\n System.out.println(whMap);\n }\n}" }, { "code": null, "e": 2894, "s": 2846, "text": "The output of the above program is as follows −" }, { "code": null, "e": 2926, "s": 2894, "text": "{A = Apple }\nFinalize method\n{}" } ]